From 69ea7494f3b3d72c7cc4ed8eacf06e48f8da93a2 Mon Sep 17 00:00:00 2001 From: Andre Medeiros Date: Sat, 7 May 2022 11:21:01 -0400 Subject: [PATCH] write tests --- internal/api/accounts.go | 2 +- internal/domain/subreddit.go | 15 +++++++++++++- internal/domain/subreddit_test.go | 34 +++++++++++++++++++++++++++++++ 3 files changed, 49 insertions(+), 2 deletions(-) create mode 100644 internal/domain/subreddit_test.go diff --git a/internal/api/accounts.go b/internal/api/accounts.go index 1b0e0fa..59c0487 100644 --- a/internal/api/accounts.go +++ b/internal/api/accounts.go @@ -195,7 +195,7 @@ func (a *api) upsertAccountsHandler(w http.ResponseWriter, r *http.Request) { return } - resp, err := a.httpClient.Do(req) + resp, _ := a.httpClient.Do(req) resp.Body.Close() }(apns) diff --git a/internal/domain/subreddit.go b/internal/domain/subreddit.go index 9c06797..9f74eb8 100644 --- a/internal/domain/subreddit.go +++ b/internal/domain/subreddit.go @@ -2,6 +2,7 @@ package domain import ( "context" + "errors" "regexp" "strings" @@ -21,9 +22,21 @@ func (sr *Subreddit) NormalizedName() string { return strings.ToLower(sr.Name) } +func validPrefix(value interface{}) error { + s, _ := value.(string) + if len(s) < 2 { + return nil + } + if s[1] != '_' || s[0] != 'u' { + return nil + } + + return errors.New("invalid subreddit format") +} + func (sr *Subreddit) Validate() error { return validation.ValidateStruct(sr, - validation.Field(&sr.Name, validation.Required, validation.Length(3, 32), validation.Match(regexp.MustCompile(`^(?!u_)[a-zA-Z0-9]\w{1,19}$`))), + validation.Field(&sr.Name, validation.Required, validation.Length(3, 32), validation.By(validPrefix), validation.Match(regexp.MustCompile(`^[a-zA-Z0-9]\w{1,19}$`))), validation.Field(&sr.SubredditID, validation.Required, validation.Length(4, 9)), ) } diff --git a/internal/domain/subreddit_test.go b/internal/domain/subreddit_test.go new file mode 100644 index 0000000..658b33d --- /dev/null +++ b/internal/domain/subreddit_test.go @@ -0,0 +1,34 @@ +package domain + +import ( + "errors" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestValidate(t *testing.T) { + tests := map[string]struct { + subreddit Subreddit + err error + }{ + "invalid subreddit prefix": {Subreddit{Name: "u_iamthatis"}, errors.New("invalid subreddit format")}, + "valid subreddit": {Subreddit{Name: "pics", SubredditID: "abcd"}, nil}, + "valid subreddit starting with u": {Subreddit{Name: "urcool", SubredditID: "abcd"}, nil}, + "valid subreddit with _": {Subreddit{Name: "p_i_x_a_r", SubredditID: "abcd"}, nil}, + } + + for scenario, tc := range tests { + t.Run(scenario, func(t *testing.T) { + err := tc.subreddit.Validate() + + if tc.err == nil { + require.NoError(t, err) + return + } + + assert.Error(t, err) + }) + } +}