如何在作用域会话中使用pytest

编程入门 行业动态 更新时间:2024-10-26 07:30:58
本文介绍了如何在作用域会话中使用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

本文发布于:2023-11-23 10:17:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1621085.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:作用   如何在   pytest

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!