pytorch-lightning
149 строк · 5.5 Кб
1# Copyright The Lightning AI team.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14"""Test that the warnings actually appear and they have the correct `stacklevel`
15
16Needs to be run outside of `pytest` as it captures all the warnings.
17
18"""
19
20import importlib21import inspect22import os23import sys24import warnings25from contextlib import redirect_stderr26from io import StringIO27from pathlib import Path28from unittest import mock29
30import lightning.fabric31import pytest32from lightning.fabric.utilities.rank_zero import rank_zero_deprecation, rank_zero_warn33from lightning.fabric.utilities.warnings import (34PossibleUserWarning,35_is_path_in_lightning,36disable_possible_user_warnings,37)
38from lightning_utilities.core.rank_zero import WarningCache, _warn39from lightning_utilities.test.warning import no_warning_call40
41
42def line_number():43return inspect.currentframe().f_back.f_lineno44
45
46if __name__ == "__main__":47stderr = StringIO()48# recording49with redirect_stderr(stderr):50base_line = line_number() + 151_warn("test1")52_warn("test2", category=DeprecationWarning)53
54rank_zero_warn("test3")55rank_zero_warn("test4", category=DeprecationWarning)56
57rank_zero_deprecation("test5")58
59cache = WarningCache()60cache.warn("test6")61cache.deprecation("test7")62
63output = stderr.getvalue()64expected_lines = [65f"test_warnings.py:{base_line}: test1",66f"test_warnings.py:{base_line + 1}: test2",67f"test_warnings.py:{base_line + 3}: test3",68f"test_warnings.py:{base_line + 4}: test4",69f"test_warnings.py:{base_line + 6}: test5",70f"test_warnings.py:{base_line + 9}: test6",71f"test_warnings.py:{base_line + 10}: test7",72]73
74for ln in expected_lines:75assert ln in output, f"Missing line {ln!r} in:\n{output}"76assert "rank_zero_warn(" not in output, "customized warning wrapper is not used"77
78# check that logging is properly configured79import logging80
81root_logger = logging.getLogger()82lightning_logger = logging.getLogger("lightning.fabric")83# should have a `StreamHandler`84assert lightning_logger.hasHandlers()85assert len(lightning_logger.handlers) == 186# set our own stream for testing87handler = lightning_logger.handlers[0]88assert isinstance(handler, logging.StreamHandler)89stderr = StringIO()90# necessary with `propagate = False`91lightning_logger.handlers[0].stream = stderr92
93# necessary with `propagate = True`94with redirect_stderr(stderr):95# Lightning should not configure the root `logging` logger by default96logging.info("test1")97root_logger.info("test1")98# but our logger instance99lightning_logger.info("test2")100# level is set to INFO101lightning_logger.debug("test3")102
103output = stderr.getvalue()104assert output == "test2\n", repr(output)105
106
107def test_is_path_in_lightning(monkeypatch, tmp_path):108monkeypatch.chdir(tmp_path)109if sys.platform != "win32":110assert _is_path_in_lightning(Path("/a/b/c/lightning"))111assert _is_path_in_lightning(Path("/a/b/c/lightning/core/lightning.py"))112assert _is_path_in_lightning(Path("/a/b/c/lightning/lightning"))113assert not _is_path_in_lightning(Path("/a/b/c/"))114# The following statements should assert the opposite for correctness, but a naive implementation of115# `_is_path_in_lightning` was requested, thus it cannot handle these cases116assert _is_path_in_lightning(Path(""))117assert _is_path_in_lightning(Path("/a/b/lightning"))118assert _is_path_in_lightning(Path("a/b/c/lightning"))119else:120assert _is_path_in_lightning(Path(r"C:\a\b\c\lightning"))121assert _is_path_in_lightning(Path(r"C:\a\b\c\lightning\core\lightning.py"))122assert _is_path_in_lightning(Path(r"C:\a\b\c\lightning\lightning"))123assert not _is_path_in_lightning(Path(r"\a\b\c"))124assert not _is_path_in_lightning(Path(r"C:\a\b\c"))125# The following statements should assert the opposite for correctness, but a naive implementation of126# `_is_path_in_lightning` was requested, thus it cannot handle these cases127assert _is_path_in_lightning(Path(r"D:\a\b\c\lightning")) # drive letter mismatch128
129
130def test_disable_possible_user_warnings():131with pytest.warns(PossibleUserWarning):132warnings.warn("test", PossibleUserWarning)133disable_possible_user_warnings()134with no_warning_call(PossibleUserWarning):135warnings.warn("test", PossibleUserWarning)136warnings.resetwarnings()137
138
139@pytest.mark.parametrize("setting", ["0", "off"])140@mock.patch.dict(os.environ, {}, clear=True)141def test_disable_possible_user_warnings_from_environment(setting):142with pytest.warns(PossibleUserWarning):143warnings.warn("test", PossibleUserWarning)144os.environ["POSSIBLE_USER_WARNINGS"] = setting145importlib.reload(lightning.fabric)146
147with no_warning_call(PossibleUserWarning):148warnings.warn("test", PossibleUserWarning)149warnings.resetwarnings()150