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 cmd := testenv.CleanCmdEnv(exec.Command(exe, name))
59 cmd.Env = append(cmd.Env, env...)
61 cmd.Env = append(cmd.Env, "RUNTIME_TEST_SHORT=1")
66 if err := cmd.Start(); err != nil {
67 t.Fatalf("starting %s %s: %v", binary, name, err)
70 // If the process doesn't complete within 1 minute,
71 // assume it is hanging and kill it to get a stack trace.
73 done := make(chan bool)
76 // This GOARCH/GOOS test is copied from cmd/dist/test.go.
77 // TODO(iant): Have cmd/dist update the environment variable.
78 if runtime.GOARCH == "arm" || runtime.GOOS == "windows" {
81 if s := os.Getenv("GO_TEST_TIMEOUT_SCALE"); s != "" {
82 if sc, err := strconv.Atoi(s); err == nil {
89 case <-time.After(time.Duration(scale) * time.Minute):
94 if err := cmd.Wait(); err != nil {
95 t.Logf("%s %s exit status: %v", binary, name, err)
102 func buildTestProg(t *testing.T, binary string, flags ...string) (string, error) {
110 defer testprog.Unlock()
111 if testprog.dir == "" {
112 dir, err := ioutil.TempDir("", "go-build")
114 t.Fatalf("failed to create temp directory: %v", err)
117 toRemove = append(toRemove, dir)
120 if testprog.target == nil {
121 testprog.target = make(map[string]buildexe)
125 name += "_" + strings.Join(flags, "_")
127 target, ok := testprog.target[name]
129 return target.exe, target.err
132 exe := filepath.Join(testprog.dir, name+".exe")
133 cmd := exec.Command(testenv.GoToolPath(t), append([]string{"build", "-o", exe}, flags...)...)
134 cmd.Dir = "testdata/" + binary
135 out, err := testenv.CleanCmdEnv(cmd).CombinedOutput()
137 target.err = fmt.Errorf("building %s %v: %v\n%s", binary, flags, err, out)
138 testprog.target[name] = target
139 return "", target.err
142 testprog.target[name] = target
146 func TestVDSO(t *testing.T) {
148 output := runTestProg(t, "testprog", "SignalInVDSO")
151 t.Fatalf("output:\n%s\n\nwanted:\n%s", output, want)
156 staleRuntimeOnce sync.Once // guards init of staleRuntimeErr
157 staleRuntimeErr error
160 func checkStaleRuntime(t *testing.T) {
161 staleRuntimeOnce.Do(func() {
162 // 'go run' uses the installed copy of runtime.a, which may be out of date.
163 out, err := testenv.CleanCmdEnv(exec.Command(testenv.GoToolPath(t), "list", "-gcflags=all="+os.Getenv("GO_GCFLAGS"), "-f", "{{.Stale}}", "runtime")).CombinedOutput()
165 staleRuntimeErr = fmt.Errorf("failed to execute 'go list': %v\n%v", err, string(out))
168 if string(out) != "false\n" {
169 t.Logf("go list -f {{.Stale}} runtime:\n%s", out)
170 out, err := testenv.CleanCmdEnv(exec.Command(testenv.GoToolPath(t), "list", "-gcflags=all="+os.Getenv("GO_GCFLAGS"), "-f", "{{.StaleReason}}", "runtime")).CombinedOutput()
172 t.Logf("go list -f {{.StaleReason}} failed: %v", err)
174 t.Logf("go list -f {{.StaleReason}} runtime:\n%s", out)
175 staleRuntimeErr = fmt.Errorf("Stale runtime.a. Run 'go install runtime'.")
178 if staleRuntimeErr != nil {
179 t.Fatal(staleRuntimeErr)
183 func testCrashHandler(t *testing.T, cgo bool) {
184 type crashTest struct {
189 output = runTestProg(t, "testprogcgo", "Crash")
191 output = runTestProg(t, "testprog", "Crash")
193 want := "main: recovered done\nnew-thread: recovered done\nsecond-new-thread: recovered done\nmain-again: recovered done\n"
195 t.Fatalf("output:\n%s\n\nwanted:\n%s", output, want)
199 func TestCrashHandler(t *testing.T) {
200 testCrashHandler(t, false)
203 func testDeadlock(t *testing.T, name string) {
204 output := runTestProg(t, "testprog", name)
205 want := "fatal error: all goroutines are asleep - deadlock!\n"
206 if !strings.HasPrefix(output, want) {
207 t.Fatalf("output does not start with %q:\n%s", want, output)
211 func TestSimpleDeadlock(t *testing.T) {
212 testDeadlock(t, "SimpleDeadlock")
215 func TestInitDeadlock(t *testing.T) {
216 testDeadlock(t, "InitDeadlock")
219 func TestLockedDeadlock(t *testing.T) {
220 testDeadlock(t, "LockedDeadlock")
223 func TestLockedDeadlock2(t *testing.T) {
224 testDeadlock(t, "LockedDeadlock2")
227 func TestGoexitDeadlock(t *testing.T) {
228 output := runTestProg(t, "testprog", "GoexitDeadlock")
229 want := "no goroutines (main called runtime.Goexit) - deadlock!"
230 if !strings.Contains(output, want) {
231 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
235 func TestStackOverflow(t *testing.T) {
236 output := runTestProg(t, "testprog", "StackOverflow")
237 want := "runtime: goroutine stack exceeds 1474560-byte limit\nfatal error: stack overflow"
238 if !strings.HasPrefix(output, want) {
239 t.Fatalf("output does not start with %q:\n%s", want, 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 TestGoexitCrash(t *testing.T) {
288 output := runTestProg(t, "testprog", "GoexitExit")
289 want := "no goroutines (main called runtime.Goexit) - deadlock!"
290 if !strings.Contains(output, want) {
291 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
295 func TestGoexitDefer(t *testing.T) {
296 c := make(chan struct{})
301 t.Errorf("non-nil recover during Goexit")
307 // Note: if the defer fails to run, we will get a deadlock here
311 func TestGoNil(t *testing.T) {
312 output := runTestProg(t, "testprog", "GoNil")
313 want := "go of nil func value"
314 if !strings.Contains(output, want) {
315 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
319 func TestMainGoroutineID(t *testing.T) {
320 output := runTestProg(t, "testprog", "MainGoroutineID")
321 want := "panic: test\n\ngoroutine 1 [running]:\n"
322 if !strings.HasPrefix(output, want) {
323 t.Fatalf("output does not start with %q:\n%s", want, output)
327 func TestNoHelperGoroutines(t *testing.T) {
328 output := runTestProg(t, "testprog", "NoHelperGoroutines")
329 matches := regexp.MustCompile(`goroutine [0-9]+ \[`).FindAllStringSubmatch(output, -1)
330 if len(matches) != 1 || matches[0][0] != "goroutine 1 [" {
331 t.Fatalf("want to see only goroutine 1, see:\n%s", output)
335 func TestBreakpoint(t *testing.T) {
336 output := runTestProg(t, "testprog", "Breakpoint")
337 // If runtime.Breakpoint() is inlined, then the stack trace prints
338 // "runtime.Breakpoint(...)" instead of "runtime.Breakpoint()".
339 want := "runtime.Breakpoint("
340 if !strings.Contains(output, want) {
341 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
345 func TestGoexitInPanic(t *testing.T) {
346 // see issue 8774: this code used to trigger an infinite recursion
347 output := runTestProg(t, "testprog", "GoexitInPanic")
348 want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
349 if !strings.HasPrefix(output, want) {
350 t.Fatalf("output does not start with %q:\n%s", want, output)
354 // Issue 14965: Runtime panics should be of type runtime.Error
355 func TestRuntimePanicWithRuntimeError(t *testing.T) {
356 testCases := [...]func(){
358 var m map[uint64]bool
362 ch := make(chan struct{})
367 var ch = make(chan struct{})
372 var s = make([]int, 2)
377 _ = make(chan bool, n)
380 close((chan bool)(nil))
384 for i, fn := range testCases {
385 got := panicValue(fn)
386 if _, ok := got.(runtime.Error); !ok {
387 t.Errorf("test #%d: recovered value %v(type %T) does not implement runtime.Error", i, got, got)
392 func panicValue(fn func()) (recovered interface{}) {
394 recovered = recover()
400 func TestPanicAfterGoexit(t *testing.T) {
401 // an uncaught panic should still work after goexit
402 output := runTestProg(t, "testprog", "PanicAfterGoexit")
403 want := "panic: hello"
404 if !strings.HasPrefix(output, want) {
405 t.Fatalf("output does not start with %q:\n%s", want, output)
409 func TestRecoveredPanicAfterGoexit(t *testing.T) {
410 output := runTestProg(t, "testprog", "RecoveredPanicAfterGoexit")
411 want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
412 if !strings.HasPrefix(output, want) {
413 t.Fatalf("output does not start with %q:\n%s", want, output)
417 func TestRecoverBeforePanicAfterGoexit(t *testing.T) {
418 // 1. defer a function that recovers
419 // 2. defer a function that panics
421 // Goexit should run the #2 defer. Its panic
422 // should be caught by the #1 defer, and execution
423 // should resume in the caller. Like the Goexit
437 func TestNetpollDeadlock(t *testing.T) {
438 if os.Getenv("GO_BUILDER_NAME") == "darwin-amd64-10_12" {
439 // A suspected kernel bug in macOS 10.12 occasionally results in
440 // an apparent deadlock when dialing localhost. The errors have not
441 // been observed on newer versions of the OS, so we don't plan to work
442 // around them. See https://golang.org/issue/22019.
443 testenv.SkipFlaky(t, 22019)
447 output := runTestProg(t, "testprognet", "NetpollDeadlock")
449 if !strings.HasSuffix(output, want) {
450 t.Fatalf("output does not start with %q:\n%s", want, output)
454 func TestPanicTraceback(t *testing.T) {
456 output := runTestProg(t, "testprog", "PanicTraceback")
457 want := "panic: hello\n\tpanic: panic pt2\n\tpanic: panic pt1\n"
458 if !strings.HasPrefix(output, want) {
459 t.Fatalf("output does not start with %q:\n%s", want, output)
462 // Check functions in the traceback.
463 fns := []string{"main.pt1.func1", "panic", "main.pt2.func1", "panic", "main.pt2", "main.pt1"}
464 for _, fn := range fns {
465 re := regexp.MustCompile(`(?m)^` + regexp.QuoteMeta(fn) + `\(.*\n`)
466 idx := re.FindStringIndex(output)
468 t.Fatalf("expected %q function in traceback:\n%s", fn, output)
470 output = output[idx[1]:]
474 func testPanicDeadlock(t *testing.T, name string, want string) {
476 output := runTestProg(t, "testprog", name)
477 if !strings.HasPrefix(output, want) {
478 t.Fatalf("output does not start with %q:\n%s", want, output)
482 func TestPanicDeadlockGosched(t *testing.T) {
483 testPanicDeadlock(t, "GoschedInPanic", "panic: errorThatGosched\n\n")
486 func TestPanicDeadlockSyscall(t *testing.T) {
487 testPanicDeadlock(t, "SyscallInPanic", "1\n2\npanic: 3\n\n")
490 func TestPanicLoop(t *testing.T) {
491 output := runTestProg(t, "testprog", "PanicLoop")
492 if want := "panic while printing panic value"; !strings.Contains(output, want) {
493 t.Errorf("output does not contain %q:\n%s", want, output)
497 func TestMemPprof(t *testing.T) {
498 testenv.MustHaveGoRun(t)
500 exe, err := buildTestProg(t, "testprog")
505 got, err := testenv.CleanCmdEnv(exec.Command(exe, "MemProf")).CombinedOutput()
509 fn := strings.TrimSpace(string(got))
512 for try := 0; try < 2; try++ {
513 cmd := testenv.CleanCmdEnv(exec.Command(testenv.GoToolPath(t), "tool", "pprof", "-alloc_space", "-top"))
514 // Check that pprof works both with and without explicit executable on command line.
516 cmd.Args = append(cmd.Args, exe, fn)
518 cmd.Args = append(cmd.Args, fn)
521 for i, e := range cmd.Env {
522 if strings.HasPrefix(e, "PPROF_TMPDIR=") {
523 cmd.Env[i] = "PPROF_TMPDIR=" + os.TempDir()
529 cmd.Env = append(cmd.Env, "PPROF_TMPDIR="+os.TempDir())
532 top, err := cmd.CombinedOutput()
533 t.Logf("%s:\n%s", cmd.Args, top)
536 } else if !bytes.Contains(top, []byte("MemProf")) {
537 t.Error("missing MemProf in pprof output")
542 var concurrentMapTest = flag.Bool("run_concurrent_map_tests", false, "also run flaky concurrent map tests")
544 func TestConcurrentMapWrites(t *testing.T) {
545 if !*concurrentMapTest {
546 t.Skip("skipping without -run_concurrent_map_tests")
548 testenv.MustHaveGoRun(t)
549 output := runTestProg(t, "testprog", "concurrentMapWrites")
550 want := "fatal error: concurrent map writes"
551 if !strings.HasPrefix(output, want) {
552 t.Fatalf("output does not start with %q:\n%s", want, output)
555 func TestConcurrentMapReadWrite(t *testing.T) {
556 if !*concurrentMapTest {
557 t.Skip("skipping without -run_concurrent_map_tests")
559 testenv.MustHaveGoRun(t)
560 output := runTestProg(t, "testprog", "concurrentMapReadWrite")
561 want := "fatal error: concurrent map read and map write"
562 if !strings.HasPrefix(output, want) {
563 t.Fatalf("output does not start with %q:\n%s", want, output)
566 func TestConcurrentMapIterateWrite(t *testing.T) {
567 if !*concurrentMapTest {
568 t.Skip("skipping without -run_concurrent_map_tests")
570 testenv.MustHaveGoRun(t)
571 output := runTestProg(t, "testprog", "concurrentMapIterateWrite")
572 want := "fatal error: concurrent map iteration and map write"
573 if !strings.HasPrefix(output, want) {
574 t.Fatalf("output does not start with %q:\n%s", want, output)
582 func (p *point) negate() {
587 // Test for issue #10152.
588 func TestPanicInlined(t *testing.T) {
592 t.Fatalf("recover failed")
594 buf := make([]byte, 2048)
595 n := runtime.Stack(buf, false)
597 if !bytes.Contains(buf, []byte("(*point).negate(")) {
598 t.Fatalf("expecting stack trace to contain call to (*point).negate()")
606 // Test for issues #3934 and #20018.
607 // We want to delay exiting until a panic print is complete.
608 func TestPanicRace(t *testing.T) {
609 testenv.MustHaveGoRun(t)
611 exe, err := buildTestProg(t, "testprog")
616 // The test is intentionally racy, and in my testing does not
617 // produce the expected output about 0.05% of the time.
618 // So run the program in a loop and only fail the test if we
619 // get the wrong output ten times in a row.
622 for i := 0; i < tries; i++ {
623 got, err := testenv.CleanCmdEnv(exec.Command(exe, "PanicRace")).CombinedOutput()
625 t.Logf("try %d: program exited successfully, should have failed", i+1)
630 t.Logf("try %d:\n", i+1)
639 for _, want := range wants {
640 if !bytes.Contains(got, []byte(want)) {
641 t.Logf("did not find expected string %q", want)
646 // Test generated expected output.
649 t.Errorf("test ran %d times without producing expected output", tries)
652 func TestBadTraceback(t *testing.T) {
653 output := runTestProg(t, "testprog", "BadTraceback")
654 for _, want := range []string{
655 "runtime: unexpected return pc",
657 "00000bad", // Smashed LR in hex dump
658 "<main.badLR", // Symbolization in hex dump (badLR1 or badLR2)
660 if !strings.Contains(output, want) {
661 t.Errorf("output does not contain %q:\n%s", want, output)
666 func TestTimePprof(t *testing.T) {
667 fn := runTestProg(t, "testprog", "TimeProf")
668 fn = strings.TrimSpace(fn)
671 cmd := testenv.CleanCmdEnv(exec.Command(testenv.GoToolPath(t), "tool", "pprof", "-top", "-nodecount=1", fn))
672 cmd.Env = append(cmd.Env, "PPROF_TMPDIR="+os.TempDir())
673 top, err := cmd.CombinedOutput()
677 } else if bytes.Contains(top, []byte("ExternalCode")) {
678 t.Error("profiler refers to ExternalCode")
682 // Test that runtime.abort does so.
683 func TestAbort(t *testing.T) {
684 // Pass GOTRACEBACK to ensure we get runtime frames.
685 output := runTestProg(t, "testprog", "Abort", "GOTRACEBACK=system")
686 if want := "runtime.abort"; !strings.Contains(output, want) {
687 t.Errorf("output does not contain %q:\n%s", want, output)
689 if strings.Contains(output, "BAD") {
690 t.Errorf("output contains BAD:\n%s", output)
692 // Check that it's a signal traceback.
694 // For systems that use a breakpoint, check specifically for that.
695 switch runtime.GOARCH {
697 switch runtime.GOOS {
699 want = "sys: breakpoint"
701 want = "Exception 0x80000003"
706 if !strings.Contains(output, want) {
707 t.Errorf("output does not contain %q:\n%s", want, output)
711 // For TestRuntimePanic: test a panic in the runtime package without
712 // involving the testing harness.
714 if os.Getenv("GO_TEST_RUNTIME_PANIC") == "1" {
716 if r := recover(); r != nil {
717 // We expect to crash, so exit 0
718 // to indicate failure.
722 runtime.PanicForTesting(nil, 1)
723 // We expect to crash, so exit 0 to indicate failure.
728 func TestRuntimePanic(t *testing.T) {
729 testenv.MustHaveExec(t)
730 cmd := testenv.CleanCmdEnv(exec.Command(os.Args[0], "-test.run=TestRuntimePanic"))
731 cmd.Env = append(cmd.Env, "GO_TEST_RUNTIME_PANIC=1")
732 out, err := cmd.CombinedOutput()
735 t.Error("child process did not fail")
736 } else if want := "runtime.unexportedPanicForTesting"; !bytes.Contains(out, []byte(want)) {
737 t.Errorf("output did not contain expected string %q", want)
741 // Test that g0 stack overflows are handled gracefully.
742 func TestG0StackOverflow(t *testing.T) {
743 testenv.MustHaveExec(t)
745 switch runtime.GOOS {
746 case "darwin", "dragonfly", "freebsd", "linux", "netbsd", "openbsd", "android":
747 t.Skipf("g0 stack is wrong on pthread platforms (see golang.org/issue/26061)")
750 if os.Getenv("TEST_G0_STACK_OVERFLOW") != "1" {
751 cmd := testenv.CleanCmdEnv(exec.Command(os.Args[0], "-test.run=TestG0StackOverflow", "-test.v"))
752 cmd.Env = append(cmd.Env, "TEST_G0_STACK_OVERFLOW=1")
753 out, err := cmd.CombinedOutput()
754 // Don't check err since it's expected to crash.
755 if n := strings.Count(string(out), "morestack on g0\n"); n != 1 {
756 t.Fatalf("%s\n(exit status %v)", out, err)
758 // Check that it's a signal-style traceback.
759 if runtime.GOOS != "windows" {
760 if want := "PC="; !strings.Contains(string(out), want) {
761 t.Errorf("output does not contain %q:\n%s", want, out)
767 runtime.G0StackOverflow()
770 // Test that panic message is not clobbered.
772 func TestDoublePanic(t *testing.T) {
773 output := runTestProg(t, "testprog", "DoublePanic", "GODEBUG=clobberfree=1")
774 wants := []string{"panic: XXX", "panic: YYY"}
775 for _, want := range wants {
776 if !strings.Contains(output, want) {
777 t.Errorf("output:\n%s\n\nwant output containing: %s", output, want)