Alastair
03/16/2026, 6:03 PMprefect config-based configuration?Marvin
03/16/2026, 6:03 PMMarvin
03/16/2026, 6:06 PM# tests/conftest.py
import os
import pytest
@pytest.fixture(scope="session", autouse=True)
def _prefect_test_guardrails(monkeypatch):
# Make accidental API use fail fast
monkeypatch.setenv("PREFECT_SERVER_ALLOW_EPHEMERAL_MODE", "false")
# Unroutable/invalid URL to guarantee immediate failure on network use
monkeypatch.setenv("PREFECT_API_URL", "<http://127.0.0.1:0>")
# Avoid picking up a local profile during tests
monkeypatch.delenv("PREFECT_PROFILE", raising=False)
yield
Why this works: prefect.testing.utilities.prefect_test_harness() uses temporary_settings() which takes precedence over env vars, so it will safely override the invalid URL inside tests that opt-in to the harness. Everywhere else, accidental API calls fail immediately without starting any server.
2) Opt-in harness fixture you can use per test
# tests/conftest.py (continued)
import pytest
from prefect.testing.utilities import prefect_test_harness
@pytest.fixture
def prefect_harness():
with prefect_test_harness():
yield
Usage options:
- Use it explicitly in a test:
def test_my_flow(prefect_harness):
...
- Or enforce it via a marker you already use:
import pytest
@pytest.mark.usefixtures("prefect_harness")
def test_flow_marked_prefect():
...
3) Optional: fail fast when a “prefect-marked” test forgot the harness
If you already mark tests that might hit Prefect (e.g., @pytest.mark.prefect), add a small guard that fails those tests if the harness was not started.
# tests/conftest.py (continued)
import pytest
from prefect.settings import PREFECT_API_URL
@pytest.fixture(autouse=True)
def _require_harness_for_prefect_mark(request):
if request.node.get_closest_marker("prefect"):
api_url = PREFECT_API_URL.value()
if not api_url or api_url == "<http://127.0.0.1:0>":
pytest.fail(
"This test is marked @pytest.mark.prefect but no test harness/API is running. "
"Use `with prefect_test_harness():` or `@pytest.mark.usefixtures('prefect_harness')`."
)
Notes and tips
- Keep Prefect client creation inside tests/functions, not at import time. Pytest fixtures apply after import; if you must guard even imports, set the same env vars in your test runner/CI command (e.g., export PREFECT_SERVER_ALLOW_EPHEMERAL_MODE=false and PREFECT_API_URL=http://127.0.0.1:0 before pytest runs).
- This approach avoids starting a server globally, keeps non-Prefect tests fast, and guarantees quick failure anywhere you forgot the harness.
Docs and source links
- How to test workflows: How to test workflows
- Testing utilities (includes prefect_test_harness): API ref: prefect.testing.utilities
- Testing fixtures: API ref: prefect.testing.fixtures
- Source: prefect_test_harness implementation utilities.pyMarvin
03/16/2026, 6:06 PMAlastair
03/16/2026, 6:09 PM