-
Notifications
You must be signed in to change notification settings - Fork 13
/
zxcvbn_test.go
104 lines (94 loc) · 2.62 KB
/
zxcvbn_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
package zxcvbn
import (
"encoding/json"
"fmt"
"io/ioutil"
"path/filepath"
"testing"
"time"
"github.com/trustelem/zxcvbn/match"
"github.com/trustelem/zxcvbn/scoring"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestPasswordStrength(t *testing.T) {
var testdata struct {
TimeStamp time.Time `json:"timestamp"`
Tests []struct {
Password string `json:"password"`
Guesses float64 `json:"guesses"`
Score int `json:"score"`
Sequence []*match.Match `json:"sequence"`
} `json:"tests"`
}
b, err := ioutil.ReadFile(filepath.Join("testdata", "output.json"))
require.NoError(t, err)
err = json.Unmarshal(b, &testdata)
require.NoError(t, err)
refYear := scoring.ReferenceYear
defer func() {
scoring.ReferenceYear = refYear
}()
scoring.ReferenceYear = testdata.TimeStamp.Year()
// maximum epsilon for guesses comparison
const maxEpsilonGuesses = 1e-15
for _, td := range testdata.Tests {
t.Run(td.Password, func(t *testing.T) {
// map character positions to rune position
runeMap := make(map[int]int, len(td.Password))
c := 0
for i := range td.Password {
runeMap[i] = c
c++
}
runeMap[len(td.Password)] = c
s := PasswordStrength(td.Password, nil)
if len(s.Sequence) == len(td.Sequence) {
for j := range td.Sequence {
expect, _ := json.Marshal(td.Sequence[j])
got, _ := json.Marshal(s.Sequence[j])
msg := func(f string) string {
return fmt.Sprintf("Password %+q, field %s: expect=%s got=%s",
td.Password,
f,
string(expect),
string(got))
}
if !assert.Equal(t, td.Sequence[j].I, runeMap[s.Sequence[j].I], msg("i")) {
return
}
if !assert.Equal(t, td.Sequence[j].J, runeMap[s.Sequence[j].J+1]-1, msg("j")) {
t.Logf("runeMap %v\n", runeMap)
return
}
if !assert.Equal(t, td.Sequence[j].Pattern, s.Sequence[j].Pattern, msg("pattern")) {
return
}
if !assert.Equal(t, td.Sequence[j].Token, s.Sequence[j].Token, msg("token")) {
return
}
if !assert.InEpsilon(t, td.Sequence[j].Guesses, s.Sequence[j].Guesses, maxEpsilonGuesses, msg("guesses")) {
return
}
}
} else {
b, _ := json.Marshal(td.Sequence)
t.Errorf("Expected sequence:\n%s\nGot:\n%s\n",
string(b),
match.ToString(s.Sequence))
return
}
assert.InEpsilon(t, td.Guesses, s.Guesses, maxEpsilonGuesses)
assert.Equal(t, td.Score, s.Score, "Wrong score")
})
}
}
func TestCornerCases(t *testing.T) {
testdata := []string{
"",
"wen\x8e\xc6",
}
for _, td := range testdata {
_ = PasswordStrength(td, nil)
}
}