def test_compress_deprecated(self): tmpdir = self._create_files() base_name = os.path.join(self.mkdtemp(), 'archive') # using compress and testing the PendingDeprecationWarning old_dir = os.getcwd() os.chdir(tmpdir) try: with check_warnings() as w: warnings.simplefilter("always") make_tarball(base_name, 'dist', compress='compress') finally: os.chdir(old_dir) tarball = base_name + '.tar.Z' self.assertTrue(os.path.exists(tarball)) self.assertEqual(len(w.warnings), 1) # same test with dry_run os.remove(tarball) old_dir = os.getcwd() os.chdir(tmpdir) try: with check_warnings() as w: warnings.simplefilter("always") make_tarball(base_name, 'dist', compress='compress', dry_run=True) finally: os.chdir(old_dir) self.assertFalse(os.path.exists(tarball)) self.assertEqual(len(w.warnings), 1)
def test_check_warnings(self): # Explicit tests for the test.support convenience wrapper wmod = self.module if wmod is not sys.modules['warnings']: self.skipTest('module to test is not loaded warnings module') with support.check_warnings(quiet=False) as w: self.assertEqual(w.warnings, []) wmod.simplefilter("always") wmod.warn("foo") self.assertEqual(str(w.message), "foo") wmod.warn("bar") self.assertEqual(str(w.message), "bar") self.assertEqual(str(w.warnings[0].message), "foo") self.assertEqual(str(w.warnings[1].message), "bar") w.reset() self.assertEqual(w.warnings, []) with support.check_warnings(): # defaults to quiet=True without argument pass with support.check_warnings(('foo', UserWarning)): wmod.warn("foo") with self.assertRaises(AssertionError): with support.check_warnings(('', RuntimeWarning)): # defaults to quiet=False with argument pass with self.assertRaises(AssertionError): with support.check_warnings(('foo', RuntimeWarning)): wmod.warn("foo")
def test_https_with_cadefault(self): handler = self.start_https_server(certfile=CERT_localhost) # Self-signed cert should fail verification with system certificate store with support.check_warnings(('', DeprecationWarning)): with self.assertRaises(urllib.error.URLError) as cm: self.urlopen("https://localhost:%s/bizarre" % handler.port, cadefault=True)
def check_all(self, modname): names = {} with support.check_warnings( (".* (module|package)", DeprecationWarning), ("", ResourceWarning), quiet=True): try: exec("import %s" % modname, names) except: # Silent fail here seems the best route since some modules # may not be available or not initialize properly in all # environments. raise FailedImport(modname) if not hasattr(sys.modules[modname], "__all__"): raise NoAll(modname) names = {} with self.subTest(module=modname): try: exec("from %s import *" % modname, names) except Exception as e: # Include the module name in the exception string self.fail("__all__ failure in {}: {}: {}".format( modname, e.__class__.__name__, e)) if "__builtins__" in names: del names["__builtins__"] if '__annotations__' in names: del names['__annotations__'] keys = set(names) all_list = sys.modules[modname].__all__ all_set = set(all_list) self.assertCountEqual(all_set, all_list, "in module {}".format(modname)) self.assertEqual(keys, all_set, "in module {}".format(modname))
def test_check_metadata_deprecated(self): # makes sure make_metadata is deprecated cmd = self._get_cmd() with check_warnings() as w: warnings.simplefilter("always") cmd.check_metadata() self.assertEqual(len(w.warnings), 1)
def test_extension_init(self): # the first argument, which is the name, must be a string self.assertRaises(AssertionError, Extension, 1, []) ext = Extension('name', []) self.assertEqual(ext.name, 'name') # the second argument, which is the list of files, must # be a list of strings self.assertRaises(AssertionError, Extension, 'name', 'file') self.assertRaises(AssertionError, Extension, 'name', ['file', 1]) ext = Extension('name', ['file1', 'file2']) self.assertEqual(ext.sources, ['file1', 'file2']) # others arguments have defaults for attr in ('include_dirs', 'define_macros', 'undef_macros', 'library_dirs', 'libraries', 'runtime_library_dirs', 'extra_objects', 'extra_compile_args', 'extra_link_args', 'export_symbols', 'swig_opts', 'depends'): self.assertEqual(getattr(ext, attr), []) self.assertEqual(ext.language, None) self.assertEqual(ext.optional, None) # if there are unknown keyword options, warn about them with check_warnings() as w: warnings.simplefilter('always') ext = Extension('name', ['file1', 'file2'], chic=True) self.assertEqual(len(w.warnings), 1) self.assertEqual(str(w.warnings[0].message), "Unknown Extension options: 'chic'")
def testWarnings(self): with check_warnings(quiet=True) as w: self.assertEqual(w.warnings, []) self.assertRaises(TypeError, self.FileIO, []) self.assertEqual(w.warnings, []) self.assertRaises(ValueError, self.FileIO, "/some/invalid/name", "rt") self.assertEqual(w.warnings, [])
def test_change_cwd__chdir_warning(self): """Check the warning message when os.chdir() fails.""" path = TESTFN + '_does_not_exist' with support.check_warnings() as recorder: with support.change_cwd(path=path, quiet=True): pass messages = [str(w.message) for w in recorder.warnings] self.assertEqual(messages, ['tests may fail, unable to change CWD to: ' + path])
def test_deprecated_parse_qs(self): # this func is moved to urllib.parse, this is just a sanity check with check_warnings(('cgi.parse_qs is deprecated, use urllib.parse.' 'parse_qs instead', DeprecationWarning)): self.assertEqual({ 'a': ['A1'], 'B': ['B3'], 'b': ['B2'] }, cgi.parse_qs('a=A1&b=B2&B=B3'))
def test_resource_warning(self): # Issue #11453 fd = os.open(support.TESTFN, os.O_RDONLY) f = asyncore.file_wrapper(fd) os.close(fd) with support.check_warnings(('', ResourceWarning)): f = None support.gc_collect()
def test_opening_mode(self): try: # invalid mode, should raise ValueError fi = FileInput(mode="w") self.fail("FileInput should reject invalid mode argument") except ValueError: pass t1 = None try: # try opening in universal newline mode t1 = writeTmp(1, [b"A\nB\r\nC\rD"], mode="wb") with check_warnings(('', DeprecationWarning)): fi = FileInput(files=t1, mode="U") with check_warnings(('', DeprecationWarning)): lines = list(fi) self.assertEqual(lines, ["A\n", "B\n", "C\n", "D"]) finally: remove_tempfiles(t1)
def test_get_loader_handles_missing_loader_attribute(self): global __loader__ this_loader = __loader__ del __loader__ try: with check_warnings() as w: self.assertIsNotNone(pkgutil.get_loader(__name__)) self.assertEqual(len(w.warnings), 0) finally: __loader__ = this_loader
def test_default_values_for_zero(self): # Make sure that using all zeros uses the proper default # values. No test for daylight savings since strftime() does # not change output based on its value and no test for year # because systems vary in their support for year 0. expected = "2000 01 01 00 00 00 1 001" with support.check_warnings(): result = time.strftime("%Y %m %d %H %M %S %w %j", (2000, ) + (0, ) * 8) self.assertEqual(expected, result)
def test___classcell___missing(self): # See issue #23722 # Some metaclasses may not pass the original namespace to type.__new__ # We test that case here by forcibly deleting __classcell__ class Meta(type): def __new__(cls, name, bases, namespace): namespace.pop('__classcell__', None) return super().__new__(cls, name, bases, namespace) # The default case should continue to work without any warnings with check_warnings() as w: warnings.simplefilter("always", DeprecationWarning) class WithoutClassRef(metaclass=Meta): pass self.assertEqual(w.warnings, []) # With zero-arg super() or an explicit __class__ reference, we expect # __build_class__ to emit a DeprecationWarning complaining that # __class__ was not set, and asking if __classcell__ was propagated # to type.__new__. # In Python 3.7, that warning will become a RuntimeError. expected_warning = ( '__class__ not set.*__classcell__ propagated', DeprecationWarning ) with check_warnings(expected_warning): warnings.simplefilter("always", DeprecationWarning) class WithClassRef(metaclass=Meta): def f(self): return __class__ # Check __class__ still gets set despite the warning self.assertIs(WithClassRef().f(), WithClassRef) # Check the warning is turned into an error as expected with warnings.catch_warnings(): warnings.simplefilter("error", DeprecationWarning) with self.assertRaises(DeprecationWarning): class WithClassRef(metaclass=Meta): def f(self): return __class__
async def start(): foo_coro = foo() self.assertRegex( repr(foo_coro), r'<CoroWrapper .*\.foo\(\) running at .*pep492.*>') with support.check_warnings((r'.*foo.*was never', RuntimeWarning)): foo_coro = None support.gc_collect() self.assertTrue(m_log.error.called) message = m_log.error.call_args[0][0] self.assertRegex(message, r'CoroWrapper.*foo.*was never')
def test_change_cwd__non_existent_dir__quiet_true(self): """Test passing a non-existent directory with quiet=True.""" original_cwd = os.getcwd() with support.temp_dir() as parent_dir: bad_dir = os.path.join(parent_dir, 'does_not_exist') with support.check_warnings() as recorder: with support.change_cwd(bad_dir, quiet=True) as new_cwd: self.assertEqual(new_cwd, original_cwd) self.assertEqual(os.getcwd(), new_cwd) warnings = [str(w.message) for w in recorder.warnings] expected = ['tests may fail, unable to change CWD to: ' + bad_dir] self.assertEqual(warnings, expected)
def test_relpath_errors(self): # Check relpath() raises friendly TypeErrors. with support.check_warnings(('', (BytesWarning, DeprecationWarning)), quiet=True): errmsg = "Can't mix strings and bytes in path components" with self.assertRaisesRegex(TypeError, errmsg): self.pathmodule.relpath(b'bytes', 'str') with self.assertRaisesRegex(TypeError, errmsg): self.pathmodule.relpath('str', b'bytes') with self.assertRaisesRegex(TypeError, 'int'): self.pathmodule.relpath(42, 'str') with self.assertRaisesRegex(TypeError, 'int'): self.pathmodule.relpath('str', 42) with self.assertRaisesRegex(TypeError, 'bytearray'): self.pathmodule.relpath(bytearray(b'foo'), bytearray(b'bar'))
def test_https_with_cafile(self): handler = self.start_https_server(certfile=CERT_localhost) with support.check_warnings(('', DeprecationWarning)): # Good cert data = self.urlopen("https://localhost:%s/bizarre" % handler.port, cafile=CERT_localhost) self.assertEqual(data, b"we care a bit") # Bad cert with self.assertRaises(urllib.error.URLError) as cm: self.urlopen("https://localhost:%s/bizarre" % handler.port, cafile=CERT_fakehostname) # Good cert, but mismatching hostname handler = self.start_https_server(certfile=CERT_fakehostname) with self.assertRaises(ssl.CertificateError) as cm: self.urlopen("https://localhost:%s/bizarre" % handler.port, cafile=CERT_fakehostname)
def test_temp_dir__existing_dir__quiet_true(self): """Test passing a directory that already exists with quiet=True.""" path = tempfile.mkdtemp() path = os.path.realpath(path) try: with support.check_warnings() as recorder: with support.temp_dir(path, quiet=True) as temp_path: self.assertEqual(path, temp_path) warnings = [str(w.message) for w in recorder.warnings] # Make sure temp_dir did not delete the original directory. self.assertTrue(os.path.isdir(path)) finally: shutil.rmtree(path) expected = ['tests may fail, unable to create temp dir: ' + path] self.assertEqual(warnings, expected)
def test_storlines(self): f = io.BytesIO(RETR_DATA.replace('\r\n', '\n').encode('ascii')) self.client.storlines('stor', f) self.check_data(self.server.handler_instance.last_received_data, RETR_DATA) # test new callback arg flag = [] f.seek(0) self.client.storlines('stor foo', f, callback=lambda x: flag.append(None)) self.assertTrue(flag) f = io.StringIO(RETR_DATA.replace('\r\n', '\n')) # storlines() expects a binary file, not a text file with support.check_warnings(('', BytesWarning), quiet=True): self.assertRaises(TypeError, self.client.storlines, 'stor foo', f)
def test_untested_modules_can_be_imported(self): untested = ('bdb', 'encodings', 'formatter', 'nturl2path', 'tabnanny') with support.check_warnings(quiet=True): for name in untested: try: support.import_module('test.test_{}'.format(name)) except unittest.SkipTest: importlib.import_module(name) else: self.fail('{} has tests even though test_sundry claims ' 'otherwise'.format(name)) import distutils.bcppcompiler import distutils.ccompiler import distutils.cygwinccompiler import distutils.filelist import distutils.text_file import distutils.unixccompiler import distutils.command.bdist_dumb if sys.platform.startswith('win'): import distutils.command.bdist_msi import distutils.command.bdist import distutils.command.bdist_rpm import distutils.command.bdist_wininst import distutils.command.build_clib import distutils.command.build_ext import distutils.command.build import distutils.command.clean import distutils.command.config import distutils.command.install_data import distutils.command.install_egg_info import distutils.command.install_headers import distutils.command.install_lib import distutils.command.register import distutils.command.sdist import distutils.command.upload import html.entities try: import tty # Not available on Windows except ImportError: if support.verbose: print("skipping tty")
def test_join_errors(self): # Check join() raises friendly TypeErrors. with support.check_warnings(('', BytesWarning), quiet=True): errmsg = "Can't mix strings and bytes in path components" with self.assertRaisesRegex(TypeError, errmsg): self.pathmodule.join(b'bytes', 'str') with self.assertRaisesRegex(TypeError, errmsg): self.pathmodule.join('str', b'bytes') # regression, see #15377 with self.assertRaisesRegex(TypeError, 'int'): self.pathmodule.join(42, 'str') with self.assertRaisesRegex(TypeError, 'int'): self.pathmodule.join('str', 42) with self.assertRaisesRegex(TypeError, 'int'): self.pathmodule.join(42) with self.assertRaisesRegex(TypeError, 'list'): self.pathmodule.join([]) with self.assertRaisesRegex(TypeError, 'bytearray'): self.pathmodule.join(bytearray(b'foo'), bytearray(b'bar'))
def test_splitunc(self): with self.assertWarns(DeprecationWarning): ntpath.splitunc('') with support.check_warnings(('', DeprecationWarning)): tester('ntpath.splitunc("c:\\foo\\bar")', ('', 'c:\\foo\\bar')) tester('ntpath.splitunc("c:/foo/bar")', ('', 'c:/foo/bar')) tester('ntpath.splitunc("\\\\conky\\mountpoint\\foo\\bar")', ('\\\\conky\\mountpoint', '\\foo\\bar')) tester('ntpath.splitunc("//conky/mountpoint/foo/bar")', ('//conky/mountpoint', '/foo/bar')) tester('ntpath.splitunc("\\\\\\conky\\mountpoint\\foo\\bar")', ('', '\\\\\\conky\\mountpoint\\foo\\bar')) tester('ntpath.splitunc("///conky/mountpoint/foo/bar")', ('', '///conky/mountpoint/foo/bar')) tester('ntpath.splitunc("\\\\conky\\\\mountpoint\\foo\\bar")', ('', '\\\\conky\\\\mountpoint\\foo\\bar')) tester('ntpath.splitunc("//conky//mountpoint/foo/bar")', ('', '//conky//mountpoint/foo/bar')) self.assertEqual(ntpath.splitunc('//conky/MOUNTPOİNT/foo/bar'), ('//conky/MOUNTPOİNT', '/foo/bar'))
def test___class___delayed(self): # See issue #23722 test_namespace = None class Meta(type): def __new__(cls, name, bases, namespace): nonlocal test_namespace test_namespace = namespace return None # This case shouldn't trigger the __classcell__ deprecation warning with check_warnings() as w: warnings.simplefilter("always", DeprecationWarning) class A(metaclass=Meta): @staticmethod def f(): return __class__ self.assertEqual(w.warnings, []) self.assertIs(A, None) B = type("B", (), test_namespace) self.assertIs(B.f(), B)
def test_iter_importers_avoids_emulation(self): with check_warnings() as w: for importer in pkgutil.iter_importers(): pass self.assertEqual(len(w.warnings), 0)
def test_get_importer_avoids_emulation(self): # We use an illegal path so *none* of the path hooks should fire with check_warnings() as w: self.assertIsNone(pkgutil.get_importer("*??")) self.assertEqual(len(w.warnings), 0)
def test_find_loader_avoids_emulation(self): with check_warnings() as w: self.assertIsNotNone(pkgutil.find_loader("sys")) self.assertIsNotNone(pkgutil.find_loader("os")) self.assertIsNotNone(pkgutil.find_loader("test.support")) self.assertEqual(len(w.warnings), 0)
def check_deprecated(self): return check_warnings( ("This emulation is deprecated, use 'importlib' instead", DeprecationWarning))
def test_certfile_arg_warn(self): with support.check_warnings(('', DeprecationWarning)): with mock.patch.object(self.imap_class, 'open'): with mock.patch.object(self.imap_class, '_connect'): self.imap_class('localhost', 143, certfile=CERTFILE)
def setUp(self): self._warnings_manager = check_warnings() self._warnings_manager.__enter__() warnings.filterwarnings("ignore", ".* class is insecure.*", DeprecationWarning)