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_compress_deprecated(self): tmpdir, tmpdir2, base_name = self._create_files() # 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.assertTrue(not os.path.exists(tarball)) self.assertEqual(len(w.warnings), 1)
def test_issue3221(self): # Regression test for http://bugs.python.org/issue3221. def check_absolute(): exec("from os import path", ns) def check_relative(): exec("from . import relimport", ns) # Check both OK with __package__ and __name__ correct ns = dict(__package__='test', __name__='test.notarealmodule') check_absolute() check_relative() # Check both OK with only __name__ wrong ns = dict(__package__='test', __name__='notarealpkg.notarealmodule') check_absolute() check_relative() # Check relative fails with only __package__ wrong ns = dict(__package__='foo', __name__='test.notarealmodule') with check_warnings(('.+foo', RuntimeWarning)): check_absolute() self.assertRaises(SystemError, check_relative) # Check relative fails with __package__ and __name__ wrong ns = dict(__package__='foo', __name__='notarealpkg.notarealmodule') with check_warnings(('.+foo', RuntimeWarning)): check_absolute() self.assertRaises(SystemError, check_relative) # Check both fail with package set to a non-string ns = dict(__package__=object()) self.assertRaises(ValueError, check_absolute) self.assertRaises(ValueError, check_relative)
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 # try opening in universal newline mode t1 = self.writeTmp(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"])
def testFormat(self): # delay importing ctypes until we know we're in CPython from ctypes import (pythonapi, create_string_buffer, sizeof, byref, c_double) PyOS_ascii_formatd = pythonapi.PyOS_ascii_formatd buf = create_string_buffer(100) tests = [ ('%f', 100.0), ('%g', 100.0), ('%#g', 100.0), ('%#.2g', 100.0), ('%#.2g', 123.4567), ('%#.2g', 1.234567e200), ('%e', 1.234567e200), ('%e', 1.234), ('%+e', 1.234), ('%-e', 1.234), ] with check_warnings(): for format, val in tests: PyOS_ascii_formatd(byref(buf), sizeof(buf), bytes(format, 'ascii'), c_double(val)) self.assertEqual(buf.value, bytes(format % val, 'ascii'))
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__"] 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_resource_warning(self): # Issue #11453 fd = os.open(support.TESTFN, os.O_RDONLY) f = asyncore.file_wrapper(fd) with support.check_warnings(('', ResourceWarning)): f = None support.gc_collect()
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 test_merge(self): with support.check_warnings(('merge is deprecated', DeprecationWarning)): merge = self.interp.tk.merge call = self.interp.tk.call testcases = [ ((), ''), (('a',), 'a'), ((2,), '2'), (('',), '{}'), ('{', '\\{'), (('a', 'b', 'c'), 'a b c'), ((' ', '\t', '\r', '\n'), '{ } {\t} {\r} {\n}'), (('a', ' ', 'c'), 'a { } c'), (('a', '€'), 'a €'), (('a', '\U000104a2'), 'a \U000104a2'), (('a', b'\xe2\x82\xac'), 'a €'), (('a', ('b', 'c')), 'a {b c}'), (('a', 2), 'a 2'), (('a', 3.4), 'a 3.4'), (('a', (2, 3.4)), 'a {2 3.4}'), ((), ''), ((call('list', 1, '2', (3.4,)),), '{1 2 3.4}'), ] if tcl_version >= (8, 5): testcases += [ ((call('dict', 'create', 12, '\u20ac', b'\xe2\x82\xac', (3.4,)),), '{12 € € 3.4}'), ] for args, res in testcases: self.assertEqual(merge(*args), res, msg=args) self.assertRaises(UnicodeDecodeError, merge, b'\x80') self.assertRaises(UnicodeEncodeError, merge, '\udc80')
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_warnings_on_cleanup(self) -> None: # Two kinds of warning on shutdown # Issue 10888: may write to stderr if modules are nulled out # ResourceWarning will be triggered by __del__ with self.do_create() as dir: if os.sep != '\\': # Embed a backslash in order to make sure string escaping # in the displayed error message is dealt with correctly suffix = '\\check_backslash_handling' else: suffix = '' d = self.do_create(dir=dir, suf=suffix) #Check for the Issue 10888 message modules = [os, os.path] if has_stat: modules.append(stat) with support.captured_stderr() as err: with NulledModules(*modules): d.cleanup() message = err.getvalue().replace('\\\\', '\\') self.assertIn("while cleaning up", message) self.assertIn(d.name, message) # Check for the resource warning with support.check_warnings(('Implicitly', ResourceWarning), quiet=False): warnings.filterwarnings("always", category=ResourceWarning) d.__del__() self.assertFalse(os.path.exists(d.name), "TemporaryDirectory %s exists after __del__" % d.name)
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 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___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_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. expected = "2000 01 01 00 00 00 1 001" with support.check_warnings(): result = time.strftime("%Y %m %d %H %M %S %w %j", (0,)*9) self.assertEqual(expected, result)
def setUp(self): # create empty file fp = open(support.TESTFN, "w+") fp.close() self.teardown_files = [support.TESTFN] self._warnings_manager = support.check_warnings() self._warnings_manager.__enter__() warnings.filterwarnings("ignore", ".* potential security risk .*", RuntimeWarning)
def setUp(self): # create empty file fp = open(support.TESTFN, 'w+') fp.close() self._warnings_manager = support.check_warnings() self._warnings_manager.__enter__() warnings.filterwarnings('ignore', '.* potential security risk .*', RuntimeWarning)
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_misuse_global_2(self): source = """if 1: def f(): x = 1 global x """ with support.check_warnings(('.*assigned to before global declaration', SyntaxWarning)): compile(source, '<testcase>', 'exec')
def test_misuse_global(self): source = """if 1: def f(): print(x) global x """ with support.check_warnings(('.*used prior to global declaration', SyntaxWarning)): compile(source, '<testcase>', 'exec')
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_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
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_onlyOnePattern(self): with check_warnings(('', DeprecationWarning)): # Issue 2522: accept exactly one % pattern, and no extra chars. self.assertRaises(ValueError, locale.format, "%f\n", 'foo') self.assertRaises(ValueError, locale.format, "%f\r", 'foo') self.assertRaises(ValueError, locale.format, "%f\r\n", 'foo') self.assertRaises(ValueError, locale.format, " %f", 'foo') self.assertRaises(ValueError, locale.format, "%fg", 'foo') self.assertRaises(ValueError, locale.format, "%^g", 'foo') self.assertRaises(ValueError, locale.format, "%f%%", 'foo')
def test_at_least_import_untested_modules(self): with support.check_warnings(quiet=True): import bdb import cgitb import code import distutils.bcppcompiler import distutils.ccompiler import distutils.cygwinccompiler import distutils.emxccompiler import distutils.filelist if sys.platform.startswith('win'): import distutils.msvccompiler 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 encodings import formatter import getpass import html.entities import imghdr import keyword import macurl2path import mailcap import nturl2path import os2emxpath import pstats import py_compile import sndhdr import tabnanny import timeit try: import tty # not available on Windows except ImportError: if support.verbose: print("skipping tty")
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__
def test_warnings_on_cleanup(self): # ResourceWarning will be triggered by __del__ with self.do_create() as dir: d = self.do_create(dir=dir, recurse=3) name = d.name # Check for the resource warning with support.check_warnings(("Implicitly", ResourceWarning), quiet=False): warnings.filterwarnings("always", category=ResourceWarning) del d support.gc_collect() self.assertFalse(os.path.exists(name), "TemporaryDirectory %s exists after __del__" % name)
def test_global_err_then_warn(self): # Bug tickler: The SyntaxError raised for one global statement # shouldn't be clobbered by a SyntaxWarning issued for a later one. source = """if 1: def error(a): global a # SyntaxError def warning(): b = 1 global b # SyntaxWarning """ with support.check_warnings((".*assigned to before global declaration", SyntaxWarning)): self._check_error(source, "local and global", lineno=2)
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_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_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(urllib.error.URLError) as cm: self.urlopen("https://localhost:%s/bizarre" % handler.port, cafile=CERT_fakehostname)
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 errmsg = r'join\(\) argument must be str or bytes, not %r' with self.assertRaisesRegex(TypeError, errmsg % 'int'): self.pathmodule.join(42, 'str') with self.assertRaisesRegex(TypeError, errmsg % 'int'): self.pathmodule.join('str', 42) with self.assertRaisesRegex(TypeError, errmsg % 'bytearray'): self.pathmodule.join(bytearray(b'foo'), bytearray(b'bar'))
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') errmsg = r'relpath\(\) argument must be str or bytes, not %r' with self.assertRaisesRegex(TypeError, errmsg % 'int'): self.pathmodule.relpath(42, 'str') with self.assertRaisesRegex(TypeError, errmsg % 'int'): self.pathmodule.relpath('str', 42) with self.assertRaisesRegex(TypeError, errmsg % 'bytearray'): self.pathmodule.relpath(bytearray(b'foo'), bytearray(b'bar'))
def test_untested_modules_can_be_imported(self): untested = ('bdb', 'encodings', 'formatter', 'imghdr', 'macurl2path', '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 if sys.platform.startswith('win'): import distutils.msvccompiler 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_import_initless_directory_warning(self): # NOTE: to test this, we have to remove Jython's JavaImporter # (bound to the string '__classpath__', which of course # supports such directories as possible Java packages. # # For Jython 3.x we really need to rethink what it does, since # it repeatedly causes questions on Jython forums, but too # late to change for 2.7, except perhaps by some option. classpath_entry = sys.path.index('__classpath__') del sys.path[classpath_entry] try: with check_warnings(('', ImportWarning)): # Just a random non-package directory we always expect to be # somewhere in sys.path... self.assertRaises(ImportError, __import__, "site-packages") finally: sys.path.insert(classpath_entry, '__classpath__')
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_join_errors(self): 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') 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_parse_bytes(self): # UTF-8 is default encoding, US-ASCII is compatible with UTF-8, # UTF-16 is autodetected encodings = ('us-ascii', 'utf-8', 'utf-16', 'utf-16le', 'utf-16be') for encoding in encodings: self.check_parse(BytesIO(xml_bytes(self.data, encoding))) make_xml_file(self.data, encoding) self.check_parse(TESTFN) with open(TESTFN, 'rb') as f: self.check_parse(f) self.check_parse(BytesIO(xml_bytes(self.data, encoding, None))) make_xml_file(self.data, encoding, None) self.check_parse(TESTFN) with open(TESTFN, 'rb') as f: self.check_parse(f) # accept UTF-8 with BOM self.check_parse(BytesIO(xml_bytes(self.data, 'utf-8-sig', 'utf-8'))) make_xml_file(self.data, 'utf-8-sig', 'utf-8') self.check_parse(TESTFN) with open(TESTFN, 'rb') as f: self.check_parse(f) self.check_parse(BytesIO(xml_bytes(self.data, 'utf-8-sig', None))) make_xml_file(self.data, 'utf-8-sig', None) self.check_parse(TESTFN) with open(TESTFN, 'rb') as f: self.check_parse(f) # accept data with declared encoding self.check_parse(BytesIO(xml_bytes(self.data, 'iso-8859-1'))) make_xml_file(self.data, 'iso-8859-1') self.check_parse(TESTFN) with open(TESTFN, 'rb') as f: self.check_parse(f) # fail on non-UTF-8 incompatible data without declared encoding with self.assertRaises(SAXException): self.check_parse(BytesIO(xml_bytes(self.data, 'iso-8859-1', None))) make_xml_file(self.data, 'iso-8859-1', None) with support.check_warnings(('unclosed file', ResourceWarning)): # XXX Failed parser leaks an opened file. with self.assertRaises(SAXException): self.check_parse(TESTFN) # Collect leaked file. gc.collect() with open(TESTFN, 'rb') as f: with self.assertRaises(SAXException): self.check_parse(f)
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] self.assertEqual(len(warnings), 1, warnings) warn = warnings[0] self.assertTrue( warn.startswith(f'tests may fail, unable to change ' f'the current working directory ' f'to {bad_dir!r}: '), warn)
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_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 os_helper.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) self.assertEqual(len(warnings), 1, warnings) warn = warnings[0] self.assertTrue( warn.startswith(f'tests may fail, unable to create ' f'temporary directory {path!r}: '), warn)
def test___class___delayed(self): test_namespace = None class Meta(type): def __new__(cls, name, bases, namespace): nonlocal test_namespace test_namespace = namespace return None 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_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 # TODO: skip now by hhatto return 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_exec(self): g = {} exec('z = 1', g) if '__builtins__' in g: del g['__builtins__'] self.assertEqual(g, {'z': 1}) exec('z = 1+1', g) if '__builtins__' in g: del g['__builtins__'] self.assertEqual(g, {'z': 2}) g = {} l = {} with check_warnings(): warnings.filterwarnings("ignore", "global statement", module="<string>") exec('global a; a = 1; b = 2', g, l) if '__builtins__' in g: del g['__builtins__'] if '__builtins__' in l: del l['__builtins__'] self.assertEqual((g, l), ({'a': 1}, {'b': 2}))
def test_unquoting(self): # Make sure unquoting of all ASCII values works escape_list = [] for num in range(128): given = hexescape(chr(num)) expect = chr(num) result = urllib.parse.unquote(given) self.assertEqual(expect, result, "using unquote(): %r != %r" % (expect, result)) result = urllib.parse.unquote_plus(given) self.assertEqual(expect, result, "using unquote_plus(): %r != %r" % (expect, result)) escape_list.append(given) escape_string = ''.join(escape_list) del escape_list result = urllib.parse.unquote(escape_string) self.assertEqual(result.count('%'), 1, "using unquote(): not all characters escaped: " "%s" % result) self.assertRaises((TypeError, AttributeError), urllib.parse.unquote, None) self.assertRaises((TypeError, AttributeError), urllib.parse.unquote, ()) with support.check_warnings(('', BytesWarning), quiet=True): self.assertRaises((TypeError, AttributeError), urllib.parse.unquote, b'')
def test_import_initless_directory_warning(self): with check_warnings(('', ImportWarning)): # Just a random non-package directory we always expect to be # somewhere in sys.path... self.assertRaises(ImportError, __import__, "site-packages")
def test_SO_value(self): with check_warnings(('', DeprecationWarning)): self.assertEqual(sysconfig.get_config_var('SO'), sysconfig.get_config_var('EXT_SUFFIX'))
def test_CheckBinary(self): with (test_support.check_warnings() if sys.version_info[0] >= 3 else test_support.check_py3k_warnings()): b = sqlite.Binary( chr(0).encode() + b"'" if sys.version_info[0] >= 3 else chr(0) + b"'")
def test_non_str_argument(self): # Issue #15778 with check_warnings(('', BytesWarning), quiet=True): arg = b'abc' exc = ImportError(arg) self.assertEqual(str(arg), str(exc))
"""Test script for the binhex C module Uses the mechanism of the python binhex module Based on an original test by Roger E. Masse. """ import unittest from test import support with support.check_warnings(('', DeprecationWarning)): binhex = support.import_fresh_module('binhex') class BinHexTestCase(unittest.TestCase): def setUp(self): # binhex supports only file names encodable to Latin1 self.fname1 = support.TESTFN_ASCII + "1" self.fname2 = support.TESTFN_ASCII + "2" self.fname3 = support.TESTFN_ASCII + "very_long_filename__very_long_filename__very_long_filename__very_long_filename__" def tearDown(self): support.unlink(self.fname1) support.unlink(self.fname2) support.unlink(self.fname3) DATA = b'Jack is my hero' def test_binhex(self): with open(self.fname1, 'wb') as f: f.write(self.DATA) binhex.binhex(self.fname1, self.fname2)
def _test_format(self, format, value, out, **format_opts): with support.check_warnings(('', DeprecationWarning)): self._test_formatfunc(format, value, out, func=locale.format, **format_opts)
def test_ushort_max(self): with support.check_warnings() as w: ts.T_USHORT = USHRT_MAX + 1 self.has_warned(w)
def test_short_min(self): with support.check_warnings() as w: ts.T_SHORT = SHRT_MIN - 1 self.has_warned(w)
def test_ubyte_max(self): with support.check_warnings() as w: ts.T_UBYTE = UCHAR_MAX + 1 self.has_warned(w)
def test_byte_min(self): with support.check_warnings() as w: ts.T_BYTE = CHAR_MIN - 1 self.has_warned(w)
def test_deprecated_parse_qsl(self): # this func is moved to urllib.parse, this is just a sanity check with check_warnings(('cgi.parse_qsl is deprecated, use urllib.parse.' 'parse_qsl instead', DeprecationWarning)): self.assertEqual([('a', 'A1'), ('b', 'B2'), ('B', 'B3')], cgi.parse_qsl('a=A1&b=B2&B=B3'))
def get_collector(self): with support.check_warnings(("", DeprecationWarning), quite=False): return EventCollector(strict=True, convert_charrefs=False)
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)