documentation: passing dynamic role variables to tests when runnning molecule verify
See original GitHub issueI know this could be batted away as something that is related to testinfra only, however, I am finding that I would like to ask here - would you accept a documentation PR that outlines a strategy for including role variables that you passed to your converge playbook, into your unit tests?
Here’s what I am currently doing:
# molecule/default/playbook.yml
---
- name: Converge
hosts: all
vars_files:
- testvars.yml
roles:
- role: my-role
foobar: "{{ test_foobar }}"
Then in a molecule/default/testvars.yml
, I have:
---
test_foobar: barfoo
Then, in my molecule/default/tests/conftest.py
, I do the following:
import os
import pytest
from testinfra.utils.ansible_runner import AnsibleRunner
DEFAULT_HOST = 'all'
inventory = os.environ['MOLECULE_INVENTORY_FILE']
runner = AnsibleRunner(inventory)
runner.get_hosts(DEFAULT_HOST)
@pytest.fixture
def testvars(host):
variables = runner.run(
DEFAULT_HOST,
'include_vars',
'testvars.yml'
)
return variables['ansible_facts']
And in my tests, I can then:
def test_something(host, testvars):
print(testvars['test_foobar'])
As far as I can see, this is the cleanest way (I’ve digged around in a lot of tickets) of matching up the dynamic variables that you pass to your role and your testinfra pytest tests.
If it isn’t, please someone tell me 😃
In any case, the main question remains - is there a place we can start to document this on the RTD setup?
Issue Analytics
- State:
- Created 5 years ago
- Reactions:6
- Comments:38 (17 by maintainers)
Top GitHub Comments
OK thanks for the explaination. I was able to adapt your code to an usage with molecule. I just added the following code to my tests (it works like yours):
Of course it could be very useful if this was integrated natively in
Testinfra
, but it could be not so easy because of the many use cases that users could encounter.Also looking forward this capability 😃