How to fix globally in pytest?

I use pytest quite a bit for my code. An example code structure is as follows. The entire code basepython-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 It looks something like this:

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'])

All tests are feature/tests/*completed using the function core.feature.service.FeatureManager.execute. However, utility.doThings()I do not need to run while I run the tests. I need this to happen during the execution of the production application, but I do not want this to happen during the execution of the tests.

I can do something like this in my 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()

It will work. However, I added Utilityonly to the code base, and I have more than 300 test cases. I would not want to go into each test case and write this statement with.

conftest.py, os, core.feature.service.FeatureManager.execute utility.doThings, , .

, - . , with . .

TL;DR: pytests?

+4
1

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()

.

+4

Source: https://habr.com/ru/post/1650159/


All Articles