1 package httpbuffer_test 2 3 import ( 4 "io" 5 "net/http" 6 "net/http/httptest" 7 "strings" 8 "testing" 9 10 "vimagination.zapto.org/httpbuffer" 11 _ "vimagination.zapto.org/httpbuffer/gzip" 12 ) 13 14 func TestBuffer(t *testing.T) { 15 for n, test := range [...]struct { 16 Buffers 17 code int 18 compress bool 19 output string 20 length int 21 }{ 22 { 23 Buffers: Buffers{}, 24 code: http.StatusNoContent, 25 output: "", 26 length: 0, 27 }, 28 { 29 Buffers: Buffers{[]byte("data")}, 30 code: http.StatusOK, 31 output: "data", 32 length: 4, 33 }, 34 { 35 Buffers: Buffers{[]byte("hello, "), []byte("world")}, 36 code: http.StatusOK, 37 output: "hello, world", 38 length: 12, 39 }, 40 { 41 Buffers: Buffers{[]byte("hello, "), []byte("world")}, 42 code: http.StatusOK, 43 compress: true, 44 output: "hello, world", 45 length: 12, 46 }, 47 } { 48 49 server := httptest.NewServer(httpbuffer.Handler{ 50 Handler: test.Buffers, 51 }) 52 53 var buf strings.Builder 54 55 r, _ := http.NewRequest(http.MethodGet, server.URL, nil) 56 57 if !test.compress { 58 r.Header.Set("Accept-Encoding", "identity") 59 } 60 61 if result, err := server.Client().Do(r); err != nil { 62 t.Errorf("test %d: unexpected error: %v", n+1, err) 63 } else if result.StatusCode != test.code { 64 t.Errorf("test %d: expecting code %d, got %d", n+1, test.code, result.StatusCode) 65 } else if result.Uncompressed != test.compress { 66 t.Errorf("test %d: unexpected Uncompressed to be %v, got %v", n+1, test.compress, result.Uncompressed) 67 } else if _, err = io.Copy(&buf, result.Body); err != nil { 68 t.Errorf("test %d: unexpected error copying body: %v", n+1, err) 69 } else if output := buf.String(); output != test.output { 70 t.Errorf("test %d: expecting output %q, got %q", n+1, test.output, output) 71 } else if len(output) != test.length { 72 t.Errorf("test %d: expecting content length %d, got %d", n+1, test.length, len(output)) 73 } 74 75 server.Close() 76 } 77 } 78 79 type Buffers [][]byte 80 81 func (b Buffers) ServeHTTP(w http.ResponseWriter, _ *http.Request) { 82 for _, p := range b { 83 w.Write(p) 84 } 85 } 86