Skip to content

Instantly share code, notes, and snippets.

@alexellis
Last active April 5, 2019 17:18
Show Gist options
  • Select an option

  • Save alexellis/adc67eb022b7fdca31afc0de6529e5ea to your computer and use it in GitHub Desktop.

Select an option

Save alexellis/adc67eb022b7fdca31afc0de6529e5ea to your computer and use it in GitHub Desktop.
Mockable os.Getenv() implementation in Go
package main
import (
"fmt"
"os"
)
func (Environment) Getenv(source EnvironmentSource, key string) string {
return source.Getenv(key)
}
type Environment struct{}
type EnvironmentSource interface {
Getenv(key string) string
}
func (OsEnv) Getenv(key string) string {
return os.Getenv(key)
}
type OsEnv struct{}
func (f FakeEnv) Getenv(key string) string {
return f.values[key]
}
func NewFakeEnv() FakeEnv {
f := FakeEnv{}
f.values = make(map[string]string)
return f
}
func (f FakeEnv) Setenv(key string, value string) {
f.values[key] = value
}
type FakeEnv struct {
values map[string]string
}
// SUT / System Under Test / Business Logic
func printHome(environment Environment, environmentSource EnvironmentSource, key string) {
val := environment.Getenv(environmentSource, key)
if len(val) == 0 {
fmt.Println("Sorry you have no home.\n")
return
}
fmt.Printf("$HOME is where the: %s is.\n", val)
}
func main() {
var key string
environment := Environment{}
environmentSource := OsEnv{}
testEnvironmentSource := NewFakeEnv()
testEnvironmentSource.Setenv("HOME", "")
key = "HOME"
printHome(environment, environmentSource, key)
printHome(environment, testEnvironmentSource, key)
key = "LANG"
fmt.Printf("%s is spoken everywhere.\n", environment.Getenv(environmentSource, key))
}
@alexellis
Copy link
Author

Comment from @marcosnils - can drop "EnvironmentSource" interface.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment