【问题标题】:Pytest call setup() before fixturePytest 在夹具之前调用 setup()
【发布时间】:2017-09-01 15:43:25
【问题描述】:

我在我的 pytest 单元测试中使用固定装置时遇到了困难。

我正在使用这样的测试类:

class TestMyApp(object):

    def setup(self):
        self.client = mock_client()

    @pytest.fixture
    def client_item(self):
        return self.client.create_item('test_item')

    def test_something1(self, client_item):
        # Test here.
        pass

当我运行上述测试时,我得到以下异常:

AttributeError: 'TestMyApp' object has no attribute 'client'

我相信这是因为 client_item() 固定函数在 setup() 函数之前被调用。

我是否错误地使用了固定装置?或者有什么方法可以强制在夹具功能之前调用setup()

提前致谢。

【问题讨论】:

    标签: python python-3.x unit-testing pytest


    【解决方案1】:

    fixtures可以使用其他fixtures,所以你可以一直使用fixtures:

    class TestMyApp(object):
    
        @pytest.fixture
        def client(self):
            return mock_client()
    
        @pytest.fixture
        def client_item(self, client):
            return client.create_item('test_item')
    
        def test_something1(self, client_item):
            # Test here.
            pass
    

    documentation 巧妙地推荐了固定装置而不是 xUnit 风格的设置/拆卸方法:

    虽然这些 setup/teardown 方法对于来自 unittestnose 背景的人来说既简单又熟悉,但您也可以考虑使用 pytest 更强大的 fixture mechanism,它利用依赖注入的概念,允许更多用于管理测试状态的模块化和更具可扩展性的方法,尤其适用于大型项目和功能测试。

    接着说这两种风格可以混用,但不清楚事情发生的顺序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-29
      • 1970-01-01
      相关资源
      最近更新 更多