package scrape import ( "fmt" "net/http" "net/url" "strings" "testing" "github.com/google/go-cmp/cmp" "golang.org/x/net/html" ) func Test_ParseForms(t *testing.T) { tests := []struct { description string html string forms []htmlForm }{ {"no forms", ``, nil}, {"empty form", `
`, []htmlForm{{Values: url.Values{}}}}, { "single form with one value", `
`, []htmlForm{{Action: "a", Method: "m", Values: url.Values{"n1": {"v1"}}}}, }, { "two forms", `
`, []htmlForm{ {Action: "a1", Method: "m1", Values: url.Values{"n1": {"v1"}}}, {Action: "a2", Method: "m2", Values: url.Values{"n2": {"v2"}}}, }, }, { "form with radio buttons (none checked)", `
`, []htmlForm{{Values: url.Values{}}}, }, { "form with radio buttons", `
`, []htmlForm{{Values: url.Values{"n1": {"v3"}}}}, }, { "form with checkboxes", `
`, []htmlForm{{Values: url.Values{"n1": {"v1"}, "n3": {"v3"}}}}, }, { "single form with textarea", `
`, []htmlForm{{Values: url.Values{"n1": {"v1"}}}}, }, } for _, tt := range tests { t.Run(tt.description, func(t *testing.T) { node, err := html.Parse(strings.NewReader(tt.html)) if err != nil { t.Errorf("error parsing html: %v", err) } if got, want := parseForms(node), tt.forms; !cmp.Equal(got, want) { t.Errorf("parseForms(%q) returned %+v, want %+v", tt.html, got, want) } }) } } func Test_FetchAndSumbitForm(t *testing.T) { client, mux, cleanup := setup() defer cleanup() var submitted bool mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, `
`) }) mux.HandleFunc("/submit", func(w http.ResponseWriter, r *http.Request) { err := r.ParseForm() if err != nil { t.Errorf("error parsing form: %v", err) } want := url.Values{"hidden": {"h"}, "name": {"n"}} if got := r.Form; !cmp.Equal(got, want) { t.Errorf("submitted form contained values %v, want %v", got, want) } submitted = true }) setValues := func(values url.Values) { values.Set("name", "n") } _, err := fetchAndSubmitForm(client.Client, client.baseURL.String()+"/", setValues) if err != nil { t.Errorf("fetchAndSubmitForm returned err: %v", err) } if !submitted { t.Error("form was never submitted") } }