aiohttp 与 pytest 的奇怪行为

问题描述 投票:0回答:1

所以,我想在特定控制器中返回

HTTPNoContent
响应(我正在使用
aiohttp
)。然后我想用
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

但是,当我像

pytest lol_test.py
那样运行时,我在这个测试中遇到了错误:

AssertionError: assert 'some test!' in ''

所以,我的

text
在我的回复中是空的,为什么?想不通。谢谢。我正在使用
3.8.5
aiohttp
pytest==7.4.2
 中的 
pytest-aiohttp==0.3.0

python-3.x pytest aiohttp
1个回答
0
投票

我对

aiohttp
不是很熟悉,但是看过源代码后,超类中有一个if语句,上面写着

        if text is None:
            if not self.empty_body:
                text = f"{self.status_code}: {reason}"

因此,如果

text
为 False,它只会填充
self.empty_body

如果你看到HttpNoContent

源代码
,这个属性被设置为
True

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

这意味着使用

HTTPNoContent
你将永远有一个空的
.text

© www.soinside.com 2019 - 2024. All rights reserved.