Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down
15 changes: 8 additions & 7 deletions pyinfra_testing/facts.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down
55 changes: 55 additions & 0 deletions pyinfra_testing/logs.py
Original file line number Diff line number Diff line change
@@ -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}"
)
55 changes: 30 additions & 25 deletions pyinfra_testing/operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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", {}))

Expand All @@ -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"])
Expand Down
8 changes: 7 additions & 1 deletion pyinfra_testing/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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_"

Expand Down
30 changes: 29 additions & 1 deletion tests/_fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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
Loading