首页 > 解决方案 > 在为其他装饰器(例如夹具、模拟)传递参数时如何正确使用 pytest mark.parametrize 装饰器?

问题描述

当我尝试将 mark.parametrize 与其他装饰器一起使用时,如下所示:

@pytest.fixture(autouse=True)
def some_fixture()
 db = create_db()
 yield db
 db.close()

@pytest.mark.parametrize('id, expected',[(1,1),(2,2)])
@mock.patch('some_module')
def some_test(mock_module, id, expected, db):
 mock_module.function.return_value = 1
 connection = db.connection()
 assert expected my_function(id, connection)

我有两个问题:

标签: pythonmockingpytest

解决方案


当一起使用 patch、parametrize 和 fixtures 时,顺序很重要:拳头应该以相反的顺序提及 patched 值,然后以任意顺序在最后提及参数化值和 fixtures。

@pytest.fixture
def some_fixture1()
    pass

@pytest.fixture
def some_fixture2()
    pass

@pytest.mark.parametrize('id, expected',[(1,1),(2,2)])
@mock.patch('some_module1')
@mock.patch('some_module2')
@mock.patch('some_module3')
def some_test(
   some_module3, 
   some_module2, 
   some_module1, 
   id, 
   expected,
   some_fixture1,
   some_fixture2,
):
    pass

推荐阅读