Custom filters and functions¶
Both functions & filters are a piece of python code, which catcher can run from the template. The algorithm is simple:
You create a python file with functions you’d like to run from your tests
You point catcher to this file (or files)
You use it in your templates
Profit.
You can use built-in functions and filters implementation catcher.modules.filter_impl.bifs()
as an example.
Functions¶
Imagine you have a file /home/user/tests/my_functions.py with content:
def function_my_custom():
return {'key': 'value'}
def some_other_function(arg):
return 'converted_to_string: ' + str(arg)
In this case function_my_custom will be imported and you will be able to use my_custom as a function in tests:
---
steps:
- kafka:
produce:
server: '{{ my_kafka }}'
topic: 'my_topic'
data: '{{ my_custom() }}'
Filters¶
Just add this code to my_functions, so it should look like this:
def function_my_custom():
return {'key': 'value'}
def filter_increment(input):
if isinstance(input, int):
return input + 1
return 'not an int'
def some_other_function(arg):
return 'converted_to_string: ' + str(arg)
In this case you have both my_custom function and increment filter available for catcher. Let’s try the filter:
---
steps:
- postgres:
request:
conf: '{{ postgres }}'
sql: 'select count(*) from test'
register: {documents: '{{ OUTPUT.count }}'}
- kafka:
produce:
server: '{{ my_kafka }}'
topic: 'my_topic'
data: '{{ documents | increment }}'
You can also have filter with parameters:
def filter_encode(input, arg='base64'):
if arg == 'base64':
import base64
return base64.b64encode(input.encode()).decode()
return str(input)
And call it in test with or without param:
---
steps:
- mongo:
request:
conf: '{{ mongo }}'
collection: 'test'
insert_one:
'user': '{{ username }}'
'password_urlencoded': '{{ password | encode('base64') }}'
'password_clean': '{{ password | encode }}'