Source code for micro.web.testing

"""
Contains various test-related utilities.

See tests/ for examples of testing Micro.Web application
"""
import asyncio

from aiohttp import client
from asynctest import TestCase


[docs]def task_succeed(result): """ Inspired by t.i.defer.succeed, wraps a value in coroutine which returns that value. Suitable for providing return values for coroutine mocks. """ def coro(): return result return asyncio.coroutine(coro)()
[docs]class AppTestCase(TestCase): """ A test case for application which is capable of creating application test servers. """ @asyncio.coroutine
[docs] def run_app(self, app): """ Run the application for testing. Be aware to call yield from stop_server() when the test succeeds :param app: Application instance to run :type app: :class:`micro.web.Micro` """ handler = app.make_handler() self.server = yield from self.loop.create_server(handler, '127.0.0.1', 0) host, port = self.server.sockets[0].getsockname() self.port = port
@asyncio.coroutine
[docs] def stop_server(self): """ Stop the running server, which has been previously started with run_app() """ self.server.close() yield from self.server.wait_closed() self.port = None
[docs] def make_request(self, method, url, *args, **kwargs): """ Make a request to a previously run application :param method: HTTP method to use for request :type method: str :param url: A relative URL to be requested :param args: Arguments to be proxied to `aiohttp.client.request` :param kwargs: Keyworded arguments to be proxied to `aiohttp.client.request` :return: Waiter for response :rtype: asyncio.Task """ url = 'http://127.0.0.1:{port}'.format(port=str(self.port)) + url return client.request(method, url, *args, **kwargs)
__all__ = ["AppTestCase", "task_succeed"]