Skip to content

Commit

Permalink
Check current python version
Browse files Browse the repository at this point in the history
  • Loading branch information
yokomotod committed Feb 7, 2022
1 parent 31657e7 commit 8b60bf2
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/poetry/utils/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -453,6 +453,17 @@ def __init__(self, expected: str, given: Optional[str] = None) -> None:
super().__init__(message)


class InvalidCurrentPythonVersionError(EnvError):
def __init__(self, expected: str, given: str) -> None:
message = (
f"Current Python version ({given}) "
f"is not allowed by the project ({expected}).\n"
'Please change python executable via the "env use" command.'
)

super().__init__(message)


class EnvManager:
"""
Environments manager
Expand Down Expand Up @@ -812,6 +823,13 @@ def create_venv(

if env.is_venv() and not force:
# Already inside a virtualenv.
current_python = Version.parse(
".".join(str(c) for c in env.version_info[:3])
)
if not self._poetry.package.python_constraint.allows(current_python):
raise InvalidCurrentPythonVersionError(
self._poetry.package.python_versions, current_python
)
return env

create_venv = self._poetry.config.get("virtualenvs.create")
Expand Down
28 changes: 28 additions & 0 deletions tests/utils/test_env.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
from poetry.utils.env import EnvCommandError
from poetry.utils.env import EnvManager
from poetry.utils.env import GenericEnv
from poetry.utils.env import InvalidCurrentPythonVersionError
from poetry.utils.env import NoCompatiblePythonVersionFound
from poetry.utils.env import SystemEnv
from poetry.utils.env import VirtualEnv
Expand Down Expand Up @@ -994,6 +995,33 @@ def test_create_venv_uses_patch_version_to_detect_compatibility_with_executable(
)


def test_create_venv_fails_if_current_python_version_is_not_supported(
manager: EnvManager, poetry: "Poetry"
):
if "VIRTUAL_ENV" in os.environ:
del os.environ["VIRTUAL_ENV"]

manager.create_venv(NullIO())

current_version = Version.parse(".".join(str(c) for c in sys.version_info[:3]))
next_version = ".".join(
str(c) for c in (current_version.major, current_version.minor + 1, 0)
)
package_version = "~" + next_version
poetry.package.python_versions = package_version

with pytest.raises(InvalidCurrentPythonVersionError) as e:
manager.create_venv(NullIO())

expected_message = (
f"Current Python version ({current_version}) is not allowed by the project"
f' ({package_version}).\nPlease change python executable via the "env use"'
" command."
)

assert expected_message == str(e.value)


def test_activate_with_in_project_setting_does_not_fail_if_no_venvs_dir(
manager: EnvManager,
poetry: "Poetry",
Expand Down

0 comments on commit 8b60bf2

Please sign in to comment.