diff --git a/pw.go b/pw.go index 28d7467..747f844 100644 --- a/pw.go +++ b/pw.go @@ -24,7 +24,8 @@ const AllChars = UpperChars + LowerChars + SpecialChars + NumberChars type Option func() string func randomFromChars(length int, chars string) string { - max := len(chars) - 1 + // rand.Int returns value in [0, max) + max := len(chars) p := "" for i := 0; i < length; i++ { diff --git a/pw_test.go b/pw_test.go index 6768d13..221d19e 100644 --- a/pw_test.go +++ b/pw_test.go @@ -15,6 +15,16 @@ func contains(chars string, password string) bool { return false } +// containsAll checks if password contains all chars in the charset +func containsAll(password, charset string) bool { + for _, char := range strings.Split(charset, "") { + if !strings.Contains(password, char) { + return false + } + } + return true +} + func TestDefaultNewPassword(t *testing.T) { l := 100 p := NewPassword(l) @@ -139,3 +149,11 @@ func TestSpecialCharOnlyPassword(t *testing.T) { t.Errorf("should not contain upper characters") } } + +func TestDistribution(t *testing.T) { + const charset = "12" + pass := randomFromChars(100, charset) + if !containsAll(pass, charset) { + t.Errorf("should contain all the chars from charset %q\n", charset) + } +}