diff --git a/README.md b/README.md index ba0fbad..a0eefd4 100644 --- a/README.md +++ b/README.md @@ -163,6 +163,8 @@ commands: # exception: { name: ValueError, message: "..." } # or names: [A, B] # require_platform: [Linux] # skip on other platforms # local_files: { files: {...}, dirs: {...}, links: {...} } +# config: { DIFF: true } # per-case pyinfra Config +# expected_logs: { contains: [...], excludes: [...] } ``` Operations are invoked via `op._inner(*args, **kwargs)`. If a case yields no @@ -181,6 +183,49 @@ Yielded commands may be plain strings, `StringCommand`, `FunctionCommand`, `FileUploadCommand`/`FileDownloadCommand` (compared as `["upload", data, dest]` / `["download", src, dest]`), or a connector-argument dict. +### Operation configuration + +Operation cases accept a `config` mapping of pyinfra `Config` options. For +example, to enable content diffs: + +```yaml +config: + DIFF: true +``` + +Each case gets a fresh state and configuration. Options omitted from `config` +use pyinfra's defaults, and changes do not carry over to other cases. + +### Checking logs + +Both fact and operation cases accept `expected_logs`. `contains` and `excludes` +are lists of literal, case-sensitive substrings checked against formatted +messages from the `pyinfra` logger and its descendants, including DEBUG messages +and logged exception tracebacks. Either list can be omitted. An `excludes` +check passes if no messages are logged, add a `contains` check when you +also want to confirm that an expected message was logged. + +```yaml +args: ["hidden:test-password"] +commands: + - raw: "echo test-password" + masked: "echo *MASKED*" +expected_logs: + contains: ["Preparing operation"] + excludes: ["test-password"] +``` + +This example assumes an operation that logs `Preparing operation` and yields +`StringCommand("echo", secret)`. The `hidden:` prefix creates a `HiddenValue`, +including inside nested argument dictionaries and lists. Expected commands +still contain the raw data intended for execution or upload. + +If a check fails, the error message shows the expected or forbidden string and +the captured logs. Cases without `expected_logs` leave logging settings alone. + +The harness checks pyinfra logs emitted while generating commands and processing +facts, not output of the commands, since they are not executed. + ### Enum and dataclass arguments `args`/`kwargs` are coerced to the operation's annotated parameter types using @@ -208,6 +253,8 @@ prefix: - `"datetime:2025-01-01T00:00:00"` → `datetime` - `"path:/etc/hosts"` → `pathlib.Path` +- `"io:template contents"` → `io.StringIO` +- `"hidden:test-password"` → `pyinfra.api.HiddenValue` - `["set:", "a", "b"]` → `set` ## Running diff --git a/pyinfra_testing/facts.py b/pyinfra_testing/facts.py index e63f5f9..d096d28 100644 --- a/pyinfra_testing/facts.py +++ b/pyinfra_testing/facts.py @@ -13,6 +13,7 @@ from pyinfra.context import ctx_host, ctx_state from pyinfra_cli.util import json_encode +from .logs import assert_logs, capture_logs from .testgen import TestGenerator from .util import FakeState, canonical_mapping_key, create_host, get_command_string @@ -83,16 +84,16 @@ class TestTests( test_prefix=f"test_{fact.name}_", test_method="_test", ): - @classmethod - def setUpClass(cls): - # Create a global fake state that attach to context state - cls.state = FakeState() + def setUp(self): + self.state = FakeState() def _test(self, test_name, test_data, fact=fact): host = create_host(self.state, facts=test_data.get("facts", {})) - with ctx_state.use(self.state): - with ctx_host.use(host): - self._test_fn(test_name, test_data, fact) + with capture_logs(enabled=test_data.get("expected_logs") is not None) as logs: + with ctx_state.use(self.state): + with ctx_host.use(host): + self._test_fn(test_name, test_data, fact) + assert_logs(logs.getvalue(), test_data.get("expected_logs")) def _test_fn(self, test_name, test_data, fact): short_fact = None diff --git a/pyinfra_testing/logs.py b/pyinfra_testing/logs.py new file mode 100644 index 0000000..2df9333 --- /dev/null +++ b/pyinfra_testing/logs.py @@ -0,0 +1,55 @@ +"""Optional log assertions for generated fact and operation tests.""" + +import logging +from collections.abc import Iterator +from contextlib import contextmanager +from io import StringIO + +from pyinfra import logger + + +@contextmanager +def capture_logs(enabled: bool = True) -> Iterator[StringIO]: + """Capture formatted pyinfra logs and restore logging settings afterward.""" + output = StringIO() + if not enabled: + yield output + return + + handler = logging.StreamHandler(output) + old_level = logger.level + logger.addHandler(handler) + logger.setLevel(logging.DEBUG) + try: + yield output + finally: + logger.removeHandler(handler) + logger.setLevel(old_level) + handler.close() + + +def assert_logs(messages: str, expected: dict[str, list[str]] | None) -> None: + """Check captured messages against a case's contains/excludes expectations.""" + if expected is None: + return + + if not isinstance(expected, dict) or expected.keys() - {"contains", "excludes"}: + raise ValueError("expected_logs must be a mapping with contains/excludes lists") + for values in expected.values(): + if not isinstance(values, list) or not all( + isinstance(item, str) for item in values + ): + raise ValueError("expected_logs contains/excludes must be lists of strings") + + for message in expected.get("excludes", []): + if message in messages: + raise AssertionError( + f"Unexpected substring in pyinfra logs: {message!r}\n" + f"Captured logs:\n{messages}" + ) + for message in expected.get("contains", []): + if message not in messages: + raise AssertionError( + f"Expected substring missing from pyinfra logs: {message!r}\n" + f"Captured logs:\n{messages}" + ) diff --git a/pyinfra_testing/operations.py b/pyinfra_testing/operations.py index fc2b672..0776dfc 100644 --- a/pyinfra_testing/operations.py +++ b/pyinfra_testing/operations.py @@ -9,9 +9,10 @@ from pyinfra.api.command import PyinfraCommand +from .logs import assert_logs, capture_logs from .testgen import TestGenerator -from pyinfra.api import FileDownloadCommand, FileUploadCommand, FunctionCommand, StringCommand +from pyinfra.api import Config, FileDownloadCommand, FileUploadCommand, FunctionCommand, StringCommand from pyinfra.context import ctx_host, ctx_state from pyinfra_cli.util import json_encode @@ -111,20 +112,21 @@ class TestTests( test_prefix=f"test_{module_name}_{op_name}_", test_method="_test", ): - @classmethod - def setUpClass(cls): - # Create a global fake state that attach to context state - cls.state = FakeState() + def setUp(self): + self.state = FakeState() def _test(self, test_name, test_data): if ( "require_platform" in test_data and PLATFORM_NAME not in test_data["require_platform"] ): - return + self.skipTest(f"Requires platform: {test_data['require_platform']}") op_test_name = f"{operation_path}/{test_name}.json" + if "config" in test_data: + self.state.config = Config(**test_data["config"]) + # Create a host with this tests facts and attach to context host host = create_host(self.state, facts=test_data.get("facts", {})) @@ -135,25 +137,28 @@ def _test(self, test_name, test_data): # Coerce values to the operation's annotated enum/dataclass types. args, kwargs = coerce_operation_arguments(op, args, kwargs) - with ctx_state.use(self.state): - with ctx_host.use(host): - with patch_files(test_data.get("local_files", {})): - try: - output_commands = list(op._inner(*args, **kwargs)) - except Exception as e: - if allowed_exception: - allowed_exception_names = allowed_exception.get("names") - if not allowed_exception_names: - allowed_exception_names = [allowed_exception["name"]] - - if e.__class__.__name__ not in allowed_exception_names: - print("Wrong exception raised!") - raise - - assert e.args[0] == allowed_exception["message"] - return - - raise + with capture_logs(enabled=test_data.get("expected_logs") is not None) as logs: + with ctx_state.use(self.state): + with ctx_host.use(host): + with patch_files(test_data.get("local_files", {})): + try: + output_commands = list(op._inner(*args, **kwargs)) + except Exception as e: + if allowed_exception: + allowed_exception_names = allowed_exception.get("names") + if not allowed_exception_names: + allowed_exception_names = [allowed_exception["name"]] + + if e.__class__.__name__ not in allowed_exception_names: + print("Wrong exception raised!") + raise + + assert e.args[0] == allowed_exception["message"] + return + + raise + + assert_logs(logs.getvalue(), test_data.get("expected_logs")) commands = parse_commands(output_commands) assert_commands(commands, test_data["commands"]) diff --git a/pyinfra_testing/util.py b/pyinfra_testing/util.py index c33a1f8..a20a8dd 100644 --- a/pyinfra_testing/util.py +++ b/pyinfra_testing/util.py @@ -13,7 +13,8 @@ from pathlib import Path from unittest.mock import patch -from pyinfra.api import Config, Inventory +from pyinfra import logger +from pyinfra.api import Config, HiddenValue, Inventory from pyinfra.api.arguments import all_argument_meta from pyinfra.api.util import get_kwargs_str @@ -56,6 +57,8 @@ def parse_value(value): return Path(value[5:]) if value.startswith("io:"): return StringIO(value[3:]) + if value.startswith("hidden:"): + return HiddenValue(value[7:]) return value if isinstance(value, list): @@ -332,6 +335,9 @@ def print_prefix(self): def noop(self, description): self.noop_description = description + def log(self, message, log_func=logger.info): + log_func(f"{self.print_prefix}{message}") + def get_temp_filename(*args, **kwargs): return "_tempfile_" diff --git a/tests/_fixtures.py b/tests/_fixtures.py index 56efa08..7c01ad8 100644 --- a/tests/_fixtures.py +++ b/tests/_fixtures.py @@ -6,9 +6,10 @@ """ import enum +import logging from dataclasses import dataclass -from pyinfra import host +from pyinfra import host, logger from pyinfra.api import FactBase, StringCommand, operation @@ -53,3 +54,30 @@ def sample_op(name, color: Color | None = None, opts: Opts | None = None, presen def fact_op(name): fact = host.get_fact(SampleFact, _sudo=True) yield StringCommand("echo", name, str(fact["value"])) + + +@operation() +def logging_op(value): + logging.getLogger("pyinfra.testing").debug("value=%s", value) + yield StringCommand("echo", value) + + +class LoggingFact(SampleFact): + def process(self, output): + logger.warning("Processing value %s", output[0]) + return super().process(output) + + +@operation() +def stateful_op(): + yield StringCommand("echo", host.state.cwd, str(host.state.config.DIFF)) + host.state.cwd = "/changed" + host.state.config.DIFF = True + + +class StatefulFact(SampleFact): + def process(self, output): + result = {"cwd": host.state.cwd, "diff": host.state.config.DIFF} + host.state.cwd = "/changed" + host.state.config.DIFF = True + return result diff --git a/tests/test_logs.py b/tests/test_logs.py new file mode 100644 index 0000000..e1cb1bb --- /dev/null +++ b/tests/test_logs.py @@ -0,0 +1,219 @@ +"""Exercise log assertions through generated unittest cases.""" + +import logging + +import pytest +import yaml +from pyinfra import logger + +from pyinfra_testing.facts import make_fact_tests +from pyinfra_testing.logs import assert_logs, capture_logs +from pyinfra_testing.operations import make_operation_tests + +from tests.test_make_tests_e2e import run, write_cases + + +def logging_case(**overrides): + return { + "args": ["test-value"], + "commands": ["echo test-value"], + "expected_logs": { + "contains": ["value=test-value"], + "excludes": ["not-logged"], + }, + **overrides, + } + + +def test_operation_log_expectations_pass(tmp_path): + write_cases(tmp_path, {"logs": logging_case()}) + result = run(make_operation_tests("tests", "_fixtures.logging_op", tmp_path)) + assert result.testsRun == 1 + assert result.wasSuccessful(), result.failures or result.errors + + +def test_forbidden_string_in_formatted_message_fails(tmp_path): + write_cases( + tmp_path, + { + "forbidden": logging_case(expected_logs={"excludes": ["test-value"]}), + }, + ) + result = run(make_operation_tests("tests", "_fixtures.logging_op", tmp_path)) + assert len(result.failures) == 1 + failure = result.failures[0][1] + assert "Unexpected substring in pyinfra logs: 'test-value'" in failure + assert "Captured logs:\nvalue=test-value" in failure + assert not result.errors + + +def test_missing_log_failure_shows_expected_string_and_captured_logs(tmp_path): + write_cases( + tmp_path, + { + "missing": logging_case(expected_logs={"contains": ["Missing message"]}), + }, + ) + result = run(make_operation_tests("tests", "_fixtures.logging_op", tmp_path)) + assert len(result.failures) == 1 + failure = result.failures[0][1] + assert "Expected substring missing from pyinfra logs: 'Missing message'" in failure + assert "Captured logs:\nvalue=test-value" in failure + assert not result.errors + + +def test_forbidden_string_in_logged_traceback_fails(): + with capture_logs() as logs: + try: + raise ValueError("test-value") + except ValueError: + logger.exception("Operation failed") + + with pytest.raises(AssertionError, match="Unexpected substring") as error: + assert_logs(logs.getvalue(), {"excludes": ["test-value"]}) + assert "ValueError: test-value" in str(error.value) + + +@pytest.mark.parametrize( + "expected, succeeds", + [ + ({"excludes": ["s3cr3t"]}, True), + ({"contains": ["missing log"]}, False), + ], +) +def test_silent_operation(tmp_path, expected, succeeds): + write_cases( + tmp_path, + { + "silent": { + "args": ["hello"], + "commands": ["echo hello"], + "expected_logs": expected, + }, + }, + ) + result = run(make_operation_tests("tests", "_fixtures.sample_op", tmp_path)) + assert result.wasSuccessful() is succeeds + assert not result.errors + + +@pytest.mark.parametrize("forbidden, succeeds", [("s3cr3t", True), ("42", False)]) +def test_fact_logs(tmp_path, forbidden, succeeds): + write_cases( + tmp_path, + { + "fact": { + "command": "echo sample", + "requires_command": "echo", + "output": ["42"], + "fact": {"value": 42}, + "expected_logs": { + "contains": ["Processing value 42"], + "excludes": [forbidden], + }, + }, + }, + ) + result = run(make_fact_tests("tests", "_fixtures.LoggingFact", tmp_path)) + assert result.wasSuccessful() is succeeds + assert not result.errors + + +def test_config_is_scoped_to_each_case(tmp_path): + write_cases( + tmp_path, + { + "diff": {"config": {"DIFF": True}, "commands": ["echo / True"]}, + "no_diff": {"commands": ["echo / False"]}, + }, + ) + result = run(make_operation_tests("tests", "_fixtures.stateful_op", tmp_path)) + assert result.testsRun == 2 + assert result.wasSuccessful(), result.failures or result.errors + + +def test_platform_skip_does_not_require_logs(tmp_path): + write_cases( + tmp_path, {"skip": logging_case(require_platform=["unsupported-platform"])} + ) + result = run(make_operation_tests("tests", "_fixtures.logging_op", tmp_path)) + assert result.wasSuccessful() + assert len(result.skipped) == 1 + + +@pytest.mark.parametrize( + "expected", + [ + {"contains": ["test-value"]}, + {"excludes": ["test-value"]}, + ], +) +def test_logger_settings_restored_even_on_failure(tmp_path, expected): + write_cases(tmp_path, {"restore": logging_case(expected_logs=expected)}) + old_level = logger.level + handlers = logger.handlers[:] + logger.setLevel(logging.ERROR) + try: + run(make_operation_tests("tests", "_fixtures.logging_op", tmp_path)) + assert logger.level == logging.ERROR + assert logger.handlers == handlers + finally: + logger.setLevel(old_level) + + +def test_log_capture_restores_settings_after_exception(): + old_level = logger.level + handlers = logger.handlers[:] + with pytest.raises(ValueError, match="test error"): + with capture_logs(): + raise ValueError("test error") + assert logger.level == old_level + assert logger.handlers == handlers + + +@pytest.mark.parametrize( + "expected", + [ + {"exclude": ["s3cr3t"]}, + {"excludes": "s3cr3t"}, + {"contains": [42]}, + ["s3cr3t"], + ], +) +def test_invalid_expectations_are_rejected(tmp_path, expected): + write_cases(tmp_path, {"invalid": logging_case(expected_logs=expected)}) + result = run(make_operation_tests("tests", "_fixtures.logging_op", tmp_path)) + assert len(result.errors) == 1 + assert "ValueError: expected_logs" in result.errors[0][1] + + +@pytest.mark.parametrize("updating", [False, True]) +def test_template_diff_logs_from_yaml_case(tmp_path, updating): + facts = { + "files.File": {"path=/etc/config": None}, + "files.Directory": {"path=/etc/config": None}, + } + contains = ["Will create", "setting=public"] + if updating: + facts.update( + { + "files.File": { + "path=/etc/config": {"mode": 644, "user": "root", "group": "root"} + }, + "files.Sha1File": {"path=/etc/config": "different"}, + "files.FileContents": {"path=/etc/config": ["setting=old"]}, + } + ) + contains = ["Will modify", "setting=old", "setting=public"] + case = { + "args": ["io:setting={{ value }}", "/etc/config"], + "kwargs": {"create_remote_dir": False, "value": "public"}, + "config": {"DIFF": True}, + "facts": facts, + "commands": [["upload", "setting=public", "/etc/config"]], + "expected_logs": {"contains": contains, "excludes": ["s3cr3t"]}, + } + (tmp_path / "template.yaml").write_text(yaml.safe_dump(case), encoding="utf-8") + result = run(make_operation_tests("pyinfra.operations", "files.template", tmp_path)) + assert result.testsRun == 1 + assert result.wasSuccessful(), result.failures or result.errors diff --git a/tests/test_make_tests_e2e.py b/tests/test_make_tests_e2e.py index efc1bc1..61051c1 100644 --- a/tests/test_make_tests_e2e.py +++ b/tests/test_make_tests_e2e.py @@ -10,6 +10,8 @@ import json import unittest +import pytest + from pyinfra_testing.facts import make_fact_tests from pyinfra_testing.operations import make_operation_tests from pyinfra_testing.util import FakeHost @@ -130,3 +132,24 @@ def test_operation_command_mismatch_is_reported(tmp_path): result = run(make_operation_tests(BASE, "_fixtures.sample_op", tmp_path)) assert result.testsRun == 1 assert not result.wasSuccessful() + + +@pytest.mark.parametrize("kind", ["operation", "fact"]) +def test_state_mutations_do_not_leak_between_cases(tmp_path, kind): + if kind == "operation": + case = {"commands": ["echo / False"]} + generator = make_operation_tests + target = "_fixtures.stateful_op" + else: + case = { + "command": "echo sample", + "requires_command": "echo", + "output": [], + "fact": {"cwd": "/", "diff": False}, + } + generator = make_fact_tests + target = "_fixtures.StatefulFact" + write_cases(tmp_path, {"first": case, "second": case}) + result = run(generator(BASE, target, tmp_path)) + assert result.testsRun == 2 + assert result.wasSuccessful(), result.failures or result.errors diff --git a/tests/test_parse_value.py b/tests/test_parse_value.py index e48ada9..f3b4905 100644 --- a/tests/test_parse_value.py +++ b/tests/test_parse_value.py @@ -3,6 +3,8 @@ from datetime import datetime from pathlib import Path +from pyinfra.api import HiddenValue + from pyinfra_testing.util import parse_value @@ -34,3 +36,12 @@ def test_recurses_into_dicts_and_lists(): def test_list_without_marker_is_plain_list(): assert parse_value(["a", "b"]) == ["a", "b"] + + +def test_hidden_values_in_nested_arguments(): + result = parse_value({"passwords": ["hidden:s3cr3t", "hidden:"]}) + secret, empty = result["passwords"] + assert isinstance(secret, HiddenValue) + assert secret.unmask() == "s3cr3t" + assert isinstance(empty, HiddenValue) + assert empty.unmask() == ""