import asyncio
import random

import pytest

from clarabot_nano.common.handler.stream import ServerResponsePartSerializationHelper


@pytest.mark.asyncio
async def test_common_handler_stream():
    s = ServerResponsePartSerializationHelper("test stream")
    res = []

    async def _request(part: int):
        await asyncio.sleep(random.random())
        async with s.serialize_processing(part):
            res.append(part)

    async with asyncio.timeout(1.25):
        await asyncio.gather(*[asyncio.create_task(_request(i)) for i in range(100)])

    assert res == list(range(100))

    with pytest.raises(Exception, match="Duplicate request for "):
        async with s.serialize_processing(99):
            assert False
