<@ULVA73B9P> How can I run a function that is a prefect flow without a prefect backend. For testing ...
m
@Marvin How can I run a function that is a prefect flow without a prefect backend. For testing purpose only. Right now I get An error occurred: Cannot create flow run. Failed to reach API at http://prefect:4200/api/
m
thought for 195.8 seconds
You’ve got two good options in Prefect 3.x depending on what you want to test: 1) Fast unit tests (no Prefect backend at all) - Call the underlying Python function with
.fn(...)
— this bypasses Prefect’s engine and will not try to reach the API. - Works for both flows and tasks. Example:
Copy code
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:
Copy code
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:
Copy code
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.