Skip to content

Commit

Permalink
Filtrate with regex (#9)
Browse files Browse the repository at this point in the history
Create new feature to allow regex in filtrate decorator.
  • Loading branch information
Otoru authored Jul 2, 2020
1 parent 43763b2 commit d5132a2
Show file tree
Hide file tree
Showing 9 changed files with 149 additions and 8 deletions.
44 changes: 44 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# https://editorconfig.org/

root = true

[*]
indent_style = space
indent_size = 4
insert_final_newline = true
trim_trailing_whitespace = true
end_of_line = lf
charset = utf-8

# Docstrings and comments use max_line_length = 79
[*.py]
max_line_length = 119

# Use 2 spaces for the HTML files
[*.html]
indent_size = 2

# The JSON files contain newlines inconsistently
[*.json]
indent_size = 2
insert_final_newline = ignore

[**/admin/js/vendor/**]
indent_style = ignore
indent_size = ignore

# Minified JavaScript files shouldn't be changed
[**.min.js]
indent_style = ignore
insert_final_newline = ignore

# Makefiles always use tabs for indentation
[Makefile]
indent_style = tab

# Batch files use tabs for indentation
[*.bat]
indent_style = tab

[docs/**.txt]
max_line_length = 79
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
Copyright 2018 Vitor Hugo de Oliveira Vargas
# Copyright 2018 Vitor Hugo de Oliveira Vargas

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

Expand Down
1 change: 1 addition & 0 deletions Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ twine = "*"
travis = "*"
flake8 = "*"
black = "*"
pytest = "*"

[packages]
greenswitch = "*"
Expand Down
1 change: 1 addition & 0 deletions examples/record_registers_in_redis.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
app = Jaspion(**freeswitch)
conn = Redis(**redis)


# Save all register in redis with expires of sip message.
@app.handle("sofia::register")
def register(event):
Expand Down
2 changes: 1 addition & 1 deletion jaspion/sketch.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from collections.abc import MutableMapping
from collections.abc import MutableSequence
from collections.abc import MutableMapping
from collections.abc import Callable
import functools
import reprlib
Expand Down
16 changes: 11 additions & 5 deletions jaspion/utils.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,33 @@
import functools
import typing
import re


def filtrate(key: str, value: str = None):
"""Method that allows to filter the events according
to a set 'key', 'value'.
def filtrate(key: str, value: str = None, regex: bool = False):
"""
Method that allows to filter the events accordingto a set 'key', 'value'.
Parameters
----------
- key: required
Key to be searched in the event.
- value: optional
Value needed in the last key.
- regex: optional
Tells whether 'value' is a regular expression.
"""

def decorator(function: typing.Callable):
@functools.wraps(function)
def wrapper(message):
if isinstance(message, dict):
if key in message:
if key is None:
content = message[key]
if value is None:
return function(message)
if not regex and content == value:
return function(message)
if message[key] == value:
if regex and re.match(value, content):
return function(message)

return wrapper
Expand Down
3 changes: 3 additions & 0 deletions pytest.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[pytest]
log_cli=True
console_output_style = count
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

setup(
name="Jaspion",
version="0.3.5.5",
version="0.3.6.0",
description="FreeSwitch Event Handler based in Flask.",
include_package_data=True,
license="MIT",
Expand Down
86 changes: 86 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
from jaspion.utils import filtrate

import pytest


class Callback:
"""
Class used to represent a callback.
"""
def __init__(self):
self.control = False

def __call__(self, *args, **kwargs):
self.control = True


def test_filtrate_is_a_callable():
"""Verify if 'filtrate' is a callable."""
assert callable(filtrate)


def test_filtrate_require_a_single_argument():
"""Verify if 'filtrate' is a callable."""
msg = "filtrate() missing 1 required positional argument: 'key'"
with pytest.raises(TypeError) as exc:
filtrate() # pylint: disable=no-value-for-parameter
assert msg in str(exc)


def test_filtrate_return_a_callable():
"""Ensures that the filtrate returns a callable when invoked correctly."""
result = filtrate('key')
assert callable(result)


tests = [
{'decorator': ['key'], 'response': True, 'event': {'key': 'value'}},
{
'decorator': ['key'],
'response': False,
'event': {
'invalid_key': 'value'
}
},
{
'decorator': ['key', 'value'],
'response': True,
'event': {
'key': 'value'
}
},
{
'decorator': ['key', 'value'],
'response': False,
'event': {
'key': 'another_value'
}
},
{
'decorator': ['key', '^[a-z]{5}$', True],
'response': True,
'event': {
'key': 'value'
}
},
{
'decorator': ['key', '^[a-z]{3}$', True],
'response': False,
'event': {
'key': 'value'
}
}
]


@pytest.mark.parametrize('content', tests)
def test_decorator_behavior(content):
"""Validates decorator behavior."""
handler = Callback()
decorator = filtrate(*content['decorator'])
new_handler = decorator(handler)
event = content['event']

new_handler(event)

assert content['response'] == handler.control

0 comments on commit d5132a2

Please sign in to comment.