Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cache the user agent #12563

Merged
merged 2 commits into from
Apr 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/pip/_internal/network/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"""

import email.utils
import functools
import io
import ipaddress
import json
Expand Down Expand Up @@ -106,6 +107,7 @@ def looks_like_ci() -> bool:
return any(name in os.environ for name in CI_ENVIRONMENT_VARIABLES)


@functools.lru_cache(maxsize=1)
def user_agent() -> str:
"""
Return a string representing the user agent.
Expand Down
11 changes: 9 additions & 2 deletions tests/unit/test_network_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,17 @@

from pip import __version__
from pip._internal.models.link import Link
from pip._internal.network.session import CI_ENVIRONMENT_VARIABLES, PipSession
from pip._internal.network.session import (
CI_ENVIRONMENT_VARIABLES,
PipSession,
user_agent,
)


def get_user_agent() -> str:
# These tests are testing the computation of the user agent, so we want to
# avoid reusing cached values.
user_agent.cache_clear()
return PipSession().headers["User-Agent"]


Expand Down Expand Up @@ -58,7 +65,7 @@ def test_user_agent__ci(

def test_user_agent_user_data(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("PIP_USER_AGENT_USER_DATA", "some_string")
assert "some_string" in PipSession().headers["User-Agent"]
assert "some_string" in get_user_agent()


class TestPipSession:
Expand Down
Loading