Debian Codegraph @

fill_test.go

raw symbols SCIP
1 package gosubmit_test
2
3 import (
4 "bytes"
5 "context"
6 "io"
7 "io/ioutil"
8 "net/http"
9 "net/url"
10 "os"
11 "reflect"
12 "regexp"
13 "strings"
14 "testing"
15
16 . "github.com/jeremija/gosubmit"
17 )
18
19 const (
20 defaultMaxMemory = 32 << 20 // 32 MB
21 )
22
23 func mustOpen(t *testing.T, filename string) io.ReadCloser {
24 f, err := os.Open(filename)
25 if err != nil {
26 t.Fatalf("Error opening file: %s (reason: %s)", filename, err)
27 }
28 return f
29 }
30
31 func TestNewTestRequest_recover(t *testing.T) {
32 var f Form
33 _, err := f.NewTestRequest()
34 if err == nil {
35 t.Fatal("Expected an error, but got nil")
36 }
37 expected := "Caught panic when creating request"
38 if msg := err.Error(); !strings.Contains(msg, expected) {
39 t.Errorf("Expected error to contain '%s', but was '%s'", expected, msg)
40 }
41 }
42
43 func TestNewRequest_no_forms_found(t *testing.T) {
44 var f Forms
45
46 for _, form := range []Form{f.First(), f.Last()} {
47 _, err := form.NewTestRequest()
48 if err == nil {
49 t.Fatal("Expected an error, but got nil")
50 }
51 expected := "No forms found"
52 if msg := err.Error(); msg != expected {
53 t.Errorf("Expected error to contain '%s', but was '%s'", expected, msg)
54 }
55 }
56 }
57
58 func TestNewTestRequest_simple_get(t *testing.T) {
59 f := mustOpen(t, "./forms/simple.html")
60 defer f.Close()
61
62 form := ParseWithURL(f, "/test").FindForm("name", "simple-get")
63
64 if form.URL != "/test" {
65 t.Fatalf("Expected form url to fallback to /test, but was %s", form.URL)
66 }
67
68 r, err := form.NewTestRequest(
69 Add("firstName", "John"),
70 )
71
72 if err != nil {
73 t.Fatalf("Could not fill form and create test request: %s", err)
74 }
75
76 if r.Method != http.MethodGet {
77 t.Errorf("Expected request method GET but was: %s", r.Method)
78 }
79
80 if r.URL.EscapedPath() != "/test" {
81 t.Errorf("Expected url path to be /test but was: %s", r.URL.EscapedPath())
82 }
83
84 r.ParseForm()
85 expected := url.Values{
86 "firstName": []string{"John"},
87 }
88 if !reflect.DeepEqual(expected, r.Form) {
89 t.Error("Expected form to be", expected, "but was", r.Form)
90 }
91 }
92
93 func TestFormValidate(t *testing.T) {
94 f := mustOpen(t, "./forms/simple.html")
95 defer f.Close()
96
97 err := ParseWithURL(f, "/test").FindForm("name", "simple-get").Validate(
98 Set("a", "b"),
99 )
100
101 expected := "Cannot find input name='a'"
102 if err == nil || err.Error() != expected {
103 t.Errorf("Expected an error message: '%s', but got '%s'", expected, err.Error())
104 }
105 }
106
107 func TestNewTestRequest_simple_post(t *testing.T) {
108 f := mustOpen(t, "./forms/simple.html")
109 defer f.Close()
110
111 form := ParseWithURL(f, "/test").FindForm("name", "simple-post")
112
113 if form.URL != "/mytest" {
114 t.Fatalf("Expected form url to fallback to /mytest, but was %s", form.URL)
115 }
116
117 r, err := form.NewTestRequest(
118 Add("firstName", "John"),
119 )
120
121 if err != nil {
122 t.Fatalf("Could not fill form and create test request: %s", err)
123 }
124
125 if r.Method != http.MethodPost {
126 t.Errorf("Expected request method POST but was: %s", r.Method)
127 }
128
129 if r.URL.EscapedPath() != "/mytest" {
130 t.Errorf("Expected url path to be /test but was: %s", r.URL.EscapedPath())
131 }
132
133 if r.Header.Get("Content-Type") != ContentTypeForm {
134 t.Errorf("Expepcted content type to be %s, but was %s",
135 ContentTypeForm,
136 r.Header.Get("Content-Type"),
137 )
138 }
139
140 r.ParseForm()
141 expected := url.Values{
142 "firstName": []string{"John"},
143 }
144 if !reflect.DeepEqual(expected, r.Form) {
145 t.Error("Expected form to be", expected, "but was", r.Form)
146 }
147 }
148
149 func TestNewTestRequest_multipart(t *testing.T) {
150 f := mustOpen(t, "./forms/big.html")
151 defer f.Close()
152
153 form := Parse(f).FirstForm()
154
155 pictureContents := []byte("test-file")
156
157 r, err := form.NewTestRequest(
158 Set("sel1", form.GetOptionsFor("sel1")[0]),
159 Add("sel2", "5"),
160 // Add("chk", form.GetOptionsFor("chk")[0]),
161 Add("chk", form.GetOptionsFor("chk")[1]),
162 Set("contact", form.GetOptionsFor("contact")[1]),
163 Set("email", "[email protected]"),
164 Set("firstName", "Test"),
165 Set("age", "33"),
166 AddFile("profile", "picture.jpg", pictureContents),
167 Click("Save 1"),
168 )
169
170 if err != nil {
171 t.Fatalf("Error creating test request: %s", err)
172 }
173
174 if r.Method != http.MethodPost {
175 t.Fatalf("Expected method to be POST, but was %s", r.Method)
176 }
177
178 if r.URL.EscapedPath() != "/submit" {
179 t.Errorf("Expected url to be /submit but was %s", r.URL.EscapedPath())
180 }
181
182 err = r.ParseMultipartForm(defaultMaxMemory)
183 if err != nil {
184 t.Fatalf("Error parsing multipart form: %s", err)
185 }
186
187 expectedForm := url.Values{
188 "sel1": []string{"1"},
189 "sel2": []string{"4", "6", "5"},
190 "chk": []string{"subscribe-mail", "subscribe-phone"},
191 "contact": []string{"phone"},
192 "email": []string{"[email protected]"},
193 "firstName": []string{"Test"},
194 "age": []string{"33"},
195 "lastName": []string{""},
196 "csrf": []string{"1234"},
197 "post": []string{"Big Text"},
198 "action": []string{"Save 1"},
199 }
200
201 if !reflect.DeepEqual(expectedForm, r.PostForm) {
202 t.Error("Expected form to be:\n", expectedForm, "\nbut was:\n", r.PostForm)
203 }
204
205 file, header, err := r.FormFile("profile")
206 if err != nil {
207 t.Errorf("Cannot read profile image: %s", err)
208 }
209 defer file.Close()
210 if header.Filename != "picture.jpg" {
211 t.Errorf("profile filename expected picture.jpg, but was %s", header.Filename)
212 }
213 fileData, err := ioutil.ReadAll(file)
214 if !bytes.Equal(pictureContents, fileData) {
215 t.Errorf("Picture contents do not match: %s vs %s", pictureContents, fileData)
216 }
217 }
218
219 func TestAutoFill(t *testing.T) {
220 f := mustOpen(t, "./forms/big-empty.html")
221 defer f.Close()
222
223 form := Parse(f).FirstForm()
224
225 r, err := form.NewTestRequest(
226 AutoFill(),
227 // autofill won't fill up fields with patterns
228 Set("firstName", "John"),
229 Click("Save 1"),
230 )
231
232 if err != nil {
233 t.Fatalf("Error creating test request: %s", err)
234 }
235
236 err = r.ParseMultipartForm(defaultMaxMemory)
237 if err != nil {
238 t.Fatalf("Error parsing multipart form: %s", err)
239 }
240
241 randomLastName := r.FormValue("lastName")
242 randomCaptcha := r.FormValue("captcha")
243
244 expectedForm := url.Values{
245 "sel2": []string{"4", "5", "6"},
246 "chk": []string{"subscribe-mail", "subscribe-phone"},
247 "contact": []string{"call"},
248 "email": []string{AutoFillEmail},
249 "firstName": []string{"John"},
250 "age": []string{"18"},
251 "captcha": []string{randomCaptcha},
252 "lastName": []string{randomLastName},
253 "someDate": []string{AutoFillDate},
254 "website": []string{AutoFillURL},
255 "other": []string{"other-autofill"},
256 "csrf": []string{"1234"},
257 "post": []string{"Big Text"},
258 "action": []string{"Save 1"},
259 }
260
261 if !reflect.DeepEqual(expectedForm, r.PostForm) {
262 t.Error("Expected form to be:\n", expectedForm, "\nbut was:\n", r.PostForm)
263 }
264
265 file, header, err := r.FormFile("profile")
266 if err != nil {
267 t.Errorf("Cannot read profile image: %s", err)
268 }
269 defer file.Close()
270 if header.Filename != "auto-filename" {
271 t.Errorf("profile filename expected auto-filename, but was %s", header.Filename)
272 }
273 fileData, err := ioutil.ReadAll(file)
274 if !bytes.Equal(AutoFillFile, fileData) {
275 t.Errorf("Picture contents do not match: %s vs %s", AutoFillFile, fileData)
276 }
277 if len(randomCaptcha) != 5 {
278 t.Errorf("Expected captcha to be 5 characters long, but was %d", len(randomCaptcha))
279 }
280 }
281
282 func TestMultipartParams_invalid(t *testing.T) {
283 f := mustOpen(t, "./forms/big.html")
284 defer f.Close()
285
286 form := Parse(f).FirstForm()
287
288 _, _, err := form.MultipartParams(
289 Set("sel1", form.GetOptionsFor("sel1")[0]),
290 )
291
292 re := regexp.MustCompile("Required field.*has no value")
293 if err == nil || !re.MatchString(err.Error()) {
294 t.Errorf("Expected error to match '%s', but was '%s'", re, err.Error())
295 }
296 }
297
298 func TestNewRequest_invalid(t *testing.T) {
299 f := mustOpen(t, "./forms/simple.html")
300 defer f.Close()
301
302 _, err := ParseWithURL(f, "/test").FirstForm().NewRequest(
303 Set("a", "b"),
304 )
305
306 re := regexp.MustCompile("Cannot find input name='a'")
307 if err == nil || !re.MatchString(err.Error()) {
308 t.Fatalf("Expected an error %s, but got: %s", re, err)
309 }
310 }
311
312 func TestNewRequest_missing(t *testing.T) {
313 f := mustOpen(t, "./forms/simple.html")
314 defer f.Close()
315
316 _, err := ParseWithURL(f, "/test").FirstForm().NewRequest()
317
318 re := regexp.MustCompile("Required field 'firstName' has no value")
319 if err == nil || !re.MatchString(err.Error()) {
320 t.Fatalf("Expected an error %s, but got: %s", re, err)
321 }
322 }
323
324 func TestFiller_Reset(t *testing.T) {
325 f := mustOpen(t, "./forms/simple.html")
326 defer f.Close()
327
328 _, err := ParseWithURL(f, "/test").FirstForm().PostParams(
329 Set("firstName", "a"),
330 Reset("firstName"),
331 )
332
333 re := regexp.MustCompile("Required field 'firstName' has no value")
334 if err == nil || !re.MatchString(err.Error()) {
335 t.Fatalf("Expected an error %s, but got: %s", re, err)
336 }
337 }
338
339 func TestFiller_IsRequired(t *testing.T) {
340 f := mustOpen(t, "./forms/simple.html")
341 defer f.Close()
342
343 isRequired := ParseWithURL(f, "/test").FirstForm().IsRequired("firstName")
344 if isRequired == false {
345 t.Fatalf("Field 'firstName' is should be required, but is not")
346 }
347 }
348
349 func TestFiller_NewRequest(t *testing.T) {
350 f := mustOpen(t, "./forms/simple.html")
351 defer f.Close()
352
353 ctx := context.WithValue(context.Background(), "a", "b")
354 r, err := ParseWithURL(f, "/test").FirstForm().NewRequest(
355 Set("firstName", "John"),
356 WithContext(ctx),
357 )
358
359 if err != nil {
360 t.Errorf("Unexpected error: %s", err)
361 }
362
363 if r == nil {
364 t.Errorf("Request is nil")
365 }
366
367 if c := r.Context(); c != ctx {
368 t.Errorf("Context should be the same, but is not")
369 }
370 }
371
372 func TestPostParams_error(t *testing.T) {
373 f := mustOpen(t, "./forms/simple.html")
374 defer f.Close()
375 _, err := Parse(f).FirstForm().PostParams(Set("a", "b"))
376 expected := "Cannot find input name='a'"
377 if err == nil || err.Error() != expected {
378 t.Errorf("Expected an error '%s' but got '%s'", expected, err)
379 }
380 }
381
382 func TestGetParams_error(t *testing.T) {
383 f := mustOpen(t, "./forms/simple.html")
384 defer f.Close()
385 _, err := Parse(f).FirstForm().GetParams(Set("a", "b"))
386 expected := "Cannot find input name='a'"
387 if err == nil || err.Error() != expected {
388 t.Errorf("Expected an error '%s' but got '%s'", expected, err)
389 }
390 }
391
392 func TestGetParams_ok(t *testing.T) {
393 f := mustOpen(t, "./forms/simple.html")
394 defer f.Close()
395 params, err := Parse(f).FirstForm().GetParams(Set("firstName", "b"))
396 if err != nil {
397 t.Errorf("Unexpected error: %s", err)
398 }
399 expected := "firstName=b"
400 if params != expected {
401 t.Errorf("Expected params to be '%s' but was '%s'", expected, params)
402 }
403 }