From a1af7a48b2b7891cc3195588b997b0e40825ce96 Mon Sep 17 00:00:00 2001 From: dylan Date: Tue, 21 Jan 2025 09:24:51 +0100 Subject: [PATCH] Fix maxVoters check and add unit tests --- cmd/web/handlers.go | 5 ++++- cmd/web/handlers_test.go | 15 ++++++++++++++- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/cmd/web/handlers.go b/cmd/web/handlers.go index b4c6d82..3ea84e7 100644 --- a/cmd/web/handlers.go +++ b/cmd/web/handlers.go @@ -72,13 +72,16 @@ func (r *createElectionRequestWithValidator) isValid() bool { r.CheckField(validator.After(r.ExpiresAt, time.Now()), "expiresAt", "must expire in a future date") r.CheckField(validator.GreaterThan(len(r.Choices), 1), "choices", "there must be more than 1 choice") r.CheckField(validator.UniqueValues(r.Choices), "choices", "must not contain duplicate values") - r.CheckField(validator.LesserThan(r.MaxVoters, 101), "maxVoters", "cannot create a known-voters election with more than 100 voters") for _, choice := range r.Choices { r.CheckField(validator.NotBlank(choice), "choice", "must not be blank") } if r.AreVotersKnown { + r.CheckField(validator.LesserThan(r.MaxVoters, 101), + "maxVoters", + "cannot create a known-voters election with more than 100 voters", + ) r.CheckField( validator.GreaterThan(r.MaxVoters, 0), "maxVoters", diff --git a/cmd/web/handlers_test.go b/cmd/web/handlers_test.go index 5d489b5..bdccb9c 100644 --- a/cmd/web/handlers_test.go +++ b/cmd/web/handlers_test.go @@ -82,7 +82,7 @@ func TestCreateElection(t *testing.T) { Choices: []string{"Gandhi", "Buddha"}, ExpiresAt: time.Now().Add(24 * time.Hour), AreVotersKnown: false, - MaxVoters: 10, + MaxVoters: 1000, Name: "Guy of the year", Tokens: 100, }, @@ -179,6 +179,19 @@ func TestCreateElection(t *testing.T) { }, expectedCode: http.StatusUnprocessableEntity, }, + { + name: "Invalid request for known voters election (max voters greater than 100)", + urlPath: path, + body: api.CreateElectionRequest{ + Choices: []string{"Gandhi", "Buddha", ""}, + ExpiresAt: time.Now().Add(24 * time.Hour), + AreVotersKnown: true, + MaxVoters: 101, + Name: "Guy of the year", + Tokens: 100, + }, + expectedCode: http.StatusUnprocessableEntity, + }, } for _, tt := range tests {