symbian-qemu-0.9.1-12/python-2.6.1/Lib/test/test_import.py
changeset 1 2fb8b9db1c86
equal deleted inserted replaced
0:ffa851df0825 1:2fb8b9db1c86
       
     1 import unittest
       
     2 import os
       
     3 import random
       
     4 import shutil
       
     5 import sys
       
     6 import py_compile
       
     7 import warnings
       
     8 from test.test_support import unlink, TESTFN, unload, run_unittest, check_warnings
       
     9 
       
    10 
       
    11 def remove_files(name):
       
    12     for f in (name + os.extsep + "py",
       
    13               name + os.extsep + "pyc",
       
    14               name + os.extsep + "pyo",
       
    15               name + os.extsep + "pyw",
       
    16               name + "$py.class"):
       
    17         if os.path.exists(f):
       
    18             os.remove(f)
       
    19 
       
    20 
       
    21 class ImportTest(unittest.TestCase):
       
    22 
       
    23     def testCaseSensitivity(self):
       
    24         # Brief digression to test that import is case-sensitive:  if we got this
       
    25         # far, we know for sure that "random" exists.
       
    26         try:
       
    27             import RAnDoM
       
    28         except ImportError:
       
    29             pass
       
    30         else:
       
    31             self.fail("import of RAnDoM should have failed (case mismatch)")
       
    32 
       
    33     def testDoubleConst(self):
       
    34         # Another brief digression to test the accuracy of manifest float constants.
       
    35         from test import double_const  # don't blink -- that *was* the test
       
    36 
       
    37     def testImport(self):
       
    38         def test_with_extension(ext):
       
    39             # ext normally ".py"; perhaps ".pyw"
       
    40             source = TESTFN + ext
       
    41             pyo = TESTFN + os.extsep + "pyo"
       
    42             if sys.platform.startswith('java'):
       
    43                 pyc = TESTFN + "$py.class"
       
    44             else:
       
    45                 pyc = TESTFN + os.extsep + "pyc"
       
    46 
       
    47             f = open(source, "w")
       
    48             print >> f, "# This tests Python's ability to import a", ext, "file."
       
    49             a = random.randrange(1000)
       
    50             b = random.randrange(1000)
       
    51             print >> f, "a =", a
       
    52             print >> f, "b =", b
       
    53             f.close()
       
    54 
       
    55             try:
       
    56                 try:
       
    57                     mod = __import__(TESTFN)
       
    58                 except ImportError, err:
       
    59                     self.fail("import from %s failed: %s" % (ext, err))
       
    60 
       
    61                 self.assertEquals(mod.a, a,
       
    62                     "module loaded (%s) but contents invalid" % mod)
       
    63                 self.assertEquals(mod.b, b,
       
    64                     "module loaded (%s) but contents invalid" % mod)
       
    65             finally:
       
    66                 os.unlink(source)
       
    67 
       
    68             try:
       
    69                 try:
       
    70                     reload(mod)
       
    71                 except ImportError, err:
       
    72                     self.fail("import from .pyc/.pyo failed: %s" % err)
       
    73             finally:
       
    74                 try:
       
    75                     os.unlink(pyc)
       
    76                 except OSError:
       
    77                     pass
       
    78                 try:
       
    79                     os.unlink(pyo)
       
    80                 except OSError:
       
    81                     pass
       
    82                 del sys.modules[TESTFN]
       
    83 
       
    84         sys.path.insert(0, os.curdir)
       
    85         try:
       
    86             test_with_extension(os.extsep + "py")
       
    87             if sys.platform.startswith("win"):
       
    88                 for ext in ".PY", ".Py", ".pY", ".pyw", ".PYW", ".pYw":
       
    89                     test_with_extension(ext)
       
    90         finally:
       
    91             del sys.path[0]
       
    92 
       
    93     def testImpModule(self):
       
    94         # Verify that the imp module can correctly load and find .py files
       
    95         import imp
       
    96         x = imp.find_module("os")
       
    97         os = imp.load_module("os", *x)
       
    98 
       
    99     def test_module_with_large_stack(self, module='longlist'):
       
   100         # create module w/list of 65000 elements to test bug #561858
       
   101         filename = module + os.extsep + 'py'
       
   102 
       
   103         # create a file with a list of 65000 elements
       
   104         f = open(filename, 'w+')
       
   105         f.write('d = [\n')
       
   106         for i in range(65000):
       
   107             f.write('"",\n')
       
   108         f.write(']')
       
   109         f.close()
       
   110 
       
   111         # compile & remove .py file, we only need .pyc (or .pyo)
       
   112         f = open(filename, 'r')
       
   113         py_compile.compile(filename)
       
   114         f.close()
       
   115         os.unlink(filename)
       
   116 
       
   117         # need to be able to load from current dir
       
   118         sys.path.append('')
       
   119 
       
   120         # this used to crash
       
   121         exec 'import ' + module
       
   122 
       
   123         # cleanup
       
   124         del sys.path[-1]
       
   125         for ext in 'pyc', 'pyo':
       
   126             fname = module + os.extsep + ext
       
   127             if os.path.exists(fname):
       
   128                 os.unlink(fname)
       
   129 
       
   130     def test_failing_import_sticks(self):
       
   131         source = TESTFN + os.extsep + "py"
       
   132         f = open(source, "w")
       
   133         print >> f, "a = 1/0"
       
   134         f.close()
       
   135 
       
   136         # New in 2.4, we shouldn't be able to import that no matter how often
       
   137         # we try.
       
   138         sys.path.insert(0, os.curdir)
       
   139         try:
       
   140             for i in 1, 2, 3:
       
   141                 try:
       
   142                     mod = __import__(TESTFN)
       
   143                 except ZeroDivisionError:
       
   144                     if TESTFN in sys.modules:
       
   145                         self.fail("damaged module in sys.modules on %i. try" % i)
       
   146                 else:
       
   147                     self.fail("was able to import a damaged module on %i. try" % i)
       
   148         finally:
       
   149             sys.path.pop(0)
       
   150             remove_files(TESTFN)
       
   151 
       
   152     def test_failing_reload(self):
       
   153         # A failing reload should leave the module object in sys.modules.
       
   154         source = TESTFN + os.extsep + "py"
       
   155         f = open(source, "w")
       
   156         print >> f, "a = 1"
       
   157         print >> f, "b = 2"
       
   158         f.close()
       
   159 
       
   160         sys.path.insert(0, os.curdir)
       
   161         try:
       
   162             mod = __import__(TESTFN)
       
   163             self.assert_(TESTFN in sys.modules, "expected module in sys.modules")
       
   164             self.assertEquals(mod.a, 1, "module has wrong attribute values")
       
   165             self.assertEquals(mod.b, 2, "module has wrong attribute values")
       
   166 
       
   167             # On WinXP, just replacing the .py file wasn't enough to
       
   168             # convince reload() to reparse it.  Maybe the timestamp didn't
       
   169             # move enough.  We force it to get reparsed by removing the
       
   170             # compiled file too.
       
   171             remove_files(TESTFN)
       
   172 
       
   173             # Now damage the module.
       
   174             f = open(source, "w")
       
   175             print >> f, "a = 10"
       
   176             print >> f, "b = 20//0"
       
   177             f.close()
       
   178 
       
   179             self.assertRaises(ZeroDivisionError, reload, mod)
       
   180 
       
   181             # But we still expect the module to be in sys.modules.
       
   182             mod = sys.modules.get(TESTFN)
       
   183             self.failIf(mod is None, "expected module to still be in sys.modules")
       
   184 
       
   185             # We should have replaced a w/ 10, but the old b value should
       
   186             # stick.
       
   187             self.assertEquals(mod.a, 10, "module has wrong attribute values")
       
   188             self.assertEquals(mod.b, 2, "module has wrong attribute values")
       
   189 
       
   190         finally:
       
   191             sys.path.pop(0)
       
   192             remove_files(TESTFN)
       
   193             if TESTFN in sys.modules:
       
   194                 del sys.modules[TESTFN]
       
   195 
       
   196     def test_infinite_reload(self):
       
   197         # Bug #742342 reports that Python segfaults (infinite recursion in C)
       
   198         #  when faced with self-recursive reload()ing.
       
   199 
       
   200         sys.path.insert(0, os.path.dirname(__file__))
       
   201         try:
       
   202             import infinite_reload
       
   203         finally:
       
   204             sys.path.pop(0)
       
   205 
       
   206     def test_import_name_binding(self):
       
   207         # import x.y.z binds x in the current namespace
       
   208         import test as x
       
   209         import test.test_support
       
   210         self.assert_(x is test, x.__name__)
       
   211         self.assert_(hasattr(test.test_support, "__file__"))
       
   212 
       
   213         # import x.y.z as w binds z as w
       
   214         import test.test_support as y
       
   215         self.assert_(y is test.test_support, y.__name__)
       
   216 
       
   217     def test_import_initless_directory_warning(self):
       
   218         with warnings.catch_warnings():
       
   219             # Just a random non-package directory we always expect to be
       
   220             # somewhere in sys.path...
       
   221             warnings.simplefilter('error', ImportWarning)
       
   222             self.assertRaises(ImportWarning, __import__, "site-packages")
       
   223 
       
   224     def test_importbyfilename(self):
       
   225         path = os.path.abspath(TESTFN)
       
   226         try:
       
   227             __import__(path)
       
   228         except ImportError, err:
       
   229             self.assertEqual("Import by filename is not supported.",
       
   230                               err.args[0])
       
   231         else:
       
   232             self.fail("import by path didn't raise an exception")
       
   233 
       
   234 class PathsTests(unittest.TestCase):
       
   235     path = TESTFN
       
   236 
       
   237     def setUp(self):
       
   238         os.mkdir(self.path)
       
   239         self.syspath = sys.path[:]
       
   240 
       
   241     def tearDown(self):
       
   242         shutil.rmtree(self.path)
       
   243         sys.path = self.syspath
       
   244 
       
   245     # http://bugs.python.org/issue1293
       
   246     def test_trailing_slash(self):
       
   247         f = open(os.path.join(self.path, 'test_trailing_slash.py'), 'w')
       
   248         f.write("testdata = 'test_trailing_slash'")
       
   249         f.close()
       
   250         sys.path.append(self.path+'/')
       
   251         mod = __import__("test_trailing_slash")
       
   252         self.assertEqual(mod.testdata, 'test_trailing_slash')
       
   253         unload("test_trailing_slash")
       
   254 
       
   255 class RelativeImport(unittest.TestCase):
       
   256     def tearDown(self):
       
   257         try:
       
   258             del sys.modules["test.relimport"]
       
   259         except:
       
   260             pass
       
   261 
       
   262     def test_relimport_star(self):
       
   263         # This will import * from .test_import.
       
   264         from . import relimport
       
   265         self.assertTrue(hasattr(relimport, "RelativeImport"))
       
   266 
       
   267     def test_issue3221(self):
       
   268         def check_absolute():
       
   269             exec "from os import path" in ns
       
   270         def check_relative():
       
   271             exec "from . import relimport" in ns
       
   272         # Check both OK with __package__ and __name__ correct
       
   273         ns = dict(__package__='test', __name__='test.notarealmodule')
       
   274         check_absolute()
       
   275         check_relative()
       
   276         # Check both OK with only __name__ wrong
       
   277         ns = dict(__package__='test', __name__='notarealpkg.notarealmodule')
       
   278         check_absolute()
       
   279         check_relative()
       
   280         # Check relative fails with only __package__ wrong
       
   281         ns = dict(__package__='foo', __name__='test.notarealmodule')
       
   282         with check_warnings() as w:
       
   283             check_absolute()
       
   284             self.assert_('foo' in str(w.message))
       
   285             self.assertEqual(w.category, RuntimeWarning)
       
   286         self.assertRaises(SystemError, check_relative)
       
   287         # Check relative fails with __package__ and __name__ wrong
       
   288         ns = dict(__package__='foo', __name__='notarealpkg.notarealmodule')
       
   289         with check_warnings() as w:
       
   290             check_absolute()
       
   291             self.assert_('foo' in str(w.message))
       
   292             self.assertEqual(w.category, RuntimeWarning)
       
   293         self.assertRaises(SystemError, check_relative)
       
   294         # Check both fail with package set to a non-string
       
   295         ns = dict(__package__=object())
       
   296         self.assertRaises(ValueError, check_absolute)
       
   297         self.assertRaises(ValueError, check_relative)
       
   298 
       
   299 def test_main(verbose=None):
       
   300     run_unittest(ImportTest, PathsTests, RelativeImport)
       
   301 
       
   302 if __name__ == '__main__':
       
   303     # test needs to be a package, so we can do relative import
       
   304     from test.test_import import test_main
       
   305     test_main()