github.com/Elemental-core/elementalcore@v0.0.0-20191206075037-63891242267a/cmd/geth/run_test.go (about) 1 // Copyright 2016 The elementalcore Authors 2 // This file is part of elementalcore. 3 // 4 // elementalcore is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // elementalcore is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU General Public License for more details. 13 // 14 // You should have received a copy of the GNU General Public License 15 // along with elementalcore. If not, see <http://www.gnu.org/licenses/>. 16 17 package main 18 19 import ( 20 "fmt" 21 "io/ioutil" 22 "os" 23 "testing" 24 25 "github.com/docker/docker/pkg/reexec" 26 "github.com/Elemental-core/elementalcore/internal/cmdtest" 27 ) 28 29 func tmpdir(t *testing.T) string { 30 dir, err := ioutil.TempDir("", "geth-test") 31 if err != nil { 32 t.Fatal(err) 33 } 34 return dir 35 } 36 37 type testgeth struct { 38 *cmdtest.TestCmd 39 40 // template variables for expect 41 Datadir string 42 Validator string 43 Coinbase string 44 } 45 46 func init() { 47 // Run the app if we've been exec'd as "geth-test" in runGeth. 48 reexec.Register("geth-test", func() { 49 if err := app.Run(os.Args); err != nil { 50 fmt.Fprintln(os.Stderr, err) 51 os.Exit(1) 52 } 53 os.Exit(0) 54 }) 55 } 56 57 func TestMain(m *testing.M) { 58 // check if we have been reexec'd 59 if reexec.Init() { 60 return 61 } 62 os.Exit(m.Run()) 63 } 64 65 // spawns geth with the given command line args. If the args don't set --datadir, the 66 // child g gets a temporary data directory. 67 func runGeth(t *testing.T, args ...string) *testgeth { 68 tt := &testgeth{} 69 tt.TestCmd = cmdtest.NewTestCmd(t, tt) 70 for i, arg := range args { 71 switch { 72 case arg == "-datadir" || arg == "--datadir": 73 if i < len(args)-1 { 74 tt.Datadir = args[i+1] 75 } 76 case arg == "-coinbase" || arg == "--coinbase": 77 if i < len(args)-1 { 78 tt.Coinbase = args[i+1] 79 } 80 case arg == "-validator" || arg == "--validator": 81 if i < len(args)-1 { 82 tt.Validator = args[i+1] 83 } 84 } 85 } 86 if tt.Datadir == "" { 87 tt.Datadir = tmpdir(t) 88 tt.Cleanup = func() { os.RemoveAll(tt.Datadir) } 89 args = append([]string{"-datadir", tt.Datadir}, args...) 90 // Remove the temporary datadir if something fails below. 91 defer func() { 92 if t.Failed() { 93 tt.Cleanup() 94 } 95 }() 96 } 97 98 // Boot "geth". This actually runs the test binary but the TestMain 99 // function will prevent any tests from running. 100 tt.Run("geth-test", args...) 101 102 return tt 103 }