github.com/ice-blockchain/go/src@v0.0.0-20240403114104-1564d284e521/runtime/ehooks_test.go (about) 1 // Copyright 2022 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. 4 5 package runtime_test 6 7 import ( 8 "internal/platform" 9 "internal/testenv" 10 "os/exec" 11 "runtime" 12 "strings" 13 "testing" 14 ) 15 16 func TestExitHooks(t *testing.T) { 17 bmodes := []string{""} 18 if testing.Short() { 19 t.Skip("skipping due to -short") 20 } 21 // Note the HasCGO() test below; this is to prevent the test 22 // running if CGO_ENABLED=0 is in effect. 23 haverace := platform.RaceDetectorSupported(runtime.GOOS, runtime.GOARCH) 24 if haverace && testenv.HasCGO() { 25 bmodes = append(bmodes, "-race") 26 } 27 for _, bmode := range bmodes { 28 scenarios := []struct { 29 mode string 30 expected string 31 musthave string 32 }{ 33 { 34 mode: "simple", 35 expected: "bar foo", 36 musthave: "", 37 }, 38 { 39 mode: "goodexit", 40 expected: "orange apple", 41 musthave: "", 42 }, 43 { 44 mode: "badexit", 45 expected: "blub blix", 46 musthave: "", 47 }, 48 { 49 mode: "panics", 50 expected: "", 51 musthave: "fatal error: internal error: exit hook invoked panic", 52 }, 53 { 54 mode: "callsexit", 55 expected: "", 56 musthave: "fatal error: internal error: exit hook invoked exit", 57 }, 58 } 59 60 exe, err := buildTestProg(t, "testexithooks", bmode) 61 if err != nil { 62 t.Fatal(err) 63 } 64 65 bt := "" 66 if bmode != "" { 67 bt = " bmode: " + bmode 68 } 69 for _, s := range scenarios { 70 cmd := exec.Command(exe, []string{"-mode", s.mode}...) 71 out, _ := cmd.CombinedOutput() 72 outs := strings.ReplaceAll(string(out), "\n", " ") 73 outs = strings.TrimSpace(outs) 74 if s.expected != "" { 75 if s.expected != outs { 76 t.Logf("raw output: %q", outs) 77 t.Errorf("failed%s mode %s: wanted %q got %q", bt, 78 s.mode, s.expected, outs) 79 } 80 } else if s.musthave != "" { 81 if !strings.Contains(outs, s.musthave) { 82 t.Logf("raw output: %q", outs) 83 t.Errorf("failed mode %s: output does not contain %q", 84 s.mode, s.musthave) 85 } 86 } else { 87 panic("badly written scenario") 88 } 89 } 90 } 91 }