github.com/blend/go-sdk@v1.20220411.3/r2/opt_log_response_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 r2 9 10 import ( 11 "context" 12 "fmt" 13 "io" 14 "net/http" 15 "net/http/httptest" 16 "testing" 17 18 "github.com/blend/go-sdk/assert" 19 "github.com/blend/go-sdk/logger" 20 ) 21 22 // NOTE: Ensure that mockLogger satisfies the logger.Triggerable interface. 23 var ( 24 _ logger.Triggerable = (*mockLogger)(nil) 25 ) 26 27 type mockLogger struct { 28 Events []logger.Event 29 } 30 31 func (ml *mockLogger) TriggerContext(ctx context.Context, e logger.Event) { 32 ml.Events = append(ml.Events, e) 33 } 34 35 func TestOptLogResponse(t *testing.T) { 36 assert := assert.New(t) 37 ml := &mockLogger{} 38 opt := OptLogResponse(ml) 39 e := logResponseHelper(assert, ml, opt, "OK!\n") 40 assert.Equal(e, Event{ 41 Flag: FlagResponse, 42 Request: e.Request, 43 Response: e.Response, 44 Body: nil, 45 Elapsed: e.Elapsed, 46 }) 47 } 48 49 func TestOptLogResponseWithBody(t *testing.T) { 50 assert := assert.New(t) 51 ml := &mockLogger{} 52 opt := OptLogResponseWithBody(ml) 53 body := "This is the response body\n" 54 e := logResponseHelper(assert, ml, opt, body) 55 assert.Equal(e, Event{ 56 Flag: FlagResponse, 57 Request: e.Request, 58 Response: e.Response, 59 Body: []byte(body), 60 Elapsed: e.Elapsed, 61 }) 62 assert.Equal(e.Request.ContentLength, 0) 63 assert.Equal(e.Response.ContentLength, 26) 64 } 65 66 func logResponseHelper(a *assert.Assertions, ml *mockLogger, opt Option, body string) Event { 67 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 68 w.WriteHeader(http.StatusOK) 69 fmt.Fprint(w, body) 70 })) 71 defer server.Close() 72 73 r := New(server.URL, opt) 74 res, err := r.Do() 75 a.Nil(err) 76 a.NotNil(res) 77 a.Equal(res.StatusCode, http.StatusOK) 78 bodyBytes, err := io.ReadAll(res.Body) 79 a.Nil(err) 80 a.Equal(bodyBytes, []byte(body)) 81 82 // Make sure the event was triggered. 83 a.Len(ml.Events, 1) 84 e, ok := ml.Events[0].(Event) 85 a.True(ok) 86 return e 87 }