diff --git a/mypy/test/testpep561.py b/mypy/test/testpep561.py index 5d2e3a5963e3..7cb65aa487d1 100644 --- a/mypy/test/testpep561.py +++ b/mypy/test/testpep561.py @@ -29,6 +29,19 @@ def check_mypy_run(cmd_line: List[str], assert returncode == expected_returncode, returncode +def is_in_venv() -> bool: + """Returns whether we are running inside a venv. + + Based on https://stackoverflow.com/a/42580137. + + """ + if hasattr(sys, 'real_prefix'): + return True + else: + # https://github.com/python/typeshed/pull/2047 + return hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix # type: ignore + + class TestPEP561(TestCase): @contextmanager def install_package(self, pkg: str, @@ -38,9 +51,7 @@ def install_package(self, pkg: str, install_cmd = [python_executable, '-m', 'pip', 'install', '.'] # if we aren't in a virtualenv, install in the # user package directory so we don't need sudo - # In a virtualenv, real_prefix is patched onto - # sys - if not hasattr(sys, 'real_prefix') or python_executable != sys.executable: + if not is_in_venv() or python_executable != sys.executable: install_cmd.append('--user') returncode, lines = run_command(install_cmd, cwd=working_dir) if returncode != 0: