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.

The properties of the request handler (like path) are available as variables in snippets.

With return end(content, status, **headers) the snippet can return 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 the following POST requests:

  • /__add reads a snippet from the request body and adds it to the request handler

  • /__del removes all snippets so far

  • /__set removes all and add this one

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 path == '/say-hello' and query.get('x') == 'y':
        return end('HELLO')
''')

# invoke it

res = requests.get('http://mock-server/say-hello?x=y')
assert res.text == 'HELLO'

The mockserver runs in a GWS container, so all gws modules are available for import.

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.

body: bytes

Raw request body.

json: dict

Request body decoded as json.

method: str

GET, POST etc.

path: str

Url path part.

protocol_version = 'HTTP/1.1'

Protocol version.

query: dict

Query string as a key => value dict, e.g. {'a': '1', 'b': '2', ...etc}

query2: dict

Query string as a key => [values] dict, e.g. {'a': ['1', '2'], ...etc}

remote_host: str

Remote host.

remote_port: int

Remote post.

text: str

Request body decoded as utf8.

do_GET()

Serve a GET request.

do_POST()
end(content, status=200, **headers)
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.

prepare(body: bytes)
run_snippets()
gws.test.mockserver.main()