From 2ed3e3f77f19b7092b1e1f1f0acb670816e91e37 Mon Sep 17 00:00:00 2001 From: Cayo Puigdefabregas Date: Wed, 25 Nov 2020 17:46:58 +0100 Subject: [PATCH] fixing LookupError of metrics --- ereuse_devicehub/resources/metric/views.py | 9 +++++++-- tests/test_metrics.py | 23 ++++++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/ereuse_devicehub/resources/metric/views.py b/ereuse_devicehub/resources/metric/views.py index a37aeb1e..0b16c8a8 100644 --- a/ereuse_devicehub/resources/metric/views.py +++ b/ereuse_devicehub/resources/metric/views.py @@ -7,6 +7,11 @@ from ereuse_devicehub.resources.device import models as m from ereuse_devicehub.resources.metric.schema import Metric +def last_action(dev, action): + act = [e for e in reversed(dev.actions) if isinstance(e, action)] + return act[0] if act else None + + class MetricsView(View): def find(self, args: dict): @@ -27,8 +32,8 @@ class MetricsView(View): devices = m.Device.query.filter(m.Device.allocated==True) count = 0 for dev in devices: - live = dev.last_action_of(Live) - allocate = dev.last_action_of(Allocate) + live = last_action(dev, Live) + allocate = last_action(dev, Allocate) if not live: continue if allocate and allocate.created > live.created: diff --git a/tests/test_metrics.py b/tests/test_metrics.py index 49874582..99020641 100644 --- a/tests/test_metrics.py +++ b/tests/test_metrics.py @@ -90,3 +90,26 @@ def test_second_hdd_metrics(user: UserClient): res, _ = user.get("/metrics/") assert res == metrics + +@pytest.mark.mvp +@pytest.mark.usefixtures(conftest.app_context.__name__) +def test_metrics_with_live_null(user: UserClient): + """ Checks one standard query of metrics """ + # Insert computer + acer = file('acer.happy.battery.snapshot') + snapshot, _ = user.post(acer, res=ma.Snapshot) + device_id = snapshot['device']['id'] + post_request = {"Transaction": "ccc", "name": "John", "end_users": 1, + "devices": [device_id], "description": "aaa", + "start_time": "2020-11-01T02:00:00+00:00", + "end_time": "2020-12-01T02:00:00+00:00" + } + + # Create Allocate + user.post(res=ma.Allocate, data=post_request) + + # Check metrics if we change the hdd we need a result of one device + metrics = {'allocateds': 1, 'live': 0} + res, _ = user.get("/metrics/") + assert res == metrics +