0

Hi I'm trying to test an SSE (Server-Sent Events) endpoint implemented with FastAPI using pytest.

In the following sample code, the endpoint works. But the test stops at client.get('/') maybe because TestClient does not SSE.

# test_main.py
from fastapi import FastAPI, Request
from fastapi.testclient import TestClient
from fastapi.responses import StreamingResponse
import asyncio
import json   

app = FastAPI()

@app.get('/')
async def main(request: Request) -> StreamingResponse:
    async def gen():
        while True: 
            yield 'data: ' + json.dumps({'msg': 'Hello World!'}) + '\n\n'
            await asyncio.sleep(0.5)
            
    return StreamingResponse(gen(), media_type='text/event-stream')
    
    
client = TestClient(app)
    
def test_read_stream():
    response = client.get("/")
    assert response.status_code == 200
    for line in response.iter_lines():
        assert line == 'data: {"msg": "Hello World"}'

How can I test the API using pytest?

ywat
  • 2,757
  • 5
  • 24
  • 32
  • Does [this](https://stackoverflow.com/a/75760884/17865804) answer your question? – Chris Jul 13 '23 at 04:48
  • Related answers may also be found [here](https://stackoverflow.com/a/75837557/17865804) and [here](https://stackoverflow.com/a/76122475/17865804) – Chris Jul 13 '23 at 04:49

0 Answers0