Skip to content

Commit

Permalink
env tests added
Browse files Browse the repository at this point in the history
  • Loading branch information
Yury Miadzelets authored and Insei committed Oct 17, 2024
1 parent 6849d90 commit b8c5139
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 33 deletions.
3 changes: 3 additions & 0 deletions drivers/env/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
ENV_VAR=true
=true
#COMMENTED=true
48 changes: 18 additions & 30 deletions drivers/env/env.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,39 +118,29 @@ func (d envDriver) GenDoc(registers ...tinyconf.Registered) string {
}

func New() (tinyconf.Driver, error) {
err := setENVs()
setENVsFromExecutable()
setENVsFromWD()

return envDriver{
name: "env",
}, err
}, nil
}

func setENVs() error {
execPath, err := os.Executable()
if err != nil {
return err
}

func setENVsFromExecutable() {
execPath, _ := os.Executable()
envPath := path.Dir(execPath)
wd, err := os.Getwd()
if err != nil {
return err
}

if err = setENVsFromPath(envPath); err != nil {
return err
}
if err = setENVsFromPath(wd); err != nil {
return err
}
setENVsFromPath(envPath)
}

return nil
func setENVsFromWD() {
wd, _ := os.Getwd()
setENVsFromPath(wd)
}

func setENVsFromPath(envDirPath string) error {
func setENVsFromPath(envDirPath string) {
envFile, err := os.Open(path.Join(envDirPath, ".env"))
if err != nil {
return err
return
}

fileScanner := bufio.NewScanner(envFile)
Expand All @@ -165,16 +155,14 @@ func setENVsFromPath(envDirPath string) error {
}

for _, envLine := range envLines {
e := strings.Split(envLine, "=")
val := ""
if len(e) > 1 {
val = e[1]
envRow := strings.Split(envLine, "=")
envVal := ""
if len(envRow) > 1 {
envVal = envRow[1]
}

if err = os.Setenv(e[0], val); err != nil {
return err
if err = os.Setenv(strings.TrimSpace(envRow[0]), envVal); err != nil {
return
}
}

return nil
}
35 changes: 32 additions & 3 deletions drivers/env/env_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,36 @@ func BenchmarkEnvDriver_GenDoc(b *testing.B) {
}

func TestNew(t *testing.T) {
driver, err := New()
assert.NoError(t, err)
assert.NotNil(t, driver)
tests := map[string]struct {
envVarName string
expectedVal string
}{
"EnvSet": {
"ENV_VAR",
"true",
},
"EnvNotSet": {
"ENV_NOT_SET",
"",
},
"EnvCommented": {
"COMMENTED",
"",
},
"EnvEmpty": {
"",
"",
},
}

for name, test := range tests {
t.Run(name, func(t *testing.T) {
driver, err := New()
envVar := os.Getenv(test.envVarName)

assert.NoError(t, err)
assert.NotNil(t, driver)
assert.Equal(t, test.expectedVal, envVar)
})
}
}

0 comments on commit b8c5139

Please sign in to comment.