toolframe-testkit 0.1.2__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.
- toolframe_testkit/__init__.py +25 -0
- toolframe_testkit/contracts.py +302 -0
- toolframe_testkit/harness.py +566 -0
- toolframe_testkit/py.typed +0 -0
- toolframe_testkit/pytest_plugin.py +79 -0
- toolframe_testkit-0.1.2.dist-info/METADATA +108 -0
- toolframe_testkit-0.1.2.dist-info/RECORD +9 -0
- toolframe_testkit-0.1.2.dist-info/WHEEL +4 -0
- toolframe_testkit-0.1.2.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Developer checks at Toolframe's public SDK, CLI and HTTP boundaries."""
|
|
2
|
+
|
|
3
|
+
from .contracts import (
|
|
4
|
+
ContractCheckError,
|
|
5
|
+
ContractIssue,
|
|
6
|
+
ContractReport,
|
|
7
|
+
ResourceExample,
|
|
8
|
+
ServiceExample,
|
|
9
|
+
check_definition,
|
|
10
|
+
)
|
|
11
|
+
from .harness import ApplicationHarness, CLIResult, HarnessError, HarnessTimeout
|
|
12
|
+
|
|
13
|
+
__version__ = "0.1.2"
|
|
14
|
+
__all__ = [
|
|
15
|
+
"ApplicationHarness",
|
|
16
|
+
"CLIResult",
|
|
17
|
+
"ContractCheckError",
|
|
18
|
+
"ContractIssue",
|
|
19
|
+
"ContractReport",
|
|
20
|
+
"HarnessError",
|
|
21
|
+
"HarnessTimeout",
|
|
22
|
+
"ResourceExample",
|
|
23
|
+
"ServiceExample",
|
|
24
|
+
"check_definition",
|
|
25
|
+
]
|
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
"""Static and concrete-example checks using the public SDK contract validators."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Iterable, Mapping
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from importlib.resources import files
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from jsonschema import SchemaError
|
|
11
|
+
from jsonschema import ValidationError as SchemaValidationError
|
|
12
|
+
from pydantic import ValidationError
|
|
13
|
+
from toolframe_sdk import (
|
|
14
|
+
SYSTEM_SCOPES,
|
|
15
|
+
PluginDefinition,
|
|
16
|
+
ServiceSpec,
|
|
17
|
+
load_object,
|
|
18
|
+
validate,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
_ABSENT = object()
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True)
|
|
25
|
+
class ContractIssue:
|
|
26
|
+
code: str
|
|
27
|
+
path: tuple[str | int, ...]
|
|
28
|
+
message: str
|
|
29
|
+
hint: str
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True)
|
|
33
|
+
class ServiceExample:
|
|
34
|
+
service: str
|
|
35
|
+
method: str
|
|
36
|
+
input: Any
|
|
37
|
+
output: Any = _ABSENT
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass(frozen=True)
|
|
41
|
+
class ResourceExample:
|
|
42
|
+
resource_id: str
|
|
43
|
+
input: Any
|
|
44
|
+
output: Any = _ABSENT
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass(frozen=True)
|
|
48
|
+
class ContractReport:
|
|
49
|
+
definition: PluginDefinition | None
|
|
50
|
+
issues: tuple[ContractIssue, ...]
|
|
51
|
+
|
|
52
|
+
@property
|
|
53
|
+
def ok(self) -> bool:
|
|
54
|
+
return not self.issues
|
|
55
|
+
|
|
56
|
+
def assert_valid(self) -> PluginDefinition:
|
|
57
|
+
if not self.ok or self.definition is None:
|
|
58
|
+
raise ContractCheckError(self)
|
|
59
|
+
return self.definition
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class ContractCheckError(ValueError):
|
|
63
|
+
def __init__(self, report: ContractReport):
|
|
64
|
+
self.report = report
|
|
65
|
+
lines = [
|
|
66
|
+
f"{item.code} at {'.'.join(map(str, item.path)) or '<definition>'}: "
|
|
67
|
+
f"{item.message} {item.hint}"
|
|
68
|
+
for item in report.issues
|
|
69
|
+
]
|
|
70
|
+
super().__init__("\n".join(lines) or "No validated definition")
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def check_definition(
|
|
74
|
+
definition: PluginDefinition | Mapping[str, Any],
|
|
75
|
+
*,
|
|
76
|
+
check_packaged_resources: bool = True,
|
|
77
|
+
load_entrypoints: bool = False,
|
|
78
|
+
external_services: Mapping[str, ServiceSpec] | None = None,
|
|
79
|
+
service_examples: Iterable[ServiceExample] = (),
|
|
80
|
+
resource_examples: Iterable[ResourceExample] = (),
|
|
81
|
+
) -> ContractReport:
|
|
82
|
+
"""Validate a definition and report repairable issues.
|
|
83
|
+
|
|
84
|
+
Entry-point imports are opt-in because importing plugin Python can execute
|
|
85
|
+
code. Packaged document checks operate in the current Python environment;
|
|
86
|
+
use a clean wheel install to verify distribution contents. MCP schemas may
|
|
87
|
+
narrow service schemas. Examples test concrete compatibility, never general
|
|
88
|
+
JSON Schema implication or Core admission/authorization.
|
|
89
|
+
"""
|
|
90
|
+
issues: list[ContractIssue] = []
|
|
91
|
+
|
|
92
|
+
def issue(code, path, message, hint):
|
|
93
|
+
issues.append(ContractIssue(code, tuple(path), message, hint))
|
|
94
|
+
|
|
95
|
+
raw = (
|
|
96
|
+
definition.model_dump(mode="python")
|
|
97
|
+
if isinstance(definition, PluginDefinition)
|
|
98
|
+
else dict(definition)
|
|
99
|
+
)
|
|
100
|
+
try:
|
|
101
|
+
# Revalidate model instances too: SDK model_copy/model_construct can bypass
|
|
102
|
+
# validators. A JSON round trip also rejects non-JSON/NaN schema values.
|
|
103
|
+
validate({}, raw)
|
|
104
|
+
checked = PluginDefinition.model_validate(raw)
|
|
105
|
+
except ValidationError as error:
|
|
106
|
+
for detail in error.errors(include_input=False, include_url=False):
|
|
107
|
+
if not detail["loc"] and "undeclared scope" in detail["msg"]:
|
|
108
|
+
# The SDK has already rejected this cross-field contract. Add
|
|
109
|
+
# exact source locations to its root-level diagnostic rather
|
|
110
|
+
# than maintaining an alternative authorization validator.
|
|
111
|
+
known = set(raw.get("authorization", {}).get("scopes", {}))
|
|
112
|
+
known.update(SYSTEM_SCOPES)
|
|
113
|
+
locations = []
|
|
114
|
+
for service, spec in raw.get("services", {}).items():
|
|
115
|
+
for method, method_spec in spec.get("methods", {}).items():
|
|
116
|
+
locations.append(
|
|
117
|
+
(
|
|
118
|
+
(
|
|
119
|
+
"services",
|
|
120
|
+
service,
|
|
121
|
+
"methods",
|
|
122
|
+
method,
|
|
123
|
+
"required_scopes",
|
|
124
|
+
),
|
|
125
|
+
method_spec.get("required_scopes", ()),
|
|
126
|
+
)
|
|
127
|
+
)
|
|
128
|
+
for index, resource in enumerate(raw.get("resources", ())):
|
|
129
|
+
locations.append(
|
|
130
|
+
(
|
|
131
|
+
("resources", index, "required_scopes"),
|
|
132
|
+
resource.get("required_scopes", ()),
|
|
133
|
+
)
|
|
134
|
+
)
|
|
135
|
+
for path, scopes in locations:
|
|
136
|
+
for index, scope in enumerate(scopes):
|
|
137
|
+
if scope not in known:
|
|
138
|
+
issue(
|
|
139
|
+
"scope_undeclared",
|
|
140
|
+
(*path, index),
|
|
141
|
+
f"Scope {scope} is not declared in this definition.",
|
|
142
|
+
"Declare an owned scope or use an SDK system scope.",
|
|
143
|
+
)
|
|
144
|
+
if issues:
|
|
145
|
+
continue
|
|
146
|
+
issue(
|
|
147
|
+
"definition_invalid",
|
|
148
|
+
detail["loc"],
|
|
149
|
+
detail["msg"],
|
|
150
|
+
"Repair this field using the public SDK PluginDefinition contract.",
|
|
151
|
+
)
|
|
152
|
+
return ContractReport(None, tuple(issues))
|
|
153
|
+
except (SchemaError, TypeError, ValueError) as error:
|
|
154
|
+
issue(
|
|
155
|
+
"definition_invalid",
|
|
156
|
+
(),
|
|
157
|
+
f"SDK schema/JSON validation failed ({type(error).__name__}).",
|
|
158
|
+
"Use valid Draft 2020-12 schemas and finite JSON values.",
|
|
159
|
+
)
|
|
160
|
+
return ContractReport(None, tuple(issues))
|
|
161
|
+
|
|
162
|
+
services = {**(external_services or {}), **checked.services}
|
|
163
|
+
|
|
164
|
+
def target(service, method, path):
|
|
165
|
+
spec = services.get(service)
|
|
166
|
+
result = spec.methods.get(method) if spec else None
|
|
167
|
+
if result is None:
|
|
168
|
+
issue(
|
|
169
|
+
"resource_target_missing",
|
|
170
|
+
path,
|
|
171
|
+
f"No declared method {service}/{method}.",
|
|
172
|
+
"Declare the target or supply its ServiceSpec in external_services.",
|
|
173
|
+
)
|
|
174
|
+
return result
|
|
175
|
+
|
|
176
|
+
def example(schema, value, path):
|
|
177
|
+
try:
|
|
178
|
+
validate(schema, value)
|
|
179
|
+
except SchemaValidationError as error:
|
|
180
|
+
issue(
|
|
181
|
+
"example_schema_invalid",
|
|
182
|
+
(*path, *error.absolute_path),
|
|
183
|
+
f"Example violates the schema's {error.validator} constraint.",
|
|
184
|
+
"Correct the example or schema; instance values are omitted.",
|
|
185
|
+
)
|
|
186
|
+
except (SchemaError, TypeError, ValueError) as error:
|
|
187
|
+
issue(
|
|
188
|
+
"example_schema_invalid",
|
|
189
|
+
path,
|
|
190
|
+
f"Example/schema is invalid JSON ({type(error).__name__}).",
|
|
191
|
+
"Use finite JSON values and valid Draft 2020-12 schemas.",
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
def entrypoint(reference, path):
|
|
195
|
+
try:
|
|
196
|
+
result = load_object(reference)
|
|
197
|
+
if not callable(result):
|
|
198
|
+
raise TypeError("Entry point must be callable")
|
|
199
|
+
except Exception as error:
|
|
200
|
+
issue(
|
|
201
|
+
"entrypoint_unavailable",
|
|
202
|
+
path,
|
|
203
|
+
f"Could not load callable {reference} ({type(error).__name__}).",
|
|
204
|
+
"Install the wheel and its dependencies; export a public callable.",
|
|
205
|
+
)
|
|
206
|
+
|
|
207
|
+
if load_entrypoints:
|
|
208
|
+
entrypoint(checked.factory, ("factory",))
|
|
209
|
+
mcp = {}
|
|
210
|
+
for index, resource in enumerate(checked.resources):
|
|
211
|
+
path = ("resources", index)
|
|
212
|
+
if resource.kind == "mcp.tool":
|
|
213
|
+
spec = target(
|
|
214
|
+
resource.data["service"],
|
|
215
|
+
resource.data["method"],
|
|
216
|
+
(*path, "data", "method"),
|
|
217
|
+
)
|
|
218
|
+
mcp[resource.id] = (resource, spec, path)
|
|
219
|
+
if resource.data["service"] not in checked.services and resource.data[
|
|
220
|
+
"service"
|
|
221
|
+
] not in {requirement.service for requirement in checked.requires.values()}:
|
|
222
|
+
issue(
|
|
223
|
+
"resource_dependency_undeclared",
|
|
224
|
+
(*path, "data", "service"),
|
|
225
|
+
"External resource target has no declared service requirement.",
|
|
226
|
+
"Declare a Requirement for the external target service.",
|
|
227
|
+
)
|
|
228
|
+
elif spec and resource.data["service"] not in checked.services:
|
|
229
|
+
supplied_version = services[resource.data["service"]].version
|
|
230
|
+
for alias, requirement in checked.requires.items():
|
|
231
|
+
if (
|
|
232
|
+
requirement.service == resource.data["service"]
|
|
233
|
+
and requirement.version != supplied_version
|
|
234
|
+
):
|
|
235
|
+
issue(
|
|
236
|
+
"resource_dependency_version_mismatch",
|
|
237
|
+
("requires", alias, "version"),
|
|
238
|
+
f"Required service v{requirement.version}, "
|
|
239
|
+
f"supplied ServiceSpec v{supplied_version}.",
|
|
240
|
+
"Supply a matching service or revise the required version.",
|
|
241
|
+
)
|
|
242
|
+
if spec and spec.audience != "business":
|
|
243
|
+
issue(
|
|
244
|
+
"resource_target_not_business",
|
|
245
|
+
(*path, "data", "method"),
|
|
246
|
+
"MCP tools can expose only business service methods.",
|
|
247
|
+
"Target a business method with explicit scopes.",
|
|
248
|
+
)
|
|
249
|
+
elif resource.kind == "dashboard.page" and load_entrypoints:
|
|
250
|
+
entrypoint(resource.data["entrypoint"], (*path, "data", "entrypoint"))
|
|
251
|
+
elif resource.kind == "llms.document" and check_packaged_resources:
|
|
252
|
+
try:
|
|
253
|
+
document = files(resource.data["package"]).joinpath(
|
|
254
|
+
resource.data["path"]
|
|
255
|
+
)
|
|
256
|
+
if not document.is_file():
|
|
257
|
+
raise FileNotFoundError()
|
|
258
|
+
content = document.read_text(encoding="utf-8")
|
|
259
|
+
if len(content.encode("utf-8")) > 256 * 1024:
|
|
260
|
+
issue(
|
|
261
|
+
"packaged_document_too_large",
|
|
262
|
+
(*path, "data", "path"),
|
|
263
|
+
"Document exceeds the SDK worker's 256 KiB limit.",
|
|
264
|
+
"Split or shorten the packaged document.",
|
|
265
|
+
)
|
|
266
|
+
except Exception as error:
|
|
267
|
+
issue(
|
|
268
|
+
"packaged_document_unavailable",
|
|
269
|
+
(*path, "data", "path"),
|
|
270
|
+
f"Packaged UTF-8 document is unavailable ({type(error).__name__}).",
|
|
271
|
+
"Include the document in the wheel; verify a clean installation.",
|
|
272
|
+
)
|
|
273
|
+
|
|
274
|
+
for index, item in enumerate(service_examples):
|
|
275
|
+
path = ("service_examples", index)
|
|
276
|
+
spec = target(item.service, item.method, (*path, "method"))
|
|
277
|
+
if spec:
|
|
278
|
+
example(spec.input_schema, item.input, (*path, "input"))
|
|
279
|
+
if item.output is not _ABSENT:
|
|
280
|
+
example(spec.output_schema, item.output, (*path, "output"))
|
|
281
|
+
for index, item in enumerate(resource_examples):
|
|
282
|
+
path = ("resource_examples", index)
|
|
283
|
+
found = mcp.get(item.resource_id)
|
|
284
|
+
if found is None:
|
|
285
|
+
issue(
|
|
286
|
+
"resource_example_missing",
|
|
287
|
+
(*path, "resource_id"),
|
|
288
|
+
f"No MCP resource {item.resource_id}.",
|
|
289
|
+
"Use a declared MCP resource ID.",
|
|
290
|
+
)
|
|
291
|
+
continue
|
|
292
|
+
resource, spec, _ = found
|
|
293
|
+
example(resource.data.get("input_schema", {}), item.input, (*path, "input"))
|
|
294
|
+
if spec:
|
|
295
|
+
example(spec.input_schema, item.input, (*path, "service_input"))
|
|
296
|
+
if item.output is not _ABSENT:
|
|
297
|
+
example(
|
|
298
|
+
resource.data.get("output_schema", {}), item.output, (*path, "output")
|
|
299
|
+
)
|
|
300
|
+
if spec:
|
|
301
|
+
example(spec.output_schema, item.output, (*path, "service_output"))
|
|
302
|
+
return ContractReport(checked, tuple(issues))
|
|
@@ -0,0 +1,566 @@
|
|
|
1
|
+
"""An owned temporary application driven only by installed CLI and HTTP APIs."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import math
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import shutil
|
|
10
|
+
import socket
|
|
11
|
+
import subprocess
|
|
12
|
+
import tempfile
|
|
13
|
+
import threading
|
|
14
|
+
import time
|
|
15
|
+
from collections.abc import Mapping, Sequence
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import Any, Literal
|
|
19
|
+
from urllib.parse import quote, urlsplit
|
|
20
|
+
|
|
21
|
+
import httpx
|
|
22
|
+
import psutil
|
|
23
|
+
import tomlkit
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class HarnessError(RuntimeError):
|
|
27
|
+
"""A CLI, operation, readiness or cleanup failure; output remains on disk."""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class HarnessTimeout(HarnessError):
|
|
31
|
+
"""A bounded application/command deadline expired."""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass(frozen=True)
|
|
35
|
+
class CLIResult:
|
|
36
|
+
returncode: int
|
|
37
|
+
stdout: str
|
|
38
|
+
stderr: str
|
|
39
|
+
output_file: Path
|
|
40
|
+
|
|
41
|
+
def json(self) -> Any:
|
|
42
|
+
return json.loads(self.stdout)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _positive(value: float, name: str) -> float:
|
|
46
|
+
if not math.isfinite(value) or value <= 0:
|
|
47
|
+
raise ValueError(f"{name} must be finite and positive")
|
|
48
|
+
return value
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _find_link(value: str | Path) -> str:
|
|
52
|
+
value = str(value)
|
|
53
|
+
parsed = urlsplit(value)
|
|
54
|
+
if parsed.scheme in {"https", "file"}:
|
|
55
|
+
if parsed.username or parsed.password or parsed.query or parsed.fragment:
|
|
56
|
+
raise ValueError(
|
|
57
|
+
"find_links URLs must not contain credentials/query/fragment"
|
|
58
|
+
)
|
|
59
|
+
return value
|
|
60
|
+
if parsed.scheme:
|
|
61
|
+
raise ValueError("find_links must be local paths or https/file URLs")
|
|
62
|
+
return str(Path(value).expanduser().resolve())
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class _ProcessWatch:
|
|
66
|
+
"""Retain identities of owned descendants even if their parent later exits."""
|
|
67
|
+
|
|
68
|
+
def __init__(self, process: subprocess.Popen):
|
|
69
|
+
self.process = psutil.Process(process.pid)
|
|
70
|
+
self._children: dict[tuple[int, float], psutil.Process] = {}
|
|
71
|
+
self._lock = threading.Lock()
|
|
72
|
+
self._done = threading.Event()
|
|
73
|
+
self._thread = threading.Thread(target=self._run, daemon=True)
|
|
74
|
+
self._thread.start()
|
|
75
|
+
|
|
76
|
+
def snapshot(self) -> list[psutil.Process]:
|
|
77
|
+
try:
|
|
78
|
+
children = self.process.children(recursive=True)
|
|
79
|
+
with self._lock:
|
|
80
|
+
for child in children:
|
|
81
|
+
try:
|
|
82
|
+
self._children[(child.pid, child.create_time())] = child
|
|
83
|
+
except psutil.NoSuchProcess:
|
|
84
|
+
pass
|
|
85
|
+
except psutil.NoSuchProcess:
|
|
86
|
+
pass
|
|
87
|
+
with self._lock:
|
|
88
|
+
return list(self._children.values())
|
|
89
|
+
|
|
90
|
+
def _run(self):
|
|
91
|
+
while not self._done.is_set():
|
|
92
|
+
self.snapshot()
|
|
93
|
+
self._done.wait(0.05)
|
|
94
|
+
|
|
95
|
+
def stop(self) -> list[psutil.Process]:
|
|
96
|
+
self._done.set()
|
|
97
|
+
self._thread.join(timeout=2)
|
|
98
|
+
return self.snapshot()
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class ApplicationHarness:
|
|
102
|
+
"""Start a private application with an explicitly supplied installed command.
|
|
103
|
+
|
|
104
|
+
The application home is always newly allocated and removed on close. Logs
|
|
105
|
+
survive under a unique directory in output_directory. Put that directory in
|
|
106
|
+
an ignored build location. No existing application home can be supplied.
|
|
107
|
+
local_control=False makes loopback visitors use Core's normal admission.
|
|
108
|
+
This harness does not simulate principals or bypass admission checks.
|
|
109
|
+
"""
|
|
110
|
+
|
|
111
|
+
def __init__(
|
|
112
|
+
self,
|
|
113
|
+
core_command: str | Path | Sequence[str],
|
|
114
|
+
*,
|
|
115
|
+
output_directory: Path,
|
|
116
|
+
port: int | None = None,
|
|
117
|
+
find_links: Sequence[str | Path] = (),
|
|
118
|
+
wheelhouse: Path | None = None,
|
|
119
|
+
uv_command: str | Path | None = None,
|
|
120
|
+
startup_timeout: float = 60,
|
|
121
|
+
command_timeout: float = 120,
|
|
122
|
+
shutdown_timeout: float = 45,
|
|
123
|
+
poll_interval: float = 0.1,
|
|
124
|
+
local_control: bool = False,
|
|
125
|
+
):
|
|
126
|
+
command = (
|
|
127
|
+
[str(core_command)]
|
|
128
|
+
if isinstance(core_command, (str, Path))
|
|
129
|
+
else list(core_command)
|
|
130
|
+
)
|
|
131
|
+
executable = shutil.which(command[0]) if command else None
|
|
132
|
+
if not executable:
|
|
133
|
+
raise ValueError("Supply an available installed Core command or binary")
|
|
134
|
+
command[0] = str(Path(executable).resolve())
|
|
135
|
+
if port is not None and not 1 <= port <= 65535:
|
|
136
|
+
raise ValueError("port must be between 1 and 65535")
|
|
137
|
+
self.startup_timeout = _positive(startup_timeout, "startup_timeout")
|
|
138
|
+
self.command_timeout = _positive(command_timeout, "command_timeout")
|
|
139
|
+
self.shutdown_timeout = _positive(shutdown_timeout, "shutdown_timeout")
|
|
140
|
+
self.poll_interval = _positive(poll_interval, "poll_interval")
|
|
141
|
+
self.core_command = tuple(command)
|
|
142
|
+
self.find_links = tuple(_find_link(link) for link in find_links)
|
|
143
|
+
self.local_control = local_control
|
|
144
|
+
if wheelhouse is not None:
|
|
145
|
+
wheelhouse = wheelhouse.expanduser().resolve()
|
|
146
|
+
if not wheelhouse.is_dir():
|
|
147
|
+
raise ValueError("wheelhouse must be an existing directory")
|
|
148
|
+
self.find_links += (str(wheelhouse),)
|
|
149
|
+
if uv_command is not None and not shutil.which(str(uv_command)):
|
|
150
|
+
raise ValueError("uv_command must be an available executable")
|
|
151
|
+
|
|
152
|
+
root = Path(output_directory).expanduser().resolve()
|
|
153
|
+
root.mkdir(parents=True, exist_ok=True)
|
|
154
|
+
self.output_directory = Path(tempfile.mkdtemp(prefix="toolframe-", dir=root))
|
|
155
|
+
self._temporary = tempfile.TemporaryDirectory(prefix="toolframe-testkit-")
|
|
156
|
+
self._root = Path(self._temporary.name).resolve()
|
|
157
|
+
self._home = self._root / "application"
|
|
158
|
+
self.home.mkdir(mode=0o700)
|
|
159
|
+
if port is None:
|
|
160
|
+
with socket.socket() as reservation:
|
|
161
|
+
reservation.bind(("127.0.0.1", 0))
|
|
162
|
+
port = reservation.getsockname()[1]
|
|
163
|
+
self.port = port
|
|
164
|
+
self.base_url = f"http://127.0.0.1:{port}"
|
|
165
|
+
# Retain only platform essentials. Global Toolframe/Python/uv/DB settings,
|
|
166
|
+
# proxy credentials and user config are never inherited by the child.
|
|
167
|
+
self._environment = {
|
|
168
|
+
name: os.environ[name]
|
|
169
|
+
for name in ("PATH", "SYSTEMROOT", "WINDIR", "LANG", "LC_ALL")
|
|
170
|
+
if name in os.environ
|
|
171
|
+
}
|
|
172
|
+
private_home = self._root / "user"
|
|
173
|
+
private_home.mkdir(mode=0o700)
|
|
174
|
+
temporary = self._root / "tmp"
|
|
175
|
+
temporary.mkdir(mode=0o700)
|
|
176
|
+
self._environment.update(
|
|
177
|
+
HOME=str(private_home),
|
|
178
|
+
USERPROFILE=str(private_home),
|
|
179
|
+
XDG_CONFIG_HOME=str(private_home / ".config"),
|
|
180
|
+
XDG_CACHE_HOME=str(private_home / ".cache"),
|
|
181
|
+
TMPDIR=str(temporary),
|
|
182
|
+
TMP=str(temporary),
|
|
183
|
+
TEMP=str(temporary),
|
|
184
|
+
UV_CACHE_DIR=str(self._root / "uv-cache"),
|
|
185
|
+
UV_NO_CONFIG="1",
|
|
186
|
+
TOOLFRAME_RUNTIME_ROOT=str(self._root / "launcher-runtime"),
|
|
187
|
+
PYTHONUNBUFFERED="1",
|
|
188
|
+
)
|
|
189
|
+
if uv_command is not None:
|
|
190
|
+
self._environment["TOOLFRAME_UV"] = str(Path(shutil.which(str(uv_command))))
|
|
191
|
+
if wheelhouse is not None:
|
|
192
|
+
self._environment["TOOLFRAME_WHEELHOUSE"] = str(wheelhouse)
|
|
193
|
+
self._client = httpx.Client(base_url=self.base_url, timeout=5, trust_env=False)
|
|
194
|
+
self._process: subprocess.Popen | None = None
|
|
195
|
+
self._serve_watch: _ProcessWatch | None = None
|
|
196
|
+
self._reader_threads: list[threading.Thread] = []
|
|
197
|
+
self._initialized = False
|
|
198
|
+
self._closed = False
|
|
199
|
+
self._log_counter = 0
|
|
200
|
+
|
|
201
|
+
@property
|
|
202
|
+
def home(self) -> Path:
|
|
203
|
+
return self._home
|
|
204
|
+
|
|
205
|
+
def __enter__(self) -> ApplicationHarness:
|
|
206
|
+
try:
|
|
207
|
+
return self.start()
|
|
208
|
+
except BaseException:
|
|
209
|
+
self.close()
|
|
210
|
+
raise
|
|
211
|
+
|
|
212
|
+
def __exit__(self, *_):
|
|
213
|
+
self.close()
|
|
214
|
+
|
|
215
|
+
def _ensure_open(self):
|
|
216
|
+
if self._closed:
|
|
217
|
+
raise HarnessError("ApplicationHarness has been closed")
|
|
218
|
+
|
|
219
|
+
def _token(self) -> str:
|
|
220
|
+
path = self.home / ".toolframe" / "management.token"
|
|
221
|
+
if path.is_symlink() or not path.resolve().is_relative_to(self.home):
|
|
222
|
+
raise HarnessError("Management token must stay inside the owned home")
|
|
223
|
+
try:
|
|
224
|
+
token = path.read_text(encoding="utf-8").strip()
|
|
225
|
+
except OSError:
|
|
226
|
+
raise HarnessError(
|
|
227
|
+
"Owned application's management token is unavailable"
|
|
228
|
+
) from None
|
|
229
|
+
if not token:
|
|
230
|
+
raise HarnessError("Owned application's management token is empty")
|
|
231
|
+
return token
|
|
232
|
+
|
|
233
|
+
def _redact(self, text: str) -> str:
|
|
234
|
+
try:
|
|
235
|
+
text = text.replace(self._token(), "[REDACTED]")
|
|
236
|
+
except HarnessError:
|
|
237
|
+
pass
|
|
238
|
+
text = re.sub(r"(?i)(Bearer\s+)[^\s\"'<>]+", r"\1[REDACTED]", text)
|
|
239
|
+
return re.sub(r"(?i)([?&]token=)[^&\s\"'<>]+", r"\1[REDACTED]", text)
|
|
240
|
+
|
|
241
|
+
def _argv(self, args: Sequence[str]) -> list[str]:
|
|
242
|
+
return [*self.core_command, "--home", str(self.home), "--json", *args]
|
|
243
|
+
|
|
244
|
+
def _log(self, label: str) -> Path:
|
|
245
|
+
self._log_counter += 1
|
|
246
|
+
return self.output_directory / f"{self._log_counter:03d}-{label}.log"
|
|
247
|
+
|
|
248
|
+
@staticmethod
|
|
249
|
+
def _cleanup_descendants(children: list[psutil.Process]):
|
|
250
|
+
# psutil Process identity includes creation time, preventing signals from
|
|
251
|
+
# being sent to a reused PID. Only observed descendants of our child count.
|
|
252
|
+
alive = [child for child in children if child.is_running()]
|
|
253
|
+
for child in reversed(alive):
|
|
254
|
+
try:
|
|
255
|
+
child.terminate()
|
|
256
|
+
except psutil.NoSuchProcess:
|
|
257
|
+
pass
|
|
258
|
+
_, alive = psutil.wait_procs(alive, timeout=2)
|
|
259
|
+
for child in alive:
|
|
260
|
+
try:
|
|
261
|
+
child.kill()
|
|
262
|
+
except psutil.NoSuchProcess:
|
|
263
|
+
pass
|
|
264
|
+
_, alive = psutil.wait_procs(alive, timeout=2)
|
|
265
|
+
if alive:
|
|
266
|
+
raise HarnessError("Owned child processes did not terminate")
|
|
267
|
+
|
|
268
|
+
def _terminate(self, process: subprocess.Popen, watch: _ProcessWatch):
|
|
269
|
+
children = watch.snapshot()
|
|
270
|
+
try:
|
|
271
|
+
if process.poll() is None:
|
|
272
|
+
process.terminate()
|
|
273
|
+
try:
|
|
274
|
+
process.wait(timeout=self.shutdown_timeout)
|
|
275
|
+
except subprocess.TimeoutExpired:
|
|
276
|
+
# Recheck for children spawned during graceful shutdown.
|
|
277
|
+
children += watch.snapshot()
|
|
278
|
+
process.kill()
|
|
279
|
+
process.wait(timeout=5)
|
|
280
|
+
finally:
|
|
281
|
+
children += watch.stop()
|
|
282
|
+
self._cleanup_descendants(list(set(children)))
|
|
283
|
+
|
|
284
|
+
def cli(
|
|
285
|
+
self, *args: str, timeout: float | None = None, check: bool = True
|
|
286
|
+
) -> CLIResult:
|
|
287
|
+
"""Run a CLI action with a deadline and sanitized retained output.
|
|
288
|
+
|
|
289
|
+
Avoid credential-producing actions: their output is intentionally redacted.
|
|
290
|
+
Args are passed as an argv list; no shell is invoked.
|
|
291
|
+
"""
|
|
292
|
+
self._ensure_open()
|
|
293
|
+
if any(arg == "--home" or arg.startswith("--home=") for arg in args):
|
|
294
|
+
raise ValueError(
|
|
295
|
+
"CLI home cannot be overridden outside the owned application"
|
|
296
|
+
)
|
|
297
|
+
timeout = _positive(
|
|
298
|
+
self.command_timeout if timeout is None else timeout, "timeout"
|
|
299
|
+
)
|
|
300
|
+
output = self._log("cli")
|
|
301
|
+
process = subprocess.Popen(
|
|
302
|
+
self._argv(args),
|
|
303
|
+
cwd=self.home,
|
|
304
|
+
env=self._environment,
|
|
305
|
+
stdin=subprocess.DEVNULL,
|
|
306
|
+
stdout=subprocess.PIPE,
|
|
307
|
+
stderr=subprocess.PIPE,
|
|
308
|
+
)
|
|
309
|
+
watch = _ProcessWatch(process)
|
|
310
|
+
expired = False
|
|
311
|
+
try:
|
|
312
|
+
stdout, stderr = process.communicate(timeout=timeout)
|
|
313
|
+
except subprocess.TimeoutExpired:
|
|
314
|
+
expired = True
|
|
315
|
+
self._terminate(process, watch)
|
|
316
|
+
stdout, stderr = process.communicate(timeout=5)
|
|
317
|
+
else:
|
|
318
|
+
self._terminate(process, watch)
|
|
319
|
+
clean_stdout = self._redact(stdout.decode("utf-8", errors="replace"))
|
|
320
|
+
clean_stderr = self._redact(stderr.decode("utf-8", errors="replace"))
|
|
321
|
+
output.write_text(
|
|
322
|
+
clean_stdout + "\n[stderr]\n" + clean_stderr, encoding="utf-8"
|
|
323
|
+
)
|
|
324
|
+
result = CLIResult(process.returncode, clean_stdout, clean_stderr, output)
|
|
325
|
+
if expired:
|
|
326
|
+
raise HarnessTimeout(f"CLI deadline expired; output: {output}")
|
|
327
|
+
if check and result.returncode:
|
|
328
|
+
raise HarnessError(f"CLI exited {result.returncode}; output: {output}")
|
|
329
|
+
return result
|
|
330
|
+
|
|
331
|
+
def initialize(self) -> ApplicationHarness:
|
|
332
|
+
self._ensure_open()
|
|
333
|
+
if self._initialized:
|
|
334
|
+
return self
|
|
335
|
+
self.cli("init", "--host", "127.0.0.1", "--port", str(self.port))
|
|
336
|
+
# This is the public composition file in our newly created home. No
|
|
337
|
+
# existing/user application composition is accepted by this harness.
|
|
338
|
+
path = self.home / "toolframe.toml"
|
|
339
|
+
document = tomlkit.parse(path.read_text(encoding="utf-8"))
|
|
340
|
+
document.setdefault("packages", {})["find_links"] = list(self.find_links)
|
|
341
|
+
document.setdefault("access", {})["local_control"] = self.local_control
|
|
342
|
+
path.write_text(tomlkit.dumps(document), encoding="utf-8")
|
|
343
|
+
self._initialized = True
|
|
344
|
+
return self
|
|
345
|
+
|
|
346
|
+
def _capture(self, stream, output: Path):
|
|
347
|
+
with output.open("w", encoding="utf-8") as handle:
|
|
348
|
+
for line in iter(stream.readline, b""):
|
|
349
|
+
handle.write(self._redact(line.decode("utf-8", errors="replace")))
|
|
350
|
+
handle.flush()
|
|
351
|
+
stream.close()
|
|
352
|
+
|
|
353
|
+
def start(self) -> ApplicationHarness:
|
|
354
|
+
self._ensure_open()
|
|
355
|
+
if self._process is not None:
|
|
356
|
+
raise HarnessError("Core is already started; call stop() before restarting")
|
|
357
|
+
self.initialize()
|
|
358
|
+
self._process = subprocess.Popen(
|
|
359
|
+
self._argv(("serve",)),
|
|
360
|
+
cwd=self.home,
|
|
361
|
+
env=self._environment,
|
|
362
|
+
stdin=subprocess.DEVNULL,
|
|
363
|
+
stdout=subprocess.PIPE,
|
|
364
|
+
stderr=subprocess.PIPE,
|
|
365
|
+
)
|
|
366
|
+
self._serve_watch = _ProcessWatch(self._process)
|
|
367
|
+
for label, stream in (
|
|
368
|
+
("serve-stdout", self._process.stdout),
|
|
369
|
+
("serve-stderr", self._process.stderr),
|
|
370
|
+
):
|
|
371
|
+
reader = threading.Thread(
|
|
372
|
+
target=self._capture, args=(stream, self._log(label)), daemon=True
|
|
373
|
+
)
|
|
374
|
+
reader.start()
|
|
375
|
+
self._reader_threads.append(reader)
|
|
376
|
+
deadline = time.monotonic() + self.startup_timeout
|
|
377
|
+
try:
|
|
378
|
+
while time.monotonic() < deadline:
|
|
379
|
+
self._alive()
|
|
380
|
+
try:
|
|
381
|
+
response = self.request(
|
|
382
|
+
"GET",
|
|
383
|
+
"/_toolframe/v1/readiness",
|
|
384
|
+
management=True,
|
|
385
|
+
timeout=min(5, max(0.01, deadline - time.monotonic())),
|
|
386
|
+
)
|
|
387
|
+
if response.status_code == 200 and response.json().get("ready"):
|
|
388
|
+
return self
|
|
389
|
+
except httpx.HTTPError, HarnessError:
|
|
390
|
+
pass
|
|
391
|
+
time.sleep(min(self.poll_interval, max(0, deadline - time.monotonic())))
|
|
392
|
+
raise HarnessTimeout(
|
|
393
|
+
f"Core readiness deadline expired; output: {self.output_directory}"
|
|
394
|
+
)
|
|
395
|
+
except BaseException:
|
|
396
|
+
self.stop()
|
|
397
|
+
raise
|
|
398
|
+
|
|
399
|
+
def _alive(self):
|
|
400
|
+
if self._process is None or self._process.poll() is not None:
|
|
401
|
+
raise HarnessError(f"Core is not running; output: {self.output_directory}")
|
|
402
|
+
|
|
403
|
+
def stop(self):
|
|
404
|
+
"""Gracefully stop this Core, then reap only its observed descendants."""
|
|
405
|
+
if self._process is not None:
|
|
406
|
+
try:
|
|
407
|
+
self._terminate(self._process, self._serve_watch)
|
|
408
|
+
finally:
|
|
409
|
+
self._process = None
|
|
410
|
+
self._serve_watch = None
|
|
411
|
+
for reader in self._reader_threads:
|
|
412
|
+
reader.join(timeout=5)
|
|
413
|
+
self._reader_threads.clear()
|
|
414
|
+
|
|
415
|
+
def close(self):
|
|
416
|
+
if self._closed:
|
|
417
|
+
return
|
|
418
|
+
try:
|
|
419
|
+
self.stop()
|
|
420
|
+
finally:
|
|
421
|
+
self._client.close()
|
|
422
|
+
self._temporary.cleanup()
|
|
423
|
+
self._closed = True
|
|
424
|
+
|
|
425
|
+
def request(
|
|
426
|
+
self, method: str, path: str, *, management: bool = False, **kwargs
|
|
427
|
+
) -> httpx.Response:
|
|
428
|
+
"""Send an HTTP request to this application, optionally as its operator."""
|
|
429
|
+
self._ensure_open()
|
|
430
|
+
if not path.startswith("/") or path.startswith("//") or urlsplit(path).netloc:
|
|
431
|
+
raise ValueError("Request path must be relative to this application")
|
|
432
|
+
headers = httpx.Headers(kwargs.pop("headers", {}))
|
|
433
|
+
if management:
|
|
434
|
+
headers["authorization"] = f"Bearer {self._token()}"
|
|
435
|
+
# Explicitly forbid following redirects which might transmit the token
|
|
436
|
+
# to an external target; consumers may inspect Location themselves.
|
|
437
|
+
if kwargs.pop("follow_redirects", False):
|
|
438
|
+
raise ValueError("Harness requests must not follow redirects")
|
|
439
|
+
return self._client.request(method, path, headers=headers, **kwargs)
|
|
440
|
+
|
|
441
|
+
def status(self) -> dict:
|
|
442
|
+
response = self.request("GET", "/_toolframe/v1/status", management=True)
|
|
443
|
+
response.raise_for_status()
|
|
444
|
+
return response.json()
|
|
445
|
+
|
|
446
|
+
def _poll_response(self, path: str, deadline: float) -> dict | None:
|
|
447
|
+
try:
|
|
448
|
+
response = self.request(
|
|
449
|
+
"GET",
|
|
450
|
+
path,
|
|
451
|
+
management=True,
|
|
452
|
+
timeout=min(5, max(0.01, deadline - time.monotonic())),
|
|
453
|
+
)
|
|
454
|
+
except httpx.TransportError:
|
|
455
|
+
return None
|
|
456
|
+
if response.status_code >= 500 or response.status_code == 429:
|
|
457
|
+
return None
|
|
458
|
+
response.raise_for_status()
|
|
459
|
+
return response.json()
|
|
460
|
+
|
|
461
|
+
def wait_for_plugin(
|
|
462
|
+
self, plugin_id: str, *, healthy: bool = True, timeout: float | None = None
|
|
463
|
+
) -> dict:
|
|
464
|
+
deadline = time.monotonic() + _positive(
|
|
465
|
+
self.command_timeout if timeout is None else timeout, "timeout"
|
|
466
|
+
)
|
|
467
|
+
while time.monotonic() < deadline:
|
|
468
|
+
self._alive()
|
|
469
|
+
report = self._poll_response("/_toolframe/v1/status", deadline)
|
|
470
|
+
for row in (report or {}).get("plugins", []):
|
|
471
|
+
if row["id"] == plugin_id and bool(row.get("healthy")) == healthy:
|
|
472
|
+
return row
|
|
473
|
+
time.sleep(min(self.poll_interval, max(0, deadline - time.monotonic())))
|
|
474
|
+
raise HarnessTimeout(
|
|
475
|
+
f"Plugin health deadline expired; output: {self.output_directory}"
|
|
476
|
+
)
|
|
477
|
+
|
|
478
|
+
def install_plugin(
|
|
479
|
+
self, source: str | Path, *, plugin_id: str | None = None, enable: bool = True
|
|
480
|
+
) -> CLIResult:
|
|
481
|
+
if isinstance(source, Path):
|
|
482
|
+
normalized = str(source.expanduser().resolve())
|
|
483
|
+
else:
|
|
484
|
+
prefix, _, value = source.partition(":")
|
|
485
|
+
if prefix in {"wheel", "path"}:
|
|
486
|
+
normalized = prefix + ":" + str(Path(value).expanduser().resolve())
|
|
487
|
+
elif source.startswith(("pypi:", "git+", "https://")):
|
|
488
|
+
normalized = source
|
|
489
|
+
else:
|
|
490
|
+
normalized = str(Path(source).expanduser().resolve())
|
|
491
|
+
args = ["plugin", "add", normalized]
|
|
492
|
+
if plugin_id is not None:
|
|
493
|
+
args += ["--id", plugin_id]
|
|
494
|
+
if enable:
|
|
495
|
+
args.append("--enable")
|
|
496
|
+
return self.cli(*args)
|
|
497
|
+
|
|
498
|
+
def plugin_action(self, action: str, plugin_id: str, *args: str) -> CLIResult:
|
|
499
|
+
if action not in {
|
|
500
|
+
"validate",
|
|
501
|
+
"update",
|
|
502
|
+
"reload",
|
|
503
|
+
"enable",
|
|
504
|
+
"disable",
|
|
505
|
+
"remove",
|
|
506
|
+
"stop",
|
|
507
|
+
"status",
|
|
508
|
+
"logs",
|
|
509
|
+
}:
|
|
510
|
+
raise ValueError("Unknown public plugin action")
|
|
511
|
+
return self.cli("plugin", action, plugin_id, *args)
|
|
512
|
+
|
|
513
|
+
def operation(
|
|
514
|
+
self,
|
|
515
|
+
action: str,
|
|
516
|
+
params: Mapping[str, Any] | None = None,
|
|
517
|
+
*,
|
|
518
|
+
timeout: float | None = None,
|
|
519
|
+
) -> dict:
|
|
520
|
+
"""Submit a public management operation and await its terminal result."""
|
|
521
|
+
deadline = time.monotonic() + _positive(
|
|
522
|
+
self.command_timeout if timeout is None else timeout, "timeout"
|
|
523
|
+
)
|
|
524
|
+
response = self.request(
|
|
525
|
+
"POST",
|
|
526
|
+
"/_toolframe/v1/operations",
|
|
527
|
+
management=True,
|
|
528
|
+
json={"action": action, "params": dict(params or {})},
|
|
529
|
+
timeout=min(5, max(0.01, deadline - time.monotonic())),
|
|
530
|
+
)
|
|
531
|
+
response.raise_for_status()
|
|
532
|
+
identifier = response.json()["id"]
|
|
533
|
+
while time.monotonic() < deadline:
|
|
534
|
+
self._alive()
|
|
535
|
+
result = self._poll_response(
|
|
536
|
+
f"/_toolframe/v1/operations/{quote(identifier, safe='')}", deadline
|
|
537
|
+
)
|
|
538
|
+
if result and result["status"] not in {"queued", "running", "cancelling"}:
|
|
539
|
+
if result["status"] != "succeeded":
|
|
540
|
+
raise HarnessError(
|
|
541
|
+
f"Operation {identifier} {result['status']}; "
|
|
542
|
+
f"output: {self.output_directory}"
|
|
543
|
+
)
|
|
544
|
+
return result
|
|
545
|
+
time.sleep(min(self.poll_interval, max(0, deadline - time.monotonic())))
|
|
546
|
+
raise HarnessTimeout(
|
|
547
|
+
f"Operation deadline expired; output: {self.output_directory}"
|
|
548
|
+
)
|
|
549
|
+
|
|
550
|
+
def service_call(
|
|
551
|
+
self,
|
|
552
|
+
owner: str,
|
|
553
|
+
service: str,
|
|
554
|
+
method: str,
|
|
555
|
+
params: Any,
|
|
556
|
+
*,
|
|
557
|
+
entrance: Literal["visitor", "public"] = "visitor",
|
|
558
|
+
management: bool = False,
|
|
559
|
+
) -> httpx.Response:
|
|
560
|
+
if entrance not in {"visitor", "public"}:
|
|
561
|
+
raise ValueError("entrance must be visitor or public")
|
|
562
|
+
prefix = "/api" if entrance == "public" else "/_toolframe/v1/services"
|
|
563
|
+
path = "/".join(quote(value, safe="") for value in (owner, service, method))
|
|
564
|
+
return self.request(
|
|
565
|
+
"POST", f"{prefix}/{path}", management=management, json=params
|
|
566
|
+
)
|
|
File without changes
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Opt-in pytest integration: load with pytest_plugins or pytest -p.
|
|
2
|
+
|
|
3
|
+
There is intentionally no automatic pytest11 entry point, and importing the
|
|
4
|
+
runtime package does not import pytest or start an application.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import shlex
|
|
10
|
+
from contextlib import ExitStack
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
import pytest
|
|
14
|
+
|
|
15
|
+
from .contracts import check_definition
|
|
16
|
+
from .harness import ApplicationHarness
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def pytest_addoption(parser):
|
|
20
|
+
group = parser.getgroup("toolframe")
|
|
21
|
+
group.addoption(
|
|
22
|
+
"--toolframe-core-command",
|
|
23
|
+
help="Explicit installed Core argv (shell-style quoting; no shell executes it)",
|
|
24
|
+
)
|
|
25
|
+
group.addoption(
|
|
26
|
+
"--toolframe-find-links",
|
|
27
|
+
action="append",
|
|
28
|
+
default=[],
|
|
29
|
+
help="Wheel directory or https/file URL (repeatable)",
|
|
30
|
+
)
|
|
31
|
+
group.addoption(
|
|
32
|
+
"--toolframe-output-directory",
|
|
33
|
+
default="build/toolframe-testkit",
|
|
34
|
+
help="Ignored directory retaining sanitized child output",
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@pytest.fixture
|
|
39
|
+
def toolframe_definition_checker():
|
|
40
|
+
"""The public definition checker, convenient for parametrized plugin tests."""
|
|
41
|
+
return check_definition
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@pytest.fixture
|
|
45
|
+
def toolframe_harness_factory(request):
|
|
46
|
+
"""Create owned harnesses and close all of them when the test ends.
|
|
47
|
+
|
|
48
|
+
A supplied command option is required only when this factory is called.
|
|
49
|
+
Explicit keyword arguments override CLI configuration.
|
|
50
|
+
"""
|
|
51
|
+
cleanup = ExitStack()
|
|
52
|
+
|
|
53
|
+
def factory(**kwargs):
|
|
54
|
+
command = kwargs.pop("core_command", None)
|
|
55
|
+
if command is None:
|
|
56
|
+
configured = request.config.getoption("--toolframe-core-command")
|
|
57
|
+
if not configured:
|
|
58
|
+
pytest.skip("Supply --toolframe-core-command for installed Core tests")
|
|
59
|
+
command = shlex.split(configured)
|
|
60
|
+
kwargs.setdefault(
|
|
61
|
+
"output_directory",
|
|
62
|
+
Path(request.config.getoption("--toolframe-output-directory")),
|
|
63
|
+
)
|
|
64
|
+
kwargs.setdefault(
|
|
65
|
+
"find_links", request.config.getoption("--toolframe-find-links")
|
|
66
|
+
)
|
|
67
|
+
app = ApplicationHarness(command, **kwargs)
|
|
68
|
+
cleanup.callback(app.close)
|
|
69
|
+
return app
|
|
70
|
+
|
|
71
|
+
with cleanup:
|
|
72
|
+
yield factory
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@pytest.fixture
|
|
76
|
+
def toolframe_application(toolframe_harness_factory):
|
|
77
|
+
"""A started private application; skip when no installed command is supplied."""
|
|
78
|
+
with toolframe_harness_factory() as app:
|
|
79
|
+
yield app
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: toolframe-testkit
|
|
3
|
+
Version: 0.1.2
|
|
4
|
+
Summary: Public contract checks and installed-application tests for Toolframe developers
|
|
5
|
+
Project-URL: Homepage, https://github.com/toolframe/toolframe-testkit
|
|
6
|
+
Project-URL: Repository, https://github.com/toolframe/toolframe-testkit
|
|
7
|
+
Project-URL: Documentation, https://github.com/toolframe/toolframe-testkit#readme
|
|
8
|
+
Project-URL: Issues, https://github.com/toolframe/toolframe-testkit/issues
|
|
9
|
+
Author-email: byfb <62798989+byfb@users.noreply.github.com>
|
|
10
|
+
License-Expression: Apache-2.0
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Requires-Python: >=3.14
|
|
13
|
+
Requires-Dist: httpx<1,>=0.28
|
|
14
|
+
Requires-Dist: jsonschema<5,>=4.23
|
|
15
|
+
Requires-Dist: psutil<9,>=7
|
|
16
|
+
Requires-Dist: pydantic<3,>=2.12.5
|
|
17
|
+
Requires-Dist: tomlkit<1,>=0.13
|
|
18
|
+
Requires-Dist: toolframe-sdk==0.3.0
|
|
19
|
+
Provides-Extra: pytest
|
|
20
|
+
Requires-Dist: pytest<10,>=8; extra == 'pytest'
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
|
|
23
|
+
# Toolframe testkit
|
|
24
|
+
|
|
25
|
+
Toolframe testkit is a Python library for checking a plugin's public SDK contract
|
|
26
|
+
and exercising an installed Toolframe Core application through its public CLI and
|
|
27
|
+
HTTP APIs. It is a developer test dependency, not a Core runtime plugin. Version
|
|
28
|
+
0.1.2 supports Python 3.14 or newer and pins `toolframe-sdk==0.3.0`.
|
|
29
|
+
|
|
30
|
+
The package is Apache-2.0 licensed. It does not install Core, choose a global
|
|
31
|
+
application, or load a pytest plugin automatically.
|
|
32
|
+
|
|
33
|
+
## Quick start
|
|
34
|
+
|
|
35
|
+
Install the checker and opt-in pytest integration from PyPI:
|
|
36
|
+
|
|
37
|
+
```sh
|
|
38
|
+
python -m pip install 'toolframe-testkit[pytest]==0.1.2'
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
The SDK is installed as a dependency. See
|
|
42
|
+
[development and verification](docs/development.md) for source builds and local
|
|
43
|
+
wheelhouse checks.
|
|
44
|
+
|
|
45
|
+
Check a public SDK definition in a unit test:
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
from toolframe_testkit import check_definition
|
|
49
|
+
from my_plugin.definition import plugin
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def test_plugin_contract():
|
|
53
|
+
check_definition(plugin).assert_valid()
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
For installed Core tests, explicitly load the pytest plugin in `conftest.py`:
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
pytest_plugins = ["toolframe_testkit.pytest_plugin"]
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Then supply an installed Core command when running the test. The plugin creates a
|
|
63
|
+
new private application home, starts Core on a loopback port, and removes the home
|
|
64
|
+
after the test. A minimal `tests/test_application.py` can check readiness without
|
|
65
|
+
installing a plugin:
|
|
66
|
+
|
|
67
|
+
```python
|
|
68
|
+
def test_application(toolframe_application):
|
|
69
|
+
assert toolframe_application.status()["ready"] is True
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Child output is retained below the selected ignored build directory:
|
|
73
|
+
|
|
74
|
+
```sh
|
|
75
|
+
pytest tests/test_application.py \
|
|
76
|
+
--toolframe-core-command "$(command -v toolframe-core)" \
|
|
77
|
+
--toolframe-output-directory build/installed-core
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
See [contract checks](docs/contracts.md) for definition and example validation,
|
|
81
|
+
[the application harness](docs/harness.md) for installed Core testing, and
|
|
82
|
+
[development and verification](docs/development.md) for wheel builds and the
|
|
83
|
+
real-Core fixture run. The complete standalone scenario is in
|
|
84
|
+
[examples/installed_application.py](examples/installed_application.py).
|
|
85
|
+
|
|
86
|
+
## Support limits
|
|
87
|
+
|
|
88
|
+
The harness is deliberately explicit: callers choose the installed Core command,
|
|
89
|
+
wheel links, and output directory. It uses public Core CLI and HTTP endpoints and
|
|
90
|
+
does not import Core internals or edit an existing user application. The default
|
|
91
|
+
`local_control=False` exercises Core's normal admission checks; setting it to
|
|
92
|
+
`True` is available only when a test specifically needs local control behavior.
|
|
93
|
+
|
|
94
|
+
The pytest integration is opt-in through `pytest_plugins` or `pytest -p`; there is
|
|
95
|
+
no `pytest11` auto-entry point. `check_definition` validates the SDK model, target
|
|
96
|
+
references, resource scopes, packaged UTF-8 documents, and supplied concrete
|
|
97
|
+
examples. Example checks do not prove general JSON Schema implication or Core
|
|
98
|
+
authorization behavior. MCP resource schemas may intentionally narrow a service
|
|
99
|
+
schema.
|
|
100
|
+
|
|
101
|
+
The installed-Core harness covers public readiness, status, plugin lifecycle,
|
|
102
|
+
service admission, authorization, schema rejection, and retained data. Browser
|
|
103
|
+
interaction, provider-specific protocols, and external service provisioning need
|
|
104
|
+
separate acceptance checks. The harness runs local processes; it does not manage
|
|
105
|
+
remote deployments. It redacts its owned management token and common bearer/token
|
|
106
|
+
query forms, but cannot guarantee redaction of arbitrary plugin output.
|
|
107
|
+
|
|
108
|
+
For release validation and Trusted Publisher setup, see [releasing](docs/releasing.md).
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
toolframe_testkit/__init__.py,sha256=bg7_duMcy9ie52gjyFPcBfdm1TT5GPJcNVDfsHhZFjw,570
|
|
2
|
+
toolframe_testkit/contracts.py,sha256=EaitfEi5p8EmbAshYjzs-257iyWl8WWU3BcKB5SuyUA,12072
|
|
3
|
+
toolframe_testkit/harness.py,sha256=osCzovKKJdup2QS84-sm1SyyIWE5qioLHRS2OgTfJ48,21965
|
|
4
|
+
toolframe_testkit/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
toolframe_testkit/pytest_plugin.py,sha256=mK3NqncKAkK1UtDoZJ0s0bTMxr1TWmxq7I7fbx5v2Sw,2431
|
|
6
|
+
toolframe_testkit-0.1.2.dist-info/METADATA,sha256=Ll9jOMVeYPyZHgBRvB7gB50v65yfG3kZ6oc8ukHPSAA,4396
|
|
7
|
+
toolframe_testkit-0.1.2.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
8
|
+
toolframe_testkit-0.1.2.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
9
|
+
toolframe_testkit-0.1.2.dist-info/RECORD,,
|
|
@@ -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.
|