Continue to make RFCOMM tests more robust

Fix logging
Add retries to rfcomm failures
Fix BleAdvertisingApiTest from past refactor

Change-Id: Ic6cf5523aff1cbd091825744a82aeb8d7a25ff0e
diff --git a/acts/framework/acts/test_utils/bt/BluetoothBaseTest.py b/acts/framework/acts/test_utils/bt/BluetoothBaseTest.py
index be8f169..6036a40 100644
--- a/acts/framework/acts/test_utils/bt/BluetoothBaseTest.py
+++ b/acts/framework/acts/test_utils/bt/BluetoothBaseTest.py
@@ -17,7 +17,9 @@
     Base Class for Defining Common Bluetooth Test Functionality
 """
 
+import os
 import time
+from acts import utils
 from acts.base_test import BaseTestClass
 from acts.controllers import android_device
 from acts.test_utils.bt.bt_test_utils import (
@@ -59,12 +61,28 @@
             "Test {} failed. Gathering bugreport and btsnoop logs".format(
                 test_name))
         take_btsnoop_logs(self.android_devices, self, test_name)
-        reset_bluetooth(self.android_devices)
+        self._take_bug_report(test_name, begin_time)
+        for _ in range(5):
+            if reset_bluetooth(self.android_devices):
+                break
+            else:
+                self.log.error("Failed to reset Bluetooth... retrying.")
+        return
 
-        if "no_bug_report_on_fail" not in self.user_params:
+    def _take_bug_report(self, test_name, begin_time):
+        if "no_bug_report_on_fail" in self.user_params:
+            return
+
+        # magical sleep to ensure the runtime restart or reboot begins
+        time.sleep(1)
+        for ad in self.android_devices:
             try:
-                android_device.take_bug_reports(test_name, begin_time,
-                                                self.android_devices)
+                ad.adb.wait_for_device()
+                ad.take_bug_report(test_name, begin_time)
+                tombstone_path = os.path.join(ad.log_path, "BugReports",
+                        "{},{}".format(begin_time, ad.serial).replace(' ','_'))
+                utils.create_dir(tombstone_path)
+                ad.adb.pull('/data/tombstones/', tombstone_path)
             except:
-                self.log.error("Failed to take a bug report for {}"
-                               .format(test_name))
+                ad.log.error("Failed to take a bug report for {}, {}"
+                             .format(ad.serial, test_name))
diff --git a/acts/framework/acts/test_utils/bt/bt_test_utils.py b/acts/framework/acts/test_utils/bt/bt_test_utils.py
index d2404b3..fb21beb 100644
--- a/acts/framework/acts/test_utils/bt/bt_test_utils.py
+++ b/acts/framework/acts/test_utils/bt/bt_test_utils.py
@@ -21,6 +21,7 @@
 import queue
 import threading
 import time
+from acts import utils
 
 from contextlib2 import suppress
 from subprocess import call
@@ -159,6 +160,9 @@
 
 def setup_multiple_devices_for_bt_test(android_devices):
     log.info("Setting up Android Devices")
+    # TODO: Temp fix for an selinux error.
+    for ad in android_devices:
+        ad.adb.shell("setenforce 0")
     threads = []
     try:
         for a in android_devices:
@@ -219,6 +223,7 @@
             if droid.bluetoothCheckState() is True:
                 log.info(".. actual state is ON")
                 return True
+            log.info(".. actual state is OFF")
             return False
     return True
 
@@ -421,10 +426,10 @@
 
 def take_btsnoop_logs(android_devices, testcase, testname):
     for a in android_devices:
-        take_btsnoop_log(a.droid, testcase, testname)
+        take_btsnoop_log(a, testcase, testname)
 
 
-def take_btsnoop_log(droid, testcase, test_name):
+def take_btsnoop_log(ad, testcase, test_name):
     """Grabs the btsnoop_hci log on a device and stores it in the log directory
     of the test class.
 
@@ -438,12 +443,14 @@
     """
     test_name = "".join(x for x in test_name if x.isalnum())
     with suppress(Exception):
-        serial = droid.getBuildSerial()
-        device_model = droid.getBuildModel()
+        serial = ad.droid.getBuildSerial()
+        device_model = ad.droid.getBuildModel()
         device_model = device_model.replace(" ", "")
         out_name = ','.join((test_name, device_model, serial))
+        snoop_path = ad.log_path + "/BluetoothSnoopLogs"
+        utils.create_dir(snoop_path)
         cmd = ''.join(("adb -s ", serial, " pull /sdcard/btsnoop_hci.log ",
-                       testcase.log_path + "/" + out_name, ".btsnoop_hci.log"))
+                       snoop_path + '/' + out_name, ".btsnoop_hci.log"))
         testcase.log.info("Test failed, grabbing the bt_snoop logs on {} {}."
                           .format(device_model, serial))
         exe_cmd(cmd)
@@ -466,6 +473,8 @@
         log.error("Failed to connect: {}".format(err))
         ad.droid.bluetoothRfcommCloseSocket()
         return
+    finally:
+        return
     return
 
 
@@ -479,6 +488,8 @@
         log.error("Failed to accept: {}".format(err))
         ad.droid.bluetoothRfcommCloseSocket()
         return
+    finally:
+        return
     return
 
 
diff --git a/acts/tests/google/ble/api/BleAdvertiseApiTest.py b/acts/tests/google/ble/api/BleAdvertiseApiTest.py
index 0a44f06..207f877 100644
--- a/acts/tests/google/ble/api/BleAdvertiseApiTest.py
+++ b/acts/tests/google/ble/api/BleAdvertiseApiTest.py
@@ -40,10 +40,6 @@
         self.droid_list = get_advanced_droid_list(self.android_devices)
         self.droid = self.android_devices[0].droid
 
-        if self.droid_list[0]['max_advertisements'] > 0:
-            self.tests = self.tests + (
-                "test_advertisement_greater_than_31_bytes", )
-
     @BluetoothBaseTest.bt_test_wrap
     def test_adv_settings_defaults(self):
         """Tests the default advertisement settings.
diff --git a/acts/tests/google/ble/filtering/UniqueFilteringTest.py b/acts/tests/google/ble/filtering/UniqueFilteringTest.py
index 6c575aa..6a3600b 100644
--- a/acts/tests/google/ble/filtering/UniqueFilteringTest.py
+++ b/acts/tests/google/ble/filtering/UniqueFilteringTest.py
@@ -44,19 +44,6 @@
         if self.droid_list[1]['max_advertisements'] == 0:
             self.tests = ()
             return
-        self.tests = (
-            "test_scan_flush_pending_scan_results",
-            "test_scan_non_existent_name_filter",
-            "test_scan_advertisement_with_device_service_uuid_filter_expect_no_events",
-            "test_scan_filter_device_address", )
-        if self.droid_list[1]['max_advertisements'] > 1:
-            self.tests = self.tests + \
-                ("test_scan_filtering_multiple_advertisements_manufacturer_data",
-                 )
-        if self.droid_list[0]['batch_scan_supported']:
-            self.tests = self.tests + (
-                "test_scan_flush_results_without_on_batch_scan_results_triggered",
-                "test_scan_trigger_on_batch_scan_results", )
 
     def blescan_verify_onfailure_event_handler(self, event):
         self.log.debug("Verifying onFailure event")
diff --git a/acts/tests/google/ble/gatt/GattConnectTest.py b/acts/tests/google/ble/gatt/GattConnectTest.py
index 31408c9..233ba60 100644
--- a/acts/tests/google/ble/gatt/GattConnectTest.py
+++ b/acts/tests/google/ble/gatt/GattConnectTest.py
@@ -101,7 +101,7 @@
         self.log.info("Disconnecting from peripheral device.")
         test_result = disconnect_gatt_connection(self.cen_ad, bluetooth_gatt,
                                                  gatt_callback)
-        self.cen_ad.droid.gattClientClose(gatt_callback)
+        self.cen_ad.droid.gattClientClose(bluetooth_gatt)
         if not test_result:
             self.log.info("Failed to disconnect from peripheral device.")
             return False
@@ -303,16 +303,16 @@
         bluetooth_gatt, gatt_callback, adv_callback = (
             orchestrate_gatt_connection(self.cen_ad, self.per_ad))
         self.adv_instances.append(adv_callback)
-        self.cen_ad.droid.gattClientRequestMtu(bluetooth_gatt,
-                                               MtuSize.MIN.value)
-        expected_event = GattCbStrings.MTU_CHANGED.value.format(bluetooth_gatt)
+        expected_mtu = MtuSize.MIN.value
+        self.cen_ad.droid.gattClientRequestMtu(bluetooth_gatt, expected_mtu)
+        expected_event = GattCbStrings.MTU_CHANGED.value.format(gatt_callback)
         try:
             mtu_event = self.cen_ad.ed.pop_event(expected_event,
                                                  self.default_timeout)
             mtu_size_found = mtu_event['data']['MTU']
-            if mtu_size_found != MtuSize.MIN.value:
+            if mtu_size_found != expected_mtu:
                 self.log.error("MTU size found: {}, expected: {}".format(
-                    mtu_size_found, MtuSize.MIN.value))
+                    mtu_size_found, expected_mtu))
                 return False
         except Empty:
             self.log.error(GattCbErr.MTU_CHANGED_ERR.value.format(
@@ -353,16 +353,16 @@
         bluetooth_gatt, gatt_callback, adv_callback = (
             orchestrate_gatt_connection(self.cen_ad, self.per_ad))
         self.adv_instances.append(adv_callback)
-        self.cen_ad.droid.gattClientRequestMtu(bluetooth_gatt,
-                                               MtuSize.MAX.value)
-        expected_event = GattCbStrings.MTU_CHANGED.value.format(bluetooth_gatt)
+        expected_mtu = MtuSize.MAX.value
+        self.cen_ad.droid.gattClientRequestMtu(bluetooth_gatt, expected_mtu)
+        expected_event = GattCbStrings.MTU_CHANGED.value.format(gatt_callback)
         try:
             mtu_event = self.cen_ad.ed.pop_event(expected_event,
                                                  self.default_timeout)
             mtu_size_found = mtu_event['data']['MTU']
-            if mtu_size_found != MtuSize.MAX.value:
+            if mtu_size_found != expected_mtu:
                 self.log.error("MTU size found: {}, expected: {}".format(
-                    mtu_size_found, MtuSize.MAX.value))
+                    mtu_size_found, expected_mtu))
                 return False
         except Empty:
             self.log.error(GattCbErr.MTU_CHANGED_ERR.value.format(
@@ -406,7 +406,7 @@
         self.adv_instances.append(adv_callback)
         self.cen_ad.droid.gattClientRequestMtu(bluetooth_gatt,
                                                MtuSize.MIN.value - 1)
-        expected_event = GattCbStrings.MTU_CHANGED.value.format(bluetooth_gatt)
+        expected_event = GattCbStrings.MTU_CHANGED.value.format(gatt_callback)
         try:
             self.cen_ad.ed.pop_event(expected_event, self.default_timeout)
             self.log.error("Found {} event when it wasn't expected".format(
@@ -1010,6 +1010,7 @@
                         return False
         return True
 
+    @BluetoothBaseTest.bt_test_wrap
     def test_gatt_connect_mitm_attack(self):
         """Test GATT connection with permission write encrypted mitm.
 
@@ -1115,6 +1116,7 @@
                                 break
         return True
 
+    @BluetoothBaseTest.bt_test_wrap
     def test_gatt_connect_mitm_attack(self):
         """Test GATT connection with permission write encrypted mitm.
 
diff --git a/acts/tests/google/bt/system_tests/RfcommLongevityTest.py b/acts/tests/google/bt/system_tests/RfcommLongevityTest.py
index 5e72c54..119b857 100644
--- a/acts/tests/google/bt/system_tests/RfcommLongevityTest.py
+++ b/acts/tests/google/bt/system_tests/RfcommLongevityTest.py
@@ -49,13 +49,21 @@
 
     def on_fail(self, test_name, begin_time):
         take_btsnoop_logs(self.android_devices, self, test_name)
-        reset_bluetooth(self.android_devices)
+        for _ in range(5):
+            if reset_bluetooth(self.android_devices):
+                break
+            else:
+                self.log.info("Failed to reset bluetooth state, retrying...")
 
     def teardown_test(self):
         with suppress(Exception):
             for thread in self.thread_list:
                 thread.join()
-        reset_bluetooth(self.android_devices)
+        for _ in range(5):
+            if reset_bluetooth(self.android_devices):
+                break
+            else:
+                self.log.info("Failed to reset bluetooth state, retrying...")
         time.sleep(20) #safeguard in case of connId errors
 
     def orchestrate_rfcomm_connect(self, server_mac):