WhileTestRunningLogger returns a logger.Logf that logs to t.Logf until the test finishes, at which point it no longer logs anything.
(t testenv.TB)
| 151 | // WhileTestRunningLogger returns a logger.Logf that logs to t.Logf until the |
| 152 | // test finishes, at which point it no longer logs anything. |
| 153 | func WhileTestRunningLogger(t testenv.TB) logger.Logf { |
| 154 | var ( |
| 155 | mu sync.RWMutex |
| 156 | done bool |
| 157 | ) |
| 158 | tlogf := logger.TestLogger(t) |
| 159 | logger := func(format string, args ...any) { |
| 160 | t.Helper() |
| 161 | |
| 162 | mu.RLock() |
| 163 | defer mu.RUnlock() |
| 164 | |
| 165 | if done { |
| 166 | return |
| 167 | } |
| 168 | tlogf(format, args...) |
| 169 | } |
| 170 | |
| 171 | // t.Cleanup is run before the test is marked as done, so by acquiring |
| 172 | // the mutex and then disabling logs, we know that all existing log |
| 173 | // functions have completed, and that no future calls to the logger |
| 174 | // will log something. |
| 175 | // |
| 176 | // We can't do this with an atomic bool, since it's possible to |
| 177 | // observe the following race: |
| 178 | // |
| 179 | // test goroutine goroutine 1 |
| 180 | // -------------- ----------- |
| 181 | // check atomic, testFinished = no |
| 182 | // test finishes |
| 183 | // run t.Cleanups |
| 184 | // set testFinished = true |
| 185 | // call t.Logf |
| 186 | // panic |
| 187 | // |
| 188 | // Using a mutex ensures that all actions in goroutine 1 in the |
| 189 | // sequence above occur atomically, and thus should not panic. |
| 190 | t.Cleanup(func() { |
| 191 | mu.Lock() |
| 192 | defer mu.Unlock() |
| 193 | done = true |
| 194 | }) |
| 195 | return logger |
| 196 | } |
searching dependent graphs…