Test a pipeline without a daemon
Test a pipeline with pytest when you want to check its plain pipeline code and its function steps in less than a second, without the daemon, the code server or a run. In this guide you add pytest to the factory py-factory of the tutorial and write three tests of intake: one checks the new tickets it returns, and two check its stops. At the end, uv run pytest prints 3 passed, and a test fails when you change what intake does. A last section tests the pipeline ship_feature, whose agent steps and human step get their step outputs and answers from the test. If pytest stops with an error, see Troubleshooting at the end of this page.
Before you start
Section titled “Before you start”- You built
intakein the tutorial Build a pipeline that files tickets, and your terminal is in its folderpy-factory. Run each command there. - The tests don’t use
codeband dev. It can run or not.
How a pipeline runs in a test
Section titled “How a pipeline runs in a test”A test that calls a pipeline calls its function once, in the test’s process. No run starts: there is no engine, no run journal and no invocation, so codeband records nothing and replays nothing.
| In pipeline code | In a run | In a test |
|---|---|---|
Plain pipeline code, such as plan_tickets |
Runs again on every invocation | Runs once |
| A function step | Runs in the code server on its first call. Every later invocation returns the recorded value | Runs as a plain function on every call, with the test’s environment variables |
| A function step that raises | Pipeline code gets cb.FunctionStepFailedError |
Pipeline code gets the function step’s own exception, such as URLError |
| A function step that runs longer than its timeout | Pipeline code gets cb.FunctionStepFailedError with the type TimeoutError |
Runs to its end. The timeout doesn’t apply |
raise cb.Stop(reason) |
The run ends stopped | The test gets cb.Stop, with the text in reason |
return None or return cb.RunResult(...) |
The run ends with nothing or with the run result, and codeband delivers its code change and its new tickets | The test gets the value. Nothing is delivered |
A with block on a cb.Stage |
The steps in the block belong to the stage | Does nothing. The code in the block runs |
cb.shell_step, Agent.do, Agent.start and cb.gather, cb.human_step, cb.run_head and cb.start_commit |
The engine runs the shell step, the agent step or the human step. cb.run_head and cb.start_commit return a commit of the run |
Raises RuntimeError, such as cb.shell_step runs only inside a run. A test that calls the pipeline with call_pipeline gives each step its step output or answer |
A function step’s exception reaches pipeline code unchanged, so contextlib.suppress(cb.FunctionStepFailedError) in intake doesn’t catch it in a test. A test controls the side effects of each function step through what the function step reads: post_summary reads PY_FACTORY_WEBHOOK. How a function step fails shows what the same function step does in a run.
A test checks what the pipeline does for an input and the step outputs that the test gives. It doesn’t check what only a run shows: that each invocation asks for the same steps in the same order, as Run replay requires, the timeouts, and the work of the programs and agents. Run the pipeline with codeband run for those.
-
Add pytest
Terminal window uv add --dev pytestuv adds
pytestto thedevdependency group ofpyproject.toml, installs it in.venvand prints the packages it installed,pytest==9.2.0among them. -
Tell pytest where your code is
Add these lines at the end of
pyproject.toml:pyproject.toml [tool.pytest]pythonpath = ["."]markers = ["unit: does not require a database or network"]pythonpathputs the folderpy-factoryon Python’s import path, so that a test can importpy_factory.uv run pytestdoesn’t add it without this line.markersregisters the markerunit, which the tests of the next step use. pytest reads the table[tool.pytest]from version 9 on. -
Write the tests
Make a folder
testsand save this file astests/test_pipeline.py:tests/test_pipeline.py """Outside a run, a pipeline is a function and its function steps run as plain functions."""import codeband as cbimport pytestfrom py_factory.function_steps import WEBHOOK_ENVfrom py_factory.pipeline import intake@pytest.fixture(autouse=True)def no_webhook(monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.delenv(WEBHOOK_ENV, raising=False)@pytest.mark.unitdef test_intake_returns_one_new_ticket_per_bullet() -> None:got = intake(title="Release 1.2", body="- Fix the crash on start\n- Add a dark mode")assert got == cb.RunResult(tickets=[cb.NewTicket(title="Fix the crash on start", body="Part of the request Release 1.2.", tags=["bug", "small"]),cb.NewTicket(title="Add a dark mode", body="Part of the request Release 1.2.", tags=["feature", "small"]),])@pytest.mark.unit@pytest.mark.parametrize(("body", "max_tickets", "reason"),[("no bullets", 5, "the request has no tickets"),("- one\n- two\n- three", 2, "the request has 3 tickets, more than 2"),],)def test_intake_stops(body: str, max_tickets: int, reason: str) -> None:with pytest.raises(cb.Stop) as stopped:intake(title="t", body=body, max_tickets=max_tickets)assert stopped.value.reason.startswith(reason)The fixture
no_webhookruns before each test of the file, because ofautouse=True. It removesPY_FACTORY_WEBHOOK, sopost_summarysends nothing and returnsFalse. pytest’smonkeypatchsets the variable back after each test.test_intake_returns_one_new_ticket_per_bulletcallsintakewith a run input of two bullets. It checks thatintakereturns acb.RunResultwith onecb.NewTicketper bullet and no code change. In a run, codeband writes these tickets as files when the run ends; in a test, nothing writes them.test_intake_stopschecks both stops ofintake:pytest.raises(cb.Stop)catches the stop, andreasonholds its text. -
Run the tests
Terminal window uv run pytestpytest finds the test file in
tests, runs the three tests and prints3 passed. Your platform line differs:Output ============================= test session starts ==============================platform darwin -- Python 3.12.13, pytest-9.2.0, pluggy-1.7.0rootdir: …/py-factoryconfigfile: pyproject.tomlcollected 3 itemstests/test_pipeline.py ... [100%]============================== 3 passed in 0.08s =============================== -
Commit the tests
A run starts at the
HEADcommit of its target repository, and the tutorial’s runs usepy-factoryfor that. Commit the tests, so thatcodeband rundoesn’t logThe repository has uncommitted changes. The run does not see them.:Terminal window git add -Agit commit -m "Test intake with pytest"git prints the commit’s ID and
3 files changed:pyproject.toml,uv.lockandtests/test_pipeline.py.
Check that it worked
Section titled “Check that it worked”Change what intake does and see a test fail. In py_factory/pipeline.py, change the request has no tickets in the first cb.Stop to the request lists no tickets, and run the tests again:
uv run pytestThe test of that stop fails. In its FAILURES section, above the summary, pytest prints the test’s code and the reason that intake gave, the request lists no tickets: write each one as a '- ' bullet:
tests/test_pipeline.py .F. [100%]…FAILED tests/test_pipeline.py::test_intake_stops[no bullets-5-the request has no tickets]========================= 1 failed, 2 passed in 0.11s ==========================Undo the change with git checkout py_factory/pipeline.py. uv run pytest prints 3 passed again.
Test a pipeline with agent steps, shell steps and human steps
Section titled “Test a pipeline with agent steps, shell steps and human steps”A pipeline that runs a shell step, an agent step or a human step raises RuntimeError when a test calls it, because no engine runs the step. Call it with call_pipeline of the module codeband.testing instead. The test gives the run input as a mapping from parameter name to argument, such as {"instruction": "greet the team"}, which call_pipeline checks against the pipeline’s parameters as a run does. It gives the step outputs of the agent steps and shell steps in step_outputs, by agent name or shell step name, and the answers to the human steps in answers, by human step name. Each step takes the next value of its name, in order. Function steps run as plain functions, as above.
The pipeline ship_feature of examples/py-factory runs the agent step planner, asks a person to approve the plan at the human step approve_plan, then runs the agent steps builder and reviewer. Its tests give each agent step an output, answer the human step and check the steps that ship_feature asked for and how it ended:
import codeband as cbimport pytestfrom codeband.testing import call_pipeline
from py_factory.feature import BuilderInput, BuilderOutput, Plan, PlanVerdict, Review, ship_feature
PLAN = Plan(summary="Add greeting.txt", steps=["Write greeting.txt.", "Commit it."])BUILT = BuilderOutput(title="Add greeting.txt", summary="Adds a file that greets the team.")
@pytest.mark.unitdef test_ship_feature_builds_the_approved_plan_and_ends_with_the_builders_commit() -> None: call = call_pipeline( ship_feature, {"instruction": "greet the team"}, step_outputs={"planner": [PLAN], "builder": [BUILT], "reviewer": [Review(approve=True, comments="")]}, answers={"approve_plan": [PlanVerdict(approve=True, notes="Be brief.")]}, )
assert [(step.id, step.stage) for step in call.steps] == [ ("planner#0", "plan"), ("approve_plan#0", ""), ("builder#0", "build"), ("reviewer#0", "review"), ] assert call.steps[2].input == BuilderInput(instruction="greet the team", steps=PLAN.steps, notes="Be brief.") assert call.code_change == cb.CodeChange( commit=call.steps[2].output.commit, title=BUILT.title, description=BUILT.summary )
@pytest.mark.unitdef test_ship_feature_stops_when_the_plan_is_not_approved() -> None: call = call_pipeline( ship_feature, {"instruction": "greet the team"}, step_outputs={"planner": [PLAN]}, answers={"approve_plan": [{"approve": False, "notes": "Greet in German."}]}, )
assert [step.id for step in call.steps] == ["planner#0", "approve_plan#0"] assert call.stop_reason == "the plan was not approved: Greet in German."
@pytest.mark.unitdef test_ship_feature_stops_when_the_reviewer_does_not_approve() -> None: call = call_pipeline( ship_feature, {"instruction": "greet the team"}, step_outputs={"planner": [PLAN], "builder": [BUILT], "reviewer": [Review(approve=False, comments="Too long.")]}, answers={"approve_plan": [PlanVerdict(approve=True)]}, )
assert call.code_change is None assert call.stop_reason == "the reviewer did not approve the change: Too long."call_pipeline returns a PipelineCall. Its steps list each step in order with its step ID, its stage, its input and the step output that pipeline code got, so call.steps[2].input is the input that builder got from the plan and the approval. Its code_change is the code change of the run result that the pipeline returned, its tickets the new tickets of the run result, and its stop_reason the reason of a cb.Stop. The commit of an agent step whose agent may write is a commit ID that call_pipeline makes from the step ID, and the run head moves there, as in a run. A step output can also be JSON, as the answer {"approve": False, ...} shows; call_pipeline checks each one against the step’s output type or answer type.
In examples/py-factory, run them:
uv run pytest tests/test_ship_feature.pypytest prints 3 passed. A shell step takes a cb.ShellStep, and exited makes one for a program that exited with an exit code: tests/test_program.py of examples/py-factory gives the shell step program of run_program the step output exited(2, "FAILED test_start\n") and checks the stop. An agent step that takes a cb.FakeFailure raises cb.AgentStepFailedError, for a test of the code that handles a failed agent step. A parallel agent step of Agent.start takes the next step output of its name when it starts and leaves the run head where it is. cb.gather returns the agent steps in argument order, or raises the cb.AgentStepFailedError of the first failed one in argument order.
When the step outputs and answers don’t fit the steps, call_pipeline raises StepOutputError, and the test fails. Troubleshooting lists the messages.
Troubleshooting
Section titled “Troubleshooting”For an error in a run, see Run problems.
ModuleNotFoundError: No module named 'py_factory'
Section titled “ModuleNotFoundError: No module named 'py_factory'”pytest can’t import your code, so it stops with Interrupted: 1 error during collection. pyproject.toml has no pythonpath, or pytest is older than version 9 and doesn’t read [tool.pytest]. Add the lines of step 2. uv run pytest --version prints the version.
PytestUnknownMarkWarning: Unknown pytest.mark.unit - is this a typo?
Section titled “PytestUnknownMarkWarning: Unknown pytest.mark.unit - is this a typo?”The tests pass, and pytest prints this warning for each test, because pyproject.toml doesn’t register the marker. Add the markers line of step 2.
RuntimeError: cb.shell_step runs only inside a run
Section titled “RuntimeError: cb.shell_step runs only inside a run”The test calls a pipeline that runs a shell step. An agent step raises RuntimeError: agent writer: an agent step runs only in a pipeline that the code server runs, and a human step raises RuntimeError: cb.human_step works only in a run, where a person can answer it. Call the pipeline with call_pipeline, as Test a pipeline with agent steps, shell steps and human steps shows.
StepOutputError: the pipeline asks for builder#0, but the test gives no step output for it
Section titled “StepOutputError: the pipeline asks for builder#0, but the test gives no step output for it”The pipeline asked for one more agent step or shell step of that name than step_outputs holds. For a human step, the message ends with gives no answer for it. Add a step output or an answer for the step, or check why the pipeline asked for it: a loop that ran once more than you expected is a finding of the test.
StepOutputError: the pipeline did not ask for every step output and answer, left over: step outputs reviewer: 1
Section titled “StepOutputError: the pipeline did not ask for every step output and answer, left over: step outputs reviewer: 1”The pipeline ended before it used each step output and answer of the test. The message counts the unused ones per name. Remove them, or check why the pipeline ended early: call.stop_reason shows a stop.
StepOutputError: the step output of builder#0 is not a BuilderOutput
Section titled “StepOutputError: the step output of builder#0 is not a BuilderOutput”A step output doesn’t match the agent’s output type, or a shell step’s step output is not a cb.ShellStep. An answer that doesn’t match the human step’s answer type gives the answer to approve_plan#0 does not fit its answer type. The rest of the message is pydantic’s error, which names each field that doesn’t match.
urllib.error.URLError: <urlopen error [Errno 61] Connection refused>
Section titled “urllib.error.URLError: <urlopen error [Errno 61] Connection refused>”A test without the fixture no_webhook, such as one in another file, gets PY_FACTORY_WEBHOOK from your shell, so post_summary sends the summary to that URL. Nothing answers there, and contextlib.suppress(cb.FunctionStepFailedError) doesn’t catch the function step’s own exception. On Linux, the number is 111. Give the test the fixture no_webhook.
Related
Section titled “Related”- Pipeline explains the run input and how a pipeline ends a run, the two things these tests check.
- Run replay lists the rules that only a run checks.
- Python SDK lists
call_pipeline, the fields ofPipelineCallandStep, and what each step gets in a test. - Handle a function step that fails or times out shows how a function step fails in a run.