# Unit testing python code ?

**URL:** <https://forum.ansible.com/t/unit-testing-python-code/17696>\
**Category:** Ansible Project\
**Created:** [March 9, 2015, 11:08am UTC](https://forum.ansible.com/t/unit-testing-python-code/17696 "2015-03-09T11:08:30Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Torsten\_Reinhard](https://avatars.discourse-cdn.com/v4/letter/t/46a35a/32.png) [@Torsten\_Reinhard](https://forum.ansible.com/u/Torsten_Reinhard)\
**Post date:** [March 9, 2015, 11:08am UTC](https://forum.ansible.com/t/unit-testing-python-code/17696/1 "2015-03-09T11:08:30Z")

</div>

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](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

---

<div class="post-metadata">

**Author:** ![sivel](https://sea1.discourse-cdn.com/ansible/user_avatar/forum.ansible.com/sivel/32/1198_2.png) [@sivel](https://forum.ansible.com/u/sivel)\
**Post date:** [March 9, 2015, 2:15pm UTC](https://forum.ansible.com/t/unit-testing-python-code/17696/2 "2015-03-09T14:15:03Z")

</div>

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](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
