pip/tests/lib/test_lib.py

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

260 lines
8.4 KiB
Python
Raw Normal View History

"""Test the test support."""
2013-05-28 23:58:08 +02:00
import filecmp
import pathlib
2013-05-28 23:58:08 +02:00
import re
import sys
from contextlib import contextmanager
2017-05-16 12:16:30 +02:00
from os.path import isdir, join
from typing import Any, Dict, Iterator, Type
2013-05-28 23:58:08 +02:00
import pytest
from tests.lib import SRC_DIR, PipTestEnvironment
2012-07-29 05:34:06 +02:00
@contextmanager
def assert_error_startswith(
exc_type: Type[Exception], expected_start: str
) -> Iterator[None]:
"""
Assert that an exception is raised starting with a certain message.
"""
with pytest.raises(exc_type) as err:
yield
2021-04-02 11:21:40 +02:00
assert str(err.value).startswith(expected_start), f"full message: {err.value}"
def test_tmp_dir_exists_in_env(script: PipTestEnvironment) -> None:
2012-07-29 05:34:06 +02:00
"""
Test that $TMPDIR == env.temp_path and path exists and env.assert_no_temp()
passes (in fast env)
2012-07-29 05:34:06 +02:00
"""
# need these tests to ensure the assert_no_temp feature of scripttest is
# working
script.assert_no_temp() # this fails if env.tmp_path doesn't exist
assert pathlib.Path(script.environ["TMPDIR"]) == script.temp_path
assert isdir(script.temp_path)
2013-05-28 23:58:08 +02:00
def test_correct_pip_version(script: PipTestEnvironment) -> None:
2013-05-28 23:58:08 +02:00
"""
Check we are running proper version of pip in run_pip.
"""
if script.zipapp:
pytest.skip("Test relies on the pip under test being in the filesystem")
2013-05-28 23:58:08 +02:00
# output is like:
# pip PIPVERSION from PIPDIRECTORY (python PYVERSION)
2021-04-02 11:21:40 +02:00
result = script.pip("--version")
2013-05-28 23:58:08 +02:00
# compare the directory tree of the invoked pip with that of this source
# distribution
match = re.match(
2021-04-02 11:21:40 +02:00
r"pip \d+(\.[\d]+)+(\.?(b|rc|dev|pre|post)\d+)? from (.*) "
r"\(python \d+(\.[\d]+)+\)$",
2021-04-02 11:21:40 +02:00
result.stdout,
)
assert match is not None
pip_folder_outputed = match.group(4)
2021-04-02 11:21:40 +02:00
pip_folder = join(SRC_DIR, "src", "pip")
2013-05-28 23:58:08 +02:00
diffs = filecmp.dircmp(pip_folder, pip_folder_outputed)
# If any non-matching .py files exist, we have a problem: run_pip
# is picking up some other version! N.B. if this project acquires
# primary resources other than .py files, this code will need
# maintenance
mismatch_py = [
2021-04-02 11:21:40 +02:00
x
for x in diffs.left_only + diffs.right_only + diffs.diff_files
if x.endswith(".py")
]
assert not mismatch_py, (
2021-04-02 11:21:40 +02:00
f"mismatched source files in {pip_folder!r} "
f"and {pip_folder_outputed!r}: {mismatch_py!r}"
)
def test_as_import(script: PipTestEnvironment) -> None:
2021-04-02 11:21:40 +02:00
"""test that pip.__init__.py does not shadow
the command submodule with a dictionary
"""
import pip._internal.commands.install as inst
2021-04-02 11:21:40 +02:00
assert inst is not None
class TestPipTestEnvironment:
def run_stderr_with_prefix(
self, script: PipTestEnvironment, prefix: str, **kwargs: Any
) -> None:
"""
Call run() that prints stderr with the given prefix.
"""
2021-04-02 11:21:40 +02:00
text = f"{prefix}: hello, world\\n"
command = f'import sys; sys.stderr.write("{text}")'
2021-04-02 11:21:40 +02:00
args = [sys.executable, "-c", command]
script.run(*args, **kwargs)
def run_with_log_command(
self, script: PipTestEnvironment, sub_string: str, **kwargs: Any
) -> None:
"""
Call run() on a command that logs a "%"-style format string using
the given substring as the string's replacement field.
"""
command = (
"import logging; logging.basicConfig(level='INFO'); "
2023-11-07 10:14:56 +01:00
f"logging.getLogger().info('sub: {sub_string}', 'foo')"
)
2021-04-02 11:21:40 +02:00
args = [sys.executable, "-c", command]
script.run(*args, **kwargs)
2021-04-02 11:21:40 +02:00
@pytest.mark.parametrize(
"prefix",
(
"DEBUG",
"INFO",
"FOO",
),
)
def test_run__allowed_stderr(self, script: PipTestEnvironment, prefix: str) -> None:
"""
Test calling run() with allowed stderr.
"""
# Check that no error happens.
self.run_stderr_with_prefix(script, prefix)
def test_run__allow_stderr_warning(self, script: PipTestEnvironment) -> None:
"""
Test passing allow_stderr_warning=True.
"""
# Check that no error happens.
self.run_stderr_with_prefix(
2021-04-02 11:21:40 +02:00
script,
"WARNING",
allow_stderr_warning=True,
)
# Check that an error still happens with ERROR.
2021-04-02 11:21:40 +02:00
expected_start = "stderr has an unexpected error"
with assert_error_startswith(RuntimeError, expected_start):
self.run_stderr_with_prefix(
2021-04-02 11:21:40 +02:00
script,
"ERROR",
allow_stderr_warning=True,
)
2021-04-02 11:21:40 +02:00
@pytest.mark.parametrize(
"prefix",
(
"WARNING",
"ERROR",
),
)
def test_run__allow_stderr_error(
self, script: PipTestEnvironment, prefix: str
) -> None:
"""
Test passing allow_stderr_error=True.
"""
# Check that no error happens.
self.run_stderr_with_prefix(script, prefix, allow_stderr_error=True)
2021-04-02 11:21:40 +02:00
@pytest.mark.parametrize(
"prefix, expected_start",
(
("WARNING", "stderr has an unexpected warning"),
("ERROR", "stderr has an unexpected error"),
),
)
def test_run__unexpected_stderr(
self, script: PipTestEnvironment, prefix: str, expected_start: str
) -> None:
"""
Test calling run() with unexpected stderr output.
"""
with assert_error_startswith(RuntimeError, expected_start):
self.run_stderr_with_prefix(script, prefix)
def test_run__logging_error(self, script: PipTestEnvironment) -> None:
"""
Test calling run() with an unexpected logging error.
"""
# Pass a good substitution string.
2021-04-02 11:21:40 +02:00
self.run_with_log_command(script, sub_string="%r")
2021-04-02 11:21:40 +02:00
expected_start = "stderr has a logging error, which is never allowed"
with assert_error_startswith(RuntimeError, expected_start):
2019-05-07 12:51:42 +02:00
# Pass a bad substitution string. Also, pass
# allow_stderr_error=True to check that the RuntimeError occurs
# even under the stricter test condition of when we are allowing
# other types of errors.
self.run_with_log_command(
2021-04-02 11:21:40 +02:00
script,
sub_string="{!r}",
allow_stderr_error=True,
2019-05-07 12:51:42 +02:00
)
def test_run__allow_stderr_error_false_error_with_expect_error(
self, script: PipTestEnvironment
) -> None:
"""
Test passing allow_stderr_error=False with expect_error=True.
"""
2021-04-02 11:21:40 +02:00
expected_start = "cannot pass allow_stderr_error=False with expect_error=True"
with assert_error_startswith(RuntimeError, expected_start):
2021-04-02 11:21:40 +02:00
script.run("python", allow_stderr_error=False, expect_error=True)
def test_run__allow_stderr_warning_false_error_with_expect_stderr(
self, script: PipTestEnvironment
) -> None:
"""
Test passing allow_stderr_warning=False with expect_stderr=True.
"""
expected_start = (
2021-04-02 11:21:40 +02:00
"cannot pass allow_stderr_warning=False with expect_stderr=True"
)
with assert_error_startswith(RuntimeError, expected_start):
script.run(
2021-04-02 11:21:40 +02:00
"python",
allow_stderr_warning=False,
expect_stderr=True,
)
2021-04-02 11:21:40 +02:00
@pytest.mark.parametrize(
"arg_name",
(
"expect_error",
"allow_stderr_error",
),
)
def test_run__allow_stderr_warning_false_error(
self, script: PipTestEnvironment, arg_name: str
) -> None:
"""
Test passing allow_stderr_warning=False when it is not allowed.
"""
kwargs: Dict[str, Any] = {"allow_stderr_warning": False, arg_name: True}
expected_start = (
"cannot pass allow_stderr_warning=False with allow_stderr_error=True"
)
with assert_error_startswith(RuntimeError, expected_start):
2021-04-02 11:21:40 +02:00
script.run("python", **kwargs)
def test_run__expect_error_fails_when_zero_returncode(
self, script: PipTestEnvironment
) -> None:
2021-04-02 11:21:40 +02:00
expected_start = "Script passed unexpectedly"
with assert_error_startswith(AssertionError, expected_start):
2021-04-02 11:21:40 +02:00
script.run("python", expect_error=True)
def test_run__no_expect_error_fails_when_nonzero_returncode(
self, script: PipTestEnvironment
) -> None:
2021-04-02 11:21:40 +02:00
expected_start = "Script returned code: 1"
with assert_error_startswith(AssertionError, expected_start):
2021-04-02 11:21:40 +02:00
script.run("python", "-c", "import sys; sys.exit(1)")