+++ /dev/null
-import imp\r
-import marshal\r
-import os\r
-import py_compile\r
-import random\r
-import stat\r
-import sys\r
-import unittest\r
-from test.test_support import (unlink, TESTFN, unload, run_unittest, rmtree,\r
- is_jython, check_warnings, EnvironmentVarGuard)\r
-import textwrap\r
-from test import script_helper\r
-\r
-def remove_files(name):\r
- for f in (name + os.extsep + "py",\r
- name + os.extsep + "pyc",\r
- name + os.extsep + "pyo",\r
- name + os.extsep + "pyw",\r
- name + "$py.class"):\r
- unlink(f)\r
-\r
-\r
-class ImportTests(unittest.TestCase):\r
-\r
- def tearDown(self):\r
- unload(TESTFN)\r
- setUp = tearDown\r
-\r
- def test_case_sensitivity(self):\r
- # Brief digression to test that import is case-sensitive: if we got\r
- # this far, we know for sure that "random" exists.\r
- try:\r
- import RAnDoM\r
- except ImportError:\r
- pass\r
- else:\r
- self.fail("import of RAnDoM should have failed (case mismatch)")\r
-\r
- def test_double_const(self):\r
- # Another brief digression to test the accuracy of manifest float\r
- # constants.\r
- from test import double_const # don't blink -- that *was* the test\r
-\r
- def test_import(self):\r
- def test_with_extension(ext):\r
- # The extension is normally ".py", perhaps ".pyw".\r
- source = TESTFN + ext\r
- pyo = TESTFN + os.extsep + "pyo"\r
- if is_jython:\r
- pyc = TESTFN + "$py.class"\r
- else:\r
- pyc = TESTFN + os.extsep + "pyc"\r
-\r
- with open(source, "w") as f:\r
- print >> f, ("# This tests Python's ability to import a", ext,\r
- "file.")\r
- a = random.randrange(1000)\r
- b = random.randrange(1000)\r
- print >> f, "a =", a\r
- print >> f, "b =", b\r
-\r
- try:\r
- mod = __import__(TESTFN)\r
- except ImportError, err:\r
- self.fail("import from %s failed: %s" % (ext, err))\r
- else:\r
- self.assertEqual(mod.a, a,\r
- "module loaded (%s) but contents invalid" % mod)\r
- self.assertEqual(mod.b, b,\r
- "module loaded (%s) but contents invalid" % mod)\r
- finally:\r
- unlink(source)\r
-\r
- try:\r
- imp.reload(mod)\r
- except ImportError, err:\r
- self.fail("import from .pyc/.pyo failed: %s" % err)\r
- finally:\r
- unlink(pyc)\r
- unlink(pyo)\r
- unload(TESTFN)\r
-\r
- sys.path.insert(0, os.curdir)\r
- try:\r
- test_with_extension(os.extsep + "py")\r
- if sys.platform.startswith("win"):\r
- for ext in [".PY", ".Py", ".pY", ".pyw", ".PYW", ".pYw"]:\r
- test_with_extension(ext)\r
- finally:\r
- del sys.path[0]\r
-\r
- @unittest.skipUnless(os.name == 'posix', "test meaningful only on posix systems")\r
- def test_execute_bit_not_copied(self):\r
- # Issue 6070: under posix .pyc files got their execute bit set if\r
- # the .py file had the execute bit set, but they aren't executable.\r
- oldmask = os.umask(022)\r
- sys.path.insert(0, os.curdir)\r
- try:\r
- fname = TESTFN + os.extsep + "py"\r
- f = open(fname, 'w').close()\r
- os.chmod(fname, (stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH |\r
- stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH))\r
- __import__(TESTFN)\r
- fn = fname + 'c'\r
- if not os.path.exists(fn):\r
- fn = fname + 'o'\r
- if not os.path.exists(fn):\r
- self.fail("__import__ did not result in creation of "\r
- "either a .pyc or .pyo file")\r
- s = os.stat(fn)\r
- self.assertEqual(stat.S_IMODE(s.st_mode),\r
- stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)\r
- finally:\r
- os.umask(oldmask)\r
- remove_files(TESTFN)\r
- unload(TESTFN)\r
- del sys.path[0]\r
-\r
- def test_imp_module(self):\r
- # Verify that the imp module can correctly load and find .py files\r
-\r
- # XXX (ncoghlan): It would be nice to use test_support.CleanImport\r
- # here, but that breaks because the os module registers some\r
- # handlers in copy_reg on import. Since CleanImport doesn't\r
- # revert that registration, the module is left in a broken\r
- # state after reversion. Reinitialising the module contents\r
- # and just reverting os.environ to its previous state is an OK\r
- # workaround\r
- orig_path = os.path\r
- orig_getenv = os.getenv\r
- with EnvironmentVarGuard():\r
- x = imp.find_module("os")\r
- new_os = imp.load_module("os", *x)\r
- self.assertIs(os, new_os)\r
- self.assertIs(orig_path, new_os.path)\r
- self.assertIsNot(orig_getenv, new_os.getenv)\r
-\r
- def test_module_with_large_stack(self, module='longlist'):\r
- # Regression test for http://bugs.python.org/issue561858.\r
- filename = module + os.extsep + 'py'\r
-\r
- # Create a file with a list of 65000 elements.\r
- with open(filename, 'w+') as f:\r
- f.write('d = [\n')\r
- for i in range(65000):\r
- f.write('"",\n')\r
- f.write(']')\r
-\r
- # Compile & remove .py file, we only need .pyc (or .pyo).\r
- with open(filename, 'r') as f:\r
- py_compile.compile(filename)\r
- unlink(filename)\r
-\r
- # Need to be able to load from current dir.\r
- sys.path.append('')\r
-\r
- # This used to crash.\r
- exec 'import ' + module\r
-\r
- # Cleanup.\r
- del sys.path[-1]\r
- unlink(filename + 'c')\r
- unlink(filename + 'o')\r
-\r
- def test_failing_import_sticks(self):\r
- source = TESTFN + os.extsep + "py"\r
- with open(source, "w") as f:\r
- print >> f, "a = 1 // 0"\r
-\r
- # New in 2.4, we shouldn't be able to import that no matter how often\r
- # we try.\r
- sys.path.insert(0, os.curdir)\r
- try:\r
- for i in [1, 2, 3]:\r
- self.assertRaises(ZeroDivisionError, __import__, TESTFN)\r
- self.assertNotIn(TESTFN, sys.modules,\r
- "damaged module in sys.modules on %i try" % i)\r
- finally:\r
- del sys.path[0]\r
- remove_files(TESTFN)\r
-\r
- def test_failing_reload(self):\r
- # A failing reload should leave the module object in sys.modules.\r
- source = TESTFN + os.extsep + "py"\r
- with open(source, "w") as f:\r
- print >> f, "a = 1"\r
- print >> f, "b = 2"\r
-\r
- sys.path.insert(0, os.curdir)\r
- try:\r
- mod = __import__(TESTFN)\r
- self.assertIn(TESTFN, sys.modules)\r
- self.assertEqual(mod.a, 1, "module has wrong attribute values")\r
- self.assertEqual(mod.b, 2, "module has wrong attribute values")\r
-\r
- # On WinXP, just replacing the .py file wasn't enough to\r
- # convince reload() to reparse it. Maybe the timestamp didn't\r
- # move enough. We force it to get reparsed by removing the\r
- # compiled file too.\r
- remove_files(TESTFN)\r
-\r
- # Now damage the module.\r
- with open(source, "w") as f:\r
- print >> f, "a = 10"\r
- print >> f, "b = 20//0"\r
-\r
- self.assertRaises(ZeroDivisionError, imp.reload, mod)\r
-\r
- # But we still expect the module to be in sys.modules.\r
- mod = sys.modules.get(TESTFN)\r
- self.assertIsNot(mod, None, "expected module to be in sys.modules")\r
-\r
- # We should have replaced a w/ 10, but the old b value should\r
- # stick.\r
- self.assertEqual(mod.a, 10, "module has wrong attribute values")\r
- self.assertEqual(mod.b, 2, "module has wrong attribute values")\r
-\r
- finally:\r
- del sys.path[0]\r
- remove_files(TESTFN)\r
- unload(TESTFN)\r
-\r
- def test_infinite_reload(self):\r
- # http://bugs.python.org/issue742342 reports that Python segfaults\r
- # (infinite recursion in C) when faced with self-recursive reload()ing.\r
-\r
- sys.path.insert(0, os.path.dirname(__file__))\r
- try:\r
- import infinite_reload\r
- finally:\r
- del sys.path[0]\r
-\r
- def test_import_name_binding(self):\r
- # import x.y.z binds x in the current namespace.\r
- import test as x\r
- import test.test_support\r
- self.assertIs(x, test, x.__name__)\r
- self.assertTrue(hasattr(test.test_support, "__file__"))\r
-\r
- # import x.y.z as w binds z as w.\r
- import test.test_support as y\r
- self.assertIs(y, test.test_support, y.__name__)\r
-\r
- def test_import_initless_directory_warning(self):\r
- with check_warnings(('', ImportWarning)):\r
- # Just a random non-package directory we always expect to be\r
- # somewhere in sys.path...\r
- self.assertRaises(ImportError, __import__, "site-packages")\r
-\r
- def test_import_by_filename(self):\r
- path = os.path.abspath(TESTFN)\r
- with self.assertRaises(ImportError) as c:\r
- __import__(path)\r
- self.assertEqual("Import by filename is not supported.",\r
- c.exception.args[0])\r
-\r
- def test_import_in_del_does_not_crash(self):\r
- # Issue 4236\r
- testfn = script_helper.make_script('', TESTFN, textwrap.dedent("""\\r
- import sys\r
- class C:\r
- def __del__(self):\r
- import imp\r
- sys.argv.insert(0, C())\r
- """))\r
- script_helper.assert_python_ok(testfn)\r
-\r
-\r
-class PycRewritingTests(unittest.TestCase):\r
- # Test that the `co_filename` attribute on code objects always points\r
- # to the right file, even when various things happen (e.g. both the .py\r
- # and the .pyc file are renamed).\r
-\r
- module_name = "unlikely_module_name"\r
- module_source = """\r
-import sys\r
-code_filename = sys._getframe().f_code.co_filename\r
-module_filename = __file__\r
-constant = 1\r
-def func():\r
- pass\r
-func_filename = func.func_code.co_filename\r
-"""\r
- dir_name = os.path.abspath(TESTFN)\r
- file_name = os.path.join(dir_name, module_name) + os.extsep + "py"\r
- compiled_name = file_name + ("c" if __debug__ else "o")\r
-\r
- def setUp(self):\r
- self.sys_path = sys.path[:]\r
- self.orig_module = sys.modules.pop(self.module_name, None)\r
- os.mkdir(self.dir_name)\r
- with open(self.file_name, "w") as f:\r
- f.write(self.module_source)\r
- sys.path.insert(0, self.dir_name)\r
-\r
- def tearDown(self):\r
- sys.path[:] = self.sys_path\r
- if self.orig_module is not None:\r
- sys.modules[self.module_name] = self.orig_module\r
- else:\r
- unload(self.module_name)\r
- unlink(self.file_name)\r
- unlink(self.compiled_name)\r
- rmtree(self.dir_name)\r
-\r
- def import_module(self):\r
- ns = globals()\r
- __import__(self.module_name, ns, ns)\r
- return sys.modules[self.module_name]\r
-\r
- def test_basics(self):\r
- mod = self.import_module()\r
- self.assertEqual(mod.module_filename, self.file_name)\r
- self.assertEqual(mod.code_filename, self.file_name)\r
- self.assertEqual(mod.func_filename, self.file_name)\r
- del sys.modules[self.module_name]\r
- mod = self.import_module()\r
- self.assertEqual(mod.module_filename, self.compiled_name)\r
- self.assertEqual(mod.code_filename, self.file_name)\r
- self.assertEqual(mod.func_filename, self.file_name)\r
-\r
- def test_incorrect_code_name(self):\r
- py_compile.compile(self.file_name, dfile="another_module.py")\r
- mod = self.import_module()\r
- self.assertEqual(mod.module_filename, self.compiled_name)\r
- self.assertEqual(mod.code_filename, self.file_name)\r
- self.assertEqual(mod.func_filename, self.file_name)\r
-\r
- def test_module_without_source(self):\r
- target = "another_module.py"\r
- py_compile.compile(self.file_name, dfile=target)\r
- os.remove(self.file_name)\r
- mod = self.import_module()\r
- self.assertEqual(mod.module_filename, self.compiled_name)\r
- self.assertEqual(mod.code_filename, target)\r
- self.assertEqual(mod.func_filename, target)\r
-\r
- def test_foreign_code(self):\r
- py_compile.compile(self.file_name)\r
- with open(self.compiled_name, "rb") as f:\r
- header = f.read(8)\r
- code = marshal.load(f)\r
- constants = list(code.co_consts)\r
- foreign_code = test_main.func_code\r
- pos = constants.index(1)\r
- constants[pos] = foreign_code\r
- code = type(code)(code.co_argcount, code.co_nlocals, code.co_stacksize,\r
- code.co_flags, code.co_code, tuple(constants),\r
- code.co_names, code.co_varnames, code.co_filename,\r
- code.co_name, code.co_firstlineno, code.co_lnotab,\r
- code.co_freevars, code.co_cellvars)\r
- with open(self.compiled_name, "wb") as f:\r
- f.write(header)\r
- marshal.dump(code, f)\r
- mod = self.import_module()\r
- self.assertEqual(mod.constant.co_filename, foreign_code.co_filename)\r
-\r
-\r
-class PathsTests(unittest.TestCase):\r
- path = TESTFN\r
-\r
- def setUp(self):\r
- os.mkdir(self.path)\r
- self.syspath = sys.path[:]\r
-\r
- def tearDown(self):\r
- rmtree(self.path)\r
- sys.path[:] = self.syspath\r
-\r
- # Regression test for http://bugs.python.org/issue1293.\r
- def test_trailing_slash(self):\r
- with open(os.path.join(self.path, 'test_trailing_slash.py'), 'w') as f:\r
- f.write("testdata = 'test_trailing_slash'")\r
- sys.path.append(self.path+'/')\r
- mod = __import__("test_trailing_slash")\r
- self.assertEqual(mod.testdata, 'test_trailing_slash')\r
- unload("test_trailing_slash")\r
-\r
- # Regression test for http://bugs.python.org/issue3677.\r
- def _test_UNC_path(self):\r
- with open(os.path.join(self.path, 'test_trailing_slash.py'), 'w') as f:\r
- f.write("testdata = 'test_trailing_slash'")\r
- # Create the UNC path, like \\myhost\c$\foo\bar.\r
- path = os.path.abspath(self.path)\r
- import socket\r
- hn = socket.gethostname()\r
- drive = path[0]\r
- unc = "\\\\%s\\%s$"%(hn, drive)\r
- unc += path[2:]\r
- sys.path.append(path)\r
- mod = __import__("test_trailing_slash")\r
- self.assertEqual(mod.testdata, 'test_trailing_slash')\r
- unload("test_trailing_slash")\r
-\r
- if sys.platform == "win32":\r
- test_UNC_path = _test_UNC_path\r
-\r
-\r
-class RelativeImportTests(unittest.TestCase):\r
-\r
- def tearDown(self):\r
- unload("test.relimport")\r
- setUp = tearDown\r
-\r
- def test_relimport_star(self):\r
- # This will import * from .test_import.\r
- from . import relimport\r
- self.assertTrue(hasattr(relimport, "RelativeImportTests"))\r
-\r
- def test_issue3221(self):\r
- # Regression test for http://bugs.python.org/issue3221.\r
- def check_absolute():\r
- exec "from os import path" in ns\r
- def check_relative():\r
- exec "from . import relimport" in ns\r
-\r
- # Check both OK with __package__ and __name__ correct\r
- ns = dict(__package__='test', __name__='test.notarealmodule')\r
- check_absolute()\r
- check_relative()\r
-\r
- # Check both OK with only __name__ wrong\r
- ns = dict(__package__='test', __name__='notarealpkg.notarealmodule')\r
- check_absolute()\r
- check_relative()\r
-\r
- # Check relative fails with only __package__ wrong\r
- ns = dict(__package__='foo', __name__='test.notarealmodule')\r
- with check_warnings(('.+foo', RuntimeWarning)):\r
- check_absolute()\r
- self.assertRaises(SystemError, check_relative)\r
-\r
- # Check relative fails with __package__ and __name__ wrong\r
- ns = dict(__package__='foo', __name__='notarealpkg.notarealmodule')\r
- with check_warnings(('.+foo', RuntimeWarning)):\r
- check_absolute()\r
- self.assertRaises(SystemError, check_relative)\r
-\r
- # Check both fail with package set to a non-string\r
- ns = dict(__package__=object())\r
- self.assertRaises(ValueError, check_absolute)\r
- self.assertRaises(ValueError, check_relative)\r
-\r
- def test_absolute_import_without_future(self):\r
- # If explicit relative import syntax is used, then do not try\r
- # to perform an absolute import in the face of failure.\r
- # Issue #7902.\r
- with self.assertRaises(ImportError):\r
- from .os import sep\r
- self.fail("explicit relative import triggered an "\r
- "implicit absolute import")\r
-\r
-\r
-def test_main(verbose=None):\r
- run_unittest(ImportTests, PycRewritingTests, PathsTests, RelativeImportTests)\r
-\r
-if __name__ == '__main__':\r
- # Test needs to be a package, so we can do relative imports.\r
- from test.test_import import test_main\r
- test_main()\r