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 output := runTestProg(t, "testprog", name)
185 want := "fatal error: all goroutines are asleep - deadlock!\n"
186 if !strings.HasPrefix(output, want) {
187 t.Fatalf("output does not start with %q:\n%s", want, output)
191 func TestSimpleDeadlock(t *testing.T) {
192 testDeadlock(t, "SimpleDeadlock")
195 func TestInitDeadlock(t *testing.T) {
196 testDeadlock(t, "InitDeadlock")
199 func TestLockedDeadlock(t *testing.T) {
200 testDeadlock(t, "LockedDeadlock")
203 func TestLockedDeadlock2(t *testing.T) {
204 testDeadlock(t, "LockedDeadlock2")
207 func TestGoexitDeadlock(t *testing.T) {
208 output := runTestProg(t, "testprog", "GoexitDeadlock")
209 want := "no goroutines (main called runtime.Goexit) - deadlock!"
210 if !strings.Contains(output, want) {
211 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
215 func TestStackOverflow(t *testing.T) {
216 output := runTestProg(t, "testprog", "StackOverflow")
218 "runtime: goroutine stack exceeds 1474560-byte limit\n",
219 "fatal error: stack overflow",
220 // information about the current SP and stack bounds
224 if !strings.HasPrefix(output, want[0]) {
225 t.Errorf("output does not start with %q", want[0])
227 for _, s := range want[1:] {
228 if !strings.Contains(output, s) {
229 t.Errorf("output does not contain %q", s)
233 t.Logf("output:\n%s", output)
237 func TestThreadExhaustion(t *testing.T) {
238 output := runTestProg(t, "testprog", "ThreadExhaustion")
239 want := "runtime: program exceeds 10-thread limit\nfatal error: thread exhaustion"
240 if !strings.HasPrefix(output, want) {
241 t.Fatalf("output does not start with %q:\n%s", want, output)
245 func TestRecursivePanic(t *testing.T) {
246 output := runTestProg(t, "testprog", "RecursivePanic")
251 if !strings.HasPrefix(output, want) {
252 t.Fatalf("output does not start with %q:\n%s", want, output)
257 func TestRecursivePanic2(t *testing.T) {
258 output := runTestProg(t, "testprog", "RecursivePanic2")
264 if !strings.HasPrefix(output, want) {
265 t.Fatalf("output does not start with %q:\n%s", want, output)
270 func TestRecursivePanic3(t *testing.T) {
271 output := runTestProg(t, "testprog", "RecursivePanic3")
272 want := `panic: first panic
275 if !strings.HasPrefix(output, want) {
276 t.Fatalf("output does not start with %q:\n%s", want, output)
281 func TestRecursivePanic4(t *testing.T) {
282 output := runTestProg(t, "testprog", "RecursivePanic4")
283 want := `panic: first panic [recovered]
286 if !strings.HasPrefix(output, want) {
287 t.Fatalf("output does not start with %q:\n%s", want, output)
292 func TestGoexitCrash(t *testing.T) {
293 output := runTestProg(t, "testprog", "GoexitExit")
294 want := "no goroutines (main called runtime.Goexit) - deadlock!"
295 if !strings.Contains(output, want) {
296 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
300 func TestGoexitDefer(t *testing.T) {
301 c := make(chan struct{})
306 t.Errorf("non-nil recover during Goexit")
312 // Note: if the defer fails to run, we will get a deadlock here
316 func TestGoNil(t *testing.T) {
317 output := runTestProg(t, "testprog", "GoNil")
318 want := "go of nil func value"
319 if !strings.Contains(output, want) {
320 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
324 func TestMainGoroutineID(t *testing.T) {
325 output := runTestProg(t, "testprog", "MainGoroutineID")
326 want := "panic: test\n\ngoroutine 1 [running]:\n"
327 if !strings.HasPrefix(output, want) {
328 t.Fatalf("output does not start with %q:\n%s", want, output)
332 func TestNoHelperGoroutines(t *testing.T) {
333 output := runTestProg(t, "testprog", "NoHelperGoroutines")
334 matches := regexp.MustCompile(`goroutine [0-9]+ \[`).FindAllStringSubmatch(output, -1)
335 if len(matches) != 1 || matches[0][0] != "goroutine 1 [" {
336 t.Fatalf("want to see only goroutine 1, see:\n%s", output)
340 func TestBreakpoint(t *testing.T) {
341 output := runTestProg(t, "testprog", "Breakpoint")
342 // If runtime.Breakpoint() is inlined, then the stack trace prints
343 // "runtime.Breakpoint(...)" instead of "runtime.Breakpoint()".
344 want := "runtime.Breakpoint("
345 if !strings.Contains(output, want) {
346 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
350 func TestGoexitInPanic(t *testing.T) {
351 // see issue 8774: this code used to trigger an infinite recursion
352 output := runTestProg(t, "testprog", "GoexitInPanic")
353 want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
354 if !strings.HasPrefix(output, want) {
355 t.Fatalf("output does not start with %q:\n%s", want, output)
359 // Issue 14965: Runtime panics should be of type runtime.Error
360 func TestRuntimePanicWithRuntimeError(t *testing.T) {
361 testCases := [...]func(){
363 var m map[uint64]bool
367 ch := make(chan struct{})
372 var ch = make(chan struct{})
377 var s = make([]int, 2)
382 _ = make(chan bool, n)
385 close((chan bool)(nil))
389 for i, fn := range testCases {
390 got := panicValue(fn)
391 if _, ok := got.(runtime.Error); !ok {
392 t.Errorf("test #%d: recovered value %v(type %T) does not implement runtime.Error", i, got, got)
397 func panicValue(fn func()) (recovered interface{}) {
399 recovered = recover()
405 func TestPanicAfterGoexit(t *testing.T) {
406 // an uncaught panic should still work after goexit
407 output := runTestProg(t, "testprog", "PanicAfterGoexit")
408 want := "panic: hello"
409 if !strings.HasPrefix(output, want) {
410 t.Fatalf("output does not start with %q:\n%s", want, output)
414 func TestRecoveredPanicAfterGoexit(t *testing.T) {
415 output := runTestProg(t, "testprog", "RecoveredPanicAfterGoexit")
416 want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
417 if !strings.HasPrefix(output, want) {
418 t.Fatalf("output does not start with %q:\n%s", want, output)
422 func TestRecoverBeforePanicAfterGoexit(t *testing.T) {
424 output := runTestProg(t, "testprog", "RecoverBeforePanicAfterGoexit")
425 want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
426 if !strings.HasPrefix(output, want) {
427 t.Fatalf("output does not start with %q:\n%s", want, output)
431 func TestRecoverBeforePanicAfterGoexit2(t *testing.T) {
433 output := runTestProg(t, "testprog", "RecoverBeforePanicAfterGoexit2")
434 want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
435 if !strings.HasPrefix(output, want) {
436 t.Fatalf("output does not start with %q:\n%s", want, output)
440 func TestNetpollDeadlock(t *testing.T) {
441 if os.Getenv("GO_BUILDER_NAME") == "darwin-amd64-10_12" {
442 // A suspected kernel bug in macOS 10.12 occasionally results in
443 // an apparent deadlock when dialing localhost. The errors have not
444 // been observed on newer versions of the OS, so we don't plan to work
445 // around them. See https://golang.org/issue/22019.
446 testenv.SkipFlaky(t, 22019)
450 output := runTestProg(t, "testprognet", "NetpollDeadlock")
452 if !strings.HasSuffix(output, want) {
453 t.Fatalf("output does not start with %q:\n%s", want, output)
457 func TestPanicTraceback(t *testing.T) {
459 output := runTestProg(t, "testprog", "PanicTraceback")
460 want := "panic: hello\n\tpanic: panic pt2\n\tpanic: panic pt1\n"
461 if !strings.HasPrefix(output, want) {
462 t.Fatalf("output does not start with %q:\n%s", want, output)
465 // Check functions in the traceback.
466 fns := []string{"main.pt1.func1", "panic", "main.pt2.func1", "panic", "main.pt2", "main.pt1"}
467 for _, fn := range fns {
468 re := regexp.MustCompile(`(?m)^` + regexp.QuoteMeta(fn) + `\(.*\n`)
469 idx := re.FindStringIndex(output)
471 t.Fatalf("expected %q function in traceback:\n%s", fn, output)
473 output = output[idx[1]:]
477 func testPanicDeadlock(t *testing.T, name string, want string) {
479 output := runTestProg(t, "testprog", name)
480 if !strings.HasPrefix(output, want) {
481 t.Fatalf("output does not start with %q:\n%s", want, output)
485 func TestPanicDeadlockGosched(t *testing.T) {
486 testPanicDeadlock(t, "GoschedInPanic", "panic: errorThatGosched\n\n")
489 func TestPanicDeadlockSyscall(t *testing.T) {
490 testPanicDeadlock(t, "SyscallInPanic", "1\n2\npanic: 3\n\n")
493 func TestPanicLoop(t *testing.T) {
494 output := runTestProg(t, "testprog", "PanicLoop")
495 if want := "panic while printing panic value"; !strings.Contains(output, want) {
496 t.Errorf("output does not contain %q:\n%s", want, output)
500 func TestMemPprof(t *testing.T) {
501 testenv.MustHaveGoRun(t)
503 exe, err := buildTestProg(t, "testprog")
508 got, err := testenv.CleanCmdEnv(exec.Command(exe, "MemProf")).CombinedOutput()
512 fn := strings.TrimSpace(string(got))
515 for try := 0; try < 2; try++ {
516 cmd := testenv.CleanCmdEnv(exec.Command(testenv.GoToolPath(t), "tool", "pprof", "-alloc_space", "-top"))
517 // Check that pprof works both with and without explicit executable on command line.
519 cmd.Args = append(cmd.Args, exe, fn)
521 cmd.Args = append(cmd.Args, fn)
524 for i, e := range cmd.Env {
525 if strings.HasPrefix(e, "PPROF_TMPDIR=") {
526 cmd.Env[i] = "PPROF_TMPDIR=" + os.TempDir()
532 cmd.Env = append(cmd.Env, "PPROF_TMPDIR="+os.TempDir())
535 top, err := cmd.CombinedOutput()
536 t.Logf("%s:\n%s", cmd.Args, top)
539 } else if !bytes.Contains(top, []byte("MemProf")) {
540 t.Error("missing MemProf in pprof output")
545 var concurrentMapTest = flag.Bool("run_concurrent_map_tests", false, "also run flaky concurrent map tests")
547 func TestConcurrentMapWrites(t *testing.T) {
548 if !*concurrentMapTest {
549 t.Skip("skipping without -run_concurrent_map_tests")
551 testenv.MustHaveGoRun(t)
552 output := runTestProg(t, "testprog", "concurrentMapWrites")
553 want := "fatal error: concurrent map writes"
554 if !strings.HasPrefix(output, want) {
555 t.Fatalf("output does not start with %q:\n%s", want, output)
558 func TestConcurrentMapReadWrite(t *testing.T) {
559 if !*concurrentMapTest {
560 t.Skip("skipping without -run_concurrent_map_tests")
562 testenv.MustHaveGoRun(t)
563 output := runTestProg(t, "testprog", "concurrentMapReadWrite")
564 want := "fatal error: concurrent map read and map write"
565 if !strings.HasPrefix(output, want) {
566 t.Fatalf("output does not start with %q:\n%s", want, output)
569 func TestConcurrentMapIterateWrite(t *testing.T) {
570 if !*concurrentMapTest {
571 t.Skip("skipping without -run_concurrent_map_tests")
573 testenv.MustHaveGoRun(t)
574 output := runTestProg(t, "testprog", "concurrentMapIterateWrite")
575 want := "fatal error: concurrent map iteration and map write"
576 if !strings.HasPrefix(output, want) {
577 t.Fatalf("output does not start with %q:\n%s", want, output)
585 func (p *point) negate() {
590 // Test for issue #10152.
591 func TestPanicInlined(t *testing.T) {
595 t.Fatalf("recover failed")
597 buf := make([]byte, 2048)
598 n := runtime.Stack(buf, false)
600 if !bytes.Contains(buf, []byte("(*point).negate(")) {
601 t.Fatalf("expecting stack trace to contain call to (*point).negate()")
609 // Test for issues #3934 and #20018.
610 // We want to delay exiting until a panic print is complete.
611 func TestPanicRace(t *testing.T) {
612 testenv.MustHaveGoRun(t)
614 exe, err := buildTestProg(t, "testprog")
619 // The test is intentionally racy, and in my testing does not
620 // produce the expected output about 0.05% of the time.
621 // So run the program in a loop and only fail the test if we
622 // get the wrong output ten times in a row.
625 for i := 0; i < tries; i++ {
626 got, err := testenv.CleanCmdEnv(exec.Command(exe, "PanicRace")).CombinedOutput()
628 t.Logf("try %d: program exited successfully, should have failed", i+1)
633 t.Logf("try %d:\n", i+1)
642 for _, want := range wants {
643 if !bytes.Contains(got, []byte(want)) {
644 t.Logf("did not find expected string %q", want)
649 // Test generated expected output.
652 t.Errorf("test ran %d times without producing expected output", tries)
655 func TestBadTraceback(t *testing.T) {
656 output := runTestProg(t, "testprog", "BadTraceback")
657 for _, want := range []string{
658 "runtime: unexpected return pc",
660 "00000bad", // Smashed LR in hex dump
661 "<main.badLR", // Symbolization in hex dump (badLR1 or badLR2)
663 if !strings.Contains(output, want) {
664 t.Errorf("output does not contain %q:\n%s", want, output)
669 func TestTimePprof(t *testing.T) {
670 fn := runTestProg(t, "testprog", "TimeProf")
671 fn = strings.TrimSpace(fn)
674 cmd := testenv.CleanCmdEnv(exec.Command(testenv.GoToolPath(t), "tool", "pprof", "-top", "-nodecount=1", fn))
675 cmd.Env = append(cmd.Env, "PPROF_TMPDIR="+os.TempDir())
676 top, err := cmd.CombinedOutput()
680 } else if bytes.Contains(top, []byte("ExternalCode")) {
681 t.Error("profiler refers to ExternalCode")
685 // Test that runtime.abort does so.
686 func TestAbort(t *testing.T) {
687 // Pass GOTRACEBACK to ensure we get runtime frames.
688 output := runTestProg(t, "testprog", "Abort", "GOTRACEBACK=system")
689 if want := "runtime.abort"; !strings.Contains(output, want) {
690 t.Errorf("output does not contain %q:\n%s", want, output)
692 if strings.Contains(output, "BAD") {
693 t.Errorf("output contains BAD:\n%s", output)
695 // Check that it's a signal traceback.
697 // For systems that use a breakpoint, check specifically for that.
698 switch runtime.GOARCH {
700 switch runtime.GOOS {
702 want = "sys: breakpoint"
704 want = "Exception 0x80000003"
709 if !strings.Contains(output, want) {
710 t.Errorf("output does not contain %q:\n%s", want, output)
714 // For TestRuntimePanic: test a panic in the runtime package without
715 // involving the testing harness.
717 if os.Getenv("GO_TEST_RUNTIME_PANIC") == "1" {
719 if r := recover(); r != nil {
720 // We expect to crash, so exit 0
721 // to indicate failure.
725 runtime.PanicForTesting(nil, 1)
726 // We expect to crash, so exit 0 to indicate failure.
731 func TestRuntimePanic(t *testing.T) {
732 testenv.MustHaveExec(t)
733 cmd := testenv.CleanCmdEnv(exec.Command(os.Args[0], "-test.run=TestRuntimePanic"))
734 cmd.Env = append(cmd.Env, "GO_TEST_RUNTIME_PANIC=1")
735 out, err := cmd.CombinedOutput()
738 t.Error("child process did not fail")
739 } else if want := "runtime.unexportedPanicForTesting"; !bytes.Contains(out, []byte(want)) {
740 t.Errorf("output did not contain expected string %q", want)
744 // Test that g0 stack overflows are handled gracefully.
745 func TestG0StackOverflow(t *testing.T) {
746 testenv.MustHaveExec(t)
748 switch runtime.GOOS {
749 case "darwin", "dragonfly", "freebsd", "linux", "netbsd", "openbsd", "android":
750 t.Skipf("g0 stack is wrong on pthread platforms (see golang.org/issue/26061)")
753 if os.Getenv("TEST_G0_STACK_OVERFLOW") != "1" {
754 cmd := testenv.CleanCmdEnv(exec.Command(os.Args[0], "-test.run=TestG0StackOverflow", "-test.v"))
755 cmd.Env = append(cmd.Env, "TEST_G0_STACK_OVERFLOW=1")
756 out, err := cmd.CombinedOutput()
757 // Don't check err since it's expected to crash.
758 if n := strings.Count(string(out), "morestack on g0\n"); n != 1 {
759 t.Fatalf("%s\n(exit status %v)", out, err)
761 // Check that it's a signal-style traceback.
762 if runtime.GOOS != "windows" {
763 if want := "PC="; !strings.Contains(string(out), want) {
764 t.Errorf("output does not contain %q:\n%s", want, out)
770 runtime.G0StackOverflow()
773 // Test that panic message is not clobbered.
775 func TestDoublePanic(t *testing.T) {
776 output := runTestProg(t, "testprog", "DoublePanic", "GODEBUG=clobberfree=1")
777 wants := []string{"panic: XXX", "panic: YYY"}
778 for _, want := range wants {
779 if !strings.Contains(output, want) {
780 t.Errorf("output:\n%s\n\nwant output containing: %s", output, want)