Commit c05312aa authored by Pierre Smeyers's avatar Pierre Smeyers
Browse files

fix: workaround GitLab behavior when a variable with forced service container visibility is unset

parent 6bc49f75
Loading
Loading
Loading
Loading
+6 −0
Original line number Diff line number Diff line
@@ -28,6 +28,12 @@ type EnvStr string

func (env EnvStr) Or(def string) string {
	if v, ok := os.LookupEnv(string(env)); ok {
		if v == "$"+string(env) || v == "" {
			// workaround of GitLab behavior when defining a variable as:
			// VAR: "$VAR"
			// when VAR is unset at project level, its value remains literally '$VAR'
			return def
		}
		return v
	}

+56 −0
Original line number Diff line number Diff line
/*
 * Copyright (C) 2021 Orange & contributors
 *
 * This program is free software; you can redistribute it and/or modify it under the terms
 *
 * of the GNU Lesser General Public License as published by the Free Software Foundation;
 * either version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along with this
 * program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth
 * Floor, Boston, MA  02110-1301, USA.
 */

package internal

import (
	"os"
	"testing"
)

func Test_getenv_when_var_unset(t *testing.T) {
	os.Unsetenv("TESTVAR")
	// os.Setenv("TESTVAR", "test")
	val := EnvStr("TESTVAR").Or("default")
	if val != "default" {
		t.Fatalf("Assert error\nExpected:\n%s\nGot:\n%s", "default", val)
	}
}

func Test_getenv_when_var_empty(t *testing.T) {
	os.Setenv("TESTVAR", "")
	val := EnvStr("TESTVAR").Or("default")
	if val != "default" {
		t.Fatalf("Assert error\nExpected:\n%s\nGot:\n%s", "default", val)
	}
}

func Test_getenv_when_var_gitlab_unset(t *testing.T) {
	os.Setenv("TESTVAR", "$TESTVAR")
	val := EnvStr("TESTVAR").Or("default")
	if val != "default" {
		t.Fatalf("Assert error\nExpected:\n%s\nGot:\n%s", "default", val)
	}
}

func Test_getenv_when_var_set(t *testing.T) {
	os.Setenv("TESTVAR", "testval")
	val := EnvStr("TESTVAR").Or("default")
	if val != "testval" {
		t.Fatalf("Assert error\nExpected:\n%s\nGot:\n%s", "testval", val)
	}
}