Skip to content
codeband is pre-release. These docs describe its first release, and some of what they describe is still being built.

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.

  • You built intake in the tutorial Build a pipeline that files tickets, and your terminal is in its folder py-factory. Run each command there.
  • The tests don’t use codeband dev. It can run or not.

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.

  1. Add pytest

    Terminal window
    uv add --dev pytest

    uv adds pytest to the dev dependency group of pyproject.toml, installs it in .venv and prints the packages it installed, pytest==9.2.0 among them.

  2. 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"]

    pythonpath puts the folder py-factory on Python’s import path, so that a test can import py_factory. uv run pytest doesn’t add it without this line. markers registers the marker unit, which the tests of the next step use. pytest reads the table [tool.pytest] from version 9 on.

  3. Write the tests

    Make a folder tests and save this file as tests/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 cb
    import pytest
    from py_factory.function_steps import WEBHOOK_ENV
    from py_factory.pipeline import intake
    @pytest.fixture(autouse=True)
    def no_webhook(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.delenv(WEBHOOK_ENV, raising=False)
    @pytest.mark.unit
    def 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_webhook runs before each test of the file, because of autouse=True. It removes PY_FACTORY_WEBHOOK, so post_summary sends nothing and returns False. pytest’s monkeypatch sets the variable back after each test.

    test_intake_returns_one_new_ticket_per_bullet calls intake with a run input of two bullets. It checks that intake returns a cb.RunResult with one cb.NewTicket per 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_stops checks both stops of intake: pytest.raises(cb.Stop) catches the stop, and reason holds its text.

  4. Run the tests

    Terminal window
    uv run pytest

    pytest finds the test file in tests, runs the three tests and prints 3 passed. Your platform line differs:

    Output
    ============================= test session starts ==============================
    platform darwin -- Python 3.12.13, pytest-9.2.0, pluggy-1.7.0
    rootdir: …/py-factory
    configfile: pyproject.toml
    collected 3 items
    tests/test_pipeline.py ... [100%]
    ============================== 3 passed in 0.08s ===============================
  5. Commit the tests

    A run starts at the HEAD commit of its target repository, and the tutorial’s runs use py-factory for that. Commit the tests, so that codeband run doesn’t log The repository has uncommitted changes. The run does not see them.:

    Terminal window
    git add -A
    git commit -m "Test intake with pytest"

    git prints the commit’s ID and 3 files changed: pyproject.toml, uv.lock and tests/test_pipeline.py.

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:

Terminal window
uv run pytest

The 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:

Output
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:

examples/py-factory/tests/test_ship_feature.py
import codeband as cb
import pytest
from 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.unit
def 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.unit
def 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.unit
def 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:

Terminal window
uv run pytest tests/test_ship_feature.py

pytest 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.

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.