你在哪里传递aiohttp测试用例中的处理程序信息client.request

时间:2018-02-08 22:55:13

标签: unit-testing python-3.6 testcase aiohttp

我正在尝试使用AioHttp TestCase库,只使用文档中提供的示例代码,但是当我运行404时它会显示pytest filename.py

我也看到了上面的一些例子,首先我不了解test_client和self.client之间的区别。他们都在做同样的事情,只是采用不同的方法吗?

另外,在下面的实现中,您在哪里传递处理程序信息? self.client不接受处理程序参数hello

from aiohttp.test_utils import AioHTTPTestCase, unittest_run_loop
from aiohttp import web

from aiohttp.test_utils import AioHTTPTestCase, unittest_run_loop
from aiohttp import web


async def hello(request):
   return web.Response(text='Hello')

class MyAppTestCase(AioHTTPTestCase):

   async def get_application(self):
        return web.Application()

   @unittest_run_loop
   async def test_example(self):
        request = await self.client.request("GET", "/")
        assert request.status == 200
        text = await request.text()
        assert "Hello, world" in text

1 个答案:

答案 0 :(得分:0)

pytest的

test_client固定装置应该只是make与AioHTTPTestCase.client相同的工厂

当我希望在TestClient中进行编码时,一切都变成了_request,看起来像这样:

async def _request(
        self,
        method: str,
        str_or_url: StrOrURL, *,
        params: Optional[Mapping[str, str]]=None,
        data: Any=None,
        json: Any=None,
        cookies: Optional[LooseCookies]=None,
        headers: LooseHeaders=None,
        skip_auto_headers: Optional[Iterable[str]]=None,
        auth: Optional[BasicAuth]=None,
        allow_redirects: bool=True,
        max_redirects: int=10,
        compress: Optional[str]=None,
        chunked: Optional[bool]=None,
        expect100: bool=False,
        raise_for_status: Optional[bool]=None,
        read_until_eof: bool=True,
        proxy: Optional[StrOrURL]=None,
        proxy_auth: Optional[BasicAuth]=None,
        timeout: Union[ClientTimeout, object]=sentinel,
        verify_ssl: Optional[bool]=None,
        fingerprint: Optional[bytes]=None,
        ssl_context: Optional[SSLContext]=None,
        ssl: Optional[Union[SSLContext, bool, Fingerprint]]=None,
        proxy_headers: Optional[LooseHeaders]=None,
        trace_request_ctx: Optional[SimpleNamespace]=None
) -> ClientResponse:

因此您可以将这些传递给客户端,它将进行呼叫。 datajson应该相同(期望与requests一样),json只是将其转储。

所以这样的事情应该起作用。至少对我来说:

class BookingTest(AioHTTPTestCase):

    async def get_application(self):
        return await create_test_app()

    @unittest_run_loop
    async def test_create_booking(self):
        data = {
            "my_id": "1234"
        }
        # the post data should be in request.body 
        # (we use connexion and we have it parsed as an argument to handler named body)
        resp = await self.client.request("POST", "/api/bookings", json=data)
        assert resp.status == 201

    @unittest_run_loop
    async def test_get_booking(self):
        booking_id = "1234"
        url = f"/be/api/bookings/{booking_id}"
        resp = await self.client.request("GET", url)
        assert resp.status == 200