1 // Copyright 2012 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
27 func TestMain(m *testing.M) {
29 for _, file := range toRemove {
35 func testEnv(cmd *exec.Cmd) *exec.Cmd {
37 panic("environment already set")
39 for _, env := range os.Environ() {
40 // Exclude GODEBUG from the environment to prevent its output
41 // from breaking tests that are trying to parse other command output.
42 if strings.HasPrefix(env, "GODEBUG=") {
45 // Exclude GOTRACEBACK for the same reason.
46 if strings.HasPrefix(env, "GOTRACEBACK=") {
49 cmd.Env = append(cmd.Env, env)
57 target map[string]buildexe
60 type buildexe struct {
65 func runTestProg(t *testing.T, binary, name string) string {
66 testenv.MustHaveGoBuild(t)
68 exe, err := buildTestProg(t, binary)
73 cmd := testEnv(exec.Command(exe, name))
77 if err := cmd.Start(); err != nil {
78 t.Fatalf("starting %s %s: %v", binary, name, err)
81 // If the process doesn't complete within 1 minute,
82 // assume it is hanging and kill it to get a stack trace.
84 done := make(chan bool)
87 // This GOARCH/GOOS test is copied from cmd/dist/test.go.
88 // TODO(iant): Have cmd/dist update the environment variable.
89 if runtime.GOARCH == "arm" || runtime.GOOS == "windows" {
92 if s := os.Getenv("GO_TEST_TIMEOUT_SCALE"); s != "" {
93 if sc, err := strconv.Atoi(s); err == nil {
100 case <-time.After(time.Duration(scale) * time.Minute):
105 if err := cmd.Wait(); err != nil {
106 t.Logf("%s %s exit status: %v", binary, name, err)
113 func buildTestProg(t *testing.T, binary string, flags ...string) (string, error) {
117 defer testprog.Unlock()
118 if testprog.dir == "" {
119 dir, err := ioutil.TempDir("", "go-build")
121 t.Fatalf("failed to create temp directory: %v", err)
124 toRemove = append(toRemove, dir)
127 if testprog.target == nil {
128 testprog.target = make(map[string]buildexe)
132 name += "_" + strings.Join(flags, "_")
134 target, ok := testprog.target[name]
136 return target.exe, target.err
139 exe := filepath.Join(testprog.dir, name+".exe")
140 cmd := exec.Command(testenv.GoToolPath(t), append([]string{"build", "-o", exe}, flags...)...)
141 cmd.Dir = "testdata/" + binary
142 out, err := testEnv(cmd).CombinedOutput()
144 target.err = fmt.Errorf("building %s %v: %v\n%s", binary, flags, err, out)
145 testprog.target[name] = target
146 return "", target.err
149 testprog.target[name] = target
154 staleRuntimeOnce sync.Once // guards init of staleRuntimeErr
155 staleRuntimeErr error
158 func checkStaleRuntime(t *testing.T) {
159 staleRuntimeOnce.Do(func() {
160 // 'go run' uses the installed copy of runtime.a, which may be out of date.
161 out, err := testEnv(exec.Command(testenv.GoToolPath(t), "list", "-f", "{{.Stale}}", "runtime")).CombinedOutput()
163 staleRuntimeErr = fmt.Errorf("failed to execute 'go list': %v\n%v", err, string(out))
166 if string(out) != "false\n" {
167 t.Logf("go list -f {{.Stale}} runtime:\n%s", out)
168 out, err := testEnv(exec.Command(testenv.GoToolPath(t), "list", "-f", "{{.StaleReason}}", "runtime")).CombinedOutput()
170 t.Logf("go list -f {{.StaleReason}} failed: %v", err)
172 t.Logf("go list -f {{.StaleReason}} runtime:\n%s", out)
173 staleRuntimeErr = fmt.Errorf("Stale runtime.a. Run 'go install runtime'.")
176 if staleRuntimeErr != nil {
177 t.Fatal(staleRuntimeErr)
181 func testCrashHandler(t *testing.T, cgo bool) {
182 type crashTest struct {
187 output = runTestProg(t, "testprogcgo", "Crash")
189 output = runTestProg(t, "testprog", "Crash")
191 want := "main: recovered done\nnew-thread: recovered done\nsecond-new-thread: recovered done\nmain-again: recovered done\n"
193 t.Fatalf("output:\n%s\n\nwanted:\n%s", output, want)
197 func TestCrashHandler(t *testing.T) {
198 testCrashHandler(t, false)
201 func testDeadlock(t *testing.T, name string) {
202 output := runTestProg(t, "testprog", name)
203 want := "fatal error: all goroutines are asleep - deadlock!\n"
204 if !strings.HasPrefix(output, want) {
205 t.Fatalf("output does not start with %q:\n%s", want, output)
209 func TestSimpleDeadlock(t *testing.T) {
210 testDeadlock(t, "SimpleDeadlock")
213 func TestInitDeadlock(t *testing.T) {
214 testDeadlock(t, "InitDeadlock")
217 func TestLockedDeadlock(t *testing.T) {
218 testDeadlock(t, "LockedDeadlock")
221 func TestLockedDeadlock2(t *testing.T) {
222 testDeadlock(t, "LockedDeadlock2")
225 func TestGoexitDeadlock(t *testing.T) {
226 output := runTestProg(t, "testprog", "GoexitDeadlock")
227 want := "no goroutines (main called runtime.Goexit) - deadlock!"
228 if !strings.Contains(output, want) {
229 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
233 func TestStackOverflow(t *testing.T) {
234 output := runTestProg(t, "testprog", "StackOverflow")
235 want := "runtime: goroutine stack exceeds 1474560-byte limit\nfatal error: stack overflow"
236 if !strings.HasPrefix(output, want) {
237 t.Fatalf("output does not start with %q:\n%s", want, output)
241 func TestThreadExhaustion(t *testing.T) {
242 output := runTestProg(t, "testprog", "ThreadExhaustion")
243 want := "runtime: program exceeds 10-thread limit\nfatal error: thread exhaustion"
244 if !strings.HasPrefix(output, want) {
245 t.Fatalf("output does not start with %q:\n%s", want, output)
249 func TestRecursivePanic(t *testing.T) {
250 output := runTestProg(t, "testprog", "RecursivePanic")
255 if !strings.HasPrefix(output, want) {
256 t.Fatalf("output does not start with %q:\n%s", want, output)
261 func TestGoexitCrash(t *testing.T) {
262 output := runTestProg(t, "testprog", "GoexitExit")
263 want := "no goroutines (main called runtime.Goexit) - deadlock!"
264 if !strings.Contains(output, want) {
265 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
269 func TestGoexitDefer(t *testing.T) {
270 c := make(chan struct{})
275 t.Errorf("non-nil recover during Goexit")
281 // Note: if the defer fails to run, we will get a deadlock here
285 func TestGoNil(t *testing.T) {
286 output := runTestProg(t, "testprog", "GoNil")
287 want := "go of nil func value"
288 if !strings.Contains(output, want) {
289 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
293 func TestMainGoroutineID(t *testing.T) {
294 output := runTestProg(t, "testprog", "MainGoroutineID")
295 want := "panic: test\n\ngoroutine 1 [running]:\n"
296 if !strings.HasPrefix(output, want) {
297 t.Fatalf("output does not start with %q:\n%s", want, output)
301 func TestNoHelperGoroutines(t *testing.T) {
302 output := runTestProg(t, "testprog", "NoHelperGoroutines")
303 matches := regexp.MustCompile(`goroutine [0-9]+ \[`).FindAllStringSubmatch(output, -1)
304 if len(matches) != 1 || matches[0][0] != "goroutine 1 [" {
305 t.Fatalf("want to see only goroutine 1, see:\n%s", output)
309 func TestBreakpoint(t *testing.T) {
310 output := runTestProg(t, "testprog", "Breakpoint")
311 // If runtime.Breakpoint() is inlined, then the stack trace prints
312 // "runtime.Breakpoint(...)" instead of "runtime.Breakpoint()".
313 want := "runtime.Breakpoint("
314 if !strings.Contains(output, want) {
315 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
319 func TestGoexitInPanic(t *testing.T) {
320 // see issue 8774: this code used to trigger an infinite recursion
321 output := runTestProg(t, "testprog", "GoexitInPanic")
322 want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
323 if !strings.HasPrefix(output, want) {
324 t.Fatalf("output does not start with %q:\n%s", want, output)
328 // Issue 14965: Runtime panics should be of type runtime.Error
329 func TestRuntimePanicWithRuntimeError(t *testing.T) {
330 testCases := [...]func(){
332 var m map[uint64]bool
336 ch := make(chan struct{})
341 var ch = make(chan struct{})
346 var s = make([]int, 2)
351 _ = make(chan bool, n)
354 close((chan bool)(nil))
358 for i, fn := range testCases {
359 got := panicValue(fn)
360 if _, ok := got.(runtime.Error); !ok {
361 t.Errorf("test #%d: recovered value %v(type %T) does not implement runtime.Error", i, got, got)
366 func panicValue(fn func()) (recovered interface{}) {
368 recovered = recover()
374 func TestPanicAfterGoexit(t *testing.T) {
375 // an uncaught panic should still work after goexit
376 output := runTestProg(t, "testprog", "PanicAfterGoexit")
377 want := "panic: hello"
378 if !strings.HasPrefix(output, want) {
379 t.Fatalf("output does not start with %q:\n%s", want, output)
383 func TestRecoveredPanicAfterGoexit(t *testing.T) {
384 output := runTestProg(t, "testprog", "RecoveredPanicAfterGoexit")
385 want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
386 if !strings.HasPrefix(output, want) {
387 t.Fatalf("output does not start with %q:\n%s", want, output)
391 func TestRecoverBeforePanicAfterGoexit(t *testing.T) {
392 // 1. defer a function that recovers
393 // 2. defer a function that panics
395 // Goexit should run the #2 defer. Its panic
396 // should be caught by the #1 defer, and execution
397 // should resume in the caller. Like the Goexit
411 func TestNetpollDeadlock(t *testing.T) {
413 output := runTestProg(t, "testprognet", "NetpollDeadlock")
415 if !strings.HasSuffix(output, want) {
416 t.Fatalf("output does not start with %q:\n%s", want, output)
420 func TestPanicTraceback(t *testing.T) {
422 output := runTestProg(t, "testprog", "PanicTraceback")
423 want := "panic: hello"
424 if !strings.HasPrefix(output, want) {
425 t.Fatalf("output does not start with %q:\n%s", want, output)
428 // Check functions in the traceback.
429 fns := []string{"main.pt1.func1", "panic", "main.pt2.func1", "panic", "main.pt2", "main.pt1"}
430 for _, fn := range fns {
431 re := regexp.MustCompile(`(?m)^` + regexp.QuoteMeta(fn) + `\(.*\n`)
432 idx := re.FindStringIndex(output)
434 t.Fatalf("expected %q function in traceback:\n%s", fn, output)
436 output = output[idx[1]:]
440 func testPanicDeadlock(t *testing.T, name string, want string) {
442 output := runTestProg(t, "testprog", name)
443 if !strings.HasPrefix(output, want) {
444 t.Fatalf("output does not start with %q:\n%s", want, output)
448 func TestPanicDeadlockGosched(t *testing.T) {
449 testPanicDeadlock(t, "GoschedInPanic", "panic: errorThatGosched\n\n")
452 func TestPanicDeadlockSyscall(t *testing.T) {
453 testPanicDeadlock(t, "SyscallInPanic", "1\n2\npanic: 3\n\n")
456 func TestPanicLoop(t *testing.T) {
457 output := runTestProg(t, "testprog", "PanicLoop")
458 if want := "panic while printing panic value"; !strings.Contains(output, want) {
459 t.Errorf("output does not contain %q:\n%s", want, output)
463 func TestMemPprof(t *testing.T) {
464 testenv.MustHaveGoRun(t)
466 exe, err := buildTestProg(t, "testprog")
471 got, err := testEnv(exec.Command(exe, "MemProf")).CombinedOutput()
475 fn := strings.TrimSpace(string(got))
478 for try := 0; try < 2; try++ {
479 cmd := testEnv(exec.Command(testenv.GoToolPath(t), "tool", "pprof", "-alloc_space", "-top"))
480 // Check that pprof works both with and without explicit executable on command line.
482 cmd.Args = append(cmd.Args, exe, fn)
484 cmd.Args = append(cmd.Args, fn)
487 for i, e := range cmd.Env {
488 if strings.HasPrefix(e, "PPROF_TMPDIR=") {
489 cmd.Env[i] = "PPROF_TMPDIR=" + os.TempDir()
495 cmd.Env = append(cmd.Env, "PPROF_TMPDIR="+os.TempDir())
498 top, err := cmd.CombinedOutput()
499 t.Logf("%s:\n%s", cmd.Args, top)
502 } else if !bytes.Contains(top, []byte("MemProf")) {
503 t.Error("missing MemProf in pprof output")
508 var concurrentMapTest = flag.Bool("run_concurrent_map_tests", false, "also run flaky concurrent map tests")
510 func TestConcurrentMapWrites(t *testing.T) {
511 if !*concurrentMapTest {
512 t.Skip("skipping without -run_concurrent_map_tests")
514 testenv.MustHaveGoRun(t)
515 output := runTestProg(t, "testprog", "concurrentMapWrites")
516 want := "fatal error: concurrent map writes"
517 if !strings.HasPrefix(output, want) {
518 t.Fatalf("output does not start with %q:\n%s", want, output)
521 func TestConcurrentMapReadWrite(t *testing.T) {
522 if !*concurrentMapTest {
523 t.Skip("skipping without -run_concurrent_map_tests")
525 testenv.MustHaveGoRun(t)
526 output := runTestProg(t, "testprog", "concurrentMapReadWrite")
527 want := "fatal error: concurrent map read and map write"
528 if !strings.HasPrefix(output, want) {
529 t.Fatalf("output does not start with %q:\n%s", want, output)
532 func TestConcurrentMapIterateWrite(t *testing.T) {
533 if !*concurrentMapTest {
534 t.Skip("skipping without -run_concurrent_map_tests")
536 testenv.MustHaveGoRun(t)
537 output := runTestProg(t, "testprog", "concurrentMapIterateWrite")
538 want := "fatal error: concurrent map iteration and map write"
539 if !strings.HasPrefix(output, want) {
540 t.Fatalf("output does not start with %q:\n%s", want, output)
548 func (p *point) negate() {
553 // Test for issue #10152.
554 func TestPanicInlined(t *testing.T) {
558 t.Fatalf("recover failed")
560 buf := make([]byte, 2048)
561 n := runtime.Stack(buf, false)
563 if !bytes.Contains(buf, []byte("(*point).negate(")) {
564 t.Fatalf("expecting stack trace to contain call to (*point).negate()")