How to test a HTTP server or REST API¶
You can create HTTP client using http_clients attribute in a TestServer subclasse:
class TestRestServer(TestServer):
http_clients = [
{
"name": "Alice",
"host": "127.0.0.1",
"port": "{port-1}",
"extra_headers": [
('Content-Type', 'application/json')
]
}
]
http_client available parameters¶
-
HTTPClient.
__init__
(host, port, timeout, tries, wait, headers, extra_headers=None)¶ Parameters: - host (str) – Server host
- port (int) – The number of tries
- tries (int) – The number of tries
- timeout (int) – Deadline before abort request
- headers (List[Tuple]) – The default headers used when you call request method without define headers parameter.
- extra_headers (List[Tuple]) – Always used when you call request method by default extra_headers contains the User-Agent.
Your HTTP clients are instantiate in clients class attribute and you may use them in the input method:
class GetHotels(TestRestServer, start=True):
def input(self):
self.clients["Alice"].get("/hotels")
HTTPClient methods¶
-
HTTPClient.
request
(method, path, headers=None, timeout=None, data=<object object>)¶ Performe HTTP request to path
Parameters: - method (str) – HTTP verb such as ‘GET’, ‘POST’, …
- path (str) – HTTP server path
- headers (List[Tuple]) – HTTP headers must be 2-tuple (header, value) if headers is not define __init__ headers parameter is used.
- timeout (int) – Deadline before abort request
- data (object) – HTTP request content. data is serialised regarding the content-type define in the HTTP headers. You can change this behavior updating serializers class attribute.
-
HTTPClient.
get
(*args, **kwargs)¶ Shortcut to request(GET, …)
-
HTTPClient.
post
(*args, **kwargs)¶ Shortcut to request(POST, …)
-
HTTPClient.
put
(*args, **kwargs)¶ Shortcut to request(PUT, …)
-
HTTPClient.
delete
(*args, **kwargs)¶ Shortcut to request(DELETE, …)
-
HTTPClient.
patch
(*args, **kwargs)¶ Shortcut to request(PATCH, …)
Response testing¶
The client stores HTTP response in response attribute using HTTPResponse object. This HTTPResponse object provide methods useful for test server.
-
HTTPResponse.
assert_header_has
(header, expected_value, separator=', ')¶ Test if header of HTTP response contains the expected_value.
-
HTTPResponse.
assert_header_is
(header, expected_values, separator=', ')¶ Test if value header of HTTP response is the expected_value.
-
HTTPResponse.
assert_status_code
(status_code)¶ Test if status code of HTTP response is status_code
-
HTTPResponse.
assert_reason
(reason)¶ Test if reason of HTTP response is reason
Example:
class GetHotels(TestRestServer, start=True):
def test_status_code_should_be_200(self):
self.clients["Alice"].response.assert_status_code(200)
def test_content_has_hotel_california(self):
content = self.clients["Alice"].response.content
expected = ({
"name": "California",
"addr": "1976 eagles street"
},)
self.assertCountEqual(content, expected)