frankie567 / httpx-ws

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

`ASGIWebSocketTransport` does not respect the response headers of the ASGI app during WebSocket handshake. #56

Closed WSH032 closed 11 months ago

WSH032 commented 11 months ago

Describe the bug

When testing with ASGIWebSocketTransport, it does not respect the response headers returned by the ASGI app, which includes the subprotocol header accepted by the app.

To Reproduce

import asyncio

import httpx
from fastapi import FastAPI
from httpx_ws import WebSocketDisconnect, aconnect_ws
from httpx_ws.transport import ASGIWebSocketTransport
from starlette.websockets import WebSocket

app = FastAPI()

@app.websocket("/")
async def _(ws: WebSocket):
    await ws.accept(subprotocol="foo")  # accept `foo` subprotocol
    await asyncio.sleep(0.1)
    await ws.close(1000, "bar")

httpx_client = httpx.AsyncClient(transport=ASGIWebSocketTransport(app=app))

async with aconnect_ws(
    "ws://www.example.com/", subprotocols=["foo", "bar"], client=httpx_client
) as ws:
    print(ws.subprotocol)  # expect `foo` but get `None`
    await asyncio.sleep(0.2)
    await ws.close(1000, "baz")

assert ws.subprotocol == "foo"  # AssertionError

Expected behavior

https://github.com/frankie567/httpx-ws/blob/1e1c252c2b678f8cc475e1c1546980a784f19702/httpx_ws/transport.py#L185

This code should not be hard-coded to generate a fixed response; rather, it should return the response generated by the app.

Configuration

Additional context

None.

frankie567 commented 11 months ago

Thank you for the detailed report @WSH032! That was indeed a miss in the implementation. FIxed in a43a1e256d8f07ad2b986210af21e18818cc2a4f