-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcoverage_test.go
More file actions
833 lines (669 loc) · 23.4 KB
/
coverage_test.go
File metadata and controls
833 lines (669 loc) · 23.4 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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
package cove_test
import (
"errors"
"fmt"
"os"
"path/filepath"
"sync"
"sync/atomic"
"testing"
"time"
_ "github.com/mattn/go-sqlite3"
"github.com/modfin/cove"
"github.com/stretchr/testify/assert"
)
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
func newCache(t *testing.T, ops ...cove.Op) *cove.Cache {
t.Helper()
ops = append([]cove.Op{cove.DBRemoveOnClose()}, ops...)
cache, err := cove.New(cove.URITemp(), ops...)
assert.NoError(t, err)
return cache
}
// ---------------------------------------------------------------------------
// BUG B1 – BatchSet(nil) / BatchSet([]KV{}) must not produce invalid SQL
// ---------------------------------------------------------------------------
func TestBatchSetEmpty(t *testing.T) {
cache := newCache(t)
defer cache.Close()
// nil slice
err := cache.BatchSet(nil)
assert.NoError(t, err, "BatchSet(nil) should be a no-op, not a SQL error")
// empty slice
err = cache.BatchSet([]cove.KV[[]byte]{})
assert.NoError(t, err, "BatchSet([]KV{}) should be a no-op, not a SQL error")
// cache should still be empty
kvs, err := cache.Range(cove.RANGE_MIN, cove.RANGE_MAX)
assert.NoError(t, err)
assert.Equal(t, 0, len(kvs))
}
// ---------------------------------------------------------------------------
// BUG B2 – BatchGet(nil) / BatchGet([]string{}) must be a safe no-op
//
// The SQLite CGo driver silently accepts "WHERE key IN ()" and returns zero
// rows, so this currently passes – but the contract (empty input → empty
// result, no error, existing keys untouched) should be pinned as a test.
// ---------------------------------------------------------------------------
func TestBatchGetEmpty(t *testing.T) {
cache := newCache(t)
defer cache.Close()
// seed something so the table isn't trivially empty
assert.NoError(t, cache.Set("k", []byte("v")))
res, err := cache.BatchGet(nil)
assert.NoError(t, err, "BatchGet(nil) should be a no-op")
assert.Equal(t, 0, len(res))
res, err = cache.BatchGet([]string{})
assert.NoError(t, err, "BatchGet([]string{}) should be a no-op")
assert.Equal(t, 0, len(res))
// existing key must be unaffected
v, err := cache.Get("k")
assert.NoError(t, err)
assert.Equal(t, []byte("v"), v)
}
// ---------------------------------------------------------------------------
// BUG B3 – BatchEvict(nil) / BatchEvict([]string{}) must be a safe no-op
//
// Same as B2: the CGo driver tolerates "WHERE key IN ()" so this currently
// passes; the test pins the correct contract.
// ---------------------------------------------------------------------------
func TestBatchEvictEmpty(t *testing.T) {
cache := newCache(t)
defer cache.Close()
assert.NoError(t, cache.Set("k", []byte("v")))
evicted, err := cache.BatchEvict(nil)
assert.NoError(t, err, "BatchEvict(nil) should be a no-op")
assert.Equal(t, 0, len(evicted))
evicted, err = cache.BatchEvict([]string{})
assert.NoError(t, err, "BatchEvict([]string{}) should be a no-op")
assert.Equal(t, 0, len(evicted))
// original key must still be present
v, err := cache.Get("k")
assert.NoError(t, err)
assert.Equal(t, []byte("v"), v)
}
// ---------------------------------------------------------------------------
// BUG B4 – TypedCache.Evict must return the evicted key in KV.K
// ---------------------------------------------------------------------------
func TestTypedEvictReturnsKey(t *testing.T) {
tc := TypedCache(t)
defer tc.Raw().Close()
const key = "my-key"
assert.NoError(t, tc.Set(key, "my-value"))
evicted, err := tc.Evict(key)
assert.NoError(t, err)
assert.Equal(t, key, evicted.K, "Evict should populate KV.K with the evicted key")
assert.Equal(t, "my-value", evicted.V)
}
// ---------------------------------------------------------------------------
// BUG B5 – NS(ns, ops...) must apply ops to the child, not the parent
// ---------------------------------------------------------------------------
func TestNSWithOption(t *testing.T) {
parent := newCache(t)
defer parent.Close()
// Give the child a very short TTL via the NS option.
// NOTE: namespace names become SQLite table name suffixes – no hyphens.
child, err := parent.NS("child_ns", cove.WithTTL(1*time.Second))
assert.NoError(t, err)
if child == nil {
// If NS returns nil the bug is in NS itself; the test still captures it.
t.Fatal("NS returned nil cache")
}
// Set a key in the child and a key in the parent
assert.NoError(t, child.Set("child_key", []byte("child-value")))
assert.NoError(t, parent.Set("parent_key", []byte("parent-value")))
// Wait for the child TTL to expire
time.Sleep(2 * time.Second)
// Child key must have expired (child got WithTTL(1s))
_, err = child.Get("child_key")
assert.True(t, errors.Is(err, cove.NotFound),
"child key should have expired because child NS was created with WithTTL(1s)")
// Parent key must still be alive (parent has NO_TTL; the op must NOT have been applied to the parent)
v, err := parent.Get("parent_key")
assert.NoError(t, err, "parent key should still be alive; op must not have mutated the parent")
assert.Equal(t, []byte("parent-value"), v)
}
// ---------------------------------------------------------------------------
// BUG B6 – Range / Keys / Values must NOT return TTL-expired entries
// ---------------------------------------------------------------------------
func TestRangeExcludesExpiredEntries(t *testing.T) {
cache := newCache(t)
defer cache.Close()
assert.NoError(t, cache.SetTTL("expires", []byte("gone"), 1*time.Second))
assert.NoError(t, cache.Set("lives", []byte("here")))
time.Sleep(2 * time.Second)
kvs, err := cache.Range(cove.RANGE_MIN, cove.RANGE_MAX)
assert.NoError(t, err)
for _, kv := range kvs {
assert.NotEqual(t, "expires", kv.K,
"Range must not return TTL-expired entries")
}
assert.Equal(t, 1, len(kvs), "only the non-expired entry should be returned")
}
func TestKeysExcludesExpiredEntries(t *testing.T) {
cache := newCache(t)
defer cache.Close()
assert.NoError(t, cache.SetTTL("expires", []byte("gone"), 1*time.Second))
assert.NoError(t, cache.Set("lives", []byte("here")))
time.Sleep(2 * time.Second)
keys, err := cache.Keys(cove.RANGE_MIN, cove.RANGE_MAX)
assert.NoError(t, err)
for _, k := range keys {
assert.NotEqual(t, "expires", k,
"Keys must not return TTL-expired keys")
}
assert.Equal(t, 1, len(keys))
}
func TestValuesExcludesExpiredEntries(t *testing.T) {
cache := newCache(t)
defer cache.Close()
assert.NoError(t, cache.SetTTL("expires", []byte("gone"), 1*time.Second))
assert.NoError(t, cache.Set("lives", []byte("here")))
time.Sleep(2 * time.Second)
vals, err := cache.Values(cove.RANGE_MIN, cove.RANGE_MAX)
assert.NoError(t, err)
assert.Equal(t, 1, len(vals), "Values must not return TTL-expired values")
}
func TestItrRangeExcludesExpiredEntries(t *testing.T) {
cache := newCache(t)
defer cache.Close()
assert.NoError(t, cache.SetTTL("expires", []byte("gone"), 1*time.Second))
assert.NoError(t, cache.Set("lives", []byte("here")))
time.Sleep(2 * time.Second)
var count int
for k := range cache.ItrKeys(cove.RANGE_MIN, cove.RANGE_MAX) {
assert.NotEqual(t, "expires", k,
"ItrRange must not yield TTL-expired entries")
count++
}
assert.Equal(t, 1, count)
}
// ---------------------------------------------------------------------------
// HAPPY PATHS
// ---------------------------------------------------------------------------
// GetOr hit path – fetcher must NOT be invoked when the key already exists
func TestGetOrHitPath(t *testing.T) {
cache := newCache(t)
defer cache.Close()
assert.NoError(t, cache.Set("key", []byte("cached")))
fetcherCalled := false
val, err := cache.GetOr("key", func(k string) ([]byte, error) {
fetcherCalled = true
return []byte("from-fetcher"), nil
})
assert.NoError(t, err)
assert.Equal(t, []byte("cached"), val)
assert.False(t, fetcherCalled, "fetcher must not be called when the key already exists")
}
// TypedCache.GetOr hit path
func TestTypedGetOrHitPath(t *testing.T) {
tc := TypedCache(t)
defer tc.Raw().Close()
assert.NoError(t, tc.Set("key", "cached"))
fetcherCalled := false
val, err := tc.GetOr("key", func(k string) (string, error) {
fetcherCalled = true
return "from-fetcher", nil
})
assert.NoError(t, err)
assert.Equal(t, "cached", val)
assert.False(t, fetcherCalled, "fetcher must not be called when the key already exists")
}
// EvictAll on raw *Cache
func TestCacheEvictAll(t *testing.T) {
cache := newCache(t)
defer cache.Close()
assert.NoError(t, cache.Set("k1", []byte("v1")))
assert.NoError(t, cache.Set("k2", []byte("v2")))
assert.NoError(t, cache.Set("k3", []byte("v3")))
n, err := cache.EvictAll()
assert.NoError(t, err)
assert.Equal(t, 3, n)
_, err = cache.Get("k1")
assert.True(t, errors.Is(err, cove.NotFound))
_, err = cache.Get("k2")
assert.True(t, errors.Is(err, cove.NotFound))
_, err = cache.Get("k3")
assert.True(t, errors.Is(err, cove.NotFound))
}
// EvictAll on empty cache must return 0
func TestCacheEvictAllEmpty(t *testing.T) {
cache := newCache(t)
defer cache.Close()
n, err := cache.EvictAll()
assert.NoError(t, err)
assert.Equal(t, 0, n)
}
// EvictAll must NOT fire onEvict (documented promise)
func TestEvictAllDoesNotCallOnEvict(t *testing.T) {
var callCount int64
cache := newCache(t, cove.WithEvictCallback(func(k string, v []byte) {
atomic.AddInt64(&callCount, 1)
}))
defer cache.Close()
assert.NoError(t, cache.Set("k1", []byte("v1")))
assert.NoError(t, cache.Set("k2", []byte("v2")))
assert.NoError(t, cache.Set("k3", []byte("v3")))
_, err := cache.EvictAll()
assert.NoError(t, err)
// Give any (unexpected) goroutines time to fire
time.Sleep(100 * time.Millisecond)
assert.Equal(t, int64(0), atomic.LoadInt64(&callCount),
"onEvict must not be called by EvictAll")
}
// Single Evict must fire onEvict asynchronously
func TestEvictFiresOnEvictCallback(t *testing.T) {
var wg sync.WaitGroup
wg.Add(1)
var gotKey string
var gotVal []byte
cache := newCache(t, cove.WithEvictCallback(func(k string, v []byte) {
gotKey = k
gotVal = v
wg.Done()
}))
defer cache.Close()
assert.NoError(t, cache.Set("fire-me", []byte("payload")))
_, err := cache.Evict("fire-me")
assert.NoError(t, err)
wg.Wait()
assert.Equal(t, "fire-me", gotKey)
assert.Equal(t, []byte("payload"), gotVal)
}
// TypedCache.Range – the only TypedCache method with no existing test
func TestTypedCacheRange(t *testing.T) {
tc := TypedCache(t)
defer tc.Raw().Close()
in := []cove.KV[string]{
{K: "a", V: "alpha"},
{K: "b", V: "beta"},
{K: "c", V: "gamma"},
}
assert.NoError(t, tc.BatchSet(in))
out, err := tc.Range(cove.RANGE_MIN, cove.RANGE_MAX)
assert.NoError(t, err)
assert.Equal(t, 3, len(out))
// Results are ordered by key in SQLite
assert.Equal(t, "a", out[0].K)
assert.Equal(t, "alpha", out[0].V)
assert.Equal(t, "b", out[1].K)
assert.Equal(t, "beta", out[1].V)
assert.Equal(t, "c", out[2].K)
assert.Equal(t, "gamma", out[2].V)
}
// Zip / Unzip / KV helpers – entirely untested in existing suite
func TestZip(t *testing.T) {
keys := []string{"a", "b", "c"}
vals := []int{1, 2, 3}
kvs := cove.Zip(keys, vals)
assert.Equal(t, 3, len(kvs))
assert.Equal(t, "a", kvs[0].K)
assert.Equal(t, 1, kvs[0].V)
assert.Equal(t, "c", kvs[2].K)
assert.Equal(t, 3, kvs[2].V)
}
func TestZipTruncatesToShorterSlice(t *testing.T) {
keys := []string{"a", "b"}
vals := []int{1, 2, 3}
kvs := cove.Zip(keys, vals)
assert.Equal(t, 2, len(kvs), "Zip must truncate to the shorter slice")
kvs2 := cove.Zip([]string{"a", "b", "c"}, []int{1})
assert.Equal(t, 1, len(kvs2))
}
func TestZipEmpty(t *testing.T) {
kvs := cove.Zip([]string{}, []int{})
assert.Equal(t, 0, len(kvs))
kvs2 := cove.Zip[int](nil, nil)
assert.Equal(t, 0, len(kvs2))
}
func TestUnzip(t *testing.T) {
in := []cove.KV[string]{
{K: "x", V: "foo"},
{K: "y", V: "bar"},
}
keys, vals := cove.Unzip(in)
assert.Equal(t, []string{"x", "y"}, keys)
assert.Equal(t, []string{"foo", "bar"}, vals)
}
func TestZipUnzipRoundTrip(t *testing.T) {
origKeys := []string{"p", "q", "r"}
origVals := []float64{1.1, 2.2, 3.3}
kvs := cove.Zip(origKeys, origVals)
keys, vals := cove.Unzip(kvs)
assert.Equal(t, origKeys, keys)
assert.Equal(t, origVals, vals)
}
func TestKVMethods(t *testing.T) {
kv := cove.KV[string]{K: "thekey", V: "thevalue"}
assert.Equal(t, "thekey", kv.Key())
assert.Equal(t, "thevalue", kv.Value())
k, v := kv.Unzip()
assert.Equal(t, "thekey", k)
assert.Equal(t, "thevalue", v)
}
// URIFromPath – persistent file lifecycle, never called in any existing test
func TestURIFromPath(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "sub", "test.db")
uri := cove.URIFromPath(path)
assert.Contains(t, uri, "file:")
// First open – write a key
c1, err := cove.New(uri) // no DBRemoveOnClose – we want persistence
assert.NoError(t, err)
assert.NoError(t, c1.Set("persist", []byte("yes")))
assert.NoError(t, c1.Close())
// Second open – key must still be there
c2, err := cove.New(uri)
assert.NoError(t, err)
defer c2.Close()
v, err := c2.Get("persist")
assert.NoError(t, err)
assert.Equal(t, []byte("yes"), v)
// Cleanup
os.RemoveAll(dir)
}
// Hit / Miss helpers – full branch coverage
func TestHitNil(t *testing.T) {
ok, err := cove.Hit(nil)
assert.NoError(t, err)
assert.True(t, ok)
}
func TestHitNotFound(t *testing.T) {
ok, err := cove.Hit(cove.NotFound)
assert.NoError(t, err)
assert.False(t, ok)
}
func TestHitOtherError(t *testing.T) {
boom := fmt.Errorf("something broke")
ok, err := cove.Hit(boom)
assert.Error(t, err)
assert.False(t, ok)
assert.Equal(t, boom, err)
}
func TestMissNil(t *testing.T) {
miss, err := cove.Miss(nil)
assert.NoError(t, err)
assert.False(t, miss, "Miss(nil) == not-missing == false")
}
func TestMissNotFound(t *testing.T) {
miss, err := cove.Miss(cove.NotFound)
assert.NoError(t, err)
assert.True(t, miss)
}
func TestMissOtherError(t *testing.T) {
// Miss(realErr) → Hit returns (false, err), so Miss returns (!false=true, err)
// meaning: "it was a miss AND there was a real error"
boom := fmt.Errorf("something broke")
miss, err := cove.Miss(boom)
assert.Error(t, err)
assert.True(t, miss, "Miss with a real error should still report a miss (and return the error)")
}
// vacuumNoResult path – Vacuum without onEvict set exercises vacuumNoResult()
func TestVacuumWithoutOnEvict(t *testing.T) {
cache, err := cove.New(
cove.URITemp(),
cove.DBRemoveOnClose(),
cove.WithTTL(300*time.Millisecond),
cove.WithVacuum(cove.Vacuum(100*time.Millisecond, 1000)),
// deliberately NO WithEvictCallback → exercises vacuumNoResult()
)
assert.NoError(t, err)
defer cache.Close()
for i := 0; i < 10; i++ {
assert.NoError(t, cache.Set(fmt.Sprintf("k%d", i), []byte("v")))
}
// Wait for TTL expiry + at least one vacuum cycle
time.Sleep(600 * time.Millisecond)
for i := 0; i < 10; i++ {
_, err := cache.Get(fmt.Sprintf("k%d", i))
assert.True(t, errors.Is(err, cove.NotFound),
"vacuumNoResult should have removed expired key k%d", i)
}
}
// SetTTL overwrite – both value and TTL must be updated
func TestSetTTLOverwrite(t *testing.T) {
cache := newCache(t)
defer cache.Close()
// Set with long TTL first
assert.NoError(t, cache.SetTTL("k", []byte("old"), 60*time.Second))
v, err := cache.Get("k")
assert.NoError(t, err)
assert.Equal(t, []byte("old"), v)
// Overwrite with new value and very short TTL
assert.NoError(t, cache.SetTTL("k", []byte("new"), 1*time.Second))
// Value must be updated immediately
v, err = cache.Get("k")
assert.NoError(t, err)
assert.Equal(t, []byte("new"), v, "overwrite must update the stored value")
// After TTL elapses, key must be gone
time.Sleep(2 * time.Second)
_, err = cache.Get("k")
assert.True(t, errors.Is(err, cove.NotFound),
"overwritten short TTL must take effect")
}
// Iterator early-exit – yield returning false must stop iteration
func TestItrRangeEarlyExit(t *testing.T) {
cache := newCache(t)
defer cache.Close()
for i := 0; i < 5; i++ {
assert.NoError(t, cache.Set(fmt.Sprintf("key%d", i), []byte("v")))
}
var count int
for range cache.ItrRange(cove.RANGE_MIN, cove.RANGE_MAX) {
count++
break // yield false after first item
}
assert.Equal(t, 1, count, "ItrRange must stop after yield returns false")
}
func TestItrKeysEarlyExit(t *testing.T) {
cache := newCache(t)
defer cache.Close()
for i := 0; i < 5; i++ {
assert.NoError(t, cache.Set(fmt.Sprintf("key%d", i), []byte("v")))
}
var count int
for range cache.ItrKeys(cove.RANGE_MIN, cove.RANGE_MAX) {
count++
break
}
assert.Equal(t, 1, count, "ItrKeys must stop after yield returns false")
}
func TestItrValuesEarlyExit(t *testing.T) {
cache := newCache(t)
defer cache.Close()
for i := 0; i < 5; i++ {
assert.NoError(t, cache.Set(fmt.Sprintf("key%d", i), []byte("v")))
}
var count int
for range cache.ItrValues(cove.RANGE_MIN, cove.RANGE_MAX) {
count++
break
}
assert.Equal(t, 1, count, "ItrValues must stop after yield returns false")
}
// WithLogger(nil) must not panic and the cache must be operational
func TestWithLoggerNil(t *testing.T) {
cache, err := cove.New(cove.URITemp(), cove.DBRemoveOnClose(), cove.WithLogger(nil))
assert.NoError(t, err)
defer cache.Close()
assert.NoError(t, cache.Set("k", []byte("v")))
v, err := cache.Get("k")
assert.NoError(t, err)
assert.Equal(t, []byte("v"), v)
}
// WithTTL(0) and WithTTL(-1) must be silently ignored (guard: if defaultTTL > 0)
func TestWithTTLZeroOrNegativeIgnored(t *testing.T) {
do := func(ttl time.Duration) func(*testing.T) {
return func(t *testing.T) {
cache, err := cove.New(cove.URITemp(), cove.DBRemoveOnClose(), cove.WithTTL(ttl))
assert.NoError(t, err)
defer cache.Close()
assert.NoError(t, cache.Set("k", []byte("v")))
time.Sleep(200 * time.Millisecond)
v, err := cache.Get("k")
assert.NoError(t, err, "key should still be alive when WithTTL(%v) is ignored", ttl)
assert.Equal(t, []byte("v"), v)
}
}
t.Run("zero", do(0))
t.Run("negative", do(-1*time.Second))
}
// Double Close must not panic (protected by sync.Once)
func TestDoubleClose(t *testing.T) {
cache := newCache(t)
assert.NotPanics(t, func() {
_ = cache.Close()
_ = cache.Close()
})
}
// ---------------------------------------------------------------------------
// SAD PATHS
// ---------------------------------------------------------------------------
// GetOr fetch function returns an error – must propagate, key must not be stored
func TestGetOrFetcherError(t *testing.T) {
cache := newCache(t)
defer cache.Close()
fetchErr := fmt.Errorf("fetch failed")
_, err := cache.GetOr("k", func(string) ([]byte, error) {
return nil, fetchErr
})
assert.Error(t, err)
assert.True(t, errors.Is(err, fetchErr))
// Key must not have been stored
_, err = cache.Get("k")
assert.True(t, errors.Is(err, cove.NotFound))
}
// TypedCache.GetOr when getter returns an error
func TestTypedGetOrFetcherError(t *testing.T) {
tc := TypedCache(t)
defer tc.Raw().Close()
fetchErr := fmt.Errorf("typed fetch failed")
_, err := tc.GetOr("k", func(string) (string, error) {
return "", fetchErr
})
assert.Error(t, err)
assert.True(t, errors.Is(err, fetchErr))
_, err = tc.Get("k")
assert.True(t, errors.Is(err, cove.NotFound))
}
// SetTTL with zero duration – key should be immediately expired
func TestSetTTLZeroDuration(t *testing.T) {
cache := newCache(t)
defer cache.Close()
assert.NoError(t, cache.SetTTL("k", []byte("v"), 0))
_, err := cache.Get("k")
assert.True(t, errors.Is(err, cove.NotFound),
"a key set with TTL=0 should be immediately expired")
}
// SetTTL with negative duration – key should be immediately expired
func TestSetTTLNegativeDuration(t *testing.T) {
cache := newCache(t)
defer cache.Close()
assert.NoError(t, cache.SetTTL("k", []byte("v"), -1*time.Second))
_, err := cache.Get("k")
assert.True(t, errors.Is(err, cove.NotFound),
"a key set with negative TTL should be immediately expired")
}
// Evict on a missing key must return NotFound
func TestEvictMissing(t *testing.T) {
cache := newCache(t)
defer cache.Close()
_, err := cache.Evict("no-such-key")
assert.True(t, errors.Is(err, cove.NotFound))
}
// TypedCache.Evict on missing key must return NotFound
func TestTypedEvictMissing(t *testing.T) {
tc := TypedCache(t)
defer tc.Raw().Close()
_, err := tc.Evict("no-such-key")
assert.True(t, errors.Is(err, cove.NotFound))
}
// TypedCache.Get on raw bytes that are not valid gob must return a decode error
func TestTypedGetCorruptGob(t *testing.T) {
cc := newCache(t)
defer cc.Close()
tc := cove.Of[string](cc)
// Write raw bytes that are not valid gob via the underlying cache
assert.NoError(t, cc.Set("corrupt", []byte("this is not gob encoded")))
_, err := tc.Get("corrupt")
assert.Error(t, err, "reading non-gob bytes through TypedCache must return a decode error")
assert.False(t, errors.Is(err, cove.NotFound),
"the error should be a decode error, not NotFound")
}
// BatchGet with all keys missing must return empty result, no error
func TestBatchGetAllMissing(t *testing.T) {
cache := newCache(t)
defer cache.Close()
res, err := cache.BatchGet([]string{"ghost1", "ghost2", "ghost3"})
assert.NoError(t, err)
assert.Equal(t, 0, len(res))
}
// BatchEvict on non-existent keys must return empty result, no error
func TestBatchEvictMissing(t *testing.T) {
cache := newCache(t)
defer cache.Close()
evicted, err := cache.BatchEvict([]string{"ghost1", "ghost2"})
assert.NoError(t, err)
assert.Equal(t, 0, len(evicted))
}
// Range(from, to) where from > to must return empty result
func TestRangeInverted(t *testing.T) {
cache := newCache(t)
defer cache.Close()
assert.NoError(t, cache.Set("key1", []byte("v1")))
assert.NoError(t, cache.Set("key2", []byte("v2")))
assert.NoError(t, cache.Set("key3", []byte("v3")))
kvs, err := cache.Range("z", "a")
assert.NoError(t, err)
assert.Equal(t, 0, len(kvs), "inverted range must return empty result")
}
// Range(k, k) must return exactly the one matching entry
func TestRangeSingleKey(t *testing.T) {
cache := newCache(t)
defer cache.Close()
assert.NoError(t, cache.Set("key1", []byte("v1")))
assert.NoError(t, cache.Set("key2", []byte("v2")))
assert.NoError(t, cache.Set("key3", []byte("v3")))
kvs, err := cache.Range("key2", "key2")
assert.NoError(t, err)
assert.Equal(t, 1, len(kvs))
assert.Equal(t, "key2", kvs[0].K)
assert.Equal(t, []byte("v2"), kvs[0].V)
}
// New with an invalid / unreachable URI must return an error
func TestNewInvalidURI(t *testing.T) {
// A path that can never be created (file inside a file)
_, err := cove.New("file:///dev/null/impossible/path.db")
assert.Error(t, err, "New with an invalid URI must return an error")
}
// Concurrent NS() creation of the same namespace must not race or duplicate.
// Namespace names become SQLite table name suffixes – no hyphens allowed.
func TestNSConcurrent(t *testing.T) {
parent := newCache(t)
defer parent.Close()
const goroutines = 20
results := make([]*cove.Cache, goroutines)
var wg sync.WaitGroup
for i := 0; i < goroutines; i++ {
wg.Add(1)
go func(idx int) {
defer wg.Done()
ns, err := parent.NS("sharedns")
assert.NoError(t, err)
results[idx] = ns
}(i)
}
wg.Wait()
// All goroutines must have received the exact same *Cache pointer
first := results[0]
assert.NotNil(t, first)
for i, r := range results {
assert.Same(t, first, r, "goroutine %d got a different namespace instance", i)
}
// The namespace must be fully functional
assert.NoError(t, first.Set("concurrentkey", []byte("ok")))
v, err := first.Get("concurrentkey")
assert.NoError(t, err)
assert.Equal(t, []byte("ok"), v)
}