From a273e3c7a0ca8a07dd016bbe65559cee6ba0f9e7 Mon Sep 17 00:00:00 2001 From: Xeronith Date: Mon, 29 May 2023 14:05:18 +0330 Subject: [PATCH] feat(app): :safety_vest: add username validator --- app/validators/username_validator.go | 21 ++++++ app/validators/username_validator_test.go | 84 +++++++++++++++++++++++ 2 files changed, 105 insertions(+) create mode 100644 app/validators/username_validator.go create mode 100644 app/validators/username_validator_test.go diff --git a/app/validators/username_validator.go b/app/validators/username_validator.go new file mode 100644 index 0000000..2d2dd84 --- /dev/null +++ b/app/validators/username_validator.go @@ -0,0 +1,21 @@ +package validators + +import ( + "regexp" + + . "github.com/reiver/greatape/components/constants" +) + +func UsernameIsValid(username string) bool { + if !regexp.MustCompile(USERNAME).MatchString(username) { + return false + } + + for _, reservedUsername := range ReservedUsernames { + if username == reservedUsername { + return false + } + } + + return true +} diff --git a/app/validators/username_validator_test.go b/app/validators/username_validator_test.go new file mode 100644 index 0000000..b455e20 --- /dev/null +++ b/app/validators/username_validator_test.go @@ -0,0 +1,84 @@ +package validators_test + +import ( + "testing" + + "github.com/reiver/greatape/app/validators" +) + +func TestUsernameValidator(test *testing.T) { + type arguments struct { + username string + } + + testCases := []struct { + name string + expectation bool + arguments arguments + }{ + { + "Case1", + false, + arguments{ + username: "", + }, + }, + { + "Case2", + false, + arguments{ + username: "admin", + }, + }, + { + "Case3", + true, + arguments{ + username: "johnny", + }, + }, + { + "Case4", + false, + arguments{ + username: "webmaster", + }, + }, + { + "Case5", + true, + arguments{ + username: "susan235", + }, + }, + { + "Case6", + true, + arguments{ + username: "new_user", + }, + }, + { + "Case7", + true, + arguments{ + username: "someone", + }, + }, + { + "Case8", + true, + arguments{ + username: "north10star", + }, + }, + } + + for _, testCase := range testCases { + test.Run(testCase.name, func(test *testing.T) { + if result := validators.UsernameIsValid(testCase.arguments.username); result != testCase.expectation { + test.Errorf("UsernameIsValid() = %v, expected %v", result, testCase.expectation) + } + }) + } +}