github.com/blend/go-sdk@v1.20220411.3/webutil/status_response_writer_test.go (about) 1 /* 2 3 Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file. 5 6 */ 7 8 package webutil 9 10 import ( 11 "bytes" 12 "io" 13 "net/http" 14 "testing" 15 16 "github.com/blend/go-sdk/assert" 17 ) 18 19 type mockResponseWriter struct { 20 Headers http.Header 21 StatusCode int 22 Output io.Writer 23 } 24 25 // Header returns the response headers. 26 func (mrw mockResponseWriter) Header() http.Header { 27 return mrw.Headers 28 } 29 30 // WriteHeader writes the status code. 31 func (mrw mockResponseWriter) WriteHeader(code int) { 32 mrw.StatusCode = code 33 } 34 35 // Write writes data. 36 func (mrw mockResponseWriter) Write(contents []byte) (int, error) { 37 return mrw.Output.Write(contents) 38 } 39 40 func Test_StatusResponseWriter(t *testing.T) { 41 assert := assert.New(t) 42 43 output := bytes.NewBuffer(nil) 44 rw := NewStatusResponseWriter(mockResponseWriter{Output: output, Headers: http.Header{}}) 45 46 rw.Header().Set("foo", "bar") 47 rw.WriteHeader(http.StatusOK) 48 _, err := rw.Write([]byte("this is a test")) 49 assert.Nil(err) 50 51 assert.Equal(http.StatusOK, rw.StatusCode()) 52 assert.Equal("this is a test", output.String()) 53 } 54 55 func Test_StatusResponseWriter_self(t *testing.T) { 56 assert := assert.New(t) 57 58 output := bytes.NewBuffer(nil) 59 rw := NewStatusResponseWriter(mockResponseWriter{Output: output, Headers: http.Header{}}) 60 61 srw := NewStatusResponseWriter(rw) 62 63 srw.Header().Set("foo", "bar") 64 srw.WriteHeader(http.StatusOK) 65 _, err := srw.Write([]byte("this is a test")) 66 assert.Nil(err) 67 68 assert.Equal(http.StatusOK, rw.StatusCode()) 69 assert.Equal("this is a test", output.String()) 70 }