github.com/docker/libcompose@v0.4.1-0.20210616120443-2a046c0bdbf2/lookup/envfile_test.go (about)

     1  package lookup
     2  
     3  import (
     4  	"io/ioutil"
     5  	"os"
     6  	"path/filepath"
     7  	"testing"
     8  )
     9  
    10  func TestEnvfileLookupReturnsEmptyIfError(t *testing.T) {
    11  	envfileLookup := &EnvfileLookup{
    12  		Path: "anything/file.env",
    13  	}
    14  	actuals := envfileLookup.Lookup("any", nil)
    15  	if len(actuals) != 0 {
    16  		t.Fatalf("expected an empty slice, got %v", actuals)
    17  	}
    18  }
    19  
    20  func TestEnvfileLookupWithGoodFile(t *testing.T) {
    21  	content := `foo=bar
    22      baz=quux
    23  # comment
    24  
    25  _foobar=foobaz
    26  with.dots=working
    27  and_underscore=working too
    28  `
    29  	tmpFolder, err := ioutil.TempDir("", "test-envfile")
    30  	if err != nil {
    31  		t.Fatal(err)
    32  	}
    33  	envfile := filepath.Join(tmpFolder, ".env")
    34  	if err := ioutil.WriteFile(envfile, []byte(content), 0700); err != nil {
    35  		t.Fatal(err)
    36  	}
    37  	defer os.RemoveAll(tmpFolder)
    38  
    39  	envfileLookup := &EnvfileLookup{
    40  		Path: envfile,
    41  	}
    42  
    43  	validateLookup(t, "baz=quux", envfileLookup.Lookup("baz", nil))
    44  	validateLookup(t, "foo=bar", envfileLookup.Lookup("foo", nil))
    45  	validateLookup(t, "_foobar=foobaz", envfileLookup.Lookup("_foobar", nil))
    46  	validateLookup(t, "with.dots=working", envfileLookup.Lookup("with.dots", nil))
    47  	validateLookup(t, "and_underscore=working too", envfileLookup.Lookup("and_underscore", nil))
    48  }
    49  
    50  func validateLookup(t *testing.T, expected string, actuals []string) {
    51  	if len(actuals) != 1 {
    52  		t.Fatalf("expected 1 result, got %v", actuals)
    53  	}
    54  	if actuals[0] != expected {
    55  		t.Fatalf("expected %s, got %s", expected, actuals[0])
    56  	}
    57  }