|
| 1 | +# Copyright (C) 2019-2024 Intel Corporation |
| 2 | +# SPDX-License-Identifier: BSD-3-Clause |
| 3 | + |
| 4 | +import logging |
| 5 | +import unittest |
| 6 | + |
| 7 | +from codebasin.cli import Formatter |
| 8 | + |
| 9 | + |
| 10 | +class TestFormatter(unittest.TestCase): |
| 11 | + """ |
| 12 | + Test Formatter class. |
| 13 | + """ |
| 14 | + |
| 15 | + def setUp(self): |
| 16 | + logging.disable() |
| 17 | + |
| 18 | + def test_constructor(self): |
| 19 | + """Check constructor arguments""" |
| 20 | + self.assertTrue(Formatter(colors=True).colors) |
| 21 | + self.assertFalse(Formatter(colors=False).colors) |
| 22 | + self.assertFalse(Formatter().colors) |
| 23 | + |
| 24 | + def test_format(self): |
| 25 | + """Check output format""" |
| 26 | + levels = ["DEBUG", "INFO", "WARNING", "ERROR"] |
| 27 | + colors = ["\033[39m", "\033[39m", "\033[93m", "\033[91m"] |
| 28 | + for colorize in [True, False]: |
| 29 | + for levelname, color in zip(levels, colors): |
| 30 | + formatter = Formatter(colors=colorize) |
| 31 | + with self.subTest( |
| 32 | + colorize=colorize, |
| 33 | + levelname=levelname, |
| 34 | + color=color, |
| 35 | + ): |
| 36 | + record = logging.makeLogRecord( |
| 37 | + { |
| 38 | + "msg": "Testing", |
| 39 | + "levelname": levelname, |
| 40 | + }, |
| 41 | + ) |
| 42 | + msg = record.msg |
| 43 | + level = record.levelname.lower() |
| 44 | + output = formatter.format(record) |
| 45 | + if level == "info": |
| 46 | + expected = msg |
| 47 | + elif colorize: |
| 48 | + expected = f"\033[1m{color}{level}\033[0m: {msg}" |
| 49 | + else: |
| 50 | + expected = f"{level}: {msg}" |
| 51 | + self.assertEqual(output, expected) |
| 52 | + |
| 53 | + |
| 54 | +if __name__ == "__main__": |
| 55 | + unittest.main() |
0 commit comments