Skip to content

Commit

Permalink
Fix cookie conflict when they are actually compatible
Browse files Browse the repository at this point in the history
  • Loading branch information
perkfly committed Sep 4, 2023
1 parent 9a8e5da commit 2a93a0c
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 2 deletions.
15 changes: 13 additions & 2 deletions curl_cffi/requests/cookies.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,14 +204,25 @@ def get( # type: ignore
in order to specify exactly which cookie to retrieve.
"""
value = None
matched_domain = ""
for cookie in self.jar:
if cookie.name == name:
if domain is None or cookie.domain == domain:
if path is None or cookie.path == path:
if value is not None:
message = f"Multiple cookies exist with name={name}"
# if cookies on two different domains do not share a same value
if (
value is not None
and not matched_domain.endswith(cookie.domain)
and not str(cookie.domain).endswith(matched_domain)
and value != cookie.value
):
message = (
f"Multiple cookies exist with name={name} on "
f"{matched_domain} and {cookie.domain}"
)
raise CookieConflict(message)
value = cookie.value
matched_domain = cookie.domain or ""

if value is None:
return default
Expand Down
10 changes: 10 additions & 0 deletions tests/unittest/test_async_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,16 @@ async def test_get(server):
assert r.status_code == 200


def test_create_session_out_of_async(server):
s = AsyncSession()

async def get():
r = await s.get(str(server.url))
assert r.status_code == 200

asyncio.run(get())


async def test_post_dict(server):
async with AsyncSession() as s:
r = await s.post(
Expand Down
26 changes: 26 additions & 0 deletions tests/unittest/test_cookies.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import pytest
from curl_cffi.requests.cookies import Cookies
from curl_cffi.requests.errors import CookieConflict


def test_cookies_conflict():
c = Cookies()
c.set("foo", "bar", domain="example.com")
c.set("foo", "baz", domain="test.local")
with pytest.raises(CookieConflict):
c.get("foo")


def test_cookies_conflict_on_subdomain():
c = Cookies()
c.set("foo", "bar", domain=".example.com")
c.set("foo", "baz", domain="a.example.com")
assert c.get("foo") in ("bar", "baz")


def test_cookies_conflict_but_same():
c = Cookies()
c = Cookies()
c.set("foo", "bar", domain="example.com")
c.set("foo", "bar", domain="test.local")
assert c.get("foo") == "bar"

0 comments on commit 2a93a0c

Please sign in to comment.