Add better error logging and fix MITM test

Change-Id: I2c9c85c9a92c3af9b1ad83d72ed74fc4f600bf1b
(cherry picked from commit f88a4b0b4cd09ecc0c644ded56a334e61e8fd182)
diff --git a/acts/framework/acts/test_utils/bt/GattConnectedBaseTest.py b/acts/framework/acts/test_utils/bt/GattConnectedBaseTest.py
index 0507543..c22ecc7 100644
--- a/acts/framework/acts/test_utils/bt/GattConnectedBaseTest.py
+++ b/acts/framework/acts/test_utils/bt/GattConnectedBaseTest.py
@@ -122,8 +122,8 @@
         characteristic_input = [
             {
                 'uuid': self.WRITABLE_CHAR_UUID,
-                'property': GattCharacteristic.PROPERTY_WRITE.value
-                | GattCharacteristic.PROPERTY_WRITE_NO_RESPONSE.value,
+                'property': GattCharacteristic.PROPERTY_WRITE.value |
+                GattCharacteristic.PROPERTY_WRITE_NO_RESPONSE.value,
                 'permission': GattCharacteristic.PERMISSION_WRITE.value
             },
             {
@@ -133,24 +133,24 @@
             },
             {
                 'uuid': self.NOTIFIABLE_CHAR_UUID,
-                'property': GattCharacteristic.PROPERTY_NOTIFY.value
-                | GattCharacteristic.PROPERTY_INDICATE.value,
+                'property': GattCharacteristic.PROPERTY_NOTIFY.value |
+                GattCharacteristic.PROPERTY_INDICATE.value,
                 'permission': GattCharacteristic.PERMISSION_READ.value
             },
         ]
         descriptor_input = [
             {
                 'uuid': self.WRITABLE_DESC_UUID,
-                'property': GattDescriptor.PERMISSION_READ.value
-                | GattCharacteristic.PERMISSION_WRITE.value,
+                'property': GattDescriptor.PERMISSION_READ.value |
+                GattCharacteristic.PERMISSION_WRITE.value,
             }, {
                 'uuid': self.READABLE_DESC_UUID,
-                'property': GattDescriptor.PERMISSION_READ.value
-                | GattDescriptor.PERMISSION_WRITE.value,
+                'property': GattDescriptor.PERMISSION_READ.value |
+                GattDescriptor.PERMISSION_WRITE.value,
             }, {
                 'uuid': self.CCC_DESC_UUID,
-                'property': GattDescriptor.PERMISSION_READ.value
-                | GattDescriptor.PERMISSION_WRITE.value,
+                'property': GattDescriptor.PERMISSION_READ.value |
+                GattDescriptor.PERMISSION_WRITE.value,
             }
         ]
         characteristic_list = setup_gatt_characteristics(droid,
@@ -161,12 +161,13 @@
 
     def _orchestrate_gatt_disconnection(self, bluetooth_gatt, gatt_callback):
         self.log.info("Disconnecting from peripheral device.")
-        test_result = disconnect_gatt_connection(self.cen_ad, bluetooth_gatt,
-                                                 gatt_callback)
-        self.cen_ad.droid.gattClientClose(bluetooth_gatt)
-        if not test_result:
-            self.log.info("Failed to disconnect from peripheral device.")
+        try:
+            disconnect_gatt_connection(self.cen_ad, bluetooth_gatt,
+                                       gatt_callback)
+        except GattTestUtilsError as err:
+            log.error(err)
             return False
+        self.cen_ad.droid.gattClientClose(bluetooth_gatt)
         return True
 
     def _find_service_added_event(self, gatt_server_callback, uuid):
@@ -176,8 +177,8 @@
             event = self.per_ad.ed.pop_event(expected_event,
                                              self.DEFAULT_TIMEOUT)
         except Empty:
-            self.log.error(GattCbErr.SERV_ADDED_ERR.value.format(
-                expected_event))
+            self.log.error(
+                GattCbErr.SERV_ADDED_ERR.value.format(expected_event))
             return False
         if event['data']['serviceUuid'].lower() != uuid.lower():
             self.log.error("Uuid mismatch. Found: {}, Expected {}.".format(
diff --git a/acts/framework/acts/test_utils/bt/bt_gatt_utils.py b/acts/framework/acts/test_utils/bt/bt_gatt_utils.py
index 152ef28..57893bf 100644
--- a/acts/framework/acts/test_utils/bt/bt_gatt_utils.py
+++ b/acts/framework/acts/test_utils/bt/bt_gatt_utils.py
@@ -37,7 +37,9 @@
     pass
 
 
-def setup_gatt_connection(cen_ad, mac_address, autoconnect,
+def setup_gatt_connection(cen_ad,
+                          mac_address,
+                          autoconnect,
                           transport=GattTransport.TRANSPORT_AUTO):
     test_result = True
     gatt_callback = cen_ad.droid.gattCreateGattCallback()
@@ -48,13 +50,13 @@
     try:
         event = cen_ad.ed.pop_event(expected_event, default_timeout)
     except Empty:
-        log.error(GattCbErr.GATT_CONN_CHANGE_ERR.value.format(expected_event))
-        test_result = False
-        return test_result, bluetooth_gatt, gatt_callback
+        raise GattTestUtilsError("Could not establish a connection to "
+                                 "peripheral. Expected event:".format(
+                                     expected_event))
     if event['data']['State'] != GattConnectionState.STATE_CONNECTED:
-        log.info("Could not establish a connection to peripheral. Event "
-                 "Details:".format(pprint.pformat(event)))
-        test_result = False
+        raise GattTestUtilsError("Could not establish a connection to "
+                                 "peripheral. Event Details:".format(
+                                     pprint.pformat(event)))
     return test_result, bluetooth_gatt, gatt_callback
 
 
@@ -64,11 +66,15 @@
     try:
         event = cen_ad.ed.pop_event(expected_event, default_timeout)
     except Empty:
-        log.error(GattCbErr.GATT_CONN_CHANGE_ERR.value.format(expected_event))
-        return False
-    if event['data']['State'] != GattConnectionState.STATE_DISCONNECTED:
-        return False
-    return True
+        raise GattTestUtilsError(
+            GattCbErr.GATT_CONN_CHANGE_ERR.value.format(expected_event))
+    found_state = event['data']['State']
+    expected_state = GattConnectionState.STATE_DISCONNECTED
+    if found_state != expected_state:
+        raise GattTestUtilsError(
+            "GATT connection state change expected {}, found {}".format(
+                expected_event, found_state))
+    return
 
 
 def orchestrate_gatt_connection(cen_ad,
@@ -83,7 +89,8 @@
                 mac_address, adv_callback = (
                     get_mac_address_of_generic_advertisement(cen_ad, per_ad))
             except BtTestUtilsError as err:
-                raise GattTestUtilsError("Error in getting mac address: {}".format(err))
+                raise GattTestUtilsError(
+                    "Error in getting mac address: {}".format(err))
         else:
             mac_address = per_ad.droid.bluetoothGetLocalAddress()
             adv_callback = None
@@ -149,8 +156,9 @@
                         try:
                             cen_ed.pop_event(expected_event, default_timeout)
                         except Empty:
-                            log.error(GattCbErr.DESC_WRITE_ERR.value.format(
-                                expected_event))
+                            log.error(
+                                GattCbErr.DESC_WRITE_ERR.value.format(
+                                    expected_event))
                             return False
 
 
@@ -158,32 +166,32 @@
     characteristic_input = [
         {
             'uuid': "aa7edd5a-4d1d-4f0e-883a-d145616a1630",
-            'property': GattCharacteristic.PROPERTY_WRITE.value
-            | GattCharacteristic.PROPERTY_WRITE_NO_RESPONSE.value,
+            'property': GattCharacteristic.PROPERTY_WRITE.value |
+            GattCharacteristic.PROPERTY_WRITE_NO_RESPONSE.value,
             'permission': GattCharacteristic.PROPERTY_WRITE.value
         },
         {
             'uuid': "21c0a0bf-ad51-4a2d-8124-b74003e4e8c8",
-            'property': GattCharacteristic.PROPERTY_NOTIFY.value
-            | GattCharacteristic.PROPERTY_READ.value,
+            'property': GattCharacteristic.PROPERTY_NOTIFY.value |
+            GattCharacteristic.PROPERTY_READ.value,
             'permission': GattCharacteristic.PERMISSION_READ.value
         },
         {
             'uuid': "6774191f-6ec3-4aa2-b8a8-cf830e41fda6",
-            'property': GattCharacteristic.PROPERTY_NOTIFY.value
-            | GattCharacteristic.PROPERTY_READ.value,
+            'property': GattCharacteristic.PROPERTY_NOTIFY.value |
+            GattCharacteristic.PROPERTY_READ.value,
             'permission': GattCharacteristic.PERMISSION_READ.value
         },
     ]
     descriptor_input = [
         {
             'uuid': "aa7edd5a-4d1d-4f0e-883a-d145616a1630",
-            'property': GattDescriptor.PERMISSION_READ.value
-            | GattDescriptor.PERMISSION_WRITE.value,
+            'property': GattDescriptor.PERMISSION_READ.value |
+            GattDescriptor.PERMISSION_WRITE.value,
         }, {
             'uuid': "76d5ed92-ca81-4edb-bb6b-9f019665fb32",
-            'property': GattDescriptor.PERMISSION_READ.value
-            | GattCharacteristic.PERMISSION_WRITE.value,
+            'property': GattDescriptor.PERMISSION_READ.value |
+            GattCharacteristic.PERMISSION_WRITE.value,
         }
     ]
     characteristic_list = setup_gatt_characteristics(droid,
@@ -247,32 +255,32 @@
     characteristic_input = [
         {
             'uuid': "aa7edd5a-4d1d-4f0e-883a-d145616a1630",
-            'property': GattCharacteristic.PROPERTY_WRITE.value
-            | GattCharacteristic.PROPERTY_WRITE_NO_RESPONSE.value,
+            'property': GattCharacteristic.PROPERTY_WRITE.value |
+            GattCharacteristic.PROPERTY_WRITE_NO_RESPONSE.value,
             'permission': GattCharacteristic.PROPERTY_WRITE.value
         },
         {
             'uuid': "21c0a0bf-ad51-4a2d-8124-b74003e4e8c8",
-            'property': GattCharacteristic.PROPERTY_NOTIFY.value
-            | GattCharacteristic.PROPERTY_READ.value,
+            'property': GattCharacteristic.PROPERTY_NOTIFY.value |
+            GattCharacteristic.PROPERTY_READ.value,
             'permission': GattCharacteristic.PERMISSION_READ.value
         },
         {
             'uuid': "6774191f-6ec3-4aa2-b8a8-cf830e41fda6",
-            'property': GattCharacteristic.PROPERTY_NOTIFY.value
-            | GattCharacteristic.PROPERTY_READ.value,
+            'property': GattCharacteristic.PROPERTY_NOTIFY.value |
+            GattCharacteristic.PROPERTY_READ.value,
             'permission': GattCharacteristic.PERMISSION_READ.value
         },
     ]
     descriptor_input = [
         {
             'uuid': "aa7edd5a-4d1d-4f0e-883a-d145616a1630",
-            'property': GattDescriptor.PERMISSION_READ.value
-            | GattDescriptor.PERMISSION_WRITE.value,
+            'property': GattDescriptor.PERMISSION_READ.value |
+            GattDescriptor.PERMISSION_WRITE.value,
         }, {
             'uuid': "76d5ed92-ca81-4edb-bb6b-9f019665fb32",
-            'property': GattDescriptor.PERMISSION_READ.value
-            | GattCharacteristic.PERMISSION_WRITE.value,
+            'property': GattDescriptor.PERMISSION_READ.value |
+            GattCharacteristic.PERMISSION_WRITE.value,
         }
     ]
     characteristic_list = setup_gatt_characteristics(droid,
@@ -293,9 +301,9 @@
 def setup_gatt_descriptors(droid, input):
     descriptor_list = []
     for item in input:
-        index = droid.gattServerCreateBluetoothGattDescriptor(
-            item['uuid'],
-            item['property'], )
+        index = droid.gattServerCreateBluetoothGattDescriptor(item['uuid'],
+                                                              item['property'],
+                                                              )
         descriptor_list.append(index)
     log.info("setup descriptor list: {}".format(descriptor_list))
     return descriptor_list
@@ -330,4 +338,3 @@
         log.error(GattCbErr.MTU_CHANGED_ERR.value.format(expected_event))
         return False
     return True
-
diff --git a/acts/tests/google/ble/gatt/GattConnectTest.py b/acts/tests/google/ble/gatt/GattConnectTest.py
index 2122ea5..7665817 100644
--- a/acts/tests/google/ble/gatt/GattConnectTest.py
+++ b/acts/tests/google/ble/gatt/GattConnectTest.py
@@ -96,12 +96,13 @@
 
     def _orchestrate_gatt_disconnection(self, bluetooth_gatt, gatt_callback):
         self.log.info("Disconnecting from peripheral device.")
-        test_result = disconnect_gatt_connection(self.cen_ad, bluetooth_gatt,
-                                                 gatt_callback)
-        self.cen_ad.droid.gattClientClose(bluetooth_gatt)
-        if not test_result:
-            self.log.info("Failed to disconnect from peripheral device.")
+        try:
+            disconnect_gatt_connection(self.cen_ad, bluetooth_gatt,
+                gatt_callback)
+        except GattTestUtilsError as err:
+            self.log.error(err)
             return False
+        self.cen_ad.droid.gattClientClose(bluetooth_gatt)
         return True
 
     def _iterate_attributes(self, discovered_services_index):
@@ -307,9 +308,13 @@
             get_mac_address_of_generic_advertisement(self.cen_ad, self.per_ad))
         test_result, bluetooth_gatt, gatt_callback = setup_gatt_connection(
             self.cen_ad, mac_address, autoconnect)
-        if not disconnect_gatt_connection(self.cen_ad, bluetooth_gatt,
-                                          gatt_callback):
+        try:
+            disconnect_gatt_connection(self.cen_ad, bluetooth_gatt,
+                                          gatt_callback)
+        except GattTestUtilsError as err:
+            self.log.error(err)
             return False
+        self.cen_ad.gattClientClose(bluetooth_gatt)
         autoconnect = True
         bluetooth_gatt = self.cen_ad.droid.gattClientConnectGatt(
             gatt_callback, mac_address, autoconnect,
@@ -320,7 +325,7 @@
             event = self.cen_ad.ed.pop_event(expected_event,
                                              self.default_timeout)
         except Empty:
-            log.error(GattCbErr.GATT_CONN_CHANGE_ERR.value.format(
+            self.log.error(GattCbErr.GATT_CONN_CHANGE_ERR.value.format(
                 expected_event))
             test_result = False
         return True
@@ -763,16 +768,27 @@
         TAGS: LE, Advertising, Filtering, Scanning, GATT, Characteristic, MITM
         Priority: 1
         """
-        gatt_server_callback, gatt_server = self._setup_multiple_services()
-        if not gatt_server_callback or not gatt_server:
-            return False
-        bonded = False
+        gatt_server_callback = (
+            self.per_ad.droid.gattServerCreateGattServerCallback())
+        gatt_server = self.per_ad.droid.gattServerOpenGattServer(
+            gatt_server_callback)
+        service_uuid = "3846D7A0-69C8-11E4-BA00-0002A5D5C51B"
         test_uuid = "aa7edd5a-4d1d-4f0e-883a-d145616a1630"
-        try:
-            bluetooth_gatt, gatt_callback, adv_callback = (
-                orchestrate_gatt_connection(self.cen_ad, self.per_ad))
-        except GattTestUtilsError:
+        bonded = False
+        characteristic = self.per_ad.droid.gattServerCreateBluetoothGattCharacteristic(
+            test_uuid, GattCharacteristic.PROPERTY_WRITE.value,
+            GattCharacteristic.PERMISSION_WRITE_ENCRYPTED_MITM.value)
+        gatt_service = self.per_ad.droid.gattServerCreateService(
+            service_uuid, GattService.SERVICE_TYPE_PRIMARY.value)
+        self.per_ad.droid.gattServerAddCharacteristicToService(gatt_service,
+                                                               characteristic)
+        self.per_ad.droid.gattServerAddService(gatt_server, gatt_service)
+        result = self._find_service_added_event(gatt_server_callback,
+                                                service_uuid)
+        if not result:
             return False
+        bluetooth_gatt, gatt_callback, adv_callback = (
+            orchestrate_gatt_connection(self.cen_ad, self.per_ad))
         self.adv_instances.append(adv_callback)
         if self.cen_ad.droid.gattClientDiscoverServices(bluetooth_gatt):
             expected_event = GattCbStrings.GATT_SERV_DISC.value.format(
@@ -788,7 +804,7 @@
         else:
             self.log.info("Failed to discover services.")
             return False
-        test_value = [1, 2, 3, 4, 5, 6, 7]
+        test_value = [1,2,3,4,5,6,7]
         services_count = self.cen_ad.droid.gattClientGetDiscoveredServicesCount(
             discovered_services_index)
         for i in range(services_count):
@@ -811,11 +827,10 @@
                         bonded_devices = self.cen_ad.droid.bluetoothGetBondedDevices(
                         )
                         for device in bonded_devices:
-                            if 'name' in device.keys() and device[
-                                    'name'] == target_name:
+                            if ('name' in device.keys() and
+                                device['name'] == target_name):
                                 bonded = True
                                 break
-        self._cleanup_services(gatt_server)
         return self._orchestrate_gatt_disconnection(bluetooth_gatt,
                                                     gatt_callback)
 
diff --git a/acts/tests/google/bt/gatt/GattOverBrEdrTest.py b/acts/tests/google/bt/gatt/GattOverBrEdrTest.py
index 72a2b5b..09a109e 100644
--- a/acts/tests/google/bt/gatt/GattOverBrEdrTest.py
+++ b/acts/tests/google/bt/gatt/GattOverBrEdrTest.py
@@ -66,32 +66,32 @@
         characteristic_input = [
             {
                 'uuid': "aa7edd5a-4d1d-4f0e-883a-d145616a1630",
-                'property': GattCharacteristic.PROPERTY_WRITE.value
-                | GattCharacteristic.PROPERTY_WRITE_NO_RESPONSE.value,
+                'property': GattCharacteristic.PROPERTY_WRITE.value |
+                GattCharacteristic.PROPERTY_WRITE_NO_RESPONSE.value,
                 'permission': GattCharacteristic.PROPERTY_WRITE.value
             },
             {
                 'uuid': "21c0a0bf-ad51-4a2d-8124-b74003e4e8c8",
-                'property': GattCharacteristic.PROPERTY_NOTIFY.value
-                | GattCharacteristic.PROPERTY_READ.value,
+                'property': GattCharacteristic.PROPERTY_NOTIFY.value |
+                GattCharacteristic.PROPERTY_READ.value,
                 'permission': GattCharacteristic.PERMISSION_READ.value
             },
             {
                 'uuid': "6774191f-6ec3-4aa2-b8a8-cf830e41fda6",
-                'property': GattCharacteristic.PROPERTY_NOTIFY.value
-                | GattCharacteristic.PROPERTY_READ.value,
+                'property': GattCharacteristic.PROPERTY_NOTIFY.value |
+                GattCharacteristic.PROPERTY_READ.value,
                 'permission': GattCharacteristic.PERMISSION_READ.value
             },
         ]
         descriptor_input = [
             {
                 'uuid': "aa7edd5a-4d1d-4f0e-883a-d145616a1630",
-                'property': GattDescriptor.PERMISSION_READ.value
-                | GattDescriptor.PERMISSION_WRITE.value,
+                'property': GattDescriptor.PERMISSION_READ.value |
+                GattDescriptor.PERMISSION_WRITE.value,
             }, {
                 'uuid': "76d5ed92-ca81-4edb-bb6b-9f019665fb32",
-                'property': GattDescriptor.PERMISSION_READ.value
-                | GattCharacteristic.PERMISSION_WRITE.value,
+                'property': GattDescriptor.PERMISSION_READ.value |
+                GattCharacteristic.PERMISSION_WRITE.value,
             }
         ]
         characteristic_list = setup_gatt_characteristics(droid,
@@ -101,10 +101,11 @@
 
     def _orchestrate_gatt_disconnection(self, bluetooth_gatt, gatt_callback):
         self.log.info("Disconnecting from peripheral device.")
-        test_result = disconnect_gatt_connection(self.cen_ad, bluetooth_gatt,
-                                                 gatt_callback)
-        if not test_result:
-            self.log.info("Failed to disconnect from peripheral device.")
+        try:
+            disconnect_gatt_connection(self.cen_ad, bluetooth_gatt,
+                                       gatt_callback)
+        except GattTestUtilsError as err:
+            self.log.error(err)
             return False
         return True
 
@@ -542,8 +543,7 @@
                             "onDescriptorWrite event found: {}".format(
                                 self.cen_ad.ed.pop_event(
                                     GattCbStrings.DESC_WRITE.value.format(
-                                        gatt_callback),
-                                    self.default_timeout)))
+                                        gatt_callback), self.default_timeout)))
         return True
 
     @BluetoothBaseTest.bt_test_wrap