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) {
28 testenv.SetModVendor()
31 for _, file := range toRemove {
40 target map[string]buildexe
43 type buildexe struct {
48 func runTestProg(t *testing.T, binary, name string, env ...string) string {
53 testenv.MustHaveGoBuild(t)
55 exe, err := buildTestProg(t, binary)
60 cmd := testenv.CleanCmdEnv(exec.Command(exe, name))
61 cmd.Env = append(cmd.Env, env...)
63 cmd.Env = append(cmd.Env, "RUNTIME_TEST_SHORT=1")
68 if err := cmd.Start(); err != nil {
69 t.Fatalf("starting %s %s: %v", binary, name, err)
72 // If the process doesn't complete within 1 minute,
73 // assume it is hanging and kill it to get a stack trace.
75 done := make(chan bool)
78 // This GOARCH/GOOS test is copied from cmd/dist/test.go.
79 // TODO(iant): Have cmd/dist update the environment variable.
80 if runtime.GOARCH == "arm" || runtime.GOOS == "windows" {
83 if s := os.Getenv("GO_TEST_TIMEOUT_SCALE"); s != "" {
84 if sc, err := strconv.Atoi(s); err == nil {
91 case <-time.After(time.Duration(scale) * time.Minute):
96 if err := cmd.Wait(); err != nil {
97 t.Logf("%s %s exit status: %v", binary, name, err)
104 func buildTestProg(t *testing.T, binary string, flags ...string) (string, error) {
112 defer testprog.Unlock()
113 if testprog.dir == "" {
114 dir, err := ioutil.TempDir("", "go-build")
116 t.Fatalf("failed to create temp directory: %v", err)
119 toRemove = append(toRemove, dir)
122 if testprog.target == nil {
123 testprog.target = make(map[string]buildexe)
127 name += "_" + strings.Join(flags, "_")
129 target, ok := testprog.target[name]
131 return target.exe, target.err
134 exe := filepath.Join(testprog.dir, name+".exe")
135 cmd := exec.Command(testenv.GoToolPath(t), append([]string{"build", "-o", exe}, flags...)...)
136 cmd.Dir = "testdata/" + binary
137 out, err := testenv.CleanCmdEnv(cmd).CombinedOutput()
139 target.err = fmt.Errorf("building %s %v: %v\n%s", binary, flags, err, out)
140 testprog.target[name] = target
141 return "", target.err
144 testprog.target[name] = target
149 staleRuntimeOnce sync.Once // guards init of staleRuntimeErr
150 staleRuntimeErr error
153 func checkStaleRuntime(t *testing.T) {
154 staleRuntimeOnce.Do(func() {
155 // 'go run' uses the installed copy of runtime.a, which may be out of date.
156 out, err := testenv.CleanCmdEnv(exec.Command(testenv.GoToolPath(t), "list", "-gcflags=all="+os.Getenv("GO_GCFLAGS"), "-f", "{{.Stale}}", "runtime")).CombinedOutput()
158 staleRuntimeErr = fmt.Errorf("failed to execute 'go list': %v\n%v", err, string(out))
161 if string(out) != "false\n" {
162 t.Logf("go list -f {{.Stale}} runtime:\n%s", out)
163 out, err := testenv.CleanCmdEnv(exec.Command(testenv.GoToolPath(t), "list", "-gcflags=all="+os.Getenv("GO_GCFLAGS"), "-f", "{{.StaleReason}}", "runtime")).CombinedOutput()
165 t.Logf("go list -f {{.StaleReason}} failed: %v", err)
167 t.Logf("go list -f {{.StaleReason}} runtime:\n%s", out)
168 staleRuntimeErr = fmt.Errorf("Stale runtime.a. Run 'go install runtime'.")
171 if staleRuntimeErr != nil {
172 t.Fatal(staleRuntimeErr)
176 func testCrashHandler(t *testing.T, cgo bool) {
177 type crashTest struct {
182 output = runTestProg(t, "testprogcgo", "Crash")
184 output = runTestProg(t, "testprog", "Crash")
186 want := "main: recovered done\nnew-thread: recovered done\nsecond-new-thread: recovered done\nmain-again: recovered done\n"
188 t.Fatalf("output:\n%s\n\nwanted:\n%s", output, want)
192 func TestCrashHandler(t *testing.T) {
193 testCrashHandler(t, false)
196 func testDeadlock(t *testing.T, name string) {
197 output := runTestProg(t, "testprog", name)
198 want := "fatal error: all goroutines are asleep - deadlock!\n"
199 if !strings.HasPrefix(output, want) {
200 t.Fatalf("output does not start with %q:\n%s", want, output)
204 func TestSimpleDeadlock(t *testing.T) {
205 testDeadlock(t, "SimpleDeadlock")
208 func TestInitDeadlock(t *testing.T) {
209 testDeadlock(t, "InitDeadlock")
212 func TestLockedDeadlock(t *testing.T) {
213 testDeadlock(t, "LockedDeadlock")
216 func TestLockedDeadlock2(t *testing.T) {
217 testDeadlock(t, "LockedDeadlock2")
220 func TestGoexitDeadlock(t *testing.T) {
221 output := runTestProg(t, "testprog", "GoexitDeadlock")
222 want := "no goroutines (main called runtime.Goexit) - deadlock!"
223 if !strings.Contains(output, want) {
224 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
228 func TestStackOverflow(t *testing.T) {
229 output := runTestProg(t, "testprog", "StackOverflow")
230 want := "runtime: goroutine stack exceeds 1474560-byte limit\nfatal error: stack overflow"
231 if !strings.HasPrefix(output, want) {
232 t.Fatalf("output does not start with %q:\n%s", want, output)
236 func TestThreadExhaustion(t *testing.T) {
237 output := runTestProg(t, "testprog", "ThreadExhaustion")
238 want := "runtime: program exceeds 10-thread limit\nfatal error: thread exhaustion"
239 if !strings.HasPrefix(output, want) {
240 t.Fatalf("output does not start with %q:\n%s", want, output)
244 func TestRecursivePanic(t *testing.T) {
245 output := runTestProg(t, "testprog", "RecursivePanic")
250 if !strings.HasPrefix(output, want) {
251 t.Fatalf("output does not start with %q:\n%s", want, output)
256 func TestGoexitCrash(t *testing.T) {
257 output := runTestProg(t, "testprog", "GoexitExit")
258 want := "no goroutines (main called runtime.Goexit) - deadlock!"
259 if !strings.Contains(output, want) {
260 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
264 func TestGoexitDefer(t *testing.T) {
265 c := make(chan struct{})
270 t.Errorf("non-nil recover during Goexit")
276 // Note: if the defer fails to run, we will get a deadlock here
280 func TestGoNil(t *testing.T) {
281 output := runTestProg(t, "testprog", "GoNil")
282 want := "go of nil func value"
283 if !strings.Contains(output, want) {
284 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
288 func TestMainGoroutineID(t *testing.T) {
289 output := runTestProg(t, "testprog", "MainGoroutineID")
290 want := "panic: test\n\ngoroutine 1 [running]:\n"
291 if !strings.HasPrefix(output, want) {
292 t.Fatalf("output does not start with %q:\n%s", want, output)
296 func TestNoHelperGoroutines(t *testing.T) {
297 output := runTestProg(t, "testprog", "NoHelperGoroutines")
298 matches := regexp.MustCompile(`goroutine [0-9]+ \[`).FindAllStringSubmatch(output, -1)
299 if len(matches) != 1 || matches[0][0] != "goroutine 1 [" {
300 t.Fatalf("want to see only goroutine 1, see:\n%s", output)
304 func TestBreakpoint(t *testing.T) {
305 output := runTestProg(t, "testprog", "Breakpoint")
306 // If runtime.Breakpoint() is inlined, then the stack trace prints
307 // "runtime.Breakpoint(...)" instead of "runtime.Breakpoint()".
308 want := "runtime.Breakpoint("
309 if !strings.Contains(output, want) {
310 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
314 func TestGoexitInPanic(t *testing.T) {
315 // see issue 8774: this code used to trigger an infinite recursion
316 output := runTestProg(t, "testprog", "GoexitInPanic")
317 want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
318 if !strings.HasPrefix(output, want) {
319 t.Fatalf("output does not start with %q:\n%s", want, output)
323 // Issue 14965: Runtime panics should be of type runtime.Error
324 func TestRuntimePanicWithRuntimeError(t *testing.T) {
325 testCases := [...]func(){
327 var m map[uint64]bool
331 ch := make(chan struct{})
336 var ch = make(chan struct{})
341 var s = make([]int, 2)
346 _ = make(chan bool, n)
349 close((chan bool)(nil))
353 for i, fn := range testCases {
354 got := panicValue(fn)
355 if _, ok := got.(runtime.Error); !ok {
356 t.Errorf("test #%d: recovered value %v(type %T) does not implement runtime.Error", i, got, got)
361 func panicValue(fn func()) (recovered interface{}) {
363 recovered = recover()
369 func TestPanicAfterGoexit(t *testing.T) {
370 // an uncaught panic should still work after goexit
371 output := runTestProg(t, "testprog", "PanicAfterGoexit")
372 want := "panic: hello"
373 if !strings.HasPrefix(output, want) {
374 t.Fatalf("output does not start with %q:\n%s", want, output)
378 func TestRecoveredPanicAfterGoexit(t *testing.T) {
379 output := runTestProg(t, "testprog", "RecoveredPanicAfterGoexit")
380 want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
381 if !strings.HasPrefix(output, want) {
382 t.Fatalf("output does not start with %q:\n%s", want, output)
386 func TestRecoverBeforePanicAfterGoexit(t *testing.T) {
387 // 1. defer a function that recovers
388 // 2. defer a function that panics
390 // Goexit should run the #2 defer. Its panic
391 // should be caught by the #1 defer, and execution
392 // should resume in the caller. Like the Goexit
406 func TestNetpollDeadlock(t *testing.T) {
408 output := runTestProg(t, "testprognet", "NetpollDeadlock")
410 if !strings.HasSuffix(output, want) {
411 t.Fatalf("output does not start with %q:\n%s", want, output)
415 func TestPanicTraceback(t *testing.T) {
417 output := runTestProg(t, "testprog", "PanicTraceback")
418 want := "panic: hello"
419 if !strings.HasPrefix(output, want) {
420 t.Fatalf("output does not start with %q:\n%s", want, output)
423 // Check functions in the traceback.
424 fns := []string{"main.pt1.func1", "panic", "main.pt2.func1", "panic", "main.pt2", "main.pt1"}
425 for _, fn := range fns {
426 re := regexp.MustCompile(`(?m)^` + regexp.QuoteMeta(fn) + `\(.*\n`)
427 idx := re.FindStringIndex(output)
429 t.Fatalf("expected %q function in traceback:\n%s", fn, output)
431 output = output[idx[1]:]
435 func testPanicDeadlock(t *testing.T, name string, want string) {
437 output := runTestProg(t, "testprog", name)
438 if !strings.HasPrefix(output, want) {
439 t.Fatalf("output does not start with %q:\n%s", want, output)
443 func TestPanicDeadlockGosched(t *testing.T) {
444 testPanicDeadlock(t, "GoschedInPanic", "panic: errorThatGosched\n\n")
447 func TestPanicDeadlockSyscall(t *testing.T) {
448 testPanicDeadlock(t, "SyscallInPanic", "1\n2\npanic: 3\n\n")
451 func TestPanicLoop(t *testing.T) {
452 output := runTestProg(t, "testprog", "PanicLoop")
453 if want := "panic while printing panic value"; !strings.Contains(output, want) {
454 t.Errorf("output does not contain %q:\n%s", want, output)
458 func TestMemPprof(t *testing.T) {
459 testenv.MustHaveGoRun(t)
461 exe, err := buildTestProg(t, "testprog")
466 got, err := testenv.CleanCmdEnv(exec.Command(exe, "MemProf")).CombinedOutput()
470 fn := strings.TrimSpace(string(got))
473 for try := 0; try < 2; try++ {
474 cmd := testenv.CleanCmdEnv(exec.Command(testenv.GoToolPath(t), "tool", "pprof", "-alloc_space", "-top"))
475 // Check that pprof works both with and without explicit executable on command line.
477 cmd.Args = append(cmd.Args, exe, fn)
479 cmd.Args = append(cmd.Args, fn)
482 for i, e := range cmd.Env {
483 if strings.HasPrefix(e, "PPROF_TMPDIR=") {
484 cmd.Env[i] = "PPROF_TMPDIR=" + os.TempDir()
490 cmd.Env = append(cmd.Env, "PPROF_TMPDIR="+os.TempDir())
493 top, err := cmd.CombinedOutput()
494 t.Logf("%s:\n%s", cmd.Args, top)
497 } else if !bytes.Contains(top, []byte("MemProf")) {
498 t.Error("missing MemProf in pprof output")
503 var concurrentMapTest = flag.Bool("run_concurrent_map_tests", false, "also run flaky concurrent map tests")
505 func TestConcurrentMapWrites(t *testing.T) {
506 if !*concurrentMapTest {
507 t.Skip("skipping without -run_concurrent_map_tests")
509 testenv.MustHaveGoRun(t)
510 output := runTestProg(t, "testprog", "concurrentMapWrites")
511 want := "fatal error: concurrent map writes"
512 if !strings.HasPrefix(output, want) {
513 t.Fatalf("output does not start with %q:\n%s", want, output)
516 func TestConcurrentMapReadWrite(t *testing.T) {
517 if !*concurrentMapTest {
518 t.Skip("skipping without -run_concurrent_map_tests")
520 testenv.MustHaveGoRun(t)
521 output := runTestProg(t, "testprog", "concurrentMapReadWrite")
522 want := "fatal error: concurrent map read and map write"
523 if !strings.HasPrefix(output, want) {
524 t.Fatalf("output does not start with %q:\n%s", want, output)
527 func TestConcurrentMapIterateWrite(t *testing.T) {
528 if !*concurrentMapTest {
529 t.Skip("skipping without -run_concurrent_map_tests")
531 testenv.MustHaveGoRun(t)
532 output := runTestProg(t, "testprog", "concurrentMapIterateWrite")
533 want := "fatal error: concurrent map iteration and map write"
534 if !strings.HasPrefix(output, want) {
535 t.Fatalf("output does not start with %q:\n%s", want, output)
543 func (p *point) negate() {
548 // Test for issue #10152.
549 func TestPanicInlined(t *testing.T) {
553 t.Fatalf("recover failed")
555 buf := make([]byte, 2048)
556 n := runtime.Stack(buf, false)
558 if !bytes.Contains(buf, []byte("(*point).negate(")) {
559 t.Fatalf("expecting stack trace to contain call to (*point).negate()")
567 // Test for issues #3934 and #20018.
568 // We want to delay exiting until a panic print is complete.
569 func TestPanicRace(t *testing.T) {
570 testenv.MustHaveGoRun(t)
572 exe, err := buildTestProg(t, "testprog")
577 // The test is intentionally racy, and in my testing does not
578 // produce the expected output about 0.05% of the time.
579 // So run the program in a loop and only fail the test if we
580 // get the wrong output ten times in a row.
583 for i := 0; i < tries; i++ {
584 got, err := testenv.CleanCmdEnv(exec.Command(exe, "PanicRace")).CombinedOutput()
586 t.Logf("try %d: program exited successfully, should have failed", i+1)
591 t.Logf("try %d:\n", i+1)
600 for _, want := range wants {
601 if !bytes.Contains(got, []byte(want)) {
602 t.Logf("did not find expected string %q", want)
607 // Test generated expected output.
610 t.Errorf("test ran %d times without producing expected output", tries)
613 func TestBadTraceback(t *testing.T) {
614 output := runTestProg(t, "testprog", "BadTraceback")
615 for _, want := range []string{
616 "runtime: unexpected return pc",
618 "00000bad", // Smashed LR in hex dump
619 "<main.badLR", // Symbolization in hex dump (badLR1 or badLR2)
621 if !strings.Contains(output, want) {
622 t.Errorf("output does not contain %q:\n%s", want, output)
627 func TestTimePprof(t *testing.T) {
628 if runtime.GOOS == "aix" {
629 t.Skip("pprof not yet available on AIX (see golang.org/issue/28555)")
631 fn := runTestProg(t, "testprog", "TimeProf")
632 fn = strings.TrimSpace(fn)
635 cmd := testenv.CleanCmdEnv(exec.Command(testenv.GoToolPath(t), "tool", "pprof", "-top", "-nodecount=1", fn))
636 cmd.Env = append(cmd.Env, "PPROF_TMPDIR="+os.TempDir())
637 top, err := cmd.CombinedOutput()
641 } else if bytes.Contains(top, []byte("ExternalCode")) {
642 t.Error("profiler refers to ExternalCode")
646 // Test that runtime.abort does so.
647 func TestAbort(t *testing.T) {
648 // Pass GOTRACEBACK to ensure we get runtime frames.
649 output := runTestProg(t, "testprog", "Abort", "GOTRACEBACK=system")
650 if want := "runtime.abort"; !strings.Contains(output, want) {
651 t.Errorf("output does not contain %q:\n%s", want, output)
653 if strings.Contains(output, "BAD") {
654 t.Errorf("output contains BAD:\n%s", output)
656 // Check that it's a signal traceback.
658 // For systems that use a breakpoint, check specifically for that.
659 switch runtime.GOARCH {
661 switch runtime.GOOS {
663 want = "sys: breakpoint"
665 want = "Exception 0x80000003"
670 if !strings.Contains(output, want) {
671 t.Errorf("output does not contain %q:\n%s", want, output)
675 // For TestRuntimePanic: test a panic in the runtime package without
676 // involving the testing harness.
678 if os.Getenv("GO_TEST_RUNTIME_PANIC") == "1" {
680 if r := recover(); r != nil {
681 // We expect to crash, so exit 0
682 // to indicate failure.
686 runtime.PanicForTesting(nil, 1)
687 // We expect to crash, so exit 0 to indicate failure.
692 func TestRuntimePanic(t *testing.T) {
693 testenv.MustHaveExec(t)
694 cmd := testenv.CleanCmdEnv(exec.Command(os.Args[0], "-test.run=TestRuntimePanic"))
695 cmd.Env = append(cmd.Env, "GO_TEST_RUNTIME_PANIC=1")
696 out, err := cmd.CombinedOutput()
699 t.Error("child process did not fail")
700 } else if want := "runtime.unexportedPanicForTesting"; !bytes.Contains(out, []byte(want)) {
701 t.Errorf("output did not contain expected string %q", want)
705 // Test that g0 stack overflows are handled gracefully.
706 func TestG0StackOverflow(t *testing.T) {
707 testenv.MustHaveExec(t)
709 switch runtime.GOOS {
710 case "darwin", "dragonfly", "freebsd", "linux", "netbsd", "openbsd", "android":
711 t.Skipf("g0 stack is wrong on pthread platforms (see golang.org/issue/26061)")
714 if os.Getenv("TEST_G0_STACK_OVERFLOW") != "1" {
715 cmd := testenv.CleanCmdEnv(exec.Command(os.Args[0], "-test.run=TestG0StackOverflow", "-test.v"))
716 cmd.Env = append(cmd.Env, "TEST_G0_STACK_OVERFLOW=1")
717 out, err := cmd.CombinedOutput()
718 // Don't check err since it's expected to crash.
719 if n := strings.Count(string(out), "morestack on g0\n"); n != 1 {
720 t.Fatalf("%s\n(exit status %v)", out, err)
722 // Check that it's a signal-style traceback.
723 if runtime.GOOS != "windows" {
724 if want := "PC="; !strings.Contains(string(out), want) {
725 t.Errorf("output does not contain %q:\n%s", want, out)
731 runtime.G0StackOverflow()
734 // Test that panic message is not clobbered.
736 func TestDoublePanic(t *testing.T) {
737 output := runTestProg(t, "testprog", "DoublePanic", "GODEBUG=clobberfree=1")
738 wants := []string{"panic: XXX", "panic: YYY"}
739 for _, want := range wants {
740 if !strings.Contains(output, want) {
741 t.Errorf("output:\n%s\n\nwant output containing: %s", output, want)