---
name: "testinfra"
section: "1"
platform: "linux"
package: "python-pytest-testinfra"
version: "10.2.2-2"
release: "Arch Linux 2026-11-01"
platforms: ["linux"]
url: "https://new.carta.tech/testinfra"
---

# testinfra(1)

testinfra Documentation Latest documentation: \<https://testinfra.readthedocs.io/en/latest\>

## NAME

testinfra - testinfra Documentation

Latest documentation: \<https://testinfra.readthedocs.io/en/latest\>

## ABOUT

With Testinfra you can write unit tests in Python to test *actual state* of your servers configured by management tools like Salt \<https://saltstack.com/\>, Ansible \<https://www.ansible.com/\>, Puppet \<https://puppetlabs.com/\>, Chef \<https://www.chef.io/\> and so on.

Testinfra aims to be a Serverspec \<https://serverspec.org/\> equivalent in python and is written as a plugin to the powerful Pytest \<https://pytest.org/\> test engine

## LICENSE

Apache License 2.0 \<https://github.com/pytest-dev/pytest-testinfra/blob/main/LICENSE\>

The logo is licensed under the Creative Commons NoDerivatives 4.0 License \<https://creativecommons.org/licenses/by-nd/4.0/\> If you have some other use in mind, contact us.

## QUICK START

Install testinfra using pip:

```
$ pip install pytest-testinfra
# or install the devel version
$ pip install 'git+https://github.com/pytest-dev/pytest-testinfra@main#egg=pytest-testinfra'
```

Write your first tests file to *test\_myinfra.py*:

```
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
```

And run it:

```
$ pytest -v test_myinfra.py
====================== test session starts ======================
platform linux -- Python 2.7.3 -- py-1.4.26 -- pytest-2.6.4
plugins: testinfra
collected 3 items
test_myinfra.py::test_passwd_file[local] PASSED
test_myinfra.py::test_nginx_is_installed[local] PASSED
test_myinfra.py::test_nginx_running_and_enabled[local] PASSED
=================== 3 passed in 0.66 seconds ====================
```

## DOCUMENTATION

### Changelog

### 10.2.2

- •

  \[FIX\] Include files required to run tests in sdist

### 10.2.1

- •

  \[FIX\] Fix releasing to pypi

### 10.2.0

- •

  \[NEW\] Query all usernames and group names

- •

  \[FIX\] Prevent Paramiko deadlock when test sends more than 2MB to stdout

- •

  \[FIX\] Follow changes in ansible shell module

- •

  \[FIX\] Add 4 to the expected exit code when running "systemctl is-active"

- •

  \[FIX\] Fix KeyError in MountPoint.\_\_repr\_\_() if mount does not exist

- •

  \[DOC\] Use pytest command instead of py.test

- •

  \[DOC\] Extend backend documentation with a general host spec section

- •

  \[MISC\] Also run lint for py 3.12 and 3.13

- •

  \[MISC\] Switch packaging to use hatchling

- •

  \[MISC\] Drop unused extra "args" argument to run\_winrm()

- •

  \[MISC\] Use ruff format instead of black/isort

- •

  \[MISC\] Use ruff instead of flake8

- •

  \[MISC\] Use f-string instead of str.format()

- •

  \[MISC\] Use builtin dict, list and tuple for typing

- •

  \[MISC\] Use python 3.11 during tests

- •

  \[MISC\] Fix salt tests

- •

  \[MISC\] Fix tests failing due to expiration date passed

- •

  \[MISC\] Remove crypt lib from testing

### 10.1.1

- •

  \[FIX\] Add check for the existence of ssh control path directory

- •

  \[FIX\] Handle is\_installed for rpm package when rpm database is corrupted

- •

  \[FIX\] Fix service.exists

### 10.1.0

- •

  \[NEW\] Add Interface.link property

- •

  \[FIX\] Make file properties follow symlinks

- •

  \[FIX\] Require pytest\>=6 and use future annotations for pytest\<7 compatibility

### 10.0.0

- •

  \[FIX\] Ansible: Fix for missing group names in get\_variables()

- •

  \[FIX\] testinfra/modules/blockdevice: Don't fail on stderr

- •

  \[DOC\] Extend and show the documentation of CommandResult

- •

  \[FIX\] Extend list of valid suffixes for systemd units

- •

  \[DOC\] Add missing Environment doc section

- •

  \[MISC\] Define types for plugin.py

- •

  \[FIX\] Missing RHEL distribution in package module

- •

  \[NEW\] Add brew support in package module

- •

  \[NEW\] Add Service.exists

- •

  \[MISC\] Make CommandResult a dataclass

### 9.0.0

- •

  \[BREAKING\] pytest-testinfra now require python \>= 3.9

- •

  \[BREAKING\] Drop deprecated module PipPackage

- •

  \[NEW\] Add support for the SSH ControlPath connection sharing option (#713)

- •

  \[FIX\] Retry SSH on ConnectionResetError (#708)

- •

  \[FIX\] List openSUSE Leap and Tumbleweed explicitly as rpm based distributions

- •

  \[FIX\] Make group name mandatory in group module

### 8.1.0

- •

  \[NEW\] Add Windows support for File and Service modules

- •

  \[NEW\] Add File.is\_executable property

### 8.0.0

- •

  \[NEW\] Add Group.members attribute

- •

  \[NEW\] Add File.inode attribute

- •

  \[NEW\] Add Interface.routes() method

- •

  \[NEW\] Add Docker.is\_restarting attribute

- •

  \[FIX\] Fix possible error in Interface.default()

- •

  \[FIX\] Fix busybox detection in Process module

- •

  \[FIX\] Fix possible KeyError in SysInfo module

- •

  \[BREAKING\] Drop support for python 3.7

### 7.0.1

- •

  \[FIX\] Fix *command -v* compatibility with dash shell

### 7.0.0

- •

  \[NEW\] Improved ssh config support in Paramiko backend

- •

  \[NEW\] Add chroot backend

- •

  \[NEW\] Add support for Manjaro-Linux

- •

  \[NEW\] Add support for Cloudlinux

- •

  \[BREAKING\] Drop support for python 3.6 which is EOL

### 6.8.0

- •

  \[NEW\] Add support for AlmaLinux and RockyLinux

### 6.7.0

- •

  \[NEW\] Handle ansible\_connection type community.docker.docker

- •

  \[NEW\] add ssh\_extra\_args option

### 6.6.0

- •

  \[NEW\] Allow to test for user password expiration

- •

  \[NEW\] Handle ANSIBLE\_SSH\_COMMON\_ARGS and ANSIBLE\_SSH\_EXTRA\_ARGS environment variables for ansible connections

- •

  \[FIX\] Fix encoding issue in salt connections

- •

  \[FIX\] Fix AttributeError when "command" is not available and fallback to "which"

### 6.5.0

- •

  Fallback to which when "command -v" fails

- •

  Use realpath by default to resolve symlinks instead of "readlink -f"

- •

  ansible: Support environment variables

- •

  Force package module to resolve to RpmPackage on Fedora

- •

  Fix new versions of supervisor may exit with status != 0

- •

  Eventually decode ansible output when it's not ascii

- •

  Either use python3 or python to get remote encoding

### 6.4.0

- •

  Implement Interface names and default (#615)

- •

  Implement Service.systemd\_properties (#612)

### 6.3.0

- •

  Fix #451 for use with pytest -p no:terminal

- •

  Add client\_version() and server\_version() and version() to docker module.

### 6.2.0

- •

  Fix #590: Systeminfo doesn't resolve Windows correctly  (#592)

- •

  First implementation of network namespaces in addr module (#596)

- •

  pip check support in PipPackage module (#605)

- •

  pip refactoring: implementation of installed and version (#606)

- •

  Allow to specify supervisorctl and supervisord.conf paths (#536)

### 6.1.0

- •

  Fix wrong package module on CentOS having dpkg tools installed #570 (#575)

- •

  Deduplicate hosts returned by get\_backends() (#572)

- •

  Use /run/systemd/system/ to detect systemd (fixes #546)

- •

  Use ssh\_args from ansible.cfg

- •

  Require python \>= 3.6

- •

  Fix ValueError with python 3.8+ when using --nagios option.

### 6.0.0

- •

  Breaking change: testinfra has moved to the \<https://github.com/pytest-dev/\> organization. Project on PyPi is renamed as pytest-testinfra. A dummy testinfra will make the transition, but you should rename to pytest-testinfra in your requirements files.

### 5.3.1

- •

  Fix newly introduced is\_masked property on systemd service \<https://github.com/philpep/testinfra/pull/569\>

### 5.3.0

- •

  Add is\_masked property on systemd service

### 5.2.2

- •

  iptables: use -w option to wait for iptables lock when running in parallel with pytest-xdist.

### 5.2.1

- •

  Fix documentation build

### 5.2.0

- •

  Allow kubeconfig context to be supplied in kubernetes backend

- •

  Drop file.\_\_ne\_\_ implementation and require python \>= 3.5

### 5.1.0

- •

  Use remote\_user and remote\_port in ansible.cfg

- •

  Add *arch* (architecture) attribute to system\_info module

### 5.0.0

- •

  Breaking change:  host.file().listdir() is now a method

### 4.1.0

- •

  Pass extra arguments to ansible CLI via host.ansible()

- •

  New method host.file.listdir() to list items in a directory.

### 4.0.0

- •

  Drop python2 support

### 3.4.0

- •

  Add podman backend and module

- •

  WARNING: this will be the latest testinfra version supporting python2, please upgrade to python3.

### 3.3.0

- •

  Add extras for backend dependencies (#454)

- •

  Various enhancements of kitchen integration documentation

- •

  ansible backend now support "password" field from ansible inventory

- •

  New backend "openshift"

### 3.2.1

- •

  Fix Process module when working with long strings (username, ...) #505

### 3.2.0

- •

  New module "environment" for getting remote environment variables

- •

  New module "block\_device" exposing block device information

- •

  Add a global flag --force-ansible to the command line

- •

  Raise an error in case of missing ansible inventory file

- •

  Fix an escape issue with ansible ssh args set inventory or configuration file

### 3.1.0

- •

  ssh connections uses persistent connections by default. You can disable this by passing controlpersist=0 to the connections options.

- •

  ansible ssh connections now use ssh backend instead of paramiko. ansible\_ssh\_common\_args and ansible\_ssh\_extra\_args are now taking in account.

- •

  Add a new ansible connection options "force\_ansible", when set to True, testinfra will always call ansible for all commands he need to run.

- •

  Handle all ansible connections types by setting force\_ansible=True for connections which doesn't have a testinfra equivalent connection (for example "network\_cli").

### 3.0.6

- •

  Issue full command logging using DEBUG log level to avoid logging sensible data when log level is INFO.

- •

  Fix possible crash when parsing ansible inventories #470

- •

  Support using alternative kubeconfig file in kubectl connections #460

- •

  Support parsing ProxyCommand from ssh\_config for paramiko connections

### 3.0.5

- •

  Set default timeout to 10s on ssh/paramiko connections

- •

  Add support for ansible inventory parameter ansible\_private\_key\_file

### 3.0.4

- •

  Add support for ansible lxc and lxd connections

### 3.0.3

- •

  Fix paramiko parsing RequestTTY from ssh configs

- •

  Re-add "groups" key from ansible.get\_variables() to be backward compatible with testinfra 2.X

### 3.0.2

- •

  Fix ansible with no inventory resolving to "localhost"

- •

  Fix support for ansible 2.8 with no inventory

- •

  Fix ansible/paramiko which wasn't reading hosts config from ~/.ssh/config

- •

  Allow to pass --ssh-config and --ssh-identity-file to ansible connection

### 3.0.1

- •

  Fix parsing of ipv6 addresses for paramiko, ssh and ansible backends.

- •

  Fix --connection=ansible invocation when no hosts are provided

### 3.0.0

- •

  New ansible backend fixing support for ansible 2.8 and license issue. See \<https://github.com/philpep/testinfra/issues/431\> for details. This make ansible using testinfra native backends and only works for local, ssh or docker connections. I you have others connection types or issues, please open a bug on \<https://github.com/philpep/testinfra/issues/new\>

- •

  Windows support is improved. "package" module is handled with Chocolatey and there's support for the "user" module.

### 2.1.0

- •

  docker: new get\_containers() classmethod

- •

  socket: fix parsing of ipv6 addresses with new versions of ss

- •

  service: systemd fallback to sysv when "systemctl is-active" is not working

### 2.0.0

- •

  Add addr module, used to test network connectivity

- •

  Drop deprecated "testinfra" command, you should use "py.test" instead

- •

  Drop deprecated top level fixtures, access them through the fixture "host" instead.

- •

  Drop support for ansible \<= 2.4

### 1.19.0

- •

  Add docker module

- •

  Fix pytest 4 compatibility

### 1.18.0

- •

  Allow to urlencode character in host specification "user:pass@host" (#387)

- •

  Fix double logging from both pytest and testinfra

- •

  Drop support for python 2.6

- •

  Allow to configure timeouts for winrm backend

### 1.17.0

- •

  Add support for ansible "become" user in ansible module

- •

  Add failed/succeeded property on run() output

### 1.16.0

- •

  packaging: Use setuptools\_scm instead of pbr

- •

  iptables: add ip6tables support

- •

  sysctl: find sysctl outside of PATH (/sbin)

### 1.15.0

- •

  Fix finding ss and netstat command in "sbin" paths for Centos (359)

- •

  Add a workaround for \<https://github.com/pytest-dev/pytest/issues/3542\>

- •

  Handle "starting" status for Service module on Alpine linux

- •

  Fix no\_ssl and no\_verify\_ssl options for WinRM backend

### 1.14.1

- •

  Fix multi-host test ordering (#347), regression introduced in 1.13.1

- •

  Fix Socket on OpenBSD hosts (#338)

### 1.14.0

- •

  Add a new lxc backend

- •

  Socket: fix is\_listening for unix sockets

- •

  Add namespace and container support for kubernetes backend

- •

  Add a cache of parsed ansible inventories for ansible backend

- •

  Service: fix service detection on Centos 6 hosts

- •

  File: implement file comparison with string paths

### 1.13.1

- •

  package: fix is\_installed and version behavior for uninstalled packages (#321 and #326)

- •

  ansible: Use predictibles test ordering when using pytest-xdist to fix random test collections errors (#316)

### 1.13.0

- •

  socket: fix detection of udp listening sockets (#311)

- •

  ssh backend: Add support for GSSAPI

### 1.12.0

- •

  ansible: fix compatibility with ansible 2.5

- •

  pip: fix compatibility with pip 10 (#299)

### 1.11.1

- •

  Socket: fix error with old versions of ss without the --no-header option (#293)

### 1.11.0

- •

  Fix bad error reporting when using ansible module without ansible backend (#288)

- •

  Socket: add a new implementation using ss instead of netstat (#124)

- •

  Add service, process, and systeminfo support for Alpine (#283)

### 1.10.1

- •

  Fix get\_variables() for ansible\>=2.0,\<2.4 (#274)

- •

  Paramiko: Use the RequireTTY setting if specified in a provided SSHConfig (#247)

### 1.10.0

- •

  New iptables module

### 1.9.1

- •

  Fix running testinfra within a suite using doctest (#268)

- •

  Service: add is\_valid method for systemd

- •

  Fix file.linked\_to() for Mac OS

### 1.9.0

- •

  Interface: allow to find 'ip' command ousite of PATH

- •

  Fix --nagios option with python 3

### 1.8.0

- •

  Deprecate testinfra command (will be dropped in 2.0), use py.test instead #135

- •

  Handle --nagios option when using py.test command

### 1.7.1

- •

  Support for ansible 2.4 (#249)

### 1.7.0

- •

  Salt: allow specify config directory (#230)

- •

  Add a WinRM backend

- •

  Socket: ipv6 sockets can handle ipv4 clients (#234)

- •

  Service: Enhance upstart detection (#243)

### 1.6.5

- •

  Service: add is\_enabled() support for OpenBSD

- •

  Add ssh identity file option for paramiko and ssh backends

- •

  Expand tilde (~) to user home directory for ssh-config, ssh-identity-file and ansible-inventory options

### 1.6.4

- •

  Service: Allow to find 'service' command outside of $PATH #211

- •

  doc fixes

### 1.6.3

- •

  Fix unwanted deprecation warning when running tests with pytest 3.1 #204

### 1.6.2

- •

  Fix wheel package for 1.6.1

### 1.6.1

- •

  Support ansible 2.3 with python 3 (#197)

### 1.6.0

- •

  New 'host' fixture as a replacement for all other fixtures. See \<https://testinfra.readthedocs.io/en/latest/modules.html#host\> (Other fixtures are deprecated and will be removed in 2.0 release).

### 1.5.5

- •

  backends: Fix ansible backend with ansible \>= 2.3 (#195)

### 1.5.4

- •

  backends: fallback to UTF-8 encoding when system encoding is ASCII.

- •

  Service: fix is\_running() on systems using Upstart

### 1.5.3

- •

  Sudo: restore backend command in case of exceptions

### 1.5.2

- •

  Honnor become\_user when using the ansible backend

### 1.5.1

- •

  Add dependency on importlib on python 2.6

### 1.5.0

- •

  New kubectl backend

- •

  Command: check\_output strip carriage return and newlines (#164)

- •

  Package: rpm improve getting version() and release()

- •

  User: add gecos (comment) field (#155)

### 1.4.5

- •

  SystemInfo: detect codename from VERSION\_CODENAME in /etc/os-release (fallback when lsb\_release isn't installed).

- •

  Package: add release property for rpm based systems.

### Invocation

### Test multiples hosts

By default Testinfra launch tests on local machine, but you can also test remotes systems using paramiko \<https://www.paramiko.org\> (a ssh implementation in python):

```
$ pip install paramiko
$ pytest -v --hosts=localhost,root@webserver:2222 test_myinfra.py
====================== test session starts ======================
platform linux -- Python 2.7.3 -- py-1.4.26 -- pytest-2.6.4
plugins: testinfra
collected 3 items
test_myinfra.py::test_passwd_file[localhost] PASSED
test_myinfra.py::test_nginx_is_installed[localhost] PASSED
test_myinfra.py::test_nginx_running_and_enabled[localhost] PASSED
test_myinfra.py::test_passwd_file[root@webserver:2222] PASSED
test_myinfra.py::test_nginx_is_installed[root@webserver:2222] PASSED
test_myinfra.py::test_nginx_running_and_enabled[root@webserver:2222] PASSED
=================== 6 passed in 8.49 seconds ====================
```

You can also set hosts per test module:

```
testinfra_hosts = ["localhost", "root@webserver:2222"]
def test_foo(host):
    [....]
```

### Parallel execution

If you have a lot of tests, you can use the pytest-xdist \<https://pypi.org/project/pytest-xdist/\> plugin to run tests using multiples process:

```
$ pip install pytest-xdist
# Launch tests using 3 processes
$ pytest -n 3 -v --host=web1,web2,web3,web4,web5,web6 test_myinfra.py
```

### Advanced invocation

```
# 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
```

For more usages and features, see the Pytest \<https://docs.pytest.org/en/latest/\> documentation.

### Connection backends

Testinfra comes with several connections backends for remote command execution.

When installing, you should select the backends you require as **extras** to ensure Python dependencies are satisfied (note various system packaged tools may still be required).  For example

```
$ pip install pytest-testinfra[ansible,salt]
```

For all backends, commands can be run as superuser with the **--sudo** option or as specific user with the **--sudo-user** option.

### General Host specification

The **--hosts** parameter in Testinfra is used to specify the target hosts for the tests.

You can specify multiple hosts by separating each target with a comma, allowing you to run tests using different backends across different environments or machines.

The user, password, and port fields are optional, providing flexibility depending on your authentication and connection requirements.

Please also read the details for the individual backends, as the host spec is handled slightly differently from backend to backend.

**Syntax:**

```
--hosts=<backend>://<user>:<password>@<host>:<port>
```

**Components:**

- •

  **\<backend\>**: type of backend to be used (e.g., ssh, docker, paramiko, local)

- •

  **\<user\>**: username for authentication (optional)

- •

  **\<password\>**: password for authentication (optional)

- •

  **\<host\>**: target hostname or IP address

- •

  **\<port\>**: target port number (optional)

Special characters (e.g. ":") in the user and password fields need to be percent-encoded according to RFC 3986. This can be done using **urllib.parse.quote()** in Python.

For example:

```
import urllib.parse
user = urllib.parse.quote('user:name')
password = urllib.parse.quote('p@ssw:rd')
host = 'hostname'
port = 22
host_spec = f"ssh://{user}:{password}@{host}:{port}"
print(host_spec)
```

This will ensure that any special characters are properly encoded, making the connection string valid.

**Examples:**

SSH Backend with Full Specification:

```
testinfra --hosts=ssh://user:password@hostname:22
```

Docker Backend:

```
testinfra --hosts=docker://container_id
```

Mixed Backends:

```
testinfra --hosts=ssh://user:password@hostname:22,docker://container_id,local://
```

### local

This is the default backend when no hosts are provided (either via **--hosts** or in modules). Commands are run locally in a subprocess under the current user:

```
$ pytest --sudo test_myinfra.py
```

### paramiko

This is the default backend when a hosts list is provided. Paramiko \<https://www.paramiko.org/\> is a Python implementation of the SSHv2 protocol. Testinfra will not ask you for a password, so you must be able to connect without password (using passwordless keys or using **ssh-agent**).

You can provide an alternate ssh-config:

```
$ pytest --ssh-config=/path/to/ssh_config --hosts=server
```

### docker

The Docker backend can be used to test *running* Docker containers. It uses the docker exec \<https://docs.docker.com/reference/commandline/exec/\> command:

```
$ pytest --hosts='docker://[user@]container_id_or_name'
```

See also the Test Docker images \<#test-docker-images\> example.

### podman

The Podman backend can be used to test *running* Podman containers. It uses the podman exec \<https://github.com/containers/libpod/blob/master/docs/source/markdown/podman.1.md\> command:

```
$ pytest --hosts='podman://[user@]container_id_or_name'
```

### ssh

This is a pure SSH backend using the **ssh** command. Example:

```
$ pytest --hosts='ssh://server'
$ pytest --ssh-config=/path/to/ssh_config --hosts='ssh://server'
$ pytest --ssh-identity-file=/path/to/key --hosts='ssh://server'
$ pytest --hosts='ssh://server?timeout=60&controlpersist=120'
$ pytest --hosts='ssh://server' --ssh-extra-args='-o StrictHostKeyChecking=no'
```

By default timeout is set to 10 seconds and ControlPersist is set to 60 seconds. You can disable persistent connection by passing *controlpersist=0* to the options.

### salt

The salt backend uses the salt Python client API \<https://docs.saltstack.com/en/latest/ref/clients/\> and can be used from the salt-master server:

```
$ pytest --hosts='salt://*'
$ pytest --hosts='salt://minion1,salt://minion2'
$ pytest --hosts='salt://web*'
$ pytest --hosts='salt://G@os:Debian'
```

Testinfra will use the salt connection channel to run commands.

Hosts can be selected by using the *glob* and compound matchers \<https://docs.saltstack.com/en/latest/topics/targeting/compound.html\>.

### ansible

Ansible inventories may be used to describe what hosts Testinfra should use and how to connect them, using Testinfra's Ansible backend.

To use the Ansible backend, prefix the **--hosts** option with **ansible://** e.g:

```
$ pytest --hosts='ansible://all' # tests all inventory hosts
$ pytest --hosts='ansible://host1,ansible://host2'
$ pytest --hosts='ansible://web*'
```

An inventory may be specified with the **--ansible-inventory** option, otherwise the default (**/etc/ansible/hosts**) is used.

The **ansible\_connection** value in your inventory will be used to determine which backend to use for individual hosts: **local**, **ssh**, **paramiko** and **docker** are supported values. Other connections (or if you are using the **--force-ansible** option) will result in testinfra running all commands via Ansible itself, which is substantially slower than the other backends:

```
$ pytest --force-ansible --hosts='ansible://all'
$ pytest --hosts='ansible://host?force_ansible=True'
```

By default, the Ansible connection backend will first try to use **ansible\_ssh\_private\_key\_file** and **ansible\_private\_key\_file** to authenticate, then fall back to the **ansible\_user** with **ansible\_ssh\_pass** variables (both are required), before finally falling back to your own host's SSH config.

This behavior may be overwritten by specifying either the **--ssh-identity-file** option or the **--ssh-config** option

Finally, these environment variables are supported and will be passed along to their corresponding ansible variable (See Ansible documentation):

\<https://docs.ansible.com/ansible/2.3/intro\_inventory.html\>

\<https://docs.ansible.com/ansible/latest/reference\_appendices/config.html\>

- •

  **ANSIBLE\_REMOTE\_USER**

- •

  **ANSIBLE\_SSH\_EXTRA\_ARGS**

- •

  **ANSIBLE\_SSH\_COMMON\_ARGS**

- •

  **ANSIBLE\_REMOTE\_PORT**

- •

  **ANSIBLE\_BECOME\_USER**

- •

  **ANSIBLE\_BECOME**

### kubectl

The kubectl backend can be used to test containers running in Kubernetes.  It uses the kubectl exec \<https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands#exec/\> command and support connecting to a given container name within a pod and using a given namespace:

```
# will use the default namespace and default container
$ pytest --hosts='kubectl://mypod-a1b2c3'
# specify container name and namespace
$ pytest --hosts='kubectl://somepod-2536ab?container=nginx&namespace=web'
# specify the kubeconfig context to use
$ pytest --hosts='kubectl://somepod-2536ab?context=k8s-cluster-a&container=nginx'
# you can specify kubeconfig either from KUBECONFIG environment variable
# or when working with multiple configuration with the "kubeconfig" option
$ pytest --hosts='kubectl://somepod-123?kubeconfig=/path/kubeconfig,kubectl://otherpod-123?kubeconfig=/other/kubeconfig'
```

### openshift

The openshift backend can be used to test containers running in OpenShift.  It uses the oc exec \<https://docs.openshift.com/container-platform/4.2/nodes/containers/nodes-containers-remote-commands.html\> command and support connecting to a given container name within a pod and using a given namespace:

```
# will use the default namespace and default container
$ pytest --hosts='openshift://mypod-a1b2c3'
# specify container name and namespace
$ pytest --hosts='openshift://somepod-2536ab?container=nginx&namespace=web'
# you can specify kubeconfig either from KUBECONFIG environment variable
# or when working with multiple configuration with the "kubeconfig" option
$ pytest --hosts='openshift://somepod-123?kubeconfig=/path/kubeconfig,openshift://otherpod-123?kubeconfig=/other/kubeconfig'
```

### winrm

The winrm backend uses pywinrm \<https://pypi.python.org/pypi/pywinrm\>:

```
$ pytest --hosts='winrm://Administrator:Password@127.0.0.1'
$ pytest --hosts='winrm://vagrant@127.0.0.1:2200?no_ssl=true&no_verify_ssl=true'
```

pywinrm's default read and operation timeout can be overridden using query arguments **read\_timeout\_sec** and **operation\_timeout\_sec**:

```
$ pytest --hosts='winrm://vagrant@127.0.0.1:2200?read_timeout_sec=120&operation_timeout_sec=100'
```

### LXC/LXD

The LXC backend can be used to test *running* LXC or LXD containers. It uses the lxc exec \<https://linuxcontainers.org/lxd/getting-started-cli/\> command:

```
$ pytest --hosts='lxc://container_name'
```

### Modules

Testinfra modules are provided through the *host* fixture \<https://docs.pytest.org/en/latest/fixture.html#fixture\>, declare it as arguments of your test function to make it available within it.

```
def test_foo(host):
    # [...]
```

### host

- **class Host(backend: BaseBackend)**

  - **ansible**

    **testinfra.modules.ansible.Ansible** class

  - **addr**

    **testinfra.modules.addr.Addr** class

  - **blockdevice**

    **testinfra.modules.blockdevice.BlockDevice** class

  - **docker**

    **testinfra.modules.docker.Docker** class

  - **environment**

    **testinfra.modules.environment.Environment** class

  - **file**

    **testinfra.modules.file.File** class

  - **group**

    **testinfra.modules.group.Group** class

  - **interface**

    **testinfra.modules.interface.Interface** class

  - **iptables**

    **testinfra.modules.iptables.Iptables** class

  - **mount\_point**

    **testinfra.modules.mountpoint.MountPoint** class

  - **package**

    **testinfra.modules.package.Package** class

  - **pip**

    **testinfra.modules.pip.Pip** class

  - **podman**

    **testinfra.modules.podman.Podman** class

  - **process**

    **testinfra.modules.process.Process** class

  - **puppet\_resource**

    **testinfra.modules.puppet.PuppetResource** class

  - **facter**

    **testinfra.modules.puppet.Facter** class

  - **salt**

    **testinfra.modules.salt.Salt** class

  - **service**

    **testinfra.modules.service.Service** class

  - **socket**

    **testinfra.modules.socket.Socket** class

  - **sudo**

    **testinfra.modules.sudo.Sudo** class

  - **supervisor**

    **testinfra.modules.supervisor.Supervisor** class

  - **sysctl**

    **testinfra.modules.sysctl.Sysctl** class

  - **system\_info**

    **testinfra.modules.systeminfo.SystemInfo** class

  - **user**

    **testinfra.modules.user.User** class

  - **property has\_command\_v: bool**

    Return True if *command -v* is available

  - **exists(command: str) -\> bool**

    Return True if given command exist in $PATH

  - **find\_command(command: str, extrapaths: Iterable\[str\] = ('/sbin', '/usr/sbin')) -\> str**

    Return path of given command

    raise ValueError if command cannot be found

  - **run(command: str, \*args: str, \*\*kwargs: Any) -\> CommandResult \<#testinfra.backend.base.CommandResult\>**

    Run given command and return rc (exit status), stdout and stderr

    ```
    >>> 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
    ```

    Good practice: always use shell arguments quoting to avoid shell injection

    ```
    >>> 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'")
    ```

  - **run\_expect(expected: list\[int\], command: str, \*args: str, \*\*kwargs: Any) -\> CommandResult \<#testinfra.backend.base.CommandResult\>**

    Run command and check it return an expected exit status

    - **Parameters**

      **expected** -- A list of expected exit status

    - **Raises**

      AssertionError

  - **run\_test(command: str, \*args: str, \*\*kwargs: Any) -\> CommandResult \<#testinfra.backend.base.CommandResult\>**

    Run command and check it return an exit status of 0 or 1

    - **Raises**

      AssertionError

  - **check\_output(command: str, \*args: str, \*\*kwargs: Any) -\> str**

    Get stdout of a command which has run successfully

    - **Returns**

      stdout without trailing newline

    - **Raises**

      AssertionError

  - **classmethod get\_host(hostspec: str, \*\*kwargs: Any) -\> Host \<#testinfra.host.Host\>**

    Return a Host instance from *hostspec*

    *hostspec* should be like *\<backend\_type\>://\<name\>?param1=value1&param2=value2*

    Params can also be passed in *\*\*kwargs* (eg. get\_host("local://", sudo=True) is equivalent to get\_host("local://?sudo=true"))

    Examples:

    ```
    >>> 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")
    ```

### Ansible

- **class Ansible(module\_name, module\_args=None, check=True)**

  Run Ansible module functions

  This module is only available with the ansible \<#ansible-connection-backend\> connection backend.

  Check mode \<https://docs.ansible.com/ansible/playbooks\_checkmode.html\> is enabled by default, you can disable it with *check=False*.

  Become \<https://docs.ansible.com/ansible/user\_guide/become.html#id1\> is *False* by default. You can enable it with *become=True*.

  Ansible arguments that are not related to the Ansible inventory or connection (both managed by testinfra) are also accepted through keyword arguments:

  - •

    **become\_method** *str* sudo, su, doas, etc.

  - •

    **become\_user** *str* become this user.

  - •

    **diff** *bool*: when changing (small) files and templates, show the differences in those files.

  - •

    **extra\_vars** *dict* serialized to a JSON string, passed to Ansible.

  - •

    **one\_line** *bool*: condense output.

  - •

    **user** *str* connect as this user.

  - •

    **verbose** *int* level of verbosity

  ```
  >>> host.ansible("apt", "name=nginx state=present")["changed"]
  False
  >>> host.ansible("apt", "name=nginx state=present", become=True)["changed"]
  False
  >>> host.ansible("command", "echo foo", check=False)["stdout"]
  'foo'
  >>> host.ansible("setup")["ansible_facts"]["ansible_lsb"]["codename"]
  'jessie'
  >>> host.ansible("file", "path=/etc/passwd")["mode"]
  '0640'
  >>> host.ansible(
  ... "command",
  ... "id --user --name",
  ... check=False,
  ... become=True,
  ... become_user="http",
  ... )["stdout"]
  'http'
  >>> host.ansible(
  ... "apt",
  ... "name={{ packages }}",
  ... check=False,
  ... extra_vars={"packages": ["neovim", "vim"]},
  ... )
  # Installs neovim and vim.
  ```

  - **exception AnsibleException(result)**

    Exception raised when an error occur in an ansible call

    result from ansible can be accessed through the **result** attribute

    ```
    >>> try:
    ...     host.ansible("command", "echo foo")
    ... except host.ansible.AnsibleException as exc:
    ...     assert exc.result['failed'] is True
    ...     assert exc.result['msg'] == 'Skipped. You might want to try check=False'  # noqa
    ```

  - **get\_variables()**

    Returns a dict of ansible variables

    ```
    >>> host.ansible.get_variables()
    {
        'inventory_hostname': 'localhost',
        'group_names': ['ungrouped'],
        'foo': 'bar',
    }
    ```

### Addr

- **class Addr(name)**

  Test remote address

  Example:

  ```
  >>> google = host.addr("google.com")
  >>> google.is_resolvable
  True
  >>> '173.194.32.225' in google.ipv4_addresses
  True
  >>> google.is_reachable
  True
  >>> google.port(443).is_reachable
  True
  >>> google.port(666).is_reachable
  False
  ```

  Can also be use within a network namespace \<https://man7.org/linux/man-pages/man7/namespaces.7.html\>.

  ```
  >>> localhost = host.addr("localhost", "ns1")
  >>> localhost.is_resolvable
  True
  ```

  Network namespaces can only be used if ip \<https://man7.org/linux/man-pages/man8/ip.8.html\> command is available because in this case, the module use ip-netns \<https://man7.org/linux/man-pages/man8/ip-netns.8.html\> as command prefix. In the other case, it will raise NotImplementedError.

  - **property name**

    Return host name

  - **property namespace**

    Return network namespace

  - **property namespace\_exists**

    Test if the network namespace exists

  - **property is\_resolvable**

    Return if address is resolvable

  - **property is\_reachable**

    Return if address is reachable

  - **property ip\_addresses**

    Return IP addresses of host

  - **property ipv4\_addresses**

    Return IPv4 addresses of host

  - **property ipv6\_addresses**

    Return IPv6 addresses of host

  - **port(port)**

    Return address-port pair

### BlockDevice

- **class BlockDevice(name)**

  Information for block device.

  Should be used with sudo or under root.

  If device is not a block device, RuntimeError is raised.

  - **property is\_partition**

    Return True if the device is a partition.

    ```
    >>> host.block_device("/dev/sda1").is_partition
    True
    ```

    ```
    >>> host.block_device("/dev/sda").is_partition
    False
    ```

  - **property size**

    Return size if the device in bytes.

    ```
    >>> host.block_device("/dev/sda1").size
    512110190592
    ```

  - **property sector\_size**

    Return sector size for the device in bytes.

    ```
    >>> host.block_device("/dev/sda1").sector_size
    512
    ```

  - **property block\_size**

    Return block size for the device in bytes.

    ```
    >>> host.block_device("/dev/sda").block_size
    4096
    ```

  - **property start\_sector**

    Return start sector of the device on the underlying device.

    Usually the value is zero for full devices and is non-zero for partitions.

    ```
    >>> host.block_device("/dev/sda1").start_sector
    2048
    ```

    ```
    >>> host.block_device("/dev/md0").start_sector
    0
    ```

  - **property is\_writable**

    Return True if device is writable (have no RO status)

    ```
    >>> host.block_device("/dev/sda").is_writable
    True
    ```

    ```
    >>> host.block_device("/dev/loop1").is_writable
    False
    ```

  - **property ra**

    Return Read Ahead for the device in 512-bytes sectors.

    ```
    >>> host.block_device("/dev/sda").ra
    256
    ```

### Docker

- **class Docker(name)**

  Test docker containers running on system.

  Example:

  ```
  >>> nginx = host.docker("app_nginx")
  >>> nginx.is_running
  True
  >>> nginx.id
  '7e67dc7495ca8f451d346b775890bdc0fb561ecdc97b68fb59ff2f77b509a8fe'
  >>> nginx.name
  'app_nginx'
  ```

  - **classmethod client\_version()**

    Docker client version

  - **classmethod server\_version()**

    Docker server version

  - **classmethod version(format=None)**

    Docker version \<https://docs.docker.com/engine/reference/commandline/version/\> with an optional format (Go template).

    ```
    >>> host.docker.version()
    Client: Docker Engine - Community
    ...
    >>> host.docker.version("{{.Client.Context}}"))
    default
    ```

  - **classmethod get\_containers(\*\*filters)**

    Return a list of containers

    By default return list of all containers, including non-running containers.

    Filtering can be done using filters keys defined on \<https://docs.docker.com/engine/reference/commandline/ps/#filtering\>

    Multiple filters for a given key is handled by giving a list of string as value.

    ```
    >>> host.docker.get_containers()
    [<docker nginx>, <docker redis>, <docker app>]
    # Get all running containers
    >>> host.docker.get_containers(status="running")
    [<docker app>]
    # Get containers named "nginx"
    >>> host.docker.get_containers(name="nginx")
    [<docker nginx>]
    # Get containers named "nginx" or "redis"
    >>> host.docker.get_containers(name=["nginx", "redis"])
    [<docker nginx>, <docker redis>]
    ```

### Environment

- **class Environment(name)**

  Get Environment variables

  Example:

  ```
  >>> host.environment()
  {
      "EDITOR": "vim",
      "SHELL": "/bin/bash",
      [...]
  }
  ```

### File

- **class File(path)**

  Test various files attributes

  - **property exists**

    Test if file exists

    ```
    >>> host.file("/etc/passwd").exists
    True
    >>> host.file("/nonexistent").exists
    False
    ```

  - **property is\_file**

    Test if the path is a regular file

  - **property is\_directory**

    Test if the path exists and a directory

  - **property is\_executable**

    Test if the path exists and permission to execute is granted

  - **property is\_pipe**

    Test if the path exists and is a pipe

  - **property is\_socket**

    Test if the path exists and is a socket

  - **property is\_symlink**

    Test if the path exists and is a symbolic link

  - **property linked\_to**

    Resolve symlink

    ```
    >>> host.file("/var/lock").linked_to
    '/run/lock'
    ```

  - **property user**

    Return file owner as string

    ```
    >>> host.file("/etc/passwd").user
    'root'
    ```

  - **property uid**

    Return file user id as integer

    ```
    >>> host.file("/etc/passwd").uid
    0
    ```

  - **property group**

    Return file group name as string

  - **property gid**

    Return file group id as integer

  - **property mode**

    Return file mode as octal integer

    ```
    >>> host.file("/etc/shadow").mode
    416  # Oo640 octal
    >>> host.file("/etc/shadow").mode == 0o640
    True
    >>> oct(host.file("/etc/shadow").mode) == '0o640'
    True
    ```

    You can also utilize the file mode constants from the stat \<https://docs.python.org/3/library/stat.html\> library for testing file mode.

    ```
    >>> import stat
    >>> host.file("/etc/shadow").mode == stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP
    True
    ```

  - **contains(pattern)**

    Checks content of file for pattern

    This uses grep and thus follows the grep regex syntax.

  - **property md5sum**

    Compute the MD5 message digest of the file content

  - **property sha256sum**

    Compute the SHA256 message digest of the file content

  - **property content**

    Return file content as bytes

    ```
    >>> host.file("/tmp/foo").content
    b'caf\xc3\xa9'
    ```

  - **property content\_string**

    Return file content as string

    ```
    >>> host.file("/tmp/foo").content_string
    'café'
    ```

  - **property mtime**

    Return time of last modification as datetime.datetime object

    ```
    >>> host.file("/etc/passwd").mtime
    datetime.datetime(2015, 3, 15, 20, 25, 40)
    ```

  - **property size**

    Return size of file in bytes

  - **listdir()**

    Return list of items under the directory

    ```
    >>> host.file("/tmp").listdir()
    ['foo_file', 'bar_dir']
    ```

### Group

- **class Group(name)**

  Test unix group

  - **property exists**

    Test if group exists

    ```
    >>> host.group("wheel").exists
    True
    >>> host.group("nosuchgroup").exists
    False
    ```

  - **property get\_all\_groups**

    Returns a list of local and remote group names

    ```
    >>> host.group("anyname").get_all_groups
    ["root", "wheel", "man", "tty", <...>]
    ```

  - **property get\_local\_groups**

    Returns a list of local group names

    ```
    >>> host.group("anyname").get_local_groups
    ["root", "wheel", "man", "tty", <...>]
    ```

  - **property gid**

    - **property members**

    Return all users that are members of this group.

### Interface

- **class Interface(name, family=None)**

  Test network interfaces

  ```
  >>> host.interface("eth0").exists
  True
  ```

  Optionally, the protocol family to use can be enforced.

  ```
  >>> host.interface("eth0", "inet6").addresses
  ['fe80::e291:f5ff:fe98:6b8c']
  ```

  - **property exists**

    - **property speed**

    - **property addresses**

    Return ipv4 and ipv6 addresses on the interface

    ```
    >>> host.interface("eth0").addresses
    ['192.168.31.254', '192.168.31.252', 'fe80::e291:f5ff:fe98:6b8c']
    ```

  - **property link**

    Return the link properties associated with the interface.

    ```
    >>> host.interface("lo").link
    {'address': '00:00:00:00:00:00',
    'broadcast': '00:00:00:00:00:00',
    'flags': ['LOOPBACK', 'UP', 'LOWER_UP'],
    'group': 'default',
    'ifindex': 1,
    'ifname': 'lo',
    'link_type': 'loopback',
    'linkmode': 'DEFAULT',
    'mtu': 65536,
    'operstate': 'UNKNOWN',
    'qdisc': 'noqueue',
    'txqlen': 1000}
    ```

  - **routes(scope=None)**

    Return the routes associated with the interface, optionally filtered by scope ("host", "link" or "global").

    ```
    >>> host.interface("eth0").routes()
    [{'dst': 'default',
    'flags': [],
    'gateway': '192.0.2.1',
    'metric': 3003,
    'prefsrc': '192.0.2.5',
    'protocol': 'dhcp'},
    {'dst': '192.0.2.0/24',
    'flags': [],
    'metric': 3003,
    'prefsrc': '192.0.2.5',
    'protocol': 'dhcp',
    'scope': 'link'}]
    ```

  - **classmethod names()**

    Return the names of all the interfaces.

    ```
    >>> host.interface.names()
    ['lo', 'tunl0', 'ip6tnl0', 'eth0']
    ```

  - **classmethod default(family=None)**

    Return the interface used for the default route.

    ```
    >>> host.interface.default()
    <interface eth0>
    ```

    Optionally, the protocol family to use can be enforced.

    ```
    >>> host.interface.default("inet6")
    None
    ```

### Iptables

- **class Iptables**

  Test iptables rule exists

  - **rules(table='filter', chain=None, version=4)**

    Returns list of iptables rules

    Based on output of *iptables -t TABLE -S CHAIN* command

    - **optionally takes takes the following arguments:**

      - •

        table: defaults to *filter*

      - •

        chain: defaults to all chains

      - •

        version: default 4 (iptables), optionally 6 (ip6tables)

    ```
    >>> host.iptables.rules()
    [
        '-P INPUT ACCEPT',
        '-P FORWARD ACCEPT',
        '-P OUTPUT ACCEPT',
        '-A INPUT -i lo -j ACCEPT',
        '-A INPUT -j REJECT'
        '-A FORWARD -j REJECT'
    ]
    >>> host.iptables.rules("nat", "INPUT")
    ['-P PREROUTING ACCEPT']
    ```

### MountPoint

- **class MountPoint(path)**

  Test Mount Points

  - **property exists**

    Return True if the mountpoint exists

    ```
    >>> host.mount_point("/").exists
    True
    ```

    ```
    >>> host.mount_point("/not/a/mountpoint").exists
    False
    ```

  - **property filesystem**

    Returns the filesystem type associated

    ```
    >>> host.mount_point("/").filesystem
    'ext4'
    ```

  - **property device**

    Return the device associated

    ```
    >>> host.mount_point("/").device
    '/dev/sda1'
    ```

  - **property options**

    Return a list of options that a mount point has been created with

    ```
    >>> host.mount_point("/").options
    ['rw', 'relatime', 'data=ordered']
    ```

  - **classmethod get\_mountpoints()**

    Returns a list of MountPoint instances

    ```
    >>> host.mount_point.get_mountpoints()
    [<MountPoint(path=/proc, device=proc, filesystem=proc, options=rw,nosuid,nodev,noexec,relatime)>,
     <MountPoint(path=/, device=/dev/sda1, filesystem=ext4, options=rw,relatime,errors=remount-ro,data=ordered)>]
    ```

### Package

- **class Package(name)**

  Test packages status and version

  - **property is\_installed**

    Test if the package is installed

    ```
    >>> host.package("nginx").is_installed
    True
    ```

    Supported package systems:

    - •

      apk (Alpine)

    - •

      apt (Debian, Ubuntu, ...)

    - •

      brew (macOS)

    - •

      pacman (Arch, Manjaro )

    - •

      pkg (FreeBSD)

    - •

      pkg\_info (NetBSD)

    - •

      pkg\_info (OpenBSD)

    - •

      rpm (RHEL, RockyLinux, Fedora, ...)

  - **property release**

    Return the release specific info from the package version

    ```
    >>> host.package("nginx").release
    '1.el6'
    ```

  - **property version**

    Return package version as returned by the package system

    ```
    >>> host.package("nginx").version
    '1.2.1-2.2+wheezy3'
    ```

### Pip

- **class Pip(name, pip\_path='pip')**

  Test pip package manager and packages

  - **property is\_installed**

    Test if the package is installed

    ```
    >>> host.package("pip").is_installed
    True
    ```

  - **property version**

    Return package version as returned by pip

    ```
    >>> host.package("pip").version
    '18.1'
    ```

  - **classmethod check(pip\_path='pip')**

    Verify installed packages have compatible dependencies.

    ```
    >>> cmd = host.pip.check()
    >>> cmd.rc
    0
    >>> cmd.stdout
    No broken requirements found.
    ```

    Can only be used if pip check \<https://pip.pypa.io/en/stable/reference/pip\_check/\> command is available, for pip versions \>= 9.0.0 \<https://pip.pypa.io/en/stable/news/#id526\>.

  - **classmethod get\_packages(pip\_path='pip')**

    Get all installed packages and versions returned by *pip list*:

    ```
    >>> 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'}}
    ```

  - **classmethod get\_outdated\_packages(pip\_path='pip')**

    Get all outdated packages with current and latest version

    ```
    >>> host.pip.get_outdated_packages(
    ...     pip_path='~/venv/website/bin/pip')
    {'Django': {'current': '1.10.2', 'latest': '1.10.3'}}
    ```

### Podman

- **class Podman(name)**

  Test podman containers running on system.

  Example:

  ```
  >>> nginx = host.podman("app_nginx")
  >>> nginx.is_running
  True
  >>> nginx.id
  '7e67dc7495ca8f451d346b775890bdc0fb561ecdc97b68fb59ff2f77b509a8fe'
  >>> nginx.name
  'app_nginx'
  ```

  - **classmethod get\_containers(\*\*filters)**

    Return a list of containers

    By default return list of all containers, including non-running containers.

    Filtering can be done using filters keys defined in [podman-ps(1)](/podman-ps/1.md).

    Multiple filters for a given key is handled by giving a list of string as value.

    ```
    >>> host.podman.get_containers()
    [<podman nginx>, <podman redis>, <podman app>]
    # Get all running containers
    >>> host.podman.get_containers(status="running")
    [<podman app>]
    # Get containers named "nginx"
    >>> host.podman.get_containers(name="nginx")
    [<podman nginx>]
    # Get containers named "nginx" or "redis"
    >>> host.podman.get_containers(name=["nginx", "redis"])
    [<podman nginx>, <podman redis>]
    ```

### Process

- **class Process**

  Test Processes attributes

  Processes are selected using **filter()** or **get()**, attributes names are described in the [ps(1)](/ps/1.md) man page \<http://man7.org/linux/man-pages/man1/ps.1.html#STANDARD\_FORMATSPECIFIERS\>.

  ```
  >>> 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
  ```

  - **filter(\*\*filters)**

    Get a list of matching process

    ```
    >>> host.process.filter(user="root", comm="zsh")
    [<process zsh (pid=2715)>, <process zsh (pid=10502)>, ...]
    ```

  - **get(\*\*filters)**

    Get one matching process

    Raise **RuntimeError** if no process found or multiple process matching filters.

### PuppetResource

- **class PuppetResource(type, name=None)**

  Get puppet resources

  Run **puppet resource --types** to get a list of available types.

  ```
  >>> host.puppet_resource("user", "www-data")
  {
      'www-data': {
          'ensure': 'present',
          'comment': 'www-data',
          'gid': '33',
          'home': '/var/www',
          'shell': '/usr/sbin/nologin',
          'uid': '33',
      },
  }
  ```

### Facter

- **class Facter(\*facts)**

  Get facts with facter \<https://puppetlabs.com/facter\>

  ```
  >>> host.facter()
  {
      "operatingsystem": "Debian",
      "kernel": "linux",
      [...]
  }
  >>> host.facter("kernelversion", "is_virtual")
  {
    "kernelversion": "3.16.0",
    "is_virtual": "false"
  }
  ```

### Salt

- **class Salt(function, args=None, local=False, config=None)**

  Run salt module functions

  ```
  >>> 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}
  ```

  Run **salt-call sys.doc** to get a complete list of functions

### Service

- **class Service(name)**

  Test services

  Implementations:

  - •

    Linux: detect Systemd, Upstart or OpenRC, fallback to SysV

  - •

    FreeBSD: service(1)

  - •

    OpenBSD: **/etc/rc.d/$name check** for **is\_running** **rcctl ls on** for **is\_enabled** (only OpenBSD \>= 5.8)

  - •

    NetBSD: **/etc/rc.d/$name onestatus** for **is\_running** (**is\_enabled** is not yet implemented)

  - **property exists**

    Test if service is exists

  - **property is\_running**

    Test if service is running

  - **property is\_enabled**

    Test if service is enabled

  - **property is\_valid**

    Test if service is valid

    This method is only available in the systemd implementation, it will raise **NotImplementedError** in others implementation

  - **property is\_masked**

    Test if service is masked

    This method is only available in the systemd implementation, it will raise **NotImplementedError** in others implementations

  - **property systemd\_properties**

    Properties of the service (unit).

    Return service properties as a *dict*, empty properties are not returned.

    ```
    >>> ntp = host.service("ntp")
    >>> ntp.systemd_properties["FragmentPath"]
    '/lib/systemd/system/ntp.service'
    ```

    This method is only available in the systemd implementation, it will raise **NotImplementedError** in others implementations

    Note: based on systemctl show \<https://man7.org/linux/man-pages/man1/systemctl.1.html\>

### Socket

- **class Socket(socketspec)**

  Test listening tcp/udp and unix sockets

  **socketspec** must be specified as **\<protocol\>://\<host\>:\<port\>**

  This module requires the **netstat** command to on the target host.

  Example:

  - •

    Unix sockets: **unix:///var/run/docker.sock**

  - •

    All ipv4 and ipv6 tcp sockets on port 22: **tcp://22**

  - •

    All ipv4 sockets on port 22: **tcp://0.0.0.0:22**

  - •

    All ipv6 sockets on port 22: **tcp://:::22**

  - •

    udp socket on 127.0.0.1 port 69: **udp://127.0.0.1:69**

  - **property is\_listening**

    Test if socket is listening

    ```
    >>> host.socket("unix:///var/run/docker.sock").is_listening
    False
    >>> # This HTTP server listen on all ipv4 addresses but not on ipv6
    >>> host.socket("tcp://0.0.0.0:80").is_listening
    True
    >>> host.socket("tcp://:::80").is_listening
    False
    >>> host.socket("tcp://80").is_listening
    False
    ```

    **Note:**

    If you don't specify a host for udp and tcp sockets, then the socket is listening if and only if the socket listen on **both** all ipv4 and ipv6 addresses (ie 0.0.0.0 and ::)

  - **property clients: list\[tuple\[str, int\] \| None\]**

    Return a list of clients connected to a listening socket

    For tcp and udp sockets a list of pair (address, port) is returned. For unix sockets a list of None is returned (thus you can make a len() for counting clients).

    ```
    >>> host.socket("tcp://22").clients
    [('2001:db8:0:1', 44298), ('192.168.31.254', 34866)]
    >>> host.socket("unix:///var/run/docker.sock")
    [None, None, None]
    ```

  - **classmethod get\_listening\_sockets()**

    Return a list of all listening sockets

    ```
    >>> host.socket.get_listening_sockets()
    ['tcp://0.0.0.0:22', 'tcp://:::22', 'unix:///run/systemd/private', ...]
    ```

### Sudo

- **class Sudo(user=None)**

  Sudo module allow to run certain portion of code under another user.

  It is used as a context manager and can be nested.

  ```
  >>> Command.check_output("whoami")
  'phil'
  >>> with host.sudo():
  ...     host.check_output("whoami")
  ...     with host.sudo("www-data"):
  ...         host.check_output("whoami")
  ...
  'root'
  'www-data'
  ```

### Supervisor

- **class Supervisor(name, supervisorctl\_path='supervisorctl', supervisorctl\_conf=None, \_attrs\_cache=None)**

  Test supervisor managed services

  ```
  >>> gunicorn = host.supervisor("gunicorn")
  >>> gunicorn.status
  'RUNNING'
  >>> gunicorn.is_running
  True
  >>> gunicorn.pid
  4242
  ```

  The path where supervisorctl and its configuration file reside can be specified.

  ```
  >>> gunicorn = host.supervisor("gunicorn", "/usr/bin/supervisorctl", "/etc/supervisor/supervisord.conf")
  >>> gunicorn.status
  'RUNNING'
  ```

  - **property is\_running**

    Return True if managed service is in status RUNNING

  - **property status**

    Return the status of the managed service

    Status can be STOPPED, STARTING, RUNNING, BACKOFF, STOPPING, EXITED, FATAL, UNKNOWN.

    See \<http://supervisord.org/subprocess.html#process-states\>

  - **property pid**

    Return the pid (as int) of the managed service

  - **classmethod get\_services(supervisorctl\_path='supervisorctl', supervisorctl\_conf=None)**

    Get a list of services running under supervisor

    ```
    >>> host.supervisor.get_services()
    [<Supervisor(name="gunicorn", status="RUNNING", pid=4232)>
     <Supervisor(name="celery", status="FATAL", pid=None)>]
    ```

    The path where supervisorctl and its configuration file reside can be specified.

    ```
    >>> host.supervisor.get_services("/usr/bin/supervisorctl", "/etc/supervisor/supervisord.conf")
    [<Supervisor(name="gunicorn", status="RUNNING", pid=4232)>
     <Supervisor(name="celery", status="FATAL", pid=None)>]
    ```

### Sysctl

- **class Sysctl(name)**

  Test kernel parameters

  ```
  >>> host.sysctl("kernel.osrelease")
  "3.16.0-4-amd64"
  >>> host.sysctl("vm.dirty_ratio")
  20
  ```

### SystemInfo

- **class SystemInfo**

  Return system information

  - **property type**

    OS type

    ```
    >>> host.system_info.type
    'linux'
    ```

  - **property distribution**

    Distribution name

    ```
    >>> host.system_info.distribution
    'debian'
    ```

  - **property release**

    Distribution release number

    ```
    >>> host.system_info.release
    '10.2'
    ```

  - **property codename**

    Release code name

    ```
    >>> host.system_info.codename
    'bullseye'
    ```

  - **property arch**

    Host architecture

    ```
    >>> host.system_info.arch
    'x86_64'
    ```

### User

- **class User(name=None)**

  Test unix users

  If name is not supplied, test the current user

  - **property name**

    Return user name

  - **property exists**

    Test if user exists

    ```
    >>> host.user("root").exists
    True
    >>> host.user("nosuchuser").exists
    False
    ```

  - **property uid**

    Return user ID

  - **property gid**

    Return effective group ID

  - **property group**

    Return effective group name

  - **property gids**

    Return the list of user group IDs

  - **property groups**

    Return the list of user group names

  - **property home**

    Return the user home directory

  - **property shell**

    Return the user login shell

  - **property password**

    Return the encrypted user password

  - **property password\_max\_days**

    Return the maximum number of days between password changes

  - **property password\_min\_days**

    Return the minimum number of days between password changes

  - **property gecos**

    Return the user comment/gecos field

  - **property expiration\_date**

    Return the account expiration date

    ```
    >>> host.user("phil").expiration_date
    datetime.datetime(2020, 1, 1, 0, 0)
    >>> host.user("root").expiration_date
    None
    ```

  - **property get\_all\_users**

    Returns a list of local and remote user names

    ```
    >>> host.user().get_all_users
    ["root", "bin", "daemon", "lp", <...>]
    ```

  - **property get\_local\_users**

    Returns a list of local user names

    ```
    >>> host.user().get_local_users
    ["root", "bin", "daemon", "lp", <...>]
    ```

### CommandResult

- **class CommandResult(backend: BaseBackend, exit\_status: int, command: bytes, \_stdout: str \| bytes, \_stderr: str \| bytes)**

  Object that encapsulates all returned details of the command execution.

  Example:

  ```
  >>> 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
  ```

  - **property succeeded: bool**

    Returns whether the command was successful

    ```
    >>> host.run("true").succeeded
    True
    ```

  - **property failed: bool**

    Returns whether the command failed

    ```
    >>> host.run("false").failed
    True
    ```

  - **property rc: int**

    Gets the returncode of a command

    ```
    >>> host.run("true").rc
    0
    ```

  - **property stdout: str**

    Gets standard output (stdout) stream of an executed command

    ```
    >>> host.run("mkdir -v new_directory").stdout
    mkdir: created directory 'new_directory'
    ```

  - **property stderr: str**

    Gets standard error (stderr) stream of an executed command

    ```
    >>> host.run("mkdir new_directory").stderr
    mkdir: cannot create directory 'new_directory': File exists
    ```

  - **property stdout\_bytes: bytes**

    Gets standard output (stdout) stream of an executed command as bytes

    ```
    >>> host.run("mkdir -v new_directory").stdout_bytes
    b"mkdir: created directory 'new_directory'"
    ```

  - **property stderr\_bytes: bytes**

    Gets standard error (stderr) stream of an executed command as bytes

    ```
    >>> host.run("mkdir new_directory").stderr_bytes
    b"mkdir: cannot create directory 'new_directory': File exists"
    ```

### API

### Connection API

You can use testinfra outside of pytest. You can dynamically get a *host* instance and call functions or access members of the respective modules:

```
>>> import testinfra
>>> host = testinfra.get_host("paramiko://root@server:2222", sudo=True)
>>> host.file("/etc/shadow").mode == 0o640
True
```

For instance you could make a test to compare two files on two different servers:

```
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
```

### Examples

### Parametrize your tests

Pytest support test parametrization \<https://pytest.org/latest/parametrize.html\>:

```
# BAD: If the test fails on nginx, python is not tested
def test_packages(host):
    for name, version in (
        ("nginx", "1.6"),
        ("python", "2.7"),
    ):
        pkg = host.package(name)
        assert pkg.is_installed
        assert pkg.version.startswith(version)
# GOOD: Each package is tested
# $ pytest -v test.py
# [...]
# test.py::test_package[local-nginx-1.6] PASSED
# test.py::test_package[local-python-2.7] PASSED
# [...]
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)
```

### Using unittest

Testinfra can be used with the standard Python unit test framework unittest \<https://docs.python.org/3/library/unittest.html\> instead of pytest:

```
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()
```

```
$ python test.py
..
----------------------------------------------------------------------
Ran 2 tests in 0.705s
OK
```

### Integration with Vagrant

Vagrant \<https://www.vagrantup.com/\> is a tool to setup and provision development environments (virtual machines).

When your Vagrant machine is up and running, you can easily run your testinfra test suite on it:

```
vagrant ssh-config > .vagrant/ssh-config
pytest --hosts=default --ssh-config=.vagrant/ssh-config tests.py
```

### Integration with Jenkins

Jenkins \<https://jenkins-ci.org/\> is a well known open source continuous integration server.

If your Jenkins slave can run Vagrant, your build scripts can be like:

```
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
```

Then configure Jenkins to get tests results from the *junit.xml* file.

### Integration with Nagios

Your tests will usually be validating that the services you are deploying run correctly. This kind of tests are close to monitoring checks, so let's push them to Nagios \<https://www.nagios.org/\> !

The Testinfra option *--nagios* enables a behavior compatible with a nagios plugin:

```
$ 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
```

You can run these tests from the nagios master or in the target host with NRPE \<https://en.wikipedia.org/wiki/Nagios#Nagios\_Remote\_Plugin\_Executor\>.

### Integration with KitchenCI

KitchenCI (aka Test Kitchen) can use testinfra via its **shell** verifier. Add the following to your **.kitchen.yml**, this requires installing *paramiko* additionally (on your host machine, not in the VM handled by kitchen)

```
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}"
```

### Test Docker images

Docker is a handy way to test your infrastructure code. This recipe shows how to build and run Docker containers with Testinfra by overloading the *host* fixture.

```
import pytest
import subprocess
import testinfra
# scope='session' uses the same container for all the tests;
# scope='function' uses a new container per test function.
@pytest.fixture(scope='session')
def host(request):
    # build local ./Dockerfile
    subprocess.check_call(['docker', 'build', '-t', 'myimage', '.'])
    # run a container
    docker_id = subprocess.check_output(
        ['docker', 'run', '-d', 'myimage']).decode().strip()
    # return a testinfra connection to the container
    yield testinfra.get_host("docker://" + docker_id)
    # at the end of the test suite, destroy the container
    subprocess.check_call(['docker', 'rm', '-f', docker_id])
def test_myimage(host):
    # 'host' now binds to the container
    assert host.check_output('myapp -v') == 'Myapp 1.0'
```

### Support

If you have questions or need help with testinfra please consider one of the following

### Issue Tracker

Checkout existing issues on project issue tracker \<https://github.com/pytest-dev/pytest-testinfra/issues\>

### IRC

You can also ask questions on IRC in #pytest \<https://web.libera.chat/?channel=#pytest\> channel on \[libera.chat\](\<https://libera.chat/\>) network.

### pytest documentation

testinfra is implemented as pytest plugin so to get the most out of please read pytest documentation \<https://docs.pytest.org/en/latest/\>

### Community Contributions

- •

  Molecule \<https://molecule.readthedocs.io\> is an Automated testing framework for Ansible roles, with native Testinfra support.

## Author

Philippe Pepiot

## Copyright

2025, Philippe Pepiot
