async def test_replays_closing_waits_for_replay(mock_replays,
                                                mock_replay_builder,
                                                mock_conn_plus_head,
                                                event_loop):
    writer = mock_conn_plus_head(ConnectionHeader.Type.WRITER, 1)
    mock_replay = mock_replays()
    mock_replay_builder.side_effect = [mock_replay]
    replays = Replays(mock_replay_builder)

    await replays.handle_connection(*writer)
    f = asyncio.ensure_future(replays.stop_all())
    await exhaust_callbacks(event_loop)
    assert not f.done()
    mock_replay.wait_for_ended._lock.set()
    await f
async def test_connections_are_not_accepted_when_closing(
        mock_replays, mock_replay_builder, mock_conn_plus_head, event_loop):
    writer = mock_conn_plus_head(ConnectionHeader.Type.WRITER, 1)
    writer_2 = mock_conn_plus_head(ConnectionHeader.Type.WRITER, 1)

    mock_replay = mock_replays()
    mock_replay_builder.side_effect = [mock_replay, mock_replay]
    replays = Replays(mock_replay_builder)

    await replays.handle_connection(*writer)
    f = asyncio.ensure_future(replays.stop_all())
    await exhaust_callbacks(event_loop)

    with pytest.raises(CannotAcceptConnectionError):
        await replays.handle_connection(*writer_2)

    mock_replay.wait_for_ended._lock.set()
    await f