以下是使用user
夹具设置测试的测试代码示例。
@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个用户?
答案 0 :(得分:1)
pytest文档有一个“factories as fixtures” - 部分解决了我的问题。
特别是这个例子(从链接中复制/粘贴):
@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")