//go:build test package zxcvbnjs import ( "strings" "sync" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) // The goja.Runtime inside Score is a package-level singleton and is not // goroutine-safe. This mutex serializes all Score calls across parallel // test functions to prevent concurrent access to the JS VM. var scoreMu sync.Mutex func TestScore_WeakPasswords(t *testing.T) { t.Parallel() tests := []struct { name string password string }{ {name: "password literal", password: "password"}, {name: "numeric", password: "123456"}, {name: "keyboard pattern", password: "qwerty"}, {name: "repeated chars", password: "aaaaaa"}, {name: "simple word", password: "abcdef"}, {name: "common word", password: "monkey"}, } for _, tt := range tests { tt := tt t.Run(tt.name, func(t *testing.T) { scoreMu.Lock() score, err := Score(tt.password) scoreMu.Unlock() require.NoError(t, err) assert.GreaterOrEqual(t, score, 0) assert.LessOrEqual(t, score, 4) }) } } func TestScore_StrongPassword(t *testing.T) { t.Parallel() scoreMu.Lock() score, err := Score("correct-horse-battery-9nN^gHm!@>") scoreMu.Unlock() require.NoError(t, err) assert.GreaterOrEqual(t, score, 3) assert.LessOrEqual(t, score, 4) } func TestScore_EmptyString(t *testing.T) { t.Parallel() scoreMu.Lock() score, err := Score("") scoreMu.Unlock() require.NoError(t, err) assert.Equal(t, 0, score) } func TestScore_VeryLongPassword(t *testing.T) { t.Parallel() longPwd := strings.Repeat("xYz9!@#", 70) scoreMu.Lock() score, err := Score(longPwd) scoreMu.Unlock() require.NoError(t, err) assert.GreaterOrEqual(t, score, 0) assert.LessOrEqual(t, score, 4) } func TestScore_RepeatedCalls(t *testing.T) { t.Parallel() scoreMu.Lock() for i := 0; i < 10; i++ { score, err := Score("test-password-42!") require.NoError(t, err) assert.GreaterOrEqual(t, score, 0) assert.LessOrEqual(t, score, 4) } scoreMu.Unlock() } func TestScore_Deterministic(t *testing.T) { t.Parallel() pwd := "Tr0ub4dor&3" scoreMu.Lock() firstScore, err := Score(pwd) require.NoError(t, err) for i := 0; i < 5; i++ { score, err := Score(pwd) require.NoError(t, err) assert.Equal(t, firstScore, score, "score should be deterministic for %q", pwd) } scoreMu.Unlock() }