1#!/usr/bin/env vpython3 2 3# Copyright 2024 The Chromium Authors 4# Use of this source code is governed by a BSD-style license that can be 5# found in the LICENSE file. 6"""File for testing time_consumption.py.""" 7 8import os 9import tempfile 10import unittest 11import unittest.mock as mock 12 13import google.protobuf.json_format as json_format 14 15from google.protobuf import any_pb2 16 17import measures 18 19from test_script_metrics_pb2 import TestScriptMetric, TestScriptMetrics 20 21 22class TimeConsumptionTest(unittest.TestCase): 23 """Test time_consumption.py.""" 24 25 @mock.patch('time_consumption.time.time', side_effect=[100, 110]) 26 def test_by_dumping(self, time_patch) -> None: 27 before = len(measures._metric._metrics) 28 with measures.time_consumption('test', 'time', 'consumption'): 29 pass 30 with tempfile.TemporaryDirectory() as tmpdir: 31 measures.dump(tmpdir) 32 with open(os.path.join(tmpdir, 33 measures.TEST_SCRIPT_METRICS_JSONPB_FILENAME), 34 'r', 35 encoding='utf-8') as rf: 36 any_msg = json_format.Parse(rf.read(), any_pb2.Any()) 37 message = TestScriptMetrics() 38 self.assertTrue(any_msg.Unpack(message)) 39 self.assertEqual(len(message.metrics), before + 1) 40 exp = TestScriptMetric() 41 exp.name = 'test/time/consumption (seconds)' 42 exp.value = 10 43 self.assertEqual(message.metrics[-1], exp) 44 self.assertEqual(time_patch.call_count, 2) 45 46 @mock.patch('time_consumption.time.time', side_effect=[100, 101, 102, 110]) 47 def test_exit_twice(self, time_patch) -> None: 48 # This is not a common use scenario, but it shouldn't crash. 49 before = len(measures._metric._metrics) 50 consumption = measures.time_consumption('test', 'time', 'consumption2') 51 with consumption: 52 pass 53 with consumption: 54 pass 55 with tempfile.TemporaryDirectory() as tmpdir: 56 measures.dump(tmpdir) 57 with open(os.path.join(tmpdir, 58 measures.TEST_SCRIPT_METRICS_JSONPB_FILENAME), 59 'r', 60 encoding='utf-8') as rf: 61 any_msg = json_format.Parse(rf.read(), any_pb2.Any()) 62 message = TestScriptMetrics() 63 self.assertTrue(any_msg.Unpack(message)) 64 self.assertEqual(len(message.metrics), before + 1) 65 exp = TestScriptMetric() 66 exp.name = 'test/time/consumption2 (seconds)' 67 exp.value = 8 68 self.assertEqual(message.metrics[-1], exp) 69 self.assertEqual(time_patch.call_count, 4) 70 71 72if __name__ == '__main__': 73 unittest.main() 74