Skip to content

Commit ad10780

Browse files
committed
fix: SCA-151 improve gzippedBody Read logic and add test coverage
- Fixed handling of empty input and buffer availability in `gzippedBody.Read`. - Added panic to ensure non-zero bytes read when expected. - Introduced `gzipped_body_test.go` for comprehensive test coverage of `gzippedBody`.
1 parent 90dbfe5 commit ad10780

2 files changed

Lines changed: 32 additions & 3 deletions

File tree

api/gzipped_body.go

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,10 +36,13 @@ func (g *gzippedBody) GetBody() (io.ReadCloser, error) {
3636
}
3737

3838
func (g *gzippedBody) Read(p []byte) (n int, err error) {
39+
if len(p) == 0 {
40+
return 0, nil
41+
}
3942
if g.gzipWriter == nil {
4043
g.gzipWriter = gzip.NewWriter(&g.buf)
4144
}
42-
for g.buf.Available() == 0 {
45+
for g.buf.Len() == 0 {
4346
if g.end {
4447
return 0, io.EOF
4548
}
@@ -55,8 +58,11 @@ func (g *gzippedBody) Read(p []byte) (n int, err error) {
5558
return 0, e
5659
}
5760
}
58-
59-
return g.reader.Read(p)
61+
n, _ = g.buf.Read(p)
62+
if n == 0 {
63+
panic("n == 0")
64+
}
65+
return
6066
}
6167

6268
func (g *gzippedBody) Close() error {

api/gzipped_body_test.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package api
2+
3+
import (
4+
"compress/gzip"
5+
"encoding/json"
6+
"fmt"
7+
"testing"
8+
9+
"github.com/stretchr/testify/assert"
10+
)
11+
12+
func TestGzippedBody_Read(t *testing.T) {
13+
var data = map[string]any{}
14+
for i := 0; i < 10000; i++ {
15+
data[fmt.Sprint(i)] = fmt.Sprint(i)
16+
}
17+
var body = NewGzippedBody(NewJsonRequestBody(data))
18+
gr, _ := gzip.NewReader(body)
19+
var dec = json.NewDecoder(gr)
20+
var data2 map[string]any
21+
assert.NoError(t, dec.Decode(&data2))
22+
assert.EqualValues(t, data, data2)
23+
}

0 commit comments

Comments
 (0)