@@ -214,3 +214,56 @@ func TestSafetyTransportDecodesGzipResponseAndStripsHeader(t *testing.T) {
214214 t .Errorf ("decoded = %q, want hello" , got )
215215 }
216216}
217+
218+ func TestSafetyTransportObservesResponseBodyBytesOnClose (t * testing.T ) {
219+ // A valid gzip stream for "hello".
220+ gzipHello := []byte {
221+ 0x1f , 0x8b , 0x08 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0xff ,
222+ 0xca , 0x48 , 0xcd , 0xc9 , 0xc9 , 0x07 , 0x04 , 0x00 , 0x00 , 0xff , 0xff ,
223+ 0x86 , 0xa6 , 0x10 , 0x36 , 0x05 , 0x00 , 0x00 , 0x00 ,
224+ }
225+ s := & stubTransport {
226+ body : string (gzipHello ),
227+ header : http.Header {
228+ "Content-Encoding" : []string {"gzip" },
229+ },
230+ }
231+
232+ var got BodyObservation
233+ st := & safetyTransport {
234+ next : s ,
235+ cfg : safetyConfig {
236+ compressionEnabled : true ,
237+ bodyObserver : func (obs BodyObservation ) {
238+ got = obs
239+ },
240+ },
241+ }
242+ req , _ := http .NewRequestWithContext (context .Background (), http .MethodGet , "http://x/path" , http .NoBody )
243+ resp , err := st .RoundTrip (req )
244+ if err != nil {
245+ t .Fatal (err )
246+ }
247+ if _ , err := io .ReadAll (resp .Body ); err != nil {
248+ t .Fatal (err )
249+ }
250+ if err := resp .Body .Close (); err != nil {
251+ t .Fatal (err )
252+ }
253+
254+ if got .URL != "http://x/path" {
255+ t .Errorf ("URL = %q, want request URL" , got .URL )
256+ }
257+ if got .StatusCode != http .StatusOK {
258+ t .Errorf ("StatusCode = %d, want 200" , got .StatusCode )
259+ }
260+ if got .CompressedBytes != int64 (len (gzipHello )) {
261+ t .Errorf ("CompressedBytes = %d, want %d" , got .CompressedBytes , len (gzipHello ))
262+ }
263+ if got .UncompressedBytes != int64 (len ("hello" )) {
264+ t .Errorf ("UncompressedBytes = %d, want %d" , got .UncompressedBytes , len ("hello" ))
265+ }
266+ if got .Duration <= 0 {
267+ t .Errorf ("Duration = %s, want positive" , got .Duration )
268+ }
269+ }
0 commit comments