Skip to content

Commit

Permalink
More tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Tinche committed Dec 15, 2023
1 parent e1fcff5 commit fbf05fe
Show file tree
Hide file tree
Showing 9 changed files with 182 additions and 110 deletions.
131 changes: 68 additions & 63 deletions pdm.lock

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ ignore = [
"B006", # trust me
"B008", # can't get it to work with extend-immutable-calls
"N818", # Exceptions
"RUF006", # Buggy for now
"RUF013", # False implicit optionals
]

Expand Down
36 changes: 18 additions & 18 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from asyncio import Event, create_task, new_event_loop
from asyncio import create_task, new_event_loop
from asyncio.exceptions import CancelledError
from collections.abc import AsyncIterator, Callable
from contextlib import suppress
Expand All @@ -8,6 +8,7 @@
from .aiohttp import make_app as make_aiohttp_app
from .aiohttp import run_on_aiohttp
from .django import run_on_django
from .django_uapi_app.views import app
from .flask import make_app as make_flask_app
from .flask import run_on_flask
from .quart import make_app as make_quart_app
Expand Down Expand Up @@ -37,13 +38,12 @@ async def server(request, unused_tcp_port_factory: Callable[..., int]):
with suppress(CancelledError):
await t
elif request.param == "flask":
shutdown_event = Event()
t = create_task(run_on_flask(make_flask_app(), unused_tcp_port, shutdown_event))
t = create_task(run_on_flask(make_flask_app(), unused_tcp_port))
yield unused_tcp_port
shutdown_event.set()
await t
t.cancel()
with suppress(CancelledError):
await t
elif request.param == "quart":
shutdown_event = Event()
t = create_task(run_on_quart(make_quart_app(), unused_tcp_port))
yield unused_tcp_port
t.cancel()
Expand All @@ -56,11 +56,11 @@ async def server(request, unused_tcp_port_factory: Callable[..., int]):
with suppress(CancelledError):
await t
elif request.param == "django":
shutdown_event = Event()
t = create_task(run_on_django(unused_tcp_port, shutdown_event))
t = create_task(run_on_django(app, unused_tcp_port))
yield unused_tcp_port
shutdown_event.set()
await t
t.cancel()
with suppress(CancelledError):
await t
else:
raise Exception("Unknown server framework")

Expand All @@ -81,13 +81,13 @@ async def server_with_openapi(
with suppress(CancelledError):
await t
elif request.param == "flask":
shutdown_event = Event()
flask_app = make_flask_app()
flask_app.serve_openapi()
t = create_task(run_on_flask(flask_app, unused_tcp_port, shutdown_event))
t = create_task(run_on_flask(flask_app, unused_tcp_port))
yield unused_tcp_port
shutdown_event.set()
await t
t.cancel()
with suppress(CancelledError):
await t
elif request.param == "quart":
quart_app = make_quart_app()
quart_app.serve_openapi()
Expand All @@ -105,10 +105,10 @@ async def server_with_openapi(
with suppress(CancelledError):
await t
elif request.param == "django":
shutdown_event = Event()
t = create_task(run_on_django(unused_tcp_port, shutdown_event))
t = create_task(run_on_django(app, unused_tcp_port))
yield unused_tcp_port
shutdown_event.set()
await t
t.cancel()
with suppress(CancelledError):
await t
else:
raise Exception("Unknown server framework")
35 changes: 31 additions & 4 deletions tests/django.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,40 @@
from asyncio import Event
from asyncio import CancelledError, Event, create_task

from hypercorn.asyncio import serve
from hypercorn.config import Config

from uapi.django import DjangoApp

async def run_on_django(port: int, shutdown_event: Event):
from .django_uapi.django_uapi.wsgi import application
# Sigh
urlpatterns: list = []


async def run_on_django(app: DjangoApp, port: int) -> None:
from django.conf import settings
from django.core.handlers.wsgi import WSGIHandler

urlpatterns.clear()
urlpatterns.extend(app.to_urlpatterns())

if not settings.configured:
settings.configure(ROOT_URLCONF=__name__, DEBUG=True)

application = WSGIHandler()

config = Config()
config.bind = [f"localhost:{port}"]

await serve(application, config, shutdown_trigger=shutdown_event.wait, mode="wsgi") # type: ignore
event = Event()

t = create_task(
serve(application, config, shutdown_trigger=event.wait, mode="wsgi") # type: ignore
)

try:
await t
except CancelledError:
event.set()
await t
raise
finally:
urlpatterns.clear()
25 changes: 18 additions & 7 deletions tests/flask.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from asyncio import Event
from asyncio import CancelledError, Event, create_task

from hypercorn.asyncio import serve
from hypercorn.config import Config
Expand Down Expand Up @@ -73,13 +73,24 @@ def request_method_native(req_method: Method) -> Response:
return app


async def run_on_flask(app: FlaskApp, port: int, shutdown_event: Event):
async def run_on_flask(app: FlaskApp, port: int):
config = Config()
config.bind = [f"localhost:{port}"]

await serve(
app.to_framework_app(__name__),
config,
shutdown_trigger=shutdown_event.wait, # type: ignore
mode="wsgi",
event = Event()

t = create_task(
serve(
app.to_framework_app(__name__),
config,
shutdown_trigger=event.wait, # type: ignore
mode="wsgi",
)
)

try:
await t
except CancelledError:
event.set()
await t
raise
12 changes: 6 additions & 6 deletions tests/openapi/test_openapi_uis.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from asyncio import Event, create_task
from asyncio import CancelledError, create_task
from collections.abc import Callable
from contextlib import suppress

import pytest

Expand All @@ -19,13 +20,12 @@ async def openapi_renderer_app(unused_tcp_port_factory: Callable[..., int]):
app.serve_redoc(openapi_path="/openapi_test.json")
app.serve_elements(openapi_path="/openapi_test.json")

shutdown_event = Event()

t = create_task(run_on_flask(app, unused_tcp_port, shutdown_event))
t = create_task(run_on_flask(app, unused_tcp_port))
yield unused_tcp_port

shutdown_event.set()
await t
t.cancel()
with suppress(CancelledError):
await t


async def test_elements(openapi_renderer_app: int) -> None:
Expand Down
11 changes: 5 additions & 6 deletions tests/sessions/conftest.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from asyncio import CancelledError, Event, create_task
from asyncio import CancelledError, create_task
from collections.abc import Callable
from contextlib import suppress

Expand Down Expand Up @@ -76,15 +76,14 @@ async def secure_cookie_session_app(
t.cancel()
with suppress(CancelledError):
await t

elif request.param == "flask":
flask_app = FlaskApp()
configure_secure_session_app(flask_app)
shutdown_event = Event()
t = create_task(run_on_flask(flask_app, unused_tcp_port, shutdown_event))
t = create_task(run_on_flask(flask_app, unused_tcp_port))
yield unused_tcp_port
shutdown_event.set()
await t
t.cancel()
with suppress(CancelledError):
await t
elif request.param == "quart":
quart_app = QuartApp()
configure_secure_session_app(quart_app)
Expand Down
3 changes: 2 additions & 1 deletion tests/test_get.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,4 +89,5 @@ async def test_user_response_class(server):
async with AsyncClient() as client:
resp = await client.get(f"http://localhost:{server}/throttled")
assert resp.status_code == 429
assert resp.headers["content-length"] == "0"
# Django omits the content-length
assert resp.headers.get("content-length", "0") == "0"
38 changes: 33 additions & 5 deletions tests/test_shorthands.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,22 @@
from datetime import datetime, timezone
from typing import Any

import pytest
from httpx import AsyncClient

from uapi.quart import App
from uapi.aiohttp import AiohttpApp
from uapi.django import DjangoApp
from uapi.flask import FlaskApp
from uapi.quart import App, QuartApp
from uapi.shorthands import ResponseShorthand
from uapi.starlette import StarletteApp
from uapi.status import BaseResponse, Created, Ok

from .aiohttp import run_on_aiohttp
from .django import run_on_django
from .flask import run_on_flask
from .quart import run_on_quart
from .starlette import run_on_starlette


class DatetimeShorthand(ResponseShorthand[datetime]):
Expand All @@ -22,15 +31,34 @@ def is_union_member(value: Any) -> bool:
return isinstance(value, datetime)


async def test_custom_shorthand(unused_tcp_port: int) -> None:
@pytest.mark.parametrize(
"app_type", [QuartApp, AiohttpApp, StarletteApp, FlaskApp, DjangoApp]
)
async def test_custom_shorthand(
unused_tcp_port: int,
app_type: type[QuartApp]
| type[AiohttpApp]
| type[StarletteApp]
| type[FlaskApp]
| type[DjangoApp],
) -> None:
"""Custom shorthands work."""
app = App().add_response_shorthand(DatetimeShorthand)
app = app_type[None]().add_response_shorthand(DatetimeShorthand) # type: ignore

@app.get("/")
async def datetime_handler() -> datetime:
def datetime_handler() -> datetime:
return datetime(2000, 1, 1, 0, 0, 0, 0, tzinfo=timezone.utc)

t = create_task(run_on_quart(app, unused_tcp_port))
if app_type is QuartApp:
t = create_task(run_on_quart(app, unused_tcp_port))
elif app_type is AiohttpApp:
t = create_task(run_on_aiohttp(app, unused_tcp_port))
elif app_type is StarletteApp:
t = create_task(run_on_starlette(app, unused_tcp_port))
elif app_type is FlaskApp:
t = create_task(run_on_flask(app, unused_tcp_port))
elif app_type is DjangoApp:
t = create_task(run_on_django(app, unused_tcp_port))

try:
async with AsyncClient() as client:
Expand Down

0 comments on commit fbf05fe

Please sign in to comment.