OSDN Git Service

Added net module.
[bytom/bytom.git] / net / http / httpjson / io_test.go
1 package httpjson
2
3 import (
4         "bytes"
5         "context"
6         "errors"
7         "net/http/httptest"
8         "os"
9         "strings"
10         "testing"
11
12         "github.com/bytom/log"
13 )
14
15 func TestWriteArray(t *testing.T) {
16         examples := []struct {
17                 in   []int
18                 want string
19         }{
20                 {nil, "[]"},
21                 {[]int{}, "[]"},
22                 {make([]int, 0), "[]"},
23         }
24
25         for _, ex := range examples {
26                 rec := httptest.NewRecorder()
27                 Write(context.Background(), rec, 200, ex.in)
28                 got := strings.TrimSpace(rec.Body.String())
29                 if got != ex.want {
30                         t.Errorf("Write(%v) = %v want %v", ex.in, got, ex.want)
31                 }
32         }
33 }
34
35 func TestWriteErr(t *testing.T) {
36         var buf bytes.Buffer
37         log.SetOutput(&buf)
38         defer log.SetOutput(os.Stderr)
39
40         want := "test-error"
41
42         ctx := context.Background()
43         resp := &errResponse{httptest.NewRecorder(), errors.New(want)}
44         Write(ctx, resp, 200, "ok")
45         got := buf.String()
46         if !strings.Contains(got, want) {
47                 t.Errorf("log = %v; should contain %q", got, want)
48         }
49 }
50
51 type errResponse struct {
52         *httptest.ResponseRecorder
53         err error
54 }
55
56 func (r *errResponse) Write([]byte) (int, error) {
57         return 0, r.err
58 }