Files
qv/cmd/web/testutils_test.go

90 lines
2.0 KiB
Go

package main
import (
"code.dlmw.ch/dlmw/qv/internal/models"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"testing"
"time"
)
func newTestApplication(t *testing.T) *application {
return &application{
logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
elections: &mockElectionModel{},
voters: &mockVoterModel{},
votes: &mockVoteModel{},
}
}
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)
}
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,
CreatedAt: time.Now(),
ExpiresAt: time.Now().Add(100 * time.Hour),
}, nil
}
type mockVoterModel struct {
}
func (v *mockVoterModel) Insert(identity string, electionID int) (int, error) {
return 1, nil
}
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
}