2016-08-04 59 views
3

我對我的代碼使用了很多pytest。示例代碼結構如下所示。整個代碼庫是python-2.7如何在pytest中全局打補丁?

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看起來是這樣的:使用core.feature.service.FeatureManager.execute功能

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/*結束了。不過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多個測試用例。我不想進入每個測試用例並寫下這個with聲明。

我可以寫一個conftest.py這臺基於操作系統級別的環境變量在其上core.feature.service.FeatureManager.execute可以決定不執行utility.doThings,但我不知道這是否是一個乾淨的解決這個問題。

如果有人能夠幫助我整個會話的全局補丁,我將不勝感激。我想要在整個會話中全球做with塊。這件事上的任何文章都會很棒。

TLDR:如何在運行pytests時創建會話範圍的補丁?

回答

3

我添加了一個名爲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() 

但只在一個會議範圍內的方式。