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 {
38 target map[string]buildexe
41 type buildexe struct {
46 func runTestProg(t *testing.T, binary, name string, env ...string) string {
51 testenv.MustHaveGoBuild(t)
53 exe, err := buildTestProg(t, binary)
58 return runBuiltTestProg(t, exe, name, env...)
61 func runBuiltTestProg(t *testing.T, exe, name string, env ...string) string {
66 testenv.MustHaveGoBuild(t)
68 cmd := testenv.CleanCmdEnv(exec.Command(exe, name))
69 cmd.Env = append(cmd.Env, env...)
71 cmd.Env = append(cmd.Env, "RUNTIME_TEST_SHORT=1")
76 if err := cmd.Start(); err != nil {
77 t.Fatalf("starting %s %s: %v", exe, name, err)
80 // If the process doesn't complete within 1 minute,
81 // assume it is hanging and kill it to get a stack trace.
83 done := make(chan bool)
86 // This GOARCH/GOOS test is copied from cmd/dist/test.go.
87 // TODO(iant): Have cmd/dist update the environment variable.
88 if runtime.GOARCH == "arm" || runtime.GOOS == "windows" {
91 if s := os.Getenv("GO_TEST_TIMEOUT_SCALE"); s != "" {
92 if sc, err := strconv.Atoi(s); err == nil {
99 case <-time.After(time.Duration(scale) * time.Minute):
104 if err := cmd.Wait(); err != nil {
105 t.Logf("%s %s exit status: %v", exe, name, err)
112 func buildTestProg(t *testing.T, binary string, flags ...string) (string, error) {
118 defer testprog.Unlock()
119 if testprog.dir == "" {
120 dir, err := ioutil.TempDir("", "go-build")
122 t.Fatalf("failed to create temp directory: %v", err)
125 toRemove = append(toRemove, dir)
128 if testprog.target == nil {
129 testprog.target = make(map[string]buildexe)
133 name += "_" + strings.Join(flags, "_")
135 target, ok := testprog.target[name]
137 return target.exe, target.err
140 exe := filepath.Join(testprog.dir, name+".exe")
141 cmd := exec.Command(testenv.GoToolPath(t), append([]string{"build", "-o", exe}, flags...)...)
142 cmd.Dir = "testdata/" + binary
143 out, err := testenv.CleanCmdEnv(cmd).CombinedOutput()
145 target.err = fmt.Errorf("building %s %v: %v\n%s", binary, flags, err, out)
146 testprog.target[name] = target
147 return "", target.err
150 testprog.target[name] = target
154 func TestVDSO(t *testing.T) {
156 output := runTestProg(t, "testprog", "SignalInVDSO")
159 t.Fatalf("output:\n%s\n\nwanted:\n%s", output, want)
163 func testCrashHandler(t *testing.T, cgo bool) {
164 type crashTest struct {
169 output = runTestProg(t, "testprogcgo", "Crash")
171 output = runTestProg(t, "testprog", "Crash")
173 want := "main: recovered done\nnew-thread: recovered done\nsecond-new-thread: recovered done\nmain-again: recovered done\n"
175 t.Fatalf("output:\n%s\n\nwanted:\n%s", output, want)
179 func TestCrashHandler(t *testing.T) {
180 testCrashHandler(t, false)
183 func testDeadlock(t *testing.T, name string) {
184 // External linking brings in cgo, causing deadlock detection not working.
185 testenv.MustInternalLink(t)
187 output := runTestProg(t, "testprog", name)
188 want := "fatal error: all goroutines are asleep - deadlock!\n"
189 if !strings.HasPrefix(output, want) {
190 t.Fatalf("output does not start with %q:\n%s", want, output)
194 func TestSimpleDeadlock(t *testing.T) {
195 testDeadlock(t, "SimpleDeadlock")
198 func TestInitDeadlock(t *testing.T) {
199 testDeadlock(t, "InitDeadlock")
202 func TestLockedDeadlock(t *testing.T) {
203 testDeadlock(t, "LockedDeadlock")
206 func TestLockedDeadlock2(t *testing.T) {
207 testDeadlock(t, "LockedDeadlock2")
210 func TestGoexitDeadlock(t *testing.T) {
211 // External linking brings in cgo, causing deadlock detection not working.
212 testenv.MustInternalLink(t)
214 output := runTestProg(t, "testprog", "GoexitDeadlock")
215 want := "no goroutines (main called runtime.Goexit) - deadlock!"
216 if !strings.Contains(output, want) {
217 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
221 func TestStackOverflow(t *testing.T) {
222 output := runTestProg(t, "testprog", "StackOverflow")
224 "runtime: goroutine stack exceeds 1474560-byte limit\n",
225 "fatal error: stack overflow",
226 // information about the current SP and stack bounds
230 if !strings.HasPrefix(output, want[0]) {
231 t.Errorf("output does not start with %q", want[0])
233 for _, s := range want[1:] {
234 if !strings.Contains(output, s) {
235 t.Errorf("output does not contain %q", s)
239 t.Logf("output:\n%s", output)
243 func TestThreadExhaustion(t *testing.T) {
244 output := runTestProg(t, "testprog", "ThreadExhaustion")
245 want := "runtime: program exceeds 10-thread limit\nfatal error: thread exhaustion"
246 if !strings.HasPrefix(output, want) {
247 t.Fatalf("output does not start with %q:\n%s", want, output)
251 func TestRecursivePanic(t *testing.T) {
252 output := runTestProg(t, "testprog", "RecursivePanic")
257 if !strings.HasPrefix(output, want) {
258 t.Fatalf("output does not start with %q:\n%s", want, output)
263 func TestRecursivePanic2(t *testing.T) {
264 output := runTestProg(t, "testprog", "RecursivePanic2")
270 if !strings.HasPrefix(output, want) {
271 t.Fatalf("output does not start with %q:\n%s", want, output)
276 func TestRecursivePanic3(t *testing.T) {
277 output := runTestProg(t, "testprog", "RecursivePanic3")
278 want := `panic: first panic
281 if !strings.HasPrefix(output, want) {
282 t.Fatalf("output does not start with %q:\n%s", want, output)
287 func TestRecursivePanic4(t *testing.T) {
288 output := runTestProg(t, "testprog", "RecursivePanic4")
289 want := `panic: first panic [recovered]
292 if !strings.HasPrefix(output, want) {
293 t.Fatalf("output does not start with %q:\n%s", want, output)
298 func TestGoexitCrash(t *testing.T) {
299 // External linking brings in cgo, causing deadlock detection not working.
300 testenv.MustInternalLink(t)
302 output := runTestProg(t, "testprog", "GoexitExit")
303 want := "no goroutines (main called runtime.Goexit) - deadlock!"
304 if !strings.Contains(output, want) {
305 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
309 func TestGoexitDefer(t *testing.T) {
310 c := make(chan struct{})
315 t.Errorf("non-nil recover during Goexit")
321 // Note: if the defer fails to run, we will get a deadlock here
325 func TestGoNil(t *testing.T) {
326 output := runTestProg(t, "testprog", "GoNil")
327 want := "go of nil func value"
328 if !strings.Contains(output, want) {
329 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
333 func TestMainGoroutineID(t *testing.T) {
334 output := runTestProg(t, "testprog", "MainGoroutineID")
335 want := "panic: test\n\ngoroutine 1 [running]:\n"
336 if !strings.HasPrefix(output, want) {
337 t.Fatalf("output does not start with %q:\n%s", want, output)
341 func TestNoHelperGoroutines(t *testing.T) {
342 output := runTestProg(t, "testprog", "NoHelperGoroutines")
343 matches := regexp.MustCompile(`goroutine [0-9]+ \[`).FindAllStringSubmatch(output, -1)
344 if len(matches) != 1 || matches[0][0] != "goroutine 1 [" {
345 t.Fatalf("want to see only goroutine 1, see:\n%s", output)
349 func TestBreakpoint(t *testing.T) {
350 output := runTestProg(t, "testprog", "Breakpoint")
351 // If runtime.Breakpoint() is inlined, then the stack trace prints
352 // "runtime.Breakpoint(...)" instead of "runtime.Breakpoint()".
353 want := "runtime.Breakpoint("
354 if !strings.Contains(output, want) {
355 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
359 func TestGoexitInPanic(t *testing.T) {
360 // External linking brings in cgo, causing deadlock detection not working.
361 testenv.MustInternalLink(t)
363 // see issue 8774: this code used to trigger an infinite recursion
364 output := runTestProg(t, "testprog", "GoexitInPanic")
365 want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
366 if !strings.HasPrefix(output, want) {
367 t.Fatalf("output does not start with %q:\n%s", want, output)
371 // Issue 14965: Runtime panics should be of type runtime.Error
372 func TestRuntimePanicWithRuntimeError(t *testing.T) {
373 testCases := [...]func(){
375 var m map[uint64]bool
379 ch := make(chan struct{})
384 var ch = make(chan struct{})
389 var s = make([]int, 2)
394 _ = make(chan bool, n)
397 close((chan bool)(nil))
401 for i, fn := range testCases {
402 got := panicValue(fn)
403 if _, ok := got.(runtime.Error); !ok {
404 t.Errorf("test #%d: recovered value %v(type %T) does not implement runtime.Error", i, got, got)
409 func panicValue(fn func()) (recovered interface{}) {
411 recovered = recover()
417 func TestPanicAfterGoexit(t *testing.T) {
418 // an uncaught panic should still work after goexit
419 output := runTestProg(t, "testprog", "PanicAfterGoexit")
420 want := "panic: hello"
421 if !strings.HasPrefix(output, want) {
422 t.Fatalf("output does not start with %q:\n%s", want, output)
426 func TestRecoveredPanicAfterGoexit(t *testing.T) {
427 // External linking brings in cgo, causing deadlock detection not working.
428 testenv.MustInternalLink(t)
430 output := runTestProg(t, "testprog", "RecoveredPanicAfterGoexit")
431 want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
432 if !strings.HasPrefix(output, want) {
433 t.Fatalf("output does not start with %q:\n%s", want, output)
437 func TestRecoverBeforePanicAfterGoexit(t *testing.T) {
438 // External linking brings in cgo, causing deadlock detection not working.
439 testenv.MustInternalLink(t)
442 output := runTestProg(t, "testprog", "RecoverBeforePanicAfterGoexit")
443 want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
444 if !strings.HasPrefix(output, want) {
445 t.Fatalf("output does not start with %q:\n%s", want, output)
449 func TestRecoverBeforePanicAfterGoexit2(t *testing.T) {
450 // External linking brings in cgo, causing deadlock detection not working.
451 testenv.MustInternalLink(t)
454 output := runTestProg(t, "testprog", "RecoverBeforePanicAfterGoexit2")
455 want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
456 if !strings.HasPrefix(output, want) {
457 t.Fatalf("output does not start with %q:\n%s", want, output)
461 func TestNetpollDeadlock(t *testing.T) {
462 if os.Getenv("GO_BUILDER_NAME") == "darwin-amd64-10_12" {
463 // A suspected kernel bug in macOS 10.12 occasionally results in
464 // an apparent deadlock when dialing localhost. The errors have not
465 // been observed on newer versions of the OS, so we don't plan to work
466 // around them. See https://golang.org/issue/22019.
467 testenv.SkipFlaky(t, 22019)
471 output := runTestProg(t, "testprognet", "NetpollDeadlock")
473 if !strings.HasSuffix(output, want) {
474 t.Fatalf("output does not start with %q:\n%s", want, output)
478 func TestPanicTraceback(t *testing.T) {
480 output := runTestProg(t, "testprog", "PanicTraceback")
481 want := "panic: hello\n\tpanic: panic pt2\n\tpanic: panic pt1\n"
482 if !strings.HasPrefix(output, want) {
483 t.Fatalf("output does not start with %q:\n%s", want, output)
486 // Check functions in the traceback.
487 fns := []string{"main.pt1.func1", "panic", "main.pt2.func1", "panic", "main.pt2", "main.pt1"}
488 for _, fn := range fns {
489 re := regexp.MustCompile(`(?m)^` + regexp.QuoteMeta(fn) + `\(.*\n`)
490 idx := re.FindStringIndex(output)
492 t.Fatalf("expected %q function in traceback:\n%s", fn, output)
494 output = output[idx[1]:]
498 func testPanicDeadlock(t *testing.T, name string, want string) {
500 output := runTestProg(t, "testprog", name)
501 if !strings.HasPrefix(output, want) {
502 t.Fatalf("output does not start with %q:\n%s", want, output)
506 func TestPanicDeadlockGosched(t *testing.T) {
507 testPanicDeadlock(t, "GoschedInPanic", "panic: errorThatGosched\n\n")
510 func TestPanicDeadlockSyscall(t *testing.T) {
511 testPanicDeadlock(t, "SyscallInPanic", "1\n2\npanic: 3\n\n")
514 func TestPanicLoop(t *testing.T) {
515 output := runTestProg(t, "testprog", "PanicLoop")
516 if want := "panic while printing panic value"; !strings.Contains(output, want) {
517 t.Errorf("output does not contain %q:\n%s", want, output)
521 func TestMemPprof(t *testing.T) {
522 testenv.MustHaveGoRun(t)
524 exe, err := buildTestProg(t, "testprog")
529 got, err := testenv.CleanCmdEnv(exec.Command(exe, "MemProf")).CombinedOutput()
533 fn := strings.TrimSpace(string(got))
536 for try := 0; try < 2; try++ {
537 cmd := testenv.CleanCmdEnv(exec.Command(testenv.GoToolPath(t), "tool", "pprof", "-alloc_space", "-top"))
538 // Check that pprof works both with and without explicit executable on command line.
540 cmd.Args = append(cmd.Args, exe, fn)
542 cmd.Args = append(cmd.Args, fn)
545 for i, e := range cmd.Env {
546 if strings.HasPrefix(e, "PPROF_TMPDIR=") {
547 cmd.Env[i] = "PPROF_TMPDIR=" + os.TempDir()
553 cmd.Env = append(cmd.Env, "PPROF_TMPDIR="+os.TempDir())
556 top, err := cmd.CombinedOutput()
557 t.Logf("%s:\n%s", cmd.Args, top)
560 } else if !bytes.Contains(top, []byte("MemProf")) {
561 t.Error("missing MemProf in pprof output")
566 var concurrentMapTest = flag.Bool("run_concurrent_map_tests", false, "also run flaky concurrent map tests")
568 func TestConcurrentMapWrites(t *testing.T) {
569 if !*concurrentMapTest {
570 t.Skip("skipping without -run_concurrent_map_tests")
572 testenv.MustHaveGoRun(t)
573 output := runTestProg(t, "testprog", "concurrentMapWrites")
574 want := "fatal error: concurrent map writes"
575 if !strings.HasPrefix(output, want) {
576 t.Fatalf("output does not start with %q:\n%s", want, output)
579 func TestConcurrentMapReadWrite(t *testing.T) {
580 if !*concurrentMapTest {
581 t.Skip("skipping without -run_concurrent_map_tests")
583 testenv.MustHaveGoRun(t)
584 output := runTestProg(t, "testprog", "concurrentMapReadWrite")
585 want := "fatal error: concurrent map read and map write"
586 if !strings.HasPrefix(output, want) {
587 t.Fatalf("output does not start with %q:\n%s", want, output)
590 func TestConcurrentMapIterateWrite(t *testing.T) {
591 if !*concurrentMapTest {
592 t.Skip("skipping without -run_concurrent_map_tests")
594 testenv.MustHaveGoRun(t)
595 output := runTestProg(t, "testprog", "concurrentMapIterateWrite")
596 want := "fatal error: concurrent map iteration and map write"
597 if !strings.HasPrefix(output, want) {
598 t.Fatalf("output does not start with %q:\n%s", want, output)
606 func (p *point) negate() {
611 // Test for issue #10152.
612 func TestPanicInlined(t *testing.T) {
616 t.Fatalf("recover failed")
618 buf := make([]byte, 2048)
619 n := runtime.Stack(buf, false)
621 if !bytes.Contains(buf, []byte("(*point).negate(")) {
622 t.Fatalf("expecting stack trace to contain call to (*point).negate()")
630 // Test for issues #3934 and #20018.
631 // We want to delay exiting until a panic print is complete.
632 func TestPanicRace(t *testing.T) {
633 testenv.MustHaveGoRun(t)
635 exe, err := buildTestProg(t, "testprog")
640 // The test is intentionally racy, and in my testing does not
641 // produce the expected output about 0.05% of the time.
642 // So run the program in a loop and only fail the test if we
643 // get the wrong output ten times in a row.
646 for i := 0; i < tries; i++ {
647 got, err := testenv.CleanCmdEnv(exec.Command(exe, "PanicRace")).CombinedOutput()
649 t.Logf("try %d: program exited successfully, should have failed", i+1)
654 t.Logf("try %d:\n", i+1)
663 for _, want := range wants {
664 if !bytes.Contains(got, []byte(want)) {
665 t.Logf("did not find expected string %q", want)
670 // Test generated expected output.
673 t.Errorf("test ran %d times without producing expected output", tries)
676 func TestBadTraceback(t *testing.T) {
677 output := runTestProg(t, "testprog", "BadTraceback")
678 for _, want := range []string{
679 "runtime: unexpected return pc",
681 "00000bad", // Smashed LR in hex dump
682 "<main.badLR", // Symbolization in hex dump (badLR1 or badLR2)
684 if !strings.Contains(output, want) {
685 t.Errorf("output does not contain %q:\n%s", want, output)
690 func TestTimePprof(t *testing.T) {
691 // Pass GOTRACEBACK for issue #41120 to try to get more
692 // information on timeout.
693 fn := runTestProg(t, "testprog", "TimeProf", "GOTRACEBACK=crash")
694 fn = strings.TrimSpace(fn)
697 cmd := testenv.CleanCmdEnv(exec.Command(testenv.GoToolPath(t), "tool", "pprof", "-top", "-nodecount=1", fn))
698 cmd.Env = append(cmd.Env, "PPROF_TMPDIR="+os.TempDir())
699 top, err := cmd.CombinedOutput()
703 } else if bytes.Contains(top, []byte("ExternalCode")) {
704 t.Error("profiler refers to ExternalCode")
708 // Test that runtime.abort does so.
709 func TestAbort(t *testing.T) {
710 // Pass GOTRACEBACK to ensure we get runtime frames.
711 output := runTestProg(t, "testprog", "Abort", "GOTRACEBACK=system")
712 if want := "runtime.abort"; !strings.Contains(output, want) {
713 t.Errorf("output does not contain %q:\n%s", want, output)
715 if strings.Contains(output, "BAD") {
716 t.Errorf("output contains BAD:\n%s", output)
718 // Check that it's a signal traceback.
720 // For systems that use a breakpoint, check specifically for that.
721 switch runtime.GOARCH {
723 switch runtime.GOOS {
725 want = "sys: breakpoint"
727 want = "Exception 0x80000003"
732 if !strings.Contains(output, want) {
733 t.Errorf("output does not contain %q:\n%s", want, output)
737 // For TestRuntimePanic: test a panic in the runtime package without
738 // involving the testing harness.
740 if os.Getenv("GO_TEST_RUNTIME_PANIC") == "1" {
742 if r := recover(); r != nil {
743 // We expect to crash, so exit 0
744 // to indicate failure.
748 runtime.PanicForTesting(nil, 1)
749 // We expect to crash, so exit 0 to indicate failure.
754 func TestRuntimePanic(t *testing.T) {
755 testenv.MustHaveExec(t)
756 cmd := testenv.CleanCmdEnv(exec.Command(os.Args[0], "-test.run=TestRuntimePanic"))
757 cmd.Env = append(cmd.Env, "GO_TEST_RUNTIME_PANIC=1")
758 out, err := cmd.CombinedOutput()
761 t.Error("child process did not fail")
762 } else if want := "runtime.unexportedPanicForTesting"; !bytes.Contains(out, []byte(want)) {
763 t.Errorf("output did not contain expected string %q", want)
767 // Test that g0 stack overflows are handled gracefully.
768 func TestG0StackOverflow(t *testing.T) {
769 testenv.MustHaveExec(t)
771 switch runtime.GOOS {
772 case "darwin", "dragonfly", "freebsd", "linux", "netbsd", "openbsd", "android":
773 t.Skipf("g0 stack is wrong on pthread platforms (see golang.org/issue/26061)")
776 if os.Getenv("TEST_G0_STACK_OVERFLOW") != "1" {
777 cmd := testenv.CleanCmdEnv(exec.Command(os.Args[0], "-test.run=TestG0StackOverflow", "-test.v"))
778 cmd.Env = append(cmd.Env, "TEST_G0_STACK_OVERFLOW=1")
779 out, err := cmd.CombinedOutput()
780 // Don't check err since it's expected to crash.
781 if n := strings.Count(string(out), "morestack on g0\n"); n != 1 {
782 t.Fatalf("%s\n(exit status %v)", out, err)
784 // Check that it's a signal-style traceback.
785 if runtime.GOOS != "windows" {
786 if want := "PC="; !strings.Contains(string(out), want) {
787 t.Errorf("output does not contain %q:\n%s", want, out)
793 runtime.G0StackOverflow()
796 // Test that panic message is not clobbered.
798 func TestDoublePanic(t *testing.T) {
799 output := runTestProg(t, "testprog", "DoublePanic", "GODEBUG=clobberfree=1")
800 wants := []string{"panic: XXX", "panic: YYY"}
801 for _, want := range wants {
802 if !strings.Contains(output, want) {
803 t.Errorf("output:\n%s\n\nwant output containing: %s", output, want)