python / python/cpython

Unable to use `logging.NOTSET` with `assertLogs` or `assertNoLogs`

Đang mở
#136,958 3 bình luận 0 reaction 0 người được giao Xem trên GitHub

Chưa có ai nhận issue này.

pending stdlib
Ngôn ngữ chính
Python
Star
77.2k
Fork
35.9k
Chỉ số merge pull request
Chỉ số pull request đang chờ

Mô tả

Bug report

Bug description:

Since logging.NOTSET equals 0 (a falsey value), the naive conditional check in _AssertLogsContext prevents it from being used as a valid level parameter with unittest.TestCase.assertLogs() or unittest.TestCase.assertNoLogs().

Example:

import logging
import unittest


class LoggerTestCase(unittest.TestCase):
    def test_logging(self):
        root_logger = logging.getLogger()
        root_logger.setLevel(logging.ERROR)

        logger = logging.getLogger("foo")

        with self.assertLogs(logger=logger, level=logging.NOTSET) as cm:
            logger.info("first message")
            logger.error("second message")
            # This test currently fails because `assertLogs(...)` sees the falsey
            # `logging.NOTSET` and sets the level to `logging.INFO` by default; so we
            # end up seeing the "INFO:foo:first message" in the output.
            self.assertEqual(cm.output, ["ERROR:foo:second message"])

In my real life use case, the logging.NOTSET interaction is useful in context of creating a custom class ExplicitlyConfiguredLogger(logging.Logger) that only logs when the logger is configured with something other than logging.NOTSET (used in https://github.com/element-hq/synapse/pull/18474) and wanting to write some tests for it.

CPython versions tested on:

3.13

Operating systems tested on:

Linux

Linked PRs
  • gh-137555

Hướng dẫn đóng góp

Mở hướng dẫn đóng góp

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Hướng nghiên cứu

Bắt đầu trong Lib/unittest/_log.py, tại điều kiện _AssertLogsContext được tham chiếu trong issue. Tái hiện ví dụ với logging.NOTSET thông qua assertLogs và assertNoLogs, sau đó xác minh rằng cả hai context đều chấp nhận level mà không mặc định thành INFO và rằng phạm vi kiểm thử hồi quy thực thi hành vi này.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Đánh giá

Công nghệ
python
Lĩnh vực
testing
Loại issue
Lỗi
Độ khó
2/5
Thời gian dự kiến
1-3 giờ
Mức độ hoạt động
Đình trệ
Độ rõ ràng
Đặc tả rõ ràng
Mức phù hợp với người mới
25/100

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.