本文介绍了如何在作用域会话中使用pytest-aiohttp固定装置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为aiohttp应用程序编写测试.我正在使用pytest-aiohttp插件.我的意图是在第一次测试执行之前初始化和运行应用程序一次,并在所有测试完成后将其拆除. pytest-aiohttp固定装置,例如'loop','test_client'很有帮助,但是它们具有scope ='function',这意味着我无法在自己的具域='session'的固定装置中使用它们.有办法解决此问题吗?如果不是,那么在不使用内置固定装置的情况下实现我的目标的正确方法是什么?我的代码如下(conftest.py)

I am trying to write tests for aiohttp application. I am using pytest-aiohttp plugin. My intention is to initialize and run the application once before first test execution and tear down after all tests finished. pytest-aiohttp fixtures like 'loop', 'test_client' are very helpful but they have scope='function' which means I can not use them from my own fixture with scope='session'. Is there a way to workaround this? And if not then what would be a proper approach for achieving my goal without using built-in fixtures?My code is as follows (conftest.py)

@pytest.fixture()
def client(test_client, loop):
    app = init(loop)
    return loop.run_until_complete(test_client(app))

然后使用我的测试

class TestGetAlerts:
async def test_get_login_url(self, client):
    resp = await client.get('/api/get_login_url')
    assert resp.status == 200

因此,我的灯具客户端"会在每次测试时运行,这是我要避免的情况

So my fixture 'client' runs for every test, which is what i want to avoid

推荐答案

test_client夹具是来自 aiohttp.test_utils .

test_client fixture is a simple wrapper around TestServer and TestClient classes from aiohttp.test_utils.

您可以使用'session'范围制作自己的灯具版本.

You can craft your own version of the fixture with 'session' scope.

但是这种方式有其自身的问题:应该隔离测试,实际上,这意味着每个测试都需要重新创建事件循环.

But this way has own problems: tests should be isolated, in practice it means event loop recreation for every test.

但是会话级的aiohttp应用程序不支持这种循环娱乐.因此,该应用程序应在单独的线程中运行,这会使编写测试断言变得更加困难.

But session-level aiohttp application doesn't support such loop recreation. Thus the app should be run in separate thread which makes writing test assertions much harder.

在我的实践中,aiohttp应用程序会立即启动,但是数据库模式迁移和数据库夹具的应用需要时间.这些活动可以轻松地在会话范围内实现,就像单独的固定装置一样,但应在每次测试中执行应用启动/停止操作.

In my practice aiohttp application starts instantly but things like DB schema migration and DB fixtures applying takes time. These activities could be implemented in session scope easy as separate fixtures but app starting/stopping should be performed inside every test.

这篇关于如何在作用域会话中使用pytest-aiohttp固定装置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 03:13