Patch does not take effect in conftest

conftest.py

@pytest.fixture(autouse=True)
def patch_result_table_permission():
    """Mock获取RT权限查询"""
    from aiops.common.apis.modules import auth

    auth.get_project_has_permission_result_table = lambda x: [
        'test_table'
    ]

It can take effect in the test file, but it does not take effect when the test file calls views in another file. It is because pytest will import modules first , and then look for fixtures in modules. At this time, the get_project_has_permission_result_table imported in the views file will be executed, and then the fixture operation will be executed.

Because the view file was imported first, it was too late to execute the fixture.

Solution 1

pytest medium new increase pytest_sessionstart

def pytest_sessionstart(session):
    from aiops.common.apis.modules import auth

    auth.get_project_has_permission_result_table = lambda x: [
		'test_table'
    ]

Solution 2

Use the mock module directly, and the path of the mock is the get_project_has_permission_result_table in the views, not the defined place, because when the function is imported in the views, it is already bound to a local name under this module.

    @mock.patch('aiops.common.apis.modules.meta.MetaApi.result_tables.retrieve')
    @mock.patch('aiops.common.apis.modules.query.QueryApi.query')
    @mock.patch('aiops.logic.sample_set.views.result_table.get_project_has_permission_result_table')
    def test_result_table_groups(self, mock_permission, mock_query, mock_result_tables_retrieve):
    mock_permission.return_value = ['test_table']

reference

https://stackoverflow.com/questions/46733332/how-to-monkeypatch-the-environment-using-pytest-in-conftest-py

Guess you like

Origin blog.csdn.net/qq_42648305/article/details/112858427