diff --git a/packages/pylint-home-assistant/README.md b/packages/pylint-home-assistant/README.md index 4616cc6971da..177dd2cb798b 100644 --- a/packages/pylint-home-assistant/README.md +++ b/packages/pylint-home-assistant/README.md @@ -127,6 +127,7 @@ Every check has a code following the | `R7404` | [`home-assistant-tests-registry-fixtures`](#r7404-home-assistant-tests-registry-fixtures) | Use the registry fixture instead of calling `.async_get(hass)` directly in tests | | `R7405` | [`home-assistant-tests-user-flow-no-data`](#r7405-home-assistant-tests-user-flow-no-data) | User config flow init in tests must not pass `data` | | `R7406` | [`home-assistant-tests-snapshot-enable-entities`](#r7406-home-assistant-tests-snapshot-enable-entities) | Use the `entity_registry_enabled_by_default` fixture instead of enabling entities before `snapshot_platform` | +| `R7407` | [`home-assistant-tests-redundant-caplog-level`](#r7407-home-assistant-tests-redundant-caplog-level) | Do not set the root `caplog` level to DEBUG, the fixture already does | | `W7401` | [`home-assistant-deprecated-import`](#w7401-home-assistant-deprecated-import) | Import uses a deprecated path | | `W7402` | [`home-assistant-async-callback-decorator`](#w7402-home-assistant-async-callback-decorator) | Coroutine should not be decorated with `@callback` | | `W7403` | [`home-assistant-pytest-fixture-decorator`](#w7403-home-assistant-pytest-fixture-decorator) | Pytest fixture has invalid scope or autouse config | @@ -1386,6 +1387,54 @@ that enable an entity without calling `snapshot_platform` (for example, to test what happens when a user enables it) are not flagged. The checker is scoped to test modules. + +## `home_assistant_tests_redundant_caplog_level` checker + +Detects tests that set the root `caplog` level to DEBUG. The `caplog` +fixture of `pytest_homeassistant` already calls +`caplog.set_level(logging.DEBUG)`, so every test that uses `caplog` captures +all log records at DEBUG and above. + +### `R7407`: `home-assistant-tests-redundant-caplog-level` + +A `caplog.set_level(...)` or `caplog.at_level(...)` call sets the level to +DEBUG without a `logger` argument. The level is recognized as +`logging.DEBUG`, `DEBUG` imported from `logging`, or the string `"DEBUG"`: + +```python +async def test_something(hass: HomeAssistant, caplog: pytest.LogCaptureFixture): + caplog.set_level(logging.DEBUG) # <-- flagged + with caplog.at_level(logging.DEBUG): # <-- flagged + ... +``` + +Calls with a `logger` argument, or with unpacked arguments, are not +flagged, as some code sets the level of its own loggers. Other levels, like +INFO or WARNING, raise the level and are not checked either. +`caplog.at_level` is only checked when it is used directly in a `with` +statement, as only then is the block it applies to visible. +Only tests, fixtures and functions nested in them are checked. A helper +function starts at whatever level its caller left, which is not visible. + +Both methods also set the level of the shared capture handler, even with a +`logger`, and set the root logger level and undo `logging.disable`. A DEBUG +call is not flagged when the level may be different at that point. A +persistent change to another level is a `caplog.set_level`, a +`caplog.at_level` that is not used directly in a `with` statement, a +`setLevel` on a logger that may be the root logger, or `logging.disable`, +however it is imported. The level may be different when the DEBUG call: + +* follows a persistent change in the same function, +* is inside a `with caplog.at_level(...)` block with another level, +* is in a loop whose body makes a persistent change, +* is in a function nested in one that sets another level, or +* is a `with caplog.at_level(logging.DEBUG)` block whose body makes a + persistent change, which the block undoes on exit. + +The checker cannot see what a fixture does to the level. Use a disable +comment when a fixture raises it. The checker is scoped to test modules. + + ## `home_assistant_test_determinism` checker `if` and `match` statements inside test functions create non-deterministic diff --git a/packages/pylint-home-assistant/pylint_home_assistant/checkers/tests/redundant_caplog_level.py b/packages/pylint-home-assistant/pylint_home_assistant/checkers/tests/redundant_caplog_level.py new file mode 100644 index 000000000000..1e015c7f7b77 --- /dev/null +++ b/packages/pylint-home-assistant/pylint_home_assistant/checkers/tests/redundant_caplog_level.py @@ -0,0 +1,337 @@ +"""Checker for redundant ``caplog`` DEBUG levels in tests. + +The ``caplog`` fixture of ``pytest_homeassistant`` already calls +``caplog.set_level(logging.DEBUG)`` before the test runs, so every test that +uses ``caplog`` captures all log records at DEBUG and above. Calling:: + + caplog.set_level(logging.DEBUG) + +or:: + + with caplog.at_level(logging.DEBUG): + ... + +without a ``logger`` argument therefore changes nothing. + +Only tests, fixtures and functions nested in them are checked. A helper +function starts at whatever level its caller left, which is not visible. + +Calls that pass a ``logger``, or unpack their arguments, are not checked: +some code sets the level of its own loggers, so lowering a named logger to +DEBUG can be needed. ``caplog.at_level`` is only checked when it is used +directly in a ``with`` statement, as only then is the block visible. + +Both methods also set the level of the shared capture handler, even with a +``logger``, and set the root logger level and undo ``logging.disable``. A +DEBUG call is therefore not checked either when the level may be different +at that point. A persistent change to another level is a +``caplog.set_level``, a ``caplog.at_level`` that is not used directly in a +``with`` statement, a ``setLevel`` on a logger that may be the root logger, +or ``logging.disable``, however it is imported. The level may be different +when the DEBUG call: + +* follows a persistent change in the same function, +* is inside a ``with caplog.at_level(...)`` block with another level, +* is in a loop whose body makes a persistent change, +* is in a function nested in one that sets another level, or +* is a ``with caplog.at_level(logging.DEBUG)`` block whose body makes a + persistent change, which the block undoes on exit. +""" + +from dataclasses import dataclass +import logging + +from astroid import nodes +from pylint.checkers import BaseChecker, utils +from pylint.lint import PyLinter + +from pylint_home_assistant.helpers.module_info import is_test_module + +_CAPLOG = "caplog" +_LEVEL_METHODS = frozenset({"set_level", "at_level"}) +_DEBUG_LEVELS = frozenset({logging.DEBUG, "DEBUG"}) + + +@dataclass(frozen=True, slots=True) +class _LevelCall: + """A ``caplog.set_level`` or ``caplog.at_level`` call.""" + + method: str + level: nodes.NodeNG | None + root_logger: bool + unpacked: bool + + @property + def sets_debug(self) -> bool: + """Return True when the call is known to set the DEBUG level.""" + return not self.unpacked and _is_debug_level(self.level) + + +def _parse_level_call(node: nodes.Call) -> _LevelCall | None: + """Return the parsed call, or ``None`` if it is not a caplog level call.""" + func = node.func + if not ( + isinstance(func, nodes.Attribute) + and func.attrname in _LEVEL_METHODS + and isinstance(func.expr, nodes.Name) + and func.expr.name == _CAPLOG + ): + return None + + level: nodes.NodeNG | None = node.args[0] if node.args else None + logger: nodes.NodeNG | None = node.args[1] if len(node.args) > 1 else None + unpacked = any(isinstance(arg, nodes.Starred) for arg in node.args) + for keyword in node.keywords or (): + if keyword.arg is None: + unpacked = True + elif keyword.arg == "level": + level = keyword.value + elif keyword.arg == "logger": + logger = keyword.value + + return _LevelCall( + method=func.attrname, + level=level, + root_logger=logger is None + or (isinstance(logger, nodes.Const) and logger.value is None), + unpacked=unpacked, + ) + + +def _is_debug_level(level: nodes.NodeNG | None) -> bool: + """Return True when *level* resolves to the DEBUG level.""" + if level is None: + return False + inferred = utils.safe_infer(level) + return isinstance(inferred, nodes.Const) and inferred.value in _DEBUG_LEVELS + + +def _is_with_item(call: nodes.Call) -> bool: + """Return True when *call* is used directly as a ``with`` item.""" + return isinstance(call.parent, nodes.With) and any( + item is call for item, _ in call.parent.items + ) + + +def _is_logging_disable(call: nodes.Call) -> bool: + """Return True when *call* calls ``logging.disable``, however imported.""" + inferred = utils.safe_infer(call.func) + return ( + isinstance(inferred, nodes.FunctionDef) + and inferred.name == "disable" + and inferred.root().name == "logging" + ) + + +def _is_fixture(function: nodes.FunctionDef) -> bool: + """Return True when *function* is decorated as a pytest fixture.""" + for decorator in function.decorators.nodes if function.decorators else (): + if isinstance(decorator, nodes.Call): + decorator = decorator.func + if ( + isinstance(decorator, nodes.Attribute) and decorator.attrname == "fixture" + ) or (isinstance(decorator, nodes.Name) and decorator.name == "fixture"): + return True + return False + + +def _in_test_or_fixture(node: nodes.NodeNG) -> bool: + """Return True when the outermost function around *node* is a test or fixture. + + Methods of a class count by their own name. + """ + outermost: nodes.NodeNG | None = None + frame = node.frame() + while not isinstance(frame, nodes.Module): + if not isinstance(frame, nodes.ClassDef): + outermost = frame + if frame.parent is None: + break + frame = frame.parent.frame() + return isinstance(outermost, nodes.FunctionDef) and ( + outermost.name.startswith("test") or _is_fixture(outermost) + ) + + +def _is_named_logger(node: nodes.NodeNG) -> bool: + """Return True when *node* is ``logging.getLogger`` with a logger name.""" + if not ( + isinstance(node, nodes.Call) + and isinstance(node.func, nodes.Attribute) + and node.func.attrname == "getLogger" + and node.args + and isinstance(node.args[0], nodes.Const) + ): + return False + name = node.args[0].value + return isinstance(name, str) and name not in ("", "root") + + +def _sets_other_level(call: nodes.Call) -> bool: + """Return True when *call* persistently sets a level other than DEBUG. + + That is ``caplog.set_level``, ``caplog.at_level`` not used directly in a + ``with`` statement, as where its context ends is not visible, ``setLevel`` + on a logger that may be the root logger, or ``logging.disable``. + """ + if (parsed := _parse_level_call(call)) is not None: + return not parsed.sets_debug and ( + parsed.method == "set_level" or not _is_with_item(call) + ) + if _is_logging_disable(call): + return True + func = call.func + if not isinstance(func, nodes.Attribute): + return False + if func.attrname != "setLevel" or _is_named_logger(func.expr): + return False + level = call.args[0] if call.args else None + return not _is_debug_level(level) + + +def _sets_other_level_in(node: nodes.NodeNG) -> bool: + """Return True when *node* contains a call that sets another level.""" + return any(_sets_other_level(call) for call in node.nodes_of_class(nodes.Call)) + + +def _level_calls(node: nodes.NodeNG) -> list[tuple[nodes.Call, _LevelCall]]: + """Return the caplog level calls in *node*, including *node* itself.""" + return [ + (call, parsed) + for call in node.nodes_of_class(nodes.Call) + if (parsed := _parse_level_call(call)) is not None + ] + + +class RedundantCaplogLevelChecker(BaseChecker): + """Checker for ``caplog`` calls that set the level already in use.""" + + name = "home_assistant_tests_redundant_caplog_level" + priority = -1 + msgs = { + "R7407": ( + "`caplog.%s(logging.DEBUG)` is redundant, the caplog fixture " + "already captures DEBUG logs", + "home-assistant-tests-redundant-caplog-level", + "Used when a test sets the root caplog level to DEBUG. The " + "caplog fixture of pytest_homeassistant already sets it to DEBUG.", + ), + } + options = () + + _active: bool + + def visit_module(self, node: nodes.Module) -> None: + """Record whether the module is a test module.""" + self._active = is_test_module(node.name) + + def visit_call(self, node: nodes.Call) -> None: + """Flag ``caplog`` calls that set the root level to DEBUG.""" + if not self._active: + return + + call = _parse_level_call(node) + if call is None or not call.root_logger or not call.sets_debug: + return + if call.method == "at_level" and not _is_with_item(node): + return + + if not _in_test_or_fixture(node): + return + + if ( + self._follows_other_level(node) + or self._loop_sets_other_level(node) + or self._nested_in_other_level(node) + or self._block_sets_other_level(node, call) + ): + return + + self.add_message( + "home-assistant-tests-redundant-caplog-level", + node=node, + args=(call.method,), + ) + + @staticmethod + def _follows_other_level(node: nodes.Call) -> bool: + """Return True when an earlier call in the function sets another level. + + That is an earlier persistent change, or an enclosing + ``with caplog.at_level(...)`` for any logger, as it also sets the + level of the shared capture handler. + """ + ancestors = set(node.node_ancestors()) + position = (node.lineno, node.col_offset) + for other in node.frame().nodes_of_class(nodes.Call): + if other is node or (other.lineno, other.col_offset) >= position: + continue + if _sets_other_level(other): + return True + parsed = _parse_level_call(other) + if ( + parsed is not None + and parsed.method == "at_level" + and not parsed.sets_debug + and other.parent in ancestors + ): + return True + return False + + @staticmethod + def _loop_sets_other_level(node: nodes.Call) -> bool: + """Return True when an enclosing loop body sets another level. + + A persistent change later in the loop body is still in effect when the + next iteration reaches the DEBUG call. + """ + frame = node.frame() + child: nodes.NodeNG = node + for ancestor in node.node_ancestors(): + if ancestor is frame: + break + if ( + isinstance(ancestor, (nodes.For, nodes.While)) + and child in ancestor.body + and any(_sets_other_level_in(statement) for statement in ancestor.body) + ): + return True + child = ancestor + return False + + @staticmethod + def _nested_in_other_level(node: nodes.Call) -> bool: + """Return True when an enclosing function sets another level. + + The level a nested function starts at depends on when it is called, + so any other level in an enclosing function counts. + """ + frame = node.frame() + while frame.parent is not None: + frame = frame.parent.frame() + if isinstance(frame, nodes.Module): + return False + # The other methods of a class do not run before this one + if isinstance(frame, nodes.ClassDef): + continue + if _sets_other_level_in(frame) or any( + not parsed.sets_debug for _, parsed in _level_calls(frame) + ): + return True + return False + + @staticmethod + def _block_sets_other_level(node: nodes.Call, call: _LevelCall) -> bool: + """Return True when a DEBUG block's body sets another level. + + ``at_level`` restores the level on exit, so without the block a + persistent change in its body would stay in effect after it. + """ + if call.method != "at_level": + return False + return any(_sets_other_level_in(statement) for statement in node.parent.body) + + +def register(linter: PyLinter) -> None: + """Register the checker.""" + linter.register_checker(RedundantCaplogLevelChecker(linter)) diff --git a/tests/components/modbus/test_init.py b/tests/components/modbus/test_init.py index 87be42076390..ad72130054d3 100644 --- a/tests/components/modbus/test_init.py +++ b/tests/components/modbus/test_init.py @@ -1010,7 +1010,8 @@ async def test_pb_service_write( } mock_modbus_with_pymodbus.reset_mock() caplog.clear() - caplog.set_level(logging.DEBUG) + # The mock_modbus_with_pymodbus fixture sets the caplog level to ERROR + caplog.set_level(logging.DEBUG) # pylint: disable=home-assistant-tests-redundant-caplog-level func_name[do_write[FUNC]].return_value = do_return[VALUE] await hass.services.async_call(DOMAIN, do_write[SERVICE], data, blocking=True) assert func_name[do_write[FUNC]].called @@ -1574,7 +1575,8 @@ async def test_integration_reload( ) -> None: """Run test for integration reload.""" - caplog.set_level(logging.DEBUG) + # The mock_modbus fixture sets the caplog level to WARNING + caplog.set_level(logging.DEBUG) # pylint: disable=home-assistant-tests-redundant-caplog-level caplog.clear() async_fire_time_changed(hass, dt_util.utcnow() + timedelta(minutes=10)) @@ -1634,7 +1636,8 @@ async def test_integration_reload_failed( hass: HomeAssistant, caplog: pytest.LogCaptureFixture, mock_modbus ) -> None: """Run test for integration connect failure on reload.""" - caplog.set_level(logging.DEBUG) + # The mock_modbus fixture sets the caplog level to WARNING + caplog.set_level(logging.DEBUG) # pylint: disable=home-assistant-tests-redundant-caplog-level caplog.clear() yaml_path = get_fixture_path("configuration.yaml", "modbus") @@ -1806,7 +1809,8 @@ async def test_pb_service_write_no_slave( } mock_modbus_with_pymodbus.reset_mock() caplog.clear() - caplog.set_level(logging.DEBUG) + # The mock_modbus_with_pymodbus fixture sets the caplog level to ERROR + caplog.set_level(logging.DEBUG) # pylint: disable=home-assistant-tests-redundant-caplog-level func_name[do_write[FUNC]].return_value = do_return[VALUE] await hass.services.async_call(DOMAIN, do_write[SERVICE], data, blocking=True) assert func_name[do_write[FUNC]].called diff --git a/tests/pylint/tests/test_redundant_caplog_level.py b/tests/pylint/tests/test_redundant_caplog_level.py new file mode 100644 index 000000000000..7aa39387fbe8 --- /dev/null +++ b/tests/pylint/tests/test_redundant_caplog_level.py @@ -0,0 +1,636 @@ +"""Tests for the redundant caplog level checker.""" + +import astroid +from pylint.testutils import UnittestLinter +from pylint_home_assistant.checkers.tests.redundant_caplog_level import ( + RedundantCaplogLevelChecker, +) +import pytest + +from tests.pylint import assert_no_messages, walk_checker + +TEST_MODULE = "tests.components.pylint_test.test_init" + + +@pytest.fixture(name="checker") +def checker_fixture(linter: UnittestLinter) -> RedundantCaplogLevelChecker: + """Fixture to provide a redundant caplog level checker.""" + return RedundantCaplogLevelChecker(linter) + + +@pytest.mark.parametrize( + ("code", "method"), + [ + pytest.param( + """ +import logging + +def test_something(caplog): + caplog.set_level(logging.DEBUG) +""", + "set_level", + id="set_level_logging_debug", + ), + pytest.param( + """ +from logging import DEBUG + +def test_something(caplog): + caplog.set_level(DEBUG) +""", + "set_level", + id="set_level_imported_debug", + ), + pytest.param( + """ +def test_something(caplog): + caplog.set_level("DEBUG") +""", + "set_level", + id="set_level_string_debug", + ), + pytest.param( + """ +import logging + +def test_something(caplog): + caplog.set_level(level=logging.DEBUG, logger=None) +""", + "set_level", + id="set_level_keywords_root_logger", + ), + pytest.param( + """ +import logging + +async def test_something(caplog): + with caplog.at_level(logging.DEBUG): + pass +""", + "at_level", + id="at_level_async_test", + ), + pytest.param( + """ +import logging +import pytest + +@pytest.fixture +def my_fixture(caplog): + caplog.set_level(logging.DEBUG) +""", + "set_level", + id="fixture", + ), + pytest.param( + """ +import logging + +def test_something(caplog): + with caplog.at_level(logging.WARNING): + pass + caplog.set_level(logging.DEBUG) +""", + "set_level", + id="after_at_level_block", + ), + pytest.param( + """ +import logging + +def test_something(caplog): + with caplog.at_level(logging.DEBUG), caplog.at_level(logging.WARNING): + pass +""", + "at_level", + id="same_line_before_other_level", + ), + pytest.param( + """ +import logging + +def test_something(caplog): + with caplog.at_level(logging.DEBUG): + caplog.set_level(logging.DEBUG, logger="homeassistant.components.hue") + with caplog.at_level(logging.WARNING): + pass +""", + "at_level", + id="block_without_persistent_other_level", + ), + pytest.param( + """ +import logging + +def test_something(caplog): + def helper(): + caplog.set_level(logging.DEBUG) + + helper() +""", + "set_level", + id="nested_helper", + ), + pytest.param( + """ +import logging + +if True: + def test_something(caplog): + caplog.set_level(logging.DEBUG) +""", + "set_level", + id="conditionally_defined_test", + ), + pytest.param( + """ +import logging + +class TestSomething: + def test_other(self, caplog): + caplog.set_level(logging.WARNING) + + def test_something(self, caplog): + caplog.set_level(logging.DEBUG) +""", + "set_level", + id="other_method_sets_other_level", + ), + pytest.param( + """ +import logging + +def test_something(caplog, items): + for item in items: + caplog.set_level(logging.DEBUG) + with caplog.at_level(logging.WARNING): + pass +""", + "set_level", + id="loop_with_restored_other_level", + ), + pytest.param( + """ +import logging + +def test_something(caplog, items): + for item in items: + pass + else: + caplog.set_level(logging.DEBUG) + caplog.set_level(logging.WARNING) +""", + "set_level", + id="loop_else_runs_once", + ), + pytest.param( + """ +import logging + +def test_something(caplog): + logging.getLogger("homeassistant.components.hue").setLevel(logging.WARNING) + logging.getLogger().setLevel(logging.DEBUG) + caplog.set_level(logging.DEBUG) +""", + "set_level", + id="after_named_logger_or_debug_set_level", + ), + pytest.param( + """ +import logging + +def test_something(caplog): + caplog.set_level(logging.DEBUG) + logging.getLogger().setLevel(logging.WARNING) +""", + "set_level", + id="before_root_logger_set_level", + ), + pytest.param( + """ +import logging + +def test_something(caplog, thing): + thing.disable() + caplog.set_level(logging.DEBUG) +""", + "set_level", + id="after_unrelated_disable", + ), + pytest.param( + """ +import logging +import pytest + +@pytest.fixture(name="restored") +def restored_fixture(caplog): + caplog.set_level(logging.DEBUG) +""", + "set_level", + id="fixture_with_arguments", + ), + ], +) +def test_redundant_debug_level( + linter: UnittestLinter, + checker: RedundantCaplogLevelChecker, + code: str, + method: str, +) -> None: + """Test that setting the root caplog level to DEBUG is flagged.""" + walk_checker(linter, checker, astroid.parse(code, TEST_MODULE)) + + messages = linter.release_messages() + assert len(messages) == 1 + assert messages[0].msg_id == "home-assistant-tests-redundant-caplog-level" + assert messages[0].args == (method,) + + +@pytest.mark.parametrize( + "code", + [ + pytest.param( + """ +import logging + +def test_something(caplog): + caplog.set_level(logging.INFO) + caplog.set_level(logging.WARNING) + with caplog.at_level(logging.ERROR): + pass +""", + id="other_levels", + ), + pytest.param( + """ +import logging + +def test_something(caplog): + caplog.set_level(logging.DEBUG, logger="homeassistant.components.hue") + caplog.set_level(logging.DEBUG, "homeassistant.components.hue") + with caplog.at_level(logging.DEBUG, logger="homeassistant.components.hue"): + pass +""", + id="named_logger", + ), + pytest.param( + """ +import logging + +def test_something(caplog): + caplog.set_level(logging.WARNING) + caplog.set_level(logging.DEBUG) +""", + id="restores_debug", + ), + pytest.param( + """ +import logging + +def test_something(caplog): + with caplog.at_level(logging.WARNING): + with caplog.at_level(logging.DEBUG): + pass +""", + id="nested_at_level", + ), + pytest.param( + """ +import logging + +def test_something(caplog): + with caplog.at_level(logging.WARNING), caplog.at_level(logging.DEBUG): + pass +""", + id="same_line_after_other_level", + ), + pytest.param( + """ +import logging + +def test_something(caplog): + caplog.set_level(logging.WARNING, logger="homeassistant.components.hue") + caplog.set_level(logging.DEBUG) +""", + id="restores_debug_after_named_logger_set_level", + ), + pytest.param( + """ +import logging + +def test_something(caplog): + with caplog.at_level(logging.WARNING, logger="homeassistant.components.hue"): + caplog.set_level(logging.DEBUG) +""", + id="inside_named_logger_at_level", + ), + pytest.param( + """ +import logging + +def test_something(caplog): + with caplog.at_level(logging.DEBUG): + caplog.set_level(logging.WARNING) + assert "debug message" in caplog.text +""", + id="block_undoes_set_level", + ), + pytest.param( + """ +import logging + +def test_something(caplog): + with caplog.at_level(logging.DEBUG): + caplog.set_level(logging.WARNING, logger="homeassistant.components.hue") +""", + id="block_undoes_named_logger_set_level", + ), + pytest.param( + """ +import logging + +def test_something(caplog): + caplog.set_level(logging.WARNING) + + def helper(): + caplog.set_level(logging.DEBUG) + + helper() +""", + id="nested_helper_after_other_level", + ), + pytest.param( + """ +import logging + +def test_something(caplog): + caplog.set_level(logging.WARNING) + + class Helper: + def restore(self): + caplog.set_level(logging.DEBUG) + + Helper().restore() +""", + id="class_method_after_other_level", + ), + pytest.param( + """ +import logging + +def test_something(caplog, items): + for item in items: + caplog.set_level(logging.DEBUG) + caplog.set_level(logging.WARNING) +""", + id="for_loop_sets_other_level_later", + ), + pytest.param( + """ +import logging + +def test_something(caplog, items): + while items: + with caplog.at_level(logging.DEBUG): + pass + caplog.set_level(logging.WARNING) +""", + id="while_loop_sets_other_level_later", + ), + pytest.param( + """ +import logging + +def test_something(caplog): + context = caplog.at_level(logging.DEBUG) + with context: + caplog.set_level(logging.WARNING) +""", + id="stored_at_level_context", + ), + pytest.param( + """ +import contextlib +import logging + +def test_something(caplog): + with contextlib.ExitStack() as stack: + stack.enter_context(caplog.at_level(logging.DEBUG)) + caplog.set_level(logging.WARNING) +""", + id="exit_stack_at_level_context", + ), + pytest.param( + """ +import logging + +def test_something(caplog): + logging.getLogger().setLevel(logging.WARNING) + caplog.set_level(logging.DEBUG) +""", + id="after_root_logger_set_level", + ), + pytest.param( + """ +import logging + +def test_something(caplog): + logging.root.setLevel(logging.WARNING) + caplog.set_level(logging.DEBUG) +""", + id="after_logging_root_set_level", + ), + pytest.param( + """ +import logging + +def test_something(caplog): + logging.disable(logging.INFO) + caplog.set_level(logging.DEBUG) +""", + id="after_logging_disable", + ), + pytest.param( + """ +import logging + +def test_something(caplog): + with caplog.at_level(logging.DEBUG): + logging.getLogger().setLevel(logging.WARNING) +""", + id="block_undoes_root_logger_set_level", + ), + pytest.param( + """ +import logging + +def test_something(caplog, items): + for item in items: + caplog.set_level(logging.DEBUG) + logging.getLogger().setLevel(logging.WARNING) +""", + id="loop_sets_root_logger_level_later", + ), + pytest.param( + """ +from logging import DEBUG, INFO, disable + +def test_something(caplog): + disable(INFO) + caplog.set_level(DEBUG) +""", + id="after_imported_logging_disable", + ), + pytest.param( + """ +import logging as log + +def test_something(caplog): + log.disable(log.INFO) + caplog.set_level(log.DEBUG) +""", + id="after_aliased_logging_disable", + ), + pytest.param( + """ +import contextlib +import logging + +def test_something(caplog): + with contextlib.ExitStack() as stack: + stack.enter_context(caplog.at_level(logging.WARNING)) + caplog.set_level(logging.DEBUG) +""", + id="after_exit_stack_other_level", + ), + pytest.param( + """ +import logging + +def test_something(caplog): + context = caplog.at_level(logging.WARNING) + with context: + caplog.set_level(logging.DEBUG) +""", + id="after_stored_other_level_context", + ), + pytest.param( + """ +import logging + +caplog.set_level(logging.DEBUG) +""", + id="module_level", + ), + pytest.param( + """ +import logging + +def restore_debug(caplog): + caplog.set_level(logging.DEBUG) + +def test_something(caplog): + caplog.set_level(logging.WARNING) + restore_debug(caplog) +""", + id="module_level_helper", + ), + pytest.param( + """ +import logging + +async def _restore_debug(caplog): + with caplog.at_level(logging.DEBUG): + pass +""", + id="async_module_level_helper", + ), + pytest.param( + """ +import logging + +class TestSomething: + def _restore_debug(self, caplog): + caplog.set_level(logging.DEBUG) +""", + id="helper_method", + ), + pytest.param( + """ +import logging + +def restore_debug(caplog): + def inner(): + caplog.set_level(logging.DEBUG) + + inner() +""", + id="nested_in_helper", + ), + pytest.param( + """ +import logging + +def test_something(caplog): + caplog.set_level(logging.DEBUG, **{"logger": "homeassistant.components.hue"}) + with caplog.at_level( + logging.DEBUG, **{"logger": "homeassistant.components.hue"} + ): + pass +""", + id="unpacked_keywords", + ), + pytest.param( + """ +import logging + +def test_something(caplog): + caplog.set_level(**{"level": logging.WARNING}) + caplog.set_level(logging.DEBUG) +""", + id="restores_debug_after_unpacked_level", + ), + pytest.param( + """ +def test_something(caplog, level): + with caplog.at_level(level): + pass +""", + id="unknown_level", + ), + pytest.param( + """ +import logging + +def test_something(other): + other.set_level(logging.DEBUG) +""", + id="not_caplog", + ), + ], +) +def test_no_warning( + linter: UnittestLinter, + checker: RedundantCaplogLevelChecker, + code: str, +) -> None: + """Test cases that should not be flagged.""" + with assert_no_messages(linter): + walk_checker(linter, checker, astroid.parse(code, TEST_MODULE)) + + +def test_not_test_module( + linter: UnittestLinter, + checker: RedundantCaplogLevelChecker, +) -> None: + """Test that non-test modules are ignored.""" + code = """ +import logging + +def setup(caplog): + caplog.set_level(logging.DEBUG) +""" + with assert_no_messages(linter): + walk_checker( + linter, checker, astroid.parse(code, "homeassistant.components.hue") + )