From c5e77ac785da53f610549e850f437e6d3e0c0599 Mon Sep 17 00:00:00 2001 From: Tim Orme Date: Sun, 23 Apr 2023 17:05:25 -0700 Subject: [PATCH] Fix rounding --- aqimon/database.py | 4 +++- tests/test_database.py | 15 +++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/aqimon/database.py b/aqimon/database.py index 6489238..55b46e9 100644 --- a/aqimon/database.py +++ b/aqimon/database.py @@ -122,7 +122,9 @@ async def get_averaged_reads(dbconn: databases.Database, lookback_to: datetime) lookback = int(lookback_to.timestamp()) result = await dbconn.fetch_one( "SELECT " - "AVG(pm25) as avg_pm25, AVG(pm10) as avg_pm10, COUNT(*) as count, MIN(event_time) as oldest_time " + "ROUND(AVG(pm25), 2) as avg_pm25, ROUND(AVG(pm10), 2) as avg_pm10, " + "COUNT(*) as count, " + "MIN(event_time) as oldest_time " "FROM read_log " "WHERE (event_time >= :lookback) OR " "(event_time = (SELECT MAX(event_time) FROM read_log WHERE event_time <= :lookback)) ORDER BY event_time ASC", diff --git a/tests/test_database.py b/tests/test_database.py index eef7713..354b2bf 100644 --- a/tests/test_database.py +++ b/tests/test_database.py @@ -207,6 +207,21 @@ async def test_get_averaged_reads(database_conn): assert result.oldest_read_time == current_time - timedelta(hours=8) +@pytest.mark.asyncio +async def test_get_averaged_reads_rounding(database_conn): + # Add reads every two hours + current_time = datetime(2020, 1, 1, 12, 0, 0) + lookback_to = current_time - timedelta(hours=8) + await database.add_read(database_conn, current_time - timedelta(hours=2), pm10=2, pm25=2) + await database.add_read(database_conn, current_time - timedelta(hours=4), pm10=4, pm25=3) + await database.add_read(database_conn, current_time - timedelta(hours=6), pm10=4, pm25=3) + + result = await database.get_averaged_reads(database_conn, lookback_to) + assert result.count == 3 + assert result.avg_pm10 == 3.33 + assert result.avg_pm25 == 2.67 + + @pytest.mark.asyncio async def test_get_averaged_reads_looks_past(database_conn): current_time = datetime(2020, 1, 1, 12, 0, 0)