Spaces:
Sleeping
Sleeping
File size: 12,857 Bytes
ab34aa7 | 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 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 | """
CLI smoke tests for src/evaluate.py.
Exercises the evaluate harness as a real subprocess to verify:
- Correct exit codes for valid and invalid inputs.
- Expected strings appear in stdout/stderr.
- Schema-invalid JSON is correctly rejected with exit code 1.
- Invalid --subenv argument is rejected by argparse.
"""
from __future__ import annotations
import json
import os
import sys
import subprocess
import tempfile
from pathlib import Path
import pytest
# ---------------------------------------------------------------------------
# Fixture
# ---------------------------------------------------------------------------
@pytest.fixture
def project_root() -> str:
return str(Path(__file__).parent.parent.parent)
def _run(args: list[str], cwd: str) -> subprocess.CompletedProcess:
"""Helper to run evaluate.py as a subprocess.
Injects PYTHONPATH=cwd so ``from src.schemas...`` absolute imports resolve
correctly — evaluate.py is invoked as a script, not as a module, so it
does not inherit the ``sys.path`` modifications that conftest.py makes.
"""
env = {**os.environ, "PYTHONPATH": cwd}
return subprocess.run(
[sys.executable, "src/evaluate.py"] + args,
capture_output=True,
text=True,
cwd=cwd,
env=env,
)
# ===========================================================================
# Dry-run tests
# ===========================================================================
def test_dry_run_subenv1_exits_zero(project_root):
"""--dry-run on a valid subenv1 file must exit 0 and print 'Schema OK'."""
result = _run(
["--test-set", "tests/test_set/subenv1_cases.json", "--subenv", "1", "--dry-run"],
cwd=project_root,
)
assert result.returncode == 0, (
f"Expected exit 0, got {result.returncode}\n"
f"stdout: {result.stdout}\nstderr: {result.stderr}"
)
assert "Schema OK" in result.stdout
def test_dry_run_subenv2_exits_zero(project_root):
"""--dry-run on a valid subenv2 file must exit 0 and print 'Schema OK'."""
result = _run(
["--test-set", "tests/test_set/subenv2_cases.json", "--subenv", "2", "--dry-run"],
cwd=project_root,
)
assert result.returncode == 0, f"stderr: {result.stderr}"
assert "Schema OK" in result.stdout
def test_dry_run_subenv3_exits_zero(project_root):
"""--dry-run on a valid subenv3 file must exit 0 and print 'Schema OK'."""
result = _run(
["--test-set", "tests/test_set/subenv3_cases.json", "--subenv", "3", "--dry-run"],
cwd=project_root,
)
assert result.returncode == 0, f"stderr: {result.stderr}"
assert "Schema OK" in result.stdout
def test_dry_run_all_exits_zero(project_root):
"""--test-set <directory> --subenv all --dry-run must exit 0."""
result = _run(
["--test-set", "tests/test_set/", "--subenv", "all", "--dry-run"],
cwd=project_root,
)
assert result.returncode == 0, (
f"Expected exit 0, got {result.returncode}\n"
f"stdout: {result.stdout}\nstderr: {result.stderr}"
)
# All three files → three "Schema OK" lines
assert result.stdout.count("Schema OK") >= 3
def test_dry_run_all_wrapped_subenv1_exits_zero(project_root):
"""--subenv all must auto-detect wrapped Sub-env 1 observations via image_obs."""
wrapped_cases = {
"cases": [
{
"id": "wrapped_001",
"observation": {
"image_obs": {
"face_occupancy_ratio": 0.6,
"estimated_yaw_degrees": 5.0,
"estimated_pitch_degrees": 2.0,
"background_complexity_score": 0.3,
"lighting_uniformity_score": 0.7,
"skin_tone_bucket": 3,
"occlusion_detected": False,
"image_resolution": [1280, 720],
"estimated_sharpness": 0.8,
"prompt_token_count": 40,
"prompt_semantic_density": 0.5,
"conflicting_descriptors": [],
"identity_anchoring_strength": 0.8,
},
"proposed_config": {"cfg": 7.0, "eta": 0.08, "denoise_alt": 0.5},
},
"ground_truth": {
"image": {
"regime_classification": "frontal_simple",
"acceptable_regimes": [],
"identified_risk_factors": [],
"valid_prompt_modifications": [],
},
"param": {
"config_risk_level": "safe",
"anomalies": [],
"predicted_failure_modes": [],
"valid_fix_directions": [],
},
},
}
]
}
with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f:
json.dump(wrapped_cases, f)
tmp_path = f.name
try:
result = _run(
["--test-set", tmp_path, "--subenv", "all", "--dry-run"],
cwd=project_root,
)
assert result.returncode == 0, (
f"Expected exit 0, got {result.returncode}\n"
f"stdout: {result.stdout}\nstderr: {result.stderr}"
)
assert "Schema OK" in result.stdout
finally:
Path(tmp_path).unlink(missing_ok=True)
# ===========================================================================
# Scoring (non-dry-run) tests
# ===========================================================================
def test_subenv1_produces_scores(project_root):
"""Full scoring run on subenv1 must print case IDs and the Mean stats line."""
result = _run(
["--test-set", "tests/test_set/subenv1_cases.json", "--subenv", "1"],
cwd=project_root,
)
assert result.returncode == 0, (
f"Expected exit 0, got {result.returncode}\n"
f"stdout: {result.stdout}\nstderr: {result.stderr}"
)
assert "Mean:" in result.stdout
assert "Case 001" in result.stdout
def test_subenv2_produces_scores(project_root):
"""Full scoring run on subenv2 must print case IDs and Mean."""
result = _run(
["--test-set", "tests/test_set/subenv2_cases.json", "--subenv", "2"],
cwd=project_root,
)
assert result.returncode == 0, f"stderr: {result.stderr}"
assert "Mean:" in result.stdout
def test_subenv3_produces_scores(project_root):
"""Full scoring run on subenv3 must print Mean."""
result = _run(
["--test-set", "tests/test_set/subenv3_cases.json", "--subenv", "3"],
cwd=project_root,
)
assert result.returncode == 0, f"stderr: {result.stderr}"
assert "Mean:" in result.stdout
def test_score_values_in_range(project_root):
"""All score values printed to stdout must fall in [0.000, 1.000]."""
result = _run(
["--test-set", "tests/test_set/subenv1_cases.json", "--subenv", "1"],
cwd=project_root,
)
assert result.returncode == 0
for line in result.stdout.splitlines():
if not line.startswith("Case"):
continue
# Line format: "Case 001 score=0.745 [...]"
token = next((t for t in line.split() if t.startswith("score=")), None)
assert token is not None, f"No score token found in: {line!r}"
score = float(token.split("=")[1])
assert 0.0 <= score <= 1.0, f"Score out of range: {score}"
# ===========================================================================
# Error-path tests
# ===========================================================================
def test_missing_required_field_exits_one(project_root):
"""A case with a missing required 'image_obs' field must cause exit 1."""
bad_cases = {
"cases": [
{
"id": "bad",
"observation": {
# 'image_obs' key is missing; only proposed_config present
"proposed_config": {"cfg": 7.0}
},
"ground_truth": {
"image": {
"regime_classification": "frontal_simple",
"acceptable_regimes": [],
"identified_risk_factors": [],
"valid_prompt_modifications": [],
},
"param": {
"config_risk_level": "safe",
"anomalies": [],
"predicted_failure_modes": [],
"valid_fix_directions": [],
},
},
}
]
}
with tempfile.NamedTemporaryFile(
mode="w", suffix=".json", delete=False
) as f:
json.dump(bad_cases, f)
tmp_path = f.name
try:
result = _run(
["--test-set", tmp_path, "--subenv", "1", "--dry-run"],
cwd=project_root,
)
assert result.returncode == 1, (
f"Expected exit 1 for missing field, got {result.returncode}\n"
f"stdout: {result.stdout}\nstderr: {result.stderr}"
)
combined = result.stdout + result.stderr
assert "ERROR" in combined or "missing" in combined.lower()
finally:
Path(tmp_path).unlink(missing_ok=True)
def test_invalid_observation_field_exits_one(project_root):
"""A case where image_obs has a wrong-type field must cause exit 1."""
bad_cases = {
"cases": [
{
"id": "bad_type",
"observation": {
"image_obs": {
"face_occupancy_ratio": "not_a_float", # wrong type
"estimated_yaw_degrees": 5.0,
"estimated_pitch_degrees": 2.0,
"background_complexity_score": 0.3,
"lighting_uniformity_score": 0.7,
"skin_tone_bucket": 3,
"occlusion_detected": False,
"image_resolution": [1280, 720],
"estimated_sharpness": 0.75,
"prompt_token_count": 40,
"prompt_semantic_density": 0.5,
"conflicting_descriptors": [],
"identity_anchoring_strength": 0.8,
},
"proposed_config": {},
},
"ground_truth": {
"image": {
"regime_classification": "frontal_simple",
"acceptable_regimes": [],
"identified_risk_factors": [],
"valid_prompt_modifications": [],
},
"param": {
"config_risk_level": "safe",
"anomalies": [],
"predicted_failure_modes": [],
"valid_fix_directions": [],
},
},
}
]
}
with tempfile.NamedTemporaryFile(
mode="w", suffix=".json", delete=False
) as f:
json.dump(bad_cases, f)
tmp_path = f.name
try:
result = _run(
["--test-set", tmp_path, "--subenv", "1", "--dry-run"],
cwd=project_root,
)
assert result.returncode == 1, (
f"Expected exit 1 for wrong type, got {result.returncode}\n"
f"stdout: {result.stdout}\nstderr: {result.stderr}"
)
finally:
Path(tmp_path).unlink(missing_ok=True)
def test_invalid_json_exits_nonzero(project_root):
"""A file with invalid JSON must cause a non-zero exit."""
with tempfile.NamedTemporaryFile(
mode="w", suffix=".json", delete=False
) as f:
f.write("{this is not json}")
tmp_path = f.name
try:
result = _run(
["--test-set", tmp_path, "--subenv", "1", "--dry-run"],
cwd=project_root,
)
assert result.returncode != 0
finally:
Path(tmp_path).unlink(missing_ok=True)
def test_invalid_subenv_argument(project_root):
"""--subenv 9 must be rejected by argparse (it's not in choices)."""
result = _run(
["--test-set", "tests/test_set/subenv1_cases.json", "--subenv", "9"],
cwd=project_root,
)
assert result.returncode != 0
# argparse writes the error to stderr
assert "9" in result.stderr or "invalid choice" in result.stderr.lower()
def test_missing_test_set_argument(project_root):
"""Omitting --test-set must exit non-zero."""
result = _run(["--subenv", "1"], cwd=project_root)
assert result.returncode != 0
|