|
1 | 1 | import gzip |
2 | 2 | import json |
3 | 3 | import sys |
| 4 | +import time |
4 | 5 | from http.client import HTTPConnection |
5 | 6 | from io import BytesIO |
6 | 7 | from typing import Tuple |
7 | 8 | from urllib.parse import quote |
8 | 9 |
|
9 | 10 | import pytest |
10 | | -from tornado.httpclient import HTTPClientError |
| 11 | +from tornado.httpclient import AsyncHTTPClient, HTTPClientError |
11 | 12 | from tornado.websocket import websocket_connect |
12 | 13 |
|
13 | 14 | # use ipv4 for CI, etc. |
@@ -343,6 +344,39 @@ def test_server_content_encoding_header( |
343 | 344 | assert f.read() == b"this is a test" |
344 | 345 |
|
345 | 346 |
|
| 347 | +async def test_eventstream(a_server_port_and_token: Tuple[int, str]) -> None: |
| 348 | + PORT, TOKEN = a_server_port_and_token |
| 349 | + # The test server under eventstream.py will send back monotonically increasing numbers |
| 350 | + # starting at 0 until the specified limit, with a 500ms gap between them. We test that: |
| 351 | + # 1. We get back as many callbacks from our streaming read as the total number, |
| 352 | + # as the server does a flush after writing each entry. |
| 353 | + # 2. The streaming entries are read (with some error margin) around the 500ms mark, to |
| 354 | + # ensure this is *actually* being streamed |
| 355 | + limit = 3 |
| 356 | + last_cb_time = time.perf_counter() |
| 357 | + times_called = 0 |
| 358 | + stream_read_intervals = [] |
| 359 | + |
| 360 | + def streaming_cb(data): |
| 361 | + nonlocal times_called, last_cb_time, stream_read_intervals |
| 362 | + time_taken = time.perf_counter() - last_cb_time |
| 363 | + last_cb_time = time.perf_counter() |
| 364 | + stream_read_intervals.append(time_taken) |
| 365 | + times_called += 1 |
| 366 | + |
| 367 | + url = f"http://{LOCALHOST}:{PORT}/python-eventstream/stream/{limit}?token={TOKEN}" |
| 368 | + client = AsyncHTTPClient() |
| 369 | + await client.fetch( |
| 370 | + url, |
| 371 | + headers={"Accept": "text/event-stream"}, |
| 372 | + request_timeout=22, |
| 373 | + streaming_callback=streaming_cb, |
| 374 | + ) |
| 375 | + assert times_called == limit |
| 376 | + print(stream_read_intervals) |
| 377 | + assert all([0.45 < t < 0.7 for t in stream_read_intervals]) |
| 378 | + |
| 379 | + |
346 | 380 | async def test_server_proxy_websocket_messages( |
347 | 381 | a_server_port_and_token: Tuple[int, str] |
348 | 382 | ) -> None: |
|
0 commit comments