| 13 | ) |
| 14 | |
| 15 | func TestHandler(t *testing.T) { |
| 16 | errX := errors.New("x") |
| 17 | |
| 18 | cases := []struct { |
| 19 | rawQuery string |
| 20 | input string |
| 21 | output string |
| 22 | f interface{} |
| 23 | wantErr error |
| 24 | }{ |
| 25 | {"", ``, `{"message":"ok"}`, func() {}, nil}, |
| 26 | {"", ``, `1`, func() int { return 1 }, nil}, |
| 27 | {"", ``, `{"message":"ok"}`, func() error { return nil }, nil}, |
| 28 | {"", ``, ``, func() error { return errX }, errX}, |
| 29 | {"", ``, `1`, func() (int, error) { return 1, nil }, nil}, |
| 30 | {"", ``, ``, func() (int, error) { return 0, errX }, errX}, |
| 31 | {"", `1`, `1`, func(i int) int { return i }, nil}, |
| 32 | {"", `1`, `1`, func(i *int) int { return *i }, nil}, |
| 33 | {"", `"foo"`, `"foo"`, func(s string) string { return s }, nil}, |
| 34 | {"", `{"x":1}`, `1`, func(x struct{ X int }) int { return x.X }, nil}, |
| 35 | {"", `{"x":1}`, `1`, func(x *struct{ X int }) int { return x.X }, nil}, |
| 36 | {"", ``, `1`, func(ctx context.Context) int { return ctx.Value("k").(int) }, nil}, |
| 37 | } |
| 38 | |
| 39 | for _, test := range cases { |
| 40 | var gotErr error |
| 41 | errFunc := func(ctx context.Context, w http.ResponseWriter, err error) { |
| 42 | gotErr = err |
| 43 | } |
| 44 | h, err := Handler(test.f, errFunc) |
| 45 | if err != nil { |
| 46 | t.Errorf("Handler(%v) got err %v", test.f, err) |
| 47 | continue |
| 48 | } |
| 49 | |
| 50 | resp := httptest.NewRecorder() |
| 51 | req, _ := http.NewRequest("GET", "/", strings.NewReader(test.input)) |
| 52 | req.URL.RawQuery = test.rawQuery |
| 53 | ctx := context.WithValue(context.Background(), "k", 1) |
| 54 | h.ServeHTTP(resp, req.WithContext(ctx)) |
| 55 | if resp.Code != 200 { |
| 56 | t.Errorf("%T response code = %d want 200", test.f, resp.Code) |
| 57 | } |
| 58 | got := strings.TrimSpace(resp.Body.String()) |
| 59 | if got != test.output { |
| 60 | t.Errorf("%T response body = %#q want %#q", test.f, got, test.output) |
| 61 | } |
| 62 | if gotErr != test.wantErr { |
| 63 | t.Errorf("%T err = %v want %v", test.f, gotErr, test.wantErr) |
| 64 | } |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | func TestReadErr(t *testing.T) { |
| 69 | var gotErr error |