-
Notifications
You must be signed in to change notification settings - Fork 1
/
uuidv8_test.go
794 lines (684 loc) · 22.1 KB
/
uuidv8_test.go
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
package uuidv8_test
import (
"encoding/json"
"sync"
"testing"
"time"
"github.com/DATA-DOG/go-sqlmock"
"github.com/ash3in/uuidv8"
)
func TestNew_DefaultBehavior(t *testing.T) {
t.Run("Generate UUIDv8 with default settings", func(t *testing.T) {
uuid, err := uuidv8.New()
if err != nil {
t.Fatalf("New() failed: %v", err)
}
// Check if the UUID is valid
if !uuidv8.IsValidUUIDv8(uuid) {
t.Errorf("New() generated an invalid UUID: %s", uuid)
}
})
}
func TestNewUUIDv8(t *testing.T) {
node := []byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}
timestamp := uint64(1633024800000000000) // Fixed timestamp for deterministic tests
clockSeq := uint16(0)
tests := []struct {
timestampBits int
expectedErr bool
description string
}{
{uuidv8.TimestampBits32, false, "32-bit timestamp"},
{uuidv8.TimestampBits48, false, "48-bit timestamp"},
{uuidv8.TimestampBits60, false, "60-bit timestamp"},
{100, true, "Invalid timestamp bit size"},
}
for _, test := range tests {
t.Run(test.description, func(t *testing.T) {
uuid, err := uuidv8.NewWithParams(timestamp, clockSeq, node, test.timestampBits)
if (err != nil) != test.expectedErr {
t.Errorf("Expected error: %v, got: %v", test.expectedErr, err)
}
if err == nil && uuid == "" {
t.Error("Generated UUID is empty")
}
})
}
}
func TestNewUUIDv8_NodeValidation(t *testing.T) {
invalidNodes := [][]byte{
nil, // Nil node
{}, // Empty node
{0x01, 0x02}, // Less than 6 bytes
{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}, // More than 6 bytes
}
for _, node := range invalidNodes {
t.Run("Invalid node length", func(t *testing.T) {
_, err := uuidv8.NewWithParams(1633024800, 0, node, uuidv8.TimestampBits48)
if err == nil {
t.Errorf("Expected error for invalid node: %v", node)
}
})
}
}
func TestIsValidUUIDv8(t *testing.T) {
tests := []struct {
uuid string
shouldPass bool
description string
}{
{"00000000-0000-0000-0000-000000000000", false, "All-zero UUIDv8"},
{"9a3d4049-0e2c-7080-0102-030405060000", false, "Incorrect version"},
{"9a3d4049-0e2c-9080-0102-030405060000", false, "Incorrect variant"},
{"invalid-uuid", false, "Invalid UUID format"},
}
for _, test := range tests {
t.Run(test.description, func(t *testing.T) {
valid := uuidv8.IsValidUUIDv8(test.uuid)
if valid != test.shouldPass {
t.Errorf("Validation mismatch for UUIDv8 %s: expected %v, got %v", test.uuid, test.shouldPass, valid)
}
})
}
}
func TestFromString(t *testing.T) {
node := []byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}
timestamp := uint64(1633024800000000000) // Fixed timestamp
clockSeq := uint16(0)
uuid, err := uuidv8.NewWithParams(timestamp, clockSeq, node, uuidv8.TimestampBits48)
if err != nil {
t.Fatalf("NewWithParams failed: %v", err)
}
parsed, err := uuidv8.FromString(uuid)
if err != nil {
t.Errorf("FromString failed: %v", err)
}
if parsed == nil {
t.Error("FromString returned nil for a valid UUID")
}
// Validate parsed fields (adjust expectations based on bit shifts in encoding)
expectedTimestamp := timestamp & ((1 << 48) - 1) // Mask to match the 48 bits encoded
if parsed.Timestamp != expectedTimestamp {
t.Errorf("Parsed timestamp mismatch: expected %d, got %d", expectedTimestamp, parsed.Timestamp)
}
if len(parsed.Node) != 6 {
t.Errorf("Parsed node length mismatch: expected 6, got %d", len(parsed.Node))
}
_, err = uuidv8.FromString("invalid-uuid")
if err == nil {
t.Error("FromString failed: did not return an error for an invalid UUID")
}
}
func TestFromStringOrNil(t *testing.T) {
// Valid UUIDv8 string
validUUID := "9a3d4049-0e2c-8080-0102-030405060000"
parsedUUID := uuidv8.FromStringOrNil(validUUID)
if parsedUUID == nil {
t.Errorf("FromStringOrNil failed: returned nil for a valid UUID %s", validUUID)
} else {
// Validate parsed fields
if parsedUUID.Timestamp == 0 {
t.Errorf("FromStringOrNil failed: Timestamp is not parsed correctly for UUID %s", validUUID)
}
if len(parsedUUID.Node) != 6 {
t.Errorf("FromStringOrNil failed: Node length is incorrect for UUID %s", validUUID)
}
}
// Invalid UUIDv8 string
invalidUUID := "invalid-uuid"
parsedInvalid := uuidv8.FromStringOrNil(invalidUUID)
if parsedInvalid != nil {
t.Errorf("FromStringOrNil failed: returned a non-nil object for an invalid UUID %s", invalidUUID)
}
// All-zero UUID
allZeroUUID := "00000000-0000-0000-0000-000000000000"
parsedZero := uuidv8.FromStringOrNil(allZeroUUID)
if parsedZero != nil {
t.Errorf("FromStringOrNil failed: returned a non-nil object for an all-zero UUID %s", allZeroUUID)
}
}
func TestConcurrencySafety(t *testing.T) {
node := []byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}
const concurrencyLevel = 100
var wg sync.WaitGroup
uuidSet := sync.Map{}
start := time.Now()
for i := 0; i < concurrencyLevel; i++ {
wg.Add(1)
go func(clockSeq uint16, index int) {
defer wg.Done()
timestamp := uint64(time.Now().UnixNano()) + uint64(index)
uuid, err := uuidv8.NewWithParams(timestamp, clockSeq, node, uuidv8.TimestampBits48)
if err != nil {
t.Errorf("Failed to generate UUIDv8 in concurrent environment: %v", err)
}
uuidSet.Store(uuid, true)
}(uint16(i), i)
}
wg.Wait()
// Measure time taken
elapsed := time.Since(start)
t.Logf("Concurrency test completed in %s", elapsed)
count := 0
uuidSet.Range(func(_, _ interface{}) bool {
count++
return true
})
if count != concurrencyLevel {
t.Errorf("Expected %d unique UUIDs, but got %d", concurrencyLevel, count)
}
}
func TestEdgeCases(t *testing.T) {
node := []byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}
t.Run("Minimum timestamp and clock sequence", func(t *testing.T) {
uuid, err := uuidv8.NewWithParams(0, 0, node, uuidv8.TimestampBits48)
if err != nil || uuid == "" {
t.Error("Failed to generate UUID with minimal timestamp and clock sequence")
}
})
t.Run("Maximum timestamp and clock sequence", func(t *testing.T) {
maxTimestamp := uint64(1<<48 - 1)
maxClockSeq := uint16(1<<12 - 1)
uuid, err := uuidv8.NewWithParams(maxTimestamp, maxClockSeq, node, uuidv8.TimestampBits48)
if err != nil || uuid == "" {
t.Error("Failed to generate UUID with maximum timestamp and clock sequence")
}
if !uuidv8.IsValidUUIDv8(uuid) {
t.Errorf("IsValidUUIDv8 failed: UUID %s is invalid", uuid)
}
})
}
func TestMarshalJSON(t *testing.T) {
node := []byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}
timestamp := uint64(1633024800000000000) // Fixed timestamp
clockSeq := uint16(0)
// Generate a valid UUIDv8
uuidStr, err := uuidv8.NewWithParams(timestamp, clockSeq, node, uuidv8.TimestampBits48)
if err != nil {
t.Fatalf("Failed to generate UUIDv8: %v", err)
}
parsedUUID, err := uuidv8.FromString(uuidStr)
if err != nil {
t.Fatalf("Failed to parse UUIDv8: %v", err)
}
// Marshal to JSON
jsonData, err := json.Marshal(parsedUUID)
if err != nil {
t.Errorf("Failed to marshal UUIDv8 to JSON: %v", err)
}
// Validate JSON output
expectedJSON := `"` + uuidStr + `"`
if string(jsonData) != expectedJSON {
t.Errorf("JSON output mismatch: expected %s, got %s", expectedJSON, string(jsonData))
}
}
func TestMarshalInvalidUUID(t *testing.T) {
// Invalid UUID with incorrect clock sequence and node length
invalidUUIDs := []*uuidv8.UUIDv8{
{Timestamp: 0, ClockSeq: 100, Node: []byte{0x01, 0x02, 0x03}}, // Invalid node length
{Timestamp: 123, ClockSeq: 0x1000, Node: []byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, // Invalid clock sequence
{Timestamp: 0, ClockSeq: 0, Node: []byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, // Invalid timestamp
}
for _, invalidUUID := range invalidUUIDs {
_, err := json.Marshal(invalidUUID)
if err == nil {
t.Errorf("Expected error when marshalling invalid UUIDv8: %+v", invalidUUID)
}
}
}
func TestMarshalValidUUID(t *testing.T) {
// Valid UUID
validUUID := &uuidv8.UUIDv8{
Timestamp: 123456789,
ClockSeq: 0x0800,
Node: []byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06},
}
data, err := json.Marshal(validUUID)
if err != nil {
t.Errorf("Failed to marshal valid UUIDv8: %v", err)
}
// Dynamically calculate the expected string
expected := uuidv8.ToString(validUUID)
if string(data) != `"`+expected+`"` {
t.Errorf("Expected JSON %s, got %s", `"`+expected+`"`, string(data))
}
}
func TestUnmarshalJSON(t *testing.T) {
node := []byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}
timestamp := uint64(1633024800000000000) // Fixed timestamp
clockSeq := uint16(0)
// Generate a valid UUIDv8
uuidStr, err := uuidv8.NewWithParams(timestamp, clockSeq, node, uuidv8.TimestampBits48)
if err != nil {
t.Fatalf("Failed to generate UUIDv8: %v", err)
}
// JSON string representing the UUID
jsonData := `"` + uuidStr + `"`
// Unmarshal JSON
var parsedUUID uuidv8.UUIDv8
err = json.Unmarshal([]byte(jsonData), &parsedUUID)
if err != nil {
t.Errorf("Failed to unmarshal JSON to UUIDv8: %v", err)
}
// Validate parsed fields
expectedUUID, _ := uuidv8.FromString(uuidStr)
if parsedUUID.Timestamp != expectedUUID.Timestamp {
t.Errorf("Timestamp mismatch: expected %d, got %d", expectedUUID.Timestamp, parsedUUID.Timestamp)
}
if parsedUUID.ClockSeq != expectedUUID.ClockSeq {
t.Errorf("ClockSeq mismatch: expected %d, got %d", expectedUUID.ClockSeq, parsedUUID.ClockSeq)
}
if len(parsedUUID.Node) != len(expectedUUID.Node) {
t.Errorf("Node length mismatch: expected %d, got %d", len(expectedUUID.Node), len(parsedUUID.Node))
}
for i := range parsedUUID.Node {
if parsedUUID.Node[i] != expectedUUID.Node[i] {
t.Errorf("Node byte mismatch at index %d: expected %x, got %x", i, expectedUUID.Node[i], parsedUUID.Node[i])
}
}
}
func TestUnmarshalInvalidJSON(t *testing.T) {
// Invalid JSON input
invalidJSONs := []string{
`"invalid-uuid"`, // Invalid UUID string
`"0193bde4-a9fa-77eb-a304-6cf8530ece78"`, // A UUIDv7
`"12345"`, // Incorrect length
`"00000000-0000-0000-0000-000000000000"`, // All-zero UUID
}
for _, jsonData := range invalidJSONs {
var parsedUUID uuidv8.UUIDv8
err := json.Unmarshal([]byte(jsonData), &parsedUUID)
if err == nil {
t.Errorf("Expected error for invalid JSON input: %s", jsonData)
}
}
}
func TestNew_Uniqueness(t *testing.T) {
const numUUIDs = 1000
uuidSet := make(map[string]struct{})
for i := 0; i < numUUIDs; i++ {
uuid, err := uuidv8.New()
if err != nil {
t.Fatalf("New() failed: %v", err)
}
if _, exists := uuidSet[uuid]; exists {
t.Errorf("Duplicate UUID generated: %s", uuid)
}
uuidSet[uuid] = struct{}{}
}
if len(uuidSet) != numUUIDs {
t.Errorf("Expected %d unique UUIDs, but got %d", numUUIDs, len(uuidSet))
}
}
func TestNew_ConcurrencySafety(t *testing.T) {
const concurrencyLevel = 100
var wg sync.WaitGroup
uuidSet := sync.Map{}
for i := 0; i < concurrencyLevel; i++ {
wg.Add(1)
go func() {
defer wg.Done()
uuid, err := uuidv8.New()
if err != nil {
t.Errorf("New() failed in concurrent environment: %v", err)
}
uuidSet.Store(uuid, true)
}()
}
wg.Wait()
// Verify uniqueness
count := 0
uuidSet.Range(func(_, _ interface{}) bool {
count++
return true
})
if count != concurrencyLevel {
t.Errorf("Expected %d unique UUIDs, but got %d", concurrencyLevel, count)
}
}
func TestNew_IntegrationWithParsing(t *testing.T) {
uuid, err := uuidv8.New()
if err != nil {
t.Fatalf("New() failed: %v", err)
}
parsed, err := uuidv8.FromString(uuid)
if err != nil {
t.Errorf("FromString failed to parse UUID generated by New(): %v", err)
}
if parsed == nil {
t.Error("Parsed UUID is nil")
}
}
func TestNew_EdgeCases(t *testing.T) {
t.Run("Minimal possible timestamp and clock sequence", func(t *testing.T) {
uuid, err := uuidv8.New()
if err != nil {
t.Fatalf("New() failed: %v", err)
}
parsed, _ := uuidv8.FromString(uuid)
if parsed.Timestamp == 0 || parsed.ClockSeq == 0 {
t.Errorf("New() generated UUID with invalid minimal values: %s", uuid)
}
})
}
func TestNew_JSONSerializationIntegration(t *testing.T) {
uuid, err := uuidv8.New()
if err != nil {
t.Fatalf("New() failed: %v", err)
}
// Serialize to JSON
jsonData, err := json.Marshal(uuid)
if err != nil {
t.Errorf("Failed to marshal UUID to JSON: %v", err)
}
// Deserialize from JSON
var parsedUUID uuidv8.UUIDv8
err = json.Unmarshal(jsonData, &parsedUUID)
if err != nil {
t.Errorf("Failed to unmarshal JSON to UUIDv8: %v", err)
}
// Ensure the deserialized UUID matches the original
if uuidv8.ToString(&parsedUUID) != uuid {
t.Errorf("Mismatch between original and deserialized UUID: original %s, deserialized %s", uuid, uuidv8.ToString(&parsedUUID))
}
}
func TestEncodeTimestamp_InvalidTimestampBits(t *testing.T) {
invalidBits := []int{0, 16, 64} // Unsupported timestamp bit sizes
for _, bits := range invalidBits {
t.Run("Invalid timestamp bits", func(t *testing.T) {
node := []byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}
_, err := uuidv8.NewWithParams(1633024800, 0, node, bits)
if err == nil {
t.Errorf("Expected error for invalid timestamp bits: %d", bits)
}
})
}
}
func TestEncodeTimestamp_BoundaryValues(t *testing.T) {
boundaryTimestamps := []struct {
timestamp uint64
bits int
}{
{timestamp: 0, bits: uuidv8.TimestampBits32}, // Minimal 32-bit
{timestamp: (1 << 32) - 1, bits: uuidv8.TimestampBits32},
{timestamp: 0, bits: uuidv8.TimestampBits48}, // Minimal 48-bit
{timestamp: (1 << 48) - 1, bits: uuidv8.TimestampBits48},
{timestamp: 0, bits: uuidv8.TimestampBits60}, // Minimal 60-bit
{timestamp: (1 << 60) - 1, bits: uuidv8.TimestampBits60},
}
for _, test := range boundaryTimestamps {
t.Run("Boundary timestamp", func(t *testing.T) {
node := []byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}
uuid, err := uuidv8.NewWithParams(test.timestamp, 0, node, test.bits)
if err != nil {
t.Errorf("Failed to generate UUID with timestamp %d and bits %d: %v", test.timestamp, test.bits, err)
}
if !uuidv8.IsValidUUIDv8(uuid) {
t.Errorf("Generated UUID is invalid: %s", uuid)
}
})
}
}
func TestParseUUID_InvalidFormats(t *testing.T) {
invalidUUIDs := []string{
"1234", // Too short
"gibberish-not-a-uuid", // Invalid characters
}
for _, uuid := range invalidUUIDs {
t.Run("Invalid format", func(t *testing.T) {
parsed := uuidv8.FromStringOrNil(uuid)
if parsed != nil {
t.Errorf("Expected nil for invalid UUID format: %s", uuid)
}
})
}
}
func TestFromString_ErrorScenarios(t *testing.T) {
t.Run("Invalid UUID string", func(t *testing.T) {
_, err := uuidv8.FromString("not-a-uuid")
if err == nil {
t.Error("Expected error for invalid UUID string")
}
})
}
func TestToString_EmptyUUID(t *testing.T) {
emptyUUID := &uuidv8.UUIDv8{} // Uninitialized UUIDv8
if result := uuidv8.ToString(emptyUUID); result != "00000000-0000-8080-0000-000000000000" {
t.Errorf("Expected empty string for uninitialized UUID, got %s", result)
}
}
func TestMarshalJSON_ErrorCases(t *testing.T) {
invalidUUID := &uuidv8.UUIDv8{
Timestamp: 0,
ClockSeq: 0x1000, // Invalid clock sequence (exceeds 12 bits)
Node: []byte{0x01, 0x02, 0x03}, // Invalid node length
}
_, err := invalidUUID.MarshalJSON()
if err == nil {
t.Errorf("Expected error for invalid UUID in MarshalJSON")
}
}
func TestUnmarshalJSON_ErrorCases(t *testing.T) {
invalidJSON := []byte(`"not-a-uuid"`)
var uuid uuidv8.UUIDv8
if err := uuid.UnmarshalJSON(invalidJSON); err == nil {
t.Error("Expected error for invalid JSON input")
}
}
func TestNewWithParams_MaxValues(t *testing.T) {
node := []byte{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}
timestamp := uint64(1<<60 - 1)
clockSeq := uint16(1<<12 - 1)
uuid, err := uuidv8.NewWithParams(timestamp, clockSeq, node, uuidv8.TimestampBits60)
if err != nil {
t.Fatalf("Failed to generate UUID with max values: %v", err)
}
if !uuidv8.IsValidUUIDv8(uuid) {
t.Errorf("Generated UUID with max values is invalid: %s", uuid)
}
}
func TestUUIDv8_Value(t *testing.T) {
tests := []struct {
name string
uuid *uuidv8.UUIDv8
mockSetup func(mock sqlmock.Sqlmock, uuidStr string)
expectError bool
}{
{
name: "Valid UUIDv8",
uuid: &uuidv8.UUIDv8{
Timestamp: 123456789,
ClockSeq: 0x0800,
Node: []byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06},
},
mockSetup: func(mock sqlmock.Sqlmock, uuidStr string) {
mock.ExpectExec("INSERT INTO items").
WithArgs(uuidStr).
WillReturnResult(sqlmock.NewResult(1, 1))
},
expectError: false,
},
{
name: "Invalid Node Length",
uuid: &uuidv8.UUIDv8{
Timestamp: 123456789,
ClockSeq: 0x0800,
Node: []byte{0x01, 0x02},
},
mockSetup: func(mock sqlmock.Sqlmock, uuidStr string) {},
expectError: true,
},
{
name: "Nil UUIDv8",
uuid: nil,
mockSetup: func(mock sqlmock.Sqlmock, uuidStr string) {
mock.ExpectExec("INSERT INTO items").
WithArgs(nil).
WillReturnResult(sqlmock.NewResult(1, 1))
},
expectError: false,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
// Mock database
db, mock, err := sqlmock.New()
if err != nil {
t.Fatalf("Failed to create mock database: %v", err)
}
defer db.Close()
var uuidStr string
if test.uuid != nil && len(test.uuid.Node) == 6 {
uuidStr = uuidv8.ToString(test.uuid)
}
test.mockSetup(mock, uuidStr)
_, err = db.Exec("INSERT INTO items (uuid) VALUES (?)", test.uuid)
if (err != nil) != test.expectError {
t.Errorf("Unexpected error status: got %v, want error=%v", err, test.expectError)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("Unmet expectations: %v", err)
}
})
}
}
func TestUUIDv8_Scan(t *testing.T) {
// Mock database
db, mock, err := sqlmock.New()
if err != nil {
t.Fatalf("Failed to create mock database: %v", err)
}
defer db.Close()
uuidStr := "9a3d4049-0e2c-8080-0102-030405060000"
rows := sqlmock.NewRows([]string{"uuid"}).AddRow(uuidStr)
mock.ExpectQuery("SELECT uuid FROM items").WillReturnRows(rows)
var uuid uuidv8.UUIDv8
err = db.QueryRow("SELECT uuid FROM items").Scan(&uuid)
if err != nil {
t.Errorf("Failed to scan mock database value: %v", err)
}
if uuidv8.ToString(&uuid) != uuidStr {
t.Errorf("Expected UUIDv8 %s, got %s", uuidStr, uuidv8.ToString(&uuid))
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("Unmet expectations: %v", err)
}
}
func TestUUIDv8_Value_EdgeCases(t *testing.T) {
tests := []struct {
name string
uuid *uuidv8.UUIDv8
expected interface{}
}{
{"Valid UUIDv8", &uuidv8.UUIDv8{
Timestamp: 123456789,
ClockSeq: 0x0800,
Node: []byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06},
}, "0000075b-cd15-8880-0102-030405060000"},
{"Nil UUIDv8", nil, nil},
{"Invalid Node Length", &uuidv8.UUIDv8{
Timestamp: 123456789,
ClockSeq: 0x0800,
Node: []byte{0x01, 0x02},
}, nil},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
value, err := test.uuid.Value()
if err != nil && test.expected != nil {
t.Errorf("Unexpected error: %v", err)
}
if value != test.expected {
t.Errorf("Expected %v, got %v", test.expected, value)
}
})
}
}
func TestUUIDv8_Scan_EdgeCases(t *testing.T) {
tests := []struct {
name string
input interface{}
expectError bool
}{
{"Valid String UUID", "0000075b-cd15-8880-0102-030405060000", false},
{"Valid Byte UUID", []byte("9a3d4049-0e2c-8080-0102-030405060000"), false},
{"Invalid String Format", "invalid-uuid", true},
{"Invalid Type", 12345, true},
{"Empty String", "", true},
{"Empty Bytes", []byte{}, true},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
var uuid uuidv8.UUIDv8
err := uuid.Scan(test.input)
if (err != nil) != test.expectError {
t.Errorf("Unexpected error status: got %v, want error=%v", err, test.expectError)
}
})
}
}
func TestFromString_InvalidInputs(t *testing.T) {
tests := []string{
"123", // Too short
"123e4567e89b12d3a4564266141740000000", // Too long
"123e4567e89b12d3a45642661417400g", // Invalid character
"123e-4567-e89b-12d3-a456-426614174000", // Misplaced dashes
"123e4567-e89b-12d3-a456-426614174000-", // Extra dash at the end
"--123e4567-e89b-12d3-a456-426614174000", // Extra dash at the start
"123e4567-e89b-12d3-a456-42-6614174000", // Randomly placed dash
"------------------------------------", // 36 dashes
"9a3d4049-0e2c-8080-0102-030405060000", // Valid UUID with dashes
}
for _, input := range tests {
t.Run("Testing UUID: "+input, func(t *testing.T) {
_, err := uuidv8.FromString(input)
// The last case is valid; others should fail
if input == "9a3d4049-0e2c-8080-0102-030405060000" {
if err != nil {
t.Errorf("Expected valid UUID but got error for input: %s", input)
}
} else {
if err == nil {
t.Errorf("Expected error, got nil for input: %s", input)
}
}
})
}
}
func TestFromStringOrNil_InvalidInputs(t *testing.T) {
tests := []string{
"123", // Too short
"123e4567e89b12d3a4564266141740000000", // Too long
"123e4567e89b12d3a45642661417400g", // Invalid character
"", // Empty string
"123e4567-e89b-12d3-a456-426614174000-", // Extra dash at the end
"--123e4567-e89b-12d3-a456-426614174000", // Extra dash at the start
"123e4567-e89b-12d3-a456-42-6614174000", // Randomly placed dash
}
for _, input := range tests {
t.Run("Invalid UUID "+input, func(t *testing.T) {
result := uuidv8.FromStringOrNil(input)
if result != nil {
t.Errorf("Expected nil for input: %s, got %v", input, result)
}
})
}
}
func TestIsValidUUIDv8_InvalidUUIDs(t *testing.T) {
invalidUUIDs := []string{
"123", // Too short
"123e4567e89b12d3a4564266141740000000", // Too long
"123e4567e89b12d3a45642661417400g", // Invalid character
"", // Empty string
"123e4567-e89b-12d3-a456-426614174000-", // Extra dash at the end
"--123e4567-e89b-12d3-a456-426614174000", // Extra dash at the start
"123e4567-e89b-12d3-a456-42-6614174000", // Randomly placed dash
}
for _, uuid := range invalidUUIDs {
t.Run("Invalid UUID "+uuid, func(t *testing.T) {
if uuidv8.IsValidUUIDv8(uuid) {
t.Errorf("Expected UUID %s to be invalid", uuid)
}
})
}
}