In-house, server tests seem to be done manually, so I would like to introduce an automation mechanism to improve efficiency. At my previous workplace, I tried to use Ruby's Serverspec and Infrataster as server test tools, but I wanted to unify them with Python's configuration management tools such as Ansible and Fabric. I found a test tool called Testinfra. Even on the official website, Testinfra was written as a tool like Ruby's Serverspec, so I tried using it. This time, I described the procedure of the introduction part from environment construction to operation test.
It is assumed that the following environment has been created
$ pip install testinfra
$ cd $HOME/.ssh $ ssh-keygen -t rsa -f test_server
$ scp test_server.pub [email protected]:/var/tmp/
$ ssh -i $HOME/.ssh/test_server [email protected]
$ vi $HOME/.ssh/ssh_config
Here, the host name of the remote server is "redmine"
Host redmine HostName 192.168.1.31 Port 22 User permit IdentityFile ~/.ssh/test_server
$ useradd -m permit -G wheel $ passwd permit
$ mkdir $HOME/.ssh $ mv /var/tmp/test_server.pub $HOME/.ssh/ $ cd $HOME/.ssh/ $ cat test_server.pub >> authorized_keys $ chmod 600 authorized_keys $ rm test_server.pub
$ vi test.py
Test code example
def test_passwd_file(File):
passwd = File("/etc/passwd")
assert passwd.contains("root")
assert passwd.user == "root"
assert passwd.group == "root"
assert passwd.mode == 0o644
$ testinfra -v test.py
=================================== test session starts ====================================
platform linux2 -- Python 2.7.9, pytest-3.0.1, py-1.4.31, pluggy-0.3.1 -- /usr/local/bin/python2.7
cachedir: .cache
rootdir: /root, inifile:
plugins: testinfra-1.4.2, pep8-1.0.6
collected 1 items
test.py::test_passwd_file[local] PASSED
================================== pytest-warning summary ==================================
WP1 None Modules are already imported so can not be re-written: testinfra
======================= 1 passed, 1 pytest-warnings in 0.03 seconds ========================
$ testinfra test.py --connection=ssh --hosts=permit@redmine --ssh-config=/root/.ssh/ssh_config
=================================== test session starts ====================================
platform linux2 -- Python 2.7.9, pytest-3.0.1, py-1.4.31, pluggy-0.3.1 -- /usr/local/bin/python2.7
cachedir: .cache
rootdir: /root, inifile:
plugins: testinfra-1.4.2, pep8-1.0.6
collected 1 items
test.py::test_passwd_file[ssh://redmine] PASSED
================================== pytest-warning summary ==================================
WP1 None Modules are already imported so can not be re-written: testinfra
======================= 1 passed, 1 pytest-warnings in 0.66 seconds ========================