go-nostr/subscription_test.go

103 lines
2.2 KiB
Go
Raw Normal View History

package nostr
import (
"context"
"fmt"
"sync/atomic"
"testing"
"time"
)
2023-08-06 20:03:05 -03:00
const RELAY = "wss://nostr.mom"
2023-06-24 21:02:12 -03:00
// test if we can fetch a couple of random events
func TestSubscribe(t *testing.T) {
2023-06-24 21:02:12 -03:00
rl := mustRelayConnect(RELAY)
2023-04-11 07:10:05 -03:00
defer rl.Close()
2023-09-06 21:00:05 -03:00
sub, err := rl.Subscribe(context.Background(), Filters{{Kinds: []int{KindTextNote}, Limit: 2}})
if err != nil {
t.Errorf("subscription failed: %v", err)
return
}
timeout := time.After(5 * time.Second)
2023-06-24 21:02:12 -03:00
n := 0
for {
select {
case event := <-sub.Events:
if event == nil {
t.Errorf("event is nil: %v", event)
}
2023-06-24 21:02:12 -03:00
n++
case <-sub.EndOfStoredEvents:
goto end
case <-rl.Context().Done():
t.Errorf("connection closed: %v", rl.Context().Err())
goto end
case <-timeout:
t.Errorf("timeout")
goto end
}
}
end:
2023-06-24 21:02:12 -03:00
if n != 2 {
t.Errorf("expected 2 events, got %d", n)
}
}
// test if we can do multiple nested subscriptions
func TestNestedSubscriptions(t *testing.T) {
rl := mustRelayConnect(RELAY)
defer rl.Close()
n := atomic.Uint32{}
// fetch 2 replies to a note
2023-09-06 21:00:05 -03:00
sub, err := rl.Subscribe(context.Background(), Filters{{Kinds: []int{KindTextNote}, Tags: TagMap{"e": []string{"0e34a74f8547e3b95d52a2543719b109fd0312aba144e2ef95cba043f42fe8c5"}}, Limit: 3}})
2023-06-24 21:02:12 -03:00
if err != nil {
t.Errorf("subscription 1 failed: %v", err)
return
}
for {
select {
case event := <-sub.Events:
// now fetch author of this
2023-09-06 21:00:05 -03:00
sub, err := rl.Subscribe(context.Background(), Filters{{Kinds: []int{KindSetMetadata}, Authors: []string{event.PubKey}, Limit: 1}})
2023-06-24 21:02:12 -03:00
if err != nil {
t.Errorf("subscription 2 failed: %v", err)
return
}
for {
select {
case <-sub.Events:
// do another subscription here in "sync" mode, just so we're sure things are not blocking
rl.QuerySync(context.Background(), Filter{Limit: 1})
2023-06-24 21:02:12 -03:00
n.Add(1)
if n.Load() == 3 {
// if we get here it means the test passed
return
2023-06-24 21:02:12 -03:00
}
case <-sub.Context.Done():
goto end
case <-sub.EndOfStoredEvents:
sub.Unsub()
2023-06-24 21:02:12 -03:00
}
}
end:
fmt.Println("")
case <-sub.EndOfStoredEvents:
sub.Unsub()
return
case <-sub.Context.Done():
2023-06-24 21:02:12 -03:00
t.Errorf("connection closed: %v", rl.Context().Err())
return
2023-06-24 21:02:12 -03:00
}
}
}