Skip to content

Commit

Permalink
Add tests for honoring env vars
Browse files Browse the repository at this point in the history
  • Loading branch information
evanphx committed Mar 1, 2024
1 parent ce782f7 commit 7e277a6
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 2 deletions.
4 changes: 2 additions & 2 deletions internal/pkg/profile/loader.go
Original file line number Diff line number Diff line change
Expand Up @@ -177,11 +177,11 @@ func (l *Loader) LoadProfile(name string) (*Profile, error) {

// Honor environment variables around org and project over whatever
// we load from the profile file.
if orgID, ok := os.LookupEnv(envVarHCPOrganizationID); ok {
if orgID, ok := os.LookupEnv(envVarHCPOrganizationID); ok && orgID != "" {
c.OrganizationID = orgID
}

if projID, ok := os.LookupEnv(envVarHCPProjectID); ok {
if projID, ok := os.LookupEnv(envVarHCPProjectID); ok && projID != "" {
c.ProjectID = projID
}

Expand Down
57 changes: 57 additions & 0 deletions internal/pkg/profile/loader_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ func TestLoader_GetActiveProfile(t *testing.T) {
r.NoError(err)
r.Equal(t.Name(), p.Name)
})

}

func TestLoader_ListProfiles(t *testing.T) {
Expand Down Expand Up @@ -208,6 +209,62 @@ project_id = "456"`,
})
}

//nolint:paralleltest
func TestLoader_LoadProfileEnv(t *testing.T) {

// These tests aren't parallel because they manipulate the environment
// and can't run concurrently.

//nolint:paralleltest
t.Run("default profile, env set", func(t *testing.T) {
defer os.Unsetenv(envVarHCPOrganizationID)
defer os.Unsetenv(envVarHCPProjectID)

os.Setenv(envVarHCPOrganizationID, "xyz")
os.Setenv(envVarHCPProjectID, "abc")

r := require.New(t)
l, err := newLoader(t.TempDir())
r.NoError(err)
prof := l.DefaultProfile()

r.Equal("xyz", prof.OrganizationID)
r.Equal("abc", prof.ProjectID)
})

//nolint:paralleltest
t.Run("valid active profile, env set", func(t *testing.T) {
r := require.New(t)
l := TestLoader(t)

defer os.Unsetenv(envVarHCPOrganizationID)
defer os.Unsetenv(envVarHCPProjectID)

p, err := l.NewProfile("test")
r.NoError(err)
p.OrganizationID = "123"
p.ProjectID = "456"
r.NoError(p.Write())

os.Setenv(envVarHCPOrganizationID, "xyz")

out, err := l.LoadProfile(p.Name)
r.NoError(err)
r.NotNil(out)
r.Equal("xyz", out.OrganizationID)
r.Equal(p.ProjectID, out.ProjectID)

os.Setenv(envVarHCPProjectID, "abc")

out, err = l.LoadProfile(p.Name)
r.NoError(err)
r.NotNil(out)
r.Equal("xyz", out.OrganizationID)
r.Equal("abc", out.ProjectID)

})
}

func TestLoader_LoadProfiles(t *testing.T) {
t.Parallel()

Expand Down

0 comments on commit 7e277a6

Please sign in to comment.