import asyncio
import pytest

from aioredis.pubsub import Receiver


@pytest.mark.run_loop
async def test_pubsub_receiver_iter(create_redis, server, loop):
    sub = await create_redis(server.tcp_address, loop=loop)
    pub = await create_redis(server.tcp_address, loop=loop)

    mpsc = Receiver(loop=loop)

    async def coro(mpsc):
        lst = []
        async for msg in mpsc.iter():
            lst.append(msg)
        return lst

    tsk = asyncio.ensure_future(coro(mpsc), loop=loop)
    snd1, = await sub.subscribe(mpsc.channel('chan:1'))
    snd2, = await sub.subscribe(mpsc.channel('chan:2'))
    snd3, = await sub.psubscribe(mpsc.pattern('chan:*'))

    await pub.publish_json('chan:1', {'Hello': 'World'})
    await pub.publish_json('chan:2', ['message'])
    mpsc.stop()
    await asyncio.sleep(0, loop=loop)
    assert await tsk == [
        (snd1, b'{"Hello": "World"}'),
        (snd3, (b'chan:1', b'{"Hello": "World"}')),
        (snd2, b'["message"]'),
        (snd3, (b'chan:2', b'["message"]')),
        ]
    assert not mpsc.is_active

@@ -655,24 +655,38 @@
 an:*'))%0A%0A   
+ subscribers =
  await pub.p
@@ -726,24 +726,65 @@
 World'%7D)%0A   
+ assert subscribers %3E 1%0A    subscribers =
  await pub.p
@@ -817,24 +817,70 @@
 ssage'%5D)%0A   
+ assert subscribers %3E 1%0A    loop.call_later(0,
  mpsc.stop()
@@ -881,14 +881,15 @@
 stop
-(
 )%0A   
+ #
  awa
@@ -1153,8 +1153,627 @@
 _active%0A
+%0A%0A@pytest.mark.run_loop(timeout=5)%0Aasync def test_pubsub_receiver_call_stop_with_empty_queue(%0A        create_redis, server, loop):%0A    sub = await create_redis(server.tcp_address, loop=loop)%0A    pub = await create_redis(server.tcp_address, loop=loop)%0A%0A    mpsc = Receiver(loop=loop)%0A%0A    # FIXME: currently at least one subscriber is needed%0A    snd1, = await sub.subscribe(mpsc.channel('chan:1'))%0A%0A    now = loop.time()%0A    loop.call_later(.5, mpsc.stop)%0A    async for _ in mpsc.iter():%0A        assert False, %22StopAsyncIteration not raised%22%0A    dt = loop.time() - now%0A    assert dt %3C= 1.5%0A    assert not mpsc.is_active%0A

add failing test