Mehdi
12/24/2025, 2:22 PMMarvin
12/24/2025, 2:22 PMMarvin
12/24/2025, 2:25 PM.fn(...) — this bypasses Prefect’s engine and will not try to reach the API.
- Works for both flows and tasks.
Example:
from prefect import flow, task
@task
def add(a, b):
return a + b
@flow
def my_flow(x, y):
# for unit tests, call task functions directly too
return add.fn(x, y)
# no API calls, just pure Python
result = my_flow.fn(1, 2)
print(result) # 3
Notes:
- If your task uses get_run_logger(), wrap the call with disable_run_logger() in tests:
from prefect.logging import disable_run_logger
with disable_run_logger():
result = my_task.fn(...)
2) Integration-style tests (exercise Prefect orchestration without an external API)
- Use prefect_test_harness() to run against a temporary local test database. This lets you call flows normally (e.g., .submit(), .result(), states) without connecting to <http://prefect:4200/api/>.
Example:
from prefect import flow, task
from prefect.testing.utilities import prefect_test_harness
@task
def add(a, b):
return a + b
@flow
def my_flow(x, y):
fut = add.submit(x, y)
return fut.result()
with prefect_test_harness():
print(my_flow(1, 2)) # 3
Why you’re seeing the error
- Calling my_flow() (not .fn) tells Prefect to create a flow run and contact the API at <http://prefect:4200/api/> (from PREFECT_API_URL). If that URL isn’t reachable, you’ll get “Cannot create flow run. Failed to reach API…”.
- For testing, either:
- Use .fn(...) to bypass the engine entirely, or
- Wrap your tests in prefect_test_harness() to run locally without a real backend.
If you share what you want to validate (pure function behavior vs. Prefect features like .submit(), retries, state), I can suggest the exact pattern to use.