python - pytest:在测试用例不可见的 fixture 中分配属性

标签 python pytest fixtures teardown

为什么我无法在 pytest fixture 中设置 self.param 值?


class TestClass:
    @pytest.fixture(scope='class', autouse=True)
    def setup_class(self, test_env):
        self.param = 2

    def teardown_method(self):
        remove_setting(self.param)
    
    def test_one(self):
        assert self.param == 2

    def test_two(self):
        assert len("hello") == 5
这导致
scratch.py::TestClass::test_one FAILED                                 

    def test_one(self):
>       assert self.param == 2
E       AttributeError: 'TestClass' object has no attribute 'param'

    def teardown_method(self):
>       remove_setting(self.param)
E       AttributeError: 'TestClass' object has no attribute 'param'
我想在设置期间设置此属性,因为我最终将使用该参数执行方法级拆卸(不是类级拆卸,所以我没有使用产量)。在这个例子中,我的测试看不到 self.param 值,我的拆卸函数也看不到。将 self.param = 2 移动到我所有的测试中很麻烦。有什么更好的方法来做到这一点?

最佳答案

docs说:

Something to be aware of when grouping tests inside classes is that each test has a unique instance of the class. Having each test share the same class instance would be very detrimental to test isolation and would promote poor test practices.


我建议使用这样的类范围 fixture :
import pytest

@pytest.fixture(scope='module')
def test_env():
    pass

@pytest.fixture(scope='class')
def param(test_env):
    return 2


class TestClass:
    def test_one(self, param):  # All tests methods share the same param
        assert param == 2

    def test_two(self, param):
        assert param == 3

关于python - pytest:在测试用例不可见的 fixture 中分配属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63552491/

相关文章:

python - 使用 enumerate 循环多个列表

python - 如何将文件列表传递给 python open() 方法

python - 如何在 Python 程序中正确使用 gdaladdo?

python - 如何找到 n 维 numpy 数组的第 i 个最大元素的索引?

python - py.test 无法导入我的模块

pytest - 执行完所有测试后如何运行特定代码?

symfony - 在 Sylius 中安装 Fixtures - Symfony2

ruby-on-rails - 用于测试的未定义方法 `users'

python-2.7 - 与另一个 fixture 一起使用时找不到 PyTest fixture

ruby-on-rails - 迁移可以应用于 Ruby on Rails 中的固定装置吗?