pytest -- how do I use global / session-wide fixtures?(pytest--如何使用全局/会话范围的fixture?)
问题描述
我希望有一个"全局装置"(在pytest中它们也可以称为"会话范围的装置"),它执行一些昂贵的环境设置,比如通常准备资源,然后在测试模块之间重用该资源。设置如下所示
Shared_env.py
会让一个fixture执行一些开销很大的工作,如启动Docker容器、MySQL服务器等。
@pytest.yield_fixture(scope="session")
def test_server():
start_docker_container(port=TEST_PORT)
yield TEST_PORT
stop_docker_container()
test_a.py
将使用服务器
def test_foo(test_server): ...
test_b.py
将使用同一服务器
def test_foo(test_server): ...
似乎pytest通过scope="session"
支持这一点,但是我不知道如何使实际的导入工作。当前安装程序将显示错误消息,如
fixture 'test_server' not found
available fixtures: pytestconfig, ...
use 'py.test --fixtures [testpath] ' for help on them
推荐答案
Pytest中有一个约定,它使用名为conftest.py
的特殊文件并包含会话装置。
我摘录了两个非常简单的示例来快速入门。它们不使用类。
取自http://pythontesting.net/framework/pytest/pytest-session-scoped-fixtures/的所有内容
示例1:
装置除非作为参数提供给test_*
函数,否则不会执行。装置some_resource
在调用引用函数之前执行,在本例中为test_2
。另一方面,终结器在结束时执行。
conftest.py:
import pytest
@pytest.fixture(scope="session")
def some_resource(request):
print('
Some resource')
def some_resource_fin():
print('
Some resource fin')
request.addfinalizer(some_resource_fin)
test_a.py:
def test_1():
print('
Test 1')
def test_2(some_resource):
print('
Test 2')
def test_3():
print('
Test 3')
结果:
$ pytest -s
======================================================= test session starts ========================================================
platform linux -- Python 3.4.3 -- py-1.4.26 -- pytest-2.7.0
rootdir: /tmp/d2, inifile:
collected 3 items
test_a.py
Test 1
.
Some recource
Test 2
.
Test 3
.
Some resource fin
示例2:
这里的fixture配置为autouse=True
,因此它在会话开始时执行一次,并且不需要被引用。其终结器在会话结束时执行。
conftest.py:
import pytest
@pytest.fixture(scope="session", autouse=True)
def auto_resource(request):
print('
Some resource')
def auto_resource_fin():
print('
Some resource fin')
request.addfinalizer(auto_resource_fin)
test_a.py:
def test_1():
print('
Test 1')
def test_2():
print('
Test 2')
def test_3():
print('
Test 3')
结果:
$ pytest -s
======================================================= test session starts ========================================================
platform linux -- Python 3.4.3 -- py-1.4.26 -- pytest-2.7.0
rootdir: /tmp/d2, inifile:
collected 3 items
test_a.py
Some recource
Test 1
.
Test 2
.
Test 3
.
Some resource fin
这篇关于pytest--如何使用全局/会话范围的fixture?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:pytest--如何使用全局/会话范围的fixture?


- 如何在 python3 中将 OrderedDict 转换为常规字典 2022-01-01
- padding='same' 转换为 PyTorch padding=# 2022-01-01
- 如何在 Python 的元组列表中对每个元组中的第一个值求和? 2022-01-01
- python check_output 失败,退出状态为 1,但 Popen 适用于相同的命令 2022-01-01
- 分析异常:路径不存在:dbfs:/databricks/python/lib/python3.7/site-packages/sampleFolder/data; 2022-01-01
- 如何将一个类的函数分成多个文件? 2022-01-01
- 使用Heroku上托管的Selenium登录Instagram时,找不到元素';用户名'; 2022-01-01
- pytorch 中的自适应池是如何工作的? 2022-07-12
- python-m http.server 443--使用SSL? 2022-01-01
- 沿轴计算直方图 2022-01-01