-
Notifications
You must be signed in to change notification settings - Fork 1
/
controller_polls_test.go
111 lines (96 loc) · 2.45 KB
/
controller_polls_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package main
import (
"context"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/go-chi/chi/v5"
"github.com/kiyutink/sowhenthen/entities"
"github.com/kiyutink/sowhenthen/storage"
)
type testPollStorage struct {
storage.Poll
}
func (tps *testPollStorage) Create(ctx context.Context, p entities.Poll) (entities.Poll, error) {
newPoll := p
newPoll.Id = "test-id"
return newPoll, nil
}
func (tps *testPollStorage) GetOne(ctx context.Context, id string) (entities.Poll, error) {
if id == "non-existent-poll" {
return entities.Poll{}, &storage.NotFoundError{Identifier: id, Err: errors.New("poll doesn't exist")}
}
return entities.Poll{
Id: "test-id",
Options: []string{"test-option-1", "test-option-2"},
Title: "test-title",
}, nil
}
func newTestController() *Controller {
testStorage := storage.Storage{Poll: &testPollStorage{}, Vote: &testVoteStorage{}}
return &Controller{testStorage}
}
func TestHandlePollsGetOne(t *testing.T) {
c := newTestController()
tests := []struct {
id string
expectedStatus int
}{
{"test-poll", http.StatusOK},
{"non-existent-poll", http.StatusNotFound},
}
for _, tt := range tests {
r := httptest.NewRequest("GET", fmt.Sprintf("/api/polls/%v", tt.id), nil)
rctx := chi.NewRouteContext()
rctx.URLParams.Add("id", tt.id)
r = r.WithContext(context.WithValue(r.Context(), chi.RouteCtxKey, rctx))
w := httptest.NewRecorder()
c.handlePollsGetOne()(w, r)
if tt.expectedStatus != w.Result().StatusCode {
t.Errorf("expected response status code to be %v, instead got %v", tt.expectedStatus, w.Code)
}
}
}
func TestHandlePollsCreateOne(t *testing.T) {
c := newTestController()
tests := []struct {
requestBody string
expectedStatus int
}{
{
`{ "title": "test", "options": ["option1"] }`,
http.StatusCreated,
},
{
`{ "title": "test", "options": [] }`,
http.StatusBadRequest,
},
{
`{ "title": "test" }`,
http.StatusBadRequest,
},
{
`{ "options": "test" }`,
http.StatusBadRequest,
},
{
`{ "options": ["test"] }`,
http.StatusBadRequest,
},
{
"",
http.StatusBadRequest,
},
}
for _, tt := range tests {
r := httptest.NewRequest("POST", "/api/polls", strings.NewReader(tt.requestBody))
w := httptest.NewRecorder()
c.handlePollsCreateOne()(w, r)
if w.Result().StatusCode != tt.expectedStatus {
t.Errorf("expected status to be %v, instead got %v", tt.expectedStatus, w.Result().StatusCode)
}
}
}