Skip to content

Instantly share code, notes, and snippets.

@nrbnlulu
Created September 20, 2023 08:34
Show Gist options
  • Save nrbnlulu/cdf31c38b5d7c4abd6296dc6aa5ee088 to your computer and use it in GitHub Desktop.
Save nrbnlulu/cdf31c38b5d7c4abd6296dc6aa5ee088 to your computer and use it in GitHub Desktop.
Run ctest tests from python
from __future__ import annotations
import json
import re
import subprocess
from pathlib import Path
import pytest
from typing_extensions import TypedDict
PROJECT_ROOT = Path(__file__).parent.parent
build_dir = PROJECT_ROOT / "build" / "Debug"
class CtestTestProperty(TypedDict):
name: str
value: str
class CtestTestDefinition(TypedDict):
name: str
properties: list[CtestTestProperty]
class CtestDiscoveryResult(TypedDict):
tests: list[CtestTestDefinition]
class CtestTestCommand:
def __init__(self, test_name: str) -> None:
self._data: list[str] = ["ctest", "-R"]
self.test_name: str = test_name
self.ret_res: subprocess.CompletedProcess | None = None
def add_command(self, command: str):
self._data.append(command)
def run(self) -> None:
self.ret_res = subprocess.run(
[*self._data, self.test_name],
cwd=build_dir.resolve(True),
capture_output=True,
)
try:
match = re.findall("(in: )(.*)(\\.log)", self.ret_res.stderr.decode())
log_file = match[0][1]
except IndexError:
return
pytest.fail(Path(log_file + ".log").resolve(True).read_text("utf-8"))
def collect_tests() -> list[CtestTestCommand]:
ret: list[CtestTestCommand] = []
res = subprocess.run(
["ctest", "--show-only=json-v1"],
cwd=build_dir.resolve(True),
capture_output=True,
)
data: CtestDiscoveryResult = json.loads(res.stdout)
for test in data["tests"]:
ret.append(CtestTestCommand(test["name"]))
return ret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment