Add deprecation warning filter (#2546)

This commit is contained in:
Adam Hopkins 2022-09-18 18:54:35 +03:00 committed by GitHub
parent 4726cf1910
commit 7f894c45b3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 40 additions and 3 deletions

View File

@ -42,7 +42,6 @@ from typing import (
Union,
)
from urllib.parse import urlencode, urlunparse
from warnings import filterwarnings
from sanic_routing.exceptions import FinalizationError, NotFound
from sanic_routing.route import Route
@ -105,8 +104,6 @@ if TYPE_CHECKING:
if OS_IS_WINDOWS: # no cov
enable_windows_color_support()
filterwarnings("once", category=DeprecationWarning)
class Sanic(BaseSanic, StartupMixin, metaclass=TouchUpMeta):
"""

View File

@ -1,9 +1,12 @@
from __future__ import annotations
import sys
from inspect import getmembers, isclass, isdatadescriptor
from os import environ
from pathlib import Path
from typing import Any, Callable, Dict, Optional, Sequence, Union
from warnings import filterwarnings
from sanic.constants import LocalCertCreator
from sanic.errorpages import DEFAULT_FORMAT, check_error_format
@ -13,6 +16,20 @@ from sanic.log import deprecation, error_logger
from sanic.utils import load_module_from_file_location, str_to_bool
if sys.version_info >= (3, 8):
from typing import Literal
FilterWarningType = Union[
Literal["default"],
Literal["error"],
Literal["ignore"],
Literal["always"],
Literal["module"],
Literal["once"],
]
else:
FilterWarningType = str
SANIC_PREFIX = "SANIC_"
@ -22,6 +39,7 @@ DEFAULT_CONFIG = {
"AUTO_EXTEND": True,
"AUTO_RELOAD": False,
"EVENT_AUTOREGISTER": False,
"DEPRECATION_FILTER": "once",
"FORWARDED_FOR_HEADER": "X-Forwarded-For",
"FORWARDED_SECRET": None,
"GRACEFUL_SHUTDOWN_TIMEOUT": 15.0, # 15 sec
@ -72,6 +90,7 @@ class Config(dict, metaclass=DescriptorMeta):
AUTO_EXTEND: bool
AUTO_RELOAD: bool
EVENT_AUTOREGISTER: bool
DEPRECATION_FILTER: FilterWarningType
FORWARDED_FOR_HEADER: str
FORWARDED_SECRET: Optional[str]
GRACEFUL_SHUTDOWN_TIMEOUT: float
@ -130,6 +149,7 @@ class Config(dict, metaclass=DescriptorMeta):
self.load_environment_vars(SANIC_PREFIX)
self._configure_header_size()
self._configure_warnings()
self._check_error_format()
self._init = True
@ -178,6 +198,8 @@ class Config(dict, metaclass=DescriptorMeta):
self.LOCAL_CERT_CREATOR = LocalCertCreator[
self.LOCAL_CERT_CREATOR.upper()
]
elif attr == "DEPRECATION_FILTER":
self._configure_warnings()
@property
def FALLBACK_ERROR_FORMAT(self) -> str:
@ -205,6 +227,13 @@ class Config(dict, metaclass=DescriptorMeta):
self.REQUEST_MAX_SIZE,
)
def _configure_warnings(self):
filterwarnings(
self.DEPRECATION_FILTER,
category=DeprecationWarning,
module=r"sanic.*",
)
def _check_error_format(self, format: Optional[str] = None):
check_error_format(format or self.FALLBACK_ERROR_FORMAT)

View File

@ -1,5 +1,6 @@
import pytest
from sanic import Sanic
from sanic.log import deprecation
@ -7,3 +8,13 @@ def test_deprecation():
message = r"\[DEPRECATION v9\.9\] hello"
with pytest.warns(DeprecationWarning, match=message):
deprecation("hello", 9.9)
@pytest.mark.parametrize(
"filter,expected",
(("default", 1), ("once", 1), ("ignore", 0)),
)
def test_deprecation_filter(app: Sanic, filter, expected, recwarn):
app.config.DEPRECATION_FILTER = filter
deprecation("hello", 9.9)
assert len(recwarn) == expected