jsonhttp_test.go 9.88 KB
Newer Older
Janos Guljas's avatar
Janos Guljas committed
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
// Copyright 2020 The Swarm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package jsonhttp_test

import (
	"encoding/json"
	"errors"
	"net"
	"net/http"
	"net/http/httptest"
	"reflect"
	"testing"

	"github.com/ethersphere/bee/pkg/jsonhttp"
)

func TestRespond_defaults(t *testing.T) {
	w := httptest.NewRecorder()

	jsonhttp.Respond(w, 0, nil)

	statusCode := w.Result().StatusCode
	wantCode := http.StatusOK
	if statusCode != wantCode {
		t.Errorf("got status code %d, want %d", statusCode, wantCode)
	}

	var m *jsonhttp.StatusResponse

	if err := json.Unmarshal(w.Body.Bytes(), &m); err != nil {
		t.Errorf("json unmarshal response body: %s", err)
	}

	if m.Code != wantCode {
		t.Errorf("got message code %d, want %d", m.Code, wantCode)
	}

	wantMessage := http.StatusText(wantCode)
	if m.Message != wantMessage {
		t.Errorf("got message message %q, want %q", m.Message, wantMessage)
	}
44 45

	testContentType(t, w)
Janos Guljas's avatar
Janos Guljas committed
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
}

func TestRespond_statusResponse(t *testing.T) {
	for _, tc := range []struct {
		code int
	}{
		{code: http.StatusContinue},
		{code: http.StatusSwitchingProtocols},
		{code: http.StatusOK},
		{code: http.StatusCreated},
		{code: http.StatusAccepted},
		{code: http.StatusNonAuthoritativeInfo},
		{code: http.StatusResetContent},
		{code: http.StatusPartialContent},
		{code: http.StatusMultipleChoices},
		{code: http.StatusMovedPermanently},
		{code: http.StatusFound},
		{code: http.StatusSeeOther},
		{code: http.StatusNotModified},
		{code: http.StatusUseProxy},
		{code: http.StatusTemporaryRedirect},
		{code: http.StatusPermanentRedirect},
		{code: http.StatusBadRequest},
		{code: http.StatusUnauthorized},
		{code: http.StatusPaymentRequired},
		{code: http.StatusForbidden},
		{code: http.StatusNotFound},
		{code: http.StatusMethodNotAllowed},
		{code: http.StatusNotAcceptable},
		{code: http.StatusProxyAuthRequired},
		{code: http.StatusRequestTimeout},
		{code: http.StatusConflict},
		{code: http.StatusGone},
		{code: http.StatusLengthRequired},
		{code: http.StatusPreconditionFailed},
		{code: http.StatusRequestEntityTooLarge},
		{code: http.StatusRequestURITooLong},
		{code: http.StatusUnsupportedMediaType},
		{code: http.StatusRequestedRangeNotSatisfiable},
		{code: http.StatusExpectationFailed},
		{code: http.StatusTeapot},
		{code: http.StatusUpgradeRequired},
		{code: http.StatusPreconditionRequired},
		{code: http.StatusTooManyRequests},
		{code: http.StatusRequestHeaderFieldsTooLarge},
		{code: http.StatusUnavailableForLegalReasons},
		{code: http.StatusInternalServerError},
		{code: http.StatusNotImplemented},
		{code: http.StatusBadGateway},
		{code: http.StatusServiceUnavailable},
		{code: http.StatusGatewayTimeout},
		{code: http.StatusHTTPVersionNotSupported},
	} {
		w := httptest.NewRecorder()

		jsonhttp.Respond(w, tc.code, nil)

		statusCode := w.Result().StatusCode
		if statusCode != tc.code {
			t.Errorf("got status code %d, want %d", statusCode, tc.code)
		}

		var m *jsonhttp.StatusResponse

		if err := json.Unmarshal(w.Body.Bytes(), &m); err != nil {
			t.Errorf("json unmarshal response body: %s", err)
		}

		if m.Code != tc.code {
			t.Errorf("got message code %d, want %d", m.Code, tc.code)
		}

		wantMessage := http.StatusText(tc.code)
		if m.Message != wantMessage {
			t.Errorf("got message message %q, want %q", m.Message, wantMessage)
		}
122 123

		testContentType(t, w)
Janos Guljas's avatar
Janos Guljas committed
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
	}
}

func TestRespond_special(t *testing.T) {
	for _, tc := range []struct {
		name        string
		code        int
		response    interface{}
		wantMessage string
	}{
		{
			name:        "string 200",
			code:        http.StatusOK,
			response:    "custom message",
			wantMessage: "custom message",
		},
		{
			name:        "string 404",
			code:        http.StatusNotFound,
			response:    "element not found",
			wantMessage: "element not found",
		},
		{
			name:        "error 400",
			code:        http.StatusBadRequest,
			response:    errors.New("test error"),
			wantMessage: "test error",
		},
		{
			name:        "error 500",
			code:        http.StatusInternalServerError,
			response:    errors.New("test error"),
			wantMessage: "test error",
		},
		{
			name:        "stringer 200",
			code:        http.StatusOK,
			response:    net.IPv4(127, 0, 0, 1), // net.IP implements Stringer interface
			wantMessage: "127.0.0.1",
		},
		{
			name:        "stringer 403",
			code:        http.StatusForbidden,
			response:    net.IPv4(2, 4, 8, 16), // net.IP implements Stringer interface
			wantMessage: "2.4.8.16",
		},
	} {
		t.Run(tc.name, func(t *testing.T) {
			w := httptest.NewRecorder()

			jsonhttp.Respond(w, tc.code, tc.response)

			statusCode := w.Result().StatusCode
			if statusCode != tc.code {
				t.Errorf("got status code %d, want %d", statusCode, tc.code)
			}

			var m *jsonhttp.StatusResponse

			if err := json.Unmarshal(w.Body.Bytes(), &m); err != nil {
				t.Errorf("json unmarshal response body: %s", err)
			}

			if m.Code != tc.code {
				t.Errorf("got message code %d, want %d", m.Code, tc.code)
			}

			if m.Message != tc.wantMessage {
				t.Errorf("got message message %q, want %q", m.Message, tc.wantMessage)
			}
194 195

			testContentType(t, w)
Janos Guljas's avatar
Janos Guljas committed
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
		})
	}
}

func TestRespond_custom(t *testing.T) {
	w := httptest.NewRecorder()

	wantCode := http.StatusTeapot

	type response struct {
		Field1 string `json:"field1"`
		Field2 int    `json:"field2"`
	}

	r := response{
		Field1: "custom message",
		Field2: 42,
	}
	jsonhttp.Respond(w, wantCode, r)

	statusCode := w.Result().StatusCode
	if statusCode != wantCode {
		t.Errorf("got status code %d, want %d", statusCode, wantCode)
	}

	var m response

	if err := json.Unmarshal(w.Body.Bytes(), &m); err != nil {
		t.Errorf("json unmarshal response body: %s", err)
	}

	if !reflect.DeepEqual(m, r) {
		t.Errorf("got response %+v, want %+v", m, r)
	}
230 231

	testContentType(t, w)
Janos Guljas's avatar
Janos Guljas committed
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
}

func TestStandardHTTPResponds(t *testing.T) {
	for _, tc := range []struct {
		f    func(w http.ResponseWriter, response interface{})
		code int
	}{
		{f: jsonhttp.Continue, code: http.StatusContinue},
		{f: jsonhttp.SwitchingProtocols, code: http.StatusSwitchingProtocols},
		{f: jsonhttp.OK, code: http.StatusOK},
		{f: jsonhttp.Created, code: http.StatusCreated},
		{f: jsonhttp.Accepted, code: http.StatusAccepted},
		{f: jsonhttp.NonAuthoritativeInfo, code: http.StatusNonAuthoritativeInfo},
		{f: jsonhttp.ResetContent, code: http.StatusResetContent},
		{f: jsonhttp.PartialContent, code: http.StatusPartialContent},
		{f: jsonhttp.MultipleChoices, code: http.StatusMultipleChoices},
		{f: jsonhttp.MovedPermanently, code: http.StatusMovedPermanently},
		{f: jsonhttp.Found, code: http.StatusFound},
		{f: jsonhttp.SeeOther, code: http.StatusSeeOther},
		{f: jsonhttp.NotModified, code: http.StatusNotModified},
		{f: jsonhttp.UseProxy, code: http.StatusUseProxy},
		{f: jsonhttp.TemporaryRedirect, code: http.StatusTemporaryRedirect},
		{f: jsonhttp.PermanentRedirect, code: http.StatusPermanentRedirect},
		{f: jsonhttp.BadRequest, code: http.StatusBadRequest},
		{f: jsonhttp.Unauthorized, code: http.StatusUnauthorized},
		{f: jsonhttp.PaymentRequired, code: http.StatusPaymentRequired},
		{f: jsonhttp.Forbidden, code: http.StatusForbidden},
		{f: jsonhttp.NotFound, code: http.StatusNotFound},
		{f: jsonhttp.MethodNotAllowed, code: http.StatusMethodNotAllowed},
		{f: jsonhttp.NotAcceptable, code: http.StatusNotAcceptable},
		{f: jsonhttp.ProxyAuthRequired, code: http.StatusProxyAuthRequired},
		{f: jsonhttp.RequestTimeout, code: http.StatusRequestTimeout},
		{f: jsonhttp.Conflict, code: http.StatusConflict},
		{f: jsonhttp.Gone, code: http.StatusGone},
		{f: jsonhttp.LengthRequired, code: http.StatusLengthRequired},
		{f: jsonhttp.PreconditionFailed, code: http.StatusPreconditionFailed},
		{f: jsonhttp.RequestEntityTooLarge, code: http.StatusRequestEntityTooLarge},
		{f: jsonhttp.RequestURITooLong, code: http.StatusRequestURITooLong},
		{f: jsonhttp.UnsupportedMediaType, code: http.StatusUnsupportedMediaType},
		{f: jsonhttp.RequestedRangeNotSatisfiable, code: http.StatusRequestedRangeNotSatisfiable},
		{f: jsonhttp.ExpectationFailed, code: http.StatusExpectationFailed},
		{f: jsonhttp.Teapot, code: http.StatusTeapot},
		{f: jsonhttp.UpgradeRequired, code: http.StatusUpgradeRequired},
		{f: jsonhttp.PreconditionRequired, code: http.StatusPreconditionRequired},
		{f: jsonhttp.TooManyRequests, code: http.StatusTooManyRequests},
		{f: jsonhttp.RequestHeaderFieldsTooLarge, code: http.StatusRequestHeaderFieldsTooLarge},
		{f: jsonhttp.UnavailableForLegalReasons, code: http.StatusUnavailableForLegalReasons},
		{f: jsonhttp.InternalServerError, code: http.StatusInternalServerError},
		{f: jsonhttp.NotImplemented, code: http.StatusNotImplemented},
		{f: jsonhttp.BadGateway, code: http.StatusBadGateway},
		{f: jsonhttp.ServiceUnavailable, code: http.StatusServiceUnavailable},
		{f: jsonhttp.GatewayTimeout, code: http.StatusGatewayTimeout},
		{f: jsonhttp.HTTPVersionNotSupported, code: http.StatusHTTPVersionNotSupported},
	} {
		w := httptest.NewRecorder()
		tc.f(w, nil)
		var m *jsonhttp.StatusResponse

		if err := json.Unmarshal(w.Body.Bytes(), &m); err != nil {
			t.Errorf("json unmarshal response body: %s", err)
		}

		if m.Code != tc.code {
			t.Errorf("expected message code %d, got %d", tc.code, m.Code)
		}

		if m.Message != http.StatusText(tc.code) {
			t.Errorf("expected message message \"%s\", got \"%s\"", http.StatusText(tc.code), m.Message)
		}
301 302

		testContentType(t, w)
Janos Guljas's avatar
Janos Guljas committed
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
	}
}

func TestPanicRespond(t *testing.T) {
	w := httptest.NewRecorder()

	defer func() {
		err := recover()
		if _, ok := err.(*json.UnsupportedTypeError); !ok {
			t.Errorf("expected error from recover json.UnsupportedTypeError, got %#v", err)
		}
	}()

	jsonhttp.Respond(w, http.StatusNotFound, map[bool]string{
		true: "",
	})
}
320 321 322 323 324 325 326 327

func testContentType(t *testing.T, r *httptest.ResponseRecorder) {
	t.Helper()

	if got := r.Header().Get("Content-Type"); got != jsonhttp.DefaultContentTypeHeader {
		t.Errorf("got content type %q, want %q", got, jsonhttp.DefaultContentTypeHeader)
	}
}