fetch-event-by-serial_test.go raw
1 package database
2
3 import (
4 "testing"
5
6 "next.orly.dev/pkg/nostr/encoders/filter"
7 "next.orly.dev/pkg/nostr/encoders/tag"
8 "next.orly.dev/pkg/database/indexes/types"
9 "next.orly.dev/pkg/utils"
10 )
11
12 func TestFetchEventBySerial(t *testing.T) {
13 // Use shared database (skips in short mode)
14 db, ctx := GetSharedDB(t)
15 savedEvents := GetSharedEvents(t)
16
17 if len(savedEvents) < 4 {
18 t.Fatalf("Need at least 4 saved events, got %d", len(savedEvents))
19 }
20 testEvent := savedEvents[3]
21
22 // Use QueryForIds to get the serial for this event
23 sers, err := db.QueryForSerials(
24 ctx, &filter.F{
25 Ids: tag.NewFromBytesSlice(testEvent.ID),
26 },
27 )
28 if err != nil {
29 t.Fatalf("Failed to query for Ids: %v", err)
30 }
31
32 // Verify we got exactly one result
33 if len(sers) != 1 {
34 t.Fatalf("Expected 1 serial, got %d", len(sers))
35 }
36
37 // Fetch the event by serial
38 fetchedEvent, err := db.FetchEventBySerial(sers[0])
39 if err != nil {
40 t.Fatalf("Failed to fetch event by serial: %v", err)
41 }
42
43 // Verify the fetched event is not nil
44 if fetchedEvent == nil {
45 t.Fatal("Expected fetched event to be non-nil, but got nil")
46 }
47
48 // Verify the fetched event has the same ID as the original event
49 if !utils.FastEqual(fetchedEvent.ID, testEvent.ID) {
50 t.Fatalf(
51 "Fetched event ID doesn't match original event ID. Got %x, expected %x",
52 fetchedEvent.ID, testEvent.ID,
53 )
54 }
55
56 // Verify other event properties match
57 if fetchedEvent.Kind != testEvent.Kind {
58 t.Fatalf(
59 "Fetched event kind doesn't match. Got %d, expected %d",
60 fetchedEvent.Kind, testEvent.Kind,
61 )
62 }
63
64 if !utils.FastEqual(fetchedEvent.Pubkey, testEvent.Pubkey) {
65 t.Fatalf(
66 "Fetched event pubkey doesn't match. Got %x, expected %x",
67 fetchedEvent.Pubkey, testEvent.Pubkey,
68 )
69 }
70
71 if fetchedEvent.CreatedAt != testEvent.CreatedAt {
72 t.Fatalf(
73 "Fetched event created_at doesn't match. Got %d, expected %d",
74 fetchedEvent.CreatedAt, testEvent.CreatedAt,
75 )
76 }
77
78 // Test with a non-existent serial
79 nonExistentSerial := new(types.Uint40)
80 err = nonExistentSerial.Set(uint64(0xFFFFFFFFFF)) // Max value
81 if err != nil {
82 t.Fatalf("Failed to create non-existent serial: %v", err)
83 }
84
85 // This should return an error since the serial doesn't exist
86 fetchedEvent, err = db.FetchEventBySerial(nonExistentSerial)
87 if err == nil {
88 t.Fatal("Expected error for non-existent serial, but got nil")
89 }
90
91 // The fetched event should be nil
92 if fetchedEvent != nil {
93 t.Fatalf(
94 "Expected nil event for non-existent serial, but got: %v",
95 fetchedEvent,
96 )
97 }
98 }
99