subscriptions_test.go raw
1 package database
2
3 import (
4 "testing"
5
6 "github.com/dgraph-io/badger/v4"
7 )
8
9 func TestSubscriptionLifecycle(t *testing.T) {
10 db, err := badger.Open(badger.DefaultOptions("").WithInMemory(true))
11 if err != nil {
12 t.Fatal(err)
13 }
14 defer db.Close()
15
16 d := &D{DB: db}
17 pubkey := []byte("test_pubkey_32_bytes_long_enough")
18
19 // First check should create trial
20 active, err := d.IsSubscriptionActive(pubkey)
21 if err != nil {
22 t.Fatal(err)
23 }
24 if !active {
25 t.Error("expected trial to be active")
26 }
27
28 // Verify trial was created
29 sub, err := d.GetSubscription(pubkey)
30 if err != nil {
31 t.Fatal(err)
32 }
33 if sub == nil {
34 t.Fatal("expected subscription to exist")
35 }
36 if sub.TrialEnd.IsZero() {
37 t.Error("expected trial end to be set")
38 }
39 if !sub.PaidUntil.IsZero() {
40 t.Error("expected paid until to be zero")
41 }
42
43 // Extend subscription
44 err = d.ExtendSubscription(pubkey, 30)
45 if err != nil {
46 t.Fatal(err)
47 }
48
49 // Check subscription is still active
50 active, err = d.IsSubscriptionActive(pubkey)
51 if err != nil {
52 t.Fatal(err)
53 }
54 if !active {
55 t.Error("expected subscription to be active after extension")
56 }
57
58 // Verify paid until was set
59 sub, err = d.GetSubscription(pubkey)
60 if err != nil {
61 t.Fatal(err)
62 }
63 if sub.PaidUntil.IsZero() {
64 t.Error("expected paid until to be set after extension")
65 }
66 }
67
68 func TestExtendSubscriptionEdgeCases(t *testing.T) {
69 db, err := badger.Open(badger.DefaultOptions("").WithInMemory(true))
70 if err != nil {
71 t.Fatal(err)
72 }
73 defer db.Close()
74
75 d := &D{DB: db}
76 pubkey := []byte("test_pubkey_32_bytes_long_enough")
77
78 // Test extending non-existent subscription
79 err = d.ExtendSubscription(pubkey, 30)
80 if err != nil {
81 t.Fatal(err)
82 }
83
84 sub, err := d.GetSubscription(pubkey)
85 if err != nil {
86 t.Fatal(err)
87 }
88 if sub.PaidUntil.IsZero() {
89 t.Error("expected paid until to be set")
90 }
91
92 // Test invalid days
93 err = d.ExtendSubscription(pubkey, 0)
94 if err == nil {
95 t.Error("expected error for 0 days")
96 }
97
98 err = d.ExtendSubscription(pubkey, -1)
99 if err == nil {
100 t.Error("expected error for negative days")
101 }
102 }
103
104 func TestGetNonExistentSubscription(t *testing.T) {
105 db, err := badger.Open(badger.DefaultOptions("").WithInMemory(true))
106 if err != nil {
107 t.Fatal(err)
108 }
109 defer db.Close()
110
111 d := &D{DB: db}
112 pubkey := []byte("non_existent_pubkey_32_bytes_long")
113
114 sub, err := d.GetSubscription(pubkey)
115 if err != nil {
116 t.Fatal(err)
117 }
118 if sub != nil {
119 t.Error("expected nil for non-existent subscription")
120 }
121 }
122