diff --git a/tools/tests/test_build_eligibility.py b/tools/tests/test_build_eligibility.py index e984e6030cc4..9bc78b0bcb13 100644 --- a/tools/tests/test_build_eligibility.py +++ b/tools/tests/test_build_eligibility.py @@ -1,7 +1,9 @@ import json import os +import queue import shutil import subprocess +import threading import tempfile import unittest from pathlib import Path @@ -11,59 +13,65 @@ HARNESS = r""" console.error("eligibility: harness-start", process.pid, process.version); const fs = require('fs'); -const scenario = JSON.parse(fs.readFileSync(process.argv[2], 'utf8')); -const script = fs.readFileSync(process.argv[3], 'utf8'); -console.error("eligibility: inputs-read", process.pid); -const calls = []; -const outputs = {}; -const warnings = []; -let summary = ''; -const github = { - rest: { - pulls: { - get: async () => ({ data: { state: 'open', base: { ref: 'main' }, head: { sha: 'head' }, mergeable: true, user: { login: 'author' } } }), - listFiles: async () => ({ data: [] }) - }, - repos: { - listCommits: async (params) => { - calls.push(['listCommits', params.sha, params.author]); - return { data: scenario.commits }; +const readline = require('readline'); +const script = fs.readFileSync(process.argv[2], 'utf8'); +const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor; +const input = readline.createInterface({ input: process.stdin, crlfDelay: Infinity }); + +async function run(scenario) { + const calls = []; + const outputs = {}; + const warnings = []; + let summary = ''; + const github = { + rest: { + pulls: { + get: async () => ({ data: { state: 'open', base: { ref: 'main' }, head: { sha: 'head' }, mergeable: true, user: { login: 'author' } } }), + listFiles: async () => ({ data: [] }) }, - getBranch: async () => ({ data: { commit: { sha: 'main' } } }), - getCollaboratorPermissionLevel: async () => ({ data: { permission: 'write' } }) - }, - search: { - issuesAndPullRequests: async (params) => { - calls.push(['search', params.q]); - if (scenario.search === null) { - throw Object.assign(new Error('API rate limit exceeded'), { status: 403 }); + repos: { + listCommits: async (params) => { + calls.push(['listCommits', params.sha, params.author]); + return { data: scenario.commits }; + }, + getBranch: async () => ({ data: { commit: { sha: 'main' } } }), + getCollaboratorPermissionLevel: async () => ({ data: { permission: 'write' } }) + }, + search: { + issuesAndPullRequests: async (params) => { + calls.push(['search', params.q]); + if (scenario.search === null) { + throw Object.assign(new Error('API rate limit exceeded'), { status: 403 }); + } + return { data: scenario.search }; } - return { data: scenario.search }; } - } - }, - paginate: async () => scenario.files.map((filename) => ({ filename })) -}; -const context = { - eventName: scenario.manual ? 'workflow_dispatch' : 'pull_request', - actor: 'maintainer', - repo: { owner: 'owner', repo: 'project' }, - payload: { pull_request: { number: 7, head: { sha: 'head' }, user: { login: 'author' } } } -}; -const core = { - setOutput: (name, value) => { outputs[name] = value; }, - info: () => {}, - warning: (message) => { warnings.push(String(message)); }, - summary: { addRaw: (text) => { summary += text; return { write: async () => {} }; } } -}; -const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor; -new AsyncFunction('github', 'context', 'core', script)(github, context, core).then( - () => { - console.error("eligibility: gate-complete", process.pid); - process.stdout.write(JSON.stringify({ outputs, warnings, calls, summary })); - }, - (error) => { console.error(error); process.exit(1); } -); + }, + paginate: async () => scenario.files.map((filename) => ({ filename })) + }; + const context = { + eventName: scenario.manual ? 'workflow_dispatch' : 'pull_request', + actor: 'maintainer', + repo: { owner: 'owner', repo: 'project' }, + payload: { pull_request: { number: 7, head: { sha: 'head' }, user: { login: 'author' } } } + }; + const core = { + setOutput: (name, value) => { outputs[name] = value; }, + info: () => {}, + warning: (message) => { warnings.push(String(message)); }, + summary: { addRaw: (text) => { summary += text; return { write: async () => {} }; } } + }; + try { + await new AsyncFunction('github', 'context', 'core', script)(github, context, core); + return { outputs, warnings, calls, summary }; + } catch (error) { + return { error: String(error), outputs, warnings, calls, summary }; + } +} + +input.on('line', (line) => { + run(JSON.parse(line)).then((result) => process.stdout.write(JSON.stringify(result) + '\n')); +}); """ @@ -81,32 +89,53 @@ def gate_script(): class RelinkerEligibilityTests(unittest.TestCase): - def setUp(self): - self.node = shutil.which("node") - if not self.node: - self.skipTest("the eligibility script runs in node") - self.temp = tempfile.TemporaryDirectory() - self.root = Path(self.temp.name) - (self.root / "harness.js").write_text(HARNESS, encoding="utf-8") - (self.root / "gate.js").write_text(gate_script(), encoding="utf-8") - - def tearDown(self): - self.temp.cleanup() + @classmethod + def setUpClass(cls): + cls.node = shutil.which("node") + if not cls.node: + raise unittest.SkipTest("the eligibility script runs in node") + cls.temp = tempfile.TemporaryDirectory() + cls.root = Path(cls.temp.name) + (cls.root / "harness.js").write_text(HARNESS, encoding="utf-8") + (cls.root / "gate.js").write_text(gate_script(), encoding="utf-8") + environment = dict(os.environ, PR_NUMBER="7", GITHUB_TRIGGERING_ACTOR="maintainer") + cls.process = subprocess.Popen( + [cls.node, "harness.js", "gate.js"], cwd=cls.root, stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding="utf-8", bufsize=1, + env=environment, + ) + + @classmethod + def tearDownClass(cls): + if cls.process.poll() is None: + cls.process.stdin.close() + try: + cls.process.wait(timeout=5) + except subprocess.TimeoutExpired: + cls.process.kill() + cls.process.wait() + cls.temp.cleanup() def run_gate(self, commits, search, files=("core/relinker/main.cpp",), manual=False): - scenario = self.root / "scenario.json" - scenario.write_text(json.dumps({"commits": commits, "search": search, "files": list(files), "manual": manual}), - encoding="utf-8") - environment = dict(os.environ, PR_NUMBER="7", GITHUB_TRIGGERING_ACTOR="maintainer") + self.process.stdin.write(json.dumps({ + "commits": commits, "search": search, "files": list(files), "manual": manual, + }) + "\n") + self.process.stdin.flush() + response = queue.Queue(maxsize=1) + threading.Thread(target=lambda: response.put(self.process.stdout.readline()), daemon=True).start() try: - result = subprocess.run([self.node, "harness.js", "scenario.json", "gate.js"], cwd=self.root, - capture_output=True, text=True, env=environment, timeout=90) - except subprocess.TimeoutExpired as error: - stdout = error.stdout.decode(errors="replace") if isinstance(error.stdout, bytes) else error.stdout or "" - stderr = error.stderr.decode(errors="replace") if isinstance(error.stderr, bytes) else error.stderr or "" - self.fail(f"Node harness timed out after {error.timeout}s: {self.node}\nstdout:\n{stdout}\nstderr:\n{stderr}") - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - return json.loads(result.stdout) + line = response.get(timeout=90) + except queue.Empty: + self.process.kill() + self.process.wait() + stderr = self.process.stderr.read() + self.fail(f"{self.node}: stderr:\n{stderr}\n" + "eligibility harness did not answer within 90 seconds") + if not line: + stderr = self.process.stderr.read() if self.process.poll() is not None else "" + self.fail(f"eligibility harness exited with status {self.process.poll()}: {stderr}") + result = json.loads(line) + self.assertNotIn("error", result, result.get("error")) + return result def test_author_with_a_commit_in_main_runs_the_relinker(self): result = self.run_gate([{"sha": "a"}], None)