Skip to content

Commit

Permalink
Fix TypeError (#21734)
Browse files Browse the repository at this point in the history
* timediff is of type timedelta. Divide by timedelta does not work.

- convert a timedelta to int
- make sure the test inputs real timestamps

* Convert the total_seconds to decimal and round the result

readings are of type Decimal, so fix test to reflect that

* split line into multiple statements

Line too long

* use total_seconds instead of timediff

* Make both values float instead of Decimal
  • Loading branch information
wburgers authored and amelchio committed Mar 9, 2019
1 parent be989eb commit 458548d
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 6 deletions.
3 changes: 2 additions & 1 deletion homeassistant/components/sensor/dsmr.py
Expand Up @@ -351,7 +351,8 @@ async def async_update(self):
# Recalculate the rate
diff = current_reading - self._previous_reading
timediff = timestamp - self._previous_timestamp
self._state = diff / timediff * 3600
total_seconds = timediff.total_seconds()
self._state = round(float(diff) / total_seconds * 3600, 3)

self._previous_reading = current_reading
self._previous_timestamp = timestamp
Expand Down
11 changes: 6 additions & 5 deletions tests/components/sensor/test_dsmr.py
Expand Up @@ -6,6 +6,7 @@
"""

import asyncio
import datetime
from decimal import Decimal
from unittest.mock import Mock

Expand Down Expand Up @@ -104,8 +105,8 @@ def test_derivative():

entity.telegram = {
'1.0.0': MBusObject([
{'value': 1551642213},
{'value': 745.695, 'unit': 'm3'},
{'value': datetime.datetime.fromtimestamp(1551642213)},
{'value': Decimal(745.695), 'unit': 'm3'},
])
}
yield from entity.async_update()
Expand All @@ -115,13 +116,13 @@ def test_derivative():

entity.telegram = {
'1.0.0': MBusObject([
{'value': 1551642543},
{'value': 745.698, 'unit': 'm3'},
{'value': datetime.datetime.fromtimestamp(1551642543)},
{'value': Decimal(745.698), 'unit': 'm3'},
])
}
yield from entity.async_update()

assert abs(entity.state - 0.03272) < 0.00001, \
assert abs(entity.state - 0.033) < 0.00001, \
'state should be hourly usage calculated from first and second update'

assert entity.unit_of_measurement == 'm3/h'
Expand Down

0 comments on commit 458548d

Please sign in to comment.