Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mock the fetching of environment variables for cleaner testings #7

Open
kmesiab opened this issue Jan 17, 2024 · 0 comments
Open

Mock the fetching of environment variables for cleaner testings #7

kmesiab opened this issue Jan 17, 2024 · 0 comments
Labels
enhancement New feature or request good first issue Good for newcomers help wanted Extra attention is needed

Comments

@kmesiab
Copy link
Owner

kmesiab commented Jan 17, 2024

It would be beneficial to have consistency in how you handle environmental overrides. Looking at TestCoalesceConfiguration_Model_CLIOverride, you're directly manipulating the environment variables within the test function. This is a bit risky because if the test were to fail before the defer statement is able to run, the environment could be left in an altered state.

Considering Go's practices, it's often better to abstract the environment variable accessors to enable easier mocking and to create a cleaner separation of concerns.

Here's a suggested approach using an interface to abstract environment variable access:

type EnvAccessor interface {
    Getenv(key string) string
    Setenv(key, value string) error
}

type RealEnv struct{}

func (r RealEnv) Getenv(key string) string {
    return os.Getenv(key)
}

func (r RealEnv) Setenv(key, value string) error {
    return os.Setenv(key, value)
}

// Use a mock in your tests
type MockEnv struct {
    vars map[string]string
}

func (m *MockEnv) Getenv(key string) string {
    return m.vars[key]
}

func (m *MockEnv) Setenv(key, value string) error {
    m.vars[key] = value
    return nil
}

Using this, you can control your environment in a much safer way in your tests without the risk of affecting the global environment.

@kmesiab kmesiab added enhancement New feature or request help wanted Extra attention is needed good first issue Good for newcomers labels Jan 17, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request good first issue Good for newcomers help wanted Extra attention is needed
Projects
None yet
Development

No branches or pull requests

1 participant