| 1 |
#!/usr/bin/env python |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
from datetime import datetime, timedelta |
| 4 |
import pytest |
| 5 |
|
| 6 |
from aiohttp_sse_client2 import client as sse_client |
| 7 |
|
| 8 |
from .const import WPT_SERVER |
| 9 |
|
| 10 |
|
| 11 |
@pytest.mark.asyncio |
| 12 |
async def test_eventsource_close(): |
| 13 |
"""Test EventSource: close. |
| 14 |
|
| 15 |
..seealso: https://github.com/web-platform-tests/wpt/blob/master/ |
| 16 |
eventsource/eventsource-close.htm |
| 17 |
""" |
| 18 |
source = sse_client.EventSource(WPT_SERVER + 'resources/message.py') |
| 19 |
assert source.ready_state == sse_client.READY_STATE_CONNECTING |
| 20 |
await source.connect() |
| 21 |
assert source.ready_state == sse_client.READY_STATE_OPEN |
| 22 |
await source.close() |
| 23 |
assert source.ready_state == sse_client.READY_STATE_CLOSED |
| 24 |
|
| 25 |
|
| 26 |
@pytest.mark.asyncio |
| 27 |
async def test_eventsource_close_reconnect(): |
| 28 |
"""Test EventSource: close/reconnect. |
| 29 |
|
| 30 |
..seealso: https://github.com/web-platform-tests/wpt/blob/master/ |
| 31 |
eventsource/eventsource-close.htm |
| 32 |
""" |
| 33 |
count = 0 |
| 34 |
reconnected = False |
| 35 |
|
| 36 |
def on_error(): |
| 37 |
nonlocal count, reconnected |
| 38 |
if count == 1: |
| 39 |
assert source.ready_state == sse_client.READY_STATE_CONNECTING |
| 40 |
reconnected = True |
| 41 |
elif count == 2: |
| 42 |
assert source.ready_state == sse_client.READY_STATE_CONNECTING |
| 43 |
count += 1 |
| 44 |
elif count == 3: |
| 45 |
assert source.ready_state == sse_client.READY_STATE_CLOSED |
| 46 |
else: |
| 47 |
assert False |
| 48 |
|
| 49 |
async with sse_client.EventSource( |
| 50 |
WPT_SERVER + 'resources/reconnect-fail.py?id=' + |
| 51 |
str(datetime.utcnow().timestamp()), |
| 52 |
reconnection_time=timedelta(milliseconds=2), |
| 53 |
on_error=on_error |
| 54 |
) as source: |
| 55 |
try: |
| 56 |
async for e in source: |
| 57 |
if count == 0: |
| 58 |
assert reconnected is False |
| 59 |
assert e.data == "opened" |
| 60 |
elif count == 1: |
| 61 |
assert reconnected is True |
| 62 |
assert e.data == "reconnected" |
| 63 |
else: |
| 64 |
assert False |
| 65 |
count += 1 |
| 66 |
except ConnectionError: |
| 67 |
pass |