| 1 |
import sys |
| 2 |
from pathlib import Path |
| 3 |
|
| 4 |
import pytest |
| 5 |
from quart import abort, Quart, ResponseReturnValue, send_file, websocket |
| 6 |
from quart.testing import WebsocketResponseError |
| 7 |
|
| 8 |
from quart_trio import QuartTrio |
| 9 |
|
| 10 |
if sys.version_info < (3, 11): |
| 11 |
from exceptiongroup import BaseExceptionGroup |
| 12 |
|
| 13 |
|
| 14 |
@pytest.fixture |
| 15 |
def app() -> Quart: |
| 16 |
app = QuartTrio(__name__) |
| 17 |
|
| 18 |
@app.route("/") |
| 19 |
async def index() -> ResponseReturnValue: |
| 20 |
return "index" |
| 21 |
|
| 22 |
@app.websocket("/ws/") |
| 23 |
async def ws() -> None: |
| 24 |
# async for message in websocket: |
| 25 |
while True: |
| 26 |
message = await websocket.receive() |
| 27 |
await websocket.send(message) |
| 28 |
|
| 29 |
@app.websocket("/ws/abort/") |
| 30 |
async def ws_abort() -> None: |
| 31 |
abort(401) |
| 32 |
|
| 33 |
return app |
| 34 |
|
| 35 |
|
| 36 |
@pytest.mark.trio |
| 37 |
async def test_index(app: Quart) -> None: |
| 38 |
test_client = app.test_client() |
| 39 |
response = await test_client.get("/") |
| 40 |
assert response.status_code == 200 |
| 41 |
assert b"index" in (await response.get_data()) |
| 42 |
|
| 43 |
|
| 44 |
@pytest.mark.trio |
| 45 |
async def test_websocket(app: Quart) -> None: |
| 46 |
test_client = app.test_client() |
| 47 |
data = b"bob" |
| 48 |
async with test_client.websocket("/ws/") as test_websocket: |
| 49 |
await test_websocket.send(data) |
| 50 |
result = await test_websocket.receive() |
| 51 |
assert result == data |
| 52 |
|
| 53 |
|
| 54 |
@pytest.mark.trio |
| 55 |
async def test_websocket_abort(app: Quart) -> None: |
| 56 |
test_client = app.test_client() |
| 57 |
try: |
| 58 |
async with test_client.websocket("/ws/abort/") as test_websocket: |
| 59 |
await test_websocket.receive() |
| 60 |
except BaseExceptionGroup as error: |
| 61 |
for exception in error.exceptions: |
| 62 |
if isinstance(exception, WebsocketResponseError): |
| 63 |
assert exception.response.status_code == 401 |
| 64 |
|
| 65 |
|
| 66 |
@pytest.mark.trio |
| 67 |
async def test_send_file_path(tmp_path: Path) -> None: |
| 68 |
app = QuartTrio(__name__) |
| 69 |
file_ = tmp_path / "send.img" |
| 70 |
file_.write_text("something") |
| 71 |
async with app.app_context(): |
| 72 |
response = await send_file(file_) |
| 73 |
assert (await response.get_data(as_text=False)) == file_.read_bytes() |