Testinfra を使って見る

Ruby の Infrataster ではなく Testinfra

Testinfra aims to be a Serverspec equivalent in python and is written as a plugin to the powerful Pytest test engine

https://github.com/philpep/testinfra

ってある通り Python 版 Serverspec。
テストランナーに PyTest を使っている。

# -*- coding: utf-8 -*-
import re

class TestNginx(object):
    def test_nginx_should_installed(self, Package):
        """ nginx should be installed. """
        nginx = Package('nginx')
        assert nginx.is_installed        
        assert nginx.version.startswith('1.6.1')
          
    def test_nginx_should_running(self, Command):
        nginx = Command('/etc/init.d/nginx status')
        assert re.match(r'^nginx*', nginx.stdout)

    def test_nginx_conf_should_exists(self, File):
        f = File('/etc/nginx/nginx.conf')
        assert f.exists                  

    def test_nginx_confd_should_exists(self, File):
        f = File('/etc/nginx/conf.d')    
        assert f.is_directory

ドキュメントのサンプルは PyTest の関数で書かれていたけど、クラスでも書ける。

$ testinfra -vs test_nginx.py --connection=ssh --ssh-config=~/.ssh/config --hosts="host_name_is_here"

こんな感じに書くと、対象のサーバーに PyTest がテストを実行してくれる。


なお現状バックエンドに MacOSX は対応しておらず動かない。
また

def test_nginx_running_and_enabled(Service):
    nginx = Service("nginx")
    assert nginx.is_enabled

が、service コマンドが見つからないと怒られた。