Unit testing python code ?

Hi,

I´ve written a simple RegEx filter (filter_plugins/filter.py) which is used by some of our playbooks:

`
import re

def matchattr(objList, attrib, pattern):
listFiltered =

for item in objList:

if re.match(pattern, item[attrib]) is not None:
listFiltered.append(item)

return listFiltered

class FilterModule(object):
def filters(self):
return {
‘matchattr’: matchattr,
}

`

I´ve looked into http://docs.ansible.com/test_strategies.html - but couldn´t find a hint on how to “unit test” those small pieces of code ?
Is there any “testing module” or some default directory layout or naming conventions which needs to be applied ?

Or recommended Python (testing) Frameworks ?

I´m just looking for something comparable to the way how (Java/C++) code is being tested before using it.

Thanx, Torsten

You have a few options.

  1. Unit Tests

As far as unit tests, you can use the unitest python module, similarly to how it is used in https://github.com/ansible/ansible/blob/devel/test/units/TestFilters.py

  1. Integration tests

For integration tests, that is literally creating a playbook with some tasks like:

  • set_fact:
    filtered_var: “{{ original_var|filter }}”

  • assert:
    that:

  • filtered_var == expected_var