File size: 1,647 Bytes
0dd7c80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
"""Pytest invocation inside the sandbox + JSON-report parsing.

Kept separate from `runner.py` so the Docker orchestration and the
pytest-harness concerns don't tangle.
"""

from __future__ import annotations

import json
from pathlib import Path
from typing import Any

from .resource_limits import REPORT_FILENAME, REPORT_PATH_IN_CONTAINER


def pytest_command() -> list[str]:
    """Pytest argv used inside the sandbox container.

    `-p no:cacheprovider` stops pytest from writing `.pytest_cache/` into the
    bind-mounted /work as the sandbox uid, which would be un-deletable by the
    host on Linux (CI, CHTC).
    """
    return [
        "pytest",
        "-q",
        "-p",
        "no:cacheprovider",
        "--json-report",
        f"--json-report-file={REPORT_PATH_IN_CONTAINER}",
        "test_solution.py",
    ]


def parse_report(workdir: Path) -> tuple[int, int]:
    """Read the JSON report from the host side of the bind mount.

    Returns (0, 0) if the report is missing or malformed — typical when the
    container was killed before pytest could flush.
    """
    report = workdir / REPORT_FILENAME
    if not report.exists():
        return 0, 0
    try:
        summary = json.loads(report.read_text()).get("summary", {})
        return int(summary.get("passed", 0)), int(summary.get("total", 0))
    except Exception:
        return 0, 0


def was_oom_killed(container: Any) -> bool:
    """True if the kernel OOM-killed the container due to mem_limit."""
    try:
        container.reload()
        return bool(container.attrs.get("State", {}).get("OOMKilled", False))
    except Exception:
        return False