async def test_handle_push_tag(monkeypatch): listener = Mock() listener.message = AsyncMock(return_value=345) relay_push_discord = AsyncMock(return_value=True) relay_push = AsyncMock(return_value=True) monkeypatch.setattr("chitanda.modules.github_relay._relay_push_discord", relay_push_discord) monkeypatch.setattr("chitanda.modules.github_relay._relay_push", relay_push) await handle_push( listener, payload={ "ref": "refs/tags/master", "before": "abcdefghi", "repository": { "name": "chitanda" }, }, cfg={ "branches": ["master"], "channel": "hi" }, ) listener.message.assert_called() relay_push_discord.assert_not_called() relay_push.assert_not_called()
async def test_process_passive(self): """Test process / reading telegrams from telegram queue. Test if device was updated.""" xknx = XKNX() callback_mock = AsyncMock() switch1 = Switch( xknx, "TestOutlet", group_address=["1/2/3", "4/4/4"], group_address_state=["1/2/30", "5/5/5"], device_updated_cb=callback_mock, ) assert switch1.state is None callback_mock.assert_not_called() telegram_on_passive = Telegram( destination_address=GroupAddress("4/4/4"), payload=GroupValueWrite(DPTBinary(1)), ) telegram_off_passive = Telegram( destination_address=GroupAddress("5/5/5"), payload=GroupValueWrite(DPTBinary(0)), ) await switch1.process(telegram_on_passive) assert switch1.state is True callback_mock.assert_called_once() callback_mock.reset_mock() await switch1.process(telegram_off_passive) assert switch1.state is False callback_mock.assert_called_once() callback_mock.reset_mock()
async def test_always_callback_sensor(self): """Test always callback sensor.""" xknx = XKNX() sensor = Sensor( xknx, "TestSensor", group_address_state="1/2/3", always_callback=False, value_type="volume_liquid_litre", ) after_update_callback = AsyncMock() sensor.register_device_updated_cb(after_update_callback) payload = DPTArray((0x00, 0x00, 0x01, 0x00)) # set initial payload of sensor sensor.sensor_value.value = 256 telegram = Telegram(destination_address=GroupAddress("1/2/3"), payload=GroupValueWrite(payload)) response_telegram = Telegram( destination_address=GroupAddress("1/2/3"), payload=GroupValueResponse(payload), ) # verify not called when always_callback is False await sensor.process(telegram) after_update_callback.assert_not_called() after_update_callback.reset_mock() sensor.always_callback = True # verify called when always_callback is True await sensor.process(telegram) after_update_callback.assert_called_once() after_update_callback.reset_mock() # verify not called when processing read responses await sensor.process(response_telegram) after_update_callback.assert_not_called()
async def test_callback_group_addresses(self): """Test telegram_received_callback after state of switch was changed.""" xknx = XKNX() async_telegram_received_cb_one = AsyncMock() async_telegram_received_cb_two = AsyncMock() callback_one = xknx.telegram_queue.register_telegram_received_cb( async_telegram_received_cb_one, address_filters=[], group_addresses=[GroupAddress("1/2/3")], ) callback_two = xknx.telegram_queue.register_telegram_received_cb( async_telegram_received_cb_two, address_filters=[], group_addresses=[]) telegram = Telegram( destination_address=GroupAddress("1/2/3"), direction=TelegramDirection.INCOMING, payload=GroupValueWrite(DPTBinary(1)), ) await xknx.telegram_queue.process_telegram_incoming(telegram) async_telegram_received_cb_one.assert_called_once_with(telegram) async_telegram_received_cb_two.assert_not_called() async_telegram_received_cb_one.reset_mock() # modify the filters - add/remove a GroupAddress callback_one.group_addresses.remove(GroupAddress("1/2/3")) callback_two.group_addresses.append(GroupAddress("1/2/3")) await xknx.telegram_queue.process_telegram_incoming(telegram) async_telegram_received_cb_one.assert_not_called() async_telegram_received_cb_two.assert_called_once_with(telegram)
async def test_disconnected_backend_raises_exception( dask_spec_local_cluster: SpecCluster, local_dask_gateway_server: DaskGatewayServer, dask_client: DaskClient, user_id: UserID, project_id: ProjectID, cluster_id: ClusterID, cpu_image: ImageParams, mocked_node_ports: None, mocked_user_completed_cb: mock.AsyncMock, ): # DISCONNECT THE CLUSTER await dask_spec_local_cluster.close() # type: ignore await local_dask_gateway_server.server.cleanup() # with pytest.raises(ComputationalBackendNotConnectedError): await dask_client.send_computation_tasks( user_id=user_id, project_id=project_id, cluster_id=cluster_id, tasks=cpu_image.fake_tasks, callback=mocked_user_completed_cb, remote_fct=None, ) mocked_user_completed_cb.assert_not_called()
async def test_process_group_value_response(self): """Test precess of GroupValueResponse telegrams.""" xknx = XKNX() switch = BinarySensor( xknx, "TestInput", group_address_state="1/2/3", ignore_internal_state=True, ) async_after_update_callback = AsyncMock() switch.register_device_updated_cb(async_after_update_callback) write_telegram = Telegram( destination_address=GroupAddress("1/2/3"), payload=GroupValueWrite(DPTBinary(1)), ) response_telegram = Telegram( destination_address=GroupAddress("1/2/3"), payload=GroupValueResponse(DPTBinary(1), ), ) assert switch.state is None # initial GroupValueResponse changes state and runs callback await switch.process(response_telegram) assert switch.state async_after_update_callback.assert_called_once_with(switch) # GroupValueWrite with same payload runs callback because of `ignore_internal_state` async_after_update_callback.reset_mock() await switch.process(write_telegram) assert switch.state async_after_update_callback.assert_called_once_with(switch) # GroupValueResponse should not run callback when state has not changed async_after_update_callback.reset_mock() await switch.process(response_telegram) async_after_update_callback.assert_not_called()
async def test_too_many_resources_send_computation_task( dask_client: DaskClient, user_id: UserID, project_id: ProjectID, node_id: NodeID, cluster_id: ClusterID, mocked_node_ports: None, mocked_user_completed_cb: mock.AsyncMock, ): # create an image that needs a huge amount of CPU image = Image( name="simcore/services/comp/pytest", tag="1.4.5", node_requirements=NodeRequirements( CPU=10000000000000000, RAM=parse_obj_as(ByteSize, "128 MiB"), MPI=None, GPU=None, ), ) # type: ignore fake_task = {node_id: image} # let's have a big number of CPUs with pytest.raises(InsuficientComputationalResourcesError): await dask_client.send_computation_tasks( user_id=user_id, project_id=project_id, cluster_id=cluster_id, tasks=fake_task, callback=mocked_user_completed_cb, remote_fct=None, ) mocked_user_completed_cb.assert_not_called()
async def test_healthcheck_job_failure(): settings = Settings() with aioresponses() as mocked_session: expected_exception = ValueError("Test exception") mocked_session.get( "http://example.com", exception=expected_exception, ) job_params = JobParams( url="http://example.com", schedule="* * * * *", ) lock = asyncio.Lock() on_result = AsyncMock() on_error = AsyncMock() await healthcheck_job( job_params=job_params, settings=settings, on_result=on_result, on_error=on_error, sync_lock=lock, ) on_result.assert_not_called() posted_on_exception: Tuple[JobParams, Exception] = on_error.call_args_list[0][0] assert posted_on_exception[0].url == "http://example.com" assert posted_on_exception[1] == expected_exception
async def test_approve(coresys: CoreSys, dns_query: AsyncMock): """Test approve existing DNS Server IPv6 error issues.""" dns_server_ipv6_errors = CheckDNSServerIPv6Errors(coresys) coresys.core.state = CoreState.RUNNING assert dns_server_ipv6_errors.dns_servers == ["dns://192.168.30.1"] dns_query.side_effect = DNSError(4, "Domain name not found") assert (await dns_server_ipv6_errors.approve_check( reference="dns://1.1.1.1") is False) dns_query.assert_not_called() assert (await dns_server_ipv6_errors.approve_check( reference="dns://192.168.30.1") is True) dns_query.assert_called_once_with("_checkdns.home-assistant.io", "AAAA") dns_query.reset_mock() dns_query.side_effect = DNSError( 1, "DNS server returned answer with no data") assert (await dns_server_ipv6_errors.approve_check( reference="dns://192.168.30.1") is False) dns_query.assert_called_once_with("_checkdns.home-assistant.io", "AAAA") dns_query.reset_mock() dns_query.side_effect = None assert (await dns_server_ipv6_errors.approve_check( reference="dns://192.168.30.1") is False) dns_query.assert_called_once_with("_checkdns.home-assistant.io", "AAAA")
def test_start_stop(self): f = AsyncMock() timer = Timer(100, f) self.assertTrue(timer.stopped) f.assert_not_called() timer.start() self.assertFalse(timer.stopped) timer.stop() self.assertTrue(timer.stopped)
async def test_on_join_with_no_actions(cog: MemberJoins, member: Mock) -> None: """On Join event with no actions""" member.guild.id = 999 send_dm = AsyncMock() send_channel = AsyncMock() with patch.multiple(cog, _send_dm=send_dm, _send_channel=send_channel): await cog.on_member_join(member) send_channel.assert_not_called() send_dm.assert_not_called()
async def test_on_message_no_channel_type(self, bot: SpellBot, monkeypatch: pytest.MonkeyPatch): super_on_message_mock = AsyncMock() monkeypatch.setattr(Bot, "on_message", super_on_message_mock) message = MagicMock() message.guild = MagicMock() message.channel = MagicMock() del message.channel.type await bot.on_message(message) super_on_message_mock.assert_not_called()
async def test_state_return(self): """Test should return if current state equals parameter.""" xknx = XKNX() async_connection_state_changed_cb = AsyncMock() xknx.connection_manager.register_connection_state_changed_cb( async_connection_state_changed_cb) assert xknx.connection_manager.state == XknxConnectionState.DISCONNECTED await xknx.connection_manager.connection_state_changed( XknxConnectionState.DISCONNECTED) async_connection_state_changed_cb.assert_not_called()
async def test_on_message_hidden(self, bot: SpellBot, monkeypatch: pytest.MonkeyPatch): super_on_message_mock = AsyncMock() monkeypatch.setattr(Bot, "on_message", super_on_message_mock) message = MagicMock() message.guild = MagicMock() message.channel = MagicMock() message.channel.type = discord.ChannelType.text message.flags.value = 64 await bot.on_message(message) super_on_message_mock.assert_not_called()
async def test_on_join_of_bot(cog: MemberJoins, member: Mock) -> None: """On Join event of a bot""" member.guild.id = 111 member.bot = True send_dm = AsyncMock() send_channel = AsyncMock() with patch.multiple(cog, _send_dm=send_dm, _send_channel=send_channel): await cog.on_member_join(member) send_channel.assert_not_called() send_dm.assert_not_called()
async def test_unregister(self): """Test unregister after register.""" xknx = XKNX() async_connection_state_changed_cb = AsyncMock() xknx.connection_manager.register_connection_state_changed_cb( async_connection_state_changed_cb) xknx.connection_manager.unregister_connection_state_changed_cb( async_connection_state_changed_cb) await xknx.connection_manager.connection_state_changed( XknxConnectionState.CONNECTED) async_connection_state_changed_cb.assert_not_called()
async def test_invalid_jwt(self): app = MockFastAPI() auth_middleware.add_auth_middleware(app, 'development') call_next = AsyncMock() request = Mock() request.headers.get.return_value = 'Bearer some_jwt' response = await app.middleware_func(request, call_next) call_next.assert_not_called() assert isinstance(response, JSONResponse) assert response.status_code == 401
async def test_on_message_happy_path( self, dpy_message: discord.Message, bot: SpellBot, monkeypatch: pytest.MonkeyPatch, ): super_on_message_mock = AsyncMock() monkeypatch.setattr(Bot, "on_message", super_on_message_mock) monkeypatch.setattr(bot, "handle_verification", AsyncMock()) dpy_message.flags.value = 16 await bot.on_message(dpy_message) super_on_message_mock.assert_not_called() bot.handle_verification.assert_called_once_with(dpy_message) dpy_message.reply.assert_not_called()
async def test_process_state(self): """Test process / reading telegrams from telegram queue. Test if device was updated.""" xknx = XKNX() callback_mock = AsyncMock() switch1 = Switch( xknx, "TestOutlet", group_address="1/2/3", group_address_state="1/2/4", device_updated_cb=callback_mock, ) switch2 = Switch( xknx, "TestOutlet", group_address="1/2/3", group_address_state="1/2/4", device_updated_cb=callback_mock, ) assert switch1.state is None assert switch2.state is None callback_mock.assert_not_called() telegram_on = Telegram( destination_address=GroupAddress("1/2/4"), payload=GroupValueResponse(DPTBinary(1)), ) telegram_off = Telegram( destination_address=GroupAddress("1/2/4"), payload=GroupValueResponse(DPTBinary(0)), ) await switch1.process(telegram_on) assert switch1.state is True callback_mock.assert_called_once() callback_mock.reset_mock() await switch1.process(telegram_off) assert switch1.state is False callback_mock.assert_called_once() callback_mock.reset_mock() # test setting switch2 to False with first telegram await switch2.process(telegram_off) assert switch2.state is False callback_mock.assert_called_once() callback_mock.reset_mock() await switch2.process(telegram_on) assert switch2.state is True callback_mock.assert_called_once() callback_mock.reset_mock()
async def test_process_fan_payload_invalid_length(self): """Test process wrong telegrams. (wrong payload length).""" xknx = XKNX() cb_mock = AsyncMock() fan = Fan(xknx, name="TestFan", group_address_speed="1/2/3", device_updated_cb=cb_mock) telegram = Telegram( destination_address=GroupAddress("1/2/3"), payload=GroupValueWrite(DPTArray((23, 24))), ) with patch("logging.Logger.warning") as log_mock: await fan.process(telegram) log_mock.assert_called_once() cb_mock.assert_not_called()
async def test_process_wrong_payload(self): """Test process wrong telegram (wrong payload type).""" xknx = XKNX() cb_mock = AsyncMock() notification = Notification(xknx, "Warning", group_address="1/2/3", device_updated_cb=cb_mock) telegram = Telegram( destination_address=GroupAddress("1/2/3"), payload=GroupValueWrite(DPTBinary(1)), ) with patch("logging.Logger.warning") as log_mock: await notification.process(telegram) log_mock.assert_called_once() cb_mock.assert_not_called()
async def test_register_with_outgoing_telegrams_does_not_trigger(self): """Test telegram_received_callback with outgoing telegrams.""" xknx = XKNX() xknx.knxip_interface = AsyncMock() async_telegram_received_cb = AsyncMock() xknx.telegram_queue.register_telegram_received_cb(async_telegram_received_cb) telegram = Telegram( destination_address=GroupAddress("1/2/3"), direction=TelegramDirection.OUTGOING, payload=GroupValueWrite(DPTBinary(1)), ) await xknx.telegram_queue.process_telegram_outgoing(telegram) async_telegram_received_cb.assert_not_called()
async def test_unregister(self): """Test telegram_received_callback after state of switch was changed.""" xknx = XKNX() async_telegram_received_callback = AsyncMock() callback = xknx.telegram_queue.register_telegram_received_cb( async_telegram_received_callback) xknx.telegram_queue.unregister_telegram_received_cb(callback) telegram = Telegram( destination_address=GroupAddress("1/2/3"), direction=TelegramDirection.INCOMING, payload=GroupValueWrite(DPTBinary(1)), ) await xknx.telegram_queue.process_telegram_incoming(telegram) async_telegram_received_callback.assert_not_called()
async def test_process_callback(self): """Test process / reading telegrams from telegram queue. Test if callback is executed.""" xknx = XKNX() cover = Cover( xknx, "TestCoverProcessCallback", group_address_long="1/2/1", group_address_short="1/2/2", group_address_stop="1/2/3", group_address_position="1/2/4", group_address_position_state="1/2/5", group_address_angle="1/2/6", group_address_angle_state="1/2/7", ) after_update_callback = AsyncMock() cover.register_device_updated_cb(after_update_callback) for address, payload, _feature in [ ("1/2/1", DPTBinary(1), "long"), ("1/2/2", DPTBinary(1), "short"), ("1/2/4", DPTArray(42), "position"), ("1/2/5", DPTArray(42), "position state"), ("1/2/6", DPTArray(42), "angle"), ("1/2/7", DPTArray(51), "angle state"), ]: telegram = Telegram( destination_address=GroupAddress(address), payload=GroupValueWrite(payload), ) await cover.process(telegram) after_update_callback.assert_called_with(cover) after_update_callback.reset_mock() # Stop only when cover is travelling telegram = Telegram(GroupAddress("1/2/3"), payload=GroupValueWrite(DPTBinary(1))) await cover.process(telegram) after_update_callback.assert_not_called() await cover.set_down() await cover.process(telegram) after_update_callback.assert_called_with(cover) await cover.stop() # clean up tasks
async def test_callback_negative_address_filters(self): """Test telegram_received_callback after state of switch was changed.""" xknx = XKNX() async_telegram_received_callback = AsyncMock() xknx.telegram_queue.register_telegram_received_cb( async_telegram_received_callback, address_filters=[AddressFilter("2/4-8/*"), AddressFilter("1/2/8-")], ) telegram = Telegram( destination_address=GroupAddress("1/2/3"), direction=TelegramDirection.INCOMING, payload=GroupValueWrite(DPTBinary(1)), ) xknx.telegrams.put_nowait(telegram) await xknx.telegram_queue._process_all_telegrams() async_telegram_received_callback.assert_not_called()
async def test_healthcheck_job_locked(monkeypatch): settings = Settings() job_params = JobParams( url="http://example.com", schedule="* * * * *", ) lock = asyncio.Lock() on_result = AsyncMock() on_error = AsyncMock() monkeypatch.setattr(lock, "_locked", True) await healthcheck_job( job_params=job_params, settings=settings, on_result=on_result, on_error=on_error, sync_lock=lock, ) on_result.assert_not_called() on_error.assert_not_called()
async def test_process_callback_ignore_internal_state(self): """Test after_update_callback after state of switch was changed.""" xknx = XKNX() switch = BinarySensor( xknx, "TestInput", group_address_state="1/2/3", ignore_internal_state=True, context_timeout=0.001, ) async_after_update_callback = AsyncMock() switch.register_device_updated_cb(async_after_update_callback) telegram = Telegram( destination_address=GroupAddress("1/2/3"), payload=GroupValueWrite(DPTBinary(1)), ) assert switch.counter == 0 await switch.process(telegram) async_after_update_callback.assert_not_called() assert switch.counter == 1 await switch._context_task async_after_update_callback.assert_called_with(switch) # once with counter 1 and once with counter 0 assert async_after_update_callback.call_count == 2 async_after_update_callback.reset_mock() # send same telegram again await switch.process(telegram) assert switch.counter == 1 await switch.process(telegram) assert switch.counter == 2 async_after_update_callback.assert_not_called() await switch._context_task async_after_update_callback.assert_called_with(switch) # once with counter 2 and once with counter 0 assert async_after_update_callback.call_count == 2 assert switch.counter == 0
async def test_process_callback(self): """Test process / reading telegrams from telegram queue. Test if callback is called.""" xknx = XKNX() sensor = NumericValue( xknx, "TestSensor", group_address="1/2/3", value_type="temperature" ) after_update_callback = AsyncMock() sensor.register_device_updated_cb(after_update_callback) telegram = Telegram( destination_address=GroupAddress("1/2/3"), payload=GroupValueWrite(DPTArray((0x01, 0x02))), ) await sensor.process(telegram) after_update_callback.assert_called_with(sensor) assert sensor.last_telegram == telegram # consecutive telegrams with same payload shall only trigger one callback after_update_callback.reset_mock() await sensor.process(telegram) after_update_callback.assert_not_called()
async def test_approve(coresys: CoreSys, dns_query: AsyncMock): """Test approve existing DNS Server failure issues.""" dns_server_failures = CheckDNSServerFailures(coresys) coresys.core.state = CoreState.RUNNING assert dns_server_failures.dns_servers == ["dns://192.168.30.1"] dns_query.side_effect = DNSError() assert await dns_server_failures.approve_check(reference="dns://1.1.1.1" ) is False dns_query.assert_not_called() assert (await dns_server_failures.approve_check( reference="dns://192.168.30.1") is True) dns_query.assert_called_once_with("_checkdns.home-assistant.io", "A") dns_query.reset_mock() dns_query.side_effect = None assert (await dns_server_failures.approve_check( reference="dns://192.168.30.1") is False) dns_query.assert_called_once_with("_checkdns.home-assistant.io", "A")
async def test_missing_resource_send_computation_task( dask_spec_local_cluster: SpecCluster, dask_client: DaskClient, user_id: UserID, project_id: ProjectID, cluster_id: ClusterID, image_params: ImageParams, mocked_node_ports: None, mocked_user_completed_cb: mock.AsyncMock, ): # remove the workers that can handle mpi scheduler_info = dask_client.dask_subsystem.client.scheduler_info() assert scheduler_info # find mpi workers workers_to_remove = [ worker_key for worker_key, worker_info in scheduler_info["workers"].items() if "MPI" in worker_info["resources"] ] await dask_client.dask_subsystem.client.retire_workers( workers=workers_to_remove) await asyncio.sleep(5) # a bit of time is needed so the cluster adapts # now let's adapt the task so it needs mpi image_params.image.node_requirements.mpi = 2 with pytest.raises(MissingComputationalResourcesError): await dask_client.send_computation_tasks( user_id=user_id, project_id=project_id, cluster_id=cluster_id, tasks=image_params.fake_task, callback=mocked_user_completed_cb, remote_fct=None, ) assert (len(dask_client._taskid_to_future_map) == 0 ), "dask client should not store any future here" mocked_user_completed_cb.assert_not_called()