File: json_test.go

package info (click to toggle)
golang-github-coreos-pkg 3-1~bpo8%2B1
  • links: PTS, VCS
  • area: main
  • in suites: jessie-backports
  • size: 320 kB
  • sloc: sh: 30; makefile: 3
file content (56 lines) | stat: -rw-r--r-- 1,152 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package httputil

import (
	"net/http/httptest"
	"testing"
)

func TestWriteJSONResponse(t *testing.T) {
	for i, test := range []struct {
		code         int
		resp         interface{}
		expectedJSON string
		expectErr    bool
	}{
		{
			200,
			struct {
				A string
				B string
			}{A: "foo", B: "bar"},
			`{"A":"foo","B":"bar"}`,
			false,
		},
		{
			500,
			// Something that json.Marshal cannot serialize.
			make(chan int),
			"",
			true,
		},
	} {
		w := httptest.NewRecorder()
		err := WriteJSONResponse(w, test.code, test.resp)

		if w.Code != test.code {
			t.Errorf("case %d: w.code == %v, want %v", i, w.Code, test.code)
		}

		if (err != nil) != test.expectErr {
			t.Errorf("case %d: (err != nil) == %v, want %v. err: %v", i, err != nil, test.expectErr, err)
		}

		if string(w.Body.Bytes()) != test.expectedJSON {
			t.Errorf("case %d: w.Body.Bytes()) == %q, want %q", i,
				string(w.Body.Bytes()), test.expectedJSON)
		}

		if !test.expectErr {
			contentType := w.Header()["Content-Type"][0]
			if contentType != JSONContentType {
				t.Errorf("case %d: contentType == %v, want %v", i, contentType, JSONContentType)
			}
		}
	}

}