How to patch globally in pytest?

I added a file called core/feature/conftest.py that looks like this

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)

This is nothing complicated. It is like doing

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

but only in a session-wide manner.


Building on the currently accepted answer for a similar use case (4.5 years later), using unittest.mock's patch with a yield also worked:

from typing import Iterator
from unittest.mock import patch

import pytest


@pytest.fixture(scope="session", autouse=True)
def default_session_fixture() -> Iterator[None]:
    log.info("Patching core.feature.service")
    with patch("core.feature.service.Utility"):
        yield
    log.info("Patching complete. Unpatching")

Aside

For this answer I utilized autouse=True. In my actual use case, to integrate into my unit tests on a test-by-test basis, I utilized @pytest.mark.usefixtures("default_session_fixture").


Versions

Python==3.8.6
pytest==6.2.2