-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathredis_client_test.go
More file actions
1558 lines (1337 loc) · 37.9 KB
/
redis_client_test.go
File metadata and controls
1558 lines (1337 loc) · 37.9 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
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package redkit
import (
"context"
"fmt"
"net"
"strconv"
"sync"
"testing"
"time"
"github.com/redis/go-redis/v9"
)
// Test helper functions
// getFreePort returns a free port for testing
func getFreePort() (int, error) {
addr, err := net.ResolveTCPAddr("tcp", "localhost:0")
if err != nil {
return 0, err
}
l, err := net.ListenTCP("tcp", addr)
if err != nil {
return 0, err
}
defer l.Close()
return l.Addr().(*net.TCPAddr).Port, nil
}
// startRedisServer starts a Redis-compatible server with comprehensive command support
func startRedisServer(t *testing.T) (*Server, *redis.Client, func()) {
port, err := getFreePort()
if err != nil {
t.Fatalf("Failed to get free port: %v", err)
}
address := fmt.Sprintf(":%d", port)
server := NewServer(address)
// Setup in-memory storage with thread safety and expiration support
storage := make(map[string]string)
expiration := make(map[string]time.Time)
mu := sync.RWMutex{}
// Helper functions for expiration handling
isExpired := func(key string) bool {
if expTime, exists := expiration[key]; exists {
return time.Now().After(expTime)
}
return false
}
cleanupExpired := func(key string) bool {
if isExpired(key) {
delete(storage, key)
delete(expiration, key)
return true
}
return false
}
// Register all Redis commands
// PING command
server.RegisterCommandFunc("PING", func(conn *Connection, cmd *Command) RedisValue {
if len(cmd.Args) == 0 {
return RedisValue{Type: SimpleString, Str: "PONG"}
}
if len(cmd.Args) == 1 {
return RedisValue{Type: BulkString, Bulk: []byte(cmd.Args[0])}
}
return RedisValue{Type: ErrorReply, Str: "ERR wrong number of arguments for 'ping' command"}
})
// ECHO command
server.RegisterCommandFunc("ECHO", func(conn *Connection, cmd *Command) RedisValue {
if len(cmd.Args) != 1 {
return RedisValue{Type: ErrorReply, Str: "ERR wrong number of arguments for 'echo' command"}
}
return RedisValue{Type: BulkString, Bulk: []byte(cmd.Args[0])}
})
// SET command
server.RegisterCommandFunc("SET", func(conn *Connection, cmd *Command) RedisValue {
if len(cmd.Args) < 2 {
return RedisValue{Type: ErrorReply, Str: "ERR wrong number of arguments for 'set' command"}
}
mu.Lock()
defer mu.Unlock()
storage[cmd.Args[0]] = cmd.Args[1]
delete(expiration, cmd.Args[0]) // Clear any existing expiration
return RedisValue{Type: SimpleString, Str: "OK"}
})
// GET command
server.RegisterCommandFunc("GET", func(conn *Connection, cmd *Command) RedisValue {
if len(cmd.Args) != 1 {
return RedisValue{Type: ErrorReply, Str: "ERR wrong number of arguments for 'get' command"}
}
mu.Lock()
defer mu.Unlock()
key := cmd.Args[0]
if cleanupExpired(key) {
return RedisValue{Type: Null}
}
value, exists := storage[key]
if !exists {
return RedisValue{Type: Null}
}
return RedisValue{Type: BulkString, Bulk: []byte(value)}
})
// DEL command
server.RegisterCommandFunc("DEL", func(conn *Connection, cmd *Command) RedisValue {
if len(cmd.Args) < 1 {
return RedisValue{Type: ErrorReply, Str: "ERR wrong number of arguments for 'del' command"}
}
mu.Lock()
defer mu.Unlock()
deleted := 0
for _, key := range cmd.Args {
if _, exists := storage[key]; exists {
delete(storage, key)
delete(expiration, key)
deleted++
}
}
return RedisValue{Type: Integer, Int: int64(deleted)}
})
// EXISTS command
server.RegisterCommandFunc("EXISTS", func(conn *Connection, cmd *Command) RedisValue {
if len(cmd.Args) < 1 {
return RedisValue{Type: ErrorReply, Str: "ERR wrong number of arguments for 'exists' command"}
}
mu.Lock()
defer mu.Unlock()
count := 0
for _, key := range cmd.Args {
if !cleanupExpired(key) {
if _, exists := storage[key]; exists {
count++
}
}
}
return RedisValue{Type: Integer, Int: int64(count)}
})
// TTL command
server.RegisterCommandFunc("TTL", func(conn *Connection, cmd *Command) RedisValue {
if len(cmd.Args) != 1 {
return RedisValue{Type: ErrorReply, Str: "ERR wrong number of arguments for 'ttl' command"}
}
mu.Lock()
defer mu.Unlock()
key := cmd.Args[0]
if cleanupExpired(key) {
return RedisValue{Type: Integer, Int: -2} // Key doesn't exist
}
if _, exists := storage[key]; !exists {
return RedisValue{Type: Integer, Int: -2} // Key doesn't exist
}
if expTime, hasExpiry := expiration[key]; hasExpiry {
ttl := int64(time.Until(expTime).Seconds())
if ttl <= 0 {
return RedisValue{Type: Integer, Int: -2}
}
return RedisValue{Type: Integer, Int: ttl}
}
return RedisValue{Type: Integer, Int: -1} // No expiry
})
// EXPIRE command
server.RegisterCommandFunc("EXPIRE", func(conn *Connection, cmd *Command) RedisValue {
if len(cmd.Args) != 2 {
return RedisValue{Type: ErrorReply, Str: "ERR wrong number of arguments for 'expire' command"}
}
key := cmd.Args[0]
seconds, err := strconv.Atoi(cmd.Args[1])
if err != nil {
return RedisValue{Type: ErrorReply, Str: "ERR invalid expire time"}
}
mu.Lock()
defer mu.Unlock()
if cleanupExpired(key) {
return RedisValue{Type: Integer, Int: 0} // Key doesn't exist
}
if _, exists := storage[key]; !exists {
return RedisValue{Type: Integer, Int: 0} // Key doesn't exist
}
expiration[key] = time.Now().Add(time.Duration(seconds) * time.Second)
return RedisValue{Type: Integer, Int: 1} // Expiration set
})
// INCR command
server.RegisterCommandFunc("INCR", func(conn *Connection, cmd *Command) RedisValue {
if len(cmd.Args) != 1 {
return RedisValue{Type: ErrorReply, Str: "ERR wrong number of arguments for 'incr' command"}
}
key := cmd.Args[0]
mu.Lock()
defer mu.Unlock()
if cleanupExpired(key) {
storage[key] = "1"
return RedisValue{Type: Integer, Int: 1}
}
value, exists := storage[key]
if !exists {
storage[key] = "1"
return RedisValue{Type: Integer, Int: 1}
}
intVal, err := strconv.Atoi(value)
if err != nil {
return RedisValue{Type: ErrorReply, Str: "ERR value is not an integer"}
}
intVal++
storage[key] = strconv.Itoa(intVal)
return RedisValue{Type: Integer, Int: int64(intVal)}
})
// INCRBY command
server.RegisterCommandFunc("INCRBY", func(conn *Connection, cmd *Command) RedisValue {
if len(cmd.Args) != 2 {
return RedisValue{Type: ErrorReply, Str: "ERR wrong number of arguments for 'incrby' command"}
}
key := cmd.Args[0]
increment, err := strconv.Atoi(cmd.Args[1])
if err != nil {
return RedisValue{Type: ErrorReply, Str: "ERR invalid increment"}
}
mu.Lock()
defer mu.Unlock()
if cleanupExpired(key) {
storage[key] = strconv.Itoa(increment)
return RedisValue{Type: Integer, Int: int64(increment)}
}
value, exists := storage[key]
if !exists {
storage[key] = strconv.Itoa(increment)
return RedisValue{Type: Integer, Int: int64(increment)}
}
intVal, err := strconv.Atoi(value)
if err != nil {
return RedisValue{Type: ErrorReply, Str: "ERR value is not an integer"}
}
intVal += increment
storage[key] = strconv.Itoa(intVal)
return RedisValue{Type: Integer, Int: int64(intVal)}
})
// DECR command
server.RegisterCommandFunc("DECR", func(conn *Connection, cmd *Command) RedisValue {
if len(cmd.Args) != 1 {
return RedisValue{Type: ErrorReply, Str: "ERR wrong number of arguments for 'decr' command"}
}
key := cmd.Args[0]
mu.Lock()
defer mu.Unlock()
if cleanupExpired(key) {
storage[key] = "-1"
return RedisValue{Type: Integer, Int: -1}
}
value, exists := storage[key]
if !exists {
storage[key] = "-1"
return RedisValue{Type: Integer, Int: -1}
}
intVal, err := strconv.Atoi(value)
if err != nil {
return RedisValue{Type: ErrorReply, Str: "ERR value is not an integer"}
}
intVal--
storage[key] = strconv.Itoa(intVal)
return RedisValue{Type: Integer, Int: int64(intVal)}
})
// DECRBY command
server.RegisterCommandFunc("DECRBY", func(conn *Connection, cmd *Command) RedisValue {
if len(cmd.Args) != 2 {
return RedisValue{Type: ErrorReply, Str: "ERR wrong number of arguments for 'decrby' command"}
}
key := cmd.Args[0]
decrement, err := strconv.Atoi(cmd.Args[1])
if err != nil {
return RedisValue{Type: ErrorReply, Str: "ERR invalid decrement"}
}
mu.Lock()
defer mu.Unlock()
if cleanupExpired(key) {
result := -decrement
storage[key] = strconv.Itoa(result)
return RedisValue{Type: Integer, Int: int64(result)}
}
value, exists := storage[key]
if !exists {
result := -decrement
storage[key] = strconv.Itoa(result)
return RedisValue{Type: Integer, Int: int64(result)}
}
intVal, err := strconv.Atoi(value)
if err != nil {
return RedisValue{Type: ErrorReply, Str: "ERR value is not an integer"}
}
intVal -= decrement
storage[key] = strconv.Itoa(intVal)
return RedisValue{Type: Integer, Int: int64(intVal)}
})
// TYPE command
server.RegisterCommandFunc("TYPE", func(conn *Connection, cmd *Command) RedisValue {
if len(cmd.Args) != 1 {
return RedisValue{Type: ErrorReply, Str: "ERR wrong number of arguments for 'type' command"}
}
key := cmd.Args[0]
mu.Lock()
defer mu.Unlock()
if cleanupExpired(key) {
return RedisValue{Type: SimpleString, Str: "none"}
}
if _, exists := storage[key]; exists {
return RedisValue{Type: SimpleString, Str: "string"}
}
return RedisValue{Type: SimpleString, Str: "none"}
})
// KEYS command
server.RegisterCommandFunc("KEYS", func(conn *Connection, cmd *Command) RedisValue {
if len(cmd.Args) != 1 {
return RedisValue{Type: ErrorReply, Str: "ERR wrong number of arguments for 'keys' command"}
}
pattern := cmd.Args[0]
mu.Lock()
defer mu.Unlock()
var keys []RedisValue
for key := range storage {
if !cleanupExpired(key) {
// Simple pattern matching - support * wildcard
if pattern == "*" || key == pattern {
keys = append(keys, RedisValue{Type: BulkString, Bulk: []byte(key)})
}
}
}
return RedisValue{Type: Array, Array: keys}
})
// SETNX command
server.RegisterCommandFunc("SETNX", func(conn *Connection, cmd *Command) RedisValue {
if len(cmd.Args) != 2 {
return RedisValue{Type: ErrorReply, Str: "ERR wrong number of arguments for 'setnx' command"}
}
key, value := cmd.Args[0], cmd.Args[1]
mu.Lock()
defer mu.Unlock()
if cleanupExpired(key) {
storage[key] = value
return RedisValue{Type: Integer, Int: 1}
}
if _, exists := storage[key]; exists {
return RedisValue{Type: Integer, Int: 0} // Key already exists
}
storage[key] = value
return RedisValue{Type: Integer, Int: 1} // Key was set
})
// MGET command
server.RegisterCommandFunc("MGET", func(conn *Connection, cmd *Command) RedisValue {
if len(cmd.Args) < 1 {
return RedisValue{Type: ErrorReply, Str: "ERR wrong number of arguments for 'mget' command"}
}
mu.Lock()
defer mu.Unlock()
result := make([]RedisValue, len(cmd.Args))
for i, key := range cmd.Args {
if cleanupExpired(key) {
result[i] = RedisValue{Type: Null}
} else if value, exists := storage[key]; exists {
result[i] = RedisValue{Type: BulkString, Bulk: []byte(value)}
} else {
result[i] = RedisValue{Type: Null}
}
}
return RedisValue{Type: Array, Array: result}
})
// MSET command
server.RegisterCommandFunc("MSET", func(conn *Connection, cmd *Command) RedisValue {
if len(cmd.Args) < 2 || len(cmd.Args)%2 != 0 {
return RedisValue{Type: ErrorReply, Str: "ERR wrong number of arguments for 'mset' command"}
}
mu.Lock()
defer mu.Unlock()
for i := 0; i < len(cmd.Args); i += 2 {
key, value := cmd.Args[i], cmd.Args[i+1]
storage[key] = value
delete(expiration, key) // Clear any existing expiration
}
return RedisValue{Type: SimpleString, Str: "OK"}
})
// FLUSHDB command
server.RegisterCommandFunc("FLUSHDB", func(conn *Connection, cmd *Command) RedisValue {
mu.Lock()
defer mu.Unlock()
storage = make(map[string]string)
expiration = make(map[string]time.Time)
return RedisValue{Type: SimpleString, Str: "OK"}
})
// FLUSHALL command
server.RegisterCommandFunc("FLUSHALL", func(conn *Connection, cmd *Command) RedisValue {
mu.Lock()
defer mu.Unlock()
storage = make(map[string]string)
expiration = make(map[string]time.Time)
return RedisValue{Type: SimpleString, Str: "OK"}
})
// Start server in goroutine
go func() {
if err := server.Serve(); err != nil {
t.Logf("Server error: %v", err)
}
}()
// Wait for server to start
time.Sleep(100 * time.Millisecond)
// Create Redis client
client := redis.NewClient(&redis.Options{
Addr: fmt.Sprintf("localhost:%d", port),
Password: "", // no password
DB: 0, // default DB
DialTimeout: 5 * time.Second,
})
// Test connection
ctx := context.Background()
_, err = client.Ping(ctx).Result()
if err != nil {
t.Fatalf("Failed to connect to Redis server: %v", err)
}
cleanup := func() {
client.Close()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
server.Shutdown(ctx)
}
return server, client, cleanup
}
// Basic command tests
func TestBasicRedisCommands(t *testing.T) {
_, client, cleanup := startRedisServer(t)
defer cleanup()
ctx := context.Background()
t.Run("PING without message", func(t *testing.T) {
result, err := client.Ping(ctx).Result()
if err != nil {
t.Errorf("PING failed: %v", err)
}
if result != "PONG" {
t.Errorf("Expected PONG, got %s", result)
}
})
t.Run("ECHO command", func(t *testing.T) {
message := "Hello, Redis!"
result, err := client.Echo(ctx, message).Result()
if err != nil {
t.Errorf("ECHO failed: %v", err)
}
if result != message {
t.Errorf("Expected '%s', got '%s'", message, result)
}
})
}
// String operations tests
func TestStringOperations(t *testing.T) {
_, client, cleanup := startRedisServer(t)
defer cleanup()
ctx := context.Background()
t.Run("SET and GET basic", func(t *testing.T) {
key := "test:string"
value := "test value"
// SET
err := client.Set(ctx, key, value, 0).Err()
if err != nil {
t.Errorf("SET failed: %v", err)
}
// GET
result, err := client.Get(ctx, key).Result()
if err != nil {
t.Errorf("GET failed: %v", err)
}
if result != value {
t.Errorf("Expected '%s', got '%s'", value, result)
}
})
t.Run("GET non-existent key", func(t *testing.T) {
_, err := client.Get(ctx, "non-existent").Result()
if err != redis.Nil {
t.Errorf("Expected redis.Nil for non-existent key, got %v", err)
}
})
t.Run("SET and GET multiple keys", func(t *testing.T) {
testCases := map[string]string{
"key1": "value1",
"key2": "value2",
"key3": "value3",
}
// Set all keys
for key, value := range testCases {
err := client.Set(ctx, key, value, 0).Err()
if err != nil {
t.Errorf("SET %s failed: %v", key, err)
}
}
// Get and verify all keys
for key, expectedValue := range testCases {
result, err := client.Get(ctx, key).Result()
if err != nil {
t.Errorf("GET %s failed: %v", key, err)
}
if result != expectedValue {
t.Errorf("Key %s: expected '%s', got '%s'", key, expectedValue, result)
}
}
})
t.Run("SET overwrites existing key", func(t *testing.T) {
key := "overwrite:test"
// Set initial value
client.Set(ctx, key, "initial", 0)
// Overwrite with new value
err := client.Set(ctx, key, "overwritten", 0).Err()
if err != nil {
t.Errorf("SET overwrite failed: %v", err)
}
// Verify new value
result, err := client.Get(ctx, key).Result()
if err != nil {
t.Errorf("GET after overwrite failed: %v", err)
}
if result != "overwritten" {
t.Errorf("Expected 'overwritten', got '%s'", result)
}
})
}
// Key management tests
func TestKeyManagement(t *testing.T) {
_, client, cleanup := startRedisServer(t)
defer cleanup()
ctx := context.Background()
t.Run("EXISTS command", func(t *testing.T) {
key := "exists:test"
// Check non-existent key
count, err := client.Exists(ctx, key).Result()
if err != nil {
t.Errorf("EXISTS failed: %v", err)
}
if count != 0 {
t.Errorf("Expected 0 for non-existent key, got %d", count)
}
// Set key and check again
client.Set(ctx, key, "value", 0)
count, err = client.Exists(ctx, key).Result()
if err != nil {
t.Errorf("EXISTS failed: %v", err)
}
if count != 1 {
t.Errorf("Expected 1 for existing key, got %d", count)
}
// Check multiple keys
client.Set(ctx, "key1", "val1", 0)
client.Set(ctx, "key2", "val2", 0)
count, err = client.Exists(ctx, "key1", "key2", "non-existent").Result()
if err != nil {
t.Errorf("EXISTS multiple failed: %v", err)
}
if count != 2 {
t.Errorf("Expected 2 existing keys, got %d", count)
}
})
t.Run("DEL command", func(t *testing.T) {
// Setup test keys
keys := []string{"del:key1", "del:key2", "del:key3"}
for _, key := range keys {
client.Set(ctx, key, "value", 0)
}
// Delete single key
deleted, err := client.Del(ctx, keys[0]).Result()
if err != nil {
t.Errorf("DEL failed: %v", err)
}
if deleted != 1 {
t.Errorf("Expected 1 deleted key, got %d", deleted)
}
// Verify key is deleted
_, err = client.Get(ctx, keys[0]).Result()
if err != redis.Nil {
t.Errorf("Key should be deleted")
}
// Delete multiple keys
deleted, err = client.Del(ctx, keys[1], keys[2], "non-existent").Result()
if err != nil {
t.Errorf("DEL multiple failed: %v", err)
}
if deleted != 2 {
t.Errorf("Expected 2 deleted keys, got %d", deleted)
}
})
t.Run("TYPE command", func(t *testing.T) {
key := "type:test"
// Check type of non-existent key
keyType, err := client.Type(ctx, key).Result()
if err != nil {
t.Errorf("TYPE failed: %v", err)
}
if keyType != "none" {
t.Errorf("Expected 'none' for non-existent key, got '%s'", keyType)
}
// Set string and check type
client.Set(ctx, key, "string value", 0)
keyType, err = client.Type(ctx, key).Result()
if err != nil {
t.Errorf("TYPE failed: %v", err)
}
if keyType != "string" {
t.Errorf("Expected 'string' type, got '%s'", keyType)
}
})
t.Run("KEYS command", func(t *testing.T) {
// Clear database first
client.FlushDB(ctx)
// Setup test data
testKeys := []string{
"keys:test:1",
"keys:test:2",
"keys:other:1",
"different:key",
}
for _, key := range testKeys {
client.Set(ctx, key, "value", 0)
}
// Get all keys
keys, err := client.Keys(ctx, "*").Result()
if err != nil {
t.Errorf("KEYS * failed: %v", err)
}
if len(keys) != len(testKeys) {
t.Errorf("Expected %d keys, got %d", len(testKeys), len(keys))
}
})
}
// Numeric operations tests
func TestNumericOperations(t *testing.T) {
_, client, cleanup := startRedisServer(t)
defer cleanup()
ctx := context.Background()
t.Run("INCR operations", func(t *testing.T) {
key := "incr:counter"
// INCR on non-existent key
result, err := client.Incr(ctx, key).Result()
if err != nil {
t.Errorf("INCR failed: %v", err)
}
if result != 1 {
t.Errorf("Expected 1, got %d", result)
}
// INCR on existing key
result, err = client.Incr(ctx, key).Result()
if err != nil {
t.Errorf("INCR failed: %v", err)
}
if result != 2 {
t.Errorf("Expected 2, got %d", result)
}
// Verify final value
value, err := client.Get(ctx, key).Result()
if err != nil {
t.Errorf("GET failed: %v", err)
}
if value != "2" {
t.Errorf("Expected '2', got '%s'", value)
}
})
t.Run("INCRBY operations", func(t *testing.T) {
key := "incrby:score"
// INCRBY on non-existent key
result, err := client.IncrBy(ctx, key, 10).Result()
if err != nil {
t.Errorf("INCRBY failed: %v", err)
}
if result != 10 {
t.Errorf("Expected 10, got %d", result)
}
// INCRBY on existing key
result, err = client.IncrBy(ctx, key, 25).Result()
if err != nil {
t.Errorf("INCRBY failed: %v", err)
}
if result != 35 {
t.Errorf("Expected 35, got %d", result)
}
})
t.Run("DECR operations", func(t *testing.T) {
key := "decr:countdown"
// Set initial value
client.Set(ctx, key, "10", 0)
// DECR operation
result, err := client.Decr(ctx, key).Result()
if err != nil {
t.Errorf("DECR failed: %v", err)
}
if result != 9 {
t.Errorf("Expected 9, got %d", result)
}
// DECR on non-existent key
newKey := "decr:new"
result, err = client.Decr(ctx, newKey).Result()
if err != nil {
t.Errorf("DECR on new key failed: %v", err)
}
if result != -1 {
t.Errorf("Expected -1, got %d", result)
}
})
t.Run("DECRBY operations", func(t *testing.T) {
key := "decrby:points"
// Set initial value
client.Set(ctx, key, "100", 0)
// DECRBY operation
result, err := client.DecrBy(ctx, key, 30).Result()
if err != nil {
t.Errorf("DECRBY failed: %v", err)
}
if result != 70 {
t.Errorf("Expected 70, got %d", result)
}
// DECRBY on non-existent key
newKey := "decrby:new"
result, err = client.DecrBy(ctx, newKey, 50).Result()
if err != nil {
t.Errorf("DECRBY on new key failed: %v", err)
}
if result != -50 {
t.Errorf("Expected -50, got %d", result)
}
})
t.Run("Mixed numeric operations", func(t *testing.T) {
key := "mixed:calc"
// Start from 0
client.Set(ctx, key, "0", 0)
// INCRBY 10
result, _ := client.IncrBy(ctx, key, 10).Result()
if result != 10 {
t.Errorf("Expected 10, got %d", result)
}
// INCR by 1
result, _ = client.Incr(ctx, key).Result()
if result != 11 {
t.Errorf("Expected 11, got %d", result)
}
// DECRBY 5
result, _ = client.DecrBy(ctx, key, 5).Result()
if result != 6 {
t.Errorf("Expected 6, got %d", result)
}
// DECR by 1
result, _ = client.Decr(ctx, key).Result()
if result != 5 {
t.Errorf("Expected 5, got %d", result)
}
})
}
// Expiration tests
func TestExpirationOperations(t *testing.T) {
_, client, cleanup := startRedisServer(t)
defer cleanup()
ctx := context.Background()
t.Run("TTL on non-existent key", func(t *testing.T) {
ttl, err := client.TTL(ctx, "non-existent").Result()
if err != nil {
t.Errorf("TTL failed: %v", err)
}
// Our server returns -2 for non-existent keys (in seconds)
// go-redis converts this to nanoseconds, so -2 seconds = -2000000000 nanoseconds
if ttl != -2*time.Nanosecond {
t.Errorf("Expected -2ns for non-existent key, got %v", ttl)
}
})
t.Run("TTL on persistent key", func(t *testing.T) {
key := "persistent:key"
client.Set(ctx, key, "value", 0)
ttl, err := client.TTL(ctx, key).Result()
if err != nil {
t.Errorf("TTL failed: %v", err)
}
// Our server returns -1 for persistent keys (in seconds)
// go-redis converts this to nanoseconds
if ttl != -1*time.Nanosecond {
t.Errorf("Expected -1ns for persistent key, got %v", ttl)
}
})
t.Run("EXPIRE operations", func(t *testing.T) {
key := "expire:test"
// EXPIRE on non-existent key
success, err := client.Expire(ctx, key, 60*time.Second).Result()
if err != nil {
t.Errorf("EXPIRE failed: %v", err)
}
if success {
t.Errorf("Expected false for non-existent key")
}
// Set key and expire it
client.Set(ctx, key, "value", 0)
success, err = client.Expire(ctx, key, 30*time.Second).Result()
if err != nil {
t.Errorf("EXPIRE failed: %v", err)
}
if !success {
t.Errorf("Expected true for successful expiration")
}
// Check TTL is set (should be between 1 and 30 seconds)
ttl, err := client.TTL(ctx, key).Result()
if err != nil {
t.Errorf("TTL failed: %v", err)
}
ttlSeconds := int64(ttl.Seconds())
if ttlSeconds <= 0 || ttlSeconds > 30 {
t.Errorf("Expected TTL between 1-30 seconds, got %v (%d seconds)", ttl, ttlSeconds)
}
// Verify key still exists
value, err := client.Get(ctx, key).Result()
if err != nil {
t.Errorf("GET failed: %v", err)
}
if value != "value" {
t.Errorf("Expected 'value', got '%s'", value)
}
})
t.Run("Key expiration behavior", func(t *testing.T) {
key := "expiring:key"
// Set key with short expiration
client.Set(ctx, key, "value", 0)
client.Expire(ctx, key, 1*time.Second)
// Verify key exists immediately
exists, err := client.Exists(ctx, key).Result()
if err != nil {
t.Errorf("EXISTS failed: %v", err)
}
if exists != 1 {
t.Errorf("Key should exist immediately after setting expiration")
}
// Wait for expiration
time.Sleep(1500 * time.Millisecond)
// Try to get the expired key
_, err = client.Get(ctx, key).Result()
if err != redis.Nil {
t.Error("Expected redis.Nil for expired key")
}
// Verify key is cleaned up
exists, err = client.Exists(ctx, key).Result()
if err != nil {
t.Errorf("EXISTS failed: %v", err)
}
if exists != 0 {
t.Errorf("Expired key should not exist")
}
})
}
// Advanced operations tests
func TestAdvancedOperations(t *testing.T) {
_, client, cleanup := startRedisServer(t)
defer cleanup()
ctx := context.Background()
t.Run("SETNX operations", func(t *testing.T) {
key := "setnx:test"
// SETNX on non-existent key
success, err := client.SetNX(ctx, key, "value1", 0).Result()
if err != nil {
t.Errorf("SETNX failed: %v", err)
}
if !success {
t.Errorf("Expected true for new key")
}
// Verify value was set
value, err := client.Get(ctx, key).Result()
if err != nil {
t.Errorf("GET failed: %v", err)
}