Testinfra使ってみた

in  Infra

前回、ServerSpecを使ってインフラのテストを書いてみましたが、 同じ思想でpythonベースのプロダクトを教えてもらったので試してみました。

1
Testinfra aims to be a Serverspec equivalent in python

インストール

pipが入っていれば簡単にインストールできちゃいます。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
$ sudo pip install testinfra
Collecting testinfra
  Downloading testinfra-1.5.4-py2.py3-none-any.whl (60kB)
    100% |████████████████████████████████| 61kB 1.9MB/s
Requirement already satisfied (use --upgrade to upgrade): six>=1.4 in /usr/lib64/python2.7/site-packages (from testinfra)
Collecting pytest!=3.0.2 (from testinfra)
  Downloading pytest-3.0.7-py2.py3-none-any.whl (172kB)
    100% |████████████████████████████████| 176kB 1.7MB/s
Requirement already satisfied (use --upgrade to upgrade): py>=1.4.29 in /usr/lib64/python2.7/site-packages (from pytest!=3.0.2->testinfra)
Requirement already satisfied (use --upgrade to upgrade): setuptools in /usr/lib64/python2.7/site-packages (from pytest!=3.0.2->testinfra)
Installing collected packages: pytest, testinfra
Successfully installed pytest-3.0.7 testinfra-1.5.4

テストの実行

テストを書きます。 assertで書けるのはxunitの方が慣れている身としては書きやすいですね。

1
2
3
4
def test_apache_running_and_enabled(Service):
    apache = Service("apache2")
    assert apache.is_running
#    assert apache.is_enabled

実行してみます。 Ansibleのダイナミックインベントリをそのまま使えるのは便利ですね。 下記のようにNameタグの値でテスト対象を指定しています。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
$ testinfra -v --connection=ansible --ansible-inventory=./ec2.py --hosts=tag_Name_gside_gentoo test.py
============================================================================== test session starts ===============================================================================
platform linux2 -- Python 2.7.12, pytest-3.0.7, py-1.4.30, pluggy-0.4.0 -- /usr/bin/python2.7
cachedir: .cache
rootdir: /home/hoge/Dropbox/ansible_private, inifile:
plugins: testinfra-1.5.4
collected 1 items

test.py::test_apache_running_and_enabled[ansible://13.112.48.230] PASSED

============================================================================= pytest-warning summary =============================================================================
WP1 None Module already imported so can not be re-written: testinfra
================================================================== 1 passed, 1 pytest-warnings in 7.90 seconds ===================================================================

ランレベルに登録されているかのテストは、今回テスト対象だったGentooには対応していないようでした。 そこはServerSpecはきっちり対応してるのがすごい所ですね。

まとめ

assertで書ける、ansibleの接続設定がそのまま使えるところは非常に使いよいです。


Share