|
| 1 | +# Copyright © 2024 Norman Fomferra |
| 2 | +# Permissions are hereby granted under the terms of the MIT License: |
| 3 | +# https://opensource.org/licenses/MIT. |
| 4 | + |
| 5 | +import logging |
| 6 | +import os |
| 7 | +import unittest |
| 8 | + |
| 9 | +from zappend.profiler import Profiler |
| 10 | + |
| 11 | + |
| 12 | +class ProfilerTest(unittest.TestCase): |
| 13 | + def test_disabled(self): |
| 14 | + profiler = Profiler(None) |
| 15 | + self.assert_profiler_config(profiler, False) |
| 16 | + with profiler: |
| 17 | + pass |
| 18 | + |
| 19 | + profiler = Profiler(False) |
| 20 | + self.assert_profiler_config(profiler, False) |
| 21 | + with profiler: |
| 22 | + pass |
| 23 | + |
| 24 | + profiler = Profiler({"enabled": False}) |
| 25 | + self.assert_profiler_config(profiler, False) |
| 26 | + with profiler: |
| 27 | + pass |
| 28 | + |
| 29 | + profiler = Profiler({"log_level": "NOTSET"}) |
| 30 | + self.assert_profiler_config(profiler, False, "NOTSET") |
| 31 | + with profiler: |
| 32 | + pass |
| 33 | + |
| 34 | + profiler = Profiler({"enabled": True, "log_level": "NOTSET"}) |
| 35 | + self.assert_profiler_config(profiler, False, "NOTSET") |
| 36 | + with profiler: |
| 37 | + pass |
| 38 | + |
| 39 | + def test_enabled(self): |
| 40 | + profiler = Profiler(True) |
| 41 | + self.assert_profiler_config(profiler, True, "INFO") |
| 42 | + with profiler: |
| 43 | + pass |
| 44 | + |
| 45 | + profiler = Profiler("prof.out") |
| 46 | + self.assert_profiler_config(profiler, True, "INFO", "prof.out") |
| 47 | + try: |
| 48 | + with profiler: |
| 49 | + pass |
| 50 | + self.assertTrue(os.path.exists("prof.out")) |
| 51 | + finally: |
| 52 | + if os.path.exists("prof.out"): |
| 53 | + os.remove("prof.out") |
| 54 | + |
| 55 | + profiler = Profiler({"path": "prof.out", "log_level": "DEBUG"}) |
| 56 | + self.assert_profiler_config(profiler, True, "DEBUG", "prof.out") |
| 57 | + try: |
| 58 | + with profiler: |
| 59 | + pass |
| 60 | + self.assertTrue(os.path.exists("prof.out")) |
| 61 | + finally: |
| 62 | + if os.path.exists("prof.out"): |
| 63 | + os.remove("prof.out") |
| 64 | + |
| 65 | + def assert_profiler_config( |
| 66 | + self, |
| 67 | + profiler: Profiler, |
| 68 | + expected_enabled, |
| 69 | + expected_log_level="INFO", |
| 70 | + expected_path=None, |
| 71 | + expected_keys=None, |
| 72 | + expected_restrictions=None, |
| 73 | + ): |
| 74 | + if expected_keys is None: |
| 75 | + expected_keys = ["tottime"] |
| 76 | + if expected_restrictions is None: |
| 77 | + expected_restrictions = [] |
| 78 | + self.assertEqual(expected_enabled, profiler.enabled) |
| 79 | + self.assertEqual(expected_log_level, profiler.log_level) |
| 80 | + self.assertEqual(expected_path, profiler.path) |
| 81 | + self.assertEqual(expected_keys, profiler.keys) |
| 82 | + self.assertEqual(expected_restrictions, profiler.restrictions) |
0 commit comments