diff --git a/doc/source/mutest.rst b/doc/source/mutest.rst index 4ca1be6..f4ffc38 100644 --- a/doc/source/mutest.rst +++ b/doc/source/mutest.rst @@ -33,6 +33,18 @@ topology with the given configuration file and execute each test on the resulting topology. The munet topology is launched at the start and brought down at the end of each test script. +For debug purposes, mutests can also be run from the munet CLI using the +``test`` command. Note that tests with side effects might fundamentally change +the state of the topology. Furthermore, progess on async internal tasks +(including handling secondary CLI commands) ends up blocked whenever a test is +running. It is recommended for most users that they rely on mutest instead of +the munet ``test`` CLI command. + +.. code-block:: console + + $ sudo munet + > test mutest_*.py + Log Files --------- diff --git a/munet/cli.py b/munet/cli.py index 86c3cd2..371f757 100644 --- a/munet/cli.py +++ b/munet/cli.py @@ -13,6 +13,7 @@ import logging import multiprocessing import os +from pathlib import Path import pty import re import readline @@ -294,6 +295,7 @@ def make_help_str(unet): cli :: open a secondary CLI window help :: this help hosts :: list hosts + test :: run mutests quit :: quit the cli HOST can be a host or one of the following: @@ -456,7 +458,7 @@ async def run_command( outf.write(f"------- End: {host} ------\n") -cli_builtins = ["cli", "help", "hosts", "quit"] +cli_builtins = ["cli", "help", "hosts", "test", "quit"] class Completer: @@ -470,11 +472,36 @@ def complete(self, text, state): tokens = line.split() # print(f"\nXXX: tokens: {tokens} text: '{text}' state: {state}'\n") - first_token = not tokens or (text and len(tokens) == 1) - # If we have already have a builtin command we are done - if tokens and tokens[0] in cli_builtins: - return [None] + if tokens: + if tokens[0] == "test": + return self.complete_test(tokens, text, state) + if tokens[0] in cli_builtins: + return [None] + return self.complete_cmd(tokens, text, state) + + def complete_test(self, tokens, text, state): + if tokens and "/" in tokens[-1]: + return None # Refuse to tab-complete anything not in the configdir + file_select = "mutest_*.py" + config_dir = self.unet.config_dirname + tests_glob = Path(config_dir).glob(file_select) + tests = {str(x.relative_to(Path(config_dir))) for x in tests_glob} + + completes = {x + " " for x in tests if x.startswith(text)} + + # remove any completions already present + if text: + done_set = set(tokens[:-1]) + else: + done_set = set(tokens) + completes -= done_set + completes = sorted(completes) + [None] + + return completes[state] + + def complete_cmd(self, tokens, text, state): + first_token = not tokens or (text and len(tokens) == 1) cli_run_cmds = set(self.unet.cli_run_cmds.keys()) top_run_cmds = {x for x in cli_run_cmds if self.unet.cli_run_cmds[x][3]} @@ -544,6 +571,75 @@ async def doline( background, ) return True + if cmd == "test": + from .mutest.__main__ import execute_test # pylint: disable=import-outside-toplevel + if not nline: + outf.write("% No tests specified\n") + return True + + tnum = 1 + exec_path = unet.rundir.joinpath("munet-test-exec.log") + exec_path.parent.mkdir(parents=True, exist_ok=True) + exec_handler = logging.FileHandler(exec_path, "w") + exec_formatter = logging.Formatter( + "%(asctime)s %(levelname)5s: %(name)s: %(message)s" + ) + exec_handler.setFormatter(exec_formatter) + + # Retrieve the existing console handler and formatter in logconf.yaml + reslog = logging.getLogger("cli.mutest.results") + if not reslog.handlers: + outf.write("% No handler configured for cli.mutest.results\n") + return True + reslog_handler = reslog.handlers[0] + + # Create a replacement targeting the current CLI + out_handler = logging.StreamHandler(outf) + out_handler.setLevel(reslog_handler.level) + out_handler.setFormatter(reslog_handler.formatter) + + # Temporarily swap the handlers + reslog.removeHandler(reslog_handler) + reslog.addHandler(out_handler) + try: + for file_select in nline.split(): + tests_glob = Path(unet.config_dirname).glob(file_select) + tests = sorted(str(x) for x in tests_glob if x.is_file()) + + if not tests: + outf.write(f"% No tests matched: {file_select}\n") + continue + + for test in tests: + # Get test case loggers + cli_logger = logging.getLogger(f"cli.mutest.output.{test}") + cli_reslog = logging.getLogger(f"cli.mutest.results.{test}") + cli_logger.addHandler(exec_handler) + cli_reslog.addHandler(exec_handler) + + try: + await execute_test( + unet, + Path(test), + {}, # Use defaults + tnum, + cli_logger, + cli_reslog, + ) + finally: + cli_logger.removeHandler(exec_handler) + cli_reslog.removeHandler(exec_handler) + tnum += 1 + return True + except ValueError as error: + outf.write(f"% Invalid test: {error}\n") + return True + finally: + # Return logging handlers to normal + reslog.removeHandler(out_handler) + reslog.addHandler(reslog_handler) + out_handler.close() + exec_handler.close() # # In window commands @@ -734,7 +830,8 @@ def write(self, x): self.writer.write(x.encode("utf-8", "ignore")) def flush(self): - self.writer.flush() + # asyncio.StreamWriter has no sync flush; the caller awaits drain() + pass if not await doline(unet, line, EncodingFile(writer), background, notty=True): logging.debug("server closing cli connection") diff --git a/munet/logconf.yaml b/munet/logconf.yaml index 430ee20..0c6a33d 100644 --- a/munet/logconf.yaml +++ b/munet/logconf.yaml @@ -4,6 +4,9 @@ formatters: format: '%(asctime)s: %(levelname)s: %(message)s' precise: format: '%(asctime)s %(levelname)s: %(name)s: %(message)s' + result_color: + class: munet.mulog.ResultColorFormatter + format: '%(levelname)5s: %(message)s' handlers: console: @@ -17,16 +20,33 @@ handlers: level: DEBUG filename: munet-exec.log mode: w + info_console: + level: INFO + class: logging.StreamHandler + formatter: result_color + stream: ext://sys.stderr root: level: DEBUG handlers: [ "console", "file" ] -# these are some loggers that get used. -# loggers: -# munet: -# level: DEBUG -# propagate: true -# munet.base.commander -# level: DEBUG -# propagate: true +loggers: + # these are some loggers that get used. + # munet: + # level: DEBUG + # propagate: true + # munet.base.commander + # level: DEBUG + # propagate: true + cli.mutest.output: + level: DEBUG + # No default handlers. A file handler must be specified in code. + handlers: [] + propagate: false + cli.mutest.results: + level: DEBUG + # Don't log to munet-exec.log, etc. by default in order to separate the test + # logging from the munet logging. Instead, default to only the console. For + # test logging, a file handler must be specified in code. + handlers: [ "info_console" ] + propagate: false diff --git a/munet/mutest/__main__.py b/munet/mutest/__main__.py index 68d799d..ba15400 100644 --- a/munet/mutest/__main__.py +++ b/munet/mutest/__main__.py @@ -195,9 +195,10 @@ async def collect(args: Namespace): async def execute_test( unet: Munet, test: Path, - args: Namespace, + args: dict, test_num: int, - exec_handler: logging.Handler, + logger: logging.Logger, + reslog: logging.Logger, ) -> (int, int, int, Exception): """Execute a test case script. @@ -207,18 +208,13 @@ async def execute_test( Args: unet: a running topology. test: path to the test case script file. - args: argparse results. + args: argparse results as a dict. test_num: the number of this test case in the run. - exec_handler: exec file handler to add to test loggers which do not propagate. + logger: logger to record test run info. + reslog: logger to record test results. """ test_name = testname_from_path(test) - # Get test case loggers - logger = logging.getLogger(f"mutest.output.{test_name}") - reslog = logging.getLogger(f"mutest.results.{test_name}") - logger.addHandler(exec_handler) - reslog.addHandler(exec_handler) - # We need to send an info level log to cause the speciifc handler to be # created, otherwise all these debug ones don't get through reslog.info("") @@ -230,7 +226,7 @@ async def execute_test( targets["."] = unet tc = uapi.TestCase( - str(test_num), test_name, test, targets, args, logger, reslog, args.full_summary + str(test_num), test_name, test, targets, args, logger, reslog, args.get('full_summary', False) ) try: passed, failed, e = tc.execute() @@ -320,8 +316,14 @@ async def run_tests(args): print_header(reslog, unet) printed_header = True + # Get test case loggers + logger = logging.getLogger(f"mutest.output.{test_name}") + reslog = logging.getLogger(f"mutest.results.{test_name}") + logger.addHandler(exec_handler) + reslog.addHandler(exec_handler) + passed, failed, e = await execute_test( - unet, test, args, tnum, exec_handler + unet, test, vars(args), tnum, logger, reslog ) except KeyboardInterrupt as error: errlog.warning("KeyboardInterrupt while running test %s", test_name) diff --git a/munet/mutest/userapi.py b/munet/mutest/userapi.py index b50d082..04604d4 100644 --- a/munet/mutest/userapi.py +++ b/munet/mutest/userapi.py @@ -126,14 +126,14 @@ def pause_test(desc=""): def act_on_result(success, args, desc=""): - if args.pause: + if args.get('pause', False): pause_test(desc) elif success or len(desc) == 0: # No success on description-less steps are not considered errors. return - if args.cli_on_error: + if args.get('cli_on_error', False): raise CLIOnErrorError(desc) - if args.pause_on_error: + if args.get('pause_on_error', False): pause_test(desc) @@ -201,7 +201,7 @@ def __init__( name: str, path: Path, targets: dict, - args: Namespace, + args: dict, output_logger: logging.Logger = None, result_logger: logging.Logger = None, full_summary: bool = False, diff --git a/munet/native.py b/munet/native.py index acc5d0e..8db774e 100644 --- a/munet/native.py +++ b/munet/native.py @@ -690,6 +690,7 @@ def __init__( self.__base_cmd.append("-q") self.__base_cmd.append("-oStrictHostKeyChecking=no") self.__base_cmd.append("-oUserKnownHostsFile=/dev/null") + self.__base_cmd.append("-oBatchMode=yes") if self.idfile: self.__base_cmd.append(f"-i{self.idfile}") # Would be nice but has to be accepted by server config so not very useful. @@ -1857,6 +1858,7 @@ def __setup_ssh(self): self.__base_cmd.append("-q") self.__base_cmd.append("-oStrictHostKeyChecking=no") self.__base_cmd.append("-oUserKnownHostsFile=/dev/null") + self.__base_cmd.append("-oBatchMode=yes") # Would be nice but has to be accepted by server config so not very useful. # self.__base_cmd.append("-oSendVar='TEST'") self.__base_cmd_pty = list(self.__base_cmd) diff --git a/tests/cli/mutest_cli_a.py b/tests/cli/mutest_cli_a.py new file mode 100644 index 0000000..93d286b --- /dev/null +++ b/tests/cli/mutest_cli_a.py @@ -0,0 +1,3 @@ +"""CLI test fixture A.""" +from munet.mutest.userapi import match_step +match_step("r1", "echo CLI_A_OK", "CLI_A_OK", "CLI marker A") diff --git a/tests/cli/mutest_cli_b.py b/tests/cli/mutest_cli_b.py new file mode 100644 index 0000000..af29694 --- /dev/null +++ b/tests/cli/mutest_cli_b.py @@ -0,0 +1,3 @@ +"""CLI test fixture B.""" +from munet.mutest.userapi import match_step +match_step("r1", "echo CLI_B_OK", "CLI_B_OK", "CLI marker B") diff --git a/tests/cli/subdir/cli_mutest_fail.py b/tests/cli/subdir/cli_mutest_fail.py new file mode 100644 index 0000000..9ce51c5 --- /dev/null +++ b/tests/cli/subdir/cli_mutest_fail.py @@ -0,0 +1,3 @@ +"""Intentionally failing CLI test fixture.""" +from munet.mutest.userapi import match_step +match_step("r1", "echo CLI_FAIL_INPUT", "DOES_NOT_MATCH", "CLI deliberate failure") diff --git a/tests/cli/test_cli_mutest.py b/tests/cli/test_cli_mutest.py new file mode 100644 index 0000000..1c8e712 --- /dev/null +++ b/tests/cli/test_cli_mutest.py @@ -0,0 +1,141 @@ +# -*- coding: utf-8 eval: (blacken-mode 1) -*- +# SPDX-License-Identifier: GPL-2.0-or-later +# +# November 17 2026, Liam Brady +# +# Copyright 2026, LabN Consulting, L.L.C. +# +"""Test invoking mutest from the munet CLI.""" + +import io +import logging +import re +from pathlib import Path + +import pytest + +from munet import cli + +pytestmark = [ + pytest.mark.asyncio, + pytest.mark.parametrize("unet", [True, False], indirect=["unet"]), +] + +# pylint: disable=redefined-outer-name + +@pytest.fixture +def cli_mutest_logging(): + """Configure the results logger as munet's logconf.yaml normally would.""" + # Save the old global logging configuration + reslog = logging.getLogger("cli.mutest.results") + olog = logging.getLogger("cli.mutest.output") + old_reslog = (reslog.level, reslog.propagate, tuple(reslog.handlers)) + old_olog = (olog.level, olog.propagate) + + # Replace the global logging configuration with a string IO handler + for handler in old_reslog[2]: + reslog.removeHandler(handler) + + handler = logging.StreamHandler(io.StringIO()) + handler.setLevel(logging.INFO) + handler.setFormatter(logging.Formatter("%(levelname)5s: %(message)s")) + reslog.addHandler(handler) + reslog.setLevel(logging.DEBUG) + reslog.propagate = False + olog.setLevel(logging.DEBUG) + olog.propagate = False + + try: + yield handler + finally: + # Restore the old global logging configuration + for current in tuple(reslog.handlers): + reslog.removeHandler(current) + if current not in old_reslog[2]: + current.close() + for original in old_reslog[2]: + reslog.addHandler(original) + reslog.setLevel(old_reslog[0]) + reslog.propagate = old_reslog[1] + olog.setLevel(old_olog[0]) + olog.propagate = old_olog[1] + + +async def run_cli_command(unet, command): + stdout = io.StringIO() + assert await cli.doline(unet, command, stdout) + return stdout.getvalue() + + +async def test_mutest_cli_basic(unet, cli_mutest_logging): + output = await run_cli_command(unet, "test mutest_cli_a.py") + assert re.search(r"PASS.*CLI marker A", output), output + assert output.count("CLI marker A") == 1 + + logfile = unet.rundir / "munet-test-exec.log" + text = logfile.read_text(encoding="utf-8") + assert "CLI_A_OK" in text + assert "CLI marker A" in text + assert logging.getLogger("cli.mutest.results").handlers == [cli_mutest_logging] + + +async def test_mutest_cli_repeated(unet, cli_mutest_logging): + test_path = Path(unet.config_dirname) / "mutest_cli_a.py" + result_logger = logging.getLogger(f"cli.mutest.results.{test_path}") + output_logger = logging.getLogger(f"cli.mutest.output.{test_path}") + before_result = tuple(result_logger.handlers) + before_output = tuple(output_logger.handlers) + + for _ in range(2): + output = await run_cli_command(unet, "test mutest_cli_a.py") + assert output.count("CLI marker A") == 1, output + assert tuple(result_logger.handlers) == before_result + assert tuple(output_logger.handlers) == before_output + # Ensure that logging handlers are not accumulated accidentally + assert logging.getLogger("cli.mutest.results").handlers == [cli_mutest_logging] + + text = (unet.rundir / "munet-test-exec.log").read_text(encoding="utf-8") + result_lines = [ + line for line in text.splitlines() + if "cli.mutest.results." in line and "CLI marker A" in line + ] + assert len(result_lines) == 1, result_lines + + +async def test_mutest_cli_glob_order(unet, cli_mutest_logging): # pylint: disable=unused-argument + output = await run_cli_command(unet, "test mutest_cli_[ab].py") + assert output.count("CLI marker A") == 1, output + assert output.count("CLI marker B") == 1, output + assert output.index("CLI marker A") < output.index("CLI marker B") + + +async def test_mutest_cli_no_match(unet, cli_mutest_logging): # pylint: disable=unused-argument + output = await run_cli_command(unet, "test mutest_missing.py mutest_cli_a.py") + assert "% No tests matched: mutest_missing.py" in output + assert re.search(r"PASS.*CLI marker A", output), output + + +async def test_mutest_cli_nested_failure(unet, cli_mutest_logging): + # Ensures two things: + # 1. Specifically selected tests (not in configdir) still execute + # 2. Failing mutests report failures to the CLI + output = await run_cli_command(unet, "test subdir/cli_mutest_fail.py") + assert re.search(r"FAIL.*CLI deliberate failure", output), output + assert output.count("CLI deliberate failure") == 1 + assert logging.getLogger("cli.mutest.results").handlers == [cli_mutest_logging] + + +async def test_mutest_cli_no_args(unet, cli_mutest_logging): + output = await run_cli_command(unet, "test") + assert "No tests specified" in output, output + assert logging.getLogger("cli.mutest.results").handlers == [cli_mutest_logging] + + +async def test_mutest_cli_multiple_explicit(unet, cli_mutest_logging): + output = await run_cli_command( + unet, "test mutest_cli_b.py mutest_cli_a.py" + ) + assert output.count("CLI marker A") == 1, output + assert output.count("CLI marker B") == 1, output + assert output.index("CLI marker B") < output.index("CLI marker A") + assert logging.getLogger("cli.mutest.results").handlers == [cli_mutest_logging] diff --git a/tests/common/sshd_config.tpl b/tests/common/sshd_config.tpl index 70cc0af..5a36603 100644 --- a/tests/common/sshd_config.tpl +++ b/tests/common/sshd_config.tpl @@ -3,6 +3,10 @@ AuthorizedKeysCommand /ssh/akeycmd.sh AuthorizedKeysCommandUser nobody HostKey $PWD/ssh_host_rsa_key PidFile $PWD/sshd.pid -UsePAM no -PermitEmptyPasswords yes + +# Without PAM, a locked root password also prevents SSH key authentication. +# Enable PAM to allow key authentication even when the root password is locked. +UsePAM yes +PasswordAuthentication no +KbdInteractiveAuthentication no PermitRootLogin without-password \ No newline at end of file diff --git a/tests/kinds.yaml b/tests/kinds.yaml index 9c79f30..d65a274 100644 --- a/tests/kinds.yaml +++ b/tests/kinds.yaml @@ -11,8 +11,8 @@ kinds: - name: sshserver cmd: | chmod 755 -R /ssh - ssh-keygen -b 2048 -t rsa -f ../id_rsa -q -N "" - ssh-keygen -b 2048 -t rsa -f ssh_host_rsa_key -q -N "" + test -e ../id_rsa || ssh-keygen -b 2048 -t rsa -f ../id_rsa -q -N "" + test -e ssh_host_rsa_key || ssh-keygen -b 2048 -t rsa -f ssh_host_rsa_key -q -N "" [ -z "${SUDO_USER}" ] || chown ${SUDO_USER} ../id_rsa printf '#!/bin/bash\ncat %RUNDIR%/../id_rsa.pub' > /ssh/akeycmd.sh chmod 755 /ssh/akeycmd.sh