Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

gh-134567: Exposes log format to users in unittest.TestCase.assertLogs#134570

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Open
garry-cairns wants to merge2 commits intopython:main
base:main
Choose a base branch
Loading
fromgarry-cairns:fix-issue-134567
Open
Show file tree
Hide file tree
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletionsLib/test/test_unittest/test_case.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -1920,6 +1920,22 @@ def testAssertLogsUnexpectedException(self):
with self.assertLogs():
raise ZeroDivisionError("Unexpected")

def testAssertLogsWithFormatter(self):
# Check alternative formats will be respected
format = "[No.1: the larch] %(levelname)s:%(name)s:%(message)s"
formatter = logging.Formatter(format)
with self.assertNoStderr():
with self.assertLogs() as cm:
log_foo.info("1")
log_foobar.debug("2")
self.assertEqual(cm.output, ["INFO:foo:1"])
self.assertLogRecords(cm.records, [{'name': 'foo'}])
with self.assertLogs(formatter=formatter) as cm:
log_foo.info("1")
log_foobar.debug("2")
self.assertEqual(cm.output, ["[No.1: the larch] INFO:foo:1"])
self.assertLogRecords(cm.records, [{'name': 'foo'}])

def testAssertNoLogsDefault(self):
with self.assertRaises(self.failureException) as cm:
with self.assertNoLogs():
Expand Down
5 changes: 3 additions & 2 deletionsLib/unittest/_log.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -30,7 +30,7 @@ class _AssertLogsContext(_BaseTestCaseContext):

LOGGING_FORMAT = "%(levelname)s:%(name)s:%(message)s"

def __init__(self, test_case, logger_name, level, no_logs):
def __init__(self, test_case, logger_name, level, no_logs, formatter=None):
_BaseTestCaseContext.__init__(self, test_case)
self.logger_name = logger_name
if level:
Expand All@@ -39,13 +39,14 @@ def __init__(self, test_case, logger_name, level, no_logs):
self.level = logging.INFO
self.msg = None
self.no_logs = no_logs
self.formatter = formatter

def __enter__(self):
if isinstance(self.logger_name, logging.Logger):
logger = self.logger = self.logger_name
else:
logger = self.logger = logging.getLogger(self.logger_name)
formatter = logging.Formatter(self.LOGGING_FORMAT)
formatter =self.formatter orlogging.Formatter(self.LOGGING_FORMAT)
handler = _CapturingHandler()
handler.setLevel(self.level)
handler.setFormatter(formatter)
Expand Down
6 changes: 4 additions & 2 deletionsLib/unittest/case.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -851,7 +851,7 @@ def _assertNotWarns(self, expected_warning, *args, **kwargs):
context = _AssertNotWarnsContext(expected_warning, self)
return context.handle('_assertNotWarns', args, kwargs)

def assertLogs(self, logger=None, level=None):
def assertLogs(self, logger=None, level=None, formatter=None):
"""Fail unless a log message of level *level* or higher is emitted
on *logger_name* or its children. If omitted, *level* defaults to
INFO and *logger* defaults to the root logger.
Expand All@@ -863,6 +863,8 @@ def assertLogs(self, logger=None, level=None):
`records` attribute will be a list of the corresponding LogRecord
objects.

Optionally supply `format` to control how messages are formatted.

Example::

with self.assertLogs('foo', level='INFO') as cm:
Expand All@@ -873,7 +875,7 @@ def assertLogs(self, logger=None, level=None):
"""
# Lazy import to avoid importing logging if it is not needed.
from ._log import _AssertLogsContext
return _AssertLogsContext(self, logger, level, no_logs=False)
return _AssertLogsContext(self, logger, level, no_logs=False, formatter=formatter)

def assertNoLogs(self, logger=None, level=None):
""" Fail unless no log messages of level *level* or higher are emitted
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
Expose log formatter to users in TestCase.assertLogs.
:func:`unittest.TestCase.assertLogs` will now accept a formatter argument so your assertions can match a custom format where you are using one.
Loading

[8]ページ先頭

©2009-2025 Movatter.jp