From 336f42c51184527be75ec53fc13cf2a56232a3a6 Mon Sep 17 00:00:00 2001 From: Riad Afridi Shibly Date: Mon, 24 Oct 2022 13:47:43 +0600 Subject: [PATCH] fix distribution --- pw.go | 3 ++- pw_test.go | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) 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) + } +}