test_site.py 9.54 KB
Newer Older
1 2 3 4 5 6 7
"""Tests for 'site'.

Tests assume the initial paths in sys.path once the interpreter has begun
executing have not been removed.

"""
import unittest
8
from test.support import run_unittest, TESTFN, EnvironmentVarGuard
9
import builtins
10 11 12
import os
import sys
import encodings
13
import subprocess
14 15 16 17 18 19
# Need to make sure to not import 'site' if someone specified ``-S`` at the
# command-line.  Detect this by just making sure 'site' has not been imported
# already.
if "site" in sys.modules:
    import site
else:
Benjamin Peterson's avatar
Benjamin Peterson committed
20
    raise unittest.SkipTest("importation of site.py suppressed")
21

22 23 24 25 26
if not os.path.isdir(site.USER_SITE):
    # need to add user site directory for tests
    os.makedirs(site.USER_SITE)
    site.addsitedir(site.USER_SITE)

27 28
class HelperFunctionsTests(unittest.TestCase):
    """Tests for helper functions.
29

30 31
    The setting of the encoding (set using sys.setdefaultencoding) used by
    the Unicode implementation is not tested.
32

33 34 35 36 37 38
    """

    def setUp(self):
        """Save a copy of sys.path"""
        self.sys_path = sys.path[:]

39
    def tearDown(self):
40 41
        """Restore sys.path"""
        sys.path = self.sys_path
42

43 44 45 46 47 48 49
    def test_makepath(self):
        # Test makepath() have an absolute path for its first return value
        # and a case-normalized version of the absolute path for its
        # second value.
        path_parts = ("Beginning", "End")
        original_dir = os.path.join(*path_parts)
        abs_dir, norm_dir = site.makepath(*path_parts)
50
        self.assertEqual(os.path.abspath(original_dir), abs_dir)
51
        if original_dir == os.path.normcase(original_dir):
52
            self.assertEqual(abs_dir, norm_dir)
53
        else:
54
            self.assertEqual(os.path.normcase(abs_dir), norm_dir)
55 56 57 58 59

    def test_init_pathinfo(self):
        dir_set = site._init_pathinfo()
        for entry in [site.makepath(path)[1] for path in sys.path
                        if path and os.path.isdir(path)]:
60
            self.assertTrue(entry in dir_set,
61 62
                            "%s from sys.path not found in set returned "
                            "by _init_pathinfo(): %s" % (entry, dir_set))
63

64 65
    def pth_file_tests(self, pth_file):
        """Contain common code for testing results of reading a .pth file"""
66
        self.assertTrue(pth_file.imported in sys.modules,
67
                "%s not in sys.path" % pth_file.imported)
68 69
        self.assertTrue(site.makepath(pth_file.good_dir_path)[0] in sys.path)
        self.assertTrue(not os.path.exists(pth_file.bad_dir_path))
70

71 72
    def test_addpackage(self):
        # Make sure addpackage() imports if the line starts with 'import',
73 74 75 76
        # adds directories to sys.path for any line in the file that is not a
        # comment or import that is a valid directory name for where the .pth
        # file resides; invalid directories are not added
        pth_file = PthFile()
77 78
        pth_file.cleanup(prep=True)  # to make sure that nothing is
                                      # pre-existing that shouldn't be
79
        try:
80 81
            pth_file.create()
            site.addpackage(pth_file.base_dir, pth_file.filename, set())
82
            self.pth_file_tests(pth_file)
83
        finally:
84
            pth_file.cleanup()
85

86
    def test_addsitedir(self):
87 88 89
        # Same tests for test_addpackage since addsitedir() essentially just
        # calls addpackage() for every .pth file in the directory
        pth_file = PthFile()
90 91
        pth_file.cleanup(prep=True) # Make sure that nothing is pre-existing
                                    # that is tested for
92
        try:
93
            pth_file.create()
94
            site.addsitedir(pth_file.base_dir, set())
95
            self.pth_file_tests(pth_file)
96
        finally:
97 98
            pth_file.cleanup()

99 100
    def test_s_option(self):
        usersite = site.USER_SITE
101
        self.assertTrue(usersite in sys.path)
102 103

        rc = subprocess.call([sys.executable, '-c',
Benjamin Peterson's avatar
Benjamin Peterson committed
104
            'import sys; sys.exit(%r in sys.path)' % usersite])
105 106 107
        self.assertEqual(rc, 1)

        rc = subprocess.call([sys.executable, '-s', '-c',
Benjamin Peterson's avatar
Benjamin Peterson committed
108
            'import sys; sys.exit(%r in sys.path)' % usersite])
109 110 111 112 113
        self.assertEqual(rc, 0)

        env = os.environ.copy()
        env["PYTHONNOUSERSITE"] = "1"
        rc = subprocess.call([sys.executable, '-c',
Benjamin Peterson's avatar
Benjamin Peterson committed
114
            'import sys; sys.exit(%r in sys.path)' % usersite],
115 116 117 118 119 120 121 122 123 124 125
            env=env)
        self.assertEqual(rc, 0)

        env = os.environ.copy()
        env["PYTHONUSERBASE"] = "/tmp"
        rc = subprocess.call([sys.executable, '-c',
            'import sys, site; sys.exit(site.USER_BASE.startswith("/tmp"))'],
            env=env)
        self.assertEqual(rc, 1)


126 127 128 129 130 131 132 133 134
class PthFile(object):
    """Helper class for handling testing of .pth files"""

    def __init__(self, filename_base=TESTFN, imported="time",
                    good_dirname="__testdir__", bad_dirname="__bad"):
        """Initialize instance variables"""
        self.filename = filename_base + ".pth"
        self.base_dir = os.path.abspath('')
        self.file_path = os.path.join(self.base_dir, self.filename)
135
        self.imported = imported
136 137 138 139 140 141 142 143 144
        self.good_dirname = good_dirname
        self.bad_dirname = bad_dirname
        self.good_dir_path = os.path.join(self.base_dir, self.good_dirname)
        self.bad_dir_path = os.path.join(self.base_dir, self.bad_dirname)

    def create(self):
        """Create a .pth file with a comment, blank lines, an ``import
        <self.imported>``, a line with self.good_dirname, and a line with
        self.bad_dirname.
145

146 147 148 149
        Creation of the directory for self.good_dir_path (based off of
        self.good_dirname) is also performed.

        Make sure to call self.cleanup() to undo anything done by this method.
150

151
        """
152
        FILE = open(self.file_path, 'w')
153
        try:
154 155 156 157 158
            print("#import @bad module name", file=FILE)
            print("\n", file=FILE)
            print("import %s" % self.imported, file=FILE)
            print(self.good_dirname, file=FILE)
            print(self.bad_dirname, file=FILE)
159 160 161
        finally:
            FILE.close()
        os.mkdir(self.good_dir_path)
162

163
    def cleanup(self, prep=False):
164 165 166
        """Make sure that the .pth file is deleted, self.imported is not in
        sys.modules, and that both self.good_dirname and self.bad_dirname are
        not existing directories."""
167
        if os.path.exists(self.file_path):
168
            os.remove(self.file_path)
169 170 171 172 173 174 175 176
        if prep:
            self.imported_module = sys.modules.get(self.imported)
            if self.imported_module:
                del sys.modules[self.imported]
        else:
            if self.imported_module:
                sys.modules[self.imported] = self.imported_module
        if os.path.exists(self.good_dir_path):
177
            os.rmdir(self.good_dir_path)
178
        if os.path.exists(self.bad_dir_path):
179
            os.rmdir(self.bad_dir_path)
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196

class ImportSideEffectTests(unittest.TestCase):
    """Test side-effects from importing 'site'."""

    def setUp(self):
        """Make a copy of sys.path"""
        self.sys_path = sys.path[:]

    def tearDown(self):
        """Restore sys.path"""
        sys.path = self.sys_path

    def test_abs__file__(self):
        # Make sure all imported modules have their __file__ attribute
        # as an absolute path.
        # Handled by abs__file__()
        site.abs__file__()
197
        for module in (sys, os, builtins):
198
            try:
199
                self.assertTrue(os.path.isabs(module.__file__), repr(module))
200 201
            except AttributeError:
                continue
202 203 204
        # We could try everything in sys.modules; however, when regrtest.py
        # runs something like test_frozen before test_site, then we will
        # be testing things loaded *after* test_site did path normalization
205 206 207 208 209 210 211

    def test_no_duplicate_paths(self):
        # No duplicate paths should exist in sys.path
        # Handled by removeduppaths()
        site.removeduppaths()
        seen_paths = set()
        for path in sys.path:
212
            self.assertTrue(path not in seen_paths)
213 214 215 216 217 218 219 220 221
            seen_paths.add(path)

    def test_add_build_dir(self):
        # Test that the build directory's Modules directory is used when it
        # should be.
        # XXX: implement
        pass

    def test_setting_quit(self):
222
        # 'quit' and 'exit' should be injected into builtins
223 224
        self.assertTrue(hasattr(builtins, "quit"))
        self.assertTrue(hasattr(builtins, "exit"))
225 226

    def test_setting_copyright(self):
227
        # 'copyright' and 'credits' should be in builtins
228 229
        self.assertTrue(hasattr(builtins, "copyright"))
        self.assertTrue(hasattr(builtins, "credits"))
230 231

    def test_setting_help(self):
232
        # 'help' should be set in builtins
233
        self.assertTrue(hasattr(builtins, "help"))
234 235 236 237 238

    def test_aliasing_mbcs(self):
        if sys.platform == "win32":
            import locale
            if locale.getdefaultlocale()[1].startswith('cp'):
239
                for value in encodings.aliases.aliases.values():
240 241 242 243 244 245 246
                    if value == "mbcs":
                        break
                else:
                    self.fail("did not alias mbcs")

    def test_setdefaultencoding_removed(self):
        # Make sure sys.setdefaultencoding is gone
247
        self.assertTrue(not hasattr(sys, "setdefaultencoding"))
248 249 250

    def test_sitecustomize_executed(self):
        # If sitecustomize is available, it should have been imported.
251
        if "sitecustomize" not in sys.modules:
252 253 254 255 256 257 258 259 260 261 262 263
            try:
                import sitecustomize
            except ImportError:
                pass
            else:
                self.fail("sitecustomize not imported automatically")

def test_main():
    run_unittest(HelperFunctionsTests, ImportSideEffectTests)

if __name__ == "__main__":
    test_main()