From b25e090a7be35022a81c9265758d43950d4a53e8 Mon Sep 17 00:00:00 2001 From: dylan Date: Thu, 9 Jan 2025 18:22:58 +0100 Subject: [PATCH] Write test for max voters reached (only in unknown voters election --- cmd/web/handlers_test.go | 52 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/cmd/web/handlers_test.go b/cmd/web/handlers_test.go index 6dc5962..a7d3002 100644 --- a/cmd/web/handlers_test.go +++ b/cmd/web/handlers_test.go @@ -588,3 +588,55 @@ func TestCreateVotes_AlreadyVoted(t *testing.T) { }) } } + +func TestCreateVotes_UnknownVotersElectionMaxVotersReached(t *testing.T) { + app := newTestApplication(t) + server := newTestServer(t, app.routes()) + defer server.Close() + + mockElections := app.elections.(*mockElectionModel) + mockElections. + On("GetById", mock.Anything). + Return(&models.Election{ + ID: 1, + Name: "Guy of the year", + Tokens: 100, + AreVotersKnown: false, + MaxVoters: 10, + CreatedAt: time.Now(), + ExpiresAt: time.Now().Add(24 * time.Hour), + Choices: []string{"Gandhi", "Buddha"}, + }, nil) + + mockVoters := app.voters.(*mockVoterModel) + mockVoters. + On("Exists", mock.Anything, mock.Anything). + Return(false, nil) + mockVoters. + On("Insert", mock.Anything, mock.Anything). + Return(1, nil) + mockVoters. + On("CountByElection", mock.Anything). + Return(10, nil) + + path := "/votes" + requestBody := api.CreateVotesRequest{ + Choices: []struct { + ChoiceText string `json:"choiceText"` + Tokens int `json:"tokens"` + }{ + {ChoiceText: "Gandhi", Tokens: 60}, + {ChoiceText: "Buddha", Tokens: 40}, + }, + ElectionId: 1, + VoterIdentity: nil, + } + requestBodyJson, err := json.Marshal(requestBody) + if err != nil { + t.Fatal(err) + } + + code, _, _ := server.post(t, path, bytes.NewReader(requestBodyJson)) + + assert.Equal(t, http.StatusUnprocessableEntity, code) +}