gws.test.mockserver
¶
Test web server.
This server runs in a dedicated docker container during testing and acts as a mock for our http-related functionality.
This server does almost nothing by default, but the client can “extend” it by providing “snippets”.
A snippet is a Python code fragment, which is injected directly into the request handler.
It views the request handler object as self
and must end with a call to self.out(text, status)
,
which returns an HTTP response to the client.
When a request arrives, all snippets added so far are executed until one of them returns.
The server understands two POST requests:
/__add
reads a snippet from the request body and adds it to the request handler/__del
removes all snippets so far.
IT IS AN EXTREMELY BAD IDEA TO RUN THIS SERVER OUTSIDE OF A TEST ENVIRONMENT.
Example of use:
# set up a snippet
requests.post('http://mock-server/__add', data=r'''
if self.path == '/say-hello':
return self.out('HELLO')
''')
# invoke it
text = requests.get('http://mock-server/say-hello')
assert text == 'HELLO'
Useful properties of the handler object (self
) to use in snippets
client_address - tuple[host, port]
path - url path
method - GET/POST
body - raw bytes body>
text - body decoded as utf8
json - body decoded as json
query - query string dict, e.g. {'a': '1', 'b': '2'}
query2 - query string array dict, e.g. {'a': ['1'], 'b': ['2']}
Source code: gws.test.mockserver
Module Contents¶
- class gws.test.mockserver.HTTPRequestHandler(*args, directory=None, **kwargs)¶
Bases:
http.server.SimpleHTTPRequestHandler
Simple HTTP request handler with GET and HEAD commands.
This serves files from the current directory and any of its subdirectories. The MIME type for files is determined by calling the .guess_type() method.
The GET and HEAD requests are identical except that the HEAD request omits the actual contents of the file.
- protocol_version = 'HTTP/1.1'¶
- method: str¶
- body: bytes¶
- text: str¶
- json: dict¶
- query: dict¶
- query2: dict¶
- handle_one_request()¶
Handle a single HTTP request.
You normally don’t need to override this method; see the class __doc__ string for information on how to handle specific HTTP commands such as GET and POST.
- do_GET()¶
Serve a GET request.
- do_POST()¶
- prepare(body: bytes)¶
- execute()¶
- out(content, status=200, content_type=None, headers=None)¶
- gws.test.mockserver.dedent(s)¶
- gws.test.mockserver.indent(s)¶
- gws.test.mockserver.main()¶