This repository was archived by the owner on Feb 5, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrandomizer_test.go
More file actions
718 lines (648 loc) · 25.6 KB
/
randomizer_test.go
File metadata and controls
718 lines (648 loc) · 25.6 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
package fastrand_test
import (
"bytes"
"regexp"
"strings"
"testing"
"github.com/SyNdicateFoundation/fastrand"
"net"
)
func checkCharset(tb testing.TB, b []byte, charset []byte) {
tb.Helper()
for i, char := range b {
if !bytes.Contains(charset, []byte{char}) {
tb.Errorf("Generated byte '%c' (0x%02X) at index %d not in expected charset %q", char, char, i, charset)
}
}
}
var emailUserPartRegex = regexp.MustCompile(`^[a-zA-Z0-9._%+-]+@`)
var emailDomainRegex = regexp.MustCompile(`@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`)
func checkEmailFormat(tb testing.TB, email []byte) {
tb.Helper()
emailStr := string(email)
if !emailUserPartRegex.Match(email) {
tb.Errorf("Generated email %q does not start with expected user format (...@)", emailStr)
}
if !emailDomainRegex.Match(email) {
tb.Errorf("Generated email %q does not end with expected domain format (@domain.tld)", emailStr)
}
parts := bytes.SplitN(email, []byte("@"), 2)
if len(parts) != 2 {
tb.Errorf("Email %q could not be split correctly on '@'", emailStr)
return
}
if len(fastrand.SafeMailProviders) > 0 {
found := false
domain := string(parts[1])
for _, provider := range fastrand.SafeMailProviders {
if domain == provider {
found = true
break
}
}
if !found {
tb.Errorf("Email domain %q not found in fastrand.SafeMailProviders list: %v", domain, fastrand.SafeMailProviders)
}
}
}
var uuidRegex = regexp.MustCompile(`^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$`)
func checkUUIDFormat(tb testing.TB, uuid []byte) {
tb.Helper()
if !uuidRegex.Match(uuid) {
tb.Errorf("Generated UUID %q does not match V4 format", uuid)
}
}
func checkIPv4Format(tb testing.TB, ipBytes []byte) {
tb.Helper()
ipStr := string(ipBytes)
ip := net.ParseIP(ipStr)
if ip == nil || ip.To4() == nil || strings.Contains(ipStr, ":") {
tb.Errorf("Generated IP %q is not a valid IPv4 address", ipStr)
}
}
func checkIPv6Format(tb testing.TB, ipBytes []byte) {
tb.Helper()
ipStr := string(ipBytes)
ip := net.ParseIP(ipStr)
if ip == nil || ip.To4() != nil || !strings.Contains(ipStr, ":") {
tb.Errorf("Generated IP %q is not a valid IPv6 address", ipStr)
}
}
var hexRegex = regexp.MustCompile(`^[a-f0-9]*$`)
func checkHexFormat(tb testing.TB, hexBytes []byte) {
tb.Helper()
if !hexRegex.Match(hexBytes) {
tb.Errorf("Generated hex %q contains non-hex characters", hexBytes)
}
if len(hexBytes)%2 != 0 {
tb.Errorf("Generated hex %q has an odd number of characters (%d)", hexBytes, len(hexBytes))
}
}
var findPlaceholderRegex = regexp.MustCompile(
`\{RAND(?:OM)?[^}]*\}` + `|` +
`%7BRAND(?:OM)?.*?%7D` + `|` +
`{RAND(?:OM)?.*?}`,
)
func TestRandomizer(t *testing.T) {
testCases := []struct {
name string
input string
expectedLen map[string]int
checkFunc map[string]func(testing.TB, []byte)
}{
{
name: "No Placeholders",
input: "Hello World",
expectedLen: map[string]int{},
},
{
name: "Default Random",
input: "Data: {RAND}",
expectedLen: map[string]int{"{RAND}": 16},
checkFunc: map[string]func(testing.TB, []byte){"{RAND}": func(tb testing.TB, b []byte) { checkCharset(tb, b, fastrand.CharsAll) }},
},
{
name: "Default Random Optional OM",
input: "Data: {RANDOM}",
expectedLen: map[string]int{"{RANDOM}": 16},
checkFunc: map[string]func(testing.TB, []byte){"{RANDOM}": func(tb testing.TB, b []byte) { checkCharset(tb, b, fastrand.CharsAll) }},
},
{
name: "Custom Length",
input: "Key: {RAND;8}",
expectedLen: map[string]int{"{RAND;8}": 8},
checkFunc: map[string]func(testing.TB, []byte){"{RAND;8}": func(tb testing.TB, b []byte) { checkCharset(tb, b, fastrand.CharsAll) }},
},
{
name: "Alphabet Lower",
input: "{RAND;10;ABL}",
expectedLen: map[string]int{"{RAND;10;ABL}": 10},
checkFunc: map[string]func(testing.TB, []byte){"{RAND;10;ABL}": func(tb testing.TB, b []byte) { checkCharset(tb, b, fastrand.CharsAlphabetLower) }},
},
{
name: "Alphabet Upper",
input: "Prefix-{RANDOM;5;ABU}-Suffix}",
expectedLen: map[string]int{"{RANDOM;5;ABU}": 5},
checkFunc: map[string]func(testing.TB, []byte){"{RANDOM;5;ABU}": func(tb testing.TB, b []byte) { checkCharset(tb, b, fastrand.CharsAlphabetUpper) }},
},
{
name: "Alphabet Mixed",
input: "{RAND;12;ABR}",
expectedLen: map[string]int{"{RAND;12;ABR}": 12},
checkFunc: map[string]func(testing.TB, []byte){"{RAND;12;ABR}": func(tb testing.TB, b []byte) { checkCharset(tb, b, fastrand.CharsAlphabet) }},
},
{
name: "Digits",
input: "ID: {RAND;6;DIGIT}",
expectedLen: map[string]int{"{RAND;6;DIGIT}": 6},
checkFunc: map[string]func(testing.TB, []byte){"{RAND;6;DIGIT}": func(tb testing.TB, b []byte) { checkCharset(tb, b, fastrand.CharsDigits) }},
},
{
name: "Hex",
input: "Token: {RAND;8;HEX}",
expectedLen: map[string]int{"{RAND;8;HEX}": 16},
checkFunc: map[string]func(testing.TB, []byte){"{RAND;8;HEX}": checkHexFormat},
},
{
name: "Space",
input: "A{RAND;5;SPACE}B",
expectedLen: map[string]int{"{RAND;5;SPACE}": 5},
checkFunc: map[string]func(testing.TB, []byte){"{RAND;5;SPACE}": func(tb testing.TB, b []byte) { checkCharset(tb, b, fastrand.CharsSpace) }},
},
{
name: "UUID",
input: "UUID: {RAND;UUID}",
expectedLen: map[string]int{"{RAND;UUID}": 36},
checkFunc: map[string]func(testing.TB, []byte){"{RAND;UUID}": checkUUIDFormat},
},
{
name: "NULL Bytes",
input: "NUL:{RAND;7;NULL}",
expectedLen: map[string]int{"{RAND;7;NULL}": 7},
checkFunc: map[string]func(testing.TB, []byte){"{RAND;7;NULL}": func(tb testing.TB, b []byte) { checkCharset(tb, b, fastrand.CharsList(fastrand.CharsNull)) }},
},
{
name: "IPv4",
input: "IP: {RAND;IPV4}",
expectedLen: map[string]int{"{RAND;IPV4}": -1},
checkFunc: map[string]func(testing.TB, []byte){"{RAND;IPV4}": checkIPv4Format},
},
{
name: "IPv6",
input: "IP: {RAND;IPV6}",
expectedLen: map[string]int{"{RAND;IPV6}": -1},
checkFunc: map[string]func(testing.TB, []byte){"{RAND;IPV6}": checkIPv6Format},
},
{
name: "Bytes",
input: "Raw: {RAND;10;BYTES}",
expectedLen: map[string]int{"{RAND;10;BYTES}": 10},
},
{
name: "Email",
input: "Contact: {RAND;8;EMAIL}",
expectedLen: map[string]int{"{RAND;8;EMAIL}": -1},
checkFunc: map[string]func(testing.TB, []byte){"{RAND;8;EMAIL}": checkEmailFormat},
},
{
name: "Multiple Placeholders",
input: "User: {RAND;6;ABU} | Session: {RANDOM;32;HEX} | ID: {RAND;UUID} | Data: {RAND;50}",
expectedLen: map[string]int{"{RAND;6;ABU}": 6, "{RANDOM;32;HEX}": 64, "{RAND;UUID}": 36, "{RAND;50}": 50},
checkFunc: map[string]func(testing.TB, []byte){
"{RAND;6;ABU}": func(tb testing.TB, b []byte) { checkCharset(tb, b, fastrand.CharsAlphabetUpper) },
"{RANDOM;32;HEX}": checkHexFormat,
"{RAND;UUID}": checkUUIDFormat,
"{RAND;50}": func(tb testing.TB, b []byte) { checkCharset(tb, b, fastrand.CharsAll) },
},
},
{
name: "Adjacent Placeholders",
input: "{RAND;3;DIGIT}{RAND;4;ABL}",
expectedLen: map[string]int{"{RAND;3;DIGIT}": 3, "{RAND;4;ABL}": 4},
checkFunc: map[string]func(testing.TB, []byte){
"{RAND;3;DIGIT}": func(tb testing.TB, b []byte) { checkCharset(tb, b, fastrand.CharsDigits) },
"{RAND;4;ABL}": func(tb testing.TB, b []byte) { checkCharset(tb, b, fastrand.CharsAlphabetLower) },
},
},
{
name: "Invalid Length With Type (Fallback Length)",
input: "Key: {RAND;abc;HEX}",
expectedLen: map[string]int{"{RAND;abc;HEX}": 32},
checkFunc: map[string]func(testing.TB, []byte){"{RAND;abc;HEX}": checkHexFormat},
},
{
name: "Max Length",
input: "Key: {RAND;99}",
expectedLen: map[string]int{"{RAND;99}": 99},
checkFunc: map[string]func(testing.TB, []byte){"{RAND;99}": func(tb testing.TB, b []byte) { checkCharset(tb, b, fastrand.CharsAll) }},
},
{
name: "Incomplete Tag Start (Literal)",
input: "Value: {RAN",
expectedLen: map[string]int{},
},
{
name: "Incomplete Tag Middle (Literal)",
input: "Value: {RAND;10",
expectedLen: map[string]int{},
},
{
name: "Incomplete Tag With Type (Literal)",
input: "Value: {RAND;10;HEX",
expectedLen: map[string]int{},
},
{
name: "Empty Input",
input: "",
expectedLen: map[string]int{},
},
{
name: "Only Placeholder",
input: "{RAND;5;DIGIT}",
expectedLen: map[string]int{"{RAND;5;DIGIT}": 5},
checkFunc: map[string]func(testing.TB, []byte){"{RAND;5;DIGIT}": func(tb testing.TB, b []byte) { checkCharset(tb, b, fastrand.CharsDigits) }},
},
{
name: "Placeholder at End",
input: "End with {RAND;UUID}",
expectedLen: map[string]int{"{RAND;UUID}": 36},
checkFunc: map[string]func(testing.TB, []byte){"{RAND;UUID}": checkUUIDFormat},
},
{
name: "Length Range",
input: "Data: {RAND;5-10;DIGIT}",
expectedLen: map[string]int{"{RAND;5-10;DIGIT}": -1},
checkFunc: map[string]func(testing.TB, []byte){"{RAND;5-10;DIGIT}": func(tb testing.TB, b []byte) {
if len(b) < 5 || len(b) > 10 {
tb.Errorf("Expected length between 5 and 10, got %d", len(b))
}
checkCharset(tb, b, fastrand.CharsDigits)
}},
},
{
name: "Length Range Invalid (Fallback)",
input: "Data: {RAND;15-5;ABU}",
expectedLen: map[string]int{"{RAND;15-5;ABU}": 16},
checkFunc: map[string]func(testing.TB, []byte){"{RAND;15-5;ABU}": func(tb testing.TB, b []byte) {
checkCharset(tb, b, fastrand.CharsAlphabetUpper)
}},
},
{
name: "Keyword Choice",
input: "Value: {RAND;UUID,IPV4,IPV6}",
expectedLen: map[string]int{"{RAND;UUID,IPV4,IPV6}": -1},
checkFunc: map[string]func(testing.TB, []byte){"{RAND;UUID,IPV4,IPV6}": func(tb testing.TB, b []byte) {
isUUID := uuidRegex.Match(b)
ip := net.ParseIP(string(b))
isIPv4 := ip != nil && ip.To4() != nil && !strings.Contains(string(b), ":")
isIPv6 := ip != nil && ip.To4() == nil && strings.Contains(string(b), ":")
if !isUUID && !isIPv4 && !isIPv6 {
tb.Errorf("Generated value %q is not a valid UUID, IPv4, or IPv6", string(b))
}
}},
},
{
name: "Keyword Choice No Length",
input: "{RAND;HEX,UUID}",
expectedLen: map[string]int{"{RAND;HEX,UUID}": -1},
checkFunc: map[string]func(testing.TB, []byte){"{RAND;HEX,UUID}": func(tb testing.TB, b []byte) {
if uuidRegex.Match(b) {
if len(b) != 36 {
tb.Errorf("Generated UUID %q has wrong length %d, expected 36", string(b), len(b))
}
} else if hexRegex.Match(b) {
if len(b) != 32 {
tb.Errorf("Generated HEX %q has wrong length %d, expected 32", string(b), len(b))
}
} else {
tb.Errorf("Generated value %q is not a valid UUID or HEX", string(b))
}
}},
},
{
name: "Combined Range and Choice",
input: "{RAND;8-12;HEX,ABL}",
expectedLen: map[string]int{"{RAND;8-12;HEX,ABL}": -1},
checkFunc: map[string]func(testing.TB, []byte){"{RAND;8-12;HEX,ABL}": func(tb testing.TB, b []byte) {
isHex := hexRegex.Match(b)
isABL := true
for _, char := range b {
if !bytes.Contains([]byte(fastrand.CharsAlphabetLower), []byte{char}) {
isABL = false
break
}
}
if isHex {
if len(b) < 16 || len(b) > 24 || len(b)%2 != 0 {
tb.Errorf("Generated HEX value %q has invalid length %d, expected between 16 and 24 and even", string(b), len(b))
}
} else if isABL {
if len(b) < 8 || len(b) > 12 {
tb.Errorf("Generated ABL value %q has invalid length %d, expected between 8 and 12", string(b), len(b))
}
} else {
tb.Errorf("Generated value %q is not valid HEX or ABL", string(b))
}
}},
},
{
name: "URL-encoded Range and Choice",
input: "Data: %7BRANDOM%3B10-20%3BDIGIT,ABL%7D",
expectedLen: map[string]int{"%7BRANDOM%3B10-20%3BDIGIT,ABL%7D": -1},
checkFunc: map[string]func(testing.TB, []byte){"%7BRANDOM%3B10-20%3BDIGIT,ABL%7D": func(tb testing.TB, b []byte) {
if len(b) < 10 || len(b) > 20 {
tb.Errorf("Expected length between 10 and 20, got %d", len(b))
}
isDigit := true
for _, char := range b {
if !bytes.Contains([]byte(fastrand.CharsDigits), []byte{char}) {
isDigit = false
break
}
}
isABL := true
for _, char := range b {
if !bytes.Contains([]byte(fastrand.CharsAlphabetLower), []byte{char}) {
isABL = false
break
}
}
if !isDigit && !isABL {
tb.Errorf("Generated value %q is not valid DIGIT or ABL", string(b))
}
}},
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
inputBytes := []byte(tc.input)
resultBytes := fastrand.Randomizer(inputBytes)
resultStr := string(resultBytes)
placeholderMatches := findPlaceholderRegex.FindAllStringIndex(tc.input, -1)
if len(tc.expectedLen) == 0 && len(placeholderMatches) > 0 {
if tc.name == "Incomplete Tag Middle (Literal)" || tc.name == "Incomplete Tag With Type (Literal)" {
if resultStr != tc.input {
t.Errorf("Expected literal output %q for incomplete tag, got %q", tc.input, resultStr)
}
return
} else if tc.name == "Incomplete Tag Start (Literal)" {
if resultStr != tc.input {
t.Errorf("Expected literal output %q for incomplete tag start, got %q", tc.input, resultStr)
}
return
} else {
t.Logf("Warning: Placeholders found by regex but none expected by test case '%s'", tc.name)
}
} else if len(tc.expectedLen) > 0 && len(placeholderMatches) == 0 {
t.Fatalf("Test setup error: Placeholders expected but none found by regex in input: %q: %s", tc.input, resultStr)
} else if len(tc.expectedLen) == 0 && len(placeholderMatches) == 0 {
if resultStr != tc.input {
t.Errorf("Expected output %q to match input %q when no placeholders are processed, got %q", tc.input, tc.input, resultStr)
}
return
}
placeholders := findPlaceholderRegex.FindAllString(tc.input, -1)
if len(placeholders) != len(placeholderMatches) {
t.Fatalf("Regex match count mismatch: FindAllStringIndex returned %d, FindAllString returned %d", len(placeholderMatches), len(placeholders))
}
lastInputIndex := 0
currentResultIndex := 0
for i, matchIndices := range placeholderMatches {
placeholder := placeholders[i]
placeholderStart := matchIndices[0]
placeholderEnd := matchIndices[1]
fixedPartBefore := tc.input[lastInputIndex:placeholderStart]
expectedFixedPartLen := len(fixedPartBefore)
if currentResultIndex+expectedFixedPartLen > len(resultStr) {
t.Errorf("[%s] Result string too short. Expected fixed part %q (len %d) at index %d, but result ends at %d.",
placeholder, fixedPartBefore, expectedFixedPartLen, currentResultIndex, len(resultStr))
continue
}
actualFixedPartResult := resultStr[currentResultIndex : currentResultIndex+expectedFixedPartLen]
if actualFixedPartResult != fixedPartBefore {
t.Errorf("[%s] Mismatch in fixed part before placeholder. Expected %q, got %q at result index %d.",
placeholder, fixedPartBefore, actualFixedPartResult, currentResultIndex)
continue
}
currentResultIndex += expectedFixedPartLen
actualReplacementStartIndex := currentResultIndex
actualReplacementEndIndex := len(resultStr)
nextPlaceholderInputStartIndex := len(tc.input)
if i+1 < len(placeholderMatches) {
nextPlaceholderInputStartIndex = placeholderMatches[i+1][0]
}
fixedPartAfterPlaceholderInInput := tc.input[placeholderEnd:nextPlaceholderInputStartIndex]
if len(fixedPartAfterPlaceholderInInput) > 0 {
foundIndex := strings.Index(resultStr[actualReplacementStartIndex:], fixedPartAfterPlaceholderInInput)
if foundIndex != -1 {
actualReplacementEndIndex = actualReplacementStartIndex + foundIndex
} else {
t.Errorf("[%s] Structure error: Could not find expected fixed part %q after placeholder in result %q (searching from index %d)",
placeholder, fixedPartAfterPlaceholderInInput, resultStr, actualReplacementStartIndex)
}
}
if actualReplacementEndIndex < actualReplacementStartIndex {
t.Errorf("[%s] Logic error: actualReplacementEndIndex (%d) < actualReplacementStartIndex (%d).",
placeholder, actualReplacementEndIndex, actualReplacementStartIndex)
continue
}
expectedLen, lenDefined := tc.expectedLen[placeholder]
if len(fixedPartAfterPlaceholderInInput) == 0 && i+1 < len(placeholderMatches) {
if lenDefined && expectedLen != -1 {
potentialEndIndex := actualReplacementStartIndex + expectedLen
if potentialEndIndex < actualReplacementEndIndex {
actualReplacementEndIndex = potentialEndIndex
}
}
}
actualReplacementLen := actualReplacementEndIndex - actualReplacementStartIndex
replacementBytes := resultBytes[actualReplacementStartIndex:actualReplacementEndIndex]
checkFunc, funcDefined := tc.checkFunc[placeholder]
if lenDefined && expectedLen != -1 && actualReplacementLen != expectedLen {
t.Errorf("Placeholder %q: Expected length %d, got %d. Replacement: %q",
placeholder, expectedLen, actualReplacementLen, string(replacementBytes))
}
if funcDefined && checkFunc != nil {
if len(replacementBytes) > 0 || (lenDefined && expectedLen == 0) {
t.Run(placeholder+"_check", func(st *testing.T) {
checkFunc(st, replacementBytes)
})
} else if len(replacementBytes) == 0 && (!lenDefined || expectedLen != 0) {
t.Errorf("Placeholder %q: Replacement is empty but expected length was %d (or variable > 0).", placeholder, expectedLen)
}
} else if !funcDefined && (!lenDefined || expectedLen > 0) {
if placeholder != "{RAND;10;BYTES}" {
t.Logf("Warning: No check function defined for placeholder %q", placeholder)
}
}
currentResultIndex = actualReplacementEndIndex
lastInputIndex = placeholderEnd
}
finalFixedPart := tc.input[lastInputIndex:]
expectedFinalFixedPartLen := len(finalFixedPart)
if currentResultIndex+expectedFinalFixedPartLen > len(resultStr) {
t.Errorf("Result string too short for final fixed part %q. Expected length %d starting at index %d, but result ends at %d.",
finalFixedPart, expectedFinalFixedPartLen, currentResultIndex, len(resultStr))
} else if currentResultIndex+expectedFinalFixedPartLen < len(resultStr) {
t.Errorf("Result string has unexpected trailing data after consuming all parts: %q", resultStr[currentResultIndex:])
} else {
actualFinalFixedPartResult := resultStr[currentResultIndex:]
if actualFinalFixedPartResult != finalFixedPart {
t.Errorf("Mismatch in final fixed part. Expected %q, got %q.", finalFixedPart, actualFinalFixedPartResult)
}
}
})
}
}
func TestEngine(t *testing.T) {
t.Run("NewEngine_Defaults", func(t *testing.T) {
engine := fastrand.NewEngine()
result := engine.RandomizerString("{RAND}")
if len(result) != 16 {
t.Errorf("Expected default length 16, got %d", len(result))
}
})
t.Run("Reset", func(t *testing.T) {
engine := fastrand.NewEngine(
fastrand.WithDefaultLength(5),
fastrand.WithDisabledKeywords("UUID"),
)
if len(engine.RandomizerString("{RAND}")) != 5 {
t.Fatal("Pre-condition failed: Default length was not set to 5")
}
engine.Reset()
if len(engine.RandomizerString("{RAND}")) != 16 {
t.Errorf("Expected default length to be 16 after Reset, got %d", len(engine.RandomizerString("{RAND}")))
}
result := engine.RandomizerString("{RAND;UUID}")
if !uuidRegex.MatchString(result) {
t.Errorf("Expected UUID to be re-enabled after Reset, got %q", result)
}
})
t.Run("WithOptions_Length", func(t *testing.T) {
engine := fastrand.NewEngine(
fastrand.WithDefaultLength(10),
fastrand.WithMinLength(5),
fastrand.WithMaxLength(20),
)
if len(engine.RandomizerString("{RAND}")) != 10 {
t.Errorf("Expected custom default length 10, got %d", len(engine.RandomizerString("{RAND}")))
}
if len(engine.RandomizerString("{RAND;2}")) != 10 {
t.Errorf("Expected length < minLength to fall back to default length 10, got %d", len(engine.RandomizerString("{RAND;2}")))
}
if len(engine.RandomizerString("{RAND;30}")) != 10 {
t.Errorf("Expected length > maxLength to fall back to default length 10, got %d", len(engine.RandomizerString("{RAND;30}")))
}
if len(engine.RandomizerString("{RAND;15}")) != 15 {
t.Errorf("Expected length 15, got %d", len(engine.RandomizerString("{RAND;15}")))
}
})
t.Run("WithOptions_DisabledKeyword", func(t *testing.T) {
engine := fastrand.NewEngine(fastrand.WithDisabledKeywords("UUID", "HEX"))
result := engine.RandomizerString("{RAND;UUID}")
if uuidRegex.MatchString(result) {
t.Errorf("Expected UUID to be disabled, but got a valid UUID: %s", result)
}
if len(result) != 16 {
t.Errorf("Expected disabled keyword to fall back to default length 16, got %d", len(result))
}
})
t.Run("WithOptions_CustomKeyword", func(t *testing.T) {
engine := fastrand.NewEngine(
fastrand.WithCustomKeyword("SKU", func(length int) []byte {
return []byte("SKU-" + fastrand.String(length, fastrand.CharsDigits))
}),
)
result := engine.RandomizerString("ID-{RAND;8;SKU}-End")
if !strings.HasPrefix(result, "ID-SKU-") {
t.Errorf("Expected custom keyword 'SKU' to produce prefixed output, got %q", result)
}
if len(result) != 19 {
t.Errorf("Expected total length 19, got %d for %q", len(result), result)
}
})
t.Run("WithOptions_CustomCharset", func(t *testing.T) {
engine := fastrand.NewEngine(
fastrand.WithCustomCharset("DIGIT", []byte("01")),
)
result := engine.RandomizerString("{RAND;10;DIGIT}")
checkCharset(t, []byte(result), []byte("01"))
})
t.Run("WithOptions_InputEncoding", func(t *testing.T) {
engine := fastrand.NewEngine(fastrand.WithInputEncoding(fastrand.RandomizerEncodingURL))
resultURL := engine.RandomizerString("%7BRAND;4;HEX%7D")
if len(resultURL) != 8 || !hexRegex.MatchString(resultURL) {
t.Errorf("Expected URL-encoded tag to be processed, got %q", resultURL)
}
resultHTML := engine.RandomizerString("{RAND;4;HEX}")
if resultHTML == resultURL || len(resultHTML) == 8 {
t.Errorf("Expected HTML-encoded tag to be ignored, but it was processed: %q", resultHTML)
}
})
t.Run("WithOptions_OutputEncoding", func(t *testing.T) {
engine := fastrand.NewEngine(fastrand.WithOutputEncoding(fastrand.RandomizerEncodingURL))
result := engine.RandomizerString("foo=bar&baz={RAND;4;HEX}")
expectedPrefix := "foo%3Dbar%26baz%3D"
if !strings.HasPrefix(result, expectedPrefix) {
t.Errorf("Expected output to be URL encoded, got %q", result)
}
hexPart := strings.TrimPrefix(result, expectedPrefix)
if len(hexPart) != 8 {
t.Errorf("Expected random part to remain un-encoded and have length 8, got %q", hexPart)
}
})
t.Run("WithOptions_DisableFeatures", func(t *testing.T) {
engine := fastrand.NewEngine(
fastrand.WithRanges(false),
fastrand.WithKeywordChoices(false),
fastrand.WithLengthChoices(false),
)
resultRange := engine.RandomizerString("{RAND;5-10;DIGIT}")
if len(resultRange) != 16 {
t.Errorf("Expected disabled range to produce default length 16, got %d", len(resultRange))
}
resultKwChoice := engine.RandomizerString("{RAND;HEX,UUID}")
if len(resultKwChoice) != 16 {
t.Errorf("Expected disabled keyword choice to produce default length 16, got %d", len(resultKwChoice))
}
resultLenChoice := engine.RandomizerString("{RAND;5,10,15;DIGIT}")
if len(resultLenChoice) != 16 {
t.Errorf("Expected disabled length choice to produce default length 16, got %d", len(resultLenChoice))
}
})
t.Run("Combination_KitchenSink", func(t *testing.T) {
engine := fastrand.NewEngine(
fastrand.WithMinLength(10),
fastrand.WithMaxLength(50),
fastrand.WithOutputEncoding(fastrand.RandomizerEncodingHTML),
fastrand.WithDisabledKeywords("IPV6"),
fastrand.WithCustomKeyword("USER", func(length int) []byte {
return []byte("user_" + fastrand.String(length, fastrand.CharsAlphabetLower))
}),
)
template := "<user id='{RAND;10-15;USER}'>Activity: {RAND;IPV4,IPV6}</user>"
result := engine.RandomizerString(template)
if !strings.HasPrefix(result, "<user id='user_") {
t.Fatalf("Output encoding or custom keyword failed. Got: %s", result)
}
startMarker := "Activity: "
endMarker := "</user>"
startIndex := strings.Index(result, startMarker)
if startIndex == -1 {
t.Fatalf("Could not find start marker %q in result", startMarker)
}
startIndex += len(startMarker)
endIndex := strings.Index(result, endMarker)
if endIndex == -1 {
t.Fatalf("Could not find end marker %q in result", endMarker)
}
generatedIP := result[startIndex:endIndex]
if strings.Contains(generatedIP, ":") {
t.Errorf("Disabled keyword IPV6 was generated. IP part: %s", generatedIP)
}
if net.ParseIP(generatedIP) == nil || net.ParseIP(generatedIP).To4() == nil {
t.Errorf("Expected a valid IPv4 address, but got %q", generatedIP)
}
})
}
func TestDefaultEngine(t *testing.T) {
t.Run("Basic", func(t *testing.T) {
result := fastrand.RandomizerString("{RAND;10;DIGIT}")
if len(result) != 10 {
t.Errorf("Expected length 10, got %d", len(result))
}
checkCharset(t, []byte(result), fastrand.CharsDigits)
})
t.Run("RangeAndChoice", func(t *testing.T) {
result := fastrand.RandomizerString("{RAND;5-8;HEX,UUID}")
isUUID := uuidRegex.MatchString(result)
isHex := hexRegex.MatchString(result)
if !isUUID && !isHex {
t.Fatalf("Expected UUID or HEX, got %q", result)
}
if isHex && (len(result) < 10 || len(result) > 16) {
t.Errorf("HEX result has wrong length: %d", len(result))
}
})
}