-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
random_test.go
614 lines (581 loc) · 15.4 KB
/
random_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
// SPDX-FileCopyrightText: 2021-2024 Winni Neessen <[email protected]>
//
// SPDX-License-Identifier: MIT
package apg
import (
"bytes"
"errors"
"fmt"
"strconv"
"strings"
"testing"
)
func TestGenerator_CoinFlip(t *testing.T) {
g := New(NewConfig())
cf := g.CoinFlip()
if cf < 0 || cf > 1 {
t.Errorf("CoinFlip failed(), expected 0 or 1, got: %d", cf)
}
}
func TestGenerator_CoinFlipBool(t *testing.T) {
g := New(NewConfig())
gt := false
for i := 0; i < 500_000; i++ {
cf := g.CoinFlipBool()
if cf {
gt = true
break
}
}
if !gt {
t.Error("CoinFlipBool likely not working, expected at least one true value in 500k tries, got none")
}
}
func TestGenerator_RandNum(t *testing.T) {
tt := []struct {
name string
v int64
max int64
min int64
sf bool
}{
{"RandNum up to 1000", 1000, 1000, 0, false},
{"RandNum should be 1", 1, 1, 0, false},
{"RandNum should fail on 1", 0, 0, 0, true},
{"RandNum should fail on negative", -1, 0, 0, true},
}
g := New(NewConfig())
for _, tc := range tt {
t.Run(tc.name, func(t *testing.T) {
rn, err := g.RandNum(tc.v)
if err == nil && tc.sf {
t.Errorf("random number generation was supposed to fail, but didn't, got: %d", rn)
}
if err != nil && !tc.sf {
t.Errorf("random number generation failed: %s", err)
}
if rn > tc.max {
t.Errorf("random number generation returned too big number expected below: %d, got: %d",
tc.max, rn)
}
if rn < tc.min {
t.Errorf("random number generation returned too small number, expected min: %d, got: %d",
tc.min, rn)
}
})
}
}
func TestGenerator_RandomBytes(t *testing.T) {
tt := []struct {
name string
l int64
sf bool
}{
{"1 bytes of randomness", 1, false},
{"100 bytes of randomness", 100, false},
{"1024 bytes of randomness", 1024, false},
{"4096 bytes of randomness", 4096, false},
{"-1 bytes of randomness", -1, true},
}
g := New(NewConfig())
for _, tc := range tt {
t.Run(tc.name, func(t *testing.T) {
rb, err := g.RandomBytes(tc.l)
if err != nil && !tc.sf {
t.Errorf("random byte generation failed: %s", err)
return
}
if tc.sf {
return
}
bl := len(rb)
if int64(bl) != tc.l {
t.Errorf("length of provided bytes does not match requested length: got: %d, expected: %d",
bl, tc.l)
}
if bytes.Equal(rb, make([]byte, tc.l)) {
t.Errorf("random byte generation failed. returned slice is empty")
}
})
}
}
func TestGenerator_RandomString(t *testing.T) {
g := New(NewConfig())
var l int64 = 32 * 1024
tt := []struct {
name string
cr string
nr string
sf bool
}{
{
"CharRange:AlphaLower", CharRangeAlphaLower,
CharRangeAlphaUpper + CharRangeNumeric + CharRangeSpecial, false,
},
{
"CharRange:AlphaUpper", CharRangeAlphaUpper,
CharRangeAlphaLower + CharRangeNumeric + CharRangeSpecial, false,
},
{
"CharRange:Number", CharRangeNumeric,
CharRangeAlphaLower + CharRangeAlphaUpper + CharRangeSpecial, false,
},
{
"CharRange:Special", CharRangeSpecial,
CharRangeAlphaLower + CharRangeAlphaUpper + CharRangeNumeric, false,
},
{
"CharRange:Invalid", "",
CharRangeAlphaLower + CharRangeAlphaUpper + CharRangeNumeric + CharRangeSpecial, true,
},
}
for _, tc := range tt {
t.Run(tc.name, func(t *testing.T) {
rs, err := g.RandomStringFromCharRange(l, tc.cr)
if err != nil && !tc.sf {
t.Errorf("RandomStringFromCharRange failed: %s", err)
}
if int64(len(rs)) != l && !tc.sf {
t.Errorf("RandomStringFromCharRange failed. Expected length: %d, got: %d", l, len(rs))
}
if strings.ContainsAny(rs, tc.nr) {
t.Errorf("RandomStringFromCharRange failed. Unexpected character found in returned string: %s", rs)
}
})
}
}
func TestGetCharRangeFromConfig(t *testing.T) {
config := NewConfig()
generator := New(config)
testCases := []struct {
Name string
ConfigMode ModeMask
ExpectedRange string
}{
{
Name: "LowerCaseHumanReadable",
ConfigMode: ModeLowerCase | ModeHumanReadable,
ExpectedRange: CharRangeAlphaLowerHuman,
},
{
Name: "LowerCaseNonHumanReadable",
ConfigMode: ModeLowerCase,
ExpectedRange: CharRangeAlphaLower,
},
{
Name: "NumericHumanReadable",
ConfigMode: ModeNumeric | ModeHumanReadable,
ExpectedRange: CharRangeNumericHuman,
},
{
Name: "NumericNonHumanReadable",
ConfigMode: ModeNumeric,
ExpectedRange: CharRangeNumeric,
},
{
Name: "SpecialHumanReadable",
ConfigMode: ModeSpecial | ModeHumanReadable,
ExpectedRange: CharRangeSpecialHuman,
},
{
Name: "SpecialNonHumanReadable",
ConfigMode: ModeSpecial,
ExpectedRange: CharRangeSpecial,
},
{
Name: "UpperCaseHumanReadable",
ConfigMode: ModeUpperCase | ModeHumanReadable,
ExpectedRange: CharRangeAlphaUpperHuman,
},
{
Name: "UpperCaseNonHumanReadable",
ConfigMode: ModeUpperCase,
ExpectedRange: CharRangeAlphaUpper,
},
{
Name: "MultipleModes",
ConfigMode: ModeLowerCase | ModeNumeric | ModeUpperCase | ModeHumanReadable,
ExpectedRange: CharRangeAlphaLowerHuman + CharRangeNumericHuman + CharRangeAlphaUpperHuman,
},
}
for _, tc := range testCases {
t.Run(tc.Name, func(t *testing.T) {
generator.config.Mode = tc.ConfigMode
actualRange := generator.GetCharRangeFromConfig()
if actualRange != tc.ExpectedRange {
t.Errorf("Expected range %s, got %s", tc.ExpectedRange, actualRange)
}
})
}
}
func TestGetCharRangeFromConfig_ExcludeChar(t *testing.T) {
defaultConf := NewConfig()
defaultGen := New(defaultConf)
defaultRange := defaultGen.GetCharRangeFromConfig()
defaultRange = strings.ReplaceAll(defaultRange, "a", "")
defaultRange = strings.ReplaceAll(defaultRange, "b", "")
config := NewConfig(WithExcludeChars("ab"))
generator := New(config)
excludeRange := generator.GetCharRangeFromConfig()
if excludeRange != defaultRange {
t.Errorf("GetCharRangeFromConfig(WithExcludeChars()) failed. Expected"+
"char range: %s, got: %s", defaultRange, excludeRange)
}
}
func TestGetPasswordLength(t *testing.T) {
config := NewConfig()
generator := New(config)
testCases := []struct {
Name string
ConfigFixedLength int64
ConfigMinLength int64
ConfigMaxLength int64
ExpectedLength int64
ExpectedError error
}{
{
Name: "FixedLength",
ConfigFixedLength: 10,
ConfigMinLength: 5,
ConfigMaxLength: 15,
ExpectedLength: 10,
ExpectedError: nil,
},
{
Name: "MinLengthEqualToMaxLength",
ConfigFixedLength: 0,
ConfigMinLength: 8,
ConfigMaxLength: 8,
ExpectedLength: 8,
ExpectedError: nil,
},
{
Name: "MinLengthGreaterThanMaxLength",
ConfigFixedLength: 0,
ConfigMinLength: 12,
ConfigMaxLength: 5,
ExpectedLength: 12,
ExpectedError: nil,
},
}
for _, tc := range testCases {
t.Run(tc.Name, func(t *testing.T) {
generator.config.FixedLength = tc.ConfigFixedLength
generator.config.MinLength = tc.ConfigMinLength
generator.config.MaxLength = tc.ConfigMaxLength
length, err := generator.GetPasswordLength()
if err != nil && !errors.Is(err, tc.ExpectedError) {
t.Errorf("Unexpected error: %v", err)
} else if err == nil && tc.ExpectedError != nil {
t.Errorf("Expected error %v, got nil", tc.ExpectedError)
} else if err == nil && length != tc.ExpectedLength {
t.Errorf("Expected length %d, got %d", tc.ExpectedLength, length)
}
})
}
}
// TestGenerateCoinFlip tries to test the coinflip. Randomness is hard to
// test, since it's supposed to be not prodictable. We think that in 100k
// tries at least one of each two results should be returned, even though
// it is possible that not. Therefore we only throw a warning
func TestGenerateCoinFlip(t *testing.T) {
config := NewConfig()
generator := New(config)
foundTails := false
foundHeads := false
for range 100_000 {
res, err := generator.generateCoinFlip()
if err != nil {
t.Errorf("generateCoinFlip() failed: %s", err)
return
}
switch res {
case "Tails":
foundTails = true
case "Heads":
foundHeads = true
}
}
if !foundTails && !foundHeads {
t.Logf("WARNING: generateCoinFlip() was supposed to find heads and tails "+
"in 100_000 tries but didn't. Heads: %t, Tails: %t", foundHeads, foundTails)
}
}
func TestGeneratePronounceable(t *testing.T) {
config := NewConfig()
generator := New(config)
foundSylables := 0
for range 100 {
res, err := generator.generatePronounceable()
if err != nil {
t.Errorf("generatePronounceable() failed: %s", err)
return
}
for _, syl := range KoremutakeSyllables {
if strings.Contains(res, syl) {
foundSylables++
}
}
}
if foundSylables < 100 {
t.Errorf("generatePronounceable() failed, expected at least 1 sylable, got none")
}
}
func TestCheckMinimumRequirements(t *testing.T) {
config := NewConfig()
generator := New(config)
testCases := []struct {
Name string
Password string
ConfigMinLowerCase int64
ConfigMinNumeric int64
ConfigMinSpecial int64
ConfigMinUpperCase int64
ExpectedResult bool
}{
{
Name: "Meets all requirements",
Password: "Th1sIsA$trongP@ssword",
ConfigMinLowerCase: 2,
ConfigMinNumeric: 1,
ConfigMinSpecial: 1,
ConfigMinUpperCase: 1,
ExpectedResult: true,
},
{
Name: "Missing lowercase",
Password: "THISIS@STRONGPASSWORD",
ConfigMinLowerCase: 2,
ConfigMinNumeric: 1,
ConfigMinSpecial: 1,
ConfigMinUpperCase: 1,
ExpectedResult: false,
},
{
Name: "Missing numeric",
Password: "ThisIsA$trongPassword",
ConfigMinLowerCase: 2,
ConfigMinNumeric: 1,
ConfigMinSpecial: 1,
ConfigMinUpperCase: 1,
ExpectedResult: false,
},
{
Name: "Missing special",
Password: "ThisIsALowercaseNumericPassword",
ConfigMinLowerCase: 2,
ConfigMinNumeric: 1,
ConfigMinSpecial: 1,
ConfigMinUpperCase: 1,
ExpectedResult: false,
},
{
Name: "Missing uppercase",
Password: "thisisanumericspecialpassword",
ConfigMinLowerCase: 2,
ConfigMinNumeric: 1,
ConfigMinSpecial: 1,
ConfigMinUpperCase: 1,
ExpectedResult: false,
},
{
Name: "Bare minimum",
Password: "a1!",
ConfigMinLowerCase: 1,
ConfigMinNumeric: 1,
ConfigMinSpecial: 1,
ConfigMinUpperCase: 0,
ExpectedResult: true,
},
{
Name: "Empty password",
Password: "",
ConfigMinLowerCase: 1,
ConfigMinNumeric: 1,
ConfigMinSpecial: 1,
ConfigMinUpperCase: 1,
ExpectedResult: false,
},
}
for _, tc := range testCases {
t.Run(tc.Name, func(t *testing.T) {
generator.config.MinLowerCase = tc.ConfigMinLowerCase
generator.config.MinNumeric = tc.ConfigMinNumeric
generator.config.MinSpecial = tc.ConfigMinSpecial
generator.config.MinUpperCase = tc.ConfigMinUpperCase
result := generator.checkMinimumRequirements(tc.Password)
if result != tc.ExpectedResult {
t.Errorf("Expected result %v, got %v", tc.ExpectedResult, result)
}
})
}
}
func TestGenerateRandom(t *testing.T) {
config := NewConfig(WithAlgorithm(AlgoRandom), WithMinLength(1),
WithMaxLength(1))
config.MinNumeric = 1
generator := New(config)
pw, err := generator.generateRandom()
if err != nil {
t.Errorf("generateRandom() failed: %s", err)
}
if len(pw) > 1 {
t.Errorf("expected password with length 1 but got: %d", len(pw))
}
n, err := strconv.Atoi(pw)
if err != nil {
t.Errorf("expected password to be a number but got an error: %s", err)
}
if n < 0 || n > 9 {
t.Errorf("expected password to be a number between 0 and 9, got: %d", n)
}
}
func TestGenerateRandom_withGrouping(t *testing.T) {
config := NewConfig(WithAlgorithm(AlgoRandom), WithMinLength(1),
WithMaxLength(1), WithMobileGrouping())
config.MinNumeric = 1
generator := New(config)
pw, err := generator.generateRandom()
if err != nil {
t.Errorf("generateRandom() failed: %s", err)
}
if len(pw) > 1 {
t.Errorf("expected password with length 1 but got: %d", len(pw))
}
n, err := strconv.Atoi(pw)
if err != nil {
t.Errorf("expected password to be a number but got an error: %s", err)
}
if n < 0 || n > 9 {
t.Errorf("expected password to be a number between 0 and 9, got: %d", n)
}
}
func TestGenerate(t *testing.T) {
tests := []struct {
name string
algorithm Algorithm
expectedErr error
}{
{
name: "Pronounceable",
algorithm: AlgoPronounceable,
},
{
name: "CoinFlip",
algorithm: AlgoCoinFlip,
},
{
name: "Random",
algorithm: AlgoRandom,
},
{
name: "Binary",
algorithm: AlgoBinary,
},
{
name: "Unsupported",
algorithm: AlgoUnsupported,
expectedErr: fmt.Errorf("unsupported algorithm"),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
config := NewConfig(WithAlgorithm(tt.algorithm))
g := New(config)
_, err := g.Generate()
if tt.expectedErr != nil {
if err == nil || err.Error() != tt.expectedErr.Error() {
t.Errorf("Expected error: %s, got: %s", tt.expectedErr, err)
}
return
}
if err != nil {
t.Errorf("Unexpected error: %s", err)
return
}
})
}
}
func TestGenerator_RandomStringFromCharRange_fail(t *testing.T) {
config := NewConfig()
gen := New(config)
_, err := gen.RandomStringFromCharRange(0, gen.GetCharRangeFromConfig())
if err == nil {
t.Errorf("RandomStringFromCharRange() with zero length is supposed" +
"to fail, but didn't")
}
}
func TestGenerator_generateBinary(t *testing.T) {
tests := []struct {
name string
config *Config
wantErr bool
}{
{
name: "Positive Case - Binary in Hex",
config: &Config{FixedLength: 10, BinaryHexMode: true},
wantErr: false,
},
{
name: "Negative Case - Insufficient length",
config: &Config{FixedLength: -1, BinaryHexMode: false},
wantErr: false,
},
{
name: "Positive Case - Binary without Hex",
config: &Config{FixedLength: 10, BinaryHexMode: false},
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
g := &Generator{config: tt.config}
_, err := g.generateBinary()
if (err != nil) != tt.wantErr {
t.Errorf("Generator.generateBinary() error = %v, wantErr %v", err, tt.wantErr)
return
}
})
}
}
func TestGenerator_checkMinimumRequirements_human(t *testing.T) {
config := NewConfig(WithModeMask(ModeLowerCase|ModeUpperCase|ModeNumeric|
ModeSpecial|ModeHumanReadable), WithMinLowercase(1), WithMinUppercase(1),
WithMinNumeric(1), WithMinSpecial(1))
gen := New(config)
pw, err := gen.Generate()
if err != nil {
t.Errorf("Generate() failed: %s", err)
}
_ = gen.checkMinimumRequirements(pw)
}
func BenchmarkGenerator_CoinFlip(b *testing.B) {
b.ReportAllocs()
g := New(NewConfig())
for i := 0; i < b.N; i++ {
_ = g.CoinFlip()
}
}
func BenchmarkGenerator_RandomBytes(b *testing.B) {
b.ReportAllocs()
g := New(NewConfig())
var l int64 = 1024
for i := 0; i < b.N; i++ {
_, err := g.RandomBytes(l)
if err != nil {
b.Errorf("failed to generate random bytes: %s", err)
return
}
}
}
func BenchmarkGenerator_RandomString(b *testing.B) {
b.ReportAllocs()
g := New(NewConfig())
cr := CharRangeAlphaUpper + CharRangeAlphaLower + CharRangeNumeric + CharRangeSpecial
for i := 0; i < b.N; i++ {
_, err := g.RandomStringFromCharRange(32, cr)
if err != nil {
b.Errorf("RandomStringFromCharRange() failed: %s", err)
}
}
}