-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresponse_test.go
More file actions
588 lines (516 loc) · 22.6 KB
/
Copy pathresponse_test.go
File metadata and controls
588 lines (516 loc) · 22.6 KB
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package httpserver
import (
"bytes"
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"testing"
"github.com/rs/zerolog"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// ============================================================================
// Context.NewResponse: status boundaries and state reset
// ============================================================================
// NewResponse must panic for statuses outside [200, 599] and accept everything
// in that range. A response whose NewResponse was never called has Status()==0.
func TestContext_NewResponse_StatusBoundaries(t *testing.T) {
t.Run("below_200_panics", func(t *testing.T) {
rec := httptest.NewRecorder()
assert.Panics(t, func() {
(&Context{writer: rec}).NewResponse(199)
})
})
t.Run("200_to_599_succeed", func(t *testing.T) {
for _, status := range []int{200, 201, 204, 301, 404, 500, 599} {
rec := httptest.NewRecorder()
assert.NotPanics(t, func() {
r := (&Context{writer: rec}).NewResponse(status)
assert.Equal(t, status, r.Status())
}, "status %d", status)
}
})
t.Run("above_599_panics", func(t *testing.T) {
rec := httptest.NewRecorder()
assert.Panics(t, func() {
(&Context{writer: rec}).NewResponse(600)
})
})
}
// A second NewResponse must clear headers/body/marshaller set by an earlier
// NewResponse so handlers cannot accidentally inherit stale state.
func TestContext_NewResponse_ClearsPreviousResponseState(t *testing.T) {
rec := httptest.NewRecorder()
ctx := &Context{writer: rec}
prev := ctx.NewResponse(http.StatusOK)
prev.Header().Set("X-Old", "value")
prev.JsonBody(map[string]string{"k": "v"}) // sets marshaller=JSON
require.Equal(t, "value", rec.Header().Get("X-Old"))
require.NotNil(t, ctx.body)
require.Equal(t, marshallerIsJson, ctx.marshaller)
ctx.NewResponse(http.StatusNoContent)
assert.Equal(t, http.StatusNoContent, ctx.status)
assert.Nil(t, ctx.body)
assert.Equal(t, marshallerIsDirect, ctx.marshaller)
assert.Empty(t, rec.Header(), "headers must be cleared by NewResponse")
}
// ============================================================================
// Response handle invalidation (stale handles panic)
// ============================================================================
// A handle returned by an earlier NewResponse is invalidated by a later one:
// only the newest handle may still mutate the response.
func TestResponse_StaleHandle_AfterNewResponse_Panics(t *testing.T) {
rec := httptest.NewRecorder()
ctx := &Context{writer: rec}
first := ctx.NewResponse(http.StatusOK)
second := ctx.NewResponse(http.StatusCreated)
assert.NotPanics(t, func() { second.StringBody("fresh") })
assert.PanicsWithValue(t, "BUG: stale response handle", func() { first.StringBody("stale") })
}
// Writing the response invalidates every handle: nothing may mutate the
// response once it is on the wire.
func TestResponse_StaleHandle_AfterWriteResponse_Panics(t *testing.T) {
rec := httptest.NewRecorder()
ctx := &Context{writer: rec}
response := ctx.NewResponse(http.StatusOK)
response.StringBody("body")
assert.NotPanics(t, func() { ctx.writeResponse(context.Background()) })
assert.PanicsWithValue(t, "BUG: stale response handle", func() { response.StringBody("late") })
assert.Equal(t, "body", rec.Body.String(), "wire content untouched by the stale setter")
}
// ============================================================================
// Context.Response: existence reporting
// ============================================================================
// Response must return the zero Response and false before NewResponse is
// called, and a live handle and true afterward.
func TestContext_Response_ReportsExistence(t *testing.T) {
rec := httptest.NewRecorder()
ctx := &Context{writer: rec}
resp, ok := ctx.Response()
assert.False(t, ok, "no response exists before NewResponse")
assert.Equal(t, Response{}, resp, "zero Response must be returned when none exists")
ctx.NewResponse(http.StatusTeapot)
resp, ok = ctx.Response()
assert.True(t, ok, "response exists after NewResponse")
assert.Same(t, ctx, resp.ctx)
assert.Equal(t, http.StatusTeapot, resp.Status())
}
// The zero Response behaves like a nil pointer: every method call panics.
func TestPanic_ZeroResponseMethods_Panic(t *testing.T) {
assert.Panics(t, func() { _ = Response{}.Status() }, "Status")
assert.Panics(t, func() { _ = Response{}.Header() }, "Header")
assert.Panics(t, func() { _ = Response{}.Body() }, "Body")
assert.Panics(t, func() { Response{}.Cookie(http.Cookie{Name: "n"}) }, "Cookie")
assert.Panics(t, func() { Response{}.BytesBody(nil) }, "BytesBody")
assert.Panics(t, func() { Response{}.StringBody("") }, "StringBody")
assert.Panics(t, func() { Response{}.StreamBody(nil) }, "StreamBody")
assert.Panics(t, func() { Response{}.PlainTextBody("") }, "PlainTextBody")
assert.Panics(t, func() { Response{}.OctetsBody(nil) }, "OctetsBody")
assert.Panics(t, func() { Response{}.JsonBody(nil) }, "JsonBody")
}
// The zero Response is loggable: it serializes as an empty object instead of
// panicking.
func TestResponse_ZeroValue_LogsAsEmptyObject(t *testing.T) {
var logBuf bytes.Buffer
logger := zerolog.New(&logBuf)
require.NotPanics(t, func() {
logger.Info().Object("response", Response{}).Msg("serialized")
})
var decoded map[string]any
require.NoError(t, json.Unmarshal(logBuf.Bytes(), &decoded))
respObj, ok := decoded["response"].(map[string]any)
require.True(t, ok, "zero Response should serialize as an empty object")
assert.Empty(t, respObj, "zero Response should not emit any fields")
}
// ============================================================================
// Response handle: Status / Header / Body / Cookie
// ============================================================================
func TestResponse_StatusGetter(t *testing.T) {
rec := httptest.NewRecorder()
r := (&Context{writer: rec}).NewResponse(http.StatusTeapot)
assert.Equal(t, http.StatusTeapot, r.Status())
}
func TestResponse_HeaderGetter(t *testing.T) {
rec := httptest.NewRecorder()
r := (&Context{writer: rec}).NewResponse(http.StatusOK)
r.Header().Set("X-Test", "value")
assert.Equal(t, "value", r.Header().Get("X-Test"))
}
// Body() returns the configured body value, or nil on a fresh response.
func TestResponse_Body_ReturnsConfiguredBody(t *testing.T) {
rec := httptest.NewRecorder()
ctx := &Context{writer: rec}
r := ctx.NewResponse(http.StatusOK)
require.Nil(t, r.Body(), "fresh response body must be nil")
r.StringBody("hello")
assert.Equal(t, "hello", r.Body())
data := []byte{1, 2, 3}
r.BytesBody(data)
assert.Equal(t, data, r.Body())
}
func TestResponse_CookieSetter(t *testing.T) {
rec := httptest.NewRecorder()
r := (&Context{writer: rec}).NewResponse(http.StatusOK)
r.Cookie(http.Cookie{Name: "session", Value: "abc"})
assert.Len(t, rec.Header().Values("Set-Cookie"), 1)
}
// Cookie must append rather than replace: multiple Cookie calls produce
// multiple Set-Cookie headers, preserving all cookies.
func TestResponse_Cookie_AppendsCookies(t *testing.T) {
rec := httptest.NewRecorder()
r := (&Context{writer: rec}).NewResponse(http.StatusOK)
r.Cookie(http.Cookie{Name: "a", Value: "1"})
r.Cookie(http.Cookie{Name: "b", Value: "2"})
assert.Equal(t, []string{"a=1", "b=2"}, rec.Header().Values("Set-Cookie"))
}
// ============================================================================
// Context context.Context delegation (Deadline / Done / Err / Value)
// ============================================================================
func TestContext_Deadline_DelegatesToRequest(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder()
ctx := &Context{request: req, writer: rec}
dl, ok := ctx.Deadline()
assert.False(t, ok)
assert.True(t, dl.IsZero())
}
func TestContext_DoneAndErr_DelegateToRequest(t *testing.T) {
rootCtx, cancel := context.WithCancel(context.Background())
defer cancel()
req := httptest.NewRequest(http.MethodGet, "/", nil).WithContext(rootCtx)
rec := httptest.NewRecorder()
ctx := &Context{request: req, writer: rec}
done := ctx.Done()
require.NotNil(t, done)
require.Nil(t, ctx.Err(), "Err before cancel should be nil")
cancel()
<-done
assert.ErrorIs(t, ctx.Err(), context.Canceled)
}
func TestContext_Value_DelegatesToRequest(t *testing.T) {
type ctxKey struct{}
req := httptest.NewRequest(http.MethodGet, "/", nil)
req = req.WithContext(context.WithValue(req.Context(), ctxKey{}, "stored"))
rec := httptest.NewRecorder()
ctx := &Context{request: req, writer: rec}
assert.Equal(t, "stored", ctx.Value(ctxKey{}))
}
// ============================================================================
// Context.writeResponse body-type matrix
// ============================================================================
func TestContext_writeResponse_NilBody(t *testing.T) {
rec := httptest.NewRecorder()
ctx := &Context{writer: rec, status: http.StatusNoContent}
ctx.writeResponse(context.Background())
assert.Equal(t, http.StatusNoContent, rec.Code)
assert.Empty(t, rec.Body.Bytes())
assert.Empty(t, rec.Header().Get("Content-Type"))
}
func TestContext_writeResponse_BytesBody(t *testing.T) {
rec := httptest.NewRecorder()
data := []byte("raw bytes")
ctx := &Context{writer: rec}
ctx.NewResponse(http.StatusOK).BytesBody(data)
ctx.writeResponse(context.Background())
assert.Equal(t, http.StatusOK, rec.Code)
assert.Equal(t, data, rec.Body.Bytes())
assert.Empty(t, rec.Header().Get("Content-Type"))
}
func TestContext_writeResponse_StringBody(t *testing.T) {
rec := httptest.NewRecorder()
ctx := &Context{writer: rec}
ctx.NewResponse(http.StatusOK).StringBody("a string")
ctx.writeResponse(context.Background())
assert.Equal(t, http.StatusOK, rec.Code)
assert.Equal(t, "a string", rec.Body.String())
assert.Empty(t, rec.Header().Get("Content-Type"))
}
// The recorder is not a *StreamWriter, so writeResponse wraps it on the fly
// (the bypass path used when the Router runs without the server's writer).
func TestContext_writeResponse_StreamBody(t *testing.T) {
rec := httptest.NewRecorder()
ctx := &Context{writer: rec}
ctx.NewResponse(http.StatusOK).StreamBody(func(w *StreamWriter) error {
_, err := w.Write([]byte("streamed"))
return err
})
ctx.writeResponse(context.Background())
assert.Equal(t, http.StatusOK, rec.Code)
assert.Equal(t, "streamed", rec.Body.String())
assert.Empty(t, rec.Header().Get("Content-Type"))
}
// The Context's lifetime ends when writeResponse hands the connection to the
// streaming body: it is cleared before the body runs, so the body must not use
// the Context or a stale Response handle, and a second writeResponse is a
// no-op rather than a 500 "response missing" fallback.
func TestContext_writeResponse_StreamBody_ClearsContext(t *testing.T) {
req, _ := http.NewRequest(http.MethodGet, "/", nil)
streamWriter := &StreamWriter{writer: newFakeResponseWriter()}
ctx := &Context{request: req, writer: streamWriter}
bodyRan := false
require.NotPanics(t, func() {
ctx.NewResponse(http.StatusOK).StreamBody(func(*StreamWriter) error {
bodyRan = true // marker only; using ctx here would be a bug
return nil
})
ctx.writeResponse(context.Background())
})
assert.True(t, bodyRan, "stream body ran")
assert.Nil(t, ctx.request, "Context cleared before the body ran")
assert.Nil(t, ctx.writer)
require.NotPanics(t, func() {
ctx.writeResponse(context.Background())
})
assert.Equal(t, http.StatusOK, streamWriter.status, "second writeResponse is a no-op")
}
// Using the Context inside a streaming body is invalid: the Context was
// cleared before the body ran, so NewResponse dies on the nil writer instead
// of silently mutating response state that will never be written.
func TestContext_NewResponse_InsideStreamBody_IsInvalid(t *testing.T) {
req, _ := http.NewRequest(http.MethodGet, "/", nil)
streamWriter := &StreamWriter{writer: newFakeResponseWriter()}
ctx := &Context{request: req, writer: streamWriter}
innerPanic := make(chan any, 1)
ctx.NewResponse(http.StatusOK).StreamBody(func(*StreamWriter) error {
defer func() { innerPanic <- recover() }()
_ = ctx.NewResponse(http.StatusOK)
return nil
})
require.NotPanics(t, func() { ctx.writeResponse(context.Background()) })
require.NotNil(t, <-innerPanic, "NewResponse inside a stream body must fail")
}
// A stream-body error occurs after [http.ResponseWriter.WriteHeader]; the
// status is already on the wire and cannot be recovered. The error is logged,
// then writeResponse panics with [http.ErrAbortHandler] so the wrapping
// server/net/http silently closes the connection. The committed status stays
// observable on the recorder.
func TestContext_writeResponse_StreamBody_Error(t *testing.T) {
rec := httptest.NewRecorder()
streamErr := errors.New("stream write failed")
ctx := &Context{writer: rec}
ctx.NewResponse(http.StatusOK).StreamBody(func(*StreamWriter) error {
return streamErr
})
assert.PanicsWithValue(t, http.ErrAbortHandler, func() {
ctx.writeResponse(context.Background())
})
assert.Equal(t, http.StatusOK, rec.Code)
}
// StreamBody with an installed StreamWriter (the server path): Write flows
// through the response accounting while Flush reaches the underlying
// connection flush. Each Flush call must land exactly once on the underlying
// flusher, between the surrounding Writes.
func TestContext_writeResponse_StreamBody_Flushes(t *testing.T) {
fake := newFakeResponseWriter()
underlying := &flushRecorderWriter{ResponseWriter: fake}
streamWriter := &StreamWriter{writer: underlying}
ctx := &Context{writer: streamWriter}
ctx.NewResponse(http.StatusOK).StreamBody(func(w *StreamWriter) error {
if _, err := w.Write([]byte("first ")); err != nil {
return err
}
w.Flush()
_, err := w.Write([]byte("second"))
return err
})
require.NotPanics(t, func() {
ctx.writeResponse(context.Background())
})
assert.Equal(t, http.StatusOK, streamWriter.status)
assert.Equal(t, len("first second"), streamWriter.bytesWritten)
assert.Equal(t, [][]byte{[]byte("first "), []byte("second")}, fake.writes)
assert.Equal(t, 1, underlying.flushes)
}
// StreamWriter.Flush is a swallowed no-op when the underlying writer does not
// implement [http.Flusher]: the stream body keeps running and the committed
// response stays as-is, because Flush carries no error to treat as fatal.
func TestContext_writeResponse_StreamBody_FlushUnsupported_IsNoOp(t *testing.T) {
streamWriter := &StreamWriter{writer: newFakeResponseWriter()}
ctx := &Context{writer: streamWriter}
bodyRan := false
ctx.NewResponse(http.StatusOK).StreamBody(func(w *StreamWriter) error {
w.Flush()
bodyRan = true
return nil
})
require.NotPanics(t, func() {
ctx.writeResponse(context.Background())
})
assert.True(t, bodyRan, "stream body kept running past the no-op flush")
assert.Equal(t, http.StatusOK, streamWriter.status)
}
func TestContext_writeResponse_PlainTextBody(t *testing.T) {
rec := httptest.NewRecorder()
ctx := &Context{writer: rec}
ctx.NewResponse(http.StatusOK).PlainTextBody("hello plain")
ctx.writeResponse(context.Background())
assert.Equal(t, http.StatusOK, rec.Code)
assert.Equal(t, "hello plain", rec.Body.String())
assert.Equal(t, "text/plain; charset=utf-8", rec.Header().Get("Content-Type"))
}
func TestContext_writeResponse_OctetsBody(t *testing.T) {
rec := httptest.NewRecorder()
data := []byte{0x00, 0x01, 0x02, 0xFF}
ctx := &Context{writer: rec}
ctx.NewResponse(http.StatusOK).OctetsBody(data)
ctx.writeResponse(context.Background())
assert.Equal(t, http.StatusOK, rec.Code)
assert.Equal(t, data, rec.Body.Bytes())
assert.Equal(t, "application/octet-stream", rec.Header().Get("Content-Type"))
}
func TestContext_writeResponse_JsonBody(t *testing.T) {
rec := httptest.NewRecorder()
type payload struct {
Name string `json:"name"`
Age int `json:"age"`
}
p := payload{Name: "alice", Age: 30}
ctx := &Context{writer: rec}
ctx.NewResponse(http.StatusCreated).JsonBody(p)
ctx.writeResponse(context.Background())
assert.Equal(t, http.StatusCreated, rec.Code)
assert.Equal(t, "application/json; charset=utf-8", rec.Header().Get("Content-Type"))
var result payload
assert.NoError(t, json.Unmarshal(rec.Body.Bytes(), &result))
assert.Equal(t, p, result)
}
// JsonBody(nil) must marshal to the JSON null literal with the JSON content
// type, not be treated as "no body".
func TestContext_writeResponse_JsonBody_Nil(t *testing.T) {
rec := httptest.NewRecorder()
ctx := &Context{writer: rec}
ctx.NewResponse(http.StatusOK).JsonBody(nil)
ctx.writeResponse(context.Background())
assert.Equal(t, http.StatusOK, rec.Code)
assert.Equal(t, "application/json; charset=utf-8", rec.Header().Get("Content-Type"))
assert.Equal(t, "null", rec.Body.String())
}
// ============================================================================
// Context.writeResponse error paths
// ============================================================================
// JSON marshal failure must clear stale headers, write 500 and leave the body
// empty. The header set just before writeResponse (after the NewResponse clear)
// must be gone after the failure path runs.
func TestContext_writeResponse_JsonMarshalError(t *testing.T) {
rec := httptest.NewRecorder()
ctx := &Context{writer: rec}
ctx.NewResponse(http.StatusOK).JsonBody(make(chan int))
ctx.writer.Header().Set("X-Added", "value")
ctx.writeResponse(context.Background())
assert.Equal(t, http.StatusInternalServerError, rec.Code)
assert.Empty(t, rec.Header().Get("X-Added"))
assert.Empty(t, rec.Body.Bytes(), "marshal failure body must be empty")
}
// Unsupported body type must clear headers and write 500.
func TestContext_writeResponse_UnknownBodyType(t *testing.T) {
rec := httptest.NewRecorder()
ctx := &Context{writer: rec, status: http.StatusOK, body: 12345}
ctx.writer.Header().Set("X-Added", "value")
ctx.writeResponse(context.Background())
assert.Equal(t, http.StatusInternalServerError, rec.Code)
assert.Empty(t, rec.Header().Get("X-Added"))
}
// Body-write errors occur after [http.ResponseWriter.WriteHeader]; the status
// is already committed and cannot be replaced. writeResponse logs the error and
// then panics with [http.ErrAbortHandler] so the wrapping server/net/http
// silently closes the connection.
func TestContext_writeResponse_BodyWriteError_AbortsConnection(t *testing.T) {
fw := &failingResponseWriter{writeErr: errors.New("write failed")}
ctx := &Context{writer: fw}
ctx.NewResponse(http.StatusOK).BytesBody([]byte("data"))
assert.PanicsWithValue(t, http.ErrAbortHandler, func() {
ctx.writeResponse(context.Background())
})
}
// TestContext_writeResponse_JsonBody_WriteError covers the JSON-marshaller
// Write-error arm (response.go:113). The marshal succeeds, WriteHeader commits
// 200, then the body Write fails: writeResponse logs and re-panics with
// [http.ErrAbortHandler]. Mirrors the BytesBody test above for the JSON path.
func TestContext_writeResponse_JsonBody_WriteError(t *testing.T) {
fw := &failingResponseWriter{writeErr: errors.New("write failed")}
ctx := &Context{writer: fw}
ctx.NewResponse(http.StatusOK).JsonBody(map[string]string{"k": "v"})
assert.PanicsWithValue(t, http.ErrAbortHandler, func() {
ctx.writeResponse(context.Background())
})
}
// TestContext_writeResponse_StringBody_WriteError covers the string-body
// Write-error arm (response.go:138). Same abort contract as the JSON/bytes
// paths; isolates the string branch which shares one panic with them.
func TestContext_writeResponse_StringBody_WriteError(t *testing.T) {
fw := &failingResponseWriter{writeErr: errors.New("write failed")}
ctx := &Context{writer: fw}
ctx.NewResponse(http.StatusOK).StringBody("a string")
assert.PanicsWithValue(t, http.ErrAbortHandler, func() {
ctx.writeResponse(context.Background())
})
}
// TestResponse_MarshalZerologObject_IncludesHeaders covers the header branch in
// [Response.MarshalZerologObject]: when the response carries at least one
// header, the serialized object must include a `header` field, alongside the
// always-emitted `status`.
func TestResponse_MarshalZerologObject_IncludesHeaders(t *testing.T) {
var logBuf bytes.Buffer
logger := zerolog.New(&logBuf)
rec := httptest.NewRecorder()
ctx := &Context{writer: rec}
response := ctx.NewResponse(http.StatusTeapot)
response.Header().Set("X-Test", "value")
logger.Info().Object("response", response).Msg("serialized")
var decoded map[string]any
require.NoError(t, json.Unmarshal(logBuf.Bytes(), &decoded))
respObj, ok := decoded["response"].(map[string]any)
require.True(t, ok, "response object should be present")
assert.EqualValues(t, http.StatusTeapot, respObj["status"])
headerObj, ok := respObj["header"].(map[string]any)
require.True(t, ok, "header field should be serialized")
assert.Equal(t, []any{"value"}, headerObj["X-Test"])
}
// TestResponse_MarshalZerologObject_IncludesBody covers the body branch in
// [Response.MarshalZerologObject] (`if r.ctx.body != nil { e.Any("body", …) }`).
// IncludesHeaders above intentionally leaves body nil; here a body is set so the
// branch executes and `body` appears alongside `status` in the serialized form.
func TestResponse_MarshalZerologObject_IncludesBody(t *testing.T) {
var logBuf bytes.Buffer
logger := zerolog.New(&logBuf)
rec := httptest.NewRecorder()
ctx := &Context{writer: rec}
response := ctx.NewResponse(http.StatusTeapot)
response.Header().Set("X-Test", "value")
response.JsonBody(map[string]string{"k": "v"})
logger.Info().Object("response", response).Msg("serialized")
var decoded map[string]any
require.NoError(t, json.Unmarshal(logBuf.Bytes(), &decoded))
respObj, ok := decoded["response"].(map[string]any)
require.True(t, ok, "response object should be present")
assert.EqualValues(t, http.StatusTeapot, respObj["status"])
bodyObj, ok := respObj["body"].(map[string]any)
require.True(t, ok, "body field should be serialized when body is set")
assert.Equal(t, "v", bodyObj["k"])
}
// ============================================================================
// helpers
// ============================================================================
// failingResponseWriter is a minimal http.ResponseWriter whose Write returns a
// configured error. Header/WriteHeader operate normally so we can isolate the
// body-write error path.
type failingResponseWriter struct {
header http.Header
status int
writeErr error
}
func (f *failingResponseWriter) Header() http.Header {
if f.header == nil {
f.header = http.Header{}
}
return f.header
}
func (f *failingResponseWriter) Write([]byte) (int, error) { return 0, f.writeErr }
func (f *failingResponseWriter) WriteHeader(statusCode int) { f.status = statusCode }