github.com/humaniq/go-ethereum@v1.6.8-0.20171225131628-061223a13848/cmd/swarm/run_test.go (about)

     1  // Copyright 2016 The go-ethereum Authors
     2  // This file is part of go-ethereum.
     3  //
     4  // go-ethereum 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  // go-ethereum 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 go-ethereum. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package main
    18  
    19  import (
    20  	"fmt"
    21  	"io/ioutil"
    22  	"net"
    23  	"os"
    24  	"path/filepath"
    25  	"runtime"
    26  	"testing"
    27  	"time"
    28  
    29  	"github.com/docker/docker/pkg/reexec"
    30  	"github.com/ethereum/go-ethereum/accounts"
    31  	"github.com/ethereum/go-ethereum/accounts/keystore"
    32  	"github.com/ethereum/go-ethereum/internal/cmdtest"
    33  	"github.com/ethereum/go-ethereum/node"
    34  	"github.com/ethereum/go-ethereum/p2p"
    35  	"github.com/ethereum/go-ethereum/rpc"
    36  	"github.com/ethereum/go-ethereum/swarm"
    37  )
    38  
    39  func init() {
    40  	// Run the app if we've been exec'd as "swarm-test" in runSwarm.
    41  	reexec.Register("swarm-test", func() {
    42  		if err := app.Run(os.Args); err != nil {
    43  			fmt.Fprintln(os.Stderr, err)
    44  			os.Exit(1)
    45  		}
    46  		os.Exit(0)
    47  	})
    48  }
    49  
    50  func TestMain(m *testing.M) {
    51  	// check if we have been reexec'd
    52  	if reexec.Init() {
    53  		return
    54  	}
    55  	os.Exit(m.Run())
    56  }
    57  
    58  func runSwarm(t *testing.T, args ...string) *cmdtest.TestCmd {
    59  	tt := cmdtest.NewTestCmd(t, nil)
    60  
    61  	// Boot "swarm". This actually runs the test binary but the TestMain
    62  	// function will prevent any tests from running.
    63  	tt.Run("swarm-test", args...)
    64  
    65  	return tt
    66  }
    67  
    68  type testCluster struct {
    69  	Nodes  []*testNode
    70  	TmpDir string
    71  }
    72  
    73  // newTestCluster starts a test swarm cluster of the given size.
    74  //
    75  // A temporary directory is created and each node gets a data directory inside
    76  // it.
    77  //
    78  // Each node listens on 127.0.0.1 with random ports for both the HTTP and p2p
    79  // ports (assigned by first listening on 127.0.0.1:0 and then passing the ports
    80  // as flags).
    81  //
    82  // When starting more than one node, they are connected together using the
    83  // admin SetPeer RPC method.
    84  func newTestCluster(t *testing.T, size int) *testCluster {
    85  	cluster := &testCluster{}
    86  	defer func() {
    87  		if t.Failed() {
    88  			cluster.Shutdown()
    89  		}
    90  	}()
    91  
    92  	tmpdir, err := ioutil.TempDir("", "swarm-test")
    93  	if err != nil {
    94  		t.Fatal(err)
    95  	}
    96  	cluster.TmpDir = tmpdir
    97  
    98  	// start the nodes
    99  	cluster.Nodes = make([]*testNode, 0, size)
   100  	for i := 0; i < size; i++ {
   101  		dir := filepath.Join(cluster.TmpDir, fmt.Sprintf("swarm%02d", i))
   102  		if err := os.Mkdir(dir, 0700); err != nil {
   103  			t.Fatal(err)
   104  		}
   105  
   106  		node := newTestNode(t, dir)
   107  		node.Name = fmt.Sprintf("swarm%02d", i)
   108  
   109  		cluster.Nodes = append(cluster.Nodes, node)
   110  	}
   111  
   112  	if size == 1 {
   113  		return cluster
   114  	}
   115  
   116  	// connect the nodes together
   117  	for _, node := range cluster.Nodes {
   118  		if err := node.Client.Call(nil, "admin_addPeer", cluster.Nodes[0].Enode); err != nil {
   119  			t.Fatal(err)
   120  		}
   121  	}
   122  
   123  	// wait until all nodes have the correct number of peers
   124  outer:
   125  	for _, node := range cluster.Nodes {
   126  		var peers []*p2p.PeerInfo
   127  		for start := time.Now(); time.Since(start) < time.Minute; time.Sleep(50 * time.Millisecond) {
   128  			if err := node.Client.Call(&peers, "admin_peers"); err != nil {
   129  				t.Fatal(err)
   130  			}
   131  			if len(peers) == len(cluster.Nodes)-1 {
   132  				continue outer
   133  			}
   134  		}
   135  		t.Fatalf("%s only has %d / %d peers", node.Name, len(peers), len(cluster.Nodes)-1)
   136  	}
   137  
   138  	return cluster
   139  }
   140  
   141  func (c *testCluster) Shutdown() {
   142  	for _, node := range c.Nodes {
   143  		node.Shutdown()
   144  	}
   145  	os.RemoveAll(c.TmpDir)
   146  }
   147  
   148  type testNode struct {
   149  	Name   string
   150  	Addr   string
   151  	URL    string
   152  	Enode  string
   153  	Dir    string
   154  	Client *rpc.Client
   155  	Cmd    *cmdtest.TestCmd
   156  }
   157  
   158  const testPassphrase = "swarm-test-passphrase"
   159  
   160  func getTestAccount(t *testing.T, dir string) (conf *node.Config, account accounts.Account) {
   161  	// create key
   162  	conf = &node.Config{
   163  		DataDir: dir,
   164  		IPCPath: "bzzd.ipc",
   165  		NoUSB:   true,
   166  	}
   167  	n, err := node.New(conf)
   168  	if err != nil {
   169  		t.Fatal(err)
   170  	}
   171  	account, err = n.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore).NewAccount(testPassphrase)
   172  	if err != nil {
   173  		t.Fatal(err)
   174  	}
   175  
   176  	// use a unique IPCPath when running tests on Windows
   177  	if runtime.GOOS == "windows" {
   178  		conf.IPCPath = fmt.Sprintf("bzzd-%s.ipc", account.Address.String())
   179  	}
   180  
   181  	return conf, account
   182  }
   183  
   184  func newTestNode(t *testing.T, dir string) *testNode {
   185  
   186  	conf, account := getTestAccount(t, dir)
   187  	node := &testNode{Dir: dir}
   188  
   189  	// assign ports
   190  	httpPort, err := assignTCPPort()
   191  	if err != nil {
   192  		t.Fatal(err)
   193  	}
   194  	p2pPort, err := assignTCPPort()
   195  	if err != nil {
   196  		t.Fatal(err)
   197  	}
   198  
   199  	// start the node
   200  	node.Cmd = runSwarm(t,
   201  		"--port", p2pPort,
   202  		"--nodiscover",
   203  		"--datadir", dir,
   204  		"--ipcpath", conf.IPCPath,
   205  		"--ens-api", "",
   206  		"--bzzaccount", account.Address.String(),
   207  		"--bzznetworkid", "321",
   208  		"--bzzport", httpPort,
   209  		"--verbosity", "6",
   210  	)
   211  	node.Cmd.InputLine(testPassphrase)
   212  	defer func() {
   213  		if t.Failed() {
   214  			node.Shutdown()
   215  		}
   216  	}()
   217  
   218  	// wait for the node to start
   219  	for start := time.Now(); time.Since(start) < 10*time.Second; time.Sleep(50 * time.Millisecond) {
   220  		node.Client, err = rpc.Dial(conf.IPCEndpoint())
   221  		if err == nil {
   222  			break
   223  		}
   224  	}
   225  	if node.Client == nil {
   226  		t.Fatal(err)
   227  	}
   228  
   229  	// load info
   230  	var info swarm.Info
   231  	if err := node.Client.Call(&info, "bzz_info"); err != nil {
   232  		t.Fatal(err)
   233  	}
   234  	node.Addr = net.JoinHostPort("127.0.0.1", info.Port)
   235  	node.URL = "http://" + node.Addr
   236  
   237  	var nodeInfo p2p.NodeInfo
   238  	if err := node.Client.Call(&nodeInfo, "admin_nodeInfo"); err != nil {
   239  		t.Fatal(err)
   240  	}
   241  	node.Enode = fmt.Sprintf("enode://%s@127.0.0.1:%s", nodeInfo.ID, p2pPort)
   242  
   243  	return node
   244  }
   245  
   246  func (n *testNode) Shutdown() {
   247  	if n.Cmd != nil {
   248  		n.Cmd.Kill()
   249  	}
   250  }
   251  
   252  func assignTCPPort() (string, error) {
   253  	l, err := net.Listen("tcp", "127.0.0.1:0")
   254  	if err != nil {
   255  		return "", err
   256  	}
   257  	l.Close()
   258  	_, port, err := net.SplitHostPort(l.Addr().String())
   259  	if err != nil {
   260  		return "", err
   261  	}
   262  	return port, nil
   263  }