github.com/opentelekomcloud/gophertelekomcloud@v0.9.3/testhelper/http_responses.go (about) 1 package testhelper 2 3 import ( 4 "encoding/json" 5 "io/ioutil" 6 "net/http" 7 "net/http/httptest" 8 "net/url" 9 "reflect" 10 "testing" 11 ) 12 13 var ( 14 // Mux is a multiplexer that can be used to register handlers. 15 Mux *http.ServeMux 16 17 // Server is an in-memory HTTP server for testing. 18 Server *httptest.Server 19 ) 20 21 // SetupHTTP prepares the Mux and Server. 22 func SetupHTTP() { 23 Mux = http.NewServeMux() 24 Server = httptest.NewServer(Mux) 25 } 26 27 // TeardownHTTP releases HTTP-related resources. 28 func TeardownHTTP() { 29 Server.Close() 30 } 31 32 // Endpoint returns a fake endpoint that will actually target the Mux. 33 func Endpoint() string { 34 return Server.URL + "/" 35 } 36 37 // TestFormValues ensures that all the URL parameters given to the http.Request are the same as values. 38 func TestFormValues(t *testing.T, r *http.Request, values map[string]string) { 39 t.Helper() 40 want := url.Values{} 41 for k, v := range values { 42 want.Add(k, v) 43 } 44 45 _ = r.ParseForm() 46 if !reflect.DeepEqual(want, r.Form) { 47 t.Errorf("Request parameters = %v, want %v", r.Form, want) 48 } 49 } 50 51 // TestMethod checks that the Request has the expected method (e.g. GET, POST). 52 func TestMethod(t *testing.T, r *http.Request, expected string) { 53 t.Helper() 54 if expected != r.Method { 55 t.Errorf("Request method = %v, expected %v", r.Method, expected) 56 } 57 } 58 59 // TestHeader checks that the header on the http.Request matches the expected value. 60 func TestHeader(t *testing.T, r *http.Request, header string, expected string) { 61 t.Helper() 62 if actual := r.Header.Get(header); expected != actual { 63 t.Errorf("Header %s = %s, expected %s", header, actual, expected) 64 } 65 } 66 67 // TestBody verifies that the request body matches an expected body. 68 func TestBody(t *testing.T, r *http.Request, expected string) { 69 t.Helper() 70 b, err := ioutil.ReadAll(r.Body) 71 if err != nil { 72 t.Errorf("Unable to read body: %v", err) 73 } 74 str := string(b) 75 if expected != str { 76 t.Errorf("Body = %s, expected %s", str, expected) 77 } 78 } 79 80 // TestJSONRequest verifies that the JSON payload of a request matches an expected structure, without asserting things about 81 // whitespace or ordering. 82 func TestJSONRequest(t *testing.T, r *http.Request, expected string) { 83 t.Helper() 84 b, err := ioutil.ReadAll(r.Body) 85 if err != nil { 86 t.Errorf("Unable to read request body: %v", err) 87 } 88 89 var actualJSON interface{} 90 err = json.Unmarshal(b, &actualJSON) 91 if err != nil { 92 t.Errorf("Unable to parse request body as JSON: %v", err) 93 } 94 95 CheckJSONEquals(t, expected, actualJSON) 96 }