forked from bakape/captchouli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservice_test.go
70 lines (58 loc) · 1.32 KB
/
service_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
package captchouli
import (
"encoding/base64"
"net/http/httptest"
"net/url"
"strings"
"testing"
"github.com/bakape/captchouli/common"
)
func TestCaptcha(t *testing.T) {
router := newService(t).Router()
// Create
r := httptest.NewRequest("GET", "/", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, r)
assertCode(t, w, 200)
// Generate solution
id, solution, err := ExtractCaptcha(w.Body)
if err != nil {
t.Fatal(err)
}
data := url.Values{
common.IDKey: {base64.StdEncoding.EncodeToString(id[:])},
}
for _, i := range solution {
data.Set(solutionIDs[i], "on")
}
dataR := strings.NewReader(data.Encode())
testRequest := func(url string, code int) {
t.Helper()
dataR.Seek(0, 0)
r = httptest.NewRequest("POST", url, dataR)
r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
w = httptest.NewRecorder()
router.ServeHTTP(w, r)
assertCode(t, w, code)
}
// Solve
testRequest("/", 200)
// Check status
testRequest("/status", 200)
if s := w.Body.String(); s != "true" {
t.Fatal(s)
}
// Second captcha should be deleted now
testRequest("/status", 200)
if s := w.Body.String(); s != "false" {
t.Fatal(s)
}
// Failure redirect
testRequest("/", 200)
}
func assertCode(t *testing.T, w *httptest.ResponseRecorder, code int) {
t.Helper()
if w.Code != code {
t.Fatal(w.Code)
}
}