python – 如何在pytest中全局修补?
我的代码使用pytest相当多.示例代码结构如下所示.整个代码库是
python-2.7
core/__init__.py core/utils.py #feature core/feature/__init__.py core/feature/service.py #tests core/feature/tests/__init__.py core/feature/tests/test1.py core/feature/tests/test2.py core/feature/tests/test3.py core/feature/tests/test4.py core/feature/tests/test10.py service.py看起来像这样: from modules import stuff from core.utils import Utility class FeatureManager: # lots of other methods def execute(self,*args,**kwargs): self._execute_step1(*args,**kwargs) # some more code self._execute_step2(*args,**kwargs) utility = Utility() utility.doThings(args[0],kwargs['variable']) feature / tests / *中的所有测试最终都使用core.feature.service.FeatureManager.execute函数.但是,当我运行测试时,我不需要运行utility.doThings().我需要它在生产应用程序运行时发生,但我不希望它在测试运行时发生. 我可以在我的core / feature / tests / test1.py中做类似的事情 from mock import patch class Test1: def test_1(): with patch('core.feature.service.Utility') as MockedUtils: exectute_test_case_1() 这会奏效.但是我刚刚在代码库中添加了Utility,我有300多个测试用例.我不想进入每个测试用例并用声明写这个. 我可以编写一个conftest.py来设置一个os级环境变量,core.feature.service.FeatureManager.execute可以决定不执行该实用程序.但是我不知道这是否是这个问题的干净解决方案. 如果有人可以帮助我完成整个会话的全局补丁,我将不胜感激.我想在整个会话期间做全局上面的with block所做的事情.这件事的任何文章都会很棒. TLDR:如何在运行pytests时创建会话范围的补丁? 解决方法
我添加了一个名为core / feature / conftest.py的文件,看起来像这样
import logging import pytest @pytest.fixture(scope="session",autouse=True) def default_session_fixture(request): """ :type request: _pytest.python.SubRequest :return: """ log.info("Patching core.feature.service") patched = mock.patch('core.feature.service.Utility') patched.__enter__() def unpatch(): patched.__exit__() log.info("Patching complete. Unpatching") request.addfinalizer(unpatch) 这并不复杂.这就像在做 with mock.patch('core.feature.service.Utility') as patched: do_things() 但只能在会议范围内. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |