1import os
2import contextlib
3import sys
4import subprocess
5from pathlib import Path
6
7import pytest
8import path
9
10from . import contexts, environment
11
12
13@pytest.fixture
14def user_override(monkeypatch):
15    """
16    Override site.USER_BASE and site.USER_SITE with temporary directories in
17    a context.
18    """
19    with contexts.tempdir() as user_base:
20        monkeypatch.setattr('site.USER_BASE', user_base)
21        with contexts.tempdir() as user_site:
22            monkeypatch.setattr('site.USER_SITE', user_site)
23            with contexts.save_user_site_setting():
24                yield
25
26
27@pytest.fixture
28def tmpdir_cwd(tmpdir):
29    with tmpdir.as_cwd() as orig:
30        yield orig
31
32
33@pytest.fixture(autouse=True, scope="session")
34def workaround_xdist_376(request):
35    """
36    Workaround pytest-dev/pytest-xdist#376
37
38    ``pytest-xdist`` tends to inject '' into ``sys.path``,
39    which may break certain isolation expectations.
40    Remove the entry so the import
41    machinery behaves the same irrespective of xdist.
42    """
43    if not request.config.pluginmanager.has_plugin('xdist'):
44        return
45
46    with contextlib.suppress(ValueError):
47        sys.path.remove('')
48
49
50@pytest.fixture
51def sample_project(tmp_path):
52    """
53    Clone the 'sampleproject' and return a path to it.
54    """
55    cmd = ['git', 'clone', 'https://github.com/pypa/sampleproject']
56    try:
57        subprocess.check_call(cmd, cwd=str(tmp_path))
58    except Exception:
59        pytest.skip("Unable to clone sampleproject")
60    return tmp_path / 'sampleproject'
61
62
63# sdist and wheel artifacts should be stable across a round of tests
64# so we can build them once per session and use the files as "readonly"
65
66
67@pytest.fixture(scope="session")
68def setuptools_sdist(tmp_path_factory, request):
69    if os.getenv("PRE_BUILT_SETUPTOOLS_SDIST"):
70        return Path(os.getenv("PRE_BUILT_SETUPTOOLS_SDIST")).resolve()
71
72    with contexts.session_locked_tmp_dir(
73            request, tmp_path_factory, "sdist_build") as tmp:
74        dist = next(tmp.glob("*.tar.gz"), None)
75        if dist:
76            return dist
77
78        subprocess.check_call([
79            sys.executable, "-m", "build", "--sdist",
80            "--outdir", str(tmp), str(request.config.rootdir)
81        ])
82        return next(tmp.glob("*.tar.gz"))
83
84
85@pytest.fixture(scope="session")
86def setuptools_wheel(tmp_path_factory, request):
87    if os.getenv("PRE_BUILT_SETUPTOOLS_WHEEL"):
88        return Path(os.getenv("PRE_BUILT_SETUPTOOLS_WHEEL")).resolve()
89
90    with contexts.session_locked_tmp_dir(
91            request, tmp_path_factory, "wheel_build") as tmp:
92        dist = next(tmp.glob("*.whl"), None)
93        if dist:
94            return dist
95
96        subprocess.check_call([
97            sys.executable, "-m", "build", "--wheel",
98            "--outdir", str(tmp) , str(request.config.rootdir)
99        ])
100        return next(tmp.glob("*.whl"))
101
102
103@pytest.fixture
104def venv(tmp_path, setuptools_wheel):
105    """Virtual env with the version of setuptools under test installed"""
106    env = environment.VirtualEnv()
107    env.root = path.Path(tmp_path / 'venv')
108    env.req = str(setuptools_wheel)
109    # In some environments (eg. downstream distro packaging),
110    # where tox isn't used to run tests and PYTHONPATH is set to point to
111    # a specific setuptools codebase, PYTHONPATH will leak into the spawned
112    # processes.
113    # env.create() should install the just created setuptools
114    # wheel, but it doesn't if it finds another existing matching setuptools
115    # installation present on PYTHONPATH:
116    # `setuptools is already installed with the same version as the provided
117    # wheel. Use --force-reinstall to force an installation of the wheel.`
118    # This prevents leaking PYTHONPATH to the created environment.
119    with contexts.environment(PYTHONPATH=None):
120        return env.create()
121
122
123@pytest.fixture
124def venv_without_setuptools(tmp_path):
125    """Virtual env without any version of setuptools installed"""
126    env = environment.VirtualEnv()
127    env.root = path.Path(tmp_path / 'venv_without_setuptools')
128    env.create_opts = ['--no-setuptools']
129    env.ensure_env()
130    return env
131
132
133@pytest.fixture
134def bare_venv(tmp_path):
135    """Virtual env without any common packages installed"""
136    env = environment.VirtualEnv()
137    env.root = path.Path(tmp_path / 'bare_venv')
138    env.create_opts = ['--no-setuptools', '--no-pip', '--no-wheel', '--no-seed']
139    env.ensure_env()
140    return env
141