私はコードに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 個以上あります。各テスト ケースにアクセスしてこのステートメントを記述するのは望ましくありませんwith
。
conftest.py
OS レベルの環境変数を設定し、それに基づいてcore.feature.service.FeatureManager.execute
が を実行しないことを決定できる を作成することもできますutility.doThings
が、それがこの問題の明確な解決策であるかどうかはわかりません。
セッション全体へのグローバル パッチについて、どなたか助けていただけるとありがたいです。with
上記のブロックで行ったことを、セッション全体に対してグローバルに実行したいと思います。この件に関する記事があれば、それもありがたいです。
TLDR: pytests の実行中にセッション全体のパッチを作成するにはどうすればよいですか?
ベストアンサー1
core/feature/conftest.py
次のようなファイルを追加しました
import logging
import pytest
from unittest import mock
@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()
ただし、セッション全体でのみ有効です。