You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

116 lines
2.7 KiB

package main
import (
"io/ioutil"
"log"
"net/http"
"net/http/httptest"
"net/url"
"os"
"testing"
)
func TestFeedbackHttpHandler(t *testing.T) {
var req *http.Request
var rr *httptest.ResponseRecorder
var handler http.HandlerFunc
var expectedBody string
var expectedStatus int
var form url.Values
var err error
// No POST data.
dir, err := ioutil.TempDir("", "rantbinTestingDir")
if err = os.Chdir(dir); err != nil {
t.Fatal(err)
}
defer os.Chdir("..")
defer os.RemoveAll(dir)
req, err = http.NewRequest(http.MethodPost, "", nil)
if err != nil {
t.Fatal(err)
}
rr = httptest.NewRecorder()
handler = http.HandlerFunc(feedbackHttpHandler)
handler.ServeHTTP(rr, req)
expectedStatus = http.StatusBadRequest
if rr.Code != expectedStatus {
t.Errorf("Got %v expected %v for empty body.", rr.Code, expectedStatus)
} else {
log.Printf("Got code %v for empty body.", rr.Code)
}
expectedBody = ErrorNoFormData + "\n"
if rr.Body.String() != expectedBody {
t.Errorf("Got %v, expected %v", rr.Body.String(), expectedBody)
} else {
log.Printf("Got body %v for empty body.", rr.Body.String())
}
req, err = http.NewRequest("POST", "", nil)
if err != nil {
t.Fatal(err)
}
// Valid request
form = url.Values{}
form.Set("page", "such a page")
form.Set("data", "much data")
req, err = http.NewRequest(http.MethodPost, "", nil)
req.Form = form
if err != nil {
t.Fatal(err)
}
rr = httptest.NewRecorder()
handler = http.HandlerFunc(feedbackHttpHandler)
handler.ServeHTTP(rr, req)
expectedStatus = http.StatusOK
if rr.Code != expectedStatus {
t.Errorf("Got %v expected %v for valid post.", rr.Code, expectedStatus)
} else {
log.Printf("Got code %v for valid post.", rr.Code)
}
expectedBody = MsgFeedbackReceived
if rr.Body.String() != expectedBody {
t.Errorf("Got %v, expected %v", rr.Body.String(), expectedBody)
} else {
log.Printf("Got body %v for valid post.", rr.Body.String())
}
// Same request again, should fail because it's already there.
form = url.Values{}
form.Set("page", "such a page")
form.Set("data", "much data")
req, err = http.NewRequest(http.MethodPost, "", nil)
req.Form = form
if err != nil {
t.Fatal(err)
}
rr = httptest.NewRecorder()
handler = http.HandlerFunc(feedbackHttpHandler)
handler.ServeHTTP(rr, req)
expectedStatus = http.StatusBadRequest
if rr.Code != expectedStatus {
t.Errorf("Got %v expected %v for identical feedback.", rr.Code, expectedStatus)
} else {
log.Printf("Got code %v for identical feedback.", rr.Code)
}
expectedBody = ErrorIdenticalFeedback + "\n"
if rr.Body.String() != expectedBody {
t.Errorf("Got %v, expected %v", rr.Body.String(), expectedBody)
} else {
log.Printf("Got body %v for identical feedback.", rr.Body.String())
}
}