# Testing with the tools

The tools do their I/O through four ports, so a harness that uses them can be tested without
running programs or reaching the network. `gvn_tools.fakes` has a fake for each of the three
ports that reach outside the machine; for the fourth, the workspace, a test uses a real
temporary directory.

- **You will learn:** how to script `FakeCommands` and `FakeHttp`, how to make them fail on
  purpose, how to check what your code asked them to do, and how a test of an agent refers
  to the tools it ran.
- **Read first:** [Tools](index.md), whose [first section](index.md#where-tools-plug-in) shows
  the ports.
- **Time:** about 10 minutes.

## Where the fakes sit

In the picture of [where tools plug in](index.md#where-tools-plug-in), the ports are the layer
under the tools. A **port** is the interface a tool does one kind of I/O through. A **fake**
is a stand-in for a port that answers from a script you write, so a test decides exactly what
a program printed or what a server said, and records what the tools asked for. Nothing above
the port changes: the same tools, the same policy, the same agent.

Steps 1 to 4 call the fakes directly, the way a tool would. In your tests you usually hand a
fake to a tool family instead, as the family pages do and as step 5 does under an agent.

## Step 1: script a program's results

`script` takes the argv, then the results to give, one per call, in turn. Each result is a
`Completed`: what a finished program gives back, its exit `code`, its `output` and its
`errors` (standard output and standard error). The fake is then called with the `Commands`
port's own method, `run`, with the argv, the working directory, a time limit in seconds and
the characters to keep of each stream. Here `make test` fails the first time and passes the
second:

```python
import asyncio
import pathlib

from gvn_tools.fakes import FakeCommands
from gvn_tools.process import Completed

commands = FakeCommands().script(
    ["make", "test"], Completed(code=2, errors="boom"), Completed(code=0)
)
here = pathlib.Path.cwd()


async def make_test_twice() -> None:
    first = await commands.run(argv=["make", "test"], cwd=here, timeout=60, limit=1000)
    second = await commands.run(argv=["make", "test"], cwd=here, timeout=60, limit=1000)
    print(first.code(), second.code())


asyncio.run(make_test_twice())  # 2 0
```

## Step 2: make a program time out

Script an exception instead of a result, and the fake raises it, as the real port would when
it kills a program at its time limit:

```python
from gvn_tools.process import TimedOut

commands.script(["slow"], TimedOut("killed at the timeout"))


async def run_slow() -> None:
    try:
        await commands.run(argv=["slow"], cwd=here, timeout=60, limit=1000)
    except TimedOut as error:
        print("TimedOut", error)


asyncio.run(run_slow())  # TimedOut killed at the timeout
```

## Step 3: a web server, with a default answer

`FakeHttp` works the same way, keyed by method and URL. A `default` answers everything not
scripted; here it is a 404, and one URL is scripted to be unreachable:

```python
from gvn_tools.fakes import FakeHttp
from gvn_tools.transport import Response, Unreachable

http = FakeHttp(default=Response(status=404)).script(
    "GET", "https://a.example.com/x", Unreachable("refused")
)


async def two_requests() -> None:
    missing = await http.send(
        method="GET", url="https://b.example.com/", headers={}, body=None, timeout=30, limit=1000
    )
    print(missing.status())
    try:
        await http.send(
            method="GET", url="https://a.example.com/x", headers={}, body=None, timeout=30,
            limit=1000,
        )
    except Unreachable as error:
        print("Unreachable", error)


asyncio.run(two_requests())
# 404
# Unreachable refused
```

## Step 4: check what was asked

Both fakes record every call, so a test can check what the code under test asked for, not
only what it did with the answer:

```python
print([call["argv"] for call in commands.calls()])
# [('make', 'test'), ('make', 'test'), ('slow',)]
print([request["url"] for request in http.requests()])
# ['https://b.example.com/', 'https://a.example.com/x']
```

## Step 5: an agent over the fakes, and the tools it ran

Pair the fakes with the framework's (`ScriptedModel`, `MemoryJournal`, `ManualClock`, see
[Testing your harness](../concepts/testing.md)) and a harness built on the tools runs fully
offline. A test refers to the tools the way the harness does: it builds the family over a
fake once, and passes the tool objects, picked from the family's named tuple by attribute,
wherever a tool is meant. Only the scripted model writes short names, because that is what
a model writes in its tool calls.

Here an agent, run with the [short path](../guides/shortcuts.md)'s `run_agent`, runs the
tests through the shell tool over `FakeCommands`. The test then picks the calls to
`run_command` out of the outcome's `"attempts"` with `calls_to`, which matches each entry
by its tool's identity (see [Tools](../concepts/tools.md#who-refers-to-tools-and-how)):

```python
from gvn.harness.messages import Message, ToolCall
from gvn.harness.ports import Reply
from gvn.harness.tools import calls_to
from gvn.shortcuts import run_agent
from gvn.testing.fakes import ScriptedModel
from gvn_tools import shell
from gvn_tools.workspace import Workspace

checkout = pathlib.Path("checkout")
checkout.mkdir()
commands = FakeCommands().script(["pytest", "-q"], Completed(code=0, output="3 passed\n"))
shell_tools = shell.tools(
    workspace=Workspace(root=checkout.resolve()), commands=commands, programs=["pytest"]
)
run_tests = ToolCall(call_id="c1", name="run_command", arguments={"argv": ["pytest", "-q"]})
model = ScriptedModel(
    script=[
        Reply(message=Message.assistant(calls=[run_tests])),
        Reply(message=Message.assistant(text="The tests pass.")),
    ]
)
run = asyncio.run(
    run_agent(
        "Run the tests.",
        "Do the tests pass?",
        model,
        tools=shell_tools,
        policy=shell.rules(shell_tools, quiet=["pytest"]),
    )
)
attempts = run.outcome().payload()["attempts"]
(ran,) = calls_to(attempts, shell_tools.run_command)
print(ran["identity"], ran["status"], ran["detail"]["output"])
# gvn_tools.shell.run_command ok 3 passed
```

Never compare an entry's `"name"` in a test: another package's tool may share the short
name, and only the identity tells them apart.

## The fakes, for lookup

| Fake | Stands in for | What it does |
|---|---|---|
| `FakeCommands(default=None)` | `Commands` | answers each argv with the results scripted for it, in turn (the last repeats); records every call |
| `FakeHttp(default=None)` | `Http` | answers each `(method, url)` with the responses scripted for it, in turn; records every request |
| `FakeMcpServer(tools=(), default=None)` | `McpServer` | lists the tools it `offer`s; answers each tool with the results scripted for it, in turn; records every call (see [MCP servers](mcp.md)) |

- `script(...)` takes `Completed`, `Response`, or `McpResult` instances, depending on the fake.
  Each also accepts an exception instance to raise and returns the fake so scripting chains.
- Without a `default`, anything not scripted raises `LookupError`; with one, it gets that
  result.
- `FakeCommands` and `FakeHttp` share argument validation with `LocalCommands` and
  `LocalHttp`. Their output and text are cut at the call's `limit`.
- `FakeCommands.calls()` gives each call's `argv`, `cwd`, `timeout`, `limit` and
  `environment`; `FakeHttp.requests()` each request's `method`, `url`, `headers`, `body`,
  `timeout` and `limit`. Like the `Http` port, `FakeHttp` never follows a redirect.

## How the package tests itself

The package's own tests live in `packages/gvn-tools/tests`, one file per module, and run in
the default suite: quick, parallel and hermetic.

- **Real files and real git.** The file tools run against real temporary directories, and the
  git tools against real repositories made by the real `git` binary under pytest's
  `tmp_path`, each with its own `HOME`, `GIT_CONFIG_GLOBAL=/dev/null` and
  `GIT_CONFIG_NOSYSTEM=1`, so a developer's own configuration and repositories are never
  touched. Process tests run real programs, kill real process groups and check that the
  parent's environment does not leak.
- **HTTP only through the fake port.** The web, Jira and GitHub tests script `FakeHttp`; no
  test reaches the network.
- **Property tests for confinement.** Hypothesis generates paths, including `..`, symbolic
  links, NUL bytes and arbitrary text, and checks that nothing resolves outside the
  workspace, that no read, list or search ever shows anything outside, and that no write or
  edit ever changes anything outside. The git, Jira and GitHub tests generate refs, queries
  and keys the same way, checking that no argument becomes a flag or widens a search.
- **A time budget.** As in the framework's fast tiers, a test may use at most 100 ms of this
  process's processor time (a program it runs is another process), and ten times that of wall
  time, unless marked `@pytest.mark.budget(seconds)`.
- **Live tests are opt-in.** Tests that call a real service are marked `live` and are left out
  of the default run.

```bash
uv run pytest packages/gvn-tools/tests
```

## Recap

- `FakeCommands` and `FakeHttp` answer from a script, in turn, and can raise on purpose.
- They validate arguments like the real ports and record every call for your assertions.
- With the framework's fakes, a harness built on these tools tests fully offline; a test
  passes the tool objects it built and finds a tool's calls with `calls_to`, by identity.

**Next:** put the tools to work in the [coding agent guide](../guides/coding-agent.md).
