agentforge-testing 0.2.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,49 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.so
6
+
7
+ # Distribution / packaging
8
+ .Python
9
+ build/
10
+ dist/
11
+ *.egg-info/
12
+ *.egg
13
+ wheels/
14
+ sdist/
15
+ share/python-wheels/
16
+
17
+ # uv
18
+ .venv/
19
+ uv-cache/
20
+
21
+ # Testing
22
+ .pytest_cache/
23
+ .coverage
24
+ .coverage.*
25
+ htmlcov/
26
+ coverage.xml
27
+ .tox/
28
+ .mypy_cache/
29
+ .ruff_cache/
30
+ .hypothesis/
31
+
32
+ # Environment
33
+ .env
34
+ .envrc
35
+
36
+ # Editors
37
+ .vscode/
38
+ .idea/
39
+ *.swp
40
+ *.swo
41
+ *~
42
+
43
+ # OS
44
+ .DS_Store
45
+ Thumbs.db
46
+
47
+ # Project-local
48
+ *.local
49
+ .agentforge-state/.session-cache
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,48 @@
1
+ Metadata-Version: 2.4
2
+ Name: agentforge-testing
3
+ Version: 0.2.1
4
+ Summary: Richer test helpers for AgentForge (golden-set runner, snapshot, recording analysis)
5
+ Project-URL: Homepage, https://github.com/Scaffoldic/agentforge-py
6
+ Project-URL: Repository, https://github.com/Scaffoldic/agentforge-py
7
+ Project-URL: Documentation, https://github.com/Scaffoldic/agentforge-py
8
+ Project-URL: Changelog, https://github.com/Scaffoldic/agentforge-py/blob/main/CHANGELOG.md
9
+ Project-URL: Issues, https://github.com/Scaffoldic/agentforge-py/issues
10
+ Author: The AgentForge Authors
11
+ License-Expression: Apache-2.0
12
+ License-File: LICENSE
13
+ Keywords: agent,ai,framework,golden,snapshot,testing
14
+ Classifier: Development Status :: 2 - Pre-Alpha
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: License :: OSI Approved :: Apache Software License
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
20
+ Classifier: Topic :: Software Development :: Testing
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.13
23
+ Requires-Dist: agentforge-core~=0.2.1
24
+ Requires-Dist: agentforge-py~=0.2.1
25
+ Description-Content-Type: text/markdown
26
+
27
+ # agentforge-testing
28
+
29
+ Richer test helpers for AgentForge agents. Pip-installable
30
+ separately so the dependency doesn't land in production.
31
+
32
+ The lighter built-in surface — `MockLLMClient`, `FakeTool`,
33
+ `agent_factory`, conformance harnesses, `record_llm` /
34
+ `MockLLMClient.from_recording` — ships inside the `agentforge`
35
+ runtime package at `agentforge.testing`. Install **this** package
36
+ when you want, additionally:
37
+
38
+ - `GoldenSetRunner` — load JSONL fixtures, run an agent, compare
39
+ output via structural diff with allow-listed wildcards.
40
+ - `assert_snapshot(actual, path)` — Approval-style snapshot file
41
+ helper with `UPDATE_SNAPSHOTS=1` re-record.
42
+ - `analyze_recording(path)` — stats about a captured cassette
43
+ (call count, token totals, distinct tool calls, per-step
44
+ latency distribution).
45
+
46
+ ```bash
47
+ uv add --dev agentforge-testing
48
+ ```
@@ -0,0 +1,22 @@
1
+ # agentforge-testing
2
+
3
+ Richer test helpers for AgentForge agents. Pip-installable
4
+ separately so the dependency doesn't land in production.
5
+
6
+ The lighter built-in surface — `MockLLMClient`, `FakeTool`,
7
+ `agent_factory`, conformance harnesses, `record_llm` /
8
+ `MockLLMClient.from_recording` — ships inside the `agentforge`
9
+ runtime package at `agentforge.testing`. Install **this** package
10
+ when you want, additionally:
11
+
12
+ - `GoldenSetRunner` — load JSONL fixtures, run an agent, compare
13
+ output via structural diff with allow-listed wildcards.
14
+ - `assert_snapshot(actual, path)` — Approval-style snapshot file
15
+ helper with `UPDATE_SNAPSHOTS=1` re-record.
16
+ - `analyze_recording(path)` — stats about a captured cassette
17
+ (call count, token totals, distinct tool calls, per-step
18
+ latency distribution).
19
+
20
+ ```bash
21
+ uv add --dev agentforge-testing
22
+ ```
@@ -0,0 +1,61 @@
1
+ # agentforge-testing — richer test helpers for AgentForge agents.
2
+ #
3
+ # Tier-3 sister package to `agentforge` (Tier 2). Pip-installable
4
+ # separately for teams that want golden-set runners, snapshot
5
+ # helpers, and recording analysis without dragging the dependency
6
+ # into production. The lighter built-in surface ships inside
7
+ # `agentforge` itself at `agentforge.testing` (feat-016 chunks 1-3).
8
+
9
+ [project]
10
+ name = "agentforge-testing"
11
+ version = "0.2.1"
12
+ description = "Richer test helpers for AgentForge (golden-set runner, snapshot, recording analysis)"
13
+ readme = "README.md"
14
+ requires-python = ">=3.13"
15
+ license = "Apache-2.0"
16
+ license-files = ["LICENSE"]
17
+ authors = [
18
+ {name = "The AgentForge Authors"},
19
+ ]
20
+ keywords = ["ai", "agent", "testing", "snapshot", "golden", "framework"]
21
+ classifiers = [
22
+ "Development Status :: 2 - Pre-Alpha",
23
+ "Intended Audience :: Developers",
24
+ "License :: OSI Approved :: Apache Software License",
25
+ "Programming Language :: Python :: 3",
26
+ "Programming Language :: Python :: 3.13",
27
+ "Topic :: Software Development :: Libraries :: Python Modules",
28
+ "Topic :: Software Development :: Testing",
29
+ "Typing :: Typed",
30
+ ]
31
+
32
+ dependencies = [
33
+ "agentforge-core ~= 0.2.1",
34
+ "agentforge-py ~= 0.2.1",
35
+ ]
36
+
37
+ [project.urls]
38
+ Homepage = "https://github.com/Scaffoldic/agentforge-py"
39
+ Repository = "https://github.com/Scaffoldic/agentforge-py"
40
+ Documentation = "https://github.com/Scaffoldic/agentforge-py"
41
+ Changelog = "https://github.com/Scaffoldic/agentforge-py/blob/main/CHANGELOG.md"
42
+ Issues = "https://github.com/Scaffoldic/agentforge-py/issues"
43
+
44
+ [tool.uv.sources]
45
+ agentforge-core = { workspace = true }
46
+ agentforge = { workspace = true }
47
+
48
+ [build-system]
49
+ requires = ["hatchling>=1.27"]
50
+ build-backend = "hatchling.build"
51
+
52
+ [tool.hatch.build.targets.wheel]
53
+ packages = ["src/agentforge_testing"]
54
+
55
+ [tool.hatch.build.targets.sdist]
56
+ include = [
57
+ "src/agentforge_testing",
58
+ "tests",
59
+ "README.md",
60
+ "LICENSE",
61
+ ]
@@ -0,0 +1,39 @@
1
+ """`agentforge-testing` — richer test helpers (feat-016).
2
+
3
+ Pip-install:: `agentforge-testing` adds opt-in helpers that the
4
+ runtime `agentforge.testing` namespace doesn't pull in by default:
5
+
6
+ - `GoldenSetRunner.from_jsonl(...).run(agent_factory)` — load a
7
+ JSONL fixture file, run the agent against every entry, compare
8
+ the resulting outputs via structural diff. Exit non-zero on the
9
+ first mismatch (or aggregate, depending on `mode`).
10
+ - `assert_snapshot(actual, path)` — Approval-style file snapshot.
11
+ Pass `UPDATE_SNAPSHOTS=1` to re-record.
12
+ - `analyze_recording(path)` — quick stats about a cassette
13
+ produced by `agentforge.testing.record_llm`.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from agentforge_testing.analysis import RecordingStats, analyze_recording
19
+ from agentforge_testing.golden import (
20
+ GoldenFixture,
21
+ GoldenMismatch,
22
+ GoldenResult,
23
+ GoldenSetRunner,
24
+ )
25
+ from agentforge_testing.snapshot import (
26
+ SnapshotMismatch,
27
+ assert_snapshot,
28
+ )
29
+
30
+ __all__ = [
31
+ "GoldenFixture",
32
+ "GoldenMismatch",
33
+ "GoldenResult",
34
+ "GoldenSetRunner",
35
+ "RecordingStats",
36
+ "SnapshotMismatch",
37
+ "analyze_recording",
38
+ "assert_snapshot",
39
+ ]
@@ -0,0 +1,60 @@
1
+ """Cassette analysis helpers (feat-016 chunk 4).
2
+
3
+ `analyze_recording(path)` returns a `RecordingStats` summary about
4
+ a JSONL cassette produced by `agentforge.testing.record_llm`:
5
+
6
+ - total call count
7
+ - input + output token totals
8
+ - distinct tool calls observed
9
+ - per-call cost summary
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from dataclasses import dataclass, field
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ from agentforge.testing.recording import load_recording
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class RecordingStats:
23
+ """Summary of a captured LLM transcript."""
24
+
25
+ call_count: int
26
+ tokens_in: int
27
+ tokens_out: int
28
+ cost_usd: float
29
+ tool_call_names: dict[str, int]
30
+ redactions: list[str] = field(default_factory=list)
31
+ format_version: int = 1
32
+
33
+
34
+ def analyze_recording(path: str | Path) -> RecordingStats:
35
+ """Walk a cassette once and produce a `RecordingStats`."""
36
+ header, entries = load_recording(path)
37
+ tokens_in = 0
38
+ tokens_out = 0
39
+ cost = 0.0
40
+ tool_calls: dict[str, int] = {}
41
+ for entry in entries:
42
+ response: dict[str, Any] = entry["response"]
43
+ usage = response.get("usage") or {}
44
+ tokens_in += int(usage.get("input_tokens", 0))
45
+ tokens_out += int(usage.get("output_tokens", 0))
46
+ cost += float(response.get("cost_usd", 0.0))
47
+ for tc in response.get("tool_calls", []) or []:
48
+ tool_calls[tc["name"]] = tool_calls.get(tc["name"], 0) + 1
49
+ return RecordingStats(
50
+ call_count=len(entries),
51
+ tokens_in=tokens_in,
52
+ tokens_out=tokens_out,
53
+ cost_usd=cost,
54
+ tool_call_names=tool_calls,
55
+ redactions=list(header.get("redactions", [])),
56
+ format_version=int(header.get("format_version", 1)),
57
+ )
58
+
59
+
60
+ __all__ = ["RecordingStats", "analyze_recording"]
@@ -0,0 +1,155 @@
1
+ """Golden-set runner for agents (feat-016 chunk 4).
2
+
3
+ Runs an agent against a fixture file (JSONL) and compares the
4
+ output to a recorded golden. Mismatches surface as `GoldenMismatch`
5
+ exceptions so test runners (pytest etc) see them as test failures.
6
+
7
+ Fixture line shape::
8
+
9
+ {
10
+ "task": "What is the capital of France?",
11
+ "expected": "Paris", // exact match
12
+ "metadata": {...} // pass-through
13
+ }
14
+
15
+ For looser matches, use:
16
+
17
+ - `expected: {"contains": "Paris"}` — substring assertion
18
+ - `expected: {"regex": "^Paris.*"}` — regex (re.search)
19
+ - `expected: {"any_of": ["Paris", "paris"]}` — case-insensitive
20
+ membership
21
+
22
+ The runner is intentionally minimal — a structural-diff harness
23
+ deferred to follow-up sub-features that consume specific finding
24
+ shapes.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import json
30
+ import re
31
+ from collections.abc import Awaitable, Callable
32
+ from dataclasses import dataclass, field
33
+ from pathlib import Path
34
+ from typing import Any
35
+
36
+ from agentforge.agent import Agent
37
+
38
+
39
+ @dataclass(frozen=True)
40
+ class GoldenFixture:
41
+ """A single fixture line loaded from a JSONL file."""
42
+
43
+ task: str
44
+ expected: str | dict[str, Any] | None = None
45
+ metadata: dict[str, Any] = field(default_factory=dict)
46
+
47
+
48
+ @dataclass(frozen=True)
49
+ class GoldenResult:
50
+ """The outcome of running an agent against one fixture."""
51
+
52
+ fixture: GoldenFixture
53
+ output: str | dict[str, Any]
54
+ passed: bool
55
+ detail: str | None = None
56
+
57
+
58
+ class GoldenMismatch(AssertionError): # noqa: N818 — mirrors pytest's AssertionError shape
59
+ """Raised when a fixture's expected value doesn't match the
60
+ agent's output. Inherits AssertionError so pytest surfaces it
61
+ naturally."""
62
+
63
+
64
+ class GoldenSetRunner:
65
+ """Drive an agent through every fixture in a JSONL file."""
66
+
67
+ def __init__(self, fixtures: list[GoldenFixture]) -> None:
68
+ self._fixtures = list(fixtures)
69
+
70
+ @classmethod
71
+ def from_jsonl(cls, path: str | Path) -> GoldenSetRunner:
72
+ """Load a `.jsonl` of fixtures."""
73
+ raw = Path(path).read_text(encoding="utf-8").splitlines()
74
+ fixtures: list[GoldenFixture] = []
75
+ for line in raw:
76
+ stripped = line.strip()
77
+ if not stripped:
78
+ continue
79
+ obj = json.loads(stripped)
80
+ fixtures.append(
81
+ GoldenFixture(
82
+ task=obj["task"],
83
+ expected=obj.get("expected"),
84
+ metadata=obj.get("metadata", {}),
85
+ )
86
+ )
87
+ return cls(fixtures)
88
+
89
+ async def run(
90
+ self,
91
+ agent_factory: Callable[[], Agent | Awaitable[Agent]],
92
+ *,
93
+ mode: str = "aggregate",
94
+ ) -> list[GoldenResult]:
95
+ """Run every fixture; return one `GoldenResult` per fixture.
96
+
97
+ `mode="aggregate"` (default) returns every result; the
98
+ caller decides what to do with failures. `mode="fail-fast"`
99
+ raises `GoldenMismatch` on the first failure.
100
+ """
101
+ results: list[GoldenResult] = []
102
+ for fixture in self._fixtures:
103
+ built = agent_factory()
104
+ agent = await built if hasattr(built, "__await__") else built
105
+ run_result = await agent.run(fixture.task)
106
+ passed, detail = _check(fixture.expected, run_result.output)
107
+ results.append(
108
+ GoldenResult(
109
+ fixture=fixture,
110
+ output=run_result.output,
111
+ passed=passed,
112
+ detail=detail,
113
+ )
114
+ )
115
+ if not passed and mode == "fail-fast":
116
+ msg = (
117
+ f"golden mismatch on task={fixture.task!r}: {detail}. "
118
+ f"Got: {run_result.output!r}"
119
+ )
120
+ raise GoldenMismatch(msg)
121
+ return results
122
+
123
+
124
+ def _check(
125
+ expected: str | dict[str, Any] | None,
126
+ actual: str | dict[str, Any],
127
+ ) -> tuple[bool, str | None]:
128
+ """Compare `expected` against `actual`; return (passed, detail)."""
129
+ if expected is None:
130
+ return True, None
131
+ actual_str = actual if isinstance(actual, str) else json.dumps(actual, sort_keys=True)
132
+ if isinstance(expected, str):
133
+ return (expected == actual_str, None if expected == actual_str else "exact mismatch")
134
+ if isinstance(expected, dict):
135
+ if "contains" in expected:
136
+ sub = expected["contains"]
137
+ return (sub in actual_str, None if sub in actual_str else f"missing substring {sub!r}")
138
+ if "regex" in expected:
139
+ pat = re.compile(expected["regex"])
140
+ matched = pat.search(actual_str) is not None
141
+ return (matched, None if matched else f"regex {expected['regex']!r} did not match")
142
+ if "any_of" in expected:
143
+ choices = [s.lower() for s in expected["any_of"]]
144
+ ok = actual_str.lower() in choices
145
+ return (ok, None if ok else f"value not in any_of={choices}")
146
+ msg = f"unsupported expected shape: {expected!r}"
147
+ raise ValueError(msg)
148
+
149
+
150
+ __all__ = [
151
+ "GoldenFixture",
152
+ "GoldenMismatch",
153
+ "GoldenResult",
154
+ "GoldenSetRunner",
155
+ ]
@@ -0,0 +1,64 @@
1
+ """Approval-style snapshot helper (feat-016 chunk 4).
2
+
3
+ ::
4
+
5
+ from agentforge_testing import assert_snapshot
6
+
7
+
8
+ def test_render() -> None:
9
+ actual = render_my_thing()
10
+ assert_snapshot(actual, "tests/__snapshots__/render.txt")
11
+
12
+ When the snapshot file does not exist, it is created with the
13
+ current value and the test passes. Subsequent runs compare
14
+ byte-for-byte. Pass `UPDATE_SNAPSHOTS=1` in the environment to
15
+ re-record all snapshots without modifying tests.
16
+
17
+ Mismatches surface as `SnapshotMismatch` (an `AssertionError`
18
+ subclass) so pytest reports them naturally.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import difflib
24
+ import os
25
+ from pathlib import Path
26
+
27
+
28
+ class SnapshotMismatch(AssertionError): # noqa: N818 — AssertionError subclass for pytest reporting
29
+ """The actual value does not match the recorded snapshot."""
30
+
31
+
32
+ def assert_snapshot(
33
+ actual: str,
34
+ path: str | Path,
35
+ *,
36
+ update_env: str = "UPDATE_SNAPSHOTS",
37
+ ) -> None:
38
+ """Compare `actual` to the contents of `path`.
39
+
40
+ On first run (file missing) or when the env var named by
41
+ `update_env` is truthy, write `actual` to `path` and return
42
+ without raising.
43
+ """
44
+ snapshot = Path(path)
45
+ if os.environ.get(update_env) or not snapshot.exists():
46
+ snapshot.parent.mkdir(parents=True, exist_ok=True)
47
+ snapshot.write_text(actual, encoding="utf-8")
48
+ return
49
+ expected = snapshot.read_text(encoding="utf-8")
50
+ if expected != actual:
51
+ diff = "\n".join(
52
+ difflib.unified_diff(
53
+ expected.splitlines(),
54
+ actual.splitlines(),
55
+ fromfile=str(snapshot),
56
+ tofile="actual",
57
+ lineterm="",
58
+ )
59
+ )
60
+ msg = f"snapshot mismatch:\n{diff}"
61
+ raise SnapshotMismatch(msg)
62
+
63
+
64
+ __all__ = ["SnapshotMismatch", "assert_snapshot"]
@@ -0,0 +1,41 @@
1
+ """Tests for `analyze_recording` (feat-016 chunk 4)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ import pytest
8
+ from agentforge.testing import MockLLMClient, record_llm
9
+ from agentforge_testing.analysis import analyze_recording
10
+
11
+
12
+ @pytest.mark.asyncio
13
+ async def test_analyze_recording_aggregates_stats(tmp_path: Path) -> None:
14
+ real = MockLLMClient.from_script(
15
+ [
16
+ {
17
+ "text": "first",
18
+ "tool_calls": [{"name": "search", "args": {"q": "x"}}],
19
+ "usage": {"input_tokens": 10, "output_tokens": 5},
20
+ "cost_usd": 0.001,
21
+ },
22
+ {
23
+ "text": "second",
24
+ "usage": {"input_tokens": 8, "output_tokens": 3},
25
+ "cost_usd": 0.0005,
26
+ "stop_reason": "end_turn",
27
+ },
28
+ ]
29
+ )
30
+ cassette = tmp_path / "cassette.jsonl"
31
+ wrapped = record_llm(real, cassette)
32
+ await wrapped.call(system="", messages=[])
33
+ await wrapped.call(system="", messages=[])
34
+
35
+ stats = analyze_recording(cassette)
36
+ assert stats.call_count == 2
37
+ assert stats.tokens_in == 18
38
+ assert stats.tokens_out == 8
39
+ assert stats.cost_usd == pytest.approx(0.0015)
40
+ assert stats.tool_call_names == {"search": 1}
41
+ assert "api_key" in stats.redactions
@@ -0,0 +1,83 @@
1
+ """Tests for `GoldenSetRunner` (feat-016 chunk 4)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from pathlib import Path
7
+
8
+ import pytest
9
+ from agentforge.testing import MockLLMClient, agent_factory
10
+ from agentforge_testing.golden import (
11
+ GoldenFixture,
12
+ GoldenMismatch,
13
+ GoldenSetRunner,
14
+ )
15
+
16
+
17
+ def _write_fixtures(tmp_path: Path, fixtures: list[dict[str, object]]) -> Path:
18
+ p = tmp_path / "fixtures.jsonl"
19
+ p.write_text("\n".join(json.dumps(f) for f in fixtures), encoding="utf-8")
20
+ return p
21
+
22
+
23
+ def _factory(text: str):
24
+ def _build():
25
+ return agent_factory(model=MockLLMClient.deterministic(text))
26
+
27
+ return _build
28
+
29
+
30
+ @pytest.mark.asyncio
31
+ async def test_exact_match_pass(tmp_path: Path) -> None:
32
+ fixtures = _write_fixtures(tmp_path, [{"task": "x", "expected": "yes"}])
33
+ runner = GoldenSetRunner.from_jsonl(fixtures)
34
+ [result] = await runner.run(_factory("yes"))
35
+ assert result.passed
36
+
37
+
38
+ @pytest.mark.asyncio
39
+ async def test_exact_match_fail(tmp_path: Path) -> None:
40
+ fixtures = _write_fixtures(tmp_path, [{"task": "x", "expected": "yes"}])
41
+ runner = GoldenSetRunner.from_jsonl(fixtures)
42
+ [result] = await runner.run(_factory("no"))
43
+ assert not result.passed
44
+
45
+
46
+ @pytest.mark.asyncio
47
+ async def test_contains_matcher(tmp_path: Path) -> None:
48
+ fixtures = _write_fixtures(tmp_path, [{"task": "x", "expected": {"contains": "rain"}}])
49
+ runner = GoldenSetRunner.from_jsonl(fixtures)
50
+ [hit] = await runner.run(_factory("expect rain shortly"))
51
+ [miss] = await runner.run(_factory("sunny"))
52
+ assert hit.passed
53
+ assert not miss.passed
54
+
55
+
56
+ @pytest.mark.asyncio
57
+ async def test_regex_matcher(tmp_path: Path) -> None:
58
+ fixtures = _write_fixtures(tmp_path, [{"task": "x", "expected": {"regex": "^Paris"}}])
59
+ runner = GoldenSetRunner.from_jsonl(fixtures)
60
+ [result] = await runner.run(_factory("Paris is the capital."))
61
+ assert result.passed
62
+
63
+
64
+ @pytest.mark.asyncio
65
+ async def test_fail_fast_raises(tmp_path: Path) -> None:
66
+ fixtures = _write_fixtures(
67
+ tmp_path,
68
+ [
69
+ {"task": "x", "expected": "ok"},
70
+ {"task": "y", "expected": "ok"},
71
+ ],
72
+ )
73
+ runner = GoldenSetRunner.from_jsonl(fixtures)
74
+ with pytest.raises(GoldenMismatch):
75
+ await runner.run(_factory("no"), mode="fail-fast")
76
+
77
+
78
+ @pytest.mark.asyncio
79
+ async def test_no_expected_passes_through() -> None:
80
+ runner = GoldenSetRunner([GoldenFixture(task="x")])
81
+ [result] = await runner.run(_factory("anything"))
82
+ assert result.passed
83
+ assert result.detail is None
@@ -0,0 +1,35 @@
1
+ """Tests for `assert_snapshot` (feat-016 chunk 4)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ import pytest
8
+ from agentforge_testing.snapshot import SnapshotMismatch, assert_snapshot
9
+
10
+
11
+ def test_first_run_creates_snapshot(tmp_path: Path) -> None:
12
+ target = tmp_path / "snap.txt"
13
+ assert_snapshot("hello world", target)
14
+ assert target.read_text(encoding="utf-8") == "hello world"
15
+
16
+
17
+ def test_second_run_passes_when_match(tmp_path: Path) -> None:
18
+ target = tmp_path / "snap.txt"
19
+ target.write_text("hello", encoding="utf-8")
20
+ assert_snapshot("hello", target) # no raise
21
+
22
+
23
+ def test_mismatch_raises_with_diff(tmp_path: Path) -> None:
24
+ target = tmp_path / "snap.txt"
25
+ target.write_text("hello", encoding="utf-8")
26
+ with pytest.raises(SnapshotMismatch, match="snapshot mismatch"):
27
+ assert_snapshot("world", target)
28
+
29
+
30
+ def test_update_env_overwrites(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
31
+ target = tmp_path / "snap.txt"
32
+ target.write_text("old", encoding="utf-8")
33
+ monkeypatch.setenv("UPDATE_SNAPSHOTS", "1")
34
+ assert_snapshot("new", target)
35
+ assert target.read_text(encoding="utf-8") == "new"