code.gitea.io/gitea@v1.19.3/modules/auth/password/password_test.go (about)

     1  // Copyright 2019 The Gitea Authors. All rights reserved.
     2  // SPDX-License-Identifier: MIT
     3  
     4  package password
     5  
     6  import (
     7  	"testing"
     8  
     9  	"github.com/stretchr/testify/assert"
    10  )
    11  
    12  func TestComplexity_IsComplexEnough(t *testing.T) {
    13  	matchComplexityOnce.Do(func() {})
    14  
    15  	testlist := []struct {
    16  		complexity  []string
    17  		truevalues  []string
    18  		falsevalues []string
    19  	}{
    20  		{[]string{"off"}, []string{"1", "-", "a", "A", "ñ", "日本語"}, []string{}},
    21  		{[]string{"lower"}, []string{"abc", "abc!"}, []string{"ABC", "123", "=!$", ""}},
    22  		{[]string{"upper"}, []string{"ABC"}, []string{"abc", "123", "=!$", "abc!", ""}},
    23  		{[]string{"digit"}, []string{"123"}, []string{"abc", "ABC", "=!$", "abc!", ""}},
    24  		{[]string{"spec"}, []string{"=!$", "abc!"}, []string{"abc", "ABC", "123", ""}},
    25  		{[]string{"off"}, []string{"abc", "ABC", "123", "=!$", "abc!", ""}, nil},
    26  		{[]string{"lower", "spec"}, []string{"abc!"}, []string{"abc", "ABC", "123", "=!$", "abcABC123", ""}},
    27  		{[]string{"lower", "upper", "digit"}, []string{"abcABC123"}, []string{"abc", "ABC", "123", "=!$", "abc!", ""}},
    28  		{[]string{""}, []string{"abC=1", "abc!9D"}, []string{"ABC", "123", "=!$", ""}},
    29  	}
    30  
    31  	for _, test := range testlist {
    32  		testComplextity(test.complexity)
    33  		for _, val := range test.truevalues {
    34  			assert.True(t, IsComplexEnough(val))
    35  		}
    36  		for _, val := range test.falsevalues {
    37  			assert.False(t, IsComplexEnough(val))
    38  		}
    39  	}
    40  
    41  	// Remove settings for other tests
    42  	testComplextity([]string{"off"})
    43  }
    44  
    45  func TestComplexity_Generate(t *testing.T) {
    46  	matchComplexityOnce.Do(func() {})
    47  
    48  	const maxCount = 50
    49  	const pwdLen = 50
    50  
    51  	test := func(t *testing.T, modes []string) {
    52  		testComplextity(modes)
    53  		for i := 0; i < maxCount; i++ {
    54  			pwd, err := Generate(pwdLen)
    55  			assert.NoError(t, err)
    56  			assert.Len(t, pwd, pwdLen)
    57  			assert.True(t, IsComplexEnough(pwd), "Failed complexities with modes %+v for generated: %s", modes, pwd)
    58  		}
    59  	}
    60  
    61  	test(t, []string{"lower"})
    62  	test(t, []string{"upper"})
    63  	test(t, []string{"lower", "upper", "spec"})
    64  	test(t, []string{"off"})
    65  	test(t, []string{""})
    66  
    67  	// Remove settings for other tests
    68  	testComplextity([]string{"off"})
    69  }
    70  
    71  func testComplextity(values []string) {
    72  	// Cleanup previous values
    73  	validChars = ""
    74  	requiredList = make([]complexity, 0, len(values))
    75  	setupComplexity(values)
    76  }