I use testinfra with ansible transport. It provides host
fixture which has ansible
, so I can do host.ansible.get_variables()
.
Now I need to create a parametrization of test based on value from this inventory.
Inventory:
foo:
hosts:
foo1:
somedata:
- data1
- data2
I want to write a test which tests each of 'data' from somedata for each host in inventory. 'Each host' part is handled by testnfra, but I'm struggling with parametrization of the test:
@pytest.fixture
def somedata(host):
return host.ansible.get_variables()["somedata"]
@pytest.fixture(params=somedata):
def data(request):
return request.param
def test_data(host, data):
assert 'data' in data
I've tried both ways:
@pytest.fixture(params=somedata)
->TypeError: 'function' object is not iterable
@pytest.fixture(params=somedata())
->Fixture "somedata" called directly. Fixtures are not meant to be called directly...
How can I do this? I understand that I can't change the number of tests at test time, but I pretty sure I have the same inventory at collection time, so, theoretically, it can be doable...
After reading a lot of source code I have came to conclusion, that it's impossible to call fixtures at collection time. There are no fixtures at collection time, and any parametrization should happen before any tests are called. Moreover, it's impossible to change number of tests at test time (so no fixture could change that).
Answering my own question on using Ansible inventory to parametrize a test function: It's possible, but it requires manually reading inventory, hosts, etc. There is a special hook for that:
pytest_generate_tests
(it's a function, not a fixture).My current code to get any test parametrized by
host_interface
fixture is: