aboutsummaryrefslogtreecommitdiffstats
path: root/vendor/go.uber.org/zap/http_handler_test.go
blob: 9da3dc7b52d6ad27bf1edfac58a042044b36b860 (plain) (blame)
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
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
122
123
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
// Copyright (c) 2016 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package zap_test

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

	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestAtomicLevelServeHTTP(t *testing.T) {
	tests := []struct {
		desc          string
		method        string
		query         string
		contentType   string
		body          string
		expectedCode  int
		expectedLevel zapcore.Level
	}{
		{
			desc:          "GET",
			method:        http.MethodGet,
			expectedCode:  http.StatusOK,
			expectedLevel: zap.InfoLevel,
		},
		{
			desc:          "PUT JSON",
			method:        http.MethodPut,
			expectedCode:  http.StatusOK,
			expectedLevel: zap.WarnLevel,
			body:          `{"level":"warn"}`,
		},
		{
			desc:          "PUT URL encoded",
			method:        http.MethodPut,
			expectedCode:  http.StatusOK,
			expectedLevel: zap.WarnLevel,
			contentType:   "application/x-www-form-urlencoded",
			body:          "level=warn",
		},
		{
			desc:          "PUT query parameters",
			method:        http.MethodPut,
			query:         "?level=warn",
			expectedCode:  http.StatusOK,
			expectedLevel: zap.WarnLevel,
			contentType:   "application/x-www-form-urlencoded",
		},
		{
			desc:          "body takes precedence over query",
			method:        http.MethodPut,
			query:         "?level=info",
			expectedCode:  http.StatusOK,
			expectedLevel: zap.WarnLevel,
			contentType:   "application/x-www-form-urlencoded",
			body:          "level=warn",
		},
		{
			desc:          "JSON ignores query",
			method:        http.MethodPut,
			query:         "?level=info",
			expectedCode:  http.StatusOK,
			expectedLevel: zap.WarnLevel,
			body:          `{"level":"warn"}`,
		},
		{
			desc:         "PUT JSON unrecognized",
			method:       http.MethodPut,
			expectedCode: http.StatusBadRequest,
			body:         `{"level":"unrecognized"}`,
		},
		{
			desc:         "PUT URL encoded unrecognized",
			method:       http.MethodPut,
			expectedCode: http.StatusBadRequest,
			contentType:  "application/x-www-form-urlencoded",
			body:         "level=unrecognized",
		},
		{
			desc:         "PUT JSON malformed",
			method:       http.MethodPut,
			expectedCode: http.StatusBadRequest,
			body:         `{"level":"warn`,
		},
		{
			desc:         "PUT URL encoded malformed",
			method:       http.MethodPut,
			query:        "?level=%",
			expectedCode: http.StatusBadRequest,
			contentType:  "application/x-www-form-urlencoded",
		},
		{
			desc:         "PUT Query parameters malformed",
			method:       http.MethodPut,
			expectedCode: http.StatusBadRequest,
			contentType:  "application/x-www-form-urlencoded",
			body:         "level=%",
		},
		{
			desc:         "PUT JSON unspecified",
			method:       http.MethodPut,
			expectedCode: http.StatusBadRequest,
			body:         `{}`,
		},
		{
			desc:         "PUT URL encoded unspecified",
			method:       http.MethodPut,
			expectedCode: http.StatusBadRequest,
			contentType:  "application/x-www-form-urlencoded",
			body:         "",
		},
		{
			desc:         "POST JSON",
			method:       http.MethodPost,
			expectedCode: http.StatusMethodNotAllowed,
			body:         `{"level":"warn"}`,
		},
		{
			desc:         "POST URL",
			method:       http.MethodPost,
			expectedCode: http.StatusMethodNotAllowed,
			contentType:  "application/x-www-form-urlencoded",
			body:         "level=warn",
		},
	}

	for _, tt := range tests {
		t.Run(tt.desc, func(t *testing.T) {
			lvl := zap.NewAtomicLevel()
			lvl.SetLevel(zapcore.InfoLevel)

			server := httptest.NewServer(lvl)
			defer server.Close()

			req, err := http.NewRequest(tt.method, server.URL+tt.query, strings.NewReader(tt.body))
			require.NoError(t, err, "Error constructing %s request.", req.Method)
			if tt.contentType != "" {
				req.Header.Set("Content-Type", tt.contentType)
			}

			res, err := http.DefaultClient.Do(req)
			require.NoError(t, err, "Error making %s request.", req.Method)
			defer func() {
				assert.NoError(t, res.Body.Close(), "Error closing response body.")
			}()

			require.Equal(t, tt.expectedCode, res.StatusCode, "Unexpected status code.")
			if tt.expectedCode != http.StatusOK {
				// Don't need to test exact error message, but one should be present.
				var pld struct {
					Error string `json:"error"`
				}
				require.NoError(t, json.NewDecoder(res.Body).Decode(&pld), "Decoding response body")
				assert.NotEmpty(t, pld.Error, "Expected an error message")
				return
			}

			var pld struct {
				Level zapcore.Level `json:"level"`
			}
			require.NoError(t, json.NewDecoder(res.Body).Decode(&pld), "Decoding response body")
			assert.Equal(t, tt.expectedLevel, pld.Level, "Unexpected logging level returned")
		})
	}
}

func TestAtomicLevelServeHTTPBrokenWriter(t *testing.T) {
	t.Parallel()

	lvl := zap.NewAtomicLevel()

	request, err := http.NewRequest(http.MethodGet, "http://localhost:1234/log/level", nil)
	require.NoError(t, err, "Error constructing request.")

	recorder := httptest.NewRecorder()
	lvl.ServeHTTP(&brokenHTTPResponseWriter{
		ResponseWriter: recorder,
	}, request)

	assert.Equal(t, http.StatusInternalServerError, recorder.Code, "Unexpected status code.")
}

type brokenHTTPResponseWriter struct {
	http.ResponseWriter
}

func (w *brokenHTTPResponseWriter) Write([]byte) (int, error) {
	return 0, errors.New("great sadness")
}