Files
EVEngine/scripts/tests/test_resource_format_suite.py
西风逍遥游 31880f0021 feat(examples): gate examples in CI and make repository scripts UTF-8 on every host
`examples/<name>/` was a tested surface in name only. The source-quality job had
no examples check at all, and scripts/smoke_examples.sh accepted any process that
had not printed one of its error markers: a project that died during startup,
exited after a single frame, or crashed without a marker was reported as PASS.
Nothing stopped a malformed or unregistered example from reaching dev, which is
how 14 examples arrived without READMEs and 20 were never registered in the
overview table.

Source side
- scripts/check_examples.py classifies every directory under examples/ as either
  runnable (main.nut plus a config.nut that assigns the engine `config` table) or
  as a reviewed non-runnable sample listed in NON_RUNNABLE_EXAMPLES with a
  reason. Both kinds must own a README.md and appear in examples/README.md.
  Stale exemptions and overview links to missing directories fail as well.
- `make check/examples` and a new source-quality CI step run the gate.
- scripts/tests/test_check_examples.py covers it and pins each failure mode
  against fixtures.

Runtime side
- scripts/smoke_examples.sh now enforces liveness, not just marker absence: every
  runnable example must still be running after MIN_RUN_SECONDS (default 2s; CI
  passes 2s), and a process that dies inside that window fails whatever its exit
  code. A clean self-exit after the window passes with an explicit note instead
  of being silently accepted as a pass.
- The Linux CI step sets MIN_RUN_SECONDS=2 and keeps RUN_SECONDS=6, so the job's
  wall clock is unchanged (13.7 min of its 20 min budget on dev).

Windows / GBK
- scripts/utf8_stdio.py re-encodes stdout/stderr as UTF-8 and every scripts/*.py
  program calls it as the first statement of its __main__ block. On a Chinese
  Windows a redirected stream falls back to the ANSI code page (cp936), and
  printing a character that code page cannot encode (arrows, superscripts, bullet
  separators, emoji - all common in this repository) raised UnicodeEncodeError
  and turned a checker into a traceback.
- The mirror image is input: read_text() without encoding= decoded UTF-8
  repository text as cp936 and raised UnicodeDecodeError.
- scripts/tests/test_utf8_stdio.py enforces both conventions for every script and
  test module; text file I/O and child-process decoding now pass encoding="utf-8"
  explicitly.
- Unit-test invocations run with `python3 -X utf8` so the runner's own output
  never follows the host code page.

Violations the new gates found on top of dev, fixed here: 14 examples shipped
without a README (fluid3d, mesh-impact-lab, mesh-modifier-lab, spline-tube-lab on
the earlier dev tip, plus pcg-depth-of-field, pcg-detail-overwrite,
pcg-layer-culling, pcg-location-system, pcg-runtime-orchestration,
pcg-scene-player-culling, pcg-snow-wind, pcg-thunder-strike, pcg-ui-scaler and
pcg-underwater added by #397), 20 were missing from the overview table (those 14
plus archspace-editor, geometry-stroke-lab, interior-mapping, layered-animation,
triplanar-decal, terrain-stamping), and scripts/export_meshret_onnx.py had no
UTF-8 stdio guard.

Verified locally: `python -m ruff check scripts` (All checks passed);
scripts/check_test_manifest.py; scripts/check_quality_metadata.py;
scripts/check_architecture_contracts.py --base HEAD; scripts/check_nodiscard.py;
`make -n check/examples`; scripts/check_examples.py (125 examples: 118 runnable,
7 reviewed non-runnable); and `python -X utf8 -m unittest discover -s scripts/tests
-p "test_*.py"` (155 tests, OK). The runtime half of the contract needs a Linux
headless build, so it is verified by the CI examples smoke step rather than
locally.
2026-09-15 20:20:23 +08:00

118 lines
5.7 KiB
Python

import importlib.util
import json
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
from unittest.mock import patch
ROOT = Path(__file__).parents[2]
# Loading a script by path bypasses the normal sys.path entry for its directory,
# so its own sibling imports (utf8_stdio) only resolve if the test puts that
# directory on sys.path itself.
sys.path.insert(0, str(ROOT / "scripts"))
SPEC = importlib.util.spec_from_file_location("suite", Path(__file__).parents[1] / "resource_format_suite.py")
suite = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(suite)
class ResourceSuiteTests(unittest.TestCase):
def invoke(self, extra):
with tempfile.TemporaryDirectory() as directory:
report = Path(directory) / "report.json"
with patch.object(sys, "argv", ["suite", "--family", "font", "--report", str(report)] + extra):
code = suite.main()
return code, json.loads(report.read_text(encoding="utf-8"))
def test_inventory_is_not_execution(self):
code, report = self.invoke([])
self.assertEqual(code, 0)
self.assertEqual(report["status"], "not-run")
def test_missing_cases_fail_before_execution(self):
with patch.object(suite.subprocess, "run", return_value=subprocess.CompletedProcess([], 0, '{"tests": []}', '')) as run:
code, report = self.invoke(["--build-dir", "/unused"])
self.assertEqual(code, 1)
self.assertTrue(report["missing_registrations"])
self.assertEqual(run.call_count, 1)
def test_failed_runtime_is_not_green(self):
names = suite.inventory()["font"]["tests"]
listing = json.dumps({"tests": [{"name": n} for n in names]})
with patch.object(suite.subprocess, "run", side_effect=[subprocess.CompletedProcess([], 0, listing, ''), subprocess.CompletedProcess([], 8, 'failure', '')]):
code, report = self.invoke(["--build-dir", "/unused"])
self.assertEqual(code, 8)
self.assertEqual(report["status"], "failed")
def test_disabled_test_is_not_success(self):
listing = {"tests": [{"name": "example", "properties": [{"name": "DISABLED", "value": True}]}]}
with patch.object(suite.subprocess, "run", return_value=subprocess.CompletedProcess([], 0, json.dumps(listing), '')) as run:
code, report = suite.run_cases(Path("/unused"), ["example"])
self.assertEqual(code, 1)
self.assertEqual(report["disabled_tests"], ["example"])
self.assertEqual(run.call_count, 1)
def real_ctest(self, script, properties=""):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
(root / "case.py").write_text(script, encoding="utf-8")
(root / "CTestTestfile.cmake").write_text(
f'add_test(example "{Path(sys.executable).as_posix()}" "{(root / "case.py").as_posix()}")\n' + properties,
encoding="utf-8")
return suite.run_cases(root, ["example"])
def test_real_ctest_success_has_per_case_evidence(self):
code, report = self.real_ctest("print('assertions passed')")
self.assertEqual(code, 0)
self.assertEqual(report["results"][0]["status"], "passed")
def test_real_ctest_zero_exit_with_assertion_log_is_failure(self):
code, report = self.real_ctest("print('ERROR Assertion Failed: pixels differ')")
self.assertNotEqual(code, 0)
self.assertEqual(report["results"][0]["status"], "failed")
def test_real_ctest_skip_is_not_pass(self):
code, report = self.real_ctest("raise SystemExit(77)",
"set_tests_properties(example PROPERTIES SKIP_RETURN_CODE 77)\n")
self.assertNotEqual(code, 0)
self.assertEqual(report["results"][0]["status"], "skipped")
def test_missing_junit_cannot_pass(self):
listing = json.dumps({"tests": [{"name": "example"}]})
with patch.object(suite.subprocess, "run", side_effect=[
subprocess.CompletedProcess([], 0, listing, ''),
subprocess.CompletedProcess([], 0, 'success without evidence', '')]):
code, report = suite.run_cases(Path("/unused"), ["example"])
self.assertEqual(code, 1)
self.assertEqual(report["results"][0]["status"], "missing-result")
def test_fixture_tampering_is_detected(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
fixtures = root / "test/fixtures/resource_formats"
fixtures.mkdir(parents=True)
(fixtures / "manifest.json").write_text(json.dumps({
"schema": "evengine.resource-format-fixtures", "version": 1,
"sha256": {"pattern.png": "0" * 64}}), encoding="utf-8")
(fixtures / "pattern.png").write_bytes(b"modified bytes")
self.assertEqual(suite.fixture_errors(root), ["pattern.png"])
def test_vrm_routing_has_real_import_contract(self):
groups = suite.inventory()
self.assertIn('.vrm', groups['model']['advertised_resource_extensions'])
self.assertEqual(groups['model']['tests']['avatar.vrm.importMorphGazeSpringAndRollback'],
'test/avatar_vrm_vulkan.cpp')
rows = suite.format_coverage(groups, [])
vrm = next(row for row in rows if row['id'] == 'model.vrm')
self.assertEqual(vrm['importTests'], ['avatar.vrm.importMorphGazeSpringAndRollback'])
self.assertEqual(vrm['importStatus'], 'not-run')
self.assertEqual(vrm['exportStatus'], 'coverage-missing')
def test_extensions_include_uncovered_routing(self):
self.assertIn(".dae", suite.inventory()["model"]["advertised_resource_extensions"])
if __name__ == "__main__":
unittest.main()