| 1 | package gosubmit |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "regexp" |
| 6 | "testing" |
| 7 | ) |
| 8 | |
| 9 | type testMock struct { |
| 10 | log []string |
| 11 | failed bool |
| 12 | helpers int |
| 13 | } |
| 14 | |
| 15 | func (t *testMock) Fatalf(format string, values ...interface{}) { |
| 16 | t.log = append(t.log, fmt.Sprintf(format, values...)) |
| 17 | t.failed = true |
| 18 | } |
| 19 | |
| 20 | func (t *testMock) Helper() { |
| 21 | t.helpers++ |
| 22 | } |
| 23 | |
| 24 | func TestTesting_ok(t *testing.T) { |
| 25 | var f Form |
| 26 | f.Inputs = Inputs{} |
| 27 | input := TextInput{} |
| 28 | input.name = "firstName" |
| 29 | input.inputType = "text" |
| 30 | f.Inputs[input.name] = input |
| 31 | f.URL = "/test" |
| 32 | |
| 33 | mock := &testMock{} |
| 34 | f.Testing(mock).NewTestRequest( |
| 35 | Set("firstName", "John"), |
| 36 | ) |
| 37 | |
| 38 | if mock.failed { |
| 39 | t.Errorf("Should not fail") |
| 40 | } |
| 41 | |
| 42 | if len(mock.log) > 0 { |
| 43 | t.Errorf("Should not write to log") |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | func TestTesting_fail(t *testing.T) { |
| 48 | var f Form |
| 49 | f.Inputs = Inputs{} |
| 50 | input := TextInput{} |
| 51 | input.name = "firstName" |
| 52 | input.inputType = "text" |
| 53 | f.Inputs[input.name] = input |
| 54 | f.URL = "/test" |
| 55 | |
| 56 | mock := &testMock{} |
| 57 | f.Testing(mock).NewTestRequest( |
| 58 | Set("a", "John"), |
| 59 | ) |
| 60 | |
| 61 | if !mock.failed { |
| 62 | t.Errorf("Should have failed") |
| 63 | } |
| 64 | |
| 65 | if len(mock.log) != 1 { |
| 66 | t.Errorf("Should write a log entry") |
| 67 | } |
| 68 | |
| 69 | if mock.helpers != 2 { |
| 70 | t.Errorf("Should have marked 2 helpers, but got: %d", mock.helpers) |
| 71 | } |
| 72 | |
| 73 | log := mock.log[0] |
| 74 | re := regexp.MustCompile("An error occurred: Cannot find input name='a'") |
| 75 | if !re.MatchString(log) { |
| 76 | t.Errorf("Expected log entry to match '%s', but was '%s'", re, log) |
| 77 | } |
| 78 | } |