Repository navigation
Expand file tree
/
Copy pathinspect_test.go
More file actions
249 lines (221 loc) · 8.41 KB
/
Copy pathinspect_test.go
File metadata and controls
249 lines (221 loc) · 8.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
package ledger_test
import (
"context"
"errors"
"fmt"
"io"
"testing"
"time"
ledger "github.com/xraph/ledger"
"github.com/xraph/ledger/id"
"github.com/xraph/ledger/meter"
"github.com/xraph/ledger/plan"
"github.com/xraph/ledger/plugin"
"github.com/xraph/ledger/store/memory"
"github.com/xraph/ledger/subscription"
"github.com/xraph/ledger/types"
)
type quotaSpy struct{ exceeded, checked int }
func (q *quotaSpy) Name() string { return "quota-spy" }
func (q *quotaSpy) OnQuotaExceeded(_ context.Context, _, _ string, _, _ int64) error {
q.exceeded++
return nil
}
func (q *quotaSpy) OnEntitlementChecked(_ context.Context, _ interface{}) error {
q.checked++
return nil
}
var (
_ plugin.OnQuotaExceeded = (*quotaSpy)(nil)
_ plugin.OnEntitlementChecked = (*quotaSpy)(nil)
)
func TestInspectEntitlementHasNoSideEffects(t *testing.T) {
ctx := context.Background()
s := memory.New()
spy := "aSpy{}
l := ledger.New(s, ledger.WithPlugin(spy))
p := activePlan(t, l, "ent", "app_1", 0)
sub := &subscription.Subscription{TenantID: "t1", PlanID: p.ID, AppID: "app_1"}
if err := l.CreateSubscription(ctx, sub); err != nil {
t.Fatalf("CreateSubscription: %v", err)
}
if err := s.IngestBatch(ctx, []*meter.UsageEvent{{ID: id.NewUsageEventID(), TenantID: "t1", AppID: "app_1", FeatureKey: "api_calls", Quantity: 1500, Timestamp: time.Now().UTC()}}); err != nil {
t.Fatalf("IngestBatch: %v", err)
}
got, err := l.InspectEntitlement(ctx, "t1", "app_1", "api_calls")
if err != nil {
t.Fatalf("InspectEntitlement: %v", err)
}
if got.Allowed || got.Used != 1500 || got.Limit != 1000 || got.Reason != "quota exceeded" {
t.Errorf("got %+v, want not allowed, used 1500 of 1000, quota exceeded", got)
}
if spy.exceeded != 0 {
t.Errorf("OnQuotaExceeded fired %d times; inspection must not fire plugin events", spy.exceeded)
}
if _, err := s.GetCached(ctx, "t1", "app_1", "api_calls"); err == nil {
t.Error("inspection must not write the entitlement cache")
}
}
func TestInspectEntitlementWithoutASubscription(t *testing.T) {
l := ledger.New(memory.New())
got, err := l.InspectEntitlement(context.Background(), "nobody", "app_1", "api_calls")
if err != nil {
t.Fatalf("InspectEntitlement: %v", err)
}
if got.Allowed || got.Reason != "no active subscription" {
t.Errorf("got %+v", got)
}
}
func TestInspectEntitlementRefusesAnEmptyTenant(t *testing.T) {
l := ledger.New(memory.New())
if _, err := l.InspectEntitlement(context.Background(), "", "app_1", "api_calls"); !errors.Is(err, ledger.ErrInvalidInput) {
t.Errorf("empty tenant: got %v, want ErrInvalidInput", err)
}
}
type stubFormatter struct{ format string }
func (f *stubFormatter) Name() string { return "stub-" + f.format }
func (f *stubFormatter) Format() string { return f.format }
func (f *stubFormatter) Render(_ context.Context, _ interface{}, w interface{}) error {
out, ok := w.(io.Writer)
if !ok {
return errors.New("writer is not an io.Writer")
}
_, err := fmt.Fprintf(out, "invoice rendered as %s", f.format)
return err
}
var _ plugin.InvoiceFormatter = (*stubFormatter)(nil)
func TestInvoiceFormatsAndExport(t *testing.T) {
ctx := context.Background()
l := ledger.New(memory.New(), ledger.WithPlugin(&stubFormatter{format: "pdf"}), ledger.WithPlugin(&stubFormatter{format: "csv"}))
if got := l.InvoiceFormats(); len(got) != 2 || got[0] != "csv" || got[1] != "pdf" {
t.Errorf("formats = %v, want [csv pdf]", got)
}
p := activePlan(t, l, "exp", "app_1", 0)
sub := &subscription.Subscription{TenantID: "t1", PlanID: p.ID, AppID: "app_1"}
if err := l.CreateSubscription(ctx, sub); err != nil {
t.Fatalf("CreateSubscription: %v", err)
}
inv, err := l.GenerateInvoice(ctx, sub.ID)
if err != nil {
t.Fatalf("GenerateInvoice: %v", err)
}
body, err := l.ExportInvoice(ctx, inv.ID, "pdf")
if err != nil || string(body) != "invoice rendered as pdf" {
t.Errorf("export pdf: %q, %v", body, err)
}
if _, err := l.ExportInvoice(ctx, inv.ID, "docx"); !errors.Is(err, ledger.ErrInvalidInput) {
t.Errorf("unknown format: got %v, want ErrInvalidInput", err)
}
}
func TestNoFormatsOrProvidersIsEmptyNotNil(t *testing.T) {
l := ledger.New(memory.New())
if got := l.InvoiceFormats(); got == nil || len(got) != 0 {
t.Errorf("formats = %#v, want an empty non-nil slice", got)
}
if got := l.ProviderNames(); got == nil || len(got) != 0 {
t.Errorf("providers = %#v, want an empty non-nil slice", got)
}
}
// entitledFixture is an over-quota tenant: 1500 of 1000 api_calls used, on a
// plan that also carries a boolean "sso" feature.
func entitledFixture(t *testing.T) (context.Context, *ledger.Ledger, *memory.Store, *quotaSpy) {
t.Helper()
ctx := context.Background()
s := memory.New()
spy := "aSpy{}
l := ledger.New(s, ledger.WithPlugin(spy))
p := &plan.Plan{
Name: "ent", Slug: "ent", Currency: "usd", AppID: "app_1",
Features: []plan.Feature{
{Key: "api_calls", Name: "API calls", Type: plan.FeatureMetered, Limit: 1000, Period: plan.PeriodMonthly},
{Key: "sso", Name: "SSO", Type: plan.FeatureBoolean, Limit: 1},
},
Pricing: &plan.Pricing{BaseAmount: types.USD(4900), BillingPeriod: plan.PeriodMonthly},
}
if err := l.CreatePlan(ctx, p); err != nil {
t.Fatalf("CreatePlan: %v", err)
}
if err := l.ActivatePlan(ctx, p.ID); err != nil {
t.Fatalf("ActivatePlan: %v", err)
}
sub := &subscription.Subscription{TenantID: "t1", PlanID: p.ID, AppID: "app_1"}
if err := l.CreateSubscription(ctx, sub); err != nil {
t.Fatalf("CreateSubscription: %v", err)
}
if err := s.IngestBatch(ctx, []*meter.UsageEvent{{ID: id.NewUsageEventID(), TenantID: "t1", AppID: "app_1", FeatureKey: "api_calls", Quantity: 1500, Timestamp: time.Now().UTC()}}); err != nil {
t.Fatalf("IngestBatch: %v", err)
}
//nolint:staticcheck,revive // Entitled reads these string keys today
ctx = context.WithValue(ctx, "tenant_id", "t1")
//nolint:staticcheck,revive // Entitled reads these string keys today
ctx = context.WithValue(ctx, "app_id", "app_1")
return ctx, l, s, spy
}
func TestEntitledMeteredOverQuotaCachesAndEmits(t *testing.T) {
ctx, l, s, spy := entitledFixture(t)
got, err := l.Entitled(ctx, "api_calls")
if err != nil {
t.Fatalf("Entitled: %v", err)
}
if got.Allowed || got.Used != 1500 || got.Limit != 1000 || got.Reason != "quota exceeded" {
t.Errorf("got %+v, want not allowed, used 1500 of 1000, quota exceeded", got)
}
if spy.exceeded != 1 {
t.Errorf("OnQuotaExceeded fired %d times, want 1", spy.exceeded)
}
if spy.checked != 1 {
t.Errorf("OnEntitlementChecked fired %d times, want 1", spy.checked)
}
cached, err := s.GetCached(ctx, "t1", "app_1", "api_calls")
if err != nil {
t.Fatalf("Entitled must write the entitlement cache: %v", err)
}
if cached.Used != 1500 || cached.Reason != "quota exceeded" {
t.Errorf("cached %+v, want the computed result", cached)
}
// A second call is answered from the cache: same result, no new events.
again, err := l.Entitled(ctx, "api_calls")
if err != nil {
t.Fatalf("Entitled (second): %v", err)
}
if again.Allowed || again.Used != 1500 || again.Reason != "quota exceeded" {
t.Errorf("second call got %+v, want the cached result", again)
}
if spy.exceeded != 1 || spy.checked != 1 {
t.Errorf("second call fired events: exceeded=%d checked=%d, want 1 and 1", spy.exceeded, spy.checked)
}
}
func TestEntitledBooleanCachesWithoutEvents(t *testing.T) {
ctx, l, s, spy := entitledFixture(t)
got, err := l.Entitled(ctx, "sso")
if err != nil {
t.Fatalf("Entitled: %v", err)
}
if !got.Allowed || got.Limit != 1 {
t.Errorf("got %+v, want allowed with limit 1", got)
}
if spy.exceeded != 0 || spy.checked != 0 {
t.Errorf("boolean feature fired events: exceeded=%d checked=%d", spy.exceeded, spy.checked)
}
if _, err := s.GetCached(ctx, "t1", "app_1", "sso"); err != nil {
t.Errorf("Entitled must cache a boolean result: %v", err)
}
}
func TestEntitledWithoutASubscriptionCachesNothing(t *testing.T) {
ctx, l, s, spy := entitledFixture(t)
//nolint:staticcheck,revive // Entitled reads these string keys today
ctx = context.WithValue(ctx, "tenant_id", "nobody")
got, err := l.Entitled(ctx, "api_calls")
if err != nil {
t.Fatalf("Entitled: %v", err)
}
if got.Allowed || got.Reason != "no active subscription" {
t.Errorf("got %+v", got)
}
if spy.exceeded != 0 || spy.checked != 0 {
t.Errorf("no-access result fired events: exceeded=%d checked=%d", spy.exceeded, spy.checked)
}
if _, err := s.GetCached(ctx, "nobody", "app_1", "api_calls"); err == nil {
t.Error("Entitled must not cache a no-access result")
}
}