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 {
47 func runTestProg(t *testing.T, binary, name string, env ...string) string {
52 testenv.MustHaveGoBuild(t)
54 exe, err := buildTestProg(t, binary)
59 return runBuiltTestProg(t, exe, name, env...)
62 func runBuiltTestProg(t *testing.T, exe, name string, env ...string) string {
69 ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
71 cmd := testenv.CleanCmdEnv(testenv.CommandContext(t, ctx, exe, name))
72 cmd.Env = append(cmd.Env, env...)
74 cmd.Env = append(cmd.Env, "RUNTIME_TEST_SHORT=1")
76 out, err := cmd.CombinedOutput()
78 if _, ok := err.(*exec.ExitError); ok {
79 t.Logf("%v: %v", cmd, err)
81 t.Fatalf("%v failed to start: %v", cmd, err)
87 var serializeBuild = make(chan bool, 2)
89 func buildTestProg(t *testing.T, binary string, flags ...string) (string, error) {
93 testenv.MustHaveGoBuild(t)
96 if testprog.dir == "" {
97 dir, err := os.MkdirTemp("", "go-build")
99 t.Fatalf("failed to create temp directory: %v", err)
102 toRemove = append(toRemove, dir)
105 if testprog.target == nil {
106 testprog.target = make(map[string]*buildexe)
110 name += "_" + strings.Join(flags, "_")
112 target, ok := testprog.target[name]
115 testprog.target[name] = target
120 // Unlock testprog while actually building, so that other
121 // tests can look up executables that were already built.
124 target.once.Do(func() {
125 // Only do two "go build"'s at a time,
126 // to keep load from getting too high.
127 serializeBuild <- true
128 defer func() { <-serializeBuild }()
130 // Don't get confused if testenv.GoToolPath calls t.Skip.
131 target.err = errors.New("building test called t.Skip")
133 exe := filepath.Join(dir, name+".exe")
135 t.Logf("running go build -o %s %s", exe, strings.Join(flags, " "))
136 cmd := exec.Command(testenv.GoToolPath(t), append([]string{"build", "-o", exe}, flags...)...)
137 cmd.Dir = "testdata/" + binary
138 out, err := testenv.CleanCmdEnv(cmd).CombinedOutput()
140 target.err = fmt.Errorf("building %s %v: %v\n%s", binary, flags, err, out)
147 return target.exe, target.err
150 func TestVDSO(t *testing.T) {
152 output := runTestProg(t, "testprog", "SignalInVDSO")
155 t.Fatalf("output:\n%s\n\nwanted:\n%s", output, want)
159 func testCrashHandler(t *testing.T, cgo bool) {
160 type crashTest struct {
165 output = runTestProg(t, "testprogcgo", "Crash")
167 output = runTestProg(t, "testprog", "Crash")
169 want := "main: recovered done\nnew-thread: recovered done\nsecond-new-thread: recovered done\nmain-again: recovered done\n"
171 t.Fatalf("output:\n%s\n\nwanted:\n%s", output, want)
175 func TestCrashHandler(t *testing.T) {
176 testCrashHandler(t, false)
179 func testDeadlock(t *testing.T, name string) {
180 // External linking brings in cgo, causing deadlock detection not working.
181 testenv.MustInternalLink(t)
183 output := runTestProg(t, "testprog", name)
184 want := "fatal error: all goroutines are asleep - deadlock!\n"
185 if !strings.HasPrefix(output, want) {
186 t.Fatalf("output does not start with %q:\n%s", want, output)
190 func TestSimpleDeadlock(t *testing.T) {
191 testDeadlock(t, "SimpleDeadlock")
194 func TestInitDeadlock(t *testing.T) {
195 testDeadlock(t, "InitDeadlock")
198 func TestLockedDeadlock(t *testing.T) {
199 testDeadlock(t, "LockedDeadlock")
202 func TestLockedDeadlock2(t *testing.T) {
203 testDeadlock(t, "LockedDeadlock2")
206 func TestGoexitDeadlock(t *testing.T) {
207 // External linking brings in cgo, causing deadlock detection not working.
208 testenv.MustInternalLink(t)
210 output := runTestProg(t, "testprog", "GoexitDeadlock")
211 want := "no goroutines (main called runtime.Goexit) - deadlock!"
212 if !strings.Contains(output, want) {
213 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
217 func TestStackOverflow(t *testing.T) {
218 output := runTestProg(t, "testprog", "StackOverflow")
220 "runtime: goroutine stack exceeds 1474560-byte limit\n",
221 "fatal error: stack overflow",
222 // information about the current SP and stack bounds
226 if !strings.HasPrefix(output, want[0]) {
227 t.Errorf("output does not start with %q", want[0])
229 for _, s := range want[1:] {
230 if !strings.Contains(output, s) {
231 t.Errorf("output does not contain %q", s)
235 t.Logf("output:\n%s", output)
239 func TestThreadExhaustion(t *testing.T) {
240 output := runTestProg(t, "testprog", "ThreadExhaustion")
241 want := "runtime: program exceeds 10-thread limit\nfatal error: thread exhaustion"
242 if !strings.HasPrefix(output, want) {
243 t.Fatalf("output does not start with %q:\n%s", want, output)
247 func TestRecursivePanic(t *testing.T) {
248 output := runTestProg(t, "testprog", "RecursivePanic")
253 if !strings.HasPrefix(output, want) {
254 t.Fatalf("output does not start with %q:\n%s", want, output)
259 func TestRecursivePanic2(t *testing.T) {
260 output := runTestProg(t, "testprog", "RecursivePanic2")
266 if !strings.HasPrefix(output, want) {
267 t.Fatalf("output does not start with %q:\n%s", want, output)
272 func TestRecursivePanic3(t *testing.T) {
273 output := runTestProg(t, "testprog", "RecursivePanic3")
274 want := `panic: first panic
277 if !strings.HasPrefix(output, want) {
278 t.Fatalf("output does not start with %q:\n%s", want, output)
283 func TestRecursivePanic4(t *testing.T) {
284 output := runTestProg(t, "testprog", "RecursivePanic4")
285 want := `panic: first panic [recovered]
288 if !strings.HasPrefix(output, want) {
289 t.Fatalf("output does not start with %q:\n%s", want, output)
294 func TestRecursivePanic5(t *testing.T) {
295 output := runTestProg(t, "testprog", "RecursivePanic5")
300 if !strings.HasPrefix(output, want) {
301 t.Fatalf("output does not start with %q:\n%s", want, output)
306 func TestGoexitCrash(t *testing.T) {
307 // External linking brings in cgo, causing deadlock detection not working.
308 testenv.MustInternalLink(t)
310 output := runTestProg(t, "testprog", "GoexitExit")
311 want := "no goroutines (main called runtime.Goexit) - deadlock!"
312 if !strings.Contains(output, want) {
313 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
317 func TestGoexitDefer(t *testing.T) {
318 c := make(chan struct{})
323 t.Errorf("non-nil recover during Goexit")
329 // Note: if the defer fails to run, we will get a deadlock here
333 func TestGoNil(t *testing.T) {
334 output := runTestProg(t, "testprog", "GoNil")
335 want := "go of nil func value"
336 if !strings.Contains(output, want) {
337 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
341 func TestMainGoroutineID(t *testing.T) {
342 output := runTestProg(t, "testprog", "MainGoroutineID")
343 want := "panic: test\n\ngoroutine 1 [running]:\n"
344 if !strings.HasPrefix(output, want) {
345 t.Fatalf("output does not start with %q:\n%s", want, output)
349 func TestNoHelperGoroutines(t *testing.T) {
350 output := runTestProg(t, "testprog", "NoHelperGoroutines")
351 matches := regexp.MustCompile(`goroutine [0-9]+ \[`).FindAllStringSubmatch(output, -1)
352 if len(matches) != 1 || matches[0][0] != "goroutine 1 [" {
353 t.Fatalf("want to see only goroutine 1, see:\n%s", output)
357 func TestBreakpoint(t *testing.T) {
358 output := runTestProg(t, "testprog", "Breakpoint")
359 // If runtime.Breakpoint() is inlined, then the stack trace prints
360 // "runtime.Breakpoint(...)" instead of "runtime.Breakpoint()".
361 want := "runtime.Breakpoint("
362 if !strings.Contains(output, want) {
363 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
367 func TestGoexitInPanic(t *testing.T) {
368 // External linking brings in cgo, causing deadlock detection not working.
369 testenv.MustInternalLink(t)
371 // see issue 8774: this code used to trigger an infinite recursion
372 output := runTestProg(t, "testprog", "GoexitInPanic")
373 want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
374 if !strings.HasPrefix(output, want) {
375 t.Fatalf("output does not start with %q:\n%s", want, output)
379 // Issue 14965: Runtime panics should be of type runtime.Error
380 func TestRuntimePanicWithRuntimeError(t *testing.T) {
381 testCases := [...]func(){
383 var m map[uint64]bool
387 ch := make(chan struct{})
392 var ch = make(chan struct{})
397 var s = make([]int, 2)
402 _ = make(chan bool, n)
405 close((chan bool)(nil))
409 for i, fn := range testCases {
410 got := panicValue(fn)
411 if _, ok := got.(runtime.Error); !ok {
412 t.Errorf("test #%d: recovered value %v(type %T) does not implement runtime.Error", i, got, got)
417 func panicValue(fn func()) (recovered any) {
419 recovered = recover()
425 func TestPanicAfterGoexit(t *testing.T) {
426 // an uncaught panic should still work after goexit
427 output := runTestProg(t, "testprog", "PanicAfterGoexit")
428 want := "panic: hello"
429 if !strings.HasPrefix(output, want) {
430 t.Fatalf("output does not start with %q:\n%s", want, output)
434 func TestRecoveredPanicAfterGoexit(t *testing.T) {
435 // External linking brings in cgo, causing deadlock detection not working.
436 testenv.MustInternalLink(t)
438 output := runTestProg(t, "testprog", "RecoveredPanicAfterGoexit")
439 want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
440 if !strings.HasPrefix(output, want) {
441 t.Fatalf("output does not start with %q:\n%s", want, output)
445 func TestRecoverBeforePanicAfterGoexit(t *testing.T) {
446 // External linking brings in cgo, causing deadlock detection not working.
447 testenv.MustInternalLink(t)
450 output := runTestProg(t, "testprog", "RecoverBeforePanicAfterGoexit")
451 want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
452 if !strings.HasPrefix(output, want) {
453 t.Fatalf("output does not start with %q:\n%s", want, output)
457 func TestRecoverBeforePanicAfterGoexit2(t *testing.T) {
458 // External linking brings in cgo, causing deadlock detection not working.
459 testenv.MustInternalLink(t)
462 output := runTestProg(t, "testprog", "RecoverBeforePanicAfterGoexit2")
463 want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
464 if !strings.HasPrefix(output, want) {
465 t.Fatalf("output does not start with %q:\n%s", want, output)
469 func TestNetpollDeadlock(t *testing.T) {
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 "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 // This test is unreliable on any system in which nanotime
693 switch runtime.GOOS {
694 case "aix", "darwin", "illumos", "openbsd", "solaris":
695 t.Skipf("skipping on %s because nanotime calls libc", runtime.GOOS)
698 // Pass GOTRACEBACK for issue #41120 to try to get more
699 // information on timeout.
700 fn := runTestProg(t, "testprog", "TimeProf", "GOTRACEBACK=crash")
701 fn = strings.TrimSpace(fn)
704 cmd := testenv.CleanCmdEnv(exec.Command(testenv.GoToolPath(t), "tool", "pprof", "-top", "-nodecount=1", fn))
705 cmd.Env = append(cmd.Env, "PPROF_TMPDIR="+os.TempDir())
706 top, err := cmd.CombinedOutput()
710 } else if bytes.Contains(top, []byte("ExternalCode")) {
711 t.Error("profiler refers to ExternalCode")
715 // Test that runtime.abort does so.
716 func TestAbort(t *testing.T) {
717 // Pass GOTRACEBACK to ensure we get runtime frames.
718 output := runTestProg(t, "testprog", "Abort", "GOTRACEBACK=system")
719 if want := "runtime.abort"; !strings.Contains(output, want) {
720 t.Errorf("output does not contain %q:\n%s", want, output)
722 if strings.Contains(output, "BAD") {
723 t.Errorf("output contains BAD:\n%s", output)
725 // Check that it's a signal traceback.
727 // For systems that use a breakpoint, check specifically for that.
728 switch runtime.GOARCH {
730 switch runtime.GOOS {
732 want = "sys: breakpoint"
734 want = "Exception 0x80000003"
739 if !strings.Contains(output, want) {
740 t.Errorf("output does not contain %q:\n%s", want, output)
744 // For TestRuntimePanic: test a panic in the runtime package without
745 // involving the testing harness.
747 if os.Getenv("GO_TEST_RUNTIME_PANIC") == "1" {
749 if r := recover(); r != nil {
750 // We expect to crash, so exit 0
751 // to indicate failure.
755 runtime.PanicForTesting(nil, 1)
756 // We expect to crash, so exit 0 to indicate failure.
761 func TestRuntimePanic(t *testing.T) {
762 testenv.MustHaveExec(t)
763 cmd := testenv.CleanCmdEnv(exec.Command(os.Args[0], "-test.run=TestRuntimePanic"))
764 cmd.Env = append(cmd.Env, "GO_TEST_RUNTIME_PANIC=1")
765 out, err := cmd.CombinedOutput()
768 t.Error("child process did not fail")
769 } else if want := "runtime.unexportedPanicForTesting"; !bytes.Contains(out, []byte(want)) {
770 t.Errorf("output did not contain expected string %q", want)
774 // Test that g0 stack overflows are handled gracefully.
775 func TestG0StackOverflow(t *testing.T) {
776 testenv.MustHaveExec(t)
778 switch runtime.GOOS {
779 case "darwin", "dragonfly", "freebsd", "linux", "netbsd", "openbsd", "android":
780 t.Skipf("g0 stack is wrong on pthread platforms (see golang.org/issue/26061)")
783 if os.Getenv("TEST_G0_STACK_OVERFLOW") != "1" {
784 cmd := testenv.CleanCmdEnv(exec.Command(os.Args[0], "-test.run=TestG0StackOverflow", "-test.v"))
785 cmd.Env = append(cmd.Env, "TEST_G0_STACK_OVERFLOW=1")
786 out, err := cmd.CombinedOutput()
787 // Don't check err since it's expected to crash.
788 if n := strings.Count(string(out), "morestack on g0\n"); n != 1 {
789 t.Fatalf("%s\n(exit status %v)", out, err)
791 // Check that it's a signal-style traceback.
792 if runtime.GOOS != "windows" {
793 if want := "PC="; !strings.Contains(string(out), want) {
794 t.Errorf("output does not contain %q:\n%s", want, out)
800 runtime.G0StackOverflow()
803 // Test that panic message is not clobbered.
805 func TestDoublePanic(t *testing.T) {
806 output := runTestProg(t, "testprog", "DoublePanic", "GODEBUG=clobberfree=1")
807 wants := []string{"panic: XXX", "panic: YYY"}
808 for _, want := range wants {
809 if !strings.Contains(output, want) {
810 t.Errorf("output:\n%s\n\nwant output containing: %s", output, want)
815 // Test that panic while panicking discards error message
817 func TestPanicWhilePanicking(t *testing.T) {
823 "panic while printing panic value: important error message",
827 "panic while printing panic value: important stringer message",
831 "panic while printing panic value: type",
835 "panic while printing panic value: type",
836 "DoubleStringerPanic",
839 "panic while printing panic value: type",
843 "important string message",
851 for _, x := range tests {
852 output := runTestProg(t, "testprog", x.Func)
853 if !strings.Contains(output, x.Want) {
854 t.Errorf("output does not contain %q:\n%s", x.Want, output)
859 func TestPanicOnUnsafeSlice(t *testing.T) {
860 output := runTestProg(t, "testprog", "panicOnNilAndEleSizeIsZero")
861 want := "panic: runtime error: unsafe.Slice: ptr is nil and len is not zero"
862 if !strings.Contains(output, want) {
863 t.Errorf("output does not contain %q:\n%s", want, output)