github.com/giovannyortegon/go@v0.0.0-20220115155912-8890063f5bdd/src/pkg/mod/golang.org/x/sys@v0.0.0-20210927094055-39ccf1dd6fa6/unix/openbsd_test.go (about) 1 // Copyright 2016 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 //go:build openbsd 6 // +build openbsd 7 8 // This, on the face of it, bizarre testing mechanism is necessary because 9 // the only reliable way to gauge whether or not a pledge(2) call has succeeded 10 // is that the program has been killed as a result of breaking its pledge. 11 12 package unix_test 13 14 import ( 15 "flag" 16 "fmt" 17 "io/ioutil" 18 "os" 19 "os/exec" 20 "path/filepath" 21 "testing" 22 23 "golang.org/x/sys/unix" 24 ) 25 26 type testProc struct { 27 fn func() // should always exit instead of returning 28 cleanup func() error // for instance, delete coredumps from testing pledge 29 success bool // whether zero-exit means success or failure 30 } 31 32 var ( 33 testProcs = map[string]testProc{} 34 procName = "" 35 ) 36 37 const ( 38 optName = "sys-unix-internal-procname" 39 ) 40 41 func init() { 42 flag.StringVar(&procName, optName, "", "internal use only") 43 } 44 45 // testCmd generates a proper command that, when executed, runs the test 46 // corresponding to the given key. 47 func testCmd(procName string) (*exec.Cmd, error) { 48 exe, err := filepath.Abs(os.Args[0]) 49 if err != nil { 50 return nil, err 51 } 52 cmd := exec.Command(exe, "-"+optName+"="+procName) 53 cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr 54 return cmd, nil 55 } 56 57 // ExitsCorrectly is a comprehensive, one-line-of-use wrapper for testing 58 // a testProc with a key. 59 func ExitsCorrectly(procName string, t *testing.T) { 60 s := testProcs[procName] 61 c, err := testCmd(procName) 62 defer func() { 63 if s.cleanup() != nil { 64 t.Fatalf("Failed to run cleanup for %s", procName) 65 } 66 }() 67 if err != nil { 68 t.Fatalf("Failed to construct command for %s", procName) 69 } 70 if (c.Run() == nil) != s.success { 71 result := "succeed" 72 if !s.success { 73 result = "fail" 74 } 75 t.Fatalf("Process did not %s when it was supposed to", result) 76 } 77 } 78 79 func TestMain(m *testing.M) { 80 flag.Parse() 81 if procName != "" { 82 testProcs[procName].fn() 83 } 84 os.Exit(m.Run()) 85 } 86 87 // For example, add a test for pledge. 88 func init() { 89 testProcs["pledge"] = testProc{ 90 func() { 91 fmt.Println(unix.Pledge("", "")) 92 os.Exit(0) 93 }, 94 func() error { 95 files, err := ioutil.ReadDir(".") 96 if err != nil { 97 return err 98 } 99 for _, file := range files { 100 if filepath.Ext(file.Name()) == ".core" { 101 if err := os.Remove(file.Name()); err != nil { 102 return err 103 } 104 } 105 } 106 return nil 107 }, 108 false, 109 } 110 } 111 112 func TestPledge(t *testing.T) { 113 ExitsCorrectly("pledge", t) 114 }