github.com/johnathanhowell/sia@v0.5.1-beta.0.20160524050156-83dcc3d37c94/modules/gateway/gateway_test.go (about) 1 package gateway 2 3 import ( 4 "io/ioutil" 5 "net" 6 "os" 7 "path/filepath" 8 "testing" 9 10 "github.com/NebulousLabs/Sia/build" 11 "github.com/NebulousLabs/Sia/modules" 12 ) 13 14 // newTestingGateway returns a gateway read to use in a testing environment. 15 func newTestingGateway(name string, t *testing.T) *Gateway { 16 g, err := New("localhost:0", build.TempDir("gateway", name)) 17 if err != nil { 18 t.Fatal(err) 19 } 20 return g 21 } 22 23 // TestAddress tests that Gateway.Address returns the address of its listener. 24 // Also tests that the address is not unspecified and is a loopback address. 25 // The address must be a loopback address for testing. 26 func TestAddress(t *testing.T) { 27 g := newTestingGateway("TestAddress", t) 28 defer g.Close() 29 if g.Address() != g.myAddr { 30 t.Fatal("Address does not return g.myAddr") 31 } 32 if g.Address() != modules.NetAddress(g.listener.Addr().String()) { 33 t.Fatalf("wrong address: expected %v, got %v", g.listener.Addr(), g.Address()) 34 } 35 host := modules.NetAddress(g.listener.Addr().String()).Host() 36 ip := net.ParseIP(host) 37 if ip.IsUnspecified() { 38 t.Fatal("expected a non-unspecified address") 39 } 40 if !ip.IsLoopback() { 41 t.Fatal("expected a loopback address") 42 } 43 } 44 45 func TestPeers(t *testing.T) { 46 g1 := newTestingGateway("TestRPC1", t) 47 defer g1.Close() 48 g2 := newTestingGateway("TestRPC2", t) 49 defer g2.Close() 50 err := g1.Connect(g2.Address()) 51 if err != nil { 52 t.Fatal("failed to connect:", err) 53 } 54 peers := g1.Peers() 55 if len(peers) != 1 || peers[0].NetAddress != g2.Address() { 56 t.Fatal("g1 has bad peer list:", peers) 57 } 58 err = g1.Disconnect(g2.Address()) 59 if err != nil { 60 t.Fatal("failed to disconnect:", err) 61 } 62 peers = g1.Peers() 63 if len(peers) != 0 { 64 t.Fatal("g1 has peers after disconnect:", peers) 65 } 66 } 67 68 func TestNew(t *testing.T) { 69 if _, err := New("", ""); err == nil { 70 t.Fatal("expecting persistDir error, got nil") 71 } 72 if _, err := New("localhost:0", ""); err == nil { 73 t.Fatal("expecting persistDir error, got nil") 74 } 75 if g, err := New("foo", build.TempDir("gateway", "TestNew1")); err == nil { 76 t.Fatal("expecting listener error, got nil", g.myAddr) 77 } 78 // create corrupted nodes.json 79 dir := build.TempDir("gateway", "TestNew2") 80 os.MkdirAll(dir, 0700) 81 err := ioutil.WriteFile(filepath.Join(dir, "nodes.json"), []byte{1, 2, 3}, 0660) 82 if err != nil { 83 t.Fatal("couldn't create corrupted file:", err) 84 } 85 if _, err := New("localhost:0", dir); err == nil { 86 t.Fatal("expected load error, got nil") 87 } 88 }