github.com/blend/go-sdk@v1.20220411.3/r2/event_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 "bytes" 12 "encoding/json" 13 "net/http" 14 "testing" 15 "time" 16 17 "github.com/blend/go-sdk/assert" 18 "github.com/blend/go-sdk/logger" 19 "github.com/blend/go-sdk/webutil" 20 ) 21 22 func TestNewEvent(t *testing.T) { 23 assert := assert.New(t) 24 25 e := NewEvent(Flag, OptEventBody([]byte("foo"))) 26 assert.Equal("foo", e.Body) 27 } 28 29 func TestEventWriteString(t *testing.T) { 30 assert := assert.New(t) 31 32 e := NewEvent(Flag, 33 OptEventRequest(webutil.NewMockRequest("GET", "http://test.com")), 34 OptEventBody([]byte("foo")), 35 ) 36 37 output := new(bytes.Buffer) 38 e.WriteText(logger.NewTextOutputFormatter(logger.OptTextNoColor()), output) 39 assert.Equal("GET http://localhost/http://test.com\nfoo", output.String()) 40 41 e.Response = &http.Response{ 42 StatusCode: http.StatusOK, 43 } 44 e.Elapsed = time.Second 45 output2 := new(bytes.Buffer) 46 e.WriteText(logger.NewTextOutputFormatter(logger.OptTextNoColor()), output2) 47 assert.Equal("GET http://localhost/http://test.com 200 (1s)\nfoo", output2.String()) 48 } 49 50 // eventJSONSchema is the json schema of the logger event. 51 type eventJSONSchema struct { 52 Req struct { 53 StartTime time.Time `json:"startTime"` 54 Method string `json:"method"` 55 URL string `json:"url"` 56 Headers map[string][]string `json:"headers"` 57 } `json:"req"` 58 Res struct { 59 CompleteTime time.Time `json:"completeTime"` 60 StatusCode int `json:"statusCode"` 61 ContentLength int `json:"contentLength"` 62 Headers map[string][]string `json:"headers"` 63 } `json:"res"` 64 Body string `json:"body"` 65 } 66 67 func TestEventMarshalJSON(t *testing.T) { 68 assert := assert.New(t) 69 70 e := NewEvent(Flag, 71 OptEventRequest(webutil.NewMockRequest("GET", "/foo")), 72 OptEventResponse(&http.Response{StatusCode: http.StatusOK, ContentLength: 500}), 73 OptEventBody([]byte("foo")), 74 ) 75 76 contents, err := json.Marshal(e.Decompose()) 77 assert.Nil(err) 78 assert.NotEmpty(contents) 79 80 var jsonContents eventJSONSchema 81 assert.Nil(json.Unmarshal(contents, &jsonContents)) 82 assert.Equal("http://localhost/foo", jsonContents.Req.URL) 83 assert.Equal("GET", jsonContents.Req.Method) 84 assert.Equal(http.StatusOK, jsonContents.Res.StatusCode) 85 assert.Equal(500, jsonContents.Res.ContentLength) 86 assert.Equal("foo", jsonContents.Body) 87 }