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
|
package gosubmit_test
import (
"net/http"
"net/http/httptest"
"regexp"
"testing"
. "github.com/jeremija/gosubmit"
)
func Serve(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodPost:
username := r.FormValue("username")
password := r.FormValue("password")
csrf := r.FormValue("csrf")
if csrf == "1234" && username == "user" && password == "pass" {
w.Write([]byte("Welcome, " + username))
return
}
w.WriteHeader(http.StatusForbidden)
default:
w.Write([]byte(`<!DOCTYPE html>
<html>
<body>
<form name="test" method="POST">
<input type="text" name="username">
<input type="password" name="password">
<input type="hidden" name="csrf" value="1234">
<input type="submit">
</form>`))
}
}
var mux *http.ServeMux
func init() {
mux = http.NewServeMux()
mux.HandleFunc("/auth/login", Serve)
}
func TestLogin(t *testing.T) {
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/auth/login", nil)
mux.ServeHTTP(w, r)
form := ParseResponse(w.Result(), r.URL).FirstForm()
for _, test := range []struct {
code int
pass string
}{
{http.StatusForbidden, "invalid-password"},
{http.StatusOK, "pass"},
} {
t.Run("password_"+test.pass, func(t *testing.T) {
w := httptest.NewRecorder()
r, err := form.NewTestRequest(
Set("username", "user"),
Set("password", test.pass),
)
if err != nil {
t.Fatalf("Error filling in form: %s", err)
}
mux.ServeHTTP(w, r)
if code := w.Result().StatusCode; code != test.code {
t.Fatalf("Expected status code %d, but got %d", test.code, code)
}
})
}
}
func TestFill_invalid(t *testing.T) {
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/auth/login", nil)
mux.ServeHTTP(w, r)
form := ParseResponse(w.Result(), r.URL).FirstForm()
_, err := form.NewTestRequest(
Set("invalid-field", "user"),
)
re := regexp.MustCompile("Cannot find input name='invalid-field'")
if err == nil || !re.MatchString(err.Error()) {
t.Errorf("Expected an error to match %s but got %s", re, err)
}
}
|