Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adapted to the new changes that drop the ContainerComponent class #65

Merged
merged 4 commits into from
Jun 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ repos:
hooks:
- id: mypy
additional_dependencies:
- asphalt@git+https://github.com/asphalt-framework/asphalt@5.0
- asphalt@git+https://github.com/asphalt-framework/asphalt@remove-container-component
- pytest
exclude: ^(examples/|tests/django_app/)

Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ test = [
"pytest >= 7.4",
"httpx",
"httpx-ws",
"aiohttp >= 3.8; python_version < '3.12'",
"aiohttp >= 3.8",
"Django >= 3.2; python_implementation == 'CPython'",
"asphalt-web[asgi3,fastapi,starlette]",
"litestar >= 2.5.5; python_implementation == 'CPython'",
Expand Down
13 changes: 5 additions & 8 deletions src/asphalt/web/aiohttp.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from aiohttp.web_response import Response
from aiohttp.web_runner import AppRunner, TCPSite
from asphalt.core import (
ContainerComponent,
Component,
Context,
add_resource,
resolve_reference,
Expand All @@ -27,7 +27,7 @@ async def asphalt_middleware(request: Request, handler: Callable[..., Awaitable]
return await handler(request)


class AIOHTTPComponent(ContainerComponent):
class AIOHTTPComponent(Component):
"""
A component that serves an aiohttp application.

Expand All @@ -40,15 +40,11 @@ class AIOHTTPComponent(ContainerComponent):

def __init__(
self,
components: dict[str, dict[str, Any] | None] | None = None,
*,
app: Application | str | None = None,
host: str = "127.0.0.1",
port: int = 8000,
middlewares: Sequence[Callable[..., Coroutine[Any, Any, Any]] | dict[str, Any]] = (),
) -> None:
super().__init__(components)

self.app = resolve_reference(app) or Application()
self.host = host
self.port = port
Expand Down Expand Up @@ -87,9 +83,10 @@ def add_middleware(
f"middleware must be either a coroutine function or a dict, not {middleware!r}"
)

async def start(self) -> None:
async def prepare(self) -> None:
add_resource(self.app)
await super().start()

async def start(self) -> None:
await self.start_server()

async def start_server(self) -> None:
Expand Down
11 changes: 5 additions & 6 deletions src/asphalt/web/asgi3.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
WebSocketScope,
)
from asphalt.core import (
ContainerComponent,
Component,
Context,
add_resource,
resolve_reference,
Expand Down Expand Up @@ -54,7 +54,7 @@ async def __call__(
await self.app(scope, receive, send)


class ASGIComponent(ContainerComponent, Generic[T_Application]):
class ASGIComponent(Component, Generic[T_Application]):
"""
A component that serves the given ASGI 3.0 application via Hypercorn.

Expand All @@ -68,14 +68,12 @@ class ASGIComponent(ContainerComponent, Generic[T_Application]):

def __init__(
self,
components: dict[str, dict[str, Any] | None] | None = None,
*,
app: T_Application | str,
host: str = "127.0.0.1",
port: int = 8000,
middlewares: Sequence[Callable[..., ASGI3Application] | dict[str, Any]] = (),
) -> None:
super().__init__(components)
self.app: T_Application = resolve_reference(app)
self.original_app = self.app
self.host = host
Expand Down Expand Up @@ -111,13 +109,14 @@ def add_middleware(self, middleware: Callable[..., ASGI3Application] | dict[str,
else:
raise TypeError(f"middleware must be either a callable or a dict, not {middleware!r}")

async def start(self) -> None:
async def prepare(self) -> None:
types = [ASGI3Application]
if not isfunction(self.original_app):
types.append(type(self.original_app))

add_resource(self.original_app, types=types)
await super().start()

async def start(self) -> None:
await self.start_server()

async def start_server(self) -> None:
Expand Down
2 changes: 0 additions & 2 deletions src/asphalt/web/fastapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,6 @@ class FastAPIComponent(ASGIComponent[FastAPI]):

def __init__(
self,
components: dict[str, dict[str, Any] | None] | None = None,
*,
app: FastAPI | str | None = None,
host: str = "127.0.0.1",
Expand All @@ -72,7 +71,6 @@ def __init__(
) -> None:
debug = debug if isinstance(debug, bool) else __debug__
super().__init__(
components,
app=app or FastAPI(debug=debug),
host=host,
port=port,
Expand Down
3 changes: 1 addition & 2 deletions src/asphalt/web/litestar.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,6 @@ class LitestarComponent(ASGIComponent[Litestar]):

def __init__(
self,
components: dict[str, dict[str, Any] | None] | None = None,
*,
host: str = "127.0.0.1",
port: int = 8000,
Expand All @@ -88,7 +87,7 @@ def __init__(
config_.setdefault("debug", __debug__)
config_["logging_config"] = None
app = Litestar(**config_)
super().__init__(components, app=app, middlewares=middlewares, host=host, port=port)
super().__init__(app=app, middlewares=middlewares, host=host, port=port)

for item in route_handlers:
if isinstance(item, str):
Expand Down
2 changes: 0 additions & 2 deletions src/asphalt/web/starlette.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@ class StarletteComponent(ASGIComponent[Starlette]):

def __init__(
self,
components: dict[str, dict[str, Any] | None] | None = None,
*,
app: Starlette | None = None,
host: str = "127.0.0.1",
Expand All @@ -56,7 +55,6 @@ def __init__(
) -> None:
debug = debug if isinstance(debug, bool) else __debug__
super().__init__(
components,
app=app or Starlette(debug=debug),
host=host,
port=port,
Expand Down
43 changes: 33 additions & 10 deletions tests/test_aiohttp.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,15 @@

import pytest
import websockets
from asphalt.core import Component, Context, add_resource, get_resource_nowait, inject, resource
from asphalt.core import (
Component,
Context,
add_resource,
get_resource_nowait,
inject,
resource,
start_component,
)
from httpx import AsyncClient

try:
Expand Down Expand Up @@ -68,9 +76,14 @@ async def start(self) -> None:
async with Context(), AsyncClient() as http:
add_resource("foo")
add_resource("bar", name="another")
await AIOHTTPComponent(
components=components, app=application, port=unused_tcp_port
).start()
await start_component(
AIOHTTPComponent,
{
"components": components,
"app": application,
"port": unused_tcp_port,
},
)

# Ensure that the application got added as a resource
get_resource_nowait(Application)
Expand Down Expand Up @@ -122,9 +135,14 @@ async def start(self) -> None:
async with Context():
add_resource("foo")
add_resource("bar", name="another")
await AIOHTTPComponent(
components=components, app=application, port=unused_tcp_port
).start()
await start_component(
AIOHTTPComponent,
{
"components": components,
"app": application,
"port": unused_tcp_port,
},
)

# Ensure that the application got added as a resource
get_resource_nowait(Application)
Expand Down Expand Up @@ -167,9 +185,14 @@ async def root(request: Request) -> Response:
async with Context(), AsyncClient() as http:
add_resource("foo")
add_resource("bar", name="another")
await AIOHTTPComponent(
app=application, port=unused_tcp_port, middlewares=middlewares
).start()
await start_component(
AIOHTTPComponent,
{
"middlewares": middlewares,
"app": application,
"port": unused_tcp_port,
},
)

# Ensure that the application got added as a resource
get_resource_nowait(Application)
Expand Down
26 changes: 23 additions & 3 deletions tests/test_asgi3.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
get_resource_nowait,
inject,
resource,
start_component,
)
from httpx import AsyncClient
from httpx_ws import aconnect_ws
Expand Down Expand Up @@ -135,7 +136,13 @@ async def test_http(unused_tcp_port: int):
async with Context(), AsyncClient() as http:
add_resource("foo")
add_resource("bar", name="another")
await ASGIComponent(app=application, port=unused_tcp_port).start()
await start_component(
ASGIComponent,
{
"app": application,
"port": unused_tcp_port,
},
)

# Ensure that the application got added as a resource
get_resource_nowait(ASGI3Application)
Expand All @@ -156,7 +163,13 @@ async def test_ws(unused_tcp_port: int):
async with Context():
add_resource("foo")
add_resource("bar", name="another")
await ASGIComponent(app=application, port=unused_tcp_port).start()
await start_component(
ASGIComponent,
{
"app": application,
"port": unused_tcp_port,
},
)

# Ensure that the application got added as a resource
get_resource_nowait(ASGI3Application)
Expand Down Expand Up @@ -189,7 +202,14 @@ async def test_middleware(unused_tcp_port: int, method: str):
async with Context(), AsyncClient() as http:
add_resource("foo")
add_resource("bar", name="another")
await ASGIComponent(app=application, port=unused_tcp_port, middlewares=middlewares).start()
await start_component(
ASGIComponent,
{
"middlewares": middlewares,
"app": application,
"port": unused_tcp_port,
},
)

# Ensure that the application got added as a resource
get_resource_nowait(ASGI3Application)
Expand Down
10 changes: 8 additions & 2 deletions tests/test_django.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import pytest
from asgiref.typing import ASGI3Application
from asphalt.core import Context, add_resource, get_resource_nowait
from asphalt.core import Context, add_resource, get_resource_nowait, start_component
from httpx import AsyncClient

try:
Expand All @@ -26,7 +26,13 @@ async def test_http(unused_tcp_port: int):
async with Context(), AsyncClient() as http:
add_resource("foo")
add_resource("bar", name="another")
await DjangoComponent(app=application, port=unused_tcp_port).start()
await start_component(
DjangoComponent,
{
"app": application,
"port": unused_tcp_port,
},
)

# Ensure that the application got added as a resource
asgi_app = get_resource_nowait(ASGI3Application)
Expand Down
42 changes: 30 additions & 12 deletions tests/test_fastapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,15 @@

import pytest
from asgiref.typing import ASGI3Application, HTTPScope, WebSocketScope
from asphalt.core import Component, Context, add_resource, get_resource_nowait, inject, resource
from asphalt.core import (
Component,
Context,
add_resource,
get_resource_nowait,
inject,
resource,
start_component,
)
from fastapi import FastAPI
from httpx import AsyncClient
from httpx_ws import aconnect_ws
Expand Down Expand Up @@ -54,9 +62,14 @@ async def start(self, app: FastAPI = resource()) -> None:
async with Context(), AsyncClient() as http:
add_resource("foo")
add_resource("bar", name="another")
await FastAPIComponent(
components=components, app=application, port=unused_tcp_port
).start()
await start_component(
FastAPIComponent,
{
"components": components,
"app": application,
"port": unused_tcp_port,
},
)

# Ensure that the application got added as a resource
asgi_app = get_resource_nowait(ASGI3Application)
Expand Down Expand Up @@ -108,9 +121,14 @@ async def start(self, app: FastAPI = resource()) -> None:
async with Context():
add_resource("foo")
add_resource("bar", name="another")
await FastAPIComponent(
components=components, app=application, port=unused_tcp_port
).start()
await start_component(
FastAPIComponent,
{
"components": components,
"app": application,
"port": unused_tcp_port,
},
)

# Ensure that the application got added as a resource
asgi_app = get_resource_nowait(ASGI3Application)
Expand All @@ -135,12 +153,11 @@ async def bad_root(request: Request, bad_resource=AsphaltDepends()) -> Response:
application.add_api_route("/", bad_root)

async with Context():
component = FastAPIComponent(app=application)
with pytest.raises(
TypeError,
match="Dependency 'bad_resource' in endpoint / is missing a type annotation",
):
await component.start()
await start_component(FastAPIComponent, {"app": application})


@pytest.mark.parametrize("method", ["direct", "dict"])
Expand All @@ -163,9 +180,10 @@ async def root(request: Request) -> Response:
application = FastAPI()
application.add_api_route("/", root)
async with Context(), AsyncClient() as http:
await FastAPIComponent(
port=unused_tcp_port, app=application, middlewares=middlewares
).start()
await start_component(
FastAPIComponent,
{"app": application, "port": unused_tcp_port, "middlewares": middlewares},
)

# Ensure that the application responds correctly to an HTTP request
response = await http.get(
Expand Down
Loading
Loading