【问题标题】:pytest fixture yield list of dict throws "yield_fixture function has more than one 'yield':"dict 的 pytest 夹具产量列表抛出“yield_fixture 函数有多个‘产量’:”
【发布时间】:2019-12-30 20:47:24
【问题描述】:

我已经定义了一个像这样的夹具:

    @pytest.fixture
    def mock_yield_data(self):
        for data in [
            {
                1: 2, 2: 3
            },
            {
                2: 4, 4: 5
            },
        ]:
            yield data

以及类似的测试方法:

    def test_fixture(self, mock_yield_data):
        for data in mock_yield_data:
            assert data

断言成功,但teardown 抛出,yield_fixture function has more than one 'yield':

==================================================================================================== ERRORS ====================================================================================================
_________________________________________________________________________ ERROR at teardown of TestClass.test_fixture _________________________________________________________________________
yield_fixture function has more than one 'yield':

【问题讨论】:

    标签: python pytest fixtures


    【解决方案1】:

    您的灯具可能只有一个yield。但是,您可以将parameters 传递给夹具,它将为每个参数运行夹具。

    all_data = [
        {
            1: 2, 2: 3
        },
        {
            2: 4, 4: 5
        }
    ]
    
    @pytest.fixture(params=all_data)
    def mock_yield_data(self, request):
        yield request.param
    

    【讨论】:

    • 你的例子比文档还要好!
    【解决方案2】:

    pytest.yieldfixture 文档的最后一部分:

    • 通常yield 用于产生多个值。但是fixture 函数只能产生一个值。产生第二个夹具值会给你一个错误。我们可以改进 pytest 以允许生成多个值作为当前参数化的替代方案。目前,您可以将正常的夹具参数化机制与 yield-style 夹具一起使用。

    由于内存占用这么小,您应该只返回整个内容:

    @pytest.fixture
    def mock_yield_data(self):
        return [
            {
                1: 2, 2: 3
            },
            {
                2: 4, 4: 5
            },
        ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-10
      • 2014-09-17
      • 1970-01-01
      • 2021-09-11
      • 1970-01-01
      • 1970-01-01
      • 2016-08-25
      相关资源
      最近更新 更多