I have written an Ansible role with a filter function class, located in my_role/filter_plugins/MyFilterClass.py
. I'd like to write a unit test for the Python class (just testing the Python code, not testing the whole role with Molecule). I'm struggling with the test setup. I found the following solution, but I'm not sure if what I'm doing is considered to be best practice:
I have placed my unit test in my_role/test/MyFilterClassTest.py
. I've added the following code (from this answer) to the top of the file to be able to import my class:
import os
import sys
import pathlib
import unittest
PACKAGE_PARENT = pathlib.Path(__file__).parent.parent
SCRIPT_DIR = PACKAGE_PARENT / "filter_plugin"
sys.path.append(str(SCRIPT_DIR))
from MyFilterClass import FilterModule
# Unit test goes here ...
Is there a better way to do this, maybe using a different folder structure/naming convention and ansible-test
?