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
Run Code Online (Sandbox Code Playgroud)
如果我想添加批量更改用户电子邮件的功能并且在测试前需要设置 10 个用户,有没有办法使用相同的固定装置在同一测试中生成多个用户对象?
pytest 文档中有一个“工厂作为固定装置”部分解决了我的问题。
特别是这个示例(从链接复制/粘贴):
@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")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4444 次 |
| 最近记录: |