-
Notifications
You must be signed in to change notification settings - Fork 0
/
recaptcha_test.go
110 lines (102 loc) · 2.57 KB
/
recaptcha_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
package recaptcha
import (
"errors"
"net/http"
"net/url"
"strings"
"testing"
)
// https://developers.google.com/recaptcha/docs/faq#id-like-to-run-automated-tests-with-recaptcha.-what-should-i-do
const (
testSecret = "6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe"
// testSitekey = "6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI"
)
func TestVerifyV2(t *testing.T) {
testCases := []struct {
description string
clientResponse string
secret string
err error
}{
{
description: "happy",
secret: testSecret, // secret always leads to success in V2
clientResponse: "anything",
},
{
description: "missing form",
err: ErrNoCaptcha,
},
{
description: "missing secret",
clientResponse: "anything",
err: ErrNoSuccess,
},
}
for _, tt := range testCases {
t.Run(tt.description, func(t *testing.T) {
req := newRequest(t, tt.clientResponse)
_, err := VerifyV2(tt.secret, req)
if !errors.Is(err, tt.err) {
t.Fatalf("want error '%v' but got '%v'", tt.err, err)
}
})
}
}
func TestVerifyV3(t *testing.T) {
testCases := []struct {
description string
clientResponse string
secret string
options []OptionV3
err error
}{
{
description: "happy",
secret: testSecret, // secret always leads to score 0.0 in V3
clientResponse: "anything",
options: []OptionV3{MinScore(0.0)},
},
{
description: "missing_form",
err: ErrNoCaptcha,
},
{
description: "missing_secret",
clientResponse: "wrong",
err: ErrNoSuccess,
},
{
description: "no_success",
secret: testSecret,
clientResponse: "anything",
err: ErrScore,
},
{
description: "wrong_action",
secret: testSecret,
clientResponse: "anything",
options: []OptionV3{MinScore(0.0), Action("register")},
err: ErrAction,
},
}
for _, tt := range testCases {
t.Run(tt.description, func(t *testing.T) {
req := newRequest(t, tt.clientResponse)
_, err := VerifyV3(tt.secret, req, tt.options...)
if !errors.Is(err, tt.err) {
t.Fatalf("want error '%v' but got '%v'", tt.err, err)
}
})
}
}
func newRequest(t *testing.T, clientResponse string) *http.Request {
form := url.Values{"g-recaptcha-response": {clientResponse}}.Encode()
req, err := http.NewRequest(http.MethodPost, "https://example.com", strings.NewReader(form))
if err != nil {
t.Fatal(err)
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.RemoteAddr = "127.0.0.1:58662"
return req
}