diff --git a/tests/conftest.py b/tests/conftest.py index 1b1f7b3..798849c 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -33,7 +33,10 @@ configure_fixed_ip, ensure_batman_mesh, is_qemu_target, + lime_report_dir, + lime_report_filename, resolve_target_yaml, + save_lime_report, suppress_kernel_console, ) @@ -181,7 +184,12 @@ def collect_lime_report(pytestconfig): Runs as a session-scoped autouse fixture so it tears down BEFORE labgrid's ``env.cleanup()`` — the SSHDriver is still active here. - Writes the output to the path in ``LIME_REPORT_OUTPUT`` if set. + + Output path: ``LIME_REPORT_OUTPUT`` if set, otherwise + ``lime-report.md`` inside the directory resolved by + :func:`lime_helpers.lime_report_dir` (``LIME_REPORT_DIR`` or the + ``--lg-log`` directory). Every CI job passes ``--lg-log``, so physical + and QEMU runs both end with a report next to the console logs. Resolves the labgrid target lazily via pytestconfig.stash instead of depending on the ``target`` fixture directly, mirroring the pattern used @@ -189,12 +197,19 @@ def collect_lime_report(pytestconfig): (conftest_mesh.py) run without ``--lg-env`` and therefore labgrid never creates an ``env``. If this fixture depended on ``target``, every mesh session would be aborted with ``missing environment config (use --lg-env)``. + Mesh sessions collect one report per node in the ``mesh_nodes`` teardown + (conftest_mesh.py), while the VMs/DUTs are still up. """ yield - report_path = os.environ.get("LIME_REPORT_OUTPUT") - if not report_path: - return + explicit_output = os.environ.get("LIME_REPORT_OUTPUT", "").strip() + if explicit_output: + report_path = Path(explicit_output) + else: + report_dir = lime_report_dir(pytestconfig) + if report_dir is None: + return + report_path = report_dir / lime_report_filename() try: from labgrid.pytestplugin.hooks import LABGRID_ENV_KEY @@ -204,8 +219,8 @@ def collect_lime_report(pytestconfig): env = None if env is None: - # No labgrid env active (typical for multi-node mesh tests): skip - # lime-report silently; mesh-specific reporting lives in conftest_mesh. + # No labgrid env active (multi-node mesh session): the per-node + # reports are written by the mesh_nodes fixture teardown. return try: @@ -213,18 +228,16 @@ def collect_lime_report(pytestconfig): if target is None: return ssh = target.get_driver("SSHDriver") - stdout, stderr, rc = ssh.run("lime-report", timeout=60) - output = "\n".join(stdout).strip() - if not output: - output = "_lime-report ran but produced no output._" - Path(report_path).write_text(output) - print( - f"\nlime-report collected: {len(output)} bytes → {report_path}", flush=True - ) - except Exception as exc: + except Exception as exc: # noqa: BLE001 - report collection must not abort teardown msg = f"_Could not collect lime-report: {exc}_" - print(f"\n[WARN] {msg}", file=__import__("sys").stderr, flush=True) + print(f"\n[WARN] {msg}", file=sys.stderr, flush=True) try: - Path(report_path).write_text(msg) - except Exception: + report_path.parent.mkdir(parents=True, exist_ok=True) + report_path.write_text(msg + "\n") + except OSError: pass + return + + ok = save_lime_report(report_path, ssh.run) + status = "collected" if ok else "NOT collected (see file for reason)" + print(f"\nlime-report {status} → {report_path}", flush=True) diff --git a/tests/conftest_mesh.py b/tests/conftest_mesh.py index 0c52678..d08f4f6 100644 --- a/tests/conftest_mesh.py +++ b/tests/conftest_mesh.py @@ -43,7 +43,14 @@ import pytest from conftest_vlan import _resolve_proxy_host -from lime_helpers import REPO_ROOT, generate_mesh_ssh_ip, resolve_target_yaml +from lime_helpers import ( + REPO_ROOT, + generate_mesh_ssh_ip, + lime_report_dir, + lime_report_filename, + resolve_target_yaml, + save_lime_report, +) # Allow importing scripts from repo root if str(REPO_ROOT) not in sys.path: @@ -273,6 +280,29 @@ def run( except subprocess.TimeoutExpired: return [], ["SSH command timed out"], 1 + def run_raw( + self, command: str, timeout: int = SSH_COMMAND_TIMEOUT + ) -> tuple[list[str], list[str], int]: + """Like :meth:`run` but keeps blank lines and does not retry. + + Used for long, formatted output such as ``lime-report`` (Markdown), + where dropping empty lines breaks the layout. + """ + try: + result = subprocess.run( + self._build_ssh_cmd(command), + capture_output=True, + text=True, + timeout=timeout, + ) + except subprocess.TimeoutExpired: + return [], ["SSH command timed out"], 1 + return ( + result.stdout.splitlines(), + result.stderr.splitlines(), + result.returncode, + ) + @dataclass class MeshNode: @@ -547,7 +577,28 @@ def _configure_vwifi_node( return rc == 0 -def _mesh_nodes_virtual(): +def _collect_mesh_lime_reports(config, nodes: list["MeshNode"]) -> None: + """Write one ``lime-report-.md`` per mesh node before teardown. + + Destination is :func:`lime_helpers.lime_report_dir` (``LIME_REPORT_DIR`` + or the ``--lg-log`` directory). Failures are logged, never raised, so a + node that died mid-session does not hide the reports of the others. + """ + report_dir = lime_report_dir(config) + if report_dir is None or not nodes: + return + for node in nodes: + path = report_dir / lime_report_filename(node.place) + ok = save_lime_report(path, node.ssh.run_raw) + logger.info( + "Node %s: lime-report %s → %s", + node.place, + "collected" if ok else "NOT collected", + path, + ) + + +def _mesh_nodes_virtual(config=None): """Launch virtual mesh (QEMU + vwifi) and yield MeshNode list. Uses LG_VIRTUAL_MESH=1, VIRTUAL_MESH_IMAGE, VIRTUAL_MESH_NODES. @@ -628,10 +679,12 @@ def _mesh_nodes_virtual(): ) _wait_for_network(mesh_nodes_list, timeout=settle_timeout) - yield mesh_nodes_list - - logger.info("Tearing down %d virtual mesh nodes", len(mesh_nodes_list)) - cleanup() + try: + yield mesh_nodes_list + finally: + _collect_mesh_lime_reports(config, mesh_nodes_list) + logger.info("Tearing down %d virtual mesh nodes", len(mesh_nodes_list)) + cleanup() @pytest.fixture(scope="session") @@ -650,7 +703,7 @@ def mesh_nodes(request, mesh_vlan_multi): Virtual: LG_VIRTUAL_MESH=1, VIRTUAL_MESH_IMAGE, VIRTUAL_MESH_NODES. """ if os.environ.get("LG_VIRTUAL_MESH") == "1": - yield from _mesh_nodes_virtual() + yield from _mesh_nodes_virtual(request.config) return places_str = os.environ.get("LG_MESH_PLACES", "") @@ -841,7 +894,12 @@ def mesh_nodes(request, mesh_vlan_multi): ) _wait_for_network(nodes, timeout=settle_timeout) - yield nodes + try: + yield nodes + finally: + # DUTs are still powered and reachable here; the boot + # subprocesses below are what power them down. + _collect_mesh_lime_reports(request.config, nodes) finally: if procs: logger.info("Tearing down %d mesh boot subprocesses", len(procs)) diff --git a/tests/lime_helpers.py b/tests/lime_helpers.py index fde1e1c..cf80456 100644 --- a/tests/lime_helpers.py +++ b/tests/lime_helpers.py @@ -858,3 +858,75 @@ def ensure_batman_mesh(target, place_name: str | None = None) -> bool: logger.warning("Could not activate batman-adv mesh") return False + + +# --------------------------------------------------------------------------- +# End-of-session lime-report +# --------------------------------------------------------------------------- + +LIME_REPORT_TIMEOUT = _read_int_env("LIME_REPORT_TIMEOUT", 180) + + +def lime_report_dir(config=None) -> Path | None: + """Return the directory where end-of-session lime-report files go. + + Resolution order: + 1. ``LIME_REPORT_DIR`` env var. + 2. Parent directory of ``LIME_REPORT_OUTPUT`` (legacy single-file knob). + 3. labgrid's ``--lg-log`` directory, so every CI job that already uploads + its log directory gets the report without extra configuration. + + Returns ``None`` when none of them is set (local runs without logging). + """ + explicit = os.environ.get("LIME_REPORT_DIR", "").strip() + if explicit: + return Path(explicit) + output = os.environ.get("LIME_REPORT_OUTPUT", "").strip() + if output: + return Path(output).parent + option = getattr(config, "option", None) + lg_log = getattr(option, "lg_log", None) + if lg_log: + return Path(lg_log) + return None + + +def lime_report_filename(label: str | None = None) -> str: + """``lime-report.md`` for single-node runs, ``lime-report-