Debian Codegraph @

tests/u/test_loggingutil.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 import logging
18 import re
19 import sys
20 from io import TextIOWrapper
21 from pathlib import Path
22 from time import sleep
23 from typing import Callable, cast
24 from unittest import mock
25
26 import pytest
27 from pytest import param
28
29 from cylc.flow import LOG
30 from cylc.flow.cfgspec.glbl_cfg import glbl_cfg
31 from cylc.flow.cfgspec.globalcfg import GlobalConfig
32 from cylc.flow.loggingutil import (
33 CylcLogFormatter,
34 RotatingLogFileHandler,
35 get_reload_start_number,
36 get_sorted_logs_by_time,
37 patch_log_level,
38 set_timestamps,
39 )
40
41
42 @pytest.fixture
43 def rotating_log_file_handler(tmp_path: Path):
44 """Fixture to create a RotatingLogFileHandler for testing."""
45 log_file = tmp_path / "log"
46 log_file.touch()
47
48 handler = cast('RotatingLogFileHandler', None)
49 orig_stream = cast('TextIOWrapper', None)
50
51 def inner(
52 *args, level: int = logging.INFO, **kwargs
53 ) -> RotatingLogFileHandler:
54 nonlocal handler, orig_stream
55 handler = RotatingLogFileHandler(log_file, *args, **kwargs)
56 orig_stream = handler.stream
57 # next line is important as pytest can have a "Bad file descriptor"
58 # due to a FileHandler with default "a" (pytest tries to r/w).
59 handler.mode = "a+"
60
61 # enable the logger
62 LOG.setLevel(level)
63 LOG.addHandler(handler)
64
65 return handler
66
67 yield inner
68
69 # clean up
70 LOG.setLevel(logging.INFO)
71 LOG.removeHandler(handler)
72
73
74 @mock.patch("cylc.flow.loggingutil.glbl_cfg")
75 def test_value_error_raises_system_exit(
76 mocked_glbl_cfg, rotating_log_file_handler
77 ):
78 """Test that a ValueError when writing to a log stream won't result
79 in multiple exceptions (what could lead to infinite loop in some
80 occasions. Instead, it **must** raise a SystemExit"""
81 # mock objects used when creating the file handler
82 mocked = mock.MagicMock()
83 mocked_glbl_cfg.return_value = mocked
84 mocked.get.return_value = 100
85 file_handler = rotating_log_file_handler(level=logging.INFO)
86
87 # Disable raising uncaught exceptions in logging, due to file
88 # handler using stdin.fileno. See the following links for more.
89 # https://github.com/pytest-dev/pytest/issues/2276 &
90 # https://github.com/pytest-dev/pytest/issues/1585
91 logging.raiseExceptions = False
92
93 # first message will initialize the stream and the handler
94 LOG.info("What could go")
95
96 # here we change the stream of the handler
97 file_handler.stream = mock.MagicMock()
98 file_handler.stream.seek = mock.MagicMock()
99 # in case where
100 file_handler.stream.seek.side_effect = ValueError
101
102 with pytest.raises(SystemExit):
103 # next call will call the emit method and use the mocked stream
104 LOG.info("wrong?!")
105
106 # clean up
107 logging.raiseExceptions = True
108
109
110 @pytest.mark.parametrize(
111 'dev_info, expect',
112 [
113 param(
114 True,
115 (
116 '%(asctime)s %(levelname)-2s - [%(module)s:%(lineno)d] - '
117 '%(message)s'
118 ),
119 id='dev_info=True'
120 ),
121 param(
122 False,
123 '%(asctime)s %(levelname)-2s - %(message)s',
124 id='dev_info=False'
125 )
126 ]
127 )
128 def test_CylcLogFormatter__init__dev_info(dev_info, expect):
129 """dev_info switch changes the logging format string."""
130 formatter = CylcLogFormatter(dev_info=dev_info)
131 assert formatter._fmt == expect
132
133
134 def test_update_log_archive(tmp_run_dir: Callable):
135 """Test log archive performs as expected"""
136 run_dir = tmp_run_dir('some_workflow')
137 log_dir = Path(run_dir / 'log' / 'scheduler')
138 log_dir.mkdir(exist_ok=True, parents=True)
139 log_file = log_dir.joinpath('log')
140 log_file.touch()
141 log_object = RotatingLogFileHandler(
142 log_file, no_detach=False, restart_num=0
143 )
144
145 for i in range(1, 5):
146 (log_dir / f'{i:02d}-start-{i:02d}.log').touch()
147 log_object.update_log_archive(2)
148 assert list((log_dir.iterdir())).sort() == [
149 Path(log_dir / 'log'),
150 Path(log_dir / '03-start-03.log'),
151 Path(log_dir / '04-start-04.log')].sort()
152
153
154 def test_get_sorted_logs_by_time(tmp_run_dir: Callable):
155 run_dir = tmp_run_dir('some_workflow')
156 config_log_dir = Path(run_dir / 'log' / 'config')
157 config_log_dir.mkdir(exist_ok=True, parents=True)
158 for file in ['01-start-01.cylc',
159 '02-start-01.cylc',
160 '03-restart-02.cylc',
161 '04-reload-02.cylc']:
162 (config_log_dir / file).touch()
163 # Sleep required to ensure modification times are sufficiently
164 # different for sort
165 sleep(0.1)
166 loggies = get_sorted_logs_by_time(config_log_dir, "*.cylc")
167 assert loggies == [f'{config_log_dir}/01-start-01.cylc',
168 f'{config_log_dir}/02-start-01.cylc',
169 f'{config_log_dir}/03-restart-02.cylc',
170 f'{config_log_dir}/04-reload-02.cylc']
171
172
173 def test_get_reload_number(tmp_run_dir: Callable):
174 run_dir = tmp_run_dir('some_reloaded_workflow')
175 config_log_dir = Path(run_dir / 'log' / 'config')
176 config_log_dir.mkdir(exist_ok=True, parents=True)
177 for file in [
178 '01-start-01.cylc',
179 '02-reload-01.cylc',
180 '03-restart-02.cylc',
181 '04-restart-02.cylc'
182 ]:
183 (config_log_dir / file).touch()
184 # Sleeps required to ensure modification times are sufficiently
185 # different for sort
186 sleep(0.1)
187 config_logs = get_sorted_logs_by_time(config_log_dir, "*.cylc")
188
189 assert get_reload_start_number(config_logs) == '02'
190
191
192 def test_get_reload_number_no_logs(tmp_run_dir: Callable):
193 run_dir = tmp_run_dir('another_reloaded_workflow')
194 config_log_dir = Path(run_dir / 'log' / 'config')
195 config_log_dir.mkdir(exist_ok=True, parents=True)
196 config_logs = get_sorted_logs_by_time(config_log_dir, "*.cylc")
197 assert get_reload_start_number(config_logs) == '01'
198
199
200 def test_set_timestamps(capsys):
201 """The enable and disable timstamp methods do what they say"""
202 # Setup log handler
203 log_handler = logging.StreamHandler(sys.stderr)
204 log_handler.setFormatter(CylcLogFormatter())
205 LOG.addHandler(log_handler)
206
207 # Log some messages with timestamps on or off:
208 LOG.warning('foo')
209 set_timestamps(LOG, False)
210 LOG.warning('bar')
211 set_timestamps(LOG, True)
212 LOG.warning('baz')
213
214 # Check 1st and 3rd error have something timestamp-like:
215 errors = capsys.readouterr().err.split('\n')
216 assert re.match('^[0-9]{4}', errors[0])
217 assert re.match('^WARNING - bar', errors[1])
218 assert re.match('^[0-9]{4}', errors[2])
219
220 LOG.removeHandler(log_handler)
221
222
223 def test_log_emit_and_glbl_cfg(
224 monkeypatch: pytest.MonkeyPatch, rotating_log_file_handler
225 ):
226 """Test that log calls do not access the global config object.
227
228 Doing so can have the side effect of expanding the global config object
229 so should be avoided - see https://github.com/cylc/cylc-flow/issues/6244
230 """
231 rotating_log_file_handler(level=logging.DEBUG)
232 mock_cfg = mock.Mock(spec=GlobalConfig)
233 monkeypatch.setattr(
234 'cylc.flow.cfgspec.globalcfg.GlobalConfig',
235 mock.Mock(
236 spec=GlobalConfig,
237 get_inst=lambda *a, **k: mock_cfg
238 )
239 )
240
241 # Check mocking is correct:
242 glbl_cfg().get(['kinesis'])
243 assert mock_cfg.get.call_args_list == [mock.call(['kinesis'])]
244 mock_cfg.reset_mock()
245
246 # Check log emit does not access global config object:
247 LOG.debug("Entering zero gravity")
248 assert mock_cfg.get.call_args_list == []
249
250
251 def test_patch_log_level(caplog: pytest.LogCaptureFixture):
252 """Test patch_log_level temporarily changes the log level."""
253 caplog.set_level(logging.DEBUG)
254 logger = logging.getLogger("forest")
255 logger.setLevel(logging.ERROR)
256 logger.info("nope")
257 assert not caplog.records
258 with patch_log_level(logger, logging.INFO):
259 LOG.info("yep")
260 assert len(caplog.records) == 1
261 logger.info("nope")
262 assert len(caplog.records) == 1
263
264
265 def test_patch_log_level__reset(caplog: pytest.LogCaptureFixture):
266 """Test patch_log_level resets the log level correctly after
267 use, not affected by the parent logger level - see
268 https://github.com/cylc/cylc-flow/pull/6327
269 """
270 caplog.set_level(logging.ERROR)
271 logger = logging.getLogger("woods")
272 assert logger.level == logging.NOTSET
273 with patch_log_level(logger, logging.INFO):
274 logger.info("emitted but not captured, as caplog is at ERROR level")
275 assert not caplog.records
276 caplog.set_level(logging.INFO)
277 logger.info("yep")
278 assert len(caplog.records) == 1
279 assert logger.level == logging.NOTSET