python – 如何在pytest中全局修补?

前端之家收集整理的这篇文章主要介绍了python – 如何在pytest中全局修补?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的代码使用pytest相当多.示例代码结构如下所示.整个代码库是 python-2.7
  1. core/__init__.py
  2. core/utils.py
  3.  
  4. #feature
  5.  
  6. core/feature/__init__.py
  7. core/feature/service.py
  8.  
  9. #tests
  10. core/feature/tests/__init__.py
  11. core/feature/tests/test1.py
  12. core/feature/tests/test2.py
  13. core/feature/tests/test3.py
  14. core/feature/tests/test4.py
  15. core/feature/tests/test10.py

service.py看起来像这样:

  1. from modules import stuff
  2. from core.utils import Utility
  3.  
  4.  
  5. class FeatureManager:
  6. # lots of other methods
  7. def execute(self,*args,**kwargs):
  8. self._execute_step1(*args,**kwargs)
  9. # some more code
  10. self._execute_step2(*args,**kwargs)
  11. utility = Utility()
  12. utility.doThings(args[0],kwargs['variable'])

feature / tests / *中的所有测试最终都使用core.feature.service.FeatureManager.execute函数.但是,当我运行测试时,我不需要运行utility.doThings().我需要它在生产应用程序运行时发生,但我不希望它在测试运行时发生.

我可以在我的core / feature / tests / test1.py中做类似的事情

  1. from mock import patch
  2.  
  3. class Test1:
  4. def test_1():
  5. with patch('core.feature.service.Utility') as MockedUtils:
  6. exectute_test_case_1()

这会奏效.但是我刚刚在代码库中添加了Utility,我有300多个测试用例.我不想进入每个测试用例并用声明写这个.

我可以编写一个conftest.py来设置一个os级环境变量,core.feature.service.FeatureManager.execute可以决定不执行该实用程序.但是我不知道这是否是这个问题的干净解决方案.

如果有人可以帮助我完成整个会话的全局补丁,我将不胜感激.我想在整个会话期间做全局上面的with block所做的事情.这件事的任何文章都会很棒.

TLDR:如何在运行pytests时创建会话范围的补丁?

解决方法

添加了一个名为core / feature / conftest.py的文件,看起来像这样
  1. import logging
  2. import pytest
  3.  
  4.  
  5. @pytest.fixture(scope="session",autouse=True)
  6. def default_session_fixture(request):
  7. """
  8. :type request: _pytest.python.SubRequest
  9. :return:
  10. """
  11. log.info("Patching core.feature.service")
  12. patched = mock.patch('core.feature.service.Utility')
  13. patched.__enter__()
  14.  
  15. def unpatch():
  16. patched.__exit__()
  17. log.info("Patching complete. Unpatching")
  18.  
  19. request.addfinalizer(unpatch)

这并不复杂.这就像在做

  1. with mock.patch('core.feature.service.Utility') as patched:
  2. do_things()

但只能在会议范围内.

猜你在找的Python相关文章