github.com/sberex/go-sberex@v1.8.2-0.20181113200658-ed96ac38f7d7/cmd/swarm/upload_test.go (about)

     1  // This file is part of the go-sberex library. The go-sberex library is 
     2  // free software: you can redistribute it and/or modify it under the terms 
     3  // of the GNU Lesser General Public License as published by the Free 
     4  // Software Foundation, either version 3 of the License, or (at your option)
     5  // any later version.
     6  //
     7  // The go-sberex library is distributed in the hope that it will be useful, 
     8  // but WITHOUT ANY WARRANTY; without even the implied warranty of
     9  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser 
    10  // General Public License <http://www.gnu.org/licenses/> for more details.
    11  
    12  package main
    13  
    14  import (
    15  	"io"
    16  	"io/ioutil"
    17  	"net/http"
    18  	"os"
    19  	"testing"
    20  )
    21  
    22  // TestCLISwarmUp tests that running 'swarm up' makes the resulting file
    23  // available from all nodes via the HTTP API
    24  func TestCLISwarmUp(t *testing.T) {
    25  	// start 3 node cluster
    26  	t.Log("starting 3 node cluster")
    27  	cluster := newTestCluster(t, 3)
    28  	defer cluster.Shutdown()
    29  
    30  	// create a tmp file
    31  	tmp, err := ioutil.TempFile("", "swarm-test")
    32  	assertNil(t, err)
    33  	defer tmp.Close()
    34  	defer os.Remove(tmp.Name())
    35  	_, err = io.WriteString(tmp, "data")
    36  	assertNil(t, err)
    37  
    38  	// upload the file with 'swarm up' and expect a hash
    39  	t.Log("uploading file with 'swarm up'")
    40  	up := runSwarm(t, "--bzzapi", cluster.Nodes[0].URL, "up", tmp.Name())
    41  	_, matches := up.ExpectRegexp(`[a-f\d]{64}`)
    42  	up.ExpectExit()
    43  	hash := matches[0]
    44  	t.Logf("file uploaded with hash %s", hash)
    45  
    46  	// get the file from the HTTP API of each node
    47  	for _, node := range cluster.Nodes {
    48  		t.Logf("getting file from %s", node.Name)
    49  		res, err := http.Get(node.URL + "/bzz:/" + hash)
    50  		assertNil(t, err)
    51  		assertHTTPResponse(t, res, http.StatusOK, "data")
    52  	}
    53  }
    54  
    55  func assertNil(t *testing.T, err error) {
    56  	if err != nil {
    57  		t.Fatal(err)
    58  	}
    59  }
    60  
    61  func assertHTTPResponse(t *testing.T, res *http.Response, expectedStatus int, expectedBody string) {
    62  	defer res.Body.Close()
    63  	if res.StatusCode != expectedStatus {
    64  		t.Fatalf("expected HTTP status %d, got %s", expectedStatus, res.Status)
    65  	}
    66  	data, err := ioutil.ReadAll(res.Body)
    67  	assertNil(t, err)
    68  	if string(data) != expectedBody {
    69  		t.Fatalf("expected HTTP body %q, got %q", expectedBody, data)
    70  	}
    71  }