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_opening_mode(self): try: # invalid mode, should raise ValueError fi = FileInput(mode="w", encoding="utf-8") 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 warnings_helper.check_warnings(('', DeprecationWarning)): fi = FileInput(files=t1, mode="U", encoding="utf-8") with warnings_helper.check_warnings(('', DeprecationWarning)): lines = list(fi) self.assertEqual(lines, ["A\n", "B\n", "C\n", "D"])
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_https_with_cadefault(self): handler = self.start_https_server(certfile=CERT_localhost) # Self-signed cert should fail verification with system certificate store with warnings_helper.check_warnings(('', DeprecationWarning)): with self.assertRaises(urllib.error.URLError) as cm: self.urlopen("https://localhost:%s/bizarre" % handler.port, cadefault=True)
def _test_format(self, format, value, out, **format_opts): with check_warnings(('', DeprecationWarning)): self._test_formatfunc(format, value, out, func=locale.format, **format_opts)
def test_minimal(self): # minimal test XXX need more tests from distutils.command.bdist_msi import bdist_msi project_dir, dist = self.create_dist() with check_warnings(("", DeprecationWarning)): cmd = bdist_msi(dist) cmd.ensure_finalized()
def test_check_metadata_deprecated(self): # makes sure make_metadata is deprecated dist, cmd = self.get_cmd() with check_warnings() as w: warnings.simplefilter("always") cmd.check_metadata() self.assertEqual(len(w.warnings), 1)
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_resource_warning(self): # Issue #11453 fd = os.open(os_helper.TESTFN, os.O_RDONLY) f = asyncore.file_wrapper(fd) os.close(fd) with warnings_helper.check_warnings(('', ResourceWarning)): f = None support.gc_collect()
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 warnings_helper.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
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_warning(self): # Test that the warning is only returned once. with warnings_helper.check_warnings((".*literal", SyntaxWarning)) as w: compile_command("0 is 0") self.assertEqual(len(w.warnings), 1) # bpo-41520: check SyntaxWarning treated as an SyntaxError with self.assertRaises(SyntaxError): warnings.simplefilter('error', SyntaxWarning) compile_command('1 is 1\n', symbol='exec')
def test_open_code(self): # Check that the default behaviour of open_code matches # open("rb") with self.FileIO(__file__, "rb") as f: expected = f.read() with check_warnings(quiet=True) as w: # Always test _open_code_with_warning with _pyio._open_code_with_warning(__file__) as f: actual = f.read() self.assertEqual(expected, actual) self.assertNotEqual(w.warnings, [])
def check_all(self, modname): names = {} with warnings_helper.check_warnings( (f".*{modname}", DeprecationWarning), (".* (module|package)", DeprecationWarning), (".* (module|package)", PendingDeprecationWarning), ("", 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): with warnings_helper.check_warnings(("", DeprecationWarning), ("", ResourceWarning), quiet=True): 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__'] if "__warningregistry__" in names: del names["__warningregistry__"] 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_warning(self): # Test that the warning is only returned once. with warnings_helper.check_warnings( (".*literal", SyntaxWarning), (".*invalid", DeprecationWarning), ) as w: compile_command(r"'\e' is 0") self.assertEqual(len(w.warnings), 2) # bpo-41520: check SyntaxWarning treated as an SyntaxError with warnings.catch_warnings(), self.assertRaises(SyntaxError): warnings.simplefilter('error', SyntaxWarning) compile_command('1 is 1', symbol='exec')
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')) # stowarnings_helper.check_warningsary file, not a text file with warnings_helper.check_warnings(('', BytesWarning), quiet=True): self.assertRaises(TypeError, self.client.storlines, 'stor foo', f)
def test_change_cwd__chdir_warning(self): """Check the warning message when os.chdir() fails.""" path = TESTFN + '_does_not_exist' with warnings_helper.check_warnings() as recorder: with os_helper.change_cwd(path=path, quiet=True): pass messages = [str(w.message) for w in recorder.warnings] self.assertEqual(len(messages), 1, messages) msg = messages[0] self.assertTrue( msg.startswith(f'tests may fail, unable to change ' f'the current working directory ' f'to {path!r}: '), msg)
def test_get_exe_bytes(self): # issue5731: command was broken on non-windows platforms # this test makes sure it works now for every platform # let's create a command pkg_pth, dist = self.create_dist() with check_warnings(("", DeprecationWarning)): cmd = bdist_wininst(dist) cmd.ensure_finalized() # let's run the code that finds the right wininst*.exe file # and make sure it finds it and returns its content # no matter what platform we have exe_file = cmd.get_exe_bytes() self.assertGreater(len(exe_file), 10)
def test_relpath_errors(self): # Check relpath() raises friendly TypeErrors. with warnings_helper.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 warnings_helper.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_untested_modules_can_be_imported(self): untested = ('encodings', 'formatter') with warnings_helper.check_warnings(quiet=True): for name in untested: try: import_helper.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') and not platform.win32_is_iot(): 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_change_cwd__non_existent_dir__quiet_true(self): """Test passing a non-existent directory with quiet=True.""" original_cwd = os.getcwd() with os_helper.temp_dir() as parent_dir: bad_dir = os.path.join(parent_dir, 'does_not_exist') with warnings_helper.check_warnings() as recorder: with os_helper.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_join_errors(self): # Check join() raises friendly TypeErrors. with warnings_helper.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_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 warnings_helper.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_defaults_UTF8(self): # Issue #18378: on (at least) macOS setting LC_CTYPE to "UTF-8" is # valid. Furthermore LC_CTYPE=UTF is used by the UTF-8 locale coercing # during interpreter startup (on macOS). import _locale import os self.assertEqual(locale._parse_localename('UTF-8'), (None, 'UTF-8')) if hasattr(_locale, '_getdefaultlocale'): orig_getlocale = _locale._getdefaultlocale del _locale._getdefaultlocale else: orig_getlocale = None orig_env = {} try: for key in ('LC_ALL', 'LC_CTYPE', 'LANG', 'LANGUAGE'): if key in os.environ: orig_env[key] = os.environ[key] del os.environ[key] os.environ['LC_CTYPE'] = 'UTF-8' with check_warnings(('', DeprecationWarning)): self.assertEqual(locale.getdefaultlocale(), (None, 'UTF-8')) finally: for k in orig_env: os.environ[k] = orig_env[k] if 'LC_CTYPE' not in orig_env: del os.environ['LC_CTYPE'] if orig_getlocale is not None: _locale._getdefaultlocale = orig_getlocale
def setUp(self): self._warnings_manager = check_warnings() self._warnings_manager.__enter__() warnings.filterwarnings("error", module="<test string>")
def test_pbkdf2_hmac_py(self): with warnings_helper.check_warnings(): self._test_pbkdf2_hmac(builtin_hashlib.pbkdf2_hmac, builtin_hashes)
def assertOldResultWarning(self, test, failures): with warnings_helper.check_warnings( ("TestResult has no add.+ method,", RuntimeWarning)): result = OldResult() test.run(result) self.assertEqual(len(result.failures), failures)
"""Tests for distutils. The tests for distutils are defined in the distutils.tests package; the test_suite() function there returns a test suite that's ready to be run. """ import warnings from test import support from test.support import warnings_helper with warnings_helper.check_warnings( ("The distutils package is deprecated", DeprecationWarning), quiet=True): import distutils.tests def test_main(): # used by regrtest support.run_unittest(distutils.tests.test_suite()) support.reap_children() def load_tests(*_): # used by unittest return distutils.tests.test_suite() if __name__ == "__main__": test_main()