diff --git a/.golangci.yml b/.golangci.yml index b8c22edfc..b3aa45cc8 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -2,6 +2,9 @@ run: timeout: 3m linters-settings: + goconst: + min-len: 2 + min-occurrences: 2 gocyclo: min-complexity: 15 godot: @@ -11,6 +14,7 @@ linters-settings: linters: enable: + - goconst - gocyclo - godot - gofmt diff --git a/cmd/authelia-scripts/cmd_build.go b/cmd/authelia-scripts/cmd_build.go index b394d5f47..8e6b98c28 100644 --- a/cmd/authelia-scripts/cmd_build.go +++ b/cmd/authelia-scripts/cmd_build.go @@ -25,7 +25,7 @@ func buildAutheliaBinary() { func buildFrontend() { // Install npm dependencies. cmd := utils.CommandWithStdout("yarn", "install") - cmd.Dir = "web" + cmd.Dir = webDirectory if err := cmd.Run(); err != nil { log.Fatal(err) @@ -33,7 +33,7 @@ func buildFrontend() { // Then build the frontend. cmd = utils.CommandWithStdout("yarn", "build") - cmd.Dir = "web" + cmd.Dir = webDirectory cmd.Env = append(os.Environ(), "INLINE_RUNTIME_CHUNK=false") if err := cmd.Run(); err != nil { diff --git a/cmd/authelia-scripts/cmd_docker.go b/cmd/authelia-scripts/cmd_docker.go index 382ef5f2e..9a9bb2b64 100644 --- a/cmd/authelia-scripts/cmd_docker.go +++ b/cmd/authelia-scripts/cmd_docker.go @@ -53,7 +53,7 @@ func dockerBuildOfficialImage(arch string) error { } if arch == "arm32v7" { - if buildkiteQEMU != "true" { + if buildkiteQEMU != stringTrue { err := utils.CommandWithStdout("docker", "run", "--rm", "--privileged", "multiarch/qemu-user-static", "--reset", "-p", "yes").Run() if err != nil { panic(err) @@ -66,7 +66,7 @@ func dockerBuildOfficialImage(arch string) error { panic(err) } } else if arch == "arm64v8" { - if buildkiteQEMU != "true" { + if buildkiteQEMU != stringTrue { err := utils.CommandWithStdout("docker", "run", "--rm", "--privileged", "multiarch/qemu-user-static", "--reset", "-p", "yes").Run() if err != nil { panic(err) @@ -83,7 +83,7 @@ func dockerBuildOfficialImage(arch string) error { gitTag := ciTag if gitTag == "" { // If commit is not tagged, mark the build has having master tag. - gitTag = "master" + gitTag = masterTag } cmd := utils.Shell("git rev-parse HEAD") @@ -213,13 +213,13 @@ func publishDockerImage(arch string) { } else { log.Fatal("Docker image will not be published, the specified tag does not conform to the standard") } - } else if ciBranch != "master" && !publicRepo.MatchString(ciBranch) { + } else if ciBranch != masterTag && !publicRepo.MatchString(ciBranch) { login(docker) deploy(docker, ciBranch+"-"+arch) - } else if ciBranch != "master" && publicRepo.MatchString(ciBranch) { + } else if ciBranch != masterTag && publicRepo.MatchString(ciBranch) { login(docker) deploy(docker, "PR"+ciPullRequest+"-"+arch) - } else if ciBranch == "master" && ciPullRequest == "false" { + } else if ciBranch == masterTag && ciPullRequest == stringFalse { login(docker) deploy(docker, "master-"+arch) } else { @@ -248,13 +248,13 @@ func publishDockerManifest() { } else { log.Fatal("Docker manifest will not be published, the specified tag does not conform to the standard") } - } else if ciBranch != "master" && !publicRepo.MatchString(ciBranch) { + } else if ciBranch != masterTag && !publicRepo.MatchString(ciBranch) { login(docker) deployManifest(docker, ciBranch, ciBranch+"-amd64", ciBranch+"-arm32v7", ciBranch+"-arm64v8") - } else if ciBranch != "master" && publicRepo.MatchString(ciBranch) { + } else if ciBranch != masterTag && publicRepo.MatchString(ciBranch) { login(docker) deployManifest(docker, "PR"+ciPullRequest, "PR"+ciPullRequest+"-amd64", "PR"+ciPullRequest+"-arm32v7", "PR"+ciPullRequest+"-arm64v8") - } else if ciBranch == "master" && ciPullRequest == "false" { + } else if ciBranch == masterTag && ciPullRequest == stringFalse { login(docker) deployManifest(docker, "master", "master-amd64", "master-arm32v7", "master-arm64v8") publishDockerReadme(docker) diff --git a/cmd/authelia-scripts/cmd_unittest.go b/cmd/authelia-scripts/cmd_unittest.go index e78943eb6..f09947dd6 100644 --- a/cmd/authelia-scripts/cmd_unittest.go +++ b/cmd/authelia-scripts/cmd_unittest.go @@ -17,7 +17,7 @@ func RunUnitTest(cobraCmd *cobra.Command, args []string) { } cmd := utils.Shell("yarn test") - cmd.Dir = "web" + cmd.Dir = webDirectory cmd.Env = append(os.Environ(), "CI=true") if err := cmd.Run(); err != nil { log.Fatal(err) diff --git a/cmd/authelia-scripts/constants.go b/cmd/authelia-scripts/const.go similarity index 75% rename from cmd/authelia-scripts/constants.go rename to cmd/authelia-scripts/const.go index 2b8c53425..efb83cde0 100644 --- a/cmd/authelia-scripts/constants.go +++ b/cmd/authelia-scripts/const.go @@ -8,3 +8,8 @@ var DockerImageName = "authelia/authelia" // IntermediateDockerImageName local name of the docker image. var IntermediateDockerImageName = "authelia:dist" + +const masterTag = "master" +const stringFalse = "false" +const stringTrue = "true" +const webDirectory = "web" diff --git a/internal/authentication/const.go b/internal/authentication/const.go index d5da7ff3d..6133ddd3b 100644 --- a/internal/authentication/const.go +++ b/internal/authentication/const.go @@ -43,3 +43,7 @@ const ( // HashingPossibleSaltCharacters represents valid hashing runes. var HashingPossibleSaltCharacters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/") + +const sha512 = "sha512" + +const testPassword = "my;secure*password" diff --git a/internal/authentication/file_user_provider.go b/internal/authentication/file_user_provider.go index c0e0c8600..5d442ee5f 100644 --- a/internal/authentication/file_user_provider.go +++ b/internal/authentication/file_user_provider.go @@ -54,7 +54,7 @@ func NewFileUserProvider(configuration *schema.FileAuthenticationBackendConfigur // TODO: Remove this. This is only here to temporarily fix the username enumeration security flaw in #949. // This generates a hash that should be usable to do a fake CheckUserPassword algorithm := configuration.Password.Algorithm - if configuration.Password.Algorithm == "sha512" { + if configuration.Password.Algorithm == sha512 { algorithm = HashingAlgorithmSHA512 } settings := getCryptSettings(utils.RandomString(configuration.Password.SaltLength, HashingPossibleSaltCharacters), @@ -143,7 +143,7 @@ func (p *FileUserProvider) UpdatePassword(username string, newPassword string) e var algorithm string if p.configuration.Password.Algorithm == "argon2id" { algorithm = HashingAlgorithmArgon2id - } else if p.configuration.Password.Algorithm == "sha512" { + } else if p.configuration.Password.Algorithm == sha512 { algorithm = HashingAlgorithmSHA512 } else { return errors.New("Invalid algorithm in configuration. It should be `argon2id` or `sha512`") diff --git a/internal/authentication/password_hash_test.go b/internal/authentication/password_hash_test.go index f3a4fd6bd..b169cb465 100644 --- a/internal/authentication/password_hash_test.go +++ b/internal/authentication/password_hash_test.go @@ -299,7 +299,7 @@ func TestNumberOfRoundsNotInt(t *testing.T) { } func TestShouldCheckPasswordArgon2idHashedWithAuthelia(t *testing.T) { - password := "my;secure*password" + password := testPassword hash, err := HashPassword(password, "", HashingAlgorithmArgon2id, schema.DefaultCIPasswordConfiguration.Iterations, schema.DefaultCIPasswordConfiguration.Memory*1024, schema.DefaultCIPasswordConfiguration.Parallelism, schema.DefaultCIPasswordConfiguration.KeyLength, schema.DefaultCIPasswordConfiguration.SaltLength) @@ -313,7 +313,7 @@ func TestShouldCheckPasswordArgon2idHashedWithAuthelia(t *testing.T) { } func TestShouldCheckPasswordSHA512HashedWithAuthelia(t *testing.T) { - password := "my;secure*password" + password := testPassword hash, err := HashPassword(password, "", HashingAlgorithmSHA512, schema.DefaultPasswordSHA512Configuration.Iterations, 0, 0, 0, schema.DefaultPasswordSHA512Configuration.SaltLength) diff --git a/internal/configuration/schema/access_control.go b/internal/configuration/schema/access_control.go index 79981798e..6db5b8ce6 100644 --- a/internal/configuration/schema/access_control.go +++ b/internal/configuration/schema/access_control.go @@ -17,7 +17,7 @@ type ACLRule struct { // IsPolicyValid check if policy is valid. func IsPolicyValid(policy string) bool { - return policy == "deny" || policy == "one_factor" || policy == "two_factor" || policy == "bypass" + return policy == denyPolicy || policy == "one_factor" || policy == "two_factor" || policy == "bypass" } // IsSubjectValid check if a subject is valid. @@ -63,7 +63,7 @@ type AccessControlConfiguration struct { // Validate validate the access control configuration. func (acc *AccessControlConfiguration) Validate(validator *StructValidator) { if acc.DefaultPolicy == "" { - acc.DefaultPolicy = "deny" + acc.DefaultPolicy = denyPolicy } if !IsPolicyValid(acc.DefaultPolicy) { diff --git a/internal/configuration/schema/const.go b/internal/configuration/schema/const.go new file mode 100644 index 000000000..c11f5b5da --- /dev/null +++ b/internal/configuration/schema/const.go @@ -0,0 +1,3 @@ +package schema + +const denyPolicy = "deny" diff --git a/internal/configuration/validator/authentication.go b/internal/configuration/validator/authentication.go index 33d73145c..19c56e998 100644 --- a/internal/configuration/validator/authentication.go +++ b/internal/configuration/validator/authentication.go @@ -22,14 +22,14 @@ func validateFileAuthenticationBackend(configuration *schema.FileAuthenticationB configuration.Password.Algorithm = schema.DefaultPasswordConfiguration.Algorithm } else { configuration.Password.Algorithm = strings.ToLower(configuration.Password.Algorithm) - if configuration.Password.Algorithm != "argon2id" && configuration.Password.Algorithm != "sha512" { + if configuration.Password.Algorithm != argon2id && configuration.Password.Algorithm != sha512 { validator.Push(fmt.Errorf("Unknown hashing algorithm supplied, valid values are argon2id and sha512, you configured '%s'", configuration.Password.Algorithm)) } } // Iterations (time) if configuration.Password.Iterations == 0 { - if configuration.Password.Algorithm == "argon2id" { + if configuration.Password.Algorithm == argon2id { configuration.Password.Iterations = schema.DefaultPasswordConfiguration.Iterations } else { configuration.Password.Iterations = schema.DefaultPasswordSHA512Configuration.Iterations @@ -47,7 +47,7 @@ func validateFileAuthenticationBackend(configuration *schema.FileAuthenticationB validator.Push(fmt.Errorf("The salt length must be 16 or less, you configured %d", configuration.Password.SaltLength)) } - if configuration.Password.Algorithm == "argon2id" { + if configuration.Password.Algorithm == argon2id { // Parallelism if configuration.Password.Parallelism == 0 { configuration.Password.Parallelism = schema.DefaultPasswordConfiguration.Parallelism @@ -80,14 +80,14 @@ func validateLdapURL(ldapURL string, validator *schema.StructValidator) string { return "" } - if !(u.Scheme == "ldap" || u.Scheme == "ldaps") { + if !(u.Scheme == schemeLDAP || u.Scheme == schemeLDAPS) { validator.Push(errors.New("Unknown scheme for ldap url, should be ldap:// or ldaps://")) return "" } - if u.Scheme == "ldap" && u.Port() == "" { + if u.Scheme == schemeLDAP && u.Port() == "" { u.Host += ":389" - } else if u.Scheme == "ldaps" && u.Port() == "" { + } else if u.Scheme == schemeLDAPS && u.Port() == "" { u.Host += ":636" } diff --git a/internal/configuration/validator/configuration_test.go b/internal/configuration/validator/configuration_test.go index a5fb1897d..fe3b2cd73 100644 --- a/internal/configuration/validator/configuration_test.go +++ b/internal/configuration/validator/configuration_test.go @@ -14,7 +14,7 @@ func newDefaultConfig() schema.Configuration { config.Host = "127.0.0.1" config.Port = 9090 config.LogLevel = "info" - config.JWTSecret = "a_secret" + config.JWTSecret = testJWTSecret config.AuthenticationBackend.File = new(schema.FileAuthenticationBackendConfiguration) config.AuthenticationBackend.File.Path = "/a/path" config.Session = schema.SessionConfiguration{ @@ -104,7 +104,7 @@ func TestShouldAddDefaultAccessControl(t *testing.T) { func TestShouldRaiseErrorWhenTLSCertWithoutKeyIsProvided(t *testing.T) { validator := schema.NewStructValidator() config := newDefaultConfig() - config.TLSCert = "/tmp/cert.pem" + config.TLSCert = testTLSCert ValidateConfiguration(&config, validator) require.Len(t, validator.Errors(), 1) @@ -114,7 +114,7 @@ func TestShouldRaiseErrorWhenTLSCertWithoutKeyIsProvided(t *testing.T) { func TestShouldRaiseErrorWhenTLSKeyWithoutCertIsProvided(t *testing.T) { validator := schema.NewStructValidator() config := newDefaultConfig() - config.TLSKey = "/tmp/key.pem" + config.TLSKey = testTLSKey ValidateConfiguration(&config, validator) require.Len(t, validator.Errors(), 1) @@ -124,8 +124,8 @@ func TestShouldRaiseErrorWhenTLSKeyWithoutCertIsProvided(t *testing.T) { func TestShouldNotRaiseErrorWhenBothTLSCertificateAndKeyAreProvided(t *testing.T) { validator := schema.NewStructValidator() config := newDefaultConfig() - config.TLSCert = "/tmp/cert.pem" - config.TLSKey = "/tmp/key.pem" + config.TLSCert = testTLSCert + config.TLSKey = testTLSKey ValidateConfiguration(&config, validator) require.Len(t, validator.Errors(), 0) diff --git a/internal/configuration/validator/const.go b/internal/configuration/validator/const.go index 019892b3a..1225dc0ae 100644 --- a/internal/configuration/validator/const.go +++ b/internal/configuration/validator/const.go @@ -150,3 +150,15 @@ var specificErrorKeys = map[string]string{ "authentication_backend.file.hashing.memory": "config key incorrect: authentication_backend.file.hashing should be authentication_backend.file.password", "authentication_backend.file.hashing.parallelism": "config key incorrect: authentication_backend.file.hashing should be authentication_backend.file.password", } + +const argon2id = "argon2id" +const sha512 = "sha512" + +const schemeLDAP = "ldap" +const schemeLDAPS = "ldaps" + +const testBadTimer = "-1" +const testModeDisabled = "disable" +const testJWTSecret = "a_secret" +const testTLSCert = "/tmp/cert.pem" +const testTLSKey = "/tmp/key.pem" diff --git a/internal/configuration/validator/session_test.go b/internal/configuration/validator/session_test.go index 786bfbefc..830c6b849 100644 --- a/internal/configuration/validator/session_test.go +++ b/internal/configuration/validator/session_test.go @@ -10,7 +10,7 @@ import ( func newDefaultSessionConfig() schema.SessionConfiguration { config := schema.SessionConfiguration{} - config.Secret = "a_secret" + config.Secret = testJWTSecret config.Domain = "example.com" return config } @@ -78,8 +78,8 @@ func TestShouldRaiseErrorWhenDomainNotSet(t *testing.T) { func TestShouldRaiseErrorWhenBadInactivityAndExpirationSet(t *testing.T) { validator := schema.NewStructValidator() config := newDefaultSessionConfig() - config.Inactivity = "-1" - config.Expiration = "-1" + config.Inactivity = testBadTimer + config.Expiration = testBadTimer ValidateSession(&config, validator) diff --git a/internal/configuration/validator/storage.go b/internal/configuration/validator/storage.go index 60b39f3e4..399dc915f 100644 --- a/internal/configuration/validator/storage.go +++ b/internal/configuration/validator/storage.go @@ -35,10 +35,10 @@ func validatePostgreSQLConfiguration(configuration *schema.PostgreSQLStorageConf validateSQLConfiguration(&configuration.SQLStorageConfiguration, validator) if configuration.SSLMode == "" { - configuration.SSLMode = "disable" + configuration.SSLMode = testModeDisabled } - if !(configuration.SSLMode == "disable" || configuration.SSLMode == "require" || + if !(configuration.SSLMode == testModeDisabled || configuration.SSLMode == "require" || configuration.SSLMode == "verify-ca" || configuration.SSLMode == "verify-full") { validator.Push(errors.New("SSL mode must be 'disable', 'require', 'verify-ca', or 'verify-full'")) } diff --git a/internal/handlers/const.go b/internal/handlers/const.go index e9f593cd5..f9e3b9172 100644 --- a/internal/handlers/const.go +++ b/internal/handlers/const.go @@ -34,3 +34,9 @@ const unableToRegisterOneTimePasswordMessage = "Unable to set up one-time passwo const unableToRegisterSecurityKeyMessage = "Unable to register your security key." const unableToResetPasswordMessage = "Unable to reset your password." const mfaValidationFailedMessage = "Authentication failed, please retry later." + +const testGATrackingID = "ABC" +const testInactivity = "10" +const testRedirectionURL = "http://redirection.local" +const testResultAllow = "allow" +const testUsername = "john" diff --git a/internal/handlers/handler_configuration_test.go b/internal/handlers/handler_configuration_test.go index 20d85deef..6a9421c21 100644 --- a/internal/handlers/handler_configuration_test.go +++ b/internal/handlers/handler_configuration_test.go @@ -25,7 +25,7 @@ func (s *ConfigurationSuite) TearDownTest() { } func (s *ConfigurationSuite) TestShouldReturnConfiguredGATrackingID() { - GATrackingID := "ABC" + GATrackingID := testGATrackingID s.mock.Ctx.Configuration.GoogleAnalyticsTrackingID = GATrackingID s.mock.Ctx.Configuration.Session.RememberMeDuration = schema.DefaultSessionConfiguration.RememberMeDuration @@ -40,7 +40,7 @@ func (s *ConfigurationSuite) TestShouldReturnConfiguredGATrackingID() { } func (s *ConfigurationSuite) TestShouldDisableRememberMe() { - GATrackingID := "ABC" + GATrackingID := testGATrackingID s.mock.Ctx.Configuration.GoogleAnalyticsTrackingID = GATrackingID s.mock.Ctx.Configuration.Session.RememberMeDuration = "0" s.mock.Ctx.Providers.SessionProvider = session.NewProvider( @@ -56,7 +56,7 @@ func (s *ConfigurationSuite) TestShouldDisableRememberMe() { } func (s *ConfigurationSuite) TestShouldDisableResetPassword() { - GATrackingID := "ABC" + GATrackingID := testGATrackingID s.mock.Ctx.Configuration.GoogleAnalyticsTrackingID = GATrackingID s.mock.Ctx.Configuration.AuthenticationBackend.DisableResetPassword = true expectedBody := ConfigurationBody{ diff --git a/internal/handlers/handler_logout_test.go b/internal/handlers/handler_logout_test.go index 2b7ee55ba..7df098856 100644 --- a/internal/handlers/handler_logout_test.go +++ b/internal/handlers/handler_logout_test.go @@ -19,7 +19,7 @@ type LogoutSuite struct { func (s *LogoutSuite) SetupTest() { s.mock = mocks.NewMockAutheliaCtx(s.T()) userSession := s.mock.Ctx.GetSession() - userSession.Username = "john" + userSession.Username = testUsername s.mock.Ctx.SaveSession(userSession) //nolint:errcheck // TODO: Legacy code, consider refactoring time permitting. } diff --git a/internal/handlers/handler_register_u2f_step1_test.go b/internal/handlers/handler_register_u2f_step1_test.go index a1a15c2e9..fd7d470f6 100644 --- a/internal/handlers/handler_register_u2f_step1_test.go +++ b/internal/handlers/handler_register_u2f_step1_test.go @@ -24,7 +24,7 @@ func (s *HandlerRegisterU2FStep1Suite) SetupTest() { s.mock = mocks.NewMockAutheliaCtx(s.T()) userSession := s.mock.Ctx.GetSession() - userSession.Username = "john" + userSession.Username = testUsername s.mock.Ctx.SaveSession(userSession) //nolint:errcheck // TODO: Legacy code, consider refactoring time permitting. } diff --git a/internal/handlers/handler_sign_duo.go b/internal/handlers/handler_sign_duo.go index cab4ba161..98624e7a0 100644 --- a/internal/handlers/handler_sign_duo.go +++ b/internal/handlers/handler_sign_duo.go @@ -52,7 +52,7 @@ func SecondFactorDuoPost(duoAPI duo.API) middlewares.RequestHandler { } } - if duoResponse.Response.Result != "allow" { + if duoResponse.Response.Result != testResultAllow { ctx.ReplyUnauthorized() return } diff --git a/internal/handlers/handler_sign_duo_test.go b/internal/handlers/handler_sign_duo_test.go index a1cd7b4a1..8a2db7873 100644 --- a/internal/handlers/handler_sign_duo_test.go +++ b/internal/handlers/handler_sign_duo_test.go @@ -24,7 +24,7 @@ type SecondFactorDuoPostSuite struct { func (s *SecondFactorDuoPostSuite) SetupTest() { s.mock = mocks.NewMockAutheliaCtx(s.T()) userSession := s.mock.Ctx.GetSession() - userSession.Username = "john" + userSession.Username = testUsername s.mock.Ctx.SaveSession(userSession) //nolint:errcheck // TODO: Legacy code, consider refactoring time permitting. } @@ -43,7 +43,7 @@ func (s *SecondFactorDuoPostSuite) TestShouldCallDuoAPIAndAllowAccess() { values.Set("pushinfo", "target%20url=https://target.example.com") response := duo.Response{} - response.Response.Result = "allow" + response.Response.Result = testResultAllow duoMock.EXPECT().Call(gomock.Eq(values), s.mock.Ctx).Return(&response, nil) @@ -99,11 +99,11 @@ func (s *SecondFactorDuoPostSuite) TestShouldRedirectUserToDefaultURL() { duoMock := mocks.NewMockAPI(s.mock.Ctrl) response := duo.Response{} - response.Response.Result = "allow" + response.Response.Result = testResultAllow duoMock.EXPECT().Call(gomock.Any(), s.mock.Ctx).Return(&response, nil) - s.mock.Ctx.Configuration.DefaultRedirectionURL = "http://redirection.local" + s.mock.Ctx.Configuration.DefaultRedirectionURL = testRedirectionURL bodyBytes, err := json.Marshal(signDuoRequestBody{}) s.Require().NoError(err) @@ -111,7 +111,7 @@ func (s *SecondFactorDuoPostSuite) TestShouldRedirectUserToDefaultURL() { SecondFactorDuoPost(duoMock)(s.mock.Ctx) s.mock.Assert200OK(s.T(), redirectResponse{ - Redirect: "http://redirection.local", + Redirect: testRedirectionURL, }) } @@ -119,7 +119,7 @@ func (s *SecondFactorDuoPostSuite) TestShouldNotReturnRedirectURL() { duoMock := mocks.NewMockAPI(s.mock.Ctrl) response := duo.Response{} - response.Response.Result = "allow" + response.Response.Result = testResultAllow duoMock.EXPECT().Call(gomock.Any(), s.mock.Ctx).Return(&response, nil) @@ -135,7 +135,7 @@ func (s *SecondFactorDuoPostSuite) TestShouldRedirectUserToSafeTargetURL() { duoMock := mocks.NewMockAPI(s.mock.Ctrl) response := duo.Response{} - response.Response.Result = "allow" + response.Response.Result = testResultAllow duoMock.EXPECT().Call(gomock.Any(), s.mock.Ctx).Return(&response, nil) @@ -155,7 +155,7 @@ func (s *SecondFactorDuoPostSuite) TestShouldNotRedirectToUnsafeURL() { duoMock := mocks.NewMockAPI(s.mock.Ctrl) response := duo.Response{} - response.Response.Result = "allow" + response.Response.Result = testResultAllow duoMock.EXPECT().Call(gomock.Any(), s.mock.Ctx).Return(&response, nil) @@ -173,7 +173,7 @@ func (s *SecondFactorDuoPostSuite) TestShouldRegenerateSessionForPreventingSessi duoMock := mocks.NewMockAPI(s.mock.Ctrl) response := duo.Response{} - response.Response.Result = "allow" + response.Response.Result = testResultAllow duoMock.EXPECT().Call(gomock.Any(), s.mock.Ctx).Return(&response, nil) diff --git a/internal/handlers/handler_sign_totp_test.go b/internal/handlers/handler_sign_totp_test.go index c496ba4b2..a4d89d996 100644 --- a/internal/handlers/handler_sign_totp_test.go +++ b/internal/handlers/handler_sign_totp_test.go @@ -22,7 +22,7 @@ type HandlerSignTOTPSuite struct { func (s *HandlerSignTOTPSuite) SetupTest() { s.mock = mocks.NewMockAutheliaCtx(s.T()) userSession := s.mock.Ctx.GetSession() - userSession.Username = "john" + userSession.Username = testUsername userSession.U2FChallenge = &u2f.Challenge{} userSession.U2FRegistration = &session.U2FRegistration{} s.mock.Ctx.SaveSession(userSession) //nolint:errcheck // TODO: Legacy code, consider refactoring time permitting. @@ -43,7 +43,7 @@ func (s *HandlerSignTOTPSuite) TestShouldRedirectUserToDefaultURL() { Verify(gomock.Eq("abc"), gomock.Eq("secret")). Return(true, nil) - s.mock.Ctx.Configuration.DefaultRedirectionURL = "http://redirection.local" + s.mock.Ctx.Configuration.DefaultRedirectionURL = testRedirectionURL bodyBytes, err := json.Marshal(signTOTPRequestBody{ Token: "abc", @@ -53,7 +53,7 @@ func (s *HandlerSignTOTPSuite) TestShouldRedirectUserToDefaultURL() { SecondFactorTOTPPost(verifier)(s.mock.Ctx) s.mock.Assert200OK(s.T(), redirectResponse{ - Redirect: "http://redirection.local", + Redirect: testRedirectionURL, }) } diff --git a/internal/handlers/handler_sign_u2f_step2_test.go b/internal/handlers/handler_sign_u2f_step2_test.go index 4d42fa19f..45a343307 100644 --- a/internal/handlers/handler_sign_u2f_step2_test.go +++ b/internal/handlers/handler_sign_u2f_step2_test.go @@ -22,7 +22,7 @@ type HandlerSignU2FStep2Suite struct { func (s *HandlerSignU2FStep2Suite) SetupTest() { s.mock = mocks.NewMockAutheliaCtx(s.T()) userSession := s.mock.Ctx.GetSession() - userSession.Username = "john" + userSession.Username = testUsername userSession.U2FChallenge = &u2f.Challenge{} userSession.U2FRegistration = &session.U2FRegistration{} s.mock.Ctx.SaveSession(userSession) //nolint:errcheck // TODO: Legacy code, consider refactoring time permitting. @@ -39,7 +39,7 @@ func (s *HandlerSignU2FStep2Suite) TestShouldRedirectUserToDefaultURL() { Verify(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). Return(nil) - s.mock.Ctx.Configuration.DefaultRedirectionURL = "http://redirection.local" + s.mock.Ctx.Configuration.DefaultRedirectionURL = testRedirectionURL bodyBytes, err := json.Marshal(signU2FRequestBody{ SignResponse: u2f.SignResponse{}, @@ -49,7 +49,7 @@ func (s *HandlerSignU2FStep2Suite) TestShouldRedirectUserToDefaultURL() { SecondFactorU2FSignPost(u2fVerifier)(s.mock.Ctx) s.mock.Assert200OK(s.T(), redirectResponse{ - Redirect: "http://redirection.local", + Redirect: testRedirectionURL, }) } diff --git a/internal/handlers/handler_user_info_test.go b/internal/handlers/handler_user_info_test.go index 2d3c20286..4d925787c 100644 --- a/internal/handlers/handler_user_info_test.go +++ b/internal/handlers/handler_user_info_test.go @@ -22,7 +22,7 @@ func (s *FetchSuite) SetupTest() { s.mock = mocks.NewMockAutheliaCtx(s.T()) // Set the initial user session. userSession := s.mock.Ctx.GetSession() - userSession.Username = "john" + userSession.Username = testUsername userSession.AuthenticationLevel = 1 s.mock.Ctx.SaveSession(userSession) //nolint:errcheck // TODO: Legacy code, consider refactoring time permitting. } @@ -90,7 +90,7 @@ func TestMethodSetToU2F(t *testing.T) { mock := mocks.NewMockAutheliaCtx(t) // Set the initial user session. userSession := mock.Ctx.GetSession() - userSession.Username = "john" + userSession.Username = testUsername userSession.AuthenticationLevel = 1 mock.Ctx.SaveSession(userSession) //nolint:errcheck // TODO: Legacy code, consider refactoring time permitting. @@ -168,7 +168,7 @@ func (s *SaveSuite) SetupTest() { s.mock = mocks.NewMockAutheliaCtx(s.T()) // Set the initial user session. userSession := s.mock.Ctx.GetSession() - userSession.Username = "john" + userSession.Username = testUsername userSession.AuthenticationLevel = 1 s.mock.Ctx.SaveSession(userSession) //nolint:errcheck // TODO: Legacy code, consider refactoring time permitting. } diff --git a/internal/handlers/handler_verify_test.go b/internal/handlers/handler_verify_test.go index 31a85a9e1..4f4521ba6 100644 --- a/internal/handlers/handler_verify_test.go +++ b/internal/handlers/handler_verify_test.go @@ -176,7 +176,7 @@ func TestShouldCheckAuthorizationMatching(t *testing.T) { username := "" if rule.AuthLevel > authentication.NotAuthenticated { - username = "john" + username = testUsername } matching := isTargetURLAuthorized(authorizer, *url, username, []string{}, net.ParseIP("127.0.0.1"), rule.AuthLevel) @@ -472,13 +472,13 @@ func TestShouldDestroySessionWhenInactiveForTooLong(t *testing.T) { clock.Set(time.Now()) past := clock.Now().Add(-1 * time.Hour) - mock.Ctx.Configuration.Session.Inactivity = "10" + mock.Ctx.Configuration.Session.Inactivity = testInactivity // Reload the session provider since the configuration is indirect. mock.Ctx.Providers.SessionProvider = session.NewProvider(mock.Ctx.Configuration.Session) assert.Equal(t, time.Second*10, mock.Ctx.Providers.SessionProvider.Inactivity) userSession := mock.Ctx.GetSession() - userSession.Username = "john" + userSession.Username = testUsername userSession.AuthenticationLevel = authentication.TwoFactor userSession.LastActivity = past.Unix() mock.Ctx.SaveSession(userSession) //nolint:errcheck // TODO: Legacy code, consider refactoring time permitting. @@ -509,7 +509,7 @@ func TestShouldDestroySessionWhenInactiveForTooLongUsingDurationNotation(t *test assert.Equal(t, time.Second*10, mock.Ctx.Providers.SessionProvider.Inactivity) userSession := mock.Ctx.GetSession() - userSession.Username = "john" + userSession.Username = testUsername userSession.AuthenticationLevel = authentication.TwoFactor userSession.LastActivity = clock.Now().Add(-1 * time.Hour).Unix() mock.Ctx.SaveSession(userSession) //nolint:errcheck // TODO: Legacy code, consider refactoring time permitting. @@ -531,10 +531,10 @@ func TestShouldKeepSessionWhenUserCheckedRememberMeAndIsInactiveForTooLong(t *te clock := mocks.TestingClock{} clock.Set(time.Now()) - mock.Ctx.Configuration.Session.Inactivity = "10" + mock.Ctx.Configuration.Session.Inactivity = testInactivity userSession := mock.Ctx.GetSession() - userSession.Username = "john" + userSession.Username = testUsername userSession.AuthenticationLevel = authentication.TwoFactor userSession.LastActivity = 0 userSession.KeepMeLoggedIn = true @@ -560,12 +560,12 @@ func TestShouldKeepSessionWhenInactivityTimeoutHasNotBeenExceeded(t *testing.T) clock := mocks.TestingClock{} clock.Set(time.Now()) - mock.Ctx.Configuration.Session.Inactivity = "10" + mock.Ctx.Configuration.Session.Inactivity = testInactivity past := clock.Now().Add(-1 * time.Hour) userSession := mock.Ctx.GetSession() - userSession.Username = "john" + userSession.Username = testUsername userSession.AuthenticationLevel = authentication.TwoFactor userSession.LastActivity = past.Unix() mock.Ctx.SaveSession(userSession) //nolint:errcheck // TODO: Legacy code, consider refactoring time permitting. @@ -592,7 +592,7 @@ func TestShouldRedirectWhenSessionInactiveForTooLongAndRDParamProvided(t *testin clock := mocks.TestingClock{} clock.Set(time.Now()) - mock.Ctx.Configuration.Session.Inactivity = "10" + mock.Ctx.Configuration.Session.Inactivity = testInactivity // Reload the session provider since the configuration is indirect. mock.Ctx.Providers.SessionProvider = session.NewProvider(mock.Ctx.Configuration.Session) assert.Equal(t, time.Second*10, mock.Ctx.Providers.SessionProvider.Inactivity) @@ -600,7 +600,7 @@ func TestShouldRedirectWhenSessionInactiveForTooLongAndRDParamProvided(t *testin past := clock.Now().Add(-1 * time.Hour) userSession := mock.Ctx.GetSession() - userSession.Username = "john" + userSession.Username = testUsername userSession.AuthenticationLevel = authentication.TwoFactor userSession.LastActivity = past.Unix() mock.Ctx.SaveSession(userSession) //nolint:errcheck // TODO: Legacy code, consider refactoring time permitting. @@ -626,12 +626,12 @@ func TestShouldUpdateInactivityTimestampEvenWhenHittingForbiddenResources(t *tes clock := mocks.TestingClock{} clock.Set(time.Now()) - mock.Ctx.Configuration.Session.Inactivity = "10" + mock.Ctx.Configuration.Session.Inactivity = testInactivity past := clock.Now().Add(-1 * time.Hour) userSession := mock.Ctx.GetSession() - userSession.Username = "john" + userSession.Username = testUsername userSession.AuthenticationLevel = authentication.TwoFactor userSession.LastActivity = past.Unix() mock.Ctx.SaveSession(userSession) //nolint:errcheck // TODO: Legacy code, consider refactoring time permitting. @@ -653,7 +653,7 @@ func TestShouldURLEncodeRedirectionURLParameter(t *testing.T) { defer mock.Close() userSession := mock.Ctx.GetSession() - userSession.Username = "john" + userSession.Username = testUsername userSession.AuthenticationLevel = authentication.NotAuthenticated mock.Ctx.SaveSession(userSession) //nolint:errcheck // TODO: Legacy code, consider refactoring time permitting. diff --git a/internal/middlewares/const.go b/internal/middlewares/const.go index 222ae0816..7565a963e 100644 --- a/internal/middlewares/const.go +++ b/internal/middlewares/const.go @@ -1,6 +1,5 @@ package middlewares -// JWTIssuer is. const jwtIssuer = "Authelia" const xForwardedProtoHeader = "X-Forwarded-Proto" diff --git a/internal/middlewares/identity_verification_test.go b/internal/middlewares/identity_verification_test.go index 4045f52f3..4634eed27 100644 --- a/internal/middlewares/identity_verification_test.go +++ b/internal/middlewares/identity_verification_test.go @@ -15,6 +15,8 @@ import ( "github.com/authelia/authelia/internal/session" ) +const testJWTSecret = "abc" + func newArgs(retriever func(ctx *middlewares.AutheliaCtx) (*session.Identity, error)) middlewares.IdentityVerificationStartArgs { return middlewares.IdentityVerificationStartArgs{ ActionClaim: "Claim", @@ -50,7 +52,7 @@ func TestShouldFailIfJWTCannotBeSaved(t *testing.T) { mock := mocks.NewMockAutheliaCtx(t) defer mock.Close() - mock.Ctx.Configuration.JWTSecret = "abc" + mock.Ctx.Configuration.JWTSecret = testJWTSecret mock.StorageProviderMock.EXPECT(). SaveIdentityVerificationToken(gomock.Any()). @@ -67,7 +69,7 @@ func TestShouldFailSendingAnEmail(t *testing.T) { mock := mocks.NewMockAutheliaCtx(t) defer mock.Close() - mock.Ctx.Configuration.JWTSecret = "abc" + mock.Ctx.Configuration.JWTSecret = testJWTSecret mock.Ctx.Request.Header.Add("X-Forwarded-Proto", "http") mock.Ctx.Request.Header.Add("X-Forwarded-Host", "host") @@ -90,7 +92,7 @@ func TestShouldFailWhenXForwardedProtoHeaderIsMissing(t *testing.T) { mock := mocks.NewMockAutheliaCtx(t) defer mock.Close() - mock.Ctx.Configuration.JWTSecret = "abc" + mock.Ctx.Configuration.JWTSecret = testJWTSecret mock.Ctx.Request.Header.Add("X-Forwarded-Host", "host") mock.StorageProviderMock.EXPECT(). @@ -108,7 +110,7 @@ func TestShouldFailWhenXForwardedHostHeaderIsMissing(t *testing.T) { mock := mocks.NewMockAutheliaCtx(t) defer mock.Close() - mock.Ctx.Configuration.JWTSecret = "abc" + mock.Ctx.Configuration.JWTSecret = testJWTSecret mock.Ctx.Request.Header.Add("X-Forwarded-Proto", "http") mock.StorageProviderMock.EXPECT(). @@ -126,7 +128,7 @@ func TestShouldSucceedIdentityVerificationStartProcess(t *testing.T) { mock := mocks.NewMockAutheliaCtx(t) defer mock.Close() - mock.Ctx.Configuration.JWTSecret = "abc" + mock.Ctx.Configuration.JWTSecret = testJWTSecret mock.Ctx.Request.Header.Add("X-Forwarded-Proto", "http") mock.Ctx.Request.Header.Add("X-Forwarded-Host", "host") @@ -154,7 +156,7 @@ type IdentityVerificationFinishProcess struct { func (s *IdentityVerificationFinishProcess) SetupTest() { s.mock = mocks.NewMockAutheliaCtx(s.T()) - s.mock.Ctx.Configuration.JWTSecret = "abc" + s.mock.Ctx.Configuration.JWTSecret = testJWTSecret } func (s *IdentityVerificationFinishProcess) TearDownTest() { diff --git a/internal/session/const.go b/internal/session/const.go index eb4c75e26..5bb9249e5 100644 --- a/internal/session/const.go +++ b/internal/session/const.go @@ -1,3 +1,8 @@ package session const userSessionStorerKey = "UserSession" + +const testDomain = "example.com" +const testExpiration = "40" +const testName = "my_session" +const testUsername = "john" diff --git a/internal/session/provider_config_test.go b/internal/session/provider_config_test.go index b720aa419..95f22e2c5 100644 --- a/internal/session/provider_config_test.go +++ b/internal/session/provider_config_test.go @@ -18,13 +18,13 @@ import ( func TestShouldCreateInMemorySessionProvider(t *testing.T) { // The redis configuration is not provided so we create a in-memory provider. configuration := schema.SessionConfiguration{} - configuration.Domain = "example.com" - configuration.Name = "my_session" - configuration.Expiration = "40" + configuration.Domain = testDomain + configuration.Name = testName + configuration.Expiration = testExpiration providerConfig := NewProviderConfig(configuration) assert.Equal(t, "my_session", providerConfig.config.CookieName) - assert.Equal(t, "example.com", providerConfig.config.Domain) + assert.Equal(t, testDomain, providerConfig.config.Domain) assert.Equal(t, true, providerConfig.config.Secure) assert.Equal(t, time.Duration(40)*time.Second, providerConfig.config.Expires) assert.True(t, providerConfig.config.IsSecureFunc(nil)) @@ -36,9 +36,9 @@ func TestShouldCreateInMemorySessionProvider(t *testing.T) { func TestShouldCreateRedisSessionProvider(t *testing.T) { // The redis configuration is not provided so we create a in-memory provider. configuration := schema.SessionConfiguration{} - configuration.Domain = "example.com" - configuration.Name = "my_session" - configuration.Expiration = "40" + configuration.Domain = testDomain + configuration.Name = testName + configuration.Expiration = testExpiration configuration.Redis = &schema.RedisSessionConfiguration{ Host: "redis.example.com", Port: 6379, @@ -47,7 +47,7 @@ func TestShouldCreateRedisSessionProvider(t *testing.T) { providerConfig := NewProviderConfig(configuration) assert.Equal(t, "my_session", providerConfig.config.CookieName) - assert.Equal(t, "example.com", providerConfig.config.Domain) + assert.Equal(t, testDomain, providerConfig.config.Domain) assert.Equal(t, true, providerConfig.config.Secure) assert.Equal(t, time.Duration(40)*time.Second, providerConfig.config.Expires) assert.True(t, providerConfig.config.IsSecureFunc(nil)) @@ -65,9 +65,9 @@ func TestShouldCreateRedisSessionProvider(t *testing.T) { func TestShouldSetDbNumber(t *testing.T) { configuration := schema.SessionConfiguration{} - configuration.Domain = "example.com" - configuration.Name = "my_session" - configuration.Expiration = "40" + configuration.Domain = testDomain + configuration.Name = testName + configuration.Expiration = testExpiration configuration.Redis = &schema.RedisSessionConfiguration{ Host: "redis.example.com", Port: 6379, diff --git a/internal/session/provider_test.go b/internal/session/provider_test.go index d8c5248b5..8e2b92640 100644 --- a/internal/session/provider_test.go +++ b/internal/session/provider_test.go @@ -14,9 +14,9 @@ import ( func TestShouldInitializerSession(t *testing.T) { ctx := &fasthttp.RequestCtx{} configuration := schema.SessionConfiguration{} - configuration.Domain = "example.com" - configuration.Name = "my_session" - configuration.Expiration = "40" + configuration.Domain = testDomain + configuration.Name = testName + configuration.Expiration = testExpiration provider := NewProvider(configuration) session, err := provider.GetSession(ctx) @@ -28,14 +28,14 @@ func TestShouldInitializerSession(t *testing.T) { func TestShouldUpdateSession(t *testing.T) { ctx := &fasthttp.RequestCtx{} configuration := schema.SessionConfiguration{} - configuration.Domain = "example.com" - configuration.Name = "my_session" - configuration.Expiration = "40" + configuration.Domain = testDomain + configuration.Name = testName + configuration.Expiration = testExpiration provider := NewProvider(configuration) session, _ := provider.GetSession(ctx) - session.Username = "john" + session.Username = testUsername session.AuthenticationLevel = authentication.TwoFactor err := provider.SaveSession(ctx, session) @@ -45,7 +45,7 @@ func TestShouldUpdateSession(t *testing.T) { require.NoError(t, err) assert.Equal(t, UserSession{ - Username: "john", + Username: testUsername, AuthenticationLevel: authentication.TwoFactor, }, session) } @@ -53,15 +53,15 @@ func TestShouldUpdateSession(t *testing.T) { func TestShouldDestroySessionAndWipeSessionData(t *testing.T) { ctx := &fasthttp.RequestCtx{} configuration := schema.SessionConfiguration{} - configuration.Domain = "example.com" - configuration.Name = "my_session" - configuration.Expiration = "40" + configuration.Domain = testDomain + configuration.Name = testName + configuration.Expiration = testExpiration provider := NewProvider(configuration) session, err := provider.GetSession(ctx) require.NoError(t, err) - session.Username = "john" + session.Username = testUsername session.AuthenticationLevel = authentication.TwoFactor err = provider.SaveSession(ctx, session) @@ -69,7 +69,7 @@ func TestShouldDestroySessionAndWipeSessionData(t *testing.T) { newUserSession, err := provider.GetSession(ctx) require.NoError(t, err) - assert.Equal(t, "john", newUserSession.Username) + assert.Equal(t, testUsername, newUserSession.Username) assert.Equal(t, authentication.TwoFactor, newUserSession.AuthenticationLevel) err = provider.DestroySession(ctx) diff --git a/internal/suites/constants.go b/internal/suites/const.go similarity index 94% rename from internal/suites/constants.go rename to internal/suites/const.go index 77962bdbe..b86fea89f 100644 --- a/internal/suites/constants.go +++ b/internal/suites/const.go @@ -40,3 +40,8 @@ var DuoBaseURL = "https://duo.example.com" // AutheliaBaseURL the base URL of Authelia service. var AutheliaBaseURL = "https://authelia.example.com:9091" + +const stringTrue = "true" + +const testUsername = "john" +const testPassword = "password" diff --git a/internal/suites/docker.go b/internal/suites/docker.go index 883533f42..eb6e78e48 100644 --- a/internal/suites/docker.go +++ b/internal/suites/docker.go @@ -18,7 +18,7 @@ type DockerEnvironment struct { // NewDockerEnvironment create a new docker environment. func NewDockerEnvironment(files []string) *DockerEnvironment { - if os.Getenv("CI") == "true" { + if os.Getenv("CI") == stringTrue { for i := range files { files[i] = strings.ReplaceAll(files[i], "{}", "dist") } diff --git a/internal/suites/environment.go b/internal/suites/environment.go index 627b49b07..c47c6dc64 100644 --- a/internal/suites/environment.go +++ b/internal/suites/environment.go @@ -63,7 +63,7 @@ func waitUntilAutheliaIsReady(dockerEnvironment *DockerEnvironment) error { return err } - if os.Getenv("CI") != "true" { + if os.Getenv("CI") != stringTrue { if err := waitUntilAutheliaFrontendIsReady(dockerEnvironment); err != nil { return err } diff --git a/internal/suites/scenario_two_factor_test.go b/internal/suites/scenario_two_factor_test.go index e01aefe68..d00f620ec 100644 --- a/internal/suites/scenario_two_factor_test.go +++ b/internal/suites/scenario_two_factor_test.go @@ -51,8 +51,8 @@ func (s *TwoFactorSuite) TestShouldAuthorizeSecretAfterTwoFactor() { ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) defer cancel() - username := "john" - password := "password" + username := testUsername + password := testPassword // Login one factor s.doLoginOneFactor(ctx, s.T(), username, password, false, "") @@ -68,7 +68,7 @@ func (s *TwoFactorSuite) TestShouldAuthorizeSecretAfterTwoFactor() { // Login again with 1FA & 2FA targetURL := fmt.Sprintf("%s/secret.html", AdminBaseURL) - s.doLoginTwoFactor(ctx, s.T(), "john", "password", false, secret, targetURL) + s.doLoginTwoFactor(ctx, s.T(), testUsername, testPassword, false, secret, targetURL) // And check if the user is redirected to the secret. s.verifySecretAuthorized(ctx, s.T()) @@ -87,10 +87,10 @@ func (s *TwoFactorSuite) TestShouldFailTwoFactor() { defer cancel() // Register TOTP secret and logout. - s.doRegisterThenLogout(ctx, s.T(), "john", "password") + s.doRegisterThenLogout(ctx, s.T(), testUsername, testPassword) wrongPasscode := "123456" - s.doLoginOneFactor(ctx, s.T(), "john", "password", false, "") + s.doLoginOneFactor(ctx, s.T(), testUsername, testPassword, false, "") s.verifyIsSecondFactorPage(ctx, s.T()) s.doEnterOTP(ctx, s.T(), wrongPasscode) diff --git a/internal/suites/suite_kubernetes.go b/internal/suites/suite_kubernetes.go index 99f00f5af..a6c40d4f7 100644 --- a/internal/suites/suite_kubernetes.go +++ b/internal/suites/suite_kubernetes.go @@ -44,7 +44,7 @@ func init() { } log.Debug("Building authelia:dist image or use cache if already built...") - if os.Getenv("CI") != "true" { + if os.Getenv("CI") != stringTrue { if err := utils.Shell("authelia-scripts docker build").Run(); err != nil { return err } diff --git a/internal/utils/const.go b/internal/utils/const.go index 895975354..2097fc3bc 100644 --- a/internal/utils/const.go +++ b/internal/utils/const.go @@ -24,3 +24,5 @@ const Year = Day * 365 // Month is an int based representation of the time unit. const Month = Year / 12 + +const testStringInput = "abcdefghijkl" diff --git a/internal/utils/strings_test.go b/internal/utils/strings_test.go index 71523836c..8c39941d6 100644 --- a/internal/utils/strings_test.go +++ b/internal/utils/strings_test.go @@ -7,7 +7,7 @@ import ( ) func TestShouldSplitIntoEvenStringsOfFour(t *testing.T) { - input := "abcdefghijkl" + input := testStringInput arrayOfStrings := SliceString(input, 4) assert.Equal(t, len(arrayOfStrings), 3) assert.Equal(t, "abcd", arrayOfStrings[0]) @@ -16,7 +16,7 @@ func TestShouldSplitIntoEvenStringsOfFour(t *testing.T) { } func TestShouldSplitIntoEvenStringsOfOne(t *testing.T) { - input := "abcdefghijkl" + input := testStringInput arrayOfStrings := SliceString(input, 1) assert.Equal(t, 12, len(arrayOfStrings)) assert.Equal(t, "a", arrayOfStrings[0]) @@ -27,7 +27,7 @@ func TestShouldSplitIntoEvenStringsOfOne(t *testing.T) { } func TestShouldSplitIntoUnevenStringsOfFour(t *testing.T) { - input := "abcdefghijklm" + input := testStringInput + "m" arrayOfStrings := SliceString(input, 4) assert.Equal(t, len(arrayOfStrings), 4) assert.Equal(t, "abcd", arrayOfStrings[0])