Files
qv/cmd/web/testutils_test.go

90 lines
2.0 KiB
Go
Raw Normal View History

2024-12-28 17:58:01 +01:00
package main
import (
"code.dlmw.ch/dlmw/qv/internal/models"
2024-12-28 17:58:01 +01:00
"io"
"log/slog"
"net/http"
"net/http/httptest"
"testing"
2024-12-31 14:35:31 +01:00
"time"
2024-12-28 17:58:01 +01:00
)
func newTestApplication(t *testing.T) *application {
return &application{
2024-12-30 20:53:53 +01:00
logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
2024-12-31 14:35:31 +01:00
elections: &mockElectionModel{},
voters: &mockVoterModel{},
2025-01-08 13:57:49 +01:00
votes: &mockVoteModel{},
2024-12-28 17:58:01 +01:00
}
}
type testServer struct {
*httptest.Server
}
func newTestServer(t *testing.T, h http.Handler) *testServer {
server := httptest.NewServer(h)
return &testServer{server}
}
func (ts *testServer) post(t *testing.T, urlPath string, body io.Reader) (int, http.Header, string) {
res, err := ts.Client().Post(ts.URL+urlPath, "application/json", body)
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
responseBody, err := io.ReadAll(res.Body)
if err != nil {
t.Fatal(err)
}
return res.StatusCode, res.Header, string(responseBody)
}
2024-12-31 14:35:31 +01:00
type mockElectionModel struct {
}
func (e *mockElectionModel) Insert(name string, tokens int, areVotersKnown bool, maxVoters int, choices []string, expiresAt time.Time) (int, error) {
return 1, nil
}
func (e *mockElectionModel) GetById(id int) (*models.Election, error) {
return &models.Election{
ID: id,
Name: "Guy of the year",
Tokens: 100,
AreVotersKnown: false,
MaxVoters: 10,
2025-01-08 13:57:49 +01:00
CreatedAt: time.Now(),
ExpiresAt: time.Now().Add(100 * time.Hour),
}, nil
}
2024-12-31 14:35:31 +01:00
type mockVoterModel struct {
}
func (v *mockVoterModel) Insert(identity string, electionID int) (int, error) {
return 1, nil
}
2025-01-08 13:57:49 +01:00
func (v *mockVoterModel) CountByElection(electionID int) (int, error) {
return 10, nil
}
func (v *mockVoterModel) Exists(voterIdentity string, electionID int) (bool, error) {
return true, nil
}
type mockVoteModel struct {
}
func (v *mockVoteModel) Insert(voterIdentity string, electionId int, choiceText string, tokens int) (int, error) {
return 1, nil
}
func (v *mockVoteModel) Exists(voterIdentity string, electionID int) (bool, error) {
return true, nil
}