Will Bradley | 7e5b8c1 | 2019-07-30 12:44:15 -0600 | [diff] [blame] | 1 | # -*- coding: utf-8 -*- |
| 2 | # Copyright 2019 The Chromium OS Authors. All rights reserved. |
| 3 | # Use of this source code is governed by a BSD-style license that can be |
| 4 | # found in the LICENSE file. |
| 5 | |
| 6 | """Tests for the api/metrics library.""" |
| 7 | |
| 8 | from __future__ import print_function |
| 9 | |
| 10 | import mock |
| 11 | |
| 12 | from chromite.api import metrics |
| 13 | from chromite.api.gen.chromite.api import build_api_test_pb2 |
| 14 | from chromite.lib import cros_test_lib |
| 15 | from chromite.utils.metrics import (MetricEvent, OP_NAMED_EVENT, OP_START_TIMER, |
| 16 | OP_STOP_TIMER) |
| 17 | |
| 18 | |
| 19 | class MetricsTest(cros_test_lib.TestCase): |
| 20 | """Test Metrics deserialization functionality at the API layer.""" |
| 21 | |
| 22 | def testDeserializeTimer(self): |
| 23 | """Test timer math and deserialization into proto objects.""" |
| 24 | response = build_api_test_pb2.TestResultMessage() |
| 25 | mock_events = [ |
| 26 | MetricEvent(600, 'a.b', OP_START_TIMER, key='100'), |
| 27 | MetricEvent(1000, 'a.b', OP_STOP_TIMER, key='100'), |
| 28 | ] |
| 29 | with mock.patch('chromite.api.metrics.metrics.read_metrics_events', |
| 30 | return_value=mock_events): |
| 31 | metrics.deserialize_metrics_log(response.events) |
| 32 | self.assertEqual(len(response.events), 1) |
| 33 | self.assertEqual(response.events[0].name, 'a.b') |
| 34 | self.assertEqual(response.events[0].timestamp_milliseconds, 1000) |
| 35 | self.assertEqual(response.events[0].duration_milliseconds, 1000-600) |
| 36 | |
| 37 | def testDeserializeNamedEvent(self): |
| 38 | """Test deserialization of a named event. |
| 39 | |
| 40 | This test also includes a prefix to test for proper prepending. |
| 41 | """ |
| 42 | response = build_api_test_pb2.TestResultMessage() |
| 43 | mock_events = [ |
| 44 | MetricEvent(1000, 'a.named_event', OP_NAMED_EVENT, key=None), |
| 45 | ] |
| 46 | with mock.patch('chromite.api.metrics.metrics.read_metrics_events', |
| 47 | return_value=mock_events): |
| 48 | metrics.deserialize_metrics_log(response.events, prefix='prefix') |
| 49 | self.assertEqual(len(response.events), 1) |
| 50 | self.assertEqual(response.events[0].name, 'prefix.a.named_event') |
| 51 | self.assertEqual(response.events[0].timestamp_milliseconds, 1000) |
| 52 | self.assertFalse(response.events[0].duration_milliseconds) |