Implement mocking and update tests for createElection

This commit is contained in:
2025-01-08 17:18:53 +01:00
parent 49a1df06d2
commit bf3368b736
4 changed files with 46 additions and 2 deletions

View File

@ -4,7 +4,9 @@ import (
"bytes"
"code.dlmw.ch/dlmw/qv/internal"
"encoding/json"
"fmt"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"net/http"
"testing"
"time"
@ -15,6 +17,11 @@ func TestCreateElection(t *testing.T) {
server := newTestServer(t, app.routes())
defer server.Close()
mockElections := app.elections.(*mockElectionModel)
mockElections.
On("Insert", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).
Return(1, nil)
path := "/election"
tests := []struct {
@ -180,3 +187,32 @@ func TestCreateElection(t *testing.T) {
})
}
}
func TestCreateElection_ServerError(t *testing.T) {
app := newTestApplication(t)
server := newTestServer(t, app.routes())
defer server.Close()
mockElections := app.elections.(*mockElectionModel)
mockElections.
On("Insert", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).
Return(0, fmt.Errorf(""))
path := "/election"
requestBody := api.CreateElectionRequest{
Choices: []string{"宮本武蔵", "伊東一刀斎"},
ExpiresAt: time.Now().Add(24 * time.Hour),
AreVotersKnown: false,
MaxVoters: 0,
Name: "強",
Tokens: 100,
}
requestBodyJson, err := json.Marshal(requestBody)
if err != nil {
t.Fatal(err)
}
code, _, _ := server.post(t, path, bytes.NewReader(requestBodyJson))
assert.Equal(t, 500, code)
}

View File

@ -2,6 +2,7 @@ package main
import (
"code.dlmw.ch/dlmw/qv/internal/models"
"github.com/stretchr/testify/mock"
"io"
"log/slog"
"net/http"
@ -44,10 +45,12 @@ func (ts *testServer) post(t *testing.T, urlPath string, body io.Reader) (int, h
}
type mockElectionModel struct {
mock.Mock
}
func (e *mockElectionModel) Insert(name string, tokens int, areVotersKnown bool, maxVoters int, choices []string, expiresAt time.Time) (int, error) {
return 1, nil
args := e.Called(name, tokens, areVotersKnown, maxVoters, choices, expiresAt)
return args.Int(0), args.Error(1)
}
func (e *mockElectionModel) GetById(id int) (*models.Election, error) {
@ -78,10 +81,12 @@ func (v *mockVoterModel) Exists(voterIdentity string, electionID int) (bool, err
}
type mockVoteModel struct {
mock.Mock
}
func (v *mockVoteModel) Insert(voterIdentity string, electionId int, choiceText string, tokens int) (int, error) {
return 1, nil
args := v.Called(voterIdentity, electionId, choiceText, tokens)
return args.Int(0), args.Error(1)
}
func (v *mockVoteModel) Exists(voterIdentity string, electionID int) (bool, error) {