Files
metin2-client/scripts/test_xxf_all.py

255 lines
14 KiB
Python

#!/usr/bin/env python3
"""Local CH5 regression orchestrator. Never deploys, connects to a game server or grants release readiness."""
import argparse
import concurrent.futures
import hashlib
import importlib.util
import json
import os
from pathlib import Path
import signal
import subprocess
import sys
import tempfile
import time
import unittest
ROOT = Path(__file__).resolve().parents[1]
MARKER = 'CH5_TEST_RESULT='
# File-level associations, not claims that every behavior of a feature is tested.
ASSOCIATIONS = {
'F01': ['test_feature_manifest', 'test_model_preview'],
'F02': ['test_queries', 'test_drops'],
'F03': ['test_target_element'], 'F04': ['test_trade_level', 'test_trade_level_ui'], 'F05': [], 'F06': [], 'F07': [], 'F08': [],
'F09': ['test_special_storage', 'test_legacy_item_ids', 'test_inventory_pages'],
'F10': ['test_channel', 'test_native_channel', 'test_ava2_channel_registry', 'test_live_endpoint'],
'F11': ['test_catalogue', 'test_chest', 'test_ava2_chest', 'test_pickup', 'test_ava2_pickup', 'test_drops', 'test_queries'],
'F12': ['test_attr_lock', 'test_attr_lock_snapshots', 'test_attr_lock_ui', 'test_attr_lock_use', 'test_attr_lock_views', 'test_switchbot', 'test_switchbot_matching'],
'F13': ['test_sash'], 'F14': ['test_pendant', 'test_applies'],
'F15': ['test_costume_slots', 'test_mount', 'test_product_costume_runtime', 'test_costume_products', 'test_costume_attr'],
'F16': ['test_shop_appearance'], 'F17': ['test_extended_items'],
'F18': ['test_extended_items'], 'F19': ['test_quiver', 'test_quiver_runtime', 'test_quiver_sync', 'test_quiver_motion', 'test_quiver_assets', 'test_quiver_staging'],
'F20': ['test_magic_reduction'], 'F21': ['test_cube_gold_debit', 'test_cube_catalog', 'test_cube_batch', 'test_cube_fence', 'test_cube_db_guards', 'test_cube_runtime', 'test_sql_fence_router', 'test_cube_handshake', 'test_cube_mutation', 'test_cube_gold', 'test_cube_outbox', 'test_cube_source', 'test_cube_owner', 'test_cube_recovery', 'test_cube_image', 'test_cube_craft', 'test_cube_presentation', 'test_cube_restore', 'test_cube_resume'],
'F22': ['test_dragonsoul_alchemy'], 'F23': ['test_dragonsoul_alchemy'],
'F24': ['test_rank', 'test_rank_runtime'], 'F25': [],
'F26': ['test_ticket_shop', 'test_ava2_ticket_shop', 'test_gaya_market', 'test_gaya_runtime', 'test_gaya_catalog'],
'F27': ['test_offline_search_names', 'test_offline_shop', 'test_offlineshop'],
'F28': ['test_offline_shop', 'test_offlineshop', 'test_shop_economy_runtime', 'test_economy_reconcile', 'test_economy_coordinator'],
'F29': ['test_gold64', 'test_economy', 'test_economy_game_ui', 'test_economy_view', 'test_economy_reconcile'],
'F30': [], 'F31': [], 'F32': [], 'F33': [],
'F34': ['test_pet_system', 'test_pet_commands_runtime', 'test_rare_attrs_and_skills'],
'F35': ['test_battlepass', 'test_calendar', 'test_boss', 'test_bosses', 'test_track_config', 'test_ava2_track', 'test_ava2_dungeon_track', 'test_native_track', 'test_timers'],
}
def sha(path):
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def child(path, arguments=()):
"""Import in its own process: supports unittest classes AND legacy top-level probes."""
path = Path(path).resolve()
sys.argv = [str(path), *arguments] # never leak the orchestrator's --child option
sys.path.insert(0, str(path.parent))
spec = importlib.util.spec_from_file_location('ch5_isolated_test', path)
mod = importlib.util.module_from_spec(spec)
sys.modules[spec.name] = mod
spec.loader.exec_module(mod)
suite = unittest.defaultTestLoader.loadTestsFromModule(mod)
result = unittest.TextTestRunner(verbosity=2).run(suite)
details = dict(tests=result.testsRun, skipped=len(result.skipped),
failures=len(result.failures), errors=len(result.errors),
mode='unittest' if result.testsRun else 'top_level_script_exit_only',
skip_reasons=[reason for _, reason in result.skipped])
print(MARKER + json.dumps(details), flush=True)
return 0 if result.wasSuccessful() else 1
def discover(root=ROOT, server=None, ava2_game_source=None):
server = server or root.parent / 'metin2-server'
groups = {'client': [root / 'tests/wiki'],
'server': [server / 'tests/features', server / 'tests/wiki'],
'data': [root / 'tools/server/ava2-items/tests',
root / 'tools/server/biolog/tests', root / 'tools/server/ring-warp/tests'],
'runner': [root / 'tests/ch5']}
jobs = []
for group, folders in groups.items():
for folder in folders:
for path in sorted(folder.glob('test_*.py')):
job = dict(id=group + ':' + str(path.relative_to(root if group != 'server' else server)),
suite=group, path=str(path), stem=path.stem,
cwd=str(root if group != 'server' else server), arguments=[])
if path == root / 'tools/server/biolog/tests/test_combat.py':
job['arguments'] = [str(server / 'src/server/game/src/battle.cpp')]
elif path == root / 'tools/server/ring-warp/tests/test_ring.py':
job['arguments'] = [str(server / 'src/server/liblua')]
elif path == root / 'tools/server/biolog/tests/test_ava2.py':
if ava2_game_source:
job['arguments'] = [str(ava2_game_source)]
else:
job['blocked_reason'] = 'Needs original AVA2 game source: --ava2-game-source (constants.cpp and cmd_general.cpp)'
jobs.append(job)
return jobs
def execute(job, output, timeout):
started = time.monotonic()
log = output / (hashlib.sha256(job['id'].encode()).hexdigest()[:16] + '.log')
result = dict(job, log=log.name, test_sha256=sha(job['path']))
if job.get('blocked_reason'):
log.write_text(job['blocked_reason'] + '\n')
result.update(status='blocked', seconds=0)
return result
with log.open('wb') as stream:
try:
env = dict(os.environ, PYTHONUNBUFFERED='1', PYTHONDONTWRITEBYTECODE='1')
command = [sys.executable, str(Path(__file__).resolve()), '--child', job['path'],
'--child-args', json.dumps(job.get('arguments', []))]
result['command'] = command
proc = subprocess.Popen(command,
cwd=job['cwd'], stdout=stream, stderr=subprocess.STDOUT,
env=env, start_new_session=True)
try:
code = proc.wait(timeout=timeout)
except subprocess.TimeoutExpired:
os.killpg(proc.pid, signal.SIGKILL)
proc.wait()
result.update(status='timeout', returncode=proc.returncode)
else:
result.update(status='pass' if code == 0 else 'fail', returncode=code)
except OSError as exc:
result.update(status='error', error=str(exc))
raw = log.read_text(errors='replace')
for line in reversed(raw.splitlines()):
if line.startswith(MARKER):
result['details'] = json.loads(line[len(MARKER):])
if result['status'] == 'pass' and result['details']['skipped']:
result['status'] = 'partial' # unittest's exit 0 may hide skipped native probes
break
if result['status'] == 'pass' and 'details' not in result:
result['status'] = 'unverified' # premature sys.exit(0) is not accepted as test evidence
result['seconds'] = round(time.monotonic() - started, 3)
return result
def feature_results(features, results):
out = []
for feature in features:
fid = feature['id']
linked = [r for r in results if r['stem'] in ASSOCIATIONS.get(fid, [])]
statuses = {r['status'] for r in linked}
local = ('fail' if statuses & {'fail', 'timeout', 'error'} else
'partial' if statuses & {'partial', 'unverified', 'blocked'} else
'related_tests_pass' if linked else 'not_covered')
out.append(dict(id=fid, name=feature['name'], local=local,
related_tests=[r['id'] for r in linked],
implementation=feature['status']['implementation'],
behavior_acceptance='pending', live='not_run', android_device='not_run',
release_ready=False))
return out
def snapshot(repo):
def git(*args):
return subprocess.check_output(['git', '-C', str(repo), *args], stderr=subprocess.DEVNULL)
try:
status = git('status', '--porcelain=v1', '-uall').decode(errors='replace')
untracked = git('ls-files', '--others', '--exclude-standard', '-z').split(b'\0')
# Bind source changes including new files, without hashing multi-GB resource packs.
hashes = {os.fsdecode(p): sha(repo / os.fsdecode(p)) for p in untracked if p
and (repo / os.fsdecode(p)).is_file()
and Path(os.fsdecode(p)).suffix in {'.py', '.cpp', '.h', '.inc', '.json', '.md'}}
return dict(head=git('rev-parse', 'HEAD').decode().strip(), status=status,
diff_sha256=hashlib.sha256(git('diff', 'HEAD', '--binary')).hexdigest(),
untracked_source_sha256=hashes)
except (OSError, subprocess.CalledProcessError):
return dict(error='git snapshot unavailable')
def render(report):
lines = ['# 五区自动回归报告', '',
'这是本地回归结果,不是全部功能、真服或 Android 验收结论。', '',
f"本地汇总:{json.dumps(report['summary'], ensure_ascii=False)}", '',
'| 功能 | 关联本地测试 | 真服 | Android | 可发布 |',
'| --- | --- | --- | --- | --- |']
for f in report['features']:
lines.append(f"| {f['id']} {f['name']} | {f['local']} | 未测 | 未测 | 否 |")
lines += ['', '## 非通过测试', '']
for r in report['results']:
if r['status'] != 'pass':
lines.append(f"- {r['id']}: {r['status']},日志 [{r['log']}]({r['log']})")
lines += ['', '全部测试的命令、耗时、跳过原因和源码快照见 report.json。',
'未覆盖表示没有登记的直接关联测试;关联测试通过也不代表该功能完整通过。', '']
return '\n'.join(lines)
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--child', help=argparse.SUPPRESS)
parser.add_argument('--child-args', default='[]', help=argparse.SUPPRESS)
parser.add_argument('--suite', action='append', choices=['client', 'server', 'data', 'runner'])
parser.add_argument('--jobs', type=int, default=2)
parser.add_argument('--timeout', type=float, default=180)
parser.add_argument('--server-root', type=Path, default=ROOT.parent / 'metin2-server')
parser.add_argument('--ava2-game-source', type=Path, help='Original AVA2 game/src for biology source comparison (optional)')
parser.add_argument('--output', type=Path, help='New directory only; existing directories are never overwritten')
parser.add_argument('--list', action='store_true')
parser.add_argument('--require-complete', action='store_true', help='Exit 2 when any full acceptance gate is pending')
args = parser.parse_args(argv)
if args.child:
return child(args.child, json.loads(args.child_args))
if args.jobs < 1 or args.timeout <= 0:
parser.error('jobs and timeout must be positive')
jobs = discover(server=args.server_root.resolve(),
ava2_game_source=args.ava2_game_source.resolve() if args.ava2_game_source else None)
selected = set(args.suite or ['client', 'server', 'data', 'runner'])
jobs = [j for j in jobs if j['suite'] in selected]
missing = selected - {j['suite'] for j in jobs}
if missing:
parser.error('missing test suites: ' + ', '.join(sorted(missing)))
if args.list:
for j in jobs:
print(j['id'])
return 0
manifest = ROOT / 'audit/xxf-ch5/features.json'
features = json.loads(manifest.read_text())['features']
if {f['id'] for f in features} != set(ASSOCIATIONS) or len(features) != len(ASSOCIATIONS):
parser.error('feature manifest changed; update explicit coverage mapping first')
if args.output:
output = args.output.resolve()
output.mkdir(parents=True, exist_ok=False)
else:
parent = ROOT / 'build/ch5-tests'
parent.mkdir(parents=True, exist_ok=True)
output = Path(tempfile.mkdtemp(prefix=time.strftime('%Y%m%d-%H%M%S-'), dir=parent))
before = {str(p): snapshot(p) for p in [ROOT, args.server_root.resolve()]}
results = []
print('Report directory:', output, flush=True)
with concurrent.futures.ThreadPoolExecutor(max_workers=args.jobs) as pool:
pending = [pool.submit(execute, j, output, args.timeout) for j in jobs]
for future in concurrent.futures.as_completed(pending):
result = future.result()
results.append(result)
print(f"[{len(results)}/{len(jobs)}] {result['status']}: {result['id']}", flush=True)
results.sort(key=lambda r: r['id'])
after = {str(p): snapshot(p) for p in [ROOT, args.server_root.resolve()]}
summary = {s: sum(r['status'] == s for r in results)
for s in ['pass', 'partial', 'fail', 'timeout', 'error', 'unverified', 'blocked']}
report = dict(schema_version=1, manifest_sha256=sha(manifest), results=results,
summary=summary, features=feature_results(features, results),
source_before=before, source_after=after, source_changed=before != after,
release_ready=False, scope='local regression only; no native build, live or device acceptance')
(output / 'report.json').write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n')
(output / 'report.md').write_text(render(report))
print(json.dumps(summary), '\nReport:', output / 'report.md')
if any(summary[s] for s in ['fail', 'timeout', 'error']) or before != after:
return 1
if args.require_complete:
return 2
return 0
if __name__ == '__main__':
sys.exit(main())