~bigbes/huntsman

ref: 766fa8055977fbe223afd8a84bcf37a3d13bb1ce huntsman/internal/pkg/httputil/response_test.go -rw-r--r-- 1.8 KiB
766fa805 — Eugene Blikh Add BSD 2-Clause license 6 days ago
                                                                                
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package httputil

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

	"sourcecraft.dev/bigbes/huntsman/internal/pkg/apierror"
)

func TestJSONStatusAndBody(t *testing.T) {
	rr := httptest.NewRecorder()
	JSON(rr, 201, map[string]int{"n": 7})

	if rr.Code != 201 {
		t.Errorf("status = %d", rr.Code)
	}
	if got := rr.Header().Get("Content-Type"); got != "application/json" {
		t.Errorf("content-type = %q", got)
	}
	var body map[string]int
	if err := json.Unmarshal(rr.Body.Bytes(), &body); err != nil {
		t.Fatalf("decode: %v", err)
	}
	if body["n"] != 7 {
		t.Errorf("body = %+v", body)
	}
}

func TestJSONNilDataWritesNoBody(t *testing.T) {
	rr := httptest.NewRecorder()
	JSON(rr, 204, nil)
	if rr.Code != 204 {
		t.Errorf("status = %d", rr.Code)
	}
	if rr.Body.Len() != 0 {
		t.Errorf("body should be empty, got %q", rr.Body.String())
	}
}

func TestOK(t *testing.T) {
	rr := httptest.NewRecorder()
	OK(rr, map[string]string{"hello": "world"})
	if rr.Code != 200 {
		t.Errorf("status = %d", rr.Code)
	}
}

func TestErrorMapsClientError(t *testing.T) {
	rr := httptest.NewRecorder()
	req := httptest.NewRequestWithContext(t.Context(), "GET", "/foo", http.NoBody)
	Error(rr, req, apierror.NotFound("widget"))
	if rr.Code != 404 {
		t.Errorf("status = %d", rr.Code)
	}
	if got := rr.Header().Get("Content-Type"); got != "application/problem+json" {
		t.Errorf("content-type = %q", got)
	}
}

func TestErrorMapsInternalError(t *testing.T) {
	rr := httptest.NewRecorder()
	req := httptest.NewRequestWithContext(t.Context(), "GET", "/foo", http.NoBody)
	Error(rr, req, errors.New("boom"))
	if rr.Code != 500 {
		t.Errorf("status = %d", rr.Code)
	}
	// Internal detail should not leak in the body.
	if got := rr.Body.String(); strings.Contains(got, "boom") {
		t.Errorf("response body leaks internal error: %q", got)
	}
}