test_ensurepip.py 11 KB
Newer Older
1 2 3
import unittest
import unittest.mock
import test.support
4 5
import os
import os.path
6 7
import contextlib
import sys
8

9 10
import ensurepip
import ensurepip._uninstall
11

12 13 14 15 16 17 18 19 20 21 22 23 24 25
# pip currently requires ssl support, so we ensure we handle
# it being missing (http://bugs.python.org/issue19744)
ensurepip_no_ssl = test.support.import_fresh_module("ensurepip",
                                                    blocked=["ssl"])
try:
    import ssl
except ImportError:
    def requires_usable_pip(f):
        deco = unittest.skip(ensurepip._MISSING_SSL_MESSAGE)
        return deco(f)
else:
    def requires_usable_pip(f):
        return f

26 27 28 29 30
class TestEnsurePipVersion(unittest.TestCase):

    def test_returns_version(self):
        self.assertEqual(ensurepip._PIP_VERSION, ensurepip.version())

31
class EnsurepipMixin:
32 33 34 35 36 37

    def setUp(self):
        run_pip_patch = unittest.mock.patch("ensurepip._run_pip")
        self.run_pip = run_pip_patch.start()
        self.addCleanup(run_pip_patch.stop)

38
        # Avoid side effects on the actual os module
39
        real_devnull = os.devnull
40 41 42
        os_patch = unittest.mock.patch("ensurepip.os")
        patched_os = os_patch.start()
        self.addCleanup(os_patch.stop)
43
        patched_os.devnull = real_devnull
44 45
        patched_os.path = os.path
        self.os_environ = patched_os.environ = os.environ.copy()
46

47

48 49
class TestBootstrap(EnsurepipMixin, unittest.TestCase):

50
    @requires_usable_pip
51 52 53 54 55 56
    def test_basic_bootstrapping(self):
        ensurepip.bootstrap()

        self.run_pip.assert_called_once_with(
            [
                "install", "--no-index", "--find-links",
57
                unittest.mock.ANY, "setuptools", "pip",
58 59 60 61 62 63 64
            ],
            unittest.mock.ANY,
        )

        additional_paths = self.run_pip.call_args[0][1]
        self.assertEqual(len(additional_paths), 2)

65
    @requires_usable_pip
66 67 68 69 70 71
    def test_bootstrapping_with_root(self):
        ensurepip.bootstrap(root="/foo/bar/")

        self.run_pip.assert_called_once_with(
            [
                "install", "--no-index", "--find-links",
72
                unittest.mock.ANY, "--root", "/foo/bar/",
73 74 75 76 77
                "setuptools", "pip",
            ],
            unittest.mock.ANY,
        )

78
    @requires_usable_pip
79 80 81 82 83 84
    def test_bootstrapping_with_user(self):
        ensurepip.bootstrap(user=True)

        self.run_pip.assert_called_once_with(
            [
                "install", "--no-index", "--find-links",
85
                unittest.mock.ANY, "--user", "setuptools", "pip",
86 87 88 89
            ],
            unittest.mock.ANY,
        )

90
    @requires_usable_pip
91 92 93 94 95 96
    def test_bootstrapping_with_upgrade(self):
        ensurepip.bootstrap(upgrade=True)

        self.run_pip.assert_called_once_with(
            [
                "install", "--no-index", "--find-links",
97
                unittest.mock.ANY, "--upgrade", "setuptools", "pip",
98 99 100 101
            ],
            unittest.mock.ANY,
        )

102
    @requires_usable_pip
103 104 105 106 107 108
    def test_bootstrapping_with_verbosity_1(self):
        ensurepip.bootstrap(verbosity=1)

        self.run_pip.assert_called_once_with(
            [
                "install", "--no-index", "--find-links",
109
                unittest.mock.ANY, "-v", "setuptools", "pip",
110 111 112 113
            ],
            unittest.mock.ANY,
        )

114
    @requires_usable_pip
115 116 117 118 119 120
    def test_bootstrapping_with_verbosity_2(self):
        ensurepip.bootstrap(verbosity=2)

        self.run_pip.assert_called_once_with(
            [
                "install", "--no-index", "--find-links",
121
                unittest.mock.ANY, "-vv", "setuptools", "pip",
122 123 124 125
            ],
            unittest.mock.ANY,
        )

126
    @requires_usable_pip
127 128 129 130 131 132
    def test_bootstrapping_with_verbosity_3(self):
        ensurepip.bootstrap(verbosity=3)

        self.run_pip.assert_called_once_with(
            [
                "install", "--no-index", "--find-links",
133
                unittest.mock.ANY, "-vvv", "setuptools", "pip",
134 135 136 137
            ],
            unittest.mock.ANY,
        )

138
    @requires_usable_pip
139 140 141 142
    def test_bootstrapping_with_regular_install(self):
        ensurepip.bootstrap()
        self.assertEqual(self.os_environ["ENSUREPIP_OPTIONS"], "install")

143
    @requires_usable_pip
144 145 146 147
    def test_bootstrapping_with_alt_install(self):
        ensurepip.bootstrap(altinstall=True)
        self.assertEqual(self.os_environ["ENSUREPIP_OPTIONS"], "altinstall")

148
    @requires_usable_pip
149 150 151 152 153 154 155
    def test_bootstrapping_with_default_pip(self):
        ensurepip.bootstrap(default_pip=True)
        self.assertNotIn("ENSUREPIP_OPTIONS", self.os_environ)

    def test_altinstall_default_pip_conflict(self):
        with self.assertRaises(ValueError):
            ensurepip.bootstrap(altinstall=True, default_pip=True)
156
        self.assertFalse(self.run_pip.called)
157

158
    @requires_usable_pip
159 160 161 162 163 164 165
    def test_pip_environment_variables_removed(self):
        # ensurepip deliberately ignores all pip environment variables
        # See http://bugs.python.org/issue19734 for details
        self.os_environ["PIP_THIS_SHOULD_GO_AWAY"] = "test fodder"
        ensurepip.bootstrap()
        self.assertNotIn("PIP_THIS_SHOULD_GO_AWAY", self.os_environ)

166 167 168 169 170 171
    @requires_usable_pip
    def test_pip_config_file_disabled(self):
        # ensurepip deliberately ignores the pip config file
        # See http://bugs.python.org/issue20053 for details
        ensurepip.bootstrap()
        self.assertEqual(self.os_environ["PIP_CONFIG_FILE"], os.devnull)
172

173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
@contextlib.contextmanager
def fake_pip(version=ensurepip._PIP_VERSION):
    if version is None:
        pip = None
    else:
        class FakePip():
            __version__ = version
        pip = FakePip()
    sentinel = object()
    orig_pip = sys.modules.get("pip", sentinel)
    sys.modules["pip"] = pip
    try:
        yield pip
    finally:
        if orig_pip is sentinel:
            del sys.modules["pip"]
        else:
            sys.modules["pip"] = orig_pip

192
class TestUninstall(EnsurepipMixin, unittest.TestCase):
193

194 195
    def test_uninstall_skipped_when_not_installed(self):
        with fake_pip(None):
196
            ensurepip._uninstall_helper()
197
        self.assertFalse(self.run_pip.called)
198

199
    def test_uninstall_skipped_with_warning_for_wrong_version(self):
200
        with fake_pip("not a valid version"):
201
            with test.support.captured_stderr() as stderr:
202
                ensurepip._uninstall_helper()
203 204
        warning = stderr.getvalue().strip()
        self.assertIn("only uninstall a matching version", warning)
205
        self.assertFalse(self.run_pip.called)
206 207


208
    @requires_usable_pip
209 210
    def test_uninstall(self):
        with fake_pip():
211
            ensurepip._uninstall_helper()
212 213 214 215 216

        self.run_pip.assert_called_once_with(
            ["uninstall", "-y", "pip", "setuptools"]
        )

217
    @requires_usable_pip
218 219
    def test_uninstall_with_verbosity_1(self):
        with fake_pip():
220
            ensurepip._uninstall_helper(verbosity=1)
221 222 223 224 225

        self.run_pip.assert_called_once_with(
            ["uninstall", "-y", "-v", "pip", "setuptools"]
        )

226
    @requires_usable_pip
227 228
    def test_uninstall_with_verbosity_2(self):
        with fake_pip():
229
            ensurepip._uninstall_helper(verbosity=2)
230 231 232 233 234

        self.run_pip.assert_called_once_with(
            ["uninstall", "-y", "-vv", "pip", "setuptools"]
        )

235
    @requires_usable_pip
236 237
    def test_uninstall_with_verbosity_3(self):
        with fake_pip():
238
            ensurepip._uninstall_helper(verbosity=3)
239 240 241 242 243

        self.run_pip.assert_called_once_with(
            ["uninstall", "-y", "-vvv", "pip", "setuptools"]
        )

244
    @requires_usable_pip
245 246 247 248 249
    def test_pip_environment_variables_removed(self):
        # ensurepip deliberately ignores all pip environment variables
        # See http://bugs.python.org/issue19734 for details
        self.os_environ["PIP_THIS_SHOULD_GO_AWAY"] = "test fodder"
        with fake_pip():
250
            ensurepip._uninstall_helper()
251
        self.assertNotIn("PIP_THIS_SHOULD_GO_AWAY", self.os_environ)
252

253 254 255 256 257 258 259 260
    @requires_usable_pip
    def test_pip_config_file_disabled(self):
        # ensurepip deliberately ignores the pip config file
        # See http://bugs.python.org/issue20053 for details
        with fake_pip():
            ensurepip._uninstall_helper()
        self.assertEqual(self.os_environ["PIP_CONFIG_FILE"], os.devnull)

261

262 263 264 265 266 267 268 269 270 271 272 273 274
class TestMissingSSL(EnsurepipMixin, unittest.TestCase):

    def setUp(self):
        sys.modules["ensurepip"] = ensurepip_no_ssl
        @self.addCleanup
        def restore_module():
            sys.modules["ensurepip"] = ensurepip
        super().setUp()

    def test_bootstrap_requires_ssl(self):
        self.os_environ["PIP_THIS_SHOULD_STAY"] = "test fodder"
        with self.assertRaisesRegex(RuntimeError, "requires SSL/TLS"):
            ensurepip_no_ssl.bootstrap()
275
        self.assertFalse(self.run_pip.called)
276 277 278 279 280 281 282
        self.assertIn("PIP_THIS_SHOULD_STAY", self.os_environ)

    def test_uninstall_requires_ssl(self):
        self.os_environ["PIP_THIS_SHOULD_STAY"] = "test fodder"
        with self.assertRaisesRegex(RuntimeError, "requires SSL/TLS"):
            with fake_pip():
                ensurepip_no_ssl._uninstall_helper()
283
        self.assertFalse(self.run_pip.called)
284 285
        self.assertIn("PIP_THIS_SHOULD_STAY", self.os_environ)

286 287 288 289 290
    def test_main_exits_early_with_warning(self):
        with test.support.captured_stderr() as stderr:
            ensurepip_no_ssl._main(["--version"])
        warning = stderr.getvalue().strip()
        self.assertTrue(warning.endswith("requires SSL/TLS"), warning)
291
        self.assertFalse(self.run_pip.called)
292

293 294 295 296 297 298
# Basic testing of the main functions and their argument parsing

EXPECTED_VERSION_OUTPUT = "pip " + ensurepip._PIP_VERSION

class TestBootstrappingMainFunction(EnsurepipMixin, unittest.TestCase):

299
    @requires_usable_pip
300 301 302 303 304 305
    def test_bootstrap_version(self):
        with test.support.captured_stdout() as stdout:
            with self.assertRaises(SystemExit):
                ensurepip._main(["--version"])
        result = stdout.getvalue().strip()
        self.assertEqual(result, EXPECTED_VERSION_OUTPUT)
306
        self.assertFalse(self.run_pip.called)
307

308
    @requires_usable_pip
309 310 311 312 313 314
    def test_basic_bootstrapping(self):
        ensurepip._main([])

        self.run_pip.assert_called_once_with(
            [
                "install", "--no-index", "--find-links",
315
                unittest.mock.ANY, "setuptools", "pip",
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
            ],
            unittest.mock.ANY,
        )

        additional_paths = self.run_pip.call_args[0][1]
        self.assertEqual(len(additional_paths), 2)

class TestUninstallationMainFunction(EnsurepipMixin, unittest.TestCase):

    def test_uninstall_version(self):
        with test.support.captured_stdout() as stdout:
            with self.assertRaises(SystemExit):
                ensurepip._uninstall._main(["--version"])
        result = stdout.getvalue().strip()
        self.assertEqual(result, EXPECTED_VERSION_OUTPUT)
331
        self.assertFalse(self.run_pip.called)
332

333
    @requires_usable_pip
334 335 336 337 338 339 340 341 342
    def test_basic_uninstall(self):
        with fake_pip():
            ensurepip._uninstall._main([])

        self.run_pip.assert_called_once_with(
            ["uninstall", "-y", "pip", "setuptools"]
        )


343 344

if __name__ == "__main__":
345
    unittest.main()