forked from astropy/astropy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_logger.py
More file actions
385 lines (285 loc) · 11.7 KB
/
Copy pathtest_logger.py
File metadata and controls
385 lines (285 loc) · 11.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
import sys
import warnings
import pytest
from .. import log
from ..logger import LoggingError
# Save original values of hooks. These are not the system values, but the
# already overwritten values since the logger already gets imported before
# this file gets executed.
_excepthook = sys.__excepthook__
_showwarning = warnings.showwarning
def setup_function(function):
# Reset hooks to original values
sys.excepthook = _excepthook
warnings.showwarning = _showwarning
# Reset internal original hooks
log._showwarning_orig = None
log._excepthook_orig = None
# Set up the logger
log._set_defaults()
# Reset hooks
if log.warnings_logging_enabled():
log.disable_warnings_logging()
if log.exception_logging_enabled():
log.disable_exception_logging()
def teardown_module(function):
# Ensure that hooks are restored to original values
sys.excepthook = _excepthook
warnings.showwarning = _showwarning
def test_warnings_logging_disable_no_enable():
with pytest.raises(LoggingError) as e:
log.disable_warnings_logging()
assert e.value.args[0] == 'Warnings logging has not been enabled'
def test_warnings_logging_enable_twice():
log.enable_warnings_logging()
with pytest.raises(LoggingError) as e:
log.enable_warnings_logging()
assert e.value.args[0] == 'Warnings logging has already been enabled'
def test_warnings_logging_overridden():
log.enable_warnings_logging()
warnings.showwarning = lambda: None
with pytest.raises(LoggingError) as e:
log.disable_warnings_logging()
assert e.value.args[0] == 'Cannot disable warnings logging: warnings.showwarning was not set by this logger, or has been overridden'
def test_warnings_logging():
# Without warnings logging
with warnings.catch_warnings(record=True) as warn_list:
with log.log_to_list() as log_list:
warnings.warn("This is a warning")
assert len(log_list) == 0
assert len(warn_list) == 1
assert warn_list[0].message.args[0] == "This is a warning"
# With warnings logging
with warnings.catch_warnings(record=True) as warn_list:
log.enable_warnings_logging()
with log.log_to_list() as log_list:
warnings.warn("This is a warning")
log.disable_warnings_logging()
assert len(log_list) == 1
assert len(warn_list) == 0
assert log_list[0].levelname == 'WARNING'
assert log_list[0].message == 'This is a warning'
assert log_list[0].origin == 'astropy.tests.test_logger'
# Without warnings logging
with warnings.catch_warnings(record=True) as warn_list:
with log.log_to_list() as log_list:
warnings.warn("This is a warning")
assert len(log_list) == 0
assert len(warn_list) == 1
assert warn_list[0].message.args[0] == "This is a warning"
def test_warnings_logging_with_custom_class():
class CustomWarningClass(Warning):
pass
# With warnings logging
with warnings.catch_warnings(record=True) as warn_list:
log.enable_warnings_logging()
with log.log_to_list() as log_list:
warnings.warn("This is a warning", CustomWarningClass)
log.disable_warnings_logging()
assert len(log_list) == 1
assert len(warn_list) == 0
assert log_list[0].levelname == 'WARNING'
assert log_list[0].message == 'CustomWarningClass: This is a warning'
assert log_list[0].origin == 'astropy.tests.test_logger'
def test_warning_logging_with_io_vo_warning():
from ..io.vo.exceptions import W02, vo_warn
with warnings.catch_warnings(record=True) as warn_list:
log.enable_warnings_logging()
with log.log_to_list() as log_list:
vo_warn(W02, ('a', 'b'))
log.disable_warnings_logging()
assert len(log_list) == 1
assert len(warn_list) == 0
assert log_list[0].levelname == 'WARNING'
assert log_list[0].message == ("W02: ?:?:?: W02: a attribute 'b' is "
"invalid. Must be a standard XML id")
assert log_list[0].origin == 'astropy.tests.test_logger'
def test_exception_logging_disable_no_enable():
with pytest.raises(LoggingError) as e:
log.disable_exception_logging()
assert e.value.args[0] == 'Exception logging has not been enabled'
def test_exception_logging_enable_twice():
log.enable_exception_logging()
with pytest.raises(LoggingError) as e:
log.enable_exception_logging()
assert e.value.args[0] == 'Exception logging has already been enabled'
def test_exception_logging_overridden():
log.enable_exception_logging()
sys.excepthook = lambda: None
with pytest.raises(LoggingError) as e:
log.disable_exception_logging()
assert e.value.args[0] == 'Cannot disable exception logging: sys.excepthook was not set by this logger, or has been overridden'
def test_exception_logging():
# Without exception logging
try:
with log.log_to_list() as log_list:
raise Exception("This is an Exception")
except Exception as exc:
sys.excepthook(*sys.exc_info())
assert exc.args[0] == "This is an Exception"
else:
assert False # exception should have been raised
assert len(log_list) == 0
# With exception logging
try:
log.enable_exception_logging()
with log.log_to_list() as log_list:
raise Exception("This is an Exception")
except Exception as exc:
sys.excepthook(*sys.exc_info())
assert exc.args[0] == "This is an Exception"
else:
assert False # exception should have been raised
assert len(log_list) == 1
assert log_list[0].levelname == 'ERROR'
assert log_list[0].message == 'Exception: This is an Exception'
assert log_list[0].origin == 'astropy.tests.test_logger'
# Without exception logging
log.disable_exception_logging()
try:
with log.log_to_list() as log_list:
raise Exception("This is an Exception")
except Exception as exc:
sys.excepthook(*sys.exc_info())
assert exc.args[0] == "This is an Exception"
else:
assert False # exception should have been raised
assert len(log_list) == 0
def test_exception_logging_origin():
# The point here is to get an exception raised from another location
# and make sure the error's origin is reported correctly
from ..utils.collections import HomogeneousList
l = HomogeneousList(int)
try:
log.enable_exception_logging()
with log.log_to_list() as log_list:
l.append('foo')
except TypeError as exc:
sys.excepthook(*sys.exc_info())
assert exc.args[0].startswith(
"homogeneous list must contain only objects of type ")
else:
assert False
assert len(log_list) == 1
assert log_list[0].levelname == 'ERROR'
assert log_list[0].message.startswith(
"TypeError: homogeneous list must contain only objects of type ")
assert log_list[0].origin == 'astropy.utils.collections'
@pytest.mark.parametrize(('level'), [None, 'DEBUG', 'INFO', 'WARN', 'ERROR'])
def test_log_to_list(level):
if level is not None:
log.setLevel(level)
with log.log_to_list() as log_list:
log.error("Error message")
log.warn("Warning message")
log.info("Information message")
log.debug("Debug message")
# Check list length
if level == 'DEBUG':
assert len(log_list) == 4
elif level is None or level == 'INFO':
assert len(log_list) == 3
elif level == 'WARN':
assert len(log_list) == 2
elif level == 'ERROR':
assert len(log_list) == 1
# Check list content
assert log_list[0].levelname == 'ERROR'
assert log_list[0].message == 'Error message'
assert log_list[0].origin == 'astropy.tests.test_logger'
if len(log_list) >= 2:
assert log_list[1].levelname == 'WARNING'
assert log_list[1].message == 'Warning message'
assert log_list[1].origin == 'astropy.tests.test_logger'
if len(log_list) >= 3:
assert log_list[2].levelname == 'INFO'
assert log_list[2].msg == 'Information message'
assert log_list[2].origin == 'astropy.tests.test_logger'
if len(log_list) >= 4:
assert log_list[3].levelname == 'DEBUG'
assert log_list[3].msg == 'Debug message'
assert log_list[3].origin == 'astropy.tests.test_logger'
def test_log_to_list_level():
with log.log_to_list(filter_level='ERROR') as log_list:
log.error("Error message")
log.warn("Warning message")
assert len(log_list) == 1 and log_list[0].levelname == 'ERROR'
def test_log_to_list_origin1():
with log.log_to_list(filter_origin='astropy.tests') as log_list:
log.error("Error message")
log.warn("Warning message")
assert len(log_list) == 2
def test_log_to_list_origin2():
with log.log_to_list(filter_origin='astropy.wcs') as log_list:
log.error("Error message")
log.warn("Warning message")
assert len(log_list) == 0
@pytest.mark.parametrize(('level'), [None, 'DEBUG', 'INFO', 'WARN', 'ERROR'])
def test_log_to_file(tmpdir, level):
local_path = tmpdir.join('test.log')
log_file = local_path.open('wb')
log_path = str(local_path.realpath())
if level is not None:
log.setLevel(level)
with log.log_to_file(log_path):
log.error("Error message")
log.warn("Warning message")
log.info("Information message")
log.debug("Debug message")
log_file.close()
log_file = local_path.open('rb')
log_entries = log_file.readlines()
log_file.close()
# Check list length
if level == 'DEBUG':
assert len(log_entries) == 4
elif level is None or level == 'INFO':
assert len(log_entries) == 3
elif level == 'WARN':
assert len(log_entries) == 2
elif level == 'ERROR':
assert len(log_entries) == 1
# Check list content
assert log_entries[0].strip().endswith(b"'astropy.tests.test_logger', 'ERROR', 'Error message'")
if len(log_entries) >= 2:
assert log_entries[1].strip().endswith(b"'astropy.tests.test_logger', 'WARNING', 'Warning message'")
if len(log_entries) >= 3:
assert log_entries[2].strip().endswith(b"'astropy.tests.test_logger', 'INFO', 'Information message'")
if len(log_entries) >= 4:
assert log_entries[3].strip().endswith(b"'astropy.tests.test_logger', 'DEBUG', 'Debug message'")
def test_log_to_file_level(tmpdir):
local_path = tmpdir.join('test.log')
log_file = local_path.open('wb')
log_path = str(local_path.realpath())
with log.log_to_file(log_path, filter_level='ERROR'):
log.error("Error message")
log.warn("Warning message")
log_file.close()
log_file = local_path.open('rb')
log_entries = log_file.readlines()
log_file.close()
assert len(log_entries) == 1 and log_entries[0].strip().endswith(b"'ERROR', 'Error message'")
def test_log_to_file_origin1(tmpdir):
local_path = tmpdir.join('test.log')
log_file = local_path.open('wb')
log_path = str(local_path.realpath())
with log.log_to_file(log_path, filter_origin='astropy.tests'):
log.error("Error message")
log.warn("Warning message")
log_file.close()
log_file = local_path.open('rb')
log_entries = log_file.readlines()
log_file.close()
assert len(log_entries) == 2
def test_log_to_file_origin2(tmpdir):
local_path = tmpdir.join('test.log')
log_file = local_path.open('wb')
log_path = str(local_path.realpath())
with log.log_to_file(log_path, filter_origin='astropy.wcs'):
log.error("Error message")
log.warn("Warning message")
log_file.close()
log_file = local_path.open('rb')
log_entries = log_file.readlines()
log_file.close()
assert len(log_entries) == 0