MCPcopy Index your code
hub / github.com/coder/coder / TestLoadEnvFile

Function TestLoadEnvFile

scripts/develop/main_test.go:860–918  ·  view source on GitHub ↗

nolint:paralleltest // loadEnvFile mutates process-global environment.

(t *testing.T)

Source from the content-addressed store, hash-verified

858
859//nolint:paralleltest // loadEnvFile mutates process-global environment.
860func TestLoadEnvFile(t *testing.T) {
861 t.Run("LoadsVariablesFromFile", func(t *testing.T) {
862 tmpDir := t.TempDir()
863 envFile := filepath.Join(tmpDir, ".env")
864 err := os.WriteFile(envFile, []byte(strings.Join([]string{
865 "# Comment line",
866 "",
867 "FOO_TEST_VAR=bar",
868 "export BAZ_TEST_VAR=qux",
869 `QUOTED_TEST_VAR="hello world"`,
870 "SINGLE_QUOTED_TEST_VAR='single quoted'",
871 }, "\n")), 0o600)
872 require.NoError(t, err)
873
874 // Ensure none are set beforehand.
875 t.Setenv("FOO_TEST_VAR", "")
876 os.Unsetenv("FOO_TEST_VAR")
877 t.Setenv("BAZ_TEST_VAR", "")
878 os.Unsetenv("BAZ_TEST_VAR")
879 t.Setenv("QUOTED_TEST_VAR", "")
880 os.Unsetenv("QUOTED_TEST_VAR")
881 t.Setenv("SINGLE_QUOTED_TEST_VAR", "")
882 os.Unsetenv("SINGLE_QUOTED_TEST_VAR")
883
884 n, err := loadEnvFile(envFile)
885 require.NoError(t, err)
886 assert.Equal(t, 4, n)
887 assert.Equal(t, "bar", os.Getenv("FOO_TEST_VAR"))
888 assert.Equal(t, "qux", os.Getenv("BAZ_TEST_VAR"))
889 assert.Equal(t, "hello world", os.Getenv("QUOTED_TEST_VAR"))
890 assert.Equal(t, "single quoted", os.Getenv("SINGLE_QUOTED_TEST_VAR"))
891 })
892
893 t.Run("DoesNotOverrideExisting", func(t *testing.T) {
894 tmpDir := t.TempDir()
895 envFile := filepath.Join(tmpDir, ".env")
896 err := os.WriteFile(envFile, []byte("EXISTING_TEST_VAR=new\n"), 0o600)
897 require.NoError(t, err)
898
899 t.Setenv("EXISTING_TEST_VAR", "original")
900
901 n, err := loadEnvFile(envFile)
902 require.NoError(t, err)
903 assert.Equal(t, 0, n)
904 assert.Equal(t, "original", os.Getenv("EXISTING_TEST_VAR"))
905 })
906
907 t.Run("ErrorsOnMissingFile", func(t *testing.T) {
908 _, err := loadEnvFile("/nonexistent/path/.env")
909 require.Error(t, err)
910 })
911
912 t.Run("ErrorsOnEmptyPath", func(t *testing.T) {
913 // This tests the caller logic (main), but we verify loadEnvFile
914 // would error on empty path since godotenv.Read("") fails.
915 _, err := loadEnvFile("")
916 require.Error(t, err)
917 })

Callers

nothing calls this directly

Calls 7

loadEnvFileFunction · 0.85
SetenvMethod · 0.80
RunMethod · 0.65
TempDirMethod · 0.65
WriteFileMethod · 0.65
EqualMethod · 0.45
ErrorMethod · 0.45

Tested by

no test coverage detected