How to disable Prefect logger for unit tests?

Option 1: disable_run_logger

Here is an example fixture you could add to conftest.py:

from prefect.logging import disable_run_logger
from prefect.testing.utilities import prefect_test_harness


@pytest.fixture(autouse=True, scope="session")
def prefect_disable_logging():
    with disable_run_logger():
        yield


@pytest.fixture(autouse=True, scope="session")
def prefect_test_fixture():
    with prefect_test_harness():
        yield

Option 2: monkeypatch

Given example flow ex.py:

from prefect import flow, get_run_logger

@flow
def my_flow():
    get_run_logger().info("I am logging stuff")
    return 42

and a test file test_ex.py, you can create the following Mock object:

from unittest.mock import Mock
from ex import my_flow

def test_my_flow(monkeypatch):
    mock_logger = Mock()
    monkeypatch.setattr("ex.get_run_logger", mock_logger)
    res = my_flow()
    ...

And you can include it as a fixture as well:

from unittest.mock import Mock
from ex import my_flow
import pytest

@pytest.fixture
def mock_logger(monkeypatch):
    mock_logger = Mock()
    monkeypatch.setattr("ex.get_run_logger", mock_logger)
    return mock_logger

def test_my_flow(mock_logger):
    res = my_flow()

Discussion