"""Exercise an isolated empty MySQL database with the host's native test runtimes.""" import argparse import http.cookiejar import json import os from pathlib import Path import secrets import shutil import socket import subprocess import sys import tempfile import time import urllib.request from build_bundle import ROOT, TEMPLATES, adapt_runtime def main(): parser = argparse.ArgumentParser() parser.add_argument('--work', type=Path, required=True) args = parser.parse_args() work = args.work.resolve() stage = Path(tempfile.mkdtemp(prefix='qc-offline-', dir='/tmp')).resolve() (work / 'smoke-root.txt').write_text(str(stage)) for folder in ('deploy/offline', 'scripts', 'runtimes', 'app', '.runtime'): (stage / folder).mkdir(parents=True, exist_ok=True, mode=0o700) for name in ('control.py', 'gateway.py'): shutil.copy2(TEMPLATES / name, stage / 'deploy/offline' / name) shutil.copy2(TEMPLATES / 'runtime_platform.py', stage / 'scripts/runtime_platform.py') for pattern in ('nao_*.py', 'analysis_visual*.py'): for path in (ROOT / 'scripts').glob(pattern): (stage / 'scripts' / path.name).write_text(adapt_runtime(path.read_text()) if path.name == 'nao_quality_runtime.py' else path.read_text()) shutil.copytree(ROOT / 'ai/nao-quality', stage / 'ai/nao-quality') shutil.copy2(next((work / 'source/backend/target').glob('*.jar')), stage / 'app/backend.jar') shutil.copytree(work / 'source/web/dist', stage / 'app/web') for name, target in (('java', ROOT / '.runtime/jdk/Contents/Home'), ('mysql', ROOT / '.runtime/mysql'), ('python', ROOT / '.runtime/nao-trial/venv')): (stage / 'runtimes' / name).symlink_to(target, target_is_directory=True) def available(port): try: with socket.socket() as test: test.bind(('127.0.0.1', port)) return True except OSError: return False port = next(p for p in (5284, 5283, 5285) if available(p)) def free(): with socket.socket() as test: test.bind(('127.0.0.1', 0)) return test.getsockname()[1] value = {'mysqlPort': free(), 'backendPort': port, 'webPort': free(), 'webBind': '127.0.0.1', 'mysqlPassword': secrets.token_urlsafe(32), 'rootPassword': secrets.token_urlsafe(32), 'adminUsername': 'admin', 'adminPassword': secrets.token_urlsafe(24)} config = stage / '.runtime/deployment.json' config.write_text(json.dumps(value)) config.chmod(0o600) report = {'environment': 'macOS isolated empty database using host-native runtimes', 'targetWindowsLinuxNativeValidated': False, 'checks': []} process = None try: for cycle in range(2): with (stage / f'cycle-{cycle}.log').open('w') as log: process = subprocess.Popen([sys.executable, str(stage / 'deploy/offline/control.py'), 'serve'], stdout=log, stderr=subprocess.STDOUT) for _ in range(180): if process.poll() is not None: raise RuntimeError('Supervisor exited; inspect ' + str(stage / f'cycle-{cycle}.log')) try: state = json.loads((stage / '.runtime/service.json').read_text()) if state.get('ready'): break except (FileNotFoundError, ValueError): pass time.sleep(1) else: raise RuntimeError('Isolated startup timed out') cookies = http.cookiejar.CookieJar() opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), urllib.request.HTTPCookieProcessor(cookies)) base = f'http://127.0.0.1:{value["webPort"]}' with opener.open(base + '/', timeout=5) as response: assert response.status == 200 and b'
' in response.read() with opener.open(base + '/actuator/health', timeout=5) as response: assert json.load(response)['status'] == 'UP' with opener.open(base + '/api/auth/csrf', timeout=5) as response: token = json.load(response)['token'] request = urllib.request.Request(base + '/api/auth/login', data=json.dumps({'username': value['adminUsername'], 'password': value['adminPassword']}).encode(), headers={'Content-Type': 'application/json', 'X-XSRF-TOKEN': token}) with opener.open(request, timeout=10) as response: assert response.status == 200 for path in ('/api/auth/me', '/api/options'): with opener.open(base + path, timeout=10) as response: assert response.status == 200 report['checks'].append({'cycle': cycle + 1, 'web': True, 'databaseMigration': True, 'csrfAndLogin': True, 'authenticatedOptions': True}) result = subprocess.run([sys.executable, str(stage / 'deploy/offline/control.py'), 'stop'], capture_output=True, text=True, timeout=150) if result.returncode: raise RuntimeError('Stop failed: ' + result.stderr) process.wait(timeout=10) process = None assert not (stage / '.runtime/service.json').exists() print('Isolated startup/login/stop cycle', cycle + 1, 'passed', flush=True) report['passed'] = True except Exception as error: report['passed'] = False report['error'] = str(error) print(str(error), flush=True) finally: if process is not None and process.poll() is None: subprocess.run([sys.executable, str(stage / 'deploy/offline/control.py'), 'stop'], capture_output=True, timeout=150) (work / 'smoke-report.json').write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n') print(json.dumps(report, ensure_ascii=False), flush=True) return 0 if report['passed'] else 1 if __name__ == '__main__': raise SystemExit(main())