### Test Package Installation with Testinfra Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/index.md Example demonstrating how to test if a package, 'nginx', is installed and check its version using Testinfra. Asserts that the package is installed and its version starts with '1.2'. ```python def test_nginx_is_installed(host): nginx = host.package("nginx") assert nginx.is_installed assert nginx.version.startswith("1.2") ``` -------------------------------- ### Use Testinfra with Python unittest Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/examples.md Shows how to integrate Testinfra with Python's standard unittest framework. This example demonstrates setting up a host connection in setUp and writing test methods to check service status and configuration. ```python import unittest import testinfra class Test(unittest.TestCase): def setUp(self): self.host = testinfra.get_host("paramiko://root@host") def test_nginx_config(self): self.assertEqual(self.host.run("nginx -t").rc, 0) def test_nginx_service(self): service = self.host.service("nginx") self.assertTrue(service.is_running) self.assertTrue(service.is_enabled) if __name__ == "__main__": unittest.main() ``` -------------------------------- ### Testinfra: Testing Package Installation Source: https://context7.com/pytest-dev/pytest-testinfra/llms.txt Demonstrates how to test package installation status and versions using `host.package()`. It covers checking if a package is installed, its version, and using pytest parametrization for testing multiple packages. ```Python def test_packages(host): # Check if package is installed nginx = host.package("nginx") assert nginx.is_installed assert nginx.version.startswith("1.") # Check package version and release (for rpm-based systems) httpd = host.package("httpd") if httpd.is_installed: assert httpd.release == "1.el8" # Test multiple packages with parametrization import pytest @pytest.mark.parametrize("name,version", [ ("nginx", "1."), ("python3", "3."), ("openssh-server", "8."), ]) def test_installed_packages(host, name, version): pkg = host.package(name) assert pkg.is_installed assert pkg.version.startswith(version) ``` -------------------------------- ### Testinfra Host Specification Examples Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/backends.md Provides examples of how to specify target hosts for Testinfra tests using different backends and configurations. This includes SSH, Docker, and mixed backend specifications. ```bash testinfra --hosts=ssh://user:password@hostname:22 ``` ```bash testinfra --hosts=docker://container_id ``` ```bash testinfra --hosts=ssh://user:password@hostname:22,docker://container_id,local:// ``` -------------------------------- ### Install Testinfra using pip Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/README.rst This command installs the Testinfra package using pip. It also shows how to install the development version directly from the main branch of the GitHub repository. ```bash pip install pytest-testinfra ``` ```bash pip install 'git+https://github.com/pytest-dev/pytest-testinfra@main#egg=pytest-testinfra' ``` -------------------------------- ### Instantiating a Host object Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/modules.md Provides examples of using the get_host class method to create a Host instance from a connection string, supporting various backends like local, paramiko, and ansible. ```default >>> get_host("local://", sudo=True) >>> get_host("paramiko://user@host", ssh_config="/path/my_ssh_config") >>> get_host("ansible://all?ansible_inventory=/etc/ansible/inventory") ``` -------------------------------- ### Integrate Testinfra with Jenkins and Vagrant Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/examples.md Illustrates a Jenkins build script for running Testinfra tests on a Vagrant machine. It includes steps for installing dependencies, starting Vagrant, configuring SSH, and generating JUnit XML reports for Jenkins. ```bash pip install pytest-testinfra paramiko vagrant up vagrant ssh-config > .vagrant/ssh-config pytest --hosts=default --ssh-config=.vagrant/ssh-config --junit-xml junit.xml tests.py ``` -------------------------------- ### Test Multiple Hosts with Paramiko Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/invocation.md This snippet demonstrates how to install the Paramiko library and run Testinfra tests against multiple remote hosts specified via the --hosts command-line argument. It shows an example of pytest output when tests are run on both localhost and a remote server. ```bash $ pip install paramiko $ pytest -v --hosts=localhost,root@webserver:2222 test_myinfra.py ``` ```python testinfra_hosts = ["localhost", "root@webserver:2222"] def test_foo(host): [....] ``` -------------------------------- ### Integrate Testinfra with KitchenCI Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/examples.md Shows how to configure KitchenCI to use Testinfra as a shell verifier. This example details the necessary additions to the `.kitchen.yml` file, including how to pass Testinfra connection details dynamically using KitchenCI variables. ```yaml verifier: name: shell command: pytest --hosts="paramiko://${KITCHEN_USERNAME}@${KITCHEN_HOSTNAME}:${KITCHEN_PORT}?ssh_identity_file=${KITCHEN_SSH_KEY}" --junit-xml "junit-${KITCHEN_INSTANCE}.xml" "test/integration/${KITCHEN_SUITE}" ``` -------------------------------- ### Install and Check Code Style with Ruff Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/CONTRIBUTING.rst This command installs the ruff linter and then checks the project's code against its defined style rules. Adhering to ruff checks is mandatory for contributing to testinfra. ```bash pip install ruff ruff check ``` -------------------------------- ### Manage System Packages Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/modules.md Verifies if a package is installed and retrieves its version and release information. ```pycon >>> host.package("nginx").is_installed True >>> host.package("nginx").release '1.el6' >>> host.package("nginx").version '1.2.1-2.2+wheezy3' ``` -------------------------------- ### Salt Backend Host Selection Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/backends.md Demonstrates how to use the Salt backend for Testinfra, allowing hosts to be selected using glob and compound matchers. Examples show targeting all minions, specific minions, or minions based on OS. ```bash pytest --hosts='salt://*' ``` ```bash pytest --hosts='salt://minion1,salt://minion2' ``` ```bash pytest --hosts='salt://web*' ``` ```bash pytest --hosts='salt://G@os:Debian' ``` -------------------------------- ### Parallel Test Execution with Pytest-xdist Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/invocation.md This snippet shows how to install the pytest-xdist plugin to enable parallel execution of Testinfra tests across multiple processes. It includes an example command to launch tests using 3 processes against a list of specified hosts. ```bash $ pip install pytest-xdist # Launch tests using 3 processes $ pytest -n 3 -v --host=web1,web2,web3,web4,web5,web6 test_myinfra.py ``` -------------------------------- ### Install Testinfra with Extras Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/backends.md Installs pytest-testinfra with specified connection backends using pip extras. This ensures that the necessary Python dependencies for the chosen backends are installed. ```bash pip install pytest-testinfra[ansible,salt] ``` -------------------------------- ### SSH Backend Options Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/backends.md Provides examples of using the pure SSH backend with various options. This includes specifying the host, an SSH configuration file, an identity file, connection timeout, and extra SSH arguments. ```bash pytest --hosts='ssh://server' ``` ```bash pytest --ssh-config=/path/to/ssh_config --hosts='ssh://server' ``` ```bash pytest --ssh-identity-file=/path/to/key --hosts='ssh://server' ``` ```bash pytest --hosts='ssh://server?timeout=60&controlpersist=120' ``` ```bash pytest --hosts='ssh://server' --ssh-extra-args='-o StrictHostKeyChecking=no' ``` -------------------------------- ### Check User Existence with Testinfra Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/modules.md Demonstrates how to check if a user exists on the system using the `exists` property of the `host.user()` object. It shows examples for both existing and non-existing users. ```python >>> host.user("root").exists True >>> host.user("nosuchuser").exists False ``` -------------------------------- ### Integrate Testinfra with Vagrant Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/examples.md Provides command-line examples for running Testinfra tests against a Vagrant-managed virtual machine. It shows how to generate an SSH config file from Vagrant and use it with pytest. ```bash vagrant ssh-config > .vagrant/ssh-config pytest --hosts=default --ssh-config=.vagrant/ssh-config tests.py ``` -------------------------------- ### Run Testinfra Tests with Nagios Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/examples.md Demonstrates how to use Testinfra's --nagios option to make tests compatible with Nagios monitoring. It shows example command-line invocations and expected output for both passing and failing tests, along with exit codes. ```bash $ pytest -qq --nagios --tb line test_ok.py; echo $? TESTINFRA OK - 2 passed, 0 failed, 0 skipped in 2.30 seconds .. 0 $ pytest -qq --nagios --tb line test_fail.py; echo $? TESTINFRA CRITICAL - 1 passed, 1 failed, 0 skipped in 2.24 seconds .F /usr/lib/python3/dist-packages/example/example.py:95: error: [Errno 111] error msg 2 ``` -------------------------------- ### Get Pip Packages Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/modules.md Retrieves a list of all installed packages and their versions using pip. It can take an optional pip_path argument to specify the pip executable. ```python >>> host.pip.get_packages(pip_path='~/venv/website/bin/pip') {'Django': {'version': '1.10.2'}, 'mywebsite': {'version': '1.0a3', 'path': '/srv/website'}, 'psycopg2': {'version': '2.6.2'}} ``` -------------------------------- ### Get All and Local Users with Testinfra Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/modules.md Shows how to retrieve lists of all users (local and remote) and specifically local users on the system using `get_all_users` and `get_local_users` properties. ```python >>> host.user().get_all_users ["root", "bin", "daemon", "lp", <...>] ``` ```python >>> host.user().get_local_users ["root", "bin", "daemon", "lp", <...>] ``` -------------------------------- ### Test Service Status with Testinfra Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/index.md Example for testing the running and enabled status of a service, 'nginx', using Testinfra. It asserts that the service is both running and enabled. ```python def test_nginx_running_and_enabled(host): nginx = host.service("nginx") assert nginx.is_running assert nginx.is_enabled ``` -------------------------------- ### Test Python Packages with host.pip() Source: https://context7.com/pytest-dev/pytest-testinfra/llms.txt Tests pip package installation and version information. It allows checking if a package is installed, verifying its version, using specific pip paths (e.g., for virtual environments), listing all installed packages, checking for outdated packages, and verifying package dependencies. Requires pip to be installed on the target system. ```python def test_pip_packages(host): # Check pip package is installed requests = host.pip("requests") assert requests.is_installed assert requests.version.startswith("2.") # Use specific pip path (for virtualenvs) django = host.pip("django", pip_path="/opt/venv/bin/pip") assert django.is_installed # List all installed packages packages = host.pip.get_packages(pip_path="/opt/venv/bin/pip") assert "django" in packages # Check for outdated packages outdated = host.pip.get_outdated_packages() # Verify package dependencies check = host.pip.check() assert check.rc == 0 ``` -------------------------------- ### Get Facter Facts Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/modules.md Retrieves system facts using the Facter tool. You can get all facts or specify particular facts to retrieve. ```python >>> host.facter() { "operatingsystem": "Debian", "kernel": "linux", [...] } ``` ```python >>> host.facter("kernelversion", "is_virtual") { "kernelversion": "3.16.0", "is_virtual": "false" } ``` -------------------------------- ### Verify Pip Packages Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/modules.md Checks the installation status and version of pip packages, and runs dependency checks. ```pycon >>> host.package("pip").is_installed True >>> host.package("pip").version '18.1' >>> cmd = host.pip.check() >>> cmd.rc 0 ``` -------------------------------- ### Run All Testinfra Tests with Tox Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/CONTRIBUTING.rst This command executes the complete test suite for testinfra using the tox automation tool. Ensure Docker and tox are installed. This is a prerequisite for submitting pull requests. ```bash tox ``` -------------------------------- ### Test File Properties with Testinfra Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/index.md Example of testing the properties of a file, specifically /etc/passwd, using Testinfra. It asserts the file contains 'root', and checks its owner, group, and permissions. ```python def test_passwd_file(host): passwd = host.file("/etc/passwd") assert passwd.contains("root") assert passwd.user == "root" assert passwd.group == "root" assert passwd.mode == 0o644 ``` -------------------------------- ### Pip API Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/modules.md Provides functionalities to test pip package manager and installed packages. ```APIDOC ## Pip Class ### Description Test pip package manager and packages. ### Method Instantiate `Pip` with `host.pip(name, pip_path='pip')`. ### Endpoint N/A (Object-oriented interface) ### Parameters #### Path Parameters - **name** (string) - Required - The name of the pip package. - **pip_path** (string) - Optional - The path to the pip executable. Defaults to 'pip'. #### Query Parameters None #### Request Body None ### Request Example ```python # Check if pip package is installed host.package("pip").is_installed # Get the version of the pip package host.package("pip").version # Check pip dependencies cmd = host.pip.check() cmd.rc cmd.stdout ``` ### Response #### Success Response (200) - **is_installed** (boolean) - True if the pip package is installed, False otherwise. - **version** (string) - The package version as returned by pip. - **check()** (Command object) - Result of the `pip check` command. #### Response Example ```json { "is_installed": true, "version": "18.1", "check_result": { "rc": 0, "stdout": "No broken requirements found." } } ``` ``` -------------------------------- ### Python Package Management (pip) Source: https://context7.com/pytest-dev/pytest-testinfra/llms.txt API for verifying installed Python packages and checking for updates. ```APIDOC ## GET /host/pip ### Description Check the installation status and version of Python packages. ### Method GET ### Endpoint host.pip(package_name) ### Parameters #### Path Parameters - **package_name** (string) - Required - Name of the pip package. ### Response #### Success Response (200) - **is_installed** (boolean) - Whether the package is present. - **version** (string) - Installed version string. ### Response Example { "is_installed": true, "version": "2.28.1" } ``` -------------------------------- ### Test Docker and Podman Containers with host.docker() and host.podman() Source: https://context7.com/pytest-dev/pytest-testinfra/llms.txt Tests the status and properties of Docker and Podman containers. It allows checking if containers are running, restarting, retrieving their IDs, listing containers with filters, and getting Docker version information. Dependencies include the Testinfra library and a running Docker or Podman daemon. ```python def test_containers(host): # Test Docker container nginx = host.docker("app_nginx") assert nginx.is_running assert not nginx.is_restarting container_id = nginx.id # Get Docker version version = host.docker.version() client_ver = host.docker.client_version() server_ver = host.docker.server_version() # List containers with filters all_containers = host.docker.get_containers() running = host.docker.get_containers(status="running") by_name = host.docker.get_containers(name=["nginx", "redis"]) # Test Podman container app = host.podman("myapp") assert app.is_running # List Podman containers podman_containers = host.podman.get_containers(status="running") ``` -------------------------------- ### Write Basic Testinfra Tests in Python Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/README.rst This Python code demonstrates how to write basic infrastructure tests using Testinfra. It covers testing file properties, installed packages, and service status. These tests are designed to be run with Pytest. ```python def test_passwd_file(host): passwd = host.file("/etc/passwd") assert passwd.contains("root") assert passwd.user == "root" assert passwd.group == "root" assert passwd.mode == 0o644 def test_nginx_is_installed(host): nginx = host.package("nginx") assert nginx.is_installed assert nginx.version.startswith("1.2") def test_nginx_running_and_enabled(host): nginx = host.service("nginx") assert nginx.is_running assert nginx.is_enabled ``` -------------------------------- ### Retrieve Command Standard Output as Bytes with Testinfra Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/modules.md Shows how to get the standard output (stdout) of a command as raw bytes using the `stdout_bytes` property of the `CommandResult` object. This is useful when dealing with non-textual output. ```python >>> host.run("mkdir -v new_directory").stdout_bytes b"mkdir: created directory 'new_directory'" ``` -------------------------------- ### Get Command Return Code with Testinfra Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/modules.md Shows how to retrieve the integer return code (`rc`) of a command execution, which is a standard way to check for command success or specific error conditions. ```python >>> host.run("true").rc 0 ``` -------------------------------- ### Inspect Processes Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/modules.md Allows inspection of system processes. You can retrieve specific processes using `get()` with filters or a list of matching processes using `filter()`. Process attributes are based on the ps(1) man page. ```python >>> master = host.process.get(user="root", comm="nginx") # Here is the master nginx process (running as root) >>> master.args 'nginx: master process /usr/sbin/nginx -g daemon on; master_process on;' # Here are the worker processes (Parent PID = master PID) >>> workers = host.process.filter(ppid=master.pid) >>> len(workers) 4 # Nginx don't eat memory >>> sum([w.pmem for w in workers]) 0.8 # But php does ! >>> sum([p.pmem for p in host.process.filter(comm="php5-fpm")]) 19.2 ``` ```python >>> host.process.filter(user="root", comm="zsh") [, , ...] ``` -------------------------------- ### Get Block Device Information Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/modules.md Retrieves information about a block device, such as its size, sector size, block size, and writability. Requires root privileges or sudo. Raises RuntimeError if the specified device is not a block device. ```python >>> host.block_device("/dev/sda1").is_partition True ``` ```python >>> host.block_device("/dev/sda").is_partition False ``` ```python >>> host.block_device("/dev/sda1").size 512110190592 ``` ```python >>> host.block_device("/dev/sda1").sector_size 512 ``` ```python >>> host.block_device("/dev/sda").block_size 4096 ``` ```python >>> host.block_device("/dev/sda1").start_sector 2048 ``` ```python >>> host.block_device("/dev/md0").start_sector 0 ``` ```python >>> host.block_device("/dev/sda").is_writable True ``` ```python >>> host.block_device("/dev/loop1").is_writable False ``` -------------------------------- ### Parametrize Pytest Tests Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/examples.md Demonstrates how to use pytest's parametrize marker to run the same test function with different inputs, improving test coverage and reducing code duplication. This is useful for testing package installations with various names and versions. ```python import pytest @pytest.mark.parametrize("name,version", [ ("nginx", "1.6"), ("python", "2.7"), ]) def test_packages(host, name, version): pkg = host.package(name) assert pkg.is_installed assert pkg.version.startswith(version) ``` -------------------------------- ### Initialize Host Connection and Verify File Permissions Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/api.md Demonstrates how to create a host instance using a connection string with sudo privileges and verify the mode of a specific file. This is useful for standalone infrastructure validation scripts. ```python import testinfra host = testinfra.get_host("paramiko://root@server:2222", sudo=True) assert host.file("/etc/shadow").mode == 0o640 ``` -------------------------------- ### Testinfra: Connecting to Hosts Source: https://context7.com/pytest-dev/pytest-testinfra/llms.txt Demonstrates how to obtain host instances using Testinfra's Connection API with different backends like local, SSH, Docker, Ansible, Kubernetes, and WinRM. It also shows comparing file content across two hosts. ```Python import testinfra # Connect to local machine localhost = testinfra.get_host("local://") # Connect via SSH with sudo host = testinfra.get_host("paramiko://root@server:2222", sudo=True) # Connect to Docker container container = testinfra.get_host("docker://my_container") # Connect via Ansible inventory ansible_host = testinfra.get_host("ansible://webserver?ansible_inventory=/etc/ansible/hosts") # Connect to Kubernetes pod k8s_host = testinfra.get_host("kubectl://mypod-a1b2c3?container=nginx&namespace=web") # Connect to Windows host via WinRM windows = testinfra.get_host("winrm://Administrator:Password@192.168.1.100") # Compare files across two servers def test_same_passwd(): a = testinfra.get_host("ssh://server-a") b = testinfra.get_host("ssh://server-b") assert a.file("/etc/passwd").content == b.file("/etc/passwd").content ``` -------------------------------- ### Testinfra: Executing Commands on Host Source: https://context7.com/pytest-dev/pytest-testinfra/llms.txt Shows how to execute shell commands on a target host using `host.run()`, `host.check_output()`, `host.run_expect()`, and `host.run_test()`. It covers capturing output, exit status, and safe argument quoting. ```Python def test_command_execution(host): # Basic command execution cmd = host.run("ls -l /etc/passwd") assert cmd.rc == 0 assert cmd.succeeded assert "-rw-r--r--" in cmd.stdout assert cmd.stderr == "" # Safe argument quoting to prevent shell injection filename = "/etc/passwd" cmd = host.run("ls -l -- %s", filename) assert cmd.succeeded # Get stdout directly (raises AssertionError if command fails) output = host.check_output("whoami") assert output == "root" # Run command expecting specific exit codes cmd = host.run_expect([0, 1], "grep -q root /etc/passwd") # Run test command (expects 0 or 1) cmd = host.run_test("test -f /etc/passwd") ``` -------------------------------- ### Verify System Service Status and Properties Source: https://context7.com/pytest-dev/pytest-testinfra/llms.txt Demonstrates how to check if a service exists, is running, or is enabled. It also shows how to inspect systemd-specific properties like masking and unit configuration. ```python def test_services(host): # Check service status nginx = host.service("nginx") assert nginx.exists assert nginx.is_running assert nginx.is_enabled # Systemd-specific tests sshd = host.service("sshd") assert sshd.is_valid assert not sshd.is_masked # Get systemd unit properties props = sshd.systemd_properties assert "FragmentPath" in props assert props["ActiveState"] == "active" ``` -------------------------------- ### Executing shell commands with Host Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/modules.md Shows how to run commands on the target host and inspect the resulting CommandResult object, including exit status and output streams. ```pycon >>> cmd = host.run("ls -l /etc/passwd") >>> cmd.rc 0 >>> cmd.stdout '-rw-r--r-- 1 root root 1790 Feb 11 00:28 /etc/passwd\n' >>> cmd.stderr '' >>> cmd.succeeded True >>> cmd.failed False ``` -------------------------------- ### Testinfra: Testing File Attributes Source: https://context7.com/pytest-dev/pytest-testinfra/llms.txt Illustrates how to test various file attributes using `host.file()`, including existence, type, ownership, permissions, content, symlinks, modification time, size, checksums, and directory listing. ```Python def test_file_attributes(host): passwd = host.file("/etc/passwd") # Check existence and type assert passwd.exists assert passwd.is_file assert not passwd.is_directory # Check ownership assert passwd.user == "root" assert passwd.group == "root" assert passwd.uid == 0 assert passwd.gid == 0 # Check permissions (octal) assert passwd.mode == 0o644 # Check file content assert passwd.contains("root") content = passwd.content_string assert "root:x:0:0" in content # Check symlinks lock = host.file("/var/lock") assert lock.is_symlink assert lock.linked_to == "/run/lock" # Check modification time mtime = passwd.mtime assert mtime.year >= 2020 # Check file size and checksums size = passwd.size md5 = passwd.md5sum sha256 = passwd.sha256sum # List directory contents tmp = host.file("/tmp") assert tmp.is_directory files = tmp.listdir() ``` -------------------------------- ### Get Outdated Pip Packages Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/modules.md Fetches a list of outdated packages, including their current and latest available versions. It accepts an optional pip_path argument. ```python >>> host.pip.get_outdated_packages( ... pip_path='~/venv/website/bin/pip') {'Django': {'current': '1.10.2', 'latest': '1.10.3'}} ``` -------------------------------- ### Compare File Content Across Multiple Servers Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/api.md Shows how to establish connections to two distinct hosts and compare the content of a specific file between them. This pattern is effective for verifying configuration consistency across server environments. ```python import testinfra def test_same_passwd(): a = testinfra.get_host("ssh://a") b = testinfra.get_host("ssh://b") assert a.file("/etc/passwd").content == b.file("/etc/passwd").content ``` -------------------------------- ### Verify Network Interface Properties Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/modules.md Demonstrates how to check for the existence of a network interface, retrieve its IP addresses, and inspect link details using the Interface class. ```pycon >>> host.interface("eth0").exists True >>> host.interface("eth0", "inet6").addresses ['fe80::e291:f5ff:fe98:6b8c'] >>> host.interface("eth0").addresses ['192.168.31.254', '192.168.31.252', 'fe80::e291:f5ff:fe98:6b8c'] >>> host.interface("lo").link ``` -------------------------------- ### Paramiko Backend SSH Configuration Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/backends.md Demonstrates how to use the Paramiko backend for SSH connections with Testinfra. It shows how to specify an alternate SSH configuration file using the `--ssh-config` option when targeting a server. ```bash pytest --ssh-config=/path/to/ssh_config --hosts=server ``` -------------------------------- ### Podman Backend Execution Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/backends.md Shows how to use the Podman backend for testing running Podman containers. The `--hosts` parameter follows the format 'podman://[user@]container_id_or_name', utilizing the `podman exec` command. ```bash pytest --hosts='podman://[user@]container_id_or_name' ``` -------------------------------- ### Access System Information with host.system_info Source: https://context7.com/pytest-dev/pytest-testinfra/llms.txt Provides access to detailed system information, including OS type, distribution name and release, codename, and architecture. This is useful for writing OS-agnostic tests or verifying specific system configurations. It relies on Testinfra's ability to gather system details. ```python def test_system_info(host): sysinfo = host.system_info # Get OS type assert sysinfo.type == "linux" # Get distribution info assert sysinfo.distribution in ["debian", "ubuntu", "centos", "rocky"] assert sysinfo.release.startswith("10") or sysinfo.release.startswith("22") assert sysinfo.codename in ["bullseye", "bookworm", "jammy"] # Get architecture assert sysinfo.arch in ["x86_64", "aarch64"] ``` -------------------------------- ### Docker Backend Execution Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/backends.md Illustrates how to use the Docker backend to test running Docker containers. The `--hosts` parameter is used with the format 'docker://[user@]container_id_or_name'. ```bash pytest --hosts='docker://[user@]container_id_or_name' ``` -------------------------------- ### Test Kernel Parameters with host.sysctl() Source: https://context7.com/pytest-dev/pytest-testinfra/llms.txt Tests kernel parameters and system tuning values using the host.sysctl() method. It allows checking specific parameters like kernel release, VM settings, and network configurations. Dependencies include the host object provided by Testinfra. ```python def test_sysctl_values(host): # Get kernel version osrelease = host.sysctl("kernel.osrelease") assert osrelease.startswith("5.") or osrelease.startswith("6.") # Check VM settings assert host.sysctl("vm.dirty_ratio") <= 40 assert host.sysctl("vm.swappiness") >= 0 # Check network settings assert host.sysctl("net.ipv4.ip_forward") == 1 assert host.sysctl("net.core.somaxconn") >= 128 ``` -------------------------------- ### Local Backend Execution Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/backends.md Shows how to run Testinfra commands locally using the default 'local' backend. Commands are executed in a subprocess under the current user. The `--sudo` option can be used to run commands as a superuser. ```bash pytest --sudo test_myinfra.py ``` -------------------------------- ### Validate User and Group Attributes Source: https://context7.com/pytest-dev/pytest-testinfra/llms.txt Shows how to verify user existence, UID/GID, home directories, and group memberships. It also covers checking group properties and listing all users or groups. ```python def test_users_and_groups(host): # Test user exists root = host.user("root") assert root.exists assert root.uid == 0 assert root.gid == 0 assert root.home == "/root" assert root.shell == "/bin/bash" # Test user groups www = host.user("www-data") assert "www-data" in www.groups assert www.group == "www-data" # Test user password expiration user = host.user("phil") expiry = user.expiration_date if expiry: assert expiry.year > 2024 # Test group exists wheel = host.group("wheel") assert wheel.exists assert wheel.gid > 0 assert "admin" in wheel.members # List all users and groups all_users = host.user().get_all_users all_groups = host.group("any").get_all_groups ``` -------------------------------- ### Run Selected Testinfra Tests with Tox and Pytest-xdist Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/CONTRIBUTING.rst This command runs specific testinfra tests filtered by 'ansible' using 4 parallel processes via pytest-xdist. It requires tox, Docker, and pytest-xdist to be installed. Useful for targeted testing. ```bash tox -- -v -n 4 -k ansible test ``` -------------------------------- ### Running commands with safe argument quoting Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/modules.md Illustrates the recommended practice of using shell argument formatting to prevent shell injection vulnerabilities when executing commands. ```pycon >>> cmd = host.run("ls -l -- %s", "/;echo inject") CommandResult( rc=2, stdout='', stderr=( 'ls: cannot access /;echo inject: No such file or directory\n'), command="ls -l '/;echo inject'") ``` -------------------------------- ### Inspect Network Interface Configurations Source: https://context7.com/pytest-dev/pytest-testinfra/llms.txt Verifies interface existence, IP addresses, link status, and routing tables. It also shows how to retrieve default interface information. ```python def test_network_interfaces(host): # Check interface exists eth0 = host.interface("eth0") assert eth0.exists # Get interface addresses addresses = eth0.addresses assert "192.168.1.100" in addresses # Filter by address family ipv4_only = host.interface("eth0", "inet") ipv6_only = host.interface("eth0", "inet6") # Get interface link properties link = eth0.link assert link["operstate"] == "UP" assert "UP" in link["flags"] # Get routes for interface routes = eth0.routes() default_routes = eth0.routes(scope="global") # List all interface names all_interfaces = host.interface.names() assert "lo" in all_interfaces # Get default interface default_iface = host.interface.default() ``` -------------------------------- ### Advanced Pytest Invocation for Testinfra Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/invocation.md This snippet covers advanced methods for invoking Testinfra tests using pytest. It includes commands for recursively testing all files starting with `test_` in the current directory and for filtering tests based on function or host names using pytest's -k option. ```bash # Test recursively all test files (starting with `test_`) in current directory $ pytest # Filter function/hosts with pytest -k option $ pytest --hosts=webserver,dnsserver -k webserver -k nginx ``` -------------------------------- ### Retrieve User Attributes with Testinfra Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/modules.md Illustrates how to retrieve various attributes of a user account, such as UID, GID, group names, home directory, shell, password information, and expiration date. This helps in verifying user configurations. ```python >>> host.user("phil").expiration_date datetime.datetime(2020, 1, 1, 0, 0) >>> host.user("root").expiration_date None ``` -------------------------------- ### Test Block Devices with host.block_device() Source: https://context7.com/pytest-dev/pytest-testinfra/llms.txt Tests block device properties using the host.block_device() method. This function requires sudo/root privileges and allows checking device writability, size, block size, partition status, and sector information. Dependencies include the host object and sudo privileges. ```python def test_block_devices(host): with host.sudo(): # Test disk device sda = host.block_device("/dev/sda") assert sda.is_writable assert sda.size > 0 assert sda.block_size in [512, 4096] # Test partition sda1 = host.block_device("/dev/sda1") assert sda1.is_partition assert sda1.start_sector > 0 assert sda1.sector_size == 512 ``` -------------------------------- ### Retrieve Network Interface Routes and Names Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/modules.md Shows how to list all network interfaces and retrieve routing information for a specific interface. ```pycon >>> host.interface("eth0").routes() >>> host.interface.names() ['lo', 'tunl0', 'ip6tnl0', 'eth0'] >>> host.interface.default() ``` -------------------------------- ### Host.run() Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/modules.md Executes a shell command on the host and returns a CommandResult object containing the exit status, stdout, and stderr. ```APIDOC ## Host.run ### Description Executes a command on the target host. It is recommended to use shell argument quoting to prevent shell injection. ### Method N/A (Python Method) ### Parameters - **command** (str) - Required - The command string to execute. - **args** (str) - Optional - Arguments to format into the command string. - **kwargs** (Any) - Optional - Additional execution parameters. ### Request Example ```python cmd = host.run("ls -l -- %s", "/etc/passwd") ``` ### Response #### Success Response (CommandResult) - **rc** (int) - The exit status code. - **stdout** (str) - The standard output of the command. - **stderr** (str) - The standard error of the command. - **succeeded** (bool) - True if the command exited with 0. - **failed** (bool) - True if the command exited with non-zero. ``` -------------------------------- ### Manage System Services Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/modules.md Provides an interface to manage and test system services across different init systems (Systemd, Upstart, OpenRC, SysV, FreeBSD service, OpenBSD rc.d, NetBSD rc.d). It allows checking for existence, running status, enabled status, validity, and mask status (systemd-specific). ```python # Test if the service exists >>> host.service.exists # Test if service is running >>> host.service.is_running # Test if service is enabled >>> host.service.is_enabled # Test if service is valid (systemd specific) >>> host.service.is_valid # Test if service is masked (systemd specific) >>> host.service.is_masked ``` -------------------------------- ### Test Supervisor Services with host.supervisor() Source: https://context7.com/pytest-dev/pytest-testinfra/llms.txt Tests services managed by the Supervisor process control system using the host.supervisor() method. It allows checking service status, PID, and managing custom supervisorctl paths and configurations. Dependencies include the host object and potentially custom paths for supervisorctl and its configuration. ```python def test_supervisor_services(host): # Test specific service gunicorn = host.supervisor("gunicorn") assert gunicorn.is_running assert gunicorn.status == "RUNNING" assert gunicorn.pid > 0 # Custom supervisorctl path celery = host.supervisor( "celery", supervisorctl_path="/usr/local/bin/supervisorctl", supervisorctl_conf="/etc/supervisor/supervisord.conf" ) assert celery.status in ["RUNNING", "STOPPED"] # List all supervisor services services = host.supervisor.get_services() for svc in services: print(f"{svc.name}: {svc.status} (PID: {svc.pid})") ``` -------------------------------- ### host.sysctl() - Test Kernel Parameters Source: https://context7.com/pytest-dev/pytest-testinfra/llms.txt Validates kernel parameters and system tuning values on the target host. ```APIDOC ## host.sysctl(parameter) ### Description Retrieves and validates kernel parameters and system tuning values. ### Method N/A (Python Method) ### Parameters #### Path Parameters - **parameter** (string) - Required - The sysctl key to query (e.g., 'net.ipv4.ip_forward'). ### Request Example ```python host.sysctl("net.ipv4.ip_forward") ``` ### Response #### Success Response (200) - **value** (int/string) - The current value of the kernel parameter. ``` -------------------------------- ### Execute Commands with Sudo Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/modules.md Uses the Sudo context manager to execute commands under a different user identity. Supports nesting to switch between multiple user contexts. ```python with host.sudo(): host.check_output("whoami") with host.sudo("www-data"): host.check_output("whoami") ``` -------------------------------- ### Retrieve Command Standard Output with Testinfra Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/modules.md Illustrates how to access the standard output (stdout) of a command as a string using the `stdout` property of the `CommandResult` object. Useful for capturing command output. ```python >>> host.run("mkdir -v new_directory").stdout mkdir: created directory 'new_directory' ``` -------------------------------- ### Filter and Test Running Processes with host.process() Source: https://context7.com/pytest-dev/pytest-testinfra/llms.txt Filters and tests running processes on the system. It enables retrieving specific processes by user and command, filtering processes by parent PID, checking memory usage, and filtering by user or command name. This functionality is useful for verifying system services and resource consumption. ```python def test_processes(host): # Get specific process master = host.process.get(user="root", comm="nginx") assert master.args.startswith("nginx: master process") # Get worker processes by parent PID workers = host.process.filter(ppid=master.pid) assert len(workers) >= 1 # Check memory usage total_mem = sum([p.pmem for p in workers]) assert total_mem < 10.0 # Filter by user root_procs = host.process.filter(user="root") # Filter by command python_procs = host.process.filter(comm="python3") for proc in python_procs: print(f"PID: {proc.pid}, Args: {proc.args}") ``` -------------------------------- ### Retrieve Environment Variables Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/modules.md Access the system environment variables as a dictionary. ```python env_vars = host.environment() ``` -------------------------------- ### Host.get_host() Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/modules.md Factory method to instantiate a Host object based on a backend specification string. ```APIDOC ## Host.get_host ### Description Creates and returns a Host instance based on the provided hostspec string (e.g., local://, paramiko://, ansible://). ### Method Class Method ### Parameters - **hostspec** (str) - Required - Connection string in format ://?params. - **kwargs** (Any) - Optional - Additional configuration parameters. ### Request Example ```python host = Host.get_host("paramiko://user@host", ssh_config="/path/to/config") ``` ### Response #### Success Response (Host) - **Host** (Object) - A configured Host instance ready for module interaction. ``` -------------------------------- ### Pytest CLI Invocation for Infrastructure Tests Source: https://context7.com/pytest-dev/pytest-testinfra/llms.txt Demonstrates various ways to invoke pytest for infrastructure testing, including specifying hosts, connection methods (SSH, Docker), sudo usage, and parallel execution with pytest-xdist. It also shows options for reporting like Nagios output and JUnit XML generation. ```bash # Test local machine pytest test_infra.py # Test with sudo pytest --sudo test_infra.py # Test remote hosts via SSH pytest --hosts=root@webserver:22 test_infra.py # Test multiple hosts pytest --hosts=web1,web2,db1 test_infra.py # Use SSH config file pytest --ssh-config=~/.ssh/config --hosts=production test_infra.py # Test Docker containers pytest --hosts=docker://container_name test_infra.py # Test via Ansible inventory pytest --hosts='ansible://all' --ansible-inventory=/etc/ansible/hosts test_infra.py # Run in parallel with pytest-xdist pytest -n 4 --hosts=web1,web2,web3,web4 test_infra.py # Output for Nagios monitoring pytest --nagios test_infra.py # Generate JUnit XML for CI pytest --junit-xml=results.xml test_infra.py ``` -------------------------------- ### Container Management (Docker/Podman) Source: https://context7.com/pytest-dev/pytest-testinfra/llms.txt API for interacting with Docker and Podman containers, allowing status checks and listing of containers. ```APIDOC ## GET /host/docker ### Description Interact with Docker containers to check status, properties, and list containers. ### Method GET ### Endpoint host.docker(name) ### Parameters #### Path Parameters - **name** (string) - Required - The name or ID of the container. ### Response #### Success Response (200) - **is_running** (boolean) - True if the container is currently running. - **id** (string) - The unique container ID. ### Response Example { "is_running": true, "id": "a1b2c3d4e5f6" } ``` -------------------------------- ### Retrieve System Information Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/modules.md Accesses various metadata about the target system, including OS type, distribution, release version, codename, and architecture. ```python os_type = host.system_info.type dist = host.system_info.distribution arch = host.system_info.arch ``` -------------------------------- ### Execute Salt Modules Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/modules.md Runs Salt module functions and returns their output. It can execute functions with single or multiple arguments, and retrieve specific grains items. ```python >>> host.salt("pkg.version", "nginx") '1.6.2-5' >>> host.salt("pkg.version", ["nginx", "php5-fpm"]) {'nginx': '1.6.2-5', 'php5-fpm': '5.6.7+dfsg-1'} >>> host.salt("grains.item", ["osarch", "mem_total", "num_cpus"]) {'osarch': 'amd64', 'num_cpus': 4, 'mem_total': 15520} ``` -------------------------------- ### Check Command Success and Failure with Testinfra Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/modules.md Demonstrates how to determine if a command executed successfully or failed using the `succeeded` and `failed` boolean properties of the `CommandResult` object. ```python >>> host.run("true").succeeded True ``` ```python >>> host.run("false").failed True ``` -------------------------------- ### host.iptables() - Test Firewall Rules Source: https://context7.com/pytest-dev/pytest-testinfra/llms.txt Retrieves and validates iptables firewall rules configuration. ```APIDOC ## host.iptables.rules(table, chain, version) ### Description Fetches firewall rules from the system to verify security policies. ### Method N/A (Python Method) ### Parameters #### Query Parameters - **table** (string) - Optional - The iptables table (default: filter). - **chain** (string) - Optional - The specific chain to inspect. - **version** (int) - Optional - IP version (4 or 6). ### Response #### Success Response (200) - **rules** (list) - A list of strings representing the active firewall rules. ``` -------------------------------- ### Test Docker Images with Testinfra Source: https://github.com/pytest-dev/pytest-testinfra/blob/main/doc/source/examples.md Provides a Python pytest fixture to build a Docker image, run a container, and establish a Testinfra connection to it. The fixture handles container cleanup after the test session. It demonstrates testing an application within the container. ```python import pytest import subprocess import testinfra @pytest.fixture(scope='session') def host(request): subprocess.check_call(['docker', 'build', '-t', 'myimage', '.']) docker_id = subprocess.check_output( ['docker', 'run', '-d', 'myimage']).decode().strip() yield testinfra.get_host("docker://" + docker_id) subprocess.check_call(['docker', 'rm', '-f', docker_id]) def test_myimage(host): assert host.check_output('myapp -v') == 'Myapp 1.0' ```