| 1 |
|
| 2 |
|
| 3 |
import os |
| 4 |
import re |
| 5 |
import subprocess |
| 6 |
import time |
| 7 |
import unittest |
| 8 |
from datetime import datetime |
| 9 |
from datetime import timedelta |
| 10 |
from pathlib import Path |
| 11 |
from typing import Any |
| 12 |
from typing import Optional |
| 13 |
|
| 14 |
from apscheduler.job import Job |
| 15 |
from apscheduler.jobstores.base import JobLookupError |
| 16 |
from apscheduler.schedulers.background import BackgroundScheduler |
| 17 |
from apscheduler.triggers.interval import IntervalTrigger |
| 18 |
from packaging import version |
| 19 |
from tzlocal import get_localzone |
| 20 |
|
| 21 |
_podman_version = None |
| 22 |
|
| 23 |
|
| 24 |
def get_podman_version() -> version.Version: |
| 25 |
""" |
| 26 |
Return the *packaging.version.Version* object for the podman binary |
| 27 |
found in PATH (cached after the first call). Raise RuntimeError |
| 28 |
if podman is missing or gives unexpected output. |
| 29 |
""" |
| 30 |
global _podman_version |
| 31 |
if _podman_version is None: |
| 32 |
try: |
| 33 |
out = subprocess.check_output( |
| 34 |
["podman", "--version"], text=True, stderr=subprocess.STDOUT |
| 35 |
) |
| 36 |
token |
| 37 |
raw = out.strip().split()[-1] |
| 38 |
_podman_version = version.parse(raw) |
| 39 |
except Exception as exc: |
| 40 |
raise RuntimeError("cannot determine podman version") from exc |
| 41 |
return _podman_version |
| 42 |
|
| 43 |
|
| 44 |
def base_path() -> Path: |
| 45 |
"""Returns the base path for the project""" |
| 46 |
return Path(__file__).parent.parent.parent |
| 47 |
|
| 48 |
|
| 49 |
def test_path() -> str: |
| 50 |
"""Returns the path to the tests directory""" |
| 51 |
return os.path.join(base_path(), "tests/integration") |
| 52 |
|
| 53 |
|
| 54 |
def podman_compose_path() -> str: |
| 55 |
"""Returns the path to the podman compose script""" |
| 56 |
return os.path.join(base_path(), "podman_compose.py") |
| 57 |
|
| 58 |
|
| 59 |
def is_systemd_available() -> bool: |
| 60 |
try: |
| 61 |
with open("/proc/1/comm", encoding="utf-8") as fh: |
| 62 |
return fh.read().strip() == "systemd" |
| 63 |
except FileNotFoundError: |
| 64 |
return False |
| 65 |
|
| 66 |
|
| 67 |
class RunSubprocessMixin: |
| 68 |
def is_debug_enabled(self) -> bool: |
| 69 |
return "TESTS_DEBUG" in os.environ |
| 70 |
|
| 71 |
def run_subprocess( |
| 72 |
self, |
| 73 |
args: list[str], |
| 74 |
env: dict[str, str] = {}, |
| 75 |
timeout: Optional[float] = None, |
| 76 |
) -> tuple[bytes, bytes, int]: |
| 77 |
begin = time.time() |
| 78 |
if self.is_debug_enabled(): |
| 79 |
print("TEST_CALL", args) |
| 80 |
proc = subprocess.Popen( |
| 81 |
args, |
| 82 |
stdout=subprocess.PIPE, |
| 83 |
stderr=subprocess.PIPE, |
| 84 |
env=os.environ | env, |
| 85 |
) |
| 86 |
out, err = proc.communicate(timeout=timeout) |
| 87 |
if self.is_debug_enabled(): |
| 88 |
print("TEST_CALL completed", time.time() - begin) |
| 89 |
print("STDOUT:", out.decode('utf-8')) |
| 90 |
print("STDERR:", err.decode('utf-8')) |
| 91 |
return out, err, proc.returncode |
| 92 |
|
| 93 |
def run_subprocess_assert_returncode( |
| 94 |
self, |
| 95 |
args: list[str], |
| 96 |
expected_returncode: int = 0, |
| 97 |
env: dict[str, str] = {}, |
| 98 |
timeout: Optional[float] = None, |
| 99 |
) -> tuple[bytes, bytes]: |
| 100 |
out, err, returncode = self.run_subprocess(args, env=env, timeout=timeout) |
| 101 |
decoded_out = out.decode('utf-8') |
| 102 |
decoded_err = err.decode('utf-8') |
| 103 |
self.assertEqual( |
| 104 |
returncode, |
| 105 |
expected_returncode, |
| 106 |
f"Invalid return code of process {returncode} != {expected_returncode}\n" |
| 107 |
f"stdout: {decoded_out}\nstderr: {decoded_err}\n", |
| 108 |
) |
| 109 |
return out, err |
| 110 |
|
| 111 |
|
| 112 |
class PodmanAwareRunSubprocessMixin(RunSubprocessMixin): |
| 113 |
def retrieve_podman_version(self) -> tuple[int, int, int]: |
| 114 |
out, _ = self.run_subprocess_assert_returncode(["podman", "--version"]) |
| 115 |
matcher = re.match(r"\D*(\d+)\.(\d+)\.(\d+)", out.decode('utf-8')) |
| 116 |
if matcher: |
| 117 |
major = int(matcher.group(1)) |
| 118 |
minor = int(matcher.group(2)) |
| 119 |
patch = int(matcher.group(3)) |
| 120 |
return (major, minor, patch) |
| 121 |
raise RuntimeError("Unable to retrieve podman version") |
| 122 |
|
| 123 |
|
| 124 |
|
| 125 |
|
| 126 |
|
| 127 |
|
| 128 |
|
| 129 |
|
| 130 |
|
| 131 |
|
| 132 |
class EnsureHealthcheckRun: |
| 133 |
def __init__( |
| 134 |
self, runner: RunSubprocessMixin, test_case: unittest.TestCase, container_name: str |
| 135 |
) -> None: |
| 136 |
self.__runner: RunSubprocessMixin = runner |
| 137 |
|
| 138 |
self.__scheduler: Optional[BackgroundScheduler] = None |
| 139 |
self.__healthcheck_job: Optional[Job] = None |
| 140 |
self.__container_name: str = container_name |
| 141 |
|
| 142 |
|
| 143 |
if not is_systemd_available(): |
| 144 |
|
| 145 |
self.__scheduler = BackgroundScheduler() |
| 146 |
self.__scheduler.start() |
| 147 |
|
| 148 |
|
| 149 |
test_case.addCleanup(self._cleanup_scheduler) |
| 150 |
|
| 151 |
def _cleanup_scheduler(self) -> None: |
| 152 |
|
| 153 |
if self.__scheduler is not None: |
| 154 |
try: |
| 155 |
if self.__healthcheck_job is not None: |
| 156 |
self.__scheduler.remove_job(self.__healthcheck_job.id) |
| 157 |
else: |
| 158 |
self.__scheduler.remove_all_jobs() |
| 159 |
except JobLookupError: |
| 160 |
|
| 161 |
self.__scheduler.remove_all_jobs() |
| 162 |
|
| 163 |
|
| 164 |
self.__scheduler.shutdown(wait=True) |
| 165 |
|
| 166 |
|
| 167 |
|
| 168 |
self.__scheduler = None |
| 169 |
|
| 170 |
def __enter__(self) -> None: |
| 171 |
|
| 172 |
if self.__scheduler is not None: |
| 173 |
self.__healthcheck_job = self.__scheduler.add_job( |
| 174 |
func=self.__runner.run_subprocess, |
| 175 |
|
| 176 |
kwargs={"args": ["podman", "healthcheck", "run", f"{self.__container_name}"]}, |
| 177 |
trigger=IntervalTrigger( |
| 178 |
|
| 179 |
seconds=3, |
| 180 |
|
| 181 |
start_date=datetime.now(get_localzone()) + timedelta(seconds=3), |
| 182 |
|
| 183 |
end_date=datetime.now(get_localzone()) + timedelta(seconds=21), |
| 184 |
), |
| 185 |
) |
| 186 |
|
| 187 |
def __exit__(self, *_: Any) -> None: |
| 188 |
|
| 189 |
self._cleanup_scheduler() |
| 190 |
|
| 191 |
|
| 192 |
class ExecutionTime: |
| 193 |
def __init__( |
| 194 |
self, |
| 195 |
min_execution_time: Optional[timedelta] = None, |
| 196 |
max_execution_time: Optional[timedelta] = None, |
| 197 |
) -> None: |
| 198 |
self.__min_execution_time = min_execution_time |
| 199 |
self.__max_execution_time = max_execution_time |
| 200 |
|
| 201 |
self.__start_time: Optional[datetime] = None |
| 202 |
|
| 203 |
def __enter__(self) -> None: |
| 204 |
self.__start_time = datetime.now() |
| 205 |
|
| 206 |
def __exit__(self, *_: Any) -> None: |
| 207 |
|
| 208 |
if self.__start_time is None: |
| 209 |
return |
| 210 |
|
| 211 |
execution_time = datetime.now() - self.__start_time |
| 212 |
|
| 213 |
if self.__min_execution_time: |
| 214 |
assert execution_time >= self.__min_execution_time |
| 215 |
if self.__max_execution_time: |
| 216 |
assert execution_time <= self.__max_execution_time |