diff --git a/docs/content/changelog.rst b/docs/content/changelog.rst index a6957f6..ce3157b 100644 --- a/docs/content/changelog.rst +++ b/docs/content/changelog.rst @@ -1,3 +1,6 @@ +- v3.2.0: Allow ``Dyn`` filters to modify the event. +- v3.1.6: Fix type hints with ``Depends``. +- v3.1.5: Add py.typed file to support type hints. - v3.1.4: Simplify calling processors by making ``EventProcessor`` callable. - v3.1.3: Fix a bug with invocation when an event matches several filters. - v3.1.2: Fix an incorrect import. diff --git a/docs/content/filters.rst b/docs/content/filters.rst index 43f554e..fe69f68 100644 --- a/docs/content/filters.rst +++ b/docs/content/filters.rst @@ -223,7 +223,8 @@ be valid for a dependency (see :ref:`Dependencies` for details). For example : False Since the Dyn filter is basically a way to do anything you can't do with static filters, it also allows modifying the -event before it gets passed to a processor function. For example : +event before it gets passed to a processor function. Note that the event is only modified if the value returned by the +dynamic function is truthy (i.e. event is unmodified if the filter doesn't match). For example : .. testcode:: diff --git a/src/event_processor/filters.py b/src/event_processor/filters.py index f204dc4..6963502 100644 --- a/src/event_processor/filters.py +++ b/src/event_processor/filters.py @@ -221,10 +221,11 @@ def matches(self, event: dict) -> bool: else: result = call_with_injection(self.resolver, event=Event(event), cache={}) - if self.inject_as: + matches = bool(result) + if self.inject_as and matches: event[self.inject_as] = result - return bool(result) + return matches def __hash__(self): return hash(self.resolver) diff --git a/src/tests/test_filters.py b/src/tests/test_filters.py index 3f168ae..df03648 100644 --- a/src/tests/test_filters.py +++ b/src/tests/test_filters.py @@ -476,7 +476,7 @@ def dyn_filter(): assert hash(filter_) == hash(dyn_filter) -def test_dyn_filter_updates_event_when_inject_as_is_specified(): +def test_dyn_filter_updates_event_when_inject_as_is_specified_and_filter_matches(): mock_event = {} filter_ = Dyn(lambda e: "my-value", inject_as="my-key") @@ -485,6 +485,15 @@ def test_dyn_filter_updates_event_when_inject_as_is_specified(): assert mock_event["my-key"] == "my-value" +def test_dyn_filter_does_not_update_event_when_inject_as_is_specified_and_filter_does_not_match(): + mock_event = {} + filter_ = Dyn(lambda e: False, inject_as="my-key") + + filter_.matches(mock_event) + + assert "my-key" not in mock_event + + def test_eq_filter_matches_when_resolvers_are_equal(): mock_resolver = Mock()