|
| 1 | +"""Run the Java Browser Bridge contract against an isolated real browser.""" |
| 2 | +import argparse |
| 3 | +from hashlib import sha256 |
| 4 | +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer |
| 5 | +import json |
| 6 | +import os |
| 7 | +from pathlib import Path |
| 8 | +import shutil |
| 9 | +import subprocess |
| 10 | +import sys |
| 11 | +import tempfile |
| 12 | +import threading |
| 13 | +import time |
| 14 | +from urllib.error import URLError |
| 15 | +from urllib.request import Request, urlopen |
| 16 | +from zipfile import ZipFile |
| 17 | + |
| 18 | +import contract_report |
| 19 | + |
| 20 | + |
| 21 | +OPENCLI_VERSION = '1.8.8' |
| 22 | +EXTENSION_VERSION = '1.0.24' |
| 23 | +EXTENSION_SHA = 'bad9163f32a66224404e302f52f35391672341d2bd0bf30c8bbaae3c6e6e246c' |
| 24 | +CHROME_VERSION = '158.0.8127.18' |
| 25 | +DAEMON_STATUS = 'http://127.0.0.1:19825/status' |
| 26 | +SUITE = 'io.github.easy4j.opencli.contract.OpenCliBrowserBridgeIT' |
| 27 | +PAGE = b"""<!doctype html><title>Bridge fixture</title><main><button id="go">Continue</button></main> |
| 28 | +<script> |
| 29 | +const capture = setInterval(() => fetch('/api/items'), 250); |
| 30 | +setTimeout(() => clearInterval(capture), 120000); |
| 31 | +</script>""" |
| 32 | + |
| 33 | + |
| 34 | +class FixtureHandler(BaseHTTPRequestHandler): |
| 35 | + def do_GET(self): |
| 36 | + if self.path == '/api/items': |
| 37 | + body, content_type = b'{"items":[{"id":17}]}', 'application/json' |
| 38 | + else: |
| 39 | + body, content_type = PAGE, 'text/html; charset=utf-8' |
| 40 | + self.send_response(200) |
| 41 | + self.send_header('Content-Type', content_type) |
| 42 | + self.send_header('Content-Length', str(len(body))) |
| 43 | + self.end_headers() |
| 44 | + self.wfile.write(body) |
| 45 | + |
| 46 | + def log_message(self, *_): |
| 47 | + pass |
| 48 | + |
| 49 | + |
| 50 | +def download_zip(url, directory, expected_sha=None): |
| 51 | + archive = directory.with_suffix('.zip') |
| 52 | + with urlopen(url, timeout=60) as response, archive.open('wb') as output: |
| 53 | + shutil.copyfileobj(response, output) |
| 54 | + if expected_sha and sha256(archive.read_bytes()).hexdigest() != expected_sha: |
| 55 | + raise RuntimeError(f'Artifact digest mismatch for {url}') |
| 56 | + with ZipFile(archive) as zipped: |
| 57 | + zipped.extractall(directory) |
| 58 | + if os.name != 'nt': |
| 59 | + for entry in zipped.infolist(): |
| 60 | + if entry.external_attr >> 16 & 0o111: |
| 61 | + (directory / entry.filename).chmod(0o755) |
| 62 | + |
| 63 | + |
| 64 | +def chrome_executable(root): |
| 65 | + platform = {'linux': 'linux64', 'win32': 'win64'}[sys.platform] |
| 66 | + download_zip( |
| 67 | + f'https://storage.googleapis.com/chrome-for-testing-public/{CHROME_VERSION}/{platform}/chrome-{platform}.zip', |
| 68 | + root / 'chrome', |
| 69 | + ) |
| 70 | + return root / 'chrome' / f'chrome-{platform}' / ('chrome.exe' if os.name == 'nt' else 'chrome') |
| 71 | + |
| 72 | + |
| 73 | +def daemon_status(): |
| 74 | + with urlopen(Request(DAEMON_STATUS, headers={'X-OpenCLI': '1'}), timeout=1) as response: |
| 75 | + return json.load(response) |
| 76 | + |
| 77 | + |
| 78 | +def wait_for_bridge(daemon, browser): |
| 79 | + deadline = time.monotonic() + 30 |
| 80 | + while time.monotonic() < deadline: |
| 81 | + if daemon.poll() is not None or browser.poll() is not None: |
| 82 | + raise RuntimeError('The isolated daemon or Chrome exited before the extension connected') |
| 83 | + try: |
| 84 | + status = daemon_status() |
| 85 | + except URLError: |
| 86 | + time.sleep(0.25) |
| 87 | + continue |
| 88 | + if status.get('pid') != daemon.pid: |
| 89 | + raise RuntimeError('The Bridge endpoint belongs to a different daemon') |
| 90 | + if status.get('extensionConnected'): |
| 91 | + if (status.get('daemonVersion'), status.get('extensionVersion')) != (OPENCLI_VERSION, EXTENSION_VERSION): |
| 92 | + raise RuntimeError('The connected Bridge versions differ from the pinned versions') |
| 93 | + return status |
| 94 | + time.sleep(0.25) |
| 95 | + raise RuntimeError('The extension did not connect to the isolated daemon') |
| 96 | + |
| 97 | + |
| 98 | +def stop(process): |
| 99 | + if process is None or process.poll() is not None: |
| 100 | + return |
| 101 | + process.terminate() |
| 102 | + try: |
| 103 | + process.wait(timeout=8) |
| 104 | + except subprocess.TimeoutExpired: |
| 105 | + process.kill() |
| 106 | + process.wait() |
| 107 | + |
| 108 | + |
| 109 | +def execute(args, root, evidence): |
| 110 | + extension = root / 'extension' |
| 111 | + download_zip(f'https://github.com/jackwener/OpenCLI/releases/download/v{OPENCLI_VERSION}/' |
| 112 | + f'opencli-extension-v{EXTENSION_VERSION}.zip', extension, EXTENSION_SHA) |
| 113 | + chrome = args.chrome or chrome_executable(root) |
| 114 | + node = shutil.which('node') |
| 115 | + if not node: |
| 116 | + raise RuntimeError('Node executable is unavailable') |
| 117 | + home = root / 'home' |
| 118 | + home.mkdir() |
| 119 | + env = dict(os.environ, HOME=str(home), USERPROFILE=str(home), |
| 120 | + OPENCLI_CONFIG_DIR=str(root / 'config'), OPENCLI_CACHE_DIR=str(root / 'cache'), |
| 121 | + OPENCLI_INSTALLED_NODE=node, OPENCLI_INSTALLED_ENTRY=str(args.cli_entry)) |
| 122 | + for name in ('OPENCLI_DAEMON_PORT', 'OPENCLI_CDP_ENDPOINT', 'OPENCLI_CDP_TARGET'): |
| 123 | + env.pop(name, None) |
| 124 | + |
| 125 | + # Use the upstream loopback port without changing the published binaries. |
| 126 | + try: |
| 127 | + daemon_status() |
| 128 | + except URLError: |
| 129 | + pass |
| 130 | + else: |
| 131 | + raise RuntimeError('An existing OpenCLI daemon already uses the fixture port') |
| 132 | + |
| 133 | + reports = Path('target/surefire-reports') |
| 134 | + xml = reports / f'TEST-{SUITE}.xml' |
| 135 | + xml.unlink(missing_ok=True) |
| 136 | + java = subprocess.run(['java', '-version'], check=True, capture_output=True, text=True) |
| 137 | + maven = subprocess.run([*args.maven, '-version'], check=True, capture_output=True, text=True) |
| 138 | + daemon = browser = None |
| 139 | + with ThreadingHTTPServer(('127.0.0.1', 0), FixtureHandler) as server: |
| 140 | + threading.Thread(target=server.serve_forever, daemon=True).start() |
| 141 | + url = f'http://127.0.0.1:{server.server_port}/fixture.html' |
| 142 | + env['OPENCLI_BRIDGE_FIXTURE_URL'] = url |
| 143 | + try: |
| 144 | + with (evidence / 'daemon.log').open('w') as log: |
| 145 | + daemon = subprocess.Popen([node, str(args.cli_entry.with_name('daemon.js'))], |
| 146 | + cwd=root, env=env, stdout=log, stderr=subprocess.STDOUT) |
| 147 | + chrome_args = [ |
| 148 | + '--headless=new', '--no-first-run', '--no-default-browser-check', |
| 149 | + '--disable-background-networking', '--disable-component-update', |
| 150 | + '--disable-sync', '--remote-debugging-port=0', '--no-proxy-server', |
| 151 | + '--host-resolver-rules=MAP localhost 127.0.0.1, MAP * ~NOTFOUND', |
| 152 | + '--user-data-dir=' + str(root / 'profile'), |
| 153 | + '--disable-extensions-except=' + str(extension), '--load-extension=' + str(extension), |
| 154 | + ] |
| 155 | + if sys.platform == 'darwin': |
| 156 | + chrome_args.append('--use-mock-keychain') |
| 157 | + with (evidence / 'chrome.log').open('w') as log: |
| 158 | + browser = subprocess.Popen([str(chrome), *chrome_args, url.replace('/fixture', '/bound-fixture')], |
| 159 | + cwd=root, env=env, stdout=log, stderr=subprocess.STDOUT) |
| 160 | + wait_for_bridge(daemon, browser) |
| 161 | + with (evidence / 'maven.log').open('w') as log: |
| 162 | + result = subprocess.run([*args.maven, '-B', '--no-transfer-progress', '-Dtest=OpenCliBrowserBridgeIT', 'test'], |
| 163 | + env=env, stdout=log, stderr=subprocess.STDOUT, timeout=180) |
| 164 | + status = wait_for_bridge(daemon, browser) |
| 165 | + (evidence / 'bridge.json').write_text(json.dumps({ |
| 166 | + 'daemonPid': daemon.pid, 'chromePid': browser.pid, 'chromeVersion': CHROME_VERSION, |
| 167 | + 'opencliVersion': status['daemonVersion'], 'extensionVersion': status['extensionVersion'], |
| 168 | + }) + '\n', encoding='utf-8') |
| 169 | + finally: |
| 170 | + stop(browser) |
| 171 | + stop(daemon) |
| 172 | + server.shutdown() |
| 173 | + |
| 174 | + if xml.exists(): |
| 175 | + shutil.copyfile(xml, evidence / xml.name) |
| 176 | + report = contract_report.build_report( |
| 177 | + evidence, head=subprocess.check_output(['git', 'rev-parse', 'HEAD'], text=True).strip(), |
| 178 | + branch=os.environ.get('GITHUB_REF_NAME') or subprocess.check_output( |
| 179 | + ['git', 'branch', '--show-current'], text=True).strip(), |
| 180 | + java_version=(java.stdout + java.stderr).strip(), maven_version=(maven.stdout + maven.stderr).strip(), |
| 181 | + exit_code=result.returncode, required_suites={'real-execution': [SUITE]}, |
| 182 | + ) |
| 183 | + (evidence / 'report.json').write_text(json.dumps(report, indent=2) + '\n', encoding='utf-8') |
| 184 | + print(json.dumps(report['layers']['real-execution'])) |
| 185 | + return 0 if report['status'] == 'PASS' else 1 |
| 186 | + |
| 187 | + |
| 188 | +def main(): |
| 189 | + parser = argparse.ArgumentParser(description=__doc__) |
| 190 | + parser.add_argument('--cli-entry', required=True, type=lambda path: Path(path).resolve()) |
| 191 | + parser.add_argument('--chrome', type=lambda path: Path(path).resolve()) |
| 192 | + parser.add_argument('--evidence', required=True, type=lambda path: Path(path).resolve()) |
| 193 | + parser.add_argument('maven', nargs='+') |
| 194 | + args = parser.parse_args() |
| 195 | + args.evidence.mkdir(parents=True, exist_ok=False) |
| 196 | + with tempfile.TemporaryDirectory(prefix='opencli-bridge-', ignore_cleanup_errors=True) as root: |
| 197 | + return execute(args, Path(root), args.evidence) |
| 198 | + |
| 199 | + |
| 200 | +if __name__ == '__main__': |
| 201 | + sys.exit(main()) |
0 commit comments