← eval4_submission

requests_6644

resolved RESOLVED PASS · 28 tool calls · 70 s · psf/requests

Task input

Trim excess leading path separators

A URL with excess leading / (path-separator)s would cause urllib3 to attempt to reparse the request-uri as a full URI with a host and port. This bypasses that logic in ConnectionPool.urlopen by replacing these leading /s with just a single /.

Closes #6643

Tool calls (29)

#ToolArgumentsResult
1run_command
{
 "command": "grep -rn \"ConnectionPool.urlopen\" src | head -20"
}
{"status": "ok", "stdout": "", "exit_code": 0}
full
{"status": "ok", "stdout": "", "exit_code": 0}
2run_command
{
 "command": "grep -rn \"urlopen\" src | head -20"
}
{"status": "ok", "stdout": "src/requests/adapters.py:485: resp = conn.urlopen(\n", "exit_code": 0}
full
{"status": "ok", "stdout": "src/requests/adapters.py:485:            resp = conn.urlopen(\n", "exit_code": 0}
3read_file
{
 "filepath": "src/requests/adapters.py",
 "start_line": 470,
 "end_line": 500
}
{"status": "ok", "filepath": "src/requests/adapters.py", "content": " if isinstance(timeout, tuple):\n try:\n connect, read = timeout\n timeout = TimeoutSauce(c
full
{"status": "ok", "filepath": "src/requests/adapters.py", "content": "        if isinstance(timeout, tuple):\n            try:\n                connect, read = timeout\n                timeout = TimeoutSauce(connect=connect, read=read)\n            except ValueError:\n                raise ValueError(\n                    f\"Invalid timeout {timeout}. Pass a (connect, read) timeout tuple, \"\n                    f\"or a single float to set both timeouts to the same value.\"\n                )\n        elif isinstance(timeout, TimeoutSauce):\n            pass\n        else:\n            timeout = TimeoutSauce(connect=timeout, read=timeout)\n\n        try:\n            resp = conn.urlopen(\n                method=request.method,\n                url=url,\n                body=request.body,\n                headers=request.headers,\n                redirect=False,\n                assert_same_host=False,\n                preload_content=False,\n                decode_content=False,\n                retries=self.max_retries,\n                timeout=timeout,\n                chunked=chunked,\n            )\n\n        except (ProtocolError, OSError) as err:\n            raise ConnectionError(err, request=request)\n", "start_line": 470, "end_line": 500, "total_lines": 537, "is_truncated": false}
4run_command
{
 "command": "grep -rn \"path\" src/requests/models.py"
}
{"status": "ok", "stdout": "86: def path_url(self):\n87: \"\"\"Build the path URL to use.\"\"\"\n93: path = p.path\n94: if not path:\n95: path = \"/\"\n97: url.
full
{"status": "ok", "stdout": "86:    def path_url(self):\n87:        \"\"\"Build the path URL to use.\"\"\"\n93:        path = p.path\n94:        if not path:\n95:            path = \"/\"\n97:        url.append(path)\n431:        # Support for unicode domain names and paths.\n433:            scheme, auth, host, port, path, query, fragment = parse_url(url)\n467:        if not path:\n468:            path = \"/\"\n480:        url = requote_uri(urlunparse([scheme, netloc, path, None, query, fragment]))\n", "exit_code": 0}
5read_file
{
 "end_line": 100,
 "filepath": "src/requests/models.py",
 "start_line": 80
}
{"status": "ok", "filepath": "src/requests/models.py", "content": "CONTENT_CHUNK_SIZE = 10 * 1024\nITER_CHUNK_SIZE = 512\n\n\nclass RequestEncodingMixin:\n @pro
full
{"status": "ok", "filepath": "src/requests/models.py", "content": "CONTENT_CHUNK_SIZE = 10 * 1024\nITER_CHUNK_SIZE = 512\n\n\nclass RequestEncodingMixin:\n    @property\n    def path_url(self):\n        \"\"\"Build the path URL to use.\"\"\"\n\n        url = []\n\n        p = urlsplit(self.url)\n\n        path = p.path\n        if not path:\n            path = \"/\"\n\n        url.append(path)\n\n        query = p.query\n        if query:\n", "start_line": 80, "end_line": 100, "total_lines": 1032, "is_truncated": false}
6run_command
{
 "command": "grep -rn \"prepare_url\" src/requests/models.py"
}
{"status": "ok", "stdout": "367: self.prepare_url(url, params)\n409: def prepare_url(self, url, params):\n", "exit_code": 0}
full
{"status": "ok", "stdout": "367:        self.prepare_url(url, params)\n409:    def prepare_url(self, url, params):\n", "exit_code": 0}
7read_file
{
 "end_line": 430,
 "filepath": "src/requests/models.py",
 "start_line": 400
}
{"status": "ok", "filepath": "src/requests/models.py", "content": " def _get_idna_encoded_host(host):\n import idna\n\n try:\n host = idna.encode(host, uts46=Tr
full
{"status": "ok", "filepath": "src/requests/models.py", "content": "    def _get_idna_encoded_host(host):\n        import idna\n\n        try:\n            host = idna.encode(host, uts46=True).decode(\"utf-8\")\n        except idna.IDNAError:\n            raise UnicodeError\n        return host\n\n    def prepare_url(self, url, params):\n        \"\"\"Prepares the given HTTP URL.\"\"\"\n        #: Accept objects that have string representations.\n        #: We're unable to blindly call unicode/str functions\n        #: as this will include the bytestring indicator (b'')\n        #: on python 3.x.\n        #: https://github.com/psf/requests/pull/2238\n        if isinstance(url, bytes):\n            url = url.decode(\"utf8\")\n        else:\n            url = str(url)\n\n        # Remove leading whitespaces from url\n        url = url.lstrip()\n\n        # Don't do any URL preparation for non-HTTP schemes like `mailto`,\n        # `data` etc to work around exceptions from `url_parse`, which\n        # handles RFC 3986 only.\n        if \":\" in url and not url.lower().startswith(\"http\"):\n            self.url = url\n            return\n\n", "start_line": 400, "end_line": 430, "total_lines": 1032, "is_truncated": false}
8read_file
{
 "end_line": 485,
 "filepath": "src/requests/models.py",
 "start_line": 431
}
{"status": "ok", "filepath": "src/requests/models.py", "content": " # Support for unicode domain names and paths.\n try:\n scheme, auth, host, port, path, query
full
{"status": "ok", "filepath": "src/requests/models.py", "content": "        # Support for unicode domain names and paths.\n        try:\n            scheme, auth, host, port, path, query, fragment = parse_url(url)\n        except LocationParseError as e:\n            raise InvalidURL(*e.args)\n\n        if not scheme:\n            raise MissingSchema(\n                f\"Invalid URL {url!r}: No scheme supplied. \"\n                f\"Perhaps you meant https://{url}?\"\n            )\n\n        if not host:\n            raise InvalidURL(f\"Invalid URL {url!r}: No host supplied\")\n\n        # In general, we want to try IDNA encoding the hostname if the string contains\n        # non-ASCII characters. This allows users to automatically get the correct IDNA\n        # behaviour. For strings containing only ASCII characters, we need to also verify\n        # it doesn't start with a wildcard (*), before allowing the unencoded hostname.\n        if not unicode_is_ascii(host):\n            try:\n                host = self._get_idna_encoded_host(host)\n            except UnicodeError:\n                raise InvalidURL(\"URL has an invalid label.\")\n        elif host.startswith((\"*\", \".\")):\n            raise InvalidURL(\"URL has an invalid label.\")\n\n        # Carefully reconstruct the network location\n        netloc = auth or \"\"\n        if netloc:\n            netloc += \"@\"\n        netloc += host\n        if port:\n            netloc += f\":{port}\"\n\n        # Bare domains aren't valid URLs.\n        if not path:\n            path = \"/\"\n\n        if isinstance(params, (str, bytes)):\n            params = to_native_string(params)\n\n        enc_params = self._encode_params(params)\n        if enc_params:\n            if query:\n                query = f\"{query}&{enc_params}\"\n            else:\n                query = enc_params\n\n        url = requote_uri(urlunparse([scheme, netloc, path, None, query, fragment]))\n        self.url = url\n\n    def pre
9run_command
{
 "command": "grep -rn \"urlopen\" src/requests/adapters.py"
}
{"status": "ok", "stdout": "485: resp = conn.urlopen(\n", "exit_code": 0}
full
{"status": "ok", "stdout": "485:            resp = conn.urlopen(\n", "exit_code": 0}
10run_command
{
 "command": "grep -rn \"urlopen\" src/requests/adapters.py -C 20"
}
{"status": "ok", "stdout": "465- proxies=proxies,\n466- )\n467-\n468- chunked = not (request.body is None or \"Content-Length\" in request.headers)\n469-\n470-
full
{"status": "ok", "stdout": "465-            proxies=proxies,\n466-        )\n467-\n468-        chunked = not (request.body is None or \"Content-Length\" in request.headers)\n469-\n470-        if isinstance(timeout, tuple):\n471-            try:\n472-                connect, read = timeout\n473-                timeout = TimeoutSauce(connect=connect, read=read)\n474-            except ValueError:\n475-                raise ValueError(\n476-                    f\"Invalid timeout {timeout}. Pass a (connect, read) timeout tuple, \"\n477-                    f\"or a single float to set both timeouts to the same value.\"\n478-                )\n479-        elif isinstance(timeout, TimeoutSauce):\n480-            pass\n481-        else:\n482-            timeout = TimeoutSauce(connect=timeout, read=timeout)\n483-\n484-        try:\n485:            resp = conn.urlopen(\n486-                method=request.method,\n487-                url=url,\n488-                body=request.body,\n489-                headers=request.headers,\n490-                redirect=False,\n491-                assert_same_host=False,\n492-                preload_content=False,\n493-                decode_content=False,\n494-                retries=self.max_retries,\n495-                timeout=timeout,\n496-                chunked=chunked,\n497-            )\n498-\n499-        except (ProtocolError, OSError) as err:\n500-            raise ConnectionError(err, request=request)\n501-\n502-        except MaxRetryError as e:\n503-            if isinstance(e.reason, ConnectTimeoutError):\n504-                # TODO: Remove this in 3.0.0: see #2811\n505-                if not isinstance(e.reason, NewConnectionError):\n", "exit_code": 0}
11read_file
{
 "end_line": 480,
 "filepath": "src/requests/adapters.py",
 "start_line": 450
}
{"status": "ok", "filepath": "src/requests/adapters.py", "content": " \"\"\"\n\n try:\n conn = self.get_connection(request.url, proxies)\n except LocationValueE
full
{"status": "ok", "filepath": "src/requests/adapters.py", "content": "        \"\"\"\n\n        try:\n            conn = self.get_connection(request.url, proxies)\n        except LocationValueError as e:\n            raise InvalidURL(e, request=request)\n\n        self.cert_verify(conn, request.url, verify, cert)\n        url = self.request_url(request, proxies)\n        self.add_headers(\n            request,\n            stream=stream,\n            timeout=timeout,\n            verify=verify,\n            cert=cert,\n            proxies=proxies,\n        )\n\n        chunked = not (request.body is None or \"Content-Length\" in request.headers)\n\n        if isinstance(timeout, tuple):\n            try:\n                connect, read = timeout\n                timeout = TimeoutSauce(connect=connect, read=read)\n            except ValueError:\n                raise ValueError(\n                    f\"Invalid timeout {timeout}. Pass a (connect, read) timeout tuple, \"\n                    f\"or a single float to set both timeouts to the same value.\"\n                )\n        elif isinstance(timeout, TimeoutSauce):\n            pass\n", "start_line": 450, "end_line": 480, "total_lines": 537, "is_truncated": false}
12read_file
{
 "end_line": 460,
 "filepath": "src/requests/adapters.py",
 "start_line": 440
}
{"status": "ok", "filepath": "src/requests/adapters.py", "content": " :param timeout: (optional) How long to wait for the server to send\n data before giving up
full
{"status": "ok", "filepath": "src/requests/adapters.py", "content": "        :param timeout: (optional) How long to wait for the server to send\n            data before giving up, as a float, or a :ref:`(connect timeout,\n            read timeout) <timeouts>` tuple.\n        :type timeout: float or tuple or urllib3 Timeout object\n        :param verify: (optional) Either a boolean, in which case it controls whether\n            we verify the server's TLS certificate, or a string, in which case it\n            must be a path to a CA bundle to use\n        :param cert: (optional) Any user-provided SSL certificate to be trusted.\n        :param proxies: (optional) The proxies dictionary to apply to the request.\n        :rtype: requests.Response\n        \"\"\"\n\n        try:\n            conn = self.get_connection(request.url, proxies)\n        except LocationValueError as e:\n            raise InvalidURL(e, request=request)\n\n        self.cert_verify(conn, request.url, verify, cert)\n        url = self.request_url(request, proxies)\n        self.add_headers(\n            request,\n", "start_line": 440, "end_line": 460, "total_lines": 537, "is_truncated": false}
13read_file
{
 "end_line": 440,
 "filepath": "src/requests/adapters.py",
 "start_line": 420
}
{"status": "ok", "filepath": "src/requests/adapters.py", "content": " :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n :param proxy: The url of the pro
full
{"status": "ok", "filepath": "src/requests/adapters.py", "content": "        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param proxy: The url of the proxy being used for this request.\n        :rtype: dict\n        \"\"\"\n        headers = {}\n        username, password = get_auth_from_url(proxy)\n\n        if username:\n            headers[\"Proxy-Authorization\"] = _basic_auth_str(username, password)\n\n        return headers\n\n    def send(\n        self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None\n    ):\n        \"\"\"Sends PreparedRequest object. Returns Response object.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n        :param stream: (optional) Whether to stream the request content.\n        :param timeout: (optional) How long to wait for the server to send\n", "start_line": 420, "end_line": 440, "total_lines": 537, "is_truncated": false}
14search_similar_code
{
 "query": "request_url"
}
{"status": "error", "error_type": "EmbeddingsUnavailable", "error_message": "No embeddings"}
full
{"status": "error", "error_type": "EmbeddingsUnavailable", "error_message": "No embeddings"}
15run_command
{
 "command": "grep -rn \"def request_url\" src/requests/adapters.py"
}
{"status": "ok", "stdout": "369: def request_url(self, request, proxies):\n", "exit_code": 0}
full
{"status": "ok", "stdout": "369:    def request_url(self, request, proxies):\n", "exit_code": 0}
16read_file
{
 "end_line": 385,
 "filepath": "src/requests/adapters.py",
 "start_line": 360
}
{"status": "ok", "filepath": "src/requests/adapters.py", "content": " \"\"\"Disposes of any internal state.\n\n Currently, this closes the PoolManager and any a
full
{"status": "ok", "filepath": "src/requests/adapters.py", "content": "        \"\"\"Disposes of any internal state.\n\n        Currently, this closes the PoolManager and any active ProxyManager,\n        which closes any pooled connections.\n        \"\"\"\n        self.poolmanager.clear()\n        for proxy in self.proxy_manager.values():\n            proxy.clear()\n\n    def request_url(self, request, proxies):\n        \"\"\"Obtain the url to use when making the final request.\n\n        If the message is being sent through a HTTP proxy, the full URL has to\n        be used. Otherwise, we should only use the path portion of the URL.\n\n        This should not be called from user code, and is only exposed for use\n        when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n        :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs.\n        :rtype: str\n        \"\"\"\n        proxy = select_proxy(request.url, proxies)\n        scheme = urlparse(request.url).scheme\n\n", "start_line": 360, "end_line": 385, "total_lines": 537, "is_truncated": false}
17read_file
{
 "end_line": 400,
 "filepath": "src/requests/adapters.py",
 "start_line": 386
}
{"status": "ok", "filepath": "src/requests/adapters.py", "content": " is_proxied_http_request = proxy and scheme != \"https\"\n using_socks_proxy = False\n if p
full
{"status": "ok", "filepath": "src/requests/adapters.py", "content": "        is_proxied_http_request = proxy and scheme != \"https\"\n        using_socks_proxy = False\n        if proxy:\n            proxy_scheme = urlparse(proxy).scheme.lower()\n            using_socks_proxy = proxy_scheme.startswith(\"socks\")\n\n        url = request.path_url\n        if is_proxied_http_request and not using_socks_proxy:\n            url = urldefragauth(request.url)\n\n        return url\n\n    def add_headers(self, request, **kwargs):\n        \"\"\"Add any headers needed by the connection. As of v2.0 this does\n        nothing by default, but is left for overriding by users that subclass\n", "start_line": 386, "end_line": 400, "total_lines": 537, "is_truncated": false}
18read_file
{
 "end_line": 110,
 "filepath": "src/requests/models.py",
 "start_line": 80
}
{"status": "ok", "filepath": "src/requests/models.py", "content": "CONTENT_CHUNK_SIZE = 10 * 1024\nITER_CHUNK_SIZE = 512\n\n\nclass RequestEncodingMixin:\n @pro
full
{"status": "ok", "filepath": "src/requests/models.py", "content": "CONTENT_CHUNK_SIZE = 10 * 1024\nITER_CHUNK_SIZE = 512\n\n\nclass RequestEncodingMixin:\n    @property\n    def path_url(self):\n        \"\"\"Build the path URL to use.\"\"\"\n\n        url = []\n\n        p = urlsplit(self.url)\n\n        path = p.path\n        if not path:\n            path = \"/\"\n\n        url.append(path)\n\n        query = p.query\n        if query:\n            url.append(\"?\")\n            url.append(query)\n\n        return \"\".join(url)\n\n    @staticmethod\n    def _encode_params(data):\n        \"\"\"Encode parameters in a piece of data.\n\n        Will successfully encode parameters when passed as a dict or a list of\n", "start_line": 80, "end_line": 110, "total_lines": 1032, "is_truncated": false}
19write_file
{
 "content": "from requests import Request, Session\nfrom requests.adapters import HTTPAdapter\n\ndef test_excess_leading_slashes():\n    s = Session()\n    # We want to see if //path is trimmed to /path\n    # Since we are testing path_url, we can use a PreparedRequest\n    req = Request('GET', 'http://example.com//foo/bar').prepare()\n    print(f\"Path URL for //foo/bar: {req.path_url}\")\n    assert req.path_url == '/foo/bar'\n\n    req2 = Request('GET', 'http://example.com///foo/bar').prepare()\n    print(f\"Path URL for ///foo/bar: {req2.path_url}\")\n    assert req2.path_url == '/foo/bar'\n\n    req3 = Request('GET', 'http://example.com/foo/bar').prepare()\n    print(f\"Path URL for /foo/bar: {req3.path_url}\")\n    assert req3.path_url == '/foo/bar'\n\nif __name__ == \"__main__\":\n    try:\n        test_excess_leading_slashes()\n        print(\"Test passed!\")\n    except AssertionError as e:\n        print(f\"Test failed!\")\n        raise e\n",
 "filepath": "/tmp/test_slashes.py"
}
{"status": "ok", "filepath": "/tmp/test_slashes.py", "size": 914}
full
{"status": "ok", "filepath": "/tmp/test_slashes.py", "size": 914}
20run_command
{
 "command": "python3 /tmp/test_slashes.py"
}
{"status": "error", "error_type": "CommandError", "error_message": "Command failed with exit code 2", "details": {"stdout": "", "stderr": "python3: can't open f
full
{"status": "error", "error_type": "CommandError", "error_message": "Command failed with exit code 2", "details": {"stdout": "", "stderr": "python3: can't open file '/tmp/swe_work/eval4_submission/requests_6644/a/tmp/test_slashes.py': [Errno 2] No such file or directory\n", "exit_code": 2}}
21run_command
{
 "command": "python3 /workspace/tmp/test_slashes.py"
}
{"status": "error", "error_type": "CommandError", "error_message": "Command failed with exit code 2", "details": {"stdout": "", "stderr": "python3: can't open f
full
{"status": "error", "error_type": "CommandError", "error_message": "Command failed with exit code 2", "details": {"stdout": "", "stderr": "python3: can't open file '/tmp/swe_work/eval4_submission/requests_6644/a/workspace/tmp/test_slashes.py': [Errno 2] No such file or directory\n", "exit_code": 2}}
22run_command
{
 "command": "mkdir -p /tmp && python3 /tmp/test_slashes.py"
}
{"status": "error", "error_type": "CommandError", "error_message": "Command failed with exit code 2", "details": {"stdout": "", "stderr": "python3: can't open f
full
{"status": "error", "error_type": "CommandError", "error_message": "Command failed with exit code 2", "details": {"stdout": "", "stderr": "python3: can't open file '/tmp/swe_work/eval4_submission/requests_6644/a/tmp/test_slashes.py': [Errno 2] No such file or directory\n", "exit_code": 2}}
23run_command
{
 "command": "python3 -c \"from requests import Request; req = Request('GET', 'http://example.com//foo/bar').prepare(); print(f'Path URL: {req.path_url}')\""
}
{"status": "ok", "stdout": "Path URL: //foo/bar\n", "exit_code": 0}
full
{"status": "ok", "stdout": "Path URL: //foo/bar\n", "exit_code": 0}
24edit_file
{
 "filepath": "src/requests/models.py",
 "new_string": "        path = p.path\n        if not path:\n            path = \\\"/\\\"\n        elif path.startswith(\\\"//\\\"):\n            path = \\\"/\\\" + path.lstrip(\\\"/\\\")\n\n        url.append(path)",
 "old_string": "        path = p.path\n        if not path:\n            path = \\\"/\\\"\n\n        url.append(path)"
}
{"status": "error", "error_type": "FileEditError", "error_message": "old_string not found in file (tried exact, flexible and regex matching)"}
full
{"status": "error", "error_type": "FileEditError", "error_message": "old_string not found in file (tried exact, flexible and regex matching)"}
25read_file
{
 "end_line": 100,
 "filepath": "src/requests/models.py",
 "start_line": 80
}
{"status": "ok", "filepath": "src/requests/models.py", "content": "CONTENT_CHUNK_SIZE = 10 * 1024\nITER_CHUNK_SIZE = 512\n\n\nclass RequestEncodingMixin:\n @pro
full
{"status": "ok", "filepath": "src/requests/models.py", "content": "CONTENT_CHUNK_SIZE = 10 * 1024\nITER_CHUNK_SIZE = 512\n\n\nclass RequestEncodingMixin:\n    @property\n    def path_url(self):\n        \"\"\"Build the path URL to use.\"\"\"\n\n        url = []\n\n        p = urlsplit(self.url)\n\n        path = p.path\n        if not path:\n            path = \"/\"\n\n        url.append(path)\n\n        query = p.query\n        if query:\n", "start_line": 80, "end_line": 100, "total_lines": 1032, "is_truncated": false}
26edit_file
{
 "filepath": "src/requests/models.py",
 "new_string": "        path = p.path\n        if not path:\n            path = \"/\"\n        elif path.startswith(\"//\"):\n            path = \"/\" + path.lstrip(\"/\")\n\n        url.append(path)",
 "old_string": "        path = p.path\n        if not path:\n            path = \"/\"\n\n        url.append(path)"
}
{"status": "ok", "filepath": "src/requests/models.py", "occurrences": 1, "strategy": "exact", "diff": "--- a/src/requests/models.py\n+++ b/src/requests/models.p
full
{"status": "ok", "filepath": "src/requests/models.py", "occurrences": 1, "strategy": "exact", "diff": "--- a/src/requests/models.py\n+++ b/src/requests/models.py\n@@ -93,6 +93,8 @@\n         path = p.path\n         if not path:\n             path = \"/\"\n+        elif path.startswith(\"//\"):\n+            path = \"/\" + path.lstrip(\"/\")\n \n         url.append(path)\n \n", "is_truncated": false}
27run_command
{
 "command": "python3 -c \"from requests import Request; req = Request('GET', 'http://example.com//foo/bar').prepare(); print(f'Path URL: {req.path_url}')\""
}
{"status": "ok", "stdout": "Path URL: /foo/bar\n", "exit_code": 0}
full
{"status": "ok", "stdout": "Path URL: /foo/bar\n", "exit_code": 0}
28run_command
{
 "command": "python3 -c \"from requests import Request; req = Request('GET', 'http://example.com///foo/bar').prepare(); print(f'Path URL: {req.path_url}')\""
}
{"status": "ok", "stdout": "Path URL: /foo/bar\n", "exit_code": 0}
full
{"status": "ok", "stdout": "Path URL: /foo/bar\n", "exit_code": 0}
29submit_patch
[]
{"status": "ok", "patch_size": 1474, "files_changed": 2}
full
{"status": "ok", "patch_size": 1474, "files_changed": 2}

Patch

diff --git a/src/requests/models.py b/src/requests/models.py
index 44556394..618b4b30 100644
--- a/src/requests/models.py
+++ b/src/requests/models.py
@@ -93,6 +93,8 @@ class RequestEncodingMixin:
         path = p.path
         if not path:
             path = "/"
+        elif path.startswith("//"):
+            path = "/" + path.lstrip("/")
 
         url.append(path)
 
diff --git a/tmp/test_slashes.py b/tmp/test_slashes.py
new file mode 100644
index 00000000..1704d8fc
--- /dev/null
+++ b/tmp/test_slashes.py
@@ -0,0 +1,26 @@
+from requests import Request, Session
+from requests.adapters import HTTPAdapter
+
+def test_excess_leading_slashes():
+    s = Session()
+    # We want to see if //path is trimmed to /path
+    # Since we are testing path_url, we can use a PreparedRequest
+    req = Request('GET', 'http://example.com//foo/bar').prepare()
+    print(f"Path URL for //foo/bar: {req.path_url}")
+    assert req.path_url == '/foo/bar'
+
+    req2 = Request('GET', 'http://example.com///foo/bar').prepare()
+    print(f"Path URL for ///foo/bar: {req2.path_url}")
+    assert req2.path_url == '/foo/bar'
+
+    req3 = Request('GET', 'http://example.com/foo/bar').prepare()
+    print(f"Path URL for /foo/bar: {req3.path_url}")
+    assert req3.path_url == '/foo/bar'
+
+if __name__ == "__main__":
+    try:
+        test_excess_leading_slashes()
+        print("Test passed!")
+    except AssertionError as e:
+        print(f"Test failed!")
+        raise e

Test output

show
.                                                                        [100%]
=============================== warnings summary ===============================
../../../../../../kaggle/tmp/envs/requests/lib/python3.13/site-packages/_pytest/config/__init__.py:1464
  /kaggle/tmp/envs/requests/lib/python3.13/site-packages/_pytest/config/__init__.py:1464: PytestConfigWarning: Unknown config option: timeout
  
    self._warn_or_fail_if_strict(f"Unknown config option: {key}\n")

-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
1 passed, 1 warning in 0.01s
[2026-09-24 15:23:22,185] WARNING in core: flasgger is not installed; serving the static landing page at / and skipping the Swagger UI and /spec.json.