Fix rangefilter ()

* Fix rangefilter

RangeFilter would break for lower or upper bounds of 0, evaluating to False and thus not being handled correctly as bounds

* Add test for zero bounds
pull/17483/head
Niels Mündler 2018-10-15 12:24:21 +02:00 committed by Pascal Vizeli
parent 373e3b12d8
commit d6752d2270
2 changed files with 22 additions and 3 deletions
homeassistant/components/sensor
tests/components/sensor

View File

@ -347,7 +347,7 @@ class RangeFilter(Filter):
"""
def __init__(self, entity,
lower_bound, upper_bound):
lower_bound=None, upper_bound=None):
"""Initialize Filter."""
super().__init__(FILTER_NAME_RANGE, entity=entity)
self._lower_bound = lower_bound
@ -356,7 +356,8 @@ class RangeFilter(Filter):
def _filter_state(self, new_state):
"""Implement the range filter."""
if self._upper_bound and new_state.state > self._upper_bound:
if (self._upper_bound is not None
and new_state.state > self._upper_bound):
self._stats_internal['erasures_up'] += 1
@ -365,7 +366,8 @@ class RangeFilter(Filter):
self._entity, new_state)
new_state.state = self._upper_bound
elif self._lower_bound and new_state.state < self._lower_bound:
elif (self._lower_bound is not None
and new_state.state < self._lower_bound):
self._stats_internal['erasures_low'] += 1

View File

@ -149,6 +149,23 @@ class TestFilterSensor(unittest.TestCase):
else:
self.assertEqual(unf, filtered.state)
def test_range_zero(self):
"""Test if range filter works with zeroes as bounds."""
lower = 0
upper = 0
filt = RangeFilter(entity=None,
lower_bound=lower,
upper_bound=upper)
for unf_state in self.values:
unf = float(unf_state.state)
filtered = filt.filter_state(unf_state)
if unf < lower:
self.assertEqual(lower, filtered.state)
elif unf > upper:
self.assertEqual(upper, filtered.state)
else:
self.assertEqual(unf, filtered.state)
def test_throttle(self):
"""Test if lowpass filter works."""
filt = ThrottleFilter(window_size=3,