// Test instantiation of Node func TestNewNode(t *testing.T) { defer log.AfterTest(t) h1, h2 := SetupTwoHosts(t, false) // Add tree + entitylist el := sda.NewRoster([]*network.ServerIdentity{h1.ServerIdentity, h2.ServerIdentity}) h1.AddRoster(el) tree := el.GenerateBinaryTree() h1.AddTree(tree) // Try directly StartNewNode proto, err := h1.StartProtocol(testProto, tree) if err != nil { t.Fatal("Could not start new protocol", err) } p := proto.(*ProtocolTest) m := <-p.DispMsg if m != "Dispatch" { t.Fatal("Dispatch() not called - msg is:", m) } m = <-p.StartMsg if m != "Start" { t.Fatal("Start() not called - msg is:", m) } h1.Close() h2.Close() }
func TestProtocolHandlers(t *testing.T) { defer log.AfterTest(t) local := sda.NewLocalTest() _, _, tree := local.GenTree(3, false, true, true) defer local.CloseAll() log.Lvl2("Sending to children") IncomingHandlers = make(chan *sda.TreeNodeInstance, 2) p, err := local.CreateProtocol(tree, "ProtocolHandlers") if err != nil { t.Fatal(err) } go p.Start() log.Lvl2("Waiting for responses") child1 := <-IncomingHandlers child2 := <-IncomingHandlers if child1.ServerIdentity().ID == child2.ServerIdentity().ID { t.Fatal("Both entities should be different") } log.Lvl2("Sending to parent") tni := p.(*ProtocolHandlers).TreeNodeInstance child1.SendTo(tni.TreeNode(), &NodeTestAggMsg{}) if len(IncomingHandlers) > 0 { t.Fatal("This should not trigger yet") } child2.SendTo(tni.TreeNode(), &NodeTestAggMsg{}) final := <-IncomingHandlers if final.ServerIdentity().ID != tni.ServerIdentity().ID { t.Fatal("This should be the same ID") } }
func TestProcessor_ProcessClientRequest(t *testing.T) { defer log.AfterTest(t) local := NewLocalTest() // generate 5 hosts, they don't connect, they process messages, and they // don't register the tree or entitylist h := local.GenLocalHosts(1, false, false)[0] defer local.CloseAll() s := local.Services[h.ServerIdentity.ID] ts := s[testServiceID] cr := &ClientRequest{Data: mkClientRequest(&testMsg{12})} ts.ProcessClientRequest(h.ServerIdentity, cr) msg := ts.(*testService).Msg if msg == nil { t.Fatal("Msg should not be nil") } tm, ok := msg.(*testMsg) if !ok { t.Fatalf("Couldn't cast to *testMsg - %+v", tm) } if tm.I != 12 { t.Fatal("Didn't send 12") } }
func TestMain(m *testing.M) { flag.Parse() log.TestOutput(testing.Verbose(), 4) code := m.Run() log.AfterTest(nil) os.Exit(code) }
func TestProcessor_AddMessage(t *testing.T) { defer log.AfterTest(t) p := NewServiceProcessor(nil) log.ErrFatal(p.RegisterMessage(procMsg)) if len(p.functions) != 1 { t.Fatal("Should have registered one function") } mt := network.TypeFromData(&testMsg{}) if mt == network.ErrorType { t.Fatal("Didn't register message-type correctly") } var wrongFunctions = []interface{}{ procMsgWrong1, procMsgWrong2, procMsgWrong3, procMsgWrong4, procMsgWrong5, procMsgWrong6, } for _, f := range wrongFunctions { log.Lvl2("Checking function", reflect.TypeOf(f).String()) err := p.RegisterMessage(f) if err == nil { t.Fatalf("Shouldn't accept function %+s", reflect.TypeOf(f).String()) } } }
// Test connection of multiple Hosts and sending messages back and forth // also tests for the counterIO interface that it works well func TestHostMessaging(t *testing.T) { defer log.AfterTest(t) h1, h2 := SetupTwoHosts(t, false) bw1 := h1.Tx() br2 := h2.Rx() msgSimple := &SimpleMessage{3} err := h1.SendRaw(h2.ServerIdentity, msgSimple) if err != nil { t.Fatal("Couldn't send from h2 -> h1:", err) } msg := h2.Receive() decoded := testMessageSimple(t, msg) if decoded.I != 3 { t.Fatal("Received message from h2 -> h1 is wrong") } written := h1.Tx() - bw1 read := h2.Rx() - br2 if written == 0 || read == 0 || written != read { t.Logf("Before => bw1 = %d vs br2 = %d", bw1, br2) t.Logf("Tx = %d, Rx = %d", written, read) t.Logf("h1.Tx() %d vs h2.Rx() %d", h1.Tx(), h2.Rx()) t.Fatal("Something is wrong with Host.CounterIO") } h1.Close() h2.Close() }
func TestNodeChannel(t *testing.T) { defer log.AfterTest(t) local := sda.NewLocalTest() _, _, tree := local.GenTree(2, false, true, true) defer local.CloseAll() p, err := local.CreateProtocol(tree, "ProtocolChannels") if err != nil { t.Fatal("Couldn't create new node:", err) } c := make(chan struct { *sda.TreeNode NodeTestMsg }, 1) tni := p.(*ProtocolChannels).TreeNodeInstance err = tni.RegisterChannel(c) if err != nil { t.Fatal("Couldn't register channel:", err) } err = tni.DispatchChannel([]*sda.ProtocolMsg{&sda.ProtocolMsg{ Msg: NodeTestMsg{3}, MsgType: network.RegisterMessageType(NodeTestMsg{}), From: &sda.Token{ TreeID: tree.ID, TreeNodeID: tree.Root.ID, }}, }) if err != nil { t.Fatal("Couldn't dispatch to channel:", err) } msg := <-c if msg.I != 3 { t.Fatal("Message should contain '3'") } }
func TestTokenId(t *testing.T) { defer log.AfterTest(t) t1 := &sda.Token{ RosterID: sda.RosterID(uuid.NewV1()), TreeID: sda.TreeID(uuid.NewV1()), ProtoID: sda.ProtocolID(uuid.NewV1()), RoundID: sda.RoundID(uuid.NewV1()), } id1 := t1.ID() t2 := &sda.Token{ RosterID: sda.RosterID(uuid.NewV1()), TreeID: sda.TreeID(uuid.NewV1()), ProtoID: sda.ProtocolID(uuid.NewV1()), RoundID: sda.RoundID(uuid.NewV1()), } id2 := t2.ID() if uuid.Equal(uuid.UUID(id1), uuid.UUID(id2)) { t.Fatal("Both token are the same") } if !uuid.Equal(uuid.UUID(id1), uuid.UUID(t1.ID())) { t.Fatal("Twice the Id of the same token should be equal") } t3 := t1.ChangeTreeNodeID(sda.TreeNodeID(uuid.NewV1())) if t1.TreeNodeID.Equal(t3.TreeNodeID) { t.Fatal("OtherToken should modify copy") } }
func TestProcessor_GetReply(t *testing.T) { defer log.AfterTest(t) p := NewServiceProcessor(nil) log.ErrFatal(p.RegisterMessage(procMsg)) pair := config.NewKeyPair(network.Suite) e := network.NewServerIdentity(pair.Public, "") rep := p.GetReply(e, mkClientRequest(&testMsg{11})) val, ok := rep.(*testMsg) if !ok { t.Fatalf("Couldn't cast reply to testMsg: %+v", rep) } if val.I != 11 { t.Fatal("Value got lost - should be 11") } rep = p.GetReply(e, mkClientRequest(&testMsg{42})) errMsg, ok := rep.(*StatusRet) if !ok { t.Fatal("42 should return an error") } if errMsg.Status == "" { t.Fatal("The error should be non-empty") } }
// Testing a full-blown server/client func TestTcpNetwork(t *testing.T) { defer log.AfterTest(t) // Create one client + one server clientHost := NewTCPHost() serverHost := NewTCPHost() // Give them keys clientPub := Suite.Point().Base() serverPub := Suite.Point().Add(Suite.Point().Base(), Suite.Point().Base()) wg := sync.WaitGroup{} client := NewSimpleClient(clientHost, clientPub, &wg) server := NewSimpleServer(serverHost, serverPub, t, &wg) // Make the server listen done := make(chan bool) go func() { err := server.Listen("127.0.0.1:5000", server.ExchangeWithClient) if err != nil { t.Fatal("Couldn't listen:", err) } done <- true }() // Make the client engage with the server client.ExchangeWithServer("127.0.0.1:5000", t) wg.Wait() if err := clientHost.Close(); err != nil { t.Fatal("could not close client", err) } if err := serverHost.Close(); err != nil { t.Fatal("could not close server", err) } <-done }
// Test closing and opening of Host on same address func TestHostClose(t *testing.T) { defer log.AfterTest(t) time.Sleep(time.Second) h1 := sda.NewLocalHost(2000) h2 := sda.NewLocalHost(2001) h1.ListenAndBind() _, err := h2.Connect(h1.ServerIdentity) if err != nil { t.Fatal("Couldn't Connect()", err) } err = h1.Close() if err != nil { t.Fatal("Couldn't close:", err) } err = h2.Close() if err != nil { t.Fatal("Couldn't close:", err) } log.Lvl3("Finished first connection, starting 2nd") h3 := sda.NewLocalHost(2002) h3.ListenAndBind() c, err := h2.Connect(h3.ServerIdentity) if err != nil { t.Fatal(h2, "Couldn Connect() to", h3) } log.Lvl3("Closing h3") err = h3.Close() if err != nil { // try closing the underlying connection manually and fail c.Close() t.Fatal("Couldn't Close()", h3) } }
func TestSimulationBF(t *testing.T) { defer log.AfterTest(t) log.TestOutput(testing.Verbose(), 4) sc, _, err := createBFTree(7, 2) if err != nil { t.Fatal(err) } addresses := []string{ "local1:2000", "local2:2000", "local1:2001", "local2:2001", "local1:2002", "local2:2002", "local1:2003", } for i, a := range sc.Roster.List { if a.Addresses[0] != addresses[i] { t.Fatal("Address", a.Addresses[0], "should be", addresses[i]) } } if !sc.Tree.IsBinary(sc.Tree.Root) { t.Fatal("Created tree is not binary") } sc, _, err = createBFTree(13, 3) if err != nil { t.Fatal(err) } if len(sc.Tree.Root.Children) != 3 { t.Fatal("Branching-factor 3 tree has not 3 children") } if !sc.Tree.IsNary(sc.Tree.Root, 3) { t.Fatal("Created tree is not binary") } }
func TestReadyNormal(t *testing.T) { defer log.AfterTest(t) log.TestOutput(testing.Verbose(), 3) m := make(map[string]string) m["servers"] = "1" stat := NewStats(m) fresh := stat.String() // First set up monitor listening mon := NewMonitor(stat) go mon.Listen() time.Sleep(100 * time.Millisecond) // Then measure err := ConnectSink("localhost:" + strconv.Itoa(DefaultSinkPort)) if err != nil { t.Fatal(fmt.Sprintf("Error starting monitor: %s", err)) return } meas := NewSingleMeasure("round", 10) meas.Record() time.Sleep(200 * time.Millisecond) NewSingleMeasure("round", 20) EndAndCleanup() time.Sleep(100 * time.Millisecond) updated := mon.Stats().String() if updated == fresh { t.Fatal("Stats not updated ?") } }
func TestKeyOrder(t *testing.T) { defer log.AfterTest(t) log.TestOutput(testing.Verbose(), 3) m := make(map[string]string) m["servers"] = "1" m["hosts"] = "1" m["bf"] = "2" // create stats stat := NewStats(m) m1 := NewSingleMeasure("round", 10) m2 := NewSingleMeasure("setup", 5) stat.Update(m1) stat.Update(m2) str := new(bytes.Buffer) stat.WriteHeader(str) stat.WriteValues(str) stat2 := NewStats(m) stat2.Update(m1) stat2.Update(m2) str2 := new(bytes.Buffer) stat2.WriteHeader(str2) stat2.WriteValues(str2) if !bytes.Equal(str.Bytes(), str2.Bytes()) { t.Fatal("KeyOrder / output not the same for same stats") } }
// Tests a 2-node system func TestBroadcast(t *testing.T) { defer log.AfterTest(t) log.TestOutput(testing.Verbose(), 3) for _, nbrNodes := range []int{3, 10, 14} { local := sda.NewLocalTest() _, _, tree := local.GenTree(nbrNodes, false, true, true) pi, err := local.CreateProtocol(tree, "Broadcast") if err != nil { t.Fatal("Couldn't start protocol:", err) } protocol := pi.(*manage.Broadcast) done := make(chan bool) protocol.RegisterOnDone(func() { done <- true }) protocol.Start() timeout := network.WaitRetry * time.Duration(network.MaxRetry*nbrNodes*2) * time.Millisecond select { case <-done: log.Lvl2("Done with connecting everybody") case <-time.After(timeout): t.Fatal("Didn't finish in time") } local.CloseAll() } }
// Tests a 2-node system func TestCloseall(t *testing.T) { defer log.AfterTest(t) log.TestOutput(testing.Verbose(), 4) local := sda.NewLocalTest() nbrNodes := 2 _, _, tree := local.GenTree(nbrNodes, false, true, true) defer local.CloseAll() pi, err := local.CreateProtocol(tree, "ExampleChannels") if err != nil { t.Fatal("Couldn't start protocol:", err) } go pi.Start() protocol := pi.(*channels.ProtocolExampleChannels) timeout := network.WaitRetry * time.Duration(network.MaxRetry*nbrNodes*2) * time.Millisecond select { case children := <-protocol.ChildCount: log.Lvl2("Instance 1 is done") if children != nbrNodes { t.Fatal("Didn't get a child-cound of", nbrNodes) } case <-time.After(timeout): t.Fatal("Didn't finish in time") } }
func TestBftCoSi(t *testing.T) { defer log.AfterTest(t) log.TestOutput(testing.Verbose(), 4) // Register test protocol using BFTCoSi sda.ProtocolRegisterName(TestProtocolName, func(n *sda.TreeNodeInstance) (sda.ProtocolInstance, error) { return NewBFTCoSiProtocol(n, verify) }) for _, nbrHosts := range []int{3, 13} { countMut.Lock() veriCount = 0 countMut.Unlock() log.Lvl2("Running BFTCoSi with", nbrHosts, "hosts") local := sda.NewLocalTest() _, _, tree := local.GenBigTree(nbrHosts, nbrHosts, 3, true, true) done := make(chan bool) // create the message we want to sign for this round msg := []byte("Hello BFTCoSi") // Start the protocol node, err := local.CreateProtocol(tree, TestProtocolName) if err != nil { t.Fatal("Couldn't create new node:", err) } // Register the function generating the protocol instance var root *ProtocolBFTCoSi root = node.(*ProtocolBFTCoSi) root.Msg = msg // function that will be called when protocol is finished by the root root.RegisterOnDone(func() { done <- true }) go node.Start() // are we done yet? wait := time.Second * 3 select { case <-done: countMut.Lock() assert.Equal(t, veriCount, nbrHosts, "Each host should have called verification.") // if assert fails we don't care for unlocking (t.Fail) countMut.Unlock() sig := root.Signature() if err := cosi.VerifyCosiSignatureWithException(root.Suite(), root.AggregatedPublic, msg, sig.Sig, sig.Exceptions); err != nil { t.Fatal(fmt.Sprintf("%s Verification of the signature failed: %s", root.Name(), err.Error())) } case <-time.After(wait): t.Fatal("Waited", wait, "sec for BFTCoSi to finish ...") } local.CloseAll() } }
func TestRegisterReflect(t *testing.T) { defer log.AfterTest(t) typ := RegisterMessageType(TestRegisterS{}) typReflect := RTypeToMessageTypeID(reflect.TypeOf(TestRegisterS{})) if typ != typReflect { t.Fatal("Register does not work") } }
func TestHostClose2(t *testing.T) { defer log.AfterTest(t) local := sda.NewLocalTest() defer local.CloseAll() _, _, tree := local.GenTree(2, false, true, true) log.Lvl3(tree.Dump()) time.Sleep(time.Millisecond * 100) log.Lvl3("Done") }
func TestBigTree(t *testing.T) { defer log.AfterTest(t) log.TestOutput(testing.Verbose(), 4) for i := uint(12); i < 15; i++ { _, _, err := createBFTree(1<<i-1, 2) if err != nil { t.Fatal(err) } } }
// This makes h2 the leader, so it creates a tree and entity list // and start a protocol. H1 should receive that message and request the entitity // list and the treelist and then instantiate the protocol. func TestProtocolAutomaticInstantiation(t *testing.T) { defer log.AfterTest(t) log.TestOutput(testing.Verbose(), 4) // setup chanH1 := make(chan bool) chanH2 := make(chan bool) chans := []chan bool{chanH1, chanH2} id := 0 // custom creation function so we know the step due to the channels fn := func(n *sda.TreeNodeInstance) (sda.ProtocolInstance, error) { ps := SimpleProtocol{ TreeNodeInstance: n, Chan: chans[id], } ps.RegisterHandler(ps.ReceiveMessage) id++ return &ps, nil } network.RegisterMessageType(SimpleMessage{}) sda.ProtocolRegisterName(simpleProto, fn) h1, h2 := SetupTwoHosts(t, true) defer h1.Close() defer h2.Close() h1.StartProcessMessages() // create small Tree el := sda.NewRoster([]*network.ServerIdentity{h1.ServerIdentity, h2.ServerIdentity}) h1.AddRoster(el) tree := el.GenerateBinaryTree() h1.AddTree(tree) // start the protocol go func() { _, err := h1.StartProtocol(simpleProto, tree) if err != nil { t.Fatal(fmt.Sprintf("Could not start protocol %v", err)) } }() // we are supposed to receive something from host1 from Start() select { case _ = <-chanH1: break case <-time.After(200 * time.Millisecond): t.Fatal("Could not receive from channel of host 1") } // Then we are supposed to receive from h2 after he got the tree and the // entity list from h1 select { case _ = <-chanH2: break case <-time.After(2 * time.Second): t.Fatal("Could not receive from channel of host 1") } }
// Test propagation of tree - both known and unknown func TestTreePropagation(t *testing.T) { defer log.AfterTest(t) local := sda.NewLocalTest() hosts, el, tree := local.GenTree(2, true, false, false) defer local.CloseAll() h1 := hosts[0] h2 := hosts[1] // Suppose both hosts have the list available, but not the tree h1.AddRoster(el) h2.AddRoster(el) h2.StartProcessMessages() // Check that h2 sends back an empty tree if it is unknown err := h1.SendRaw(h2.ServerIdentity, &sda.RequestTree{TreeID: tree.ID}) if err != nil { t.Fatal("Couldn't send message to h2:", err) } msg := h1.Receive() if msg.MsgType != sda.SendTreeMessageID { network.DumpTypes() t.Fatal("h1 didn't receive SendTree type:", msg.MsgType) } if msg.Msg.(sda.TreeMarshal).RosterID != sda.RosterID(uuid.Nil) { t.Fatal("List should be empty") } // Now add the list to h2 and try again h2.AddTree(tree) err = h1.SendRaw(h2.ServerIdentity, &sda.RequestTree{TreeID: tree.ID}) if err != nil { t.Fatal("Couldn't send message to h2:", err) } msg = h1.Receive() if msg.MsgType != sda.SendTreeMessageID { t.Fatal("h1 didn't receive Tree-type") } if msg.Msg.(sda.TreeMarshal).TreeID != tree.ID { t.Fatal("Tree should be equal to original tree") } // And test whether it gets stored correctly h1.StartProcessMessages() err = h1.SendRaw(h2.ServerIdentity, &sda.RequestTree{TreeID: tree.ID}) if err != nil { t.Fatal("Couldn't send message to h2:", err) } time.Sleep(time.Second) tree2, ok := h1.GetTree(tree.ID) if !ok { t.Fatal("List-id not found") } if !tree.Equal(tree2) { t.Fatal("Trees do not match") } }
// Test setting up of Host func TestHostNew(t *testing.T) { defer log.AfterTest(t) h1 := sda.NewLocalHost(2000) if h1 == nil { t.Fatal("Couldn't setup a Host") } err := h1.Close() if err != nil { t.Fatal("Couldn't close", err) } }
// Test propagation of peer-lists - both known and unknown func TestPeerListPropagation(t *testing.T) { defer log.AfterTest(t) local := sda.NewLocalTest() hosts, el, _ := local.GenTree(2, false, false, false) defer local.CloseAll() h1 := hosts[0] h2 := hosts[1] h2.StartProcessMessages() // Check that h2 sends back an empty list if it is unknown err := h1.SendRaw(h2.ServerIdentity, &sda.RequestRoster{ RosterID: el.ID}) if err != nil { t.Fatal("Couldn't send message to h2:", err) } msg := h1.Receive() if msg.MsgType != sda.SendRosterMessageID { t.Fatal("h1 didn't receive Roster type, but", msg.MsgType) } if msg.Msg.(sda.Roster).ID != sda.RosterID(uuid.Nil) { t.Fatal("List should be empty") } // Now add the list to h2 and try again h2.AddRoster(el) err = h1.SendRaw(h2.ServerIdentity, &sda.RequestRoster{RosterID: el.ID}) if err != nil { t.Fatal("Couldn't send message to h2:", err) } msg = h1.Receive() if msg.MsgType != sda.SendRosterMessageID { t.Fatal("h1 didn't receive Roster type") } if msg.Msg.(sda.Roster).ID != el.ID { t.Fatal("List should be equal to original list") } // And test whether it gets stored correctly h1.StartProcessMessages() err = h1.SendRaw(h2.ServerIdentity, &sda.RequestRoster{RosterID: el.ID}) if err != nil { t.Fatal("Couldn't send message to h2:", err) } time.Sleep(time.Second) list, ok := h1.Roster(el.ID) if !ok { t.Fatal("List-id not found") } if list.ID != el.ID { t.Fatal("IDs do not match") } }
func TestBlocking(t *testing.T) { defer log.AfterTest(t) l := sda.NewLocalTest() _, _, tree := l.GenTree(2, true, true, true) defer l.CloseAll() n1, err := l.StartProtocol("ProtocolBlocking", tree) if err != nil { t.Fatal("Couldn't start protocol") } n2, err := l.StartProtocol("ProtocolBlocking", tree) if err != nil { t.Fatal("Couldn't start protocol") } p1 := n1.(*BlockingProtocol) p2 := n2.(*BlockingProtocol) tn1 := p1.TreeNodeInstance tn2 := p2.TreeNodeInstance go func() { // Send two messages to n1, which blocks the old interface err := l.SendTreeNode("", tn2, tn1, &NodeTestMsg{}) if err != nil { t.Fatal("Couldn't send message:", err) } err = l.SendTreeNode("", tn2, tn1, &NodeTestMsg{}) if err != nil { t.Fatal("Couldn't send message:", err) } // Now send a message to n2, but in the old interface this // blocks. err = l.SendTreeNode("", tn1, tn2, &NodeTestMsg{}) if err != nil { t.Fatal("Couldn't send message:", err) } }() // Release p2 p2.stopBlockChan <- true select { case <-p2.doneChan: log.Lvl2("Node 2 done") p1.stopBlockChan <- true <-p1.doneChan case <-time.After(time.Second): t.Fatal("Node 2 didn't receive") } }
func TestNtree(t *testing.T) { defer log.AfterTest(t) log.TestOutput(testing.Verbose(), 4) for _, nbrHosts := range []int{1, 3, 13} { log.Lvl2("Running ntree with", nbrHosts, "hosts") local := sda.NewLocalTest() _, _, tree := local.GenBigTree(nbrHosts, nbrHosts, 3, true, true) done := make(chan bool) // create the message we want to sign for this round msg := []byte("Ntree rocks slowly") // Register the function generating the protocol instance var root *ntree.Protocol // function that will be called when protocol is finished by the root doneFunc := func() bool { done <- true return true } // Start the protocol pi, err := local.CreateProtocol(tree, "NaiveTree") if err != nil { t.Fatal("Couldn't create new node:", err) } root = pi.(*ntree.Protocol) root.Message = msg root.OnDoneCallback(doneFunc) err = pi.Start() if nbrHosts == 1 { if err == nil { t.Fatal("Shouldn't be able to start NTree with 1 node") } } else if err != nil { t.Fatal("Couldn't start protocol:", err) } else { select { case <-done: case <-time.After(time.Second * 2): t.Fatal("Protocol didn't finish in time") } } local.CloseAll() } }
func TestTcpCounterIO(t *testing.T) { defer log.AfterTest(t) RegisterMessageType(&TestRegisterS{}) log.TestOutput(testing.Verbose(), 4) receiverStarted := make(chan bool) fn := func(s Conn) { err := s.Send(context.TODO(), &TestRegisterS{10}) if err != nil { t.Fatal("Error while sending message:", err) } close(receiverStarted) } h1 := NewTCPHost() h2 := NewTCPHost() done := make(chan bool) go func() { err := h1.Listen("localhost:3000", fn) if err != nil { t.Fatal("Listening failed for h1:", err) } done <- true }() c2, err := h2.Open("localhost:3000") if err != nil { t.Fatal("Couldn't open h2:", err) } <-receiverStarted c2.Receive(context.TODO()) err = h1.Close() if err != nil { t.Fatal("Couldn't close:", err) } err = h2.Close() if err != nil { t.Fatal("Couldn't close:", err) } <-done // verify the amount of bytes read / written if h1.Tx() == 0 || h1.Tx() != h2.Rx() || h2.Rx() == 0 || h2.Rx() != c2.Rx() { t.Fatal("stg is wrong with CounterIO implementation of TcpConn / TcpHost") } }
// Testing exchange of entity func TestSecureTcp(t *testing.T) { defer log.AfterTest(t) log.TestOutput(testing.Verbose(), 4) opened := make(chan bool) fn := func(s SecureConn) { log.Lvl3("Getting connection from", s) opened <- true } kp1 := config.NewKeyPair(Suite) entity1 := NewServerIdentity(kp1.Public, "localhost:2000") kp2 := config.NewKeyPair(Suite) entity2 := NewServerIdentity(kp2.Public, "localhost:2001") host1 := NewSecureTCPHost(kp1.Secret, entity1) host2 := NewSecureTCPHost(kp1.Secret, entity2) done := make(chan bool) go func() { err := host1.Listen(fn) if err != nil { t.Fatal("Couldn't listen:", err) } done <- true }() conn, err := host2.Open(entity1) if err != nil { t.Fatal("Couldn't connect to host1:", err) } if !conn.ServerIdentity().Public.Equal(kp1.Public) { t.Fatal("Connection-id is not from host1") } if !<-opened { t.Fatal("Lazy programmers - no select") } log.Lvl4("Closing connections") if err := host1.Close(); err != nil { t.Fatal("Couldn't close host", host1) } if err := host2.Close(); err != nil { t.Fatal("Couldn't close host", host2) } <-done }
// Test when a peer receives a New Roster, it can create the trees that are // waiting on this specific entitiy list, to be constructed. func TestPeerPendingTreeMarshal(t *testing.T) { defer log.AfterTest(t) local := sda.NewLocalTest() hosts, el, tree := local.GenTree(2, false, false, false) defer local.CloseAll() h1 := hosts[0] // Add the marshalled version of the tree local.AddPendingTreeMarshal(h1, tree.MakeTreeMarshal()) if _, ok := h1.GetTree(tree.ID); ok { t.Fatal("host 1 should not have the tree definition yet.") } // Now make it check local.CheckPendingTreeMarshal(h1, el) if _, ok := h1.GetTree(tree.ID); !ok { t.Fatal("Host 1 should have the tree definition now.") } }
func TestRegister(t *testing.T) { defer log.AfterTest(t) if TypeFromData(&TestRegisterS{}) != ErrorType { t.Fatal("TestRegister should not yet be there") } trType := RegisterMessageType(&TestRegisterS{}) if uuid.Equal(uuid.UUID(trType), uuid.Nil) { t.Fatal("Couldn't register TestRegister-struct") } if TypeFromData(&TestRegisterS{}) != trType { t.Fatal("TestRegister is different now") } if TypeFromData(TestRegisterS{}) != trType { t.Fatal("TestRegister is different now") } }