File tree Expand file tree Collapse file tree 2 files changed +81
-0
lines changed Expand file tree Collapse file tree 2 files changed +81
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ Package form provides methods to generate models from Form and Form from Request.
3+ */
4+ package form
5+
6+ import (
7+ "net/http"
8+
9+ "github.com/gopherdojo/dojo3/kadai4/hioki-daichi/fortune"
10+ "github.com/gopherdojo/dojo3/kadai4/hioki-daichi/person"
11+ )
12+
13+ // RootForm has name.
14+ type RootForm struct {
15+ name string
16+ }
17+
18+ // NewRootForm returns a form for the route of "/".
19+ func NewRootForm (req * http.Request ) * RootForm {
20+ f := & RootForm {}
21+ nameParam := req .URL .Query ().Get ("name" )
22+ if nameParam != "" {
23+ f .name = nameParam
24+ } else {
25+ f .name = "Gopher"
26+ }
27+ return f
28+ }
29+
30+ // NewPerson generates a person according to the content of form.
31+ func (f * RootForm ) NewPerson (ftn fortune.Fortune ) * person.Person {
32+ return person .NewPerson (f .name , ftn )
33+ }
Original file line number Diff line number Diff line change 1+ package form
2+
3+ import (
4+ "net/http/httptest"
5+ "testing"
6+
7+ "github.com/gopherdojo/dojo3/kadai4/hioki-daichi/fortune"
8+ )
9+
10+ func TestForm_NewRootForm (t * testing.T ) {
11+ cases := map [string ]struct {
12+ nameParam string
13+ expected string
14+ }{
15+ "/?name=hioki-daichi" : {nameParam : "hioki-daichi" , expected : "hioki-daichi" },
16+ "/" : {nameParam : "" , expected : "Gopher" },
17+ }
18+
19+ for n , c := range cases {
20+ t .Run (n , func (t * testing.T ) {
21+ nameParam := c .nameParam
22+ expected := c .expected
23+
24+ req := httptest .NewRequest ("GET" , "/" , nil )
25+ q := req .URL .Query ()
26+ q .Add ("name" , nameParam )
27+ req .URL .RawQuery = q .Encode ()
28+ f := NewRootForm (req )
29+
30+ actual := f .name
31+ if actual != expected {
32+ t .Errorf (`unexpected name: expected: "%s" actual: "%s"` , expected , actual )
33+ }
34+ })
35+ }
36+ }
37+
38+ func TestForm_NewPerson (t * testing.T ) {
39+ name := "foo"
40+
41+ f := RootForm {name : name }
42+ p := f .NewPerson (fortune .Daikichi )
43+
44+ actual := p .Name
45+ if actual != name {
46+ t .Errorf (`unexpected name: expected: "%s" actual: "%s"` , name , actual )
47+ }
48+ }
You can’t perform that action at this time.
0 commit comments