godotenv/godotenv_test.go

74 lines
1.8 KiB
Go
Raw Normal View History

package godotenv
import (
"os"
"testing"
)
2013-07-30 08:15:58 +00:00
func parseAndCompare(t *testing.T, rawEnvLine string, expectedKey string, expectedValue string) {
key, value, _ := parseLine(rawEnvLine)
if key != expectedKey || value != expectedValue {
t.Errorf("Expected '%v' to parse as '%v' => '%v', got '%v' => '%v' instead", rawEnvLine, expectedKey, expectedValue, key, value)
}
}
2013-07-30 07:48:37 +00:00
func loadEnvAndCompareValues(t *testing.T, envFileName string, expectedValues map[string]string) {
err := Load(envFileName)
if err != nil {
t.Fatalf("Error loading %v", envFileName)
}
for k := range expectedValues {
envValue := os.Getenv(k)
v := expectedValues[k]
if envValue != v {
t.Errorf("Mismatch for key '%v': expected '%v' got '%v'", k, v, envValue)
}
}
}
2013-07-30 07:44:28 +00:00
func TestLoadFileNotFound(t *testing.T) {
err := Load("somefilethatwillneverexistever.env")
if err == nil {
t.Error("File wasn't found but Load didn't return an error")
}
}
func TestLoadPlainEnv(t *testing.T) {
envFileName := "fixtures/plain.env"
plainValues := map[string]string{
"OPTION_A": "1",
"OPTION_B": "2",
"OPTION_C": "3",
"OPTION_D": "4",
"OPTION_E": "5",
}
2013-07-30 07:48:37 +00:00
loadEnvAndCompareValues(t, envFileName, plainValues)
}
2013-07-30 08:15:58 +00:00
func TestParsing(t *testing.T) {
// unquoted values
parseAndCompare(t, "FOO=bar", "FOO", "bar")
// parses values with spaces around equal sign
parseAndCompare(t, "FOO =bar", "FOO", "bar")
parseAndCompare(t, "FOO= bar", "FOO", "bar")
// parses double quoted values
parseAndCompare(t, "FOO=\"bar\"", "FOO", "bar")
// parses single quoted values
parseAndCompare(t, "FOO='bar'", "FOO", "bar")
// parses escaped double quotes
parseAndCompare(t, "FOO=escaped\\\"bar\"", "FOO", "escaped\"bar")
2013-07-30 08:34:51 +00:00
// parses yaml style options
parseAndCompare(t, "OPTION_A: 1", "OPTION_A", "1")
2013-07-30 08:38:10 +00:00
// parses export keyword
parseAndCompare(t, "export OPTION_A=2", "OPTION_A", "2")
2013-07-30 08:15:58 +00:00
}