import name while suppressing deprecationwarning with warnings catchwarnings warnings simplefilter ignore categorydeprecationwarning return importlib importmodulename def checksyntaxwarningtestcase statement errtext lineno1 offsetnone test also that a warning is emitted only once from test support import checksyntaxerror with warnings catchwarningsrecordtrue as warns warnings simplefilter always syntaxwarning compilestatement testcase exec testcase assertequallenwarns 1 warns warn warns testcase asserttrueissubclasswarn category syntaxwarning warn category if errtext testcase assertregexstrwarn message errtext testcase assertequalwarn filename testcase testcase assertisnotnonewarn lineno if lineno is not none testcase assertequalwarn lineno lineno syntaxwarning should be converted to syntaxerror when raised since the latter contains more information and provides better error report with warnings catchwarningsrecordtrue as warns warnings simplefilter error syntaxwarning checksyntaxerrortestcase statement errtext linenolineno offsetoffset no warnings are leaked when a syntaxerror is raised testcase assertequalwarns def ignorewarnings category def decoratortest functools wrapstest def wrapperself args kwargs with warnings catchwarnings warnings simplefilter ignore categorycategory return testself args kwargs return wrapper return decorator class warningsrecorderobject def initself warningslist self warnings warningslist self last 0 def getattrself attr if lenself warnings self last return getattrself warnings1 attr elif attr in warnings warningmessage warningdetails return none raise attributeerrorr has no attribute r self attr property def warningsself return self warningsself last def resetself self last lenself warnings contextlib contextmanager def checkwarningsfilters kwargs quiet kwargs get quiet if not filters filters warning preserve backward compatibility if quiet is none quiet true return filterwarningsfilters quiet contextlib contextmanager def checknowarningstestcase message categorywarning forcegcfalse from test support import gccollect with warnings catchwarningsrecordtrue as warns warnings filterwarnings always messagemessage categorycategory yield if forcegc gccollect testcase assertequalwarns contextlib contextmanager def checknoresourcewarningtestcase with checknowarningstestcase categoryresourcewarning forcegctrue yield def filterwarningsfilters quietfalse clear the warning registry of the calling module in order to reraise the warnings frame sys getframe2 registry frame fglobals get warningregistry if registry registry clear with warnings catchwarningsrecordtrue as w set filter always to record all warnings because testwarnings swap the module we need to look up in the sys modules dictionary sys modules warnings simplefilteralways yield warningsrecorderw filter the recorded warnings reraise listw missing for msg cat in filters seen false for w in reraise warning w message filter out the matching messages if re matchmsg strwarning re i and issubclasswarning class cat seen true reraise removew if not seen and not quiet this filter caught nothing missing appendmsg cat name if reraise raise assertionerrorunhandled warning s reraise0 if missing raise assertionerrorfilter r s did not catch any warning missing0 contextlib contextmanager def saverestorewarningsfilters oldfilters warnings filters try yield finally warnings filters oldfilters def warnaboutdeprecation warnings warn this is used in testsupport test to ensure support ignoredeprecationsfrom works as expected you should not be seeing this deprecationwarning stacklevel0 import name while suppressing deprecationwarning test also that a warning is emitted only once syntaxwarning should be converted to syntaxerror when raised since the latter contains more information and provides better error report no warnings are leaked when a syntaxerror is raised decorator to suppress warnings use of context managers to hide warnings make diffs more noisy and tools like git blame less useful convenience wrapper for the warnings list returned on entry to the warnings catch_warnings context manager context manager to silence warnings accept 2 tuples as positional arguments message regexp warningcategory optional argument if quiet is true it does not fail if a filter catches nothing default true without argument default false if some filters are defined without argument it defaults to check_warnings warning quiet true preserve backward compatibility context manager to check that no warnings are emitted this context manager enables a given warning within its scope and checks that no warnings are emitted even with that warning enabled if force_gc is true a garbage collection is attempted before checking for warnings this may help to catch warnings emitted when objects are deleted such as resourcewarning other keyword arguments are passed to warnings filterwarnings context manager to check that no resourcewarning is emitted usage with check_no_resource_warning self f open del f you must remove the object which may emit resourcewarning before the end of the context manager catch the warnings then check if all the expected warnings have been raised and re raise unexpected warnings if quiet is true only re raise the unexpected warnings clear the warning registry of the calling module in order to re raise the warnings set filter always to record all warnings because test_warnings swap the module we need to look up in the sys modules dictionary filter the recorded warnings filter out the matching messages this filter caught nothing
import contextlib
import functools
import importlib
import re
import sys
import warnings


def import_deprecated(name):
    
    with warnings.catch_warnings():
        warnings.simplefilter('ignore', category=DeprecationWarning)
        return importlib.import_module(name)


def check_syntax_warning(testcase, statement, errtext='',
                         *, lineno=1, offset=None):
    
    from test.support import check_syntax_error
    with warnings.catch_warnings(record=True) as warns:
        warnings.simplefilter('always', SyntaxWarning)
        compile(statement, '<testcase>', 'exec')
    testcase.assertEqual(len(warns), 1, warns)

    warn, = warns
    testcase.assertTrue(issubclass(warn.category, SyntaxWarning),
                        warn.category)
    if errtext:
        testcase.assertRegex(str(warn.message), errtext)
    testcase.assertEqual(warn.filename, '<testcase>')
    testcase.assertIsNotNone(warn.lineno)
    if lineno is not None:
        testcase.assertEqual(warn.lineno, lineno)

    
    
    
    with warnings.catch_warnings(record=True) as warns:
        warnings.simplefilter('error', SyntaxWarning)
        check_syntax_error(testcase, statement, errtext,
                           lineno=lineno, offset=offset)
    
    testcase.assertEqual(warns, [])


def ignore_warnings(*, category):
    
    def decorator(test):
        @functools.wraps(test)
        def wrapper(self, *args, **kwargs):
            with warnings.catch_warnings():
                warnings.simplefilter('ignore', category=category)
                return test(self, *args, **kwargs)
        return wrapper
    return decorator


class WarningsRecorder(object):
    
    def __init__(self, warnings_list):
        self._warnings = warnings_list
        self._last = 0

    def __getattr__(self, attr):
        if len(self._warnings) > self._last:
            return getattr(self._warnings[-1], attr)
        elif attr in warnings.WarningMessage._WARNING_DETAILS:
            return None
        raise AttributeError("%r has no attribute %r" % (self, attr))

    @property
    def warnings(self):
        return self._warnings[self._last:]

    def reset(self):
        self._last = len(self._warnings)


@contextlib.contextmanager
def check_warnings(*filters, **kwargs):
    
    quiet = kwargs.get('quiet')
    if not filters:
        filters = (("", Warning),)
        
        if quiet is None:
            quiet = True
    return _filterwarnings(filters, quiet)


@contextlib.contextmanager
def check_no_warnings(testcase, message='', category=Warning, force_gc=False):
    
    from test.support import gc_collect
    with warnings.catch_warnings(record=True) as warns:
        warnings.filterwarnings('always',
                                message=message,
                                category=category)
        yield
        if force_gc:
            gc_collect()
    testcase.assertEqual(warns, [])


@contextlib.contextmanager
def check_no_resource_warning(testcase):
    
    with check_no_warnings(testcase, category=ResourceWarning, force_gc=True):
        yield


def _filterwarnings(filters, quiet=False):
    
    
    
    frame = sys._getframe(2)
    registry = frame.f_globals.get('__warningregistry__')
    if registry:
        registry.clear()
    with warnings.catch_warnings(record=True) as w:
        
        
        
        sys.modules['warnings'].simplefilter("always")
        yield WarningsRecorder(w)
    
    reraise = list(w)
    missing = []
    for msg, cat in filters:
        seen = False
        for w in reraise[:]:
            warning = w.message
            
            if (re.match(msg, str(warning), re.I) and
                issubclass(warning.__class__, cat)):
                seen = True
                reraise.remove(w)
        if not seen and not quiet:
            
            missing.append((msg, cat.__name__))
    if reraise:
        raise AssertionError("unhandled warning %s" % reraise[0])
    if missing:
        raise AssertionError("filter (%r, %s) did not catch any warning" %
                             missing[0])


@contextlib.contextmanager
def save_restore_warnings_filters():
    old_filters = warnings.filters[:]
    try:
        yield
    finally:
        warnings.filters[:] = old_filters


def _warn_about_deprecation():
    warnings.warn(
        "This is used in test_support test to ensure"
        " support.ignore_deprecations_from() works as expected."
        " You should not be seeing this.",
        DeprecationWarning,
        stacklevel=0,
    )