# -*- coding: utf-8 -*-
from unittest import mock

from aiohttp.web import WebSocketResponse

from homehub_backend.app import app
from homehub_backend.lib import websocket


async def test_notify_subscribers():
    # Given
    error_subscriber = WebSocketResponse()
    error_subscriber['SUBSCRIBER_ID'] = 'test_notify_subscribers.error_subscriber'
    app['SUBSCRIBERS'].append(error_subscriber)

    ok_subscriber = WebSocketResponse()
    ok_subscriber['SUBSCRIBER_ID'] = 'test_notify_subscribers.ok_subscriber'
    app['SUBSCRIBERS'].append(ok_subscriber)

    closed_subscriber = WebSocketResponse()
    closed_subscriber['SUBSCRIBER_ID'] = 'test_notify_subscribers.closed_subscriber'
    closed_subscriber._closed = True
    app['SUBSCRIBERS'].append(closed_subscriber)

    payload = {'spam': True}

    with mock.patch.object(error_subscriber, 'send_json') as error_subscriber_send_json:
        with mock.patch.object(ok_subscriber, 'send_json'):
            with mock.patch.object(closed_subscriber, 'send_json'):
                error_subscriber_send_json.side_effect = RuntimeError('FIAL')

                # When
                await websocket.notify_subscribers(app, payload)

                # Then
                error_subscriber.send_json.assert_called_with(payload)
                ok_subscriber.send_json.assert_called_with(payload)
                assert not closed_subscriber.send_json.called

    # After
    app['SUBSCRIBERS'].remove(error_subscriber)
    app['SUBSCRIBERS'].remove(ok_subscriber)
    app['SUBSCRIBERS'].remove(closed_subscriber)
