Multi-host testing with the pytest-mh framework
The pytest-mh project is a plugin that provides a multi-host test framework for the popular pytest unit-testing framework and test runner. Work on pytest-mh started in 2023 to solve a multitude of issues that cropped up for developers and testers when testing the SSSD project, which is a client for enterprise identity management. I was not happy with the state of testing of the SSSD project and wanted to create something that would increase test readability, remove duplication, eliminate errors, and provide multi-host testing capabilities, while having the flexibility to build a new API around it. Finally, I also wanted something that can be used by anyone to test their projects as well.
The pytest-mh plugin is licensed under the GPLv3. (The pytest framework is under the MIT license.) It provides building blocks to build a test framework around a project, and tools that connect the tests to one or more hosts. Developers can write tests in Python that execute commands on remote systems as well as implement complex automated setup and teardown to ensure that each test starts with a well-defined environment.
The pytest-mh plugin is designed for applications that work on multiple hosts, such as client/server applications. Unlike pytest, pytest-mh is not designed for unit testing. Instead it allows users to write tests that will exercise the application as a complete product, which is often referred to as system testing or application testing. Projects do not need to be written in Python to work with pytest-mh, making it a potential solution for all kinds of projects.
The main focus of pytest-mh is to test applications by executing commands on virtual machines, containers, or remote hosts; then to automatically revert all changes that were made to the host during a test to make sure that every single test starts with a fresh and clearly-defined environment. It also has a well-documented, and extensible, API that helps to write readable and maintainable test cases. While small or single-host projects can benefit from the framework, it is meant for projects that consist of multiple components that usually run on different hosts—typical examples are client/server and frontend/backend models, or those projects that are tightly integrated with the operating system where writing tests can be often more difficult than implementing new features.
Brief introduction to pytest
The pytest command-line application supports automatic collection of tests from a directory structure, test parameterization (running a single test with different parameters), and fixtures (functions that provide context for tests, such as content or environment details). It has a comprehensive plugin system that can be used to alter and enhance its behavior and functionality.
This snippet shows an example of a test for the strip() method. This is a built-in Python method available on string objects that removes all whitespace characters that are present around the string. The test provides a single body that is run multiple times for different parameters.
import pytest
@pytest.mark.parametrize("value", ["hello", " hello", "hello ", " hello "])
def test_strip(value):
assert value.strip() == "hello"
$ pytest -vvv tests/test_strip.py
============ test session starts ============
platform linux -- Python 3.13.1, pytest-8.3.4, pluggy-1.5.0 -- /usr/bin/python3
cachedir: .pytest_cache
rootdir: /var/home/pbrezina/workspace/pytest-mh
configfile: pytest.ini
collected 4 items
tests/test_strip.py::test_strip[hello] PASSED [ 25%]
tests/test_strip.py::test_strip[ hello] PASSED [ 50%]
tests/test_strip.py::test_strip[hello ] PASSED [ 75%]
tests/test_strip.py::test_strip[ hello ] PASSED [100%]
============= 4 passed in 0.01s =============
More information about pytest can be found on the project's documentation site including a get started guide.
What is multi-host testing
Multi-host testing, as the name suggests, is a kind of application testing that requires multiple hosts (usually virtual machines or containers) to run a test. While it is often possible to run all components of the application on a single host, that may not always be the case or it may require non-trivial work to enable testing on a single machine. Therefore it is often beneficial to install individual components of the application on multiple hosts to simplify the work and provide a testing environment that is closer to reality.
Consider SSSD as an example project. SSSD provides a system daemon that connects to various authentication and authorization backends such as LDAP, FreeIPA, SambaDC, and Active Directory. When requested, it reads data from one or more backends, stores it in a local cache, then passes the data via defined interfaces to other system components such as nsswitch, PAM, sudo, or autofs. SSSD therefore requires a complex test environment with a client connecting to many different backends with addition of NFS and Kerberos Key Distribution Center (KDC) servers in order to test autofs and Kerberos integration.
SSSD is written in C, and used to run tests on a single machine inside a chroot, utilizing cwrap to get control over many system calls. While testing using cwrap was possible, these tests were limited only to the LDAP backend. Adding new functionality required by new SSSD features was quite difficult and time consuming. SSSD switched to pytest-mh to make testing easier and more straightforward. Much of the code from tests has been moved into a reusable framework that is supported by pytest-mh's built in features, to reduce the amount of time worrying about how to test software and spend more time on what to test.
Introduction to pytest-mh
The pytest project provides markers, (pytest.mark.$markername) which are decorators that can be used to perform simple filtering by keyword. For example, "pytest -m $markername" would only run tests marked with $markername. They can also be used to implement advanced features inside a plugin. To support testing across multiple hosts, pytest-mh includes a topology marker (@pytest.mark.topology). A topology declares the hosts and roles that are required to run a test. It can be used to allow developers and testers to execute commands on the hosts, and to automatically filter out tests that cannot be run because some of the required hosts are not currently available. If a test requires two hosts such as "ldap" and "client" and only the "client" host is available then the test is skipped.
The supported connectors for running commands on remote hosts are, currently, SSHClient for connecting via SSH, and ContainerClient for connections to containers running under Docker or Podman. It is expected that the project is fully installed on one of the defined hosts. The tests then execute commands on the hosts in order to test the application. Here is a simple test from SSSD's test suite that utilizes the pytest-mh topology marker to associate the test with specific topology requirements.
@pytest.mark.topology(KnownTopology.LDAP)
def test_sssctl__check_missing_id_provider(client: Client):
# create sssd.conf and start the sssd, with default configuration with a LDAP server.
client.sssd.start()
# remove id_provider parameter from domain section.
client.sssd.config.remove_option("domain/test", "id_provider")
client.sssd.config_apply(check_config=False)
# Check the error message in output of # sssctl config-check
output = client.host.conn.run("sssctl config-check", raise_on_error=False)
assert "[rule/sssd_checks]: Attribute 'id_provider' is missing in section 'domain/test'." in output.stdout_lines[1]
$ pytest --mh-config=./mhc.yaml -k test_sssctl__check_missing_id_provider -vvv
...
tests/test_sssctl.py::test_sssctl__check_missing_id_provider (ldap) PASSED [100%]
This test is associated with an LDAP topology by the pytest.mark.topology marker. This particular topology from the sssd-test-framework declares that the test requires one client and one LDAP host for it to run. If this requirement cannot be satisfied, the test is skipped.
The test starts SSSD with the default configuration, makes changes to the configuration to render it invalid and applies these changes. This is all implemented in the sssd-test-framework using pytest-mh building blocks. Then the test runs sssctl config-check on the client host and asserts its result. The client fixture is dynamically created by pytest-mh, and it allows access to the client host; it is an instance of the client role that gives access to various functionality required by SSSD tests.
Multi-host topology
When pytest is run, it collects all tests from available test files. But each test may require different hosts to run properly. Running a test suite like that would often end up with lots of timeouts and failed tests, unless tests that should not be executed are explicitly filtered out either by deselecting them on the command line or by splitting the test suite into multiple distinct smaller sets.
The pytest-mh project solves this by associating each test with a multi-host topology which declares a set of hosts and their roles that are required to run a test. A test suite may include many topologies. pytest-mh requires a configuration file that defines which hosts and roles are currently available. It is possible that available hosts satisfy more than one topology, in this case all tests that can be run are executed.
The topology from the previous example can be defined as:
LDAP = TopologyMark(
"ldap",
Topology(TopologyDomain("myproject", client=1, ldap=1)),
fixtures=dict(client='myproject.client[0]', ldap='myproject.ldap[0]')
)
This says that topology LDAP requires one host that supports the client role and one host that supports the ldap role. It also defines the name of the fixtures: client and ldap pointing to the relevant host objects.
A configuration file that will support this topology can define two hosts with required roles and how to access them via SSH, which is the default connector.
domains:
- id: myproject
hosts:
- hostname: client.myproject.test
role: client
conn:
type: ssh
host: 192.168.0.10
user: root
password: Secret123
- hostname: ldap.myproject.test
role: ldap
conn:
type: ssh
host: 192.168.0.20 # IP address or hostname
user: root
private_key: /my/private/key/path
private_key_password: Secret123
In this example, pytest-mh will establish an SSH connection to the hosts as the root user, using a password for client and private key for LDAP.
Topology parameterization
Some projects provide one interface to the user but may fetch data from different backends (e.g. different SQL databases) or over different setups (e.g. encrypted versus an unencrypted communication channel). SSSD is a perfect example as it provides user information from various identity management solutions. The result is always the same for the user that runs id pbrezina, but the triggered code path is completely different for each backend inside SSSD. Normally, testing this would require duplicating a test code with slight modifications to its setup like adding a user to the IPA server instead of Active Directory and then configuring SSSD properly. However, pytest-mh brings pytest's parameterization to multi-host topology.
Topology parameterization allows a developer or tester to associate a single test with multiple topologies, which can rapidly increase code coverage. The test is then run multiple times, once for each topology. A different setup of each topology can be handled by the topology controller. The following test uses SSSD's topology controllers and KnownTopologyGroup.AnyProvider, which expands to multiple topologies: Active Directory, Samba DC, LDAP, and IPA. The test is executed once for each topology, having the same body but testing completely different code paths, demonstrating a test failure for the IPA backend.
@pytest.mark.topology(KnownTopologyGroup.AnyProvider)
def test_identity__lookup_username_with_id_command(client: Client, provider: GenericProvider):
ids = [("user1", 10001), ("user2", 10002), ("user3", 10003)]
for user, id in ids:
provider.user(user).add(uid=id, gid=id + 500)
client.sssd.domain["ldap_id_mapping"] = "false"
client.sssd.start()
for name, uid in ids:
result = client.tools.id(name)
assert result is not None, f"User {name} was not found using id!"
assert result.user.name == name, f"Username {result.user.name} is incorrect, {name} expected!"
assert result.user.id == uid, f"User id {result.user.id} is incorrect, {uid} expected!"
$ pytest --mh-config=./mhc.yaml -k test_identity__lookup_username_with_id_command -vvv
...
tests/test_identity.py::test_identity__lookup_username_with_id_command (ad) PASSED [ 25%]
tests/test_identity.py::test_identity__lookup_username_with_id_command (ipa) FAILED [ 50%]
tests/test_identity.py::test_identity__lookup_username_with_id_command (ldap) PASSED [ 75%]
tests/test_identity.py::test_identity__lookup_username_with_id_command (samba) PASSED [100%]
================================== FAILURES ===================================
========================== short test summary info ============================
____________ test_identity__lookup_username_with_id_command (ipa) _____________
client = <sssd_test_framework.roles.client.Client object at
0x7f7d92bfb770>,
provider = <sssd_test_framework.roles.ipa.IPA object at 0x7f7d92691e80>
@pytest.mark.topology(KnownTopologyGroup.AnyProvider)
def test_identity__lookup_username_with_id_command(client: Client, provider: GenericProvider):
ids = [("user1", 10001), ("user2", 10002), ("user3", 10003)]
for user, id in ids:
provider.user(user).add(uid=id, gid=id + 500)
client.sssd.domain["ldap_id_mapping"] = "false"
client.sssd.start()
for name, uid in ids:
result = client.tools.id(name)
> assert result is not None, f"User {name} was not found using id!"
E AssertionError: User user1 was not found using id!
E assert None is not None
tests/test_identity.py:30: AssertionError
------------------------------ Captured log setup -----------------------------
...
========================== short test summary info ============================
FAILED
tests/test_identity.py::test_identity__lookup_username_with_id_command
(ipa) - AssertionError: User user1 was not found using id!
assert None is not None
===== 1 failed, 2 passed, 690 deselected, 3 warnings in 74.47s (0:01:14) ======
Building blocks
Besides filtering and running the tests, pytest-mh provides many building blocks and ready-to-use utilities. Building blocks provide classes to implement custom hosts, roles and topologies to support testing the project. Utilities are used to share code. One utility, that is probably used the most, handles filesystem management: reading and writing files, creating directories, uploading, downloading and so on. Other utilities can start or stop systemd services, manipulate the system firewall, fail tests when there is a core dump or an SELinux denial is detected, or simulate network delays.
All utilities that are included in pytest-mh include thorough setup and teardown code to make sure that the host is set up as expected and all changes are automatically reverted. If a file is created, it is automatically removed when the test is done; if a host is blocked by firewall, it is unblocked at the end of the test, and so on.
Further reading
This article only scratches the surface of pytest-mh's capabilities. The best way to go from here is to visit the pytest-mh documentation and getting started guide that implements a small and basic test suite for sudo. For a real project use case, it is recommended to look into the sssd-test-framework and sssd tests. Another good example is the shadow-utils test suite that has much lower complexity. This is still a young project so contributions are welcome, whether they are bug reports, feature requests, or pull requests to fix bugs and add features.
| Index entries for this article | |
|---|---|
| GuestArticles | Březina, Pavel |
The LWN site is currently under high scraper load, so comment display has been suppressed for anonymous users. If you are a human, you may read the comments by clicking the button below:
Note: you can avoid this step in the future by logging into your LWN account.
