LEFT | RIGHT |
1 #!/usr/bin/env python | |
2 # | |
3 # Copyright 2001-2013 by Vinay Sajip. All Rights Reserved. | 1 # Copyright 2001-2013 by Vinay Sajip. All Rights Reserved. |
4 # | 2 # |
5 # Permission to use, copy, modify, and distribute this software and its | 3 # Permission to use, copy, modify, and distribute this software and its |
6 # documentation for any purpose and without fee is hereby granted, | 4 # documentation for any purpose and without fee is hereby granted, |
7 # provided that the above copyright notice appear in all copies and that | 5 # provided that the above copyright notice appear in all copies and that |
8 # both that copyright notice and this permission notice appear in | 6 # both that copyright notice and this permission notice appear in |
9 # supporting documentation, and that the name of Vinay Sajip | 7 # supporting documentation, and that the name of Vinay Sajip |
10 # not be used in advertising or publicity pertaining to distribution | 8 # not be used in advertising or publicity pertaining to distribution |
11 # of the software without specific, written prior permission. | 9 # of the software without specific, written prior permission. |
12 # VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING | 10 # VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING |
(...skipping 21 matching lines...) Expand all Loading... |
34 import json | 32 import json |
35 import os | 33 import os |
36 import queue | 34 import queue |
37 import random | 35 import random |
38 import re | 36 import re |
39 import select | 37 import select |
40 import socket | 38 import socket |
41 import struct | 39 import struct |
42 import sys | 40 import sys |
43 import tempfile | 41 import tempfile |
| 42 from test.script_helper import assert_python_ok |
44 from test.support import (captured_stdout, run_with_locale, run_unittest, | 43 from test.support import (captured_stdout, run_with_locale, run_unittest, |
45 patch, requires_zlib, TestHandler, Matcher) | 44 patch, requires_zlib, TestHandler, Matcher) |
46 import textwrap | 45 import textwrap |
47 import time | 46 import time |
48 import unittest | 47 import unittest |
49 import warnings | 48 import warnings |
50 import weakref | 49 import weakref |
51 try: | 50 try: |
52 import threading | 51 import threading |
53 # The following imports are needed only for tests which | 52 # The following imports are needed only for tests which |
(...skipping 529 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
583 h.close() | 582 h.close() |
584 | 583 |
585 @unittest.skipIf(os.name == 'nt', 'WatchedFileHandler not appropriate for Wi
ndows.') | 584 @unittest.skipIf(os.name == 'nt', 'WatchedFileHandler not appropriate for Wi
ndows.') |
586 @unittest.skipUnless(threading, 'Threading required for this test.') | 585 @unittest.skipUnless(threading, 'Threading required for this test.') |
587 def test_race(self): | 586 def test_race(self): |
588 # Issue #14632 refers. | 587 # Issue #14632 refers. |
589 def remove_loop(fname, tries): | 588 def remove_loop(fname, tries): |
590 for _ in range(tries): | 589 for _ in range(tries): |
591 try: | 590 try: |
592 os.unlink(fname) | 591 os.unlink(fname) |
| 592 self.deletion_time = time.time() |
593 except OSError: | 593 except OSError: |
594 pass | 594 pass |
595 time.sleep(0.004 * random.randint(0, 4)) | 595 time.sleep(0.004 * random.randint(0, 4)) |
596 | 596 |
597 del_count = 500 | 597 del_count = 500 |
598 log_count = 500 | 598 log_count = 500 |
| 599 |
| 600 self.handle_time = None |
| 601 self.deletion_time = None |
599 | 602 |
600 for delay in (False, True): | 603 for delay in (False, True): |
601 fd, fn = tempfile.mkstemp('.log', 'test_logging-3-') | 604 fd, fn = tempfile.mkstemp('.log', 'test_logging-3-') |
602 os.close(fd) | 605 os.close(fd) |
603 remover = threading.Thread(target=remove_loop, args=(fn, del_count)) | 606 remover = threading.Thread(target=remove_loop, args=(fn, del_count)) |
604 remover.daemon = True | 607 remover.daemon = True |
605 remover.start() | 608 remover.start() |
606 h = logging.handlers.WatchedFileHandler(fn, delay=delay) | 609 h = logging.handlers.WatchedFileHandler(fn, delay=delay) |
607 f = logging.Formatter('%(asctime)s: %(levelname)s: %(message)s') | 610 f = logging.Formatter('%(asctime)s: %(levelname)s: %(message)s') |
608 h.setFormatter(f) | 611 h.setFormatter(f) |
609 try: | 612 try: |
610 for _ in range(log_count): | 613 for _ in range(log_count): |
611 time.sleep(0.005) | 614 time.sleep(0.005) |
612 r = logging.makeLogRecord({'msg': 'testing' }) | 615 r = logging.makeLogRecord({'msg': 'testing' }) |
613 h.handle(r) | 616 try: |
| 617 self.handle_time = time.time() |
| 618 h.handle(r) |
| 619 except Exception: |
| 620 print('Deleted at %s, ' |
| 621 'opened at %s' % (self.deletion_time, |
| 622 self.handle_time)) |
| 623 raise |
614 finally: | 624 finally: |
615 remover.join() | 625 remover.join() |
616 h.close() | 626 h.close() |
617 if os.path.exists(fn): | 627 if os.path.exists(fn): |
618 os.unlink(fn) | 628 os.unlink(fn) |
619 | 629 |
620 | 630 |
621 class BadStream(object): | 631 class BadStream(object): |
622 def write(self, data): | 632 def write(self, data): |
623 raise RuntimeError('deliberate mistake') | 633 raise RuntimeError('deliberate mistake') |
(...skipping 281 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
905 super(TestUDPServer, self).server_close() | 915 super(TestUDPServer, self).server_close() |
906 self._closed = True | 916 self._closed = True |
907 | 917 |
908 class TestUnixDatagramServer(TestUDPServer): | 918 class TestUnixDatagramServer(TestUDPServer): |
909 address_family = socket.AF_UNIX | 919 address_family = socket.AF_UNIX |
910 | 920 |
911 # - end of server_helper section | 921 # - end of server_helper section |
912 | 922 |
913 @unittest.skipUnless(threading, 'Threading required for this test.') | 923 @unittest.skipUnless(threading, 'Threading required for this test.') |
914 class SMTPHandlerTest(BaseTest): | 924 class SMTPHandlerTest(BaseTest): |
| 925 TIMEOUT = 8.0 |
915 def test_basic(self): | 926 def test_basic(self): |
916 sockmap = {} | 927 sockmap = {} |
917 server = TestSMTPServer(('localhost', 0), self.process_message, 0.001, | 928 server = TestSMTPServer(('localhost', 0), self.process_message, 0.001, |
918 sockmap) | 929 sockmap) |
919 server.start() | 930 server.start() |
920 addr = ('localhost', server.port) | 931 addr = ('localhost', server.port) |
921 h = logging.handlers.SMTPHandler(addr, 'me', 'you', 'Log', timeout=5.0) | 932 h = logging.handlers.SMTPHandler(addr, 'me', 'you', 'Log', |
| 933 timeout=self.TIMEOUT) |
922 self.assertEqual(h.toaddrs, ['you']) | 934 self.assertEqual(h.toaddrs, ['you']) |
923 self.messages = [] | 935 self.messages = [] |
924 r = logging.makeLogRecord({'msg': 'Hello'}) | 936 r = logging.makeLogRecord({'msg': 'Hello'}) |
925 self.handled = threading.Event() | 937 self.handled = threading.Event() |
926 h.handle(r) | 938 h.handle(r) |
927 self.handled.wait(5.0) # 14314: don't wait forever | 939 self.handled.wait(self.TIMEOUT) # 14314: don't wait forever |
928 server.stop() | 940 server.stop() |
929 self.assertTrue(self.handled.is_set()) | 941 self.assertTrue(self.handled.is_set()) |
930 self.assertEqual(len(self.messages), 1) | 942 self.assertEqual(len(self.messages), 1) |
931 peer, mailfrom, rcpttos, data = self.messages[0] | 943 peer, mailfrom, rcpttos, data = self.messages[0] |
932 self.assertEqual(mailfrom, 'me') | 944 self.assertEqual(mailfrom, 'me') |
933 self.assertEqual(rcpttos, ['you']) | 945 self.assertEqual(rcpttos, ['you']) |
934 self.assertIn('\nSubject: Log\n', data) | 946 self.assertIn('\nSubject: Log\n', data) |
935 self.assertTrue(data.endswith('\n\nHello')) | 947 self.assertTrue(data.endswith('\n\nHello')) |
936 h.close() | 948 h.close() |
937 | 949 |
(...skipping 2439 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
3377 | 3389 |
3378 class MyLogger(logging.Logger): | 3390 class MyLogger(logging.Logger): |
3379 pass | 3391 pass |
3380 | 3392 |
3381 logging.setLoggerClass(MyLogger) | 3393 logging.setLoggerClass(MyLogger) |
3382 self.assertEqual(logging.getLoggerClass(), MyLogger) | 3394 self.assertEqual(logging.getLoggerClass(), MyLogger) |
3383 | 3395 |
3384 logging.setLoggerClass(logging.Logger) | 3396 logging.setLoggerClass(logging.Logger) |
3385 self.assertEqual(logging.getLoggerClass(), logging.Logger) | 3397 self.assertEqual(logging.getLoggerClass(), logging.Logger) |
3386 | 3398 |
| 3399 def test_logging_at_shutdown(self): |
| 3400 # Issue #20037 |
| 3401 code = """if 1: |
| 3402 import logging |
| 3403 |
| 3404 class A: |
| 3405 def __del__(self): |
| 3406 try: |
| 3407 raise ValueError("some error") |
| 3408 except Exception: |
| 3409 logging.exception("exception in __del__") |
| 3410 |
| 3411 a = A()""" |
| 3412 rc, out, err = assert_python_ok("-c", code) |
| 3413 err = err.decode() |
| 3414 self.assertIn("exception in __del__", err) |
| 3415 self.assertIn("ValueError: some error", err) |
| 3416 |
| 3417 |
3387 class LogRecordTest(BaseTest): | 3418 class LogRecordTest(BaseTest): |
3388 def test_str_rep(self): | 3419 def test_str_rep(self): |
3389 r = logging.makeLogRecord({}) | 3420 r = logging.makeLogRecord({}) |
3390 s = str(r) | 3421 s = str(r) |
3391 self.assertTrue(s.startswith('<LogRecord: ')) | 3422 self.assertTrue(s.startswith('<LogRecord: ')) |
3392 self.assertTrue(s.endswith('>')) | 3423 self.assertTrue(s.endswith('>')) |
3393 | 3424 |
3394 def test_dict_arg(self): | 3425 def test_dict_arg(self): |
3395 h = RecordingHandler() | 3426 h = RecordingHandler() |
3396 r = logging.getLogger() | 3427 r = logging.getLogger() |
(...skipping 79 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
3476 formatter = handler.formatter | 3507 formatter = handler.formatter |
3477 # format defaults to logging.BASIC_FORMAT | 3508 # format defaults to logging.BASIC_FORMAT |
3478 self.assertEqual(formatter._style._fmt, logging.BASIC_FORMAT) | 3509 self.assertEqual(formatter._style._fmt, logging.BASIC_FORMAT) |
3479 # datefmt defaults to None | 3510 # datefmt defaults to None |
3480 self.assertIsNone(formatter.datefmt) | 3511 self.assertIsNone(formatter.datefmt) |
3481 # style defaults to % | 3512 # style defaults to % |
3482 self.assertIsInstance(formatter._style, logging.PercentStyle) | 3513 self.assertIsInstance(formatter._style, logging.PercentStyle) |
3483 | 3514 |
3484 # level is not explicitly set | 3515 # level is not explicitly set |
3485 self.assertEqual(logging.root.level, self.original_logging_level) | 3516 self.assertEqual(logging.root.level, self.original_logging_level) |
| 3517 |
| 3518 def test_strformatstyle(self): |
| 3519 with captured_stdout() as output: |
| 3520 logging.basicConfig(stream=sys.stdout, style="{") |
| 3521 logging.error("Log an error") |
| 3522 sys.stdout.seek(0) |
| 3523 self.assertEqual(output.getvalue().strip(), |
| 3524 "ERROR:root:Log an error") |
| 3525 |
| 3526 def test_stringtemplatestyle(self): |
| 3527 with captured_stdout() as output: |
| 3528 logging.basicConfig(stream=sys.stdout, style="$") |
| 3529 logging.error("Log an error") |
| 3530 sys.stdout.seek(0) |
| 3531 self.assertEqual(output.getvalue().strip(), |
| 3532 "ERROR:root:Log an error") |
3486 | 3533 |
3487 def test_filename(self): | 3534 def test_filename(self): |
3488 | 3535 |
3489 def cleanup(h1, h2, fn): | 3536 def cleanup(h1, h2, fn): |
3490 h1.close() | 3537 h1.close() |
3491 h2.close() | 3538 h2.close() |
3492 os.remove(fn) | 3539 os.remove(fn) |
3493 | 3540 |
3494 logging.basicConfig(filename='test.log') | 3541 logging.basicConfig(filename='test.log') |
3495 | 3542 |
(...skipping 621 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
4117 BasicConfigTest, LoggerAdapterTest, LoggerTest, | 4164 BasicConfigTest, LoggerAdapterTest, LoggerTest, |
4118 SMTPHandlerTest, FileHandlerTest, RotatingFileHandlerTest, | 4165 SMTPHandlerTest, FileHandlerTest, RotatingFileHandlerTest, |
4119 LastResortTest, LogRecordTest, ExceptionTest, | 4166 LastResortTest, LogRecordTest, ExceptionTest, |
4120 SysLogHandlerTest, HTTPHandlerTest, NTEventLogHandlerTest, | 4167 SysLogHandlerTest, HTTPHandlerTest, NTEventLogHandlerTest, |
4121 TimedRotatingFileHandlerTest, UnixSocketHandlerTest, | 4168 TimedRotatingFileHandlerTest, UnixSocketHandlerTest, |
4122 UnixDatagramHandlerTest, UnixSysLogHandlerTest | 4169 UnixDatagramHandlerTest, UnixSysLogHandlerTest |
4123 ) | 4170 ) |
4124 | 4171 |
4125 if __name__ == "__main__": | 4172 if __name__ == "__main__": |
4126 test_main() | 4173 test_main() |
LEFT | RIGHT |