conftest.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. import io
  2. import os
  3. import shutil
  4. import subprocess
  5. import sys
  6. import pytest
  7. import six
  8. import pip._internal
  9. from tests.lib import SRC_DIR, TestData
  10. from tests.lib.path import Path
  11. from tests.lib.scripttest import PipTestEnvironment
  12. from tests.lib.venv import VirtualEnvironment
  13. def pytest_addoption(parser):
  14. parser.addoption(
  15. "--keep-tmpdir", action="store_true",
  16. default=False, help="keep temporary test directories"
  17. )
  18. def pytest_collection_modifyitems(items):
  19. for item in items:
  20. if not hasattr(item, 'module'): # e.g.: DoctestTextfile
  21. continue
  22. # Mark network tests as flaky
  23. if item.get_marker('network') is not None and "CI" in os.environ:
  24. item.add_marker(pytest.mark.flaky(reruns=3))
  25. module_path = os.path.relpath(
  26. item.module.__file__,
  27. os.path.commonprefix([__file__, item.module.__file__]),
  28. )
  29. module_root_dir = module_path.split(os.pathsep)[0]
  30. if (module_root_dir.startswith("functional") or
  31. module_root_dir.startswith("integration") or
  32. module_root_dir.startswith("lib")):
  33. item.add_marker(pytest.mark.integration)
  34. elif module_root_dir.startswith("unit"):
  35. item.add_marker(pytest.mark.unit)
  36. # We don't want to allow using the script resource if this is a
  37. # unit test, as unit tests should not need all that heavy lifting
  38. if set(getattr(item, "funcargnames", [])) & {"script"}:
  39. raise RuntimeError(
  40. "Cannot use the ``script`` funcarg in a unit test: "
  41. "(filename = {}, item = {})".format(module_path, item)
  42. )
  43. else:
  44. raise RuntimeError(
  45. "Unknown test type (filename = {})".format(module_path)
  46. )
  47. @pytest.yield_fixture
  48. def tmpdir(request, tmpdir):
  49. """
  50. Return a temporary directory path object which is unique to each test
  51. function invocation, created as a sub directory of the base temporary
  52. directory. The returned object is a ``tests.lib.path.Path`` object.
  53. This uses the built-in tmpdir fixture from pytest itself but modified
  54. to return our typical path object instead of py.path.local as well as
  55. deleting the temporary directories at the end of each test case.
  56. """
  57. assert tmpdir.isdir()
  58. yield Path(str(tmpdir))
  59. # Clear out the temporary directory after the test has finished using it.
  60. # This should prevent us from needing a multiple gigabyte temporary
  61. # directory while running the tests.
  62. if not request.config.getoption("--keep-tmpdir"):
  63. tmpdir.remove(ignore_errors=True)
  64. @pytest.fixture(autouse=True)
  65. def isolate(tmpdir):
  66. """
  67. Isolate our tests so that things like global configuration files and the
  68. like do not affect our test results.
  69. We use an autouse function scoped fixture because we want to ensure that
  70. every test has it's own isolated home directory.
  71. """
  72. # TODO: Figure out how to isolate from *system* level configuration files
  73. # as well as user level configuration files.
  74. # Create a directory to use as our home location.
  75. home_dir = os.path.join(str(tmpdir), "home")
  76. os.makedirs(home_dir)
  77. # Create a directory to use as a fake root
  78. fake_root = os.path.join(str(tmpdir), "fake-root")
  79. os.makedirs(fake_root)
  80. if sys.platform == 'win32':
  81. # Note: this will only take effect in subprocesses...
  82. home_drive, home_path = os.path.splitdrive(home_dir)
  83. os.environ.update({
  84. 'USERPROFILE': home_dir,
  85. 'HOMEDRIVE': home_drive,
  86. 'HOMEPATH': home_path,
  87. })
  88. for env_var, sub_path in (
  89. ('APPDATA', 'AppData/Roaming'),
  90. ('LOCALAPPDATA', 'AppData/Local'),
  91. ):
  92. path = os.path.join(home_dir, *sub_path.split('/'))
  93. os.environ[env_var] = path
  94. os.makedirs(path)
  95. else:
  96. # Set our home directory to our temporary directory, this should force
  97. # all of our relative configuration files to be read from here instead
  98. # of the user's actual $HOME directory.
  99. os.environ["HOME"] = home_dir
  100. # Isolate ourselves from XDG directories
  101. os.environ["XDG_DATA_HOME"] = os.path.join(home_dir, ".local", "share")
  102. os.environ["XDG_CONFIG_HOME"] = os.path.join(home_dir, ".config")
  103. os.environ["XDG_CACHE_HOME"] = os.path.join(home_dir, ".cache")
  104. os.environ["XDG_RUNTIME_DIR"] = os.path.join(home_dir, ".runtime")
  105. os.environ["XDG_DATA_DIRS"] = ":".join([
  106. os.path.join(fake_root, "usr", "local", "share"),
  107. os.path.join(fake_root, "usr", "share"),
  108. ])
  109. os.environ["XDG_CONFIG_DIRS"] = os.path.join(fake_root, "etc", "xdg")
  110. # Configure git, because without an author name/email git will complain
  111. # and cause test failures.
  112. os.environ["GIT_CONFIG_NOSYSTEM"] = "1"
  113. os.environ["GIT_AUTHOR_NAME"] = "pip"
  114. os.environ["GIT_AUTHOR_EMAIL"] = "pypa-dev@googlegroups.com"
  115. # We want to disable the version check from running in the tests
  116. os.environ["PIP_DISABLE_PIP_VERSION_CHECK"] = "true"
  117. # Make sure tests don't share a requirements tracker.
  118. os.environ.pop('PIP_REQ_TRACKER', None)
  119. # FIXME: Windows...
  120. os.makedirs(os.path.join(home_dir, ".config", "git"))
  121. with open(os.path.join(home_dir, ".config", "git", "config"), "wb") as fp:
  122. fp.write(
  123. b"[user]\n\tname = pip\n\temail = pypa-dev@googlegroups.com\n"
  124. )
  125. @pytest.fixture(scope='session')
  126. def pip_src(tmpdir_factory):
  127. pip_src = Path(str(tmpdir_factory.mktemp('pip_src'))).join('pip_src')
  128. # Copy over our source tree so that each use is self contained
  129. shutil.copytree(
  130. SRC_DIR,
  131. pip_src.abspath,
  132. ignore=shutil.ignore_patterns(
  133. "*.pyc", "__pycache__", "contrib", "docs", "tasks", "*.txt",
  134. "tests", "pip.egg-info", "build", "dist", ".tox", ".git",
  135. ),
  136. )
  137. return pip_src
  138. @pytest.yield_fixture(scope='session')
  139. def virtualenv_template(tmpdir_factory, pip_src):
  140. tmpdir = Path(str(tmpdir_factory.mktemp('virtualenv')))
  141. # Create the virtual environment
  142. venv = VirtualEnvironment.create(
  143. tmpdir.join("venv_orig"),
  144. pip_source_dir=pip_src,
  145. relocatable=True,
  146. )
  147. # Fix `site.py`.
  148. site_py = venv.lib / 'site.py'
  149. with open(site_py) as fp:
  150. site_contents = fp.read()
  151. for pattern, replace in (
  152. (
  153. # Ensure `virtualenv.system_site_packages = True` (needed
  154. # for testing `--user`) does not result in adding the real
  155. # site-packages' directory to `sys.path`.
  156. (
  157. '\ndef virtual_addsitepackages(known_paths):\n'
  158. ),
  159. (
  160. '\ndef virtual_addsitepackages(known_paths):\n'
  161. ' return known_paths\n'
  162. ),
  163. ),
  164. (
  165. # Fix sites ordering: user site must be added before system site.
  166. (
  167. '\n paths_in_sys = addsitepackages(paths_in_sys)'
  168. '\n paths_in_sys = addusersitepackages(paths_in_sys)\n'
  169. ),
  170. (
  171. '\n paths_in_sys = addusersitepackages(paths_in_sys)'
  172. '\n paths_in_sys = addsitepackages(paths_in_sys)\n'
  173. ),
  174. ),
  175. ):
  176. assert pattern in site_contents
  177. site_contents = site_contents.replace(pattern, replace)
  178. with open(site_py, 'w') as fp:
  179. fp.write(site_contents)
  180. if sys.platform == 'win32':
  181. # Work around setuptools' easy_install.exe
  182. # not working properly after relocation.
  183. for exe in os.listdir(venv.bin):
  184. if exe.startswith('easy_install'):
  185. (venv.bin / exe).remove()
  186. with open(venv.bin / 'easy_install.bat', 'w') as fp:
  187. fp.write('python.exe -m easy_install %*\n')
  188. # Rename original virtualenv directory to make sure
  189. # it's not reused by mistake from one of the copies.
  190. venv_template = tmpdir / "venv_template"
  191. os.rename(venv.location, venv_template)
  192. yield venv_template
  193. tmpdir.rmtree(noerrors=True)
  194. @pytest.yield_fixture
  195. def virtualenv(virtualenv_template, tmpdir, isolate):
  196. """
  197. Return a virtual environment which is unique to each test function
  198. invocation created inside of a sub directory of the test function's
  199. temporary directory. The returned object is a
  200. ``tests.lib.venv.VirtualEnvironment`` object.
  201. """
  202. venv_location = tmpdir.join("workspace", "venv")
  203. shutil.copytree(virtualenv_template, venv_location, symlinks=True)
  204. venv = VirtualEnvironment(venv_location)
  205. yield venv
  206. venv_location.rmtree(noerrors=True)
  207. @pytest.fixture
  208. def script(tmpdir, virtualenv):
  209. """
  210. Return a PipTestEnvironment which is unique to each test function and
  211. will execute all commands inside of the unique virtual environment for this
  212. test function. The returned object is a
  213. ``tests.lib.scripttest.PipTestEnvironment``.
  214. """
  215. return PipTestEnvironment(
  216. # The base location for our test environment
  217. tmpdir.join("workspace"),
  218. # Tell the Test Environment where our virtualenv is located
  219. virtualenv=virtualenv.location,
  220. # Do not ignore hidden files, they need to be checked as well
  221. ignore_hidden=False,
  222. # We are starting with an already empty directory
  223. start_clear=False,
  224. # We want to ensure no temporary files are left behind, so the
  225. # PipTestEnvironment needs to capture and assert against temp
  226. capture_temp=True,
  227. assert_no_temp=True,
  228. )
  229. @pytest.fixture(scope="session")
  230. def common_wheels(tmpdir_factory):
  231. """Provide a directory with latest setuptools and wheel wheels"""
  232. wheels_dir = tmpdir_factory.mktemp('common_wheels')
  233. subprocess.check_call([
  234. 'pip', 'download', 'wheel', 'setuptools',
  235. '-d', str(wheels_dir),
  236. ])
  237. yield wheels_dir
  238. wheels_dir.remove(ignore_errors=True)
  239. @pytest.fixture
  240. def data(tmpdir):
  241. return TestData.copy(tmpdir.join("data"))
  242. class InMemoryPipResult(object):
  243. def __init__(self, returncode, stdout):
  244. self.returncode = returncode
  245. self.stdout = stdout
  246. class InMemoryPip(object):
  247. def pip(self, *args):
  248. orig_stdout = sys.stdout
  249. if six.PY3:
  250. stdout = io.StringIO()
  251. else:
  252. stdout = io.BytesIO()
  253. sys.stdout = stdout
  254. try:
  255. returncode = pip._internal.main(list(args))
  256. except SystemExit as e:
  257. returncode = e.code or 0
  258. finally:
  259. sys.stdout = orig_stdout
  260. return InMemoryPipResult(returncode, stdout.getvalue())
  261. @pytest.fixture
  262. def in_memory_pip():
  263. return InMemoryPip()