【问题标题】:How to organize tests in a class in Pytest?如何在 Pytest 的类中组织测试?
【发布时间】:2021-03-27 14:27:19
【问题描述】:
根据 Pytest 中的“https://docs.pytest.org/en/stable/getting-started.html”在类内对测试进行分组时,每个测试都有一个唯一的类实例。让每个测试共享同一个类实例对测试隔离非常不利,并且会促进不良的测试实践。这是什么意思?这概述如下:
test_class_demo 的内容。
class TestClassDemoInstance:
def test_one(self):
assert 0
def test_two(self):
assert 0
【问题讨论】:
标签:
python
selenium
pytest
【解决方案1】:
假设您正在测试一个用户帐户系统,您可以在其中创建用户和更改密码。您需要有一个用户才能更改其密码,并且您不想重复自己,因此您可以像这样天真地构建测试:
class TestUserService:
def test_create_user(self):
# Store user_id on self to reuse it in subsequent tests.
self.user_id = UserService.create_user("timmy")
assert UserService.get_user_id("timmy") == self.user_id
def test_set_password(self):
# Set the password of the user we created in the previous test.
UserService.set_password(self.user_id, "hunter2")
assert UserService.is_password_valid(self.user_id, "hunter2")
但是通过使用self 将数据从一个测试用例传递到下一个测试用例,您会产生几个问题:
- 测试必须按此顺序运行。首先是
test_create_user,然后是test_set_password。
- 必须运行所有测试。您不能单独重新运行
test_set_password。
- 之前的所有测试都必须通过。如果
test_create_user 失败,我们就不能再有意义地运行test_set_password。
- 测试不能再并行运行。
所以为了防止这种设计,pytest 明智地决定每个测试都获得一个全新的测试类实例。