Example #1
0
async def test_listen(ds: IdexDatastream):
    msg_data = '{"payload":"{"some": "data"}"}'

    ds._check_connection = CoroutineMock()
    ds._ws = MagicMock()
    ds._ws.closed = False
    ds._ws.__aiter__.return_value = (msg_data, )

    processed_message = {'a': 'b'}
    ds._process_message: Mock = Mock()
    ds._process_message.return_value = processed_message

    msg = None
    async for m in ds.listen():
        msg = m
        break

    ds._process_message.assert_called_once_with(msg_data)
    assert msg == processed_message
Example #2
0
async def channel_seeder(channel_tdef, loop, tmp_path_factory):  # pylint: disable=unused-argument, redefined-outer-name
    config = LibtorrentSettings()
    config.dht = False
    config.upnp = False
    config.natpmp = False
    config.lsd = False
    seeder_dlmgr = DownloadManager(
        state_dir=tmp_path_factory.mktemp('state_dir'),
        config=config,
        notifier=MagicMock(),
        peer_mid=b"0000")
    seeder_dlmgr.metadata_tmpdir = tmp_path_factory.mktemp('metadata_tmpdir')
    seeder_dlmgr.initialize()
    dscfg_seed = DownloadConfig()
    dscfg_seed.set_dest_dir(TESTS_DATA_DIR / 'sample_channel')
    upload = seeder_dlmgr.start_download(tdef=channel_tdef, config=dscfg_seed)
    await upload.wait_for_status(DLSTATUS_SEEDING)
    yield seeder_dlmgr
    await seeder_dlmgr.shutdown()
async def test_health_postgres_connection(mock_res, res):
    """

    :param mock_res:
    :param res:
    :return:
    """
    postgres = MagicMock(PostgreSQLDb(""))

    class EngineMock:
        async def execute(self, *args, **kwargs):
            if not mock_res:
                raise Exception("blah fake exception")
            return mock_res

    postgres.engine.acquire().__aenter__.return_value = EngineMock
    postgres.engine.acquire().__aexit__.return_value = None
    health_service = HealthService(postgres)
    assert await health_service.postgres_connection_check() == res
Example #4
0
async def test_homekit_setup(hass, hk_driver):
    """Test setup of bridge and driver."""
    entry = MockConfigEntry(
        domain=DOMAIN,
        data={CONF_NAME: "mock_name", CONF_PORT: 12345},
        source=SOURCE_IMPORT,
    )
    homekit = HomeKit(
        hass,
        BRIDGE_NAME,
        DEFAULT_PORT,
        None,
        {},
        {},
        DEFAULT_SAFE_MODE,
        advertise_ip=None,
        entry_id=entry.entry_id,
    )

    zeroconf_mock = MagicMock()
    with patch(
        f"{PATH_HOMEKIT}.accessories.HomeDriver", return_value=hk_driver
    ) as mock_driver, patch("homeassistant.util.get_local_ip") as mock_ip:
        mock_ip.return_value = IP_ADDRESS
        await hass.async_add_executor_job(homekit.setup, zeroconf_mock)

    path = get_persist_fullpath_for_entry_id(hass, entry.entry_id)
    assert isinstance(homekit.bridge, HomeBridge)
    mock_driver.assert_called_with(
        hass,
        entry.entry_id,
        BRIDGE_NAME,
        address=IP_ADDRESS,
        port=DEFAULT_PORT,
        persist_file=path,
        advertised_address=None,
        zeroconf_instance=zeroconf_mock,
    )
    assert homekit.driver.safe_mode is False

    # Test if stop listener is setup
    assert hass.bus.async_listeners().get(EVENT_HOMEASSISTANT_STOP) == 1
Example #5
0
async def test_horizon_retry_successes(setup):

    class MockedGet:
        def __init__(self, return_value):
            self.return_value = return_value

        async def __aenter__(self):
            return self.return_value

        async def __aexit__(self, exc_type, exc_val, exc_tb):
            pass

    async with Horizon(setup.horizon_endpoint_uri) as horizon:
        real_resp = await horizon._session.get(setup.horizon_endpoint_uri + "/accounts/GA3FLH3EVYHZUHTPQZU63JPX7ECJQL2XZFCMALPCLFYMSYC4JKVLAJWM")
        horizon._session.get = MagicMock(side_effect=[ClientConnectionError, MockedGet(real_resp)])
        horizon.num_retries = 3
        res = await horizon.account('GA3FLH3EVYHZUHTPQZU63JPX7ECJQL2XZFCMALPCLFYMSYC4JKVLAJWM')

        assert horizon._session.get.call_count == 2
        assert res
Example #6
0
def test_games_reformat_to_dict(hass):
    """Test old data format is converted to new format."""
    with patch(
            "homeassistant.components.ps4.load_json",
            return_value=MOCK_GAMES_DATA_OLD_STR_FORMAT,
    ), patch("homeassistant.components.ps4.save_json",
             side_effect=MagicMock()), patch("os.path.isfile",
                                             return_value=True):
        mock_games = ps4.load_games(hass)

    # New format is a nested dict.
    assert isinstance(mock_games, dict)
    assert mock_games["mock_id"][ATTR_MEDIA_TITLE] == "mock_title"
    assert mock_games["mock_id2"][ATTR_MEDIA_TITLE] == "mock_title2"
    for mock_game in mock_games:
        mock_data = mock_games[mock_game]
        assert isinstance(mock_data, dict)
        assert mock_data
        assert mock_data[ATTR_MEDIA_IMAGE_URL] is None
        assert mock_data[ATTR_LOCKED] is False
        assert mock_data[ATTR_MEDIA_CONTENT_TYPE] == MEDIA_TYPE_GAME
Example #7
0
def test_send_message_without_sender():
    class SendBehaviour(OneShotBehaviour):
        async def run(self):
            msg = Message()
            await self.send(msg)
            self.kill()

    agent = make_connected_agent()
    agent.start(auto_register=False)

    agent.aiothread.client = MagicMock()
    agent.client.send = CoroutineMock()
    behaviour = SendBehaviour()
    agent.add_behaviour(behaviour)

    wait_for_behaviour_is_killed(behaviour)

    msg_arg = agent.client.send.await_args[0][0]
    assert msg_arg.from_ == aioxmpp.JID.fromstr("fake@jid")

    agent.stop()
Example #8
0
def _mock_powerwall_return_value(
    site_info=None,
    charge=None,
    sitemaster=None,
    meters=None,
    grid_status=None,
    status=None,
    device_type=None,
    serial_numbers=None,
):
    powerwall_mock = MagicMock(Powerwall("1.2.3.4"))
    powerwall_mock.get_site_info = Mock(return_value=site_info)
    powerwall_mock.get_charge = Mock(return_value=charge)
    powerwall_mock.get_sitemaster = Mock(return_value=sitemaster)
    powerwall_mock.get_meters = Mock(return_value=meters)
    powerwall_mock.get_grid_status = Mock(return_value=grid_status)
    powerwall_mock.get_status = Mock(return_value=status)
    powerwall_mock.get_device_type = Mock(return_value=device_type)
    powerwall_mock.get_serial_numbers = Mock(return_value=serial_numbers)

    return powerwall_mock
Example #9
0
    async def test_send_mail_from_disk_success(self, envelope_peer_spooled):
        file_path = MagicMock(Path)
        file_manager = MagicMock(FileManager)
        file_manager.open_file = CoroutineMock()
        file_manager.open_file.return_value = envelope_peer_spooled
        scheduler = MagicMock(BaseScheduler)
        scheduler.remove_job = MagicMock()
        session = MagicMock(Session)
        session.mr_agent = MagicMock()
        session.mr_agent.send_mail = CoroutineMock()
        session.mr_agent.send_mail.return_value = True

        result = await ModernRelay.relay.send_mail_from_disk(file_path, file_manager, scheduler, session)

        assert result
        scheduler.remove_job.assert_called_once()
Example #10
0
async def test_special_kwargs_added(fn, resource):
    body = {'metadata': {'uid': 'uid', 'name': 'name', 'namespace': 'ns'},
            'spec': {'field': 'value'},
            'status': {'info': 'payload'}}

    # Values can be any.
    cause = ResourceChangingCause(
        logger=logging.getLogger('kopf.test.fake.logger'),
        resource=resource,
        patch=Patch(),
        initial=False,
        reason=Reason.NOOP,
        body=body,
        diff=object(),
        old=object(),
        new=object(),
    )

    fn = MagicMock(fn)
    await invoke(fn, cause=cause)

    assert fn.called
    assert fn.call_count == 1

    assert len(fn.call_args[1]) >= 2
    assert fn.call_args[1]['cause'] is cause
    assert fn.call_args[1]['event'] is cause.reason  # deprecated
    assert fn.call_args[1]['reason'] is cause.reason
    assert fn.call_args[1]['body'] is cause.body
    assert fn.call_args[1]['spec'] == cause.body['spec']
    assert fn.call_args[1]['meta'] == cause.body['metadata']
    assert fn.call_args[1]['status'] == cause.body['status']
    assert fn.call_args[1]['diff'] is cause.diff
    assert fn.call_args[1]['old'] is cause.old
    assert fn.call_args[1]['new'] is cause.new
    assert fn.call_args[1]['patch'] is cause.patch
    assert fn.call_args[1]['logger'] is cause.logger
    assert fn.call_args[1]['uid'] == cause.body['metadata']['uid']
    assert fn.call_args[1]['name'] == cause.body['metadata']['name']
    assert fn.call_args[1]['namespace'] == cause.body['metadata']['namespace']
Example #11
0
def dummy_db_pool(monkeypatch):
    """
    A fixture which provides a mock database connection.

    Yields
    ------
    MagicMock
        The mock db connection that will be used
    """
    dummy = MagicMock()

    # A MagicMock can't be used in an 'await' expression,
    # so we need to make connection.set_type_codec a CoroutineMock
    # (awaited in stream_result_as_json())
    dummy.acquire.return_value.__aenter__.return_value.set_type_codec = CoroutineMock(
    )

    async def f(*args, **kwargs):
        return dummy

    monkeypatch.setattr(asyncpg, "create_pool", f)
    yield dummy
Example #12
0
def mock_get_schedules_response(
    schedule_object, ) -> Generator[MagicMock, Any, None]:
    """Fixture for mocking the get_schedules response.

    Args:
      schedule_object: Fixture of mocked ``SwitcherV2Schedule`` object.

    Yields:
      Mocked ``SwitcherV2GetScheduleResponseMSG`` object.

    """
    mock_response = MagicMock(messages.SwitcherV2GetScheduleResponseMSG)
    mock_response.successful = True
    mock_response.found_schedules = True
    mock_response.get_schedules = [schedule_object]
    mock_response.msg_type = messages.ResponseMessageType.GET_SCHEDULES

    with patch(
            "request_handlers.messages.SwitcherV2GetScheduleResponseMSG",
            new=mock_response,
    ) as patcher:
        yield patcher
Example #13
0
    async def test_should_log_if_hook_fail(self, format_tb, repr):
        logger = MagicMock()
        exception = Exception()

        async def before_consume(msg):
            raise exception

        self.monitor._logger = logger
        self.hook1.before_consume = before_consume
        self.hook2.before_consume = CoroutineMock()
        await self.monitor.dispatch_before_consume({})
        repr.assert_called_once_with(exception)
        format_tb.assert_called_once_with(exception.__traceback__)
        logger.error.assert_called_once_with({
            "message":
            f"Error on hook method {before_consume}",
            "exception":
            repr.return_value,
            "traceback":
            format_tb.return_value,
        })
        self.hook2.before_consume.assert_called_with({})
Example #14
0
async def test_homekit_setup_safe_mode(hass, hk_driver):
    """Test if safe_mode flag is set."""
    entry = MockConfigEntry(
        domain=DOMAIN,
        data={CONF_NAME: "mock_name", CONF_PORT: 12345},
        source=SOURCE_IMPORT,
    )
    homekit = HomeKit(
        hass,
        BRIDGE_NAME,
        DEFAULT_PORT,
        None,
        {},
        {},
        True,
        advertise_ip=None,
        entry_id=entry.entry_id,
    )

    with patch(f"{PATH_HOMEKIT}.accessories.HomeDriver", return_value=hk_driver):
        await hass.async_add_executor_job(homekit.setup, MagicMock())
    assert homekit.driver.safe_mode is True
async def test_flow_import_onvif_api_error(hass):
    """Test that config flow fails when ONVIF API fails."""
    with patch("homeassistant.components.onvif.config_flow.get_device"
               ) as mock_onvif_camera:
        setup_mock_onvif_camera(mock_onvif_camera)
        mock_onvif_camera.create_devicemgmt_service = MagicMock(
            side_effect=ONVIFError("Could not get device mgmt service"))

        result = await hass.config_entries.flow.async_init(
            config_flow.DOMAIN,
            context={"source": config_entries.SOURCE_IMPORT},
            data={
                config_flow.CONF_NAME: NAME,
                config_flow.CONF_HOST: HOST,
                config_flow.CONF_PORT: PORT,
                config_flow.CONF_USERNAME: USERNAME,
                config_flow.CONF_PASSWORD: PASSWORD,
            },
        )

        assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT
        assert result["reason"] == "onvif_error"
Example #16
0
def test_process_url_unmanaged(mocker, SETTINGS, event_loop):
    REPOSITORIES = mocker.patch(
        'jenkins_epo.procedures.REPOSITORIES', MagicMock()
    )
    REPOSITORIES.__contains__.return_value = False
    Bot = mocker.patch('jenkins_epo.procedures.Bot')
    from_url = mocker.patch(
        'jenkins_epo.procedures.Head.from_url', CoroutineMock()
    )

    from jenkins_epo.procedures import process_url

    bot = Bot.return_value
    bot.run = CoroutineMock()
    head = from_url.return_value
    head.url = 'url://test_process_url_exclusive'
    head.repository.load_settings = CoroutineMock()

    yield from process_url(head.url, throttle=False)

    assert not head.repository.load_settings.mock_calls
    assert not bot.run.mock_calls
Example #17
0
def test_send_message_without_sender():
    class SendBehaviour(OneShotBehaviour):
        async def run(self):
            msg = Message()
            await self.send(msg)
            self.kill()

    agent = MockedAgentFactory()
    future = agent.start(auto_register=False)
    future.result()

    agent.client = MagicMock()
    agent.client.send = CoroutineMock()
    behaviour = SendBehaviour()
    agent.add_behaviour(behaviour)

    behaviour.join()

    msg_arg = agent.client.send.await_args[0][0]
    assert msg_arg.from_ == aioxmpp.JID.fromstr("fake@jid")

    agent.stop()
Example #18
0
def test_send_message_to_external_agent():
    message = Message(
        to="to@external_xmpp.com",
        sender="sender@localhost",
        body="message body",
        thread="thread-id",
        metadata={"metadata1": "value1", "metadata2": "value2"},
    )

    class SendBehaviour(OneShotBehaviour):
        async def run(self):
            await self.send(message)
            self.kill()

    agent = MockedAgentFactory()
    future = agent.start(auto_register=False)
    future.result()

    agent.client = MagicMock()
    agent.client.send = CoroutineMock()
    behaviour = SendBehaviour()
    agent.add_behaviour(behaviour)

    behaviour.join()

    assert agent.client.send.await_count == 1
    msg_arg = agent.client.send.await_args[0][0]
    assert msg_arg.body[None] == "message body"
    assert msg_arg.to == aioxmpp.JID.fromstr("to@external_xmpp.com")
    thread_found = False
    for data in msg_arg.xep0004_data:
        if data.title == SPADE_X_METADATA:
            for field in data.fields:
                if field.var == "_thread_node":
                    assert field.values[0] == "thread-id"
                    thread_found = True
    assert thread_found

    agent.stop()
Example #19
0
async def test_form_invalid_auth(hass):
    """Test we handle invalid auth."""
    result = await hass.config_entries.flow.async_init(
        DOMAIN, context={"source": config_entries.SOURCE_USER}
    )

    with patch(
        "homeassistant.components.nuheat.config_flow.nuheat.NuHeat.authenticate",
        side_effect=Exception,
    ):
        result = await hass.config_entries.flow.async_configure(
            result["flow_id"],
            {
                CONF_SERIAL_NUMBER: "12345",
                CONF_USERNAME: "******",
                CONF_PASSWORD: "******",
            },
        )

    assert result["type"] == "form"
    assert result["errors"] == {"base": "invalid_auth"}

    response_mock = MagicMock()
    type(response_mock).status_code = 401
    with patch(
        "homeassistant.components.nuheat.config_flow.nuheat.NuHeat.authenticate",
        side_effect=requests.HTTPError(response=response_mock),
    ):
        result2 = await hass.config_entries.flow.async_configure(
            result["flow_id"],
            {
                CONF_SERIAL_NUMBER: "12345",
                CONF_USERNAME: "******",
                CONF_PASSWORD: "******",
            },
        )

    assert result2["type"] == "form"
    assert result2["errors"] == {"base": "invalid_auth"}
Example #20
0
def client(client_class):
    client = MagicMock(spec=bleak.BleakClient)
    client_class.return_value = client

    connected = False

    async def is_connected():
        nonlocal connected
        return connected

    async def connect():
        nonlocal connected
        connected = True

    async def disconnect():
        nonlocal connected
        connected = False

    client.is_connected.side_effect = is_connected
    client.connect.side_effect = connect
    client.disconnect.side_effect = disconnect

    yield client
    def test_dispatch_sending_emails(self):
        service = SendEmailService(
            self.web_client, self.email_client, self.settings_storage, 2
        )

        with patch.object(service, "send_emails", MagicMock()) as send_emails:
            service.dispatch_sending_emails(
                [
                    {"id": i, "email": f"guy_{i}@co.co", "name": "Guy"}
                    for i in range(1, 6)
                ],
                "Hi {name}! Have a nice day",
                "Subject",
            )
            send_emails.assert_called_once_with(
                [
                    {"id": i, "email": f"guy_{i}@co.co", "name": "Guy"}
                    for i in range(1, 6)
                ],
                "Hi {name}! Have a nice day",
                "Subject",
            )
            self.ensure_future_mock.assert_called_once_with(send_emails.return_value)
Example #22
0
def test_send_message(message):
    class SendBehaviour(OneShotBehaviour):
        async def run(self):
            await self.send(message)
            self.kill()

    agent = make_connected_agent()
    agent.start(auto_register=False)

    agent.aiothread.stream = MagicMock()
    agent.stream.send = CoroutineMock()
    behaviour = SendBehaviour()
    agent.add_behaviour(behaviour)

    wait_for_behaviour_is_killed(behaviour)

    assert agent.stream.send.await_count == 1
    msg_arg = agent.stream.send.await_args[0][0]
    assert msg_arg.body[None] == "message body"
    assert msg_arg.to == aioxmpp.JID.fromstr("to@localhost")
    assert msg_arg.thread == "thread-id"

    agent.stop()
async def test_flow_import_onvif_auth_error(hass):
    """Test that config flow fails when ONVIF API fails."""
    with patch("homeassistant.components.onvif.config_flow.get_device"
               ) as mock_onvif_camera:
        setup_mock_onvif_camera(mock_onvif_camera)
        mock_onvif_camera.create_devicemgmt_service = MagicMock(
            side_effect=Fault("Auth Error"))

        result = await hass.config_entries.flow.async_init(
            config_flow.DOMAIN,
            context={"source": config_entries.SOURCE_IMPORT},
            data={
                config_flow.CONF_NAME: NAME,
                config_flow.CONF_HOST: HOST,
                config_flow.CONF_PORT: PORT,
                config_flow.CONF_USERNAME: USERNAME,
                config_flow.CONF_PASSWORD: PASSWORD,
            },
        )

        assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
        assert result["step_id"] == "auth"
        assert result["errors"]["base"] == "connection_failed"
Example #24
0
async def test_homekit_setup_advertise_ip(hass, hk_driver):
    """Test setup with given IP address to advertise."""
    entry = MockConfigEntry(
        domain=DOMAIN,
        data={
            CONF_NAME: "mock_name",
            CONF_PORT: 12345
        },
        source=SOURCE_IMPORT,
    )
    homekit = HomeKit(
        hass,
        BRIDGE_NAME,
        DEFAULT_PORT,
        "0.0.0.0",
        {},
        {},
        None,
        "192.168.1.100",
        entry_id=entry.entry_id,
    )

    zeroconf_instance = MagicMock()
    path = get_persist_fullpath_for_entry_id(hass, entry.entry_id)
    with patch(f"{PATH_HOMEKIT}.accessories.HomeDriver",
               return_value=hk_driver) as mock_driver:
        await hass.async_add_executor_job(homekit.setup, zeroconf_instance)
    mock_driver.assert_called_with(
        hass,
        entry.entry_id,
        BRIDGE_NAME,
        address="0.0.0.0",
        port=DEFAULT_PORT,
        persist_file=path,
        advertised_address="192.168.1.100",
        zeroconf_instance=zeroconf_instance,
    )
Example #25
0
async def test_init_from_file(
        hass: HomeAssistant, vera_component_factory: ComponentFactory) -> None:
    """Test function."""
    vera_device1 = MagicMock(
        spec=pv.VeraBinarySensor)  # type: pv.VeraBinarySensor
    vera_device1.device_id = 1
    vera_device1.vera_device_id = 1
    vera_device1.name = "first_dev"
    vera_device1.is_tripped = False
    entity1_id = "binary_sensor.first_dev_1"

    await vera_component_factory.configure_component(
        hass=hass,
        controller_config=new_simple_controller_config(
            config={CONF_CONTROLLER: "http://127.0.0.1:111"},
            config_from_file=True,
            serial_number="first_serial",
            devices=(vera_device1, ),
        ),
    )

    entity_registry = await hass.helpers.entity_registry.async_get_registry()
    entry1 = entity_registry.async_get(entity1_id)
    assert entry1
Example #26
0
def test_process_url_repo_denied(mocker, SETTINGS):
    REPOSITORIES = mocker.patch(
        'jenkins_epo.procedures.REPOSITORIES', MagicMock()
    )
    REPOSITORIES.__contains__.return_value = True
    Bot = mocker.patch('jenkins_epo.procedures.Bot')
    from_url = mocker.patch(
        'jenkins_epo.procedures.Head.from_url', CoroutineMock()
    )

    from jenkins_epo.procedures import process_url, UnauthorizedRepository

    bot = Bot.return_value
    head = from_url.return_value
    head.sha = 'cafed0d0'
    head.url = 'url://test_process_url_repo_denied'
    head.repository.load_settings = CoroutineMock(
        side_effect=UnauthorizedRepository()
    )

    yield from process_url(head.url, throttle=False)

    assert head.repository.load_settings.mock_calls
    assert not bot.run.mock_calls
Example #27
0
async def test_form_invalid_auth(hass):
    """Test we handle invalid auth."""
    result = await hass.config_entries.flow.async_init(
        DOMAIN, context={"source": config_entries.SOURCE_USER})

    response_mock = MagicMock()
    type(response_mock).status_code = 401
    mock_tado_api = _get_mock_tado_api(getMe=requests.HTTPError(
        response=response_mock))

    with patch(
            "homeassistant.components.tado.config_flow.Tado",
            return_value=mock_tado_api,
    ):
        result2 = await hass.config_entries.flow.async_configure(
            result["flow_id"],
            {
                "username": "******",
                "password": "******"
            },
        )

    assert result2["type"] == "form"
    assert result2["errors"] == {"base": "invalid_auth"}
Example #28
0
    def test_unsubscribe(self):
        channel1 = Channel('heartbeat', ['BTC-USD', 'LTC-USD', 'LTC-EUR'])
        channel2 = Channel('level2', ['LTC-USD'])
        channel3 = Channel('heartbeat', ['LTC-EUR'])
        channel4 = Channel('heartbeat', ['BTC-USD', 'BTC-EUR'])
        channel5 = Channel('heartbeat', ['BCH-USD', 'LTC-USD'])

        client = Client(self.loop, [channel1, channel2], auto_connect=False)

        client.unsubscribe(channel3)

        self.assertIn(channel3.name, client.channels)
        self.assertEqual(client.channels[channel3.name],
                         Channel('heartbeat', ['BTC-USD', 'LTC-USD']))

        client.unsubscribe(channel4)

        self.assertIn(channel4.name, client.channels)
        self.assertEqual(client.channels[channel4.name],
                         Channel('heartbeat', ['LTC-USD']))

        client.unsubscribe(channel3)
        self.assertIn(channel3.name, client.channels)
        self.assertEqual(client.channels[channel3.name],
                         Channel('heartbeat', ['LTC-USD']))

        client.unsubscribe(channel2)
        self.assertNotIn(channel2.name, client.channels)

        client.protocol.sendMessage = MagicMock()
        client.connected.set()

        client.unsubscribe(channel5)
        self.assertEqual(client.channels, {})
        msg = client._get_subscribe_message([channel5], unsubscribe=True)
        client.protocol.sendMessage.assert_called_with(msg)
Example #29
0
def withings_api_fixture() -> WithingsApi:
    """Provide withings api."""
    withings_api = WithingsApi.__new__(WithingsApi)
    withings_api.get_measures = MagicMock()
    withings_api.get_sleep = MagicMock()
    return withings_api
 async def test_stop(self):
     self.source.websocket = MagicMock()
     self.source.websocket.close = asynctest.CoroutineMock(
         return_value=True)
     res = await self.source.stop()
     assert res == True