<@ULVA73B9P> for unit testing is it possible to ru...
# ask-marvin
k
@Marvin for unit testing is it possible to run a flow and pass it a uuid for its flow run id?
m
thought for 351.2 seconds
Short answer: yes, in Prefect 3.x you can run a flow under test with a specific flow run ID so that
prefect.runtime.flow_run.id()
returns your UUID. Do it by running the flow via the engine and supplying a context dict. Example (pytest-style):
Copy code
from uuid import uuid4
from prefect import flow
from prefect.flow_engine import run_flow_sync
from prefect.runtime import flow_run as runtime_flow_run

@flow
def my_flow():
    return runtime_flow_run.id()

def test_flow_uses_given_run_id():
    run_id = str(uuid4())
    result = run_flow_sync(my_flow, context={"flow_run": {"id": run_id}})
    assert result == run_id
Notes: - This approach is preferable to trying to pass a custom run ID through the high-level
my_flow()
call, which does not accept it. - There isn’t a public environment variable to force the runtime flow run id. The supported way is to pass
context
to `run_flow_sync`/`run_flow_async`. - For unit tests that don’t need Prefect context, consider structuring your business logic to accept a
run_id
as a normal parameter and call
my_flow.fn(...)
to bypass the engine. But if your code reads
prefect.runtime.flow_run.id()
, use the engine + context approach above. Are you on Prefect 3.x? If you’re on 2.x, the approach differs slightly and I can share the 2.x pattern too.