chore(project): 统一回归入口并清理审评遗留问题
This commit is contained in:
+177
@@ -0,0 +1,177 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build and run the repository's independent checks; GUI/network checks are opt-in."""
|
||||
import argparse
|
||||
import os
|
||||
import signal
|
||||
from pathlib import Path
|
||||
import plistlib
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
CORE = sorted(str(p.relative_to(ROOT)) for folder in ("Models", "Monitors", "Services", "Extensions")
|
||||
for p in (ROOT / "kymo/Core" / folder).glob("*.swift"))
|
||||
CHECKS = {name: list(CORE) for name in (
|
||||
"SamplingChecks", "SamplingIntervalChecks", "UnifiedPanelChecks", "MemoryChecks",
|
||||
"GPUStatisticsChecks", "StageCChecks", "MachPortChecks")}
|
||||
CHECKS.update({
|
||||
"TrendScrollChecks": CORE + ["kymo/UI/Charts/TrendScroll.swift"],
|
||||
"CPUCoreGridChecks": ["kymo/Features/MenuBar/CPUCoreGrid.swift", "kymo/Core/Services/CPUCoreTopology.swift",
|
||||
"kymo/Core/Extensions/MetricFormat.swift", "kymo/UI/Components/MetricProgressBar.swift"],
|
||||
"CPUTemperatureChecks": ["kymo/Core/Monitors/CPUTemperatureMonitor.swift"],
|
||||
"DiskHealthChecks": ["kymo/Core/Models/DiskHealthMetrics.swift", "kymo/Core/Monitors/DiskHealthReport.swift"],
|
||||
"PublicIPAddressChecks": ["kymo/Core/Services/PublicIPAddressService.swift"],
|
||||
"ProcessSelectionChecks": ["kymo/Core/Models/ProcessMetrics.swift", "kymo/Features/MenuBar/ProcessTableProjection.swift"],
|
||||
"PanelLayoutChecks": ["kymo/Core/Models/ProcessMetrics.swift", "kymo/Features/MenuBar/PanelLayout.swift",
|
||||
"kymo/Features/MenuBar/ProcessTableProjection.swift"],
|
||||
"PanelCurveChecks": ["kymo/UI/Charts/PanelCurveGeometry.swift", "kymo/UI/Charts/PanelCurveFrame.swift"],
|
||||
"FanChecks": ["kymo/Core/Models/FanMetrics.swift", "kymo/Core/Monitors/CPUTemperatureMonitor.swift",
|
||||
"kymo/UI/Components/FanSpeedIndicator.swift", "kymo/UI/Components/AnimatedMetricText.swift"],
|
||||
"KeepAwakeChecks": ["kymo/Core/Services/KeepAwakeService.swift"],
|
||||
"LocalizationChecks": ["kymo/Core/Services/LanguagePreferences.swift", "kymo/UI/Components/AppLocalization.swift"],
|
||||
"CodeIdentityChecks": ["kymo/Core/Services/CodeIdentity.swift"],
|
||||
"PanelAssetChecks": [],
|
||||
"PresentationChecks": ["kymo/Core/Services/AppearancePreferences.swift", "kymo/Core/Services/LanguagePreferences.swift",
|
||||
"kymo/UI/Components/AppearanceStyle.swift", "kymo/UI/Components/DetailPlacement.swift",
|
||||
"kymo/UI/Components/AppLocalization.swift"],
|
||||
"LanguageScopeChecks": ["kymo/Core/Services/LanguagePreferences.swift", "kymo/UI/Components/AppLanguageScope.swift"],
|
||||
"SettingsWindowChecks": ["kymo/Core/Services/SettingsPresentation.swift", "kymo/Features/Settings/SettingsWindowLifecycle.swift"],
|
||||
"PanelWindowChecks": ["kymo/Features/MenuBar/MenuPanelController.swift", "kymo/Features/MenuBar/PanelLayout.swift",
|
||||
"kymo/UI/Components/IntervalControl.swift"],
|
||||
"SandboxNetworkChecks": [],
|
||||
})
|
||||
GUI = {"LanguageScopeChecks", "SettingsWindowChecks", "PanelWindowChecks"}
|
||||
NETWORK = {"SandboxNetworkChecks"}
|
||||
|
||||
|
||||
def run(command, *, timeout=120):
|
||||
result = subprocess.run([str(v) for v in command], cwd=ROOT, capture_output=True, text=True, timeout=timeout)
|
||||
if result.stdout.strip():
|
||||
print(result.stdout.strip(), flush=True)
|
||||
if result.returncode:
|
||||
raise RuntimeError(f"{' '.join(map(str, command))}\n{result.stderr[-8000:]}")
|
||||
if result.stderr.strip():
|
||||
print(result.stderr.strip(), flush=True)
|
||||
return result
|
||||
|
||||
|
||||
def entitlements(app):
|
||||
result = subprocess.run(["codesign", "-d", "--entitlements", ":-", str(app)], capture_output=True, check=True)
|
||||
value = plistlib.loads(result.stdout)
|
||||
for key in ("com.apple.security.app-sandbox", "com.apple.security.network.client"):
|
||||
if value.get(key) is not True:
|
||||
raise RuntimeError(f"Missing built entitlement: {key}")
|
||||
print("PASS: built host has sandbox and network client entitlements", flush=True)
|
||||
return value
|
||||
|
||||
|
||||
def test_bundle(work, name, executable, host_entitlements=None):
|
||||
app = work / (name + ".app")
|
||||
contents = app / "Contents"
|
||||
(contents / "MacOS").mkdir(parents=True)
|
||||
shutil.copy2(executable, contents / "MacOS" / name)
|
||||
(contents / "Info.plist").write_bytes(plistlib.dumps({
|
||||
"CFBundleIdentifier": "cn.airnan.kymo.checks." + uuid.uuid4().hex,
|
||||
"CFBundleExecutable": name, "CFBundlePackageType": "APPL",
|
||||
"LSUIElement": name in {"PanelWindowChecks", "SandboxNetworkChecks"},
|
||||
}))
|
||||
command = ["codesign", "--force", "--sign", "-"]
|
||||
if host_entitlements:
|
||||
path = work / "network.entitlements"
|
||||
path.write_bytes(plistlib.dumps(host_entitlements))
|
||||
command += ["--entitlements", path]
|
||||
run(command + [app])
|
||||
return app
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--app", type=Path, help="Use an already built app instead of building")
|
||||
parser.add_argument("--configuration", choices=["Debug", "Release"], default="Debug")
|
||||
parser.add_argument("--gui", action="store_true", help="Also launch temporary native test apps")
|
||||
parser.add_argument("--network", action="store_true", help="Also make a real sandboxed HTTPS request")
|
||||
parser.add_argument("--only", nargs="+", choices=sorted(CHECKS), help="Run selected Swift checks")
|
||||
parser.add_argument("--list", action="store_true")
|
||||
args = parser.parse_args()
|
||||
unknown = {p.stem for p in (ROOT / "kymoTests").glob("*.swift")} - CHECKS.keys()
|
||||
if unknown:
|
||||
parser.error("Checks missing from runner: " + ", ".join(sorted(unknown)))
|
||||
if args.list:
|
||||
for name in sorted(CHECKS):
|
||||
print(name + (" [GUI]" if name in GUI else " [network]" if name in NETWORK else ""))
|
||||
return
|
||||
requested = args.only or list(CHECKS)
|
||||
selected = []
|
||||
for name in requested:
|
||||
disabled = (name in GUI and not args.gui) or (name in NETWORK and not args.network)
|
||||
if disabled and args.only:
|
||||
parser.error(f"{name} requires {'--gui' if name in GUI else '--network'}")
|
||||
if disabled:
|
||||
print(f"SKIP: {name} (opt-in {'--gui' if name in GUI else '--network'})", flush=True)
|
||||
else:
|
||||
selected.append(name)
|
||||
with tempfile.TemporaryDirectory(prefix="kymo-checks-") as temp:
|
||||
work = Path(temp)
|
||||
if args.app:
|
||||
app = args.app.expanduser().resolve()
|
||||
if not (app / "Contents/MacOS/kymo").is_file():
|
||||
parser.error("--app must point to a built kymo.app")
|
||||
else:
|
||||
result = subprocess.run(["xcodebuild", "-project", "kymo.xcodeproj", "-scheme", "kymo",
|
||||
"-configuration", args.configuration, "-derivedDataPath", str(work / "build"), "build"],
|
||||
cwd=ROOT, capture_output=True, text=True, timeout=180)
|
||||
if result.returncode:
|
||||
raise RuntimeError(result.stdout[-10000:] + result.stderr[-3000:])
|
||||
for line in result.stdout.splitlines():
|
||||
if "warning:" in line or "BUILD SUCCEEDED" in line:
|
||||
print(line, flush=True)
|
||||
app = work / "build/Build/Products" / args.configuration / "kymo.app"
|
||||
host_entitlements = entitlements(app)
|
||||
run([sys.executable, "kymoTests/LocalizationCatalogChecks.py"])
|
||||
for index, name in enumerate(selected, 1):
|
||||
print(f"[{index}/{len(selected)}] {name}", flush=True)
|
||||
executable = work / name
|
||||
run(["swiftc", "-parse-as-library", "-module-cache-path", work / "cache", *CHECKS[name],
|
||||
f"kymoTests/{name}.swift", "-o", executable])
|
||||
if name in GUI:
|
||||
bundle = test_bundle(work, name, executable)
|
||||
# Open the complete app for native activation semantics, while collecting its output.
|
||||
output = work / (name + ".out")
|
||||
error = work / (name + ".err")
|
||||
try:
|
||||
run(["open", "-n", "-W", "--stdout", output, "--stderr", error, bundle], timeout=30)
|
||||
finally:
|
||||
# A timed-out open waiter may leave its child app running. Only stop this exact test binary.
|
||||
processes = subprocess.run(["ps", "-axo", "pid=,comm="], capture_output=True, text=True, check=True)
|
||||
target = (bundle / "Contents/MacOS" / name).resolve()
|
||||
for line in processes.stdout.splitlines():
|
||||
fields = line.strip().split(None, 1)
|
||||
if len(fields) == 2 and Path(fields[1]).resolve() == target:
|
||||
try:
|
||||
os.kill(int(fields[0]), signal.SIGTERM)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
text = output.read_text() if output.exists() else ""
|
||||
print(text.strip(), flush=True)
|
||||
if "PASS:" not in text:
|
||||
raise RuntimeError(f"{name} did not report success\n" + (error.read_text() if error.exists() else ""))
|
||||
elif name in NETWORK:
|
||||
bundle = test_bundle(work, name, executable, host_entitlements)
|
||||
run([bundle / "Contents/MacOS" / name], timeout=15)
|
||||
else:
|
||||
extra = [app] if name in {"LocalizationChecks", "PanelAssetChecks"} else []
|
||||
if name == "CodeIdentityChecks":
|
||||
extra = [app, app / "Contents/XPCServices/SMARTService.xpc"]
|
||||
run([executable, *extra], timeout=45)
|
||||
print(f"PASS: {len(selected)} Swift checks + catalog + host entitlements; temporary files cleaned on exit", flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except (RuntimeError, subprocess.SubprocessError, OSError) as error:
|
||||
print(f"FAIL: {error}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
Reference in New Issue
Block a user