github.com/theQRL/go-zond@v0.1.1/p2p/simulations/http_test.go (about) 1 // Copyright 2017 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser 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 // The go-ethereum library 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 Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 package simulations 18 19 import ( 20 "context" 21 "flag" 22 "fmt" 23 "math/rand" 24 "net/http/httptest" 25 "os" 26 "reflect" 27 "sync" 28 "sync/atomic" 29 "testing" 30 "time" 31 32 "github.com/mattn/go-colorable" 33 "github.com/theQRL/go-zond/event" 34 "github.com/theQRL/go-zond/log" 35 "github.com/theQRL/go-zond/node" 36 "github.com/theQRL/go-zond/p2p" 37 "github.com/theQRL/go-zond/p2p/enode" 38 "github.com/theQRL/go-zond/p2p/simulations/adapters" 39 "github.com/theQRL/go-zond/rpc" 40 ) 41 42 func TestMain(m *testing.M) { 43 loglevel := flag.Int("loglevel", 2, "verbosity of logs") 44 45 flag.Parse() 46 log.PrintOrigins(true) 47 log.Root().SetHandler(log.LvlFilterHandler(log.Lvl(*loglevel), log.StreamHandler(colorable.NewColorableStderr(), log.TerminalFormat(true)))) 48 os.Exit(m.Run()) 49 } 50 51 // testService implements the node.Service interface and provides protocols 52 // and APIs which are useful for testing nodes in a simulation network 53 type testService struct { 54 id enode.ID 55 56 // peerCount is incremented once a peer handshake has been performed 57 peerCount int64 58 59 peers map[enode.ID]*testPeer 60 peersMtx sync.Mutex 61 62 // state stores []byte which is used to test creating and loading 63 // snapshots 64 state atomic.Value 65 } 66 67 func newTestService(ctx *adapters.ServiceContext, stack *node.Node) (node.Lifecycle, error) { 68 svc := &testService{ 69 id: ctx.Config.ID, 70 peers: make(map[enode.ID]*testPeer), 71 } 72 svc.state.Store(ctx.Snapshot) 73 74 stack.RegisterProtocols(svc.Protocols()) 75 stack.RegisterAPIs(svc.APIs()) 76 return svc, nil 77 } 78 79 type testPeer struct { 80 testReady chan struct{} 81 dumReady chan struct{} 82 } 83 84 func (t *testService) peer(id enode.ID) *testPeer { 85 t.peersMtx.Lock() 86 defer t.peersMtx.Unlock() 87 if peer, ok := t.peers[id]; ok { 88 return peer 89 } 90 peer := &testPeer{ 91 testReady: make(chan struct{}), 92 dumReady: make(chan struct{}), 93 } 94 t.peers[id] = peer 95 return peer 96 } 97 98 func (t *testService) Protocols() []p2p.Protocol { 99 return []p2p.Protocol{ 100 { 101 Name: "test", 102 Version: 1, 103 Length: 3, 104 Run: t.RunTest, 105 }, 106 { 107 Name: "dum", 108 Version: 1, 109 Length: 1, 110 Run: t.RunDum, 111 }, 112 { 113 Name: "prb", 114 Version: 1, 115 Length: 1, 116 Run: t.RunPrb, 117 }, 118 } 119 } 120 121 func (t *testService) APIs() []rpc.API { 122 return []rpc.API{{ 123 Namespace: "test", 124 Version: "1.0", 125 Service: &TestAPI{ 126 state: &t.state, 127 peerCount: &t.peerCount, 128 }, 129 }} 130 } 131 132 func (t *testService) Start() error { 133 return nil 134 } 135 136 func (t *testService) Stop() error { 137 return nil 138 } 139 140 // handshake performs a peer handshake by sending and expecting an empty 141 // message with the given code 142 func (t *testService) handshake(rw p2p.MsgReadWriter, code uint64) error { 143 errc := make(chan error, 2) 144 go func() { errc <- p2p.SendItems(rw, code) }() 145 go func() { errc <- p2p.ExpectMsg(rw, code, struct{}{}) }() 146 for i := 0; i < 2; i++ { 147 if err := <-errc; err != nil { 148 return err 149 } 150 } 151 return nil 152 } 153 154 func (t *testService) RunTest(p *p2p.Peer, rw p2p.MsgReadWriter) error { 155 peer := t.peer(p.ID()) 156 157 // perform three handshakes with three different message codes, 158 // used to test message sending and filtering 159 if err := t.handshake(rw, 2); err != nil { 160 return err 161 } 162 if err := t.handshake(rw, 1); err != nil { 163 return err 164 } 165 if err := t.handshake(rw, 0); err != nil { 166 return err 167 } 168 169 // close the testReady channel so that other protocols can run 170 close(peer.testReady) 171 172 // track the peer 173 atomic.AddInt64(&t.peerCount, 1) 174 defer atomic.AddInt64(&t.peerCount, -1) 175 176 // block until the peer is dropped 177 for { 178 _, err := rw.ReadMsg() 179 if err != nil { 180 return err 181 } 182 } 183 } 184 185 func (t *testService) RunDum(p *p2p.Peer, rw p2p.MsgReadWriter) error { 186 peer := t.peer(p.ID()) 187 188 // wait for the test protocol to perform its handshake 189 <-peer.testReady 190 191 // perform a handshake 192 if err := t.handshake(rw, 0); err != nil { 193 return err 194 } 195 196 // close the dumReady channel so that other protocols can run 197 close(peer.dumReady) 198 199 // block until the peer is dropped 200 for { 201 _, err := rw.ReadMsg() 202 if err != nil { 203 return err 204 } 205 } 206 } 207 func (t *testService) RunPrb(p *p2p.Peer, rw p2p.MsgReadWriter) error { 208 peer := t.peer(p.ID()) 209 210 // wait for the dum protocol to perform its handshake 211 <-peer.dumReady 212 213 // perform a handshake 214 if err := t.handshake(rw, 0); err != nil { 215 return err 216 } 217 218 // block until the peer is dropped 219 for { 220 _, err := rw.ReadMsg() 221 if err != nil { 222 return err 223 } 224 } 225 } 226 227 func (t *testService) Snapshot() ([]byte, error) { 228 return t.state.Load().([]byte), nil 229 } 230 231 // TestAPI provides a test API to: 232 // * get the peer count 233 // * get and set an arbitrary state byte slice 234 // * get and increment a counter 235 // * subscribe to counter increment events 236 type TestAPI struct { 237 state *atomic.Value 238 peerCount *int64 239 counter int64 240 feed event.Feed 241 } 242 243 func (t *TestAPI) PeerCount() int64 { 244 return atomic.LoadInt64(t.peerCount) 245 } 246 247 func (t *TestAPI) Get() int64 { 248 return atomic.LoadInt64(&t.counter) 249 } 250 251 func (t *TestAPI) Add(delta int64) { 252 atomic.AddInt64(&t.counter, delta) 253 t.feed.Send(delta) 254 } 255 256 func (t *TestAPI) GetState() []byte { 257 return t.state.Load().([]byte) 258 } 259 260 func (t *TestAPI) SetState(state []byte) { 261 t.state.Store(state) 262 } 263 264 func (t *TestAPI) Events(ctx context.Context) (*rpc.Subscription, error) { 265 notifier, supported := rpc.NotifierFromContext(ctx) 266 if !supported { 267 return nil, rpc.ErrNotificationsUnsupported 268 } 269 270 rpcSub := notifier.CreateSubscription() 271 272 go func() { 273 events := make(chan int64) 274 sub := t.feed.Subscribe(events) 275 defer sub.Unsubscribe() 276 277 for { 278 select { 279 case event := <-events: 280 notifier.Notify(rpcSub.ID, event) 281 case <-sub.Err(): 282 return 283 case <-rpcSub.Err(): 284 return 285 case <-notifier.Closed(): 286 return 287 } 288 } 289 }() 290 291 return rpcSub, nil 292 } 293 294 var testServices = adapters.LifecycleConstructors{ 295 "test": newTestService, 296 } 297 298 func testHTTPServer(t *testing.T) (*Network, *httptest.Server) { 299 t.Helper() 300 adapter := adapters.NewSimAdapter(testServices) 301 network := NewNetwork(adapter, &NetworkConfig{ 302 DefaultService: "test", 303 }) 304 return network, httptest.NewServer(NewServer(network)) 305 } 306 307 // TestHTTPNetwork tests interacting with a simulation network using the HTTP 308 // API 309 func TestHTTPNetwork(t *testing.T) { 310 // start the server 311 network, s := testHTTPServer(t) 312 defer s.Close() 313 314 // subscribe to events so we can check them later 315 client := NewClient(s.URL) 316 events := make(chan *Event, 100) 317 var opts SubscribeOpts 318 sub, err := client.SubscribeNetwork(events, opts) 319 if err != nil { 320 t.Fatalf("error subscribing to network events: %s", err) 321 } 322 defer sub.Unsubscribe() 323 324 // check we can retrieve details about the network 325 gotNetwork, err := client.GetNetwork() 326 if err != nil { 327 t.Fatalf("error getting network: %s", err) 328 } 329 if gotNetwork.ID != network.ID { 330 t.Fatalf("expected network to have ID %q, got %q", network.ID, gotNetwork.ID) 331 } 332 333 // start a simulation network 334 nodeIDs := startTestNetwork(t, client) 335 336 // check we got all the events 337 x := &expectEvents{t, events, sub} 338 x.expect( 339 x.nodeEvent(nodeIDs[0], false), 340 x.nodeEvent(nodeIDs[1], false), 341 x.nodeEvent(nodeIDs[0], true), 342 x.nodeEvent(nodeIDs[1], true), 343 x.connEvent(nodeIDs[0], nodeIDs[1], false), 344 x.connEvent(nodeIDs[0], nodeIDs[1], true), 345 ) 346 347 // reconnect the stream and check we get the current nodes and conns 348 events = make(chan *Event, 100) 349 opts.Current = true 350 sub, err = client.SubscribeNetwork(events, opts) 351 if err != nil { 352 t.Fatalf("error subscribing to network events: %s", err) 353 } 354 defer sub.Unsubscribe() 355 x = &expectEvents{t, events, sub} 356 x.expect( 357 x.nodeEvent(nodeIDs[0], true), 358 x.nodeEvent(nodeIDs[1], true), 359 x.connEvent(nodeIDs[0], nodeIDs[1], true), 360 ) 361 } 362 363 func startTestNetwork(t *testing.T, client *Client) []string { 364 // create two nodes 365 nodeCount := 2 366 nodeIDs := make([]string, nodeCount) 367 for i := 0; i < nodeCount; i++ { 368 config := adapters.RandomNodeConfig() 369 node, err := client.CreateNode(config) 370 if err != nil { 371 t.Fatalf("error creating node: %s", err) 372 } 373 nodeIDs[i] = node.ID 374 } 375 376 // check both nodes exist 377 nodes, err := client.GetNodes() 378 if err != nil { 379 t.Fatalf("error getting nodes: %s", err) 380 } 381 if len(nodes) != nodeCount { 382 t.Fatalf("expected %d nodes, got %d", nodeCount, len(nodes)) 383 } 384 for i, nodeID := range nodeIDs { 385 if nodes[i].ID != nodeID { 386 t.Fatalf("expected node %d to have ID %q, got %q", i, nodeID, nodes[i].ID) 387 } 388 node, err := client.GetNode(nodeID) 389 if err != nil { 390 t.Fatalf("error getting node %d: %s", i, err) 391 } 392 if node.ID != nodeID { 393 t.Fatalf("expected node %d to have ID %q, got %q", i, nodeID, node.ID) 394 } 395 } 396 397 // start both nodes 398 for _, nodeID := range nodeIDs { 399 if err := client.StartNode(nodeID); err != nil { 400 t.Fatalf("error starting node %q: %s", nodeID, err) 401 } 402 } 403 404 // connect the nodes 405 for i := 0; i < nodeCount-1; i++ { 406 peerId := i + 1 407 if i == nodeCount-1 { 408 peerId = 0 409 } 410 if err := client.ConnectNode(nodeIDs[i], nodeIDs[peerId]); err != nil { 411 t.Fatalf("error connecting nodes: %s", err) 412 } 413 } 414 415 return nodeIDs 416 } 417 418 type expectEvents struct { 419 *testing.T 420 421 events chan *Event 422 sub event.Subscription 423 } 424 425 func (t *expectEvents) nodeEvent(id string, up bool) *Event { 426 config := &adapters.NodeConfig{ID: enode.HexID(id)} 427 return &Event{Type: EventTypeNode, Node: newNode(nil, config, up)} 428 } 429 430 func (t *expectEvents) connEvent(one, other string, up bool) *Event { 431 return &Event{ 432 Type: EventTypeConn, 433 Conn: &Conn{ 434 One: enode.HexID(one), 435 Other: enode.HexID(other), 436 Up: up, 437 }, 438 } 439 } 440 441 func (t *expectEvents) expectMsgs(expected map[MsgFilter]int) { 442 actual := make(map[MsgFilter]int) 443 timeout := time.After(10 * time.Second) 444 loop: 445 for { 446 select { 447 case event := <-t.events: 448 t.Logf("received %s event: %v", event.Type, event) 449 450 if event.Type != EventTypeMsg || event.Msg.Received { 451 continue loop 452 } 453 if event.Msg == nil { 454 t.Fatal("expected event.Msg to be set") 455 } 456 filter := MsgFilter{ 457 Proto: event.Msg.Protocol, 458 Code: int64(event.Msg.Code), 459 } 460 actual[filter]++ 461 if actual[filter] > expected[filter] { 462 t.Fatalf("received too many msgs for filter: %v", filter) 463 } 464 if reflect.DeepEqual(actual, expected) { 465 return 466 } 467 468 case err := <-t.sub.Err(): 469 t.Fatalf("network stream closed unexpectedly: %s", err) 470 471 case <-timeout: 472 t.Fatal("timed out waiting for expected events") 473 } 474 } 475 } 476 477 func (t *expectEvents) expect(events ...*Event) { 478 t.Helper() 479 timeout := time.After(10 * time.Second) 480 i := 0 481 for { 482 select { 483 case event := <-t.events: 484 t.Logf("received %s event: %v", event.Type, event) 485 486 expected := events[i] 487 if event.Type != expected.Type { 488 t.Fatalf("expected event %d to have type %q, got %q", i, expected.Type, event.Type) 489 } 490 491 switch expected.Type { 492 case EventTypeNode: 493 if event.Node == nil { 494 t.Fatal("expected event.Node to be set") 495 } 496 if event.Node.ID() != expected.Node.ID() { 497 t.Fatalf("expected node event %d to have id %q, got %q", i, expected.Node.ID().TerminalString(), event.Node.ID().TerminalString()) 498 } 499 if event.Node.Up() != expected.Node.Up() { 500 t.Fatalf("expected node event %d to have up=%t, got up=%t", i, expected.Node.Up(), event.Node.Up()) 501 } 502 503 case EventTypeConn: 504 if event.Conn == nil { 505 t.Fatal("expected event.Conn to be set") 506 } 507 if event.Conn.One != expected.Conn.One { 508 t.Fatalf("expected conn event %d to have one=%q, got one=%q", i, expected.Conn.One.TerminalString(), event.Conn.One.TerminalString()) 509 } 510 if event.Conn.Other != expected.Conn.Other { 511 t.Fatalf("expected conn event %d to have other=%q, got other=%q", i, expected.Conn.Other.TerminalString(), event.Conn.Other.TerminalString()) 512 } 513 if event.Conn.Up != expected.Conn.Up { 514 t.Fatalf("expected conn event %d to have up=%t, got up=%t", i, expected.Conn.Up, event.Conn.Up) 515 } 516 } 517 518 i++ 519 if i == len(events) { 520 return 521 } 522 523 case err := <-t.sub.Err(): 524 t.Fatalf("network stream closed unexpectedly: %s", err) 525 526 case <-timeout: 527 t.Fatal("timed out waiting for expected events") 528 } 529 } 530 } 531 532 // TestHTTPNodeRPC tests calling RPC methods on nodes via the HTTP API 533 func TestHTTPNodeRPC(t *testing.T) { 534 // start the server 535 _, s := testHTTPServer(t) 536 defer s.Close() 537 538 // start a node in the network 539 client := NewClient(s.URL) 540 541 config := adapters.RandomNodeConfig() 542 node, err := client.CreateNode(config) 543 if err != nil { 544 t.Fatalf("error creating node: %s", err) 545 } 546 if err := client.StartNode(node.ID); err != nil { 547 t.Fatalf("error starting node: %s", err) 548 } 549 550 // create two RPC clients 551 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) 552 defer cancel() 553 rpcClient1, err := client.RPCClient(ctx, node.ID) 554 if err != nil { 555 t.Fatalf("error getting node RPC client: %s", err) 556 } 557 rpcClient2, err := client.RPCClient(ctx, node.ID) 558 if err != nil { 559 t.Fatalf("error getting node RPC client: %s", err) 560 } 561 562 // subscribe to events using client 1 563 events := make(chan int64, 1) 564 sub, err := rpcClient1.Subscribe(ctx, "test", events, "events") 565 if err != nil { 566 t.Fatalf("error subscribing to events: %s", err) 567 } 568 defer sub.Unsubscribe() 569 570 // call some RPC methods using client 2 571 if err := rpcClient2.CallContext(ctx, nil, "test_add", 10); err != nil { 572 t.Fatalf("error calling RPC method: %s", err) 573 } 574 var result int64 575 if err := rpcClient2.CallContext(ctx, &result, "test_get"); err != nil { 576 t.Fatalf("error calling RPC method: %s", err) 577 } 578 if result != 10 { 579 t.Fatalf("expected result to be 10, got %d", result) 580 } 581 582 // check we got an event from client 1 583 select { 584 case event := <-events: 585 if event != 10 { 586 t.Fatalf("expected event to be 10, got %d", event) 587 } 588 case <-ctx.Done(): 589 t.Fatal(ctx.Err()) 590 } 591 } 592 593 // TestHTTPSnapshot tests creating and loading network snapshots 594 func TestHTTPSnapshot(t *testing.T) { 595 // start the server 596 network, s := testHTTPServer(t) 597 defer s.Close() 598 599 var eventsDone = make(chan struct{}, 1) 600 count := 1 601 eventsDoneChan := make(chan *Event) 602 eventSub := network.Events().Subscribe(eventsDoneChan) 603 go func() { 604 defer eventSub.Unsubscribe() 605 for event := range eventsDoneChan { 606 if event.Type == EventTypeConn && !event.Control { 607 count-- 608 if count == 0 { 609 eventsDone <- struct{}{} 610 return 611 } 612 } 613 } 614 }() 615 616 // create a two-node network 617 client := NewClient(s.URL) 618 nodeCount := 2 619 nodes := make([]*p2p.NodeInfo, nodeCount) 620 for i := 0; i < nodeCount; i++ { 621 config := adapters.RandomNodeConfig() 622 node, err := client.CreateNode(config) 623 if err != nil { 624 t.Fatalf("error creating node: %s", err) 625 } 626 if err := client.StartNode(node.ID); err != nil { 627 t.Fatalf("error starting node: %s", err) 628 } 629 nodes[i] = node 630 } 631 if err := client.ConnectNode(nodes[0].ID, nodes[1].ID); err != nil { 632 t.Fatalf("error connecting nodes: %s", err) 633 } 634 635 // store some state in the test services 636 states := make([]string, nodeCount) 637 for i, node := range nodes { 638 rpc, err := client.RPCClient(context.Background(), node.ID) 639 if err != nil { 640 t.Fatalf("error getting RPC client: %s", err) 641 } 642 defer rpc.Close() 643 state := fmt.Sprintf("%x", rand.Int()) 644 if err := rpc.Call(nil, "test_setState", []byte(state)); err != nil { 645 t.Fatalf("error setting service state: %s", err) 646 } 647 states[i] = state 648 } 649 <-eventsDone 650 // create a snapshot 651 snap, err := client.CreateSnapshot() 652 if err != nil { 653 t.Fatalf("error creating snapshot: %s", err) 654 } 655 for i, state := range states { 656 gotState := snap.Nodes[i].Snapshots["test"] 657 if string(gotState) != state { 658 t.Fatalf("expected snapshot state %q, got %q", state, gotState) 659 } 660 } 661 662 // create another network 663 network2, s := testHTTPServer(t) 664 defer s.Close() 665 client = NewClient(s.URL) 666 count = 1 667 eventSub = network2.Events().Subscribe(eventsDoneChan) 668 go func() { 669 defer eventSub.Unsubscribe() 670 for event := range eventsDoneChan { 671 if event.Type == EventTypeConn && !event.Control { 672 count-- 673 if count == 0 { 674 eventsDone <- struct{}{} 675 return 676 } 677 } 678 } 679 }() 680 681 // subscribe to events so we can check them later 682 events := make(chan *Event, 100) 683 var opts SubscribeOpts 684 sub, err := client.SubscribeNetwork(events, opts) 685 if err != nil { 686 t.Fatalf("error subscribing to network events: %s", err) 687 } 688 defer sub.Unsubscribe() 689 690 // load the snapshot 691 if err := client.LoadSnapshot(snap); err != nil { 692 t.Fatalf("error loading snapshot: %s", err) 693 } 694 <-eventsDone 695 696 // check the nodes and connection exists 697 net, err := client.GetNetwork() 698 if err != nil { 699 t.Fatalf("error getting network: %s", err) 700 } 701 if len(net.Nodes) != nodeCount { 702 t.Fatalf("expected network to have %d nodes, got %d", nodeCount, len(net.Nodes)) 703 } 704 for i, node := range nodes { 705 id := net.Nodes[i].ID().String() 706 if id != node.ID { 707 t.Fatalf("expected node %d to have ID %s, got %s", i, node.ID, id) 708 } 709 } 710 if len(net.Conns) != 1 { 711 t.Fatalf("expected network to have 1 connection, got %d", len(net.Conns)) 712 } 713 conn := net.Conns[0] 714 if conn.One.String() != nodes[0].ID { 715 t.Fatalf("expected connection to have one=%q, got one=%q", nodes[0].ID, conn.One) 716 } 717 if conn.Other.String() != nodes[1].ID { 718 t.Fatalf("expected connection to have other=%q, got other=%q", nodes[1].ID, conn.Other) 719 } 720 if !conn.Up { 721 t.Fatal("should be up") 722 } 723 724 // check the node states were restored 725 for i, node := range nodes { 726 rpc, err := client.RPCClient(context.Background(), node.ID) 727 if err != nil { 728 t.Fatalf("error getting RPC client: %s", err) 729 } 730 defer rpc.Close() 731 var state []byte 732 if err := rpc.Call(&state, "test_getState"); err != nil { 733 t.Fatalf("error getting service state: %s", err) 734 } 735 if string(state) != states[i] { 736 t.Fatalf("expected snapshot state %q, got %q", states[i], state) 737 } 738 } 739 740 // check we got all the events 741 x := &expectEvents{t, events, sub} 742 x.expect( 743 x.nodeEvent(nodes[0].ID, false), 744 x.nodeEvent(nodes[0].ID, true), 745 x.nodeEvent(nodes[1].ID, false), 746 x.nodeEvent(nodes[1].ID, true), 747 x.connEvent(nodes[0].ID, nodes[1].ID, false), 748 x.connEvent(nodes[0].ID, nodes[1].ID, true), 749 ) 750 } 751 752 // TestMsgFilterPassMultiple tests streaming message events using a filter 753 // with multiple protocols 754 func TestMsgFilterPassMultiple(t *testing.T) { 755 // start the server 756 _, s := testHTTPServer(t) 757 defer s.Close() 758 759 // subscribe to events with a message filter 760 client := NewClient(s.URL) 761 events := make(chan *Event, 10) 762 opts := SubscribeOpts{ 763 Filter: "prb:0-test:0", 764 } 765 sub, err := client.SubscribeNetwork(events, opts) 766 if err != nil { 767 t.Fatalf("error subscribing to network events: %s", err) 768 } 769 defer sub.Unsubscribe() 770 771 // start a simulation network 772 startTestNetwork(t, client) 773 774 // check we got the expected events 775 x := &expectEvents{t, events, sub} 776 x.expectMsgs(map[MsgFilter]int{ 777 {"test", 0}: 2, 778 {"prb", 0}: 2, 779 }) 780 } 781 782 // TestMsgFilterPassWildcard tests streaming message events using a filter 783 // with a code wildcard 784 func TestMsgFilterPassWildcard(t *testing.T) { 785 // start the server 786 _, s := testHTTPServer(t) 787 defer s.Close() 788 789 // subscribe to events with a message filter 790 client := NewClient(s.URL) 791 events := make(chan *Event, 10) 792 opts := SubscribeOpts{ 793 Filter: "prb:0,2-test:*", 794 } 795 sub, err := client.SubscribeNetwork(events, opts) 796 if err != nil { 797 t.Fatalf("error subscribing to network events: %s", err) 798 } 799 defer sub.Unsubscribe() 800 801 // start a simulation network 802 startTestNetwork(t, client) 803 804 // check we got the expected events 805 x := &expectEvents{t, events, sub} 806 x.expectMsgs(map[MsgFilter]int{ 807 {"test", 2}: 2, 808 {"test", 1}: 2, 809 {"test", 0}: 2, 810 {"prb", 0}: 2, 811 }) 812 } 813 814 // TestMsgFilterPassSingle tests streaming message events using a filter 815 // with a single protocol and code 816 func TestMsgFilterPassSingle(t *testing.T) { 817 // start the server 818 _, s := testHTTPServer(t) 819 defer s.Close() 820 821 // subscribe to events with a message filter 822 client := NewClient(s.URL) 823 events := make(chan *Event, 10) 824 opts := SubscribeOpts{ 825 Filter: "dum:0", 826 } 827 sub, err := client.SubscribeNetwork(events, opts) 828 if err != nil { 829 t.Fatalf("error subscribing to network events: %s", err) 830 } 831 defer sub.Unsubscribe() 832 833 // start a simulation network 834 startTestNetwork(t, client) 835 836 // check we got the expected events 837 x := &expectEvents{t, events, sub} 838 x.expectMsgs(map[MsgFilter]int{ 839 {"dum", 0}: 2, 840 }) 841 } 842 843 // TestMsgFilterPassSingle tests streaming message events using an invalid 844 // filter 845 func TestMsgFilterFailBadParams(t *testing.T) { 846 // start the server 847 _, s := testHTTPServer(t) 848 defer s.Close() 849 850 client := NewClient(s.URL) 851 events := make(chan *Event, 10) 852 opts := SubscribeOpts{ 853 Filter: "foo:", 854 } 855 _, err := client.SubscribeNetwork(events, opts) 856 if err == nil { 857 t.Fatalf("expected event subscription to fail but succeeded!") 858 } 859 860 opts.Filter = "bzz:aa" 861 _, err = client.SubscribeNetwork(events, opts) 862 if err == nil { 863 t.Fatalf("expected event subscription to fail but succeeded!") 864 } 865 866 opts.Filter = "invalid" 867 _, err = client.SubscribeNetwork(events, opts) 868 if err == nil { 869 t.Fatalf("expected event subscription to fail but succeeded!") 870 } 871 }