-
Notifications
You must be signed in to change notification settings - Fork 1
/
main_test.go
276 lines (226 loc) · 6.46 KB
/
main_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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
package main
import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/gorilla/mux"
"github.com/jackc/pgx/v4"
"github.com/stretchr/testify/require"
"github.com/brandur/passages-signup/db"
"github.com/brandur/passages-signup/newslettermeta"
"github.com/brandur/passages-signup/testhelpers"
)
func makeServer(ctx context.Context, t *testing.T, txStarter db.TXStarter, newsletterID string) *Server {
t.Helper()
s, err := NewServer(ctx, &Conf{
DatabaseTXStarter: txStarter,
MailgunAPIKey: "fake-key",
NewsletterID: newsletterID,
// Make sure that we're in testing so that we don't hit the actual Mailgun
// API
PassagesEnv: envTesting,
Port: "5001",
PublicURL: testhelpers.TestPublicURL,
})
require.NoError(t, err)
return s
}
func TestStaticAssets(t *testing.T) {
setup := func(test func(*testing.T)) func(*testing.T) {
return func(t *testing.T) {
t.Helper()
test(t)
}
}
// Wraps the handler in a mux router for a more realistic simulation.
wrapHandler := func(handler http.Handler) http.Handler {
r := mux.NewRouter()
r.PathPrefix("/public/").Handler(handler)
return r
}
t.Run("Disk", setup(func(t *testing.T) { //nolint:thelper
handler := wrapHandler(staticAssetsHandler(false))
recorder := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/public/tiny-preload-image.png", nil)
handler.ServeHTTP(recorder, req)
requireStatusOrPrintBody(t, http.StatusOK, recorder)
}))
t.Run("Embedded", setup(func(t *testing.T) { //nolint:thelper
handler := wrapHandler(staticAssetsHandler(true))
recorder := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/public/tiny-preload-image.png", nil)
handler.ServeHTTP(recorder, req)
requireStatusOrPrintBody(t, http.StatusOK, recorder)
}))
}
func TestHandleConfirm(t *testing.T) {
var (
ctx context.Context
router *mux.Router
server *Server
token string
tx pgx.Tx
)
setup := func(test func(*testing.T)) func(*testing.T) {
return func(t *testing.T) {
t.Helper()
ctx = context.Background()
testhelpers.WithTestTransaction(ctx, t, func(testTx pgx.Tx) {
server = makeServer(ctx, t, testTx, newslettermeta.PassagesID)
token = "test-token"
tx = testTx
// Need to create a router so that path variables are processed correctly.
router = mux.NewRouter()
router.HandleFunc("/confirm/{token}", server.handleConfirm)
test(t)
})
}
}
t.Run("FinishSignup", setup(func(t *testing.T) { //nolint:thelper
// Manually insert a record ready to be finished
_, err := tx.Exec(ctx, `
INSERT INTO signup
(email, token)
VALUES
($1, $2)
`, testhelpers.TestEmail, token)
require.NoError(t, err)
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/confirm/"+token, nil)
router.ServeHTTP(w, req)
resp := w.Result()
defer resp.Body.Close()
require.Equal(t, http.StatusOK, resp.StatusCode)
_, err = io.ReadAll(resp.Body)
require.NoError(t, err)
// Verify that the process has successfully transition the row's
// `completed_at` to a non-nil value.
var completedAt *time.Time
err = tx.QueryRow(ctx, `
SELECT completed_at
FROM signup
WHERE token = $1
`, token).Scan(&completedAt)
require.NoError(t, err)
require.NotNil(t, completedAt)
}))
t.Run("UnknownToken", setup(func(t *testing.T) { //nolint:thelper
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/confirm/"+token, nil)
router.ServeHTTP(w, req)
resp := w.Result()
defer resp.Body.Close()
require.Equal(t, http.StatusNotFound, resp.StatusCode)
_, err := io.ReadAll(resp.Body)
require.NoError(t, err)
}))
}
func TestHandleShow_DifferentNewsletters(t *testing.T) {
var (
ctx context.Context
server *Server
tx pgx.Tx
)
setup := func(test func(*testing.T)) func(*testing.T) {
return func(t *testing.T) {
t.Helper()
ctx = context.Background()
testhelpers.WithTestTransaction(ctx, t, func(testTx pgx.Tx) {
tx = testTx
test(t)
})
}
}
t.Run("NanoglyphSuccess", setup(func(t *testing.T) { //nolint:thelper
server = makeServer(ctx, t, tx, newslettermeta.NanoglyphID)
req := httptest.NewRequest(http.MethodGet, "/", nil)
w := httptest.NewRecorder()
server.handleShow(w, req)
resp := w.Result()
defer resp.Body.Close()
require.Equal(t, http.StatusOK, resp.StatusCode)
_, err := io.ReadAll(resp.Body)
require.NoError(t, err)
}))
t.Run("PassagesSuccess", setup(func(t *testing.T) { //nolint:thelper
server = makeServer(ctx, t, tx, newslettermeta.PassagesID)
req := httptest.NewRequest(http.MethodGet, "/", nil)
w := httptest.NewRecorder()
server.handleShow(w, req)
resp := w.Result()
defer resp.Body.Close()
require.Equal(t, http.StatusOK, resp.StatusCode)
_, err := io.ReadAll(resp.Body)
require.NoError(t, err)
}))
}
func TestHandleSubmit(t *testing.T) {
var (
ctx context.Context
server *Server
)
setup := func(test func(*testing.T)) func(*testing.T) {
return func(t *testing.T) {
t.Helper()
ctx = context.Background()
testhelpers.WithTestTransaction(ctx, t, func(testTx pgx.Tx) {
server = makeServer(ctx, t, testTx, newslettermeta.PassagesID)
test(t)
})
}
}
testCases := []struct {
name string
verb, path string
body io.Reader
wantStatus int
}{
{
"Renders",
"POST", "/submit",
bytes.NewBufferString("email=brandur@example.com"),
http.StatusOK,
},
{
"OnlyRespondsToPOST",
"GET", "/submit",
nil,
http.StatusNotFound,
},
{
"RequiresEmail",
"POST", "/submit",
nil,
http.StatusUnprocessableEntity,
},
}
for _, tc := range testCases {
t.Run(tc.name, setup(func(t *testing.T) { //nolint:thelper
req := httptest.NewRequest(tc.verb, tc.path, tc.body)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
w := httptest.NewRecorder()
server.handleSubmit(w, req)
resp := w.Result()
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.Equal(t, tc.wantStatus, resp.StatusCode,
fmt.Sprintf("Wrong status code (see above); body: %v", string(body)))
}))
}
}
func requireStatusOrPrintBody(t *testing.T, expectedStatusCode int, recorder *httptest.ResponseRecorder) {
t.Helper()
//nolint:bodyclose
require.Equal(t, expectedStatusCode, recorder.Result().StatusCode,
"Expected status %v, but got %v; body was: %s",
expectedStatusCode,
recorder.Result().StatusCode,
recorder.Body.String(),
)
}