github.com/unicornultrafoundation/go-u2u@v1.0.0-rc1.0.20240205080301-e74a83d3fadc/cmd/u2u/launcher/run_test.go (about) 1 package launcher 2 3 import ( 4 "context" 5 "fmt" 6 "io/ioutil" 7 "os" 8 "strings" 9 "testing" 10 "time" 11 12 "github.com/docker/docker/pkg/reexec" 13 14 "github.com/unicornultrafoundation/go-u2u/cmd/cmdtest" 15 "github.com/unicornultrafoundation/go-u2u/common" 16 "github.com/unicornultrafoundation/go-u2u/rpc" 17 ) 18 19 func tmpdir(t *testing.T) string { 20 dir, err := ioutil.TempDir("", "u2u-test") 21 if err != nil { 22 t.Fatal(err) 23 } 24 return dir 25 } 26 27 type testcli struct { 28 *cmdtest.TestCmd 29 30 // template variables for expect 31 Datadir string 32 Coinbase string 33 } 34 35 func (tt *testcli) readConfig() { 36 cfg := defaultNodeConfig() 37 cfg.DataDir = tt.Datadir 38 addr := common.Address{} // TODO: addr = emitter coinbase 39 tt.Coinbase = strings.ToLower(addr.String()) 40 } 41 42 func init() { 43 // Run the app if we've been exec'd as "u2u-test" in exec(). 44 reexec.Register("u2u-test", func() { 45 if err := app.Run(os.Args); err != nil { 46 fmt.Fprintln(os.Stderr, err) 47 os.Exit(1) 48 } 49 os.Exit(0) 50 }) 51 } 52 53 func TestMain(m *testing.M) { 54 // check if we have been reexec'd 55 if reexec.Init() { 56 return 57 } 58 os.Exit(m.Run()) 59 } 60 61 // exec cli with the given command line args. If the args don't set --datadir, the 62 // child g gets a temporary data directory. 63 func exec(t *testing.T, args ...string) *testcli { 64 tt := &testcli{} 65 tt.TestCmd = cmdtest.NewTestCmd(t, tt) 66 67 if len(args) < 1 || args[0] != "attach" { 68 // make datadir 69 for i, arg := range args { 70 switch { 71 case arg == "-datadir" || arg == "--datadir": 72 if i < len(args)-1 { 73 tt.Datadir = args[i+1] 74 } 75 } 76 } 77 if tt.Datadir == "" { 78 tt.Datadir = tmpdir(t) 79 args = append([]string{"-datadir", tt.Datadir}, args...) 80 } 81 82 // Remove the temporary datadir. 83 tt.Cleanup = func() { os.RemoveAll(tt.Datadir) } 84 defer func() { 85 if t.Failed() { 86 tt.Cleanup() 87 } 88 }() 89 } 90 91 // Boot "u2u". This actually runs the test binary but the TestMain 92 // function will prevent any tests from running. 93 tt.Run("u2u-test", args...) 94 95 // Read the generated key 96 tt.readConfig() 97 98 return tt 99 } 100 101 // waitForEndpoint attempts to connect to an RPC endpoint until it succeeds. 102 func waitForEndpoint(t *testing.T, endpoint string, timeout time.Duration) { 103 probe := func() bool { 104 ctx, cancel := context.WithTimeout(context.Background(), timeout) 105 defer cancel() 106 c, err := rpc.DialContext(ctx, endpoint) 107 if c != nil { 108 _, err = c.SupportedModules() 109 c.Close() 110 } 111 return err == nil 112 } 113 114 start := time.Now() 115 for { 116 if probe() { 117 return 118 } 119 if time.Since(start) > timeout { 120 t.Fatal("endpoint", endpoint, "did not open within", timeout) 121 } 122 time.Sleep(200 * time.Millisecond) 123 } 124 }