[英]How to organize tests in a class in Pytest?
根据 Pytest 中的“https://docs.pytest.org/en/stable/getting-started.html”,当在类中对测试进行分组时,每个测试都有一个唯一的 ZA2F2ED4F8EBC2CBB4C21A29DC40AB6 实例让每个测试共享相同的 class 实例将对测试隔离非常不利,并且会促进不良的测试实践。这是什么意思? 这概述如下: test_class_demo 的内容。
class TestClassDemoInstance:
def test_one(self):
assert 0
def test_two(self):
assert 0
假设您正在测试一个用户帐户系统,您可以在其中创建用户和更改密码。 您需要有一个用户才能更改其密码,并且您不想重复自己,因此您可以像这样天真地构建测试:
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 明智地决定每个测试都获得一个全新的测试实例 class。
只是为了添加到Thomas的答案中,请注意,您提到的文档中目前存在错误。 如pytest Github 上的这个未决问题中所述,在下面的解释中,两个测试都被证明共享相同的 class 实例,位于 0xadbeef. 这似乎证明了与所说的相反(实例不相同)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.