(
code: string,
{ timeout = 15000, name = `ava-python-test-${randomUUID()}` } = {}
)
| 9 | |
| 10 | /** Every invocation owns one container, including cleanup after a killed Docker client. */ |
| 11 | export async function executeDocker( |
| 12 | code: string, |
| 13 | { timeout = 15000, name = `ava-python-test-${randomUUID()}` } = {} |
| 14 | ): Promise<ExecutionResult> { |
| 15 | try { |
| 16 | return await new Promise((resolve, reject) => { |
| 17 | const child = execFile( |
| 18 | 'docker', |
| 19 | [ |
| 20 | 'run', |
| 21 | '--rm', |
| 22 | '-i', |
| 23 | '--name', |
| 24 | name, |
| 25 | '--network=none', |
| 26 | '--read-only', |
| 27 | '--user=65534:65534', |
| 28 | '--cap-drop=ALL', |
| 29 | '--security-opt=no-new-privileges', |
| 30 | '--cpus=1', |
| 31 | '--memory=256m', |
| 32 | '--memory-swap=256m', |
| 33 | '--pids-limit=64', |
| 34 | '--tmpfs=/tmp:rw,noexec,nosuid,size=16m', |
| 35 | '-e', |
| 36 | 'OPENBLAS_NUM_THREADS=1', |
| 37 | '-e', |
| 38 | 'PYTHONDONTWRITEBYTECODE=1', |
| 39 | image, |
| 40 | 'python3', |
| 41 | '-', |
| 42 | ], |
| 43 | { timeout, killSignal: 'SIGKILL', maxBuffer: 4 * 1024 * 1024, encoding: 'utf8' }, |
| 44 | (error, stdout, stderr) => { |
| 45 | if (error) { |
| 46 | reject(new Error(error.killed ? 'Docker execution timed out' : stderr.trim() || error.message)); |
| 47 | return; |
| 48 | } |
| 49 | try { |
| 50 | resolve(JSON.parse(stdout)); |
| 51 | } catch { |
| 52 | reject(new Error('Docker returned invalid JSON')); |
| 53 | } |
| 54 | } |
| 55 | ); |
| 56 | child.stdin!.on('error', reject); |
| 57 | child.stdin!.end(code); |
| 58 | }); |
| 59 | } finally { |
| 60 | // Do not mask a cleanup failure: a leaked container must fail the test. |
| 61 | await docker('docker', ['rm', '-f', name]).catch((error) => { |
| 62 | if (!String(error.stderr).includes('No such container')) throw error; |
| 63 | }); |
| 64 | } |
| 65 | } |
no test coverage detected