From 46b65f325af287cac31f7ee49f219dc0b865f6f8 Mon Sep 17 00:00:00 2001
From: Vivien Nicolas <vnicolas@apple.com>
Date: Mon, 19 Sep 2022 18:19:45 +0200
Subject: [PATCH] Ensure the connection and the disconnect handler are accessed
 from the same dispatch queue in MTRProtocolTests.m

---
 .../Framework/CHIPTests/MTRXPCProtocolTests.m | 24 ++++++++++++-------
 1 file changed, 15 insertions(+), 9 deletions(-)

diff --git a/src/darwin/Framework/CHIPTests/MTRXPCProtocolTests.m b/src/darwin/Framework/CHIPTests/MTRXPCProtocolTests.m
index b9dcf916a12b62..6e8e5d18418870 100644
--- a/src/darwin/Framework/CHIPTests/MTRXPCProtocolTests.m
+++ b/src/darwin/Framework/CHIPTests/MTRXPCProtocolTests.m
@@ -174,15 +174,19 @@ - (BOOL)listener:(NSXPCListener *)listener shouldAcceptNewConnection:(NSXPCConne
     newConnection.remoteObjectInterface = _clientInterface;
     newConnection.exportedObject = self;
     newConnection.invalidationHandler = ^{
-        NSLog(@"XPC connection disconnected");
-        self.xpcConnection = nil;
-        if (self.xpcDisconnectExpectation) {
-            [self.xpcDisconnectExpectation fulfill];
-            self.xpcDisconnectExpectation = nil;
-        }
+        dispatch_async(dispatch_get_main_queue(), ^{
+            NSLog(@"XPC connection disconnected");
+            self.xpcConnection = nil;
+            if (self.xpcDisconnectExpectation) {
+                [self.xpcDisconnectExpectation fulfill];
+                self.xpcDisconnectExpectation = nil;
+            }
+        });
     };
-    _xpcConnection = newConnection;
-    [newConnection resume];
+    dispatch_async(dispatch_get_main_queue(), ^{
+        self.xpcConnection = newConnection;
+        [newConnection resume];
+    });
     return YES;
 }
 
@@ -2263,6 +2267,8 @@ - (void)testReadClusterStateCacheSuccess
               completion([MTRDeviceController encodeXPCResponseValues:myValues], nil);
           };
 
+    _xpcDisconnectExpectation = [self expectationWithDescription:@"XPC Disconnected"];
+
     [clusterStateCacheContainer subscribeWithDeviceController:_remoteDeviceController
                                                      deviceID:@(myNodeId)
                                                        params:nil
@@ -2272,7 +2278,7 @@ - (void)testReadClusterStateCacheSuccess
                                                        XCTAssertNil(error);
                                                        [subscribeExpectation fulfill];
                                                    }];
-    [self waitForExpectations:@[ subscribeExpectation ] timeout:kTimeoutInSeconds];
+    [self waitForExpectations:@[ subscribeExpectation, _xpcDisconnectExpectation ] timeout:kTimeoutInSeconds];
 
     _xpcDisconnectExpectation = [self expectationWithDescription:@"XPC Disconnected"];
     [clusterStateCacheContainer