Spaces:
Sleeping
Sleeping
File size: 15,412 Bytes
1993d5c | 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 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 | """Comprehensive Regression Test Suite for Geometry Engine, Validator, VisualizationSpec,
and Manim Job Lifecycle.
"""
from __future__ import annotations
import asyncio
import math
from typing import Any, Dict
import numpy as np
import pytest
from unittest.mock import AsyncMock, patch, MagicMock
from solver.dsl_parser import DSLParser
from solver.engine import GeometryEngine
from solver.validator import GeometryValidator, ValidationResult
from solver.models import Point, Constraint
from manim_client.schemas import (
ErrorCode,
StructuredError,
VisualizationConfig,
VisualizationSpec,
MathRenderResponse,
build_visualization_spec,
)
from manim_client.client import ManimClient
# ============================================================================
# 1. GEOMETRY ENGINE & CANONICAL PLACEMENT TESTS
# ============================================================================
def test_2d_rectangle_constraints():
"""Tests 2D rectangle parsing, solving, canonical placement and validation."""
dsl = """
RECTANGLE(ABCD)
LENGTH(AB, 8)
LENGTH(BC, 6)
"""
parser = DSLParser()
points, constraints, is_3d = parser.parse(dsl)
assert not is_3d
engine = GeometryEngine()
result = engine.solve(points, constraints, is_3d)
assert result is not None
coords = result["coordinates"]
assert "A" in coords and "B" in coords and "C" in coords and "D" in coords
# Check mathematical scale and dimensions
vA = np.array(coords["A"][:2])
vB = np.array(coords["B"][:2])
vC = np.array(coords["C"][:2])
vD = np.array(coords["D"][:2])
assert pytest.approx(np.linalg.norm(vB - vA), rel=1e-3) == 8.0
assert pytest.approx(np.linalg.norm(vC - vB), rel=1e-3) == 6.0
assert pytest.approx(np.linalg.norm(vD - vC), rel=1e-3) == 8.0
assert pytest.approx(np.linalg.norm(vA - vD), rel=1e-3) == 6.0
# Orthogonality: AB ⊥ BC
dot = np.dot(vB - vA, vC - vB)
assert pytest.approx(dot, abs=1e-3) == 0.0
# Validate with GeometryValidator
validator = GeometryValidator()
val_res = validator.validate(result, constraints, is_3d)
assert val_res.is_valid, f"Validation failed: {val_res.errors}"
def test_2d_equilateral_triangle():
"""Tests equilateral triangle parsing and solving."""
dsl = """
EQUILATERAL_TRIANGLE(ABC, 6)
"""
parser = DSLParser()
points, constraints, is_3d = parser.parse(dsl)
engine = GeometryEngine()
result = engine.solve(points, constraints, is_3d)
assert result is not None
coords = result["coordinates"]
vA = np.array(coords["A"][:2])
vB = np.array(coords["B"][:2])
vC = np.array(coords["C"][:2])
assert pytest.approx(np.linalg.norm(vB - vA), rel=1e-2) == 6.0
assert pytest.approx(np.linalg.norm(vC - vB), rel=1e-2) == 6.0
assert pytest.approx(np.linalg.norm(vA - vC), rel=1e-2) == 6.0
validator = GeometryValidator()
val_res = validator.validate(result, constraints, is_3d)
assert val_res.is_valid, f"Validation failed: {val_res.errors}"
def test_3d_canonical_pyramid_placement():
"""
Tests 3D Pyramid S.ABCD with square base AB=4, SO ⊥ (ABCD), SO=6.
Ensures canonical coordinate policy:
- Base on z=0
- Center O at mean of base
- Apex S at (Ox, Oy, 6) along +Z
- Mathematical scale preserved.
"""
dsl = """
PYRAMID(S_ABCD)
SQUARE(ABCD)
LENGTH(AB, 4)
POINT(S)
POINT(O)
CENTER(O, ABCD)
PERPENDICULAR_PLANE(SO, ABCD)
LENGTH(SO, 6)
"""
parser = DSLParser()
points, constraints, is_3d = parser.parse(dsl)
assert is_3d
engine = GeometryEngine()
result = engine.solve(points, constraints, is_3d)
assert result is not None
coords = result["coordinates"]
# Verify base vertices are in plane z = 0
for p in ["A", "B", "C", "D", "O"]:
assert pytest.approx(coords[p][2], abs=1e-3) == 0.0, f"Point {p} not on z=0 ground plane"
# Base square edge length = 4
vA = np.array(coords["A"])
vB = np.array(coords["B"])
assert pytest.approx(np.linalg.norm(vB - vA), rel=1e-3) == 4.0
# Center O is at midpoint/mean
vO = np.array(coords["O"])
mean_base = np.mean([coords["A"], coords["B"], coords["C"], coords["D"]], axis=0)
assert pytest.approx(np.linalg.norm(vO - mean_base), abs=1e-3) == 0.0
# Apex S is directly above O along +Z with height 6
vS = np.array(coords["S"])
assert pytest.approx(vS[0], abs=1e-3) == vO[0]
assert pytest.approx(vS[1], abs=1e-3) == vO[1]
assert pytest.approx(vS[2], abs=1e-3) == 6.0
assert pytest.approx(np.linalg.norm(vS - vO), rel=1e-3) == 6.0
# Validate with GeometryValidator
validator = GeometryValidator()
val_res = validator.validate(result, constraints, is_3d)
assert val_res.is_valid, f"Validation failed: {val_res.errors}"
def test_3d_prism_canonical():
"""Tests 3D Triangular Prism ABC.DEF with side 5, height 8."""
dsl = """
PRISM(ABC_DEF)
EQUILATERAL_TRIANGLE(ABC, 5)
EQUILATERAL_TRIANGLE(DEF, 5)
LENGTH(AD, 8)
"""
parser = DSLParser()
points, constraints, is_3d = parser.parse(dsl)
assert is_3d
engine = GeometryEngine()
result = engine.solve(points, constraints, is_3d)
assert result is not None
coords = result["coordinates"]
# Base 1 on z=0
for p in ["A", "B", "C"]:
assert pytest.approx(coords[p][2], abs=1e-3) == 0.0
# Base 2 on z=8
for p in ["D", "E", "F"]:
assert pytest.approx(coords[p][2], abs=1e-3) == 8.0
validator = GeometryValidator()
val_res = validator.validate(result, constraints, is_3d)
assert val_res.is_valid, f"Validation failed: {val_res.errors}"
def test_geometric_constraints_midpoint_section_point_on():
"""Tests MIDPOINT, SECTION, and POINT_ON constraints."""
dsl = """
POINT(A, 0, 0)
POINT(B, 10, 0)
POINT(M)
MIDPOINT(M, AB)
POINT(E)
SECTION(E, A, B, 0.3)
POINT(P)
POINT_ON(P, AB)
LENGTH(AP, 7)
"""
parser = DSLParser()
points, constraints, is_3d = parser.parse(dsl)
engine = GeometryEngine()
result = engine.solve(points, constraints, is_3d)
assert result is not None
coords = result["coordinates"]
assert pytest.approx(coords["M"][0], abs=1e-3) == 5.0
assert pytest.approx(coords["E"][0], abs=1e-3) == 3.0
assert pytest.approx(coords["P"][0], abs=1e-3) == 7.0
validator = GeometryValidator()
val_res = validator.validate(result, constraints, is_3d)
assert val_res.is_valid, f"Validation failed: {val_res.errors}"
# ============================================================================
# 2. GEOMETRY VALIDATOR REJECTION TESTS
# ============================================================================
def test_validator_detects_length_violation():
"""Validator should reject coordinates when length constraint is violated."""
engine_result = {
"coordinates": {
"A": [0.0, 0.0, 0.0],
"B": [10.0, 0.0, 0.0],
},
"drawing_phases": [{"phase": 1, "points": ["A", "B"], "segments": [["A", "B"]]}],
}
# Expected length 5, actual is 10
constraints = [Constraint(type="length", targets=["A", "B"], value=5.0)]
validator = GeometryValidator(tolerance=0.05)
val_res = validator.validate(engine_result, constraints, is_3d=False)
assert not val_res.is_valid
assert any("Length constraint violated" in err for err in val_res.errors)
def test_validator_detects_perpendicularity_violation():
"""Validator should reject non-orthogonal vectors for perpendicular constraint."""
engine_result = {
"coordinates": {
"A": [0.0, 0.0, 0.0],
"B": [1.0, 0.0, 0.0],
"C": [0.0, 0.0, 0.0],
"D": [1.0, 1.0, 0.0], # 45 deg angle, not 90 deg
},
"drawing_phases": [],
}
constraints = [Constraint(type="perpendicular", targets=["A", "B", "C", "D"], value=0)]
validator = GeometryValidator(tolerance=0.05)
val_res = validator.validate(engine_result, constraints, is_3d=False)
assert not val_res.is_valid
assert any("Perpendicularity violated" in err for err in val_res.errors)
def test_validator_detects_degenerate_pyramid():
"""Validator should reject a 3D pyramid with collapsed coplanar apex."""
engine_result = {
"coordinates": {
"S": [0.5, 0.5, 0.0], # Apex on same plane as base
"A": [0.0, 0.0, 0.0],
"B": [1.0, 0.0, 0.0],
"C": [1.0, 1.0, 0.0],
"D": [0.0, 1.0, 0.0],
},
"solids": [{"type": "pyramid", "apex": "S", "base": ["A", "B", "C", "D"]}],
"drawing_phases": [],
}
validator = GeometryValidator()
val_res = validator.validate(engine_result, [], is_3d=True)
assert not val_res.is_valid
assert any("coplanar with base" in err for err in val_res.errors)
# ============================================================================
# 3. VISUALIZATIONSPEC & CONFIGURATION TESTS
# ============================================================================
def test_visualization_spec_show_axes_and_presentation_config():
"""Tests VisualizationSpec separation of geometry vs presentation config."""
geometry_data = {
"problem": "Hình chóp tam giác S.ABC",
"coordinates": {
"S": [0.0, 0.0, 4.0],
"A": [0.0, 0.0, 0.0],
"B": [3.0, 0.0, 0.0],
"C": [1.5, 2.5, 0.0],
},
"solids": [{"type": "tetrahedron", "apex": "S", "base": ["A", "B", "C"], "points": ["S", "A", "B", "C"]}],
"solution": {"steps": ["Bước 1: Dựng đáy ABC", "Bước 2: Dựng đỉnh S"]},
"is_3d": True,
"show_axes": True,
"quality": "1080p",
}
spec = build_visualization_spec(geometry_data)
# Verify presentation config
assert spec.config.show_axes is True
assert spec.config.is_3d is True
assert spec.config.quality == "1080p"
assert spec.show_axes is True
# Verify mathematical geometry preserved
assert len(spec.geometry) >= 4
point_s = next(g for g in spec.geometry if g.label == "S")
assert point_s.properties["coordinates"] == [0.0, 0.0, 4.0]
# Verify prompt includes show_axes directive
prompt = spec.to_prompt()
assert "show_axes=True" in prompt
def test_visualization_spec_backward_compatibility():
"""Tests backward compatibility with default show_axes and output_config."""
spec = build_visualization_spec(
problem_text="Tính diện tích tam giác",
coordinates={"A": [0, 0], "B": [4, 0], "C": [0, 3]},
is_3d=False,
)
assert spec.config.show_axes is False
assert spec.show_axes is False
assert spec.output_config.format == "mp4"
# ============================================================================
# 4. MANIM CLIENT & LIFECYCLE TESTS
# ============================================================================
@pytest.mark.asyncio
async def test_manim_client_successful_lifecycle():
"""Tests successful lifecycle transitions: queued -> rendering -> completed."""
client = ManimClient(base_url="http://mock-manim:8001")
spec = build_visualization_spec("Test problem")
with patch("httpx.AsyncClient.post") as mock_post, patch("httpx.AsyncClient.get") as mock_get:
# 1. Submit job -> returns queued
mock_post.return_value = MagicMock(
status_code=200,
json=lambda: {"job_id": "test-uuid-123", "status": "queued"},
)
resp = await client.submit_render_job(spec)
assert resp.status == "queued"
assert resp.job_id == "test-uuid-123"
# 2. Status polling -> generating -> rendering -> completed
call_count = 0
def mock_status():
nonlocal call_count
call_count += 1
if call_count == 1:
return {"job_id": "test-uuid-123", "status": "generating"}
elif call_count == 2:
return {"job_id": "test-uuid-123", "status": "rendering"}
else:
return {
"job_id": "test-uuid-123",
"status": "completed",
"video_url": "https://cdn.example.com/video.mp4",
}
mock_get.return_value = MagicMock(
status_code=200,
json=mock_status,
)
completed_resp = await client.poll_job_completion("test-uuid-123", timeout=10.0, poll_interval=0.01)
assert completed_resp.status == "completed"
assert completed_resp.video_url == "https://cdn.example.com/video.mp4"
assert completed_resp.is_terminal() is True
@pytest.mark.asyncio
async def test_manim_client_unavailable_structured_error():
"""When Manim server is unreachable, returns terminal failed with MANIM_UNAVAILABLE."""
import httpx
client = ManimClient(base_url="http://unreachable-host:9999")
spec = build_visualization_spec("Test problem")
with patch("httpx.AsyncClient.post", side_effect=httpx.ConnectError("Connection refused")):
resp = await client.submit_render_job(spec)
assert resp.status == "failed"
assert resp.get_error_code() == ErrorCode.MANIM_UNAVAILABLE
assert "không khả dụng" in (resp.get_error_message() or "")
@pytest.mark.asyncio
async def test_manim_client_polling_timeout_terminal_failed():
"""When polling times out, returns terminal failed with MANIM_TIMEOUT (no hanging)."""
client = ManimClient(base_url="http://mock-manim:8001")
with patch("httpx.AsyncClient.get") as mock_get:
mock_get.return_value = MagicMock(
status_code=200,
json=lambda: {"job_id": "slow-job", "status": "rendering"},
)
resp = await client.poll_job_completion("slow-job", timeout=0.05, poll_interval=0.01)
assert resp.status == "failed"
assert resp.get_error_code() == ErrorCode.MANIM_TIMEOUT
assert resp.is_terminal() is True
@pytest.mark.asyncio
async def test_manim_client_404_job_not_found():
"""When job status returns HTTP 404, returns JOB_NOT_FOUND error code."""
client = ManimClient(base_url="http://mock-manim:8001")
with patch("httpx.AsyncClient.get") as mock_get:
mock_get.return_value = MagicMock(
status_code=404,
text="Not Found",
)
resp = await client.get_job_status("nonexistent-job")
assert resp.status == "failed"
assert resp.get_error_code() == ErrorCode.JOB_NOT_FOUND
@pytest.mark.asyncio
async def test_manim_client_render_failed_structured_error():
"""When render job fails on server, returns MANIM_RENDER_FAILED error code."""
client = ManimClient(base_url="http://mock-manim:8001")
with patch("httpx.AsyncClient.get") as mock_get:
mock_get.return_value = MagicMock(
status_code=200,
json=lambda: {
"job_id": "failed-job",
"status": "failed",
"error": "Manim compilation syntax error at line 42",
},
)
resp = await client.get_job_status("failed-job")
assert resp.status == "failed"
assert resp.get_error_code() == ErrorCode.MANIM_RENDER_FAILED
assert "Manim compilation" in (resp.get_error_message() or "")
|