diff options
-rw-r--r-- | Lib/test/test_cgi.py | 27 | ||||
-rw-r--r-- | Lib/test/test_coding.py | 31 | ||||
-rw-r--r-- | Lib/test/test_import.py | 109 | ||||
-rw-r--r-- | Lib/test/test_io.py | 18 | ||||
-rw-r--r-- | Lib/test/test_shutil.py | 20 | ||||
-rw-r--r-- | Lib/test/test_structmembers.py | 21 |
6 files changed, 100 insertions, 126 deletions
diff --git a/Lib/test/test_cgi.py b/Lib/test/test_cgi.py index a77abf0..4fca2ed 100644 --- a/Lib/test/test_cgi.py +++ b/Lib/test/test_cgi.py @@ -1,11 +1,10 @@ -from test.support import run_unittest +from test.support import run_unittest, check_warnings import cgi import os import sys import tempfile import unittest from io import StringIO -from warnings import catch_warnings, filterwarnings class HackedSysModule: # The regression test will have real values in sys.argv, which @@ -15,10 +14,6 @@ class HackedSysModule: cgi.sys = HackedSysModule() -try: - from io import StringIO -except ImportError: - from io import StringIO class ComparableException: def __init__(self, err): @@ -117,7 +112,7 @@ def gen_result(data, environ): result = {} for k, v in dict(form).items(): - result[k] = type(v) is list and form.getlist(k) or v.value + result[k] = isinstance(v, list) and form.getlist(k) or v.value return result @@ -133,7 +128,7 @@ class CgiTests(unittest.TestCase): env = {'QUERY_STRING': orig} fs = cgi.FieldStorage(environ=env) - if type(expect) == type({}): + if isinstance(expect, dict): # test dict interface self.assertEqual(len(expect), len(fs)) self.assertEqual(norm(expect.keys()), norm(fs.keys())) @@ -308,20 +303,16 @@ this is the content of the fake file self.assertEqual(result, v) def test_deprecated_parse_qs(self): - # this func is moved to urlparse, this is just a sanity check - with catch_warnings(): - filterwarnings('ignore', - 'cgi.parse_qs is deprecated, use urllib.parse.parse_qs instead', - DeprecationWarning) + # 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_deprecated_parse_qsl(self): - # this func is moved to urlparse, this is just a sanity check - with catch_warnings(): - filterwarnings('ignore', - 'cgi.parse_qsl is deprecated, use urllib.parse.parse_qsl instead', - DeprecationWarning) + # 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')) diff --git a/Lib/test/test_coding.py b/Lib/test/test_coding.py index 9d368c5..f9db0b4 100644 --- a/Lib/test/test_coding.py +++ b/Lib/test/test_coding.py @@ -1,6 +1,6 @@ import test.support, unittest -from test.support import TESTFN, unlink +from test.support import TESTFN, unlink, unload import os, sys class CodingTest(unittest.TestCase): @@ -17,9 +17,8 @@ class CodingTest(unittest.TestCase): path = os.path.dirname(__file__) filename = os.path.join(path, module_name + '.py') - fp = open(filename, "rb") - bytes = fp.read() - fp.close() + with open(filename, "rb") as fp: + bytes = fp.read() self.assertRaises(SyntaxError, compile, bytes, filename, 'exec') def test_exec_valid_coding(self): @@ -30,9 +29,8 @@ class CodingTest(unittest.TestCase): def test_file_parse(self): # issue1134: all encodings outside latin-1 and utf-8 fail on # multiline strings and long lines (>512 columns) - if TESTFN in sys.modules: - del sys.modules[TESTFN] - sys.path.insert(0, ".") + unload(TESTFN) + sys.path.insert(0, os.curdir) filename = TESTFN + ".py" f = open(filename, "w") try: @@ -45,21 +43,20 @@ class CodingTest(unittest.TestCase): __import__(TESTFN) finally: f.close() - unlink(TESTFN+".py") - unlink(TESTFN+".pyc") - sys.path.pop(0) + unlink(filename) + unlink(filename + "c") + unload(TESTFN) + del sys.path[0] def test_error_from_string(self): # See http://bugs.python.org/issue6289 input = "# coding: ascii\n\N{SNOWMAN}".encode('utf-8') - try: + with self.assertRaises(SyntaxError) as c: compile(input, "<string>", "exec") - except SyntaxError as e: - expected = "'ascii' codec can't decode byte 0xe2 in position 16: " \ - "ordinal not in range(128)" - self.assertTrue(str(e).startswith(expected)) - else: - self.fail("didn't raise") + expected = "'ascii' codec can't decode byte 0xe2 in position 16: " \ + "ordinal not in range(128)" + self.assertTrue(c.exception.args[0].startswith(expected)) + def test_main(): test.support.run_unittest(CodingTest) diff --git a/Lib/test/test_import.py b/Lib/test/test_import.py index 9922407..9b34467 100644 --- a/Lib/test/test_import.py +++ b/Lib/test/test_import.py @@ -8,9 +8,8 @@ import shutil import stat import sys import unittest -import warnings -from test.support import (unlink, TESTFN, unload, run_unittest, - TestFailed, EnvironmentVarGuard, swap_attr, swap_item) +from test.support import (unlink, TESTFN, unload, run_unittest, is_jython, + check_warnings, EnvironmentVarGuard, swap_attr, swap_item) def remove_files(name): @@ -19,12 +18,15 @@ def remove_files(name): name + ".pyo", name + ".pyw", name + "$py.class"): - if os.path.exists(f): - os.remove(f) + unlink(f) class ImportTests(unittest.TestCase): + def tearDown(self): + unload(TESTFN) + setUp = tearDown + def test_case_sensitivity(self): # Brief digression to test that import is case-sensitive: if we got # this far, we know for sure that "random" exists. @@ -45,7 +47,7 @@ class ImportTests(unittest.TestCase): # The extension is normally ".py", perhaps ".pyw". source = TESTFN + ext pyo = TESTFN + ".pyo" - if sys.platform.startswith('java'): + if is_jython: pyc = TESTFN + "$py.class" else: pyc = TESTFN + ".pyc" @@ -66,15 +68,15 @@ class ImportTests(unittest.TestCase): except ImportError as err: self.fail("import from %s failed: %s" % (ext, err)) - self.assertEquals(mod.a, a, + self.assertEqual(mod.a, a, "module loaded (%s) but contents invalid" % mod) - self.assertEquals(mod.b, b, + self.assertEqual(mod.b, b, "module loaded (%s) but contents invalid" % mod) finally: unlink(source) unlink(pyc) unlink(pyo) - del sys.modules[TESTFN] + unload(TESTFN) sys.path.insert(0, os.curdir) try: @@ -100,21 +102,22 @@ class ImportTests(unittest.TestCase): fn = fname + 'c' if not os.path.exists(fn): fn = fname + 'o' - if not os.path.exists(fn): raise TestFailed("__import__ did " - "not result in creation of either a .pyc or .pyo file") + if not os.path.exists(fn): + self.fail("__import__ did not result in creation of " + "either a .pyc or .pyo file") s = os.stat(fn) - self.assertEquals(stat.S_IMODE(s.st_mode), - stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH) + self.assertEqual(stat.S_IMODE(s.st_mode), + stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH) finally: os.umask(oldmask) remove_files(TESTFN) - if TESTFN in sys.modules: del sys.modules[TESTFN] + unload(TESTFN) del sys.path[0] def test_imp_module(self): # Verify that the imp module can correctly load and find .py files import imp, os - # XXX (ncoghlan): It would be nice to use test_support.CleanImport + # XXX (ncoghlan): It would be nice to use support.CleanImport # here, but that breaks because the os module registers some # handlers in copy_reg on import. Since CleanImport doesn't # revert that registration, the module is left in a broken @@ -144,7 +147,7 @@ class ImportTests(unittest.TestCase): # Compile & remove .py file, we only need .pyc (or .pyo). with open(filename, 'r') as f: py_compile.compile(filename) - os.unlink(filename) + unlink(filename) # Need to be able to load from current dir. sys.path.append('') @@ -154,10 +157,8 @@ class ImportTests(unittest.TestCase): # Cleanup. del sys.path[-1] - for ext in '.pyc', '.pyo': - fname = module + ext - if os.path.exists(fname): - os.unlink(fname) + unlink(filename + 'c') + unlink(filename + 'o') def test_failing_import_sticks(self): source = TESTFN + ".py" @@ -171,15 +172,11 @@ class ImportTests(unittest.TestCase): del sys.modules[TESTFN] try: for i in [1, 2, 3]: - try: - mod = __import__(TESTFN) - except ZeroDivisionError: - if TESTFN in sys.modules: - self.fail("damaged module in sys.modules on %i. try" % i) - else: - self.fail("was able to import a damaged module on %i. try" % i) + self.assertRaises(ZeroDivisionError, __import__, TESTFN) + self.assertNotIn(TESTFN, sys.modules, + "damaged module in sys.modules on %i try" % i) finally: - sys.path.pop(0) + del sys.path[0] remove_files(TESTFN) def test_import_name_binding(self): @@ -210,8 +207,8 @@ class ImportTests(unittest.TestCase): try: mod = __import__(TESTFN) self.assertIn(TESTFN, sys.modules) - self.assertEquals(mod.a, 1, "module has wrong attribute values") - self.assertEquals(mod.b, 2, "module has wrong attribute values") + self.assertEqual(mod.a, 1, "module has wrong attribute values") + self.assertEqual(mod.b, 2, "module has wrong attribute values") # On WinXP, just replacing the .py file wasn't enough to # convince reload() to reparse it. Maybe the timestamp didn't @@ -226,18 +223,17 @@ class ImportTests(unittest.TestCase): self.assertRaises(ZeroDivisionError, imp.reload, mod) # But we still expect the module to be in sys.modules. mod = sys.modules.get(TESTFN) - self.assertFalse(mod is None, "expected module to be in sys.modules") + self.assertIsNot(mod, None, "expected module to be in sys.modules") # We should have replaced a w/ 10, but the old b value should # stick. - self.assertEquals(mod.a, 10, "module has wrong attribute values") - self.assertEquals(mod.b, 2, "module has wrong attribute values") + self.assertEqual(mod.a, 10, "module has wrong attribute values") + self.assertEqual(mod.b, 2, "module has wrong attribute values") finally: - sys.path.pop(0) + del sys.path[0] remove_files(TESTFN) - if TESTFN in sys.modules: - del sys.modules[TESTFN] + unload(TESTFN) def test_file_to_source(self): # check if __file__ points to the source file where available @@ -255,19 +251,34 @@ class ImportTests(unittest.TestCase): ext = mod.__file__[-4:] self.assertIn(ext, ('.pyc', '.pyo')) finally: - sys.path.pop(0) + del sys.path[0] remove_files(TESTFN) if TESTFN in sys.modules: del sys.modules[TESTFN] + def test_import_name_binding(self): + # import x.y.z binds x in the current namespace. + import test as x + import test.support + self.assertIs(x, test, x.__name__) + self.assertTrue(hasattr(test.support, "__file__")) + + # import x.y.z as w binds z as w. + import test.support as y + self.assertIs(y, test.support, y.__name__) + + 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_import_by_filename(self): path = os.path.abspath(TESTFN) - try: + with self.assertRaises(ImportError) as c: __import__(path) - except ImportError as err: - pass - else: - self.fail("import by path didn't raise an exception") + self.assertEqual("Import by filename is not supported.", + c.exception.args[0]) class PycRewritingTests(unittest.TestCase): @@ -302,10 +313,9 @@ func_filename = func.__code__.co_filename if self.orig_module is not None: sys.modules[self.module_name] = self.orig_module else: - del sys.modules[self.module_name] - for file_name in self.file_name, self.compiled_name: - if os.path.exists(file_name): - os.remove(file_name) + unload(self.module_name) + unlink(self.file_name) + unlink(self.compiled_name) if os.path.exists(self.dir_name): shutil.rmtree(self.dir_name) @@ -406,11 +416,10 @@ class PathsTests(unittest.TestCase): class RelativeImportTests(unittest.TestCase): + def tearDown(self): - try: - del sys.modules["test.relimport"] - except: - pass + unload("test.relimport") + setUp = tearDown def test_relimport_star(self): # This will import * from .test_import. diff --git a/Lib/test/test_io.py b/Lib/test/test_io.py index 1b2d491..bf0d03f 100644 --- a/Lib/test/test_io.py +++ b/Lib/test/test_io.py @@ -1046,14 +1046,9 @@ class BufferedWriterTest(unittest.TestCase, CommonBufferedTests): self.assertRaises(IOError, bufio.write, b"abcdef") def test_max_buffer_size_deprecation(self): - with support.check_warnings() as w: - warnings.simplefilter("always", DeprecationWarning) + with support.check_warnings(("max_buffer_size is deprecated", + DeprecationWarning)): self.tp(self.MockRawIO(), 8, 12) - self.assertEqual(len(w.warnings), 1) - warning = w.warnings[0] - self.assertTrue(warning.category is DeprecationWarning) - self.assertEqual(str(warning.message), - "max_buffer_size is deprecated") class CBufferedWriterTest(BufferedWriterTest): @@ -1109,14 +1104,9 @@ class BufferedRWPairTest(unittest.TestCase): self.assertRaises(self.UnsupportedOperation, pair.detach) def test_constructor_max_buffer_size_deprecation(self): - with support.check_warnings() as w: - warnings.simplefilter("always", DeprecationWarning) + with support.check_warnings(("max_buffer_size is deprecated", + DeprecationWarning)): self.tp(self.MockRawIO(), self.MockRawIO(), 8, 12) - self.assertEqual(len(w.warnings), 1) - warning = w.warnings[0] - self.assertTrue(warning.category is DeprecationWarning) - self.assertEqual(str(warning.message), - "max_buffer_size is deprecated") def test_constructor_with_not_readable(self): class NotReadable(MockRawIO): diff --git a/Lib/test/test_shutil.py b/Lib/test/test_shutil.py index f2e5d9b..3faa95e 100644 --- a/Lib/test/test_shutil.py +++ b/Lib/test/test_shutil.py @@ -464,30 +464,26 @@ class TestShutil(unittest.TestCase): old_dir = os.getcwd() os.chdir(tmpdir) try: - with captured_stdout() as s: - with check_warnings() as w: - warnings.simplefilter("always") - _make_tarball(base_name, 'dist', compress='compress') + with captured_stdout() as s, check_warnings(quiet=False) as w: + _make_tarball(base_name, 'dist', compress='compress') finally: os.chdir(old_dir) tarball = base_name + '.tar.Z' self.assertTrue(os.path.exists(tarball)) - self.assertEquals(len(w.warnings), 1) + self.assertEqual(len(w.warnings), 1) # same test with dry_run os.remove(tarball) old_dir = os.getcwd() os.chdir(tmpdir) try: - with captured_stdout() as s: - with check_warnings() as w: - warnings.simplefilter("always") - _make_tarball(base_name, 'dist', compress='compress', - dry_run=True) + with captured_stdout() as s, check_warnings(quiet=False) as w: + _make_tarball(base_name, 'dist', compress='compress', + dry_run=True) finally: os.chdir(old_dir) - self.assertTrue(not os.path.exists(tarball)) - self.assertEquals(len(w.warnings), 1) + self.assertFalse(os.path.exists(tarball)) + self.assertEqual(len(w.warnings), 1) @unittest.skipUnless(zlib, "Requires zlib") @unittest.skipUnless(ZIP_SUPPORT, 'Need zip support to run') diff --git a/Lib/test/test_structmembers.py b/Lib/test/test_structmembers.py index 013c50a..e1a0e6b 100644 --- a/Lib/test/test_structmembers.py +++ b/Lib/test/test_structmembers.py @@ -103,39 +103,30 @@ class ReadWriteTests(unittest.TestCase): class TestWarnings(unittest.TestCase): - def has_warned(self, w): - self.assertEqual(w.category, RuntimeWarning) def test_byte_max(self): - with support.check_warnings() as w: + with support.check_warnings(('', RuntimeWarning)): ts.T_BYTE = CHAR_MAX+1 - self.has_warned(w) def test_byte_min(self): - with support.check_warnings() as w: + with support.check_warnings(('', RuntimeWarning)): ts.T_BYTE = CHAR_MIN-1 - self.has_warned(w) def test_ubyte_max(self): - with support.check_warnings() as w: + with support.check_warnings(('', RuntimeWarning)): ts.T_UBYTE = UCHAR_MAX+1 - self.has_warned(w) def test_short_max(self): - with support.check_warnings() as w: + with support.check_warnings(('', RuntimeWarning)): ts.T_SHORT = SHRT_MAX+1 - self.has_warned(w) def test_short_min(self): - with support.check_warnings() as w: + with support.check_warnings(('', RuntimeWarning)): ts.T_SHORT = SHRT_MIN-1 - self.has_warned(w) def test_ushort_max(self): - with support.check_warnings() as w: + with support.check_warnings(('', RuntimeWarning)): ts.T_USHORT = USHRT_MAX+1 - self.has_warned(w) - def test_main(verbose=None): |