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.
25 func TestMain(m *testing.M) {
27 for _, file := range toRemove {
36 target map[string]*buildexe
39 type buildexe struct {
45 func runTestProg(t *testing.T, binary, name string, env ...string) string {
50 testenv.MustHaveGoBuild(t)
52 exe, err := buildTestProg(t, binary)
57 return runBuiltTestProg(t, exe, name, env...)
60 func runBuiltTestProg(t *testing.T, exe, name string, env ...string) string {
65 testenv.MustHaveGoBuild(t)
67 cmd := testenv.CleanCmdEnv(exec.Command(exe, name))
68 cmd.Env = append(cmd.Env, env...)
70 cmd.Env = append(cmd.Env, "RUNTIME_TEST_SHORT=1")
72 out, _ := testenv.RunWithTimeout(t, cmd)
76 var serializeBuild = make(chan bool, 2)
78 func buildTestProg(t *testing.T, binary string, flags ...string) (string, error) {
82 testenv.MustHaveGoBuild(t)
85 if testprog.dir == "" {
86 dir, err := os.MkdirTemp("", "go-build")
88 t.Fatalf("failed to create temp directory: %v", err)
91 toRemove = append(toRemove, dir)
94 if testprog.target == nil {
95 testprog.target = make(map[string]*buildexe)
99 name += "_" + strings.Join(flags, "_")
101 target, ok := testprog.target[name]
104 testprog.target[name] = target
109 // Unlock testprog while actually building, so that other
110 // tests can look up executables that were already built.
113 target.once.Do(func() {
114 // Only do two "go build"'s at a time,
115 // to keep load from getting too high.
116 serializeBuild <- true
117 defer func() { <-serializeBuild }()
119 // Don't get confused if testenv.GoToolPath calls t.Skip.
120 target.err = errors.New("building test called t.Skip")
122 exe := filepath.Join(dir, name+".exe")
124 t.Logf("running go build -o %s %s", exe, strings.Join(flags, " "))
125 cmd := exec.Command(testenv.GoToolPath(t), append([]string{"build", "-o", exe}, flags...)...)
126 cmd.Dir = "testdata/" + binary
127 out, err := testenv.CleanCmdEnv(cmd).CombinedOutput()
129 target.err = fmt.Errorf("building %s %v: %v\n%s", binary, flags, err, out)
136 return target.exe, target.err
139 func TestVDSO(t *testing.T) {
141 output := runTestProg(t, "testprog", "SignalInVDSO")
144 t.Fatalf("output:\n%s\n\nwanted:\n%s", output, want)
148 func testCrashHandler(t *testing.T, cgo bool) {
149 type crashTest struct {
154 output = runTestProg(t, "testprogcgo", "Crash")
156 output = runTestProg(t, "testprog", "Crash")
158 want := "main: recovered done\nnew-thread: recovered done\nsecond-new-thread: recovered done\nmain-again: recovered done\n"
160 t.Fatalf("output:\n%s\n\nwanted:\n%s", output, want)
164 func TestCrashHandler(t *testing.T) {
165 testCrashHandler(t, false)
168 func testDeadlock(t *testing.T, name string) {
169 // External linking brings in cgo, causing deadlock detection not working.
170 testenv.MustInternalLink(t)
172 output := runTestProg(t, "testprog", name)
173 want := "fatal error: all goroutines are asleep - deadlock!\n"
174 if !strings.HasPrefix(output, want) {
175 t.Fatalf("output does not start with %q:\n%s", want, output)
179 func TestSimpleDeadlock(t *testing.T) {
180 testDeadlock(t, "SimpleDeadlock")
183 func TestInitDeadlock(t *testing.T) {
184 testDeadlock(t, "InitDeadlock")
187 func TestLockedDeadlock(t *testing.T) {
188 testDeadlock(t, "LockedDeadlock")
191 func TestLockedDeadlock2(t *testing.T) {
192 testDeadlock(t, "LockedDeadlock2")
195 func TestGoexitDeadlock(t *testing.T) {
196 // External linking brings in cgo, causing deadlock detection not working.
197 testenv.MustInternalLink(t)
199 output := runTestProg(t, "testprog", "GoexitDeadlock")
200 want := "no goroutines (main called runtime.Goexit) - deadlock!"
201 if !strings.Contains(output, want) {
202 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
206 func TestStackOverflow(t *testing.T) {
207 output := runTestProg(t, "testprog", "StackOverflow")
209 "runtime: goroutine stack exceeds 1474560-byte limit\n",
210 "fatal error: stack overflow",
211 // information about the current SP and stack bounds
215 if !strings.HasPrefix(output, want[0]) {
216 t.Errorf("output does not start with %q", want[0])
218 for _, s := range want[1:] {
219 if !strings.Contains(output, s) {
220 t.Errorf("output does not contain %q", s)
224 t.Logf("output:\n%s", output)
228 func TestThreadExhaustion(t *testing.T) {
229 output := runTestProg(t, "testprog", "ThreadExhaustion")
230 want := "runtime: program exceeds 10-thread limit\nfatal error: thread exhaustion"
231 if !strings.HasPrefix(output, want) {
232 t.Fatalf("output does not start with %q:\n%s", want, output)
236 func TestRecursivePanic(t *testing.T) {
237 output := runTestProg(t, "testprog", "RecursivePanic")
242 if !strings.HasPrefix(output, want) {
243 t.Fatalf("output does not start with %q:\n%s", want, output)
248 func TestRecursivePanic2(t *testing.T) {
249 output := runTestProg(t, "testprog", "RecursivePanic2")
255 if !strings.HasPrefix(output, want) {
256 t.Fatalf("output does not start with %q:\n%s", want, output)
261 func TestRecursivePanic3(t *testing.T) {
262 output := runTestProg(t, "testprog", "RecursivePanic3")
263 want := `panic: first panic
266 if !strings.HasPrefix(output, want) {
267 t.Fatalf("output does not start with %q:\n%s", want, output)
272 func TestRecursivePanic4(t *testing.T) {
273 output := runTestProg(t, "testprog", "RecursivePanic4")
274 want := `panic: first panic [recovered]
277 if !strings.HasPrefix(output, want) {
278 t.Fatalf("output does not start with %q:\n%s", want, output)
283 func TestRecursivePanic5(t *testing.T) {
284 output := runTestProg(t, "testprog", "RecursivePanic5")
289 if !strings.HasPrefix(output, want) {
290 t.Fatalf("output does not start with %q:\n%s", want, output)
295 func TestGoexitCrash(t *testing.T) {
296 // External linking brings in cgo, causing deadlock detection not working.
297 testenv.MustInternalLink(t)
299 output := runTestProg(t, "testprog", "GoexitExit")
300 want := "no goroutines (main called runtime.Goexit) - deadlock!"
301 if !strings.Contains(output, want) {
302 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
306 func TestGoexitDefer(t *testing.T) {
307 c := make(chan struct{})
312 t.Errorf("non-nil recover during Goexit")
318 // Note: if the defer fails to run, we will get a deadlock here
322 func TestGoNil(t *testing.T) {
323 output := runTestProg(t, "testprog", "GoNil")
324 want := "go of nil func value"
325 if !strings.Contains(output, want) {
326 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
330 func TestMainGoroutineID(t *testing.T) {
331 output := runTestProg(t, "testprog", "MainGoroutineID")
332 want := "panic: test\n\ngoroutine 1 [running]:\n"
333 if !strings.HasPrefix(output, want) {
334 t.Fatalf("output does not start with %q:\n%s", want, output)
338 func TestNoHelperGoroutines(t *testing.T) {
339 output := runTestProg(t, "testprog", "NoHelperGoroutines")
340 matches := regexp.MustCompile(`goroutine [0-9]+ \[`).FindAllStringSubmatch(output, -1)
341 if len(matches) != 1 || matches[0][0] != "goroutine 1 [" {
342 t.Fatalf("want to see only goroutine 1, see:\n%s", output)
346 func TestBreakpoint(t *testing.T) {
347 output := runTestProg(t, "testprog", "Breakpoint")
348 // If runtime.Breakpoint() is inlined, then the stack trace prints
349 // "runtime.Breakpoint(...)" instead of "runtime.Breakpoint()".
350 want := "runtime.Breakpoint("
351 if !strings.Contains(output, want) {
352 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
356 func TestGoexitInPanic(t *testing.T) {
357 // External linking brings in cgo, causing deadlock detection not working.
358 testenv.MustInternalLink(t)
360 // see issue 8774: this code used to trigger an infinite recursion
361 output := runTestProg(t, "testprog", "GoexitInPanic")
362 want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
363 if !strings.HasPrefix(output, want) {
364 t.Fatalf("output does not start with %q:\n%s", want, output)
368 // Issue 14965: Runtime panics should be of type runtime.Error
369 func TestRuntimePanicWithRuntimeError(t *testing.T) {
370 testCases := [...]func(){
372 var m map[uint64]bool
376 ch := make(chan struct{})
381 var ch = make(chan struct{})
386 var s = make([]int, 2)
391 _ = make(chan bool, n)
394 close((chan bool)(nil))
398 for i, fn := range testCases {
399 got := panicValue(fn)
400 if _, ok := got.(runtime.Error); !ok {
401 t.Errorf("test #%d: recovered value %v(type %T) does not implement runtime.Error", i, got, got)
406 func panicValue(fn func()) (recovered interface{}) {
408 recovered = recover()
414 func TestPanicAfterGoexit(t *testing.T) {
415 // an uncaught panic should still work after goexit
416 output := runTestProg(t, "testprog", "PanicAfterGoexit")
417 want := "panic: hello"
418 if !strings.HasPrefix(output, want) {
419 t.Fatalf("output does not start with %q:\n%s", want, output)
423 func TestRecoveredPanicAfterGoexit(t *testing.T) {
424 // External linking brings in cgo, causing deadlock detection not working.
425 testenv.MustInternalLink(t)
427 output := runTestProg(t, "testprog", "RecoveredPanicAfterGoexit")
428 want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
429 if !strings.HasPrefix(output, want) {
430 t.Fatalf("output does not start with %q:\n%s", want, output)
434 func TestRecoverBeforePanicAfterGoexit(t *testing.T) {
435 // External linking brings in cgo, causing deadlock detection not working.
436 testenv.MustInternalLink(t)
439 output := runTestProg(t, "testprog", "RecoverBeforePanicAfterGoexit")
440 want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
441 if !strings.HasPrefix(output, want) {
442 t.Fatalf("output does not start with %q:\n%s", want, output)
446 func TestRecoverBeforePanicAfterGoexit2(t *testing.T) {
447 // External linking brings in cgo, causing deadlock detection not working.
448 testenv.MustInternalLink(t)
451 output := runTestProg(t, "testprog", "RecoverBeforePanicAfterGoexit2")
452 want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
453 if !strings.HasPrefix(output, want) {
454 t.Fatalf("output does not start with %q:\n%s", want, output)
458 func TestNetpollDeadlock(t *testing.T) {
460 output := runTestProg(t, "testprognet", "NetpollDeadlock")
462 if !strings.HasSuffix(output, want) {
463 t.Fatalf("output does not start with %q:\n%s", want, output)
467 func TestPanicTraceback(t *testing.T) {
469 output := runTestProg(t, "testprog", "PanicTraceback")
470 want := "panic: hello\n\tpanic: panic pt2\n\tpanic: panic pt1\n"
471 if !strings.HasPrefix(output, want) {
472 t.Fatalf("output does not start with %q:\n%s", want, output)
475 // Check functions in the traceback.
476 fns := []string{"main.pt1.func1", "panic", "main.pt2.func1", "panic", "main.pt2", "main.pt1"}
477 for _, fn := range fns {
478 re := regexp.MustCompile(`(?m)^` + regexp.QuoteMeta(fn) + `\(.*\n`)
479 idx := re.FindStringIndex(output)
481 t.Fatalf("expected %q function in traceback:\n%s", fn, output)
483 output = output[idx[1]:]
487 func testPanicDeadlock(t *testing.T, name string, want string) {
489 output := runTestProg(t, "testprog", name)
490 if !strings.HasPrefix(output, want) {
491 t.Fatalf("output does not start with %q:\n%s", want, output)
495 func TestPanicDeadlockGosched(t *testing.T) {
496 testPanicDeadlock(t, "GoschedInPanic", "panic: errorThatGosched\n\n")
499 func TestPanicDeadlockSyscall(t *testing.T) {
500 testPanicDeadlock(t, "SyscallInPanic", "1\n2\npanic: 3\n\n")
503 func TestPanicLoop(t *testing.T) {
504 output := runTestProg(t, "testprog", "PanicLoop")
505 if want := "panic while printing panic value"; !strings.Contains(output, want) {
506 t.Errorf("output does not contain %q:\n%s", want, output)
510 func TestMemPprof(t *testing.T) {
511 testenv.MustHaveGoRun(t)
513 exe, err := buildTestProg(t, "testprog")
518 got, err := testenv.CleanCmdEnv(exec.Command(exe, "MemProf")).CombinedOutput()
522 fn := strings.TrimSpace(string(got))
525 for try := 0; try < 2; try++ {
526 cmd := testenv.CleanCmdEnv(exec.Command(testenv.GoToolPath(t), "tool", "pprof", "-alloc_space", "-top"))
527 // Check that pprof works both with and without explicit executable on command line.
529 cmd.Args = append(cmd.Args, exe, fn)
531 cmd.Args = append(cmd.Args, fn)
534 for i, e := range cmd.Env {
535 if strings.HasPrefix(e, "PPROF_TMPDIR=") {
536 cmd.Env[i] = "PPROF_TMPDIR=" + os.TempDir()
542 cmd.Env = append(cmd.Env, "PPROF_TMPDIR="+os.TempDir())
545 top, err := cmd.CombinedOutput()
546 t.Logf("%s:\n%s", cmd.Args, top)
549 } else if !bytes.Contains(top, []byte("MemProf")) {
550 t.Error("missing MemProf in pprof output")
555 var concurrentMapTest = flag.Bool("run_concurrent_map_tests", false, "also run flaky concurrent map tests")
557 func TestConcurrentMapWrites(t *testing.T) {
558 if !*concurrentMapTest {
559 t.Skip("skipping without -run_concurrent_map_tests")
561 testenv.MustHaveGoRun(t)
562 output := runTestProg(t, "testprog", "concurrentMapWrites")
563 want := "fatal error: concurrent map writes"
564 if !strings.HasPrefix(output, want) {
565 t.Fatalf("output does not start with %q:\n%s", want, output)
568 func TestConcurrentMapReadWrite(t *testing.T) {
569 if !*concurrentMapTest {
570 t.Skip("skipping without -run_concurrent_map_tests")
572 testenv.MustHaveGoRun(t)
573 output := runTestProg(t, "testprog", "concurrentMapReadWrite")
574 want := "fatal error: concurrent map read and map write"
575 if !strings.HasPrefix(output, want) {
576 t.Fatalf("output does not start with %q:\n%s", want, output)
579 func TestConcurrentMapIterateWrite(t *testing.T) {
580 if !*concurrentMapTest {
581 t.Skip("skipping without -run_concurrent_map_tests")
583 testenv.MustHaveGoRun(t)
584 output := runTestProg(t, "testprog", "concurrentMapIterateWrite")
585 want := "fatal error: concurrent map iteration and map write"
586 if !strings.HasPrefix(output, want) {
587 t.Fatalf("output does not start with %q:\n%s", want, output)
595 func (p *point) negate() {
600 // Test for issue #10152.
601 func TestPanicInlined(t *testing.T) {
605 t.Fatalf("recover failed")
607 buf := make([]byte, 2048)
608 n := runtime.Stack(buf, false)
610 if !bytes.Contains(buf, []byte("(*point).negate(")) {
611 t.Fatalf("expecting stack trace to contain call to (*point).negate()")
619 // Test for issues #3934 and #20018.
620 // We want to delay exiting until a panic print is complete.
621 func TestPanicRace(t *testing.T) {
622 testenv.MustHaveGoRun(t)
624 exe, err := buildTestProg(t, "testprog")
629 // The test is intentionally racy, and in my testing does not
630 // produce the expected output about 0.05% of the time.
631 // So run the program in a loop and only fail the test if we
632 // get the wrong output ten times in a row.
635 for i := 0; i < tries; i++ {
636 got, err := testenv.CleanCmdEnv(exec.Command(exe, "PanicRace")).CombinedOutput()
638 t.Logf("try %d: program exited successfully, should have failed", i+1)
643 t.Logf("try %d:\n", i+1)
652 for _, want := range wants {
653 if !bytes.Contains(got, []byte(want)) {
654 t.Logf("did not find expected string %q", want)
659 // Test generated expected output.
662 t.Errorf("test ran %d times without producing expected output", tries)
665 func TestBadTraceback(t *testing.T) {
666 output := runTestProg(t, "testprog", "BadTraceback")
667 for _, want := range []string{
668 "runtime: unexpected return pc",
670 "00000bad", // Smashed LR in hex dump
671 "<main.badLR", // Symbolization in hex dump (badLR1 or badLR2)
673 if !strings.Contains(output, want) {
674 t.Errorf("output does not contain %q:\n%s", want, output)
679 func TestTimePprof(t *testing.T) {
680 // This test is unreliable on any system in which nanotime
682 switch runtime.GOOS {
683 case "aix", "darwin", "illumos", "openbsd", "solaris":
684 t.Skipf("skipping on %s because nanotime calls libc", runtime.GOOS)
687 // Pass GOTRACEBACK for issue #41120 to try to get more
688 // information on timeout.
689 fn := runTestProg(t, "testprog", "TimeProf", "GOTRACEBACK=crash")
690 fn = strings.TrimSpace(fn)
693 cmd := testenv.CleanCmdEnv(exec.Command(testenv.GoToolPath(t), "tool", "pprof", "-top", "-nodecount=1", fn))
694 cmd.Env = append(cmd.Env, "PPROF_TMPDIR="+os.TempDir())
695 top, err := cmd.CombinedOutput()
699 } else if bytes.Contains(top, []byte("ExternalCode")) {
700 t.Error("profiler refers to ExternalCode")
704 // Test that runtime.abort does so.
705 func TestAbort(t *testing.T) {
706 // Pass GOTRACEBACK to ensure we get runtime frames.
707 output := runTestProg(t, "testprog", "Abort", "GOTRACEBACK=system")
708 if want := "runtime.abort"; !strings.Contains(output, want) {
709 t.Errorf("output does not contain %q:\n%s", want, output)
711 if strings.Contains(output, "BAD") {
712 t.Errorf("output contains BAD:\n%s", output)
714 // Check that it's a signal traceback.
716 // For systems that use a breakpoint, check specifically for that.
717 switch runtime.GOARCH {
719 switch runtime.GOOS {
721 want = "sys: breakpoint"
723 want = "Exception 0x80000003"
728 if !strings.Contains(output, want) {
729 t.Errorf("output does not contain %q:\n%s", want, output)
733 // For TestRuntimePanic: test a panic in the runtime package without
734 // involving the testing harness.
736 if os.Getenv("GO_TEST_RUNTIME_PANIC") == "1" {
738 if r := recover(); r != nil {
739 // We expect to crash, so exit 0
740 // to indicate failure.
744 runtime.PanicForTesting(nil, 1)
745 // We expect to crash, so exit 0 to indicate failure.
750 func TestRuntimePanic(t *testing.T) {
751 testenv.MustHaveExec(t)
752 cmd := testenv.CleanCmdEnv(exec.Command(os.Args[0], "-test.run=TestRuntimePanic"))
753 cmd.Env = append(cmd.Env, "GO_TEST_RUNTIME_PANIC=1")
754 out, err := cmd.CombinedOutput()
757 t.Error("child process did not fail")
758 } else if want := "runtime.unexportedPanicForTesting"; !bytes.Contains(out, []byte(want)) {
759 t.Errorf("output did not contain expected string %q", want)
763 // Test that g0 stack overflows are handled gracefully.
764 func TestG0StackOverflow(t *testing.T) {
765 testenv.MustHaveExec(t)
767 switch runtime.GOOS {
768 case "darwin", "dragonfly", "freebsd", "linux", "netbsd", "openbsd", "android":
769 t.Skipf("g0 stack is wrong on pthread platforms (see golang.org/issue/26061)")
772 if os.Getenv("TEST_G0_STACK_OVERFLOW") != "1" {
773 cmd := testenv.CleanCmdEnv(exec.Command(os.Args[0], "-test.run=TestG0StackOverflow", "-test.v"))
774 cmd.Env = append(cmd.Env, "TEST_G0_STACK_OVERFLOW=1")
775 out, err := cmd.CombinedOutput()
776 // Don't check err since it's expected to crash.
777 if n := strings.Count(string(out), "morestack on g0\n"); n != 1 {
778 t.Fatalf("%s\n(exit status %v)", out, err)
780 // Check that it's a signal-style traceback.
781 if runtime.GOOS != "windows" {
782 if want := "PC="; !strings.Contains(string(out), want) {
783 t.Errorf("output does not contain %q:\n%s", want, out)
789 runtime.G0StackOverflow()
792 // Test that panic message is not clobbered.
794 func TestDoublePanic(t *testing.T) {
795 output := runTestProg(t, "testprog", "DoublePanic", "GODEBUG=clobberfree=1")
796 wants := []string{"panic: XXX", "panic: YYY"}
797 for _, want := range wants {
798 if !strings.Contains(output, want) {
799 t.Errorf("output:\n%s\n\nwant output containing: %s", output, want)