PyXR

c:\python24\lib \ test \ test_site.py



0001 """Tests for 'site'.
0002 
0003 Tests assume the initial paths in sys.path once the interpreter has begun
0004 executing have not been removed.
0005 
0006 """
0007 import unittest
0008 from test.test_support import TestSkipped, TestFailed, run_unittest, TESTFN
0009 import __builtin__
0010 import os
0011 import sys
0012 import encodings
0013 import tempfile
0014 # Need to make sure to not import 'site' if someone specified ``-S`` at the
0015 # command-line.  Detect this by just making sure 'site' has not been imported
0016 # already.
0017 if "site" in sys.modules:
0018     import site
0019 else:
0020     raise TestSkipped("importation of site.py suppressed")
0021 
0022 class HelperFunctionsTests(unittest.TestCase):
0023     """Tests for helper functions.
0024 
0025     The setting of the encoding (set using sys.setdefaultencoding) used by
0026     the Unicode implementation is not tested.
0027 
0028     """
0029 
0030     def setUp(self):
0031         """Save a copy of sys.path"""
0032         self.sys_path = sys.path[:]
0033 
0034     def tearDown(self):
0035         """Restore sys.path"""
0036         sys.path = self.sys_path
0037 
0038     def test_makepath(self):
0039         # Test makepath() have an absolute path for its first return value
0040         # and a case-normalized version of the absolute path for its
0041         # second value.
0042         path_parts = ("Beginning", "End")
0043         original_dir = os.path.join(*path_parts)
0044         abs_dir, norm_dir = site.makepath(*path_parts)
0045         self.failUnlessEqual(os.path.abspath(original_dir), abs_dir)
0046         if original_dir == os.path.normcase(original_dir):
0047             self.failUnlessEqual(abs_dir, norm_dir)
0048         else:
0049             self.failUnlessEqual(os.path.normcase(abs_dir), norm_dir)
0050 
0051     def test_init_pathinfo(self):
0052         dir_set = site._init_pathinfo()
0053         for entry in [site.makepath(path)[1] for path in sys.path
0054                         if path and os.path.isdir(path)]:
0055             self.failUnless(entry in dir_set,
0056                             "%s from sys.path not found in set returned "
0057                             "by _init_pathinfo(): %s" % (entry, dir_set))
0058 
0059     def pth_file_tests(self, pth_file):
0060         """Contain common code for testing results of reading a .pth file"""
0061         self.failUnless(pth_file.imported in sys.modules,
0062                 "%s not in sys.path" % pth_file.imported)
0063         self.failUnless(site.makepath(pth_file.good_dir_path)[0] in sys.path)
0064         self.failUnless(not os.path.exists(pth_file.bad_dir_path))
0065 
0066     def test_addpackage(self):
0067         # Make sure addpackage() imports if the line starts with 'import',
0068         # adds directories to sys.path for any line in the file that is not a
0069         # comment or import that is a valid directory name for where the .pth
0070         # file resides; invalid directories are not added
0071         pth_file = PthFile()
0072         pth_file.cleanup(prep=True)  # to make sure that nothing is
0073                                       # pre-existing that shouldn't be
0074         try:
0075             pth_file.create()
0076             site.addpackage(pth_file.base_dir, pth_file.filename, set())
0077             self.pth_file_tests(pth_file)
0078         finally:
0079             pth_file.cleanup()
0080 
0081     def test_addsitedir(self):
0082         # Same tests for test_addpackage since addsitedir() essentially just
0083         # calls addpackage() for every .pth file in the directory
0084         pth_file = PthFile()
0085         pth_file.cleanup(prep=True) # Make sure that nothing is pre-existing
0086                                     # that is tested for
0087         try:
0088             pth_file.create()
0089             site.addsitedir(pth_file.base_dir, set())
0090             self.pth_file_tests(pth_file)
0091         finally:
0092             pth_file.cleanup()
0093 
0094 class PthFile(object):
0095     """Helper class for handling testing of .pth files"""
0096 
0097     def __init__(self, filename_base=TESTFN, imported="time",
0098                     good_dirname="__testdir__", bad_dirname="__bad"):
0099         """Initialize instance variables"""
0100         self.filename = filename_base + ".pth"
0101         self.base_dir = os.path.abspath('')
0102         self.file_path = os.path.join(self.base_dir, self.filename)
0103         self.imported = imported
0104         self.good_dirname = good_dirname
0105         self.bad_dirname = bad_dirname
0106         self.good_dir_path = os.path.join(self.base_dir, self.good_dirname)
0107         self.bad_dir_path = os.path.join(self.base_dir, self.bad_dirname)
0108 
0109     def create(self):
0110         """Create a .pth file with a comment, blank lines, an ``import
0111         <self.imported>``, a line with self.good_dirname, and a line with
0112         self.bad_dirname.
0113 
0114         Creation of the directory for self.good_dir_path (based off of
0115         self.good_dirname) is also performed.
0116 
0117         Make sure to call self.cleanup() to undo anything done by this method.
0118 
0119         """
0120         FILE = open(self.file_path, 'wU')
0121         try:
0122             print>>FILE, "#import @bad module name"
0123             print>>FILE, "\n"
0124             print>>FILE, "import %s" % self.imported
0125             print>>FILE, self.good_dirname
0126             print>>FILE, self.bad_dirname
0127         finally:
0128             FILE.close()
0129         os.mkdir(self.good_dir_path)
0130 
0131     def cleanup(self, prep=False):
0132         """Make sure that the .pth file is deleted, self.imported is not in
0133         sys.modules, and that both self.good_dirname and self.bad_dirname are
0134         not existing directories."""
0135         if os.path.exists(self.file_path):
0136             os.remove(self.file_path)
0137         if prep:
0138             self.imported_module = sys.modules.get(self.imported)
0139             if self.imported_module:
0140                 del sys.modules[self.imported]
0141         else:
0142             if self.imported_module:
0143                 sys.modules[self.imported] = self.imported_module
0144         if os.path.exists(self.good_dir_path):
0145             os.rmdir(self.good_dir_path)
0146         if os.path.exists(self.bad_dir_path):
0147             os.rmdir(self.bad_dir_path)
0148 
0149 class ImportSideEffectTests(unittest.TestCase):
0150     """Test side-effects from importing 'site'."""
0151 
0152     def setUp(self):
0153         """Make a copy of sys.path"""
0154         self.sys_path = sys.path[:]
0155 
0156     def tearDown(self):
0157         """Restore sys.path"""
0158         sys.path = self.sys_path
0159 
0160     def test_abs__file__(self):
0161         # Make sure all imported modules have their __file__ attribute
0162         # as an absolute path.
0163         # Handled by abs__file__()
0164         site.abs__file__()
0165         for module in (sys, os, __builtin__):
0166             try:
0167                 self.failUnless(os.path.isabs(module.__file__), `module`)
0168             except AttributeError:
0169                 continue
0170         # We could try everything in sys.modules; however, when regrtest.py
0171         # runs something like test_frozen before test_site, then we will
0172         # be testing things loaded *after* test_site did path normalization
0173 
0174     def test_no_duplicate_paths(self):
0175         # No duplicate paths should exist in sys.path
0176         # Handled by removeduppaths()
0177         site.removeduppaths()
0178         seen_paths = set()
0179         for path in sys.path:
0180             self.failUnless(path not in seen_paths)
0181             seen_paths.add(path)
0182 
0183     def test_add_build_dir(self):
0184         # Test that the build directory's Modules directory is used when it
0185         # should be.
0186         # XXX: implement
0187         pass
0188 
0189     def test_setting_quit(self):
0190         # 'quit' and 'exit' should be injected into __builtin__
0191         self.failUnless(hasattr(__builtin__, "quit"))
0192         self.failUnless(hasattr(__builtin__, "exit"))
0193 
0194     def test_setting_copyright(self):
0195         # 'copyright' and 'credits' should be in __builtin__
0196         self.failUnless(hasattr(__builtin__, "copyright"))
0197         self.failUnless(hasattr(__builtin__, "credits"))
0198 
0199     def test_setting_help(self):
0200         # 'help' should be set in __builtin__
0201         self.failUnless(hasattr(__builtin__, "help"))
0202 
0203     def test_aliasing_mbcs(self):
0204         if sys.platform == "win32":
0205             import locale
0206             if locale.getdefaultlocale()[1].startswith('cp'):
0207                 for value in encodings.aliases.aliases.itervalues():
0208                     if value == "mbcs":
0209                         break
0210                 else:
0211                     self.fail("did not alias mbcs")
0212 
0213     def test_setdefaultencoding_removed(self):
0214         # Make sure sys.setdefaultencoding is gone
0215         self.failUnless(not hasattr(sys, "setdefaultencoding"))
0216 
0217     def test_sitecustomize_executed(self):
0218         # If sitecustomize is available, it should have been imported.
0219         if not sys.modules.has_key("sitecustomize"):
0220             try:
0221                 import sitecustomize
0222             except ImportError:
0223                 pass
0224             else:
0225                 self.fail("sitecustomize not imported automatically")
0226 
0227 
0228 
0229 
0230 def test_main():
0231     run_unittest(HelperFunctionsTests, ImportSideEffectTests)
0232 
0233 
0234 
0235 if __name__ == "__main__":
0236     test_main()
0237 

Generated by PyXR 0.9.4
SourceForge.net Logo