|
| 1 | +package coreapi_test |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "github.com/ipfs/go-ipfs/core/coreapi/interface/options" |
| 6 | + "testing" |
| 7 | + "time" |
| 8 | +) |
| 9 | + |
| 10 | +func TestBasicPubSub(t *testing.T) { |
| 11 | + ctx, cancel := context.WithCancel(context.Background()) |
| 12 | + defer cancel() |
| 13 | + |
| 14 | + nds, apis, err := makeAPISwarm(ctx, true, 2) |
| 15 | + if err != nil { |
| 16 | + t.Fatal(err) |
| 17 | + } |
| 18 | + |
| 19 | + sub, err := apis[0].PubSub().Subscribe(ctx, "testch") |
| 20 | + if err != nil { |
| 21 | + t.Fatal(err) |
| 22 | + } |
| 23 | + |
| 24 | + go func() { |
| 25 | + tick := time.Tick(100 * time.Millisecond) |
| 26 | + |
| 27 | + for { |
| 28 | + err = apis[1].PubSub().Publish(ctx, "testch", []byte("hello world")) |
| 29 | + if err != nil { |
| 30 | + t.Fatal(err) |
| 31 | + } |
| 32 | + select { |
| 33 | + case <-tick: |
| 34 | + case <-ctx.Done(): |
| 35 | + return |
| 36 | + } |
| 37 | + } |
| 38 | + }() |
| 39 | + |
| 40 | + m, err := sub.Next(ctx) |
| 41 | + if err != nil { |
| 42 | + t.Fatal(err) |
| 43 | + } |
| 44 | + |
| 45 | + if string(m.Data()) != "hello world" { |
| 46 | + t.Errorf("got invalid data: %s", string(m.Data())) |
| 47 | + } |
| 48 | + |
| 49 | + if m.From() != nds[1].Identity { |
| 50 | + t.Errorf("m.From didn't match") |
| 51 | + } |
| 52 | + |
| 53 | + peers, err := apis[1].PubSub().Peers(ctx, options.PubSub.Topic("testch")) |
| 54 | + if err != nil { |
| 55 | + t.Fatal(err) |
| 56 | + } |
| 57 | + |
| 58 | + if len(peers) != 1 { |
| 59 | + t.Fatalf("got incorrect number of peers: %d", len(peers)) |
| 60 | + } |
| 61 | + |
| 62 | + if peers[0] != nds[0].Identity { |
| 63 | + t.Errorf("peer didn't match") |
| 64 | + } |
| 65 | + |
| 66 | + peers, err = apis[1].PubSub().Peers(ctx, options.PubSub.Topic("nottestch")) |
| 67 | + if err != nil { |
| 68 | + t.Fatal(err) |
| 69 | + } |
| 70 | + |
| 71 | + if len(peers) != 0 { |
| 72 | + t.Fatalf("got incorrect number of peers: %d", len(peers)) |
| 73 | + } |
| 74 | + |
| 75 | + topics, err := apis[0].PubSub().Ls(ctx) |
| 76 | + if err != nil { |
| 77 | + t.Fatal(err) |
| 78 | + } |
| 79 | + |
| 80 | + if len(topics) != 1 { |
| 81 | + t.Fatalf("got incorrect number of topics: %d", len(peers)) |
| 82 | + } |
| 83 | + |
| 84 | + if topics[0] != "testch" { |
| 85 | + t.Errorf("topic didn't match") |
| 86 | + } |
| 87 | + |
| 88 | + topics, err = apis[1].PubSub().Ls(ctx) |
| 89 | + if err != nil { |
| 90 | + t.Fatal(err) |
| 91 | + } |
| 92 | + |
| 93 | + if len(topics) != 0 { |
| 94 | + t.Fatalf("got incorrect number of topics: %d", len(peers)) |
| 95 | + } |
| 96 | +} |
0 commit comments