-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathspec_loader.py
More file actions
231 lines (167 loc) · 7.11 KB
/
Copy pathspec_loader.py
File metadata and controls
231 lines (167 loc) · 7.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
"""Load BTX LLM-span spec YAML files.
Handles the custom YAML tags used in the spec:
!fn <name-or-lambda> — named predicate or arbitrary lambda (eval'd in Python)
!starts_with <prefix> — string prefix check
!or [...] — at-least-one-of validator
!gen <generator-name> — value generated by the test runner (e.g. test_runner_client)
"""
from __future__ import annotations
import dataclasses
import os
import uuid
from pathlib import Path
from typing import Any
import yaml
# ---------------------------------------------------------------------------
# Matcher / generator types
# ---------------------------------------------------------------------------
@dataclasses.dataclass
class FnMatcher:
"""A named or lambda-expression validator."""
expr: str # e.g. "is_non_negative_number" or "lambda value: value > 0"
@dataclasses.dataclass
class StartsWithMatcher:
prefix: str
@dataclasses.dataclass
class OrMatcher:
alternatives: list[Any]
@dataclasses.dataclass
class GenValue:
"""A value generated by the test runner at execution time.
The generator name determines what value is produced:
test_runner_client — a string identifying this SDK/client (e.g. "python-openai")
vcr_nonce — a random string that changes every run (busts caches)
"""
generator: str # e.g. "test_runner_client", "vcr_nonce"
# ---------------------------------------------------------------------------
# YAML custom constructors
# ---------------------------------------------------------------------------
def _fn_constructor(loader: yaml.SafeLoader, node: yaml.Node) -> FnMatcher:
expr = loader.construct_scalar(node) # type: ignore[arg-type]
return FnMatcher(expr=expr)
def _starts_with_constructor(loader: yaml.SafeLoader, node: yaml.Node) -> StartsWithMatcher:
prefix = loader.construct_scalar(node) # type: ignore[arg-type]
return StartsWithMatcher(prefix=prefix)
def _or_constructor(loader: yaml.SafeLoader, node: yaml.Node) -> OrMatcher:
alternatives = loader.construct_sequence(node, deep=True)
return OrMatcher(alternatives=alternatives)
def _gen_constructor(loader: yaml.SafeLoader, node: yaml.Node) -> GenValue:
generator = loader.construct_scalar(node) # type: ignore[arg-type]
return GenValue(generator=generator)
def _make_loader() -> type:
"""Return a SafeLoader subclass with BTX custom tags registered."""
class BtxLoader(yaml.SafeLoader):
pass
BtxLoader.add_constructor("!fn", _fn_constructor)
BtxLoader.add_constructor("!starts_with", _starts_with_constructor)
BtxLoader.add_constructor("!or", _or_constructor)
BtxLoader.add_constructor("!gen", _gen_constructor)
return BtxLoader
# ---------------------------------------------------------------------------
# Generator resolution
# ---------------------------------------------------------------------------
# Stable client identifier for this SDK implementation.
_CLIENT_ID = "python-btx"
# Per-process nonce — constant within a run so cassette body matching is stable,
# but differs across runs so cache-busting specs actually bust caches.
_VCR_NONCE = str(uuid.uuid4())[:8]
_GENERATORS: dict[str, str] = {
"test_runner_client": _CLIENT_ID,
"vcr_nonce": _VCR_NONCE,
}
def _resolve_gen(value: GenValue) -> str:
if value.generator in _GENERATORS:
return _GENERATORS[value.generator]
raise ValueError(f"Unknown !gen generator: {value.generator!r}")
def _resolve_variables(variables: dict[str, Any]) -> dict[str, str]:
"""Resolve all !gen values in the variables map to concrete strings."""
resolved: dict[str, str] = {}
for key, val in variables.items():
if isinstance(val, GenValue):
resolved[key] = _resolve_gen(val)
else:
resolved[key] = str(val)
return resolved
def _substitute_templates(obj: Any, variables: dict[str, str]) -> Any:
"""Recursively substitute {{var}} placeholders in strings."""
if isinstance(obj, str):
for key, value in variables.items():
obj = obj.replace(f"{{{{{key}}}}}", value)
return obj
if isinstance(obj, dict):
return {k: _substitute_templates(v, variables) for k, v in obj.items()}
if isinstance(obj, list):
return [_substitute_templates(item, variables) for item in obj]
return obj
# ---------------------------------------------------------------------------
# Spec dataclass
# ---------------------------------------------------------------------------
@dataclasses.dataclass
class LlmSpanSpec:
name: str
type: str
provider: str
endpoint: str
requests: list[dict[str, Any]]
expected_brainstore_spans: list[dict[str, Any]]
headers: dict[str, str]
source_path: Path
@property
def display_name(self) -> str:
"""pytest ID: <provider>/<name>"""
return f"{self.provider}/{self.name}"
@classmethod
def from_dict(cls, data: dict[str, Any], source_path: Path) -> "LlmSpanSpec":
# Resolve variables and substitute templates in requests
raw_variables = data.get("variables", {})
variables = _resolve_variables(raw_variables)
requests = _substitute_templates(data.get("requests", []), variables)
return cls(
name=data["name"],
type=data["type"],
provider=data["provider"],
endpoint=data["endpoint"],
requests=requests,
expected_brainstore_spans=data.get("expected_brainstore_spans", []),
headers=data.get("headers", {}),
source_path=source_path,
)
# ---------------------------------------------------------------------------
# Loader
# ---------------------------------------------------------------------------
_BTX_DIR = Path(__file__).parent
def _spec_root(override: str | None = None) -> Path:
if override:
return Path(override)
env = os.environ.get("BTX_SPEC_ROOT")
if env:
return Path(env)
return _BTX_DIR / "spec" / "test" / "llm_span"
def load_specs(
spec_root: str | Path | None = None,
providers: list[str] | None = None,
) -> list[LlmSpanSpec]:
"""Load all YAML spec files under *spec_root*.
Args:
spec_root: Path to the ``test/llm_span`` directory.
providers: Optional allow-list of provider names (e.g. ``["openai"]``).
Returns:
Sorted list of :class:`LlmSpanSpec` instances.
"""
root = Path(spec_root) if spec_root is not None else _spec_root()
if not root.exists():
raise FileNotFoundError(
f"BTX spec root not found: {root}\n"
"Run the spec-fetch fixture or set BTX_SPEC_ROOT to the llm_span directory."
)
loader_cls = _make_loader()
specs: list[LlmSpanSpec] = []
for yaml_path in sorted(root.rglob("*.yaml")):
provider_dir = yaml_path.parent.name
if providers is not None and provider_dir not in providers:
continue
with open(yaml_path) as f:
data = yaml.load(f, Loader=loader_cls) # noqa: S506 — intentional, custom loader
spec = LlmSpanSpec.from_dict(data, source_path=yaml_path)
specs.append(spec)
return specs