seclib_test.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package seclib2
  15. import (
  16. "math/rand"
  17. "testing"
  18. "time"
  19. "yunion.io/x/pkg/util/httputils"
  20. "yunion.io/x/onecloud/pkg/httperrors"
  21. )
  22. func TestRandomPassword2(t *testing.T) {
  23. rand.Seed(time.Now().Unix())
  24. t.Logf("%s", RandomPassword2(12))
  25. }
  26. func TestMeetComplxity(t *testing.T) {
  27. cases := []struct {
  28. in string
  29. want bool
  30. }{
  31. {"123456", false},
  32. {"123abcABC!@#", true},
  33. {"123abcABC-@=", true},
  34. }
  35. for _, c := range cases {
  36. if c.want != MeetComplxity(c.in) {
  37. t.Errorf("%s != %v", c.in, c.want)
  38. }
  39. }
  40. }
  41. func TestPassword(t *testing.T) {
  42. cases := []struct {
  43. in string
  44. valid bool
  45. errClass string
  46. invalidCharacters []byte
  47. }{
  48. {in: "123456", valid: false, errClass: httperrors.ErrWeakPassword.Error()},
  49. {in: "123abcABC!@#", valid: true},
  50. {in: "123abcABC-@=", valid: true},
  51. }
  52. for _, c := range cases {
  53. ap := AnalyzePasswordStrenth(c.in)
  54. if string(ap.Invalid) != string(c.invalidCharacters) {
  55. t.Fatalf("%s invalid character %s != %s", c.in, string(ap.Invalid), string(c.invalidCharacters))
  56. }
  57. err := ValidatePassword(c.in)
  58. if err != nil {
  59. t.Logf("%s -> %v", c.in, err)
  60. e := err.(*httputils.JSONClientError)
  61. if e.Class != c.errClass {
  62. t.Fatalf("%s invalid error class %s != %s", c.in, e.Class, c.errClass)
  63. }
  64. } else if !c.valid {
  65. t.Fatalf("%s should be invalid", c.in)
  66. }
  67. }
  68. }