diff --git a/src/poetry/utils/password_manager.py b/src/poetry/utils/password_manager.py index 78a5559b2ae..e687711b5db 100644 --- a/src/poetry/utils/password_manager.py +++ b/src/poetry/utils/password_manager.py @@ -170,12 +170,21 @@ def set_pypi_token(self, name: str, token: str) -> None: else: self.keyring.set_password(name, "__token__", token) - def get_pypi_token(self, name: str) -> str | None: - if not self.keyring.is_available(): - token: str | None = self._config.get(f"pypi-token.{name}") + def get_pypi_token(self, repo_name: str) -> str | None: + """Get PyPi token. + + First checks the environment variables for a token, + then the configured username/password and the + available keyring. + + :param repo_name: Name of repository. + :return: Returns a token as a string if found, otherwise None. + """ + token: str | None = self._config.get(f"pypi-token.{repo_name}") + if token: return token - return self.keyring.get_password(name, "__token__") + return self.keyring.get_password(repo_name, "__token__") def delete_pypi_token(self, name: str) -> None: if not self.keyring.is_available(): diff --git a/tests/utils/test_password_manager.py b/tests/utils/test_password_manager.py index 5859069ed0a..468ef14f689 100644 --- a/tests/utils/test_password_manager.py +++ b/tests/utils/test_password_manager.py @@ -231,3 +231,31 @@ def test_get_http_auth_from_environment_variables( assert auth["username"] == "bar" assert auth["password"] == "baz" + + +def test_get_pypi_token_with_env_var_positive( + mocker: MockerFixture, + config: Config, + with_simple_keyring: None, + dummy_keyring: DummyBackend, +): + sample_token = "sampletoken-1234" + repo_name = "foo" + manager = PasswordManager(config) + mocker.patch.dict( + os.environ, + {f"POETRY_PYPI_TOKEN_{repo_name.upper()}": sample_token}, + ) + + assert manager.get_pypi_token(repo_name) == sample_token + + +def test_get_pypi_token_with_env_var_not_available( + config: Config, with_simple_keyring: None, dummy_keyring: DummyBackend +): + repo_name = "foo" + manager = PasswordManager(config) + + result_token = manager.get_pypi_token(repo_name) + + assert result_token is None