Skip to content

Commit 953085c

Browse files
tests: add new tests (#2)
* tests: add new tests * more harnesses
1 parent 29b590d commit 953085c

13 files changed

Lines changed: 794 additions & 5 deletions
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# Runs the real Claude Code CLI through safeagents against a scripted model (tests/harnesses).
2+
# Pull requests test the Claude Code version docs/claude-code.md was checked against;
3+
# pushes to main also test the latest release, to catch Claude Code changes that break the guide.
4+
name: harness / claude-code
5+
6+
on:
7+
push:
8+
branches: [main]
9+
pull_request:
10+
11+
permissions:
12+
contents: read
13+
14+
jobs:
15+
claude-code:
16+
runs-on: ubuntu-latest
17+
timeout-minutes: 15
18+
strategy:
19+
fail-fast: false
20+
matrix:
21+
claude-code-version: ${{ fromJSON(github.event_name == 'pull_request' && '["2.1.304"]' || '["2.1.304", "latest"]') }}
22+
name: claude-code ${{ matrix.claude-code-version }}
23+
steps:
24+
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
25+
with:
26+
persist-credentials: false
27+
28+
- uses: astral-sh/setup-uv@18d369b23da25a81e9458561248e1aafff6a70fa # v10.3.1
29+
30+
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
31+
with:
32+
node-version: "22"
33+
34+
- name: Install safeagents
35+
run: uv sync --locked
36+
37+
- name: Install Claude Code ${{ matrix.claude-code-version }}
38+
run: |
39+
npm install --global --no-audit --no-fund @anthropic-ai/claude-code@${{ matrix.claude-code-version }}
40+
claude --version
41+
42+
- name: Run Claude Code through safeagents
43+
run: uv run pytest tests/harnesses/test_claude_code.py -v --durations=0
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# Runs the real DeepSeek Harness (dsh) CLI through safeagents against a scripted model
2+
# (tests/harnesses). Pull requests test the dsh version docs/deepseek-harness.md was
3+
# checked against; pushes to main also test the latest release, to catch dsh changes
4+
# that break the guide.
5+
name: harness / deepseek-harness
6+
7+
on:
8+
push:
9+
branches: [main]
10+
pull_request:
11+
12+
permissions:
13+
contents: read
14+
15+
jobs:
16+
deepseek-harness:
17+
runs-on: ubuntu-latest
18+
timeout-minutes: 15
19+
strategy:
20+
fail-fast: false
21+
matrix:
22+
dsh-version: ${{ fromJSON(github.event_name == 'pull_request' && '["0.2.1-rc.2"]' || '["0.2.1-rc.2", "latest"]') }}
23+
name: dsh ${{ matrix.dsh-version }}
24+
steps:
25+
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
26+
with:
27+
persist-credentials: false
28+
29+
- uses: astral-sh/setup-uv@18d369b23da25a81e9458561248e1aafff6a70fa # v10.3.1
30+
31+
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
32+
with:
33+
node-version: "22"
34+
35+
- name: Install safeagents
36+
run: uv sync --locked
37+
38+
- name: Install dsh ${{ matrix.dsh-version }}
39+
run: |
40+
npm install --global --no-audit --no-fund @deepseek-ai/dsh@${{ matrix.dsh-version }}
41+
dsh --version
42+
43+
- name: Run dsh through safeagents
44+
run: uv run pytest tests/harnesses/test_deepseek_harness.py -v --durations=0
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
# Runs the OpenHands Software Agent SDK through safeagents against a scripted model
2+
# (tests/harnesses). The SDK goes into its own virtualenv, not safeagents' locked one;
3+
# the test runs it through OPENHANDS_PYTHON. Pull requests test the SDK version
4+
# docs/openhands.md was checked against; pushes to main also test the latest release,
5+
# to catch SDK changes that break the guide.
6+
name: harness / openhands
7+
8+
on:
9+
push:
10+
branches: [main]
11+
pull_request:
12+
13+
permissions:
14+
contents: read
15+
16+
jobs:
17+
openhands:
18+
runs-on: ubuntu-latest
19+
timeout-minutes: 15
20+
strategy:
21+
fail-fast: false
22+
matrix:
23+
openhands-version: ${{ fromJSON(github.event_name == 'pull_request' && '["1.56.0"]' || '["1.56.0", "latest"]') }}
24+
name: openhands-sdk ${{ matrix.openhands-version }}
25+
steps:
26+
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
27+
with:
28+
persist-credentials: false
29+
30+
- uses: astral-sh/setup-uv@18d369b23da25a81e9458561248e1aafff6a70fa # v10.3.1
31+
32+
- name: Install safeagents
33+
run: uv sync --locked
34+
35+
- name: Install openhands-sdk ${{ matrix.openhands-version }}
36+
env:
37+
OPENHANDS_VERSION: ${{ matrix.openhands-version }}
38+
OPENHANDS_VENV: ${{ runner.temp }}/openhands
39+
run: |
40+
if [ "$OPENHANDS_VERSION" = latest ]; then
41+
packages="openhands-sdk openhands-tools"
42+
else
43+
packages="openhands-sdk==$OPENHANDS_VERSION openhands-tools==$OPENHANDS_VERSION"
44+
fi
45+
uv venv --python 3.12 "$OPENHANDS_VENV"
46+
uv pip install --python "$OPENHANDS_VENV/bin/python" $packages
47+
uv pip list --python "$OPENHANDS_VENV/bin/python" | grep -E '^(openhands-sdk|openhands-tools|litellm) '
48+
LITELLM_LOCAL_MODEL_COST_MAP=True OPENHANDS_SUPPRESS_BANNER=1 \
49+
"$OPENHANDS_VENV/bin/python" -c "import openhands.sdk, openhands.tools.terminal"
50+
echo "OPENHANDS_PYTHON=$OPENHANDS_VENV/bin/python" >> "$GITHUB_ENV"
51+
52+
- name: Run the OpenHands SDK through safeagents
53+
run: uv run pytest tests/harnesses/test_openhands.py -v --durations=0

‎.github/workflows/tests.yml‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# Unit tests for safeagents itself. Harness end-to-end tests live in tests/harnesses
2+
# and run in their own harness-*.yml workflows.
3+
name: tests
4+
5+
on:
6+
push:
7+
branches: [main]
8+
pull_request:
9+
10+
permissions:
11+
contents: read
12+
13+
jobs:
14+
pytest:
15+
runs-on: ubuntu-latest
16+
timeout-minutes: 10
17+
steps:
18+
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
19+
with:
20+
persist-credentials: false
21+
22+
- uses: astral-sh/setup-uv@18d369b23da25a81e9458561248e1aafff6a70fa # v10.3.1
23+
24+
- name: Install safeagents
25+
run: uv sync --locked
26+
27+
- name: Run unit tests
28+
run: uv run pytest --ignore=tests/harnesses -v

‎docs/deepseek-harness.md‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,13 @@ Start safeagents with the matching upstream (`https://api.anthropic.com` or `htt
5555

5656
## 3. Check it
5757

58-
Open a session in `dsh web` and ask it to list the files in the workspace. The safeagents terminal should show the request and a `PASS` line for the call.
58+
Run one task without the web UI:
59+
60+
```bash
61+
dsh headless "List the files in this directory"
62+
```
63+
64+
The safeagents terminal should show the request and a `PASS` line for the call. The same works from a session in `dsh web`.
5965

6066
## Notes
6167

@@ -65,6 +71,7 @@ Open a session in `dsh web` and ask it to list the files in the workspace. The s
6571
- **The `web_search` tool has its own endpoint** (`DEEPSEEK_SEARCH_BASE_URL`), so it doesn't go through the proxy. It runs server-side and returns no client tool calls, so there is nothing there for safeagents to check.
6672
- dsh adds non-standard fields to its requests (`dsh_session_log`, `dsh_plugin_packages`, mid-conversation system messages). safeagents forwards them unchanged. It also includes them in the context it searches for hosts the conversation mentions.
6773
- dsh requests are always streamed and refuse redirects. safeagents doesn't redirect, so this needs nothing from you.
74+
- dsh sends telemetry to its own collector, by default only when you submit feedback. `DSH_TELEMETRY_DISABLED=1` turns it off.
6875

6976
## Sources
7077

‎src/safeagents/rewrite.py‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -180,10 +180,13 @@ async def event(self, event: object, raw: bytes) -> Out:
180180
async def _release_block(self, held: _HeldBlock) -> list[bytes | dict]:
181181
if await self._allow(held.name, held.input):
182182
return list(held.raw)
183-
# Keep the block index so the stream's block numbering stays intact.
184-
text_block = {"type": "text", "text": self.guard.flagged[-1].notice()}
183+
# Keep the block index so the stream's block numbering stays intact. The notice
184+
# goes in a delta: clients such as Claude Code build text only from deltas.
185+
text_block = {"type": "text", "text": ""}
186+
text_delta = {"type": "text_delta", "text": self.guard.flagged[-1].notice()}
185187
return [
186188
{"type": "content_block_start", "index": held.index, "content_block": text_block},
189+
{"type": "content_block_delta", "index": held.index, "delta": text_delta},
187190
{"type": "content_block_stop", "index": held.index},
188191
]
189192

‎tests/harnesses/fake_model.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,15 +44,15 @@
4444
"clean": f"echo {CLEAN_OUTPUT}",
4545
}
4646
FINAL_TEXT = "Done."
47-
_MARKER = re.compile(r"^(SCENARIO|TOOL|ARG|EXTRA)=(\S+)", re.MULTILINE)
47+
_MARKER = re.compile(r"^(SCENARIO|TOOL|ARG|EXTRA)=(.+?)\s*$", re.MULTILINE)
4848
_MODEL_INFO = {"id": "fake-model", "object": "model", "created": 0, "owned_by": "fake", "type": "model"}
4949

5050

5151
def scenario_prompt(scenario: str, tool: str = "bash", arg: str = "command", extra: dict | None = None) -> str:
5252
"""The prompt a test gives the harness, telling the fake model which call to make."""
5353
lines = ["Run the scripted step.", f"SCENARIO={scenario}", f"TOOL={tool}", f"ARG={arg}"]
5454
if extra:
55-
lines.append("EXTRA=" + json.dumps(extra, separators=(",", ":")))
55+
lines.append("EXTRA=" + json.dumps(extra))
5656
return "\n".join(lines)
5757

5858

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
# Copyright 2026-present the HuggingFace Inc. team.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
"""Runs the real Claude Code CLI through safeagents, set up as in docs/claude-code.md.
15+
16+
Skipped unless `claude` is installed (or `CLAUDE_BIN` points at it).
17+
"""
18+
19+
from __future__ import annotations
20+
21+
import os
22+
import shutil
23+
import subprocess
24+
from pathlib import Path
25+
26+
import pytest
27+
from fake_model import FakeModel, scenario_prompt
28+
from stack import BLOCKED_SCENARIOS, check_blocked, check_ran, running_proxy
29+
30+
CLAUDE_BIN = os.environ.get("CLAUDE_BIN") or shutil.which("claude")
31+
pytestmark = pytest.mark.skipif(CLAUDE_BIN is None, reason="Claude Code is not installed")
32+
33+
SHELL_TOOL = "Bash"
34+
# Variables from the calling shell that would change which account, endpoint or
35+
# settings Claude Code uses.
36+
INHERITED_PREFIXES = ("ANTHROPIC_", "CLAUDE")
37+
38+
39+
@pytest.fixture(scope="module")
40+
def stack(tmp_path_factory):
41+
with FakeModel() as model, running_proxy(model.url, tmp_path_factory.mktemp("proxy")) as proxy:
42+
yield model, proxy
43+
44+
45+
@pytest.fixture
46+
def claude_home(tmp_path) -> Path:
47+
"""An empty home directory, so no user settings, logins or CLAUDE.md files apply."""
48+
home = tmp_path / "home"
49+
home.mkdir()
50+
return home
51+
52+
53+
def run_claude(claude_home: Path, workdir: Path, base_url: str, scenario: str) -> str:
54+
"""Runs one headless Claude Code prompt and returns its JSON event stream."""
55+
env = {}
56+
for name, value in os.environ.items():
57+
if not name.startswith(INHERITED_PREFIXES):
58+
env[name] = value
59+
env.update(
60+
{
61+
"HOME": str(claude_home),
62+
"CLAUDE_CONFIG_DIR": str(claude_home / ".claude"),
63+
# As in docs/claude-code.md: the proxy URL, without /v1.
64+
"ANTHROPIC_BASE_URL": base_url,
65+
"ANTHROPIC_API_KEY": "test-key",
66+
"CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1",
67+
"DISABLE_AUTOUPDATER": "1",
68+
}
69+
)
70+
# The prompt comes first: `--tools` and `--allowedTools` take every value after them.
71+
command = [
72+
CLAUDE_BIN,
73+
"--print",
74+
scenario_prompt(scenario, tool=SHELL_TOOL),
75+
"--output-format",
76+
"stream-json",
77+
"--verbose",
78+
"--no-session-persistence",
79+
"--tools",
80+
SHELL_TOOL,
81+
"--allowedTools",
82+
SHELL_TOOL,
83+
]
84+
completed = subprocess.run(
85+
command,
86+
cwd=workdir,
87+
env=env,
88+
stdin=subprocess.DEVNULL,
89+
capture_output=True,
90+
text=True,
91+
timeout=120,
92+
check=False,
93+
)
94+
assert completed.returncode == 0, f"Claude Code failed:\n{completed.stderr}"
95+
return completed.stdout
96+
97+
98+
@pytest.mark.parametrize(("scenario", "reason"), BLOCKED_SCENARIOS)
99+
def test_flagged_call_is_blocked(stack, claude_home, tmp_path, scenario, reason):
100+
model, proxy = stack
101+
model.requests.clear()
102+
output = run_claude(claude_home, tmp_path, proxy.url, scenario)
103+
check_blocked(model, proxy, output, scenario, SHELL_TOOL, reason)
104+
105+
106+
def test_clean_call_runs(stack, claude_home, tmp_path):
107+
model, proxy = stack
108+
model.requests.clear()
109+
output = run_claude(claude_home, tmp_path, proxy.url, "clean")
110+
check_ran(model, output)

0 commit comments

Comments
 (0)