From b66defed25b13528d6c60050290528033ec01dad Mon Sep 17 00:00:00 2001 From: b3b Date: Wed, 15 Dec 2021 21:18:31 +0300 Subject: [PATCH] add a prohibition to combine scan filters of the same type #25 --- able/filters.py | 12 ++++++++++++ tests/test_filters.py | 8 ++++++++ 2 files changed, 20 insertions(+) diff --git a/able/filters.py b/able/filters.py index 6eeee94..383c23a 100644 --- a/able/filters.py +++ b/able/filters.py @@ -16,11 +16,23 @@ @dataclass class Filter: + """Base class for BLE scanning fiters. + + >>> # Filters of different kinds could be ANDed to set multiple conditions. + >>> # Both device name and address required: + >>> combined_filter = DeviceNameFilter("Example") & DeviceAddressFilter("01:02:03:AB:CD:EF") + + >>> DeviceNameFilter("Example1") & DeviceNameFilter("Example2") + Traceback (most recent call last): + ValueError: cannot combine filters of the same type + """ def __post_init__(self): self.filters = [self] def __and__(self, other): + if type(self) in (type(f) for f in other.filters): + raise ValueError('cannot combine filters of the same type') self.filters.extend(other.filters) return self diff --git a/tests/test_filters.py b/tests/test_filters.py index c027da8..bd2f446 100644 --- a/tests/test_filters.py +++ b/tests/test_filters.py @@ -40,3 +40,11 @@ def test_filters_combined(java_builder): ("setManufacturerData", ("test-id", [1, 2, 3])), ("build", ) ] + + +def test_combine_same_type_exception(java_builder): + with pytest.raises(ValueError, match="cannot combine filters of the same type"): + f = filters.DeviceNameFilter("test") & ( + filters.DeviceAddressFilter("AA:AA:AA:AA:AA:AA") & + filters.DeviceNameFilter("test2") + )