Ignore:
Timestamp:
Mar 19, 2014, 11:31:01 PM (11 years ago)
Author:
dmik
Message:

python: Merge vendor 2.7.6 to trunk.

Location:
python/trunk
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • python/trunk

  • python/trunk/Lib/test/test_site.py

    r2 r391  
    66"""
    77import unittest
    8 from test.test_support import TestSkipped, run_unittest, TESTFN, EnvironmentVarGuard
     8from test.test_support import run_unittest, TESTFN, EnvironmentVarGuard
     9from test.test_support import captured_output
    910import __builtin__
    1011import os
    1112import sys
     13import re
    1214import encodings
    1315import subprocess
     16import sysconfig
     17from copy import copy
     18
    1419# Need to make sure to not import 'site' if someone specified ``-S`` at the
    1520# command-line.  Detect this by just making sure 'site' has not been imported
     
    1823    import site
    1924else:
    20     raise TestSkipped("importation of site.py suppressed")
    21 
    22 if not os.path.isdir(site.USER_SITE):
     25    raise unittest.SkipTest("importation of site.py suppressed")
     26
     27if site.ENABLE_USER_SITE and not os.path.isdir(site.USER_SITE):
    2328    # need to add user site directory for tests
    2429    os.makedirs(site.USER_SITE)
     
    3641        """Save a copy of sys.path"""
    3742        self.sys_path = sys.path[:]
     43        self.old_base = site.USER_BASE
     44        self.old_site = site.USER_SITE
     45        self.old_prefixes = site.PREFIXES
     46        self.old_vars = copy(sysconfig._CONFIG_VARS)
    3847
    3948    def tearDown(self):
    4049        """Restore sys.path"""
    41         sys.path = self.sys_path
     50        sys.path[:] = self.sys_path
     51        site.USER_BASE = self.old_base
     52        site.USER_SITE = self.old_site
     53        site.PREFIXES = self.old_prefixes
     54        sysconfig._CONFIG_VARS = self.old_vars
    4255
    4356    def test_makepath(self):
     
    4861        original_dir = os.path.join(*path_parts)
    4962        abs_dir, norm_dir = site.makepath(*path_parts)
    50         self.failUnlessEqual(os.path.abspath(original_dir), abs_dir)
     63        self.assertEqual(os.path.abspath(original_dir), abs_dir)
    5164        if original_dir == os.path.normcase(original_dir):
    52             self.failUnlessEqual(abs_dir, norm_dir)
     65            self.assertEqual(abs_dir, norm_dir)
    5366        else:
    54             self.failUnlessEqual(os.path.normcase(abs_dir), norm_dir)
     67            self.assertEqual(os.path.normcase(abs_dir), norm_dir)
    5568
    5669    def test_init_pathinfo(self):
     
    5871        for entry in [site.makepath(path)[1] for path in sys.path
    5972                        if path and os.path.isdir(path)]:
    60             self.failUnless(entry in dir_set,
    61                             "%s from sys.path not found in set returned "
    62                             "by _init_pathinfo(): %s" % (entry, dir_set))
     73            self.assertIn(entry, dir_set,
     74                          "%s from sys.path not found in set returned "
     75                          "by _init_pathinfo(): %s" % (entry, dir_set))
    6376
    6477    def pth_file_tests(self, pth_file):
    6578        """Contain common code for testing results of reading a .pth file"""
    66         self.failUnless(pth_file.imported in sys.modules,
    67                 "%s not in sys.path" % pth_file.imported)
    68         self.failUnless(site.makepath(pth_file.good_dir_path)[0] in sys.path)
    69         self.failUnless(not os.path.exists(pth_file.bad_dir_path))
     79        self.assertIn(pth_file.imported, sys.modules,
     80                      "%s not in sys.modules" % pth_file.imported)
     81        self.assertIn(site.makepath(pth_file.good_dir_path)[0], sys.path)
     82        self.assertFalse(os.path.exists(pth_file.bad_dir_path))
    7083
    7184    def test_addpackage(self):
     
    8497            pth_file.cleanup()
    8598
     99    def make_pth(self, contents, pth_dir='.', pth_name=TESTFN):
     100        # Create a .pth file and return its (abspath, basename).
     101        pth_dir = os.path.abspath(pth_dir)
     102        pth_basename = pth_name + '.pth'
     103        pth_fn = os.path.join(pth_dir, pth_basename)
     104        pth_file = open(pth_fn, 'w')
     105        self.addCleanup(lambda: os.remove(pth_fn))
     106        pth_file.write(contents)
     107        pth_file.close()
     108        return pth_dir, pth_basename
     109
     110    def test_addpackage_import_bad_syntax(self):
     111        # Issue 10642
     112        pth_dir, pth_fn = self.make_pth("import bad)syntax\n")
     113        with captured_output("stderr") as err_out:
     114            site.addpackage(pth_dir, pth_fn, set())
     115        self.assertRegexpMatches(err_out.getvalue(), "line 1")
     116        self.assertRegexpMatches(err_out.getvalue(),
     117            re.escape(os.path.join(pth_dir, pth_fn)))
     118        # XXX: the previous two should be independent checks so that the
     119        # order doesn't matter.  The next three could be a single check
     120        # but my regex foo isn't good enough to write it.
     121        self.assertRegexpMatches(err_out.getvalue(), 'Traceback')
     122        self.assertRegexpMatches(err_out.getvalue(), r'import bad\)syntax')
     123        self.assertRegexpMatches(err_out.getvalue(), 'SyntaxError')
     124
     125    def test_addpackage_import_bad_exec(self):
     126        # Issue 10642
     127        pth_dir, pth_fn = self.make_pth("randompath\nimport nosuchmodule\n")
     128        with captured_output("stderr") as err_out:
     129            site.addpackage(pth_dir, pth_fn, set())
     130        self.assertRegexpMatches(err_out.getvalue(), "line 2")
     131        self.assertRegexpMatches(err_out.getvalue(),
     132            re.escape(os.path.join(pth_dir, pth_fn)))
     133        # XXX: ditto previous XXX comment.
     134        self.assertRegexpMatches(err_out.getvalue(), 'Traceback')
     135        self.assertRegexpMatches(err_out.getvalue(), 'ImportError')
     136
     137    @unittest.skipIf(sys.platform == "win32", "Windows does not raise an "
     138                      "error for file paths containing null characters")
     139    def test_addpackage_import_bad_pth_file(self):
     140        # Issue 5258
     141        pth_dir, pth_fn = self.make_pth("abc\x00def\n")
     142        with captured_output("stderr") as err_out:
     143            site.addpackage(pth_dir, pth_fn, set())
     144        self.assertRegexpMatches(err_out.getvalue(), "line 1")
     145        self.assertRegexpMatches(err_out.getvalue(),
     146            re.escape(os.path.join(pth_dir, pth_fn)))
     147        # XXX: ditto previous XXX comment.
     148        self.assertRegexpMatches(err_out.getvalue(), 'Traceback')
     149        self.assertRegexpMatches(err_out.getvalue(), 'TypeError')
     150
    86151    def test_addsitedir(self):
    87152        # Same tests for test_addpackage since addsitedir() essentially just
     
    97162            pth_file.cleanup()
    98163
     164    @unittest.skipUnless(site.ENABLE_USER_SITE, "requires access to PEP 370 "
     165                          "user-site (site.ENABLE_USER_SITE)")
    99166    def test_s_option(self):
    100167        usersite = site.USER_SITE
    101         self.assert_(usersite in sys.path)
    102 
     168        self.assertIn(usersite, sys.path)
     169
     170        env = os.environ.copy()
    103171        rc = subprocess.call([sys.executable, '-c',
    104             'import sys; sys.exit(%r in sys.path)' % usersite])
    105         self.assertEqual(rc, 1)
    106 
     172            'import sys; sys.exit(%r in sys.path)' % usersite],
     173            env=env)
     174        self.assertEqual(rc, 1, "%r is not in sys.path (sys.exit returned %r)"
     175                % (usersite, rc))
     176
     177        env = os.environ.copy()
    107178        rc = subprocess.call([sys.executable, '-s', '-c',
    108             'import sys; sys.exit(%r in sys.path)' % usersite])
     179            'import sys; sys.exit(%r in sys.path)' % usersite],
     180            env=env)
    109181        self.assertEqual(rc, 0)
    110182
     
    123195        self.assertEqual(rc, 1)
    124196
     197    def test_getuserbase(self):
     198        site.USER_BASE = None
     199        user_base = site.getuserbase()
     200
     201        # the call sets site.USER_BASE
     202        self.assertEqual(site.USER_BASE, user_base)
     203
     204        # let's set PYTHONUSERBASE and see if it uses it
     205        site.USER_BASE = None
     206        import sysconfig
     207        sysconfig._CONFIG_VARS = None
     208
     209        with EnvironmentVarGuard() as environ:
     210            environ['PYTHONUSERBASE'] = 'xoxo'
     211            self.assertTrue(site.getuserbase().startswith('xoxo'),
     212                            site.getuserbase())
     213
     214    def test_getusersitepackages(self):
     215        site.USER_SITE = None
     216        site.USER_BASE = None
     217        user_site = site.getusersitepackages()
     218
     219        # the call sets USER_BASE *and* USER_SITE
     220        self.assertEqual(site.USER_SITE, user_site)
     221        self.assertTrue(user_site.startswith(site.USER_BASE), user_site)
     222
     223    def test_getsitepackages(self):
     224        site.PREFIXES = ['xoxo']
     225        dirs = site.getsitepackages()
     226
     227        if sys.platform in ('os2emx', 'riscos'):
     228            self.assertEqual(len(dirs), 1)
     229            wanted = os.path.join('xoxo', 'Lib', 'site-packages')
     230            self.assertEqual(dirs[0], wanted)
     231        elif (sys.platform == "darwin" and
     232            sysconfig.get_config_var("PYTHONFRAMEWORK")):
     233            # OS X framework builds
     234            site.PREFIXES = ['Python.framework']
     235            dirs = site.getsitepackages()
     236            self.assertEqual(len(dirs), 3)
     237            wanted = os.path.join('/Library',
     238                                  sysconfig.get_config_var("PYTHONFRAMEWORK"),
     239                                  sys.version[:3],
     240                                  'site-packages')
     241            self.assertEqual(dirs[2], wanted)
     242        elif os.sep == '/':
     243            # OS X non-framwework builds, Linux, FreeBSD, etc
     244            self.assertEqual(len(dirs), 2)
     245            wanted = os.path.join('xoxo', 'lib', 'python' + sys.version[:3],
     246                                  'site-packages')
     247            self.assertEqual(dirs[0], wanted)
     248            wanted = os.path.join('xoxo', 'lib', 'site-python')
     249            self.assertEqual(dirs[1], wanted)
     250        else:
     251            # other platforms
     252            self.assertEqual(len(dirs), 2)
     253            self.assertEqual(dirs[0], 'xoxo')
     254            wanted = os.path.join('xoxo', 'lib', 'site-packages')
     255            self.assertEqual(dirs[1], wanted)
    125256
    126257class PthFile(object):
     
    188319    def tearDown(self):
    189320        """Restore sys.path"""
    190         sys.path = self.sys_path
     321        sys.path[:] = self.sys_path
    191322
    192323    def test_abs__file__(self):
     
    197328        for module in (sys, os, __builtin__):
    198329            try:
    199                 self.failUnless(os.path.isabs(module.__file__), `module`)
     330                self.assertTrue(os.path.isabs(module.__file__), repr(module))
    200331            except AttributeError:
    201332                continue
     
    210341        seen_paths = set()
    211342        for path in sys.path:
    212             self.failUnless(path not in seen_paths)
     343            self.assertNotIn(path, seen_paths)
    213344            seen_paths.add(path)
    214345
     
    221352    def test_setting_quit(self):
    222353        # 'quit' and 'exit' should be injected into __builtin__
    223         self.failUnless(hasattr(__builtin__, "quit"))
    224         self.failUnless(hasattr(__builtin__, "exit"))
     354        self.assertTrue(hasattr(__builtin__, "quit"))
     355        self.assertTrue(hasattr(__builtin__, "exit"))
    225356
    226357    def test_setting_copyright(self):
    227358        # 'copyright' and 'credits' should be in __builtin__
    228         self.failUnless(hasattr(__builtin__, "copyright"))
    229         self.failUnless(hasattr(__builtin__, "credits"))
     359        self.assertTrue(hasattr(__builtin__, "copyright"))
     360        self.assertTrue(hasattr(__builtin__, "credits"))
    230361
    231362    def test_setting_help(self):
    232363        # 'help' should be set in __builtin__
    233         self.failUnless(hasattr(__builtin__, "help"))
     364        self.assertTrue(hasattr(__builtin__, "help"))
    234365
    235366    def test_aliasing_mbcs(self):
     
    245376    def test_setdefaultencoding_removed(self):
    246377        # Make sure sys.setdefaultencoding is gone
    247         self.failUnless(not hasattr(sys, "setdefaultencoding"))
     378        self.assertTrue(not hasattr(sys, "setdefaultencoding"))
    248379
    249380    def test_sitecustomize_executed(self):
    250381        # If sitecustomize is available, it should have been imported.
    251         if not sys.modules.has_key("sitecustomize"):
     382        if "sitecustomize" not in sys.modules:
    252383            try:
    253384                import sitecustomize
Note: See TracChangeset for help on using the changeset viewer.