Debian Codegraph @

tests/unit/scripts/test_cat_log.py

raw
1 # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
2 # Copyright (C) NIWA & British Crown (Met Office) & Contributors.
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17 from subprocess import Popen, PIPE
18
19 from ansimarkup import parse as cparse
20 from colorama import Style
21 import pytest
22
23 from cylc.flow.loggingutil import CylcLogFormatter
24 from cylc.flow.scripts.cat_log import (
25 colorise_cat_log,
26 )
27
28
29 @pytest.fixture
30 def log_file(tmp_path):
31 _log_file = tmp_path / 'log'
32 with open(_log_file, 'w+') as fh:
33 fh.write('DEBUG - 1\n')
34 fh.write('INFO - 2\n')
35 fh.write('WARNING - 3\n')
36 fh.write('ERROR - 4\n')
37 fh.write('CRITICAL - 5\n')
38 return _log_file
39
40
41 def test_colorise_cat_log_plain(log_file):
42 """It should not colourise logs when color=False."""
43 # command for colorise_cat_log to colourise
44 cat_proc = Popen(
45 ['cat', str(log_file)],
46 stdout=PIPE,
47 )
48 colorise_cat_log(cat_proc, color=False)
49 assert cat_proc.communicate()[0].decode().splitlines() == [
50 # there should not be any ansii color characters here
51 'DEBUG - 1',
52 'INFO - 2',
53 'WARNING - 3',
54 'ERROR - 4',
55 'CRITICAL - 5',
56 ]
57
58
59 def test_colorise_cat_log_colour(log_file):
60 """It should colourise logs when color=True."""
61 # command for colorise_cat_log to colourise
62 cat_proc = Popen(
63 ['cat', str(log_file)],
64 stdout=PIPE,
65 )
66 out, err = colorise_cat_log(cat_proc, color=True, stdout=PIPE)
67
68 # strip the line breaks (because tags can come before or after them)
69 # strip the reset tags (because they might not be needed if redeclared)
70 out = ''.join(
71 line.replace(Style.RESET_ALL, '')
72 for line in out.decode().splitlines()
73 )
74
75 col = CylcLogFormatter.COLORS
76 assert out == (
77 ''.join([
78 # strip the reset tags
79 cparse(line).replace(Style.RESET_ALL, '')
80 for line in [
81 col['DEBUG'].format('DEBUG - 1'),
82 'INFO - 2',
83 col['WARNING'].format('WARNING - 3'),
84 col['ERROR'].format('ERROR - 4'),
85 col['CRITICAL'].format('CRITICAL - 5'),
86 ''
87 ]
88 ])
89 )