Search code examples
pythonpython-3.xpytestaiohttp

strange behavior of aiohttp with pytest


So, I want to return HTTPNoContent response in specific controller (I'm using aiohttp). And then I want to test it with pytest:

from aiohttp import web
from aiohttp.web import HTTPNoContent

async def hello(request):
    raise HTTPNoContent(text="some test!")
    return web.Response(text='Hello, world')

async def test_hello(aiohttp_client):
    app = web.Application()
    app.router.add_get('/', hello)
    client = await aiohttp_client(app)
    resp = await client.get('/')
    assert resp.status == 204
    text = await resp.text()
    assert 'some test!' in text

But, when i'm runnin it like pytest lol_test.py I'm getting error in this test:

AssertionError: assert 'some test!' in ''

So, my text is empty in my response, why? Can't figure it out. Thanks. Im using 3.8.5 of aiohttp, pytest==7.4.2, pytest-aiohttp==0.3.0


Solution

  • I'm not very familiar with aiohttp but after seeing the source code in the version you're using, there is an if statement in the superclass which says:

            if self.body is None and not self.empty_body:
                self.text = f"{self.status}: {self.reason}"
    

    so it will only populate text if self.empty_body is False.

    And if you see the source code of HttpNoContent, this attribute is set to True:

    class HTTPNoContent(HTTPSuccessful):
        status_code = 204
        empty_body = True
    

    This means that with HTTPNoContent you'll always have an empty .text.

    After all, 204 reponses should not have any content:

    204 No Content

    The server successfully processed the request, and is not returning any content.