Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading