我定义了一个固定装置,它接受在集成样式测试中使用的参数,该测试需要在完成后进行一些拆卸。它看起来像这样:
@pytest.fixture
def create_user_in_third_party():
from clients import third_party_client
def _create_user_in_third_party(user: User):
third_party_client.create_user(user)
return _create_user_in_third_party
但是,一旦测试的生命周期完成,我们希望清理创建的用户。在标准装置中,这可能看起来像:
@pytest.fixture
def create_user():
user = User(name="Jim")
user.save()
yield user
user.delete()
当将相同的范例应用于采用上面参数的固定装置时,我根本没有看到固定装置被调用(返回一个不执行内部方法代码的生成器)。
该代码(不起作用)如下所示:
def create_user_in_third_party():
from clients import third_party_client
def _create_user_in_third_party(user: User):
third_party_client.create_user(user)
yield # give back control to caller
third_party_client.delete_user(user)
return _create_user_in_third_party
是否可以实现上述目标,而不必将创建和删除分解为两个不同的装置?
根据文档,您可以使用标记将数据传递到夹具,例如:
test.py
import pytest
class User:
def __init__(self, name):
self.name = name
def save(self):
pass
def delete(self):
pass
@pytest.fixture
def create_user(request):
marker = request.node.get_closest_marker("db_username")
if marker is None:
name = 'Jim'
else:
name = marker.args[0]
user = User(name=name)
user.save()
yield user
user.delete()
@pytest.mark.db_username('John')
def test_user(create_user):
assert create_user.name == 'John'
同时在 pytest.ini
中
对准标记。
pytest.ini
[pytest]
markers =
db_username: data for create_user fixture
跑步
pytest test.py
:
(venv) $ pytest test.py
================= test session starts =================
platform linux -- Python 3.8.10, pytest-8.2.0, pluggy-1.5.0
rootdir: /app/pytest-test
configfile: pytest.ini
collected 1 item
test.py . [100%]
========================================== 1 passed in 0.00s ==========================================