2024-12-28 17:58:01 +01:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2025-01-02 19:24:32 +01:00
|
|
|
"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{},
|
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
|
|
|
|
}
|
|
|
|
|
2025-01-02 19:24:32 +01:00
|
|
|
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().String(),
|
|
|
|
ExpiresAt: time.Now().Add(100 * time.Hour).String(),
|
|
|
|
}, 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
|
|
|
|
}
|