gvn-tools 0.1.0__py3-none-any.whl

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.
gvn_tools/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """gvn_tools: ready-made tools for gvn harnesses, each with its safety rules."""
gvn_tools/fakes.py ADDED
@@ -0,0 +1,302 @@
1
+ """gvn_tools.fakes: in-memory ports for tests. See the tools contract.
2
+
3
+ ``FakeCommands`` (scripted results per argv, records calls) stands in for
4
+ ``gvn_tools.process.Commands``; ``FakeHttp`` for ``gvn_tools.transport.Http``;
5
+ ``FakeMcpServer`` (a scripted tool listing, scripted results per tool, records calls) for
6
+ ``gvn_tools.protocol.McpServer``.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import copy
12
+ import pathlib
13
+ import typing
14
+
15
+ from gvn_tools.process import Commands, Completed, check_run
16
+ from gvn_tools.protocol import McpResult, McpServer, ToolListing, check_call
17
+ from gvn_tools.transport import Http, Response, check_request
18
+
19
+ if typing.TYPE_CHECKING:
20
+ from collections.abc import Iterable, Mapping, Sequence
21
+
22
+ # --------------------------------------------------------------------------- FakeCommands
23
+
24
+
25
+ class FakeCommands(Commands):
26
+ """A Commands that runs nothing: it answers each argv with what was scripted for it.
27
+
28
+ fake = FakeCommands() # unscripted argv -> LookupError
29
+ fake = FakeCommands(default=Completed(0)) # unscripted argv -> that result
30
+ fake.script(["git", "status"], Completed(0, "clean\\n"))
31
+ fake.script(["make"], Completed(2, errors="boom"), Completed(0)) # in turn
32
+ fake.script(["slow"], TimedOut("killed")) # an exception instance is raised
33
+ await fake.run(["git", "status"], path, 60, 20000)
34
+ fake.calls() # [{"argv": (...), "cwd": Path, "timeout", "limit", "environment"}]
35
+
36
+ ``run`` validates its arguments exactly as ``LocalCommands`` does (TypeError/ValueError)
37
+ and records every valid call, including those that end in a scripted exception. The
38
+ results scripted for one argv are given in turn; the last one repeats. A scripted
39
+ Completed's output and errors are cut at the ``limit`` of the call, as a real run would
40
+ be (``truncated()`` then True). Not safe for use from several threads.
41
+ """
42
+
43
+ def __init__(self, default: Completed | None = None) -> None:
44
+ """``default``: the Completed for an argv nothing was scripted for, or None to raise
45
+ LookupError for it. TypeError otherwise."""
46
+ if default is not None and not isinstance(default, Completed):
47
+ raise TypeError(f"default must be a Completed or None, got {type(default).__name__}")
48
+ self._default = default
49
+ self._scripts = {}
50
+ self._calls = []
51
+
52
+ def script(self, argv: Sequence[str], *results: Completed | BaseException) -> typing.Self:
53
+ """Answer ``argv`` (a list or tuple of str) with ``results`` in turn, the last
54
+ repeating. Each is a Completed or an exception instance to raise. Replaces anything
55
+ scripted for that argv before. Returns this fake. TypeError/ValueError."""
56
+ key, _, _, _, _ = check_run(argv, pathlib.Path("/"), 1, 0)
57
+ if not results:
58
+ raise ValueError("script at least one result")
59
+ for result in results:
60
+ if not isinstance(result, (Completed, BaseException)):
61
+ raise TypeError(
62
+ f"a scripted result is a Completed or an exception, got {type(result).__name__}"
63
+ )
64
+ self._scripts[key] = list(results)
65
+ return self
66
+
67
+ def calls(self) -> list[dict[str, typing.Any]]:
68
+ """A fresh list of every call made, oldest first: dicts with ``argv`` (tuple),
69
+ ``cwd`` (Path), ``timeout``, ``limit`` and ``environment`` (a dict, {} for None)."""
70
+ return [dict(call, environment=dict(call["environment"])) for call in self._calls]
71
+
72
+ async def run(
73
+ self,
74
+ argv: Sequence[str],
75
+ cwd: pathlib.Path,
76
+ timeout: float,
77
+ limit: int,
78
+ environment: Mapping[str, str] | None = None,
79
+ ) -> Completed:
80
+ argv, cwd, timeout, limit, extra = check_run(argv, cwd, timeout, limit, environment)
81
+ self._calls.append(
82
+ {"argv": argv, "cwd": cwd, "timeout": timeout, "limit": limit, "environment": extra}
83
+ )
84
+ queue = self._scripts.get(argv)
85
+ if queue is None:
86
+ if self._default is None:
87
+ raise LookupError(f"FakeCommands has nothing scripted for {list(argv)!r}")
88
+ result = self._default
89
+ else:
90
+ result = queue.pop(0) if len(queue) > 1 else queue[0]
91
+ if isinstance(result, BaseException):
92
+ raise result
93
+ output, errors = result.output(), result.errors()
94
+ if len(output) <= limit and len(errors) <= limit:
95
+ return result
96
+ return Completed(result.code(), output[:limit], errors[:limit], True)
97
+
98
+ def __repr__(self) -> str:
99
+ return f"FakeCommands(scripted={len(self._scripts)}, calls={len(self._calls)})"
100
+
101
+
102
+ # --------------------------------------------------------------------------- FakeHttp
103
+
104
+
105
+ class FakeHttp(Http):
106
+ """An Http that sends nothing: it answers each (method, url) with what was scripted.
107
+
108
+ fake = FakeHttp() # unscripted request -> LookupError
109
+ fake = FakeHttp(default=Response(404)) # unscripted request -> that response
110
+ fake.script("GET", "https://api.example.com/x", Response(200, text="hi"))
111
+ fake.script("POST", url, Response(500), Response(201)) # in turn
112
+ fake.script("GET", url, Unreachable("refused")) # raised when asked
113
+ await fake.send("GET", url, {}, None, 30, 100000)
114
+ fake.requests() # [{"method", "url", "headers", "body", "timeout", "limit"}]
115
+
116
+ ``method`` and ``url`` are matched exactly (the method upper-cased, the URL as a str,
117
+ query and all). ``send`` validates its arguments as ``LocalHttp`` does
118
+ (TypeError/ValueError) and records every valid request, including those answered with
119
+ a scripted exception or LookupError. The responses scripted for one request are given
120
+ in turn; the last one repeats. A scripted Response's text is cut at the ``limit`` of
121
+ the request, as a real exchange would be (``truncated()`` then True). Like the port, it
122
+ never follows a redirect. Not safe for use from several threads.
123
+ """
124
+
125
+ def __init__(self, default: Response | None = None) -> None:
126
+ """``default``: the Response for a request nothing was scripted for, or None to
127
+ raise LookupError for it. TypeError otherwise."""
128
+ if default is not None and not isinstance(default, Response):
129
+ raise TypeError(f"default must be a Response or None, got {type(default).__name__}")
130
+ self._default = default
131
+ self._scripts = {}
132
+ self._requests = []
133
+
134
+ def script(self, method: str, url: str, *responses: Response | BaseException) -> typing.Self:
135
+ """Answer ``method`` ``url`` with ``responses`` in turn, the last repeating. Each is a
136
+ Response or an exception instance to raise. Replaces anything scripted for that
137
+ request before. Returns this fake. TypeError/ValueError."""
138
+ check_request(method, url, {}, None, 1, 0)
139
+ if not responses:
140
+ raise ValueError("script at least one response")
141
+ for response in responses:
142
+ if not isinstance(response, (Response, BaseException)):
143
+ raise TypeError(
144
+ "a scripted response is a Response or an exception, "
145
+ f"got {type(response).__name__}"
146
+ )
147
+ self._scripts[(method.upper(), url)] = list(responses)
148
+ return self
149
+
150
+ def requests(self) -> list[dict[str, typing.Any]]:
151
+ """A fresh list of every request made, oldest first: dicts with ``method``, ``url``,
152
+ ``headers`` (a dict, names lower-cased), ``body``, ``timeout`` and ``limit``."""
153
+ return [dict(each, headers=dict(each["headers"])) for each in self._requests]
154
+
155
+ async def send(
156
+ self,
157
+ method: str,
158
+ url: str,
159
+ headers: Mapping[str, str],
160
+ body: str | None,
161
+ timeout: float,
162
+ limit: int,
163
+ ) -> Response:
164
+ found = check_request(method, url, headers, body, timeout, limit)
165
+ self._requests.append(
166
+ {
167
+ "method": method,
168
+ "url": url,
169
+ "headers": found,
170
+ "body": body,
171
+ "timeout": timeout,
172
+ "limit": limit,
173
+ }
174
+ )
175
+ queue = self._scripts.get((method.upper(), url))
176
+ if queue is None:
177
+ if self._default is None:
178
+ raise LookupError(f"FakeHttp has nothing scripted for {method} {url}")
179
+ response = self._default
180
+ else:
181
+ response = queue.pop(0) if len(queue) > 1 else queue[0]
182
+ if isinstance(response, BaseException):
183
+ raise response
184
+ if len(response.text()) <= limit:
185
+ return response
186
+ return Response(response.status(), response.headers(), response.text()[:limit], True)
187
+
188
+ def __repr__(self) -> str:
189
+ return f"FakeHttp(scripted={len(self._scripts)}, requests={len(self._requests)})"
190
+
191
+
192
+ # --------------------------------------------------------------------------- FakeMcpServer
193
+
194
+
195
+ class FakeMcpServer(McpServer):
196
+ """An McpServer that runs nothing: it lists the tools it was given and answers each call
197
+ with what was scripted for that tool.
198
+
199
+ fake = FakeMcpServer(tools=[ToolListing("add", "Add.", schema)])
200
+ fake = FakeMcpServer(tools=[...], default=McpResult([text("ok")])) # unscripted
201
+ fake.script("add", McpResult([text("3")])) # every call to "add"
202
+ fake.script("add", McpResult([text("no")], failed=True), McpResult([text("3")]))
203
+ fake.script("add", Unavailable("no answer")) # raised when called
204
+ fake.offer(ToolListing("add", "Add.", other_schema)) # the listing changes
205
+ fake.offer(Unavailable("down")) # listing() raises it
206
+ await fake.listing(); await fake.call("add", {"a": 1}, 60)
207
+ fake.calls() # [{"name", "arguments", "timeout", "meta"}]
208
+ fake.listings() # how many times listing() was asked
209
+
210
+ ``call`` validates its arguments as ``LocalMcpServer`` does (TypeError/ValueError) and
211
+ records every valid call, including those that end in a scripted exception. It does not
212
+ check that the tool is listed: a real server may answer a call to a tool it no longer
213
+ lists. A tool nothing was scripted for gets ``default``, or LookupError without one. The
214
+ results scripted for one tool are given in turn; the last one repeats. Not safe for use
215
+ from several threads.
216
+ """
217
+
218
+ def __init__(self, tools: Iterable[ToolListing] = (), default: McpResult | None = None) -> None:
219
+ """``tools``: the ToolListings ``listing()`` answers. ``default``: the McpResult for a
220
+ tool nothing was scripted for, or None to raise LookupError. TypeError/ValueError."""
221
+ if default is not None and not isinstance(default, McpResult):
222
+ raise TypeError(f"default must be an McpResult or None, got {type(default).__name__}")
223
+ self._default = default
224
+ self._listing = ()
225
+ self._scripts = {}
226
+ self._calls = []
227
+ self._listings = 0
228
+ self.offer(*tools)
229
+
230
+ def offer(self, *tools: ToolListing | BaseException) -> typing.Self:
231
+ """From now on ``listing()`` answers these ToolListings (names unique), or, given one
232
+ exception instance instead, raises it. Returns this fake. TypeError/ValueError."""
233
+ if len(tools) == 1 and isinstance(tools[0], BaseException):
234
+ self._listing = tools[0]
235
+ return self
236
+ names = set()
237
+ for tool in tools:
238
+ if not isinstance(tool, ToolListing):
239
+ raise TypeError(f"a listed tool is a ToolListing, got {type(tool).__name__}")
240
+ if tool.name() in names:
241
+ raise ValueError(f"tool {tool.name()!r} listed twice")
242
+ names.add(tool.name())
243
+ self._listing = tuple(tools)
244
+ return self
245
+
246
+ def script(self, name: str, *results: McpResult | BaseException) -> typing.Self:
247
+ """Answer calls to tool ``name`` with ``results`` in turn, the last repeating. Each is
248
+ an McpResult or an exception instance to raise. Replaces anything scripted for that
249
+ tool before. Returns this fake. TypeError/ValueError."""
250
+ check_call(name, {}, 1)
251
+ if not results:
252
+ raise ValueError("script at least one result")
253
+ for result in results:
254
+ if not isinstance(result, (McpResult, BaseException)):
255
+ raise TypeError(
256
+ "a scripted result is an McpResult or an exception, "
257
+ f"got {type(result).__name__}"
258
+ )
259
+ self._scripts[name] = list(results)
260
+ return self
261
+
262
+ def calls(self) -> list[dict[str, typing.Any]]:
263
+ """A fresh list of every call made, oldest first: dicts with ``name``, ``arguments``
264
+ (a plain dict), ``timeout`` and ``meta`` (the request's extra ``_meta``, {} for none)."""
265
+ return [
266
+ dict(each, arguments=copy.deepcopy(each["arguments"]), meta=copy.deepcopy(each["meta"]))
267
+ for each in self._calls
268
+ ]
269
+
270
+ def listings(self) -> int:
271
+ """How many times ``listing()`` was asked."""
272
+ return self._listings
273
+
274
+ async def listing(self) -> tuple[ToolListing, ...]:
275
+ self._listings += 1
276
+ if isinstance(self._listing, BaseException):
277
+ raise self._listing
278
+ return self._listing
279
+
280
+ async def call(
281
+ self,
282
+ name: str,
283
+ arguments: Mapping[str, typing.Any],
284
+ timeout: float,
285
+ meta: Mapping[str, typing.Any] | None = None,
286
+ ) -> McpResult:
287
+ plain, extra = check_call(name, arguments, timeout, meta)
288
+ self._calls.append({"name": name, "arguments": plain, "timeout": timeout, "meta": extra})
289
+ queue = self._scripts.get(name)
290
+ if queue is None:
291
+ if self._default is None:
292
+ raise LookupError(f"FakeMcpServer has nothing scripted for {name!r}")
293
+ result = self._default
294
+ else:
295
+ result = queue.pop(0) if len(queue) > 1 else queue[0]
296
+ if isinstance(result, BaseException):
297
+ raise result
298
+ return result
299
+
300
+ def __repr__(self) -> str:
301
+ listed = 0 if isinstance(self._listing, BaseException) else len(self._listing)
302
+ return f"FakeMcpServer(tools={listed}, calls={len(self._calls)})"