Skip to content

Commit fcc9ff3

Browse files
committed
contrib/sanic: handle 24.12 CookieJar.items() removal
1 parent b7294d9 commit fcc9ff3

File tree

3 files changed

+25
-1
lines changed

3 files changed

+25
-1
lines changed

elasticapm/contrib/sanic/utils.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,4 +148,12 @@ def make_client(client_cls=Client, **defaults) -> Client:
148148

149149
def _transform_response_cookie(cookies: CookieJar) -> Dict[str, str]:
150150
"""Transform the Sanic's CookieJar instance into a Normal dictionary to build the context"""
151-
return {k: {"value": v.value, "path": v["path"]} for k, v in cookies.items()}
151+
# old sanic versions used to have an items() method
152+
if hasattr(cookies, "items"):
153+
return {k: {"value": v.value, "path": v["path"]} for k, v in cookies.items()}
154+
155+
try:
156+
return {cookie.key: {"value": cookie.value, "path": cookie.path} for cookie in cookies.cookies}
157+
except KeyError:
158+
# cookies.cookies assumes Set-Cookie header will be there
159+
return {}

tests/contrib/sanic/fixtures.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,12 @@ async def raise_value_error(request):
155155
async def custom_headers(request):
156156
return json({"data": "message"}, headers={"sessionid": 1234555})
157157

158+
@app.get("/add-cookies")
159+
async def add_cookies(request):
160+
response = json({"data": "message"}, headers={"sessionid": 1234555})
161+
response.add_cookie("some", "cookie")
162+
return response
163+
158164
try:
159165
yield app, apm
160166
finally:

tests/contrib/sanic/sanic_tests.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,16 @@ def test_header_field_sanitization(sanic_elastic_app, elasticapm_client):
194194
assert transaction["context"]["request"]["headers"]["api_key"] == "[REDACTED]"
195195

196196

197+
def test_cookies_normalization(sanic_elastic_app, elasticapm_client):
198+
sanic_app, apm = next(sanic_elastic_app(elastic_client=elasticapm_client))
199+
_, resp = sanic_app.test_client.get(
200+
"/add-cookies",
201+
)
202+
assert len(apm._client.events[constants.TRANSACTION]) == 1
203+
transaction = apm._client.events[constants.TRANSACTION][0]
204+
assert transaction["context"]["response"]["cookies"] == {"some": {"value": "cookie", "path": "/"}}
205+
206+
197207
def test_custom_callback_handlers(sanic_elastic_app, elasticapm_client):
198208
def _custom_transaction_callback(request):
199209
return "my-custom-name"

0 commit comments

Comments
 (0)