| 1 |
"""Tests for 'site'. |
| 2 |
|
| 3 |
Tests assume the initial paths in sys.path once the interpreter has begun |
| 4 |
executing have not been removed. |
| 5 |
|
| 6 |
""" |
| 7 |
import unittest |
| 8 |
import test.support |
| 9 |
from test import support |
| 10 |
from test.support import os_helper, check_impl_detail, cpython_only |
| 11 |
from test.support import socket_helper |
| 12 |
from test.support import captured_stderr |
| 13 |
from test.support.os_helper import TESTFN, EnvironmentVarGuard, change_cwd |
| 14 |
import ast |
| 15 |
import builtins |
| 16 |
import encodings |
| 17 |
import glob |
| 18 |
import io |
| 19 |
import os |
| 20 |
import re |
| 21 |
import shutil |
| 22 |
import stat |
| 23 |
import subprocess |
| 24 |
import sys |
| 25 |
import sysconfig |
| 26 |
import tempfile |
| 27 |
import urllib.error |
| 28 |
import urllib.request |
| 29 |
from unittest import mock |
| 30 |
from copy import copy |
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
if sys.flags.no_site: |
| 36 |
raise unittest.SkipTest("Python was invoked with -S") |
| 37 |
|
| 38 |
import site |
| 39 |
|
| 40 |
|
| 41 |
HAS_USER_SITE = (site.USER_SITE is not None) |
| 42 |
OLD_SYS_PATH = None |
| 43 |
|
| 44 |
|
| 45 |
def setUpModule(): |
| 46 |
global OLD_SYS_PATH |
| 47 |
OLD_SYS_PATH = sys.path[:] |
| 48 |
|
| 49 |
if site.ENABLE_USER_SITE and not os.path.isdir(site.USER_SITE): |
| 50 |
|
| 51 |
try: |
| 52 |
os.makedirs(site.USER_SITE) |
| 53 |
|
| 54 |
site.addsitedir(site.USER_SITE) |
| 55 |
except PermissionError as exc: |
| 56 |
raise unittest.SkipTest('unable to create user site directory (%r): %s' |
| 57 |
% (site.USER_SITE, exc)) |
| 58 |
|
| 59 |
|
| 60 |
def tearDownModule(): |
| 61 |
sys.path[:] = OLD_SYS_PATH |
| 62 |
|
| 63 |
|
| 64 |
class HelperFunctionsTests(unittest.TestCase): |
| 65 |
"""Tests for helper functions. |
| 66 |
""" |
| 67 |
|
| 68 |
def setUp(self): |
| 69 |
"""Save a copy of sys.path""" |
| 70 |
self.sys_path = sys.path[:] |
| 71 |
self.old_base = site.USER_BASE |
| 72 |
self.old_site = site.USER_SITE |
| 73 |
self.old_prefixes = site.PREFIXES |
| 74 |
self.original_vars = sysconfig._CONFIG_VARS |
| 75 |
self.old_vars = copy(sysconfig._CONFIG_VARS) |
| 76 |
|
| 77 |
def tearDown(self): |
| 78 |
"""Restore sys.path""" |
| 79 |
sys.path[:] = self.sys_path |
| 80 |
site.USER_BASE = self.old_base |
| 81 |
site.USER_SITE = self.old_site |
| 82 |
site.PREFIXES = self.old_prefixes |
| 83 |
sysconfig._CONFIG_VARS = self.original_vars |
| 84 |
|
| 85 |
if sysconfig._CONFIG_VARS is not None: |
| 86 |
sysconfig._CONFIG_VARS.clear() |
| 87 |
sysconfig._CONFIG_VARS.update(self.old_vars) |
| 88 |
|
| 89 |
def test_makepath(self): |
| 90 |
|
| 91 |
|
| 92 |
|
| 93 |
path_parts = ("Beginning", "End") |
| 94 |
original_dir = os.path.join(*path_parts) |
| 95 |
abs_dir, norm_dir = site.makepath(*path_parts) |
| 96 |
self.assertEqual(os.path.abspath(original_dir), abs_dir) |
| 97 |
if original_dir == os.path.normcase(original_dir): |
| 98 |
self.assertEqual(abs_dir, norm_dir) |
| 99 |
else: |
| 100 |
self.assertEqual(os.path.normcase(abs_dir), norm_dir) |
| 101 |
|
| 102 |
def test_init_pathinfo(self): |
| 103 |
dir_set = site._init_pathinfo() |
| 104 |
for entry in [site.makepath(path)[1] for path in sys.path |
| 105 |
if path and os.path.exists(path)]: |
| 106 |
self.assertIn(entry, dir_set, |
| 107 |
"%s from sys.path not found in set returned " |
| 108 |
"by _init_pathinfo(): %s" % (entry, dir_set)) |
| 109 |
|
| 110 |
def pth_file_tests(self, pth_file): |
| 111 |
"""Contain common code for testing results of reading a .pth file""" |
| 112 |
self.assertIn(pth_file.imported, sys.modules, |
| 113 |
"%s not in sys.modules" % pth_file.imported) |
| 114 |
self.assertIn(site.makepath(pth_file.good_dir_path)[0], sys.path) |
| 115 |
self.assertFalse(os.path.exists(pth_file.bad_dir_path)) |
| 116 |
|
| 117 |
def test_addpackage(self): |
| 118 |
|
| 119 |
|
| 120 |
|
| 121 |
|
| 122 |
pth_file = PthFile() |
| 123 |
pth_file.cleanup(prep=True) |
| 124 |
|
| 125 |
try: |
| 126 |
pth_file.create() |
| 127 |
site.addpackage(pth_file.base_dir, pth_file.filename, set()) |
| 128 |
self.pth_file_tests(pth_file) |
| 129 |
finally: |
| 130 |
pth_file.cleanup() |
| 131 |
|
| 132 |
def make_pth(self, contents, pth_dir='.', pth_name=TESTFN): |
| 133 |
|
| 134 |
pth_dir = os.path.abspath(pth_dir) |
| 135 |
pth_basename = pth_name + '.pth' |
| 136 |
pth_fn = os.path.join(pth_dir, pth_basename) |
| 137 |
with open(pth_fn, 'w', encoding='utf-8') as pth_file: |
| 138 |
self.addCleanup(lambda: os.remove(pth_fn)) |
| 139 |
pth_file.write(contents) |
| 140 |
return pth_dir, pth_basename |
| 141 |
|
| 142 |
def test_addpackage_import_bad_syntax(self): |
| 143 |
|
| 144 |
pth_dir, pth_fn = self.make_pth("import bad-syntax\n") |
| 145 |
with captured_stderr() as err_out: |
| 146 |
site.addpackage(pth_dir, pth_fn, set()) |
| 147 |
self.assertRegex(err_out.getvalue(), "line 1") |
| 148 |
self.assertRegex(err_out.getvalue(), |
| 149 |
re.escape(os.path.join(pth_dir, pth_fn))) |
| 150 |
|
| 151 |
|
| 152 |
|
| 153 |
self.assertRegex(err_out.getvalue(), 'Traceback') |
| 154 |
self.assertRegex(err_out.getvalue(), r'import bad-syntax') |
| 155 |
self.assertRegex(err_out.getvalue(), 'SyntaxError') |
| 156 |
|
| 157 |
def test_addpackage_import_bad_exec(self): |
| 158 |
|
| 159 |
pth_dir, pth_fn = self.make_pth("randompath\nimport nosuchmodule\n") |
| 160 |
with captured_stderr() as err_out: |
| 161 |
site.addpackage(pth_dir, pth_fn, set()) |
| 162 |
self.assertRegex(err_out.getvalue(), "line 2") |
| 163 |
self.assertRegex(err_out.getvalue(), |
| 164 |
re.escape(os.path.join(pth_dir, pth_fn))) |
| 165 |
|
| 166 |
self.assertRegex(err_out.getvalue(), 'Traceback') |
| 167 |
self.assertRegex(err_out.getvalue(), 'ModuleNotFoundError') |
| 168 |
|
| 169 |
def test_addpackage_empty_lines(self): |
| 170 |
|
| 171 |
pth_dir, pth_fn = self.make_pth("\n\n \n\n") |
| 172 |
known_paths = site.addpackage(pth_dir, pth_fn, set()) |
| 173 |
self.assertEqual(known_paths, set()) |
| 174 |
|
| 175 |
def test_addpackage_import_bad_pth_file(self): |
| 176 |
|
| 177 |
pth_dir, pth_fn = self.make_pth("abc\x00def\n") |
| 178 |
with captured_stderr() as err_out: |
| 179 |
self.assertFalse(site.addpackage(pth_dir, pth_fn, set())) |
| 180 |
self.maxDiff = None |
| 181 |
self.assertEqual(err_out.getvalue(), "") |
| 182 |
for path in sys.path: |
| 183 |
if isinstance(path, str): |
| 184 |
self.assertNotIn("abc\x00def", path) |
| 185 |
|
| 186 |
def test_addsitedir(self): |
| 187 |
|
| 188 |
|
| 189 |
pth_file = PthFile() |
| 190 |
pth_file.cleanup(prep=True) |
| 191 |
|
| 192 |
try: |
| 193 |
pth_file.create() |
| 194 |
site.addsitedir(pth_file.base_dir, set()) |
| 195 |
self.pth_file_tests(pth_file) |
| 196 |
finally: |
| 197 |
pth_file.cleanup() |
| 198 |
|
| 199 |
def test_addsitedir_dotfile(self): |
| 200 |
pth_file = PthFile('.dotfile') |
| 201 |
pth_file.cleanup(prep=True) |
| 202 |
try: |
| 203 |
pth_file.create() |
| 204 |
site.addsitedir(pth_file.base_dir, set()) |
| 205 |
self.assertNotIn(site.makepath(pth_file.good_dir_path)[0], sys.path) |
| 206 |
self.assertIn(pth_file.base_dir, sys.path) |
| 207 |
finally: |
| 208 |
pth_file.cleanup() |
| 209 |
|
| 210 |
@unittest.skipUnless(hasattr(os, 'chflags'), 'test needs os.chflags()') |
| 211 |
def test_addsitedir_hidden_flags(self): |
| 212 |
pth_file = PthFile() |
| 213 |
pth_file.cleanup(prep=True) |
| 214 |
try: |
| 215 |
pth_file.create() |
| 216 |
st = os.stat(pth_file.file_path) |
| 217 |
os.chflags(pth_file.file_path, st.st_flags | stat.UF_HIDDEN) |
| 218 |
site.addsitedir(pth_file.base_dir, set()) |
| 219 |
self.assertNotIn(site.makepath(pth_file.good_dir_path)[0], sys.path) |
| 220 |
self.assertIn(pth_file.base_dir, sys.path) |
| 221 |
finally: |
| 222 |
pth_file.cleanup() |
| 223 |
|
| 224 |
@unittest.skipUnless(sys.platform == 'win32', 'test needs Windows') |
| 225 |
@support.requires_subprocess() |
| 226 |
def test_addsitedir_hidden_file_attribute(self): |
| 227 |
pth_file = PthFile() |
| 228 |
pth_file.cleanup(prep=True) |
| 229 |
try: |
| 230 |
pth_file.create() |
| 231 |
subprocess.check_call(['attrib', '+H', pth_file.file_path]) |
| 232 |
site.addsitedir(pth_file.base_dir, set()) |
| 233 |
self.assertNotIn(site.makepath(pth_file.good_dir_path)[0], sys.path) |
| 234 |
self.assertIn(pth_file.base_dir, sys.path) |
| 235 |
finally: |
| 236 |
pth_file.cleanup() |
| 237 |
|
| 238 |
|
| 239 |
|
| 240 |
def test__getuserbase(self): |
| 241 |
self.assertEqual(site._getuserbase(), sysconfig._getuserbase()) |
| 242 |
|
| 243 |
@unittest.skipUnless(HAS_USER_SITE, 'need user site') |
| 244 |
def test_get_path(self): |
| 245 |
if sys.platform == 'darwin' and sys._framework: |
| 246 |
scheme = 'osx_framework_user' |
| 247 |
else: |
| 248 |
scheme = os.name + '_user' |
| 249 |
self.assertEqual(os.path.normpath(site._get_path(site._getuserbase())), |
| 250 |
sysconfig.get_path('purelib', scheme)) |
| 251 |
|
| 252 |
@unittest.skipUnless(site.ENABLE_USER_SITE, "requires access to PEP 370 " |
| 253 |
"user-site (site.ENABLE_USER_SITE)") |
| 254 |
@support.requires_subprocess() |
| 255 |
def test_s_option(self): |
| 256 |
|
| 257 |
usersite = os.path.normpath(site.USER_SITE) |
| 258 |
self.assertIn(usersite, sys.path) |
| 259 |
|
| 260 |
env = os.environ.copy() |
| 261 |
rc = subprocess.call([sys.executable, '-c', |
| 262 |
'import sys; sys.exit(%r in sys.path)' % usersite], |
| 263 |
env=env) |
| 264 |
self.assertEqual(rc, 1) |
| 265 |
|
| 266 |
env = os.environ.copy() |
| 267 |
rc = subprocess.call([sys.executable, '-s', '-c', |
| 268 |
'import sys; sys.exit(%r in sys.path)' % usersite], |
| 269 |
env=env) |
| 270 |
if usersite == site.getsitepackages()[0]: |
| 271 |
self.assertEqual(rc, 1) |
| 272 |
else: |
| 273 |
self.assertEqual(rc, 0, "User site still added to path with -s") |
| 274 |
|
| 275 |
env = os.environ.copy() |
| 276 |
env["PYTHONNOUSERSITE"] = "1" |
| 277 |
rc = subprocess.call([sys.executable, '-c', |
| 278 |
'import sys; sys.exit(%r in sys.path)' % usersite], |
| 279 |
env=env) |
| 280 |
if usersite == site.getsitepackages()[0]: |
| 281 |
self.assertEqual(rc, 1) |
| 282 |
else: |
| 283 |
self.assertEqual(rc, 0, |
| 284 |
"User site still added to path with PYTHONNOUSERSITE") |
| 285 |
|
| 286 |
env = os.environ.copy() |
| 287 |
env["PYTHONUSERBASE"] = "/tmp" |
| 288 |
rc = subprocess.call([sys.executable, '-c', |
| 289 |
'import sys, site; sys.exit(site.USER_BASE.startswith("/tmp"))'], |
| 290 |
env=env) |
| 291 |
self.assertEqual(rc, 1, |
| 292 |
"User base not set by PYTHONUSERBASE") |
| 293 |
|
| 294 |
@unittest.skipUnless(HAS_USER_SITE, 'need user site') |
| 295 |
def test_getuserbase(self): |
| 296 |
site.USER_BASE = None |
| 297 |
user_base = site.getuserbase() |
| 298 |
|
| 299 |
|
| 300 |
self.assertEqual(site.USER_BASE, user_base) |
| 301 |
|
| 302 |
|
| 303 |
site.USER_BASE = None |
| 304 |
import sysconfig |
| 305 |
sysconfig._CONFIG_VARS = None |
| 306 |
|
| 307 |
with EnvironmentVarGuard() as environ: |
| 308 |
environ['PYTHONUSERBASE'] = 'xoxo' |
| 309 |
self.assertTrue(site.getuserbase().startswith('xoxo'), |
| 310 |
site.getuserbase()) |
| 311 |
|
| 312 |
@unittest.skipUnless(HAS_USER_SITE, 'need user site') |
| 313 |
def test_getusersitepackages(self): |
| 314 |
site.USER_SITE = None |
| 315 |
site.USER_BASE = None |
| 316 |
user_site = site.getusersitepackages() |
| 317 |
|
| 318 |
|
| 319 |
self.assertEqual(site.USER_SITE, user_site) |
| 320 |
self.assertTrue(user_site.startswith(site.USER_BASE), user_site) |
| 321 |
self.assertEqual(site.USER_BASE, site.getuserbase()) |
| 322 |
|
| 323 |
def test_getsitepackages(self): |
| 324 |
site.PREFIXES = ['xoxo'] |
| 325 |
dirs = site.getsitepackages() |
| 326 |
if check_impl_detail(pypy=True): |
| 327 |
implementation = 'pypy' |
| 328 |
else: |
| 329 |
implementation = 'python' |
| 330 |
ver = sys.version_info |
| 331 |
if os.sep == '/': |
| 332 |
|
| 333 |
if sys.platlibdir != "lib": |
| 334 |
self.assertEqual(len(dirs), 2) |
| 335 |
wanted = os.path.join('xoxo', sys.platlibdir, |
| 336 |
'python%d.%d' % sys.version_info[:2], |
| 337 |
'site-packages') |
| 338 |
self.assertEqual(dirs[0], wanted) |
| 339 |
else: |
| 340 |
self.assertEqual(len(dirs), 1) |
| 341 |
wanted = os.path.join('xoxo', 'lib', |
| 342 |
f'{implementation}{ver[0]}.{ver[1]}', |
| 343 |
'site-packages') |
| 344 |
self.assertEqual(dirs[-1], wanted) |
| 345 |
else: |
| 346 |
|
| 347 |
self.assertEqual(len(dirs), 2) |
| 348 |
self.assertEqual(dirs[0], 'xoxo') |
| 349 |
wanted = os.path.join('xoxo', 'lib', 'site-packages') |
| 350 |
self.assertEqual(os.path.normcase(dirs[1]), |
| 351 |
os.path.normcase(wanted)) |
| 352 |
|
| 353 |
@unittest.skipUnless(HAS_USER_SITE, 'need user site') |
| 354 |
def test_no_home_directory(self): |
| 355 |
|
| 356 |
|
| 357 |
|
| 358 |
site.USER_SITE = None |
| 359 |
site.USER_BASE = None |
| 360 |
|
| 361 |
with EnvironmentVarGuard() as environ, \ |
| 362 |
mock.patch('os.path.expanduser', lambda path: path): |
| 363 |
|
| 364 |
del environ['PYTHONUSERBASE'] |
| 365 |
del environ['APPDATA'] |
| 366 |
|
| 367 |
user_base = site.getuserbase() |
| 368 |
self.assertTrue(user_base.startswith('~' + os.sep), |
| 369 |
user_base) |
| 370 |
|
| 371 |
user_site = site.getusersitepackages() |
| 372 |
self.assertTrue(user_site.startswith(user_base), user_site) |
| 373 |
|
| 374 |
with mock.patch('os.path.isdir', return_value=False) as mock_isdir, \ |
| 375 |
mock.patch.object(site, 'addsitedir') as mock_addsitedir, \ |
| 376 |
support.swap_attr(site, 'ENABLE_USER_SITE', True): |
| 377 |
|
| 378 |
|
| 379 |
|
| 380 |
known_paths = set() |
| 381 |
site.addusersitepackages(known_paths) |
| 382 |
|
| 383 |
mock_isdir.assert_called_once_with(user_site) |
| 384 |
mock_addsitedir.assert_not_called() |
| 385 |
self.assertFalse(known_paths) |
| 386 |
|
| 387 |
def test_trace(self): |
| 388 |
message = "bla-bla-bla" |
| 389 |
for verbose, out in (True, message + "\n"), (False, ""): |
| 390 |
with mock.patch('sys.flags', mock.Mock(verbose=verbose)), \ |
| 391 |
mock.patch('sys.stderr', io.StringIO()): |
| 392 |
site._trace(message) |
| 393 |
self.assertEqual(sys.stderr.getvalue(), out) |
| 394 |
|
| 395 |
|
| 396 |
class PthFile(object): |
| 397 |
"""Helper class for handling testing of .pth files""" |
| 398 |
|
| 399 |
def __init__(self, filename_base=TESTFN, imported="time", |
| 400 |
good_dirname="__testdir__", bad_dirname="__bad"): |
| 401 |
"""Initialize instance variables""" |
| 402 |
self.filename = filename_base + ".pth" |
| 403 |
self.base_dir = os.path.abspath('') |
| 404 |
self.file_path = os.path.join(self.base_dir, self.filename) |
| 405 |
self.imported = imported |
| 406 |
self.good_dirname = good_dirname |
| 407 |
self.bad_dirname = bad_dirname |
| 408 |
self.good_dir_path = os.path.join(self.base_dir, self.good_dirname) |
| 409 |
self.bad_dir_path = os.path.join(self.base_dir, self.bad_dirname) |
| 410 |
|
| 411 |
def create(self): |
| 412 |
"""Create a .pth file with a comment, blank lines, an ``import |
| 413 |
<self.imported>``, a line with self.good_dirname, and a line with |
| 414 |
self.bad_dirname. |
| 415 |
|
| 416 |
Creation of the directory for self.good_dir_path (based off of |
| 417 |
self.good_dirname) is also performed. |
| 418 |
|
| 419 |
Make sure to call self.cleanup() to undo anything done by this method. |
| 420 |
|
| 421 |
""" |
| 422 |
FILE = open(self.file_path, 'w') |
| 423 |
try: |
| 424 |
print("#import @bad module name", file=FILE) |
| 425 |
print("\n", file=FILE) |
| 426 |
print("import %s" % self.imported, file=FILE) |
| 427 |
print(self.good_dirname, file=FILE) |
| 428 |
print(self.bad_dirname, file=FILE) |
| 429 |
finally: |
| 430 |
FILE.close() |
| 431 |
os.mkdir(self.good_dir_path) |
| 432 |
|
| 433 |
def cleanup(self, prep=False): |
| 434 |
"""Make sure that the .pth file is deleted, self.imported is not in |
| 435 |
sys.modules, and that both self.good_dirname and self.bad_dirname are |
| 436 |
not existing directories.""" |
| 437 |
if os.path.exists(self.file_path): |
| 438 |
os.remove(self.file_path) |
| 439 |
if prep: |
| 440 |
self.imported_module = sys.modules.get(self.imported) |
| 441 |
if self.imported_module: |
| 442 |
del sys.modules[self.imported] |
| 443 |
else: |
| 444 |
if self.imported_module: |
| 445 |
sys.modules[self.imported] = self.imported_module |
| 446 |
if os.path.exists(self.good_dir_path): |
| 447 |
os.rmdir(self.good_dir_path) |
| 448 |
if os.path.exists(self.bad_dir_path): |
| 449 |
os.rmdir(self.bad_dir_path) |
| 450 |
|
| 451 |
class ImportSideEffectTests(unittest.TestCase): |
| 452 |
"""Test side-effects from importing 'site'.""" |
| 453 |
|
| 454 |
def setUp(self): |
| 455 |
"""Make a copy of sys.path""" |
| 456 |
self.sys_path = sys.path[:] |
| 457 |
|
| 458 |
def tearDown(self): |
| 459 |
"""Restore sys.path""" |
| 460 |
sys.path[:] = self.sys_path |
| 461 |
|
| 462 |
def test_abs_paths_cached_None(self): |
| 463 |
"""Test for __cached__ is None. |
| 464 |
|
| 465 |
Regarding to PEP 3147, __cached__ can be None. |
| 466 |
|
| 467 |
See also: https://bugs.python.org/issue30167 |
| 468 |
""" |
| 469 |
sys.modules['test'].__cached__ = None |
| 470 |
site.abs_paths() |
| 471 |
self.assertIsNone(sys.modules['test'].__cached__) |
| 472 |
|
| 473 |
def test_no_duplicate_paths(self): |
| 474 |
|
| 475 |
|
| 476 |
site.removeduppaths() |
| 477 |
seen_paths = set() |
| 478 |
for path in sys.path: |
| 479 |
self.assertNotIn(path, seen_paths) |
| 480 |
seen_paths.add(path) |
| 481 |
|
| 482 |
@unittest.skip('test not implemented') |
| 483 |
def test_add_build_dir(self): |
| 484 |
|
| 485 |
|
| 486 |
|
| 487 |
pass |
| 488 |
|
| 489 |
def test_setting_quit(self): |
| 490 |
|
| 491 |
self.assertTrue(hasattr(builtins, "quit")) |
| 492 |
self.assertTrue(hasattr(builtins, "exit")) |
| 493 |
|
| 494 |
def test_setting_copyright(self): |
| 495 |
|
| 496 |
self.assertTrue(hasattr(builtins, "copyright")) |
| 497 |
self.assertTrue(hasattr(builtins, "credits")) |
| 498 |
self.assertTrue(hasattr(builtins, "license")) |
| 499 |
|
| 500 |
def test_setting_help(self): |
| 501 |
|
| 502 |
self.assertTrue(hasattr(builtins, "help")) |
| 503 |
|
| 504 |
def test_sitecustomize_executed(self): |
| 505 |
|
| 506 |
if "sitecustomize" not in sys.modules: |
| 507 |
try: |
| 508 |
import sitecustomize |
| 509 |
except ImportError: |
| 510 |
pass |
| 511 |
else: |
| 512 |
self.fail("sitecustomize not imported automatically") |
| 513 |
|
| 514 |
@unittest.skipUnless(hasattr(urllib.request, "HTTPSHandler"), |
| 515 |
'need SSL support to download license') |
| 516 |
@test.support.requires_resource('network') |
| 517 |
@test.support.system_must_validate_cert |
| 518 |
def test_license_exists_at_url(self): |
| 519 |
|
| 520 |
|
| 521 |
url = license._Printer__data.split()[1] |
| 522 |
req = urllib.request.Request(url, method='HEAD') |
| 523 |
|
| 524 |
self.addCleanup(urllib.request.urlcleanup) |
| 525 |
try: |
| 526 |
with socket_helper.transient_internet(url): |
| 527 |
with urllib.request.urlopen(req) as data: |
| 528 |
code = data.getcode() |
| 529 |
except urllib.error.HTTPError as e: |
| 530 |
code = e.code |
| 531 |
self.assertEqual(code, 200, msg="Can't find " + url) |
| 532 |
|
| 533 |
|
| 534 |
class StartupImportTests(unittest.TestCase): |
| 535 |
|
| 536 |
@support.requires_subprocess() |
| 537 |
def test_startup_imports(self): |
| 538 |
|
| 539 |
popen = subprocess.Popen([sys.executable, '-X', 'utf8', '-I', |
| 540 |
'-c', 'import sys; print(repr(sys.path))'], |
| 541 |
stdout=subprocess.PIPE, |
| 542 |
encoding='utf-8', |
| 543 |
errors='surrogateescape') |
| 544 |
stdout = popen.communicate()[0] |
| 545 |
self.assertEqual(popen.returncode, 0, repr(stdout)) |
| 546 |
isolated_paths = ast.literal_eval(stdout) |
| 547 |
|
| 548 |
|
| 549 |
|
| 550 |
|
| 551 |
for path in isolated_paths: |
| 552 |
pth_files = glob.glob(os.path.join(glob.escape(path), "*.pth")) |
| 553 |
if pth_files: |
| 554 |
self.skipTest(f"found {len(pth_files)} .pth files in: {path}") |
| 555 |
|
| 556 |
|
| 557 |
|
| 558 |
popen = subprocess.Popen([sys.executable, '-X', 'utf8', '-I', '-v', |
| 559 |
'-c', 'import sys; print(set(sys.modules))'], |
| 560 |
stdout=subprocess.PIPE, |
| 561 |
stderr=subprocess.PIPE, |
| 562 |
encoding='utf-8', |
| 563 |
errors='surrogateescape') |
| 564 |
stdout, stderr = popen.communicate() |
| 565 |
self.assertEqual(popen.returncode, 0, (stdout, stderr)) |
| 566 |
modules = ast.literal_eval(stdout) |
| 567 |
|
| 568 |
self.assertIn('site', modules) |
| 569 |
|
| 570 |
|
| 571 |
re_mods = {'re', '_sre', 're._compiler', 're._constants', 're._parser'} |
| 572 |
self.assertFalse(modules.intersection(re_mods), stderr) |
| 573 |
|
| 574 |
|
| 575 |
self.assertNotIn('locale', modules, stderr) |
| 576 |
|
| 577 |
|
| 578 |
self.assertNotIn('copyreg', modules, stderr) |
| 579 |
|
| 580 |
|
| 581 |
collection_mods = {'_collections', 'collections', 'functools', |
| 582 |
'heapq', 'itertools', 'keyword', 'operator', |
| 583 |
'reprlib', 'types', 'weakref' |
| 584 |
}.difference(sys.builtin_module_names) |
| 585 |
self.assertFalse(modules.intersection(collection_mods), stderr) |
| 586 |
|
| 587 |
@support.requires_subprocess() |
| 588 |
def test_startup_interactivehook(self): |
| 589 |
r = subprocess.Popen([sys.executable, '-c', |
| 590 |
'import sys; sys.exit(hasattr(sys, "__interactivehook__"))']).wait() |
| 591 |
self.assertTrue(r, "'__interactivehook__' not added by site") |
| 592 |
|
| 593 |
@support.requires_subprocess() |
| 594 |
def test_startup_interactivehook_isolated(self): |
| 595 |
|
| 596 |
r = subprocess.Popen([sys.executable, '-I', '-c', |
| 597 |
'import sys; sys.exit(hasattr(sys, "__interactivehook__"))']).wait() |
| 598 |
self.assertFalse(r, "'__interactivehook__' added in isolated mode") |
| 599 |
|
| 600 |
@support.requires_subprocess() |
| 601 |
def test_startup_interactivehook_isolated_explicit(self): |
| 602 |
|
| 603 |
r = subprocess.Popen([sys.executable, '-I', '-c', |
| 604 |
'import site, sys; site.enablerlcompleter(); sys.exit(hasattr(sys, "__interactivehook__"))']).wait() |
| 605 |
self.assertTrue(r, "'__interactivehook__' not added by enablerlcompleter()") |
| 606 |
|
| 607 |
class _pthFileTests(unittest.TestCase): |
| 608 |
|
| 609 |
if sys.platform == 'win32': |
| 610 |
def _create_underpth_exe(self, lines, exe_pth=True): |
| 611 |
import _winapi |
| 612 |
temp_dir = tempfile.mkdtemp() |
| 613 |
self.addCleanup(os_helper.rmtree, temp_dir) |
| 614 |
exe_file = os.path.join(temp_dir, os.path.split(sys.executable)[1]) |
| 615 |
dll_src_file = _winapi.GetModuleFileName(sys.dllhandle) |
| 616 |
dll_file = os.path.join(temp_dir, os.path.split(dll_src_file)[1]) |
| 617 |
shutil.copy(sys.executable, exe_file) |
| 618 |
shutil.copy(dll_src_file, dll_file) |
| 619 |
for fn in glob.glob(os.path.join(os.path.split(dll_src_file)[0], "vcruntime*.dll")): |
| 620 |
shutil.copy(fn, os.path.join(temp_dir, os.path.split(fn)[1])) |
| 621 |
if exe_pth: |
| 622 |
_pth_file = os.path.splitext(exe_file)[0] + '._pth' |
| 623 |
else: |
| 624 |
_pth_file = os.path.splitext(dll_file)[0] + '._pth' |
| 625 |
with open(_pth_file, 'w', encoding='utf8') as f: |
| 626 |
for line in lines: |
| 627 |
print(line, file=f) |
| 628 |
return exe_file |
| 629 |
else: |
| 630 |
def _create_underpth_exe(self, lines, exe_pth=True): |
| 631 |
if not exe_pth: |
| 632 |
raise unittest.SkipTest("library ._pth file not supported on this platform") |
| 633 |
temp_dir = tempfile.mkdtemp() |
| 634 |
self.addCleanup(os_helper.rmtree, temp_dir) |
| 635 |
exe_file = os.path.join(temp_dir, os.path.split(sys.executable)[1]) |
| 636 |
os.symlink(sys.executable, exe_file) |
| 637 |
_pth_file = exe_file + '._pth' |
| 638 |
with open(_pth_file, 'w') as f: |
| 639 |
for line in lines: |
| 640 |
print(line, file=f) |
| 641 |
return exe_file |
| 642 |
|
| 643 |
def _calc_sys_path_for_underpth_nosite(self, sys_prefix, lines): |
| 644 |
sys_path = [] |
| 645 |
for line in lines: |
| 646 |
if not line or line[0] == '#': |
| 647 |
continue |
| 648 |
abs_path = os.path.abspath(os.path.join(sys_prefix, line)) |
| 649 |
sys_path.append(abs_path) |
| 650 |
return sys_path |
| 651 |
|
| 652 |
def _get_pth_lines(self, libpath: str, *, import_site: bool): |
| 653 |
pth_lines = ['fake-path-name'] |
| 654 |
|
| 655 |
|
| 656 |
|
| 657 |
encoded_libpath_length = len(libpath.encode("utf-8")) |
| 658 |
repetitions = min(200, 30000 // encoded_libpath_length) |
| 659 |
if repetitions <= 2: |
| 660 |
self.skipTest( |
| 661 |
f"Python stdlib path is too long ({encoded_libpath_length:,} bytes)") |
| 662 |
pth_lines.extend(libpath for _ in range(repetitions)) |
| 663 |
pth_lines.extend(['', '# comment']) |
| 664 |
if import_site: |
| 665 |
pth_lines.append('import site') |
| 666 |
return pth_lines |
| 667 |
|
| 668 |
@support.requires_subprocess() |
| 669 |
@cpython_only |
| 670 |
def test_underpth_basic(self): |
| 671 |
pth_lines = ['#.', '# ..', *sys.path, '.', '..'] |
| 672 |
exe_file = self._create_underpth_exe(pth_lines) |
| 673 |
sys_path = self._calc_sys_path_for_underpth_nosite( |
| 674 |
os.path.dirname(exe_file), |
| 675 |
pth_lines) |
| 676 |
|
| 677 |
output = subprocess.check_output([exe_file, '-X', 'utf8', '-c', |
| 678 |
'import sys; print("\\n".join(sys.path) if sys.flags.no_site else "")' |
| 679 |
], encoding='utf-8', errors='surrogateescape') |
| 680 |
actual_sys_path = output.rstrip().split('\n') |
| 681 |
self.assertTrue(actual_sys_path, "sys.flags.no_site was False") |
| 682 |
self.assertEqual( |
| 683 |
actual_sys_path, |
| 684 |
sys_path, |
| 685 |
"sys.path is incorrect" |
| 686 |
) |
| 687 |
|
| 688 |
@support.requires_subprocess() |
| 689 |
@cpython_only |
| 690 |
def test_underpth_nosite_file(self): |
| 691 |
libpath = test.support.STDLIB_DIR |
| 692 |
exe_prefix = os.path.dirname(sys.executable) |
| 693 |
pth_lines = self._get_pth_lines(libpath, import_site=False) |
| 694 |
exe_file = self._create_underpth_exe(pth_lines) |
| 695 |
sys_path = self._calc_sys_path_for_underpth_nosite( |
| 696 |
os.path.dirname(exe_file), |
| 697 |
pth_lines) |
| 698 |
|
| 699 |
env = os.environ.copy() |
| 700 |
env['PYTHONPATH'] = 'from-env' |
| 701 |
env['PATH'] = '{}{}{}'.format(exe_prefix, os.pathsep, os.getenv('PATH')) |
| 702 |
output = subprocess.check_output([exe_file, '-c', |
| 703 |
'import sys; print("\\n".join(sys.path) if sys.flags.no_site else "")' |
| 704 |
], env=env, encoding='utf-8', errors='surrogateescape') |
| 705 |
actual_sys_path = output.rstrip().split('\n') |
| 706 |
import pdb;pdb.set_trace() |
| 707 |
self.assertTrue(actual_sys_path, "sys.flags.no_site was False") |
| 708 |
self.assertEqual( |
| 709 |
actual_sys_path, |
| 710 |
sys_path, |
| 711 |
"sys.path is incorrect" |
| 712 |
) |
| 713 |
|
| 714 |
@support.requires_subprocess() |
| 715 |
@cpython_only |
| 716 |
def test_underpth_file(self): |
| 717 |
libpath = test.support.STDLIB_DIR |
| 718 |
exe_prefix = os.path.dirname(sys.executable) |
| 719 |
exe_file = self._create_underpth_exe( |
| 720 |
self._get_pth_lines(libpath, import_site=True)) |
| 721 |
sys_prefix = os.path.dirname(exe_file) |
| 722 |
env = os.environ.copy() |
| 723 |
env['PYTHONPATH'] = 'from-env' |
| 724 |
env['PATH'] = '{};{}'.format(exe_prefix, os.getenv('PATH')) |
| 725 |
rc = subprocess.call([exe_file, '-c', |
| 726 |
'import sys; sys.exit(not sys.flags.no_site and ' |
| 727 |
'%r in sys.path and %r in sys.path and %r not in sys.path and ' |
| 728 |
'all("\\r" not in p and "\\n" not in p for p in sys.path))' % ( |
| 729 |
os.path.join(sys_prefix, 'fake-path-name'), |
| 730 |
libpath, |
| 731 |
os.path.join(sys_prefix, 'from-env'), |
| 732 |
)], env=env) |
| 733 |
self.assertTrue(rc, "sys.path is incorrect") |
| 734 |
|
| 735 |
@support.requires_subprocess() |
| 736 |
@cpython_only |
| 737 |
def test_underpth_dll_file(self): |
| 738 |
libpath = test.support.STDLIB_DIR |
| 739 |
exe_prefix = os.path.dirname(sys.executable) |
| 740 |
exe_file = self._create_underpth_exe( |
| 741 |
self._get_pth_lines(libpath, import_site=True), exe_pth=False) |
| 742 |
sys_prefix = os.path.dirname(exe_file) |
| 743 |
env = os.environ.copy() |
| 744 |
env['PYTHONPATH'] = 'from-env' |
| 745 |
env['PATH'] = '{};{}'.format(exe_prefix, os.getenv('PATH')) |
| 746 |
rc = subprocess.call([exe_file, '-c', |
| 747 |
'import sys; sys.exit(not sys.flags.no_site and ' |
| 748 |
'%r in sys.path and %r in sys.path and %r not in sys.path and ' |
| 749 |
'all("\\r" not in p and "\\n" not in p for p in sys.path))' % ( |
| 750 |
os.path.join(sys_prefix, 'fake-path-name'), |
| 751 |
libpath, |
| 752 |
os.path.join(sys_prefix, 'from-env'), |
| 753 |
)], env=env) |
| 754 |
self.assertTrue(rc, "sys.path is incorrect") |
| 755 |
|
| 756 |
|
| 757 |
if __name__ == "__main__": |
| 758 |
unittest.main() |