Commit 155d1b6f authored by Kamil Trzcinski's avatar Kamil Trzcinski

Added test for new helper methods

parent 81fc0554
......@@ -186,5 +186,6 @@ func ReadRequestBody(w http.ResponseWriter, r *http.Request, maxBodySize int64)
func CloneRequestWithNewBody(r *http.Request, body []byte) *http.Request {
newReq := *r
newReq.Body = ioutil.NopCloser(bytes.NewReader(body))
newReq.ContentLength = int64(len(body))
return &newReq
}
package helper
import (
"bytes"
"io"
"net/http"
"net/http/httptest"
"testing"
)
......@@ -47,3 +50,54 @@ func TestSetForwardedForGeneratesHeader(t *testing.T) {
}
}
}
func TestReadRequestBody(t *testing.T) {
data := []byte("123456")
rw := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/test", bytes.NewBuffer(data))
result, err := ReadRequestBody(rw, req, 1000)
if !bytes.Equal(result, data) {
t.Fatalf("Expected to receive the same result, got %v", result)
}
if err != nil {
t.Fatalf("Expected to not receive error from reading")
}
}
func TestReadRequestBodyLimit(t *testing.T) {
data := []byte("123456")
rw := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/test", bytes.NewBuffer(data))
result, err := ReadRequestBody(rw, req, 2)
if len(result) != 0 {
t.Fatalf("Expected empty result, got %v", result)
}
if err == nil {
t.Fatalf("Expected to receive error from reading")
}
}
func TestCloneRequestWithBody(t *testing.T) {
input := []byte("test")
newInput := []byte("new body")
req := httptest.NewRequest("POST", "/test", bytes.NewBuffer(input))
newReq := CloneRequestWithNewBody(req, newInput)
if req == newReq {
t.Fatalf("Expected a new request to be different from old one")
}
if req.Body == newReq.Body {
t.Fatalf("Expected the body object to be different")
}
if newReq.ContentLength != int64(len(newInput)) {
t.Fatalf("Expected the Content-Length to be updated")
}
var buffer bytes.Buffer
io.Copy(&buffer, newReq.Body)
if !bytes.Equal(buffer.Bytes(), newInput) {
t.Fatal("Expected the readed body to be the same as passed to function")
}
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment