| 1 | package gosubmit_test |
| 2 | |
| 3 | import ( |
| 4 | "net/http" |
| 5 | "net/http/httptest" |
| 6 | "regexp" |
| 7 | "testing" |
| 8 | |
| 9 | . "github.com/jeremija/gosubmit" |
| 10 | ) |
| 11 | |
| 12 | func Serve(w http.ResponseWriter, r *http.Request) { |
| 13 | switch r.Method { |
| 14 | case http.MethodPost: |
| 15 | username := r.FormValue("username") |
| 16 | password := r.FormValue("password") |
| 17 | csrf := r.FormValue("csrf") |
| 18 | if csrf == "1234" && username == "user" && password == "pass" { |
| 19 | w.Write([]byte("Welcome, " + username)) |
| 20 | return |
| 21 | } |
| 22 | w.WriteHeader(http.StatusForbidden) |
| 23 | default: |
| 24 | w.Write([]byte(`<!DOCTYPE html> |
| 25 | <html> |
| 26 | <body> |
| 27 | <form name="test" method="POST"> |
| 28 | <input type="text" name="username"> |
| 29 | <input type="password" name="password"> |
| 30 | <input type="hidden" name="csrf" value="1234"> |
| 31 | <input type="submit"> |
| 32 | </form>`)) |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | var mux *http.ServeMux |
| 37 | |
| 38 | func init() { |
| 39 | mux = http.NewServeMux() |
| 40 | mux.HandleFunc("/auth/login", Serve) |
| 41 | } |
| 42 | |
| 43 | func TestLogin(t *testing.T) { |
| 44 | w := httptest.NewRecorder() |
| 45 | r := httptest.NewRequest("GET", "/auth/login", nil) |
| 46 | |
| 47 | mux.ServeHTTP(w, r) |
| 48 | |
| 49 | form := ParseResponse(w.Result(), r.URL).FirstForm() |
| 50 | |
| 51 | for _, test := range []struct { |
| 52 | code int |
| 53 | pass string |
| 54 | }{ |
| 55 | {http.StatusForbidden, "invalid-password"}, |
| 56 | {http.StatusOK, "pass"}, |
| 57 | } { |
| 58 | t.Run("password_"+test.pass, func(t *testing.T) { |
| 59 | w := httptest.NewRecorder() |
| 60 | r, err := form.NewTestRequest( |
| 61 | Set("username", "user"), |
| 62 | Set("password", test.pass), |
| 63 | ) |
| 64 | |
| 65 | if err != nil { |
| 66 | t.Fatalf("Error filling in form: %s", err) |
| 67 | } |
| 68 | |
| 69 | mux.ServeHTTP(w, r) |
| 70 | |
| 71 | if code := w.Result().StatusCode; code != test.code { |
| 72 | t.Fatalf("Expected status code %d, but got %d", test.code, code) |
| 73 | } |
| 74 | }) |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | func TestFill_invalid(t *testing.T) { |
| 79 | w := httptest.NewRecorder() |
| 80 | r := httptest.NewRequest("GET", "/auth/login", nil) |
| 81 | |
| 82 | mux.ServeHTTP(w, r) |
| 83 | |
| 84 | form := ParseResponse(w.Result(), r.URL).FirstForm() |
| 85 | |
| 86 | _, err := form.NewTestRequest( |
| 87 | Set("invalid-field", "user"), |
| 88 | ) |
| 89 | |
| 90 | re := regexp.MustCompile("Cannot find input name='invalid-field'") |
| 91 | if err == nil || !re.MatchString(err.Error()) { |
| 92 | t.Errorf("Expected an error to match %s but got %s", re, err) |
| 93 | } |
| 94 | } |