Skip to content

Commit

Permalink
simplify code
Browse files Browse the repository at this point in the history
  • Loading branch information
Kludex committed Dec 17, 2022
1 parent b8e7931 commit 0433643
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 31 deletions.
10 changes: 2 additions & 8 deletions starlette/responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import sys
import typing
from datetime import datetime
from email.utils import formatdate
from email.utils import format_datetime, formatdate
from functools import partial
from mimetypes import guess_type as mimetypes_guess_type
from urllib.parse import quote
Expand Down Expand Up @@ -36,12 +36,6 @@ def guess_type(
return mimetypes_guess_type(url, strict)


# Cookie expire format
# As described by https://www.rfc-editor.org/rfc/rfc6265#section-4.1.1
# And defined by https://www.rfc-editor.org/rfc/rfc2616#section-3.3.1
COOKIE_DATETIME_FORMAT = "%a, %d %b %Y %H:%M:%S GMT"


class Response:
media_type = None
charset = "utf-8"
Expand Down Expand Up @@ -125,7 +119,7 @@ def set_cookie(
cookie[key]["max-age"] = max_age
if expires is not None:
if isinstance(expires, datetime):
cookie[key]["expires"] = expires.strftime(COOKIE_DATETIME_FORMAT)
cookie[key]["expires"] = format_datetime(expires, usegmt=True)
else:
cookie[key]["expires"] = expires
if path is not None:
Expand Down
29 changes: 6 additions & 23 deletions tests/test_responses.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import os
import re
from datetime import datetime, timedelta, timezone
from http.cookies import SimpleCookie

Expand Down Expand Up @@ -312,35 +311,19 @@ async def app(scope, receive, send):
assert response.text == "Hello, world!"


def test_set_cookie_with_expire_datetime(test_client_factory):
@pytest.mark.parametrize(
"expires", [datetime.now(timezone.utc) + timedelta(days=1), 10]
)
def test_expires_on_set_cookie(test_client_factory, expires):
async def app(scope, receive, send):
response = Response("Hello, world!", media_type="text/plain")
now = datetime.now(timezone.utc)
expires = now + timedelta(minutes=1)
response.set_cookie(
"mycookie",
"myvalue",
max_age=10,
expires=expires,
path="/",
domain="localhost",
secure=True,
httponly=True,
samesite="none",
)
response.set_cookie("mycookie", "myvalue", expires=expires)
await response(scope, receive, send)

client = test_client_factory(app)
response = client.get("/")
cookie: SimpleCookie = SimpleCookie(response.headers.get("set-cookie"))

expires = cookie["mycookie"]["expires"]

# Date format spec from
# And defined by https://www.rfc-editor.org/rfc/rfc2616#section-3.3.1
pattern = r"\w{3}, \d{2} \w{3} \d{4} \d{2}:\d{2}:\d{2}"

assert re.search(pattern, expires)
assert cookie["mycookie"]["expires"]


def test_delete_cookie(test_client_factory):
Expand Down

0 comments on commit 0433643

Please sign in to comment.