221 lines
13 KiB
Python
221 lines
13 KiB
Python
#!/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 re
|
|
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", "ReleaseServiceChecks", "DetailDemandChecks")}
|
|
CHECKS.update({
|
|
"BackgroundTrendChecks": CORE + ["kymo/UI/Charts/PanelCurveGeometry.swift"],
|
|
"ProcessEnergyChecks": ["kymo/Core/Models/ProcessMetrics.swift", "kymo/Core/Models/ProcessEnergy.swift", "kymo/Core/Monitors/ProcessEnergyMonitor.swift"],
|
|
"ProcessEnergyReaderChecks": ["kymo/Core/Models/ProcessMetrics.swift", "kymo/Core/Models/ProcessEnergy.swift", "SMARTService/ProcessEnergyReader.swift"],
|
|
"BoundedProcessChecks": ["kymo/Core/Services/BoundedProcess.swift"],
|
|
"SensorScheduleChecks": ["kymo/Core/Services/SensorSchedule.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"],
|
|
"NativeMetricDrawingChecks": ["kymo/UI/Charts/NativePanelCurve.swift", "kymo/UI/Charts/PanelCurveFrame.swift",
|
|
"kymo/UI/Charts/PanelCurveGeometry.swift"],
|
|
"NativeContentHostChecks": ["kymo/UI/Components/NativeContentHost.swift", "kymo/UI/Components/MetricText.swift"],
|
|
"ProcessCPULiveChecks": ["kymo/Core/Models/ProcessMetrics.swift", "kymo/Core/Monitors/ProcessMonitor.swift"],
|
|
"AppearancePreferencesChecks": ["kymo/Core/Services/AppearancePreferences.swift", "kymo/Core/Services/SamplingPreferences.swift"],
|
|
"NetworkAddressChecks": ["kymo/Core/Monitors/NetworkMonitor.swift"],
|
|
"ProcessIconCacheChecks": ["kymo/Features/MenuBar/ProcessIconCache.swift"],
|
|
"TabPickerChecks": ["kymo/UI/Components/NeutralTabPicker.swift", "kymo/UI/Components/AppLocalization.swift",
|
|
"kymo/Core/Services/LanguagePreferences.swift"],
|
|
"MemoryHeaderChecks": CORE + ["kymo/Features/MenuBar/MemoryHeaderInfo.swift", "kymo/UI/Components/AppLocalization.swift"],
|
|
"NativeProcessTableChecks": ["kymo/Core/Models/ProcessMetrics.swift", "kymo/Features/MenuBar/ProcessTableProjection.swift",
|
|
"kymo/Features/MenuBar/NativeProcessTable.swift", "kymo/Features/MenuBar/ProcessIconCache.swift",
|
|
"kymo/Core/Services/LanguagePreferences.swift", "kymo/UI/Components/AppLocalization.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/MetricText.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/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/Features/MenuBar/PanelWindowObserver.swift", "kymo/UI/Components/IntervalControl.swift"],
|
|
"SandboxNetworkChecks": ["kymo/Core/Services/PublicIPAddressService.swift"],
|
|
})
|
|
GUI = {"NativeMetricDrawingChecks", "NativeContentHostChecks", "NativeProcessTableChecks", "LanguageScopeChecks", "SettingsWindowChecks", "PanelWindowChecks", "TabPickerChecks"}
|
|
NETWORK = {"SandboxNetworkChecks"}
|
|
SERVICES = {"ReleaseServiceChecks"}
|
|
|
|
|
|
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, resources=None, service=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", "NativeMetricDrawingChecks", "NativeContentHostChecks", "NativeProcessTableChecks", "NetworkAddressChecks", "SandboxNetworkChecks", "TabPickerChecks"},
|
|
}))
|
|
if resources:
|
|
shutil.copytree(resources, contents / "Resources")
|
|
if service:
|
|
shutil.copytree(service, contents / "XPCServices/SMARTService.xpc")
|
|
command = ["codesign", "--force", "--sign", "-"]
|
|
if service:
|
|
command += ["--options", "runtime"]
|
|
if host_entitlements:
|
|
path = work / "network.entitlements"
|
|
path.write_bytes(plistlib.dumps(host_entitlements))
|
|
command += ["--entitlements", path]
|
|
run(command + [app])
|
|
return app
|
|
|
|
|
|
|
|
def clean_test_container(bundle):
|
|
# Only the random bundle ID generated by this runner; never the real app's data.
|
|
identifier = plistlib.loads((bundle / "Contents/Info.plist").read_bytes())["CFBundleIdentifier"]
|
|
if not re.fullmatch(r"cn\.airnan\.kymo\.checks\.[a-f0-9]{32}", identifier):
|
|
raise RuntimeError("Refusing to clean an unrecognized test container")
|
|
container = Path.home() / "Library/Containers" / identifier
|
|
if container.is_symlink():
|
|
raise RuntimeError("Refusing to follow a test-container symlink")
|
|
if container.exists():
|
|
shutil.rmtree(container)
|
|
|
|
|
|
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("--services", action="store_true", help="Test packaged XPC in a temporary hardened sandbox host")
|
|
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 "") + (" [services]" if name in SERVICES 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) or (name in SERVICES and not args.services)
|
|
if disabled and args.only:
|
|
parser.error(f"{name} requires {'--gui' if name in GUI else '--services' if name in SERVICES else '--network'}")
|
|
if disabled:
|
|
print(f"SKIP: {name} (opt-in {'--gui' if name in GUI else '--services' if name in SERVICES 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, resources=app / "Contents/Resources" if name in {"NativeProcessTableChecks", "TabPickerChecks"} else None)
|
|
# 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 or name in SERVICES or name == "NetworkAddressChecks":
|
|
service = app / "Contents/XPCServices/SMARTService.xpc" if name in SERVICES else None
|
|
bundle = test_bundle(work, name, executable, host_entitlements, service=service)
|
|
try:
|
|
run([bundle / "Contents/MacOS" / name], timeout=15)
|
|
finally:
|
|
clean_test_container(bundle)
|
|
else:
|
|
extra = [app] if name in {"LocalizationChecks", "PanelAssetChecks", "MemoryHeaderChecks"} 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)
|