-
Notifications
You must be signed in to change notification settings - Fork 20
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
Add tests for ASGI specification compliance #50
Open
LucidDan
wants to merge
10
commits into
vinissimus:master
Choose a base branch
from
LucidDan:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
0610b93
Add tests for ASGI specification compliance
LucidDan b5f4d74
Allow http.response.body event with no 'body' key
LucidDan dbe96c4
Allow http.response.start event with no 'headers' key
LucidDan f655b85
Ensure websocket events include 'asgi' in scope
LucidDan 3ff2e15
Disable lifespan protocol if apps do not support it
LucidDan 732b1e6
Remove test for custom scope
LucidDan 2037ec9
Fix formatting
LucidDan b6f93cd
Merge branch 'vinissimus:master' into master
LucidDan 3f79e78
Notify the user if lifespan protocol raised an exception
LucidDan cbb6100
Fix method is uppercased in HTTP
LucidDan File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
"""Exceptions for TestClient | ||
|
||
Base Exception class and sub-classed exceptions to make it easy | ||
(and in some cases, possible at all) to handle errors in different | ||
ways. | ||
""" | ||
from async_asgi_testclient.utils import Message | ||
from typing import Optional | ||
|
||
|
||
class TestClientError(Exception): | ||
"""An error in async_asgi_testclient""" | ||
|
||
def __init__(self, *args, message: Optional[Message] = None): | ||
super().__init__(*args) | ||
self.message = message |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,175 @@ | ||
"""Test setup for ASGI spec tests | ||
|
||
Mock application used for testing ASGI standard compliance. | ||
""" | ||
from enum import Enum | ||
from functools import partial | ||
from sys import version_info as PY_VER # noqa | ||
|
||
import pytest | ||
|
||
|
||
class AppState(Enum): | ||
PREINIT = 0 | ||
INIT = 1 | ||
READY = 2 | ||
SHUTDOWN = 3 | ||
|
||
|
||
class BaseMockApp(object): | ||
"""A mock application object passed to TestClient for the tests""" | ||
|
||
# Make it easy to override these for lifespan related test scenarios | ||
lifespan_startup_message = {"type": "lifespan.startup.complete", "message": "OK"} | ||
lifespan_shutdown_message = {"type": "lifespan.shutdown.complete", "message": "OK"} | ||
use_lifespan = True | ||
|
||
def __init__(self, **kwargs): | ||
for k, v in kwargs: | ||
setattr(self, k, v) | ||
self.state = AppState.PREINIT | ||
|
||
async def lifespan_startup(self, scope, receive, send, msg): | ||
if self.state == AppState.READY: | ||
# Technically, this isn't explicitly forbidden in the spec. | ||
# But I think it should not happen. | ||
raise RuntimeError("Received more than one lifespan.startup") | ||
self.state = AppState.READY | ||
return await send(self.lifespan_startup_message) | ||
|
||
async def lifespan_shutdown(self, scope, receive, send, msg): | ||
if self.state == AppState.SHUTDOWN: | ||
# Technically, this isn't explicitly forbidden in the spec. | ||
# But I think it should not happen. | ||
raise RuntimeError("Received more than one lifespan.shutdown") | ||
self.state = AppState.SHUTDOWN | ||
return await send(self.lifespan_shutdown_message) | ||
|
||
async def lifespan(self, scope, receive, send): | ||
if not self.use_lifespan: | ||
raise RuntimeError(f"Type '{scope['type']}' is not supported.") | ||
while True: | ||
try: | ||
msg = await receive() | ||
except RuntimeError as e: | ||
if e.args == ("Event loop is closed",): | ||
return | ||
else: | ||
raise | ||
|
||
if msg["type"] == "lifespan.startup": | ||
await self.lifespan_startup(scope, receive, send, msg) | ||
elif msg["type"] == "lifespan.shutdown": | ||
await self.lifespan_shutdown(scope, receive, send, msg) | ||
else: | ||
raise RuntimeError(f"Received unknown message type '{msg['type']}") | ||
if self.state == AppState.SHUTDOWN: | ||
return | ||
|
||
async def http_request(self, scope, receive, send, msg): | ||
# Default behaviour, just send a minimal response with OK to any request | ||
await send({"type": "http.response.start", "headers": [], "status": 200}) | ||
await send({"type": "http.response.body", "body": b"OK"}) | ||
|
||
async def http_disconnect(self, scope, receive, send, msg): | ||
raise RuntimeError(f"Received http.disconnect message {msg}") | ||
|
||
async def http(self, scope, receive, send): | ||
msg = [] | ||
# Receive http.requests until http.disconnect or more_body = False | ||
while True: | ||
msg.append(await receive()) | ||
if msg[-1]["type"] == "http.disconnect" or not msg[-1].get( | ||
"more_body", False | ||
): | ||
break | ||
if msg[0]["type"] == "http.disconnect": | ||
# Honestly this shouldn't really happen, but it's allowed in spec, so check. | ||
return await self.http_disconnect(scope, receive, send, msg) | ||
else: | ||
return await self.http_request(scope, receive, send, msg) | ||
|
||
async def websocket_connect(self, scope, receive, send, msg, msg_history): | ||
await send({"type": "websocket.accept"}) | ||
return True | ||
|
||
async def websocket_receive(self, scope, receive, send, msg, msg_history): | ||
return True | ||
|
||
async def websocket_disconnect(self, scope, receive, send, msg, msg_history): | ||
return False | ||
|
||
async def websocket(self, scope, receive, send): | ||
msg_history = [] | ||
while True: | ||
msg = await receive() | ||
|
||
# Send websocket events to a handler | ||
func = getattr( | ||
self, msg["type"].replace(".", "_").replace("-", "__"), "handle_unknown" | ||
) | ||
res = await func(scope, receive, send, msg, msg_history) | ||
msg_history.append(msg) | ||
|
||
# If the event handler returns false, assume we closed the socket. | ||
if msg["type"] == "websocket.disconnect" or not res: | ||
return | ||
|
||
async def handle_unknown(self, scope, receive, send): | ||
if self.state != AppState.READY: | ||
raise RuntimeError( | ||
"Received another request before lifespan.startup.complete sent" | ||
) | ||
raise RuntimeError(f"Type '{scope['type']}' is not supported.") | ||
|
||
async def handle_all(self, scope, receive, send): | ||
# Do nothing unless something monkeypatches us | ||
pass | ||
|
||
async def asgi_call(self, scope, receive, send): | ||
# Initial catch-all, for testing things like scope type itself | ||
await self.handle_all(scope, receive, send) | ||
|
||
if self.state == AppState.PREINIT: | ||
if self.use_lifespan: | ||
self.state = AppState.INIT | ||
else: | ||
self.state = AppState.READY | ||
if self.state == AppState.SHUTDOWN: | ||
raise RuntimeError(f"Got message after shutting down: {scope}") | ||
|
||
# call hooks based on scope type, so we can monkeypatch them in tests | ||
# the lifespan, http, and websocket protocol types all have simple methods already | ||
# implemented. | ||
func = getattr( | ||
self, scope["type"].replace(".", "_").replace("-", "__"), "handle_unknown" | ||
) | ||
return await func(scope, receive, send) | ||
|
||
|
||
class MockApp(BaseMockApp): | ||
"""Modern ASGI single-callable app""" | ||
|
||
async def __call__(self, scope, receive, send): | ||
return await super().asgi_call(scope, receive, send) | ||
|
||
|
||
class LegacyMockApp(BaseMockApp): | ||
"""Legacy ASGI 'two-callable' app""" | ||
|
||
def __call__(self, scope): | ||
return partial(super().asgi_call, scope) | ||
|
||
|
||
@pytest.fixture(scope="function") | ||
def mock_app(): | ||
"""Create a mock ASGI App to test the TestClient against""" | ||
|
||
return MockApp() | ||
|
||
|
||
@pytest.fixture(scope="function") | ||
def legacy_mock_app(): | ||
"""Create a mock legacy ASGI App to test the TestClient against""" | ||
|
||
return LegacyMockApp() |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Should we check that if have not received a
http.disconnect
, it is ahttp.request
?Like:
So we can catch unexpected events sent by asgi-testclient.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes this makes sense. That whole function could probably be rewritten to be more readable too, now that I look at it after a break. ;-)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
great!