def test_keyring_set_password( monkeypatch: pytest.MonkeyPatch, response_status: int, creds: Tuple[str, str, bool], expect_save: bool, ) -> None: keyring = KeyringModuleV1() monkeypatch.setattr("pip._internal.network.auth.keyring", keyring) auth = MultiDomainBasicAuth(prompting=True) monkeypatch.setattr(auth, "_get_url_and_credentials", lambda u: (u, None, None)) monkeypatch.setattr(auth, "_prompt_for_password", lambda *a: creds) if creds[2]: # when _prompt_for_password indicates to save, we should save def should_save_password_to_keyring(*a: Any) -> bool: return True else: # when _prompt_for_password indicates not to save, we should # never call this function def should_save_password_to_keyring(*a: Any) -> bool: assert False, "_should_save_password_to_keyring should not be called" monkeypatch.setattr(auth, "_should_save_password_to_keyring", should_save_password_to_keyring) req = MockRequest("https://example.com") resp = MockResponse(b"") resp.url = req.url connection = MockConnection() def _send(sent_req: MockRequest, **kwargs: Any) -> MockResponse: assert sent_req is req assert "Authorization" in sent_req.headers r = MockResponse(b"") r.status_code = response_status return r # https://github.com/python/mypy/issues/2427 connection._send = _send # type: ignore[assignment] resp.request = req resp.status_code = 401 resp.connection = connection auth.handle_401(resp) if expect_save: assert keyring.saved_passwords == [("example.com", creds[0], creds[1])] else: assert keyring.saved_passwords == []
def test_keyring_set_password(monkeypatch, response_status, creds, expect_save): keyring = KeyringModuleV1() monkeypatch.setattr('pip._internal.network.auth.keyring', keyring) auth = MultiDomainBasicAuth(prompting=True) monkeypatch.setattr(auth, '_get_url_and_credentials', lambda u: (u, None, None)) monkeypatch.setattr(auth, '_prompt_for_password', lambda *a: creds) if creds[2]: # when _prompt_for_password indicates to save, we should save def should_save_password_to_keyring(*a): return True else: # when _prompt_for_password indicates not to save, we should # never call this function def should_save_password_to_keyring(*a): assert False, ("_should_save_password_to_keyring should not be " + "called") monkeypatch.setattr(auth, '_should_save_password_to_keyring', should_save_password_to_keyring) req = MockRequest("https://example.com") resp = MockResponse(b"") resp.url = req.url connection = MockConnection() def _send(sent_req, **kwargs): assert sent_req is req assert "Authorization" in sent_req.headers r = MockResponse(b"") r.status_code = response_status return r connection._send = _send resp.request = req resp.status_code = 401 resp.connection = connection auth.handle_401(resp) if expect_save: assert keyring.saved_passwords == [("example.com", creds[0], creds[1])] else: assert keyring.saved_passwords == []