NewIsolatedTestConfig returns the real config implementation, built from cfgString and isolated from the machine running the tests. Pass "" for a config with no content. It also returns a function that reads back anything written to disk. Use it when the code under test exercises real config behavi
(t *testing.T, cfgString string)
| 124 | // Callers that want one of the auth env vars set should set it after calling this, |
| 125 | // otherwise the value is cleared along with the ambient environment. |
| 126 | func NewIsolatedTestConfig(t *testing.T, cfgString string) (*cfg, func(io.Writer, io.Writer)) { |
| 127 | keyring.MockInit() |
| 128 | |
| 129 | // go-gh reads these ahead of any stored config, so isolating the config file is |
| 130 | // not enough on its own. A developer with GH_TOKEN exported, or any CI image that |
| 131 | // provides one, would otherwise see an authenticated config here and fail tests |
| 132 | // that assert on the logged out state. |
| 133 | for _, key := range []string{ |
| 134 | "GH_TOKEN", |
| 135 | "GITHUB_TOKEN", |
| 136 | "GH_ENTERPRISE_TOKEN", |
| 137 | "GITHUB_ENTERPRISE_TOKEN", |
| 138 | "GH_HOST", |
| 139 | } { |
| 140 | t.Setenv(key, "") |
| 141 | } |
| 142 | |
| 143 | c := ghConfig.ReadFromString(cfgString) |
| 144 | cfg := cfg{c} |
| 145 | |
| 146 | // The real implementation of config.Read uses a sync.Once |
| 147 | // to read config files and initialise package level variables |
| 148 | // that are used from then on. |
| 149 | // |
| 150 | // This means that tests can't be isolated from each other, so |
| 151 | // we swap out the function here to return a new config each time. |
| 152 | ghConfig.Read = func(_ *ghConfig.Config) (*ghConfig.Config, error) { |
| 153 | return c, nil |
| 154 | } |
| 155 | |
| 156 | // The config.Write method isn't defined in the same way as Read to allow |
| 157 | // the function to be swapped out and it does try to write to disk. |
| 158 | // |
| 159 | // We should consider whether it makes sense to change that but in the meantime |
| 160 | // we can use GH_CONFIG_DIR env var to ensure the tests remain isolated. |
| 161 | readConfigs := StubWriteConfig(t) |
| 162 | |
| 163 | return &cfg, readConfigs |
| 164 | } |
| 165 | |
| 166 | // StubWriteConfig stubs out the filesystem where config file are written. |
| 167 | // It then returns a function that will read in the config files into io.Writers. |