-
Notifications
You must be signed in to change notification settings - Fork 15
/
middleware_test.go
76 lines (59 loc) · 1.65 KB
/
middleware_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
package main
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"testing"
"github.com/recursecenter/pairing-bot/internal/assert"
)
func Test_cron(t *testing.T) {
t.Run("run job for AppEngine", func(t *testing.T) {
// Arrange a cron job that tells us whether it ran.
ran := false
handler := cron(func(context.Context) error {
ran = true
return nil
})
// Prepare an AppEngine-sourced request.
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.Header.Set("X-Appengine-Cron", "true")
// Run it!
w := httptest.NewRecorder()
handler(w, req)
resp := w.Result()
defer resp.Body.Close()
assert.Equal(t, ran, true)
assert.Equal(t, resp.StatusCode, 200)
})
t.Run("deny request outside of cron", func(t *testing.T) {
// Arrange a cron job that fails the test if it runs.
handler := cron(func(context.Context) error {
t.Error("handler should not have run")
return nil
})
// Prepare a request from outside of AppEngine (no custom header).
req := httptest.NewRequest(http.MethodGet, "/", nil)
// Run it!
w := httptest.NewRecorder()
handler(w, req)
resp := w.Result()
defer resp.Body.Close()
assert.Equal(t, resp.StatusCode, 404)
})
t.Run("report job failure", func(t *testing.T) {
// Arrange a cron job that errors.
handler := cron(func(context.Context) error {
return errors.New("test error")
})
// Prepare an AppEngine-sourced request.
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.Header.Set("X-Appengine-Cron", "true")
// Run it!
w := httptest.NewRecorder()
handler(w, req)
resp := w.Result()
defer resp.Body.Close()
assert.Equal(t, resp.StatusCode, 500)
})
}