frankie567 / httpx-ws

WebSocket support for HTTPX
https://frankie567.github.io/httpx-ws/
MIT License
110 stars 17 forks source link

Propagate server errors in ASGI testing #30

Closed ysmu closed 1 year ago

ysmu commented 1 year ago

Describe the bug

I'm writing some tests with the library and I noticed that this library does not propagate the server errors like the httpx test client and hangs the test indefinitely. Call the test with some asyncio timeout solves the hang issue, but I'm still unable to see the stacktrace of the exception. The issue gets slightly worse if the exception happens before websocket.accept(): it appears that it would block on thread.join() somewhere. In Linux this can be aborted with a Ctrl-C but in Windows this is uninterruptable :(

To Reproduce

I took the sample almost as-is from the docs. The main change is that I added a 1/0 in ws_hello.

import asyncio

import httpx
from httpx_ws import aconnect_ws
from httpx_ws.transport import ASGIWebSocketTransport
from starlette.applications import Starlette
from starlette.responses import HTMLResponse
from starlette.routing import Route, WebSocketRoute

async def http_hello(request):
    return HTMLResponse("Hello World!")

async def ws_hello(websocket):
    1/0
    await websocket.accept()
    await websocket.send_text("Hello World!")
    await websocket.close()

app = Starlette(
    routes=[
        Route("/http", http_hello),
        WebSocketRoute("/ws", ws_hello),
    ],
)

async def main():
    async with httpx.AsyncClient(transport=ASGIWebSocketTransport(app)) as client:
        http_response = await client.get("http://server/http")
        assert http_response.status_code == 200

        print("connecting to ws")
        async with aconnect_ws("http://server/ws", client) as ws:
            message = await ws.receive_text()
            assert message == "Hello World!"

    print("done")

asyncio.run(main())

Expected behavior

The httpx client to propagate the error the server encountered.

Configuration

Python 3.10.4 (tags/v3.10.4:9d38120, Mar 23 2022, 23:13:41) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import starlette, httpx, httpx_ws
>>> starlette.__version__
'0.26.1'
>>> httpx.__version__
'0.23.3'
>>> httpx_ws.__version__
'0.3.0'
frankie567 commented 1 year ago

Thank you for the detailed and relevant bug report, @ysmu 👍 This is fixed! I'll make a release.

frankie567 commented 1 year ago

@all-contributors add @ysmu for bug

allcontributors[bot] commented 1 year ago

@frankie567

I've put up a pull request to add @ysmu! :tada: