【问题标题】: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 将数据从一个测试用例传递到下一个测试用例,您会产生几个问题:

    1. 测试必须按此顺序运行。首先是test_create_user,然后是test_set_password
    2. 必须运行所有测试。您不能单独重新运行 test_set_password
    3. 之前的所有测试都必须通过。如果test_create_user 失败,我们就不能再有意义地运行test_set_password
    4. 测试不能再并行运行。

    所以为了防止这种设计,pytest 明智地决定每个测试都获得一个全新的测试类实例。

    【讨论】:

      【解决方案2】:

      只是添加到Thomas 答案,请注意目前您提到的文档中存在错误。正如open issue on pytest Github 中所述,在下面的解释中,两个测试都被证明共享相同的类实例,位于 0xdeadbeef。这似乎证明了与所说的相反(实例不相同)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-04
        • 2021-05-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多