1 | n/a | # Copyright 2001-2017 by Vinay Sajip. All Rights Reserved. |
---|
2 | n/a | # |
---|
3 | n/a | # Permission to use, copy, modify, and distribute this software and its |
---|
4 | n/a | # documentation for any purpose and without fee is hereby granted, |
---|
5 | n/a | # provided that the above copyright notice appear in all copies and that |
---|
6 | n/a | # both that copyright notice and this permission notice appear in |
---|
7 | n/a | # supporting documentation, and that the name of Vinay Sajip |
---|
8 | n/a | # not be used in advertising or publicity pertaining to distribution |
---|
9 | n/a | # of the software without specific, written prior permission. |
---|
10 | n/a | # VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING |
---|
11 | n/a | # ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL |
---|
12 | n/a | # VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR |
---|
13 | n/a | # ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER |
---|
14 | n/a | # IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT |
---|
15 | n/a | # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. |
---|
16 | n/a | |
---|
17 | n/a | """Test harness for the logging module. Run all tests. |
---|
18 | n/a | |
---|
19 | n/a | Copyright (C) 2001-2017 Vinay Sajip. All Rights Reserved. |
---|
20 | n/a | """ |
---|
21 | n/a | |
---|
22 | n/a | import logging |
---|
23 | n/a | import logging.handlers |
---|
24 | n/a | import logging.config |
---|
25 | n/a | |
---|
26 | n/a | import codecs |
---|
27 | n/a | import configparser |
---|
28 | n/a | import datetime |
---|
29 | n/a | import pathlib |
---|
30 | n/a | import pickle |
---|
31 | n/a | import io |
---|
32 | n/a | import gc |
---|
33 | n/a | import json |
---|
34 | n/a | import os |
---|
35 | n/a | import queue |
---|
36 | n/a | import random |
---|
37 | n/a | import re |
---|
38 | n/a | import socket |
---|
39 | n/a | import struct |
---|
40 | n/a | import sys |
---|
41 | n/a | import tempfile |
---|
42 | n/a | from test.support.script_helper import assert_python_ok |
---|
43 | n/a | from test import support |
---|
44 | n/a | import textwrap |
---|
45 | n/a | import time |
---|
46 | n/a | import unittest |
---|
47 | n/a | import warnings |
---|
48 | n/a | import weakref |
---|
49 | n/a | try: |
---|
50 | n/a | import threading |
---|
51 | n/a | # The following imports are needed only for tests which |
---|
52 | n/a | # require threading |
---|
53 | n/a | import asyncore |
---|
54 | n/a | from http.server import HTTPServer, BaseHTTPRequestHandler |
---|
55 | n/a | import smtpd |
---|
56 | n/a | from urllib.parse import urlparse, parse_qs |
---|
57 | n/a | from socketserver import (ThreadingUDPServer, DatagramRequestHandler, |
---|
58 | n/a | ThreadingTCPServer, StreamRequestHandler) |
---|
59 | n/a | except ImportError: |
---|
60 | n/a | threading = None |
---|
61 | n/a | try: |
---|
62 | n/a | import win32evtlog, win32evtlogutil, pywintypes |
---|
63 | n/a | except ImportError: |
---|
64 | n/a | win32evtlog = win32evtlogutil = pywintypes = None |
---|
65 | n/a | |
---|
66 | n/a | try: |
---|
67 | n/a | import zlib |
---|
68 | n/a | except ImportError: |
---|
69 | n/a | pass |
---|
70 | n/a | |
---|
71 | n/a | class BaseTest(unittest.TestCase): |
---|
72 | n/a | |
---|
73 | n/a | """Base class for logging tests.""" |
---|
74 | n/a | |
---|
75 | n/a | log_format = "%(name)s -> %(levelname)s: %(message)s" |
---|
76 | n/a | expected_log_pat = r"^([\w.]+) -> (\w+): (\d+)$" |
---|
77 | n/a | message_num = 0 |
---|
78 | n/a | |
---|
79 | n/a | def setUp(self): |
---|
80 | n/a | """Setup the default logging stream to an internal StringIO instance, |
---|
81 | n/a | so that we can examine log output as we want.""" |
---|
82 | n/a | logger_dict = logging.getLogger().manager.loggerDict |
---|
83 | n/a | logging._acquireLock() |
---|
84 | n/a | try: |
---|
85 | n/a | self.saved_handlers = logging._handlers.copy() |
---|
86 | n/a | self.saved_handler_list = logging._handlerList[:] |
---|
87 | n/a | self.saved_loggers = saved_loggers = logger_dict.copy() |
---|
88 | n/a | self.saved_name_to_level = logging._nameToLevel.copy() |
---|
89 | n/a | self.saved_level_to_name = logging._levelToName.copy() |
---|
90 | n/a | self.logger_states = logger_states = {} |
---|
91 | n/a | for name in saved_loggers: |
---|
92 | n/a | logger_states[name] = getattr(saved_loggers[name], |
---|
93 | n/a | 'disabled', None) |
---|
94 | n/a | finally: |
---|
95 | n/a | logging._releaseLock() |
---|
96 | n/a | |
---|
97 | n/a | # Set two unused loggers |
---|
98 | n/a | self.logger1 = logging.getLogger("\xab\xd7\xbb") |
---|
99 | n/a | self.logger2 = logging.getLogger("\u013f\u00d6\u0047") |
---|
100 | n/a | |
---|
101 | n/a | self.root_logger = logging.getLogger("") |
---|
102 | n/a | self.original_logging_level = self.root_logger.getEffectiveLevel() |
---|
103 | n/a | |
---|
104 | n/a | self.stream = io.StringIO() |
---|
105 | n/a | self.root_logger.setLevel(logging.DEBUG) |
---|
106 | n/a | self.root_hdlr = logging.StreamHandler(self.stream) |
---|
107 | n/a | self.root_formatter = logging.Formatter(self.log_format) |
---|
108 | n/a | self.root_hdlr.setFormatter(self.root_formatter) |
---|
109 | n/a | if self.logger1.hasHandlers(): |
---|
110 | n/a | hlist = self.logger1.handlers + self.root_logger.handlers |
---|
111 | n/a | raise AssertionError('Unexpected handlers: %s' % hlist) |
---|
112 | n/a | if self.logger2.hasHandlers(): |
---|
113 | n/a | hlist = self.logger2.handlers + self.root_logger.handlers |
---|
114 | n/a | raise AssertionError('Unexpected handlers: %s' % hlist) |
---|
115 | n/a | self.root_logger.addHandler(self.root_hdlr) |
---|
116 | n/a | self.assertTrue(self.logger1.hasHandlers()) |
---|
117 | n/a | self.assertTrue(self.logger2.hasHandlers()) |
---|
118 | n/a | |
---|
119 | n/a | def tearDown(self): |
---|
120 | n/a | """Remove our logging stream, and restore the original logging |
---|
121 | n/a | level.""" |
---|
122 | n/a | self.stream.close() |
---|
123 | n/a | self.root_logger.removeHandler(self.root_hdlr) |
---|
124 | n/a | while self.root_logger.handlers: |
---|
125 | n/a | h = self.root_logger.handlers[0] |
---|
126 | n/a | self.root_logger.removeHandler(h) |
---|
127 | n/a | h.close() |
---|
128 | n/a | self.root_logger.setLevel(self.original_logging_level) |
---|
129 | n/a | logging._acquireLock() |
---|
130 | n/a | try: |
---|
131 | n/a | logging._levelToName.clear() |
---|
132 | n/a | logging._levelToName.update(self.saved_level_to_name) |
---|
133 | n/a | logging._nameToLevel.clear() |
---|
134 | n/a | logging._nameToLevel.update(self.saved_name_to_level) |
---|
135 | n/a | logging._handlers.clear() |
---|
136 | n/a | logging._handlers.update(self.saved_handlers) |
---|
137 | n/a | logging._handlerList[:] = self.saved_handler_list |
---|
138 | n/a | loggerDict = logging.getLogger().manager.loggerDict |
---|
139 | n/a | loggerDict.clear() |
---|
140 | n/a | loggerDict.update(self.saved_loggers) |
---|
141 | n/a | logger_states = self.logger_states |
---|
142 | n/a | for name in self.logger_states: |
---|
143 | n/a | if logger_states[name] is not None: |
---|
144 | n/a | self.saved_loggers[name].disabled = logger_states[name] |
---|
145 | n/a | finally: |
---|
146 | n/a | logging._releaseLock() |
---|
147 | n/a | |
---|
148 | n/a | def assert_log_lines(self, expected_values, stream=None, pat=None): |
---|
149 | n/a | """Match the collected log lines against the regular expression |
---|
150 | n/a | self.expected_log_pat, and compare the extracted group values to |
---|
151 | n/a | the expected_values list of tuples.""" |
---|
152 | n/a | stream = stream or self.stream |
---|
153 | n/a | pat = re.compile(pat or self.expected_log_pat) |
---|
154 | n/a | actual_lines = stream.getvalue().splitlines() |
---|
155 | n/a | self.assertEqual(len(actual_lines), len(expected_values)) |
---|
156 | n/a | for actual, expected in zip(actual_lines, expected_values): |
---|
157 | n/a | match = pat.search(actual) |
---|
158 | n/a | if not match: |
---|
159 | n/a | self.fail("Log line does not match expected pattern:\n" + |
---|
160 | n/a | actual) |
---|
161 | n/a | self.assertEqual(tuple(match.groups()), expected) |
---|
162 | n/a | s = stream.read() |
---|
163 | n/a | if s: |
---|
164 | n/a | self.fail("Remaining output at end of log stream:\n" + s) |
---|
165 | n/a | |
---|
166 | n/a | def next_message(self): |
---|
167 | n/a | """Generate a message consisting solely of an auto-incrementing |
---|
168 | n/a | integer.""" |
---|
169 | n/a | self.message_num += 1 |
---|
170 | n/a | return "%d" % self.message_num |
---|
171 | n/a | |
---|
172 | n/a | |
---|
173 | n/a | class BuiltinLevelsTest(BaseTest): |
---|
174 | n/a | """Test builtin levels and their inheritance.""" |
---|
175 | n/a | |
---|
176 | n/a | def test_flat(self): |
---|
177 | n/a | #Logging levels in a flat logger namespace. |
---|
178 | n/a | m = self.next_message |
---|
179 | n/a | |
---|
180 | n/a | ERR = logging.getLogger("ERR") |
---|
181 | n/a | ERR.setLevel(logging.ERROR) |
---|
182 | n/a | INF = logging.LoggerAdapter(logging.getLogger("INF"), {}) |
---|
183 | n/a | INF.setLevel(logging.INFO) |
---|
184 | n/a | DEB = logging.getLogger("DEB") |
---|
185 | n/a | DEB.setLevel(logging.DEBUG) |
---|
186 | n/a | |
---|
187 | n/a | # These should log. |
---|
188 | n/a | ERR.log(logging.CRITICAL, m()) |
---|
189 | n/a | ERR.error(m()) |
---|
190 | n/a | |
---|
191 | n/a | INF.log(logging.CRITICAL, m()) |
---|
192 | n/a | INF.error(m()) |
---|
193 | n/a | INF.warning(m()) |
---|
194 | n/a | INF.info(m()) |
---|
195 | n/a | |
---|
196 | n/a | DEB.log(logging.CRITICAL, m()) |
---|
197 | n/a | DEB.error(m()) |
---|
198 | n/a | DEB.warning(m()) |
---|
199 | n/a | DEB.info(m()) |
---|
200 | n/a | DEB.debug(m()) |
---|
201 | n/a | |
---|
202 | n/a | # These should not log. |
---|
203 | n/a | ERR.warning(m()) |
---|
204 | n/a | ERR.info(m()) |
---|
205 | n/a | ERR.debug(m()) |
---|
206 | n/a | |
---|
207 | n/a | INF.debug(m()) |
---|
208 | n/a | |
---|
209 | n/a | self.assert_log_lines([ |
---|
210 | n/a | ('ERR', 'CRITICAL', '1'), |
---|
211 | n/a | ('ERR', 'ERROR', '2'), |
---|
212 | n/a | ('INF', 'CRITICAL', '3'), |
---|
213 | n/a | ('INF', 'ERROR', '4'), |
---|
214 | n/a | ('INF', 'WARNING', '5'), |
---|
215 | n/a | ('INF', 'INFO', '6'), |
---|
216 | n/a | ('DEB', 'CRITICAL', '7'), |
---|
217 | n/a | ('DEB', 'ERROR', '8'), |
---|
218 | n/a | ('DEB', 'WARNING', '9'), |
---|
219 | n/a | ('DEB', 'INFO', '10'), |
---|
220 | n/a | ('DEB', 'DEBUG', '11'), |
---|
221 | n/a | ]) |
---|
222 | n/a | |
---|
223 | n/a | def test_nested_explicit(self): |
---|
224 | n/a | # Logging levels in a nested namespace, all explicitly set. |
---|
225 | n/a | m = self.next_message |
---|
226 | n/a | |
---|
227 | n/a | INF = logging.getLogger("INF") |
---|
228 | n/a | INF.setLevel(logging.INFO) |
---|
229 | n/a | INF_ERR = logging.getLogger("INF.ERR") |
---|
230 | n/a | INF_ERR.setLevel(logging.ERROR) |
---|
231 | n/a | |
---|
232 | n/a | # These should log. |
---|
233 | n/a | INF_ERR.log(logging.CRITICAL, m()) |
---|
234 | n/a | INF_ERR.error(m()) |
---|
235 | n/a | |
---|
236 | n/a | # These should not log. |
---|
237 | n/a | INF_ERR.warning(m()) |
---|
238 | n/a | INF_ERR.info(m()) |
---|
239 | n/a | INF_ERR.debug(m()) |
---|
240 | n/a | |
---|
241 | n/a | self.assert_log_lines([ |
---|
242 | n/a | ('INF.ERR', 'CRITICAL', '1'), |
---|
243 | n/a | ('INF.ERR', 'ERROR', '2'), |
---|
244 | n/a | ]) |
---|
245 | n/a | |
---|
246 | n/a | def test_nested_inherited(self): |
---|
247 | n/a | #Logging levels in a nested namespace, inherited from parent loggers. |
---|
248 | n/a | m = self.next_message |
---|
249 | n/a | |
---|
250 | n/a | INF = logging.getLogger("INF") |
---|
251 | n/a | INF.setLevel(logging.INFO) |
---|
252 | n/a | INF_ERR = logging.getLogger("INF.ERR") |
---|
253 | n/a | INF_ERR.setLevel(logging.ERROR) |
---|
254 | n/a | INF_UNDEF = logging.getLogger("INF.UNDEF") |
---|
255 | n/a | INF_ERR_UNDEF = logging.getLogger("INF.ERR.UNDEF") |
---|
256 | n/a | UNDEF = logging.getLogger("UNDEF") |
---|
257 | n/a | |
---|
258 | n/a | # These should log. |
---|
259 | n/a | INF_UNDEF.log(logging.CRITICAL, m()) |
---|
260 | n/a | INF_UNDEF.error(m()) |
---|
261 | n/a | INF_UNDEF.warning(m()) |
---|
262 | n/a | INF_UNDEF.info(m()) |
---|
263 | n/a | INF_ERR_UNDEF.log(logging.CRITICAL, m()) |
---|
264 | n/a | INF_ERR_UNDEF.error(m()) |
---|
265 | n/a | |
---|
266 | n/a | # These should not log. |
---|
267 | n/a | INF_UNDEF.debug(m()) |
---|
268 | n/a | INF_ERR_UNDEF.warning(m()) |
---|
269 | n/a | INF_ERR_UNDEF.info(m()) |
---|
270 | n/a | INF_ERR_UNDEF.debug(m()) |
---|
271 | n/a | |
---|
272 | n/a | self.assert_log_lines([ |
---|
273 | n/a | ('INF.UNDEF', 'CRITICAL', '1'), |
---|
274 | n/a | ('INF.UNDEF', 'ERROR', '2'), |
---|
275 | n/a | ('INF.UNDEF', 'WARNING', '3'), |
---|
276 | n/a | ('INF.UNDEF', 'INFO', '4'), |
---|
277 | n/a | ('INF.ERR.UNDEF', 'CRITICAL', '5'), |
---|
278 | n/a | ('INF.ERR.UNDEF', 'ERROR', '6'), |
---|
279 | n/a | ]) |
---|
280 | n/a | |
---|
281 | n/a | def test_nested_with_virtual_parent(self): |
---|
282 | n/a | # Logging levels when some parent does not exist yet. |
---|
283 | n/a | m = self.next_message |
---|
284 | n/a | |
---|
285 | n/a | INF = logging.getLogger("INF") |
---|
286 | n/a | GRANDCHILD = logging.getLogger("INF.BADPARENT.UNDEF") |
---|
287 | n/a | CHILD = logging.getLogger("INF.BADPARENT") |
---|
288 | n/a | INF.setLevel(logging.INFO) |
---|
289 | n/a | |
---|
290 | n/a | # These should log. |
---|
291 | n/a | GRANDCHILD.log(logging.FATAL, m()) |
---|
292 | n/a | GRANDCHILD.info(m()) |
---|
293 | n/a | CHILD.log(logging.FATAL, m()) |
---|
294 | n/a | CHILD.info(m()) |
---|
295 | n/a | |
---|
296 | n/a | # These should not log. |
---|
297 | n/a | GRANDCHILD.debug(m()) |
---|
298 | n/a | CHILD.debug(m()) |
---|
299 | n/a | |
---|
300 | n/a | self.assert_log_lines([ |
---|
301 | n/a | ('INF.BADPARENT.UNDEF', 'CRITICAL', '1'), |
---|
302 | n/a | ('INF.BADPARENT.UNDEF', 'INFO', '2'), |
---|
303 | n/a | ('INF.BADPARENT', 'CRITICAL', '3'), |
---|
304 | n/a | ('INF.BADPARENT', 'INFO', '4'), |
---|
305 | n/a | ]) |
---|
306 | n/a | |
---|
307 | n/a | def test_regression_22386(self): |
---|
308 | n/a | """See issue #22386 for more information.""" |
---|
309 | n/a | self.assertEqual(logging.getLevelName('INFO'), logging.INFO) |
---|
310 | n/a | self.assertEqual(logging.getLevelName(logging.INFO), 'INFO') |
---|
311 | n/a | |
---|
312 | n/a | def test_regression_29220(self): |
---|
313 | n/a | """See issue #29220 for more information.""" |
---|
314 | n/a | logging.addLevelName(logging.INFO, '') |
---|
315 | n/a | self.addCleanup(logging.addLevelName, logging.INFO, 'INFO') |
---|
316 | n/a | self.assertEqual(logging.getLevelName(logging.INFO), '') |
---|
317 | n/a | |
---|
318 | n/a | def test_issue27935(self): |
---|
319 | n/a | fatal = logging.getLevelName('FATAL') |
---|
320 | n/a | self.assertEqual(fatal, logging.FATAL) |
---|
321 | n/a | |
---|
322 | n/a | def test_regression_29220(self): |
---|
323 | n/a | """See issue #29220 for more information.""" |
---|
324 | n/a | logging.addLevelName(logging.INFO, '') |
---|
325 | n/a | self.addCleanup(logging.addLevelName, logging.INFO, 'INFO') |
---|
326 | n/a | self.assertEqual(logging.getLevelName(logging.INFO), '') |
---|
327 | n/a | self.assertEqual(logging.getLevelName(logging.NOTSET), 'NOTSET') |
---|
328 | n/a | self.assertEqual(logging.getLevelName('NOTSET'), logging.NOTSET) |
---|
329 | n/a | |
---|
330 | n/a | class BasicFilterTest(BaseTest): |
---|
331 | n/a | |
---|
332 | n/a | """Test the bundled Filter class.""" |
---|
333 | n/a | |
---|
334 | n/a | def test_filter(self): |
---|
335 | n/a | # Only messages satisfying the specified criteria pass through the |
---|
336 | n/a | # filter. |
---|
337 | n/a | filter_ = logging.Filter("spam.eggs") |
---|
338 | n/a | handler = self.root_logger.handlers[0] |
---|
339 | n/a | try: |
---|
340 | n/a | handler.addFilter(filter_) |
---|
341 | n/a | spam = logging.getLogger("spam") |
---|
342 | n/a | spam_eggs = logging.getLogger("spam.eggs") |
---|
343 | n/a | spam_eggs_fish = logging.getLogger("spam.eggs.fish") |
---|
344 | n/a | spam_bakedbeans = logging.getLogger("spam.bakedbeans") |
---|
345 | n/a | |
---|
346 | n/a | spam.info(self.next_message()) |
---|
347 | n/a | spam_eggs.info(self.next_message()) # Good. |
---|
348 | n/a | spam_eggs_fish.info(self.next_message()) # Good. |
---|
349 | n/a | spam_bakedbeans.info(self.next_message()) |
---|
350 | n/a | |
---|
351 | n/a | self.assert_log_lines([ |
---|
352 | n/a | ('spam.eggs', 'INFO', '2'), |
---|
353 | n/a | ('spam.eggs.fish', 'INFO', '3'), |
---|
354 | n/a | ]) |
---|
355 | n/a | finally: |
---|
356 | n/a | handler.removeFilter(filter_) |
---|
357 | n/a | |
---|
358 | n/a | def test_callable_filter(self): |
---|
359 | n/a | # Only messages satisfying the specified criteria pass through the |
---|
360 | n/a | # filter. |
---|
361 | n/a | |
---|
362 | n/a | def filterfunc(record): |
---|
363 | n/a | parts = record.name.split('.') |
---|
364 | n/a | prefix = '.'.join(parts[:2]) |
---|
365 | n/a | return prefix == 'spam.eggs' |
---|
366 | n/a | |
---|
367 | n/a | handler = self.root_logger.handlers[0] |
---|
368 | n/a | try: |
---|
369 | n/a | handler.addFilter(filterfunc) |
---|
370 | n/a | spam = logging.getLogger("spam") |
---|
371 | n/a | spam_eggs = logging.getLogger("spam.eggs") |
---|
372 | n/a | spam_eggs_fish = logging.getLogger("spam.eggs.fish") |
---|
373 | n/a | spam_bakedbeans = logging.getLogger("spam.bakedbeans") |
---|
374 | n/a | |
---|
375 | n/a | spam.info(self.next_message()) |
---|
376 | n/a | spam_eggs.info(self.next_message()) # Good. |
---|
377 | n/a | spam_eggs_fish.info(self.next_message()) # Good. |
---|
378 | n/a | spam_bakedbeans.info(self.next_message()) |
---|
379 | n/a | |
---|
380 | n/a | self.assert_log_lines([ |
---|
381 | n/a | ('spam.eggs', 'INFO', '2'), |
---|
382 | n/a | ('spam.eggs.fish', 'INFO', '3'), |
---|
383 | n/a | ]) |
---|
384 | n/a | finally: |
---|
385 | n/a | handler.removeFilter(filterfunc) |
---|
386 | n/a | |
---|
387 | n/a | def test_empty_filter(self): |
---|
388 | n/a | f = logging.Filter() |
---|
389 | n/a | r = logging.makeLogRecord({'name': 'spam.eggs'}) |
---|
390 | n/a | self.assertTrue(f.filter(r)) |
---|
391 | n/a | |
---|
392 | n/a | # |
---|
393 | n/a | # First, we define our levels. There can be as many as you want - the only |
---|
394 | n/a | # limitations are that they should be integers, the lowest should be > 0 and |
---|
395 | n/a | # larger values mean less information being logged. If you need specific |
---|
396 | n/a | # level values which do not fit into these limitations, you can use a |
---|
397 | n/a | # mapping dictionary to convert between your application levels and the |
---|
398 | n/a | # logging system. |
---|
399 | n/a | # |
---|
400 | n/a | SILENT = 120 |
---|
401 | n/a | TACITURN = 119 |
---|
402 | n/a | TERSE = 118 |
---|
403 | n/a | EFFUSIVE = 117 |
---|
404 | n/a | SOCIABLE = 116 |
---|
405 | n/a | VERBOSE = 115 |
---|
406 | n/a | TALKATIVE = 114 |
---|
407 | n/a | GARRULOUS = 113 |
---|
408 | n/a | CHATTERBOX = 112 |
---|
409 | n/a | BORING = 111 |
---|
410 | n/a | |
---|
411 | n/a | LEVEL_RANGE = range(BORING, SILENT + 1) |
---|
412 | n/a | |
---|
413 | n/a | # |
---|
414 | n/a | # Next, we define names for our levels. You don't need to do this - in which |
---|
415 | n/a | # case the system will use "Level n" to denote the text for the level. |
---|
416 | n/a | # |
---|
417 | n/a | my_logging_levels = { |
---|
418 | n/a | SILENT : 'Silent', |
---|
419 | n/a | TACITURN : 'Taciturn', |
---|
420 | n/a | TERSE : 'Terse', |
---|
421 | n/a | EFFUSIVE : 'Effusive', |
---|
422 | n/a | SOCIABLE : 'Sociable', |
---|
423 | n/a | VERBOSE : 'Verbose', |
---|
424 | n/a | TALKATIVE : 'Talkative', |
---|
425 | n/a | GARRULOUS : 'Garrulous', |
---|
426 | n/a | CHATTERBOX : 'Chatterbox', |
---|
427 | n/a | BORING : 'Boring', |
---|
428 | n/a | } |
---|
429 | n/a | |
---|
430 | n/a | class GarrulousFilter(logging.Filter): |
---|
431 | n/a | |
---|
432 | n/a | """A filter which blocks garrulous messages.""" |
---|
433 | n/a | |
---|
434 | n/a | def filter(self, record): |
---|
435 | n/a | return record.levelno != GARRULOUS |
---|
436 | n/a | |
---|
437 | n/a | class VerySpecificFilter(logging.Filter): |
---|
438 | n/a | |
---|
439 | n/a | """A filter which blocks sociable and taciturn messages.""" |
---|
440 | n/a | |
---|
441 | n/a | def filter(self, record): |
---|
442 | n/a | return record.levelno not in [SOCIABLE, TACITURN] |
---|
443 | n/a | |
---|
444 | n/a | |
---|
445 | n/a | class CustomLevelsAndFiltersTest(BaseTest): |
---|
446 | n/a | |
---|
447 | n/a | """Test various filtering possibilities with custom logging levels.""" |
---|
448 | n/a | |
---|
449 | n/a | # Skip the logger name group. |
---|
450 | n/a | expected_log_pat = r"^[\w.]+ -> (\w+): (\d+)$" |
---|
451 | n/a | |
---|
452 | n/a | def setUp(self): |
---|
453 | n/a | BaseTest.setUp(self) |
---|
454 | n/a | for k, v in my_logging_levels.items(): |
---|
455 | n/a | logging.addLevelName(k, v) |
---|
456 | n/a | |
---|
457 | n/a | def log_at_all_levels(self, logger): |
---|
458 | n/a | for lvl in LEVEL_RANGE: |
---|
459 | n/a | logger.log(lvl, self.next_message()) |
---|
460 | n/a | |
---|
461 | n/a | def test_logger_filter(self): |
---|
462 | n/a | # Filter at logger level. |
---|
463 | n/a | self.root_logger.setLevel(VERBOSE) |
---|
464 | n/a | # Levels >= 'Verbose' are good. |
---|
465 | n/a | self.log_at_all_levels(self.root_logger) |
---|
466 | n/a | self.assert_log_lines([ |
---|
467 | n/a | ('Verbose', '5'), |
---|
468 | n/a | ('Sociable', '6'), |
---|
469 | n/a | ('Effusive', '7'), |
---|
470 | n/a | ('Terse', '8'), |
---|
471 | n/a | ('Taciturn', '9'), |
---|
472 | n/a | ('Silent', '10'), |
---|
473 | n/a | ]) |
---|
474 | n/a | |
---|
475 | n/a | def test_handler_filter(self): |
---|
476 | n/a | # Filter at handler level. |
---|
477 | n/a | self.root_logger.handlers[0].setLevel(SOCIABLE) |
---|
478 | n/a | try: |
---|
479 | n/a | # Levels >= 'Sociable' are good. |
---|
480 | n/a | self.log_at_all_levels(self.root_logger) |
---|
481 | n/a | self.assert_log_lines([ |
---|
482 | n/a | ('Sociable', '6'), |
---|
483 | n/a | ('Effusive', '7'), |
---|
484 | n/a | ('Terse', '8'), |
---|
485 | n/a | ('Taciturn', '9'), |
---|
486 | n/a | ('Silent', '10'), |
---|
487 | n/a | ]) |
---|
488 | n/a | finally: |
---|
489 | n/a | self.root_logger.handlers[0].setLevel(logging.NOTSET) |
---|
490 | n/a | |
---|
491 | n/a | def test_specific_filters(self): |
---|
492 | n/a | # Set a specific filter object on the handler, and then add another |
---|
493 | n/a | # filter object on the logger itself. |
---|
494 | n/a | handler = self.root_logger.handlers[0] |
---|
495 | n/a | specific_filter = None |
---|
496 | n/a | garr = GarrulousFilter() |
---|
497 | n/a | handler.addFilter(garr) |
---|
498 | n/a | try: |
---|
499 | n/a | self.log_at_all_levels(self.root_logger) |
---|
500 | n/a | first_lines = [ |
---|
501 | n/a | # Notice how 'Garrulous' is missing |
---|
502 | n/a | ('Boring', '1'), |
---|
503 | n/a | ('Chatterbox', '2'), |
---|
504 | n/a | ('Talkative', '4'), |
---|
505 | n/a | ('Verbose', '5'), |
---|
506 | n/a | ('Sociable', '6'), |
---|
507 | n/a | ('Effusive', '7'), |
---|
508 | n/a | ('Terse', '8'), |
---|
509 | n/a | ('Taciturn', '9'), |
---|
510 | n/a | ('Silent', '10'), |
---|
511 | n/a | ] |
---|
512 | n/a | self.assert_log_lines(first_lines) |
---|
513 | n/a | |
---|
514 | n/a | specific_filter = VerySpecificFilter() |
---|
515 | n/a | self.root_logger.addFilter(specific_filter) |
---|
516 | n/a | self.log_at_all_levels(self.root_logger) |
---|
517 | n/a | self.assert_log_lines(first_lines + [ |
---|
518 | n/a | # Not only 'Garrulous' is still missing, but also 'Sociable' |
---|
519 | n/a | # and 'Taciturn' |
---|
520 | n/a | ('Boring', '11'), |
---|
521 | n/a | ('Chatterbox', '12'), |
---|
522 | n/a | ('Talkative', '14'), |
---|
523 | n/a | ('Verbose', '15'), |
---|
524 | n/a | ('Effusive', '17'), |
---|
525 | n/a | ('Terse', '18'), |
---|
526 | n/a | ('Silent', '20'), |
---|
527 | n/a | ]) |
---|
528 | n/a | finally: |
---|
529 | n/a | if specific_filter: |
---|
530 | n/a | self.root_logger.removeFilter(specific_filter) |
---|
531 | n/a | handler.removeFilter(garr) |
---|
532 | n/a | |
---|
533 | n/a | |
---|
534 | n/a | class HandlerTest(BaseTest): |
---|
535 | n/a | def test_name(self): |
---|
536 | n/a | h = logging.Handler() |
---|
537 | n/a | h.name = 'generic' |
---|
538 | n/a | self.assertEqual(h.name, 'generic') |
---|
539 | n/a | h.name = 'anothergeneric' |
---|
540 | n/a | self.assertEqual(h.name, 'anothergeneric') |
---|
541 | n/a | self.assertRaises(NotImplementedError, h.emit, None) |
---|
542 | n/a | |
---|
543 | n/a | def test_builtin_handlers(self): |
---|
544 | n/a | # We can't actually *use* too many handlers in the tests, |
---|
545 | n/a | # but we can try instantiating them with various options |
---|
546 | n/a | if sys.platform in ('linux', 'darwin'): |
---|
547 | n/a | for existing in (True, False): |
---|
548 | n/a | fd, fn = tempfile.mkstemp() |
---|
549 | n/a | os.close(fd) |
---|
550 | n/a | if not existing: |
---|
551 | n/a | os.unlink(fn) |
---|
552 | n/a | h = logging.handlers.WatchedFileHandler(fn, delay=True) |
---|
553 | n/a | if existing: |
---|
554 | n/a | dev, ino = h.dev, h.ino |
---|
555 | n/a | self.assertEqual(dev, -1) |
---|
556 | n/a | self.assertEqual(ino, -1) |
---|
557 | n/a | r = logging.makeLogRecord({'msg': 'Test'}) |
---|
558 | n/a | h.handle(r) |
---|
559 | n/a | # Now remove the file. |
---|
560 | n/a | os.unlink(fn) |
---|
561 | n/a | self.assertFalse(os.path.exists(fn)) |
---|
562 | n/a | # The next call should recreate the file. |
---|
563 | n/a | h.handle(r) |
---|
564 | n/a | self.assertTrue(os.path.exists(fn)) |
---|
565 | n/a | else: |
---|
566 | n/a | self.assertEqual(h.dev, -1) |
---|
567 | n/a | self.assertEqual(h.ino, -1) |
---|
568 | n/a | h.close() |
---|
569 | n/a | if existing: |
---|
570 | n/a | os.unlink(fn) |
---|
571 | n/a | if sys.platform == 'darwin': |
---|
572 | n/a | sockname = '/var/run/syslog' |
---|
573 | n/a | else: |
---|
574 | n/a | sockname = '/dev/log' |
---|
575 | n/a | try: |
---|
576 | n/a | h = logging.handlers.SysLogHandler(sockname) |
---|
577 | n/a | self.assertEqual(h.facility, h.LOG_USER) |
---|
578 | n/a | self.assertTrue(h.unixsocket) |
---|
579 | n/a | h.close() |
---|
580 | n/a | except OSError: # syslogd might not be available |
---|
581 | n/a | pass |
---|
582 | n/a | for method in ('GET', 'POST', 'PUT'): |
---|
583 | n/a | if method == 'PUT': |
---|
584 | n/a | self.assertRaises(ValueError, logging.handlers.HTTPHandler, |
---|
585 | n/a | 'localhost', '/log', method) |
---|
586 | n/a | else: |
---|
587 | n/a | h = logging.handlers.HTTPHandler('localhost', '/log', method) |
---|
588 | n/a | h.close() |
---|
589 | n/a | h = logging.handlers.BufferingHandler(0) |
---|
590 | n/a | r = logging.makeLogRecord({}) |
---|
591 | n/a | self.assertTrue(h.shouldFlush(r)) |
---|
592 | n/a | h.close() |
---|
593 | n/a | h = logging.handlers.BufferingHandler(1) |
---|
594 | n/a | self.assertFalse(h.shouldFlush(r)) |
---|
595 | n/a | h.close() |
---|
596 | n/a | |
---|
597 | n/a | def test_path_objects(self): |
---|
598 | n/a | """ |
---|
599 | n/a | Test that Path objects are accepted as filename arguments to handlers. |
---|
600 | n/a | |
---|
601 | n/a | See Issue #27493. |
---|
602 | n/a | """ |
---|
603 | n/a | fd, fn = tempfile.mkstemp() |
---|
604 | n/a | os.close(fd) |
---|
605 | n/a | os.unlink(fn) |
---|
606 | n/a | pfn = pathlib.Path(fn) |
---|
607 | n/a | cases = ( |
---|
608 | n/a | (logging.FileHandler, (pfn, 'w')), |
---|
609 | n/a | (logging.handlers.RotatingFileHandler, (pfn, 'a')), |
---|
610 | n/a | (logging.handlers.TimedRotatingFileHandler, (pfn, 'h')), |
---|
611 | n/a | ) |
---|
612 | n/a | if sys.platform in ('linux', 'darwin'): |
---|
613 | n/a | cases += ((logging.handlers.WatchedFileHandler, (pfn, 'w')),) |
---|
614 | n/a | for cls, args in cases: |
---|
615 | n/a | h = cls(*args) |
---|
616 | n/a | self.assertTrue(os.path.exists(fn)) |
---|
617 | n/a | h.close() |
---|
618 | n/a | os.unlink(fn) |
---|
619 | n/a | |
---|
620 | n/a | @unittest.skipIf(os.name == 'nt', 'WatchedFileHandler not appropriate for Windows.') |
---|
621 | n/a | @unittest.skipUnless(threading, 'Threading required for this test.') |
---|
622 | n/a | def test_race(self): |
---|
623 | n/a | # Issue #14632 refers. |
---|
624 | n/a | def remove_loop(fname, tries): |
---|
625 | n/a | for _ in range(tries): |
---|
626 | n/a | try: |
---|
627 | n/a | os.unlink(fname) |
---|
628 | n/a | self.deletion_time = time.time() |
---|
629 | n/a | except OSError: |
---|
630 | n/a | pass |
---|
631 | n/a | time.sleep(0.004 * random.randint(0, 4)) |
---|
632 | n/a | |
---|
633 | n/a | del_count = 500 |
---|
634 | n/a | log_count = 500 |
---|
635 | n/a | |
---|
636 | n/a | self.handle_time = None |
---|
637 | n/a | self.deletion_time = None |
---|
638 | n/a | |
---|
639 | n/a | for delay in (False, True): |
---|
640 | n/a | fd, fn = tempfile.mkstemp('.log', 'test_logging-3-') |
---|
641 | n/a | os.close(fd) |
---|
642 | n/a | remover = threading.Thread(target=remove_loop, args=(fn, del_count)) |
---|
643 | n/a | remover.daemon = True |
---|
644 | n/a | remover.start() |
---|
645 | n/a | h = logging.handlers.WatchedFileHandler(fn, delay=delay) |
---|
646 | n/a | f = logging.Formatter('%(asctime)s: %(levelname)s: %(message)s') |
---|
647 | n/a | h.setFormatter(f) |
---|
648 | n/a | try: |
---|
649 | n/a | for _ in range(log_count): |
---|
650 | n/a | time.sleep(0.005) |
---|
651 | n/a | r = logging.makeLogRecord({'msg': 'testing' }) |
---|
652 | n/a | try: |
---|
653 | n/a | self.handle_time = time.time() |
---|
654 | n/a | h.handle(r) |
---|
655 | n/a | except Exception: |
---|
656 | n/a | print('Deleted at %s, ' |
---|
657 | n/a | 'opened at %s' % (self.deletion_time, |
---|
658 | n/a | self.handle_time)) |
---|
659 | n/a | raise |
---|
660 | n/a | finally: |
---|
661 | n/a | remover.join() |
---|
662 | n/a | h.close() |
---|
663 | n/a | if os.path.exists(fn): |
---|
664 | n/a | os.unlink(fn) |
---|
665 | n/a | |
---|
666 | n/a | |
---|
667 | n/a | class BadStream(object): |
---|
668 | n/a | def write(self, data): |
---|
669 | n/a | raise RuntimeError('deliberate mistake') |
---|
670 | n/a | |
---|
671 | n/a | class TestStreamHandler(logging.StreamHandler): |
---|
672 | n/a | def handleError(self, record): |
---|
673 | n/a | self.error_record = record |
---|
674 | n/a | |
---|
675 | n/a | class StreamHandlerTest(BaseTest): |
---|
676 | n/a | def test_error_handling(self): |
---|
677 | n/a | h = TestStreamHandler(BadStream()) |
---|
678 | n/a | r = logging.makeLogRecord({}) |
---|
679 | n/a | old_raise = logging.raiseExceptions |
---|
680 | n/a | |
---|
681 | n/a | try: |
---|
682 | n/a | h.handle(r) |
---|
683 | n/a | self.assertIs(h.error_record, r) |
---|
684 | n/a | |
---|
685 | n/a | h = logging.StreamHandler(BadStream()) |
---|
686 | n/a | with support.captured_stderr() as stderr: |
---|
687 | n/a | h.handle(r) |
---|
688 | n/a | msg = '\nRuntimeError: deliberate mistake\n' |
---|
689 | n/a | self.assertIn(msg, stderr.getvalue()) |
---|
690 | n/a | |
---|
691 | n/a | logging.raiseExceptions = False |
---|
692 | n/a | with support.captured_stderr() as stderr: |
---|
693 | n/a | h.handle(r) |
---|
694 | n/a | self.assertEqual('', stderr.getvalue()) |
---|
695 | n/a | finally: |
---|
696 | n/a | logging.raiseExceptions = old_raise |
---|
697 | n/a | |
---|
698 | n/a | # -- The following section could be moved into a server_helper.py module |
---|
699 | n/a | # -- if it proves to be of wider utility than just test_logging |
---|
700 | n/a | |
---|
701 | n/a | if threading: |
---|
702 | n/a | class TestSMTPServer(smtpd.SMTPServer): |
---|
703 | n/a | """ |
---|
704 | n/a | This class implements a test SMTP server. |
---|
705 | n/a | |
---|
706 | n/a | :param addr: A (host, port) tuple which the server listens on. |
---|
707 | n/a | You can specify a port value of zero: the server's |
---|
708 | n/a | *port* attribute will hold the actual port number |
---|
709 | n/a | used, which can be used in client connections. |
---|
710 | n/a | :param handler: A callable which will be called to process |
---|
711 | n/a | incoming messages. The handler will be passed |
---|
712 | n/a | the client address tuple, who the message is from, |
---|
713 | n/a | a list of recipients and the message data. |
---|
714 | n/a | :param poll_interval: The interval, in seconds, used in the underlying |
---|
715 | n/a | :func:`select` or :func:`poll` call by |
---|
716 | n/a | :func:`asyncore.loop`. |
---|
717 | n/a | :param sockmap: A dictionary which will be used to hold |
---|
718 | n/a | :class:`asyncore.dispatcher` instances used by |
---|
719 | n/a | :func:`asyncore.loop`. This avoids changing the |
---|
720 | n/a | :mod:`asyncore` module's global state. |
---|
721 | n/a | """ |
---|
722 | n/a | |
---|
723 | n/a | def __init__(self, addr, handler, poll_interval, sockmap): |
---|
724 | n/a | smtpd.SMTPServer.__init__(self, addr, None, map=sockmap, |
---|
725 | n/a | decode_data=True) |
---|
726 | n/a | self.port = self.socket.getsockname()[1] |
---|
727 | n/a | self._handler = handler |
---|
728 | n/a | self._thread = None |
---|
729 | n/a | self.poll_interval = poll_interval |
---|
730 | n/a | |
---|
731 | n/a | def process_message(self, peer, mailfrom, rcpttos, data): |
---|
732 | n/a | """ |
---|
733 | n/a | Delegates to the handler passed in to the server's constructor. |
---|
734 | n/a | |
---|
735 | n/a | Typically, this will be a test case method. |
---|
736 | n/a | :param peer: The client (host, port) tuple. |
---|
737 | n/a | :param mailfrom: The address of the sender. |
---|
738 | n/a | :param rcpttos: The addresses of the recipients. |
---|
739 | n/a | :param data: The message. |
---|
740 | n/a | """ |
---|
741 | n/a | self._handler(peer, mailfrom, rcpttos, data) |
---|
742 | n/a | |
---|
743 | n/a | def start(self): |
---|
744 | n/a | """ |
---|
745 | n/a | Start the server running on a separate daemon thread. |
---|
746 | n/a | """ |
---|
747 | n/a | self._thread = t = threading.Thread(target=self.serve_forever, |
---|
748 | n/a | args=(self.poll_interval,)) |
---|
749 | n/a | t.setDaemon(True) |
---|
750 | n/a | t.start() |
---|
751 | n/a | |
---|
752 | n/a | def serve_forever(self, poll_interval): |
---|
753 | n/a | """ |
---|
754 | n/a | Run the :mod:`asyncore` loop until normal termination |
---|
755 | n/a | conditions arise. |
---|
756 | n/a | :param poll_interval: The interval, in seconds, used in the underlying |
---|
757 | n/a | :func:`select` or :func:`poll` call by |
---|
758 | n/a | :func:`asyncore.loop`. |
---|
759 | n/a | """ |
---|
760 | n/a | try: |
---|
761 | n/a | asyncore.loop(poll_interval, map=self._map) |
---|
762 | n/a | except OSError: |
---|
763 | n/a | # On FreeBSD 8, closing the server repeatably |
---|
764 | n/a | # raises this error. We swallow it if the |
---|
765 | n/a | # server has been closed. |
---|
766 | n/a | if self.connected or self.accepting: |
---|
767 | n/a | raise |
---|
768 | n/a | |
---|
769 | n/a | def stop(self, timeout=None): |
---|
770 | n/a | """ |
---|
771 | n/a | Stop the thread by closing the server instance. |
---|
772 | n/a | Wait for the server thread to terminate. |
---|
773 | n/a | |
---|
774 | n/a | :param timeout: How long to wait for the server thread |
---|
775 | n/a | to terminate. |
---|
776 | n/a | """ |
---|
777 | n/a | self.close() |
---|
778 | n/a | self._thread.join(timeout) |
---|
779 | n/a | self._thread = None |
---|
780 | n/a | |
---|
781 | n/a | class ControlMixin(object): |
---|
782 | n/a | """ |
---|
783 | n/a | This mixin is used to start a server on a separate thread, and |
---|
784 | n/a | shut it down programmatically. Request handling is simplified - instead |
---|
785 | n/a | of needing to derive a suitable RequestHandler subclass, you just |
---|
786 | n/a | provide a callable which will be passed each received request to be |
---|
787 | n/a | processed. |
---|
788 | n/a | |
---|
789 | n/a | :param handler: A handler callable which will be called with a |
---|
790 | n/a | single parameter - the request - in order to |
---|
791 | n/a | process the request. This handler is called on the |
---|
792 | n/a | server thread, effectively meaning that requests are |
---|
793 | n/a | processed serially. While not quite Web scale ;-), |
---|
794 | n/a | this should be fine for testing applications. |
---|
795 | n/a | :param poll_interval: The polling interval in seconds. |
---|
796 | n/a | """ |
---|
797 | n/a | def __init__(self, handler, poll_interval): |
---|
798 | n/a | self._thread = None |
---|
799 | n/a | self.poll_interval = poll_interval |
---|
800 | n/a | self._handler = handler |
---|
801 | n/a | self.ready = threading.Event() |
---|
802 | n/a | |
---|
803 | n/a | def start(self): |
---|
804 | n/a | """ |
---|
805 | n/a | Create a daemon thread to run the server, and start it. |
---|
806 | n/a | """ |
---|
807 | n/a | self._thread = t = threading.Thread(target=self.serve_forever, |
---|
808 | n/a | args=(self.poll_interval,)) |
---|
809 | n/a | t.setDaemon(True) |
---|
810 | n/a | t.start() |
---|
811 | n/a | |
---|
812 | n/a | def serve_forever(self, poll_interval): |
---|
813 | n/a | """ |
---|
814 | n/a | Run the server. Set the ready flag before entering the |
---|
815 | n/a | service loop. |
---|
816 | n/a | """ |
---|
817 | n/a | self.ready.set() |
---|
818 | n/a | super(ControlMixin, self).serve_forever(poll_interval) |
---|
819 | n/a | |
---|
820 | n/a | def stop(self, timeout=None): |
---|
821 | n/a | """ |
---|
822 | n/a | Tell the server thread to stop, and wait for it to do so. |
---|
823 | n/a | |
---|
824 | n/a | :param timeout: How long to wait for the server thread |
---|
825 | n/a | to terminate. |
---|
826 | n/a | """ |
---|
827 | n/a | self.shutdown() |
---|
828 | n/a | if self._thread is not None: |
---|
829 | n/a | self._thread.join(timeout) |
---|
830 | n/a | self._thread = None |
---|
831 | n/a | self.server_close() |
---|
832 | n/a | self.ready.clear() |
---|
833 | n/a | |
---|
834 | n/a | class TestHTTPServer(ControlMixin, HTTPServer): |
---|
835 | n/a | """ |
---|
836 | n/a | An HTTP server which is controllable using :class:`ControlMixin`. |
---|
837 | n/a | |
---|
838 | n/a | :param addr: A tuple with the IP address and port to listen on. |
---|
839 | n/a | :param handler: A handler callable which will be called with a |
---|
840 | n/a | single parameter - the request - in order to |
---|
841 | n/a | process the request. |
---|
842 | n/a | :param poll_interval: The polling interval in seconds. |
---|
843 | n/a | :param log: Pass ``True`` to enable log messages. |
---|
844 | n/a | """ |
---|
845 | n/a | def __init__(self, addr, handler, poll_interval=0.5, |
---|
846 | n/a | log=False, sslctx=None): |
---|
847 | n/a | class DelegatingHTTPRequestHandler(BaseHTTPRequestHandler): |
---|
848 | n/a | def __getattr__(self, name, default=None): |
---|
849 | n/a | if name.startswith('do_'): |
---|
850 | n/a | return self.process_request |
---|
851 | n/a | raise AttributeError(name) |
---|
852 | n/a | |
---|
853 | n/a | def process_request(self): |
---|
854 | n/a | self.server._handler(self) |
---|
855 | n/a | |
---|
856 | n/a | def log_message(self, format, *args): |
---|
857 | n/a | if log: |
---|
858 | n/a | super(DelegatingHTTPRequestHandler, |
---|
859 | n/a | self).log_message(format, *args) |
---|
860 | n/a | HTTPServer.__init__(self, addr, DelegatingHTTPRequestHandler) |
---|
861 | n/a | ControlMixin.__init__(self, handler, poll_interval) |
---|
862 | n/a | self.sslctx = sslctx |
---|
863 | n/a | |
---|
864 | n/a | def get_request(self): |
---|
865 | n/a | try: |
---|
866 | n/a | sock, addr = self.socket.accept() |
---|
867 | n/a | if self.sslctx: |
---|
868 | n/a | sock = self.sslctx.wrap_socket(sock, server_side=True) |
---|
869 | n/a | except OSError as e: |
---|
870 | n/a | # socket errors are silenced by the caller, print them here |
---|
871 | n/a | sys.stderr.write("Got an error:\n%s\n" % e) |
---|
872 | n/a | raise |
---|
873 | n/a | return sock, addr |
---|
874 | n/a | |
---|
875 | n/a | class TestTCPServer(ControlMixin, ThreadingTCPServer): |
---|
876 | n/a | """ |
---|
877 | n/a | A TCP server which is controllable using :class:`ControlMixin`. |
---|
878 | n/a | |
---|
879 | n/a | :param addr: A tuple with the IP address and port to listen on. |
---|
880 | n/a | :param handler: A handler callable which will be called with a single |
---|
881 | n/a | parameter - the request - in order to process the request. |
---|
882 | n/a | :param poll_interval: The polling interval in seconds. |
---|
883 | n/a | :bind_and_activate: If True (the default), binds the server and starts it |
---|
884 | n/a | listening. If False, you need to call |
---|
885 | n/a | :meth:`server_bind` and :meth:`server_activate` at |
---|
886 | n/a | some later time before calling :meth:`start`, so that |
---|
887 | n/a | the server will set up the socket and listen on it. |
---|
888 | n/a | """ |
---|
889 | n/a | |
---|
890 | n/a | allow_reuse_address = True |
---|
891 | n/a | |
---|
892 | n/a | def __init__(self, addr, handler, poll_interval=0.5, |
---|
893 | n/a | bind_and_activate=True): |
---|
894 | n/a | class DelegatingTCPRequestHandler(StreamRequestHandler): |
---|
895 | n/a | |
---|
896 | n/a | def handle(self): |
---|
897 | n/a | self.server._handler(self) |
---|
898 | n/a | ThreadingTCPServer.__init__(self, addr, DelegatingTCPRequestHandler, |
---|
899 | n/a | bind_and_activate) |
---|
900 | n/a | ControlMixin.__init__(self, handler, poll_interval) |
---|
901 | n/a | |
---|
902 | n/a | def server_bind(self): |
---|
903 | n/a | super(TestTCPServer, self).server_bind() |
---|
904 | n/a | self.port = self.socket.getsockname()[1] |
---|
905 | n/a | |
---|
906 | n/a | class TestUDPServer(ControlMixin, ThreadingUDPServer): |
---|
907 | n/a | """ |
---|
908 | n/a | A UDP server which is controllable using :class:`ControlMixin`. |
---|
909 | n/a | |
---|
910 | n/a | :param addr: A tuple with the IP address and port to listen on. |
---|
911 | n/a | :param handler: A handler callable which will be called with a |
---|
912 | n/a | single parameter - the request - in order to |
---|
913 | n/a | process the request. |
---|
914 | n/a | :param poll_interval: The polling interval for shutdown requests, |
---|
915 | n/a | in seconds. |
---|
916 | n/a | :bind_and_activate: If True (the default), binds the server and |
---|
917 | n/a | starts it listening. If False, you need to |
---|
918 | n/a | call :meth:`server_bind` and |
---|
919 | n/a | :meth:`server_activate` at some later time |
---|
920 | n/a | before calling :meth:`start`, so that the server will |
---|
921 | n/a | set up the socket and listen on it. |
---|
922 | n/a | """ |
---|
923 | n/a | def __init__(self, addr, handler, poll_interval=0.5, |
---|
924 | n/a | bind_and_activate=True): |
---|
925 | n/a | class DelegatingUDPRequestHandler(DatagramRequestHandler): |
---|
926 | n/a | |
---|
927 | n/a | def handle(self): |
---|
928 | n/a | self.server._handler(self) |
---|
929 | n/a | |
---|
930 | n/a | def finish(self): |
---|
931 | n/a | data = self.wfile.getvalue() |
---|
932 | n/a | if data: |
---|
933 | n/a | try: |
---|
934 | n/a | super(DelegatingUDPRequestHandler, self).finish() |
---|
935 | n/a | except OSError: |
---|
936 | n/a | if not self.server._closed: |
---|
937 | n/a | raise |
---|
938 | n/a | |
---|
939 | n/a | ThreadingUDPServer.__init__(self, addr, |
---|
940 | n/a | DelegatingUDPRequestHandler, |
---|
941 | n/a | bind_and_activate) |
---|
942 | n/a | ControlMixin.__init__(self, handler, poll_interval) |
---|
943 | n/a | self._closed = False |
---|
944 | n/a | |
---|
945 | n/a | def server_bind(self): |
---|
946 | n/a | super(TestUDPServer, self).server_bind() |
---|
947 | n/a | self.port = self.socket.getsockname()[1] |
---|
948 | n/a | |
---|
949 | n/a | def server_close(self): |
---|
950 | n/a | super(TestUDPServer, self).server_close() |
---|
951 | n/a | self._closed = True |
---|
952 | n/a | |
---|
953 | n/a | if hasattr(socket, "AF_UNIX"): |
---|
954 | n/a | class TestUnixStreamServer(TestTCPServer): |
---|
955 | n/a | address_family = socket.AF_UNIX |
---|
956 | n/a | |
---|
957 | n/a | class TestUnixDatagramServer(TestUDPServer): |
---|
958 | n/a | address_family = socket.AF_UNIX |
---|
959 | n/a | |
---|
960 | n/a | # - end of server_helper section |
---|
961 | n/a | |
---|
962 | n/a | @unittest.skipUnless(threading, 'Threading required for this test.') |
---|
963 | n/a | class SMTPHandlerTest(BaseTest): |
---|
964 | n/a | TIMEOUT = 8.0 |
---|
965 | n/a | def test_basic(self): |
---|
966 | n/a | sockmap = {} |
---|
967 | n/a | server = TestSMTPServer((support.HOST, 0), self.process_message, 0.001, |
---|
968 | n/a | sockmap) |
---|
969 | n/a | server.start() |
---|
970 | n/a | addr = (support.HOST, server.port) |
---|
971 | n/a | h = logging.handlers.SMTPHandler(addr, 'me', 'you', 'Log', |
---|
972 | n/a | timeout=self.TIMEOUT) |
---|
973 | n/a | self.assertEqual(h.toaddrs, ['you']) |
---|
974 | n/a | self.messages = [] |
---|
975 | n/a | r = logging.makeLogRecord({'msg': 'Hello \u2713'}) |
---|
976 | n/a | self.handled = threading.Event() |
---|
977 | n/a | h.handle(r) |
---|
978 | n/a | self.handled.wait(self.TIMEOUT) # 14314: don't wait forever |
---|
979 | n/a | server.stop() |
---|
980 | n/a | self.assertTrue(self.handled.is_set()) |
---|
981 | n/a | self.assertEqual(len(self.messages), 1) |
---|
982 | n/a | peer, mailfrom, rcpttos, data = self.messages[0] |
---|
983 | n/a | self.assertEqual(mailfrom, 'me') |
---|
984 | n/a | self.assertEqual(rcpttos, ['you']) |
---|
985 | n/a | self.assertIn('\nSubject: Log\n', data) |
---|
986 | n/a | self.assertTrue(data.endswith('\n\nHello \u2713')) |
---|
987 | n/a | h.close() |
---|
988 | n/a | |
---|
989 | n/a | def process_message(self, *args): |
---|
990 | n/a | self.messages.append(args) |
---|
991 | n/a | self.handled.set() |
---|
992 | n/a | |
---|
993 | n/a | class MemoryHandlerTest(BaseTest): |
---|
994 | n/a | |
---|
995 | n/a | """Tests for the MemoryHandler.""" |
---|
996 | n/a | |
---|
997 | n/a | # Do not bother with a logger name group. |
---|
998 | n/a | expected_log_pat = r"^[\w.]+ -> (\w+): (\d+)$" |
---|
999 | n/a | |
---|
1000 | n/a | def setUp(self): |
---|
1001 | n/a | BaseTest.setUp(self) |
---|
1002 | n/a | self.mem_hdlr = logging.handlers.MemoryHandler(10, logging.WARNING, |
---|
1003 | n/a | self.root_hdlr) |
---|
1004 | n/a | self.mem_logger = logging.getLogger('mem') |
---|
1005 | n/a | self.mem_logger.propagate = 0 |
---|
1006 | n/a | self.mem_logger.addHandler(self.mem_hdlr) |
---|
1007 | n/a | |
---|
1008 | n/a | def tearDown(self): |
---|
1009 | n/a | self.mem_hdlr.close() |
---|
1010 | n/a | BaseTest.tearDown(self) |
---|
1011 | n/a | |
---|
1012 | n/a | def test_flush(self): |
---|
1013 | n/a | # The memory handler flushes to its target handler based on specific |
---|
1014 | n/a | # criteria (message count and message level). |
---|
1015 | n/a | self.mem_logger.debug(self.next_message()) |
---|
1016 | n/a | self.assert_log_lines([]) |
---|
1017 | n/a | self.mem_logger.info(self.next_message()) |
---|
1018 | n/a | self.assert_log_lines([]) |
---|
1019 | n/a | # This will flush because the level is >= logging.WARNING |
---|
1020 | n/a | self.mem_logger.warning(self.next_message()) |
---|
1021 | n/a | lines = [ |
---|
1022 | n/a | ('DEBUG', '1'), |
---|
1023 | n/a | ('INFO', '2'), |
---|
1024 | n/a | ('WARNING', '3'), |
---|
1025 | n/a | ] |
---|
1026 | n/a | self.assert_log_lines(lines) |
---|
1027 | n/a | for n in (4, 14): |
---|
1028 | n/a | for i in range(9): |
---|
1029 | n/a | self.mem_logger.debug(self.next_message()) |
---|
1030 | n/a | self.assert_log_lines(lines) |
---|
1031 | n/a | # This will flush because it's the 10th message since the last |
---|
1032 | n/a | # flush. |
---|
1033 | n/a | self.mem_logger.debug(self.next_message()) |
---|
1034 | n/a | lines = lines + [('DEBUG', str(i)) for i in range(n, n + 10)] |
---|
1035 | n/a | self.assert_log_lines(lines) |
---|
1036 | n/a | |
---|
1037 | n/a | self.mem_logger.debug(self.next_message()) |
---|
1038 | n/a | self.assert_log_lines(lines) |
---|
1039 | n/a | |
---|
1040 | n/a | def test_flush_on_close(self): |
---|
1041 | n/a | """ |
---|
1042 | n/a | Test that the flush-on-close configuration works as expected. |
---|
1043 | n/a | """ |
---|
1044 | n/a | self.mem_logger.debug(self.next_message()) |
---|
1045 | n/a | self.assert_log_lines([]) |
---|
1046 | n/a | self.mem_logger.info(self.next_message()) |
---|
1047 | n/a | self.assert_log_lines([]) |
---|
1048 | n/a | self.mem_logger.removeHandler(self.mem_hdlr) |
---|
1049 | n/a | # Default behaviour is to flush on close. Check that it happens. |
---|
1050 | n/a | self.mem_hdlr.close() |
---|
1051 | n/a | lines = [ |
---|
1052 | n/a | ('DEBUG', '1'), |
---|
1053 | n/a | ('INFO', '2'), |
---|
1054 | n/a | ] |
---|
1055 | n/a | self.assert_log_lines(lines) |
---|
1056 | n/a | # Now configure for flushing not to be done on close. |
---|
1057 | n/a | self.mem_hdlr = logging.handlers.MemoryHandler(10, logging.WARNING, |
---|
1058 | n/a | self.root_hdlr, |
---|
1059 | n/a | False) |
---|
1060 | n/a | self.mem_logger.addHandler(self.mem_hdlr) |
---|
1061 | n/a | self.mem_logger.debug(self.next_message()) |
---|
1062 | n/a | self.assert_log_lines(lines) # no change |
---|
1063 | n/a | self.mem_logger.info(self.next_message()) |
---|
1064 | n/a | self.assert_log_lines(lines) # no change |
---|
1065 | n/a | self.mem_logger.removeHandler(self.mem_hdlr) |
---|
1066 | n/a | self.mem_hdlr.close() |
---|
1067 | n/a | # assert that no new lines have been added |
---|
1068 | n/a | self.assert_log_lines(lines) # no change |
---|
1069 | n/a | |
---|
1070 | n/a | |
---|
1071 | n/a | class ExceptionFormatter(logging.Formatter): |
---|
1072 | n/a | """A special exception formatter.""" |
---|
1073 | n/a | def formatException(self, ei): |
---|
1074 | n/a | return "Got a [%s]" % ei[0].__name__ |
---|
1075 | n/a | |
---|
1076 | n/a | |
---|
1077 | n/a | class ConfigFileTest(BaseTest): |
---|
1078 | n/a | |
---|
1079 | n/a | """Reading logging config from a .ini-style config file.""" |
---|
1080 | n/a | |
---|
1081 | n/a | expected_log_pat = r"^(\w+) \+\+ (\w+)$" |
---|
1082 | n/a | |
---|
1083 | n/a | # config0 is a standard configuration. |
---|
1084 | n/a | config0 = """ |
---|
1085 | n/a | [loggers] |
---|
1086 | n/a | keys=root |
---|
1087 | n/a | |
---|
1088 | n/a | [handlers] |
---|
1089 | n/a | keys=hand1 |
---|
1090 | n/a | |
---|
1091 | n/a | [formatters] |
---|
1092 | n/a | keys=form1 |
---|
1093 | n/a | |
---|
1094 | n/a | [logger_root] |
---|
1095 | n/a | level=WARNING |
---|
1096 | n/a | handlers=hand1 |
---|
1097 | n/a | |
---|
1098 | n/a | [handler_hand1] |
---|
1099 | n/a | class=StreamHandler |
---|
1100 | n/a | level=NOTSET |
---|
1101 | n/a | formatter=form1 |
---|
1102 | n/a | args=(sys.stdout,) |
---|
1103 | n/a | |
---|
1104 | n/a | [formatter_form1] |
---|
1105 | n/a | format=%(levelname)s ++ %(message)s |
---|
1106 | n/a | datefmt= |
---|
1107 | n/a | """ |
---|
1108 | n/a | |
---|
1109 | n/a | # config1 adds a little to the standard configuration. |
---|
1110 | n/a | config1 = """ |
---|
1111 | n/a | [loggers] |
---|
1112 | n/a | keys=root,parser |
---|
1113 | n/a | |
---|
1114 | n/a | [handlers] |
---|
1115 | n/a | keys=hand1 |
---|
1116 | n/a | |
---|
1117 | n/a | [formatters] |
---|
1118 | n/a | keys=form1 |
---|
1119 | n/a | |
---|
1120 | n/a | [logger_root] |
---|
1121 | n/a | level=WARNING |
---|
1122 | n/a | handlers= |
---|
1123 | n/a | |
---|
1124 | n/a | [logger_parser] |
---|
1125 | n/a | level=DEBUG |
---|
1126 | n/a | handlers=hand1 |
---|
1127 | n/a | propagate=1 |
---|
1128 | n/a | qualname=compiler.parser |
---|
1129 | n/a | |
---|
1130 | n/a | [handler_hand1] |
---|
1131 | n/a | class=StreamHandler |
---|
1132 | n/a | level=NOTSET |
---|
1133 | n/a | formatter=form1 |
---|
1134 | n/a | args=(sys.stdout,) |
---|
1135 | n/a | |
---|
1136 | n/a | [formatter_form1] |
---|
1137 | n/a | format=%(levelname)s ++ %(message)s |
---|
1138 | n/a | datefmt= |
---|
1139 | n/a | """ |
---|
1140 | n/a | |
---|
1141 | n/a | # config1a moves the handler to the root. |
---|
1142 | n/a | config1a = """ |
---|
1143 | n/a | [loggers] |
---|
1144 | n/a | keys=root,parser |
---|
1145 | n/a | |
---|
1146 | n/a | [handlers] |
---|
1147 | n/a | keys=hand1 |
---|
1148 | n/a | |
---|
1149 | n/a | [formatters] |
---|
1150 | n/a | keys=form1 |
---|
1151 | n/a | |
---|
1152 | n/a | [logger_root] |
---|
1153 | n/a | level=WARNING |
---|
1154 | n/a | handlers=hand1 |
---|
1155 | n/a | |
---|
1156 | n/a | [logger_parser] |
---|
1157 | n/a | level=DEBUG |
---|
1158 | n/a | handlers= |
---|
1159 | n/a | propagate=1 |
---|
1160 | n/a | qualname=compiler.parser |
---|
1161 | n/a | |
---|
1162 | n/a | [handler_hand1] |
---|
1163 | n/a | class=StreamHandler |
---|
1164 | n/a | level=NOTSET |
---|
1165 | n/a | formatter=form1 |
---|
1166 | n/a | args=(sys.stdout,) |
---|
1167 | n/a | |
---|
1168 | n/a | [formatter_form1] |
---|
1169 | n/a | format=%(levelname)s ++ %(message)s |
---|
1170 | n/a | datefmt= |
---|
1171 | n/a | """ |
---|
1172 | n/a | |
---|
1173 | n/a | # config2 has a subtle configuration error that should be reported |
---|
1174 | n/a | config2 = config1.replace("sys.stdout", "sys.stbout") |
---|
1175 | n/a | |
---|
1176 | n/a | # config3 has a less subtle configuration error |
---|
1177 | n/a | config3 = config1.replace("formatter=form1", "formatter=misspelled_name") |
---|
1178 | n/a | |
---|
1179 | n/a | # config4 specifies a custom formatter class to be loaded |
---|
1180 | n/a | config4 = """ |
---|
1181 | n/a | [loggers] |
---|
1182 | n/a | keys=root |
---|
1183 | n/a | |
---|
1184 | n/a | [handlers] |
---|
1185 | n/a | keys=hand1 |
---|
1186 | n/a | |
---|
1187 | n/a | [formatters] |
---|
1188 | n/a | keys=form1 |
---|
1189 | n/a | |
---|
1190 | n/a | [logger_root] |
---|
1191 | n/a | level=NOTSET |
---|
1192 | n/a | handlers=hand1 |
---|
1193 | n/a | |
---|
1194 | n/a | [handler_hand1] |
---|
1195 | n/a | class=StreamHandler |
---|
1196 | n/a | level=NOTSET |
---|
1197 | n/a | formatter=form1 |
---|
1198 | n/a | args=(sys.stdout,) |
---|
1199 | n/a | |
---|
1200 | n/a | [formatter_form1] |
---|
1201 | n/a | class=""" + __name__ + """.ExceptionFormatter |
---|
1202 | n/a | format=%(levelname)s:%(name)s:%(message)s |
---|
1203 | n/a | datefmt= |
---|
1204 | n/a | """ |
---|
1205 | n/a | |
---|
1206 | n/a | # config5 specifies a custom handler class to be loaded |
---|
1207 | n/a | config5 = config1.replace('class=StreamHandler', 'class=logging.StreamHandler') |
---|
1208 | n/a | |
---|
1209 | n/a | # config6 uses ', ' delimiters in the handlers and formatters sections |
---|
1210 | n/a | config6 = """ |
---|
1211 | n/a | [loggers] |
---|
1212 | n/a | keys=root,parser |
---|
1213 | n/a | |
---|
1214 | n/a | [handlers] |
---|
1215 | n/a | keys=hand1, hand2 |
---|
1216 | n/a | |
---|
1217 | n/a | [formatters] |
---|
1218 | n/a | keys=form1, form2 |
---|
1219 | n/a | |
---|
1220 | n/a | [logger_root] |
---|
1221 | n/a | level=WARNING |
---|
1222 | n/a | handlers= |
---|
1223 | n/a | |
---|
1224 | n/a | [logger_parser] |
---|
1225 | n/a | level=DEBUG |
---|
1226 | n/a | handlers=hand1 |
---|
1227 | n/a | propagate=1 |
---|
1228 | n/a | qualname=compiler.parser |
---|
1229 | n/a | |
---|
1230 | n/a | [handler_hand1] |
---|
1231 | n/a | class=StreamHandler |
---|
1232 | n/a | level=NOTSET |
---|
1233 | n/a | formatter=form1 |
---|
1234 | n/a | args=(sys.stdout,) |
---|
1235 | n/a | |
---|
1236 | n/a | [handler_hand2] |
---|
1237 | n/a | class=StreamHandler |
---|
1238 | n/a | level=NOTSET |
---|
1239 | n/a | formatter=form1 |
---|
1240 | n/a | args=(sys.stderr,) |
---|
1241 | n/a | |
---|
1242 | n/a | [formatter_form1] |
---|
1243 | n/a | format=%(levelname)s ++ %(message)s |
---|
1244 | n/a | datefmt= |
---|
1245 | n/a | |
---|
1246 | n/a | [formatter_form2] |
---|
1247 | n/a | format=%(message)s |
---|
1248 | n/a | datefmt= |
---|
1249 | n/a | """ |
---|
1250 | n/a | |
---|
1251 | n/a | # config7 adds a compiler logger. |
---|
1252 | n/a | config7 = """ |
---|
1253 | n/a | [loggers] |
---|
1254 | n/a | keys=root,parser,compiler |
---|
1255 | n/a | |
---|
1256 | n/a | [handlers] |
---|
1257 | n/a | keys=hand1 |
---|
1258 | n/a | |
---|
1259 | n/a | [formatters] |
---|
1260 | n/a | keys=form1 |
---|
1261 | n/a | |
---|
1262 | n/a | [logger_root] |
---|
1263 | n/a | level=WARNING |
---|
1264 | n/a | handlers=hand1 |
---|
1265 | n/a | |
---|
1266 | n/a | [logger_compiler] |
---|
1267 | n/a | level=DEBUG |
---|
1268 | n/a | handlers= |
---|
1269 | n/a | propagate=1 |
---|
1270 | n/a | qualname=compiler |
---|
1271 | n/a | |
---|
1272 | n/a | [logger_parser] |
---|
1273 | n/a | level=DEBUG |
---|
1274 | n/a | handlers= |
---|
1275 | n/a | propagate=1 |
---|
1276 | n/a | qualname=compiler.parser |
---|
1277 | n/a | |
---|
1278 | n/a | [handler_hand1] |
---|
1279 | n/a | class=StreamHandler |
---|
1280 | n/a | level=NOTSET |
---|
1281 | n/a | formatter=form1 |
---|
1282 | n/a | args=(sys.stdout,) |
---|
1283 | n/a | |
---|
1284 | n/a | [formatter_form1] |
---|
1285 | n/a | format=%(levelname)s ++ %(message)s |
---|
1286 | n/a | datefmt= |
---|
1287 | n/a | """ |
---|
1288 | n/a | |
---|
1289 | n/a | disable_test = """ |
---|
1290 | n/a | [loggers] |
---|
1291 | n/a | keys=root |
---|
1292 | n/a | |
---|
1293 | n/a | [handlers] |
---|
1294 | n/a | keys=screen |
---|
1295 | n/a | |
---|
1296 | n/a | [formatters] |
---|
1297 | n/a | keys= |
---|
1298 | n/a | |
---|
1299 | n/a | [logger_root] |
---|
1300 | n/a | level=DEBUG |
---|
1301 | n/a | handlers=screen |
---|
1302 | n/a | |
---|
1303 | n/a | [handler_screen] |
---|
1304 | n/a | level=DEBUG |
---|
1305 | n/a | class=StreamHandler |
---|
1306 | n/a | args=(sys.stdout,) |
---|
1307 | n/a | formatter= |
---|
1308 | n/a | """ |
---|
1309 | n/a | |
---|
1310 | n/a | def apply_config(self, conf, **kwargs): |
---|
1311 | n/a | file = io.StringIO(textwrap.dedent(conf)) |
---|
1312 | n/a | logging.config.fileConfig(file, **kwargs) |
---|
1313 | n/a | |
---|
1314 | n/a | def test_config0_ok(self): |
---|
1315 | n/a | # A simple config file which overrides the default settings. |
---|
1316 | n/a | with support.captured_stdout() as output: |
---|
1317 | n/a | self.apply_config(self.config0) |
---|
1318 | n/a | logger = logging.getLogger() |
---|
1319 | n/a | # Won't output anything |
---|
1320 | n/a | logger.info(self.next_message()) |
---|
1321 | n/a | # Outputs a message |
---|
1322 | n/a | logger.error(self.next_message()) |
---|
1323 | n/a | self.assert_log_lines([ |
---|
1324 | n/a | ('ERROR', '2'), |
---|
1325 | n/a | ], stream=output) |
---|
1326 | n/a | # Original logger output is empty. |
---|
1327 | n/a | self.assert_log_lines([]) |
---|
1328 | n/a | |
---|
1329 | n/a | def test_config0_using_cp_ok(self): |
---|
1330 | n/a | # A simple config file which overrides the default settings. |
---|
1331 | n/a | with support.captured_stdout() as output: |
---|
1332 | n/a | file = io.StringIO(textwrap.dedent(self.config0)) |
---|
1333 | n/a | cp = configparser.ConfigParser() |
---|
1334 | n/a | cp.read_file(file) |
---|
1335 | n/a | logging.config.fileConfig(cp) |
---|
1336 | n/a | logger = logging.getLogger() |
---|
1337 | n/a | # Won't output anything |
---|
1338 | n/a | logger.info(self.next_message()) |
---|
1339 | n/a | # Outputs a message |
---|
1340 | n/a | logger.error(self.next_message()) |
---|
1341 | n/a | self.assert_log_lines([ |
---|
1342 | n/a | ('ERROR', '2'), |
---|
1343 | n/a | ], stream=output) |
---|
1344 | n/a | # Original logger output is empty. |
---|
1345 | n/a | self.assert_log_lines([]) |
---|
1346 | n/a | |
---|
1347 | n/a | def test_config1_ok(self, config=config1): |
---|
1348 | n/a | # A config file defining a sub-parser as well. |
---|
1349 | n/a | with support.captured_stdout() as output: |
---|
1350 | n/a | self.apply_config(config) |
---|
1351 | n/a | logger = logging.getLogger("compiler.parser") |
---|
1352 | n/a | # Both will output a message |
---|
1353 | n/a | logger.info(self.next_message()) |
---|
1354 | n/a | logger.error(self.next_message()) |
---|
1355 | n/a | self.assert_log_lines([ |
---|
1356 | n/a | ('INFO', '1'), |
---|
1357 | n/a | ('ERROR', '2'), |
---|
1358 | n/a | ], stream=output) |
---|
1359 | n/a | # Original logger output is empty. |
---|
1360 | n/a | self.assert_log_lines([]) |
---|
1361 | n/a | |
---|
1362 | n/a | def test_config2_failure(self): |
---|
1363 | n/a | # A simple config file which overrides the default settings. |
---|
1364 | n/a | self.assertRaises(Exception, self.apply_config, self.config2) |
---|
1365 | n/a | |
---|
1366 | n/a | def test_config3_failure(self): |
---|
1367 | n/a | # A simple config file which overrides the default settings. |
---|
1368 | n/a | self.assertRaises(Exception, self.apply_config, self.config3) |
---|
1369 | n/a | |
---|
1370 | n/a | def test_config4_ok(self): |
---|
1371 | n/a | # A config file specifying a custom formatter class. |
---|
1372 | n/a | with support.captured_stdout() as output: |
---|
1373 | n/a | self.apply_config(self.config4) |
---|
1374 | n/a | logger = logging.getLogger() |
---|
1375 | n/a | try: |
---|
1376 | n/a | raise RuntimeError() |
---|
1377 | n/a | except RuntimeError: |
---|
1378 | n/a | logging.exception("just testing") |
---|
1379 | n/a | sys.stdout.seek(0) |
---|
1380 | n/a | self.assertEqual(output.getvalue(), |
---|
1381 | n/a | "ERROR:root:just testing\nGot a [RuntimeError]\n") |
---|
1382 | n/a | # Original logger output is empty |
---|
1383 | n/a | self.assert_log_lines([]) |
---|
1384 | n/a | |
---|
1385 | n/a | def test_config5_ok(self): |
---|
1386 | n/a | self.test_config1_ok(config=self.config5) |
---|
1387 | n/a | |
---|
1388 | n/a | def test_config6_ok(self): |
---|
1389 | n/a | self.test_config1_ok(config=self.config6) |
---|
1390 | n/a | |
---|
1391 | n/a | def test_config7_ok(self): |
---|
1392 | n/a | with support.captured_stdout() as output: |
---|
1393 | n/a | self.apply_config(self.config1a) |
---|
1394 | n/a | logger = logging.getLogger("compiler.parser") |
---|
1395 | n/a | # See issue #11424. compiler-hyphenated sorts |
---|
1396 | n/a | # between compiler and compiler.xyz and this |
---|
1397 | n/a | # was preventing compiler.xyz from being included |
---|
1398 | n/a | # in the child loggers of compiler because of an |
---|
1399 | n/a | # overzealous loop termination condition. |
---|
1400 | n/a | hyphenated = logging.getLogger('compiler-hyphenated') |
---|
1401 | n/a | # All will output a message |
---|
1402 | n/a | logger.info(self.next_message()) |
---|
1403 | n/a | logger.error(self.next_message()) |
---|
1404 | n/a | hyphenated.critical(self.next_message()) |
---|
1405 | n/a | self.assert_log_lines([ |
---|
1406 | n/a | ('INFO', '1'), |
---|
1407 | n/a | ('ERROR', '2'), |
---|
1408 | n/a | ('CRITICAL', '3'), |
---|
1409 | n/a | ], stream=output) |
---|
1410 | n/a | # Original logger output is empty. |
---|
1411 | n/a | self.assert_log_lines([]) |
---|
1412 | n/a | with support.captured_stdout() as output: |
---|
1413 | n/a | self.apply_config(self.config7) |
---|
1414 | n/a | logger = logging.getLogger("compiler.parser") |
---|
1415 | n/a | self.assertFalse(logger.disabled) |
---|
1416 | n/a | # Both will output a message |
---|
1417 | n/a | logger.info(self.next_message()) |
---|
1418 | n/a | logger.error(self.next_message()) |
---|
1419 | n/a | logger = logging.getLogger("compiler.lexer") |
---|
1420 | n/a | # Both will output a message |
---|
1421 | n/a | logger.info(self.next_message()) |
---|
1422 | n/a | logger.error(self.next_message()) |
---|
1423 | n/a | # Will not appear |
---|
1424 | n/a | hyphenated.critical(self.next_message()) |
---|
1425 | n/a | self.assert_log_lines([ |
---|
1426 | n/a | ('INFO', '4'), |
---|
1427 | n/a | ('ERROR', '5'), |
---|
1428 | n/a | ('INFO', '6'), |
---|
1429 | n/a | ('ERROR', '7'), |
---|
1430 | n/a | ], stream=output) |
---|
1431 | n/a | # Original logger output is empty. |
---|
1432 | n/a | self.assert_log_lines([]) |
---|
1433 | n/a | |
---|
1434 | n/a | def test_logger_disabling(self): |
---|
1435 | n/a | self.apply_config(self.disable_test) |
---|
1436 | n/a | logger = logging.getLogger('some_pristine_logger') |
---|
1437 | n/a | self.assertFalse(logger.disabled) |
---|
1438 | n/a | self.apply_config(self.disable_test) |
---|
1439 | n/a | self.assertTrue(logger.disabled) |
---|
1440 | n/a | self.apply_config(self.disable_test, disable_existing_loggers=False) |
---|
1441 | n/a | self.assertFalse(logger.disabled) |
---|
1442 | n/a | |
---|
1443 | n/a | |
---|
1444 | n/a | @unittest.skipUnless(threading, 'Threading required for this test.') |
---|
1445 | n/a | class SocketHandlerTest(BaseTest): |
---|
1446 | n/a | |
---|
1447 | n/a | """Test for SocketHandler objects.""" |
---|
1448 | n/a | |
---|
1449 | n/a | if threading: |
---|
1450 | n/a | server_class = TestTCPServer |
---|
1451 | n/a | address = ('localhost', 0) |
---|
1452 | n/a | |
---|
1453 | n/a | def setUp(self): |
---|
1454 | n/a | """Set up a TCP server to receive log messages, and a SocketHandler |
---|
1455 | n/a | pointing to that server's address and port.""" |
---|
1456 | n/a | BaseTest.setUp(self) |
---|
1457 | n/a | # Issue #29177: deal with errors that happen during setup |
---|
1458 | n/a | self.server = self.sock_hdlr = self.server_exception = None |
---|
1459 | n/a | try: |
---|
1460 | n/a | self.server = server = self.server_class(self.address, |
---|
1461 | n/a | self.handle_socket, 0.01) |
---|
1462 | n/a | server.start() |
---|
1463 | n/a | # Uncomment next line to test error recovery in setUp() |
---|
1464 | n/a | # raise OSError('dummy error raised') |
---|
1465 | n/a | except OSError as e: |
---|
1466 | n/a | self.server_exception = e |
---|
1467 | n/a | return |
---|
1468 | n/a | server.ready.wait() |
---|
1469 | n/a | hcls = logging.handlers.SocketHandler |
---|
1470 | n/a | if isinstance(server.server_address, tuple): |
---|
1471 | n/a | self.sock_hdlr = hcls('localhost', server.port) |
---|
1472 | n/a | else: |
---|
1473 | n/a | self.sock_hdlr = hcls(server.server_address, None) |
---|
1474 | n/a | self.log_output = '' |
---|
1475 | n/a | self.root_logger.removeHandler(self.root_logger.handlers[0]) |
---|
1476 | n/a | self.root_logger.addHandler(self.sock_hdlr) |
---|
1477 | n/a | self.handled = threading.Semaphore(0) |
---|
1478 | n/a | |
---|
1479 | n/a | def tearDown(self): |
---|
1480 | n/a | """Shutdown the TCP server.""" |
---|
1481 | n/a | try: |
---|
1482 | n/a | if self.server: |
---|
1483 | n/a | self.server.stop(2.0) |
---|
1484 | n/a | if self.sock_hdlr: |
---|
1485 | n/a | self.root_logger.removeHandler(self.sock_hdlr) |
---|
1486 | n/a | self.sock_hdlr.close() |
---|
1487 | n/a | finally: |
---|
1488 | n/a | BaseTest.tearDown(self) |
---|
1489 | n/a | |
---|
1490 | n/a | def handle_socket(self, request): |
---|
1491 | n/a | conn = request.connection |
---|
1492 | n/a | while True: |
---|
1493 | n/a | chunk = conn.recv(4) |
---|
1494 | n/a | if len(chunk) < 4: |
---|
1495 | n/a | break |
---|
1496 | n/a | slen = struct.unpack(">L", chunk)[0] |
---|
1497 | n/a | chunk = conn.recv(slen) |
---|
1498 | n/a | while len(chunk) < slen: |
---|
1499 | n/a | chunk = chunk + conn.recv(slen - len(chunk)) |
---|
1500 | n/a | obj = pickle.loads(chunk) |
---|
1501 | n/a | record = logging.makeLogRecord(obj) |
---|
1502 | n/a | self.log_output += record.msg + '\n' |
---|
1503 | n/a | self.handled.release() |
---|
1504 | n/a | |
---|
1505 | n/a | def test_output(self): |
---|
1506 | n/a | # The log message sent to the SocketHandler is properly received. |
---|
1507 | n/a | if self.server_exception: |
---|
1508 | n/a | self.skipTest(self.server_exception) |
---|
1509 | n/a | logger = logging.getLogger("tcp") |
---|
1510 | n/a | logger.error("spam") |
---|
1511 | n/a | self.handled.acquire() |
---|
1512 | n/a | logger.debug("eggs") |
---|
1513 | n/a | self.handled.acquire() |
---|
1514 | n/a | self.assertEqual(self.log_output, "spam\neggs\n") |
---|
1515 | n/a | |
---|
1516 | n/a | def test_noserver(self): |
---|
1517 | n/a | if self.server_exception: |
---|
1518 | n/a | self.skipTest(self.server_exception) |
---|
1519 | n/a | # Avoid timing-related failures due to SocketHandler's own hard-wired |
---|
1520 | n/a | # one-second timeout on socket.create_connection() (issue #16264). |
---|
1521 | n/a | self.sock_hdlr.retryStart = 2.5 |
---|
1522 | n/a | # Kill the server |
---|
1523 | n/a | self.server.stop(2.0) |
---|
1524 | n/a | # The logging call should try to connect, which should fail |
---|
1525 | n/a | try: |
---|
1526 | n/a | raise RuntimeError('Deliberate mistake') |
---|
1527 | n/a | except RuntimeError: |
---|
1528 | n/a | self.root_logger.exception('Never sent') |
---|
1529 | n/a | self.root_logger.error('Never sent, either') |
---|
1530 | n/a | now = time.time() |
---|
1531 | n/a | self.assertGreater(self.sock_hdlr.retryTime, now) |
---|
1532 | n/a | time.sleep(self.sock_hdlr.retryTime - now + 0.001) |
---|
1533 | n/a | self.root_logger.error('Nor this') |
---|
1534 | n/a | |
---|
1535 | n/a | def _get_temp_domain_socket(): |
---|
1536 | n/a | fd, fn = tempfile.mkstemp(prefix='test_logging_', suffix='.sock') |
---|
1537 | n/a | os.close(fd) |
---|
1538 | n/a | # just need a name - file can't be present, or we'll get an |
---|
1539 | n/a | # 'address already in use' error. |
---|
1540 | n/a | os.remove(fn) |
---|
1541 | n/a | return fn |
---|
1542 | n/a | |
---|
1543 | n/a | @unittest.skipUnless(hasattr(socket, "AF_UNIX"), "Unix sockets required") |
---|
1544 | n/a | @unittest.skipUnless(threading, 'Threading required for this test.') |
---|
1545 | n/a | class UnixSocketHandlerTest(SocketHandlerTest): |
---|
1546 | n/a | |
---|
1547 | n/a | """Test for SocketHandler with unix sockets.""" |
---|
1548 | n/a | |
---|
1549 | n/a | if threading and hasattr(socket, "AF_UNIX"): |
---|
1550 | n/a | server_class = TestUnixStreamServer |
---|
1551 | n/a | |
---|
1552 | n/a | def setUp(self): |
---|
1553 | n/a | # override the definition in the base class |
---|
1554 | n/a | self.address = _get_temp_domain_socket() |
---|
1555 | n/a | SocketHandlerTest.setUp(self) |
---|
1556 | n/a | |
---|
1557 | n/a | def tearDown(self): |
---|
1558 | n/a | SocketHandlerTest.tearDown(self) |
---|
1559 | n/a | support.unlink(self.address) |
---|
1560 | n/a | |
---|
1561 | n/a | @unittest.skipUnless(threading, 'Threading required for this test.') |
---|
1562 | n/a | class DatagramHandlerTest(BaseTest): |
---|
1563 | n/a | |
---|
1564 | n/a | """Test for DatagramHandler.""" |
---|
1565 | n/a | |
---|
1566 | n/a | if threading: |
---|
1567 | n/a | server_class = TestUDPServer |
---|
1568 | n/a | address = ('localhost', 0) |
---|
1569 | n/a | |
---|
1570 | n/a | def setUp(self): |
---|
1571 | n/a | """Set up a UDP server to receive log messages, and a DatagramHandler |
---|
1572 | n/a | pointing to that server's address and port.""" |
---|
1573 | n/a | BaseTest.setUp(self) |
---|
1574 | n/a | # Issue #29177: deal with errors that happen during setup |
---|
1575 | n/a | self.server = self.sock_hdlr = self.server_exception = None |
---|
1576 | n/a | try: |
---|
1577 | n/a | self.server = server = self.server_class(self.address, |
---|
1578 | n/a | self.handle_datagram, 0.01) |
---|
1579 | n/a | server.start() |
---|
1580 | n/a | # Uncomment next line to test error recovery in setUp() |
---|
1581 | n/a | # raise OSError('dummy error raised') |
---|
1582 | n/a | except OSError as e: |
---|
1583 | n/a | self.server_exception = e |
---|
1584 | n/a | return |
---|
1585 | n/a | server.ready.wait() |
---|
1586 | n/a | hcls = logging.handlers.DatagramHandler |
---|
1587 | n/a | if isinstance(server.server_address, tuple): |
---|
1588 | n/a | self.sock_hdlr = hcls('localhost', server.port) |
---|
1589 | n/a | else: |
---|
1590 | n/a | self.sock_hdlr = hcls(server.server_address, None) |
---|
1591 | n/a | self.log_output = '' |
---|
1592 | n/a | self.root_logger.removeHandler(self.root_logger.handlers[0]) |
---|
1593 | n/a | self.root_logger.addHandler(self.sock_hdlr) |
---|
1594 | n/a | self.handled = threading.Event() |
---|
1595 | n/a | |
---|
1596 | n/a | def tearDown(self): |
---|
1597 | n/a | """Shutdown the UDP server.""" |
---|
1598 | n/a | try: |
---|
1599 | n/a | if self.server: |
---|
1600 | n/a | self.server.stop(2.0) |
---|
1601 | n/a | if self.sock_hdlr: |
---|
1602 | n/a | self.root_logger.removeHandler(self.sock_hdlr) |
---|
1603 | n/a | self.sock_hdlr.close() |
---|
1604 | n/a | finally: |
---|
1605 | n/a | BaseTest.tearDown(self) |
---|
1606 | n/a | |
---|
1607 | n/a | def handle_datagram(self, request): |
---|
1608 | n/a | slen = struct.pack('>L', 0) # length of prefix |
---|
1609 | n/a | packet = request.packet[len(slen):] |
---|
1610 | n/a | obj = pickle.loads(packet) |
---|
1611 | n/a | record = logging.makeLogRecord(obj) |
---|
1612 | n/a | self.log_output += record.msg + '\n' |
---|
1613 | n/a | self.handled.set() |
---|
1614 | n/a | |
---|
1615 | n/a | def test_output(self): |
---|
1616 | n/a | # The log message sent to the DatagramHandler is properly received. |
---|
1617 | n/a | if self.server_exception: |
---|
1618 | n/a | self.skipTest(self.server_exception) |
---|
1619 | n/a | logger = logging.getLogger("udp") |
---|
1620 | n/a | logger.error("spam") |
---|
1621 | n/a | self.handled.wait() |
---|
1622 | n/a | self.handled.clear() |
---|
1623 | n/a | logger.error("eggs") |
---|
1624 | n/a | self.handled.wait() |
---|
1625 | n/a | self.assertEqual(self.log_output, "spam\neggs\n") |
---|
1626 | n/a | |
---|
1627 | n/a | @unittest.skipUnless(hasattr(socket, "AF_UNIX"), "Unix sockets required") |
---|
1628 | n/a | @unittest.skipUnless(threading, 'Threading required for this test.') |
---|
1629 | n/a | class UnixDatagramHandlerTest(DatagramHandlerTest): |
---|
1630 | n/a | |
---|
1631 | n/a | """Test for DatagramHandler using Unix sockets.""" |
---|
1632 | n/a | |
---|
1633 | n/a | if threading and hasattr(socket, "AF_UNIX"): |
---|
1634 | n/a | server_class = TestUnixDatagramServer |
---|
1635 | n/a | |
---|
1636 | n/a | def setUp(self): |
---|
1637 | n/a | # override the definition in the base class |
---|
1638 | n/a | self.address = _get_temp_domain_socket() |
---|
1639 | n/a | DatagramHandlerTest.setUp(self) |
---|
1640 | n/a | |
---|
1641 | n/a | def tearDown(self): |
---|
1642 | n/a | DatagramHandlerTest.tearDown(self) |
---|
1643 | n/a | support.unlink(self.address) |
---|
1644 | n/a | |
---|
1645 | n/a | @unittest.skipUnless(threading, 'Threading required for this test.') |
---|
1646 | n/a | class SysLogHandlerTest(BaseTest): |
---|
1647 | n/a | |
---|
1648 | n/a | """Test for SysLogHandler using UDP.""" |
---|
1649 | n/a | |
---|
1650 | n/a | if threading: |
---|
1651 | n/a | server_class = TestUDPServer |
---|
1652 | n/a | address = ('localhost', 0) |
---|
1653 | n/a | |
---|
1654 | n/a | def setUp(self): |
---|
1655 | n/a | """Set up a UDP server to receive log messages, and a SysLogHandler |
---|
1656 | n/a | pointing to that server's address and port.""" |
---|
1657 | n/a | BaseTest.setUp(self) |
---|
1658 | n/a | # Issue #29177: deal with errors that happen during setup |
---|
1659 | n/a | self.server = self.sl_hdlr = self.server_exception = None |
---|
1660 | n/a | try: |
---|
1661 | n/a | self.server = server = self.server_class(self.address, |
---|
1662 | n/a | self.handle_datagram, 0.01) |
---|
1663 | n/a | server.start() |
---|
1664 | n/a | # Uncomment next line to test error recovery in setUp() |
---|
1665 | n/a | # raise OSError('dummy error raised') |
---|
1666 | n/a | except OSError as e: |
---|
1667 | n/a | self.server_exception = e |
---|
1668 | n/a | return |
---|
1669 | n/a | server.ready.wait() |
---|
1670 | n/a | hcls = logging.handlers.SysLogHandler |
---|
1671 | n/a | if isinstance(server.server_address, tuple): |
---|
1672 | n/a | self.sl_hdlr = hcls(('localhost', server.port)) |
---|
1673 | n/a | else: |
---|
1674 | n/a | self.sl_hdlr = hcls(server.server_address) |
---|
1675 | n/a | self.log_output = '' |
---|
1676 | n/a | self.root_logger.removeHandler(self.root_logger.handlers[0]) |
---|
1677 | n/a | self.root_logger.addHandler(self.sl_hdlr) |
---|
1678 | n/a | self.handled = threading.Event() |
---|
1679 | n/a | |
---|
1680 | n/a | def tearDown(self): |
---|
1681 | n/a | """Shutdown the server.""" |
---|
1682 | n/a | try: |
---|
1683 | n/a | if self.server: |
---|
1684 | n/a | self.server.stop(2.0) |
---|
1685 | n/a | if self.sl_hdlr: |
---|
1686 | n/a | self.root_logger.removeHandler(self.sl_hdlr) |
---|
1687 | n/a | self.sl_hdlr.close() |
---|
1688 | n/a | finally: |
---|
1689 | n/a | BaseTest.tearDown(self) |
---|
1690 | n/a | |
---|
1691 | n/a | def handle_datagram(self, request): |
---|
1692 | n/a | self.log_output = request.packet |
---|
1693 | n/a | self.handled.set() |
---|
1694 | n/a | |
---|
1695 | n/a | def test_output(self): |
---|
1696 | n/a | if self.server_exception: |
---|
1697 | n/a | self.skipTest(self.server_exception) |
---|
1698 | n/a | # The log message sent to the SysLogHandler is properly received. |
---|
1699 | n/a | logger = logging.getLogger("slh") |
---|
1700 | n/a | logger.error("sp\xe4m") |
---|
1701 | n/a | self.handled.wait() |
---|
1702 | n/a | self.assertEqual(self.log_output, b'<11>sp\xc3\xa4m\x00') |
---|
1703 | n/a | self.handled.clear() |
---|
1704 | n/a | self.sl_hdlr.append_nul = False |
---|
1705 | n/a | logger.error("sp\xe4m") |
---|
1706 | n/a | self.handled.wait() |
---|
1707 | n/a | self.assertEqual(self.log_output, b'<11>sp\xc3\xa4m') |
---|
1708 | n/a | self.handled.clear() |
---|
1709 | n/a | self.sl_hdlr.ident = "h\xe4m-" |
---|
1710 | n/a | logger.error("sp\xe4m") |
---|
1711 | n/a | self.handled.wait() |
---|
1712 | n/a | self.assertEqual(self.log_output, b'<11>h\xc3\xa4m-sp\xc3\xa4m') |
---|
1713 | n/a | |
---|
1714 | n/a | @unittest.skipUnless(hasattr(socket, "AF_UNIX"), "Unix sockets required") |
---|
1715 | n/a | @unittest.skipUnless(threading, 'Threading required for this test.') |
---|
1716 | n/a | class UnixSysLogHandlerTest(SysLogHandlerTest): |
---|
1717 | n/a | |
---|
1718 | n/a | """Test for SysLogHandler with Unix sockets.""" |
---|
1719 | n/a | |
---|
1720 | n/a | if threading and hasattr(socket, "AF_UNIX"): |
---|
1721 | n/a | server_class = TestUnixDatagramServer |
---|
1722 | n/a | |
---|
1723 | n/a | def setUp(self): |
---|
1724 | n/a | # override the definition in the base class |
---|
1725 | n/a | self.address = _get_temp_domain_socket() |
---|
1726 | n/a | SysLogHandlerTest.setUp(self) |
---|
1727 | n/a | |
---|
1728 | n/a | def tearDown(self): |
---|
1729 | n/a | SysLogHandlerTest.tearDown(self) |
---|
1730 | n/a | support.unlink(self.address) |
---|
1731 | n/a | |
---|
1732 | n/a | @unittest.skipUnless(threading, 'Threading required for this test.') |
---|
1733 | n/a | class HTTPHandlerTest(BaseTest): |
---|
1734 | n/a | """Test for HTTPHandler.""" |
---|
1735 | n/a | |
---|
1736 | n/a | def setUp(self): |
---|
1737 | n/a | """Set up an HTTP server to receive log messages, and a HTTPHandler |
---|
1738 | n/a | pointing to that server's address and port.""" |
---|
1739 | n/a | BaseTest.setUp(self) |
---|
1740 | n/a | self.handled = threading.Event() |
---|
1741 | n/a | |
---|
1742 | n/a | def handle_request(self, request): |
---|
1743 | n/a | self.command = request.command |
---|
1744 | n/a | self.log_data = urlparse(request.path) |
---|
1745 | n/a | if self.command == 'POST': |
---|
1746 | n/a | try: |
---|
1747 | n/a | rlen = int(request.headers['Content-Length']) |
---|
1748 | n/a | self.post_data = request.rfile.read(rlen) |
---|
1749 | n/a | except: |
---|
1750 | n/a | self.post_data = None |
---|
1751 | n/a | request.send_response(200) |
---|
1752 | n/a | request.end_headers() |
---|
1753 | n/a | self.handled.set() |
---|
1754 | n/a | |
---|
1755 | n/a | def test_output(self): |
---|
1756 | n/a | # The log message sent to the HTTPHandler is properly received. |
---|
1757 | n/a | logger = logging.getLogger("http") |
---|
1758 | n/a | root_logger = self.root_logger |
---|
1759 | n/a | root_logger.removeHandler(self.root_logger.handlers[0]) |
---|
1760 | n/a | for secure in (False, True): |
---|
1761 | n/a | addr = ('localhost', 0) |
---|
1762 | n/a | if secure: |
---|
1763 | n/a | try: |
---|
1764 | n/a | import ssl |
---|
1765 | n/a | except ImportError: |
---|
1766 | n/a | sslctx = None |
---|
1767 | n/a | else: |
---|
1768 | n/a | here = os.path.dirname(__file__) |
---|
1769 | n/a | localhost_cert = os.path.join(here, "keycert.pem") |
---|
1770 | n/a | sslctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) |
---|
1771 | n/a | sslctx.load_cert_chain(localhost_cert) |
---|
1772 | n/a | |
---|
1773 | n/a | context = ssl.create_default_context(cafile=localhost_cert) |
---|
1774 | n/a | else: |
---|
1775 | n/a | sslctx = None |
---|
1776 | n/a | context = None |
---|
1777 | n/a | self.server = server = TestHTTPServer(addr, self.handle_request, |
---|
1778 | n/a | 0.01, sslctx=sslctx) |
---|
1779 | n/a | server.start() |
---|
1780 | n/a | server.ready.wait() |
---|
1781 | n/a | host = 'localhost:%d' % server.server_port |
---|
1782 | n/a | secure_client = secure and sslctx |
---|
1783 | n/a | self.h_hdlr = logging.handlers.HTTPHandler(host, '/frob', |
---|
1784 | n/a | secure=secure_client, |
---|
1785 | n/a | context=context, |
---|
1786 | n/a | credentials=('foo', 'bar')) |
---|
1787 | n/a | self.log_data = None |
---|
1788 | n/a | root_logger.addHandler(self.h_hdlr) |
---|
1789 | n/a | |
---|
1790 | n/a | for method in ('GET', 'POST'): |
---|
1791 | n/a | self.h_hdlr.method = method |
---|
1792 | n/a | self.handled.clear() |
---|
1793 | n/a | msg = "sp\xe4m" |
---|
1794 | n/a | logger.error(msg) |
---|
1795 | n/a | self.handled.wait() |
---|
1796 | n/a | self.assertEqual(self.log_data.path, '/frob') |
---|
1797 | n/a | self.assertEqual(self.command, method) |
---|
1798 | n/a | if method == 'GET': |
---|
1799 | n/a | d = parse_qs(self.log_data.query) |
---|
1800 | n/a | else: |
---|
1801 | n/a | d = parse_qs(self.post_data.decode('utf-8')) |
---|
1802 | n/a | self.assertEqual(d['name'], ['http']) |
---|
1803 | n/a | self.assertEqual(d['funcName'], ['test_output']) |
---|
1804 | n/a | self.assertEqual(d['msg'], [msg]) |
---|
1805 | n/a | |
---|
1806 | n/a | self.server.stop(2.0) |
---|
1807 | n/a | self.root_logger.removeHandler(self.h_hdlr) |
---|
1808 | n/a | self.h_hdlr.close() |
---|
1809 | n/a | |
---|
1810 | n/a | class MemoryTest(BaseTest): |
---|
1811 | n/a | |
---|
1812 | n/a | """Test memory persistence of logger objects.""" |
---|
1813 | n/a | |
---|
1814 | n/a | def setUp(self): |
---|
1815 | n/a | """Create a dict to remember potentially destroyed objects.""" |
---|
1816 | n/a | BaseTest.setUp(self) |
---|
1817 | n/a | self._survivors = {} |
---|
1818 | n/a | |
---|
1819 | n/a | def _watch_for_survival(self, *args): |
---|
1820 | n/a | """Watch the given objects for survival, by creating weakrefs to |
---|
1821 | n/a | them.""" |
---|
1822 | n/a | for obj in args: |
---|
1823 | n/a | key = id(obj), repr(obj) |
---|
1824 | n/a | self._survivors[key] = weakref.ref(obj) |
---|
1825 | n/a | |
---|
1826 | n/a | def _assertTruesurvival(self): |
---|
1827 | n/a | """Assert that all objects watched for survival have survived.""" |
---|
1828 | n/a | # Trigger cycle breaking. |
---|
1829 | n/a | gc.collect() |
---|
1830 | n/a | dead = [] |
---|
1831 | n/a | for (id_, repr_), ref in self._survivors.items(): |
---|
1832 | n/a | if ref() is None: |
---|
1833 | n/a | dead.append(repr_) |
---|
1834 | n/a | if dead: |
---|
1835 | n/a | self.fail("%d objects should have survived " |
---|
1836 | n/a | "but have been destroyed: %s" % (len(dead), ", ".join(dead))) |
---|
1837 | n/a | |
---|
1838 | n/a | def test_persistent_loggers(self): |
---|
1839 | n/a | # Logger objects are persistent and retain their configuration, even |
---|
1840 | n/a | # if visible references are destroyed. |
---|
1841 | n/a | self.root_logger.setLevel(logging.INFO) |
---|
1842 | n/a | foo = logging.getLogger("foo") |
---|
1843 | n/a | self._watch_for_survival(foo) |
---|
1844 | n/a | foo.setLevel(logging.DEBUG) |
---|
1845 | n/a | self.root_logger.debug(self.next_message()) |
---|
1846 | n/a | foo.debug(self.next_message()) |
---|
1847 | n/a | self.assert_log_lines([ |
---|
1848 | n/a | ('foo', 'DEBUG', '2'), |
---|
1849 | n/a | ]) |
---|
1850 | n/a | del foo |
---|
1851 | n/a | # foo has survived. |
---|
1852 | n/a | self._assertTruesurvival() |
---|
1853 | n/a | # foo has retained its settings. |
---|
1854 | n/a | bar = logging.getLogger("foo") |
---|
1855 | n/a | bar.debug(self.next_message()) |
---|
1856 | n/a | self.assert_log_lines([ |
---|
1857 | n/a | ('foo', 'DEBUG', '2'), |
---|
1858 | n/a | ('foo', 'DEBUG', '3'), |
---|
1859 | n/a | ]) |
---|
1860 | n/a | |
---|
1861 | n/a | |
---|
1862 | n/a | class EncodingTest(BaseTest): |
---|
1863 | n/a | def test_encoding_plain_file(self): |
---|
1864 | n/a | # In Python 2.x, a plain file object is treated as having no encoding. |
---|
1865 | n/a | log = logging.getLogger("test") |
---|
1866 | n/a | fd, fn = tempfile.mkstemp(".log", "test_logging-1-") |
---|
1867 | n/a | os.close(fd) |
---|
1868 | n/a | # the non-ascii data we write to the log. |
---|
1869 | n/a | data = "foo\x80" |
---|
1870 | n/a | try: |
---|
1871 | n/a | handler = logging.FileHandler(fn, encoding="utf-8") |
---|
1872 | n/a | log.addHandler(handler) |
---|
1873 | n/a | try: |
---|
1874 | n/a | # write non-ascii data to the log. |
---|
1875 | n/a | log.warning(data) |
---|
1876 | n/a | finally: |
---|
1877 | n/a | log.removeHandler(handler) |
---|
1878 | n/a | handler.close() |
---|
1879 | n/a | # check we wrote exactly those bytes, ignoring trailing \n etc |
---|
1880 | n/a | f = open(fn, encoding="utf-8") |
---|
1881 | n/a | try: |
---|
1882 | n/a | self.assertEqual(f.read().rstrip(), data) |
---|
1883 | n/a | finally: |
---|
1884 | n/a | f.close() |
---|
1885 | n/a | finally: |
---|
1886 | n/a | if os.path.isfile(fn): |
---|
1887 | n/a | os.remove(fn) |
---|
1888 | n/a | |
---|
1889 | n/a | def test_encoding_cyrillic_unicode(self): |
---|
1890 | n/a | log = logging.getLogger("test") |
---|
1891 | n/a | #Get a message in Unicode: Do svidanya in Cyrillic (meaning goodbye) |
---|
1892 | n/a | message = '\u0434\u043e \u0441\u0432\u0438\u0434\u0430\u043d\u0438\u044f' |
---|
1893 | n/a | #Ensure it's written in a Cyrillic encoding |
---|
1894 | n/a | writer_class = codecs.getwriter('cp1251') |
---|
1895 | n/a | writer_class.encoding = 'cp1251' |
---|
1896 | n/a | stream = io.BytesIO() |
---|
1897 | n/a | writer = writer_class(stream, 'strict') |
---|
1898 | n/a | handler = logging.StreamHandler(writer) |
---|
1899 | n/a | log.addHandler(handler) |
---|
1900 | n/a | try: |
---|
1901 | n/a | log.warning(message) |
---|
1902 | n/a | finally: |
---|
1903 | n/a | log.removeHandler(handler) |
---|
1904 | n/a | handler.close() |
---|
1905 | n/a | # check we wrote exactly those bytes, ignoring trailing \n etc |
---|
1906 | n/a | s = stream.getvalue() |
---|
1907 | n/a | #Compare against what the data should be when encoded in CP-1251 |
---|
1908 | n/a | self.assertEqual(s, b'\xe4\xee \xf1\xe2\xe8\xe4\xe0\xed\xe8\xff\n') |
---|
1909 | n/a | |
---|
1910 | n/a | |
---|
1911 | n/a | class WarningsTest(BaseTest): |
---|
1912 | n/a | |
---|
1913 | n/a | def test_warnings(self): |
---|
1914 | n/a | with warnings.catch_warnings(): |
---|
1915 | n/a | logging.captureWarnings(True) |
---|
1916 | n/a | self.addCleanup(logging.captureWarnings, False) |
---|
1917 | n/a | warnings.filterwarnings("always", category=UserWarning) |
---|
1918 | n/a | stream = io.StringIO() |
---|
1919 | n/a | h = logging.StreamHandler(stream) |
---|
1920 | n/a | logger = logging.getLogger("py.warnings") |
---|
1921 | n/a | logger.addHandler(h) |
---|
1922 | n/a | warnings.warn("I'm warning you...") |
---|
1923 | n/a | logger.removeHandler(h) |
---|
1924 | n/a | s = stream.getvalue() |
---|
1925 | n/a | h.close() |
---|
1926 | n/a | self.assertGreater(s.find("UserWarning: I'm warning you...\n"), 0) |
---|
1927 | n/a | |
---|
1928 | n/a | #See if an explicit file uses the original implementation |
---|
1929 | n/a | a_file = io.StringIO() |
---|
1930 | n/a | warnings.showwarning("Explicit", UserWarning, "dummy.py", 42, |
---|
1931 | n/a | a_file, "Dummy line") |
---|
1932 | n/a | s = a_file.getvalue() |
---|
1933 | n/a | a_file.close() |
---|
1934 | n/a | self.assertEqual(s, |
---|
1935 | n/a | "dummy.py:42: UserWarning: Explicit\n Dummy line\n") |
---|
1936 | n/a | |
---|
1937 | n/a | def test_warnings_no_handlers(self): |
---|
1938 | n/a | with warnings.catch_warnings(): |
---|
1939 | n/a | logging.captureWarnings(True) |
---|
1940 | n/a | self.addCleanup(logging.captureWarnings, False) |
---|
1941 | n/a | |
---|
1942 | n/a | # confirm our assumption: no loggers are set |
---|
1943 | n/a | logger = logging.getLogger("py.warnings") |
---|
1944 | n/a | self.assertEqual(logger.handlers, []) |
---|
1945 | n/a | |
---|
1946 | n/a | warnings.showwarning("Explicit", UserWarning, "dummy.py", 42) |
---|
1947 | n/a | self.assertEqual(len(logger.handlers), 1) |
---|
1948 | n/a | self.assertIsInstance(logger.handlers[0], logging.NullHandler) |
---|
1949 | n/a | |
---|
1950 | n/a | |
---|
1951 | n/a | def formatFunc(format, datefmt=None): |
---|
1952 | n/a | return logging.Formatter(format, datefmt) |
---|
1953 | n/a | |
---|
1954 | n/a | def handlerFunc(): |
---|
1955 | n/a | return logging.StreamHandler() |
---|
1956 | n/a | |
---|
1957 | n/a | class CustomHandler(logging.StreamHandler): |
---|
1958 | n/a | pass |
---|
1959 | n/a | |
---|
1960 | n/a | class ConfigDictTest(BaseTest): |
---|
1961 | n/a | |
---|
1962 | n/a | """Reading logging config from a dictionary.""" |
---|
1963 | n/a | |
---|
1964 | n/a | expected_log_pat = r"^(\w+) \+\+ (\w+)$" |
---|
1965 | n/a | |
---|
1966 | n/a | # config0 is a standard configuration. |
---|
1967 | n/a | config0 = { |
---|
1968 | n/a | 'version': 1, |
---|
1969 | n/a | 'formatters': { |
---|
1970 | n/a | 'form1' : { |
---|
1971 | n/a | 'format' : '%(levelname)s ++ %(message)s', |
---|
1972 | n/a | }, |
---|
1973 | n/a | }, |
---|
1974 | n/a | 'handlers' : { |
---|
1975 | n/a | 'hand1' : { |
---|
1976 | n/a | 'class' : 'logging.StreamHandler', |
---|
1977 | n/a | 'formatter' : 'form1', |
---|
1978 | n/a | 'level' : 'NOTSET', |
---|
1979 | n/a | 'stream' : 'ext://sys.stdout', |
---|
1980 | n/a | }, |
---|
1981 | n/a | }, |
---|
1982 | n/a | 'root' : { |
---|
1983 | n/a | 'level' : 'WARNING', |
---|
1984 | n/a | 'handlers' : ['hand1'], |
---|
1985 | n/a | }, |
---|
1986 | n/a | } |
---|
1987 | n/a | |
---|
1988 | n/a | # config1 adds a little to the standard configuration. |
---|
1989 | n/a | config1 = { |
---|
1990 | n/a | 'version': 1, |
---|
1991 | n/a | 'formatters': { |
---|
1992 | n/a | 'form1' : { |
---|
1993 | n/a | 'format' : '%(levelname)s ++ %(message)s', |
---|
1994 | n/a | }, |
---|
1995 | n/a | }, |
---|
1996 | n/a | 'handlers' : { |
---|
1997 | n/a | 'hand1' : { |
---|
1998 | n/a | 'class' : 'logging.StreamHandler', |
---|
1999 | n/a | 'formatter' : 'form1', |
---|
2000 | n/a | 'level' : 'NOTSET', |
---|
2001 | n/a | 'stream' : 'ext://sys.stdout', |
---|
2002 | n/a | }, |
---|
2003 | n/a | }, |
---|
2004 | n/a | 'loggers' : { |
---|
2005 | n/a | 'compiler.parser' : { |
---|
2006 | n/a | 'level' : 'DEBUG', |
---|
2007 | n/a | 'handlers' : ['hand1'], |
---|
2008 | n/a | }, |
---|
2009 | n/a | }, |
---|
2010 | n/a | 'root' : { |
---|
2011 | n/a | 'level' : 'WARNING', |
---|
2012 | n/a | }, |
---|
2013 | n/a | } |
---|
2014 | n/a | |
---|
2015 | n/a | # config1a moves the handler to the root. Used with config8a |
---|
2016 | n/a | config1a = { |
---|
2017 | n/a | 'version': 1, |
---|
2018 | n/a | 'formatters': { |
---|
2019 | n/a | 'form1' : { |
---|
2020 | n/a | 'format' : '%(levelname)s ++ %(message)s', |
---|
2021 | n/a | }, |
---|
2022 | n/a | }, |
---|
2023 | n/a | 'handlers' : { |
---|
2024 | n/a | 'hand1' : { |
---|
2025 | n/a | 'class' : 'logging.StreamHandler', |
---|
2026 | n/a | 'formatter' : 'form1', |
---|
2027 | n/a | 'level' : 'NOTSET', |
---|
2028 | n/a | 'stream' : 'ext://sys.stdout', |
---|
2029 | n/a | }, |
---|
2030 | n/a | }, |
---|
2031 | n/a | 'loggers' : { |
---|
2032 | n/a | 'compiler.parser' : { |
---|
2033 | n/a | 'level' : 'DEBUG', |
---|
2034 | n/a | }, |
---|
2035 | n/a | }, |
---|
2036 | n/a | 'root' : { |
---|
2037 | n/a | 'level' : 'WARNING', |
---|
2038 | n/a | 'handlers' : ['hand1'], |
---|
2039 | n/a | }, |
---|
2040 | n/a | } |
---|
2041 | n/a | |
---|
2042 | n/a | # config2 has a subtle configuration error that should be reported |
---|
2043 | n/a | config2 = { |
---|
2044 | n/a | 'version': 1, |
---|
2045 | n/a | 'formatters': { |
---|
2046 | n/a | 'form1' : { |
---|
2047 | n/a | 'format' : '%(levelname)s ++ %(message)s', |
---|
2048 | n/a | }, |
---|
2049 | n/a | }, |
---|
2050 | n/a | 'handlers' : { |
---|
2051 | n/a | 'hand1' : { |
---|
2052 | n/a | 'class' : 'logging.StreamHandler', |
---|
2053 | n/a | 'formatter' : 'form1', |
---|
2054 | n/a | 'level' : 'NOTSET', |
---|
2055 | n/a | 'stream' : 'ext://sys.stdbout', |
---|
2056 | n/a | }, |
---|
2057 | n/a | }, |
---|
2058 | n/a | 'loggers' : { |
---|
2059 | n/a | 'compiler.parser' : { |
---|
2060 | n/a | 'level' : 'DEBUG', |
---|
2061 | n/a | 'handlers' : ['hand1'], |
---|
2062 | n/a | }, |
---|
2063 | n/a | }, |
---|
2064 | n/a | 'root' : { |
---|
2065 | n/a | 'level' : 'WARNING', |
---|
2066 | n/a | }, |
---|
2067 | n/a | } |
---|
2068 | n/a | |
---|
2069 | n/a | #As config1 but with a misspelt level on a handler |
---|
2070 | n/a | config2a = { |
---|
2071 | n/a | 'version': 1, |
---|
2072 | n/a | 'formatters': { |
---|
2073 | n/a | 'form1' : { |
---|
2074 | n/a | 'format' : '%(levelname)s ++ %(message)s', |
---|
2075 | n/a | }, |
---|
2076 | n/a | }, |
---|
2077 | n/a | 'handlers' : { |
---|
2078 | n/a | 'hand1' : { |
---|
2079 | n/a | 'class' : 'logging.StreamHandler', |
---|
2080 | n/a | 'formatter' : 'form1', |
---|
2081 | n/a | 'level' : 'NTOSET', |
---|
2082 | n/a | 'stream' : 'ext://sys.stdout', |
---|
2083 | n/a | }, |
---|
2084 | n/a | }, |
---|
2085 | n/a | 'loggers' : { |
---|
2086 | n/a | 'compiler.parser' : { |
---|
2087 | n/a | 'level' : 'DEBUG', |
---|
2088 | n/a | 'handlers' : ['hand1'], |
---|
2089 | n/a | }, |
---|
2090 | n/a | }, |
---|
2091 | n/a | 'root' : { |
---|
2092 | n/a | 'level' : 'WARNING', |
---|
2093 | n/a | }, |
---|
2094 | n/a | } |
---|
2095 | n/a | |
---|
2096 | n/a | |
---|
2097 | n/a | #As config1 but with a misspelt level on a logger |
---|
2098 | n/a | config2b = { |
---|
2099 | n/a | 'version': 1, |
---|
2100 | n/a | 'formatters': { |
---|
2101 | n/a | 'form1' : { |
---|
2102 | n/a | 'format' : '%(levelname)s ++ %(message)s', |
---|
2103 | n/a | }, |
---|
2104 | n/a | }, |
---|
2105 | n/a | 'handlers' : { |
---|
2106 | n/a | 'hand1' : { |
---|
2107 | n/a | 'class' : 'logging.StreamHandler', |
---|
2108 | n/a | 'formatter' : 'form1', |
---|
2109 | n/a | 'level' : 'NOTSET', |
---|
2110 | n/a | 'stream' : 'ext://sys.stdout', |
---|
2111 | n/a | }, |
---|
2112 | n/a | }, |
---|
2113 | n/a | 'loggers' : { |
---|
2114 | n/a | 'compiler.parser' : { |
---|
2115 | n/a | 'level' : 'DEBUG', |
---|
2116 | n/a | 'handlers' : ['hand1'], |
---|
2117 | n/a | }, |
---|
2118 | n/a | }, |
---|
2119 | n/a | 'root' : { |
---|
2120 | n/a | 'level' : 'WRANING', |
---|
2121 | n/a | }, |
---|
2122 | n/a | } |
---|
2123 | n/a | |
---|
2124 | n/a | # config3 has a less subtle configuration error |
---|
2125 | n/a | config3 = { |
---|
2126 | n/a | 'version': 1, |
---|
2127 | n/a | 'formatters': { |
---|
2128 | n/a | 'form1' : { |
---|
2129 | n/a | 'format' : '%(levelname)s ++ %(message)s', |
---|
2130 | n/a | }, |
---|
2131 | n/a | }, |
---|
2132 | n/a | 'handlers' : { |
---|
2133 | n/a | 'hand1' : { |
---|
2134 | n/a | 'class' : 'logging.StreamHandler', |
---|
2135 | n/a | 'formatter' : 'misspelled_name', |
---|
2136 | n/a | 'level' : 'NOTSET', |
---|
2137 | n/a | 'stream' : 'ext://sys.stdout', |
---|
2138 | n/a | }, |
---|
2139 | n/a | }, |
---|
2140 | n/a | 'loggers' : { |
---|
2141 | n/a | 'compiler.parser' : { |
---|
2142 | n/a | 'level' : 'DEBUG', |
---|
2143 | n/a | 'handlers' : ['hand1'], |
---|
2144 | n/a | }, |
---|
2145 | n/a | }, |
---|
2146 | n/a | 'root' : { |
---|
2147 | n/a | 'level' : 'WARNING', |
---|
2148 | n/a | }, |
---|
2149 | n/a | } |
---|
2150 | n/a | |
---|
2151 | n/a | # config4 specifies a custom formatter class to be loaded |
---|
2152 | n/a | config4 = { |
---|
2153 | n/a | 'version': 1, |
---|
2154 | n/a | 'formatters': { |
---|
2155 | n/a | 'form1' : { |
---|
2156 | n/a | '()' : __name__ + '.ExceptionFormatter', |
---|
2157 | n/a | 'format' : '%(levelname)s:%(name)s:%(message)s', |
---|
2158 | n/a | }, |
---|
2159 | n/a | }, |
---|
2160 | n/a | 'handlers' : { |
---|
2161 | n/a | 'hand1' : { |
---|
2162 | n/a | 'class' : 'logging.StreamHandler', |
---|
2163 | n/a | 'formatter' : 'form1', |
---|
2164 | n/a | 'level' : 'NOTSET', |
---|
2165 | n/a | 'stream' : 'ext://sys.stdout', |
---|
2166 | n/a | }, |
---|
2167 | n/a | }, |
---|
2168 | n/a | 'root' : { |
---|
2169 | n/a | 'level' : 'NOTSET', |
---|
2170 | n/a | 'handlers' : ['hand1'], |
---|
2171 | n/a | }, |
---|
2172 | n/a | } |
---|
2173 | n/a | |
---|
2174 | n/a | # As config4 but using an actual callable rather than a string |
---|
2175 | n/a | config4a = { |
---|
2176 | n/a | 'version': 1, |
---|
2177 | n/a | 'formatters': { |
---|
2178 | n/a | 'form1' : { |
---|
2179 | n/a | '()' : ExceptionFormatter, |
---|
2180 | n/a | 'format' : '%(levelname)s:%(name)s:%(message)s', |
---|
2181 | n/a | }, |
---|
2182 | n/a | 'form2' : { |
---|
2183 | n/a | '()' : __name__ + '.formatFunc', |
---|
2184 | n/a | 'format' : '%(levelname)s:%(name)s:%(message)s', |
---|
2185 | n/a | }, |
---|
2186 | n/a | 'form3' : { |
---|
2187 | n/a | '()' : formatFunc, |
---|
2188 | n/a | 'format' : '%(levelname)s:%(name)s:%(message)s', |
---|
2189 | n/a | }, |
---|
2190 | n/a | }, |
---|
2191 | n/a | 'handlers' : { |
---|
2192 | n/a | 'hand1' : { |
---|
2193 | n/a | 'class' : 'logging.StreamHandler', |
---|
2194 | n/a | 'formatter' : 'form1', |
---|
2195 | n/a | 'level' : 'NOTSET', |
---|
2196 | n/a | 'stream' : 'ext://sys.stdout', |
---|
2197 | n/a | }, |
---|
2198 | n/a | 'hand2' : { |
---|
2199 | n/a | '()' : handlerFunc, |
---|
2200 | n/a | }, |
---|
2201 | n/a | }, |
---|
2202 | n/a | 'root' : { |
---|
2203 | n/a | 'level' : 'NOTSET', |
---|
2204 | n/a | 'handlers' : ['hand1'], |
---|
2205 | n/a | }, |
---|
2206 | n/a | } |
---|
2207 | n/a | |
---|
2208 | n/a | # config5 specifies a custom handler class to be loaded |
---|
2209 | n/a | config5 = { |
---|
2210 | n/a | 'version': 1, |
---|
2211 | n/a | 'formatters': { |
---|
2212 | n/a | 'form1' : { |
---|
2213 | n/a | 'format' : '%(levelname)s ++ %(message)s', |
---|
2214 | n/a | }, |
---|
2215 | n/a | }, |
---|
2216 | n/a | 'handlers' : { |
---|
2217 | n/a | 'hand1' : { |
---|
2218 | n/a | 'class' : __name__ + '.CustomHandler', |
---|
2219 | n/a | 'formatter' : 'form1', |
---|
2220 | n/a | 'level' : 'NOTSET', |
---|
2221 | n/a | 'stream' : 'ext://sys.stdout', |
---|
2222 | n/a | }, |
---|
2223 | n/a | }, |
---|
2224 | n/a | 'loggers' : { |
---|
2225 | n/a | 'compiler.parser' : { |
---|
2226 | n/a | 'level' : 'DEBUG', |
---|
2227 | n/a | 'handlers' : ['hand1'], |
---|
2228 | n/a | }, |
---|
2229 | n/a | }, |
---|
2230 | n/a | 'root' : { |
---|
2231 | n/a | 'level' : 'WARNING', |
---|
2232 | n/a | }, |
---|
2233 | n/a | } |
---|
2234 | n/a | |
---|
2235 | n/a | # config6 specifies a custom handler class to be loaded |
---|
2236 | n/a | # but has bad arguments |
---|
2237 | n/a | config6 = { |
---|
2238 | n/a | 'version': 1, |
---|
2239 | n/a | 'formatters': { |
---|
2240 | n/a | 'form1' : { |
---|
2241 | n/a | 'format' : '%(levelname)s ++ %(message)s', |
---|
2242 | n/a | }, |
---|
2243 | n/a | }, |
---|
2244 | n/a | 'handlers' : { |
---|
2245 | n/a | 'hand1' : { |
---|
2246 | n/a | 'class' : __name__ + '.CustomHandler', |
---|
2247 | n/a | 'formatter' : 'form1', |
---|
2248 | n/a | 'level' : 'NOTSET', |
---|
2249 | n/a | 'stream' : 'ext://sys.stdout', |
---|
2250 | n/a | '9' : 'invalid parameter name', |
---|
2251 | n/a | }, |
---|
2252 | n/a | }, |
---|
2253 | n/a | 'loggers' : { |
---|
2254 | n/a | 'compiler.parser' : { |
---|
2255 | n/a | 'level' : 'DEBUG', |
---|
2256 | n/a | 'handlers' : ['hand1'], |
---|
2257 | n/a | }, |
---|
2258 | n/a | }, |
---|
2259 | n/a | 'root' : { |
---|
2260 | n/a | 'level' : 'WARNING', |
---|
2261 | n/a | }, |
---|
2262 | n/a | } |
---|
2263 | n/a | |
---|
2264 | n/a | #config 7 does not define compiler.parser but defines compiler.lexer |
---|
2265 | n/a | #so compiler.parser should be disabled after applying it |
---|
2266 | n/a | config7 = { |
---|
2267 | n/a | 'version': 1, |
---|
2268 | n/a | 'formatters': { |
---|
2269 | n/a | 'form1' : { |
---|
2270 | n/a | 'format' : '%(levelname)s ++ %(message)s', |
---|
2271 | n/a | }, |
---|
2272 | n/a | }, |
---|
2273 | n/a | 'handlers' : { |
---|
2274 | n/a | 'hand1' : { |
---|
2275 | n/a | 'class' : 'logging.StreamHandler', |
---|
2276 | n/a | 'formatter' : 'form1', |
---|
2277 | n/a | 'level' : 'NOTSET', |
---|
2278 | n/a | 'stream' : 'ext://sys.stdout', |
---|
2279 | n/a | }, |
---|
2280 | n/a | }, |
---|
2281 | n/a | 'loggers' : { |
---|
2282 | n/a | 'compiler.lexer' : { |
---|
2283 | n/a | 'level' : 'DEBUG', |
---|
2284 | n/a | 'handlers' : ['hand1'], |
---|
2285 | n/a | }, |
---|
2286 | n/a | }, |
---|
2287 | n/a | 'root' : { |
---|
2288 | n/a | 'level' : 'WARNING', |
---|
2289 | n/a | }, |
---|
2290 | n/a | } |
---|
2291 | n/a | |
---|
2292 | n/a | # config8 defines both compiler and compiler.lexer |
---|
2293 | n/a | # so compiler.parser should not be disabled (since |
---|
2294 | n/a | # compiler is defined) |
---|
2295 | n/a | config8 = { |
---|
2296 | n/a | 'version': 1, |
---|
2297 | n/a | 'disable_existing_loggers' : False, |
---|
2298 | n/a | 'formatters': { |
---|
2299 | n/a | 'form1' : { |
---|
2300 | n/a | 'format' : '%(levelname)s ++ %(message)s', |
---|
2301 | n/a | }, |
---|
2302 | n/a | }, |
---|
2303 | n/a | 'handlers' : { |
---|
2304 | n/a | 'hand1' : { |
---|
2305 | n/a | 'class' : 'logging.StreamHandler', |
---|
2306 | n/a | 'formatter' : 'form1', |
---|
2307 | n/a | 'level' : 'NOTSET', |
---|
2308 | n/a | 'stream' : 'ext://sys.stdout', |
---|
2309 | n/a | }, |
---|
2310 | n/a | }, |
---|
2311 | n/a | 'loggers' : { |
---|
2312 | n/a | 'compiler' : { |
---|
2313 | n/a | 'level' : 'DEBUG', |
---|
2314 | n/a | 'handlers' : ['hand1'], |
---|
2315 | n/a | }, |
---|
2316 | n/a | 'compiler.lexer' : { |
---|
2317 | n/a | }, |
---|
2318 | n/a | }, |
---|
2319 | n/a | 'root' : { |
---|
2320 | n/a | 'level' : 'WARNING', |
---|
2321 | n/a | }, |
---|
2322 | n/a | } |
---|
2323 | n/a | |
---|
2324 | n/a | # config8a disables existing loggers |
---|
2325 | n/a | config8a = { |
---|
2326 | n/a | 'version': 1, |
---|
2327 | n/a | 'disable_existing_loggers' : True, |
---|
2328 | n/a | 'formatters': { |
---|
2329 | n/a | 'form1' : { |
---|
2330 | n/a | 'format' : '%(levelname)s ++ %(message)s', |
---|
2331 | n/a | }, |
---|
2332 | n/a | }, |
---|
2333 | n/a | 'handlers' : { |
---|
2334 | n/a | 'hand1' : { |
---|
2335 | n/a | 'class' : 'logging.StreamHandler', |
---|
2336 | n/a | 'formatter' : 'form1', |
---|
2337 | n/a | 'level' : 'NOTSET', |
---|
2338 | n/a | 'stream' : 'ext://sys.stdout', |
---|
2339 | n/a | }, |
---|
2340 | n/a | }, |
---|
2341 | n/a | 'loggers' : { |
---|
2342 | n/a | 'compiler' : { |
---|
2343 | n/a | 'level' : 'DEBUG', |
---|
2344 | n/a | 'handlers' : ['hand1'], |
---|
2345 | n/a | }, |
---|
2346 | n/a | 'compiler.lexer' : { |
---|
2347 | n/a | }, |
---|
2348 | n/a | }, |
---|
2349 | n/a | 'root' : { |
---|
2350 | n/a | 'level' : 'WARNING', |
---|
2351 | n/a | }, |
---|
2352 | n/a | } |
---|
2353 | n/a | |
---|
2354 | n/a | config9 = { |
---|
2355 | n/a | 'version': 1, |
---|
2356 | n/a | 'formatters': { |
---|
2357 | n/a | 'form1' : { |
---|
2358 | n/a | 'format' : '%(levelname)s ++ %(message)s', |
---|
2359 | n/a | }, |
---|
2360 | n/a | }, |
---|
2361 | n/a | 'handlers' : { |
---|
2362 | n/a | 'hand1' : { |
---|
2363 | n/a | 'class' : 'logging.StreamHandler', |
---|
2364 | n/a | 'formatter' : 'form1', |
---|
2365 | n/a | 'level' : 'WARNING', |
---|
2366 | n/a | 'stream' : 'ext://sys.stdout', |
---|
2367 | n/a | }, |
---|
2368 | n/a | }, |
---|
2369 | n/a | 'loggers' : { |
---|
2370 | n/a | 'compiler.parser' : { |
---|
2371 | n/a | 'level' : 'WARNING', |
---|
2372 | n/a | 'handlers' : ['hand1'], |
---|
2373 | n/a | }, |
---|
2374 | n/a | }, |
---|
2375 | n/a | 'root' : { |
---|
2376 | n/a | 'level' : 'NOTSET', |
---|
2377 | n/a | }, |
---|
2378 | n/a | } |
---|
2379 | n/a | |
---|
2380 | n/a | config9a = { |
---|
2381 | n/a | 'version': 1, |
---|
2382 | n/a | 'incremental' : True, |
---|
2383 | n/a | 'handlers' : { |
---|
2384 | n/a | 'hand1' : { |
---|
2385 | n/a | 'level' : 'WARNING', |
---|
2386 | n/a | }, |
---|
2387 | n/a | }, |
---|
2388 | n/a | 'loggers' : { |
---|
2389 | n/a | 'compiler.parser' : { |
---|
2390 | n/a | 'level' : 'INFO', |
---|
2391 | n/a | }, |
---|
2392 | n/a | }, |
---|
2393 | n/a | } |
---|
2394 | n/a | |
---|
2395 | n/a | config9b = { |
---|
2396 | n/a | 'version': 1, |
---|
2397 | n/a | 'incremental' : True, |
---|
2398 | n/a | 'handlers' : { |
---|
2399 | n/a | 'hand1' : { |
---|
2400 | n/a | 'level' : 'INFO', |
---|
2401 | n/a | }, |
---|
2402 | n/a | }, |
---|
2403 | n/a | 'loggers' : { |
---|
2404 | n/a | 'compiler.parser' : { |
---|
2405 | n/a | 'level' : 'INFO', |
---|
2406 | n/a | }, |
---|
2407 | n/a | }, |
---|
2408 | n/a | } |
---|
2409 | n/a | |
---|
2410 | n/a | #As config1 but with a filter added |
---|
2411 | n/a | config10 = { |
---|
2412 | n/a | 'version': 1, |
---|
2413 | n/a | 'formatters': { |
---|
2414 | n/a | 'form1' : { |
---|
2415 | n/a | 'format' : '%(levelname)s ++ %(message)s', |
---|
2416 | n/a | }, |
---|
2417 | n/a | }, |
---|
2418 | n/a | 'filters' : { |
---|
2419 | n/a | 'filt1' : { |
---|
2420 | n/a | 'name' : 'compiler.parser', |
---|
2421 | n/a | }, |
---|
2422 | n/a | }, |
---|
2423 | n/a | 'handlers' : { |
---|
2424 | n/a | 'hand1' : { |
---|
2425 | n/a | 'class' : 'logging.StreamHandler', |
---|
2426 | n/a | 'formatter' : 'form1', |
---|
2427 | n/a | 'level' : 'NOTSET', |
---|
2428 | n/a | 'stream' : 'ext://sys.stdout', |
---|
2429 | n/a | 'filters' : ['filt1'], |
---|
2430 | n/a | }, |
---|
2431 | n/a | }, |
---|
2432 | n/a | 'loggers' : { |
---|
2433 | n/a | 'compiler.parser' : { |
---|
2434 | n/a | 'level' : 'DEBUG', |
---|
2435 | n/a | 'filters' : ['filt1'], |
---|
2436 | n/a | }, |
---|
2437 | n/a | }, |
---|
2438 | n/a | 'root' : { |
---|
2439 | n/a | 'level' : 'WARNING', |
---|
2440 | n/a | 'handlers' : ['hand1'], |
---|
2441 | n/a | }, |
---|
2442 | n/a | } |
---|
2443 | n/a | |
---|
2444 | n/a | #As config1 but using cfg:// references |
---|
2445 | n/a | config11 = { |
---|
2446 | n/a | 'version': 1, |
---|
2447 | n/a | 'true_formatters': { |
---|
2448 | n/a | 'form1' : { |
---|
2449 | n/a | 'format' : '%(levelname)s ++ %(message)s', |
---|
2450 | n/a | }, |
---|
2451 | n/a | }, |
---|
2452 | n/a | 'handler_configs': { |
---|
2453 | n/a | 'hand1' : { |
---|
2454 | n/a | 'class' : 'logging.StreamHandler', |
---|
2455 | n/a | 'formatter' : 'form1', |
---|
2456 | n/a | 'level' : 'NOTSET', |
---|
2457 | n/a | 'stream' : 'ext://sys.stdout', |
---|
2458 | n/a | }, |
---|
2459 | n/a | }, |
---|
2460 | n/a | 'formatters' : 'cfg://true_formatters', |
---|
2461 | n/a | 'handlers' : { |
---|
2462 | n/a | 'hand1' : 'cfg://handler_configs[hand1]', |
---|
2463 | n/a | }, |
---|
2464 | n/a | 'loggers' : { |
---|
2465 | n/a | 'compiler.parser' : { |
---|
2466 | n/a | 'level' : 'DEBUG', |
---|
2467 | n/a | 'handlers' : ['hand1'], |
---|
2468 | n/a | }, |
---|
2469 | n/a | }, |
---|
2470 | n/a | 'root' : { |
---|
2471 | n/a | 'level' : 'WARNING', |
---|
2472 | n/a | }, |
---|
2473 | n/a | } |
---|
2474 | n/a | |
---|
2475 | n/a | #As config11 but missing the version key |
---|
2476 | n/a | config12 = { |
---|
2477 | n/a | 'true_formatters': { |
---|
2478 | n/a | 'form1' : { |
---|
2479 | n/a | 'format' : '%(levelname)s ++ %(message)s', |
---|
2480 | n/a | }, |
---|
2481 | n/a | }, |
---|
2482 | n/a | 'handler_configs': { |
---|
2483 | n/a | 'hand1' : { |
---|
2484 | n/a | 'class' : 'logging.StreamHandler', |
---|
2485 | n/a | 'formatter' : 'form1', |
---|
2486 | n/a | 'level' : 'NOTSET', |
---|
2487 | n/a | 'stream' : 'ext://sys.stdout', |
---|
2488 | n/a | }, |
---|
2489 | n/a | }, |
---|
2490 | n/a | 'formatters' : 'cfg://true_formatters', |
---|
2491 | n/a | 'handlers' : { |
---|
2492 | n/a | 'hand1' : 'cfg://handler_configs[hand1]', |
---|
2493 | n/a | }, |
---|
2494 | n/a | 'loggers' : { |
---|
2495 | n/a | 'compiler.parser' : { |
---|
2496 | n/a | 'level' : 'DEBUG', |
---|
2497 | n/a | 'handlers' : ['hand1'], |
---|
2498 | n/a | }, |
---|
2499 | n/a | }, |
---|
2500 | n/a | 'root' : { |
---|
2501 | n/a | 'level' : 'WARNING', |
---|
2502 | n/a | }, |
---|
2503 | n/a | } |
---|
2504 | n/a | |
---|
2505 | n/a | #As config11 but using an unsupported version |
---|
2506 | n/a | config13 = { |
---|
2507 | n/a | 'version': 2, |
---|
2508 | n/a | 'true_formatters': { |
---|
2509 | n/a | 'form1' : { |
---|
2510 | n/a | 'format' : '%(levelname)s ++ %(message)s', |
---|
2511 | n/a | }, |
---|
2512 | n/a | }, |
---|
2513 | n/a | 'handler_configs': { |
---|
2514 | n/a | 'hand1' : { |
---|
2515 | n/a | 'class' : 'logging.StreamHandler', |
---|
2516 | n/a | 'formatter' : 'form1', |
---|
2517 | n/a | 'level' : 'NOTSET', |
---|
2518 | n/a | 'stream' : 'ext://sys.stdout', |
---|
2519 | n/a | }, |
---|
2520 | n/a | }, |
---|
2521 | n/a | 'formatters' : 'cfg://true_formatters', |
---|
2522 | n/a | 'handlers' : { |
---|
2523 | n/a | 'hand1' : 'cfg://handler_configs[hand1]', |
---|
2524 | n/a | }, |
---|
2525 | n/a | 'loggers' : { |
---|
2526 | n/a | 'compiler.parser' : { |
---|
2527 | n/a | 'level' : 'DEBUG', |
---|
2528 | n/a | 'handlers' : ['hand1'], |
---|
2529 | n/a | }, |
---|
2530 | n/a | }, |
---|
2531 | n/a | 'root' : { |
---|
2532 | n/a | 'level' : 'WARNING', |
---|
2533 | n/a | }, |
---|
2534 | n/a | } |
---|
2535 | n/a | |
---|
2536 | n/a | # As config0, but with properties |
---|
2537 | n/a | config14 = { |
---|
2538 | n/a | 'version': 1, |
---|
2539 | n/a | 'formatters': { |
---|
2540 | n/a | 'form1' : { |
---|
2541 | n/a | 'format' : '%(levelname)s ++ %(message)s', |
---|
2542 | n/a | }, |
---|
2543 | n/a | }, |
---|
2544 | n/a | 'handlers' : { |
---|
2545 | n/a | 'hand1' : { |
---|
2546 | n/a | 'class' : 'logging.StreamHandler', |
---|
2547 | n/a | 'formatter' : 'form1', |
---|
2548 | n/a | 'level' : 'NOTSET', |
---|
2549 | n/a | 'stream' : 'ext://sys.stdout', |
---|
2550 | n/a | '.': { |
---|
2551 | n/a | 'foo': 'bar', |
---|
2552 | n/a | 'terminator': '!\n', |
---|
2553 | n/a | } |
---|
2554 | n/a | }, |
---|
2555 | n/a | }, |
---|
2556 | n/a | 'root' : { |
---|
2557 | n/a | 'level' : 'WARNING', |
---|
2558 | n/a | 'handlers' : ['hand1'], |
---|
2559 | n/a | }, |
---|
2560 | n/a | } |
---|
2561 | n/a | |
---|
2562 | n/a | out_of_order = { |
---|
2563 | n/a | "version": 1, |
---|
2564 | n/a | "formatters": { |
---|
2565 | n/a | "mySimpleFormatter": { |
---|
2566 | n/a | "format": "%(asctime)s (%(name)s) %(levelname)s: %(message)s", |
---|
2567 | n/a | "style": "$" |
---|
2568 | n/a | } |
---|
2569 | n/a | }, |
---|
2570 | n/a | "handlers": { |
---|
2571 | n/a | "fileGlobal": { |
---|
2572 | n/a | "class": "logging.StreamHandler", |
---|
2573 | n/a | "level": "DEBUG", |
---|
2574 | n/a | "formatter": "mySimpleFormatter" |
---|
2575 | n/a | }, |
---|
2576 | n/a | "bufferGlobal": { |
---|
2577 | n/a | "class": "logging.handlers.MemoryHandler", |
---|
2578 | n/a | "capacity": 5, |
---|
2579 | n/a | "formatter": "mySimpleFormatter", |
---|
2580 | n/a | "target": "fileGlobal", |
---|
2581 | n/a | "level": "DEBUG" |
---|
2582 | n/a | } |
---|
2583 | n/a | }, |
---|
2584 | n/a | "loggers": { |
---|
2585 | n/a | "mymodule": { |
---|
2586 | n/a | "level": "DEBUG", |
---|
2587 | n/a | "handlers": ["bufferGlobal"], |
---|
2588 | n/a | "propagate": "true" |
---|
2589 | n/a | } |
---|
2590 | n/a | } |
---|
2591 | n/a | } |
---|
2592 | n/a | |
---|
2593 | n/a | def apply_config(self, conf): |
---|
2594 | n/a | logging.config.dictConfig(conf) |
---|
2595 | n/a | |
---|
2596 | n/a | def test_config0_ok(self): |
---|
2597 | n/a | # A simple config which overrides the default settings. |
---|
2598 | n/a | with support.captured_stdout() as output: |
---|
2599 | n/a | self.apply_config(self.config0) |
---|
2600 | n/a | logger = logging.getLogger() |
---|
2601 | n/a | # Won't output anything |
---|
2602 | n/a | logger.info(self.next_message()) |
---|
2603 | n/a | # Outputs a message |
---|
2604 | n/a | logger.error(self.next_message()) |
---|
2605 | n/a | self.assert_log_lines([ |
---|
2606 | n/a | ('ERROR', '2'), |
---|
2607 | n/a | ], stream=output) |
---|
2608 | n/a | # Original logger output is empty. |
---|
2609 | n/a | self.assert_log_lines([]) |
---|
2610 | n/a | |
---|
2611 | n/a | def test_config1_ok(self, config=config1): |
---|
2612 | n/a | # A config defining a sub-parser as well. |
---|
2613 | n/a | with support.captured_stdout() as output: |
---|
2614 | n/a | self.apply_config(config) |
---|
2615 | n/a | logger = logging.getLogger("compiler.parser") |
---|
2616 | n/a | # Both will output a message |
---|
2617 | n/a | logger.info(self.next_message()) |
---|
2618 | n/a | logger.error(self.next_message()) |
---|
2619 | n/a | self.assert_log_lines([ |
---|
2620 | n/a | ('INFO', '1'), |
---|
2621 | n/a | ('ERROR', '2'), |
---|
2622 | n/a | ], stream=output) |
---|
2623 | n/a | # Original logger output is empty. |
---|
2624 | n/a | self.assert_log_lines([]) |
---|
2625 | n/a | |
---|
2626 | n/a | def test_config2_failure(self): |
---|
2627 | n/a | # A simple config which overrides the default settings. |
---|
2628 | n/a | self.assertRaises(Exception, self.apply_config, self.config2) |
---|
2629 | n/a | |
---|
2630 | n/a | def test_config2a_failure(self): |
---|
2631 | n/a | # A simple config which overrides the default settings. |
---|
2632 | n/a | self.assertRaises(Exception, self.apply_config, self.config2a) |
---|
2633 | n/a | |
---|
2634 | n/a | def test_config2b_failure(self): |
---|
2635 | n/a | # A simple config which overrides the default settings. |
---|
2636 | n/a | self.assertRaises(Exception, self.apply_config, self.config2b) |
---|
2637 | n/a | |
---|
2638 | n/a | def test_config3_failure(self): |
---|
2639 | n/a | # A simple config which overrides the default settings. |
---|
2640 | n/a | self.assertRaises(Exception, self.apply_config, self.config3) |
---|
2641 | n/a | |
---|
2642 | n/a | def test_config4_ok(self): |
---|
2643 | n/a | # A config specifying a custom formatter class. |
---|
2644 | n/a | with support.captured_stdout() as output: |
---|
2645 | n/a | self.apply_config(self.config4) |
---|
2646 | n/a | #logger = logging.getLogger() |
---|
2647 | n/a | try: |
---|
2648 | n/a | raise RuntimeError() |
---|
2649 | n/a | except RuntimeError: |
---|
2650 | n/a | logging.exception("just testing") |
---|
2651 | n/a | sys.stdout.seek(0) |
---|
2652 | n/a | self.assertEqual(output.getvalue(), |
---|
2653 | n/a | "ERROR:root:just testing\nGot a [RuntimeError]\n") |
---|
2654 | n/a | # Original logger output is empty |
---|
2655 | n/a | self.assert_log_lines([]) |
---|
2656 | n/a | |
---|
2657 | n/a | def test_config4a_ok(self): |
---|
2658 | n/a | # A config specifying a custom formatter class. |
---|
2659 | n/a | with support.captured_stdout() as output: |
---|
2660 | n/a | self.apply_config(self.config4a) |
---|
2661 | n/a | #logger = logging.getLogger() |
---|
2662 | n/a | try: |
---|
2663 | n/a | raise RuntimeError() |
---|
2664 | n/a | except RuntimeError: |
---|
2665 | n/a | logging.exception("just testing") |
---|
2666 | n/a | sys.stdout.seek(0) |
---|
2667 | n/a | self.assertEqual(output.getvalue(), |
---|
2668 | n/a | "ERROR:root:just testing\nGot a [RuntimeError]\n") |
---|
2669 | n/a | # Original logger output is empty |
---|
2670 | n/a | self.assert_log_lines([]) |
---|
2671 | n/a | |
---|
2672 | n/a | def test_config5_ok(self): |
---|
2673 | n/a | self.test_config1_ok(config=self.config5) |
---|
2674 | n/a | |
---|
2675 | n/a | def test_config6_failure(self): |
---|
2676 | n/a | self.assertRaises(Exception, self.apply_config, self.config6) |
---|
2677 | n/a | |
---|
2678 | n/a | def test_config7_ok(self): |
---|
2679 | n/a | with support.captured_stdout() as output: |
---|
2680 | n/a | self.apply_config(self.config1) |
---|
2681 | n/a | logger = logging.getLogger("compiler.parser") |
---|
2682 | n/a | # Both will output a message |
---|
2683 | n/a | logger.info(self.next_message()) |
---|
2684 | n/a | logger.error(self.next_message()) |
---|
2685 | n/a | self.assert_log_lines([ |
---|
2686 | n/a | ('INFO', '1'), |
---|
2687 | n/a | ('ERROR', '2'), |
---|
2688 | n/a | ], stream=output) |
---|
2689 | n/a | # Original logger output is empty. |
---|
2690 | n/a | self.assert_log_lines([]) |
---|
2691 | n/a | with support.captured_stdout() as output: |
---|
2692 | n/a | self.apply_config(self.config7) |
---|
2693 | n/a | logger = logging.getLogger("compiler.parser") |
---|
2694 | n/a | self.assertTrue(logger.disabled) |
---|
2695 | n/a | logger = logging.getLogger("compiler.lexer") |
---|
2696 | n/a | # Both will output a message |
---|
2697 | n/a | logger.info(self.next_message()) |
---|
2698 | n/a | logger.error(self.next_message()) |
---|
2699 | n/a | self.assert_log_lines([ |
---|
2700 | n/a | ('INFO', '3'), |
---|
2701 | n/a | ('ERROR', '4'), |
---|
2702 | n/a | ], stream=output) |
---|
2703 | n/a | # Original logger output is empty. |
---|
2704 | n/a | self.assert_log_lines([]) |
---|
2705 | n/a | |
---|
2706 | n/a | #Same as test_config_7_ok but don't disable old loggers. |
---|
2707 | n/a | def test_config_8_ok(self): |
---|
2708 | n/a | with support.captured_stdout() as output: |
---|
2709 | n/a | self.apply_config(self.config1) |
---|
2710 | n/a | logger = logging.getLogger("compiler.parser") |
---|
2711 | n/a | # All will output a message |
---|
2712 | n/a | logger.info(self.next_message()) |
---|
2713 | n/a | logger.error(self.next_message()) |
---|
2714 | n/a | self.assert_log_lines([ |
---|
2715 | n/a | ('INFO', '1'), |
---|
2716 | n/a | ('ERROR', '2'), |
---|
2717 | n/a | ], stream=output) |
---|
2718 | n/a | # Original logger output is empty. |
---|
2719 | n/a | self.assert_log_lines([]) |
---|
2720 | n/a | with support.captured_stdout() as output: |
---|
2721 | n/a | self.apply_config(self.config8) |
---|
2722 | n/a | logger = logging.getLogger("compiler.parser") |
---|
2723 | n/a | self.assertFalse(logger.disabled) |
---|
2724 | n/a | # Both will output a message |
---|
2725 | n/a | logger.info(self.next_message()) |
---|
2726 | n/a | logger.error(self.next_message()) |
---|
2727 | n/a | logger = logging.getLogger("compiler.lexer") |
---|
2728 | n/a | # Both will output a message |
---|
2729 | n/a | logger.info(self.next_message()) |
---|
2730 | n/a | logger.error(self.next_message()) |
---|
2731 | n/a | self.assert_log_lines([ |
---|
2732 | n/a | ('INFO', '3'), |
---|
2733 | n/a | ('ERROR', '4'), |
---|
2734 | n/a | ('INFO', '5'), |
---|
2735 | n/a | ('ERROR', '6'), |
---|
2736 | n/a | ], stream=output) |
---|
2737 | n/a | # Original logger output is empty. |
---|
2738 | n/a | self.assert_log_lines([]) |
---|
2739 | n/a | |
---|
2740 | n/a | def test_config_8a_ok(self): |
---|
2741 | n/a | with support.captured_stdout() as output: |
---|
2742 | n/a | self.apply_config(self.config1a) |
---|
2743 | n/a | logger = logging.getLogger("compiler.parser") |
---|
2744 | n/a | # See issue #11424. compiler-hyphenated sorts |
---|
2745 | n/a | # between compiler and compiler.xyz and this |
---|
2746 | n/a | # was preventing compiler.xyz from being included |
---|
2747 | n/a | # in the child loggers of compiler because of an |
---|
2748 | n/a | # overzealous loop termination condition. |
---|
2749 | n/a | hyphenated = logging.getLogger('compiler-hyphenated') |
---|
2750 | n/a | # All will output a message |
---|
2751 | n/a | logger.info(self.next_message()) |
---|
2752 | n/a | logger.error(self.next_message()) |
---|
2753 | n/a | hyphenated.critical(self.next_message()) |
---|
2754 | n/a | self.assert_log_lines([ |
---|
2755 | n/a | ('INFO', '1'), |
---|
2756 | n/a | ('ERROR', '2'), |
---|
2757 | n/a | ('CRITICAL', '3'), |
---|
2758 | n/a | ], stream=output) |
---|
2759 | n/a | # Original logger output is empty. |
---|
2760 | n/a | self.assert_log_lines([]) |
---|
2761 | n/a | with support.captured_stdout() as output: |
---|
2762 | n/a | self.apply_config(self.config8a) |
---|
2763 | n/a | logger = logging.getLogger("compiler.parser") |
---|
2764 | n/a | self.assertFalse(logger.disabled) |
---|
2765 | n/a | # Both will output a message |
---|
2766 | n/a | logger.info(self.next_message()) |
---|
2767 | n/a | logger.error(self.next_message()) |
---|
2768 | n/a | logger = logging.getLogger("compiler.lexer") |
---|
2769 | n/a | # Both will output a message |
---|
2770 | n/a | logger.info(self.next_message()) |
---|
2771 | n/a | logger.error(self.next_message()) |
---|
2772 | n/a | # Will not appear |
---|
2773 | n/a | hyphenated.critical(self.next_message()) |
---|
2774 | n/a | self.assert_log_lines([ |
---|
2775 | n/a | ('INFO', '4'), |
---|
2776 | n/a | ('ERROR', '5'), |
---|
2777 | n/a | ('INFO', '6'), |
---|
2778 | n/a | ('ERROR', '7'), |
---|
2779 | n/a | ], stream=output) |
---|
2780 | n/a | # Original logger output is empty. |
---|
2781 | n/a | self.assert_log_lines([]) |
---|
2782 | n/a | |
---|
2783 | n/a | def test_config_9_ok(self): |
---|
2784 | n/a | with support.captured_stdout() as output: |
---|
2785 | n/a | self.apply_config(self.config9) |
---|
2786 | n/a | logger = logging.getLogger("compiler.parser") |
---|
2787 | n/a | #Nothing will be output since both handler and logger are set to WARNING |
---|
2788 | n/a | logger.info(self.next_message()) |
---|
2789 | n/a | self.assert_log_lines([], stream=output) |
---|
2790 | n/a | self.apply_config(self.config9a) |
---|
2791 | n/a | #Nothing will be output since both handler is still set to WARNING |
---|
2792 | n/a | logger.info(self.next_message()) |
---|
2793 | n/a | self.assert_log_lines([], stream=output) |
---|
2794 | n/a | self.apply_config(self.config9b) |
---|
2795 | n/a | #Message should now be output |
---|
2796 | n/a | logger.info(self.next_message()) |
---|
2797 | n/a | self.assert_log_lines([ |
---|
2798 | n/a | ('INFO', '3'), |
---|
2799 | n/a | ], stream=output) |
---|
2800 | n/a | |
---|
2801 | n/a | def test_config_10_ok(self): |
---|
2802 | n/a | with support.captured_stdout() as output: |
---|
2803 | n/a | self.apply_config(self.config10) |
---|
2804 | n/a | logger = logging.getLogger("compiler.parser") |
---|
2805 | n/a | logger.warning(self.next_message()) |
---|
2806 | n/a | logger = logging.getLogger('compiler') |
---|
2807 | n/a | #Not output, because filtered |
---|
2808 | n/a | logger.warning(self.next_message()) |
---|
2809 | n/a | logger = logging.getLogger('compiler.lexer') |
---|
2810 | n/a | #Not output, because filtered |
---|
2811 | n/a | logger.warning(self.next_message()) |
---|
2812 | n/a | logger = logging.getLogger("compiler.parser.codegen") |
---|
2813 | n/a | #Output, as not filtered |
---|
2814 | n/a | logger.error(self.next_message()) |
---|
2815 | n/a | self.assert_log_lines([ |
---|
2816 | n/a | ('WARNING', '1'), |
---|
2817 | n/a | ('ERROR', '4'), |
---|
2818 | n/a | ], stream=output) |
---|
2819 | n/a | |
---|
2820 | n/a | def test_config11_ok(self): |
---|
2821 | n/a | self.test_config1_ok(self.config11) |
---|
2822 | n/a | |
---|
2823 | n/a | def test_config12_failure(self): |
---|
2824 | n/a | self.assertRaises(Exception, self.apply_config, self.config12) |
---|
2825 | n/a | |
---|
2826 | n/a | def test_config13_failure(self): |
---|
2827 | n/a | self.assertRaises(Exception, self.apply_config, self.config13) |
---|
2828 | n/a | |
---|
2829 | n/a | def test_config14_ok(self): |
---|
2830 | n/a | with support.captured_stdout() as output: |
---|
2831 | n/a | self.apply_config(self.config14) |
---|
2832 | n/a | h = logging._handlers['hand1'] |
---|
2833 | n/a | self.assertEqual(h.foo, 'bar') |
---|
2834 | n/a | self.assertEqual(h.terminator, '!\n') |
---|
2835 | n/a | logging.warning('Exclamation') |
---|
2836 | n/a | self.assertTrue(output.getvalue().endswith('Exclamation!\n')) |
---|
2837 | n/a | |
---|
2838 | n/a | @unittest.skipUnless(threading, 'listen() needs threading to work') |
---|
2839 | n/a | def setup_via_listener(self, text, verify=None): |
---|
2840 | n/a | text = text.encode("utf-8") |
---|
2841 | n/a | # Ask for a randomly assigned port (by using port 0) |
---|
2842 | n/a | t = logging.config.listen(0, verify) |
---|
2843 | n/a | t.start() |
---|
2844 | n/a | t.ready.wait() |
---|
2845 | n/a | # Now get the port allocated |
---|
2846 | n/a | port = t.port |
---|
2847 | n/a | t.ready.clear() |
---|
2848 | n/a | try: |
---|
2849 | n/a | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
---|
2850 | n/a | sock.settimeout(2.0) |
---|
2851 | n/a | sock.connect(('localhost', port)) |
---|
2852 | n/a | |
---|
2853 | n/a | slen = struct.pack('>L', len(text)) |
---|
2854 | n/a | s = slen + text |
---|
2855 | n/a | sentsofar = 0 |
---|
2856 | n/a | left = len(s) |
---|
2857 | n/a | while left > 0: |
---|
2858 | n/a | sent = sock.send(s[sentsofar:]) |
---|
2859 | n/a | sentsofar += sent |
---|
2860 | n/a | left -= sent |
---|
2861 | n/a | sock.close() |
---|
2862 | n/a | finally: |
---|
2863 | n/a | t.ready.wait(2.0) |
---|
2864 | n/a | logging.config.stopListening() |
---|
2865 | n/a | t.join(2.0) |
---|
2866 | n/a | |
---|
2867 | n/a | @unittest.skipUnless(threading, 'Threading required for this test.') |
---|
2868 | n/a | def test_listen_config_10_ok(self): |
---|
2869 | n/a | with support.captured_stdout() as output: |
---|
2870 | n/a | self.setup_via_listener(json.dumps(self.config10)) |
---|
2871 | n/a | logger = logging.getLogger("compiler.parser") |
---|
2872 | n/a | logger.warning(self.next_message()) |
---|
2873 | n/a | logger = logging.getLogger('compiler') |
---|
2874 | n/a | #Not output, because filtered |
---|
2875 | n/a | logger.warning(self.next_message()) |
---|
2876 | n/a | logger = logging.getLogger('compiler.lexer') |
---|
2877 | n/a | #Not output, because filtered |
---|
2878 | n/a | logger.warning(self.next_message()) |
---|
2879 | n/a | logger = logging.getLogger("compiler.parser.codegen") |
---|
2880 | n/a | #Output, as not filtered |
---|
2881 | n/a | logger.error(self.next_message()) |
---|
2882 | n/a | self.assert_log_lines([ |
---|
2883 | n/a | ('WARNING', '1'), |
---|
2884 | n/a | ('ERROR', '4'), |
---|
2885 | n/a | ], stream=output) |
---|
2886 | n/a | |
---|
2887 | n/a | @unittest.skipUnless(threading, 'Threading required for this test.') |
---|
2888 | n/a | def test_listen_config_1_ok(self): |
---|
2889 | n/a | with support.captured_stdout() as output: |
---|
2890 | n/a | self.setup_via_listener(textwrap.dedent(ConfigFileTest.config1)) |
---|
2891 | n/a | logger = logging.getLogger("compiler.parser") |
---|
2892 | n/a | # Both will output a message |
---|
2893 | n/a | logger.info(self.next_message()) |
---|
2894 | n/a | logger.error(self.next_message()) |
---|
2895 | n/a | self.assert_log_lines([ |
---|
2896 | n/a | ('INFO', '1'), |
---|
2897 | n/a | ('ERROR', '2'), |
---|
2898 | n/a | ], stream=output) |
---|
2899 | n/a | # Original logger output is empty. |
---|
2900 | n/a | self.assert_log_lines([]) |
---|
2901 | n/a | |
---|
2902 | n/a | @unittest.skipUnless(threading, 'Threading required for this test.') |
---|
2903 | n/a | def test_listen_verify(self): |
---|
2904 | n/a | |
---|
2905 | n/a | def verify_fail(stuff): |
---|
2906 | n/a | return None |
---|
2907 | n/a | |
---|
2908 | n/a | def verify_reverse(stuff): |
---|
2909 | n/a | return stuff[::-1] |
---|
2910 | n/a | |
---|
2911 | n/a | logger = logging.getLogger("compiler.parser") |
---|
2912 | n/a | to_send = textwrap.dedent(ConfigFileTest.config1) |
---|
2913 | n/a | # First, specify a verification function that will fail. |
---|
2914 | n/a | # We expect to see no output, since our configuration |
---|
2915 | n/a | # never took effect. |
---|
2916 | n/a | with support.captured_stdout() as output: |
---|
2917 | n/a | self.setup_via_listener(to_send, verify_fail) |
---|
2918 | n/a | # Both will output a message |
---|
2919 | n/a | logger.info(self.next_message()) |
---|
2920 | n/a | logger.error(self.next_message()) |
---|
2921 | n/a | self.assert_log_lines([], stream=output) |
---|
2922 | n/a | # Original logger output has the stuff we logged. |
---|
2923 | n/a | self.assert_log_lines([ |
---|
2924 | n/a | ('INFO', '1'), |
---|
2925 | n/a | ('ERROR', '2'), |
---|
2926 | n/a | ], pat=r"^[\w.]+ -> (\w+): (\d+)$") |
---|
2927 | n/a | |
---|
2928 | n/a | # Now, perform no verification. Our configuration |
---|
2929 | n/a | # should take effect. |
---|
2930 | n/a | |
---|
2931 | n/a | with support.captured_stdout() as output: |
---|
2932 | n/a | self.setup_via_listener(to_send) # no verify callable specified |
---|
2933 | n/a | logger = logging.getLogger("compiler.parser") |
---|
2934 | n/a | # Both will output a message |
---|
2935 | n/a | logger.info(self.next_message()) |
---|
2936 | n/a | logger.error(self.next_message()) |
---|
2937 | n/a | self.assert_log_lines([ |
---|
2938 | n/a | ('INFO', '3'), |
---|
2939 | n/a | ('ERROR', '4'), |
---|
2940 | n/a | ], stream=output) |
---|
2941 | n/a | # Original logger output still has the stuff we logged before. |
---|
2942 | n/a | self.assert_log_lines([ |
---|
2943 | n/a | ('INFO', '1'), |
---|
2944 | n/a | ('ERROR', '2'), |
---|
2945 | n/a | ], pat=r"^[\w.]+ -> (\w+): (\d+)$") |
---|
2946 | n/a | |
---|
2947 | n/a | # Now, perform verification which transforms the bytes. |
---|
2948 | n/a | |
---|
2949 | n/a | with support.captured_stdout() as output: |
---|
2950 | n/a | self.setup_via_listener(to_send[::-1], verify_reverse) |
---|
2951 | n/a | logger = logging.getLogger("compiler.parser") |
---|
2952 | n/a | # Both will output a message |
---|
2953 | n/a | logger.info(self.next_message()) |
---|
2954 | n/a | logger.error(self.next_message()) |
---|
2955 | n/a | self.assert_log_lines([ |
---|
2956 | n/a | ('INFO', '5'), |
---|
2957 | n/a | ('ERROR', '6'), |
---|
2958 | n/a | ], stream=output) |
---|
2959 | n/a | # Original logger output still has the stuff we logged before. |
---|
2960 | n/a | self.assert_log_lines([ |
---|
2961 | n/a | ('INFO', '1'), |
---|
2962 | n/a | ('ERROR', '2'), |
---|
2963 | n/a | ], pat=r"^[\w.]+ -> (\w+): (\d+)$") |
---|
2964 | n/a | |
---|
2965 | n/a | def test_out_of_order(self): |
---|
2966 | n/a | self.apply_config(self.out_of_order) |
---|
2967 | n/a | handler = logging.getLogger('mymodule').handlers[0] |
---|
2968 | n/a | self.assertIsInstance(handler.target, logging.Handler) |
---|
2969 | n/a | self.assertIsInstance(handler.formatter._style, |
---|
2970 | n/a | logging.StringTemplateStyle) |
---|
2971 | n/a | |
---|
2972 | n/a | def test_baseconfig(self): |
---|
2973 | n/a | d = { |
---|
2974 | n/a | 'atuple': (1, 2, 3), |
---|
2975 | n/a | 'alist': ['a', 'b', 'c'], |
---|
2976 | n/a | 'adict': {'d': 'e', 'f': 3 }, |
---|
2977 | n/a | 'nest1': ('g', ('h', 'i'), 'j'), |
---|
2978 | n/a | 'nest2': ['k', ['l', 'm'], 'n'], |
---|
2979 | n/a | 'nest3': ['o', 'cfg://alist', 'p'], |
---|
2980 | n/a | } |
---|
2981 | n/a | bc = logging.config.BaseConfigurator(d) |
---|
2982 | n/a | self.assertEqual(bc.convert('cfg://atuple[1]'), 2) |
---|
2983 | n/a | self.assertEqual(bc.convert('cfg://alist[1]'), 'b') |
---|
2984 | n/a | self.assertEqual(bc.convert('cfg://nest1[1][0]'), 'h') |
---|
2985 | n/a | self.assertEqual(bc.convert('cfg://nest2[1][1]'), 'm') |
---|
2986 | n/a | self.assertEqual(bc.convert('cfg://adict.d'), 'e') |
---|
2987 | n/a | self.assertEqual(bc.convert('cfg://adict[f]'), 3) |
---|
2988 | n/a | v = bc.convert('cfg://nest3') |
---|
2989 | n/a | self.assertEqual(v.pop(1), ['a', 'b', 'c']) |
---|
2990 | n/a | self.assertRaises(KeyError, bc.convert, 'cfg://nosuch') |
---|
2991 | n/a | self.assertRaises(ValueError, bc.convert, 'cfg://!') |
---|
2992 | n/a | self.assertRaises(KeyError, bc.convert, 'cfg://adict[2]') |
---|
2993 | n/a | |
---|
2994 | n/a | class ManagerTest(BaseTest): |
---|
2995 | n/a | def test_manager_loggerclass(self): |
---|
2996 | n/a | logged = [] |
---|
2997 | n/a | |
---|
2998 | n/a | class MyLogger(logging.Logger): |
---|
2999 | n/a | def _log(self, level, msg, args, exc_info=None, extra=None): |
---|
3000 | n/a | logged.append(msg) |
---|
3001 | n/a | |
---|
3002 | n/a | man = logging.Manager(None) |
---|
3003 | n/a | self.assertRaises(TypeError, man.setLoggerClass, int) |
---|
3004 | n/a | man.setLoggerClass(MyLogger) |
---|
3005 | n/a | logger = man.getLogger('test') |
---|
3006 | n/a | logger.warning('should appear in logged') |
---|
3007 | n/a | logging.warning('should not appear in logged') |
---|
3008 | n/a | |
---|
3009 | n/a | self.assertEqual(logged, ['should appear in logged']) |
---|
3010 | n/a | |
---|
3011 | n/a | def test_set_log_record_factory(self): |
---|
3012 | n/a | man = logging.Manager(None) |
---|
3013 | n/a | expected = object() |
---|
3014 | n/a | man.setLogRecordFactory(expected) |
---|
3015 | n/a | self.assertEqual(man.logRecordFactory, expected) |
---|
3016 | n/a | |
---|
3017 | n/a | class ChildLoggerTest(BaseTest): |
---|
3018 | n/a | def test_child_loggers(self): |
---|
3019 | n/a | r = logging.getLogger() |
---|
3020 | n/a | l1 = logging.getLogger('abc') |
---|
3021 | n/a | l2 = logging.getLogger('def.ghi') |
---|
3022 | n/a | c1 = r.getChild('xyz') |
---|
3023 | n/a | c2 = r.getChild('uvw.xyz') |
---|
3024 | n/a | self.assertIs(c1, logging.getLogger('xyz')) |
---|
3025 | n/a | self.assertIs(c2, logging.getLogger('uvw.xyz')) |
---|
3026 | n/a | c1 = l1.getChild('def') |
---|
3027 | n/a | c2 = c1.getChild('ghi') |
---|
3028 | n/a | c3 = l1.getChild('def.ghi') |
---|
3029 | n/a | self.assertIs(c1, logging.getLogger('abc.def')) |
---|
3030 | n/a | self.assertIs(c2, logging.getLogger('abc.def.ghi')) |
---|
3031 | n/a | self.assertIs(c2, c3) |
---|
3032 | n/a | |
---|
3033 | n/a | |
---|
3034 | n/a | class DerivedLogRecord(logging.LogRecord): |
---|
3035 | n/a | pass |
---|
3036 | n/a | |
---|
3037 | n/a | class LogRecordFactoryTest(BaseTest): |
---|
3038 | n/a | |
---|
3039 | n/a | def setUp(self): |
---|
3040 | n/a | class CheckingFilter(logging.Filter): |
---|
3041 | n/a | def __init__(self, cls): |
---|
3042 | n/a | self.cls = cls |
---|
3043 | n/a | |
---|
3044 | n/a | def filter(self, record): |
---|
3045 | n/a | t = type(record) |
---|
3046 | n/a | if t is not self.cls: |
---|
3047 | n/a | msg = 'Unexpected LogRecord type %s, expected %s' % (t, |
---|
3048 | n/a | self.cls) |
---|
3049 | n/a | raise TypeError(msg) |
---|
3050 | n/a | return True |
---|
3051 | n/a | |
---|
3052 | n/a | BaseTest.setUp(self) |
---|
3053 | n/a | self.filter = CheckingFilter(DerivedLogRecord) |
---|
3054 | n/a | self.root_logger.addFilter(self.filter) |
---|
3055 | n/a | self.orig_factory = logging.getLogRecordFactory() |
---|
3056 | n/a | |
---|
3057 | n/a | def tearDown(self): |
---|
3058 | n/a | self.root_logger.removeFilter(self.filter) |
---|
3059 | n/a | BaseTest.tearDown(self) |
---|
3060 | n/a | logging.setLogRecordFactory(self.orig_factory) |
---|
3061 | n/a | |
---|
3062 | n/a | def test_logrecord_class(self): |
---|
3063 | n/a | self.assertRaises(TypeError, self.root_logger.warning, |
---|
3064 | n/a | self.next_message()) |
---|
3065 | n/a | logging.setLogRecordFactory(DerivedLogRecord) |
---|
3066 | n/a | self.root_logger.error(self.next_message()) |
---|
3067 | n/a | self.assert_log_lines([ |
---|
3068 | n/a | ('root', 'ERROR', '2'), |
---|
3069 | n/a | ]) |
---|
3070 | n/a | |
---|
3071 | n/a | |
---|
3072 | n/a | class QueueHandlerTest(BaseTest): |
---|
3073 | n/a | # Do not bother with a logger name group. |
---|
3074 | n/a | expected_log_pat = r"^[\w.]+ -> (\w+): (\d+)$" |
---|
3075 | n/a | |
---|
3076 | n/a | def setUp(self): |
---|
3077 | n/a | BaseTest.setUp(self) |
---|
3078 | n/a | self.queue = queue.Queue(-1) |
---|
3079 | n/a | self.que_hdlr = logging.handlers.QueueHandler(self.queue) |
---|
3080 | n/a | self.que_logger = logging.getLogger('que') |
---|
3081 | n/a | self.que_logger.propagate = False |
---|
3082 | n/a | self.que_logger.setLevel(logging.WARNING) |
---|
3083 | n/a | self.que_logger.addHandler(self.que_hdlr) |
---|
3084 | n/a | |
---|
3085 | n/a | def tearDown(self): |
---|
3086 | n/a | self.que_hdlr.close() |
---|
3087 | n/a | BaseTest.tearDown(self) |
---|
3088 | n/a | |
---|
3089 | n/a | def test_queue_handler(self): |
---|
3090 | n/a | self.que_logger.debug(self.next_message()) |
---|
3091 | n/a | self.assertRaises(queue.Empty, self.queue.get_nowait) |
---|
3092 | n/a | self.que_logger.info(self.next_message()) |
---|
3093 | n/a | self.assertRaises(queue.Empty, self.queue.get_nowait) |
---|
3094 | n/a | msg = self.next_message() |
---|
3095 | n/a | self.que_logger.warning(msg) |
---|
3096 | n/a | data = self.queue.get_nowait() |
---|
3097 | n/a | self.assertTrue(isinstance(data, logging.LogRecord)) |
---|
3098 | n/a | self.assertEqual(data.name, self.que_logger.name) |
---|
3099 | n/a | self.assertEqual((data.msg, data.args), (msg, None)) |
---|
3100 | n/a | |
---|
3101 | n/a | @unittest.skipUnless(hasattr(logging.handlers, 'QueueListener'), |
---|
3102 | n/a | 'logging.handlers.QueueListener required for this test') |
---|
3103 | n/a | def test_queue_listener(self): |
---|
3104 | n/a | handler = support.TestHandler(support.Matcher()) |
---|
3105 | n/a | listener = logging.handlers.QueueListener(self.queue, handler) |
---|
3106 | n/a | listener.start() |
---|
3107 | n/a | try: |
---|
3108 | n/a | self.que_logger.warning(self.next_message()) |
---|
3109 | n/a | self.que_logger.error(self.next_message()) |
---|
3110 | n/a | self.que_logger.critical(self.next_message()) |
---|
3111 | n/a | finally: |
---|
3112 | n/a | listener.stop() |
---|
3113 | n/a | self.assertTrue(handler.matches(levelno=logging.WARNING, message='1')) |
---|
3114 | n/a | self.assertTrue(handler.matches(levelno=logging.ERROR, message='2')) |
---|
3115 | n/a | self.assertTrue(handler.matches(levelno=logging.CRITICAL, message='3')) |
---|
3116 | n/a | handler.close() |
---|
3117 | n/a | |
---|
3118 | n/a | # Now test with respect_handler_level set |
---|
3119 | n/a | |
---|
3120 | n/a | handler = support.TestHandler(support.Matcher()) |
---|
3121 | n/a | handler.setLevel(logging.CRITICAL) |
---|
3122 | n/a | listener = logging.handlers.QueueListener(self.queue, handler, |
---|
3123 | n/a | respect_handler_level=True) |
---|
3124 | n/a | listener.start() |
---|
3125 | n/a | try: |
---|
3126 | n/a | self.que_logger.warning(self.next_message()) |
---|
3127 | n/a | self.que_logger.error(self.next_message()) |
---|
3128 | n/a | self.que_logger.critical(self.next_message()) |
---|
3129 | n/a | finally: |
---|
3130 | n/a | listener.stop() |
---|
3131 | n/a | self.assertFalse(handler.matches(levelno=logging.WARNING, message='4')) |
---|
3132 | n/a | self.assertFalse(handler.matches(levelno=logging.ERROR, message='5')) |
---|
3133 | n/a | self.assertTrue(handler.matches(levelno=logging.CRITICAL, message='6')) |
---|
3134 | n/a | |
---|
3135 | n/a | if hasattr(logging.handlers, 'QueueListener'): |
---|
3136 | n/a | import multiprocessing |
---|
3137 | n/a | from unittest.mock import patch |
---|
3138 | n/a | |
---|
3139 | n/a | class QueueListenerTest(BaseTest): |
---|
3140 | n/a | """ |
---|
3141 | n/a | Tests based on patch submitted for issue #27930. Ensure that |
---|
3142 | n/a | QueueListener handles all log messages. |
---|
3143 | n/a | """ |
---|
3144 | n/a | |
---|
3145 | n/a | repeat = 20 |
---|
3146 | n/a | |
---|
3147 | n/a | @staticmethod |
---|
3148 | n/a | def setup_and_log(log_queue, ident): |
---|
3149 | n/a | """ |
---|
3150 | n/a | Creates a logger with a QueueHandler that logs to a queue read by a |
---|
3151 | n/a | QueueListener. Starts the listener, logs five messages, and stops |
---|
3152 | n/a | the listener. |
---|
3153 | n/a | """ |
---|
3154 | n/a | logger = logging.getLogger('test_logger_with_id_%s' % ident) |
---|
3155 | n/a | logger.setLevel(logging.DEBUG) |
---|
3156 | n/a | handler = logging.handlers.QueueHandler(log_queue) |
---|
3157 | n/a | logger.addHandler(handler) |
---|
3158 | n/a | listener = logging.handlers.QueueListener(log_queue) |
---|
3159 | n/a | listener.start() |
---|
3160 | n/a | |
---|
3161 | n/a | logger.info('one') |
---|
3162 | n/a | logger.info('two') |
---|
3163 | n/a | logger.info('three') |
---|
3164 | n/a | logger.info('four') |
---|
3165 | n/a | logger.info('five') |
---|
3166 | n/a | |
---|
3167 | n/a | listener.stop() |
---|
3168 | n/a | logger.removeHandler(handler) |
---|
3169 | n/a | handler.close() |
---|
3170 | n/a | |
---|
3171 | n/a | @patch.object(logging.handlers.QueueListener, 'handle') |
---|
3172 | n/a | def test_handle_called_with_queue_queue(self, mock_handle): |
---|
3173 | n/a | for i in range(self.repeat): |
---|
3174 | n/a | log_queue = queue.Queue() |
---|
3175 | n/a | self.setup_and_log(log_queue, '%s_%s' % (self.id(), i)) |
---|
3176 | n/a | self.assertEqual(mock_handle.call_count, 5 * self.repeat, |
---|
3177 | n/a | 'correct number of handled log messages') |
---|
3178 | n/a | |
---|
3179 | n/a | @support.requires_multiprocessing_queue |
---|
3180 | n/a | @patch.object(logging.handlers.QueueListener, 'handle') |
---|
3181 | n/a | def test_handle_called_with_mp_queue(self, mock_handle): |
---|
3182 | n/a | for i in range(self.repeat): |
---|
3183 | n/a | log_queue = multiprocessing.Queue() |
---|
3184 | n/a | self.setup_and_log(log_queue, '%s_%s' % (self.id(), i)) |
---|
3185 | n/a | self.assertEqual(mock_handle.call_count, 5 * self.repeat, |
---|
3186 | n/a | 'correct number of handled log messages') |
---|
3187 | n/a | |
---|
3188 | n/a | @staticmethod |
---|
3189 | n/a | def get_all_from_queue(log_queue): |
---|
3190 | n/a | try: |
---|
3191 | n/a | while True: |
---|
3192 | n/a | yield log_queue.get_nowait() |
---|
3193 | n/a | except queue.Empty: |
---|
3194 | n/a | return [] |
---|
3195 | n/a | |
---|
3196 | n/a | @support.requires_multiprocessing_queue |
---|
3197 | n/a | def test_no_messages_in_queue_after_stop(self): |
---|
3198 | n/a | """ |
---|
3199 | n/a | Five messages are logged then the QueueListener is stopped. This |
---|
3200 | n/a | test then gets everything off the queue. Failure of this test |
---|
3201 | n/a | indicates that messages were not registered on the queue until |
---|
3202 | n/a | _after_ the QueueListener stopped. |
---|
3203 | n/a | """ |
---|
3204 | n/a | for i in range(self.repeat): |
---|
3205 | n/a | queue = multiprocessing.Queue() |
---|
3206 | n/a | self.setup_and_log(queue, '%s_%s' %(self.id(), i)) |
---|
3207 | n/a | # time.sleep(1) |
---|
3208 | n/a | items = list(self.get_all_from_queue(queue)) |
---|
3209 | n/a | expected = [[], [logging.handlers.QueueListener._sentinel]] |
---|
3210 | n/a | self.assertIn(items, expected, |
---|
3211 | n/a | 'Found unexpected messages in queue: %s' % ( |
---|
3212 | n/a | [m.msg if isinstance(m, logging.LogRecord) |
---|
3213 | n/a | else m for m in items])) |
---|
3214 | n/a | |
---|
3215 | n/a | |
---|
3216 | n/a | ZERO = datetime.timedelta(0) |
---|
3217 | n/a | |
---|
3218 | n/a | class UTC(datetime.tzinfo): |
---|
3219 | n/a | def utcoffset(self, dt): |
---|
3220 | n/a | return ZERO |
---|
3221 | n/a | |
---|
3222 | n/a | dst = utcoffset |
---|
3223 | n/a | |
---|
3224 | n/a | def tzname(self, dt): |
---|
3225 | n/a | return 'UTC' |
---|
3226 | n/a | |
---|
3227 | n/a | utc = UTC() |
---|
3228 | n/a | |
---|
3229 | n/a | class FormatterTest(unittest.TestCase): |
---|
3230 | n/a | def setUp(self): |
---|
3231 | n/a | self.common = { |
---|
3232 | n/a | 'name': 'formatter.test', |
---|
3233 | n/a | 'level': logging.DEBUG, |
---|
3234 | n/a | 'pathname': os.path.join('path', 'to', 'dummy.ext'), |
---|
3235 | n/a | 'lineno': 42, |
---|
3236 | n/a | 'exc_info': None, |
---|
3237 | n/a | 'func': None, |
---|
3238 | n/a | 'msg': 'Message with %d %s', |
---|
3239 | n/a | 'args': (2, 'placeholders'), |
---|
3240 | n/a | } |
---|
3241 | n/a | self.variants = { |
---|
3242 | n/a | } |
---|
3243 | n/a | |
---|
3244 | n/a | def get_record(self, name=None): |
---|
3245 | n/a | result = dict(self.common) |
---|
3246 | n/a | if name is not None: |
---|
3247 | n/a | result.update(self.variants[name]) |
---|
3248 | n/a | return logging.makeLogRecord(result) |
---|
3249 | n/a | |
---|
3250 | n/a | def test_percent(self): |
---|
3251 | n/a | # Test %-formatting |
---|
3252 | n/a | r = self.get_record() |
---|
3253 | n/a | f = logging.Formatter('${%(message)s}') |
---|
3254 | n/a | self.assertEqual(f.format(r), '${Message with 2 placeholders}') |
---|
3255 | n/a | f = logging.Formatter('%(random)s') |
---|
3256 | n/a | self.assertRaises(KeyError, f.format, r) |
---|
3257 | n/a | self.assertFalse(f.usesTime()) |
---|
3258 | n/a | f = logging.Formatter('%(asctime)s') |
---|
3259 | n/a | self.assertTrue(f.usesTime()) |
---|
3260 | n/a | f = logging.Formatter('%(asctime)-15s') |
---|
3261 | n/a | self.assertTrue(f.usesTime()) |
---|
3262 | n/a | f = logging.Formatter('asctime') |
---|
3263 | n/a | self.assertFalse(f.usesTime()) |
---|
3264 | n/a | |
---|
3265 | n/a | def test_braces(self): |
---|
3266 | n/a | # Test {}-formatting |
---|
3267 | n/a | r = self.get_record() |
---|
3268 | n/a | f = logging.Formatter('$%{message}%$', style='{') |
---|
3269 | n/a | self.assertEqual(f.format(r), '$%Message with 2 placeholders%$') |
---|
3270 | n/a | f = logging.Formatter('{random}', style='{') |
---|
3271 | n/a | self.assertRaises(KeyError, f.format, r) |
---|
3272 | n/a | self.assertFalse(f.usesTime()) |
---|
3273 | n/a | f = logging.Formatter('{asctime}', style='{') |
---|
3274 | n/a | self.assertTrue(f.usesTime()) |
---|
3275 | n/a | f = logging.Formatter('{asctime!s:15}', style='{') |
---|
3276 | n/a | self.assertTrue(f.usesTime()) |
---|
3277 | n/a | f = logging.Formatter('{asctime:15}', style='{') |
---|
3278 | n/a | self.assertTrue(f.usesTime()) |
---|
3279 | n/a | f = logging.Formatter('asctime', style='{') |
---|
3280 | n/a | self.assertFalse(f.usesTime()) |
---|
3281 | n/a | |
---|
3282 | n/a | def test_dollars(self): |
---|
3283 | n/a | # Test $-formatting |
---|
3284 | n/a | r = self.get_record() |
---|
3285 | n/a | f = logging.Formatter('$message', style='$') |
---|
3286 | n/a | self.assertEqual(f.format(r), 'Message with 2 placeholders') |
---|
3287 | n/a | f = logging.Formatter('$$%${message}%$$', style='$') |
---|
3288 | n/a | self.assertEqual(f.format(r), '$%Message with 2 placeholders%$') |
---|
3289 | n/a | f = logging.Formatter('${random}', style='$') |
---|
3290 | n/a | self.assertRaises(KeyError, f.format, r) |
---|
3291 | n/a | self.assertFalse(f.usesTime()) |
---|
3292 | n/a | f = logging.Formatter('${asctime}', style='$') |
---|
3293 | n/a | self.assertTrue(f.usesTime()) |
---|
3294 | n/a | f = logging.Formatter('${asctime', style='$') |
---|
3295 | n/a | self.assertFalse(f.usesTime()) |
---|
3296 | n/a | f = logging.Formatter('$asctime', style='$') |
---|
3297 | n/a | self.assertTrue(f.usesTime()) |
---|
3298 | n/a | f = logging.Formatter('asctime', style='$') |
---|
3299 | n/a | self.assertFalse(f.usesTime()) |
---|
3300 | n/a | |
---|
3301 | n/a | def test_invalid_style(self): |
---|
3302 | n/a | self.assertRaises(ValueError, logging.Formatter, None, None, 'x') |
---|
3303 | n/a | |
---|
3304 | n/a | def test_time(self): |
---|
3305 | n/a | r = self.get_record() |
---|
3306 | n/a | dt = datetime.datetime(1993, 4, 21, 8, 3, 0, 0, utc) |
---|
3307 | n/a | # We use None to indicate we want the local timezone |
---|
3308 | n/a | # We're essentially converting a UTC time to local time |
---|
3309 | n/a | r.created = time.mktime(dt.astimezone(None).timetuple()) |
---|
3310 | n/a | r.msecs = 123 |
---|
3311 | n/a | f = logging.Formatter('%(asctime)s %(message)s') |
---|
3312 | n/a | f.converter = time.gmtime |
---|
3313 | n/a | self.assertEqual(f.formatTime(r), '1993-04-21 08:03:00,123') |
---|
3314 | n/a | self.assertEqual(f.formatTime(r, '%Y:%d'), '1993:21') |
---|
3315 | n/a | f.format(r) |
---|
3316 | n/a | self.assertEqual(r.asctime, '1993-04-21 08:03:00,123') |
---|
3317 | n/a | |
---|
3318 | n/a | class TestBufferingFormatter(logging.BufferingFormatter): |
---|
3319 | n/a | def formatHeader(self, records): |
---|
3320 | n/a | return '[(%d)' % len(records) |
---|
3321 | n/a | |
---|
3322 | n/a | def formatFooter(self, records): |
---|
3323 | n/a | return '(%d)]' % len(records) |
---|
3324 | n/a | |
---|
3325 | n/a | class BufferingFormatterTest(unittest.TestCase): |
---|
3326 | n/a | def setUp(self): |
---|
3327 | n/a | self.records = [ |
---|
3328 | n/a | logging.makeLogRecord({'msg': 'one'}), |
---|
3329 | n/a | logging.makeLogRecord({'msg': 'two'}), |
---|
3330 | n/a | ] |
---|
3331 | n/a | |
---|
3332 | n/a | def test_default(self): |
---|
3333 | n/a | f = logging.BufferingFormatter() |
---|
3334 | n/a | self.assertEqual('', f.format([])) |
---|
3335 | n/a | self.assertEqual('onetwo', f.format(self.records)) |
---|
3336 | n/a | |
---|
3337 | n/a | def test_custom(self): |
---|
3338 | n/a | f = TestBufferingFormatter() |
---|
3339 | n/a | self.assertEqual('[(2)onetwo(2)]', f.format(self.records)) |
---|
3340 | n/a | lf = logging.Formatter('<%(message)s>') |
---|
3341 | n/a | f = TestBufferingFormatter(lf) |
---|
3342 | n/a | self.assertEqual('[(2)<one><two>(2)]', f.format(self.records)) |
---|
3343 | n/a | |
---|
3344 | n/a | class ExceptionTest(BaseTest): |
---|
3345 | n/a | def test_formatting(self): |
---|
3346 | n/a | r = self.root_logger |
---|
3347 | n/a | h = RecordingHandler() |
---|
3348 | n/a | r.addHandler(h) |
---|
3349 | n/a | try: |
---|
3350 | n/a | raise RuntimeError('deliberate mistake') |
---|
3351 | n/a | except: |
---|
3352 | n/a | logging.exception('failed', stack_info=True) |
---|
3353 | n/a | r.removeHandler(h) |
---|
3354 | n/a | h.close() |
---|
3355 | n/a | r = h.records[0] |
---|
3356 | n/a | self.assertTrue(r.exc_text.startswith('Traceback (most recent ' |
---|
3357 | n/a | 'call last):\n')) |
---|
3358 | n/a | self.assertTrue(r.exc_text.endswith('\nRuntimeError: ' |
---|
3359 | n/a | 'deliberate mistake')) |
---|
3360 | n/a | self.assertTrue(r.stack_info.startswith('Stack (most recent ' |
---|
3361 | n/a | 'call last):\n')) |
---|
3362 | n/a | self.assertTrue(r.stack_info.endswith('logging.exception(\'failed\', ' |
---|
3363 | n/a | 'stack_info=True)')) |
---|
3364 | n/a | |
---|
3365 | n/a | |
---|
3366 | n/a | class LastResortTest(BaseTest): |
---|
3367 | n/a | def test_last_resort(self): |
---|
3368 | n/a | # Test the last resort handler |
---|
3369 | n/a | root = self.root_logger |
---|
3370 | n/a | root.removeHandler(self.root_hdlr) |
---|
3371 | n/a | old_lastresort = logging.lastResort |
---|
3372 | n/a | old_raise_exceptions = logging.raiseExceptions |
---|
3373 | n/a | |
---|
3374 | n/a | try: |
---|
3375 | n/a | with support.captured_stderr() as stderr: |
---|
3376 | n/a | root.debug('This should not appear') |
---|
3377 | n/a | self.assertEqual(stderr.getvalue(), '') |
---|
3378 | n/a | root.warning('Final chance!') |
---|
3379 | n/a | self.assertEqual(stderr.getvalue(), 'Final chance!\n') |
---|
3380 | n/a | |
---|
3381 | n/a | # No handlers and no last resort, so 'No handlers' message |
---|
3382 | n/a | logging.lastResort = None |
---|
3383 | n/a | with support.captured_stderr() as stderr: |
---|
3384 | n/a | root.warning('Final chance!') |
---|
3385 | n/a | msg = 'No handlers could be found for logger "root"\n' |
---|
3386 | n/a | self.assertEqual(stderr.getvalue(), msg) |
---|
3387 | n/a | |
---|
3388 | n/a | # 'No handlers' message only printed once |
---|
3389 | n/a | with support.captured_stderr() as stderr: |
---|
3390 | n/a | root.warning('Final chance!') |
---|
3391 | n/a | self.assertEqual(stderr.getvalue(), '') |
---|
3392 | n/a | |
---|
3393 | n/a | # If raiseExceptions is False, no message is printed |
---|
3394 | n/a | root.manager.emittedNoHandlerWarning = False |
---|
3395 | n/a | logging.raiseExceptions = False |
---|
3396 | n/a | with support.captured_stderr() as stderr: |
---|
3397 | n/a | root.warning('Final chance!') |
---|
3398 | n/a | self.assertEqual(stderr.getvalue(), '') |
---|
3399 | n/a | finally: |
---|
3400 | n/a | root.addHandler(self.root_hdlr) |
---|
3401 | n/a | logging.lastResort = old_lastresort |
---|
3402 | n/a | logging.raiseExceptions = old_raise_exceptions |
---|
3403 | n/a | |
---|
3404 | n/a | |
---|
3405 | n/a | class FakeHandler: |
---|
3406 | n/a | |
---|
3407 | n/a | def __init__(self, identifier, called): |
---|
3408 | n/a | for method in ('acquire', 'flush', 'close', 'release'): |
---|
3409 | n/a | setattr(self, method, self.record_call(identifier, method, called)) |
---|
3410 | n/a | |
---|
3411 | n/a | def record_call(self, identifier, method_name, called): |
---|
3412 | n/a | def inner(): |
---|
3413 | n/a | called.append('{} - {}'.format(identifier, method_name)) |
---|
3414 | n/a | return inner |
---|
3415 | n/a | |
---|
3416 | n/a | |
---|
3417 | n/a | class RecordingHandler(logging.NullHandler): |
---|
3418 | n/a | |
---|
3419 | n/a | def __init__(self, *args, **kwargs): |
---|
3420 | n/a | super(RecordingHandler, self).__init__(*args, **kwargs) |
---|
3421 | n/a | self.records = [] |
---|
3422 | n/a | |
---|
3423 | n/a | def handle(self, record): |
---|
3424 | n/a | """Keep track of all the emitted records.""" |
---|
3425 | n/a | self.records.append(record) |
---|
3426 | n/a | |
---|
3427 | n/a | |
---|
3428 | n/a | class ShutdownTest(BaseTest): |
---|
3429 | n/a | |
---|
3430 | n/a | """Test suite for the shutdown method.""" |
---|
3431 | n/a | |
---|
3432 | n/a | def setUp(self): |
---|
3433 | n/a | super(ShutdownTest, self).setUp() |
---|
3434 | n/a | self.called = [] |
---|
3435 | n/a | |
---|
3436 | n/a | raise_exceptions = logging.raiseExceptions |
---|
3437 | n/a | self.addCleanup(setattr, logging, 'raiseExceptions', raise_exceptions) |
---|
3438 | n/a | |
---|
3439 | n/a | def raise_error(self, error): |
---|
3440 | n/a | def inner(): |
---|
3441 | n/a | raise error() |
---|
3442 | n/a | return inner |
---|
3443 | n/a | |
---|
3444 | n/a | def test_no_failure(self): |
---|
3445 | n/a | # create some fake handlers |
---|
3446 | n/a | handler0 = FakeHandler(0, self.called) |
---|
3447 | n/a | handler1 = FakeHandler(1, self.called) |
---|
3448 | n/a | handler2 = FakeHandler(2, self.called) |
---|
3449 | n/a | |
---|
3450 | n/a | # create live weakref to those handlers |
---|
3451 | n/a | handlers = map(logging.weakref.ref, [handler0, handler1, handler2]) |
---|
3452 | n/a | |
---|
3453 | n/a | logging.shutdown(handlerList=list(handlers)) |
---|
3454 | n/a | |
---|
3455 | n/a | expected = ['2 - acquire', '2 - flush', '2 - close', '2 - release', |
---|
3456 | n/a | '1 - acquire', '1 - flush', '1 - close', '1 - release', |
---|
3457 | n/a | '0 - acquire', '0 - flush', '0 - close', '0 - release'] |
---|
3458 | n/a | self.assertEqual(expected, self.called) |
---|
3459 | n/a | |
---|
3460 | n/a | def _test_with_failure_in_method(self, method, error): |
---|
3461 | n/a | handler = FakeHandler(0, self.called) |
---|
3462 | n/a | setattr(handler, method, self.raise_error(error)) |
---|
3463 | n/a | handlers = [logging.weakref.ref(handler)] |
---|
3464 | n/a | |
---|
3465 | n/a | logging.shutdown(handlerList=list(handlers)) |
---|
3466 | n/a | |
---|
3467 | n/a | self.assertEqual('0 - release', self.called[-1]) |
---|
3468 | n/a | |
---|
3469 | n/a | def test_with_ioerror_in_acquire(self): |
---|
3470 | n/a | self._test_with_failure_in_method('acquire', OSError) |
---|
3471 | n/a | |
---|
3472 | n/a | def test_with_ioerror_in_flush(self): |
---|
3473 | n/a | self._test_with_failure_in_method('flush', OSError) |
---|
3474 | n/a | |
---|
3475 | n/a | def test_with_ioerror_in_close(self): |
---|
3476 | n/a | self._test_with_failure_in_method('close', OSError) |
---|
3477 | n/a | |
---|
3478 | n/a | def test_with_valueerror_in_acquire(self): |
---|
3479 | n/a | self._test_with_failure_in_method('acquire', ValueError) |
---|
3480 | n/a | |
---|
3481 | n/a | def test_with_valueerror_in_flush(self): |
---|
3482 | n/a | self._test_with_failure_in_method('flush', ValueError) |
---|
3483 | n/a | |
---|
3484 | n/a | def test_with_valueerror_in_close(self): |
---|
3485 | n/a | self._test_with_failure_in_method('close', ValueError) |
---|
3486 | n/a | |
---|
3487 | n/a | def test_with_other_error_in_acquire_without_raise(self): |
---|
3488 | n/a | logging.raiseExceptions = False |
---|
3489 | n/a | self._test_with_failure_in_method('acquire', IndexError) |
---|
3490 | n/a | |
---|
3491 | n/a | def test_with_other_error_in_flush_without_raise(self): |
---|
3492 | n/a | logging.raiseExceptions = False |
---|
3493 | n/a | self._test_with_failure_in_method('flush', IndexError) |
---|
3494 | n/a | |
---|
3495 | n/a | def test_with_other_error_in_close_without_raise(self): |
---|
3496 | n/a | logging.raiseExceptions = False |
---|
3497 | n/a | self._test_with_failure_in_method('close', IndexError) |
---|
3498 | n/a | |
---|
3499 | n/a | def test_with_other_error_in_acquire_with_raise(self): |
---|
3500 | n/a | logging.raiseExceptions = True |
---|
3501 | n/a | self.assertRaises(IndexError, self._test_with_failure_in_method, |
---|
3502 | n/a | 'acquire', IndexError) |
---|
3503 | n/a | |
---|
3504 | n/a | def test_with_other_error_in_flush_with_raise(self): |
---|
3505 | n/a | logging.raiseExceptions = True |
---|
3506 | n/a | self.assertRaises(IndexError, self._test_with_failure_in_method, |
---|
3507 | n/a | 'flush', IndexError) |
---|
3508 | n/a | |
---|
3509 | n/a | def test_with_other_error_in_close_with_raise(self): |
---|
3510 | n/a | logging.raiseExceptions = True |
---|
3511 | n/a | self.assertRaises(IndexError, self._test_with_failure_in_method, |
---|
3512 | n/a | 'close', IndexError) |
---|
3513 | n/a | |
---|
3514 | n/a | |
---|
3515 | n/a | class ModuleLevelMiscTest(BaseTest): |
---|
3516 | n/a | |
---|
3517 | n/a | """Test suite for some module level methods.""" |
---|
3518 | n/a | |
---|
3519 | n/a | def test_disable(self): |
---|
3520 | n/a | old_disable = logging.root.manager.disable |
---|
3521 | n/a | # confirm our assumptions are correct |
---|
3522 | n/a | self.assertEqual(old_disable, 0) |
---|
3523 | n/a | self.addCleanup(logging.disable, old_disable) |
---|
3524 | n/a | |
---|
3525 | n/a | logging.disable(83) |
---|
3526 | n/a | self.assertEqual(logging.root.manager.disable, 83) |
---|
3527 | n/a | |
---|
3528 | n/a | # test the default value introduced in 3.7 |
---|
3529 | n/a | # (Issue #28524) |
---|
3530 | n/a | logging.disable() |
---|
3531 | n/a | self.assertEqual(logging.root.manager.disable, logging.CRITICAL) |
---|
3532 | n/a | |
---|
3533 | n/a | def _test_log(self, method, level=None): |
---|
3534 | n/a | called = [] |
---|
3535 | n/a | support.patch(self, logging, 'basicConfig', |
---|
3536 | n/a | lambda *a, **kw: called.append((a, kw))) |
---|
3537 | n/a | |
---|
3538 | n/a | recording = RecordingHandler() |
---|
3539 | n/a | logging.root.addHandler(recording) |
---|
3540 | n/a | |
---|
3541 | n/a | log_method = getattr(logging, method) |
---|
3542 | n/a | if level is not None: |
---|
3543 | n/a | log_method(level, "test me: %r", recording) |
---|
3544 | n/a | else: |
---|
3545 | n/a | log_method("test me: %r", recording) |
---|
3546 | n/a | |
---|
3547 | n/a | self.assertEqual(len(recording.records), 1) |
---|
3548 | n/a | record = recording.records[0] |
---|
3549 | n/a | self.assertEqual(record.getMessage(), "test me: %r" % recording) |
---|
3550 | n/a | |
---|
3551 | n/a | expected_level = level if level is not None else getattr(logging, method.upper()) |
---|
3552 | n/a | self.assertEqual(record.levelno, expected_level) |
---|
3553 | n/a | |
---|
3554 | n/a | # basicConfig was not called! |
---|
3555 | n/a | self.assertEqual(called, []) |
---|
3556 | n/a | |
---|
3557 | n/a | def test_log(self): |
---|
3558 | n/a | self._test_log('log', logging.ERROR) |
---|
3559 | n/a | |
---|
3560 | n/a | def test_debug(self): |
---|
3561 | n/a | self._test_log('debug') |
---|
3562 | n/a | |
---|
3563 | n/a | def test_info(self): |
---|
3564 | n/a | self._test_log('info') |
---|
3565 | n/a | |
---|
3566 | n/a | def test_warning(self): |
---|
3567 | n/a | self._test_log('warning') |
---|
3568 | n/a | |
---|
3569 | n/a | def test_error(self): |
---|
3570 | n/a | self._test_log('error') |
---|
3571 | n/a | |
---|
3572 | n/a | def test_critical(self): |
---|
3573 | n/a | self._test_log('critical') |
---|
3574 | n/a | |
---|
3575 | n/a | def test_set_logger_class(self): |
---|
3576 | n/a | self.assertRaises(TypeError, logging.setLoggerClass, object) |
---|
3577 | n/a | |
---|
3578 | n/a | class MyLogger(logging.Logger): |
---|
3579 | n/a | pass |
---|
3580 | n/a | |
---|
3581 | n/a | logging.setLoggerClass(MyLogger) |
---|
3582 | n/a | self.assertEqual(logging.getLoggerClass(), MyLogger) |
---|
3583 | n/a | |
---|
3584 | n/a | logging.setLoggerClass(logging.Logger) |
---|
3585 | n/a | self.assertEqual(logging.getLoggerClass(), logging.Logger) |
---|
3586 | n/a | |
---|
3587 | n/a | @support.requires_type_collecting |
---|
3588 | n/a | def test_logging_at_shutdown(self): |
---|
3589 | n/a | # Issue #20037 |
---|
3590 | n/a | code = """if 1: |
---|
3591 | n/a | import logging |
---|
3592 | n/a | |
---|
3593 | n/a | class A: |
---|
3594 | n/a | def __del__(self): |
---|
3595 | n/a | try: |
---|
3596 | n/a | raise ValueError("some error") |
---|
3597 | n/a | except Exception: |
---|
3598 | n/a | logging.exception("exception in __del__") |
---|
3599 | n/a | |
---|
3600 | n/a | a = A()""" |
---|
3601 | n/a | rc, out, err = assert_python_ok("-c", code) |
---|
3602 | n/a | err = err.decode() |
---|
3603 | n/a | self.assertIn("exception in __del__", err) |
---|
3604 | n/a | self.assertIn("ValueError: some error", err) |
---|
3605 | n/a | |
---|
3606 | n/a | |
---|
3607 | n/a | class LogRecordTest(BaseTest): |
---|
3608 | n/a | def test_str_rep(self): |
---|
3609 | n/a | r = logging.makeLogRecord({}) |
---|
3610 | n/a | s = str(r) |
---|
3611 | n/a | self.assertTrue(s.startswith('<LogRecord: ')) |
---|
3612 | n/a | self.assertTrue(s.endswith('>')) |
---|
3613 | n/a | |
---|
3614 | n/a | def test_dict_arg(self): |
---|
3615 | n/a | h = RecordingHandler() |
---|
3616 | n/a | r = logging.getLogger() |
---|
3617 | n/a | r.addHandler(h) |
---|
3618 | n/a | d = {'less' : 'more' } |
---|
3619 | n/a | logging.warning('less is %(less)s', d) |
---|
3620 | n/a | self.assertIs(h.records[0].args, d) |
---|
3621 | n/a | self.assertEqual(h.records[0].message, 'less is more') |
---|
3622 | n/a | r.removeHandler(h) |
---|
3623 | n/a | h.close() |
---|
3624 | n/a | |
---|
3625 | n/a | def test_multiprocessing(self): |
---|
3626 | n/a | r = logging.makeLogRecord({}) |
---|
3627 | n/a | self.assertEqual(r.processName, 'MainProcess') |
---|
3628 | n/a | try: |
---|
3629 | n/a | import multiprocessing as mp |
---|
3630 | n/a | r = logging.makeLogRecord({}) |
---|
3631 | n/a | self.assertEqual(r.processName, mp.current_process().name) |
---|
3632 | n/a | except ImportError: |
---|
3633 | n/a | pass |
---|
3634 | n/a | |
---|
3635 | n/a | def test_optional(self): |
---|
3636 | n/a | r = logging.makeLogRecord({}) |
---|
3637 | n/a | NOT_NONE = self.assertIsNotNone |
---|
3638 | n/a | if threading: |
---|
3639 | n/a | NOT_NONE(r.thread) |
---|
3640 | n/a | NOT_NONE(r.threadName) |
---|
3641 | n/a | NOT_NONE(r.process) |
---|
3642 | n/a | NOT_NONE(r.processName) |
---|
3643 | n/a | log_threads = logging.logThreads |
---|
3644 | n/a | log_processes = logging.logProcesses |
---|
3645 | n/a | log_multiprocessing = logging.logMultiprocessing |
---|
3646 | n/a | try: |
---|
3647 | n/a | logging.logThreads = False |
---|
3648 | n/a | logging.logProcesses = False |
---|
3649 | n/a | logging.logMultiprocessing = False |
---|
3650 | n/a | r = logging.makeLogRecord({}) |
---|
3651 | n/a | NONE = self.assertIsNone |
---|
3652 | n/a | NONE(r.thread) |
---|
3653 | n/a | NONE(r.threadName) |
---|
3654 | n/a | NONE(r.process) |
---|
3655 | n/a | NONE(r.processName) |
---|
3656 | n/a | finally: |
---|
3657 | n/a | logging.logThreads = log_threads |
---|
3658 | n/a | logging.logProcesses = log_processes |
---|
3659 | n/a | logging.logMultiprocessing = log_multiprocessing |
---|
3660 | n/a | |
---|
3661 | n/a | class BasicConfigTest(unittest.TestCase): |
---|
3662 | n/a | |
---|
3663 | n/a | """Test suite for logging.basicConfig.""" |
---|
3664 | n/a | |
---|
3665 | n/a | def setUp(self): |
---|
3666 | n/a | super(BasicConfigTest, self).setUp() |
---|
3667 | n/a | self.handlers = logging.root.handlers |
---|
3668 | n/a | self.saved_handlers = logging._handlers.copy() |
---|
3669 | n/a | self.saved_handler_list = logging._handlerList[:] |
---|
3670 | n/a | self.original_logging_level = logging.root.level |
---|
3671 | n/a | self.addCleanup(self.cleanup) |
---|
3672 | n/a | logging.root.handlers = [] |
---|
3673 | n/a | |
---|
3674 | n/a | def tearDown(self): |
---|
3675 | n/a | for h in logging.root.handlers[:]: |
---|
3676 | n/a | logging.root.removeHandler(h) |
---|
3677 | n/a | h.close() |
---|
3678 | n/a | super(BasicConfigTest, self).tearDown() |
---|
3679 | n/a | |
---|
3680 | n/a | def cleanup(self): |
---|
3681 | n/a | setattr(logging.root, 'handlers', self.handlers) |
---|
3682 | n/a | logging._handlers.clear() |
---|
3683 | n/a | logging._handlers.update(self.saved_handlers) |
---|
3684 | n/a | logging._handlerList[:] = self.saved_handler_list |
---|
3685 | n/a | logging.root.level = self.original_logging_level |
---|
3686 | n/a | |
---|
3687 | n/a | def test_no_kwargs(self): |
---|
3688 | n/a | logging.basicConfig() |
---|
3689 | n/a | |
---|
3690 | n/a | # handler defaults to a StreamHandler to sys.stderr |
---|
3691 | n/a | self.assertEqual(len(logging.root.handlers), 1) |
---|
3692 | n/a | handler = logging.root.handlers[0] |
---|
3693 | n/a | self.assertIsInstance(handler, logging.StreamHandler) |
---|
3694 | n/a | self.assertEqual(handler.stream, sys.stderr) |
---|
3695 | n/a | |
---|
3696 | n/a | formatter = handler.formatter |
---|
3697 | n/a | # format defaults to logging.BASIC_FORMAT |
---|
3698 | n/a | self.assertEqual(formatter._style._fmt, logging.BASIC_FORMAT) |
---|
3699 | n/a | # datefmt defaults to None |
---|
3700 | n/a | self.assertIsNone(formatter.datefmt) |
---|
3701 | n/a | # style defaults to % |
---|
3702 | n/a | self.assertIsInstance(formatter._style, logging.PercentStyle) |
---|
3703 | n/a | |
---|
3704 | n/a | # level is not explicitly set |
---|
3705 | n/a | self.assertEqual(logging.root.level, self.original_logging_level) |
---|
3706 | n/a | |
---|
3707 | n/a | def test_strformatstyle(self): |
---|
3708 | n/a | with support.captured_stdout() as output: |
---|
3709 | n/a | logging.basicConfig(stream=sys.stdout, style="{") |
---|
3710 | n/a | logging.error("Log an error") |
---|
3711 | n/a | sys.stdout.seek(0) |
---|
3712 | n/a | self.assertEqual(output.getvalue().strip(), |
---|
3713 | n/a | "ERROR:root:Log an error") |
---|
3714 | n/a | |
---|
3715 | n/a | def test_stringtemplatestyle(self): |
---|
3716 | n/a | with support.captured_stdout() as output: |
---|
3717 | n/a | logging.basicConfig(stream=sys.stdout, style="$") |
---|
3718 | n/a | logging.error("Log an error") |
---|
3719 | n/a | sys.stdout.seek(0) |
---|
3720 | n/a | self.assertEqual(output.getvalue().strip(), |
---|
3721 | n/a | "ERROR:root:Log an error") |
---|
3722 | n/a | |
---|
3723 | n/a | def test_filename(self): |
---|
3724 | n/a | |
---|
3725 | n/a | def cleanup(h1, h2, fn): |
---|
3726 | n/a | h1.close() |
---|
3727 | n/a | h2.close() |
---|
3728 | n/a | os.remove(fn) |
---|
3729 | n/a | |
---|
3730 | n/a | logging.basicConfig(filename='test.log') |
---|
3731 | n/a | |
---|
3732 | n/a | self.assertEqual(len(logging.root.handlers), 1) |
---|
3733 | n/a | handler = logging.root.handlers[0] |
---|
3734 | n/a | self.assertIsInstance(handler, logging.FileHandler) |
---|
3735 | n/a | |
---|
3736 | n/a | expected = logging.FileHandler('test.log', 'a') |
---|
3737 | n/a | self.assertEqual(handler.stream.mode, expected.stream.mode) |
---|
3738 | n/a | self.assertEqual(handler.stream.name, expected.stream.name) |
---|
3739 | n/a | self.addCleanup(cleanup, handler, expected, 'test.log') |
---|
3740 | n/a | |
---|
3741 | n/a | def test_filemode(self): |
---|
3742 | n/a | |
---|
3743 | n/a | def cleanup(h1, h2, fn): |
---|
3744 | n/a | h1.close() |
---|
3745 | n/a | h2.close() |
---|
3746 | n/a | os.remove(fn) |
---|
3747 | n/a | |
---|
3748 | n/a | logging.basicConfig(filename='test.log', filemode='wb') |
---|
3749 | n/a | |
---|
3750 | n/a | handler = logging.root.handlers[0] |
---|
3751 | n/a | expected = logging.FileHandler('test.log', 'wb') |
---|
3752 | n/a | self.assertEqual(handler.stream.mode, expected.stream.mode) |
---|
3753 | n/a | self.addCleanup(cleanup, handler, expected, 'test.log') |
---|
3754 | n/a | |
---|
3755 | n/a | def test_stream(self): |
---|
3756 | n/a | stream = io.StringIO() |
---|
3757 | n/a | self.addCleanup(stream.close) |
---|
3758 | n/a | logging.basicConfig(stream=stream) |
---|
3759 | n/a | |
---|
3760 | n/a | self.assertEqual(len(logging.root.handlers), 1) |
---|
3761 | n/a | handler = logging.root.handlers[0] |
---|
3762 | n/a | self.assertIsInstance(handler, logging.StreamHandler) |
---|
3763 | n/a | self.assertEqual(handler.stream, stream) |
---|
3764 | n/a | |
---|
3765 | n/a | def test_format(self): |
---|
3766 | n/a | logging.basicConfig(format='foo') |
---|
3767 | n/a | |
---|
3768 | n/a | formatter = logging.root.handlers[0].formatter |
---|
3769 | n/a | self.assertEqual(formatter._style._fmt, 'foo') |
---|
3770 | n/a | |
---|
3771 | n/a | def test_datefmt(self): |
---|
3772 | n/a | logging.basicConfig(datefmt='bar') |
---|
3773 | n/a | |
---|
3774 | n/a | formatter = logging.root.handlers[0].formatter |
---|
3775 | n/a | self.assertEqual(formatter.datefmt, 'bar') |
---|
3776 | n/a | |
---|
3777 | n/a | def test_style(self): |
---|
3778 | n/a | logging.basicConfig(style='$') |
---|
3779 | n/a | |
---|
3780 | n/a | formatter = logging.root.handlers[0].formatter |
---|
3781 | n/a | self.assertIsInstance(formatter._style, logging.StringTemplateStyle) |
---|
3782 | n/a | |
---|
3783 | n/a | def test_level(self): |
---|
3784 | n/a | old_level = logging.root.level |
---|
3785 | n/a | self.addCleanup(logging.root.setLevel, old_level) |
---|
3786 | n/a | |
---|
3787 | n/a | logging.basicConfig(level=57) |
---|
3788 | n/a | self.assertEqual(logging.root.level, 57) |
---|
3789 | n/a | # Test that second call has no effect |
---|
3790 | n/a | logging.basicConfig(level=58) |
---|
3791 | n/a | self.assertEqual(logging.root.level, 57) |
---|
3792 | n/a | |
---|
3793 | n/a | def test_incompatible(self): |
---|
3794 | n/a | assertRaises = self.assertRaises |
---|
3795 | n/a | handlers = [logging.StreamHandler()] |
---|
3796 | n/a | stream = sys.stderr |
---|
3797 | n/a | assertRaises(ValueError, logging.basicConfig, filename='test.log', |
---|
3798 | n/a | stream=stream) |
---|
3799 | n/a | assertRaises(ValueError, logging.basicConfig, filename='test.log', |
---|
3800 | n/a | handlers=handlers) |
---|
3801 | n/a | assertRaises(ValueError, logging.basicConfig, stream=stream, |
---|
3802 | n/a | handlers=handlers) |
---|
3803 | n/a | # Issue 23207: test for invalid kwargs |
---|
3804 | n/a | assertRaises(ValueError, logging.basicConfig, loglevel=logging.INFO) |
---|
3805 | n/a | # Should pop both filename and filemode even if filename is None |
---|
3806 | n/a | logging.basicConfig(filename=None, filemode='a') |
---|
3807 | n/a | |
---|
3808 | n/a | def test_handlers(self): |
---|
3809 | n/a | handlers = [ |
---|
3810 | n/a | logging.StreamHandler(), |
---|
3811 | n/a | logging.StreamHandler(sys.stdout), |
---|
3812 | n/a | logging.StreamHandler(), |
---|
3813 | n/a | ] |
---|
3814 | n/a | f = logging.Formatter() |
---|
3815 | n/a | handlers[2].setFormatter(f) |
---|
3816 | n/a | logging.basicConfig(handlers=handlers) |
---|
3817 | n/a | self.assertIs(handlers[0], logging.root.handlers[0]) |
---|
3818 | n/a | self.assertIs(handlers[1], logging.root.handlers[1]) |
---|
3819 | n/a | self.assertIs(handlers[2], logging.root.handlers[2]) |
---|
3820 | n/a | self.assertIsNotNone(handlers[0].formatter) |
---|
3821 | n/a | self.assertIsNotNone(handlers[1].formatter) |
---|
3822 | n/a | self.assertIs(handlers[2].formatter, f) |
---|
3823 | n/a | self.assertIs(handlers[0].formatter, handlers[1].formatter) |
---|
3824 | n/a | |
---|
3825 | n/a | def _test_log(self, method, level=None): |
---|
3826 | n/a | # logging.root has no handlers so basicConfig should be called |
---|
3827 | n/a | called = [] |
---|
3828 | n/a | |
---|
3829 | n/a | old_basic_config = logging.basicConfig |
---|
3830 | n/a | def my_basic_config(*a, **kw): |
---|
3831 | n/a | old_basic_config() |
---|
3832 | n/a | old_level = logging.root.level |
---|
3833 | n/a | logging.root.setLevel(100) # avoid having messages in stderr |
---|
3834 | n/a | self.addCleanup(logging.root.setLevel, old_level) |
---|
3835 | n/a | called.append((a, kw)) |
---|
3836 | n/a | |
---|
3837 | n/a | support.patch(self, logging, 'basicConfig', my_basic_config) |
---|
3838 | n/a | |
---|
3839 | n/a | log_method = getattr(logging, method) |
---|
3840 | n/a | if level is not None: |
---|
3841 | n/a | log_method(level, "test me") |
---|
3842 | n/a | else: |
---|
3843 | n/a | log_method("test me") |
---|
3844 | n/a | |
---|
3845 | n/a | # basicConfig was called with no arguments |
---|
3846 | n/a | self.assertEqual(called, [((), {})]) |
---|
3847 | n/a | |
---|
3848 | n/a | def test_log(self): |
---|
3849 | n/a | self._test_log('log', logging.WARNING) |
---|
3850 | n/a | |
---|
3851 | n/a | def test_debug(self): |
---|
3852 | n/a | self._test_log('debug') |
---|
3853 | n/a | |
---|
3854 | n/a | def test_info(self): |
---|
3855 | n/a | self._test_log('info') |
---|
3856 | n/a | |
---|
3857 | n/a | def test_warning(self): |
---|
3858 | n/a | self._test_log('warning') |
---|
3859 | n/a | |
---|
3860 | n/a | def test_error(self): |
---|
3861 | n/a | self._test_log('error') |
---|
3862 | n/a | |
---|
3863 | n/a | def test_critical(self): |
---|
3864 | n/a | self._test_log('critical') |
---|
3865 | n/a | |
---|
3866 | n/a | |
---|
3867 | n/a | class LoggerAdapterTest(unittest.TestCase): |
---|
3868 | n/a | |
---|
3869 | n/a | def setUp(self): |
---|
3870 | n/a | super(LoggerAdapterTest, self).setUp() |
---|
3871 | n/a | old_handler_list = logging._handlerList[:] |
---|
3872 | n/a | |
---|
3873 | n/a | self.recording = RecordingHandler() |
---|
3874 | n/a | self.logger = logging.root |
---|
3875 | n/a | self.logger.addHandler(self.recording) |
---|
3876 | n/a | self.addCleanup(self.logger.removeHandler, self.recording) |
---|
3877 | n/a | self.addCleanup(self.recording.close) |
---|
3878 | n/a | |
---|
3879 | n/a | def cleanup(): |
---|
3880 | n/a | logging._handlerList[:] = old_handler_list |
---|
3881 | n/a | |
---|
3882 | n/a | self.addCleanup(cleanup) |
---|
3883 | n/a | self.addCleanup(logging.shutdown) |
---|
3884 | n/a | self.adapter = logging.LoggerAdapter(logger=self.logger, extra=None) |
---|
3885 | n/a | |
---|
3886 | n/a | def test_exception(self): |
---|
3887 | n/a | msg = 'testing exception: %r' |
---|
3888 | n/a | exc = None |
---|
3889 | n/a | try: |
---|
3890 | n/a | 1 / 0 |
---|
3891 | n/a | except ZeroDivisionError as e: |
---|
3892 | n/a | exc = e |
---|
3893 | n/a | self.adapter.exception(msg, self.recording) |
---|
3894 | n/a | |
---|
3895 | n/a | self.assertEqual(len(self.recording.records), 1) |
---|
3896 | n/a | record = self.recording.records[0] |
---|
3897 | n/a | self.assertEqual(record.levelno, logging.ERROR) |
---|
3898 | n/a | self.assertEqual(record.msg, msg) |
---|
3899 | n/a | self.assertEqual(record.args, (self.recording,)) |
---|
3900 | n/a | self.assertEqual(record.exc_info, |
---|
3901 | n/a | (exc.__class__, exc, exc.__traceback__)) |
---|
3902 | n/a | |
---|
3903 | n/a | def test_exception_excinfo(self): |
---|
3904 | n/a | try: |
---|
3905 | n/a | 1 / 0 |
---|
3906 | n/a | except ZeroDivisionError as e: |
---|
3907 | n/a | exc = e |
---|
3908 | n/a | |
---|
3909 | n/a | self.adapter.exception('exc_info test', exc_info=exc) |
---|
3910 | n/a | |
---|
3911 | n/a | self.assertEqual(len(self.recording.records), 1) |
---|
3912 | n/a | record = self.recording.records[0] |
---|
3913 | n/a | self.assertEqual(record.exc_info, |
---|
3914 | n/a | (exc.__class__, exc, exc.__traceback__)) |
---|
3915 | n/a | |
---|
3916 | n/a | def test_critical(self): |
---|
3917 | n/a | msg = 'critical test! %r' |
---|
3918 | n/a | self.adapter.critical(msg, self.recording) |
---|
3919 | n/a | |
---|
3920 | n/a | self.assertEqual(len(self.recording.records), 1) |
---|
3921 | n/a | record = self.recording.records[0] |
---|
3922 | n/a | self.assertEqual(record.levelno, logging.CRITICAL) |
---|
3923 | n/a | self.assertEqual(record.msg, msg) |
---|
3924 | n/a | self.assertEqual(record.args, (self.recording,)) |
---|
3925 | n/a | |
---|
3926 | n/a | def test_is_enabled_for(self): |
---|
3927 | n/a | old_disable = self.adapter.logger.manager.disable |
---|
3928 | n/a | self.adapter.logger.manager.disable = 33 |
---|
3929 | n/a | self.addCleanup(setattr, self.adapter.logger.manager, 'disable', |
---|
3930 | n/a | old_disable) |
---|
3931 | n/a | self.assertFalse(self.adapter.isEnabledFor(32)) |
---|
3932 | n/a | |
---|
3933 | n/a | def test_has_handlers(self): |
---|
3934 | n/a | self.assertTrue(self.adapter.hasHandlers()) |
---|
3935 | n/a | |
---|
3936 | n/a | for handler in self.logger.handlers: |
---|
3937 | n/a | self.logger.removeHandler(handler) |
---|
3938 | n/a | |
---|
3939 | n/a | self.assertFalse(self.logger.hasHandlers()) |
---|
3940 | n/a | self.assertFalse(self.adapter.hasHandlers()) |
---|
3941 | n/a | |
---|
3942 | n/a | |
---|
3943 | n/a | class LoggerTest(BaseTest): |
---|
3944 | n/a | |
---|
3945 | n/a | def setUp(self): |
---|
3946 | n/a | super(LoggerTest, self).setUp() |
---|
3947 | n/a | self.recording = RecordingHandler() |
---|
3948 | n/a | self.logger = logging.Logger(name='blah') |
---|
3949 | n/a | self.logger.addHandler(self.recording) |
---|
3950 | n/a | self.addCleanup(self.logger.removeHandler, self.recording) |
---|
3951 | n/a | self.addCleanup(self.recording.close) |
---|
3952 | n/a | self.addCleanup(logging.shutdown) |
---|
3953 | n/a | |
---|
3954 | n/a | def test_set_invalid_level(self): |
---|
3955 | n/a | self.assertRaises(TypeError, self.logger.setLevel, object()) |
---|
3956 | n/a | |
---|
3957 | n/a | def test_exception(self): |
---|
3958 | n/a | msg = 'testing exception: %r' |
---|
3959 | n/a | exc = None |
---|
3960 | n/a | try: |
---|
3961 | n/a | 1 / 0 |
---|
3962 | n/a | except ZeroDivisionError as e: |
---|
3963 | n/a | exc = e |
---|
3964 | n/a | self.logger.exception(msg, self.recording) |
---|
3965 | n/a | |
---|
3966 | n/a | self.assertEqual(len(self.recording.records), 1) |
---|
3967 | n/a | record = self.recording.records[0] |
---|
3968 | n/a | self.assertEqual(record.levelno, logging.ERROR) |
---|
3969 | n/a | self.assertEqual(record.msg, msg) |
---|
3970 | n/a | self.assertEqual(record.args, (self.recording,)) |
---|
3971 | n/a | self.assertEqual(record.exc_info, |
---|
3972 | n/a | (exc.__class__, exc, exc.__traceback__)) |
---|
3973 | n/a | |
---|
3974 | n/a | def test_log_invalid_level_with_raise(self): |
---|
3975 | n/a | with support.swap_attr(logging, 'raiseExceptions', True): |
---|
3976 | n/a | self.assertRaises(TypeError, self.logger.log, '10', 'test message') |
---|
3977 | n/a | |
---|
3978 | n/a | def test_log_invalid_level_no_raise(self): |
---|
3979 | n/a | with support.swap_attr(logging, 'raiseExceptions', False): |
---|
3980 | n/a | self.logger.log('10', 'test message') # no exception happens |
---|
3981 | n/a | |
---|
3982 | n/a | def test_find_caller_with_stack_info(self): |
---|
3983 | n/a | called = [] |
---|
3984 | n/a | support.patch(self, logging.traceback, 'print_stack', |
---|
3985 | n/a | lambda f, file: called.append(file.getvalue())) |
---|
3986 | n/a | |
---|
3987 | n/a | self.logger.findCaller(stack_info=True) |
---|
3988 | n/a | |
---|
3989 | n/a | self.assertEqual(len(called), 1) |
---|
3990 | n/a | self.assertEqual('Stack (most recent call last):\n', called[0]) |
---|
3991 | n/a | |
---|
3992 | n/a | def test_make_record_with_extra_overwrite(self): |
---|
3993 | n/a | name = 'my record' |
---|
3994 | n/a | level = 13 |
---|
3995 | n/a | fn = lno = msg = args = exc_info = func = sinfo = None |
---|
3996 | n/a | rv = logging._logRecordFactory(name, level, fn, lno, msg, args, |
---|
3997 | n/a | exc_info, func, sinfo) |
---|
3998 | n/a | |
---|
3999 | n/a | for key in ('message', 'asctime') + tuple(rv.__dict__.keys()): |
---|
4000 | n/a | extra = {key: 'some value'} |
---|
4001 | n/a | self.assertRaises(KeyError, self.logger.makeRecord, name, level, |
---|
4002 | n/a | fn, lno, msg, args, exc_info, |
---|
4003 | n/a | extra=extra, sinfo=sinfo) |
---|
4004 | n/a | |
---|
4005 | n/a | def test_make_record_with_extra_no_overwrite(self): |
---|
4006 | n/a | name = 'my record' |
---|
4007 | n/a | level = 13 |
---|
4008 | n/a | fn = lno = msg = args = exc_info = func = sinfo = None |
---|
4009 | n/a | extra = {'valid_key': 'some value'} |
---|
4010 | n/a | result = self.logger.makeRecord(name, level, fn, lno, msg, args, |
---|
4011 | n/a | exc_info, extra=extra, sinfo=sinfo) |
---|
4012 | n/a | self.assertIn('valid_key', result.__dict__) |
---|
4013 | n/a | |
---|
4014 | n/a | def test_has_handlers(self): |
---|
4015 | n/a | self.assertTrue(self.logger.hasHandlers()) |
---|
4016 | n/a | |
---|
4017 | n/a | for handler in self.logger.handlers: |
---|
4018 | n/a | self.logger.removeHandler(handler) |
---|
4019 | n/a | self.assertFalse(self.logger.hasHandlers()) |
---|
4020 | n/a | |
---|
4021 | n/a | def test_has_handlers_no_propagate(self): |
---|
4022 | n/a | child_logger = logging.getLogger('blah.child') |
---|
4023 | n/a | child_logger.propagate = False |
---|
4024 | n/a | self.assertFalse(child_logger.hasHandlers()) |
---|
4025 | n/a | |
---|
4026 | n/a | def test_is_enabled_for(self): |
---|
4027 | n/a | old_disable = self.logger.manager.disable |
---|
4028 | n/a | self.logger.manager.disable = 23 |
---|
4029 | n/a | self.addCleanup(setattr, self.logger.manager, 'disable', old_disable) |
---|
4030 | n/a | self.assertFalse(self.logger.isEnabledFor(22)) |
---|
4031 | n/a | |
---|
4032 | n/a | def test_root_logger_aliases(self): |
---|
4033 | n/a | root = logging.getLogger() |
---|
4034 | n/a | self.assertIs(root, logging.root) |
---|
4035 | n/a | self.assertIs(root, logging.getLogger(None)) |
---|
4036 | n/a | self.assertIs(root, logging.getLogger('')) |
---|
4037 | n/a | self.assertIs(root, logging.getLogger('foo').root) |
---|
4038 | n/a | self.assertIs(root, logging.getLogger('foo.bar').root) |
---|
4039 | n/a | self.assertIs(root, logging.getLogger('foo').parent) |
---|
4040 | n/a | |
---|
4041 | n/a | self.assertIsNot(root, logging.getLogger('\0')) |
---|
4042 | n/a | self.assertIsNot(root, logging.getLogger('foo.bar').parent) |
---|
4043 | n/a | |
---|
4044 | n/a | def test_invalid_names(self): |
---|
4045 | n/a | self.assertRaises(TypeError, logging.getLogger, any) |
---|
4046 | n/a | self.assertRaises(TypeError, logging.getLogger, b'foo') |
---|
4047 | n/a | |
---|
4048 | n/a | |
---|
4049 | n/a | class BaseFileTest(BaseTest): |
---|
4050 | n/a | "Base class for handler tests that write log files" |
---|
4051 | n/a | |
---|
4052 | n/a | def setUp(self): |
---|
4053 | n/a | BaseTest.setUp(self) |
---|
4054 | n/a | fd, self.fn = tempfile.mkstemp(".log", "test_logging-2-") |
---|
4055 | n/a | os.close(fd) |
---|
4056 | n/a | self.rmfiles = [] |
---|
4057 | n/a | |
---|
4058 | n/a | def tearDown(self): |
---|
4059 | n/a | for fn in self.rmfiles: |
---|
4060 | n/a | os.unlink(fn) |
---|
4061 | n/a | if os.path.exists(self.fn): |
---|
4062 | n/a | os.unlink(self.fn) |
---|
4063 | n/a | BaseTest.tearDown(self) |
---|
4064 | n/a | |
---|
4065 | n/a | def assertLogFile(self, filename): |
---|
4066 | n/a | "Assert a log file is there and register it for deletion" |
---|
4067 | n/a | self.assertTrue(os.path.exists(filename), |
---|
4068 | n/a | msg="Log file %r does not exist" % filename) |
---|
4069 | n/a | self.rmfiles.append(filename) |
---|
4070 | n/a | |
---|
4071 | n/a | |
---|
4072 | n/a | class FileHandlerTest(BaseFileTest): |
---|
4073 | n/a | def test_delay(self): |
---|
4074 | n/a | os.unlink(self.fn) |
---|
4075 | n/a | fh = logging.FileHandler(self.fn, delay=True) |
---|
4076 | n/a | self.assertIsNone(fh.stream) |
---|
4077 | n/a | self.assertFalse(os.path.exists(self.fn)) |
---|
4078 | n/a | fh.handle(logging.makeLogRecord({})) |
---|
4079 | n/a | self.assertIsNotNone(fh.stream) |
---|
4080 | n/a | self.assertTrue(os.path.exists(self.fn)) |
---|
4081 | n/a | fh.close() |
---|
4082 | n/a | |
---|
4083 | n/a | class RotatingFileHandlerTest(BaseFileTest): |
---|
4084 | n/a | def next_rec(self): |
---|
4085 | n/a | return logging.LogRecord('n', logging.DEBUG, 'p', 1, |
---|
4086 | n/a | self.next_message(), None, None, None) |
---|
4087 | n/a | |
---|
4088 | n/a | def test_should_not_rollover(self): |
---|
4089 | n/a | # If maxbytes is zero rollover never occurs |
---|
4090 | n/a | rh = logging.handlers.RotatingFileHandler(self.fn, maxBytes=0) |
---|
4091 | n/a | self.assertFalse(rh.shouldRollover(None)) |
---|
4092 | n/a | rh.close() |
---|
4093 | n/a | |
---|
4094 | n/a | def test_should_rollover(self): |
---|
4095 | n/a | rh = logging.handlers.RotatingFileHandler(self.fn, maxBytes=1) |
---|
4096 | n/a | self.assertTrue(rh.shouldRollover(self.next_rec())) |
---|
4097 | n/a | rh.close() |
---|
4098 | n/a | |
---|
4099 | n/a | def test_file_created(self): |
---|
4100 | n/a | # checks that the file is created and assumes it was created |
---|
4101 | n/a | # by us |
---|
4102 | n/a | rh = logging.handlers.RotatingFileHandler(self.fn) |
---|
4103 | n/a | rh.emit(self.next_rec()) |
---|
4104 | n/a | self.assertLogFile(self.fn) |
---|
4105 | n/a | rh.close() |
---|
4106 | n/a | |
---|
4107 | n/a | def test_rollover_filenames(self): |
---|
4108 | n/a | def namer(name): |
---|
4109 | n/a | return name + ".test" |
---|
4110 | n/a | rh = logging.handlers.RotatingFileHandler( |
---|
4111 | n/a | self.fn, backupCount=2, maxBytes=1) |
---|
4112 | n/a | rh.namer = namer |
---|
4113 | n/a | rh.emit(self.next_rec()) |
---|
4114 | n/a | self.assertLogFile(self.fn) |
---|
4115 | n/a | rh.emit(self.next_rec()) |
---|
4116 | n/a | self.assertLogFile(namer(self.fn + ".1")) |
---|
4117 | n/a | rh.emit(self.next_rec()) |
---|
4118 | n/a | self.assertLogFile(namer(self.fn + ".2")) |
---|
4119 | n/a | self.assertFalse(os.path.exists(namer(self.fn + ".3"))) |
---|
4120 | n/a | rh.close() |
---|
4121 | n/a | |
---|
4122 | n/a | @support.requires_zlib |
---|
4123 | n/a | def test_rotator(self): |
---|
4124 | n/a | def namer(name): |
---|
4125 | n/a | return name + ".gz" |
---|
4126 | n/a | |
---|
4127 | n/a | def rotator(source, dest): |
---|
4128 | n/a | with open(source, "rb") as sf: |
---|
4129 | n/a | data = sf.read() |
---|
4130 | n/a | compressed = zlib.compress(data, 9) |
---|
4131 | n/a | with open(dest, "wb") as df: |
---|
4132 | n/a | df.write(compressed) |
---|
4133 | n/a | os.remove(source) |
---|
4134 | n/a | |
---|
4135 | n/a | rh = logging.handlers.RotatingFileHandler( |
---|
4136 | n/a | self.fn, backupCount=2, maxBytes=1) |
---|
4137 | n/a | rh.rotator = rotator |
---|
4138 | n/a | rh.namer = namer |
---|
4139 | n/a | m1 = self.next_rec() |
---|
4140 | n/a | rh.emit(m1) |
---|
4141 | n/a | self.assertLogFile(self.fn) |
---|
4142 | n/a | m2 = self.next_rec() |
---|
4143 | n/a | rh.emit(m2) |
---|
4144 | n/a | fn = namer(self.fn + ".1") |
---|
4145 | n/a | self.assertLogFile(fn) |
---|
4146 | n/a | newline = os.linesep |
---|
4147 | n/a | with open(fn, "rb") as f: |
---|
4148 | n/a | compressed = f.read() |
---|
4149 | n/a | data = zlib.decompress(compressed) |
---|
4150 | n/a | self.assertEqual(data.decode("ascii"), m1.msg + newline) |
---|
4151 | n/a | rh.emit(self.next_rec()) |
---|
4152 | n/a | fn = namer(self.fn + ".2") |
---|
4153 | n/a | self.assertLogFile(fn) |
---|
4154 | n/a | with open(fn, "rb") as f: |
---|
4155 | n/a | compressed = f.read() |
---|
4156 | n/a | data = zlib.decompress(compressed) |
---|
4157 | n/a | self.assertEqual(data.decode("ascii"), m1.msg + newline) |
---|
4158 | n/a | rh.emit(self.next_rec()) |
---|
4159 | n/a | fn = namer(self.fn + ".2") |
---|
4160 | n/a | with open(fn, "rb") as f: |
---|
4161 | n/a | compressed = f.read() |
---|
4162 | n/a | data = zlib.decompress(compressed) |
---|
4163 | n/a | self.assertEqual(data.decode("ascii"), m2.msg + newline) |
---|
4164 | n/a | self.assertFalse(os.path.exists(namer(self.fn + ".3"))) |
---|
4165 | n/a | rh.close() |
---|
4166 | n/a | |
---|
4167 | n/a | class TimedRotatingFileHandlerTest(BaseFileTest): |
---|
4168 | n/a | # other test methods added below |
---|
4169 | n/a | def test_rollover(self): |
---|
4170 | n/a | fh = logging.handlers.TimedRotatingFileHandler(self.fn, 'S', |
---|
4171 | n/a | backupCount=1) |
---|
4172 | n/a | fmt = logging.Formatter('%(asctime)s %(message)s') |
---|
4173 | n/a | fh.setFormatter(fmt) |
---|
4174 | n/a | r1 = logging.makeLogRecord({'msg': 'testing - initial'}) |
---|
4175 | n/a | fh.emit(r1) |
---|
4176 | n/a | self.assertLogFile(self.fn) |
---|
4177 | n/a | time.sleep(1.1) # a little over a second ... |
---|
4178 | n/a | r2 = logging.makeLogRecord({'msg': 'testing - after delay'}) |
---|
4179 | n/a | fh.emit(r2) |
---|
4180 | n/a | fh.close() |
---|
4181 | n/a | # At this point, we should have a recent rotated file which we |
---|
4182 | n/a | # can test for the existence of. However, in practice, on some |
---|
4183 | n/a | # machines which run really slowly, we don't know how far back |
---|
4184 | n/a | # in time to go to look for the log file. So, we go back a fair |
---|
4185 | n/a | # bit, and stop as soon as we see a rotated file. In theory this |
---|
4186 | n/a | # could of course still fail, but the chances are lower. |
---|
4187 | n/a | found = False |
---|
4188 | n/a | now = datetime.datetime.now() |
---|
4189 | n/a | GO_BACK = 5 * 60 # seconds |
---|
4190 | n/a | for secs in range(GO_BACK): |
---|
4191 | n/a | prev = now - datetime.timedelta(seconds=secs) |
---|
4192 | n/a | fn = self.fn + prev.strftime(".%Y-%m-%d_%H-%M-%S") |
---|
4193 | n/a | found = os.path.exists(fn) |
---|
4194 | n/a | if found: |
---|
4195 | n/a | self.rmfiles.append(fn) |
---|
4196 | n/a | break |
---|
4197 | n/a | msg = 'No rotated files found, went back %d seconds' % GO_BACK |
---|
4198 | n/a | if not found: |
---|
4199 | n/a | #print additional diagnostics |
---|
4200 | n/a | dn, fn = os.path.split(self.fn) |
---|
4201 | n/a | files = [f for f in os.listdir(dn) if f.startswith(fn)] |
---|
4202 | n/a | print('Test time: %s' % now.strftime("%Y-%m-%d %H-%M-%S"), file=sys.stderr) |
---|
4203 | n/a | print('The only matching files are: %s' % files, file=sys.stderr) |
---|
4204 | n/a | for f in files: |
---|
4205 | n/a | print('Contents of %s:' % f) |
---|
4206 | n/a | path = os.path.join(dn, f) |
---|
4207 | n/a | with open(path, 'r') as tf: |
---|
4208 | n/a | print(tf.read()) |
---|
4209 | n/a | self.assertTrue(found, msg=msg) |
---|
4210 | n/a | |
---|
4211 | n/a | def test_invalid(self): |
---|
4212 | n/a | assertRaises = self.assertRaises |
---|
4213 | n/a | assertRaises(ValueError, logging.handlers.TimedRotatingFileHandler, |
---|
4214 | n/a | self.fn, 'X', delay=True) |
---|
4215 | n/a | assertRaises(ValueError, logging.handlers.TimedRotatingFileHandler, |
---|
4216 | n/a | self.fn, 'W', delay=True) |
---|
4217 | n/a | assertRaises(ValueError, logging.handlers.TimedRotatingFileHandler, |
---|
4218 | n/a | self.fn, 'W7', delay=True) |
---|
4219 | n/a | |
---|
4220 | n/a | def test_compute_rollover_daily_attime(self): |
---|
4221 | n/a | currentTime = 0 |
---|
4222 | n/a | atTime = datetime.time(12, 0, 0) |
---|
4223 | n/a | rh = logging.handlers.TimedRotatingFileHandler( |
---|
4224 | n/a | self.fn, when='MIDNIGHT', interval=1, backupCount=0, utc=True, |
---|
4225 | n/a | atTime=atTime) |
---|
4226 | n/a | try: |
---|
4227 | n/a | actual = rh.computeRollover(currentTime) |
---|
4228 | n/a | self.assertEqual(actual, currentTime + 12 * 60 * 60) |
---|
4229 | n/a | |
---|
4230 | n/a | actual = rh.computeRollover(currentTime + 13 * 60 * 60) |
---|
4231 | n/a | self.assertEqual(actual, currentTime + 36 * 60 * 60) |
---|
4232 | n/a | finally: |
---|
4233 | n/a | rh.close() |
---|
4234 | n/a | |
---|
4235 | n/a | #@unittest.skipIf(True, 'Temporarily skipped while failures investigated.') |
---|
4236 | n/a | def test_compute_rollover_weekly_attime(self): |
---|
4237 | n/a | currentTime = int(time.time()) |
---|
4238 | n/a | today = currentTime - currentTime % 86400 |
---|
4239 | n/a | |
---|
4240 | n/a | atTime = datetime.time(12, 0, 0) |
---|
4241 | n/a | |
---|
4242 | n/a | wday = time.gmtime(today).tm_wday |
---|
4243 | n/a | for day in range(7): |
---|
4244 | n/a | rh = logging.handlers.TimedRotatingFileHandler( |
---|
4245 | n/a | self.fn, when='W%d' % day, interval=1, backupCount=0, utc=True, |
---|
4246 | n/a | atTime=atTime) |
---|
4247 | n/a | try: |
---|
4248 | n/a | if wday > day: |
---|
4249 | n/a | # The rollover day has already passed this week, so we |
---|
4250 | n/a | # go over into next week |
---|
4251 | n/a | expected = (7 - wday + day) |
---|
4252 | n/a | else: |
---|
4253 | n/a | expected = (day - wday) |
---|
4254 | n/a | # At this point expected is in days from now, convert to seconds |
---|
4255 | n/a | expected *= 24 * 60 * 60 |
---|
4256 | n/a | # Add in the rollover time |
---|
4257 | n/a | expected += 12 * 60 * 60 |
---|
4258 | n/a | # Add in adjustment for today |
---|
4259 | n/a | expected += today |
---|
4260 | n/a | actual = rh.computeRollover(today) |
---|
4261 | n/a | if actual != expected: |
---|
4262 | n/a | print('failed in timezone: %d' % time.timezone) |
---|
4263 | n/a | print('local vars: %s' % locals()) |
---|
4264 | n/a | self.assertEqual(actual, expected) |
---|
4265 | n/a | if day == wday: |
---|
4266 | n/a | # goes into following week |
---|
4267 | n/a | expected += 7 * 24 * 60 * 60 |
---|
4268 | n/a | actual = rh.computeRollover(today + 13 * 60 * 60) |
---|
4269 | n/a | if actual != expected: |
---|
4270 | n/a | print('failed in timezone: %d' % time.timezone) |
---|
4271 | n/a | print('local vars: %s' % locals()) |
---|
4272 | n/a | self.assertEqual(actual, expected) |
---|
4273 | n/a | finally: |
---|
4274 | n/a | rh.close() |
---|
4275 | n/a | |
---|
4276 | n/a | |
---|
4277 | n/a | def secs(**kw): |
---|
4278 | n/a | return datetime.timedelta(**kw) // datetime.timedelta(seconds=1) |
---|
4279 | n/a | |
---|
4280 | n/a | for when, exp in (('S', 1), |
---|
4281 | n/a | ('M', 60), |
---|
4282 | n/a | ('H', 60 * 60), |
---|
4283 | n/a | ('D', 60 * 60 * 24), |
---|
4284 | n/a | ('MIDNIGHT', 60 * 60 * 24), |
---|
4285 | n/a | # current time (epoch start) is a Thursday, W0 means Monday |
---|
4286 | n/a | ('W0', secs(days=4, hours=24)), |
---|
4287 | n/a | ): |
---|
4288 | n/a | def test_compute_rollover(self, when=when, exp=exp): |
---|
4289 | n/a | rh = logging.handlers.TimedRotatingFileHandler( |
---|
4290 | n/a | self.fn, when=when, interval=1, backupCount=0, utc=True) |
---|
4291 | n/a | currentTime = 0.0 |
---|
4292 | n/a | actual = rh.computeRollover(currentTime) |
---|
4293 | n/a | if exp != actual: |
---|
4294 | n/a | # Failures occur on some systems for MIDNIGHT and W0. |
---|
4295 | n/a | # Print detailed calculation for MIDNIGHT so we can try to see |
---|
4296 | n/a | # what's going on |
---|
4297 | n/a | if when == 'MIDNIGHT': |
---|
4298 | n/a | try: |
---|
4299 | n/a | if rh.utc: |
---|
4300 | n/a | t = time.gmtime(currentTime) |
---|
4301 | n/a | else: |
---|
4302 | n/a | t = time.localtime(currentTime) |
---|
4303 | n/a | currentHour = t[3] |
---|
4304 | n/a | currentMinute = t[4] |
---|
4305 | n/a | currentSecond = t[5] |
---|
4306 | n/a | # r is the number of seconds left between now and midnight |
---|
4307 | n/a | r = logging.handlers._MIDNIGHT - ((currentHour * 60 + |
---|
4308 | n/a | currentMinute) * 60 + |
---|
4309 | n/a | currentSecond) |
---|
4310 | n/a | result = currentTime + r |
---|
4311 | n/a | print('t: %s (%s)' % (t, rh.utc), file=sys.stderr) |
---|
4312 | n/a | print('currentHour: %s' % currentHour, file=sys.stderr) |
---|
4313 | n/a | print('currentMinute: %s' % currentMinute, file=sys.stderr) |
---|
4314 | n/a | print('currentSecond: %s' % currentSecond, file=sys.stderr) |
---|
4315 | n/a | print('r: %s' % r, file=sys.stderr) |
---|
4316 | n/a | print('result: %s' % result, file=sys.stderr) |
---|
4317 | n/a | except Exception: |
---|
4318 | n/a | print('exception in diagnostic code: %s' % sys.exc_info()[1], file=sys.stderr) |
---|
4319 | n/a | self.assertEqual(exp, actual) |
---|
4320 | n/a | rh.close() |
---|
4321 | n/a | setattr(TimedRotatingFileHandlerTest, "test_compute_rollover_%s" % when, test_compute_rollover) |
---|
4322 | n/a | |
---|
4323 | n/a | |
---|
4324 | n/a | @unittest.skipUnless(win32evtlog, 'win32evtlog/win32evtlogutil/pywintypes required for this test.') |
---|
4325 | n/a | class NTEventLogHandlerTest(BaseTest): |
---|
4326 | n/a | def test_basic(self): |
---|
4327 | n/a | logtype = 'Application' |
---|
4328 | n/a | elh = win32evtlog.OpenEventLog(None, logtype) |
---|
4329 | n/a | num_recs = win32evtlog.GetNumberOfEventLogRecords(elh) |
---|
4330 | n/a | |
---|
4331 | n/a | try: |
---|
4332 | n/a | h = logging.handlers.NTEventLogHandler('test_logging') |
---|
4333 | n/a | except pywintypes.error as e: |
---|
4334 | n/a | if e.winerror == 5: # access denied |
---|
4335 | n/a | raise unittest.SkipTest('Insufficient privileges to run test') |
---|
4336 | n/a | raise |
---|
4337 | n/a | |
---|
4338 | n/a | r = logging.makeLogRecord({'msg': 'Test Log Message'}) |
---|
4339 | n/a | h.handle(r) |
---|
4340 | n/a | h.close() |
---|
4341 | n/a | # Now see if the event is recorded |
---|
4342 | n/a | self.assertLess(num_recs, win32evtlog.GetNumberOfEventLogRecords(elh)) |
---|
4343 | n/a | flags = win32evtlog.EVENTLOG_BACKWARDS_READ | \ |
---|
4344 | n/a | win32evtlog.EVENTLOG_SEQUENTIAL_READ |
---|
4345 | n/a | found = False |
---|
4346 | n/a | GO_BACK = 100 |
---|
4347 | n/a | events = win32evtlog.ReadEventLog(elh, flags, GO_BACK) |
---|
4348 | n/a | for e in events: |
---|
4349 | n/a | if e.SourceName != 'test_logging': |
---|
4350 | n/a | continue |
---|
4351 | n/a | msg = win32evtlogutil.SafeFormatMessage(e, logtype) |
---|
4352 | n/a | if msg != 'Test Log Message\r\n': |
---|
4353 | n/a | continue |
---|
4354 | n/a | found = True |
---|
4355 | n/a | break |
---|
4356 | n/a | msg = 'Record not found in event log, went back %d records' % GO_BACK |
---|
4357 | n/a | self.assertTrue(found, msg=msg) |
---|
4358 | n/a | |
---|
4359 | n/a | |
---|
4360 | n/a | class MiscTestCase(unittest.TestCase): |
---|
4361 | n/a | def test__all__(self): |
---|
4362 | n/a | blacklist = {'logThreads', 'logMultiprocessing', |
---|
4363 | n/a | 'logProcesses', 'currentframe', |
---|
4364 | n/a | 'PercentStyle', 'StrFormatStyle', 'StringTemplateStyle', |
---|
4365 | n/a | 'Filterer', 'PlaceHolder', 'Manager', 'RootLogger', |
---|
4366 | n/a | 'root', 'threading'} |
---|
4367 | n/a | support.check__all__(self, logging, blacklist=blacklist) |
---|
4368 | n/a | |
---|
4369 | n/a | |
---|
4370 | n/a | # Set the locale to the platform-dependent default. I have no idea |
---|
4371 | n/a | # why the test does this, but in any case we save the current locale |
---|
4372 | n/a | # first and restore it at the end. |
---|
4373 | n/a | @support.run_with_locale('LC_ALL', '') |
---|
4374 | n/a | def test_main(): |
---|
4375 | n/a | tests = [ |
---|
4376 | n/a | BuiltinLevelsTest, BasicFilterTest, CustomLevelsAndFiltersTest, |
---|
4377 | n/a | HandlerTest, MemoryHandlerTest, ConfigFileTest, SocketHandlerTest, |
---|
4378 | n/a | DatagramHandlerTest, MemoryTest, EncodingTest, WarningsTest, |
---|
4379 | n/a | ConfigDictTest, ManagerTest, FormatterTest, BufferingFormatterTest, |
---|
4380 | n/a | StreamHandlerTest, LogRecordFactoryTest, ChildLoggerTest, |
---|
4381 | n/a | QueueHandlerTest, ShutdownTest, ModuleLevelMiscTest, BasicConfigTest, |
---|
4382 | n/a | LoggerAdapterTest, LoggerTest, SMTPHandlerTest, FileHandlerTest, |
---|
4383 | n/a | RotatingFileHandlerTest, LastResortTest, LogRecordTest, |
---|
4384 | n/a | ExceptionTest, SysLogHandlerTest, HTTPHandlerTest, |
---|
4385 | n/a | NTEventLogHandlerTest, TimedRotatingFileHandlerTest, |
---|
4386 | n/a | UnixSocketHandlerTest, UnixDatagramHandlerTest, UnixSysLogHandlerTest, |
---|
4387 | n/a | MiscTestCase |
---|
4388 | n/a | ] |
---|
4389 | n/a | if hasattr(logging.handlers, 'QueueListener'): |
---|
4390 | n/a | tests.append(QueueListenerTest) |
---|
4391 | n/a | support.run_unittest(*tests) |
---|
4392 | n/a | |
---|
4393 | n/a | if __name__ == "__main__": |
---|
4394 | n/a | test_main() |
---|