在同一个测试中重用 pytest 固定装置 [英] Reusing pytest fixture in the same test
本文介绍了在同一个测试中重用 pytest 固定装置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下是使用 user
固定装置设置测试的测试代码示例.
Below is an example of test code that uses a user
fixture to setup the test.
@pytest.fixture
def user():
# Setup db connection
yield User('test@example.com')
# Close db connection
def test_change_email(user):
new_email = 'new@example.com'
change_email(user, new_email)
assert user.email == new_email
有没有办法在同一个测试中使用同一个夹具生成多个用户对象,如果我想,例如添加批量更改用户电子邮件的功能,并且需要在测试前设置 10 个用户?
Is there a way to generate multiple user objects in the same test using the same fixture, if I wanted to e.g. add functionality for changing user emails in bulk and needed 10 users setup before the test?
推荐答案
pytest 文档有一个工厂作为固定装置"-解决了我的问题的部分.
The pytest documentation had a "factories as fixtures"-section that solved my problem.
特别是这个例子(从链接复制/粘贴):
This example in particular (copy/pasted from the link):
@pytest.fixture
def make_customer_record():
created_records = []
def _make_customer_record(name):
record = models.Customer(name=name, orders=[])
created_records.append(record)
return record
yield _make_customer_record
for record in created_records:
record.destroy()
def test_customer_records(make_customer_record):
customer_1 = make_customer_record("Lisa")
customer_2 = make_customer_record("Mike")
customer_3 = make_customer_record("Meredith")
这篇关于在同一个测试中重用 pytest 固定装置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文