* CallerInfo is necessary because the assert functions use the testing object internally, causing it to print the file:line of the assert method, rather than where the problem actually occurred in calling code.*/ CallerInfo returns an array of strings containing the file and line number of each stac
()
| 208 | // of each stack frame leading from the current test to the assert call that |
| 209 | // failed. |
| 210 | func CallerInfo() []string { |
| 211 | |
| 212 | var pc uintptr |
| 213 | var ok bool |
| 214 | var file string |
| 215 | var line int |
| 216 | var name string |
| 217 | |
| 218 | callers := []string{} |
| 219 | for i := 0; ; i++ { |
| 220 | pc, file, line, ok = runtime.Caller(i) |
| 221 | if !ok { |
| 222 | // The breaks below failed to terminate the loop, and we ran off the |
| 223 | // end of the call stack. |
| 224 | break |
| 225 | } |
| 226 | |
| 227 | // This is a huge edge case, but it will panic if this is the case, see #180 |
| 228 | if file == "<autogenerated>" { |
| 229 | break |
| 230 | } |
| 231 | |
| 232 | f := runtime.FuncForPC(pc) |
| 233 | if f == nil { |
| 234 | break |
| 235 | } |
| 236 | name = f.Name() |
| 237 | |
| 238 | // testing.tRunner is the standard library function that calls |
| 239 | // tests. Subtests are called directly by tRunner, without going through |
| 240 | // the Test/Benchmark/Example function that contains the t.Run calls, so |
| 241 | // with subtests we should break when we hit tRunner, without adding it |
| 242 | // to the list of callers. |
| 243 | if name == "testing.tRunner" { |
| 244 | break |
| 245 | } |
| 246 | |
| 247 | parts := strings.Split(file, "/") |
| 248 | if len(parts) > 1 { |
| 249 | filename := parts[len(parts)-1] |
| 250 | dir := parts[len(parts)-2] |
| 251 | if (dir != "assert" && dir != "mock" && dir != "require") || filename == "mock_test.go" { |
| 252 | callers = append(callers, fmt.Sprintf("%s:%d", file, line)) |
| 253 | } |
| 254 | } |
| 255 | |
| 256 | // Drop the package |
| 257 | segments := strings.Split(name, ".") |
| 258 | name = segments[len(segments)-1] |
| 259 | if isTest(name, "Test") || |
| 260 | isTest(name, "Benchmark") || |
| 261 | isTest(name, "Example") { |
| 262 | break |
| 263 | } |
| 264 | } |
| 265 | |
| 266 | return callers |
| 267 | } |
searching dependent graphs…