How Do You Use Testinfra (the Python module)?

Problem scenario
You prefer Python to Ruby for certain tasks, and you want to have a way of testing your configuration management tools. You want to use Testinfra to accomplish this (https://testinfra.readthedocs.io/en/latest/). You want to install Testinfra to test it out. What do you do?

Solution
Prerequisites
i. You must have pip3 installed on the server.
For Ubuntu/Debian systems, you would run this: sudo yum install -y python3-pip
For CentOS/RHEL/Fedora systems, you would run this: sudo apt-get install -y python3-pip

ii. This assumes that you have installed Nginx and have it running. With Ubuntu/Debian systems, you
would run this:

sudo apt -y install nginx && sudo systemctl start nginx

For CentOS/RHEL/Fedora systems, you would run this:

sudo yum install -y nginx && sudo systemctl enable nginx && sudo systemctl start nginx

Procedures
1. Run this command: sudo pip3 install testinfra

2. Create this file test_nginx.py
It should have these lines in it:

def test_nginx_is_installed(host):
     nginx = host.package("nginx")
     assert nginx.is_installed
     assert nginx.version.startswith("1.14")
 def test_nginx_running_and_enabled(host):
     nginx = host.service("nginx")
     assert nginx.is_running
     assert nginx.is_enabled 

3. Run this command from the directory where the above file is: pytest

4. The file above test if nginx 1.14 has been installed. If you want to generate a failure, run this: sudo systemctl stop nginx

Leave a comment

Your email address will not be published. Required fields are marked *