Last active
April 5, 2019 17:18
-
-
Save alexellis/adc67eb022b7fdca31afc0de6529e5ea to your computer and use it in GitHub Desktop.
Mockable os.Getenv() implementation in Go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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)) | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Comment from @marcosnils - can drop "EnvironmentSource" interface.