如何在pytest中全局修补?

2024-10-01 17:25:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我经常在代码中使用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如下所示:

^{pr2}$

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

像这样的事我可以做

from mock import patch

class Test1:
   def test_1():
       with patch('core.feature.service.Utility') as MockedUtils:
           exectute_test_case_1()

这会有用的。不过,我刚刚在代码库中添加了Utility,我有300多个测试用例。我不想深入每个测试用例并编写这个with语句。在

我可以写一个conftest.py,它设置一个操作系统级的环境变量,core.feature.service.FeatureManager.execute可以根据这个变量决定不执行utility.doThings,但我不知道这是否是解决这个问题的一个干净的解决方案。在

如果有人能在整个会议期间帮我做全球补丁,我将不胜感激。我想在整个会话中全局地使用上面的with块。任何关于这件事的文章都会很棒。在

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


Tags: 代码pycoretestexecuteinitservicewith
1条回答
网友
1楼 · 发布于 2024-10-01 17:25:26

我添加了一个名为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)

这没什么复杂的。就像在做

^{pr2}$

但只是以整个会话的方式。在

相关问题 更多 >

    热门问题