@@ -305,6 +305,59 @@ async def test_gateway_create_group_with_id_without_id(
305305 assert zha_group3 .group_id == 0x0003
306306
307307
308+ async def test_remove_device_cleans_up_group_membership (
309+ zha_gateway : Gateway ,
310+ device_light_1 , # pylint: disable=redefined-outer-name
311+ device_light_2 , # pylint: disable=redefined-outer-name
312+ coordinator , # pylint: disable=redefined-outer-name
313+ caplog : pytest .LogCaptureFixture ,
314+ ) -> None :
315+ """Test group membership cleanup when removing a device in a group."""
316+
317+ zha_gateway .coordinator_zha_device = coordinator
318+ coordinator ._zha_gateway = zha_gateway
319+ device_light_1 ._zha_gateway = zha_gateway
320+ device_light_2 ._zha_gateway = zha_gateway
321+
322+ member_ieee_addresses = [device_light_1 .ieee , device_light_2 .ieee ]
323+ members = [
324+ GroupMemberReference (ieee = device_light_1 .ieee , endpoint_id = 1 ),
325+ GroupMemberReference (ieee = device_light_2 .ieee , endpoint_id = 1 ),
326+ ]
327+
328+ # test creating a group with 2 members
329+ zha_group : Group = await zha_gateway .async_create_zigpy_group ("Test Group" , members )
330+ await zha_gateway .async_block_till_done ()
331+
332+ assert zha_group is not None
333+ assert len (zha_group .members ) == 2
334+ for member in zha_group .members :
335+ assert member .device .ieee in member_ieee_addresses
336+ assert member .group == zha_group
337+ assert member .endpoint is not None
338+
339+ await zha_gateway .async_remove_device (coordinator .ieee )
340+ await zha_gateway .async_block_till_done ()
341+ assert len (zha_group .members ) == 2
342+ assert (
343+ f"Removing the active coordinator ({ str (coordinator .ieee )} ) is not allowed"
344+ in caplog .text
345+ )
346+
347+ non_existent_ieee = zigpy .types .EUI64 .convert ("01:2d:6f:70:7a:40:79:e8" )
348+ await zha_gateway .async_remove_device (non_existent_ieee )
349+ await zha_gateway .async_block_till_done ()
350+ assert len (zha_group .members ) == 2
351+ assert f"Device: { str (non_existent_ieee )} could not be found" in caplog .text
352+
353+ await zha_gateway .async_remove_device (device_light_1 .ieee )
354+ await zha_gateway .async_block_till_done ()
355+
356+ assert len (zha_group .members ) == 1
357+ assert zha_group .members [0 ].device .ieee == device_light_2 .ieee
358+ assert device_light_1 .ieee not in zha_gateway .devices
359+
360+
308361@patch (
309362 "zha.application.gateway.Gateway.load_devices" ,
310363 MagicMock (),
0 commit comments