refactor these tests to ensure nested subscriptions are not blocking each other.

This commit is contained in:
fiatjaf
2023-06-25 00:17:57 -03:00
parent 54d3de4908
commit 3b44ab9381

View File

@@ -2,11 +2,13 @@ package nostr
import ( import (
"context" "context"
"fmt"
"sync/atomic"
"testing" "testing"
"time" "time"
) )
const RELAY = "wss://relay.damus.io" const RELAY = "wss://relay.nostr.band"
// test if we can fetch a couple of random events // test if we can fetch a couple of random events
func TestSubscribe(t *testing.T) { func TestSubscribe(t *testing.T) {
@@ -51,19 +53,19 @@ func TestNestedSubscriptions(t *testing.T) {
rl := mustRelayConnect(RELAY) rl := mustRelayConnect(RELAY)
defer rl.Close() defer rl.Close()
// fetch any note n := atomic.Uint32{}
sub, err := rl.Subscribe(context.Background(), Filters{{Kinds: []int{1}, Limit: 1}})
// fetch 2 replies to a note
sub, err := rl.Subscribe(context.Background(), Filters{{Kinds: []int{1}, Tags: TagMap{"e": []string{"0e34a74f8547e3b95d52a2543719b109fd0312aba144e2ef95cba043f42fe8c5"}}, Limit: 3}})
if err != nil { if err != nil {
t.Errorf("subscription 1 failed: %v", err) t.Errorf("subscription 1 failed: %v", err)
return return
} }
timeout := time.After(5 * time.Second)
for { for {
select { select {
case event := <-sub.Events: case event := <-sub.Events:
// now fetch author of this event // now fetch author of this
sub, err := rl.Subscribe(context.Background(), Filters{{Kinds: []int{0}, Authors: []string{event.PubKey}, Limit: 1}}) sub, err := rl.Subscribe(context.Background(), Filters{{Kinds: []int{0}, Authors: []string{event.PubKey}, Limit: 1}})
if err != nil { if err != nil {
t.Errorf("subscription 2 failed: %v", err) t.Errorf("subscription 2 failed: %v", err)
@@ -73,30 +75,28 @@ func TestNestedSubscriptions(t *testing.T) {
for { for {
select { select {
case <-sub.Events: case <-sub.Events:
// now mentions of this person // do another subscription here in "sync" mode, just so we're sure things are not blocking
sub, err := rl.Subscribe(context.Background(), Filters{{Kinds: []int{1}, Tags: TagMap{"p": []string{event.PubKey}}, Limit: 1}}) rl.QuerySync(context.Background(), Filter{Limit: 1})
if err != nil {
t.Errorf("subscription 3 failed: %v", err) n.Add(1)
if n.Load() == 3 {
// if we get here it means the test passed
return return
} }
case <-sub.Context.Done():
for { goto end
select { case <-sub.EndOfStoredEvents:
case <-sub.Events: sub.Unsub()
// if we get here safely we won
return
case <-timeout:
t.Errorf("timeout 3")
}
}
case <-timeout:
t.Errorf("timeout 2")
} }
} }
case <-rl.Context().Done(): end:
fmt.Println("")
case <-sub.EndOfStoredEvents:
sub.Unsub()
return
case <-sub.Context.Done():
t.Errorf("connection closed: %v", rl.Context().Err()) t.Errorf("connection closed: %v", rl.Context().Err())
case <-timeout: return
t.Errorf("timeout 1")
} }
} }
} }