techraf techraf - 4 months ago 12
Python Question

How to get target OS type in Testinfra when running a test remotely?

Within Testinfra, how can I create a test condition for the target operating system (if at all)?

I'd like to run the test on

target
host through:

$ testinfra -v --host=target test.py


I tried:

def test_passwd_file(File):
passwd = File("/etc/passwd")
if SystemInfo.type == "darwin"
assert passwd.group == "wheel"


I tried:

if SystemInfo.type == "darwin"
def test_passwd_file(File):
passwd = File("/etc/passwd")
assert passwd.group == "wheel"


But these were basically shots in the dark, due to lack of examples and documentation, and did not work.

Answer

I had kinda the same problem, but solved it like this when I took a better look at this part: http://testinfra.readthedocs.io/en/latest/examples.html#test-docker-images

I have in my test file: import testinfra

os = testinfra.get_backend(
  "local://"
).get_module("SystemInfo").distribution

def test_zabbix_package(Package):
    zabbixagent = Package('zabbix-agent')
    assert zabbixagent.is_installed

    if os == 'centos':
        assert zabbixagent.version.startswith("3.0")
    elif os == 'debian':
        assert zabbixagent.version.startswith("1:3.0")

First import the 'testinfra' module. Create the os variable by executing the testinfra_get_backend module. In my case I had to run the SystemInfo module with the distribution function.

In the test I can make use of the os variable and use it in a if statement.

For your problem, I would like to suggest it like this: import testinfra

os = testinfra.get_backend(
  "local://"
).get_module("SystemInfo").type

def test_passwd_file(File):
    passwd = File("/etc/passwd")
    if os == "darwin":
        assert passwd.group == "wheel"

Edit: I've re-editted my Answer, As SO wants this.

I have the following working now for my role for Zabbix Agent:

def test_zabbix_package(Package, SystemInfo):
    zabbixagent = Package('zabbix-agent')
    assert zabbixagent.is_installed

    if SystemInfo.distribution == 'debian':
        assert zabbixagent.version.startswith("1:3.0")
    if SystemInfo.distribution == 'centos':
        assert zabbixagent.version.startswith("3.0")

This works on both the Debian and CentOS container.

def test_passwd_file(File, SystemInfo):
    passwd = File("/etc/passwd")
    if SystemInfo.type == "darwin":
        assert passwd.group == "wheel"

Good luck!