diff options
53 files changed, 1416 insertions, 3052 deletions
diff --git a/system/build/toolchain/clang/get_clang_suffix.py b/system/build/toolchain/clang/get_clang_suffix.py index fbfe16c959..6bf7b9c8ba 100644 --- a/system/build/toolchain/clang/get_clang_suffix.py +++ b/system/build/toolchain/clang/get_clang_suffix.py @@ -18,8 +18,7 @@ clang_version_major = 0 clang_version_minor = 0 if clang_path: - clang_version_out = subprocess.Popen( - [clang_path, "--version"], stdout=subprocess.PIPE).communicate()[0] + clang_version_out = subprocess.Popen([clang_path, "--version"], stdout=subprocess.PIPE).communicate()[0] clang_version_match = re.search(CLANG_VERSION_REGEX, clang_version_out) clang_version_str = clang_version_match.group(1) clang_version_array = clang_version_str.split('.') diff --git a/system/gd/cert/async_subprocess_logger.py b/system/gd/cert/async_subprocess_logger.py index 329927548a..f3f69de897 100644 --- a/system/gd/cert/async_subprocess_logger.py +++ b/system/gd/cert/async_subprocess_logger.py @@ -66,26 +66,19 @@ class AsyncSubprocessLogger: try: result = self.future.result(timeout=self.WAIT_TIMEOUT_SECONDS) if result: - logging.error( - "logging thread %s produced an error when executing: %s" % - (self.tag, str(result))) + logging.error("logging thread %s produced an error when executing: %s" % (self.tag, str(result))) except concurrent.futures.TimeoutError: - logging.error("logging thread %s failed to finish after %d seconds" - % (self.tag, self.WAIT_TIMEOUT_SECONDS)) + logging.error("logging thread %s failed to finish after %d seconds" % (self.tag, self.WAIT_TIMEOUT_SECONDS)) self.executor.shutdown(wait=False) def __logging_loop(self): with ExitStack() as stack: - log_files = [ - stack.enter_context(open(file_path, 'w')) - for file_path in self.log_file_paths - ] + log_files = [stack.enter_context(open(file_path, 'w')) for file_path in self.log_file_paths] for line in self.process.stdout: for log_file in log_files: log_file.write(line) if self.log_to_stdout: if self.color: - print("[%s%s%s] %s" % (self.color, self.tag, - TerminalColor.END, line.strip())) + print("[%s%s%s] %s" % (self.color, self.tag, TerminalColor.END, line.strip())) else: print("[%s] %s" % (self.tag, line.strip())) diff --git a/system/gd/cert/behavior.py b/system/gd/cert/behavior.py index 8b94124e22..8403dd6f21 100644 --- a/system/gd/cert/behavior.py +++ b/system/gd/cert/behavior.py @@ -79,8 +79,7 @@ class SingleArgumentBehavior(object): self.__obj_invoked(obj) else: raise signals.TestFailure( - "%s: behavior for %s went unhandled" % - (self._reply_stage_factory().__class__.__name__, obj), + "%s: behavior for %s went unhandled" % (self._reply_stage_factory().__class__.__name__, obj), extras=None) def __obj_invoked(self, obj): @@ -125,8 +124,7 @@ class ReplyStage(object): self._persistence = persistence def _commit(self, fn): - self._behavior.append( - BehaviorInstance(self._matcher, self._persistence, fn)) + self._behavior.append(BehaviorInstance(self._matcher, self._persistence, fn)) class BehaviorInstance(object): @@ -156,8 +154,7 @@ class BoundVerificationStage(object): self._timeout = timeout def times(self, times=1): - return self._behavior.wait_until_invoked(self._matcher, times, - self._timeout) + return self._behavior.wait_until_invoked(self._matcher, times, self._timeout) class WaitForBehaviorSubject(object): diff --git a/system/gd/cert/bluetooth_packets_python3_setup.py b/system/gd/cert/bluetooth_packets_python3_setup.py index 7cca0196ae..2ee7d82828 100644 --- a/system/gd/cert/bluetooth_packets_python3_setup.py +++ b/system/gd/cert/bluetooth_packets_python3_setup.py @@ -29,16 +29,12 @@ import glob from setuptools import setup, Extension ANDROID_BUILD_TOP = os.getenv("ANDROID_BUILD_TOP") -PYBIND11_INCLUDE_DIR = os.path.join(ANDROID_BUILD_TOP, - "external/python/pybind11/include") +PYBIND11_INCLUDE_DIR = os.path.join(ANDROID_BUILD_TOP, "external/python/pybind11/include") GD_DIR = os.path.join(ANDROID_BUILD_TOP, "packages/modules/Bluetooth/system/gd") -BT_PACKETS_GEN_DIR = os.path.join( - ANDROID_BUILD_TOP, - "out/soong/.intermediates/packages/modules/Bluetooth/system/gd/BluetoothGeneratedPackets_h/gen") -BT_PACKETS_PY3_GEN_DIR = os.path.join( - ANDROID_BUILD_TOP, - "out/soong/.intermediates/packages/modules/Bluetooth/system/gd/BluetoothGeneratedPackets_python3_cc/gen" -) +BT_PACKETS_GEN_DIR = os.path.join(ANDROID_BUILD_TOP, + "out/soong/.intermediates/packages/modules/Bluetooth/system/gd/BluetoothGeneratedPackets_h/gen") +BT_PACKETS_PY3_GEN_DIR = os.path.join(ANDROID_BUILD_TOP, + "out/soong/.intermediates/packages/modules/Bluetooth/system/gd/BluetoothGeneratedPackets_python3_cc/gen") BT_PACKETS_BASE_SRCS = [ os.path.join(GD_DIR, "l2cap/fcs.cc"), @@ -61,9 +57,7 @@ BT_PACKETS_PY3_SRCs = \ bluetooth_packets_python3_module = Extension( 'bluetooth_packets_python3', sources=BT_PACKETS_BASE_SRCS + BT_PACKETS_PY3_SRCs, - include_dirs=[ - GD_DIR, BT_PACKETS_GEN_DIR, BT_PACKETS_PY3_GEN_DIR, PYBIND11_INCLUDE_DIR - ], + include_dirs=[GD_DIR, BT_PACKETS_GEN_DIR, BT_PACKETS_PY3_GEN_DIR, PYBIND11_INCLUDE_DIR], extra_compile_args=['-std=c++17']) setup( diff --git a/system/gd/cert/captures.py b/system/gd/cert/captures.py index 1a779f38d9..1c8e6b6714 100644 --- a/system/gd/cert/captures.py +++ b/system/gd/cert/captures.py @@ -26,126 +26,99 @@ class HalCaptures(object): @staticmethod def ReadBdAddrCompleteCapture(): - return Capture(lambda packet: b'\x0e\x0a\x01\x09\x10' in packet.payload, - lambda packet: hci_packets.ReadBdAddrCompleteView( - hci_packets.CommandCompleteView( - hci_packets.EventPacketView( - bt_packets.PacketViewLittleEndian( - list(packet.payload)))))) + return Capture( + lambda packet: b'\x0e\x0a\x01\x09\x10' in packet.payload, lambda packet: hci_packets.ReadBdAddrCompleteView( + hci_packets.CommandCompleteView( + hci_packets.EventPacketView(bt_packets.PacketViewLittleEndian(list(packet.payload)))))) @staticmethod def ConnectionRequestCapture(): - return Capture(lambda packet: b'\x04\x0a' in packet.payload, - lambda packet: hci_packets.ConnectionRequestView( - hci_packets.EventPacketView( - bt_packets.PacketViewLittleEndian( - list(packet.payload))))) + return Capture( + lambda packet: b'\x04\x0a' in packet.payload, lambda packet: hci_packets.ConnectionRequestView( + hci_packets.EventPacketView(bt_packets.PacketViewLittleEndian(list(packet.payload))))) @staticmethod def ConnectionCompleteCapture(): - return Capture(lambda packet: b'\x03\x0b\x00' in packet.payload, - lambda packet: hci_packets.ConnectionCompleteView( - hci_packets.EventPacketView( - bt_packets.PacketViewLittleEndian( - list(packet.payload))))) + return Capture( + lambda packet: b'\x03\x0b\x00' in packet.payload, lambda packet: hci_packets.ConnectionCompleteView( + hci_packets.EventPacketView(bt_packets.PacketViewLittleEndian(list(packet.payload))))) @staticmethod def LeConnectionCompleteCapture(): - return Capture(lambda packet: packet.payload[0] == 0x3e - and (packet.payload[2] == 0x01 or packet.payload[2] == 0x0a), - lambda packet: hci_packets.LeConnectionCompleteView( - hci_packets.LeMetaEventView( - hci_packets.EventPacketView( - bt_packets.PacketViewLittleEndian( - list(packet.payload)))))) + return Capture( + lambda packet: packet.payload[0] == 0x3e and (packet.payload[2] == 0x01 or packet.payload[2] == 0x0a), + lambda packet: hci_packets.LeConnectionCompleteView( + hci_packets.LeMetaEventView( + hci_packets.EventPacketView(bt_packets.PacketViewLittleEndian(list(packet.payload)))))) class HciCaptures(object): @staticmethod def ReadBdAddrCompleteCapture(): - return Capture(lambda packet: b'\x0e\x0a\x01\x09\x10' in packet.event, - lambda packet: hci_packets.ReadBdAddrCompleteView( - hci_packets.CommandCompleteView( - hci_packets.EventPacketView( - bt_packets.PacketViewLittleEndian( - list(packet.event)))))) + return Capture( + lambda packet: b'\x0e\x0a\x01\x09\x10' in packet.event, lambda packet: hci_packets.ReadBdAddrCompleteView( + hci_packets.CommandCompleteView( + hci_packets.EventPacketView(bt_packets.PacketViewLittleEndian(list(packet.event)))))) @staticmethod def ConnectionRequestCapture(): - return Capture(lambda packet: b'\x04\x0a' in packet.event, - lambda packet: hci_packets.ConnectionRequestView( - hci_packets.EventPacketView( - bt_packets.PacketViewLittleEndian( - list(packet.event))))) + return Capture( + lambda packet: b'\x04\x0a' in packet.event, lambda packet: hci_packets.ConnectionRequestView( + hci_packets.EventPacketView(bt_packets.PacketViewLittleEndian(list(packet.event))))) @staticmethod def ConnectionCompleteCapture(): - return Capture(lambda packet: b'\x03\x0b\x00' in packet.event, - lambda packet: hci_packets.ConnectionCompleteView( - hci_packets.EventPacketView( - bt_packets.PacketViewLittleEndian( - list(packet.event))))) + return Capture( + lambda packet: b'\x03\x0b\x00' in packet.event, lambda packet: hci_packets.ConnectionCompleteView( + hci_packets.EventPacketView(bt_packets.PacketViewLittleEndian(list(packet.event))))) @staticmethod def LeConnectionCompleteCapture(): - return Capture(lambda packet: packet.event[0] == 0x3e - and (packet.event[2] == 0x01 or packet.event[2] == 0x0a), + return Capture( + lambda packet: packet.event[0] == 0x3e and (packet.event[2] == 0x01 or packet.event[2] == 0x0a), lambda packet: hci_packets.LeConnectionCompleteView( hci_packets.LeMetaEventView( - hci_packets.EventPacketView( - bt_packets.PacketViewLittleEndian( - list(packet.event)))))) + hci_packets.EventPacketView(bt_packets.PacketViewLittleEndian(list(packet.event)))))) class L2capCaptures(object): @staticmethod def ConnectionRequest(psm): - return Capture( - L2capMatchers.ConnectionRequest(psm), - L2capCaptures._extract_connection_request) + return Capture(L2capMatchers.ConnectionRequest(psm), L2capCaptures._extract_connection_request) @staticmethod def _extract_connection_request(packet): - frame = L2capMatchers.control_frame_with_code( - packet, CommandCode.CONNECTION_REQUEST) + frame = L2capMatchers.control_frame_with_code(packet, CommandCode.CONNECTION_REQUEST) return l2cap_packets.ConnectionRequestView(frame) @staticmethod def ConnectionResponse(scid): - return Capture( - L2capMatchers.ConnectionResponse(scid), - L2capCaptures._extract_connection_response) + return Capture(L2capMatchers.ConnectionResponse(scid), L2capCaptures._extract_connection_response) @staticmethod def _extract_connection_response(packet): - frame = L2capMatchers.control_frame_with_code( - packet, CommandCode.CONNECTION_RESPONSE) + frame = L2capMatchers.control_frame_with_code(packet, CommandCode.CONNECTION_RESPONSE) return l2cap_packets.ConnectionResponseView(frame) @staticmethod def ConfigurationRequest(cid=None): - return Capture( - L2capMatchers.ConfigurationRequest(cid), - L2capCaptures._extract_configuration_request) + return Capture(L2capMatchers.ConfigurationRequest(cid), L2capCaptures._extract_configuration_request) @staticmethod def _extract_configuration_request(packet): - frame = L2capMatchers.control_frame_with_code( - packet, CommandCode.CONFIGURATION_REQUEST) + frame = L2capMatchers.control_frame_with_code(packet, CommandCode.CONFIGURATION_REQUEST) return l2cap_packets.ConfigurationRequestView(frame) @staticmethod def CreditBasedConnectionRequest(psm): return Capture( - L2capMatchers.CreditBasedConnectionRequest(psm), - L2capCaptures._extract_credit_based_connection_request) + L2capMatchers.CreditBasedConnectionRequest(psm), L2capCaptures._extract_credit_based_connection_request) @staticmethod def _extract_credit_based_connection_request(packet): - frame = L2capMatchers.le_control_frame_with_code( - packet, LeCommandCode.LE_CREDIT_BASED_CONNECTION_REQUEST) + frame = L2capMatchers.le_control_frame_with_code(packet, LeCommandCode.LE_CREDIT_BASED_CONNECTION_REQUEST) return l2cap_packets.LeCreditBasedConnectionRequestView(frame) @staticmethod @@ -155,6 +128,5 @@ class L2capCaptures(object): @staticmethod def _extract_credit_based_connection_response(packet): - frame = L2capMatchers.le_control_frame_with_code( - packet, LeCommandCode.LE_CREDIT_BASED_CONNECTION_RESPONSE) + frame = L2capMatchers.le_control_frame_with_code(packet, LeCommandCode.LE_CREDIT_BASED_CONNECTION_RESPONSE) return l2cap_packets.LeCreditBasedConnectionResponseView(frame) diff --git a/system/gd/cert/cert_self_test.py b/system/gd/cert/cert_self_test.py index 401987fd61..fa55b6ae12 100644 --- a/system/gd/cert/cert_self_test.py +++ b/system/gd/cert/cert_self_test.py @@ -98,8 +98,7 @@ class FetchEvents: class TestBehaviors(object): def __init__(self, parent): - self.test_request_behavior = SingleArgumentBehavior( - lambda: TestBehaviors.TestRequestReplyStage(parent)) + self.test_request_behavior = SingleArgumentBehavior(lambda: TestBehaviors.TestRequestReplyStage(parent)) def test_request(self, matcher): return self.test_request_behavior.begin(matcher) @@ -151,8 +150,7 @@ class CertSelfTest(BaseTestClass): def test_assert_none_fails(self): try: - with EventStream(FetchEvents(events=[17], - delay_ms=50)) as event_stream: + with EventStream(FetchEvents(events=[17], delay_ms=50)) as event_stream: event_stream.assert_none(timeout=timedelta(seconds=1)) except Exception as e: logging.debug(e) @@ -160,69 +158,50 @@ class CertSelfTest(BaseTestClass): return False def test_assert_none_matching_passes(self): - with EventStream(FetchEvents(events=[1, 2, 3], - delay_ms=50)) as event_stream: - event_stream.assert_none_matching( - lambda data: data.value_ == 4, timeout=timedelta(seconds=0.15)) + with EventStream(FetchEvents(events=[1, 2, 3], delay_ms=50)) as event_stream: + event_stream.assert_none_matching(lambda data: data.value_ == 4, timeout=timedelta(seconds=0.15)) def test_assert_none_matching_passes_after_1_second(self): - with EventStream(FetchEvents(events=[1, 2, 3, 4], - delay_ms=400)) as event_stream: - event_stream.assert_none_matching( - lambda data: data.value_ == 4, timeout=timedelta(seconds=1)) + with EventStream(FetchEvents(events=[1, 2, 3, 4], delay_ms=400)) as event_stream: + event_stream.assert_none_matching(lambda data: data.value_ == 4, timeout=timedelta(seconds=1)) def test_assert_none_matching_fails(self): try: - with EventStream(FetchEvents(events=[1, 2, 3], - delay_ms=50)) as event_stream: - event_stream.assert_none_matching( - lambda data: data.value_ == 2, timeout=timedelta(seconds=1)) + with EventStream(FetchEvents(events=[1, 2, 3], delay_ms=50)) as event_stream: + event_stream.assert_none_matching(lambda data: data.value_ == 2, timeout=timedelta(seconds=1)) except Exception as e: logging.debug(e) return True # Failed as expected return False def test_assert_occurs_at_least_passes(self): - with EventStream(FetchEvents(events=[1, 2, 3, 1, 2, 3], - delay_ms=40)) as event_stream: + with EventStream(FetchEvents(events=[1, 2, 3, 1, 2, 3], delay_ms=40)) as event_stream: event_stream.assert_event_occurs( - lambda data: data.value_ == 1, - timeout=timedelta(milliseconds=300), - at_least_times=2) + lambda data: data.value_ == 1, timeout=timedelta(milliseconds=300), at_least_times=2) def test_assert_occurs_passes(self): - with EventStream(FetchEvents(events=[1, 2, 3], - delay_ms=50)) as event_stream: - event_stream.assert_event_occurs( - lambda data: data.value_ == 1, timeout=timedelta(seconds=1)) + with EventStream(FetchEvents(events=[1, 2, 3], delay_ms=50)) as event_stream: + event_stream.assert_event_occurs(lambda data: data.value_ == 1, timeout=timedelta(seconds=1)) def test_assert_occurs_fails(self): try: - with EventStream(FetchEvents(events=[1, 2, 3], - delay_ms=50)) as event_stream: - event_stream.assert_event_occurs( - lambda data: data.value_ == 4, timeout=timedelta(seconds=1)) + with EventStream(FetchEvents(events=[1, 2, 3], delay_ms=50)) as event_stream: + event_stream.assert_event_occurs(lambda data: data.value_ == 4, timeout=timedelta(seconds=1)) except Exception as e: logging.debug(e) return True # Failed as expected return False def test_assert_occurs_at_most_passes(self): - with EventStream(FetchEvents(events=[1, 2, 3, 4], - delay_ms=50)) as event_stream: + with EventStream(FetchEvents(events=[1, 2, 3, 4], delay_ms=50)) as event_stream: event_stream.assert_event_occurs_at_most( - lambda data: data.value_ < 4, - timeout=timedelta(seconds=1), - at_most_times=3) + lambda data: data.value_ < 4, timeout=timedelta(seconds=1), at_most_times=3) def test_assert_occurs_at_most_fails(self): try: - with EventStream(FetchEvents(events=[1, 2, 3, 4], - delay_ms=50)) as event_stream: + with EventStream(FetchEvents(events=[1, 2, 3, 4], delay_ms=50)) as event_stream: event_stream.assert_event_occurs_at_most( - lambda data: data.value_ > 1, - timeout=timedelta(seconds=1), - at_most_times=2) + lambda data: data.value_ > 1, timeout=timedelta(seconds=1), at_most_times=2) except Exception as e: logging.debug(e) return True # Failed as expected @@ -237,10 +216,8 @@ class CertSelfTest(BaseTestClass): inside = hci_packets.ReadScanEnableBuilder() logging.debug(inside.Serialize()) logging.debug("building outside") - outside = hci_packets.AclPacketBuilder( - handle, - hci_packets.PacketBoundaryFlag.FIRST_NON_AUTOMATICALLY_FLUSHABLE, - hci_packets.BroadcastFlag.POINT_TO_POINT, inside) + outside = hci_packets.AclPacketBuilder(handle, hci_packets.PacketBoundaryFlag.FIRST_NON_AUTOMATICALLY_FLUSHABLE, + hci_packets.BroadcastFlag.POINT_TO_POINT, inside) logging.debug(outside.Serialize()) logging.debug("Done!") @@ -256,13 +233,10 @@ class CertSelfTest(BaseTestClass): [mtu_opt, fcs_opt]) request_b_frame = l2cap_packets.BasicFrameBuilder(0x01, request) handle = 123 - wrapped = hci_packets.AclPacketBuilder( - handle, - hci_packets.PacketBoundaryFlag.FIRST_NON_AUTOMATICALLY_FLUSHABLE, - hci_packets.BroadcastFlag.POINT_TO_POINT, request_b_frame) + wrapped = hci_packets.AclPacketBuilder(handle, hci_packets.PacketBoundaryFlag.FIRST_NON_AUTOMATICALLY_FLUSHABLE, + hci_packets.BroadcastFlag.POINT_TO_POINT, request_b_frame) # Size is ACL (4) + L2CAP (4) + Configure (8) + MTU (4) + FCS (3) - asserts.assert_true( - len(wrapped.Serialize()) == 23, "Packet serialized incorrectly") + asserts.assert_true(len(wrapped.Serialize()) == 23, "Packet serialized incorrectly") def test_assertThat_boolean_success(self): assertThat(True).isTrue() @@ -317,20 +291,16 @@ class CertSelfTest(BaseTestClass): return False def test_assertThat_eventStream_emits_passes(self): - with EventStream(FetchEvents(events=[1, 2, 3], - delay_ms=50)) as event_stream: + with EventStream(FetchEvents(events=[1, 2, 3], delay_ms=50)) as event_stream: assertThat(event_stream).emits(lambda data: data.value_ == 1) def test_assertThat_eventStream_emits_then_passes(self): - with EventStream(FetchEvents(events=[1, 2, 3], - delay_ms=50)) as event_stream: - assertThat(event_stream).emits(lambda data: data.value_ == 1).then( - lambda data: data.value_ == 3) + with EventStream(FetchEvents(events=[1, 2, 3], delay_ms=50)) as event_stream: + assertThat(event_stream).emits(lambda data: data.value_ == 1).then(lambda data: data.value_ == 3) def test_assertThat_eventStream_emits_fails(self): try: - with EventStream(FetchEvents(events=[1, 2, 3], - delay_ms=50)) as event_stream: + with EventStream(FetchEvents(events=[1, 2, 3], delay_ms=50)) as event_stream: assertThat(event_stream).emits(lambda data: data.value_ == 4) except Exception as e: logging.debug(e) @@ -339,38 +309,27 @@ class CertSelfTest(BaseTestClass): def test_assertThat_eventStream_emits_then_fails(self): try: - with EventStream(FetchEvents(events=[1, 2, 3], - delay_ms=50)) as event_stream: - assertThat(event_stream).emits( - lambda data: data.value_ == 1).emits( - lambda data: data.value_ == 4) + with EventStream(FetchEvents(events=[1, 2, 3], delay_ms=50)) as event_stream: + assertThat(event_stream).emits(lambda data: data.value_ == 1).emits(lambda data: data.value_ == 4) except Exception as e: logging.debug(e) return True # Failed as expected return False def test_assertThat_eventStream_emitsInOrder_passes(self): - with EventStream(FetchEvents(events=[1, 2, 3], - delay_ms=50)) as event_stream: - assertThat(event_stream).emits( - lambda data: data.value_ == 1, - lambda data: data.value_ == 2).inOrder() + with EventStream(FetchEvents(events=[1, 2, 3], delay_ms=50)) as event_stream: + assertThat(event_stream).emits(lambda data: data.value_ == 1, lambda data: data.value_ == 2).inOrder() def test_assertThat_eventStream_emitsInAnyOrder_passes(self): - with EventStream(FetchEvents(events=[1, 2, 3], - delay_ms=50)) as event_stream: + with EventStream(FetchEvents(events=[1, 2, 3], delay_ms=50)) as event_stream: assertThat(event_stream).emits( lambda data: data.value_ == 2, - lambda data: data.value_ == 1).inAnyOrder().then( - lambda data: data.value_ == 3) + lambda data: data.value_ == 1).inAnyOrder().then(lambda data: data.value_ == 3) def test_assertThat_eventStream_emitsInOrder_fails(self): try: - with EventStream(FetchEvents(events=[1, 2, 3], - delay_ms=50)) as event_stream: - assertThat(event_stream).emits( - lambda data: data.value_ == 2, - lambda data: data.value_ == 1).inOrder() + with EventStream(FetchEvents(events=[1, 2, 3], delay_ms=50)) as event_stream: + assertThat(event_stream).emits(lambda data: data.value_ == 2, lambda data: data.value_ == 1).inOrder() except Exception as e: logging.debug(e) return True # Failed as expected @@ -378,37 +337,28 @@ class CertSelfTest(BaseTestClass): def test_assertThat_eventStream_emitsInAnyOrder_fails(self): try: - with EventStream(FetchEvents(events=[1, 2, 3], - delay_ms=50)) as event_stream: - assertThat(event_stream).emits( - lambda data: data.value_ == 4, - lambda data: data.value_ == 1).inAnyOrder() + with EventStream(FetchEvents(events=[1, 2, 3], delay_ms=50)) as event_stream: + assertThat(event_stream).emits(lambda data: data.value_ == 4, + lambda data: data.value_ == 1).inAnyOrder() except Exception as e: logging.debug(e) return True # Failed as expected return False def test_assertThat_emitsNone_passes(self): - with EventStream(FetchEvents(events=[1, 2, 3], - delay_ms=50)) as event_stream: + with EventStream(FetchEvents(events=[1, 2, 3], delay_ms=50)) as event_stream: assertThat(event_stream).emitsNone( - lambda data: data.value_ == 4, - timeout=timedelta(seconds=0.15)).thenNone( - lambda data: data.value_ == 5, - timeout=timedelta(seconds=0.15)) + lambda data: data.value_ == 4, timeout=timedelta(seconds=0.15)).thenNone( + lambda data: data.value_ == 5, timeout=timedelta(seconds=0.15)) def test_assertThat_emitsNone_passes_after_1_second(self): - with EventStream(FetchEvents(events=[1, 2, 3, 4], - delay_ms=400)) as event_stream: - assertThat(event_stream).emitsNone( - lambda data: data.value_ == 4, timeout=timedelta(seconds=1)) + with EventStream(FetchEvents(events=[1, 2, 3, 4], delay_ms=400)) as event_stream: + assertThat(event_stream).emitsNone(lambda data: data.value_ == 4, timeout=timedelta(seconds=1)) def test_assertThat_emitsNone_fails(self): try: - with EventStream(FetchEvents(events=[1, 2, 3], - delay_ms=50)) as event_stream: - assertThat(event_stream).emitsNone( - lambda data: data.value_ == 2, timeout=timedelta(seconds=1)) + with EventStream(FetchEvents(events=[1, 2, 3], delay_ms=50)) as event_stream: + assertThat(event_stream).emitsNone(lambda data: data.value_ == 2, timeout=timedelta(seconds=1)) except Exception as e: logging.debug(e) return True # Failed as expected @@ -416,9 +366,8 @@ class CertSelfTest(BaseTestClass): def test_assertThat_emitsNone_zero_passes(self): with EventStream(FetchEvents(events=[], delay_ms=50)) as event_stream: - assertThat(event_stream).emitsNone( - timeout=timedelta(milliseconds=10)).thenNone( - timeout=timedelta(milliseconds=10)) + assertThat(event_stream).emitsNone(timeout=timedelta(milliseconds=10)).thenNone( + timeout=timedelta(milliseconds=10)) def test_assertThat_emitsNone_zero_passes_after_one_second(self): with EventStream(FetchEvents([1], delay_ms=1500)) as event_stream: @@ -426,8 +375,7 @@ class CertSelfTest(BaseTestClass): def test_assertThat_emitsNone_zero_fails(self): try: - with EventStream(FetchEvents(events=[17], - delay_ms=50)) as event_stream: + with EventStream(FetchEvents(events=[17], delay_ms=50)) as event_stream: assertThat(event_stream).emitsNone(timeout=timedelta(seconds=1)) except Exception as e: logging.debug(e) @@ -435,8 +383,7 @@ class CertSelfTest(BaseTestClass): return False def test_filtering_event_stream_none_filter_function(self): - with EventStream(FetchEvents(events=[1, 2, 3], - delay_ms=50)) as event_stream: + with EventStream(FetchEvents(events=[1, 2, 3], delay_ms=50)) as event_stream: filtered_event_stream = FilteringEventStream(event_stream, None) assertThat(filtered_event_stream)\ .emits(lambda data: data.value_ == 1)\ @@ -454,8 +401,7 @@ class CertSelfTest(BaseTestClass): pass except Exception as e: asserts.fail("@metadata() should only raise signals.TestFailure, " - "but raised %s with msg %s instead" % - (e.__class__.__name__, str(e))) + "but raised %s with msg %s instead" % (e.__class__.__name__, str(e))) else: asserts.fail("@metadata() should not work") @@ -471,8 +417,7 @@ class CertSelfTest(BaseTestClass): pass except Exception as e: asserts.fail("@metadata should only raise signals.TestFailure, " - "but raised %s with msg %s instead" % - (e.__class__.__name__, str(e))) + "but raised %s with msg %s instead" % (e.__class__.__name__, str(e))) else: asserts.fail("@metadata should not work") @@ -488,8 +433,7 @@ class CertSelfTest(BaseTestClass): pass except Exception as e: asserts.fail("should only raise signals.TestFailure, " - "but raised %s with msg %s instead" % - (e.__class__.__name__, str(e))) + "but raised %s with msg %s instead" % (e.__class__.__name__, str(e))) else: asserts.fail("missing pts_test_id should not work") @@ -505,8 +449,7 @@ class CertSelfTest(BaseTestClass): pass except Exception as e: asserts.fail("should only raise signals.TestFailure, " - "but raised %s with msg %s instead" % - (e.__class__.__name__, str(e))) + "but raised %s with msg %s instead" % (e.__class__.__name__, str(e))) else: asserts.fail("missing pts_test_name should not work") @@ -519,13 +462,9 @@ class CertSelfTest(BaseTestClass): try: simple_pass_test(1) except signals.TestPass as e: - asserts.assert_true( - "pts_test_id" in e.extras, - msg=("pts_test_id not in extra: %s" % str(e.extras))) + asserts.assert_true("pts_test_id" in e.extras, msg=("pts_test_id not in extra: %s" % str(e.extras))) asserts.assert_equal(e.extras["pts_test_id"], "A/B/C") - asserts.assert_true( - "pts_test_name" in e.extras, - msg=("pts_test_name not in extra: %s" % str(e.extras))) + asserts.assert_true("pts_test_name" in e.extras, msg=("pts_test_name not in extra: %s" % str(e.extras))) asserts.assert_equal(e.extras["pts_test_name"], "Hello world") else: asserts.fail("Must throw an exception using @metadata decorator") @@ -539,19 +478,14 @@ class CertSelfTest(BaseTestClass): try: simple_fail_test("BEEFBEEF") except signals.TestError as e: - asserts.assert_true( - "pts_test_id" in e.extras, - msg=("pts_test_id not in extra: %s" % str(e.extras))) + asserts.assert_true("pts_test_id" in e.extras, msg=("pts_test_id not in extra: %s" % str(e.extras))) asserts.assert_equal(e.extras["pts_test_id"], "A/B/C") - asserts.assert_true( - "pts_test_name" in e.extras, - msg=("pts_test_name not in extra: %s" % str(e.extras))) + asserts.assert_true("pts_test_name" in e.extras, msg=("pts_test_name not in extra: %s" % str(e.extras))) asserts.assert_equal(e.extras["pts_test_name"], "Hello world") trace_str = traceback.format_exc() asserts.assert_true( "raise ValueError(failure_argument)" in trace_str, - msg="Failed test method not in error stack trace: %s" % - trace_str) + msg="Failed test method not in error stack trace: %s" % trace_str) else: asserts.fail("Must throw an exception using @metadata decorator") @@ -607,8 +541,7 @@ class CertSelfTest(BaseTestClass): thing = ObjectWithBehaviors() thing.behaviors.test_request_behavior.set_default_to_ignore() - when(thing).test_request( - lambda obj: obj == "B").always().increment_count() + when(thing).test_request(lambda obj: obj == "B").always().increment_count() thing.behaviors.test_request_behavior.run("A") thing.behaviors.test_request_behavior.run("B") @@ -621,8 +554,7 @@ class CertSelfTest(BaseTestClass): thing = ObjectWithBehaviors() thing.behaviors.test_request_behavior.set_default_to_ignore() - when(thing).test_request( - anything()).then().increment_count().increment_count() + when(thing).test_request(anything()).then().increment_count().increment_count() thing.behaviors.test_request_behavior.run("A") thing.behaviors.test_request_behavior.run("B") @@ -635,10 +567,8 @@ class CertSelfTest(BaseTestClass): thing = ObjectWithBehaviors() thing.behaviors.test_request_behavior.set_default_to_ignore() - when(thing).test_request(lambda obj: obj == "B").then( - times=1).increment_count() - when(thing).test_request( - lambda obj: obj == "C").always().increment_count() + when(thing).test_request(lambda obj: obj == "B").then(times=1).increment_count() + when(thing).test_request(lambda obj: obj == "C").always().increment_count() thing.behaviors.test_request_behavior.run("A") thing.behaviors.test_request_behavior.run("B") @@ -665,8 +595,7 @@ class CertSelfTest(BaseTestClass): def test_fluent_behavior__set_default_works(self): thing = ObjectWithBehaviors() - thing.behaviors.test_request_behavior.set_default( - lambda obj: thing.increment_unhandled()) + thing.behaviors.test_request_behavior.set_default(lambda obj: thing.increment_unhandled()) when(thing).test_request(anything()).then().increment_count() @@ -689,8 +618,7 @@ class CertSelfTest(BaseTestClass): def test_fluent_behavior__wait_until_done_different_lambda(self): thing = ObjectWithBehaviors() - when(thing).test_request( - lambda obj: obj == "A").then().increment_count() + when(thing).test_request(lambda obj: obj == "A").then().increment_count() closure = lambda: thing.behaviors.test_request_behavior.run("A") t = Timer(0.5, closure) @@ -702,8 +630,7 @@ class CertSelfTest(BaseTestClass): def test_fluent_behavior__wait_until_done_anything(self): thing = ObjectWithBehaviors() - when(thing).test_request( - lambda obj: obj == "A").then().increment_count() + when(thing).test_request(lambda obj: obj == "A").then().increment_count() closure = lambda: thing.behaviors.test_request_behavior.run("A") t = Timer(0.5, closure) @@ -716,20 +643,16 @@ class CertSelfTest(BaseTestClass): def test_fluent_behavior__wait_until_done_not_happened(self): thing = ObjectWithBehaviors() thing.behaviors.test_request_behavior.set_default_to_ignore() - when(thing).test_request( - lambda obj: obj == "A").then().increment_count() + when(thing).test_request(lambda obj: obj == "A").then().increment_count() closure = lambda: thing.behaviors.test_request_behavior.run("B") t = Timer(0.5, closure) t.start() - assertThat( - wait_until(thing).test_request(lambda obj: obj == "A").times( - 1)).isFalse() + assertThat(wait_until(thing).test_request(lambda obj: obj == "A").times(1)).isFalse() def test_fluent_behavior__wait_until_done_with_default(self): thing = ObjectWithBehaviors() - thing.behaviors.test_request_behavior.set_default( - lambda obj: thing.increment_unhandled()) + thing.behaviors.test_request_behavior.set_default(lambda obj: thing.increment_unhandled()) closure = lambda: thing.behaviors.test_request_behavior.run("A") t = Timer(0.5, closure) @@ -740,8 +663,7 @@ class CertSelfTest(BaseTestClass): def test_fluent_behavior__wait_until_done_two_events_AA(self): thing = ObjectWithBehaviors() - when(thing).test_request( - lambda obj: obj == "A").then().increment_count().increment_count() + when(thing).test_request(lambda obj: obj == "A").then().increment_count().increment_count() closure1 = lambda: thing.behaviors.test_request_behavior.run("A") t1 = Timer(0.5, closure1) @@ -779,6 +701,4 @@ class CertSelfTest(BaseTestClass): closure2 = lambda: thing.behaviors.test_request_behavior.run("B") t2 = Timer(3, closure2) t2.start() - assertThat( - wait_until(thing).test_request(lambda obj: obj == "A").times( - 2)).isFalse() + assertThat(wait_until(thing).test_request(lambda obj: obj == "A").times(2)).isFalse() diff --git a/system/gd/cert/event_stream.py b/system/gd/cert/event_stream.py index 0c84172741..ac4172becf 100644 --- a/system/gd/cert/event_stream.py +++ b/system/gd/cert/event_stream.py @@ -43,9 +43,7 @@ class FilteringEventStream(IEventStream): self.event_queue = SimpleQueue() self.stream = stream - self.stream.register_callback( - self.__event_callback, - lambda packet: self.filter_fn(packet) is not None) + self.stream.register_callback(self.__event_callback, lambda packet: self.filter_fn(packet) is not None) def __event_callback(self, event): self.event_queue.put(self.filter_fn(event)) @@ -58,9 +56,7 @@ class FilteringEventStream(IEventStream): def pretty_print(proto_event): - return '{} {}'.format( - type(proto_event).__name__, - text_format.MessageToString(proto_event, as_one_line=True)) + return '{} {}'.format(type(proto_event).__name__, text_format.MessageToString(proto_event, as_one_line=True)) DEFAULT_TIMEOUT_SECONDS = 3 @@ -173,8 +169,7 @@ class EventStream(IEventStream, Closable): """ NOT_FOR_YOU_assert_none(self, timeout) - def assert_none_matching( - self, match_fn, timeout=timedelta(seconds=DEFAULT_TIMEOUT_SECONDS)): + def assert_none_matching(self, match_fn, timeout=timedelta(seconds=DEFAULT_TIMEOUT_SECONDS)): """ Assert no events where match_fn(event) is True happen within timeout period @@ -185,10 +180,7 @@ class EventStream(IEventStream, Closable): """ NOT_FOR_YOU_assert_none_matching(self, match_fn, timeout) - def assert_event_occurs(self, - match_fn, - at_least_times=1, - timeout=timedelta(seconds=DEFAULT_TIMEOUT_SECONDS)): + def assert_event_occurs(self, match_fn, at_least_times=1, timeout=timedelta(seconds=DEFAULT_TIMEOUT_SECONDS)): """ Assert at least |at_least_times| instances of events happen where match_fn(event) returns True within timeout period @@ -201,11 +193,7 @@ class EventStream(IEventStream, Closable): """ NOT_FOR_YOU_assert_event_occurs(self, match_fn, at_least_times, timeout) - def assert_event_occurs_at_most( - self, - match_fn, - at_most_times, - timeout=timedelta(seconds=DEFAULT_TIMEOUT_SECONDS)): + def assert_event_occurs_at_most(self, match_fn, at_most_times, timeout=timedelta(seconds=DEFAULT_TIMEOUT_SECONDS)): """ Assert at most |at_most_times| instances of events happen where match_fn(event) returns True within timeout period @@ -221,11 +209,9 @@ class EventStream(IEventStream, Closable): end_time = datetime.now() + timeout while len(event_list) <= at_most_times and datetime.now() < end_time: remaining = static_remaining_time_delta(end_time) - logging.debug("Waiting for event iteration (%fs remaining)" % - (remaining.total_seconds())) + logging.debug("Waiting for event iteration (%fs remaining)" % (remaining.total_seconds())) try: - current_event = self.event_queue.get( - timeout=remaining.total_seconds()) + current_event = self.event_queue.get(timeout=remaining.total_seconds()) if match_fn(current_event): event_list.append(current_event) except Empty: @@ -233,16 +219,10 @@ class EventStream(IEventStream, Closable): logging.debug("Done waiting, got %d events" % len(event_list)) asserts.assert_true( len(event_list) <= at_most_times, - msg=("Expected at most %d events, but got %d" % (at_most_times, - len(event_list)))) + msg=("Expected at most %d events, but got %d" % (at_most_times, len(event_list)))) - def assert_all_events_occur( - self, - match_fns, - order_matters, - timeout=timedelta(seconds=DEFAULT_TIMEOUT_SECONDS)): - NOT_FOR_YOU_assert_all_events_occur(self, match_fns, order_matters, - timeout) + def assert_all_events_occur(self, match_fns, order_matters, timeout=timedelta(seconds=DEFAULT_TIMEOUT_SECONDS)): + NOT_FOR_YOU_assert_all_events_occur(self, match_fns, order_matters, timeout) def static_remaining_time_delta(end_time): @@ -252,22 +232,18 @@ def static_remaining_time_delta(end_time): return remaining -def NOT_FOR_YOU_assert_event_occurs( - istream, - match_fn, - at_least_times=1, - timeout=timedelta(seconds=DEFAULT_TIMEOUT_SECONDS)): - logging.debug("assert_event_occurs %d %fs" % (at_least_times, - timeout.total_seconds())) +def NOT_FOR_YOU_assert_event_occurs(istream, + match_fn, + at_least_times=1, + timeout=timedelta(seconds=DEFAULT_TIMEOUT_SECONDS)): + logging.debug("assert_event_occurs %d %fs" % (at_least_times, timeout.total_seconds())) event_list = [] end_time = datetime.now() + timeout while len(event_list) < at_least_times and datetime.now() < end_time: remaining = static_remaining_time_delta(end_time) - logging.debug( - "Waiting for event (%fs remaining)" % (remaining.total_seconds())) + logging.debug("Waiting for event (%fs remaining)" % (remaining.total_seconds())) try: - current_event = istream.get_event_queue().get( - timeout=remaining.total_seconds()) + current_event = istream.get_event_queue().get(timeout=remaining.total_seconds()) logging.debug("current_event: %s", current_event) if match_fn(current_event): event_list.append(current_event) @@ -276,26 +252,22 @@ def NOT_FOR_YOU_assert_event_occurs( logging.debug("Done waiting for event, received %d", len(event_list)) asserts.assert_true( len(event_list) >= at_least_times, - msg=("Expected at least %d events, but got %d" % (at_least_times, - len(event_list)))) + msg=("Expected at least %d events, but got %d" % (at_least_times, len(event_list)))) -def NOT_FOR_YOU_assert_all_events_occur( - istream, - match_fns, - order_matters, - timeout=timedelta(seconds=DEFAULT_TIMEOUT_SECONDS)): +def NOT_FOR_YOU_assert_all_events_occur(istream, + match_fns, + order_matters, + timeout=timedelta(seconds=DEFAULT_TIMEOUT_SECONDS)): logging.debug("assert_all_events_occur %fs" % timeout.total_seconds()) pending_matches = list(match_fns) matched_order = [] end_time = datetime.now() + timeout while len(pending_matches) > 0 and datetime.now() < end_time: remaining = static_remaining_time_delta(end_time) - logging.debug( - "Waiting for event (%fs remaining)" % (remaining.total_seconds())) + logging.debug("Waiting for event (%fs remaining)" % (remaining.total_seconds())) try: - current_event = istream.get_event_queue().get( - timeout=remaining.total_seconds()) + current_event = istream.get_event_queue().get(timeout=remaining.total_seconds()) for match_fn in pending_matches: if match_fn(current_event): pending_matches.remove(match_fn) @@ -305,8 +277,7 @@ def NOT_FOR_YOU_assert_all_events_occur( logging.debug("Done waiting for event") asserts.assert_true( len(matched_order) == len(match_fns), - msg=("Expected at least %d events, but got %d" % (len(match_fns), - len(matched_order)))) + msg=("Expected at least %d events, but got %d" % (len(match_fns), len(matched_order)))) if order_matters: correct_order = True i = 0 @@ -315,23 +286,18 @@ def NOT_FOR_YOU_assert_all_events_occur( correct_order = False break i += 1 - asserts.assert_true( - correct_order, "Events not received in correct order %s %s" % - (match_fns, matched_order)) + asserts.assert_true(correct_order, "Events not received in correct order %s %s" % (match_fns, matched_order)) -def NOT_FOR_YOU_assert_none_matching( - istream, match_fn, timeout=timedelta(seconds=DEFAULT_TIMEOUT_SECONDS)): +def NOT_FOR_YOU_assert_none_matching(istream, match_fn, timeout=timedelta(seconds=DEFAULT_TIMEOUT_SECONDS)): logging.debug("assert_none_matching %fs" % (timeout.total_seconds())) event = None end_time = datetime.now() + timeout while event is None and datetime.now() < end_time: remaining = static_remaining_time_delta(end_time) - logging.debug( - "Waiting for event (%fs remaining)" % (remaining.total_seconds())) + logging.debug("Waiting for event (%fs remaining)" % (remaining.total_seconds())) try: - current_event = istream.get_event_queue().get( - timeout=remaining.total_seconds()) + current_event = istream.get_event_queue().get(timeout=remaining.total_seconds()) if match_fn(current_event): event = current_event except Empty: @@ -339,18 +305,13 @@ def NOT_FOR_YOU_assert_none_matching( logging.debug("Done waiting for an event") if event is None: return # Avoid an assert in MessageToString(None, ...) - asserts.assert_true( - event is None, - msg='Expected None matching, but got {}'.format(pretty_print(event))) + asserts.assert_true(event is None, msg='Expected None matching, but got {}'.format(pretty_print(event))) -def NOT_FOR_YOU_assert_none(istream, - timeout=timedelta(seconds=DEFAULT_TIMEOUT_SECONDS)): +def NOT_FOR_YOU_assert_none(istream, timeout=timedelta(seconds=DEFAULT_TIMEOUT_SECONDS)): logging.debug("assert_none %fs" % (timeout.total_seconds())) try: event = istream.get_event_queue().get(timeout=timeout.total_seconds()) - asserts.assert_true( - event is None, - msg='Expected None, but got {}'.format(pretty_print(event))) + asserts.assert_true(event is None, msg='Expected None, but got {}'.format(pretty_print(event))) except Empty: return diff --git a/system/gd/cert/gd_base_test.py b/system/gd/cert/gd_base_test.py index 85d139dd77..2d571678d8 100644 --- a/system/gd/cert/gd_base_test.py +++ b/system/gd/cert/gd_base_test.py @@ -56,28 +56,22 @@ class GdBaseTestClass(BaseTestClass): self.rootcanal_running = True # Get root canal binary rootcanal = os.path.join(get_gd_root(), "root-canal") - asserts.assert_true( - os.path.isfile(rootcanal), - "Root canal does not exist at %s" % rootcanal) + asserts.assert_true(os.path.isfile(rootcanal), "Root canal does not exist at %s" % rootcanal) # Get root canal log - self.rootcanal_logpath = os.path.join(self.log_path_base, - 'rootcanal_logs.txt') + self.rootcanal_logpath = os.path.join(self.log_path_base, 'rootcanal_logs.txt') # Make sure ports are available rootcanal_config = self.controller_configs['rootcanal'] rootcanal_test_port = int(rootcanal_config.get("test_port", "6401")) rootcanal_hci_port = int(rootcanal_config.get("hci_port", "6402")) - rootcanal_link_layer_port = int( - rootcanal_config.get("link_layer_port", "6403")) + rootcanal_link_layer_port = int(rootcanal_config.get("link_layer_port", "6403")) asserts.assert_true( - make_ports_available((rootcanal_test_port, rootcanal_hci_port, - rootcanal_link_layer_port)), + make_ports_available((rootcanal_test_port, rootcanal_hci_port, rootcanal_link_layer_port)), "Failed to make root canal ports available") # Start root canal process rootcanal_cmd = [ - rootcanal, - str(rootcanal_test_port), + rootcanal, str(rootcanal_test_port), str(rootcanal_hci_port), str(rootcanal_link_layer_port) ] @@ -89,12 +83,9 @@ class GdBaseTestClass(BaseTestClass): stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True) + asserts.assert_true(self.rootcanal_process, msg="Cannot start root-canal at " + str(rootcanal)) asserts.assert_true( - self.rootcanal_process, - msg="Cannot start root-canal at " + str(rootcanal)) - asserts.assert_true( - is_subprocess_alive(self.rootcanal_process), - msg="root-canal stopped immediately after running") + is_subprocess_alive(self.rootcanal_process), msg="root-canal stopped immediately after running") self.rootcanal_logger = AsyncSubprocessLogger( self.rootcanal_process, [self.rootcanal_logpath], @@ -107,8 +98,7 @@ class GdBaseTestClass(BaseTestClass): gd_device_config["rootcanal_port"] = str(rootcanal_hci_port) # Parse and construct GD device objects - self.register_controller( - importlib.import_module('cert.gd_device'), builtin=True) + self.register_controller(importlib.import_module('cert.gd_device'), builtin=True) self.dut = self.gd_devices[1] self.cert = self.gd_devices[0] @@ -117,17 +107,13 @@ class GdBaseTestClass(BaseTestClass): stop_signal = signal.SIGINT self.rootcanal_process.send_signal(stop_signal) try: - return_code = self.rootcanal_process.wait( - timeout=self.SUBPROCESS_WAIT_TIMEOUT_SECONDS) + return_code = self.rootcanal_process.wait(timeout=self.SUBPROCESS_WAIT_TIMEOUT_SECONDS) except subprocess.TimeoutExpired: - logging.error( - "Failed to interrupt root canal via SIGINT, sending SIGKILL" - ) + logging.error("Failed to interrupt root canal via SIGINT, sending SIGKILL") stop_signal = signal.SIGKILL self.rootcanal_process.kill() try: - return_code = self.rootcanal_process.wait( - timeout=self.SUBPROCESS_WAIT_TIMEOUT_SECONDS) + return_code = self.rootcanal_process.wait(timeout=self.SUBPROCESS_WAIT_TIMEOUT_SECONDS) except subprocess.TimeoutExpired: logging.error("Failed to kill root canal") return_code = -65536 @@ -138,12 +124,10 @@ class GdBaseTestClass(BaseTestClass): def setup_test(self): self.dut.rootservice.StartStack( facade_rootservice.StartStackRequest( - module_under_test=facade_rootservice.BluetoothModule.Value( - self.dut_module),)) + module_under_test=facade_rootservice.BluetoothModule.Value(self.dut_module),)) self.cert.rootservice.StartStack( facade_rootservice.StartStackRequest( - module_under_test=facade_rootservice.BluetoothModule.Value( - self.cert_module),)) + module_under_test=facade_rootservice.BluetoothModule.Value(self.cert_module),)) self.dut.wait_channel_ready() self.cert.wait_channel_ready() @@ -162,22 +146,17 @@ class GdBaseTestClass(BaseTestClass): try: return attr(*args, **kwargs) except RpcError as e: - exception_info = "".join( - traceback.format_exception(e.__class__, e, e.__traceback__)) + exception_info = "".join(traceback.format_exception(e.__class__, e, e.__traceback__)) raise signals.TestFailure( - "RpcError during test\n\nRpcError:\n\n%s\n%s" % - (exception_info, self.__dump_crashes())) + "RpcError during test\n\nRpcError:\n\n%s\n%s" % (exception_info, self.__dump_crashes())) return __wrapped - __ENTRY_METHODS = { - "setup_class", "teardown_class", "setup_test", "teardown_test" - } + __ENTRY_METHODS = {"setup_class", "teardown_class", "setup_test", "teardown_test"} @staticmethod def __is_entry_function(name): - return name.startswith( - "test_") or name in GdBaseTestClass.__ENTRY_METHODS + return name.startswith("test_") or name in GdBaseTestClass.__ENTRY_METHODS def __dump_crashes(self): """ @@ -187,10 +166,8 @@ class GdBaseTestClass(BaseTestClass): cert_crash, cert_log_tail = self.cert.get_crash_snippet_and_log_tail() rootcanal_crash = None rootcanal_log_tail = None - if self.rootcanal_running and not is_subprocess_alive( - self.rootcanal_process): - rootcanal_crash, roocanal_log_tail = read_crash_snippet_and_log_tail( - self.rootcanal_logpath) + if self.rootcanal_running and not is_subprocess_alive(self.rootcanal_process): + rootcanal_crash, roocanal_log_tail = read_crash_snippet_and_log_tail(self.rootcanal_logpath) crash_detail = "" if dut_crash or cert_crash or rootcanal_crash: diff --git a/system/gd/cert/gd_device.py b/system/gd/cert/gd_device.py index 7ba452169c..c46ac80cd1 100644 --- a/system/gd/cert/gd_device.py +++ b/system/gd/cert/gd_device.py @@ -73,8 +73,7 @@ def destroy(devices): try: device.teardown() except: - logging.exception( - "[%s] Failed to clean up properly due to" % device.label) + logging.exception("[%s] Failed to clean up properly due to" % device.label) def get_info(devices): @@ -91,16 +90,13 @@ def get_instances_with_configs(configs): resolved_cmd.append(replace_vars(arg, config)) verbose_mode = bool(config.get('verbose_mode', False)) if config.get("serial_number"): - device = GdAndroidDevice( - config["grpc_port"], config["grpc_root_server_port"], - config["signal_port"], resolved_cmd, config["label"], - ACTS_CONTROLLER_CONFIG_NAME, config["name"], - config["serial_number"], verbose_mode) + device = GdAndroidDevice(config["grpc_port"], config["grpc_root_server_port"], config["signal_port"], + resolved_cmd, config["label"], ACTS_CONTROLLER_CONFIG_NAME, config["name"], + config["serial_number"], verbose_mode) else: - device = GdHostOnlyDevice( - config["grpc_port"], config["grpc_root_server_port"], - config["signal_port"], resolved_cmd, config["label"], - ACTS_CONTROLLER_CONFIG_NAME, config["name"], verbose_mode) + device = GdHostOnlyDevice(config["grpc_port"], config["grpc_root_server_port"], config["signal_port"], + resolved_cmd, config["label"], ACTS_CONTROLLER_CONFIG_NAME, config["name"], + verbose_mode) device.setup() devices.append(device) return devices @@ -137,8 +133,7 @@ class GdDeviceBase(ABC): WAIT_CHANNEL_READY_TIMEOUT_SECONDS = 10 - def __init__(self, grpc_port: str, grpc_root_server_port: str, - signal_port: str, cmd: List[str], label: str, + def __init__(self, grpc_port: str, grpc_root_server_port: str, signal_port: str, cmd: List[str], label: str, type_identifier: str, name: str, verbose_mode: bool): """Base GD device, common traits for both device based and host only GD cert tests @@ -152,16 +147,9 @@ class GdDeviceBase(ABC): """ # Must be at the first line of __init__ method values = locals() - arguments = [ - values[arg] - for arg in inspect.getfullargspec(GdDeviceBase.__init__).args - if arg != "verbose_mode" - ] - asserts.assert_true( - all(arguments), - "All arguments to GdDeviceBase must not be None nor empty") - asserts.assert_true( - all(cmd), "cmd list should not have None nor empty component") + arguments = [values[arg] for arg in inspect.getfullargspec(GdDeviceBase.__init__).args if arg != "verbose_mode"] + asserts.assert_true(all(arguments), "All arguments to GdDeviceBase must not be None nor empty") + asserts.assert_true(all(cmd), "cmd list should not have None nor empty component") self.verbose_mode = verbose_mode self.grpc_root_server_port = int(grpc_root_server_port) self.grpc_port = int(grpc_port) @@ -173,12 +161,10 @@ class GdDeviceBase(ABC): self.log_path_base = get_current_context().get_full_output_path() self.test_runner_base_path = \ get_current_context().get_base_output_path() - self.backing_process_log_path = os.path.join( - self.log_path_base, - '%s_%s_backing_logs.txt' % (self.type_identifier, self.label)) + self.backing_process_log_path = os.path.join(self.log_path_base, + '%s_%s_backing_logs.txt' % (self.type_identifier, self.label)) if "--btsnoop=" not in " ".join(cmd): - cmd.append("--btsnoop=%s" % os.path.join( - self.log_path_base, '%s_btsnoop_hci.log' % self.label)) + cmd.append("--btsnoop=%s" % os.path.join(self.log_path_base, '%s_btsnoop_hci.log' % self.label)) self.cmd = cmd self.environment = os.environ.copy() if "cert" in self.label: @@ -195,8 +181,7 @@ class GdDeviceBase(ABC): # Ensure signal port is available # signal port is the only port that always listen on the host machine asserts.assert_true( - make_ports_available([self.signal_port]), - "[%s] Failed to make signal port available" % self.label) + make_ports_available([self.signal_port]), "[%s] Failed to make signal port available" % self.label) # Start backing process with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as signal_socket: # Setup signaling socket @@ -213,13 +198,10 @@ class GdDeviceBase(ABC): stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True) - asserts.assert_true( - self.backing_process, - msg="Cannot start backing_process at " + " ".join(self.cmd)) + asserts.assert_true(self.backing_process, msg="Cannot start backing_process at " + " ".join(self.cmd)) asserts.assert_true( is_subprocess_alive(self.backing_process), - msg="backing_process stopped immediately after running " + - " ".join(self.cmd)) + msg="backing_process stopped immediately after running " + " ".join(self.cmd)) # Wait for process to be ready signal_socket.accept() @@ -231,40 +213,27 @@ class GdDeviceBase(ABC): color=self.terminal_color) # Setup gRPC management channels - self.grpc_root_server_channel = grpc.insecure_channel( - "localhost:%d" % self.grpc_root_server_port) - self.grpc_channel = grpc.insecure_channel( - "localhost:%d" % self.grpc_port) + self.grpc_root_server_channel = grpc.insecure_channel("localhost:%d" % self.grpc_root_server_port) + self.grpc_channel = grpc.insecure_channel("localhost:%d" % self.grpc_port) # Establish services from facades - self.rootservice = facade_rootservice_pb2_grpc.RootFacadeStub( - self.grpc_root_server_channel) + self.rootservice = facade_rootservice_pb2_grpc.RootFacadeStub(self.grpc_root_server_channel) self.hal = hal_facade_pb2_grpc.HciHalFacadeStub(self.grpc_channel) - self.controller_read_only_property = facade_rootservice_pb2_grpc.ReadOnlyPropertyStub( - self.grpc_channel) + self.controller_read_only_property = facade_rootservice_pb2_grpc.ReadOnlyPropertyStub(self.grpc_channel) self.hci = hci_facade_pb2_grpc.HciLayerFacadeStub(self.grpc_channel) - self.l2cap = l2cap_facade_pb2_grpc.L2capClassicModuleFacadeStub( - self.grpc_channel) - self.l2cap_le = l2cap_le_facade_pb2_grpc.L2capLeModuleFacadeStub( - self.grpc_channel) - self.hci_acl_manager = acl_manager_facade_pb2_grpc.AclManagerFacadeStub( - self.grpc_channel) - self.hci_le_acl_manager = le_acl_manager_facade_pb2_grpc.LeAclManagerFacadeStub( - self.grpc_channel) - self.hci_controller = controller_facade_pb2_grpc.ControllerFacadeStub( - self.grpc_channel) - self.hci_controller.GetMacAddressSimple = lambda: self.hci_controller.GetMacAddress( - empty_proto.Empty()).address - self.hci_controller.GetLocalNameSimple = lambda: self.hci_controller.GetLocalName( - empty_proto.Empty()).name + self.l2cap = l2cap_facade_pb2_grpc.L2capClassicModuleFacadeStub(self.grpc_channel) + self.l2cap_le = l2cap_le_facade_pb2_grpc.L2capLeModuleFacadeStub(self.grpc_channel) + self.hci_acl_manager = acl_manager_facade_pb2_grpc.AclManagerFacadeStub(self.grpc_channel) + self.hci_le_acl_manager = le_acl_manager_facade_pb2_grpc.LeAclManagerFacadeStub(self.grpc_channel) + self.hci_controller = controller_facade_pb2_grpc.ControllerFacadeStub(self.grpc_channel) + self.hci_controller.GetMacAddressSimple = lambda: self.hci_controller.GetMacAddress(empty_proto.Empty()).address + self.hci_controller.GetLocalNameSimple = lambda: self.hci_controller.GetLocalName(empty_proto.Empty()).name self.hci_le_advertising_manager = le_advertising_manager_facade_pb2_grpc.LeAdvertisingManagerFacadeStub( self.grpc_channel) self.hci_le_scanning_manager = le_scanning_manager_facade_pb2_grpc.LeScanningManagerFacadeStub( self.grpc_channel) - self.neighbor = neighbor_facade_pb2_grpc.NeighborFacadeStub( - self.grpc_channel) - self.security = security_facade_pb2_grpc.SecurityModuleFacadeStub( - self.grpc_channel) + self.neighbor = neighbor_facade_pb2_grpc.NeighborFacadeStub(self.grpc_channel) + self.security = security_facade_pb2_grpc.SecurityModuleFacadeStub(self.grpc_channel) def get_crash_snippet_and_log_tail(self): if is_subprocess_alive(self.backing_process): @@ -283,23 +252,18 @@ class GdDeviceBase(ABC): stop_signal = signal.SIGINT self.backing_process.send_signal(stop_signal) try: - return_code = self.backing_process.wait( - timeout=self.WAIT_CHANNEL_READY_TIMEOUT_SECONDS) + return_code = self.backing_process.wait(timeout=self.WAIT_CHANNEL_READY_TIMEOUT_SECONDS) except subprocess.TimeoutExpired: - logging.error( - "[%s] Failed to interrupt backing process via SIGINT, sending SIGKILL" - % self.label) + logging.error("[%s] Failed to interrupt backing process via SIGINT, sending SIGKILL" % self.label) stop_signal = signal.SIGKILL self.backing_process.kill() try: - return_code = self.backing_process.wait( - timeout=self.WAIT_CHANNEL_READY_TIMEOUT_SECONDS) + return_code = self.backing_process.wait(timeout=self.WAIT_CHANNEL_READY_TIMEOUT_SECONDS) except subprocess.TimeoutExpired: logging.error("Failed to kill backing process") return_code = -65536 if return_code not in [-stop_signal, 0]: - logging.error("backing process %s stopped with code: %d" % - (self.label, return_code)) + logging.error("backing process %s stopped with code: %d" % (self.label, return_code)) self.backing_process_logger.stop() def wait_channel_ready(self): @@ -315,17 +279,14 @@ class GdHostOnlyDevice(GdDeviceBase): Host only device where the backing process is running on the host machine """ - def __init__(self, grpc_port: str, grpc_root_server_port: str, - signal_port: str, cmd: List[str], label: str, + def __init__(self, grpc_port: str, grpc_root_server_port: str, signal_port: str, cmd: List[str], label: str, type_identifier: str, name: str, verbose_mode: bool): - super().__init__(grpc_port, grpc_root_server_port, signal_port, cmd, - label, ACTS_CONTROLLER_CONFIG_NAME, name, verbose_mode) + super().__init__(grpc_port, grpc_root_server_port, signal_port, cmd, label, ACTS_CONTROLLER_CONFIG_NAME, name, + verbose_mode) # Enable LLVM code coverage output for host only tests - self.backing_process_profraw_path = pathlib.Path( - self.log_path_base).joinpath("%s_%s_backing_coverage.profraw" % - (self.type_identifier, self.label)) - self.environment["LLVM_PROFILE_FILE"] = str( - self.backing_process_profraw_path) + self.backing_process_profraw_path = pathlib.Path(self.log_path_base).joinpath( + "%s_%s_backing_coverage.profraw" % (self.type_identifier, self.label)) + self.environment["LLVM_PROFILE_FILE"] = str(self.backing_process_profraw_path) def teardown(self): super().teardown() @@ -333,94 +294,66 @@ class GdHostOnlyDevice(GdDeviceBase): def generate_coverage_report(self): if not self.backing_process_profraw_path.is_file(): - logging.info( - "[%s] Skip coverage report as there is no profraw file at %s" % - (self.label, str(self.backing_process_profraw_path))) + logging.info("[%s] Skip coverage report as there is no profraw file at %s" % + (self.label, str(self.backing_process_profraw_path))) return try: if self.backing_process_profraw_path.stat().st_size <= 0: - logging.info( - "[%s] Skip coverage report as profraw file is empty at %s" % - (self.label, str(self.backing_process_profraw_path))) + logging.info("[%s] Skip coverage report as profraw file is empty at %s" % + (self.label, str(self.backing_process_profraw_path))) return except OSError: - logging.info( - "[%s] Skip coverage report as profraw file is inaccessible at %s" - % (self.label, str(self.backing_process_profraw_path))) + logging.info("[%s] Skip coverage report as profraw file is inaccessible at %s" % + (self.label, str(self.backing_process_profraw_path))) return - llvm_binutils = pathlib.Path( - get_gd_root()).joinpath("llvm_binutils").joinpath("bin") + llvm_binutils = pathlib.Path(get_gd_root()).joinpath("llvm_binutils").joinpath("bin") llvm_profdata = llvm_binutils.joinpath("llvm-profdata") if not llvm_profdata.is_file(): logging.info( - "[%s] Skip coverage report as llvm-profdata is not found at %s" - % (self.label, str(llvm_profdata))) + "[%s] Skip coverage report as llvm-profdata is not found at %s" % (self.label, str(llvm_profdata))) return llvm_cov = llvm_binutils.joinpath("llvm-cov") if not llvm_cov.is_file(): - logging.info( - "[%s] Skip coverage report as llvm-cov is not found at %s" % - (self.label, str(llvm_cov))) + logging.info("[%s] Skip coverage report as llvm-cov is not found at %s" % (self.label, str(llvm_cov))) return logging.info("[%s] Generating coverage report" % self.label) profdata_path = pathlib.Path(self.test_runner_base_path).joinpath( - "%s_%s_backing_process_coverage.profdata" % (self.type_identifier, - self.label)) + "%s_%s_backing_process_coverage.profdata" % (self.type_identifier, self.label)) profdata_path_tmp = pathlib.Path(self.test_runner_base_path).joinpath( - "%s_%s_backing_process_coverage_tmp.profdata" % - (self.type_identifier, self.label)) + "%s_%s_backing_process_coverage_tmp.profdata" % (self.type_identifier, self.label)) # Merge with existing profdata if possible - profdata_cmd = [ - str(llvm_profdata), "merge", "-sparse", - str(self.backing_process_profraw_path) - ] + profdata_cmd = [str(llvm_profdata), "merge", "-sparse", str(self.backing_process_profraw_path)] if profdata_path.is_file(): profdata_cmd.append(str(profdata_path)) profdata_cmd += ["-o", str(profdata_path_tmp)] - result = subprocess.run( - profdata_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + result = subprocess.run(profdata_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) if result.returncode != 0: - logging.warning("[%s] Failed to index profdata, cmd result: %r" % - (self.label, result)) + logging.warning("[%s] Failed to index profdata, cmd result: %r" % (self.label, result)) profdata_path.unlink(missing_ok=True) return shutil.move(profdata_path_tmp, profdata_path) - coverage_result_path = pathlib.Path( - self.test_runner_base_path).joinpath( - "%s_%s_backing_process_coverage.json" % (self.type_identifier, - self.label)) + coverage_result_path = pathlib.Path(self.test_runner_base_path).joinpath( + "%s_%s_backing_process_coverage.json" % (self.type_identifier, self.label)) with coverage_result_path.open("w") as coverage_result_file: result = subprocess.run( - [ - str(llvm_cov), "export", "--format=text", "--instr-profile", - profdata_path, self.cmd[0] - ], + [str(llvm_cov), "export", "--format=text", "--instr-profile", profdata_path, self.cmd[0]], stderr=subprocess.PIPE, stdout=coverage_result_file, cwd=os.path.join(get_gd_root())) if result.returncode != 0: - logging.warning( - "[%s] Failed to generated coverage report, cmd result: %r" % - (self.label, result)) + logging.warning("[%s] Failed to generated coverage report, cmd result: %r" % (self.label, result)) coverage_result_path.unlink(missing_ok=True) return - coverage_summary_path = pathlib.Path( - self.test_runner_base_path).joinpath( - "%s_%s_backing_process_coverage_summary.txt" % - (self.type_identifier, self.label)) + coverage_summary_path = pathlib.Path(self.test_runner_base_path).joinpath( + "%s_%s_backing_process_coverage_summary.txt" % (self.type_identifier, self.label)) with coverage_summary_path.open("w") as coverage_summary_file: result = subprocess.run( - [ - llvm_cov, "report", "--instr-profile", profdata_path, - self.cmd[0] - ], + [llvm_cov, "report", "--instr-profile", profdata_path, self.cmd[0]], stderr=subprocess.PIPE, stdout=coverage_summary_file, cwd=os.path.join(get_gd_root())) if result.returncode != 0: - logging.warning( - "[%s] Failed to generated coverage summary, cmd result: %r" % - (self.label, result)) + logging.warning("[%s] Failed to generated coverage summary, cmd result: %r" % (self.label, result)) coverage_summary_path.unlink(missing_ok=True) def setup(self): @@ -440,22 +373,16 @@ class GdAndroidDevice(GdDeviceBase): WAIT_FOR_DEVICE_TIMEOUT_SECONDS = 180 - def __init__(self, grpc_port: str, grpc_root_server_port: str, - signal_port: str, cmd: List[str], label: str, - type_identifier: str, name: str, serial_number: str, - verbose_mode: bool): - super().__init__(grpc_port, grpc_root_server_port, signal_port, cmd, - label, type_identifier, name, verbose_mode) - asserts.assert_true(serial_number, - "serial_number must not be None nor empty") + def __init__(self, grpc_port: str, grpc_root_server_port: str, signal_port: str, cmd: List[str], label: str, + type_identifier: str, name: str, serial_number: str, verbose_mode: bool): + super().__init__(grpc_port, grpc_root_server_port, signal_port, cmd, label, type_identifier, name, verbose_mode) + asserts.assert_true(serial_number, "serial_number must not be None nor empty") self.serial_number = serial_number self.adb = AdbProxy(serial_number) def setup(self): - logging.info( - "Setting up device %s %s" % (self.label, self.serial_number)) - asserts.assert_true(self.adb.ensure_root(), - "device %s cannot run as root", self.serial_number) + logging.info("Setting up device %s %s" % (self.label, self.serial_number)) + asserts.assert_true(self.adb.ensure_root(), "device %s cannot run as root", self.serial_number) self.ensure_verity_disabled() # Try freeing ports and ignore results @@ -464,44 +391,27 @@ class GdAndroidDevice(GdDeviceBase): # Set up port forwarding or reverse or die self.tcp_forward_or_die(self.grpc_port, self.grpc_port) - self.tcp_forward_or_die(self.grpc_root_server_port, - self.grpc_root_server_port) + self.tcp_forward_or_die(self.grpc_root_server_port, self.grpc_root_server_port) self.tcp_reverse_or_die(self.signal_port, self.signal_port) # Push test binaries - self.push_or_die( - os.path.join(get_gd_root(), "target", - "bluetooth_stack_with_facade"), "system/bin") - self.push_or_die( - os.path.join(get_gd_root(), "target", "libbluetooth_gd.so"), - "system/lib64") - self.push_or_die( - os.path.join(get_gd_root(), "target", "libgrpc++_unsecure.so"), - "system/lib64") + self.push_or_die(os.path.join(get_gd_root(), "target", "bluetooth_stack_with_facade"), "system/bin") + self.push_or_die(os.path.join(get_gd_root(), "target", "libbluetooth_gd.so"), "system/lib64") + self.push_or_die(os.path.join(get_gd_root(), "target", "libgrpc++_unsecure.so"), "system/lib64") self.adb.shell("rm /data/misc/bluetooth/logs/btsnoop_hci.log") self.ensure_no_output(self.adb.shell("svc bluetooth disable")) # Start logcat logging self.logcat_output_path = os.path.join( - self.log_path_base, '%s_%s_%s_logcat_logs.txt' % - (self.type_identifier, self.label, self.serial_number)) - self.logcat_cmd = [ - "adb", "-s", self.serial_number, "logcat", "-T", "1", "-v", "year", - "-v", "uid" - ] + self.log_path_base, '%s_%s_%s_logcat_logs.txt' % (self.type_identifier, self.label, self.serial_number)) + self.logcat_cmd = ["adb", "-s", self.serial_number, "logcat", "-T", "1", "-v", "year", "-v", "uid"] logging.debug("Running %s", " ".join(self.logcat_cmd)) self.logcat_process = subprocess.Popen( - self.logcat_cmd, - stdout=subprocess.PIPE, - stderr=subprocess.STDOUT, - universal_newlines=True) - asserts.assert_true( - self.logcat_process, - msg="Cannot start logcat_process at " + " ".join(self.logcat_cmd)) + self.logcat_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True) + asserts.assert_true(self.logcat_process, msg="Cannot start logcat_process at " + " ".join(self.logcat_cmd)) asserts.assert_true( is_subprocess_alive(self.logcat_process), - msg="logcat_process stopped immediately after running " + " ".join( - self.logcat_cmd)) + msg="logcat_process stopped immediately after running " + " ".join(self.logcat_cmd)) self.logcat_logger = AsyncSubprocessLogger( self.logcat_process, [self.logcat_output_path], log_to_stdout=self.verbose_mode, @@ -509,8 +419,7 @@ class GdAndroidDevice(GdDeviceBase): color=self.terminal_color) # Done run parent setup - logging.info("Done preparation for %s, starting backing process" % - self.serial_number) + logging.info("Done preparation for %s, starting backing process" % self.serial_number) super().setup() def teardown(self): @@ -518,29 +427,23 @@ class GdAndroidDevice(GdDeviceBase): stop_signal = signal.SIGINT self.logcat_process.send_signal(stop_signal) try: - return_code = self.logcat_process.wait( - timeout=self.WAIT_CHANNEL_READY_TIMEOUT_SECONDS) + return_code = self.logcat_process.wait(timeout=self.WAIT_CHANNEL_READY_TIMEOUT_SECONDS) except subprocess.TimeoutExpired: - logging.error( - "[%s_%s] Failed to interrupt logcat process via SIGINT, sending SIGKILL" - % (self.label, self.serial_number)) + logging.error("[%s_%s] Failed to interrupt logcat process via SIGINT, sending SIGKILL" % + (self.label, self.serial_number)) stop_signal = signal.SIGKILL self.logcat_process.kill() try: - return_code = self.logcat_process.wait( - timeout=self.WAIT_CHANNEL_READY_TIMEOUT_SECONDS) + return_code = self.logcat_process.wait(timeout=self.WAIT_CHANNEL_READY_TIMEOUT_SECONDS) except subprocess.TimeoutExpired: - logging.error("Failed to kill logcat_process %s %s" % - (self.label, self.serial_number)) + logging.error("Failed to kill logcat_process %s %s" % (self.label, self.serial_number)) return_code = -65536 if return_code not in [-stop_signal, 0]: - logging.error("logcat_process %s_%s stopped with code: %d" % - (self.label, self.serial_number, return_code)) + logging.error("logcat_process %s_%s stopped with code: %d" % (self.label, self.serial_number, return_code)) self.logcat_logger.stop() self.cleanup_port_forwarding() - self.adb.pull( - "/data/misc/bluetooth/logs/btsnoop_hci.log %s" % os.path.join( - self.log_path_base, "%s_btsnoop_hci.log" % self.label)) + self.adb.pull("/data/misc/bluetooth/logs/btsnoop_hci.log %s" % os.path.join(self.log_path_base, + "%s_btsnoop_hci.log" % self.label)) def cleanup_port_forwarding(self): self.adb.remove_tcp_forward(self.grpc_port) @@ -553,35 +456,30 @@ class GdAndroidDevice(GdDeviceBase): Ensure a command has not output """ asserts.assert_true( - result is None or len(result) == 0, - msg="command returned something when it shouldn't: %s" % result) + result is None or len(result) == 0, msg="command returned something when it shouldn't: %s" % result) def sync_device_time(self): self.adb.shell("settings put global auto_time 0") self.adb.shell("settings put global auto_time_zone 0") device_tz = self.adb.shell("date +%z") - asserts.assert_true( - device_tz, "date +%z must return device timezone, " - "but returned {} instead".format(device_tz)) + asserts.assert_true(device_tz, "date +%z must return device timezone, " + "but returned {} instead".format(device_tz)) host_tz = time.strftime("%z") if device_tz != host_tz: target_timezone = utils.get_timezone_olson_id() logging.debug("Device timezone %s does not match host timezone %s, " - "syncing them by setting timezone to %s" % - (device_tz, host_tz, target_timezone)) + "syncing them by setting timezone to %s" % (device_tz, host_tz, target_timezone)) self.adb.shell("setprop persist.sys.timezone %s" % target_timezone) self.reboot() device_tz = self.adb.shell("date +%z") asserts.assert_equal( - host_tz, device_tz, - "Device timezone %s still does not match host " + host_tz, device_tz, "Device timezone %s still does not match host " "timezone %s after reset" % (device_tz, host_tz)) self.adb.shell("date %s" % time.strftime("%m%d%H%M%Y.%S")) datetime_format = "%Y-%m-%dZ%H:%M:%S%z" host_time = datetime.today() try: - device_time = datetime.strptime( - self.adb.shell("date +'%s'" % datetime_format), datetime_format) + device_time = datetime.strptime(self.adb.shell("date +'%s'" % datetime_format), datetime_format) except ValueError: asserts.fail("Failed to get time after sync") return @@ -590,8 +488,7 @@ class GdAndroidDevice(GdDeviceBase): (device_time - host_time).total_seconds(), 0, msg="Device time %s and host time %s off by >%dms after sync" % - (device_time.isoformat, host_time.isoformat(), - int(max_delta_seconds * 1000)), + (device_time.isoformat, host_time.isoformat(), int(max_delta_seconds * 1000)), delta=max_delta_seconds) def push_or_die(self, src_file_path, dst_file_path, push_timeout=300): @@ -603,16 +500,11 @@ class GdAndroidDevice(GdDeviceBase): push_timeout: How long to wait for the push to finish in seconds """ try: - out = self.adb.push( - '%s %s' % (src_file_path, dst_file_path), timeout=push_timeout) + out = self.adb.push('%s %s' % (src_file_path, dst_file_path), timeout=push_timeout) if 'error' in out: - asserts.fail('Unable to push file %s to %s due to %s' % - (src_file_path, dst_file_path, out)) + asserts.fail('Unable to push file %s to %s due to %s' % (src_file_path, dst_file_path, out)) except Exception as e: - asserts.fail( - msg='Unable to push file %s to %s due to %s' % - (src_file_path, dst_file_path, e), - extras=e) + asserts.fail(msg='Unable to push file %s to %s due to %s' % (src_file_path, dst_file_path, e), extras=e) def tcp_forward_or_die(self, host_port, device_port, num_retry=1): """ @@ -630,15 +522,13 @@ class GdAndroidDevice(GdDeviceBase): if num_retry > 0: # If requested, reboot an retry num_retry -= 1 - logging.warning("[%s] Failed to TCP forward host port %d to " - "device port %d, num_retries left is %d" % - (self.label, host_port, device_port, num_retry)) + logging.warning( + "[%s] Failed to TCP forward host port %d to " + "device port %d, num_retries left is %d" % (self.label, host_port, device_port, num_retry)) self.reboot() - return self.tcp_forward_or_die( - host_port, device_port, num_retry=num_retry) + return self.tcp_forward_or_die(host_port, device_port, num_retry=num_retry) asserts.fail( - 'Unable to forward host port %d to device port %d, error %s' % - (host_port, device_port, error_or_port)) + 'Unable to forward host port %d to device port %d, error %s' % (host_port, device_port, error_or_port)) return error_or_port def tcp_reverse_or_die(self, device_port, host_port, num_retry=1): @@ -649,8 +539,7 @@ class GdAndroidDevice(GdDeviceBase): :param num_retry: number of times to reboot and retry this before dying :return: device port int """ - error_or_port = self.adb.reverse( - "tcp:%d tcp:%d" % (device_port, host_port)) + error_or_port = self.adb.reverse("tcp:%d tcp:%d" % (device_port, host_port)) if not error_or_port: logging.debug("device port %d was already reversed" % device_port) return device_port @@ -660,15 +549,13 @@ class GdAndroidDevice(GdDeviceBase): if num_retry > 0: # If requested, reboot an retry num_retry -= 1 - logging.warning("[%s] Failed to TCP reverse device port %d to " - "host port %d, num_retries left is %d" % - (self.label, device_port, host_port, num_retry)) + logging.warning( + "[%s] Failed to TCP reverse device port %d to " + "host port %d, num_retries left is %d" % (self.label, device_port, host_port, num_retry)) self.reboot() - return self.tcp_reverse_or_die( - device_port, host_port, num_retry=num_retry) + return self.tcp_reverse_or_die(device_port, host_port, num_retry=num_retry) asserts.fail( - 'Unable to reverse device port %d to host port %d, error %s' % - (device_port, host_port, error_or_port)) + 'Unable to reverse device port %d to host port %d, error %s' % (device_port, host_port, error_or_port)) return error_or_port def ensure_verity_disabled(self): @@ -712,9 +599,7 @@ class GdAndroidDevice(GdDeviceBase): break minutes_left = timeout_minutes - (time.time() - timeout_start) / 60.0 self.wait_for_boot_completion(timeout_minutes=minutes_left) - asserts.assert_true(self.adb.ensure_root(), - "device %s cannot run as root after reboot", - self.serial_number) + asserts.assert_true(self.adb.ensure_root(), "device %s cannot run as root after reboot", self.serial_number) def wait_for_boot_completion(self, timeout_minutes=15.0): """ @@ -735,5 +620,4 @@ class GdAndroidDevice(GdDeviceBase): # process, which is normal. Ignoring these errors. pass time.sleep(5) - asserts.fail(msg='Device %s booting process timed out.' % - self.serial_number) + asserts.fail(msg='Device %s booting process timed out.' % self.serial_number) diff --git a/system/gd/cert/matchers.py b/system/gd/cert/matchers.py index 72244f5e15..d8587a8547 100644 --- a/system/gd/cert/matchers.py +++ b/system/gd/cert/matchers.py @@ -32,10 +32,8 @@ class HciMatchers(object): return lambda msg: HciMatchers._is_matching_command_complete(msg.event, opcode, num_complete) @staticmethod - def _is_matching_command_complete(packet_bytes, opcode=None, - num_complete=1): - hci_event = HciMatchers.extract_hci_event_with_code( - packet_bytes, EventCode.COMMAND_COMPLETE) + def _is_matching_command_complete(packet_bytes, opcode=None, num_complete=1): + hci_event = HciMatchers.extract_hci_event_with_code(packet_bytes, EventCode.COMMAND_COMPLETE) if hci_event is None: return False frame = hci_packets.CommandCompleteView(hci_event) @@ -48,8 +46,7 @@ class HciMatchers(object): @staticmethod def extract_hci_event_with_code(packet_bytes, event_code=None): - hci_event = hci_packets.EventPacketView( - bt_packets.PacketViewLittleEndian(list(packet_bytes))) + hci_event = hci_packets.EventPacketView(bt_packets.PacketViewLittleEndian(list(packet_bytes))) if hci_event is None: return None if event_code is not None and hci_event.GetEventCode() != event_code: @@ -101,8 +98,7 @@ class NeighborMatchers(object): @staticmethod def _is_matching_inquiry_result(packet, address): - hci_event = HciMatchers.extract_hci_event_with_code( - packet, EventCode.INQUIRY_RESULT) + hci_event = HciMatchers.extract_hci_event_with_code(packet, EventCode.INQUIRY_RESULT) if hci_event is None: return False inquiry_view = hci_packets.InquiryResultView(hci_event) @@ -117,8 +113,7 @@ class NeighborMatchers(object): @staticmethod def _is_matching_inquiry_result_with_rssi(packet, address): - hci_event = HciMatchers.extract_hci_event_with_code( - packet, EventCode.INQUIRY_RESULT_WITH_RSSI) + hci_event = HciMatchers.extract_hci_event_with_code(packet, EventCode.INQUIRY_RESULT_WITH_RSSI) if hci_event is None: return False inquiry_view = hci_packets.InquiryResultWithRssiView(hci_event) @@ -133,8 +128,7 @@ class NeighborMatchers(object): @staticmethod def _is_matching_extended_inquiry_result(packet, address): - hci_event = HciMatchers.extract_hci_event_with_code( - packet, EventCode.EXTENDED_INQUIRY_RESULT) + hci_event = HciMatchers.extract_hci_event_with_code(packet, EventCode.EXTENDED_INQUIRY_RESULT) if hci_event is None: return False extended_view = hci_packets.ExtendedInquiryResultView(hci_event) @@ -191,12 +185,11 @@ class L2capMatchers(object): @staticmethod def LeConnectionParameterUpdateRequest(): - return lambda packet: L2capMatchers._is_le_control_frame_with_code(packet, LeCommandCode.CONNECTION_PARAMETER_UPDATE_REQUEST) + return lambda packet: L2capMatchers._is_le_control_frame_with_code( + packet, LeCommandCode.CONNECTION_PARAMETER_UPDATE_REQUEST) @staticmethod - def LeConnectionParameterUpdateResponse( - result=l2cap_packets.ConnectionParameterUpdateResponseResult. - ACCEPTED): + def LeConnectionParameterUpdateResponse(result=l2cap_packets.ConnectionParameterUpdateResponseResult.ACCEPTED): return lambda packet: L2capMatchers._is_matching_connection_parameter_update_response(packet, result) @staticmethod @@ -204,13 +197,14 @@ class L2capMatchers(object): return lambda packet: L2capMatchers._is_matching_credit_based_connection_request(packet, psm) @staticmethod - def CreditBasedConnectionResponse( - result=LeCreditBasedConnectionResponseResult.SUCCESS): + def CreditBasedConnectionResponse(result=LeCreditBasedConnectionResponseResult.SUCCESS): return lambda packet: L2capMatchers._is_matching_credit_based_connection_response(packet, result) @staticmethod def CreditBasedConnectionResponseUsedCid(): - return lambda packet: L2capMatchers._is_matching_credit_based_connection_response(packet, LeCreditBasedConnectionResponseResult.SOURCE_CID_ALREADY_ALLOCATED) or L2capMatchers._is_le_control_frame_with_code(packet, LeCommandCode.COMMAND_REJECT) + return lambda packet: L2capMatchers._is_matching_credit_based_connection_response( + packet, LeCreditBasedConnectionResponseResult.SOURCE_CID_ALREADY_ALLOCATED + ) or L2capMatchers._is_le_control_frame_with_code(packet, LeCommandCode.COMMAND_REJECT) @staticmethod def LeDisconnectionRequest(scid, dcid): @@ -285,21 +279,20 @@ class L2capMatchers(object): supports_streaming=None, supports_fcs=None, supports_fixed_channels=None): - return lambda packet: L2capMatchers._is_matching_information_response_extended_features(packet, supports_ertm, supports_streaming, supports_fcs, supports_fixed_channels) + return lambda packet: L2capMatchers._is_matching_information_response_extended_features( + packet, supports_ertm, supports_streaming, supports_fcs, supports_fixed_channels) @staticmethod def _basic_frame(packet): if packet is None: return None - return l2cap_packets.BasicFrameView( - bt_packets.PacketViewLittleEndian(list(packet.payload))) + return l2cap_packets.BasicFrameView(bt_packets.PacketViewLittleEndian(list(packet.payload))) @staticmethod def _basic_frame_with_fcs(packet): if packet is None: return None - return l2cap_packets.BasicFrameWithFcsView( - bt_packets.PacketViewLittleEndian(list(packet.payload))) + return l2cap_packets.BasicFrameWithFcsView(bt_packets.PacketViewLittleEndian(list(packet.payload))) @staticmethod def _basic_frame_for(packet, scid): @@ -346,8 +339,7 @@ class L2capMatchers(object): start_frame = L2capMatchers._information_frame_with_fcs(packet) if start_frame is None: return None - return l2cap_packets.EnhancedInformationStartFrameWithFcsView( - start_frame) + return l2cap_packets.EnhancedInformationStartFrameWithFcsView(start_frame) @staticmethod def _supervisory_frame(packet): @@ -373,11 +365,7 @@ class L2capMatchers(object): return True @staticmethod - def _is_matching_information_start_frame(packet, - tx_seq, - payload, - f, - fcs=False): + def _is_matching_information_start_frame(packet, tx_seq, payload, f, fcs=False): if fcs: frame = L2capMatchers._information_start_frame_with_fcs(packet) else: @@ -410,8 +398,7 @@ class L2capMatchers(object): @staticmethod def _is_matching_first_le_i_frame(packet, payload, sdu_size): first_le_i_frame = l2cap_packets.FirstLeInformationFrameView(packet) - return first_le_i_frame.GetPayload().GetBytes( - ) == payload and first_le_i_frame.GetL2capSduLength() == sdu_size + return first_le_i_frame.GetPayload().GetBytes() == payload and first_le_i_frame.GetL2capSduLength() == sdu_size @staticmethod def _control_frame(packet): @@ -445,13 +432,11 @@ class L2capMatchers(object): @staticmethod def _is_le_control_frame_with_code(packet, code): - return L2capMatchers.le_control_frame_with_code(packet, - code) is not None + return L2capMatchers.le_control_frame_with_code(packet, code) is not None @staticmethod def _is_matching_connection_request(packet, psm): - frame = L2capMatchers.control_frame_with_code( - packet, CommandCode.CONNECTION_REQUEST) + frame = L2capMatchers.control_frame_with_code(packet, CommandCode.CONNECTION_REQUEST) if frame is None: return False request = l2cap_packets.ConnectionRequestView(frame) @@ -459,19 +444,16 @@ class L2capMatchers(object): @staticmethod def _is_matching_connection_response(packet, scid): - frame = L2capMatchers.control_frame_with_code( - packet, CommandCode.CONNECTION_RESPONSE) + frame = L2capMatchers.control_frame_with_code(packet, CommandCode.CONNECTION_RESPONSE) if frame is None: return False response = l2cap_packets.ConnectionResponseView(frame) return response.GetSourceCid() == scid and response.GetResult( - ) == ConnectionResponseResult.SUCCESS and response.GetDestinationCid( - ) != 0 + ) == ConnectionResponseResult.SUCCESS and response.GetDestinationCid() != 0 @staticmethod def _is_matching_configuration_request_with_cid(packet, cid=None): - frame = L2capMatchers.control_frame_with_code( - packet, CommandCode.CONFIGURATION_REQUEST) + frame = L2capMatchers.control_frame_with_code(packet, CommandCode.CONFIGURATION_REQUEST) if frame is None: return False request = l2cap_packets.ConfigurationRequestView(frame) @@ -480,8 +462,7 @@ class L2capMatchers(object): @staticmethod def _is_matching_configuration_request_with_ertm(packet): - frame = L2capMatchers.control_frame_with_code( - packet, CommandCode.CONFIGURATION_REQUEST) + frame = L2capMatchers.control_frame_with_code(packet, CommandCode.CONFIGURATION_REQUEST) if frame is None: return False request = l2cap_packets.ConfigurationRequestView(frame) @@ -490,10 +471,8 @@ class L2capMatchers(object): return b"\x04\x09\x03" in config_bytes @staticmethod - def _is_matching_configuration_response( - packet, result=ConfigurationResponseResult.SUCCESS): - frame = L2capMatchers.control_frame_with_code( - packet, CommandCode.CONFIGURATION_RESPONSE) + def _is_matching_configuration_response(packet, result=ConfigurationResponseResult.SUCCESS): + frame = L2capMatchers.control_frame_with_code(packet, CommandCode.CONFIGURATION_RESPONSE) if frame is None: return False response = l2cap_packets.ConfigurationResponseView(frame) @@ -501,48 +480,39 @@ class L2capMatchers(object): @staticmethod def _is_matching_disconnection_request(packet, scid, dcid): - frame = L2capMatchers.control_frame_with_code( - packet, CommandCode.DISCONNECTION_REQUEST) + frame = L2capMatchers.control_frame_with_code(packet, CommandCode.DISCONNECTION_REQUEST) if frame is None: return False request = l2cap_packets.DisconnectionRequestView(frame) - return request.GetSourceCid() == scid and request.GetDestinationCid( - ) == dcid + return request.GetSourceCid() == scid and request.GetDestinationCid() == dcid @staticmethod def _is_matching_disconnection_response(packet, scid, dcid): - frame = L2capMatchers.control_frame_with_code( - packet, CommandCode.DISCONNECTION_RESPONSE) + frame = L2capMatchers.control_frame_with_code(packet, CommandCode.DISCONNECTION_RESPONSE) if frame is None: return False response = l2cap_packets.DisconnectionResponseView(frame) - return response.GetSourceCid() == scid and response.GetDestinationCid( - ) == dcid + return response.GetSourceCid() == scid and response.GetDestinationCid() == dcid @staticmethod def _is_matching_le_disconnection_response(packet, scid, dcid): - frame = L2capMatchers.le_control_frame_with_code( - packet, LeCommandCode.DISCONNECTION_RESPONSE) + frame = L2capMatchers.le_control_frame_with_code(packet, LeCommandCode.DISCONNECTION_RESPONSE) if frame is None: return False response = l2cap_packets.LeDisconnectionResponseView(frame) - return response.GetSourceCid() == scid and response.GetDestinationCid( - ) == dcid + return response.GetSourceCid() == scid and response.GetDestinationCid() == dcid @staticmethod def _is_matching_le_disconnection_request(packet, scid, dcid): - frame = L2capMatchers.le_control_frame_with_code( - packet, LeCommandCode.DISCONNECTION_REQUEST) + frame = L2capMatchers.le_control_frame_with_code(packet, LeCommandCode.DISCONNECTION_REQUEST) if frame is None: return False request = l2cap_packets.LeDisconnectionRequestView(frame) - return request.GetSourceCid() == scid and request.GetDestinationCid( - ) == dcid + return request.GetSourceCid() == scid and request.GetDestinationCid() == dcid @staticmethod def _is_matching_le_flow_control_credit(packet, cid): - frame = L2capMatchers.le_control_frame_with_code( - packet, LeCommandCode.LE_FLOW_CONTROL_CREDIT) + frame = L2capMatchers.le_control_frame_with_code(packet, LeCommandCode.LE_FLOW_CONTROL_CREDIT) if frame is None: return False request = l2cap_packets.LeFlowControlCreditView(frame) @@ -550,8 +520,7 @@ class L2capMatchers(object): @staticmethod def _information_request_with_type(packet, info_type): - frame = L2capMatchers.control_frame_with_code( - packet, CommandCode.INFORMATION_REQUEST) + frame = L2capMatchers.control_frame_with_code(packet, CommandCode.INFORMATION_REQUEST) if frame is None: return None request = l2cap_packets.InformationRequestView(frame) @@ -561,8 +530,7 @@ class L2capMatchers(object): @staticmethod def _information_response_with_type(packet, info_type): - frame = L2capMatchers.control_frame_with_code( - packet, CommandCode.INFORMATION_RESPONSE) + frame = L2capMatchers.control_frame_with_code(packet, CommandCode.INFORMATION_RESPONSE) if frame is None: return None response = l2cap_packets.InformationResponseView(frame) @@ -571,39 +539,33 @@ class L2capMatchers(object): return response @staticmethod - def _is_matching_information_response_extended_features( - packet, supports_ertm, supports_streaming, supports_fcs, - supports_fixed_channels): - frame = L2capMatchers._information_response_with_type( - packet, InformationRequestInfoType.EXTENDED_FEATURES_SUPPORTED) + def _is_matching_information_response_extended_features(packet, supports_ertm, supports_streaming, supports_fcs, + supports_fixed_channels): + frame = L2capMatchers._information_response_with_type(packet, + InformationRequestInfoType.EXTENDED_FEATURES_SUPPORTED) if frame is None: return False features = l2cap_packets.InformationResponseExtendedFeaturesView(frame) - if supports_ertm is not None and features.GetEnhancedRetransmissionMode( - ) != supports_ertm: + if supports_ertm is not None and features.GetEnhancedRetransmissionMode() != supports_ertm: return False if supports_streaming is not None and features.GetStreamingMode != supports_streaming: return False if supports_fcs is not None and features.GetFcsOption() != supports_fcs: return False - if supports_fixed_channels is not None and features.GetFixedChannels( - ) != supports_fixed_channels: + if supports_fixed_channels is not None and features.GetFixedChannels() != supports_fixed_channels: return False return True @staticmethod def _is_matching_connection_parameter_update_response(packet, result): - frame = L2capMatchers.le_control_frame_with_code( - packet, LeCommandCode.CONNECTION_PARAMETER_UPDATE_RESPONSE) + frame = L2capMatchers.le_control_frame_with_code(packet, LeCommandCode.CONNECTION_PARAMETER_UPDATE_RESPONSE) if frame is None: return False - return l2cap_packets.ConnectionParameterUpdateResponseView( - frame).GetResult() == result + return l2cap_packets.ConnectionParameterUpdateResponseView(frame).GetResult() == result @staticmethod def _is_matching_credit_based_connection_request(packet, psm): - frame = L2capMatchers.le_control_frame_with_code( - packet, LeCommandCode.LE_CREDIT_BASED_CONNECTION_REQUEST) + frame = L2capMatchers.le_control_frame_with_code(packet, LeCommandCode.LE_CREDIT_BASED_CONNECTION_REQUEST) if frame is None: return False request = l2cap_packets.LeCreditBasedConnectionRequestView(frame) @@ -611,11 +573,9 @@ class L2capMatchers(object): @staticmethod def _is_matching_credit_based_connection_response(packet, result): - frame = L2capMatchers.le_control_frame_with_code( - packet, LeCommandCode.LE_CREDIT_BASED_CONNECTION_RESPONSE) + frame = L2capMatchers.le_control_frame_with_code(packet, LeCommandCode.LE_CREDIT_BASED_CONNECTION_RESPONSE) if frame is None: return False response = l2cap_packets.LeCreditBasedConnectionResponseView(frame) - return response.GetResult() == result and ( - result != LeCreditBasedConnectionResponseResult.SUCCESS or - response.GetDestinationCid() != 0) + return response.GetResult() == result and (result != LeCreditBasedConnectionResponseResult.SUCCESS or + response.GetDestinationCid() != 0) diff --git a/system/gd/cert/metadata.py b/system/gd/cert/metadata.py index 437fb0fc2f..17579ae28f 100644 --- a/system/gd/cert/metadata.py +++ b/system/gd/cert/metadata.py @@ -57,8 +57,7 @@ def metadata(_do_not_use=None, pts_test_id=None, pts_test_name=None): if _do_not_use is not None: def fail(*args, **kwargs): - asserts.fail("@metadata must be used in functional form such " - "as @metadta(key=value)") + asserts.fail("@metadata must be used in functional form such " "as @metadta(key=value)") return fail @@ -74,7 +73,6 @@ def metadata(_do_not_use=None, pts_test_id=None, pts_test_name=None): # Validate pts_test_id and pts_test_name if any((pts_test_id, pts_test_name)) and \ not all((pts_test_id, pts_test_name)): - return _fail_decorator("pts_test_id and pts_test_name must both " - "be valid if one of them is valid") + return _fail_decorator("pts_test_id and pts_test_name must both " "be valid if one of them is valid") return test_info(**args) diff --git a/system/gd/cert/os_utils.py b/system/gd/cert/os_utils.py index 6cdd9a0989..6ee9c0b30c 100644 --- a/system/gd/cert/os_utils.py +++ b/system/gd/cert/os_utils.py @@ -73,23 +73,18 @@ def make_ports_available(ports: Container[int], timeout_seconds=10): psutil.net_connections()) success = True for conn in listening_conns_for_port: - logging.warning( - "Freeing port %d used by %s" % (conn.laddr.port, str(conn))) + logging.warning("Freeing port %d used by %s" % (conn.laddr.port, str(conn))) if not conn.pid: - logging.error( - "Failed to kill process occupying port %d due to lack of pid" % - conn.laddr.port) + logging.error("Failed to kill process occupying port %d due to lack of pid" % conn.laddr.port) success = False continue - logging.warning("Killing pid %d that is using port port %d" % - (conn.pid, conn.laddr.port)) + logging.warning("Killing pid %d that is using port port %d" % (conn.pid, conn.laddr.port)) process = psutil.Process(conn.pid) process.kill() try: process.wait(timeout=timeout_seconds) except psutil.TimeoutExpired: - logging.error("SIGKILL timeout after %d seconds for pid %d" % - (timeout_seconds, conn.pid)) + logging.error("SIGKILL timeout after %d seconds for pid %d" % (timeout_seconds, conn.pid)) continue return success @@ -125,8 +120,7 @@ def read_crash_snippet_and_log_tail(logpath): host_crash_match = HOST_CRASH_LINE_REGEX.match(line) if host_crash_match: - crash_line = host_crash_match.group("line").replace( - gd_root_prefix, "") + crash_line = host_crash_match.group("line").replace(gd_root_prefix, "") if HOST_ABORT_HEADER in crash_line \ and len(last_20_lines) > 1: abort_line = last_20_lines[-2] diff --git a/system/gd/cert/pts_base_test.py b/system/gd/cert/pts_base_test.py index 2b1b5558dd..8099407787 100644 --- a/system/gd/cert/pts_base_test.py +++ b/system/gd/cert/pts_base_test.py @@ -26,5 +26,4 @@ class PTSBaseTestClass(BaseTestClass): gd_devices = self.controller_configs.get("GdDevice") - self.register_controller( - importlib.import_module('cert.gd_device'), builtin=True) + self.register_controller(importlib.import_module('cert.gd_device'), builtin=True) diff --git a/system/gd/cert/py_acl_manager.py b/system/gd/cert/py_acl_manager.py index 8465b75299..3bf082d6a6 100644 --- a/system/gd/cert/py_acl_manager.py +++ b/system/gd/cert/py_acl_manager.py @@ -35,15 +35,11 @@ class PyAclManagerAclConnection(IEventStream, Closable): self.our_acl_stream = acl_stream if remote_addr: - remote_addr_bytes = bytes( - remote_addr, - 'utf8') if type(remote_addr) is str else bytes(remote_addr) + remote_addr_bytes = bytes(remote_addr, 'utf8') if type(remote_addr) is str else bytes(remote_addr) self.connection_event_stream = EventStream( self.device.hci_acl_manager.CreateConnection( acl_manager_facade.ConnectionMsg( - address_type=int( - hci_packets.AddressType.PUBLIC_DEVICE_ADDRESS), - address=remote_addr_bytes))) + address_type=int(hci_packets.AddressType.PUBLIC_DEVICE_ADDRESS), address=remote_addr_bytes))) else: self.connection_event_stream = None @@ -56,8 +52,7 @@ class PyAclManagerAclConnection(IEventStream, Closable): self.handle = connection_complete.get().GetConnectionHandle() def send(self, data): - self.device.hci_acl_manager.SendAclData( - acl_manager_facade.AclData(handle=self.handle, payload=bytes(data))) + self.device.hci_acl_manager.SendAclData(acl_manager_facade.AclData(handle=self.handle, payload=bytes(data))) def get_event_queue(self): return self.our_acl_stream.get_event_queue() @@ -68,8 +63,7 @@ class PyAclManager(Closable): def __init__(self, device): self.device = device - self.acl_stream = EventStream( - self.device.hci_acl_manager.FetchAclData(empty_proto.Empty())) + self.acl_stream = EventStream(self.device.hci_acl_manager.FetchAclData(empty_proto.Empty())) self.incoming_connection_stream = None def close(self): @@ -82,16 +76,13 @@ class PyAclManager(Closable): def listen_for_incoming_connections(self): self.incoming_connection_stream = EventStream( - self.device.hci_acl_manager.FetchIncomingConnection( - empty_proto.Empty())) + self.device.hci_acl_manager.FetchIncomingConnection(empty_proto.Empty())) def initiate_connection(self, remote_addr): - return PyAclManagerAclConnection(self.device, self.acl_stream, - remote_addr, None) + return PyAclManagerAclConnection(self.device, self.acl_stream, remote_addr, None) def accept_connection(self): connection_complete = HciCaptures.ConnectionCompleteCapture() assertThat(self.incoming_connection_stream).emits(connection_complete) handle = connection_complete.get().GetConnectionHandle() - return PyAclManagerAclConnection(self.device, self.acl_stream, None, - handle) + return PyAclManagerAclConnection(self.device, self.acl_stream, None, handle) diff --git a/system/gd/cert/py_hal.py b/system/gd/cert/py_hal.py index e5b29b9469..bce039e9fd 100644 --- a/system/gd/cert/py_hal.py +++ b/system/gd/cert/py_hal.py @@ -26,10 +26,8 @@ class PyHal(Closable): def __init__(self, device): self.device = device - self.hci_event_stream = EventStream( - self.device.hal.FetchHciEvent(empty_proto.Empty())) - self.acl_stream = EventStream( - self.device.hal.FetchHciAcl(empty_proto.Empty())) + self.hci_event_stream = EventStream(self.device.hal.FetchHciEvent(empty_proto.Empty())) + self.acl_stream = EventStream(self.device.hal.FetchHciAcl(empty_proto.Empty())) # We don't deal with SCO for now @@ -44,8 +42,7 @@ class PyHal(Closable): return self.acl_stream def send_hci_command(self, command): - self.device.hal.SendHciCommand( - hal_facade.HciCommandPacket(payload=bytes(command))) + self.device.hal.SendHciCommand(hal_facade.HciCommandPacket(payload=bytes(command))) def send_acl(self, acl): self.device.hal.SendHciAcl(hal_facade.HciAclPacket(payload=bytes(acl))) diff --git a/system/gd/cert/py_hci.py b/system/gd/cert/py_hci.py index 8c56294ced..5c7e5e028d 100644 --- a/system/gd/cert/py_hci.py +++ b/system/gd/cert/py_hci.py @@ -36,10 +36,7 @@ class PyHciAclConnection(IEventStream): def send(self, pb_flag, b_flag, data): acl_msg = hci_facade.AclMsg( - handle=self.handle, - packet_boundary_flag=int(pb_flag), - broadcast_flag=int(b_flag), - data=data) + handle=self.handle, packet_boundary_flag=int(pb_flag), broadcast_flag=int(b_flag), data=data) self.device.hci.SendAclData(acl_msg) def send_first(self, data): @@ -47,8 +44,8 @@ class PyHciAclConnection(IEventStream): hci_packets.BroadcastFlag.POINT_TO_POINT, bytes(data)) def send_continuing(self, data): - self.send(hci_packets.PacketBoundaryFlag.CONTINUING_FRAGMENT, - hci_packets.BroadcastFlag.POINT_TO_POINT, bytes(data)) + self.send(hci_packets.PacketBoundaryFlag.CONTINUING_FRAGMENT, hci_packets.BroadcastFlag.POINT_TO_POINT, + bytes(data)) def get_event_queue(self): return self.our_acl_stream.get_event_queue() @@ -70,24 +67,19 @@ class PyHci(Closable): self._setup_event_stream() self._setup_le_event_stream() if acl_streaming: - self.register_for_events( - hci_packets.EventCode.ROLE_CHANGE, - hci_packets.EventCode.CONNECTION_REQUEST, - hci_packets.EventCode.CONNECTION_COMPLETE, - hci_packets.EventCode.CONNECTION_PACKET_TYPE_CHANGED) + self.register_for_events(hci_packets.EventCode.ROLE_CHANGE, hci_packets.EventCode.CONNECTION_REQUEST, + hci_packets.EventCode.CONNECTION_COMPLETE, + hci_packets.EventCode.CONNECTION_PACKET_TYPE_CHANGED) self._setup_acl_stream() def _setup_event_stream(self): - self.event_stream = EventStream( - self.device.hci.FetchEvents(empty_proto.Empty())) + self.event_stream = EventStream(self.device.hci.FetchEvents(empty_proto.Empty())) def _setup_le_event_stream(self): - self.le_event_stream = EventStream( - self.device.hci.FetchLeSubevents(empty_proto.Empty())) + self.le_event_stream = EventStream(self.device.hci.FetchLeSubevents(empty_proto.Empty())) def _setup_acl_stream(self): - self.acl_stream = EventStream( - self.device.hci.FetchAclPackets(empty_proto.Empty())) + self.acl_stream = EventStream(self.device.hci.FetchAclPackets(empty_proto.Empty())) def close(self): safeClose(self.event_stream) @@ -102,8 +94,7 @@ class PyHci(Closable): def get_raw_acl_stream(self): if self.acl_stream is None: - raise Exception("Please construct '%s' with acl_streaming=True!" % - self.__class__.__name__) + raise Exception("Please construct '%s' with acl_streaming=True!" % self.__class__.__name__) return self.acl_stream def register_for_events(self, *event_codes): @@ -128,8 +119,7 @@ class PyHci(Closable): def enable_inquiry_and_page_scan(self): self.send_command_with_complete( - hci_packets.WriteScanEnableBuilder( - hci_packets.ScanEnable.INQUIRY_AND_PAGE_SCAN)) + hci_packets.WriteScanEnableBuilder(hci_packets.ScanEnable.INQUIRY_AND_PAGE_SCAN)) def read_own_address(self): self.send_command_with_complete(hci_packets.ReadBdAddrBuilder()) @@ -152,9 +142,8 @@ class PyHci(Closable): assertThat(self.event_stream).emits(connection_request) self.send_command_with_status( - hci_packets.AcceptConnectionRequestBuilder( - connection_request.get().GetBdAddr(), - hci_packets.AcceptConnectionRequestRole.REMAIN_SLAVE)) + hci_packets.AcceptConnectionRequestBuilder(connection_request.get().GetBdAddr(), + hci_packets.AcceptConnectionRequestRole.REMAIN_SLAVE)) return self.complete_connection() def complete_connection(self): @@ -163,6 +152,5 @@ class PyHci(Closable): handle = connection_complete.get().GetConnectionHandle() if self.acl_stream is None: - raise Exception("Please construct '%s' with acl_streaming=True!" % - self.__class__.__name__) + raise Exception("Please construct '%s' with acl_streaming=True!" % self.__class__.__name__) return PyHciAclConnection(handle, self.acl_stream, self.device) diff --git a/system/gd/cert/py_l2cap.py b/system/gd/cert/py_l2cap.py index 3989dcd090..2eb0ca001e 100644 --- a/system/gd/cert/py_l2cap.py +++ b/system/gd/cert/py_l2cap.py @@ -34,26 +34,21 @@ class PyL2capChannel(IEventStream): self._device = device self._psm = psm self._le_l2cap_stream = l2cap_stream - self._our_le_l2cap_view = FilteringEventStream( - self._le_l2cap_stream, - L2capMatchers.PacketPayloadWithMatchingPsm(self._psm)) + self._our_le_l2cap_view = FilteringEventStream(self._le_l2cap_stream, + L2capMatchers.PacketPayloadWithMatchingPsm(self._psm)) def get_event_queue(self): return self._our_le_l2cap_view.get_event_queue() def send(self, payload): self._device.l2cap.SendDynamicChannelPacket( - l2cap_facade_pb2.DynamicChannelPacket( - psm=self._psm, payload=payload)) + l2cap_facade_pb2.DynamicChannelPacket(psm=self._psm, payload=payload)) def close_channel(self): - self._device.l2cap.CloseChannel( - l2cap_facade_pb2.CloseChannelRequest(psm=self._psm)) + self._device.l2cap.CloseChannel(l2cap_facade_pb2.CloseChannelRequest(psm=self._psm)) def set_traffic_paused(self, paused): - self._device.l2cap.SetTrafficPaused( - l2cap_facade_pb2.SetTrafficPausedRequest( - psm=self._psm, paused=paused)) + self._device.l2cap.SetTrafficPaused(l2cap_facade_pb2.SetTrafficPausedRequest(psm=self._psm, paused=paused)) class _ClassicConnectionResponseFutureWrapper(object): @@ -77,36 +72,26 @@ class PyL2cap(Closable): def __init__(self, device, cert_address): self._device = device self._cert_address = cert_address - self._l2cap_stream = EventStream( - self._device.l2cap.FetchL2capData(empty_proto.Empty())) + self._l2cap_stream = EventStream(self._device.l2cap.FetchL2capData(empty_proto.Empty())) def close(self): safeClose(self._l2cap_stream) - def register_dynamic_channel( - self, - psm=0x33, - mode=l2cap_facade_pb2.RetransmissionFlowControlMode.BASIC): + def register_dynamic_channel(self, psm=0x33, mode=l2cap_facade_pb2.RetransmissionFlowControlMode.BASIC): self._device.l2cap.SetDynamicChannel( - l2cap_facade_pb2.SetEnableDynamicChannelRequest( - psm=psm, retransmission_mode=mode)) + l2cap_facade_pb2.SetEnableDynamicChannelRequest(psm=psm, retransmission_mode=mode)) return PyL2capChannel(self._device, psm, self._l2cap_stream) - def connect_dynamic_channel_to_cert( - self, - psm=0x33, - mode=l2cap_facade_pb2.RetransmissionFlowControlMode.BASIC): + def connect_dynamic_channel_to_cert(self, psm=0x33, mode=l2cap_facade_pb2.RetransmissionFlowControlMode.BASIC): """ Send open Dynamic channel request to CERT. Get a future for connection result, to be used after CERT accepts request """ self.register_dynamic_channel(psm, mode) response_future = self._device.l2cap.OpenChannel.future( - l2cap_facade_pb2.OpenChannelRequest( - psm=psm, remote=self._cert_address, mode=mode)) + l2cap_facade_pb2.OpenChannelRequest(psm=psm, remote=self._cert_address, mode=mode)) - return _ClassicConnectionResponseFutureWrapper( - response_future, self._device, psm, self._l2cap_stream) + return _ClassicConnectionResponseFutureWrapper(response_future, self._device, psm, self._l2cap_stream) def get_channel_queue_buffer_size(self): return self._device.l2cap.GetChannelQueueDepth(empty_proto.Empty()).size @@ -118,22 +103,19 @@ class PyLeL2capFixedChannel(IEventStream): self._device = device self._cid = cid self._le_l2cap_stream = l2cap_stream - self._our_le_l2cap_view = FilteringEventStream( - self._le_l2cap_stream, - L2capMatchers.PacketPayloadWithMatchingCid(self._cid)) + self._our_le_l2cap_view = FilteringEventStream(self._le_l2cap_stream, + L2capMatchers.PacketPayloadWithMatchingCid(self._cid)) def get_event_queue(self): return self._our_le_l2cap_view.get_event_queue() def send(self, payload): self._device.l2cap_le.SendFixedChannelPacket( - l2cap_le_facade_pb2.FixedChannelPacket( - cid=self._cid, payload=payload)) + l2cap_le_facade_pb2.FixedChannelPacket(cid=self._cid, payload=payload)) def close_channel(self): self._device.l2cap_le.SetFixedChannel( - l2cap_le_facade_pb2.SetEnableFixedChannelRequest( - cid=self._cid, enable=False)) + l2cap_le_facade_pb2.SetEnableFixedChannelRequest(cid=self._cid, enable=False)) class PyLeL2capDynamicChannel(IEventStream): @@ -143,22 +125,19 @@ class PyLeL2capDynamicChannel(IEventStream): self._cert_address = cert_address self._psm = psm self._le_l2cap_stream = l2cap_stream - self._our_le_l2cap_view = FilteringEventStream( - self._le_l2cap_stream, - L2capMatchers.PacketPayloadWithMatchingPsm(self._psm)) + self._our_le_l2cap_view = FilteringEventStream(self._le_l2cap_stream, + L2capMatchers.PacketPayloadWithMatchingPsm(self._psm)) def get_event_queue(self): return self._our_le_l2cap_view.get_event_queue() def send(self, payload): self._device.l2cap_le.SendDynamicChannelPacket( - l2cap_le_facade_pb2.DynamicChannelPacket( - psm=self._psm, payload=payload)) + l2cap_le_facade_pb2.DynamicChannelPacket(psm=self._psm, payload=payload)) def close_channel(self): self._device.l2cap_le.CloseDynamicChannel( - l2cap_le_facade_pb2.CloseDynamicChannelRequest( - remote=self._cert_address, psm=self._psm)) + l2cap_le_facade_pb2.CloseDynamicChannelRequest(remote=self._cert_address, psm=self._psm)) class _CreditBasedConnectionResponseFutureWrapper(object): @@ -167,8 +146,7 @@ class _CreditBasedConnectionResponseFutureWrapper(object): create the corresponding PyLeL2capDynamicChannel object later """ - def __init__(self, grpc_response_future, device, cert_address, psm, - le_l2cap_stream): + def __init__(self, grpc_response_future, device, cert_address, psm, le_l2cap_stream): self._grpc_response_future = grpc_response_future self._device = device self._cert_address = cert_address @@ -176,43 +154,32 @@ class _CreditBasedConnectionResponseFutureWrapper(object): self._le_l2cap_stream = le_l2cap_stream def get_status(self): - return l2cap_packets.LeCreditBasedConnectionResponseResult( - self._grpc_response_future.result().status) + return l2cap_packets.LeCreditBasedConnectionResponseResult(self._grpc_response_future.result().status) def get_channel(self): - assertThat(self.get_status()).isEqualTo( - l2cap_packets.LeCreditBasedConnectionResponseResult.SUCCESS) - return PyLeL2capDynamicChannel(self._device, self._cert_address, - self._psm, self._le_l2cap_stream) + assertThat(self.get_status()).isEqualTo(l2cap_packets.LeCreditBasedConnectionResponseResult.SUCCESS) + return PyLeL2capDynamicChannel(self._device, self._cert_address, self._psm, self._le_l2cap_stream) class PyLeL2cap(Closable): def __init__(self, device): self._device = device - self._le_l2cap_stream = EventStream( - self._device.l2cap_le.FetchL2capData(empty_proto.Empty())) + self._le_l2cap_stream = EventStream(self._device.l2cap_le.FetchL2capData(empty_proto.Empty())) def close(self): safeClose(self._le_l2cap_stream) def enable_fixed_channel(self, cid=4): - self._device.l2cap_le.SetFixedChannel( - l2cap_le_facade_pb2.SetEnableFixedChannelRequest( - cid=cid, enable=True)) + self._device.l2cap_le.SetFixedChannel(l2cap_le_facade_pb2.SetEnableFixedChannelRequest(cid=cid, enable=True)) def get_fixed_channel(self, cid=4): return PyLeL2capFixedChannel(self._device, cid, self._le_l2cap_stream) - def register_coc(self, - cert_address, - psm=0x33, - security_level=SecurityLevel.NO_SECURITY): + def register_coc(self, cert_address, psm=0x33, security_level=SecurityLevel.NO_SECURITY): self._device.l2cap_le.SetDynamicChannel( - l2cap_le_facade_pb2.SetEnableDynamicChannelRequest( - psm=psm, enable=True, security_level=security_level)) - return PyLeL2capDynamicChannel(self._device, cert_address, psm, - self._le_l2cap_stream) + l2cap_le_facade_pb2.SetEnableDynamicChannelRequest(psm=psm, enable=True, security_level=security_level)) + return PyLeL2capDynamicChannel(self._device, cert_address, psm, self._le_l2cap_stream) def connect_coc_to_cert(self, cert_address, psm=0x33): """ @@ -220,12 +187,10 @@ class PyLeL2cap(Closable): """ self.register_coc(cert_address, psm) response_future = self._device.l2cap_le.OpenDynamicChannel.future( - l2cap_le_facade_pb2.OpenDynamicChannelRequest( - psm=psm, remote=cert_address)) + l2cap_le_facade_pb2.OpenDynamicChannelRequest(psm=psm, remote=cert_address)) - return _CreditBasedConnectionResponseFutureWrapper( - response_future, self._device, cert_address, psm, - self._le_l2cap_stream) + return _CreditBasedConnectionResponseFutureWrapper(response_future, self._device, cert_address, psm, + self._le_l2cap_stream) def update_connection_parameter(self, conn_interval_min=0x10, diff --git a/system/gd/cert/py_le_acl_manager.py b/system/gd/cert/py_le_acl_manager.py index c1eb07484e..aeae8bc027 100644 --- a/system/gd/cert/py_le_acl_manager.py +++ b/system/gd/cert/py_le_acl_manager.py @@ -43,14 +43,13 @@ class PyLeAclManagerAclConnection(IEventStream, Closable): self.our_acl_stream = acl_stream if remote_addr: - remote_addr_bytes = bytes( - remote_addr.address.address, - 'utf8') if type(remote_addr.address.address) is str else bytes(remote_addr.address.address) + remote_addr_bytes = bytes(remote_addr.address.address, + 'utf8') if type(remote_addr.address.address) is str else bytes( + remote_addr.address.address) self.connection_event_stream = EventStream( self.device.hci_le_acl_manager.CreateConnection( le_acl_manager_facade.LeConnectionMsg( - address_type=int(remote_addr.type), - address=remote_addr_bytes))) + address_type=int(remote_addr.type), address=remote_addr_bytes))) else: self.connection_event_stream = None @@ -64,8 +63,7 @@ class PyLeAclManagerAclConnection(IEventStream, Closable): def send(self, data): self.device.hci_le_acl_manager.SendAclData( - le_acl_manager_facade.LeAclData( - handle=self.handle, payload=bytes(data))) + le_acl_manager_facade.LeAclData(handle=self.handle, payload=bytes(data))) def get_event_queue(self): return self.our_acl_stream.get_event_queue() @@ -80,8 +78,7 @@ class PyLeAclManager(Closable): """ self.device = device - self.le_acl_stream = EventStream( - self.device.hci_le_acl_manager.FetchAclData(empty_proto.Empty())) + self.le_acl_stream = EventStream(self.device.hci_le_acl_manager.FetchAclData(empty_proto.Empty())) self.incoming_connection_stream = None def close(self): @@ -94,16 +91,13 @@ class PyLeAclManager(Closable): def listen_for_incoming_connections(self): self.incoming_connection_stream = EventStream( - self.device.hci_le_acl_manager.FetchIncomingConnection( - empty_proto.Empty())) + self.device.hci_le_acl_manager.FetchIncomingConnection(empty_proto.Empty())) def initiate_connection(self, remote_addr): - return PyLeAclManagerAclConnection(self.device, self.le_acl_stream, - remote_addr, None) + return PyLeAclManagerAclConnection(self.device, self.le_acl_stream, remote_addr, None) def accept_connection(self): connection_complete = HciCaptures.LeConnectionCompleteCapture() assertThat(self.incoming_connection_stream).emits(connection_complete) handle = connection_complete.get().GetConnectionHandle() - return PyLeAclManagerAclConnection(self.device, self.le_acl_stream, - None, handle) + return PyLeAclManagerAclConnection(self.device, self.le_acl_stream, None, handle) diff --git a/system/gd/cert/py_le_security.py b/system/gd/cert/py_le_security.py index a8d3780280..17d945c396 100644 --- a/system/gd/cert/py_le_security.py +++ b/system/gd/cert/py_le_security.py @@ -43,22 +43,18 @@ class PyLeSecurity(Closable): logging.info("DUT: Init") self._device = device self._device.wait_channel_ready() - self._ui_event_stream = EventStream( - self._device.security.FetchUiEvents(empty_proto.Empty())) - self._bond_event_stream = EventStream( - self._device.security.FetchBondEvents(empty_proto.Empty())) + self._ui_event_stream = EventStream(self._device.security.FetchUiEvents(empty_proto.Empty())) + self._bond_event_stream = EventStream(self._device.security.FetchBondEvents(empty_proto.Empty())) - def wait_for_bond_event( - self, expected_bond_event, timeout=timedelta( - seconds=3)): # =timedelta(seconds=DEFAULT_TIMEOUT_SECONDS) + def wait_for_bond_event(self, expected_bond_event, + timeout=timedelta(seconds=3)): # =timedelta(seconds=DEFAULT_TIMEOUT_SECONDS) """ A bond event will be triggered once the bond process is complete. For the DUT we need to wait for it, for Cert it isn't needed. """ self._bond_event_stream.assert_event_occurs( - match_fn=lambda event: event.message_type == expected_bond_event, - timeout=timeout) + match_fn=lambda event: event.message_type == expected_bond_event, timeout=timeout) def close(self): if self._ui_event_stream is not None: diff --git a/system/gd/cert/py_security.py b/system/gd/cert/py_security.py index 8b1a801450..2633a53570 100644 --- a/system/gd/cert/py_security.py +++ b/system/gd/cert/py_security.py @@ -42,20 +42,16 @@ class PySecurity(Closable): logging.info("DUT: Init") self._device = device self._device.wait_channel_ready() - self._ui_event_stream = EventStream( - self._device.security.FetchUiEvents(empty_proto.Empty())) - self._bond_event_stream = EventStream( - self._device.security.FetchBondEvents(empty_proto.Empty())) + self._ui_event_stream = EventStream(self._device.security.FetchUiEvents(empty_proto.Empty())) + self._bond_event_stream = EventStream(self._device.security.FetchBondEvents(empty_proto.Empty())) def create_bond(self, address, type): """ Triggers stack under test to create bond """ - logging.info("DUT: Creating bond to '%s' from '%s'" % - (str(address), str(self._device.address))) + logging.info("DUT: Creating bond to '%s' from '%s'" % (str(address), str(self._device.address))) self._device.security.CreateBond( - common.BluetoothAddressWithType( - address=common.BluetoothAddress(address=address), type=type)) + common.BluetoothAddressWithType(address=common.BluetoothAddress(address=address), type=type)) def remove_bond(self, address_with_type): """ @@ -67,34 +63,28 @@ class PySecurity(Closable): """ Set the IO Capabilities used for the DUT """ - logging.info( - "DUT: setting IO Capabilities data to '%s'" % io_capabilities) - self._device.security.SetIoCapability( - IoCapabilityMessage(capability=io_capabilities)) + logging.info("DUT: setting IO Capabilities data to '%s'" % io_capabilities) + self._device.security.SetIoCapability(IoCapabilityMessage(capability=io_capabilities)) def set_authentication_requirements(self, auth_reqs): """ Establish authentication requirements for the stack """ - logging.info( - "DUT: setting Authentication Requirements data to '%s'" % auth_reqs) - self._device.security.SetAuthenticationRequirements( - AuthenticationRequirementsMessage(requirement=auth_reqs)) + logging.info("DUT: setting Authentication Requirements data to '%s'" % auth_reqs) + self._device.security.SetAuthenticationRequirements(AuthenticationRequirementsMessage(requirement=auth_reqs)) def set_oob_data(self, data_present): """ Set the Out-of-band data present flag for SSP pairing """ logging.info("DUT: setting OOB data present to '%s'" % data_present) - self._device.security.SetOobDataPresent( - OobDataMessage(data_present=data_present)) + self._device.security.SetOobDataPresent(OobDataMessage(data_present=data_present)) def send_ui_callback(self, address, callback_type, b, uid): """ Send a callback from the UI as if the user pressed a button on the dialog """ - logging.info( - "DUT: Sending user input response uid: %d; response: %s" % (uid, b)) + logging.info("DUT: Sending user input response uid: %d; response: %s" % (uid, b)) self._device.security.SendUiCallback( UiCallbackMsg( message_type=callback_type, @@ -102,8 +92,7 @@ class PySecurity(Closable): unique_id=uid, address=common.BluetoothAddressWithType( address=common.BluetoothAddress(address=address), - type=common.BluetoothAddressTypeEnum.PUBLIC_DEVICE_ADDRESS)) - ) + type=common.BluetoothAddressTypeEnum.PUBLIC_DEVICE_ADDRESS))) def enable_secure_simple_pairing(self): """ @@ -140,8 +129,7 @@ class PySecurity(Closable): logging.info("DUT: Waiting for expected UI event") self._ui_event_stream.assert_event_occurs(get_unique_id) # TODO(optedoblivion): Make UiCallbackType dynamic for PASSKEY when added - self.send_ui_callback(cert_address, UiCallbackType.YES_NO, - reply_boolean, ui_id) + self.send_ui_callback(cert_address, UiCallbackType.YES_NO, reply_boolean, ui_id) def get_address(self): return self._device.address @@ -152,8 +140,7 @@ class PySecurity(Closable): is complete. For the DUT we need to wait for it, for Cert it isn't needed. """ - self._bond_event_stream.assert_event_occurs( - lambda event: event.message_type == expected_bond_event) + self._bond_event_stream.assert_event_occurs(lambda event: event.message_type == expected_bond_event) def close(self): if self._ui_event_stream is not None: diff --git a/system/gd/cert/truth.py b/system/gd/cert/truth.py index d1dfb7a46c..54f41ec44f 100644 --- a/system/gd/cert/truth.py +++ b/system/gd/cert/truth.py @@ -34,26 +34,19 @@ class ObjectSubject(object): def isEqualTo(self, other): if self._value != other: - raise signals.TestFailure( - "Expected \"%s\" to be equal to \"%s\"" % (self._value, other), - extras=None) + raise signals.TestFailure("Expected \"%s\" to be equal to \"%s\"" % (self._value, other), extras=None) def isNotEqualTo(self, other): if self._value == other: - raise signals.TestFailure( - "Expected \"%s\" to not be equal to \"%s\"" % (self._value, - other), - extras=None) + raise signals.TestFailure("Expected \"%s\" to not be equal to \"%s\"" % (self._value, other), extras=None) def isNone(self): if self._value is not None: - raise signals.TestFailure( - "Expected \"%s\" to be None" % self._value, extras=None) + raise signals.TestFailure("Expected \"%s\" to be None" % self._value, extras=None) def isNotNone(self): if self._value is None: - raise signals.TestFailure( - "Expected \"%s\" to not be None" % self._value, extras=None) + raise signals.TestFailure("Expected \"%s\" to not be None" % self._value, extras=None) DEFAULT_TIMEOUT = timedelta(seconds=3) @@ -68,11 +61,7 @@ class EventStreamSubject(ObjectSubject): if len(match_fns) == 0: raise signals.TestFailure("Must specify a match function") elif len(match_fns) == 1: - NOT_FOR_YOU_assert_event_occurs( - self._value, - match_fns[0], - at_least_times=at_least_times, - timeout=timeout) + NOT_FOR_YOU_assert_event_occurs(self._value, match_fns[0], at_least_times=at_least_times, timeout=timeout) return EventStreamContinuationSubject(self._value) else: return MultiMatchStreamSubject(self._value, match_fns, timeout) @@ -82,8 +71,7 @@ class EventStreamSubject(ObjectSubject): NOT_FOR_YOU_assert_none(self._value, timeout=timeout) return EventStreamContinuationSubject(self._value) elif len(match_fns) == 1: - NOT_FOR_YOU_assert_none_matching( - self._value, match_fns[0], timeout=timeout) + NOT_FOR_YOU_assert_none_matching(self._value, match_fns[0], timeout=timeout) return EventStreamContinuationSubject(self._value) else: raise signals.TestFailure("Cannot specify multiple match functions") @@ -97,19 +85,11 @@ class MultiMatchStreamSubject(object): self._timeout = timeout def inAnyOrder(self): - NOT_FOR_YOU_assert_all_events_occur( - self._stream, - self._match_fns, - order_matters=False, - timeout=self._timeout) + NOT_FOR_YOU_assert_all_events_occur(self._stream, self._match_fns, order_matters=False, timeout=self._timeout) return EventStreamContinuationSubject(self._stream) def inOrder(self): - NOT_FOR_YOU_assert_all_events_occur( - self._stream, - self._match_fns, - order_matters=True, - timeout=self._timeout) + NOT_FOR_YOU_assert_all_events_occur(self._stream, self._match_fns, order_matters=True, timeout=self._timeout) return EventStreamContinuationSubject(self._stream) @@ -122,11 +102,7 @@ class EventStreamContinuationSubject(ObjectSubject): if len(match_fns) == 0: raise signals.TestFailure("Must specify a match function") elif len(match_fns) == 1: - NOT_FOR_YOU_assert_event_occurs( - self._value, - match_fns[0], - at_least_times=at_least_times, - timeout=timeout) + NOT_FOR_YOU_assert_event_occurs(self._value, match_fns[0], at_least_times=at_least_times, timeout=timeout) return EventStreamContinuationSubject(self._value) else: return MultiMatchStreamSubject(self._value, match_fns, timeout) @@ -136,8 +112,7 @@ class EventStreamContinuationSubject(ObjectSubject): NOT_FOR_YOU_assert_none(self._value, timeout=timeout) return EventStreamContinuationSubject(self._value) elif len(match_fns) == 1: - NOT_FOR_YOU_assert_none_matching( - self._value, match_fns[0], timeout=timeout) + NOT_FOR_YOU_assert_none_matching(self._value, match_fns[0], timeout=timeout) return EventStreamContinuationSubject(self._value) else: raise signals.TestFailure("Cannot specify multiple match functions") diff --git a/system/gd/hal/cert/simple_hal_test.py b/system/gd/hal/cert/simple_hal_test.py index 6b053e24eb..eaed5a019a 100644 --- a/system/gd/hal/cert/simple_hal_test.py +++ b/system/gd/hal/cert/simple_hal_test.py @@ -38,8 +38,7 @@ class SimpleHalTest(GdBaseTestClass): self.send_cert_hci_command(hci_packets.ResetBuilder()) def send_cert_hci_command(self, command): - self.cert.hal.SendHciCommand( - hal_facade_pb2.HciCommandPacket(payload=bytes(command.Serialize()))) + self.cert.hal.SendHciCommand(hal_facade_pb2.HciCommandPacket(payload=bytes(command.Serialize()))) def send_cert_acl_data(self, handle, pb_flag, b_flag, acl): lower = handle & 0xff @@ -48,14 +47,11 @@ class SimpleHalTest(GdBaseTestClass): upper = upper | ((int(b_flag) & 0x3) << 2) lower_length = len(acl) & 0xff upper_length = (len(acl) & 0xff00) >> 8 - concatenated = bytes([lower, upper, lower_length, upper_length] + - list(acl)) - self.cert.hal.SendHciAcl( - hal_facade_pb2.HciAclPacket(payload=concatenated)) + concatenated = bytes([lower, upper, lower_length, upper_length] + list(acl)) + self.cert.hal.SendHciAcl(hal_facade_pb2.HciAclPacket(payload=concatenated)) def send_dut_hci_command(self, command): - self.dut.hal.SendHciCommand( - hal_facade_pb2.HciCommandPacket(payload=bytes(command.Serialize()))) + self.dut.hal.SendHciCommand(hal_facade_pb2.HciCommandPacket(payload=bytes(command.Serialize()))) def send_dut_acl_data(self, handle, pb_flag, b_flag, acl): lower = handle & 0xff @@ -64,83 +60,62 @@ class SimpleHalTest(GdBaseTestClass): upper = upper | ((int(b_flag) & 0x3) << 2) lower_length = len(acl) & 0xff upper_length = (len(acl) & 0xff00) >> 8 - concatenated = bytes([lower, upper, lower_length, upper_length] + - list(acl)) - self.dut.hal.SendHciAcl( - hal_facade_pb2.HciAclPacket(payload=concatenated)) + concatenated = bytes([lower, upper, lower_length, upper_length] + list(acl)) + self.dut.hal.SendHciAcl(hal_facade_pb2.HciAclPacket(payload=concatenated)) def test_none_event(self): - with EventStream(self.dut.hal.FetchHciEvent( - empty_pb2.Empty())) as hci_event_stream: + with EventStream(self.dut.hal.FetchHciEvent(empty_pb2.Empty())) as hci_event_stream: hci_event_stream.assert_none(timeout=timedelta(seconds=1)) def test_fetch_hci_event(self): - with EventStream(self.dut.hal.FetchHciEvent( - empty_pb2.Empty())) as hci_event_stream: + with EventStream(self.dut.hal.FetchHciEvent(empty_pb2.Empty())) as hci_event_stream: self.send_dut_hci_command( - hci_packets.LeAddDeviceToWhiteListBuilder( - hci_packets.WhiteListAddressType.RANDOM, - '0C:05:04:03:02:01')) - event = hci_packets.LeAddDeviceToWhiteListCompleteBuilder( - 1, hci_packets.ErrorCode.SUCCESS) + hci_packets.LeAddDeviceToWhiteListBuilder(hci_packets.WhiteListAddressType.RANDOM, '0C:05:04:03:02:01')) + event = hci_packets.LeAddDeviceToWhiteListCompleteBuilder(1, hci_packets.ErrorCode.SUCCESS) - assertThat(hci_event_stream).emits( - lambda packet: bytes(event.Serialize()) in packet.payload) + assertThat(hci_event_stream).emits(lambda packet: bytes(event.Serialize()) in packet.payload) def test_loopback_hci_command(self): - with EventStream(self.dut.hal.FetchHciEvent( - empty_pb2.Empty())) as hci_event_stream: + with EventStream(self.dut.hal.FetchHciEvent(empty_pb2.Empty())) as hci_event_stream: - self.send_dut_hci_command( - hci_packets.WriteLoopbackModeBuilder( - hci_packets.LoopbackMode.ENABLE_LOCAL)) + self.send_dut_hci_command(hci_packets.WriteLoopbackModeBuilder(hci_packets.LoopbackMode.ENABLE_LOCAL)) - command = hci_packets.LeAddDeviceToWhiteListBuilder( - hci_packets.WhiteListAddressType.RANDOM, '0C:05:04:03:02:01') + command = hci_packets.LeAddDeviceToWhiteListBuilder(hci_packets.WhiteListAddressType.RANDOM, + '0C:05:04:03:02:01') self.send_dut_hci_command(command) - assertThat(hci_event_stream).emits( - lambda packet: bytes(command.Serialize()) in packet.payload) + assertThat(hci_event_stream).emits(lambda packet: bytes(command.Serialize()) in packet.payload) def test_inquiry_from_dut(self): - with EventStream(self.dut.hal.FetchHciEvent( - empty_pb2.Empty())) as hci_event_stream: + with EventStream(self.dut.hal.FetchHciEvent(empty_pb2.Empty())) as hci_event_stream: - self.send_cert_hci_command( - hci_packets.WriteScanEnableBuilder( - hci_packets.ScanEnable.INQUIRY_AND_PAGE_SCAN)) + self.send_cert_hci_command(hci_packets.WriteScanEnableBuilder(hci_packets.ScanEnable.INQUIRY_AND_PAGE_SCAN)) lap = hci_packets.Lap() lap.lap = 0x33 - self.send_dut_hci_command( - hci_packets.InquiryBuilder(lap, 0x30, 0xff)) + self.send_dut_hci_command(hci_packets.InquiryBuilder(lap, 0x30, 0xff)) - assertThat(hci_event_stream).emits( - lambda packet: b'\x02\x0f' in packet.payload - # Expecting an HCI Event (code 0x02, length 0x0f) - ) + assertThat(hci_event_stream).emits(lambda packet: b'\x02\x0f' in packet.payload + # Expecting an HCI Event (code 0x02, length 0x0f) + ) def test_le_ad_scan_cert_advertises(self): - with EventStream(self.dut.hal.FetchHciEvent( - empty_pb2.Empty())) as hci_event_stream: + with EventStream(self.dut.hal.FetchHciEvent(empty_pb2.Empty())) as hci_event_stream: # DUT scans - self.send_dut_hci_command( - hci_packets.LeSetRandomAddressBuilder('0D:05:04:03:02:01')) + self.send_dut_hci_command(hci_packets.LeSetRandomAddressBuilder('0D:05:04:03:02:01')) phy_scan_params = hci_packets.PhyScanParameters() phy_scan_params.le_scan_interval = 6553 phy_scan_params.le_scan_window = 6553 phy_scan_params.le_scan_type = hci_packets.LeScanType.ACTIVE self.send_dut_hci_command( - hci_packets.LeSetExtendedScanParametersBuilder( - hci_packets.AddressType.RANDOM_DEVICE_ADDRESS, - hci_packets.LeSetScanningFilterPolicy.ACCEPT_ALL, 1, - [phy_scan_params])) + hci_packets.LeSetExtendedScanParametersBuilder(hci_packets.AddressType.RANDOM_DEVICE_ADDRESS, + hci_packets.LeSetScanningFilterPolicy.ACCEPT_ALL, 1, + [phy_scan_params])) self.send_dut_hci_command( - hci_packets.LeSetExtendedScanEnableBuilder( - hci_packets.Enable.ENABLED, - hci_packets.FilterDuplicates.DISABLED, 0, 0)) + hci_packets.LeSetExtendedScanEnableBuilder(hci_packets.Enable.ENABLED, + hci_packets.FilterDuplicates.DISABLED, 0, 0)) # CERT Advertises advertising_handle = 0 @@ -152,8 +127,7 @@ class SimpleHalTest(GdBaseTestClass): 768, 7, hci_packets.OwnAddressType.RANDOM_DEVICE_ADDRESS, - hci_packets.PeerAddressType. - PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, + hci_packets.PeerAddressType.PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, 'A6:A5:A4:A3:A2:A1', hci_packets.AdvertisingFilterPolicy.ALL_DEVICES, 0x7F, @@ -162,8 +136,7 @@ class SimpleHalTest(GdBaseTestClass): )) self.send_cert_hci_command( - hci_packets.LeSetExtendedAdvertisingRandomAddressBuilder( - advertising_handle, '0C:05:04:03:02:01')) + hci_packets.LeSetExtendedAdvertisingRandomAddressBuilder(advertising_handle, '0C:05:04:03:02:01')) gap_name = hci_packets.GapData() gap_name.data_type = hci_packets.GapDataType.COMPLETE_LOCAL_NAME @@ -171,31 +144,25 @@ class SimpleHalTest(GdBaseTestClass): self.send_cert_hci_command( hci_packets.LeSetExtendedAdvertisingDataBuilder( - advertising_handle, - hci_packets.Operation.COMPLETE_ADVERTISEMENT, - hci_packets.FragmentPreference.CONTROLLER_SHOULD_NOT, - [gap_name])) + advertising_handle, hci_packets.Operation.COMPLETE_ADVERTISEMENT, + hci_packets.FragmentPreference.CONTROLLER_SHOULD_NOT, [gap_name])) enabled_set = hci_packets.EnabledSet() enabled_set.advertising_handle = advertising_handle enabled_set.duration = 0 enabled_set.max_extended_advertising_events = 0 self.send_cert_hci_command( - hci_packets.LeSetExtendedAdvertisingEnableBuilder( - hci_packets.Enable.ENABLED, [enabled_set])) + hci_packets.LeSetExtendedAdvertisingEnableBuilder(hci_packets.Enable.ENABLED, [enabled_set])) - assertThat(hci_event_stream).emits( - lambda packet: b'Im_A_Cert' in packet.payload) + assertThat(hci_event_stream).emits(lambda packet: b'Im_A_Cert' in packet.payload) # Disable Advertising self.send_cert_hci_command( - hci_packets.LeSetExtendedAdvertisingEnableBuilder( - hci_packets.Enable.DISABLED, [enabled_set])) + hci_packets.LeSetExtendedAdvertisingEnableBuilder(hci_packets.Enable.DISABLED, [enabled_set])) # Disable Scanning self.send_dut_hci_command( - hci_packets.LeSetExtendedScanEnableBuilder( - hci_packets.Enable.ENABLED, - hci_packets.FilterDuplicates.DISABLED, 0, 0)) + hci_packets.LeSetExtendedScanEnableBuilder(hci_packets.Enable.ENABLED, + hci_packets.FilterDuplicates.DISABLED, 0, 0)) def test_le_connection_dut_advertises(self): with EventStream(self.dut.hal.FetchHciEvent(empty_pb2.Empty())) as hci_event_stream, \ @@ -204,8 +171,7 @@ class SimpleHalTest(GdBaseTestClass): EventStream(self.cert.hal.FetchHciAcl(empty_pb2.Empty())) as cert_acl_data_stream: # Cert Connects - self.send_cert_hci_command( - hci_packets.LeSetRandomAddressBuilder('0C:05:04:03:02:01')) + self.send_cert_hci_command(hci_packets.LeSetRandomAddressBuilder('0C:05:04:03:02:01')) phy_scan_params = hci_packets.LeCreateConnPhyScanParameters() phy_scan_params.scan_interval = 0x60 phy_scan_params.scan_window = 0x30 @@ -216,11 +182,10 @@ class SimpleHalTest(GdBaseTestClass): phy_scan_params.min_ce_length = 0 phy_scan_params.max_ce_length = 0 self.send_cert_hci_command( - hci_packets.LeExtendedCreateConnectionBuilder( - hci_packets.InitiatorFilterPolicy.USE_PEER_ADDRESS, - hci_packets.OwnAddressType.RANDOM_DEVICE_ADDRESS, - hci_packets.AddressType.RANDOM_DEVICE_ADDRESS, - '0D:05:04:03:02:01', 1, [phy_scan_params])) + hci_packets.LeExtendedCreateConnectionBuilder(hci_packets.InitiatorFilterPolicy.USE_PEER_ADDRESS, + hci_packets.OwnAddressType.RANDOM_DEVICE_ADDRESS, + hci_packets.AddressType.RANDOM_DEVICE_ADDRESS, + '0D:05:04:03:02:01', 1, [phy_scan_params])) # DUT Advertises advertising_handle = 0 @@ -232,8 +197,7 @@ class SimpleHalTest(GdBaseTestClass): 450, 7, hci_packets.OwnAddressType.RANDOM_DEVICE_ADDRESS, - hci_packets.PeerAddressType. - PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, + hci_packets.PeerAddressType.PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, '00:00:00:00:00:00', hci_packets.AdvertisingFilterPolicy.ALL_DEVICES, 0xF8, @@ -242,20 +206,16 @@ class SimpleHalTest(GdBaseTestClass): )) self.send_dut_hci_command( - hci_packets.LeSetExtendedAdvertisingRandomAddressBuilder( - advertising_handle, '0D:05:04:03:02:01')) + hci_packets.LeSetExtendedAdvertisingRandomAddressBuilder(advertising_handle, '0D:05:04:03:02:01')) gap_name = hci_packets.GapData() gap_name.data_type = hci_packets.GapDataType.COMPLETE_LOCAL_NAME - gap_name.data = list( - bytes(b'Im_The_DUT!')) # TODO: Fix and remove ! + gap_name.data = list(bytes(b'Im_The_DUT!')) # TODO: Fix and remove ! self.send_dut_hci_command( hci_packets.LeSetExtendedAdvertisingDataBuilder( - advertising_handle, - hci_packets.Operation.COMPLETE_ADVERTISEMENT, - hci_packets.FragmentPreference.CONTROLLER_SHOULD_NOT, - [gap_name])) + advertising_handle, hci_packets.Operation.COMPLETE_ADVERTISEMENT, + hci_packets.FragmentPreference.CONTROLLER_SHOULD_NOT, [gap_name])) gap_short_name = hci_packets.GapData() gap_short_name.data_type = hci_packets.GapDataType.SHORTENED_LOCAL_NAME @@ -263,18 +223,15 @@ class SimpleHalTest(GdBaseTestClass): self.send_dut_hci_command( hci_packets.LeSetExtendedAdvertisingScanResponseBuilder( - advertising_handle, - hci_packets.Operation.COMPLETE_ADVERTISEMENT, - hci_packets.FragmentPreference.CONTROLLER_SHOULD_NOT, - [gap_short_name])) + advertising_handle, hci_packets.Operation.COMPLETE_ADVERTISEMENT, + hci_packets.FragmentPreference.CONTROLLER_SHOULD_NOT, [gap_short_name])) enabled_set = hci_packets.EnabledSet() enabled_set.advertising_handle = advertising_handle enabled_set.duration = 0 enabled_set.max_extended_advertising_events = 0 self.send_dut_hci_command( - hci_packets.LeSetExtendedAdvertisingEnableBuilder( - hci_packets.Enable.ENABLED, [enabled_set])) + hci_packets.LeSetExtendedAdvertisingEnableBuilder(hci_packets.Enable.ENABLED, [enabled_set])) conn_handle = 0xfff @@ -284,9 +241,7 @@ class SimpleHalTest(GdBaseTestClass): nonlocal conn_handle cc_view = hci_packets.LeConnectionCompleteView( hci_packets.LeMetaEventView( - hci_packets.EventPacketView( - bt_packets.PacketViewLittleEndian( - list(packet_bytes))))) + hci_packets.EventPacketView(bt_packets.PacketViewLittleEndian(list(packet_bytes))))) conn_handle = cc_view.GetConnectionHandle() return True return False @@ -298,33 +253,22 @@ class SimpleHalTest(GdBaseTestClass): dut_handle = conn_handle # Send ACL Data - self.send_dut_acl_data( - dut_handle, hci_packets.PacketBoundaryFlag. - FIRST_NON_AUTOMATICALLY_FLUSHABLE, - hci_packets.BroadcastFlag.POINT_TO_POINT, - bytes(b'Just SomeAclData')) - self.send_cert_acl_data( - cert_handle, hci_packets.PacketBoundaryFlag. - FIRST_NON_AUTOMATICALLY_FLUSHABLE, - hci_packets.BroadcastFlag.POINT_TO_POINT, - bytes(b'Just SomeMoreAclData')) - - assertThat(cert_acl_data_stream).emits( - lambda packet: b'SomeAclData' in packet.payload) - assertThat(acl_data_stream).emits( - lambda packet: b'SomeMoreAclData' in packet.payload) + self.send_dut_acl_data(dut_handle, hci_packets.PacketBoundaryFlag.FIRST_NON_AUTOMATICALLY_FLUSHABLE, + hci_packets.BroadcastFlag.POINT_TO_POINT, bytes(b'Just SomeAclData')) + self.send_cert_acl_data(cert_handle, hci_packets.PacketBoundaryFlag.FIRST_NON_AUTOMATICALLY_FLUSHABLE, + hci_packets.BroadcastFlag.POINT_TO_POINT, bytes(b'Just SomeMoreAclData')) + + assertThat(cert_acl_data_stream).emits(lambda packet: b'SomeAclData' in packet.payload) + assertThat(acl_data_stream).emits(lambda packet: b'SomeMoreAclData' in packet.payload) def test_le_white_list_connection_cert_advertises(self): with EventStream(self.dut.hal.FetchHciEvent(empty_pb2.Empty())) as hci_event_stream, \ EventStream(self.cert.hal.FetchHciEvent(empty_pb2.Empty())) as cert_hci_event_stream: # DUT Connects + self.send_dut_hci_command(hci_packets.LeSetRandomAddressBuilder('0D:05:04:03:02:01')) self.send_dut_hci_command( - hci_packets.LeSetRandomAddressBuilder('0D:05:04:03:02:01')) - self.send_dut_hci_command( - hci_packets.LeAddDeviceToWhiteListBuilder( - hci_packets.WhiteListAddressType.RANDOM, - '0C:05:04:03:02:01')) + hci_packets.LeAddDeviceToWhiteListBuilder(hci_packets.WhiteListAddressType.RANDOM, '0C:05:04:03:02:01')) phy_scan_params = hci_packets.LeCreateConnPhyScanParameters() phy_scan_params.scan_interval = 0x60 phy_scan_params.scan_window = 0x30 @@ -336,10 +280,8 @@ class SimpleHalTest(GdBaseTestClass): phy_scan_params.max_ce_length = 0 self.send_dut_hci_command( hci_packets.LeExtendedCreateConnectionBuilder( - hci_packets.InitiatorFilterPolicy.USE_WHITE_LIST, - hci_packets.OwnAddressType.RANDOM_DEVICE_ADDRESS, - hci_packets.AddressType.RANDOM_DEVICE_ADDRESS, - 'BA:D5:A4:A3:A2:A1', 1, [phy_scan_params])) + hci_packets.InitiatorFilterPolicy.USE_WHITE_LIST, hci_packets.OwnAddressType.RANDOM_DEVICE_ADDRESS, + hci_packets.AddressType.RANDOM_DEVICE_ADDRESS, 'BA:D5:A4:A3:A2:A1', 1, [phy_scan_params])) # CERT Advertises advertising_handle = 1 @@ -351,8 +293,7 @@ class SimpleHalTest(GdBaseTestClass): 768, 7, hci_packets.OwnAddressType.RANDOM_DEVICE_ADDRESS, - hci_packets.PeerAddressType. - PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, + hci_packets.PeerAddressType.PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, 'A6:A5:A4:A3:A2:A1', hci_packets.AdvertisingFilterPolicy.ALL_DEVICES, 0x7F, @@ -361,8 +302,7 @@ class SimpleHalTest(GdBaseTestClass): )) self.send_cert_hci_command( - hci_packets.LeSetExtendedAdvertisingRandomAddressBuilder( - advertising_handle, '0C:05:04:03:02:01')) + hci_packets.LeSetExtendedAdvertisingRandomAddressBuilder(advertising_handle, '0C:05:04:03:02:01')) gap_name = hci_packets.GapData() gap_name.data_type = hci_packets.GapDataType.COMPLETE_LOCAL_NAME @@ -370,22 +310,17 @@ class SimpleHalTest(GdBaseTestClass): self.send_cert_hci_command( hci_packets.LeSetExtendedAdvertisingDataBuilder( - advertising_handle, - hci_packets.Operation.COMPLETE_ADVERTISEMENT, - hci_packets.FragmentPreference.CONTROLLER_SHOULD_NOT, - [gap_name])) + advertising_handle, hci_packets.Operation.COMPLETE_ADVERTISEMENT, + hci_packets.FragmentPreference.CONTROLLER_SHOULD_NOT, [gap_name])) enabled_set = hci_packets.EnabledSet() enabled_set.advertising_handle = 1 enabled_set.duration = 0 enabled_set.max_extended_advertising_events = 0 self.send_cert_hci_command( - hci_packets.LeSetExtendedAdvertisingEnableBuilder( - hci_packets.Enable.ENABLED, [enabled_set])) + hci_packets.LeSetExtendedAdvertisingEnableBuilder(hci_packets.Enable.ENABLED, [enabled_set])) # LeConnectionComplete cert_hci_event_stream.assert_event_occurs( - lambda packet: b'\x3e\x13\x01\x00' in packet.payload, - timeout=timedelta(seconds=20)) + lambda packet: b'\x3e\x13\x01\x00' in packet.payload, timeout=timedelta(seconds=20)) hci_event_stream.assert_event_occurs( - lambda packet: b'\x3e\x13\x01\x00' in packet.payload, - timeout=timedelta(seconds=20)) + lambda packet: b'\x3e\x13\x01\x00' in packet.payload, timeout=timedelta(seconds=20)) diff --git a/system/gd/hci/cert/acl_manager_test.py b/system/gd/hci/cert/acl_manager_test.py index 842810bead..ab6a4bc0c7 100644 --- a/system/gd/hci/cert/acl_manager_test.py +++ b/system/gd/hci/cert/acl_manager_test.py @@ -54,23 +54,18 @@ class AclManagerTest(GdBaseTestClass): with self.dut_acl_manager.initiate_connection(cert_address) as dut_acl: cert_acl = self.cert_hci.accept_connection() - cert_acl.send_first( - b'\x26\x00\x07\x00This is just SomeAclData from the Cert') + cert_acl.send_first(b'\x26\x00\x07\x00This is just SomeAclData from the Cert') dut_acl.wait_for_connection_complete() - dut_acl.send( - b'\x29\x00\x07\x00This is just SomeMoreAclData from the DUT') + dut_acl.send(b'\x29\x00\x07\x00This is just SomeMoreAclData from the DUT') - assertThat(cert_acl).emits( - lambda packet: b'SomeMoreAclData' in packet.data) - assertThat(dut_acl).emits( - lambda packet: b'SomeAclData' in packet.payload) + assertThat(cert_acl).emits(lambda packet: b'SomeMoreAclData' in packet.data) + assertThat(dut_acl).emits(lambda packet: b'SomeAclData' in packet.payload) def test_cert_connects(self): dut_address = self.dut.hci_controller.GetMacAddressSimple() - self.dut.neighbor.EnablePageScan( - neighbor_facade.EnableMsg(enabled=True)) + self.dut.neighbor.EnablePageScan(neighbor_facade.EnableMsg(enabled=True)) self.dut_acl_manager.listen_for_incoming_connections() self.cert_hci.initiate_connection(dut_address) @@ -79,16 +74,12 @@ class AclManagerTest(GdBaseTestClass): cert_acl = self.cert_hci.complete_connection() - dut_acl.send( - b'\x29\x00\x07\x00This is just SomeMoreAclData from the DUT') + dut_acl.send(b'\x29\x00\x07\x00This is just SomeMoreAclData from the DUT') - cert_acl.send_first( - b'\x26\x00\x07\x00This is just SomeAclData from the Cert') + cert_acl.send_first(b'\x26\x00\x07\x00This is just SomeAclData from the Cert') - assertThat(cert_acl).emits( - lambda packet: b'SomeMoreAclData' in packet.data) - assertThat(dut_acl).emits( - lambda packet: b'SomeAclData' in packet.payload) + assertThat(cert_acl).emits(lambda packet: b'SomeMoreAclData' in packet.data) + assertThat(dut_acl).emits(lambda packet: b'SomeAclData' in packet.payload) def test_recombination_l2cap_packet(self): self.cert_hci.enable_inquiry_and_page_scan() @@ -102,6 +93,5 @@ class AclManagerTest(GdBaseTestClass): dut_acl.wait_for_connection_complete() - assertThat(dut_acl).emits( - lambda packet: b'Hello!' in packet.payload, - lambda packet: b'Hello' * 200 in packet.payload).inOrder() + assertThat(dut_acl).emits(lambda packet: b'Hello!' in packet.payload, + lambda packet: b'Hello' * 200 in packet.payload).inOrder() diff --git a/system/gd/hci/cert/controller_test.py b/system/gd/hci/cert/controller_test.py index 6e6030ffe4..dbc7793d5b 100644 --- a/system/gd/hci/cert/controller_test.py +++ b/system/gd/hci/cert/controller_test.py @@ -26,8 +26,7 @@ from hci.facade import controller_facade_pb2 as controller_facade class ControllerTest(GdBaseTestClass): def setup_class(self): - super().setup_class( - dut_module='HCI_INTERFACES', cert_module='HCI_INTERFACES') + super().setup_class(dut_module='HCI_INTERFACES', cert_module='HCI_INTERFACES') def test_get_addresses(self): cert_address = self.cert.hci_controller.GetMacAddressSimple() @@ -39,21 +38,16 @@ class ControllerTest(GdBaseTestClass): def test_get_local_extended_features(self): request = controller_facade.PageNumberMsg() request.page_number = 1 - dut_feature_response1 = self.dut.hci_controller.GetLocalExtendedFeatures( - request) + dut_feature_response1 = self.dut.hci_controller.GetLocalExtendedFeatures(request) request0 = controller_facade.PageNumberMsg() request0.page_number = 0 - dut_feature_response0 = self.dut.hci_controller.GetLocalExtendedFeatures( - request0) + dut_feature_response0 = self.dut.hci_controller.GetLocalExtendedFeatures(request0) - assertThat(dut_feature_response1.page).isNotEqualTo( - dut_feature_response0.page) + assertThat(dut_feature_response1.page).isNotEqualTo(dut_feature_response0.page) def test_write_local_name(self): - self.dut.hci_controller.WriteLocalName( - controller_facade.NameMsg(name=b'ImTheDUT')) - self.cert.hci_controller.WriteLocalName( - controller_facade.NameMsg(name=b'ImTheCert')) + self.dut.hci_controller.WriteLocalName(controller_facade.NameMsg(name=b'ImTheDUT')) + self.cert.hci_controller.WriteLocalName(controller_facade.NameMsg(name=b'ImTheCert')) cert_name = self.cert.hci_controller.GetLocalNameSimple() dut_name = self.dut.hci_controller.GetLocalNameSimple() diff --git a/system/gd/hci/cert/direct_hci_test.py b/system/gd/hci/cert/direct_hci_test.py index 91a59a1a1d..15a4f111a6 100644 --- a/system/gd/hci/cert/direct_hci_test.py +++ b/system/gd/hci/cert/direct_hci_test.py @@ -48,10 +48,7 @@ class DirectHciTest(GdBaseTestClass): def enqueue_acl_data(self, handle, pb_flag, b_flag, acl): acl_msg = hci_facade.AclMsg( - handle=int(handle), - packet_boundary_flag=int(pb_flag), - broadcast_flag=int(b_flag), - data=acl) + handle=int(handle), packet_boundary_flag=int(pb_flag), broadcast_flag=int(b_flag), data=acl) self.dut.hci.SendAclData(acl_msg) def send_hal_acl_data(self, handle, pb_flag, b_flag, acl): @@ -61,8 +58,7 @@ class DirectHciTest(GdBaseTestClass): upper = upper | ((int(b_flag) & 0x3) << 2) lower_length = len(acl) & 0xff upper_length = (len(acl) & 0xff00) >> 8 - concatenated = bytes([lower, upper, lower_length, upper_length] + - list(acl)) + concatenated = bytes([lower, upper, lower_length, upper_length] + list(acl)) self.cert_hal.send_acl(concatenated) def test_local_hci_cmd_and_event(self): @@ -70,52 +66,42 @@ class DirectHciTest(GdBaseTestClass): self.dut_hci.register_for_events(hci_packets.EventCode.LOOPBACK_COMMAND) self.dut_hci.send_command_with_complete( - hci_packets.WriteLoopbackModeBuilder( - hci_packets.LoopbackMode.ENABLE_LOCAL)) + hci_packets.WriteLoopbackModeBuilder(hci_packets.LoopbackMode.ENABLE_LOCAL)) cmd2loop = hci_packets.ReadLocalNameBuilder() self.dut_hci.send_command_with_complete(cmd2loop) looped_bytes = bytes(cmd2loop.Serialize()) - assertThat(self.dut_hci.get_event_stream()).emits( - lambda packet: looped_bytes in packet.event) + assertThat(self.dut_hci.get_event_stream()).emits(lambda packet: looped_bytes in packet.event) def test_inquiry_from_dut(self): self.dut_hci.register_for_events(hci_packets.EventCode.INQUIRY_RESULT) - self.send_hal_hci_command( - hci_packets.WriteScanEnableBuilder( - hci_packets.ScanEnable.INQUIRY_AND_PAGE_SCAN)) + self.send_hal_hci_command(hci_packets.WriteScanEnableBuilder(hci_packets.ScanEnable.INQUIRY_AND_PAGE_SCAN)) lap = hci_packets.Lap() lap.lap = 0x33 - self.dut_hci.send_command_with_status( - hci_packets.InquiryBuilder(lap, 0x30, 0xff)) + self.dut_hci.send_command_with_status(hci_packets.InquiryBuilder(lap, 0x30, 0xff)) assertThat(self.dut_hci.get_event_stream()).emits( HciMatchers.EventWithCode(hci_packets.EventCode.INQUIRY_RESULT)) def test_le_ad_scan_cert_advertises(self): - self.dut_hci.register_for_le_events( - hci_packets.SubeventCode.EXTENDED_ADVERTISING_REPORT) - self.dut_hci.register_for_le_events( - hci_packets.SubeventCode.ADVERTISING_REPORT) + self.dut_hci.register_for_le_events(hci_packets.SubeventCode.EXTENDED_ADVERTISING_REPORT) + self.dut_hci.register_for_le_events(hci_packets.SubeventCode.ADVERTISING_REPORT) # DUT Scans - self.dut_hci.send_command_with_complete( - hci_packets.LeSetRandomAddressBuilder('0D:05:04:03:02:01')) + self.dut_hci.send_command_with_complete(hci_packets.LeSetRandomAddressBuilder('0D:05:04:03:02:01')) phy_scan_params = hci_packets.PhyScanParameters() phy_scan_params.le_scan_interval = 6553 phy_scan_params.le_scan_window = 6553 phy_scan_params.le_scan_type = hci_packets.LeScanType.ACTIVE self.dut_hci.send_command_with_complete( - hci_packets.LeSetExtendedScanParametersBuilder( - hci_packets.AddressType.RANDOM_DEVICE_ADDRESS, - hci_packets.LeSetScanningFilterPolicy.ACCEPT_ALL, 1, - [phy_scan_params])) + hci_packets.LeSetExtendedScanParametersBuilder(hci_packets.AddressType.RANDOM_DEVICE_ADDRESS, + hci_packets.LeSetScanningFilterPolicy.ACCEPT_ALL, 1, + [phy_scan_params])) self.dut_hci.send_command_with_complete( - hci_packets.LeSetExtendedScanEnableBuilder( - hci_packets.Enable.ENABLED, - hci_packets.FilterDuplicates.DISABLED, 0, 0)) + hci_packets.LeSetExtendedScanEnableBuilder(hci_packets.Enable.ENABLED, + hci_packets.FilterDuplicates.DISABLED, 0, 0)) # CERT Advertises advertising_handle = 0 @@ -136,18 +122,15 @@ class DirectHciTest(GdBaseTestClass): )) self.send_hal_hci_command( - hci_packets.LeSetExtendedAdvertisingRandomAddressBuilder( - advertising_handle, '0C:05:04:03:02:01')) + hci_packets.LeSetExtendedAdvertisingRandomAddressBuilder(advertising_handle, '0C:05:04:03:02:01')) gap_name = hci_packets.GapData() gap_name.data_type = hci_packets.GapDataType.COMPLETE_LOCAL_NAME gap_name.data = list(bytes(b'Im_A_Cert!')) # TODO: Fix and remove ! self.send_hal_hci_command( hci_packets.LeSetExtendedAdvertisingDataBuilder( - advertising_handle, - hci_packets.Operation.COMPLETE_ADVERTISEMENT, - hci_packets.FragmentPreference.CONTROLLER_SHOULD_NOT, - [gap_name])) + advertising_handle, hci_packets.Operation.COMPLETE_ADVERTISEMENT, + hci_packets.FragmentPreference.CONTROLLER_SHOULD_NOT, [gap_name])) gap_short_name = hci_packets.GapData() gap_short_name.data_type = hci_packets.GapDataType.SHORTENED_LOCAL_NAME @@ -155,39 +138,31 @@ class DirectHciTest(GdBaseTestClass): self.send_hal_hci_command( hci_packets.LeSetExtendedAdvertisingScanResponseBuilder( - advertising_handle, - hci_packets.Operation.COMPLETE_ADVERTISEMENT, - hci_packets.FragmentPreference.CONTROLLER_SHOULD_NOT, - [gap_short_name])) + advertising_handle, hci_packets.Operation.COMPLETE_ADVERTISEMENT, + hci_packets.FragmentPreference.CONTROLLER_SHOULD_NOT, [gap_short_name])) enabled_set = hci_packets.EnabledSet() enabled_set.advertising_handle = 0 enabled_set.duration = 0 enabled_set.max_extended_advertising_events = 0 self.send_hal_hci_command( - hci_packets.LeSetExtendedAdvertisingEnableBuilder( - hci_packets.Enable.ENABLED, [enabled_set])) + hci_packets.LeSetExtendedAdvertisingEnableBuilder(hci_packets.Enable.ENABLED, [enabled_set])) - assertThat(self.dut_hci.get_le_event_stream()).emits( - lambda packet: b'Im_A_Cert' in packet.event) + assertThat(self.dut_hci.get_le_event_stream()).emits(lambda packet: b'Im_A_Cert' in packet.event) self.send_hal_hci_command( - hci_packets.LeSetExtendedAdvertisingEnableBuilder( - hci_packets.Enable.DISABLED, [enabled_set])) + hci_packets.LeSetExtendedAdvertisingEnableBuilder(hci_packets.Enable.DISABLED, [enabled_set])) self.dut_hci.send_command_with_complete( - hci_packets.LeSetExtendedScanEnableBuilder( - hci_packets.Enable.DISABLED, - hci_packets.FilterDuplicates.DISABLED, 0, 0)) + hci_packets.LeSetExtendedScanEnableBuilder(hci_packets.Enable.DISABLED, + hci_packets.FilterDuplicates.DISABLED, 0, 0)) def _verify_le_connection_complete(self): cert_conn_complete_capture = HalCaptures.LeConnectionCompleteCapture() - assertThat(self.cert_hal.get_hci_event_stream()).emits( - cert_conn_complete_capture) + assertThat(self.cert_hal.get_hci_event_stream()).emits(cert_conn_complete_capture) cert_handle = cert_conn_complete_capture.get().GetConnectionHandle() dut_conn_complete_capture = HciCaptures.LeConnectionCompleteCapture() - assertThat( - self.dut_hci.get_le_event_stream()).emits(dut_conn_complete_capture) + assertThat(self.dut_hci.get_le_event_stream()).emits(dut_conn_complete_capture) dut_handle = dut_conn_complete_capture.get().GetConnectionHandle() return (dut_handle, cert_handle) @@ -206,18 +181,14 @@ class DirectHciTest(GdBaseTestClass): return phy_scan_params def test_le_connection_dut_advertises(self): - self.dut_hci.register_for_le_events( - hci_packets.SubeventCode.CONNECTION_COMPLETE) + self.dut_hci.register_for_le_events(hci_packets.SubeventCode.CONNECTION_COMPLETE) # Cert Connects - self.send_hal_hci_command( - hci_packets.LeSetRandomAddressBuilder('0C:05:04:03:02:01')) + self.send_hal_hci_command(hci_packets.LeSetRandomAddressBuilder('0C:05:04:03:02:01')) phy_scan_params = DirectHciTest._create_phy_scan_params() self.send_hal_hci_command( hci_packets.LeExtendedCreateConnectionBuilder( - hci_packets.InitiatorFilterPolicy.USE_PEER_ADDRESS, - hci_packets.OwnAddressType.RANDOM_DEVICE_ADDRESS, - hci_packets.AddressType.RANDOM_DEVICE_ADDRESS, - '0D:05:04:03:02:01', 1, [phy_scan_params])) + hci_packets.InitiatorFilterPolicy.USE_PEER_ADDRESS, hci_packets.OwnAddressType.RANDOM_DEVICE_ADDRESS, + hci_packets.AddressType.RANDOM_DEVICE_ADDRESS, '0D:05:04:03:02:01', 1, [phy_scan_params])) # DUT Advertises advertising_handle = 0 @@ -238,8 +209,7 @@ class DirectHciTest(GdBaseTestClass): )) self.dut_hci.send_command_with_complete( - hci_packets.LeSetExtendedAdvertisingRandomAddressBuilder( - advertising_handle, '0D:05:04:03:02:01')) + hci_packets.LeSetExtendedAdvertisingRandomAddressBuilder(advertising_handle, '0D:05:04:03:02:01')) gap_name = hci_packets.GapData() gap_name.data_type = hci_packets.GapDataType.COMPLETE_LOCAL_NAME @@ -247,10 +217,8 @@ class DirectHciTest(GdBaseTestClass): self.dut_hci.send_command_with_complete( hci_packets.LeSetExtendedAdvertisingDataBuilder( - advertising_handle, - hci_packets.Operation.COMPLETE_ADVERTISEMENT, - hci_packets.FragmentPreference.CONTROLLER_SHOULD_NOT, - [gap_name])) + advertising_handle, hci_packets.Operation.COMPLETE_ADVERTISEMENT, + hci_packets.FragmentPreference.CONTROLLER_SHOULD_NOT, [gap_name])) gap_short_name = hci_packets.GapData() gap_short_name.data_type = hci_packets.GapDataType.SHORTENED_LOCAL_NAME @@ -258,61 +226,44 @@ class DirectHciTest(GdBaseTestClass): self.dut_hci.send_command_with_complete( hci_packets.LeSetExtendedAdvertisingScanResponseBuilder( - advertising_handle, - hci_packets.Operation.COMPLETE_ADVERTISEMENT, - hci_packets.FragmentPreference.CONTROLLER_SHOULD_NOT, - [gap_short_name])) + advertising_handle, hci_packets.Operation.COMPLETE_ADVERTISEMENT, + hci_packets.FragmentPreference.CONTROLLER_SHOULD_NOT, [gap_short_name])) enabled_set = hci_packets.EnabledSet() enabled_set.advertising_handle = advertising_handle enabled_set.duration = 0 enabled_set.max_extended_advertising_events = 0 self.dut_hci.send_command_with_complete( - hci_packets.LeSetExtendedAdvertisingEnableBuilder( - hci_packets.Enable.ENABLED, [enabled_set])) + hci_packets.LeSetExtendedAdvertisingEnableBuilder(hci_packets.Enable.ENABLED, [enabled_set])) # Check for success of Enable assertThat(self.dut_hci.get_event_stream()).emits( - HciMatchers.CommandComplete( - hci_packets.OpCode.LE_SET_EXTENDED_ADVERTISING_ENABLE)) + HciMatchers.CommandComplete(hci_packets.OpCode.LE_SET_EXTENDED_ADVERTISING_ENABLE)) (dut_handle, cert_handle) = self._verify_le_connection_complete() # Send ACL Data - self.enqueue_acl_data( - dut_handle, - hci_packets.PacketBoundaryFlag.FIRST_NON_AUTOMATICALLY_FLUSHABLE, - hci_packets.BroadcastFlag.POINT_TO_POINT, - bytes(b'Just SomeAclData')) - self.send_hal_acl_data( - cert_handle, - hci_packets.PacketBoundaryFlag.FIRST_NON_AUTOMATICALLY_FLUSHABLE, - hci_packets.BroadcastFlag.POINT_TO_POINT, - bytes(b'Just SomeMoreAclData')) + self.enqueue_acl_data(dut_handle, hci_packets.PacketBoundaryFlag.FIRST_NON_AUTOMATICALLY_FLUSHABLE, + hci_packets.BroadcastFlag.POINT_TO_POINT, bytes(b'Just SomeAclData')) + self.send_hal_acl_data(cert_handle, hci_packets.PacketBoundaryFlag.FIRST_NON_AUTOMATICALLY_FLUSHABLE, + hci_packets.BroadcastFlag.POINT_TO_POINT, bytes(b'Just SomeMoreAclData')) assertThat(self.cert_hal.get_acl_stream()).emits( - lambda packet: logging.debug(packet.payload) or b'SomeAclData' in packet.payload - ) + lambda packet: logging.debug(packet.payload) or b'SomeAclData' in packet.payload) assertThat(self.dut_hci.get_raw_acl_stream()).emits( - lambda packet: logging.debug(packet.data) or b'SomeMoreAclData' in packet.data - ) + lambda packet: logging.debug(packet.data) or b'SomeMoreAclData' in packet.data) def test_le_white_list_connection_cert_advertises(self): - self.dut_hci.register_for_le_events( - hci_packets.SubeventCode.CONNECTION_COMPLETE) + self.dut_hci.register_for_le_events(hci_packets.SubeventCode.CONNECTION_COMPLETE) # DUT Connects + self.dut_hci.send_command_with_complete(hci_packets.LeSetRandomAddressBuilder('0D:05:04:03:02:01')) self.dut_hci.send_command_with_complete( - hci_packets.LeSetRandomAddressBuilder('0D:05:04:03:02:01')) - self.dut_hci.send_command_with_complete( - hci_packets.LeAddDeviceToWhiteListBuilder( - hci_packets.WhiteListAddressType.RANDOM, '0C:05:04:03:02:01')) + hci_packets.LeAddDeviceToWhiteListBuilder(hci_packets.WhiteListAddressType.RANDOM, '0C:05:04:03:02:01')) phy_scan_params = DirectHciTest._create_phy_scan_params() self.dut_hci.send_command_with_status( hci_packets.LeExtendedCreateConnectionBuilder( - hci_packets.InitiatorFilterPolicy.USE_WHITE_LIST, - hci_packets.OwnAddressType.RANDOM_DEVICE_ADDRESS, - hci_packets.AddressType.RANDOM_DEVICE_ADDRESS, - 'BA:D5:A4:A3:A2:A1', 1, [phy_scan_params])) + hci_packets.InitiatorFilterPolicy.USE_WHITE_LIST, hci_packets.OwnAddressType.RANDOM_DEVICE_ADDRESS, + hci_packets.AddressType.RANDOM_DEVICE_ADDRESS, 'BA:D5:A4:A3:A2:A1', 1, [phy_scan_params])) # CERT Advertises advertising_handle = 1 @@ -333,8 +284,7 @@ class DirectHciTest(GdBaseTestClass): )) self.send_hal_hci_command( - hci_packets.LeSetExtendedAdvertisingRandomAddressBuilder( - advertising_handle, '0C:05:04:03:02:01')) + hci_packets.LeSetExtendedAdvertisingRandomAddressBuilder(advertising_handle, '0C:05:04:03:02:01')) gap_name = hci_packets.GapData() gap_name.data_type = hci_packets.GapDataType.COMPLETE_LOCAL_NAME @@ -342,52 +292,40 @@ class DirectHciTest(GdBaseTestClass): self.send_hal_hci_command( hci_packets.LeSetExtendedAdvertisingDataBuilder( - advertising_handle, - hci_packets.Operation.COMPLETE_ADVERTISEMENT, - hci_packets.FragmentPreference.CONTROLLER_SHOULD_NOT, - [gap_name])) + advertising_handle, hci_packets.Operation.COMPLETE_ADVERTISEMENT, + hci_packets.FragmentPreference.CONTROLLER_SHOULD_NOT, [gap_name])) enabled_set = hci_packets.EnabledSet() enabled_set.advertising_handle = 1 enabled_set.duration = 0 enabled_set.max_extended_advertising_events = 0 self.send_hal_hci_command( - hci_packets.LeSetExtendedAdvertisingEnableBuilder( - hci_packets.Enable.ENABLED, [enabled_set])) + hci_packets.LeSetExtendedAdvertisingEnableBuilder(hci_packets.Enable.ENABLED, [enabled_set])) # LeConnectionComplete self._verify_le_connection_complete() def _verify_connection_complete(self): - cert_connection_complete_capture = HalCaptures.ConnectionCompleteCapture( - ) - assertThat(self.cert_hal.get_hci_event_stream()).emits( - cert_connection_complete_capture) - cert_handle = cert_connection_complete_capture.get( - ).GetConnectionHandle() - - dut_connection_complete_capture = HciCaptures.ConnectionCompleteCapture( - ) - assertThat(self.dut_hci.get_event_stream()).emits( - dut_connection_complete_capture) + cert_connection_complete_capture = HalCaptures.ConnectionCompleteCapture() + assertThat(self.cert_hal.get_hci_event_stream()).emits(cert_connection_complete_capture) + cert_handle = cert_connection_complete_capture.get().GetConnectionHandle() + + dut_connection_complete_capture = HciCaptures.ConnectionCompleteCapture() + assertThat(self.dut_hci.get_event_stream()).emits(dut_connection_complete_capture) dut_handle = dut_connection_complete_capture.get().GetConnectionHandle() return (dut_handle, cert_handle) def test_connection_dut_connects(self): - self.dut_hci.send_command_with_complete( - hci_packets.WritePageTimeoutBuilder(0x4000)) + self.dut_hci.send_command_with_complete(hci_packets.WritePageTimeoutBuilder(0x4000)) # CERT Enables scans and gets its address self.send_hal_hci_command(hci_packets.ReadBdAddrBuilder()) cert_read_bd_addr_capture = HalCaptures.ReadBdAddrCompleteCapture() - assertThat(self.cert_hal.get_hci_event_stream()).emits( - cert_read_bd_addr_capture) + assertThat(self.cert_hal.get_hci_event_stream()).emits(cert_read_bd_addr_capture) address = cert_read_bd_addr_capture.get().GetBdAddr() - self.send_hal_hci_command( - hci_packets.WriteScanEnableBuilder( - hci_packets.ScanEnable.INQUIRY_AND_PAGE_SCAN)) + self.send_hal_hci_command(hci_packets.WriteScanEnableBuilder(hci_packets.ScanEnable.INQUIRY_AND_PAGE_SCAN)) # DUT Connects self.dut_hci.send_command_with_status( @@ -401,40 +339,29 @@ class DirectHciTest(GdBaseTestClass): # Cert Accepts connect_request_capture = HalCaptures.ConnectionRequestCapture() - assertThat(self.cert_hal.get_hci_event_stream()).emits( - connect_request_capture, timeout=timedelta(seconds=20)) + assertThat(self.cert_hal.get_hci_event_stream()).emits(connect_request_capture, timeout=timedelta(seconds=20)) connection_request = connect_request_capture.get() self.send_hal_hci_command( - hci_packets.AcceptConnectionRequestBuilder( - connection_request.GetBdAddr(), - hci_packets.AcceptConnectionRequestRole.REMAIN_SLAVE)) + hci_packets.AcceptConnectionRequestBuilder(connection_request.GetBdAddr(), + hci_packets.AcceptConnectionRequestRole.REMAIN_SLAVE)) (dut_handle, cert_handle) = self._verify_connection_complete() # Send ACL Data - self.enqueue_acl_data( - dut_handle, - hci_packets.PacketBoundaryFlag.FIRST_NON_AUTOMATICALLY_FLUSHABLE, - hci_packets.BroadcastFlag.POINT_TO_POINT, - bytes(b'Just SomeAclData')) - self.send_hal_acl_data( - cert_handle, - hci_packets.PacketBoundaryFlag.FIRST_NON_AUTOMATICALLY_FLUSHABLE, - hci_packets.BroadcastFlag.POINT_TO_POINT, - bytes(b'Just SomeMoreAclData')) + self.enqueue_acl_data(dut_handle, hci_packets.PacketBoundaryFlag.FIRST_NON_AUTOMATICALLY_FLUSHABLE, + hci_packets.BroadcastFlag.POINT_TO_POINT, bytes(b'Just SomeAclData')) + self.send_hal_acl_data(cert_handle, hci_packets.PacketBoundaryFlag.FIRST_NON_AUTOMATICALLY_FLUSHABLE, + hci_packets.BroadcastFlag.POINT_TO_POINT, bytes(b'Just SomeMoreAclData')) - assertThat(self.cert_hal.get_acl_stream()).emits( - lambda packet: b'SomeAclData' in packet.payload) - assertThat(self.dut_hci.get_raw_acl_stream()).emits( - lambda packet: b'SomeMoreAclData' in packet.data) + assertThat(self.cert_hal.get_acl_stream()).emits(lambda packet: b'SomeAclData' in packet.payload) + assertThat(self.dut_hci.get_raw_acl_stream()).emits(lambda packet: b'SomeMoreAclData' in packet.data) def test_connection_cert_connects(self): self.send_hal_hci_command(hci_packets.WritePageTimeoutBuilder(0x4000)) # DUT Enables scans and gets its address self.dut_hci.send_command_with_complete( - hci_packets.WriteScanEnableBuilder( - hci_packets.ScanEnable.INQUIRY_AND_PAGE_SCAN)) + hci_packets.WriteScanEnableBuilder(hci_packets.ScanEnable.INQUIRY_AND_PAGE_SCAN)) self.dut_hci.send_command_with_complete(hci_packets.ReadBdAddrBuilder()) read_bd_addr_capture = HciCaptures.ReadBdAddrCompleteCapture() @@ -453,29 +380,19 @@ class DirectHciTest(GdBaseTestClass): # DUT Accepts connection_request_capture = HciCaptures.ConnectionRequestCapture() - assertThat(self.dut_hci.get_event_stream()).emits( - connection_request_capture, timeout=timedelta(seconds=20)) + assertThat(self.dut_hci.get_event_stream()).emits(connection_request_capture, timeout=timedelta(seconds=20)) connection_request = connection_request_capture.get() self.dut_hci.send_command_with_status( - hci_packets.AcceptConnectionRequestBuilder( - connection_request.GetBdAddr(), - hci_packets.AcceptConnectionRequestRole.REMAIN_SLAVE)) + hci_packets.AcceptConnectionRequestBuilder(connection_request.GetBdAddr(), + hci_packets.AcceptConnectionRequestRole.REMAIN_SLAVE)) (dut_handle, cert_handle) = self._verify_connection_complete() # Send ACL Data - self.enqueue_acl_data( - dut_handle, - hci_packets.PacketBoundaryFlag.FIRST_NON_AUTOMATICALLY_FLUSHABLE, - hci_packets.BroadcastFlag.POINT_TO_POINT, - bytes(b'This is just SomeAclData')) - self.send_hal_acl_data( - cert_handle, - hci_packets.PacketBoundaryFlag.FIRST_NON_AUTOMATICALLY_FLUSHABLE, - hci_packets.BroadcastFlag.POINT_TO_POINT, - bytes(b'This is just SomeMoreAclData')) + self.enqueue_acl_data(dut_handle, hci_packets.PacketBoundaryFlag.FIRST_NON_AUTOMATICALLY_FLUSHABLE, + hci_packets.BroadcastFlag.POINT_TO_POINT, bytes(b'This is just SomeAclData')) + self.send_hal_acl_data(cert_handle, hci_packets.PacketBoundaryFlag.FIRST_NON_AUTOMATICALLY_FLUSHABLE, + hci_packets.BroadcastFlag.POINT_TO_POINT, bytes(b'This is just SomeMoreAclData')) - assertThat(self.cert_hal.get_acl_stream()).emits( - lambda packet: b'SomeAclData' in packet.payload) - assertThat(self.dut_hci.get_raw_acl_stream()).emits( - lambda packet: b'SomeMoreAclData' in packet.data) + assertThat(self.cert_hal.get_acl_stream()).emits(lambda packet: b'SomeAclData' in packet.payload) + assertThat(self.dut_hci.get_raw_acl_stream()).emits(lambda packet: b'SomeMoreAclData' in packet.data) diff --git a/system/gd/hci/cert/le_acl_manager_test.py b/system/gd/hci/cert/le_acl_manager_test.py index de1efe05e8..cba3b6f976 100644 --- a/system/gd/hci/cert/le_acl_manager_test.py +++ b/system/gd/hci/cert/le_acl_manager_test.py @@ -34,23 +34,17 @@ class LeAclManagerTest(GdBaseTestClass): def setup_test(self): super().setup_test() dut_address = common.BluetoothAddressWithType( - address=common.BluetoothAddress( - address=bytes(b'0D:05:04:03:02:01')), - type=common.RANDOM_DEVICE_ADDRESS) + address=common.BluetoothAddress(address=bytes(b'0D:05:04:03:02:01')), type=common.RANDOM_DEVICE_ADDRESS) self.dut.hci_le_acl_manager.SetInitiatorAddress(dut_address) private_policy = le_acl_manager_facade.PrivacyPolicy( - address_policy=le_acl_manager_facade.AddressPolicy. - USE_RESOLVABLE_ADDRESS, + address_policy=le_acl_manager_facade.AddressPolicy.USE_RESOLVABLE_ADDRESS, address_with_type=common.BluetoothAddressWithType( - address=common.BluetoothAddress( - address=bytes(b'00:00:00:00:00:00')), + address=common.BluetoothAddress(address=bytes(b'00:00:00:00:00:00')), type=common.RANDOM_DEVICE_ADDRESS), - rotation_irk= - b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + rotation_irk=b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', minimum_rotation_time=(7 * 60 * 1000), maximum_rotation_time=(15 * 60 * 1000)) - self.dut.hci_le_acl_manager.SetPrivacyPolicyForInitiatorAddress( - private_policy) + self.dut.hci_le_acl_manager.SetPrivacyPolicyForInitiatorAddress(private_policy) def register_for_event(self, event_code): msg = hci_facade.EventCodeMsg(code=int(event_code)) @@ -70,10 +64,7 @@ class LeAclManagerTest(GdBaseTestClass): def enqueue_acl_data(self, handle, pb_flag, b_flag, acl): acl_msg = hci_facade.AclMsg( - handle=int(handle), - packet_boundary_flag=int(pb_flag), - broadcast_flag=int(b_flag), - data=acl) + handle=int(handle), packet_boundary_flag=int(pb_flag), broadcast_flag=int(b_flag), data=acl) self.cert.hci.SendAclData(acl_msg) def test_dut_connects(self): @@ -92,8 +83,7 @@ class LeAclManagerTest(GdBaseTestClass): 450, 7, hci_packets.OwnAddressType.RANDOM_DEVICE_ADDRESS, - hci_packets.PeerAddressType. - PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, + hci_packets.PeerAddressType.PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, '00:00:00:00:00:00', hci_packets.AdvertisingFilterPolicy.ALL_DEVICES, 0xF8, @@ -103,8 +93,7 @@ class LeAclManagerTest(GdBaseTestClass): True) self.enqueue_hci_command( - hci_packets.LeSetExtendedAdvertisingRandomAddressBuilder( - advertising_handle, '0C:05:04:03:02:01'), True) + hci_packets.LeSetExtendedAdvertisingRandomAddressBuilder(advertising_handle, '0C:05:04:03:02:01'), True) gap_name = hci_packets.GapData() gap_name.data_type = hci_packets.GapDataType.COMPLETE_LOCAL_NAME @@ -112,10 +101,8 @@ class LeAclManagerTest(GdBaseTestClass): self.enqueue_hci_command( hci_packets.LeSetExtendedAdvertisingDataBuilder( - advertising_handle, - hci_packets.Operation.COMPLETE_ADVERTISEMENT, - hci_packets.FragmentPreference.CONTROLLER_SHOULD_NOT, - [gap_name]), True) + advertising_handle, hci_packets.Operation.COMPLETE_ADVERTISEMENT, + hci_packets.FragmentPreference.CONTROLLER_SHOULD_NOT, [gap_name]), True) gap_short_name = hci_packets.GapData() gap_short_name.data_type = hci_packets.GapDataType.SHORTENED_LOCAL_NAME @@ -123,26 +110,21 @@ class LeAclManagerTest(GdBaseTestClass): self.enqueue_hci_command( hci_packets.LeSetExtendedAdvertisingScanResponseBuilder( - advertising_handle, - hci_packets.Operation.COMPLETE_ADVERTISEMENT, - hci_packets.FragmentPreference.CONTROLLER_SHOULD_NOT, - [gap_short_name]), True) + advertising_handle, hci_packets.Operation.COMPLETE_ADVERTISEMENT, + hci_packets.FragmentPreference.CONTROLLER_SHOULD_NOT, [gap_short_name]), True) enabled_set = hci_packets.EnabledSet() enabled_set.advertising_handle = advertising_handle enabled_set.duration = 0 enabled_set.max_extended_advertising_events = 0 self.enqueue_hci_command( - hci_packets.LeSetExtendedAdvertisingEnableBuilder( - hci_packets.Enable.ENABLED, [enabled_set]), True) + hci_packets.LeSetExtendedAdvertisingEnableBuilder(hci_packets.Enable.ENABLED, [enabled_set]), True) with EventStream( self.dut.hci_le_acl_manager.CreateConnection( le_acl_manager_facade.LeConnectionMsg( - address_type=int( - hci_packets.AddressType.RANDOM_DEVICE_ADDRESS), - address=bytes('0C:05:04:03:02:01', - 'utf8')))) as connection_event_stream: + address_type=int(hci_packets.AddressType.RANDOM_DEVICE_ADDRESS), + address=bytes('0C:05:04:03:02:01', 'utf8')))) as connection_event_stream: # Cert gets ConnectionComplete with a handle and sends ACL data handle = 0xfff @@ -153,17 +135,13 @@ class LeAclManagerTest(GdBaseTestClass): if b'\x3e\x13\x01\x00' in packet_bytes: cc_view = hci_packets.LeConnectionCompleteView( hci_packets.LeMetaEventView( - hci_packets.EventPacketView( - bt_packets.PacketViewLittleEndian( - list(packet_bytes))))) + hci_packets.EventPacketView(bt_packets.PacketViewLittleEndian(list(packet_bytes))))) handle = cc_view.GetConnectionHandle() return True if b'\x3e\x13\x0A\x00' in packet_bytes: cc_view = hci_packets.LeEnhancedConnectionCompleteView( hci_packets.LeMetaEventView( - hci_packets.EventPacketView( - bt_packets.PacketViewLittleEndian( - list(packet_bytes))))) + hci_packets.EventPacketView(bt_packets.PacketViewLittleEndian(list(packet_bytes))))) handle = cc_view.GetConnectionHandle() return True return False @@ -171,11 +149,9 @@ class LeAclManagerTest(GdBaseTestClass): cert_hci_le_event_stream.assert_event_occurs(get_handle) cert_handle = handle - self.enqueue_acl_data( - cert_handle, hci_packets.PacketBoundaryFlag. - FIRST_AUTOMATICALLY_FLUSHABLE, - hci_packets.BroadcastFlag.POINT_TO_POINT, - bytes(b'\x19\x00\x07\x00SomeAclData from the Cert')) + self.enqueue_acl_data(cert_handle, hci_packets.PacketBoundaryFlag.FIRST_AUTOMATICALLY_FLUSHABLE, + hci_packets.BroadcastFlag.POINT_TO_POINT, + bytes(b'\x19\x00\x07\x00SomeAclData from the Cert')) # DUT gets a connection complete event and sends and receives handle = 0xfff @@ -183,14 +159,10 @@ class LeAclManagerTest(GdBaseTestClass): self.dut.hci_le_acl_manager.SendAclData( le_acl_manager_facade.LeAclData( - handle=handle, - payload=bytes( - b'\x1C\x00\x07\x00SomeMoreAclData from the DUT'))) + handle=handle, payload=bytes(b'\x1C\x00\x07\x00SomeMoreAclData from the DUT'))) - cert_acl_data_stream.assert_event_occurs( - lambda packet: b'SomeMoreAclData' in packet.data) - acl_data_stream.assert_event_occurs( - lambda packet: b'SomeAclData' in packet.payload) + cert_acl_data_stream.assert_event_occurs(lambda packet: b'SomeMoreAclData' in packet.data) + acl_data_stream.assert_event_occurs(lambda packet: b'SomeAclData' in packet.payload) def test_cert_connects(self): self.register_for_le_event(hci_packets.SubeventCode.CONNECTION_COMPLETE) @@ -203,32 +175,24 @@ class LeAclManagerTest(GdBaseTestClass): gap_name = hci_packets.GapData() gap_name.data_type = hci_packets.GapDataType.COMPLETE_LOCAL_NAME gap_name.data = list(bytes(b'Im_The_DUT')) - gap_data = le_advertising_facade.GapDataMsg( - data=bytes(gap_name.Serialize())) + gap_data = le_advertising_facade.GapDataMsg(data=bytes(gap_name.Serialize())) config = le_advertising_facade.AdvertisingConfig( advertisement=[gap_data], - random_address=common.BluetoothAddress( - address=bytes(b'0D:05:04:03:02:01')), + random_address=common.BluetoothAddress(address=bytes(b'0D:05:04:03:02:01')), interval_min=512, interval_max=768, event_type=le_advertising_facade.AdvertisingEventType.ADV_IND, address_type=common.RANDOM_DEVICE_ADDRESS, peer_address_type=common.PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - peer_address=common.BluetoothAddress( - address=bytes(b'A6:A5:A4:A3:A2:A1')), + peer_address=common.BluetoothAddress(address=bytes(b'A6:A5:A4:A3:A2:A1')), channel_map=7, - filter_policy=le_advertising_facade.AdvertisingFilterPolicy. - ALL_DEVICES) - request = le_advertising_facade.CreateAdvertiserRequest( - config=config) + filter_policy=le_advertising_facade.AdvertisingFilterPolicy.ALL_DEVICES) + request = le_advertising_facade.CreateAdvertiserRequest(config=config) - create_response = self.dut.hci_le_advertising_manager.CreateAdvertiser( - request) + create_response = self.dut.hci_le_advertising_manager.CreateAdvertiser(request) # Cert Connects - self.enqueue_hci_command( - hci_packets.LeSetRandomAddressBuilder('0C:05:04:03:02:01'), - True) + self.enqueue_hci_command(hci_packets.LeSetRandomAddressBuilder('0C:05:04:03:02:01'), True) phy_scan_params = hci_packets.LeCreateConnPhyScanParameters() phy_scan_params.scan_interval = 0x60 phy_scan_params.scan_window = 0x30 @@ -239,11 +203,10 @@ class LeAclManagerTest(GdBaseTestClass): phy_scan_params.min_ce_length = 0 phy_scan_params.max_ce_length = 0 self.enqueue_hci_command( - hci_packets.LeExtendedCreateConnectionBuilder( - hci_packets.InitiatorFilterPolicy.USE_PEER_ADDRESS, - hci_packets.OwnAddressType.RANDOM_DEVICE_ADDRESS, - hci_packets.AddressType.RANDOM_DEVICE_ADDRESS, - '0D:05:04:03:02:01', 1, [phy_scan_params]), False) + hci_packets.LeExtendedCreateConnectionBuilder(hci_packets.InitiatorFilterPolicy.USE_PEER_ADDRESS, + hci_packets.OwnAddressType.RANDOM_DEVICE_ADDRESS, + hci_packets.AddressType.RANDOM_DEVICE_ADDRESS, + '0D:05:04:03:02:01', 1, [phy_scan_params]), False) # Cert gets ConnectionComplete with a handle and sends ACL data handle = 0xfff @@ -254,17 +217,13 @@ class LeAclManagerTest(GdBaseTestClass): if b'\x3e\x13\x01\x00' in packet_bytes: cc_view = hci_packets.LeConnectionCompleteView( hci_packets.LeMetaEventView( - hci_packets.EventPacketView( - bt_packets.PacketViewLittleEndian( - list(packet_bytes))))) + hci_packets.EventPacketView(bt_packets.PacketViewLittleEndian(list(packet_bytes))))) handle = cc_view.GetConnectionHandle() return True if b'\x3e\x13\x0A\x00' in packet_bytes: cc_view = hci_packets.LeEnhancedConnectionCompleteView( hci_packets.LeMetaEventView( - hci_packets.EventPacketView( - bt_packets.PacketViewLittleEndian( - list(packet_bytes))))) + hci_packets.EventPacketView(bt_packets.PacketViewLittleEndian(list(packet_bytes))))) handle = cc_view.GetConnectionHandle() return True return False @@ -272,11 +231,9 @@ class LeAclManagerTest(GdBaseTestClass): cert_hci_le_event_stream.assert_event_occurs(get_handle) cert_handle = handle - self.enqueue_acl_data( - cert_handle, - hci_packets.PacketBoundaryFlag.FIRST_AUTOMATICALLY_FLUSHABLE, - hci_packets.BroadcastFlag.POINT_TO_POINT, - bytes(b'\x19\x00\x07\x00SomeAclData from the Cert')) + self.enqueue_acl_data(cert_handle, hci_packets.PacketBoundaryFlag.FIRST_AUTOMATICALLY_FLUSHABLE, + hci_packets.BroadcastFlag.POINT_TO_POINT, + bytes(b'\x19\x00\x07\x00SomeAclData from the Cert')) # DUT gets a connection complete event and sends and receives handle = 0xfff @@ -284,14 +241,10 @@ class LeAclManagerTest(GdBaseTestClass): self.dut.hci_le_acl_manager.SendAclData( le_acl_manager_facade.LeAclData( - handle=handle, - payload=bytes( - b'\x1C\x00\x07\x00SomeMoreAclData from the DUT'))) + handle=handle, payload=bytes(b'\x1C\x00\x07\x00SomeMoreAclData from the DUT'))) - cert_acl_data_stream.assert_event_occurs( - lambda packet: b'SomeMoreAclData' in packet.data) - acl_data_stream.assert_event_occurs( - lambda packet: b'SomeAclData' in packet.payload) + cert_acl_data_stream.assert_event_occurs(lambda packet: b'SomeMoreAclData' in packet.data) + acl_data_stream.assert_event_occurs(lambda packet: b'SomeAclData' in packet.payload) def test_recombination_l2cap_packet(self): self.register_for_le_event(hci_packets.SubeventCode.CONNECTION_COMPLETE) @@ -309,8 +262,7 @@ class LeAclManagerTest(GdBaseTestClass): 450, 7, hci_packets.OwnAddressType.RANDOM_DEVICE_ADDRESS, - hci_packets.PeerAddressType. - PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, + hci_packets.PeerAddressType.PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, '00:00:00:00:00:00', hci_packets.AdvertisingFilterPolicy.ALL_DEVICES, 0xF8, @@ -320,8 +272,7 @@ class LeAclManagerTest(GdBaseTestClass): True) self.enqueue_hci_command( - hci_packets.LeSetExtendedAdvertisingRandomAddressBuilder( - advertising_handle, '0C:05:04:03:02:01'), True) + hci_packets.LeSetExtendedAdvertisingRandomAddressBuilder(advertising_handle, '0C:05:04:03:02:01'), True) gap_name = hci_packets.GapData() gap_name.data_type = hci_packets.GapDataType.COMPLETE_LOCAL_NAME @@ -329,10 +280,8 @@ class LeAclManagerTest(GdBaseTestClass): self.enqueue_hci_command( hci_packets.LeSetExtendedAdvertisingDataBuilder( - advertising_handle, - hci_packets.Operation.COMPLETE_ADVERTISEMENT, - hci_packets.FragmentPreference.CONTROLLER_SHOULD_NOT, - [gap_name]), True) + advertising_handle, hci_packets.Operation.COMPLETE_ADVERTISEMENT, + hci_packets.FragmentPreference.CONTROLLER_SHOULD_NOT, [gap_name]), True) gap_short_name = hci_packets.GapData() gap_short_name.data_type = hci_packets.GapDataType.SHORTENED_LOCAL_NAME @@ -340,26 +289,21 @@ class LeAclManagerTest(GdBaseTestClass): self.enqueue_hci_command( hci_packets.LeSetExtendedAdvertisingScanResponseBuilder( - advertising_handle, - hci_packets.Operation.COMPLETE_ADVERTISEMENT, - hci_packets.FragmentPreference.CONTROLLER_SHOULD_NOT, - [gap_short_name]), True) + advertising_handle, hci_packets.Operation.COMPLETE_ADVERTISEMENT, + hci_packets.FragmentPreference.CONTROLLER_SHOULD_NOT, [gap_short_name]), True) enabled_set = hci_packets.EnabledSet() enabled_set.advertising_handle = advertising_handle enabled_set.duration = 0 enabled_set.max_extended_advertising_events = 0 self.enqueue_hci_command( - hci_packets.LeSetExtendedAdvertisingEnableBuilder( - hci_packets.Enable.ENABLED, [enabled_set]), True) + hci_packets.LeSetExtendedAdvertisingEnableBuilder(hci_packets.Enable.ENABLED, [enabled_set]), True) with EventStream( self.dut.hci_le_acl_manager.CreateConnection( le_acl_manager_facade.LeConnectionMsg( - address_type=int( - hci_packets.AddressType.RANDOM_DEVICE_ADDRESS), - address=bytes('0C:05:04:03:02:01', - 'utf8')))) as connection_event_stream: + address_type=int(hci_packets.AddressType.RANDOM_DEVICE_ADDRESS), + address=bytes('0C:05:04:03:02:01', 'utf8')))) as connection_event_stream: # Cert gets ConnectionComplete with a handle and sends ACL data handle = 0xfff @@ -370,17 +314,13 @@ class LeAclManagerTest(GdBaseTestClass): if b'\x3e\x13\x01\x00' in packet_bytes: cc_view = hci_packets.LeConnectionCompleteView( hci_packets.LeMetaEventView( - hci_packets.EventPacketView( - bt_packets.PacketViewLittleEndian( - list(packet_bytes))))) + hci_packets.EventPacketView(bt_packets.PacketViewLittleEndian(list(packet_bytes))))) handle = cc_view.GetConnectionHandle() return True if b'\x3e\x13\x0A\x00' in packet_bytes: cc_view = hci_packets.LeEnhancedConnectionCompleteView( hci_packets.LeMetaEventView( - hci_packets.EventPacketView( - bt_packets.PacketViewLittleEndian( - list(packet_bytes))))) + hci_packets.EventPacketView(bt_packets.PacketViewLittleEndian(list(packet_bytes))))) handle = cc_view.GetConnectionHandle() return True return False @@ -391,15 +331,9 @@ class LeAclManagerTest(GdBaseTestClass): # DUT gets a connection complete event connection_event_stream.assert_event_occurs(get_handle) - self.enqueue_acl_data( - cert_handle, hci_packets.PacketBoundaryFlag. - FIRST_AUTOMATICALLY_FLUSHABLE, - hci_packets.BroadcastFlag.POINT_TO_POINT, - bytes(b'\x06\x00\x07\x00Hello')) - self.enqueue_acl_data( - cert_handle, - hci_packets.PacketBoundaryFlag.CONTINUING_FRAGMENT, - hci_packets.BroadcastFlag.POINT_TO_POINT, bytes(b'!')) - - acl_data_stream.assert_event_occurs( - lambda packet: b'Hello!' in packet.payload) + self.enqueue_acl_data(cert_handle, hci_packets.PacketBoundaryFlag.FIRST_AUTOMATICALLY_FLUSHABLE, + hci_packets.BroadcastFlag.POINT_TO_POINT, bytes(b'\x06\x00\x07\x00Hello')) + self.enqueue_acl_data(cert_handle, hci_packets.PacketBoundaryFlag.CONTINUING_FRAGMENT, + hci_packets.BroadcastFlag.POINT_TO_POINT, bytes(b'!')) + + acl_data_stream.assert_event_occurs(lambda packet: b'Hello!' in packet.payload) diff --git a/system/gd/hci/cert/le_advertising_manager_test.py b/system/gd/hci/cert/le_advertising_manager_test.py index 722fb10d8a..c7bb2afb5a 100644 --- a/system/gd/hci/cert/le_advertising_manager_test.py +++ b/system/gd/hci/cert/le_advertising_manager_test.py @@ -52,62 +52,46 @@ class LeAdvertisingManagerTest(GdBaseTestClass): def test_le_ad_scan_dut_advertises(self): self.register_for_le_event(hci_packets.SubeventCode.ADVERTISING_REPORT) - self.register_for_le_event( - hci_packets.SubeventCode.EXTENDED_ADVERTISING_REPORT) - with EventStream(self.cert.hci.FetchLeSubevents( - empty_proto.Empty())) as hci_le_event_stream: + self.register_for_le_event(hci_packets.SubeventCode.EXTENDED_ADVERTISING_REPORT) + with EventStream(self.cert.hci.FetchLeSubevents(empty_proto.Empty())) as hci_le_event_stream: # CERT Scans - self.enqueue_hci_command( - hci_packets.LeSetRandomAddressBuilder('0C:05:04:03:02:01'), - True) + self.enqueue_hci_command(hci_packets.LeSetRandomAddressBuilder('0C:05:04:03:02:01'), True) scan_parameters = hci_packets.PhyScanParameters() scan_parameters.le_scan_type = hci_packets.LeScanType.ACTIVE scan_parameters.le_scan_interval = 40 scan_parameters.le_scan_window = 20 self.enqueue_hci_command( - hci_packets.LeSetExtendedScanParametersBuilder( - hci_packets.AddressType.RANDOM_DEVICE_ADDRESS, - hci_packets.LeSetScanningFilterPolicy.ACCEPT_ALL, 1, - [scan_parameters]), True) + hci_packets.LeSetExtendedScanParametersBuilder(hci_packets.AddressType.RANDOM_DEVICE_ADDRESS, + hci_packets.LeSetScanningFilterPolicy.ACCEPT_ALL, 1, + [scan_parameters]), True) self.enqueue_hci_command( - hci_packets.LeSetExtendedScanEnableBuilder( - hci_packets.Enable.ENABLED, - hci_packets.FilterDuplicates.DISABLED, 0, 0), True) + hci_packets.LeSetExtendedScanEnableBuilder(hci_packets.Enable.ENABLED, + hci_packets.FilterDuplicates.DISABLED, 0, 0), True) # DUT Advertises gap_name = hci_packets.GapData() gap_name.data_type = hci_packets.GapDataType.COMPLETE_LOCAL_NAME gap_name.data = list(bytes(b'Im_The_DUT!')) - gap_data = le_advertising_facade.GapDataMsg( - data=bytes(gap_name.Serialize())) + gap_data = le_advertising_facade.GapDataMsg(data=bytes(gap_name.Serialize())) config = le_advertising_facade.AdvertisingConfig( advertisement=[gap_data], - random_address=common.BluetoothAddress( - address=bytes(b'0D:05:04:03:02:01')), + random_address=common.BluetoothAddress(address=bytes(b'0D:05:04:03:02:01')), interval_min=512, interval_max=768, event_type=le_advertising_facade.AdvertisingEventType.ADV_IND, address_type=common.RANDOM_DEVICE_ADDRESS, peer_address_type=common.PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - peer_address=common.BluetoothAddress( - address=bytes(b'A6:A5:A4:A3:A2:A1')), + peer_address=common.BluetoothAddress(address=bytes(b'A6:A5:A4:A3:A2:A1')), channel_map=7, - filter_policy=le_advertising_facade.AdvertisingFilterPolicy. - ALL_DEVICES) - request = le_advertising_facade.CreateAdvertiserRequest( - config=config) + filter_policy=le_advertising_facade.AdvertisingFilterPolicy.ALL_DEVICES) + request = le_advertising_facade.CreateAdvertiserRequest(config=config) - create_response = self.dut.hci_le_advertising_manager.CreateAdvertiser( - request) + create_response = self.dut.hci_le_advertising_manager.CreateAdvertiser(request) - hci_le_event_stream.assert_event_occurs( - lambda packet: b'Im_The_DUT' in packet.event) + hci_le_event_stream.assert_event_occurs(lambda packet: b'Im_The_DUT' in packet.event) - remove_request = le_advertising_facade.RemoveAdvertiserRequest( - advertiser_id=create_response.advertiser_id) + remove_request = le_advertising_facade.RemoveAdvertiserRequest(advertiser_id=create_response.advertiser_id) self.dut.hci_le_advertising_manager.RemoveAdvertiser(remove_request) self.enqueue_hci_command( - hci_packets.LeSetScanEnableBuilder(hci_packets.Enable.DISABLED, - hci_packets.Enable.DISABLED), - True) + hci_packets.LeSetScanEnableBuilder(hci_packets.Enable.DISABLED, hci_packets.Enable.DISABLED), True) diff --git a/system/gd/hci/cert/le_scanning_manager_test.py b/system/gd/hci/cert/le_scanning_manager_test.py index 41e4790b62..dbadc89068 100644 --- a/system/gd/hci/cert/le_scanning_manager_test.py +++ b/system/gd/hci/cert/le_scanning_manager_test.py @@ -32,8 +32,7 @@ from facade import common_pb2 as common class LeScanningManagerTest(GdBaseTestClass): def setup_class(self): - super().setup_class( - dut_module='HCI_INTERFACES', cert_module='HCI_INTERFACES') + super().setup_class(dut_module='HCI_INTERFACES', cert_module='HCI_INTERFACES') def register_for_event(self, event_code): msg = hci_facade.EventCodeMsg(code=int(event_code)) @@ -54,39 +53,29 @@ class LeScanningManagerTest(GdBaseTestClass): def test_le_ad_scan_dut_scans(self): with EventStream( # DUT Scans - self.dut.hci_le_scanning_manager.StartScan( - empty_proto.Empty())) as advertising_event_stream: + self.dut.hci_le_scanning_manager.StartScan(empty_proto.Empty())) as advertising_event_stream: # CERT Advertises gap_name = hci_packets.GapData() gap_name.data_type = hci_packets.GapDataType.COMPLETE_LOCAL_NAME gap_name.data = list(bytes(b'Im_The_CERT!')) - gap_data = le_advertising_facade.GapDataMsg( - data=bytes(gap_name.Serialize())) + gap_data = le_advertising_facade.GapDataMsg(data=bytes(gap_name.Serialize())) config = le_advertising_facade.AdvertisingConfig( advertisement=[gap_data], - random_address=common.BluetoothAddress( - address=bytes(b'A6:A5:A4:A3:A2:A1')), + random_address=common.BluetoothAddress(address=bytes(b'A6:A5:A4:A3:A2:A1')), interval_min=512, interval_max=768, event_type=le_advertising_facade.AdvertisingEventType.ADV_IND, address_type=common.RANDOM_DEVICE_ADDRESS, peer_address_type=common.PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - peer_address=common.BluetoothAddress( - address=bytes(b'0C:05:04:03:02:01')), + peer_address=common.BluetoothAddress(address=bytes(b'0C:05:04:03:02:01')), channel_map=7, - filter_policy=le_advertising_facade.AdvertisingFilterPolicy. - ALL_DEVICES) - request = le_advertising_facade.CreateAdvertiserRequest( - config=config) + filter_policy=le_advertising_facade.AdvertisingFilterPolicy.ALL_DEVICES) + request = le_advertising_facade.CreateAdvertiserRequest(config=config) - create_response = self.cert.hci_le_advertising_manager.CreateAdvertiser( - request) + create_response = self.cert.hci_le_advertising_manager.CreateAdvertiser(request) - advertising_event_stream.assert_event_occurs( - lambda packet: b'Im_The_CERT' in packet.event) + advertising_event_stream.assert_event_occurs(lambda packet: b'Im_The_CERT' in packet.event) - remove_request = le_advertising_facade.RemoveAdvertiserRequest( - advertiser_id=create_response.advertiser_id) - self.cert.hci_le_advertising_manager.RemoveAdvertiser( - remove_request) + remove_request = le_advertising_facade.RemoveAdvertiserRequest(advertiser_id=create_response.advertiser_id) + self.cert.hci_le_advertising_manager.RemoveAdvertiser(remove_request) diff --git a/system/gd/l2cap/classic/cert/cert_l2cap.py b/system/gd/l2cap/classic/cert/cert_l2cap.py index 88e902fbc3..e1141357da 100644 --- a/system/gd/l2cap/classic/cert/cert_l2cap.py +++ b/system/gd/l2cap/classic/cert/cert_l2cap.py @@ -38,14 +38,7 @@ from cert.captures import L2capCaptures class CertL2capChannel(IEventStream): - def __init__(self, - device, - scid, - dcid, - acl_stream, - acl, - control_channel, - fcs=None): + def __init__(self, device, scid, dcid, acl_stream, acl, control_channel, fcs=None): self._device = device self._scid = scid self._dcid = dcid @@ -55,11 +48,9 @@ class CertL2capChannel(IEventStream): self._config_rsp_received = False self._config_rsp_sent = False if fcs == l2cap_packets.FcsType.DEFAULT: - self._our_acl_view = FilteringEventStream( - acl_stream, L2capMatchers.ExtractBasicFrameWithFcs(scid)) + self._our_acl_view = FilteringEventStream(acl_stream, L2capMatchers.ExtractBasicFrameWithFcs(scid)) else: - self._our_acl_view = FilteringEventStream( - acl_stream, L2capMatchers.ExtractBasicFrame(scid)) + self._our_acl_view = FilteringEventStream(acl_stream, L2capMatchers.ExtractBasicFrame(scid)) def get_event_queue(self): return self._our_acl_view.get_event_queue() @@ -79,86 +70,63 @@ class CertL2capChannel(IEventStream): payload=None, fcs=False): if fcs == l2cap_packets.FcsType.DEFAULT: - frame = l2cap_packets.EnhancedInformationFrameWithFcsBuilder( - self._dcid, tx_seq, f, req_seq, sar, payload) + frame = l2cap_packets.EnhancedInformationFrameWithFcsBuilder(self._dcid, tx_seq, f, req_seq, sar, payload) else: - frame = l2cap_packets.EnhancedInformationFrameBuilder( - self._dcid, tx_seq, f, req_seq, sar, payload) + frame = l2cap_packets.EnhancedInformationFrameBuilder(self._dcid, tx_seq, f, req_seq, sar, payload) self._acl.send(frame.Serialize()) - def send_s_frame(self, - req_seq, - s=SupervisoryFunction.RECEIVER_READY, - p=Poll.NOT_SET, - f=Final.NOT_SET): - frame = l2cap_packets.EnhancedSupervisoryFrameBuilder( - self._dcid, s, p, f, req_seq) + def send_s_frame(self, req_seq, s=SupervisoryFunction.RECEIVER_READY, p=Poll.NOT_SET, f=Final.NOT_SET): + frame = l2cap_packets.EnhancedSupervisoryFrameBuilder(self._dcid, s, p, f, req_seq) self._acl.send(frame.Serialize()) def config_request_for_me(self): return L2capMatchers.ConfigurationRequest(self._scid) - def send_configure_request(self, - options, - sid=2, - continuation=l2cap_packets.Continuation.END): + def send_configure_request(self, options, sid=2, continuation=l2cap_packets.Continuation.END): assertThat(self._scid).isNotEqualTo(1) - request = l2cap_packets.ConfigurationRequestBuilder( - sid, self._dcid, continuation, options) + request = l2cap_packets.ConfigurationRequestBuilder(sid, self._dcid, continuation, options) self._control_channel.send(request) def _send_information_request(self, type): assertThat(self._scid).isEqualTo(1) signal_id = 3 - information_request = l2cap_packets.InformationRequestBuilder( - signal_id, type) + information_request = l2cap_packets.InformationRequestBuilder(signal_id, type) self.send(information_request) def send_extended_features_request(self): - self._send_information_request( - InformationRequestInfoType.EXTENDED_FEATURES_SUPPORTED) + self._send_information_request(InformationRequestInfoType.EXTENDED_FEATURES_SUPPORTED) - def verify_configuration_request_and_respond( - self, result=ConfigurationResponseResult.SUCCESS, options=None): + def verify_configuration_request_and_respond(self, result=ConfigurationResponseResult.SUCCESS, options=None): request_capture = L2capCaptures.ConfigurationRequest(self._scid) assertThat(self._control_channel).emits(request_capture) request = request_capture.get() sid = request.GetIdentifier() if options is None: options = [] - config_response = l2cap_packets.ConfigurationResponseBuilder( - sid, self._dcid, l2cap_packets.Continuation.END, result, options) + config_response = l2cap_packets.ConfigurationResponseBuilder(sid, self._dcid, l2cap_packets.Continuation.END, + result, options) self._control_channel.send(config_response) - def send_configuration_response(self, - request, - result=ConfigurationResponseResult.SUCCESS, - options=None): + def send_configuration_response(self, request, result=ConfigurationResponseResult.SUCCESS, options=None): sid = request.GetIdentifier() if options is None: options = [] - config_response = l2cap_packets.ConfigurationResponseBuilder( - sid, self._dcid, l2cap_packets.Continuation.END, result, options) + config_response = l2cap_packets.ConfigurationResponseBuilder(sid, self._dcid, l2cap_packets.Continuation.END, + result, options) self._control_channel.send(config_response) self._config_rsp_sent = True - def verify_configuration_response( - self, result=ConfigurationResponseResult.SUCCESS): - assertThat(self._control_channel).emits( - L2capMatchers.ConfigurationResponse(result)) + def verify_configuration_response(self, result=ConfigurationResponseResult.SUCCESS): + assertThat(self._control_channel).emits(L2capMatchers.ConfigurationResponse(result)) def disconnect_and_verify(self): assertThat(self._scid).isNotEqualTo(1) - self._control_channel.send( - l2cap_packets.DisconnectionRequestBuilder(1, self._dcid, - self._scid)) + self._control_channel.send(l2cap_packets.DisconnectionRequestBuilder(1, self._dcid, self._scid)) - assertThat(self._control_channel).emits( - L2capMatchers.DisconnectionResponse(self._scid, self._dcid)) + assertThat(self._control_channel).emits(L2capMatchers.DisconnectionResponse(self._scid, self._dcid)) def verify_disconnect_request(self): - assertThat(self._control_channel).emits( - L2capMatchers.DisconnectionRequest(self._dcid, self._scid)) + assertThat(self._control_channel).emits(L2capMatchers.DisconnectionRequest(self._dcid, self._scid)) class CertL2capControlChannelBehaviors(object): @@ -175,22 +143,16 @@ class CertL2capControlChannelBehaviors(object): def __init__(self, parent): self.parent = parent - def send_configuration_response( - self, result=ConfigurationResponseResult.SUCCESS, options=None): + def send_configuration_response(self, result=ConfigurationResponseResult.SUCCESS, options=None): self._commit(lambda request: self._send_configuration_response(request, result, options)) return self - def _send_configuration_response( - self, - request, - result=ConfigurationResponseResult.SUCCESS, - options=None): + def _send_configuration_response(self, request, result=ConfigurationResponseResult.SUCCESS, options=None): dcid = request.GetDestinationCid() if dcid not in self.parent.scid_to_channel: logging.warning("Received config request with unknown dcid") return - self.parent.scid_to_channel[dcid].send_configuration_response( - request, result, options) + self.parent.scid_to_channel[dcid].send_configuration_response(request, result, options) class CertL2cap(Closable, IHasBehaviors): @@ -201,20 +163,13 @@ class CertL2cap(Closable, IHasBehaviors): self._acl = None self.control_table = { - CommandCode.CONNECTION_RESPONSE: - self._on_connection_response_default, - CommandCode.CONFIGURATION_REQUEST: - self._on_configuration_request_default, - CommandCode.CONFIGURATION_RESPONSE: - self._on_configuration_response_default, - CommandCode.DISCONNECTION_REQUEST: - self._on_disconnection_request_default, - CommandCode.DISCONNECTION_RESPONSE: - self._on_disconnection_response_default, - CommandCode.INFORMATION_REQUEST: - self._on_information_request_default, - CommandCode.INFORMATION_RESPONSE: - self._on_information_response_default + CommandCode.CONNECTION_RESPONSE: self._on_connection_response_default, + CommandCode.CONFIGURATION_REQUEST: self._on_configuration_request_default, + CommandCode.CONFIGURATION_RESPONSE: self._on_configuration_response_default, + CommandCode.DISCONNECTION_REQUEST: self._on_disconnection_request_default, + CommandCode.DISCONNECTION_RESPONSE: self._on_disconnection_response_default, + CommandCode.INFORMATION_REQUEST: self._on_information_request_default, + CommandCode.INFORMATION_RESPONSE: self._on_information_response_default } self.scid_to_channel = {} @@ -223,8 +178,7 @@ class CertL2cap(Closable, IHasBehaviors): self.support_fcs = True self._control_behaviors = CertL2capControlChannelBehaviors(self) - self._control_behaviors.on_config_req_behavior.set_default( - self._send_configuration_response_default) + self._control_behaviors.on_config_req_behavior.set_default(self._send_configuration_response_default) def close(self): self._acl_manager.close() @@ -237,32 +191,22 @@ class CertL2cap(Closable, IHasBehaviors): self._acl = self._acl_manager.initiate_connection(remote_addr) self._acl.wait_for_connection_complete() self.control_channel = CertL2capChannel( - self._device, - 1, - 1, - self._get_acl_stream(), - self._acl, - control_channel=None) + self._device, 1, 1, self._get_acl_stream(), self._acl, control_channel=None) self._get_acl_stream().register_callback(self._handle_control_packet) def open_channel(self, signal_id, psm, scid, fcs=None): - self.control_channel.send( - l2cap_packets.ConnectionRequestBuilder(signal_id, psm, scid)) + self.control_channel.send(l2cap_packets.ConnectionRequestBuilder(signal_id, psm, scid)) response = L2capCaptures.ConnectionResponse(scid) assertThat(self.control_channel).emits(response) channel = CertL2capChannel(self._device, scid, - response.get().GetDestinationCid(), - self._get_acl_stream(), self._acl, + response.get().GetDestinationCid(), self._get_acl_stream(), self._acl, self.control_channel, fcs) self.scid_to_channel[scid] = channel return channel - def verify_and_respond_open_channel_from_remote(self, - psm=0x33, - scid=None, - fcs=None): + def verify_and_respond_open_channel_from_remote(self, psm=0x33, scid=None, fcs=None): request = L2capCaptures.ConnectionRequest(psm) assertThat(self.control_channel).emits(request) @@ -271,15 +215,13 @@ class CertL2cap(Closable, IHasBehaviors): dcid = request.get().GetSourceCid() if scid is None or scid in self.scid_to_channel: scid = dcid - channel = CertL2capChannel(self._device, scid, dcid, - self._get_acl_stream(), self._acl, - self.control_channel, fcs) + channel = CertL2capChannel(self._device, scid, dcid, self._get_acl_stream(), self._acl, self.control_channel, + fcs) self.scid_to_channel[scid] = channel connection_response = l2cap_packets.ConnectionResponseBuilder( sid, scid, dcid, l2cap_packets.ConnectionResponseResult.SUCCESS, - l2cap_packets.ConnectionResponseStatus. - NO_FURTHER_INFORMATION_AVAILABLE) + l2cap_packets.ConnectionResponseStatus.NO_FURTHER_INFORMATION_AVAILABLE) self.control_channel.send(connection_response) return channel @@ -313,15 +255,13 @@ class CertL2cap(Closable, IHasBehaviors): dcid = captured_request_view.GetDestinationCid() if dcid not in self.scid_to_channel: return - self.scid_to_channel[dcid].send_configuration_response( - captured_request_view) + self.scid_to_channel[dcid].send_configuration_response(captured_request_view) @staticmethod def config_option_basic_explicit(mtu=642): mtu_opt = l2cap_packets.MtuConfigurationOption() mtu_opt.mtu = mtu - rfc_opt = l2cap_packets.RetransmissionAndFlowControlConfigurationOption( - ) + rfc_opt = l2cap_packets.RetransmissionAndFlowControlConfigurationOption() rfc_opt.mode = l2cap_packets.RetransmissionAndFlowControlModeOption.L2CAP_BASIC return [mtu_opt, rfc_opt] @@ -347,8 +287,7 @@ class CertL2cap(Closable, IHasBehaviors): fcs_opt = l2cap_packets.FrameCheckSequenceOption() fcs_opt.fcs_type = fcs result.append(fcs_opt) - rfc_opt = l2cap_packets.RetransmissionAndFlowControlConfigurationOption( - ) + rfc_opt = l2cap_packets.RetransmissionAndFlowControlConfigurationOption() rfc_opt.mode = l2cap_packets.RetransmissionAndFlowControlModeOption.ENHANCED_RETRANSMISSION rfc_opt.tx_window_size = tx_window_size rfc_opt.max_transmit = max_transmit @@ -377,21 +316,18 @@ class CertL2cap(Closable, IHasBehaviors): self.scid_to_channel[scid]._config_rsp_received = True def _on_disconnection_request_default(self, l2cap_control_view): - disconnection_request = l2cap_packets.DisconnectionRequestView( - l2cap_control_view) + disconnection_request = l2cap_packets.DisconnectionRequestView(l2cap_control_view) sid = disconnection_request.GetIdentifier() scid = disconnection_request.GetSourceCid() dcid = disconnection_request.GetDestinationCid() - disconnection_response = l2cap_packets.DisconnectionResponseBuilder( - sid, dcid, scid) + disconnection_response = l2cap_packets.DisconnectionResponseBuilder(sid, dcid, scid) self.control_channel.send(disconnection_response) def _on_disconnection_response_default(self, l2cap_control_view): pass def _on_information_request_default(self, l2cap_control_view): - information_request = l2cap_packets.InformationRequestView( - l2cap_control_view) + information_request = l2cap_packets.InformationRequestView(l2cap_control_view) sid = information_request.GetIdentifier() information_type = information_request.GetInfoType() if information_type == l2cap_packets.InformationRequestInfoType.CONNECTIONLESS_MTU: @@ -401,8 +337,8 @@ class CertL2cap(Closable, IHasBehaviors): return if information_type == l2cap_packets.InformationRequestInfoType.EXTENDED_FEATURES_SUPPORTED: response = l2cap_packets.InformationResponseExtendedFeaturesBuilder( - sid, l2cap_packets.InformationRequestResult.SUCCESS, 0, 0, 0, - self.support_ertm, 0, self.support_fcs, 0, 0, 0, 0) + sid, l2cap_packets.InformationRequestResult.SUCCESS, 0, 0, 0, self.support_ertm, 0, self.support_fcs, 0, + 0, 0, 0) self.control_channel.send(response) return if information_type == l2cap_packets.InformationRequestInfoType.FIXED_CHANNELS_SUPPORTED: @@ -416,8 +352,7 @@ class CertL2cap(Closable, IHasBehaviors): def _handle_control_packet(self, l2cap_packet): packet_bytes = l2cap_packet.payload - l2cap_view = l2cap_packets.BasicFrameView( - bt_packets.PacketViewLittleEndian(list(packet_bytes))) + l2cap_view = l2cap_packets.BasicFrameView(bt_packets.PacketViewLittleEndian(list(packet_bytes))) if l2cap_view.GetChannelId() != 1: return l2cap_control_view = l2cap_packets.ControlView(l2cap_view.GetPayload()) diff --git a/system/gd/l2cap/classic/cert/l2cap_test.py b/system/gd/l2cap/classic/cert/l2cap_test.py index abd617373f..b4e7fdfba9 100644 --- a/system/gd/l2cap/classic/cert/l2cap_test.py +++ b/system/gd/l2cap/classic/cert/l2cap_test.py @@ -51,8 +51,7 @@ class L2capTest(GdBaseTestClass): self.dut_address = self.dut.hci_controller.GetMacAddressSimple() cert_address = common_pb2.BluetoothAddress( - address=self.cert.controller_read_only_property.ReadLocalAddress( - empty_proto.Empty()).address) + address=self.cert.controller_read_only_property.ReadLocalAddress(empty_proto.Empty()).address) self.dut_l2cap = PyL2cap(self.dut, cert_address) self.cert_l2cap = CertL2cap(self.cert) @@ -63,21 +62,18 @@ class L2capTest(GdBaseTestClass): super().teardown_test() def _setup_link_from_cert(self): - self.dut.neighbor.EnablePageScan( - neighbor_facade.EnableMsg(enabled=True)) + self.dut.neighbor.EnablePageScan(neighbor_facade.EnableMsg(enabled=True)) self.cert_l2cap.connect_acl(self.dut_address) - def _open_unconfigured_channel_from_cert( - self, - signal_id=1, - scid=0x0101, - psm=0x33, - mode=RetransmissionFlowControlMode.BASIC, - fcs=None): + def _open_unconfigured_channel_from_cert(self, + signal_id=1, + scid=0x0101, + psm=0x33, + mode=RetransmissionFlowControlMode.BASIC, + fcs=None): dut_channel = self.dut_l2cap.register_dynamic_channel(psm, mode) - cert_channel = self.cert_l2cap.open_channel( - signal_id, psm, scid, fcs=fcs) + cert_channel = self.cert_l2cap.open_channel(signal_id, psm, scid, fcs=fcs) return (dut_channel, cert_channel) @@ -91,15 +87,13 @@ class L2capTest(GdBaseTestClass): rsp_config_options=None): request_matcher = L2capMatchers.ConfigurationRequestView(scid) if rsp_config_options is not None: - when(self.cert_l2cap).on_config_req(request_matcher).then( - ).send_configuration_response(options=rsp_config_options) + when(self.cert_l2cap).on_config_req(request_matcher).then().send_configuration_response( + options=rsp_config_options) if rsp_config_options is None and fcs is not None: - when(self.cert_l2cap).on_config_req( - request_matcher).then().send_configuration_response( - options=CertL2cap.config_option_ertm(fcs=fcs)) + when(self.cert_l2cap).on_config_req(request_matcher).then().send_configuration_response( + options=CertL2cap.config_option_ertm(fcs=fcs)) - (dut_channel, cert_channel) = self._open_unconfigured_channel_from_cert( - signal_id, scid, psm, mode, fcs) + (dut_channel, cert_channel) = self._open_unconfigured_channel_from_cert(signal_id, scid, psm, mode, fcs) if req_config_options is None: req_config_options = CertL2cap.config_option_ertm( fcs=fcs) if mode == RetransmissionFlowControlMode.ERTM else [] @@ -114,13 +108,9 @@ class L2capTest(GdBaseTestClass): return (dut_channel, cert_channel) - def _open_channel_from_dut(self, - psm=0x33, - mode=RetransmissionFlowControlMode.BASIC): - dut_channel_future = self.dut_l2cap.connect_dynamic_channel_to_cert( - psm, mode) - cert_channel = self.cert_l2cap.verify_and_respond_open_channel_from_remote( - psm) + def _open_channel_from_dut(self, psm=0x33, mode=RetransmissionFlowControlMode.BASIC): + dut_channel_future = self.dut_l2cap.connect_dynamic_channel_to_cert(psm, mode) + cert_channel = self.cert_l2cap.verify_and_respond_open_channel_from_remote(psm) dut_channel = dut_channel_future.get_channel() cert_channel.verify_configuration_request_and_respond() @@ -143,15 +133,12 @@ class L2capTest(GdBaseTestClass): def test_receive_packet_from_unknown_channel(self): self._setup_link_from_cert() - (dut_channel, cert_channel) = self._open_channel_from_cert( - scid=0x41, psm=0x33) + (dut_channel, cert_channel) = self._open_channel_from_cert(scid=0x41, psm=0x33) i_frame = l2cap_packets.EnhancedInformationFrameBuilder( - 0x99, 0, Final.NOT_SET, 1, - l2cap_packets.SegmentationAndReassembly.UNSEGMENTED, SAMPLE_PACKET) + 0x99, 0, Final.NOT_SET, 1, l2cap_packets.SegmentationAndReassembly.UNSEGMENTED, SAMPLE_PACKET) self.cert_l2cap.send_acl(i_frame) - assertThat(cert_channel).emitsNone( - L2capMatchers.SFrame(req_seq=4), timeout=timedelta(seconds=1)) + assertThat(cert_channel).emitsNone(L2capMatchers.SFrame(req_seq=4), timeout=timedelta(seconds=1)) def test_open_two_channels(self): self._setup_link_from_cert() @@ -166,14 +153,12 @@ class L2capTest(GdBaseTestClass): mode=RetransmissionFlowControlMode.ERTM, fcs=FcsType.NO_FCS) dut_channel.send(b'abc' * 34) - assertThat(cert_channel).emits( - L2capMatchers.IFrame(tx_seq=0, payload=b'abc' * 34)) + assertThat(cert_channel).emits(L2capMatchers.IFrame(tx_seq=0, payload=b'abc' * 34)) cert_channel.send_i_frame(tx_seq=0, req_seq=1, payload=SAMPLE_PACKET) # todo verify received? - @metadata( - pts_test_id="L2CAP/COS/CED/BV-01-C", pts_test_name="Request Connection") + @metadata(pts_test_id="L2CAP/COS/CED/BV-01-C", pts_test_name="Request Connection") def test_basic_operation_request_connection(self): """ Verify that the IUT is able to request the connection establishment for @@ -204,8 +189,7 @@ class L2capTest(GdBaseTestClass): dut_channel.close_channel() cert_channel.verify_disconnect_request() - @metadata( - pts_test_id="L2CAP/COS/CED/BV-05-C", pts_test_name="Accept connection") + @metadata(pts_test_id="L2CAP/COS/CED/BV-05-C", pts_test_name="Accept connection") def test_accept_connection(self): """ Also verify that DUT can send 48 bytes PDU (minimal MTU) @@ -216,8 +200,7 @@ class L2capTest(GdBaseTestClass): dut_channel.send(b'a' * 48) assertThat(cert_channel).emits(L2capMatchers.Data(b'a' * 48)) - @metadata( - pts_test_id="L2CAP/COS/CED/BV-07-C", pts_test_name="Accept Disconnect") + @metadata(pts_test_id="L2CAP/COS/CED/BV-07-C", pts_test_name="Accept Disconnect") def test_accept_disconnect(self): """ Verify that the IUT is able to respond to the request to disconnect the @@ -228,9 +211,7 @@ class L2capTest(GdBaseTestClass): (dut_channel, cert_channel) = self._open_channel_from_cert() cert_channel.disconnect_and_verify() - @metadata( - pts_test_id="L2CAP/COS/CED/BV-08-C", - pts_test_name="Disconnect on Timeout") + @metadata(pts_test_id="L2CAP/COS/CED/BV-08-C", pts_test_name="Disconnect on Timeout") def test_disconnect_on_timeout(self): """ Verify that the IUT disconnects the data channel and shuts down this @@ -238,29 +219,23 @@ class L2capTest(GdBaseTestClass): """ self._setup_link_from_cert() - (dut_channel, - cert_channel) = self._open_unconfigured_channel_from_cert() + (dut_channel, cert_channel) = self._open_unconfigured_channel_from_cert() - assertThat(self.cert_l2cap.get_control_channel()).emitsNone( - L2capMatchers.ConfigurationResponse()) + assertThat(self.cert_l2cap.get_control_channel()).emitsNone(L2capMatchers.ConfigurationResponse()) # TODO: Verify that IUT sends disconnect request (not mandated) - @metadata( - pts_test_id="L2CAP/COS/CED/BV-11-C", pts_test_name="Configure MTU size") + @metadata(pts_test_id="L2CAP/COS/CED/BV-11-C", pts_test_name="Configure MTU size") def test_configure_mtu_size(self): """ Verify that the IUT is able to configure the supported MTU size """ self._setup_link_from_cert() - (dut_channel, - cert_channel) = self._open_unconfigured_channel_from_cert() - cert_channel.send_configure_request( - CertL2cap.config_option_mtu_explicit(672)) + (dut_channel, cert_channel) = self._open_unconfigured_channel_from_cert() + cert_channel.send_configure_request(CertL2cap.config_option_mtu_explicit(672)) cert_channel.verify_configuration_request_and_respond() # TODO: Probably remove verify_configuration_request_and_respond - @metadata( - pts_test_id="L2CAP/COS/CFD/BV-01-C", pts_test_name="Continuation Flag") + @metadata(pts_test_id="L2CAP/COS/CFD/BV-01-C", pts_test_name="Continuation Flag") def test_continuation_flag(self): """ Verify the IUT is able to receive configuration requests that have the @@ -268,26 +243,20 @@ class L2capTest(GdBaseTestClass): """ self._setup_link_from_cert() - (dut_channel, - cert_channel) = self._open_unconfigured_channel_from_cert() + (dut_channel, cert_channel) = self._open_unconfigured_channel_from_cert() # Send configuration request with CONTINUE mtu_opt = l2cap_packets.MtuConfigurationOption() mtu_opt.mtu = 0x1234 - cert_channel.send_configure_request([mtu_opt], 2, - l2cap_packets.Continuation.CONTINUE) + cert_channel.send_configure_request([mtu_opt], 2, l2cap_packets.Continuation.CONTINUE) flush_timeout_option = l2cap_packets.FlushTimeoutConfigurationOption() flush_timeout_option.flush_timeout = 65535 - cert_channel.send_configure_request([flush_timeout_option], 3, - l2cap_packets.Continuation.END) + cert_channel.send_configure_request([flush_timeout_option], 3, l2cap_packets.Continuation.END) - assertThat(self.cert_l2cap.get_control_channel()).emits( - L2capMatchers.ConfigurationResponse(), at_least_times=2) + assertThat(self.cert_l2cap.get_control_channel()).emits(L2capMatchers.ConfigurationResponse(), at_least_times=2) - @metadata( - pts_test_id="L2CAP/COS/CFD/BV-02-C", - pts_test_name="Negotiation with Reject") + @metadata(pts_test_id="L2CAP/COS/CFD/BV-02-C", pts_test_name="Negotiation with Reject") def test_retry_config_after_rejection(self): """ Verify that the IUT is able to perform negotiation while the Lower @@ -296,35 +265,25 @@ class L2capTest(GdBaseTestClass): self._setup_link_from_cert() scid = 0x41 when(self.cert_l2cap).on_config_req( - L2capMatchers.ConfigurationRequestView( - scid)).then().send_configuration_response( - result=l2cap_packets.ConfigurationResponseResult. - UNACCEPTABLE_PARAMETERS, - options=CertL2cap.config_option_mtu_explicit( - 200)).send_configuration_response(options=[]) - (dut_channel, - cert_channel) = self._open_unconfigured_channel_from_cert(scid=scid) + L2capMatchers.ConfigurationRequestView(scid)).then().send_configuration_response( + result=l2cap_packets.ConfigurationResponseResult.UNACCEPTABLE_PARAMETERS, + options=CertL2cap.config_option_mtu_explicit(200)).send_configuration_response(options=[]) + (dut_channel, cert_channel) = self._open_unconfigured_channel_from_cert(scid=scid) - assertThat(self.cert_l2cap.get_control_channel()).emits( - L2capMatchers.ConfigurationRequest(), at_least_times=2) + assertThat(self.cert_l2cap.get_control_channel()).emits(L2capMatchers.ConfigurationRequest(), at_least_times=2) - @metadata( - pts_test_id="L2CAP/COS/CFD/BV-03-C", - pts_test_name="Send Requested Options") + @metadata(pts_test_id="L2CAP/COS/CFD/BV-03-C", pts_test_name="Send Requested Options") def test_send_requested_options(self): """ Verify that the IUT can receive a configuration request with no options and send the requested options to the Lower Tester """ self._setup_link_from_cert() - (dut_channel, cert_channel) = self._open_channel_from_cert( - scid=0x41, psm=0x33) + (dut_channel, cert_channel) = self._open_channel_from_cert(scid=0x41, psm=0x33) # TODO(hsz) implement me! - @metadata( - pts_test_id="L2CAP/COS/CFD/BV-08-C", - pts_test_name="Non-blocking Config Response") + @metadata(pts_test_id="L2CAP/COS/CFD/BV-08-C", pts_test_name="Non-blocking Config Response") def test_non_blocking_config_response(self): """ Verify that the IUT does not block transmitting L2CAP_ConfigRsp while @@ -332,8 +291,7 @@ class L2capTest(GdBaseTestClass): """ self._setup_link_from_cert() - (dut_channel, - cert_channel) = self._open_unconfigured_channel_from_cert() + (dut_channel, cert_channel) = self._open_unconfigured_channel_from_cert() cert_channel.send_configure_request([]) cert_channel.verify_configuration_response() @@ -341,42 +299,33 @@ class L2capTest(GdBaseTestClass): # TODO(hsz) implement me! - @metadata( - pts_test_id="L2CAP/COS/CFD/BV-09-C", - pts_test_name="Mandatory 48 Byte MTU") + @metadata(pts_test_id="L2CAP/COS/CFD/BV-09-C", pts_test_name="Mandatory 48 Byte MTU") def test_mandatory_48_byte_mtu(self): """ Verify that the IUT can support mandatory 48 byte MTU """ self._setup_link_from_cert() - (dut_channel, cert_channel) = self._open_channel_from_cert( - req_config_options=CertL2cap.config_option_mtu_explicit(48)) + (dut_channel, + cert_channel) = self._open_channel_from_cert(req_config_options=CertL2cap.config_option_mtu_explicit(48)) dut_channel.send(b"a" * 44) assertThat(cert_channel).emits(L2capMatchers.Data(b"a" * 44)) - @metadata( - pts_test_id="L2CAP/COS/CFD/BV-11-C", - pts_test_name="Negotiation of Unsupported Parameter") + @metadata(pts_test_id="L2CAP/COS/CFD/BV-11-C", pts_test_name="Negotiation of Unsupported Parameter") def test_negotiation_of_unsupported_parameter(self): """ Verify that the IUT can negotiate when the Lower Tester proposes an unsupported configuration parameter value. """ self._setup_link_from_cert() - (dut_channel, - cert_channel) = self._open_unconfigured_channel_from_cert() + (dut_channel, cert_channel) = self._open_unconfigured_channel_from_cert() - cert_channel.send_configure_request( - CertL2cap.config_option_mtu_explicit(20)) + cert_channel.send_configure_request(CertL2cap.config_option_mtu_explicit(20)) # Invalid because minimum is 48 - cert_channel.verify_configuration_response( - l2cap_packets.ConfigurationResponseResult.UNACCEPTABLE_PARAMETERS) + cert_channel.verify_configuration_response(l2cap_packets.ConfigurationResponseResult.UNACCEPTABLE_PARAMETERS) - @metadata( - pts_test_id="L2CAP/COS/CFD/BV-12-C", - pts_test_name="Unknown Option Response") + @metadata(pts_test_id="L2CAP/COS/CFD/BV-12-C", pts_test_name="Unknown Option Response") def test_config_unknown_options_with_hint(self): """ Verify that the IUT can give the appropriate error code when the Lower @@ -385,8 +334,7 @@ class L2capTest(GdBaseTestClass): """ self._setup_link_from_cert() - (dut_channel, - cert_channel) = self._open_unconfigured_channel_from_cert() + (dut_channel, cert_channel) = self._open_unconfigured_channel_from_cert() unknown_opt_hint = l2cap_packets.ExtendedWindowSizeOption() unknown_opt_hint.max_window_size = 20 @@ -394,12 +342,9 @@ class L2capTest(GdBaseTestClass): for i in range(10): cert_channel.send_configure_request([unknown_opt_hint] * i) - cert_channel.verify_configuration_response( - l2cap_packets.ConfigurationResponseResult.SUCCESS) + cert_channel.verify_configuration_response(l2cap_packets.ConfigurationResponseResult.SUCCESS) - @metadata( - pts_test_id="L2CAP/COS/CFD/BV-14-C", - pts_test_name="Unknown Mandatory Options Request") + @metadata(pts_test_id="L2CAP/COS/CFD/BV-14-C", pts_test_name="Unknown Mandatory Options Request") def test_unknown_mandatory_options_request(self): """ Verify that the IUT can give the appropriate error code when the Lower @@ -410,8 +355,7 @@ class L2capTest(GdBaseTestClass): """ self._setup_link_from_cert() - (dut_channel, cert_channel) = self._open_unconfigured_channel_from_cert( - scid=0x41, psm=0x33) + (dut_channel, cert_channel) = self._open_unconfigured_channel_from_cert(scid=0x41, psm=0x33) unknown_opt = l2cap_packets.ExtendedWindowSizeOption() unknown_opt.max_window_size = 20 @@ -420,56 +364,38 @@ class L2capTest(GdBaseTestClass): unknown_opt_hint.max_window_size = 20 unknown_opt_hint.is_hint = l2cap_packets.ConfigurationOptionIsHint.OPTION_IS_A_HINT - configuration_option_attempts = [[unknown_opt], [ - unknown_opt, unknown_opt_hint - ], [unknown_opt, unknown_opt, unknown_opt], [ - unknown_opt, unknown_opt_hint, unknown_opt_hint, unknown_opt - ], [ - unknown_opt_hint, unknown_opt_hint, unknown_opt_hint, - unknown_opt_hint, unknown_opt - ], [ - unknown_opt, unknown_opt_hint, unknown_opt_hint, unknown_opt, - unknown_opt_hint, unknown_opt_hint - ], [ - unknown_opt, unknown_opt, unknown_opt, unknown_opt, unknown_opt, - unknown_opt, unknown_opt - ], [ - unknown_opt_hint, unknown_opt_hint, unknown_opt_hint, - unknown_opt_hint, unknown_opt_hint, unknown_opt_hint, - unknown_opt_hint, unknown_opt - ], [ - unknown_opt_hint, unknown_opt_hint, unknown_opt_hint, - unknown_opt_hint, unknown_opt_hint, unknown_opt_hint, - unknown_opt_hint, unknown_opt, unknown_opt - ], [ - unknown_opt_hint, unknown_opt_hint, unknown_opt_hint, - unknown_opt_hint, unknown_opt_hint, unknown_opt_hint, - unknown_opt_hint, unknown_opt_hint, unknown_opt_hint, unknown_opt - ]] + configuration_option_attempts = [[unknown_opt], [unknown_opt, unknown_opt_hint], [ + unknown_opt, unknown_opt, unknown_opt + ], [unknown_opt, unknown_opt_hint, unknown_opt_hint, + unknown_opt], [unknown_opt_hint, unknown_opt_hint, unknown_opt_hint, unknown_opt_hint, unknown_opt], [ + unknown_opt, unknown_opt_hint, unknown_opt_hint, unknown_opt, unknown_opt_hint, unknown_opt_hint + ], [unknown_opt, unknown_opt, unknown_opt, unknown_opt, unknown_opt, unknown_opt, unknown_opt], [ + unknown_opt_hint, unknown_opt_hint, unknown_opt_hint, unknown_opt_hint, unknown_opt_hint, + unknown_opt_hint, unknown_opt_hint, unknown_opt + ], [ + unknown_opt_hint, unknown_opt_hint, unknown_opt_hint, unknown_opt_hint, unknown_opt_hint, + unknown_opt_hint, unknown_opt_hint, unknown_opt, unknown_opt + ], [ + unknown_opt_hint, unknown_opt_hint, unknown_opt_hint, unknown_opt_hint, unknown_opt_hint, + unknown_opt_hint, unknown_opt_hint, unknown_opt_hint, unknown_opt_hint, unknown_opt + ]] for option_list in configuration_option_attempts: cert_channel.send_configure_request(option_list) - cert_channel.verify_configuration_response( - l2cap_packets.ConfigurationResponseResult.UNKNOWN_OPTIONS) + cert_channel.verify_configuration_response(l2cap_packets.ConfigurationResponseResult.UNKNOWN_OPTIONS) - @metadata( - pts_test_id="L2CAP/COS/ECH/BV-01-C", - pts_test_name="Respond to Echo Request") + @metadata(pts_test_id="L2CAP/COS/ECH/BV-01-C", pts_test_name="Respond to Echo Request") def test_respond_to_echo_request(self): """ Verify that the IUT responds to an echo request. """ self._setup_link_from_cert() - echo_request = l2cap_packets.EchoRequestBuilder(100, - RawBuilder([1, 2, 3])) + echo_request = l2cap_packets.EchoRequestBuilder(100, RawBuilder([1, 2, 3])) self.cert_l2cap.get_control_channel().send(echo_request) - assertThat(self.cert_l2cap.get_control_channel()).emits( - L2capMatchers.EchoResponse()) + assertThat(self.cert_l2cap.get_control_channel()).emits(L2capMatchers.EchoResponse()) - @metadata( - pts_test_id="L2CAP/COS/CED/BI-01-C", - pts_test_name="Reject Unknown Command") + @metadata(pts_test_id="L2CAP/COS/CED/BI-01-C", pts_test_name="Reject Unknown Command") def test_reject_unknown_command(self): """ Verify that the IUT rejects an unknown signaling command @@ -480,12 +406,9 @@ class L2capTest(GdBaseTestClass): invalid_command_packet = RawBuilder([0xff, 0x01, 0x00, 0x00]) self.cert_l2cap.get_control_channel().send(invalid_command_packet) - assertThat(self.cert_l2cap.get_control_channel()).emits( - L2capMatchers.CommandReject()) + assertThat(self.cert_l2cap.get_control_channel()).emits(L2capMatchers.CommandReject()) - @metadata( - pts_test_id="L2CAP/COS/IEX/BV-01-C", - pts_test_name="Query for 1.2 Features") + @metadata(pts_test_id="L2CAP/COS/IEX/BV-01-C", pts_test_name="Query for 1.2 Features") def test_query_for_1_2_features(self): """ Verify that the IUT transmits an information request command to solicit @@ -494,12 +417,9 @@ class L2capTest(GdBaseTestClass): self._setup_link_from_cert() assertThat(self.cert_l2cap.get_control_channel()).emits( L2capMatchers.InformationRequestWithType( - l2cap_packets.InformationRequestInfoType. - EXTENDED_FEATURES_SUPPORTED)) + l2cap_packets.InformationRequestInfoType.EXTENDED_FEATURES_SUPPORTED)) - @metadata( - pts_test_id="L2CAP/COS/IEX/BV-02-C", - pts_test_name="Respond with 1.2 Features") + @metadata(pts_test_id="L2CAP/COS/IEX/BV-02-C", pts_test_name="Respond with 1.2 Features") def test_respond_with_1_2_features(self): """ Verify that the IUT responds to an information request command @@ -510,8 +430,7 @@ class L2capTest(GdBaseTestClass): control_channel.send_extended_features_request() - assertThat(control_channel).emits( - L2capMatchers.InformationResponseExtendedFeatures()) + assertThat(control_channel).emits(L2capMatchers.InformationResponseExtendedFeatures()) @metadata( pts_test_id="L2CAP/EXF/BV-01-C", @@ -528,13 +447,10 @@ class L2capTest(GdBaseTestClass): control_channel.send_extended_features_request() - assertThat(control_channel).emits( - L2capMatchers.InformationResponseExtendedFeatures( - supports_ertm=True)) + assertThat(control_channel).emits(L2capMatchers.InformationResponseExtendedFeatures(supports_ertm=True)) @metadata( - pts_test_id="L2CAP/EXF/BV-02-C", - pts_test_name="Extended Features Information Response for " + pts_test_id="L2CAP/EXF/BV-02-C", pts_test_name="Extended Features Information Response for " "Streaming Mode") def test_extended_feature_info_response_streaming(self): """ @@ -548,14 +464,9 @@ class L2capTest(GdBaseTestClass): control_channel.send_extended_features_request() - assertThat(control_channel).emits( - L2capMatchers.InformationResponseExtendedFeatures( - supports_streaming=True)) + assertThat(control_channel).emits(L2capMatchers.InformationResponseExtendedFeatures(supports_streaming=True)) - @metadata( - pts_test_id="L2CAP/EXF/BV-03-C", - pts_test_name="Extended Features Information Response for FCS " - "Option") + @metadata(pts_test_id="L2CAP/EXF/BV-03-C", pts_test_name="Extended Features Information Response for FCS " "Option") def test_extended_feature_info_response_fcs(self): """ Verify the IUT can format an Information Response for the information @@ -569,13 +480,10 @@ class L2capTest(GdBaseTestClass): control_channel.send_extended_features_request() - assertThat(control_channel).emits( - L2capMatchers.InformationResponseExtendedFeatures( - supports_fcs=True)) + assertThat(control_channel).emits(L2capMatchers.InformationResponseExtendedFeatures(supports_fcs=True)) @metadata( - pts_test_id="L2CAP/EXF/BV-05-C", - pts_test_name="Extended Features Information Response for Fixed " + pts_test_id="L2CAP/EXF/BV-05-C", pts_test_name="Extended Features Information Response for Fixed " "Channels") def test_extended_feature_info_response_fixed_channels(self): """ @@ -591,12 +499,9 @@ class L2capTest(GdBaseTestClass): control_channel.send_extended_features_request() assertThat(control_channel).emits( - L2capMatchers.InformationResponseExtendedFeatures( - supports_fixed_channels=True)) + L2capMatchers.InformationResponseExtendedFeatures(supports_fixed_channels=True)) - @metadata( - pts_test_id="L2CAP/FIX/BV-01-C", - pts_test_name="Fixed Channels Supported Information Request") + @metadata(pts_test_id="L2CAP/FIX/BV-01-C", pts_test_name="Fixed Channels Supported Information Request") def test_fixed_channels_supported_information_request(self): """ Verify that the IUT can send an Information Request for the information @@ -604,13 +509,9 @@ class L2capTest(GdBaseTestClass): """ self._setup_link_from_cert() assertThat(self.cert_l2cap.get_control_channel()).emits( - L2capMatchers.InformationRequestWithType( - l2cap_packets.InformationRequestInfoType. - FIXED_CHANNELS_SUPPORTED)) + L2capMatchers.InformationRequestWithType(l2cap_packets.InformationRequestInfoType.FIXED_CHANNELS_SUPPORTED)) - @metadata( - pts_test_id="L2CAP/FOC/BV-01-C", - pts_test_name="IUT Initiated Configuration of the FCS Option") + @metadata(pts_test_id="L2CAP/FOC/BV-01-C", pts_test_name="IUT Initiated Configuration of the FCS Option") def test_config_channel_not_use_FCS(self): """ Verify the IUT can configure a channel to not use FCS in I/S-frames. @@ -621,13 +522,9 @@ class L2capTest(GdBaseTestClass): mode=RetransmissionFlowControlMode.ERTM, fcs=FcsType.NO_FCS) dut_channel.send(b'abc') - assertThat(cert_channel).emits( - L2capMatchers.IFrame(tx_seq=0, payload=b'abc')) + assertThat(cert_channel).emits(L2capMatchers.IFrame(tx_seq=0, payload=b'abc')) - @metadata( - pts_test_id="L2CAP/FOC/BV-02-C", - pts_test_name="Lower Tester Explicitly Requests FCS should be " - "Used") + @metadata(pts_test_id="L2CAP/FOC/BV-02-C", pts_test_name="Lower Tester Explicitly Requests FCS should be " "Used") def test_explicitly_request_use_FCS(self): """ Verify the IUT will include the FCS in I/S-frames if the Lower Tester @@ -639,13 +536,9 @@ class L2capTest(GdBaseTestClass): mode=RetransmissionFlowControlMode.ERTM, fcs=FcsType.DEFAULT) dut_channel.send(b'abc') - assertThat(cert_channel).emits( - L2capMatchers.IFrameWithFcs(payload=b"abc")) + assertThat(cert_channel).emits(L2capMatchers.IFrameWithFcs(payload=b"abc")) - @metadata( - pts_test_id="L2CAP/FOC/BV-03-C", - pts_test_name="Lower Tester Implicitly Requests FCS should be " - "Used") + @metadata(pts_test_id="L2CAP/FOC/BV-03-C", pts_test_name="Lower Tester Implicitly Requests FCS should be " "Used") def test_implicitly_request_use_FCS(self): """ Verify the IUT will include the FCS in I/S-frames if the Lower Tester @@ -659,12 +552,9 @@ class L2capTest(GdBaseTestClass): req_config_options=CertL2cap.config_option_ertm(fcs=FcsType.NO_FCS)) dut_channel.send(b'abc') - assertThat(cert_channel).emits( - L2capMatchers.IFrameWithFcs(payload=b"abc")) + assertThat(cert_channel).emits(L2capMatchers.IFrameWithFcs(payload=b"abc")) - @metadata( - pts_test_id="L2CAP/OFS/BV-01-C", - pts_test_name="Sending I-Frames without FCS for ERTM") + @metadata(pts_test_id="L2CAP/OFS/BV-01-C", pts_test_name="Sending I-Frames without FCS for ERTM") def test_sending_i_frames_without_fcs_for_ertm(self): """ Verify the IUT does not include the FCS in I-frames. @@ -675,12 +565,9 @@ class L2capTest(GdBaseTestClass): mode=RetransmissionFlowControlMode.ERTM, fcs=FcsType.NO_FCS) dut_channel.send(b'abc') - assertThat(cert_channel).emits( - L2capMatchers.IFrame(tx_seq=0, payload=b"abc")) + assertThat(cert_channel).emits(L2capMatchers.IFrame(tx_seq=0, payload=b"abc")) - @metadata( - pts_test_id="L2CAP/OFS/BV-02-C", - pts_test_name="Receiving I-Frames without FCS for ERTM") + @metadata(pts_test_id="L2CAP/OFS/BV-02-C", pts_test_name="Receiving I-Frames without FCS for ERTM") def test_receiving_i_frames_without_fcs_for_ertm(self): """ Verify the IUT can handle I-frames that do not contain the FCS. @@ -691,12 +578,9 @@ class L2capTest(GdBaseTestClass): mode=RetransmissionFlowControlMode.ERTM, fcs=FcsType.NO_FCS) cert_channel.send_i_frame(tx_seq=0, req_seq=0, payload=SAMPLE_PACKET) - assertThat(dut_channel).emits( - L2capMatchers.PacketPayloadRawData(SAMPLE_PACKET_DATA)) + assertThat(dut_channel).emits(L2capMatchers.PacketPayloadRawData(SAMPLE_PACKET_DATA)) - @metadata( - pts_test_id="L2CAP/OFS/BV-05-C", - pts_test_name="Sending I-Frames with FCS for ERTM") + @metadata(pts_test_id="L2CAP/OFS/BV-05-C", pts_test_name="Sending I-Frames with FCS for ERTM") def test_sending_i_frames_with_fcs_for_ertm(self): """ Verify the IUT does include the FCS in I-frames. @@ -707,12 +591,9 @@ class L2capTest(GdBaseTestClass): mode=RetransmissionFlowControlMode.ERTM, fcs=FcsType.DEFAULT) dut_channel.send(b'abc') - assertThat(cert_channel).emits( - L2capMatchers.IFrameWithFcs(tx_seq=0, payload=b"abc")) + assertThat(cert_channel).emits(L2capMatchers.IFrameWithFcs(tx_seq=0, payload=b"abc")) - @metadata( - pts_test_id="L2CAP/OFS/BV-06-C", - pts_test_name="Receiving I-Frames with FCS for ERTM") + @metadata(pts_test_id="L2CAP/OFS/BV-06-C", pts_test_name="Receiving I-Frames with FCS for ERTM") def test_receiving_i_frames_with_fcs_for_ertm(self): """ Verify the IUT can handle I-frames that do contain the FCS. @@ -722,13 +603,10 @@ class L2capTest(GdBaseTestClass): (dut_channel, cert_channel) = self._open_channel_from_cert( mode=RetransmissionFlowControlMode.ERTM, fcs=FcsType.DEFAULT) - cert_channel.send_i_frame( - tx_seq=0, req_seq=0, payload=SAMPLE_PACKET, fcs=FcsType.DEFAULT) - assertThat(dut_channel).emits( - L2capMatchers.PacketPayloadRawData(SAMPLE_PACKET_DATA)) + cert_channel.send_i_frame(tx_seq=0, req_seq=0, payload=SAMPLE_PACKET, fcs=FcsType.DEFAULT) + assertThat(dut_channel).emits(L2capMatchers.PacketPayloadRawData(SAMPLE_PACKET_DATA)) - @metadata( - pts_test_id="L2CAP/ERM/BV-01-C", pts_test_name="Transmit I-frames") + @metadata(pts_test_id="L2CAP/ERM/BV-01-C", pts_test_name="Transmit I-frames") def test_transmit_i_frames(self): """ Verify the IUT can send correctly formatted sequential I-frames with @@ -741,14 +619,12 @@ class L2capTest(GdBaseTestClass): mode=RetransmissionFlowControlMode.ERTM, fcs=FcsType.NO_FCS) dut_channel.send(b'abc') - assertThat(cert_channel).emits( - L2capMatchers.IFrame(tx_seq=0, payload=b"abc")) + assertThat(cert_channel).emits(L2capMatchers.IFrame(tx_seq=0, payload=b"abc")) cert_channel.send_i_frame(tx_seq=0, req_seq=1, payload=SAMPLE_PACKET) dut_channel.send(b'abc') - assertThat(cert_channel).emits( - L2capMatchers.IFrame(tx_seq=1, payload=b"abc")) + assertThat(cert_channel).emits(L2capMatchers.IFrame(tx_seq=1, payload=b"abc")) cert_channel.send_i_frame(tx_seq=1, req_seq=2, payload=SAMPLE_PACKET) @@ -769,34 +645,20 @@ class L2capTest(GdBaseTestClass): mode=RetransmissionFlowControlMode.ERTM, fcs=FcsType.NO_FCS) for i in range(3): - cert_channel.send_i_frame( - tx_seq=i, req_seq=0, payload=SAMPLE_PACKET) + cert_channel.send_i_frame(tx_seq=i, req_seq=0, payload=SAMPLE_PACKET) assertThat(cert_channel).emits(L2capMatchers.SFrame(req_seq=i + 1)) - cert_channel.send_i_frame( - tx_seq=3, - req_seq=0, - sar=SegmentationAndReassembly.START, - payload=SAMPLE_PACKET) + cert_channel.send_i_frame(tx_seq=3, req_seq=0, sar=SegmentationAndReassembly.START, payload=SAMPLE_PACKET) assertThat(cert_channel).emits(L2capMatchers.SFrame(req_seq=4)) cert_channel.send_i_frame( - tx_seq=4, - req_seq=0, - sar=SegmentationAndReassembly.CONTINUATION, - payload=SAMPLE_PACKET) + tx_seq=4, req_seq=0, sar=SegmentationAndReassembly.CONTINUATION, payload=SAMPLE_PACKET) assertThat(cert_channel).emits(L2capMatchers.SFrame(req_seq=5)) - cert_channel.send_i_frame( - tx_seq=5, - req_seq=0, - sar=SegmentationAndReassembly.END, - payload=SAMPLE_PACKET) + cert_channel.send_i_frame(tx_seq=5, req_seq=0, sar=SegmentationAndReassembly.END, payload=SAMPLE_PACKET) assertThat(cert_channel).emits(L2capMatchers.SFrame(req_seq=6)) - @metadata( - pts_test_id="L2CAP/ERM/BV-03-C", - pts_test_name="Acknowledging Received I-Frames") + @metadata(pts_test_id="L2CAP/ERM/BV-03-C", pts_test_name="Acknowledging Received I-Frames") def test_acknowledging_received_i_frames(self): """ Verify the IUT sends S-frame [RR] with the Poll bit not set to @@ -808,12 +670,10 @@ class L2capTest(GdBaseTestClass): mode=RetransmissionFlowControlMode.ERTM, fcs=FcsType.NO_FCS) for i in range(3): - cert_channel.send_i_frame( - tx_seq=i, req_seq=0, payload=SAMPLE_PACKET) + cert_channel.send_i_frame(tx_seq=i, req_seq=0, payload=SAMPLE_PACKET) assertThat(cert_channel).emits(L2capMatchers.SFrame(req_seq=i + 1)) - assertThat(cert_channel).emitsNone( - L2capMatchers.SFrame(req_seq=4), timeout=timedelta(seconds=1)) + assertThat(cert_channel).emitsNone(L2capMatchers.SFrame(req_seq=4), timeout=timedelta(seconds=1)) @metadata( pts_test_id="L2CAP/ERM/BV-05-C", @@ -828,28 +688,22 @@ class L2capTest(GdBaseTestClass): """ self._setup_link_from_cert() - config = CertL2cap.config_option_ertm( - fcs=FcsType.NO_FCS, tx_window_size=1) + config = CertL2cap.config_option_ertm(fcs=FcsType.NO_FCS, tx_window_size=1) (dut_channel, cert_channel) = self._open_channel_from_cert( - mode=RetransmissionFlowControlMode.ERTM, - req_config_options=config, - rsp_config_options=config) + mode=RetransmissionFlowControlMode.ERTM, req_config_options=config, rsp_config_options=config) dut_channel.send(b'abc') dut_channel.send(b'def') - assertThat(cert_channel).emits( - L2capMatchers.IFrame(tx_seq=0, payload=b'abc')) - assertThat(cert_channel).emitsNone( - L2capMatchers.IFrame(tx_seq=1, payload=b'def')) + assertThat(cert_channel).emits(L2capMatchers.IFrame(tx_seq=0, payload=b'abc')) + assertThat(cert_channel).emitsNone(L2capMatchers.IFrame(tx_seq=1, payload=b'def')) cert_channel.send_s_frame(req_seq=1, f=Final.POLL_RESPONSE) assertThat(cert_channel).emits(L2capMatchers.IFrame(tx_seq=1)) @metadata( - pts_test_id="L2CAP/ERM/BV-06-C", - pts_test_name="Resume Transmitting I-Frames when an I-Frame is " + pts_test_id="L2CAP/ERM/BV-06-C", pts_test_name="Resume Transmitting I-Frames when an I-Frame is " "Received") def test_resume_transmitting_when_acknowledge_previously_sent(self): """ @@ -859,32 +713,25 @@ class L2capTest(GdBaseTestClass): """ self._setup_link_from_cert() - config = CertL2cap.config_option_ertm( - fcs=FcsType.NO_FCS, tx_window_size=1) + config = CertL2cap.config_option_ertm(fcs=FcsType.NO_FCS, tx_window_size=1) (dut_channel, cert_channel) = self._open_channel_from_cert( - mode=RetransmissionFlowControlMode.ERTM, - req_config_options=config, - rsp_config_options=config) + mode=RetransmissionFlowControlMode.ERTM, req_config_options=config, rsp_config_options=config) dut_channel.send(b'abc') dut_channel.send(b'def') - assertThat(cert_channel).emits( - L2capMatchers.IFrame(tx_seq=0, payload=b'abc')) + assertThat(cert_channel).emits(L2capMatchers.IFrame(tx_seq=0, payload=b'abc')) assertThat(cert_channel).emitsNone( - L2capMatchers.IFrame(tx_seq=1, payload=b'abc'), - timeout=timedelta(seconds=0.5)) + L2capMatchers.IFrame(tx_seq=1, payload=b'abc'), timeout=timedelta(seconds=0.5)) cert_channel.send_i_frame(tx_seq=0, req_seq=1, payload=SAMPLE_PACKET) - assertThat(cert_channel).emits( - L2capMatchers.IFrame(tx_seq=1, payload=b'def')) + assertThat(cert_channel).emits(L2capMatchers.IFrame(tx_seq=1, payload=b'def')) cert_channel.send_i_frame(tx_seq=1, req_seq=2, payload=SAMPLE_PACKET) - @metadata( - pts_test_id="L2CAP/ERM/BV-07-C", pts_test_name="Send S-Frame [RNR]") + @metadata(pts_test_id="L2CAP/ERM/BV-07-C", pts_test_name="Send S-Frame [RNR]") def test_send_s_frame_rnr(self): """ Verify the IUT sends an S-frame [RNR] when it detects local busy condition @@ -893,8 +740,7 @@ class L2capTest(GdBaseTestClass): """ self._setup_link_from_cert() - config = CertL2cap.config_option_ertm( - fcs=FcsType.NO_FCS, tx_window_size=10) + config = CertL2cap.config_option_ertm(fcs=FcsType.NO_FCS, tx_window_size=10) (dut_channel, cert_channel) = self._open_channel_from_cert( mode=RetransmissionFlowControlMode.ERTM, @@ -903,8 +749,7 @@ class L2capTest(GdBaseTestClass): rsp_config_options=config) dut_channel.send(b'abc') - assertThat(cert_channel).emits( - L2capMatchers.IFrame(tx_seq=0, payload=b'abc')) + assertThat(cert_channel).emits(L2capMatchers.IFrame(tx_seq=0, payload=b'abc')) cert_channel.send_i_frame(tx_seq=0, req_seq=1, payload=SAMPLE_PACKET) dut_channel.set_traffic_paused(True) @@ -912,21 +757,13 @@ class L2capTest(GdBaseTestClass): buffer_size = self.dut_l2cap.get_channel_queue_buffer_size() for i in range(buffer_size): - cert_channel.send_i_frame( - tx_seq=i + 1, req_seq=1, payload=SAMPLE_PACKET) - assertThat(cert_channel).emits( - L2capMatchers.SFrame( - s=l2cap_packets.SupervisoryFunction.RECEIVER_READY)) + cert_channel.send_i_frame(tx_seq=i + 1, req_seq=1, payload=SAMPLE_PACKET) + assertThat(cert_channel).emits(L2capMatchers.SFrame(s=l2cap_packets.SupervisoryFunction.RECEIVER_READY)) - cert_channel.send_i_frame( - tx_seq=buffer_size + 1, req_seq=1, payload=SAMPLE_PACKET) - assertThat(cert_channel).emits( - L2capMatchers.SFrame( - s=l2cap_packets.SupervisoryFunction.RECEIVER_NOT_READY)) + cert_channel.send_i_frame(tx_seq=buffer_size + 1, req_seq=1, payload=SAMPLE_PACKET) + assertThat(cert_channel).emits(L2capMatchers.SFrame(s=l2cap_packets.SupervisoryFunction.RECEIVER_NOT_READY)) - @metadata( - pts_test_id="L2CAP/ERM/BV-08-C", - pts_test_name="Send S-Frame [RR] with Poll Bit Set") + @metadata(pts_test_id="L2CAP/ERM/BV-08-C", pts_test_name="Send S-Frame [RR] with Poll Bit Set") def test_transmit_s_frame_rr_with_poll_bit_set(self): """ Verify the IUT sends an S-frame [RR] with the Poll bit set when its @@ -934,8 +771,7 @@ class L2capTest(GdBaseTestClass): """ self._setup_link_from_cert() - config = CertL2cap.config_option_ertm( - fcs=FcsType.NO_FCS, retransmission_time_out=1500) + config = CertL2cap.config_option_ertm(fcs=FcsType.NO_FCS, retransmission_time_out=1500) (dut_channel, cert_channel) = self._open_channel_from_cert( mode=RetransmissionFlowControlMode.ERTM, @@ -944,12 +780,9 @@ class L2capTest(GdBaseTestClass): rsp_config_options=config) dut_channel.send(b'abc') - assertThat(cert_channel).emits( - L2capMatchers.SFrame(p=l2cap_packets.Poll.POLL)) + assertThat(cert_channel).emits(L2capMatchers.SFrame(p=l2cap_packets.Poll.POLL)) - @metadata( - pts_test_id="L2CAP/ERM/BV-09-C", - pts_test_name="Send S-Frame [RR] with Final Bit Set") + @metadata(pts_test_id="L2CAP/ERM/BV-09-C", pts_test_name="Send S-Frame [RR] with Final Bit Set") def test_transmit_s_frame_rr_with_final_bit_set(self): """ Verify the IUT responds with an S-frame [RR] with the Final bit set @@ -961,12 +794,9 @@ class L2capTest(GdBaseTestClass): mode=RetransmissionFlowControlMode.ERTM, fcs=FcsType.NO_FCS) cert_channel.send_s_frame(req_seq=0, p=Poll.POLL) - assertThat(cert_channel).emits( - L2capMatchers.SFrame(f=Final.POLL_RESPONSE)) + assertThat(cert_channel).emits(L2capMatchers.SFrame(f=Final.POLL_RESPONSE)) - @metadata( - pts_test_id="L2CAP/ERM/BV-10-C", - pts_test_name="Retransmit S-Frame [RR] with Final Bit Set") + @metadata(pts_test_id="L2CAP/ERM/BV-10-C", pts_test_name="Retransmit S-Frame [RR] with Final Bit Set") def test_retransmit_s_frame_rr_with_poll_bit_set(self): """ Verify the IUT will retransmit the S-frame [RR] with the Poll bit set @@ -978,38 +808,26 @@ class L2capTest(GdBaseTestClass): mode=RetransmissionFlowControlMode.ERTM, fcs=FcsType.NO_FCS) dut_channel.send(b'abc') - assertThat(cert_channel).emits( - L2capMatchers.IFrame(tx_seq=0, payload=b'abc')) - assertThat(cert_channel).emits( - L2capMatchers.SFrame(req_seq=0, p=Poll.POLL, f=Final.NOT_SET)) + assertThat(cert_channel).emits(L2capMatchers.IFrame(tx_seq=0, payload=b'abc')) + assertThat(cert_channel).emits(L2capMatchers.SFrame(req_seq=0, p=Poll.POLL, f=Final.NOT_SET)) cert_channel.send_s_frame(req_seq=1, f=Final.POLL_RESPONSE) - @metadata( - pts_test_id="L2CAP/ERM/BV-11-C", - pts_test_name="S-Frame Transmissions Exceed MaxTransmit") + @metadata(pts_test_id="L2CAP/ERM/BV-11-C", pts_test_name="S-Frame Transmissions Exceed MaxTransmit") def test_s_frame_transmissions_exceed_max_transmit(self): """ Verify the IUT will close the channel when the Monitor Timer expires. """ self._setup_link_from_cert() - config = CertL2cap.config_option_ertm( - fcs=FcsType.NO_FCS, - tx_window_size=1, - max_transmit=1, - monitor_time_out=10) + config = CertL2cap.config_option_ertm(fcs=FcsType.NO_FCS, tx_window_size=1, max_transmit=1, monitor_time_out=10) (dut_channel, cert_channel) = self._open_channel_from_cert( - mode=RetransmissionFlowControlMode.ERTM, - req_config_options=config, - rsp_config_options=config) + mode=RetransmissionFlowControlMode.ERTM, req_config_options=config, rsp_config_options=config) dut_channel.send(b'abc') cert_channel.verify_disconnect_request() - @metadata( - pts_test_id="L2CAP/ERM/BV-12-C", - pts_test_name="I-Frame Transmissions Exceed MaxTransmit") + @metadata(pts_test_id="L2CAP/ERM/BV-12-C", pts_test_name="I-Frame Transmissions Exceed MaxTransmit") def test_i_frame_transmissions_exceed_max_transmit(self): """ Verify the IUT will close the channel when it receives an S-frame [RR] @@ -1018,25 +836,18 @@ class L2capTest(GdBaseTestClass): """ self._setup_link_from_cert() - config = CertL2cap.config_option_ertm( - fcs=FcsType.NO_FCS, tx_window_size=1, max_transmit=1) + config = CertL2cap.config_option_ertm(fcs=FcsType.NO_FCS, tx_window_size=1, max_transmit=1) (dut_channel, cert_channel) = self._open_channel_from_cert( - mode=RetransmissionFlowControlMode.ERTM, - req_config_options=config, - rsp_config_options=config) + mode=RetransmissionFlowControlMode.ERTM, req_config_options=config, rsp_config_options=config) dut_channel.send(b'abc') - assertThat(cert_channel).emits( - L2capMatchers.IFrame(tx_seq=0), - L2capMatchers.SFrame(p=Poll.POLL)).inOrder() + assertThat(cert_channel).emits(L2capMatchers.IFrame(tx_seq=0), L2capMatchers.SFrame(p=Poll.POLL)).inOrder() cert_channel.send_s_frame(req_seq=0, f=Final.POLL_RESPONSE) cert_channel.verify_disconnect_request() - @metadata( - pts_test_id="L2CAP/ERM/BV-13-C", - pts_test_name="Respond to S-Frame [REJ]") + @metadata(pts_test_id="L2CAP/ERM/BV-13-C", pts_test_name="Respond to S-Frame [REJ]") def test_respond_to_rej(self): """ Verify the IUT retransmits I-frames starting from the sequence number @@ -1044,29 +855,22 @@ class L2capTest(GdBaseTestClass): """ self._setup_link_from_cert() - config = CertL2cap.config_option_ertm( - fcs=FcsType.NO_FCS, tx_window_size=2, max_transmit=2) + config = CertL2cap.config_option_ertm(fcs=FcsType.NO_FCS, tx_window_size=2, max_transmit=2) (dut_channel, cert_channel) = self._open_channel_from_cert( - mode=RetransmissionFlowControlMode.ERTM, - req_config_options=config, - rsp_config_options=config) + mode=RetransmissionFlowControlMode.ERTM, req_config_options=config, rsp_config_options=config) dut_channel.send(b'abc') dut_channel.send(b'abc') assertThat(cert_channel).emits( - L2capMatchers.IFrame(tx_seq=0, payload=b'abc'), - L2capMatchers.IFrame(tx_seq=1, payload=b'abc')).inOrder() + L2capMatchers.IFrame(tx_seq=0, payload=b'abc'), L2capMatchers.IFrame(tx_seq=1, payload=b'abc')).inOrder() cert_channel.send_s_frame(req_seq=0, s=SupervisoryFunction.REJECT) assertThat(cert_channel).emits( - L2capMatchers.IFrame(tx_seq=0, payload=b'abc'), - L2capMatchers.IFrame(tx_seq=1, payload=b'abc')).inOrder() + L2capMatchers.IFrame(tx_seq=0, payload=b'abc'), L2capMatchers.IFrame(tx_seq=1, payload=b'abc')).inOrder() - @metadata( - pts_test_id="L2CAP/ERM/BV-14-C", - pts_test_name="Respond to S-Frame [SREJ] POLL Bit Set") + @metadata(pts_test_id="L2CAP/ERM/BV-14-C", pts_test_name="Respond to S-Frame [SREJ] POLL Bit Set") def test_respond_to_srej_p_set(self): """ Verify the IUT responds with the correct I-frame when sent an SREJ @@ -1075,63 +879,46 @@ class L2capTest(GdBaseTestClass): """ self._setup_link_from_cert() - config = CertL2cap.config_option_ertm( - fcs=FcsType.NO_FCS, max_transmit=2, tx_window_size=3) + config = CertL2cap.config_option_ertm(fcs=FcsType.NO_FCS, max_transmit=2, tx_window_size=3) (dut_channel, cert_channel) = self._open_channel_from_cert( - mode=RetransmissionFlowControlMode.ERTM, - req_config_options=config, - rsp_config_options=config) + mode=RetransmissionFlowControlMode.ERTM, req_config_options=config, rsp_config_options=config) for _ in range(4): dut_channel.send(b'abc') assertThat(cert_channel).emits( - L2capMatchers.IFrame(tx_seq=0, payload=b'abc'), - L2capMatchers.IFrame(tx_seq=1, payload=b'abc'), + L2capMatchers.IFrame(tx_seq=0, payload=b'abc'), L2capMatchers.IFrame(tx_seq=1, payload=b'abc'), L2capMatchers.IFrame(tx_seq=2, payload=b'abc')).inOrder() - cert_channel.send_s_frame( - req_seq=1, p=Poll.POLL, s=SupervisoryFunction.SELECT_REJECT) + cert_channel.send_s_frame(req_seq=1, p=Poll.POLL, s=SupervisoryFunction.SELECT_REJECT) assertThat(cert_channel).emits( - L2capMatchers.IFrame( - tx_seq=1, payload=b'abc', f=Final.POLL_RESPONSE), + L2capMatchers.IFrame(tx_seq=1, payload=b'abc', f=Final.POLL_RESPONSE), L2capMatchers.IFrame(tx_seq=3, payload=b'abc')).inOrder() - @metadata( - pts_test_id="L2CAP/ERM/BV-15-C", - pts_test_name="Respond to S-Frame [SREJ] POLL Bit Clear") + @metadata(pts_test_id="L2CAP/ERM/BV-15-C", pts_test_name="Respond to S-Frame [SREJ] POLL Bit Clear") def test_respond_to_srej_p_clear(self): """ Verify the IUT responds with the correct I-frame when sent an SREJ frame """ self._setup_link_from_cert() - config = CertL2cap.config_option_ertm( - fcs=FcsType.NO_FCS, max_transmit=2, tx_window_size=3) + config = CertL2cap.config_option_ertm(fcs=FcsType.NO_FCS, max_transmit=2, tx_window_size=3) (dut_channel, cert_channel) = self._open_channel_from_cert( - mode=RetransmissionFlowControlMode.ERTM, - req_config_options=config, - rsp_config_options=config) + mode=RetransmissionFlowControlMode.ERTM, req_config_options=config, rsp_config_options=config) for _ in range(4): dut_channel.send(b'abc') assertThat(cert_channel).emits( - L2capMatchers.IFrame(tx_seq=0, payload=b'abc'), - L2capMatchers.IFrame(tx_seq=1, payload=b'abc'), + L2capMatchers.IFrame(tx_seq=0, payload=b'abc'), L2capMatchers.IFrame(tx_seq=1, payload=b'abc'), L2capMatchers.IFrame(tx_seq=2, payload=b'abc')).inOrder() - cert_channel.send_s_frame( - req_seq=1, s=SupervisoryFunction.SELECT_REJECT) - assertThat(cert_channel).emits( - L2capMatchers.IFrame(tx_seq=1, payload=b'abc', f=Final.NOT_SET)) - cert_channel.send_s_frame( - req_seq=3, s=SupervisoryFunction.RECEIVER_READY) - assertThat(cert_channel).emits( - L2capMatchers.IFrame(tx_seq=3, payload=b'abc', f=Final.NOT_SET)) + cert_channel.send_s_frame(req_seq=1, s=SupervisoryFunction.SELECT_REJECT) + assertThat(cert_channel).emits(L2capMatchers.IFrame(tx_seq=1, payload=b'abc', f=Final.NOT_SET)) + cert_channel.send_s_frame(req_seq=3, s=SupervisoryFunction.RECEIVER_READY) + assertThat(cert_channel).emits(L2capMatchers.IFrame(tx_seq=3, payload=b'abc', f=Final.NOT_SET)) - @metadata( - pts_test_id="L2CAP/ERM/BV-16-C", pts_test_name="Send S-Frame [REJ]") + @metadata(pts_test_id="L2CAP/ERM/BV-16-C", pts_test_name="Send S-Frame [REJ]") def test_send_s_frame_rej(self): """ Verify the IUT can send an S-Frame [REJ] after receiving out of sequence @@ -1140,38 +927,23 @@ class L2capTest(GdBaseTestClass): self._setup_link_from_cert() tx_window_size = 4 - config = CertL2cap.config_option_ertm( - fcs=FcsType.NO_FCS, tx_window_size=tx_window_size) + config = CertL2cap.config_option_ertm(fcs=FcsType.NO_FCS, tx_window_size=tx_window_size) (dut_channel, cert_channel) = self._open_channel_from_cert( - mode=RetransmissionFlowControlMode.ERTM, - req_config_options=config, - rsp_config_options=config) + mode=RetransmissionFlowControlMode.ERTM, req_config_options=config, rsp_config_options=config) - cert_channel.send_i_frame( - tx_seq=0, req_seq=0, f=Final.NOT_SET, payload=SAMPLE_PACKET) - cert_channel.send_i_frame( - tx_seq=2, req_seq=0, f=Final.NOT_SET, payload=SAMPLE_PACKET) + cert_channel.send_i_frame(tx_seq=0, req_seq=0, f=Final.NOT_SET, payload=SAMPLE_PACKET) + cert_channel.send_i_frame(tx_seq=2, req_seq=0, f=Final.NOT_SET, payload=SAMPLE_PACKET) assertThat(cert_channel).emits( - L2capMatchers.SFrame( - req_seq=1, - f=Final.NOT_SET, - s=SupervisoryFunction.REJECT, - p=Poll.NOT_SET)) + L2capMatchers.SFrame(req_seq=1, f=Final.NOT_SET, s=SupervisoryFunction.REJECT, p=Poll.NOT_SET)) for i in range(1, tx_window_size): - cert_channel.send_i_frame( - tx_seq=i, req_seq=0, f=Final.NOT_SET, payload=SAMPLE_PACKET) + cert_channel.send_i_frame(tx_seq=i, req_seq=0, f=Final.NOT_SET, payload=SAMPLE_PACKET) assertThat(cert_channel).emits( L2capMatchers.SFrame( - req_seq=tx_window_size, - f=Final.NOT_SET, - s=SupervisoryFunction.RECEIVER_READY, - p=Poll.NOT_SET)) + req_seq=tx_window_size, f=Final.NOT_SET, s=SupervisoryFunction.RECEIVER_READY, p=Poll.NOT_SET)) - @metadata( - pts_test_id="L2CAP/ERM/BV-18-C", - pts_test_name="Receive S-Frame [RR] Final Bit = 1") + @metadata(pts_test_id="L2CAP/ERM/BV-18-C", pts_test_name="Receive S-Frame [RR] Final Bit = 1") def test_receive_s_frame_rr_final_bit_set(self): """ Verify the IUT will retransmit any previously sent I-frames @@ -1179,25 +951,19 @@ class L2capTest(GdBaseTestClass): """ self._setup_link_from_cert() - config = CertL2cap.config_option_ertm( - fcs=FcsType.NO_FCS, retransmission_time_out=1500) + config = CertL2cap.config_option_ertm(fcs=FcsType.NO_FCS, retransmission_time_out=1500) (dut_channel, cert_channel) = self._open_channel_from_cert( - mode=RetransmissionFlowControlMode.ERTM, - req_config_options=config, - rsp_config_options=config) + mode=RetransmissionFlowControlMode.ERTM, req_config_options=config, rsp_config_options=config) dut_channel.send(b'abc') - assertThat(cert_channel).emits( - L2capMatchers.SFrame(p=l2cap_packets.Poll.POLL)) + assertThat(cert_channel).emits(L2capMatchers.SFrame(p=l2cap_packets.Poll.POLL)) cert_channel.send_s_frame(req_seq=0, f=Final.POLL_RESPONSE) assertThat(cert_channel).emits(L2capMatchers.IFrame(tx_seq=0)) - @metadata( - pts_test_id="L2CAP/ERM/BV-19-C", - pts_test_name="Receive I-Frame Final Bit = 1") + @metadata(pts_test_id="L2CAP/ERM/BV-19-C", pts_test_name="Receive I-Frame Final Bit = 1") def test_receive_i_frame_final_bit_set(self): """ Verify the IUT will retransmit any previously sent I-frames @@ -1205,23 +971,17 @@ class L2capTest(GdBaseTestClass): """ self._setup_link_from_cert() - config = CertL2cap.config_option_ertm( - fcs=FcsType.NO_FCS, retransmission_time_out=1500) + config = CertL2cap.config_option_ertm(fcs=FcsType.NO_FCS, retransmission_time_out=1500) (dut_channel, cert_channel) = self._open_channel_from_cert( - mode=RetransmissionFlowControlMode.ERTM, - req_config_options=config, - rsp_config_options=config) + mode=RetransmissionFlowControlMode.ERTM, req_config_options=config, rsp_config_options=config) dut_channel.send(b'abc') assertThat(cert_channel).emits(L2capMatchers.SFrame(p=Poll.POLL)) - cert_channel.send_i_frame( - tx_seq=0, req_seq=0, f=Final.POLL_RESPONSE, payload=SAMPLE_PACKET) + cert_channel.send_i_frame(tx_seq=0, req_seq=0, f=Final.POLL_RESPONSE, payload=SAMPLE_PACKET) assertThat(cert_channel).emits(L2capMatchers.IFrame(tx_seq=0)) - @metadata( - pts_test_id="L2CAP/ERM/BV-20-C", - pts_test_name="Enter Remote Busy Condition") + @metadata(pts_test_id="L2CAP/ERM/BV-20-C", pts_test_name="Enter Remote Busy Condition") def test_receive_rnr(self): """ Verify the IUT will not retransmit any I-frames when it receives a @@ -1229,26 +989,17 @@ class L2capTest(GdBaseTestClass): """ self._setup_link_from_cert() - config = CertL2cap.config_option_ertm( - fcs=FcsType.NO_FCS, retransmission_time_out=1500) + config = CertL2cap.config_option_ertm(fcs=FcsType.NO_FCS, retransmission_time_out=1500) (dut_channel, cert_channel) = self._open_channel_from_cert( - mode=RetransmissionFlowControlMode.ERTM, - req_config_options=config, - rsp_config_options=config) + mode=RetransmissionFlowControlMode.ERTM, req_config_options=config, rsp_config_options=config) dut_channel.send(b'abc') - assertThat(cert_channel).emits( - L2capMatchers.SFrame(p=l2cap_packets.Poll.POLL)) + assertThat(cert_channel).emits(L2capMatchers.SFrame(p=l2cap_packets.Poll.POLL)) - cert_channel.send_s_frame( - req_seq=0, - s=SupervisoryFunction.RECEIVER_NOT_READY, - f=Final.POLL_RESPONSE) + cert_channel.send_s_frame(req_seq=0, s=SupervisoryFunction.RECEIVER_NOT_READY, f=Final.POLL_RESPONSE) assertThat(cert_channel).emitsNone(L2capMatchers.IFrame(tx_seq=0)) - @metadata( - pts_test_id="L2CAP/ERM/BV-22-C", - pts_test_name="Exit Local Busy Condition") + @metadata(pts_test_id="L2CAP/ERM/BV-22-C", pts_test_name="Exit Local Busy Condition") def test_exit_local_busy_condition(self): """ Verify the IUT sends an S-frame [RR] Poll = 1 when the local busy condition is cleared @@ -1257,8 +1008,7 @@ class L2capTest(GdBaseTestClass): """ self._setup_link_from_cert() - config = CertL2cap.config_option_ertm( - fcs=FcsType.NO_FCS, tx_window_size=10) + config = CertL2cap.config_option_ertm(fcs=FcsType.NO_FCS, tx_window_size=10) (dut_channel, cert_channel) = self._open_channel_from_cert( mode=RetransmissionFlowControlMode.ERTM, @@ -1267,8 +1017,7 @@ class L2capTest(GdBaseTestClass): rsp_config_options=config) dut_channel.send(b'abc') - assertThat(cert_channel).emits( - L2capMatchers.IFrame(tx_seq=0, payload=b'abc')) + assertThat(cert_channel).emits(L2capMatchers.IFrame(tx_seq=0, payload=b'abc')) cert_channel.send_i_frame(tx_seq=0, req_seq=1, payload=SAMPLE_PACKET) dut_channel.set_traffic_paused(True) @@ -1276,28 +1025,18 @@ class L2capTest(GdBaseTestClass): buffer_size = self.dut_l2cap.get_channel_queue_buffer_size() for i in range(buffer_size): - cert_channel.send_i_frame( - tx_seq=i + 1, req_seq=1, payload=SAMPLE_PACKET) - assertThat(cert_channel).emits( - L2capMatchers.SFrame( - s=l2cap_packets.SupervisoryFunction.RECEIVER_READY)) + cert_channel.send_i_frame(tx_seq=i + 1, req_seq=1, payload=SAMPLE_PACKET) + assertThat(cert_channel).emits(L2capMatchers.SFrame(s=l2cap_packets.SupervisoryFunction.RECEIVER_READY)) - cert_channel.send_i_frame( - tx_seq=buffer_size + 1, req_seq=1, payload=SAMPLE_PACKET) - assertThat(cert_channel).emits( - L2capMatchers.SFrame( - s=l2cap_packets.SupervisoryFunction.RECEIVER_NOT_READY)) + cert_channel.send_i_frame(tx_seq=buffer_size + 1, req_seq=1, payload=SAMPLE_PACKET) + assertThat(cert_channel).emits(L2capMatchers.SFrame(s=l2cap_packets.SupervisoryFunction.RECEIVER_NOT_READY)) dut_channel.set_traffic_paused(False) assertThat(cert_channel).emits( - L2capMatchers.SFrame( - s=l2cap_packets.SupervisoryFunction.RECEIVER_READY, - p=l2cap_packets.Poll.POLL)) + L2capMatchers.SFrame(s=l2cap_packets.SupervisoryFunction.RECEIVER_READY, p=l2cap_packets.Poll.POLL)) cert_channel.send_s_frame(1, f=l2cap_packets.Final.POLL_RESPONSE) - @metadata( - pts_test_id="L2CAP/ERM/BV-23-C", - pts_test_name="Transmit I-Frames using SAR") + @metadata(pts_test_id="L2CAP/ERM/BV-23-C", pts_test_name="Transmit I-Frames using SAR") def test_transmit_i_frames_using_sar(self): """ Verify the IUT can send correctly formatted sequential I-frames with @@ -1308,30 +1047,23 @@ class L2capTest(GdBaseTestClass): config = CertL2cap.config_option_ertm(fcs=FcsType.NO_FCS, mps=11) (dut_channel, cert_channel) = self._open_channel_from_cert( - mode=RetransmissionFlowControlMode.ERTM, - req_config_options=config, - rsp_config_options=config) + mode=RetransmissionFlowControlMode.ERTM, req_config_options=config, rsp_config_options=config) dut_channel.send(b'abcabcabc') # First IFrame should contain SDU size after control field assertThat(cert_channel).emits( - L2capMatchers.IFrameStart(tx_seq=0, payload=b'abc'), - L2capMatchers.IFrame(tx_seq=1, payload=b'abc'), + L2capMatchers.IFrameStart(tx_seq=0, payload=b'abc'), L2capMatchers.IFrame(tx_seq=1, payload=b'abc'), L2capMatchers.IFrame(tx_seq=2, payload=b'abc')).inOrder() - cert_channel.send_s_frame( - req_seq=3, s=SupervisoryFunction.RECEIVER_READY) + cert_channel.send_s_frame(req_seq=3, s=SupervisoryFunction.RECEIVER_READY) dut_channel.send(b'defdefdef') # First IFrame should contain SDU size after control field assertThat(cert_channel).emits( - L2capMatchers.IFrameStart(tx_seq=3, payload=b'def'), - L2capMatchers.IFrame(tx_seq=4, payload=b'def'), + L2capMatchers.IFrameStart(tx_seq=3, payload=b'def'), L2capMatchers.IFrame(tx_seq=4, payload=b'def'), L2capMatchers.IFrame(tx_seq=5, payload=b'def')).inOrder() - @metadata( - pts_test_id="L2CAP/ERM/BI-01-C", - pts_test_name="S-Frame [REJ] Lost or Corrupted") + @metadata(pts_test_id="L2CAP/ERM/BI-01-C", pts_test_name="S-Frame [REJ] Lost or Corrupted") def test_sent_rej_lost(self): """ Verify the IUT can handle receipt of an S-=frame [RR] Poll = 1 if the @@ -1340,34 +1072,24 @@ class L2capTest(GdBaseTestClass): self._setup_link_from_cert() ertm_tx_window_size = 5 - config = CertL2cap.config_option_ertm( - fcs=FcsType.NO_FCS, tx_window_size=ertm_tx_window_size) + config = CertL2cap.config_option_ertm(fcs=FcsType.NO_FCS, tx_window_size=ertm_tx_window_size) (dut_channel, cert_channel) = self._open_channel_from_cert( - mode=RetransmissionFlowControlMode.ERTM, - req_config_options=config, - rsp_config_options=config) + mode=RetransmissionFlowControlMode.ERTM, req_config_options=config, rsp_config_options=config) cert_channel.send_i_frame(tx_seq=0, req_seq=0, payload=SAMPLE_PACKET) assertThat(cert_channel).emits(L2capMatchers.SFrame(req_seq=1)) - cert_channel.send_i_frame( - tx_seq=ertm_tx_window_size - 1, req_seq=0, payload=SAMPLE_PACKET) - assertThat(cert_channel).emits( - L2capMatchers.SFrame(s=SupervisoryFunction.REJECT)) + cert_channel.send_i_frame(tx_seq=ertm_tx_window_size - 1, req_seq=0, payload=SAMPLE_PACKET) + assertThat(cert_channel).emits(L2capMatchers.SFrame(s=SupervisoryFunction.REJECT)) cert_channel.send_s_frame(req_seq=0, p=Poll.POLL) - assertThat(cert_channel).emits( - L2capMatchers.SFrame( - req_seq=1, f=l2cap_packets.Final.POLL_RESPONSE)) + assertThat(cert_channel).emits(L2capMatchers.SFrame(req_seq=1, f=l2cap_packets.Final.POLL_RESPONSE)) for i in range(1, ertm_tx_window_size): - cert_channel.send_i_frame( - tx_seq=i, req_seq=0, payload=SAMPLE_PACKET) + cert_channel.send_i_frame(tx_seq=i, req_seq=0, payload=SAMPLE_PACKET) assertThat(cert_channel).emits(L2capMatchers.SFrame(req_seq=i + 1)) - @metadata( - pts_test_id="L2CAP/ERM/BI-03-C", - pts_test_name="Handle Duplicate S-Frame [SREJ]") + @metadata(pts_test_id="L2CAP/ERM/BI-03-C", pts_test_name="Handle Duplicate S-Frame [SREJ]") def test_handle_duplicate_srej(self): """ Verify the IUT will only retransmit the requested I-frame once after @@ -1381,18 +1103,13 @@ class L2capTest(GdBaseTestClass): dut_channel.send(b'abc') dut_channel.send(b'abc') assertThat(cert_channel).emits( - L2capMatchers.IFrame(tx_seq=0), - L2capMatchers.IFrame(tx_seq=1), + L2capMatchers.IFrame(tx_seq=0), L2capMatchers.IFrame(tx_seq=1), L2capMatchers.SFrame(p=Poll.POLL)).inOrder() - cert_channel.send_s_frame( - req_seq=0, s=SupervisoryFunction.SELECT_REJECT) + cert_channel.send_s_frame(req_seq=0, s=SupervisoryFunction.SELECT_REJECT) assertThat(cert_channel).emitsNone(timeout=timedelta(seconds=0.5)) - cert_channel.send_s_frame( - req_seq=0, - s=SupervisoryFunction.SELECT_REJECT, - f=Final.POLL_RESPONSE) + cert_channel.send_s_frame(req_seq=0, s=SupervisoryFunction.SELECT_REJECT, f=Final.POLL_RESPONSE) assertThat(cert_channel).emits(L2capMatchers.IFrame(tx_seq=0)) @metadata( @@ -1422,8 +1139,7 @@ class L2capTest(GdBaseTestClass): assertThat(cert_channel).emitsNone(timeout=timedelta(seconds=0.5)) # Send RR with F set - cert_channel.send_s_frame( - req_seq=0, s=SupervisoryFunction.REJECT, f=Final.POLL_RESPONSE) + cert_channel.send_s_frame(req_seq=0, s=SupervisoryFunction.REJECT, f=Final.POLL_RESPONSE) assertThat(cert_channel).emits(L2capMatchers.IFrame(tx_seq=0)) assertThat(cert_channel).emits(L2capMatchers.IFrame(tx_seq=1)) @@ -1451,19 +1167,16 @@ class L2capTest(GdBaseTestClass): L2capMatchers.SFrame(p=l2cap_packets.Poll.POLL)).inOrder() # Send SREJ with F not set - cert_channel.send_s_frame( - req_seq=0, s=SupervisoryFunction.SELECT_REJECT) + cert_channel.send_s_frame(req_seq=0, s=SupervisoryFunction.SELECT_REJECT) assertThat(cert_channel).emitsNone(timeout=timedelta(seconds=0.5)) - cert_channel.send_i_frame( - tx_seq=0, req_seq=0, f=Final.POLL_RESPONSE, payload=SAMPLE_PACKET) + cert_channel.send_i_frame(tx_seq=0, req_seq=0, f=Final.POLL_RESPONSE, payload=SAMPLE_PACKET) assertThat(cert_channel).emits(L2capMatchers.IFrame(tx_seq=0)) assertThat(cert_channel).emits(L2capMatchers.IFrame(tx_seq=1)) @metadata( - pts_test_id="L2CAP/CMC/BV-01-C", - pts_test_name="IUT Initiated Configuration of Enhanced " + pts_test_id="L2CAP/CMC/BV-01-C", pts_test_name="IUT Initiated Configuration of Enhanced " "Retransmission Mode") def test_initiated_configuration_request_ertm(self): """ @@ -1472,11 +1185,9 @@ class L2capTest(GdBaseTestClass): """ self._setup_link_from_cert() - self._open_unconfigured_channel_from_cert( - scid=0x41, psm=0x33, mode=RetransmissionFlowControlMode.ERTM) + self._open_unconfigured_channel_from_cert(scid=0x41, psm=0x33, mode=RetransmissionFlowControlMode.ERTM) - assertThat(self.cert_l2cap.get_control_channel()).emits( - L2capMatchers.ConfigurationRequestWithErtm()) + assertThat(self.cert_l2cap.get_control_channel()).emits(L2capMatchers.ConfigurationRequestWithErtm()) @metadata( pts_test_id="L2CAP/CMC/BV-02-C", @@ -1489,8 +1200,7 @@ class L2capTest(GdBaseTestClass): """ self._setup_link_from_cert() - self._open_channel_from_dut( - psm=0x33, mode=RetransmissionFlowControlMode.ERTM) + self._open_channel_from_dut(psm=0x33, mode=RetransmissionFlowControlMode.ERTM) @metadata( pts_test_id="L2CAP/CMC/BV-12-C", @@ -1507,8 +1217,7 @@ class L2capTest(GdBaseTestClass): self.cert_l2cap.claim_ertm_unsupported() dut_channel_future = self.dut_l2cap.connect_dynamic_channel_to_cert( psm=0x33, mode=RetransmissionFlowControlMode.ERTM) - assertThat(self.cert_l2cap.get_control_channel()).emitsNone( - L2capMatchers.ConnectionRequest(0x33)) + assertThat(self.cert_l2cap.get_control_channel()).emitsNone(L2capMatchers.ConnectionRequest(0x33)) @metadata( pts_test_id="L2CAP/CMC/BI-01-C", @@ -1544,8 +1253,6 @@ class L2capTest(GdBaseTestClass): """ self._setup_link_from_cert() - (dut_channel, cert_channel) = self._open_unconfigured_channel_from_cert( - mode=RetransmissionFlowControlMode.ERTM) - cert_channel.send_configure_request( - CertL2cap.config_option_basic_explicit()) + (dut_channel, cert_channel) = self._open_unconfigured_channel_from_cert(mode=RetransmissionFlowControlMode.ERTM) + cert_channel.send_configure_request(CertL2cap.config_option_basic_explicit()) cert_channel.verify_disconnect_request() diff --git a/system/gd/l2cap/classic/cert/pts_l2cap_test.py b/system/gd/l2cap/classic/cert/pts_l2cap_test.py index 266c8d9294..6b1ea3333b 100644 --- a/system/gd/l2cap/classic/cert/pts_l2cap_test.py +++ b/system/gd/l2cap/classic/cert/pts_l2cap_test.py @@ -32,47 +32,35 @@ class PTSL2capTest(PTSBaseTestClass): self.device_under_test.rootservice.StartStack( facade_rootservice_pb2.StartStackRequest( - module_under_test=facade_rootservice_pb2.BluetoothModule.Value( - 'L2CAP'),)) + module_under_test=facade_rootservice_pb2.BluetoothModule.Value('L2CAP'),)) self.device_under_test.wait_channel_ready() - dut_address = self.device_under_test.controller_read_only_property.ReadLocalAddress( - empty_pb2.Empty()).address + dut_address = self.device_under_test.controller_read_only_property.ReadLocalAddress(empty_pb2.Empty()).address pts_address = self.controller_configs.get('pts_address').lower() self.device_under_test.address = dut_address - self.dut_address = common_pb2.BluetoothAddress( - address=self.device_under_test.address) - self.pts_address = common_pb2.BluetoothAddress( - address=str.encode(pts_address)) + self.dut_address = common_pb2.BluetoothAddress(address=self.device_under_test.address) + self.pts_address = common_pb2.BluetoothAddress(address=str.encode(pts_address)) - self.device_under_test.neighbor.EnablePageScan( - neighbor_facade.EnableMsg(enabled=True)) + self.device_under_test.neighbor.EnablePageScan(neighbor_facade.EnableMsg(enabled=True)) def teardown_test(self): - self.device_under_test.rootservice.StopStack( - facade_rootservice_pb2.StopStackRequest()) + self.device_under_test.rootservice.StopStack(facade_rootservice_pb2.StopStackRequest()) def _dut_connection_stream(self): - return EventStream( - self.device_under_test.l2cap.FetchConnectionComplete( - empty_pb2.Empty())) + return EventStream(self.device_under_test.l2cap.FetchConnectionComplete(empty_pb2.Empty())) def _dut_connection_close_stream(self): - return EventStream( - self.device_under_test.l2cap.FetchConnectionClose( - empty_pb2.Empty())) + return EventStream(self.device_under_test.l2cap.FetchConnectionClose(empty_pb2.Empty())) def _assert_connection_complete(self, due_connection_stream, timeout=30): due_connection_stream.assert_event_occurs( - lambda device: device.remote.address == self.pts_address.address, - timeout=timedelta(seconds=timeout)) + lambda device: device.remote.address == self.pts_address.address, timeout=timedelta(seconds=timeout)) def _assert_connection_close(self, due_connection_close_stream, timeout=30): due_connection_close_stream.assert_event_occurs( - lambda device: device.remote.address == self.pts_address.address, - timeout=timedelta(seconds=timeout)) + lambda device: device.remote.address == self.pts_address.address, timeout=timedelta(seconds=timeout)) def test_L2CAP_IEX_BV_01_C(self): """ @@ -81,9 +69,7 @@ class PTSL2capTest(PTSBaseTestClass): Specification 1.2 features. """ psm = 1 - self.device_under_test.l2cap.OpenChannel( - l2cap_facade_pb2.OpenChannelRequest( - remote=self.pts_address, psm=psm)) + self.device_under_test.l2cap.OpenChannel(l2cap_facade_pb2.OpenChannelRequest(remote=self.pts_address, psm=psm)) time.sleep(5) def test_L2CAP_IEX_BV_02_C(self): @@ -95,8 +81,7 @@ class PTSL2capTest(PTSBaseTestClass): psm = 1 retransmission_mode = l2cap_facade_pb2.RetransmissionFlowControlMode.ERTM self.device_under_test.l2cap.SetDynamicChannel( - l2cap_facade_pb2.SetEnableDynamicChannelRequest( - psm=psm, retransmission_mode=retransmission_mode)) + l2cap_facade_pb2.SetEnableDynamicChannelRequest(psm=psm, retransmission_mode=retransmission_mode)) time.sleep(20) def test_L2CAP_EXF_BV_01_C(self): @@ -109,8 +94,7 @@ class PTSL2capTest(PTSBaseTestClass): psm = 1 retransmission_mode = l2cap_facade_pb2.RetransmissionFlowControlMode.ERTM self.device_under_test.l2cap.SetDynamicChannel( - l2cap_facade_pb2.SetEnableDynamicChannelRequest( - psm=psm, retransmission_mode=retransmission_mode)) + l2cap_facade_pb2.SetEnableDynamicChannelRequest(psm=psm, retransmission_mode=retransmission_mode)) time.sleep(5) def test_L2CAP_EXF_BV_03_C(self): @@ -122,8 +106,7 @@ class PTSL2capTest(PTSBaseTestClass): psm = 1 retransmission_mode = l2cap_facade_pb2.RetransmissionFlowControlMode.ERTM self.device_under_test.l2cap.SetDynamicChannel( - l2cap_facade_pb2.SetEnableDynamicChannelRequest( - psm=psm, retransmission_mode=retransmission_mode)) + l2cap_facade_pb2.SetEnableDynamicChannelRequest(psm=psm, retransmission_mode=retransmission_mode)) time.sleep(5) def test_L2CAP_CMC_BV_01_C(self): @@ -136,8 +119,7 @@ class PTSL2capTest(PTSBaseTestClass): psm = 1 retransmission_mode = l2cap_facade_pb2.RetransmissionFlowControlMode.ERTM self.device_under_test.l2cap.SetDynamicChannel( - l2cap_facade_pb2.SetEnableDynamicChannelRequest( - psm=psm, retransmission_mode=retransmission_mode)) + l2cap_facade_pb2.SetEnableDynamicChannelRequest(psm=psm, retransmission_mode=retransmission_mode)) self._assert_connection_close(due_connection_close_stream) def test_L2CAP_CMC_BV_02_C(self): @@ -150,8 +132,7 @@ class PTSL2capTest(PTSBaseTestClass): psm = 1 retransmission_mode = l2cap_facade_pb2.RetransmissionFlowControlMode.ERTM self.device_under_test.l2cap.SetDynamicChannel( - l2cap_facade_pb2.SetEnableDynamicChannelRequest( - psm=psm, retransmission_mode=retransmission_mode)) + l2cap_facade_pb2.SetEnableDynamicChannelRequest(psm=psm, retransmission_mode=retransmission_mode)) self._assert_connection_close(due_connection_close_stream) def test_L2CAP_ERM_BV_01_C(self): @@ -165,8 +146,7 @@ class PTSL2capTest(PTSBaseTestClass): psm = 1 retransmission_mode = l2cap_facade_pb2.RetransmissionFlowControlMode.ERTM self.device_under_test.l2cap.SetDynamicChannel( - l2cap_facade_pb2.SetEnableDynamicChannelRequest( - psm=psm, retransmission_mode=retransmission_mode)) + l2cap_facade_pb2.SetEnableDynamicChannelRequest(psm=psm, retransmission_mode=retransmission_mode)) self._assert_connection_complete(due_connection_stream) self.device_under_test.l2cap.SendDynamicChannelPacket( l2cap_facade_pb2.DynamicChannelPacket(psm=psm, payload=b'abc')) @@ -186,8 +166,7 @@ class PTSL2capTest(PTSBaseTestClass): psm = 1 retransmission_mode = l2cap_facade_pb2.RetransmissionFlowControlMode.ERTM self.device_under_test.l2cap.SetDynamicChannel( - l2cap_facade_pb2.SetEnableDynamicChannelRequest( - psm=psm, retransmission_mode=retransmission_mode)) + l2cap_facade_pb2.SetEnableDynamicChannelRequest(psm=psm, retransmission_mode=retransmission_mode)) self._assert_connection_complete(due_connection_stream) self._assert_connection_close(due_connection_close_stream) @@ -200,8 +179,7 @@ class PTSL2capTest(PTSBaseTestClass): psm = 1 retransmission_mode = l2cap_facade_pb2.RetransmissionFlowControlMode.ERTM self.device_under_test.l2cap.SetDynamicChannel( - l2cap_facade_pb2.SetEnableDynamicChannelRequest( - psm=psm, retransmission_mode=retransmission_mode)) + l2cap_facade_pb2.SetEnableDynamicChannelRequest(psm=psm, retransmission_mode=retransmission_mode)) self._assert_connection_complete(due_connection_stream) self._assert_connection_close(due_connection_close_stream) @@ -218,9 +196,7 @@ class PTSL2capTest(PTSBaseTestClass): self.device_under_test.l2cap.SetDynamicChannel( l2cap_facade_pb2.SetEnableDynamicChannelRequest( - psm=psm, - retransmission_mode=l2cap_facade_pb2. - RetransmissionFlowControlMode.ERTM)) + psm=psm, retransmission_mode=l2cap_facade_pb2.RetransmissionFlowControlMode.ERTM)) self._assert_connection_complete(due_connection_stream) self.device_under_test.l2cap.SendDynamicChannelPacket( l2cap_facade_pb2.DynamicChannelPacket(psm=psm, payload=b'abc')) @@ -241,9 +217,7 @@ class PTSL2capTest(PTSBaseTestClass): self.device_under_test.l2cap.SetDynamicChannel( l2cap_facade_pb2.SetEnableDynamicChannelRequest( - psm=psm, - retransmission_mode=l2cap_facade_pb2. - RetransmissionFlowControlMode.ERTM)) + psm=psm, retransmission_mode=l2cap_facade_pb2.RetransmissionFlowControlMode.ERTM)) self._assert_connection_complete(due_connection_stream) self.device_under_test.l2cap.SendDynamicChannelPacket( l2cap_facade_pb2.DynamicChannelPacket(psm=psm, payload=b'abc')) @@ -261,8 +235,7 @@ class PTSL2capTest(PTSBaseTestClass): psm = 1 retransmission_mode = l2cap_facade_pb2.RetransmissionFlowControlMode.ERTM self.device_under_test.l2cap.SetDynamicChannel( - l2cap_facade_pb2.SetEnableDynamicChannelRequest( - psm=psm, retransmission_mode=retransmission_mode)) + l2cap_facade_pb2.SetEnableDynamicChannelRequest(psm=psm, retransmission_mode=retransmission_mode)) self._assert_connection_complete(due_connection_stream) self.device_under_test.l2cap.SendDynamicChannelPacket( l2cap_facade_pb2.DynamicChannelPacket(psm=psm, payload=b'abc')) @@ -279,8 +252,7 @@ class PTSL2capTest(PTSBaseTestClass): psm = 1 retransmission_mode = l2cap_facade_pb2.RetransmissionFlowControlMode.ERTM self.device_under_test.l2cap.SetDynamicChannel( - l2cap_facade_pb2.SetEnableDynamicChannelRequest( - psm=psm, retransmission_mode=retransmission_mode)) + l2cap_facade_pb2.SetEnableDynamicChannelRequest(psm=psm, retransmission_mode=retransmission_mode)) self._assert_connection_complete(due_connection_stream) self._assert_connection_close(due_connection_close_stream) @@ -294,8 +266,7 @@ class PTSL2capTest(PTSBaseTestClass): psm = 1 retransmission_mode = l2cap_facade_pb2.RetransmissionFlowControlMode.ERTM self.device_under_test.l2cap.SetDynamicChannel( - l2cap_facade_pb2.SetEnableDynamicChannelRequest( - psm=psm, retransmission_mode=retransmission_mode)) + l2cap_facade_pb2.SetEnableDynamicChannelRequest(psm=psm, retransmission_mode=retransmission_mode)) self._assert_connection_complete(due_connection_stream) self.device_under_test.l2cap.SendDynamicChannelPacket( l2cap_facade_pb2.DynamicChannelPacket(psm=psm, payload=b'abc')) @@ -311,9 +282,7 @@ class PTSL2capTest(PTSBaseTestClass): self.device_under_test.l2cap.SetDynamicChannel( l2cap_facade_pb2.SetEnableDynamicChannelRequest( - psm=psm, - retransmission_mode=l2cap_facade_pb2. - RetransmissionFlowControlMode.ERTM)) + psm=psm, retransmission_mode=l2cap_facade_pb2.RetransmissionFlowControlMode.ERTM)) self._assert_connection_complete(due_connection_stream) self.device_under_test.l2cap.SendDynamicChannelPacket( l2cap_facade_pb2.DynamicChannelPacket(psm=psm, payload=b'abc')) @@ -332,12 +301,9 @@ class PTSL2capTest(PTSBaseTestClass): self.device_under_test.l2cap.SetDynamicChannel( l2cap_facade_pb2.SetEnableDynamicChannelRequest( - psm=psm, - retransmission_mode=l2cap_facade_pb2. - RetransmissionFlowControlMode.ERTM)) + psm=psm, retransmission_mode=l2cap_facade_pb2.RetransmissionFlowControlMode.ERTM)) self._assert_connection_complete(due_connection_stream) - self._assert_connection_close( - due_connection_close_stream, timeout=60) + self._assert_connection_close(due_connection_close_stream, timeout=60) def test_L2CAP_ERM_BV_18_C(self): """ @@ -350,8 +316,7 @@ class PTSL2capTest(PTSBaseTestClass): psm = 1 retransmission_mode = l2cap_facade_pb2.RetransmissionFlowControlMode.ERTM self.device_under_test.l2cap.SetDynamicChannel( - l2cap_facade_pb2.SetEnableDynamicChannelRequest( - psm=psm, retransmission_mode=retransmission_mode)) + l2cap_facade_pb2.SetEnableDynamicChannelRequest(psm=psm, retransmission_mode=retransmission_mode)) self._assert_connection_complete(due_connection_stream) self.device_under_test.l2cap.SendDynamicChannelPacket( l2cap_facade_pb2.DynamicChannelPacket(psm=psm, payload=b'abc')) @@ -368,8 +333,7 @@ class PTSL2capTest(PTSBaseTestClass): psm = 1 retransmission_mode = l2cap_facade_pb2.RetransmissionFlowControlMode.ERTM self.device_under_test.l2cap.SetDynamicChannel( - l2cap_facade_pb2.SetEnableDynamicChannelRequest( - psm=psm, retransmission_mode=retransmission_mode)) + l2cap_facade_pb2.SetEnableDynamicChannelRequest(psm=psm, retransmission_mode=retransmission_mode)) self._assert_connection_complete(due_connection_stream) self.device_under_test.l2cap.SendDynamicChannelPacket( l2cap_facade_pb2.DynamicChannelPacket(psm=psm, payload=b'abc')) @@ -386,8 +350,7 @@ class PTSL2capTest(PTSBaseTestClass): psm = 1 retransmission_mode = l2cap_facade_pb2.RetransmissionFlowControlMode.ERTM self.device_under_test.l2cap.SetDynamicChannel( - l2cap_facade_pb2.SetEnableDynamicChannelRequest( - psm=psm, retransmission_mode=retransmission_mode)) + l2cap_facade_pb2.SetEnableDynamicChannelRequest(psm=psm, retransmission_mode=retransmission_mode)) self._assert_connection_complete(due_connection_stream) self.device_under_test.l2cap.SendDynamicChannelPacket( l2cap_facade_pb2.DynamicChannelPacket(psm=psm, payload=b'abc')) @@ -403,12 +366,10 @@ class PTSL2capTest(PTSBaseTestClass): self._dut_connection_close_stream() as dut_connection_close_stream: psm = 1 self.device_under_test.l2cap.OpenChannel( - l2cap_facade_pb2.OpenChannelRequest( - remote=self.pts_address, psm=psm)) + l2cap_facade_pb2.OpenChannelRequest(remote=self.pts_address, psm=psm)) self._assert_connection_complete(due_connection_stream) - self.device_under_test.l2cap.CloseChannel( - l2cap_facade_pb2.CloseChannelRequest(psm=psm)) + self.device_under_test.l2cap.CloseChannel(l2cap_facade_pb2.CloseChannelRequest(psm=psm)) self._assert_connection_close(due_connection_close_stream) def test_L2CAP_COS_CED_BV_03_C(self): @@ -421,13 +382,11 @@ class PTSL2capTest(PTSBaseTestClass): psm = 1 retransmission_mode = l2cap_facade_pb2.RetransmissionFlowControlMode.BASIC self.device_under_test.l2cap.SetDynamicChannel( - l2cap_facade_pb2.SetEnableDynamicChannelRequest( - psm=psm, retransmission_mode=retransmission_mode)) + l2cap_facade_pb2.SetEnableDynamicChannelRequest(psm=psm, retransmission_mode=retransmission_mode)) self._assert_connection_complete(due_connection_stream) self.device_under_test.l2cap.SendDynamicChannelPacket( - l2cap_facade_pb2.DynamicChannelPacket( - psm=psm, payload=b'abc' * 34)) + l2cap_facade_pb2.DynamicChannelPacket(psm=psm, payload=b'abc' * 34)) self._assert_connection_close(due_connection_close_stream) def test_L2CAP_COS_CED_BV_04_C(self): @@ -440,12 +399,10 @@ class PTSL2capTest(PTSBaseTestClass): psm = 1 retransmission_mode = l2cap_facade_pb2.RetransmissionFlowControlMode.BASIC self.device_under_test.l2cap.SetDynamicChannel( - l2cap_facade_pb2.SetEnableDynamicChannelRequest( - psm=psm, retransmission_mode=retransmission_mode)) + l2cap_facade_pb2.SetEnableDynamicChannelRequest(psm=psm, retransmission_mode=retransmission_mode)) self._assert_connection_complete(due_connection_stream) time.sleep(2) - self.device_under_test.l2cap.CloseChannel( - l2cap_facade_pb2.CloseChannelRequest(psm=psm)) + self.device_under_test.l2cap.CloseChannel(l2cap_facade_pb2.CloseChannelRequest(psm=psm)) self._assert_connection_close(due_connection_close_stream) def test_L2CAP_COS_CED_BV_05_C(self): @@ -458,8 +415,7 @@ class PTSL2capTest(PTSBaseTestClass): psm = 1 retransmission_mode = l2cap_facade_pb2.RetransmissionFlowControlMode.BASIC self.device_under_test.l2cap.SetDynamicChannel( - l2cap_facade_pb2.SetEnableDynamicChannelRequest( - psm=psm, retransmission_mode=retransmission_mode)) + l2cap_facade_pb2.SetEnableDynamicChannelRequest(psm=psm, retransmission_mode=retransmission_mode)) self._assert_connection_complete(due_connection_stream) self._assert_connection_close(due_connection_close_stream) @@ -473,8 +429,7 @@ class PTSL2capTest(PTSBaseTestClass): psm = 1 retransmission_mode = l2cap_facade_pb2.RetransmissionFlowControlMode.BASIC self.device_under_test.l2cap.SetDynamicChannel( - l2cap_facade_pb2.SetEnableDynamicChannelRequest( - psm=psm, retransmission_mode=retransmission_mode)) + l2cap_facade_pb2.SetEnableDynamicChannelRequest(psm=psm, retransmission_mode=retransmission_mode)) self._assert_connection_complete(due_connection_stream) self._assert_connection_close(due_connection_close_stream) @@ -488,8 +443,7 @@ class PTSL2capTest(PTSBaseTestClass): psm = 1 retransmission_mode = l2cap_facade_pb2.RetransmissionFlowControlMode.BASIC self.device_under_test.l2cap.SetDynamicChannel( - l2cap_facade_pb2.SetEnableDynamicChannelRequest( - psm=psm, retransmission_mode=retransmission_mode)) + l2cap_facade_pb2.SetEnableDynamicChannelRequest(psm=psm, retransmission_mode=retransmission_mode)) time.sleep(120) def test_L2CAP_COS_CED_BV_09_C(self): @@ -502,8 +456,7 @@ class PTSL2capTest(PTSBaseTestClass): psm = 1 retransmission_mode = l2cap_facade_pb2.RetransmissionFlowControlMode.BASIC self.device_under_test.l2cap.SetDynamicChannel( - l2cap_facade_pb2.SetEnableDynamicChannelRequest( - psm=psm, retransmission_mode=retransmission_mode)) + l2cap_facade_pb2.SetEnableDynamicChannelRequest(psm=psm, retransmission_mode=retransmission_mode)) self._assert_connection_complete(due_connection_stream) self._assert_connection_close(due_connection_close_stream) @@ -517,8 +470,7 @@ class PTSL2capTest(PTSBaseTestClass): psm = 1 retransmission_mode = l2cap_facade_pb2.RetransmissionFlowControlMode.BASIC self.device_under_test.l2cap.SetDynamicChannel( - l2cap_facade_pb2.SetEnableDynamicChannelRequest( - psm=psm, retransmission_mode=retransmission_mode)) + l2cap_facade_pb2.SetEnableDynamicChannelRequest(psm=psm, retransmission_mode=retransmission_mode)) self._assert_connection_complete(due_connection_stream) self._assert_connection_close(due_connection_close_stream) @@ -532,8 +484,7 @@ class PTSL2capTest(PTSBaseTestClass): psm = 1 retransmission_mode = l2cap_facade_pb2.RetransmissionFlowControlMode.BASIC self.device_under_test.l2cap.SetDynamicChannel( - l2cap_facade_pb2.SetEnableDynamicChannelRequest( - psm=psm, retransmission_mode=retransmission_mode)) + l2cap_facade_pb2.SetEnableDynamicChannelRequest(psm=psm, retransmission_mode=retransmission_mode)) self._assert_connection_complete(due_connection_stream) time.sleep(5) @@ -548,8 +499,7 @@ class PTSL2capTest(PTSBaseTestClass): psm = 1 retransmission_mode = l2cap_facade_pb2.RetransmissionFlowControlMode.BASIC self.device_under_test.l2cap.SetDynamicChannel( - l2cap_facade_pb2.SetEnableDynamicChannelRequest( - psm=psm, retransmission_mode=retransmission_mode)) + l2cap_facade_pb2.SetEnableDynamicChannelRequest(psm=psm, retransmission_mode=retransmission_mode)) self._assert_connection_close(due_connection_close_stream) def test_L2CAP_COS_CFD_BV_08_C(self): @@ -563,11 +513,9 @@ class PTSL2capTest(PTSBaseTestClass): psm = 1 self.device_under_test.l2cap.OpenChannel( - l2cap_facade_pb2.OpenChannelRequest( - remote=self.pts_address, psm=psm)) + l2cap_facade_pb2.OpenChannelRequest(remote=self.pts_address, psm=psm)) self._assert_connection_complete(due_connection_stream) - self.device_under_test.l2cap.CloseChannel( - l2cap_facade_pb2.CloseChannelRequest(psm=psm)) + self.device_under_test.l2cap.CloseChannel(l2cap_facade_pb2.CloseChannelRequest(psm=psm)) self._assert_connection_close(due_connection_close_stream) def test_L2CAP_ERM_BI_01_C(self): @@ -581,8 +529,7 @@ class PTSL2capTest(PTSBaseTestClass): psm = 1 retransmission_mode = l2cap_facade_pb2.RetransmissionFlowControlMode.ERTM self.device_under_test.l2cap.SetDynamicChannel( - l2cap_facade_pb2.SetEnableDynamicChannelRequest( - psm=psm, retransmission_mode=retransmission_mode)) + l2cap_facade_pb2.SetEnableDynamicChannelRequest(psm=psm, retransmission_mode=retransmission_mode)) self._assert_connection_complete(due_connection_stream) self._assert_connection_close(due_connection_close_stream) @@ -596,9 +543,7 @@ class PTSL2capTest(PTSBaseTestClass): self.device_under_test.l2cap.SetDynamicChannel( l2cap_facade_pb2.SetEnableDynamicChannelRequest( - psm=psm, - retransmission_mode=l2cap_facade_pb2. - RetransmissionFlowControlMode.ERTM)) + psm=psm, retransmission_mode=l2cap_facade_pb2.RetransmissionFlowControlMode.ERTM)) self._assert_connection_complete(due_connection_stream) self.device_under_test.l2cap.SendDynamicChannelPacket( l2cap_facade_pb2.DynamicChannelPacket(psm=psm, payload=b'abc')) @@ -617,9 +562,7 @@ class PTSL2capTest(PTSBaseTestClass): self.device_under_test.l2cap.SetDynamicChannel( l2cap_facade_pb2.SetEnableDynamicChannelRequest( - psm=psm, - retransmission_mode=l2cap_facade_pb2. - RetransmissionFlowControlMode.ERTM)) + psm=psm, retransmission_mode=l2cap_facade_pb2.RetransmissionFlowControlMode.ERTM)) self._assert_connection_complete(due_connection_stream) self.device_under_test.l2cap.SendDynamicChannelPacket( l2cap_facade_pb2.DynamicChannelPacket(psm=psm, payload=b'abc')) @@ -638,9 +581,7 @@ class PTSL2capTest(PTSBaseTestClass): self.device_under_test.l2cap.SetDynamicChannel( l2cap_facade_pb2.SetEnableDynamicChannelRequest( - psm=psm, - retransmission_mode=l2cap_facade_pb2. - RetransmissionFlowControlMode.ERTM)) + psm=psm, retransmission_mode=l2cap_facade_pb2.RetransmissionFlowControlMode.ERTM)) self._assert_connection_complete(due_connection_stream) self.device_under_test.l2cap.SendDynamicChannelPacket( l2cap_facade_pb2.DynamicChannelPacket(psm=psm, payload=b'abc')) diff --git a/system/gd/l2cap/le/cert/cert_le_l2cap.py b/system/gd/l2cap/le/cert/cert_le_l2cap.py index 6d56fbaf8c..2c9c3dcd5d 100644 --- a/system/gd/l2cap/le/cert/cert_le_l2cap.py +++ b/system/gd/l2cap/le/cert/cert_le_l2cap.py @@ -31,22 +31,14 @@ from mobly import asserts class CertLeL2capChannel(IEventStream): - def __init__(self, - device, - scid, - dcid, - acl_stream, - acl, - control_channel, - initial_credits=0): + def __init__(self, device, scid, dcid, acl_stream, acl, control_channel, initial_credits=0): self._device = device self._scid = scid self._dcid = dcid self._acl_stream = acl_stream self._acl = acl self._control_channel = control_channel - self._our_acl_view = FilteringEventStream( - acl_stream, L2capMatchers.ExtractBasicFrame(scid)) + self._our_acl_view = FilteringEventStream(acl_stream, L2capMatchers.ExtractBasicFrame(scid)) self._credits_left = initial_credits def get_event_queue(self): @@ -58,28 +50,21 @@ class CertLeL2capChannel(IEventStream): self._credits_left -= 1 def send_first_le_i_frame(self, sdu_size, packet): - frame = l2cap_packets.FirstLeInformationFrameBuilder( - self._dcid, sdu_size, packet) + frame = l2cap_packets.FirstLeInformationFrameBuilder(self._dcid, sdu_size, packet) self._acl.send(frame.Serialize()) self._credits_left -= 1 def disconnect_and_verify(self): assertThat(self._scid).isNotEqualTo(1) - self._control_channel.send( - l2cap_packets.LeDisconnectionRequestBuilder(1, self._dcid, - self._scid)) + self._control_channel.send(l2cap_packets.LeDisconnectionRequestBuilder(1, self._dcid, self._scid)) - assertThat(self._control_channel).emits( - L2capMatchers.LeDisconnectionResponse(self._scid, self._dcid)) + assertThat(self._control_channel).emits(L2capMatchers.LeDisconnectionResponse(self._scid, self._dcid)) def verify_disconnect_request(self): - assertThat(self._control_channel).emits( - L2capMatchers.LeDisconnectionRequest(self._dcid, self._scid)) + assertThat(self._control_channel).emits(L2capMatchers.LeDisconnectionRequest(self._dcid, self._scid)) def send_credits(self, num_credits): - self._control_channel.send( - l2cap_packets.LeFlowControlCreditBuilder(2, self._scid, - num_credits)) + self._control_channel.send(l2cap_packets.LeFlowControlCreditBuilder(2, self._scid, num_credits)) def credits_left(self): return self._credits_left @@ -93,12 +78,9 @@ class CertLeL2cap(Closable): self._le_acl = None self.control_table = { - LeCommandCode.DISCONNECTION_REQUEST: - self._on_disconnection_request_default, - LeCommandCode.DISCONNECTION_RESPONSE: - self._on_disconnection_response_default, - LeCommandCode.LE_FLOW_CONTROL_CREDIT: - self._on_credit, + LeCommandCode.DISCONNECTION_REQUEST: self._on_disconnection_request_default, + LeCommandCode.DISCONNECTION_RESPONSE: self._on_disconnection_response_default, + LeCommandCode.LE_FLOW_CONTROL_CREDIT: self._on_credit, } self._cid_to_cert_channels = {} @@ -111,74 +93,47 @@ class CertLeL2cap(Closable): self._le_acl = self._le_acl_manager.initiate_connection(remote_addr) self._le_acl.wait_for_connection_complete() self.control_channel = CertLeL2capChannel( - self._device, - 5, - 5, - self._get_acl_stream(), - self._le_acl, - control_channel=None) + self._device, 5, 5, self._get_acl_stream(), self._le_acl, control_channel=None) self._get_acl_stream().register_callback(self._handle_control_packet) def wait_for_connection(self): self._le_acl_manager.listen_for_incoming_connections() self._le_acl = self._le_acl_manager.accept_connection() self.control_channel = CertLeL2capChannel( - self._device, - 5, - 5, - self._get_acl_stream(), - self._le_acl, - control_channel=None) + self._device, 5, 5, self._get_acl_stream(), self._le_acl, control_channel=None) self._get_acl_stream().register_callback(self._handle_control_packet) def open_fixed_channel(self, cid=4): - channel = CertLeL2capChannel(self._device, cid, cid, - self._get_acl_stream(), self._le_acl, None, - 0) + channel = CertLeL2capChannel(self._device, cid, cid, self._get_acl_stream(), self._le_acl, None, 0) return channel - def open_channel(self, - signal_id, - psm, - scid, - mtu=1000, - mps=100, - initial_credit=6): + def open_channel(self, signal_id, psm, scid, mtu=1000, mps=100, initial_credit=6): self.control_channel.send( - l2cap_packets.LeCreditBasedConnectionRequestBuilder( - signal_id, psm, scid, mtu, mps, initial_credit)) + l2cap_packets.LeCreditBasedConnectionRequestBuilder(signal_id, psm, scid, mtu, mps, initial_credit)) response = L2capCaptures.CreditBasedConnectionResponse() assertThat(self.control_channel).emits(response) channel = CertLeL2capChannel(self._device, scid, - response.get().GetDestinationCid(), - self._get_acl_stream(), self._le_acl, + response.get().GetDestinationCid(), self._get_acl_stream(), self._le_acl, self.control_channel, response.get().GetInitialCredits()) self._cid_to_cert_channels[scid] = channel return channel - def open_channel_with_expected_result( - self, psm=0x33, - result=LeCreditBasedConnectionResponseResult.SUCCESS): - self.control_channel.send( - l2cap_packets.LeCreditBasedConnectionRequestBuilder( - 1, psm, 0x40, 1000, 100, 6)) + def open_channel_with_expected_result(self, psm=0x33, result=LeCreditBasedConnectionResponseResult.SUCCESS): + self.control_channel.send(l2cap_packets.LeCreditBasedConnectionRequestBuilder(1, psm, 0x40, 1000, 100, 6)) response = L2capMatchers.CreditBasedConnectionResponse(result) assertThat(self.control_channel).emits(response) - def verify_and_respond_open_channel_from_remote( - self, - psm=0x33, - result=LeCreditBasedConnectionResponseResult.SUCCESS, - our_scid=None): + def verify_and_respond_open_channel_from_remote(self, + psm=0x33, + result=LeCreditBasedConnectionResponseResult.SUCCESS, + our_scid=None): request = L2capCaptures.CreditBasedConnectionRequest(psm) assertThat(self.control_channel).emits(request) - (scid, dcid) = self._respond_connection_request_default( - request.get(), result, our_scid) - channel = CertLeL2capChannel(self._device, scid, dcid, - self._get_acl_stream(), self._le_acl, + (scid, dcid) = self._respond_connection_request_default(request.get(), result, our_scid) + channel = CertLeL2capChannel(self._device, scid, dcid, self._get_acl_stream(), self._le_acl, self.control_channel, request.get().GetInitialCredits()) self._cid_to_cert_channels[scid] = channel @@ -192,14 +147,12 @@ class CertLeL2cap(Closable): self.control_channel.send(reject) def verify_le_flow_control_credit(self, channel): - assertThat(self.control_channel).emits( - L2capMatchers.LeFlowControlCredit(channel._dcid)) - - def _respond_connection_request_default( - self, - request, - result=LeCreditBasedConnectionResponseResult.SUCCESS, - our_scid=None): + assertThat(self.control_channel).emits(L2capMatchers.LeFlowControlCredit(channel._dcid)) + + def _respond_connection_request_default(self, + request, + result=LeCreditBasedConnectionResponseResult.SUCCESS, + our_scid=None): sid = request.GetIdentifier() their_scid = request.GetSourceCid() mtu = request.GetMtu() @@ -209,8 +162,8 @@ class CertLeL2cap(Closable): if our_scid is None: our_scid = their_scid our_dcid = their_scid - response = l2cap_packets.LeCreditBasedConnectionResponseBuilder( - sid, our_scid, mtu, mps, initial_credits, result) + response = l2cap_packets.LeCreditBasedConnectionResponseBuilder(sid, our_scid, mtu, mps, initial_credits, + result) self.control_channel.send(response) return (our_scid, our_dcid) @@ -221,8 +174,7 @@ class CertLeL2cap(Closable): return self._le_acl_manager.get_le_acl_stream() def _on_disconnection_request_default(self, request): - disconnection_request = l2cap_packets.LeDisconnectionRequestView( - request) + disconnection_request = l2cap_packets.LeDisconnectionRequestView(request) sid = disconnection_request.GetIdentifier() scid = disconnection_request.GetSourceCid() dcid = disconnection_request.GetDestinationCid() @@ -230,22 +182,18 @@ class CertLeL2cap(Closable): self.control_channel.send(response) def _on_disconnection_response_default(self, request): - disconnection_response = l2cap_packets.LeDisconnectionResponseView( - request) + disconnection_response = l2cap_packets.LeDisconnectionResponseView(request) def _on_credit(self, l2cap_le_control_view): - credit_view = l2cap_packets.LeFlowControlCreditView( - l2cap_le_control_view) + credit_view = l2cap_packets.LeFlowControlCreditView(l2cap_le_control_view) cid = credit_view.GetCid() if cid not in self._cid_to_cert_channels: return - self._cid_to_cert_channels[ - cid]._credits_left += credit_view.GetCredits() + self._cid_to_cert_channels[cid]._credits_left += credit_view.GetCredits() def _handle_control_packet(self, l2cap_packet): packet_bytes = l2cap_packet.payload - l2cap_view = l2cap_packets.BasicFrameView( - bt_packets.PacketViewLittleEndian(list(packet_bytes))) + l2cap_view = l2cap_packets.BasicFrameView(bt_packets.PacketViewLittleEndian(list(packet_bytes))) if l2cap_view.GetChannelId() != 5: return request = l2cap_packets.LeControlView(l2cap_view.GetPayload()) diff --git a/system/gd/l2cap/le/cert/dual_l2cap_test.py b/system/gd/l2cap/le/cert/dual_l2cap_test.py index 0c88705594..38c2e98c9d 100644 --- a/system/gd/l2cap/le/cert/dual_l2cap_test.py +++ b/system/gd/l2cap/le/cert/dual_l2cap_test.py @@ -42,36 +42,26 @@ class DualL2capTest(GdBaseTestClass): self.dut_address = self.dut.hci_controller.GetMacAddressSimple() cert_address = common.BluetoothAddress( - address=self.cert.controller_read_only_property.ReadLocalAddress( - empty_proto.Empty()).address) + address=self.cert.controller_read_only_property.ReadLocalAddress(empty_proto.Empty()).address) self.dut_l2cap = PyL2cap(self.dut, cert_address) self.cert_l2cap = CertL2cap(self.cert) self.dut_le_l2cap = PyLeL2cap(self.dut) self.cert_le_l2cap = CertLeL2cap(self.cert) self.dut_le_address = common.BluetoothAddressWithType( - address=common.BluetoothAddress( - address=bytes(b'0D:05:04:03:02:01')), - type=common.RANDOM_DEVICE_ADDRESS) + address=common.BluetoothAddress(address=bytes(b'0D:05:04:03:02:01')), type=common.RANDOM_DEVICE_ADDRESS) self.cert_address = common.BluetoothAddressWithType( - address=common.BluetoothAddress( - address=bytes(b'55:11:FF:AA:33:22')), - type=common.RANDOM_DEVICE_ADDRESS) - self.cert_le_l2cap._device.hci_le_acl_manager.SetInitiatorAddress( - self.cert_address) + address=common.BluetoothAddress(address=bytes(b'55:11:FF:AA:33:22')), type=common.RANDOM_DEVICE_ADDRESS) + self.cert_le_l2cap._device.hci_le_acl_manager.SetInitiatorAddress(self.cert_address) private_policy = le_acl_manager_facade.PrivacyPolicy( - address_policy=le_acl_manager_facade.AddressPolicy. - USE_RESOLVABLE_ADDRESS, + address_policy=le_acl_manager_facade.AddressPolicy.USE_RESOLVABLE_ADDRESS, address_with_type=common.BluetoothAddressWithType( - address=common.BluetoothAddress( - address=bytes(b'00:00:00:00:00:00')), + address=common.BluetoothAddress(address=bytes(b'00:00:00:00:00:00')), type=common.RANDOM_DEVICE_ADDRESS), - rotation_irk= - b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + rotation_irk=b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', minimum_rotation_time=(7 * 60 * 1000), maximum_rotation_time=(15 * 60 * 1000)) - self.cert_le_l2cap._device.hci_le_acl_manager.SetPrivacyPolicyForInitiatorAddress( - private_policy) + self.cert_le_l2cap._device.hci_le_acl_manager.SetPrivacyPolicyForInitiatorAddress(private_policy) def teardown_test(self): self.cert_le_l2cap.close() @@ -81,8 +71,7 @@ class DualL2capTest(GdBaseTestClass): super().teardown_test() def _setup_acl_link_from_cert(self): - self.dut.neighbor.EnablePageScan( - neighbor_facade.EnableMsg(enabled=True)) + self.dut.neighbor.EnablePageScan(neighbor_facade.EnableMsg(enabled=True)) self.cert_l2cap.connect_acl(self.dut_address) def _setup_le_link_from_cert(self): @@ -90,8 +79,7 @@ class DualL2capTest(GdBaseTestClass): gap_name = hci_packets.GapData() gap_name.data_type = hci_packets.GapDataType.COMPLETE_LOCAL_NAME gap_name.data = list(bytes(b'Im_The_DUT')) - gap_data = le_advertising_facade.GapDataMsg( - data=bytes(gap_name.Serialize())) + gap_data = le_advertising_facade.GapDataMsg(data=bytes(gap_name.Serialize())) config = le_advertising_facade.AdvertisingConfig( advertisement=[gap_data], random_address=self.dut_le_address.address, @@ -100,28 +88,22 @@ class DualL2capTest(GdBaseTestClass): event_type=le_advertising_facade.AdvertisingEventType.ADV_IND, address_type=common.RANDOM_DEVICE_ADDRESS, peer_address_type=common.PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - peer_address=common.BluetoothAddress( - address=bytes(b'00:00:00:00:00:00')), + peer_address=common.BluetoothAddress(address=bytes(b'00:00:00:00:00:00')), channel_map=7, - filter_policy=le_advertising_facade.AdvertisingFilterPolicy. - ALL_DEVICES) + filter_policy=le_advertising_facade.AdvertisingFilterPolicy.ALL_DEVICES) request = le_advertising_facade.CreateAdvertiserRequest(config=config) - create_response = self.dut.hci_le_advertising_manager.CreateAdvertiser( - request) + create_response = self.dut.hci_le_advertising_manager.CreateAdvertiser(request) self.cert_le_l2cap.connect_le_acl(self.dut_le_address) def _open_le_coc_from_dut(self, psm=0x33, our_scid=None): - response_future = self.dut_le_l2cap.connect_coc_to_cert( - self.cert_address, psm) - cert_channel = self.cert_le_l2cap.verify_and_respond_open_channel_from_remote( - psm=psm, our_scid=our_scid) + response_future = self.dut_le_l2cap.connect_coc_to_cert(self.cert_address, psm) + cert_channel = self.cert_le_l2cap.verify_and_respond_open_channel_from_remote(psm=psm, our_scid=our_scid) dut_channel = response_future.get_channel() return (dut_channel, cert_channel) def _open_channel_from_dut(self, psm=0x33, our_scid=None): dut_channel_future = self.dut_l2cap.connect_dynamic_channel_to_cert(psm) - cert_channel = self.cert_l2cap.verify_and_respond_open_channel_from_remote( - psm=psm, scid=our_scid) + cert_channel = self.cert_l2cap.verify_and_respond_open_channel_from_remote(psm=psm, scid=our_scid) dut_channel = dut_channel_future.get_channel() cert_channel.verify_configuration_request_and_respond() @@ -130,10 +112,7 @@ class DualL2capTest(GdBaseTestClass): return (dut_channel, cert_channel) - def _open_unconfigured_channel_from_cert(self, - signal_id=1, - scid=0x0101, - psm=0x33): + def _open_unconfigured_channel_from_cert(self, signal_id=1, scid=0x0101, psm=0x33): dut_channel = self.dut_l2cap.register_dynamic_channel(psm) cert_channel = self.cert_l2cap.open_channel(signal_id, psm, scid) @@ -141,31 +120,21 @@ class DualL2capTest(GdBaseTestClass): return (dut_channel, cert_channel) def _open_channel_from_cert(self, signal_id=1, scid=0x0101, psm=0x33): - (dut_channel, cert_channel) = self._open_unconfigured_channel_from_cert( - signal_id, scid, psm) + (dut_channel, cert_channel) = self._open_unconfigured_channel_from_cert(signal_id, scid, psm) cert_channel.verify_configuration_request_and_respond() cert_channel.send_configure_request([]) cert_channel.verify_configuration_response() return (dut_channel, cert_channel) - def _open_le_coc_from_cert(self, - signal_id=1, - scid=0x0101, - psm=0x35, - mtu=1000, - mps=100, - initial_credit=6): + def _open_le_coc_from_cert(self, signal_id=1, scid=0x0101, psm=0x35, mtu=1000, mps=100, initial_credit=6): dut_channel = self.dut_le_l2cap.register_coc(self.cert_address, psm) - cert_channel = self.cert_le_l2cap.open_channel(signal_id, psm, scid, - mtu, mps, initial_credit) + cert_channel = self.cert_le_l2cap.open_channel(signal_id, psm, scid, mtu, mps, initial_credit) return (dut_channel, cert_channel) - @metadata( - pts_test_id="L2CAP/LE/CID/BV-01-C", - pts_test_name="Receiving DCID over BR/EDR and LE") + @metadata(pts_test_id="L2CAP/LE/CID/BV-01-C", pts_test_name="Receiving DCID over BR/EDR and LE") def test_receiving_dcid_over_bredr_and_le(self): """ Test that the L2CAP entity can receive the same DCID in L2CAP connect responses on both the @@ -176,26 +145,21 @@ class DualL2capTest(GdBaseTestClass): # TODO: Update AclManager::impl::create_le_connection self._setup_le_link_from_cert() (dut_channel, cert_channel) = self._open_channel_from_dut(0x33, 0x70) - (le_dut_channel, le_cert_channel) = self._open_le_coc_from_dut( - 0x35, 0x70) + (le_dut_channel, le_cert_channel) = self._open_le_coc_from_dut(0x35, 0x70) dut_channel.send(b'abc') assertThat(cert_channel).emits(L2capMatchers.Data(b'abc')) le_dut_channel.send(b'hello') - assertThat(le_cert_channel).emits( - L2capMatchers.FirstLeIFrame(b'hello', sdu_size=5)) + assertThat(le_cert_channel).emits(L2capMatchers.FirstLeIFrame(b'hello', sdu_size=5)) le_cert_channel.send_first_le_i_frame(4, SAMPLE_PACKET) - assertThat(le_dut_channel).emits( - L2capMatchers.PacketPayloadRawData(b'\x19\x26\x08\x17')) + assertThat(le_dut_channel).emits(L2capMatchers.PacketPayloadRawData(b'\x19\x26\x08\x17')) cert_channel.disconnect_and_verify() le_cert_channel.disconnect_and_verify() - @metadata( - pts_test_id="L2CAP/LE/CID/BV-02-C", - pts_test_name="Receiving SCID over BR/EDR and LE") + @metadata(pts_test_id="L2CAP/LE/CID/BV-02-C", pts_test_name="Receiving SCID over BR/EDR and LE") def test_receiving_scid_over_bredr_and_le(self): """ Test that the L2CAP entity can receive the same SCID in L2CAP connect requests on both the @@ -206,19 +170,16 @@ class DualL2capTest(GdBaseTestClass): # TODO: Update AclManager::impl::create_le_connection self._setup_le_link_from_cert() (dut_channel, cert_channel) = self._open_channel_from_cert(0x33, 0x70) - (le_dut_channel, le_cert_channel) = self._open_le_coc_from_cert( - 0x35, 0x70) + (le_dut_channel, le_cert_channel) = self._open_le_coc_from_cert(0x35, 0x70) dut_channel.send(b'abc') assertThat(cert_channel).emits(L2capMatchers.Data(b'abc')) le_dut_channel.send(b'hello') - assertThat(le_cert_channel).emits( - L2capMatchers.FirstLeIFrame(b'hello', sdu_size=5)) + assertThat(le_cert_channel).emits(L2capMatchers.FirstLeIFrame(b'hello', sdu_size=5)) le_cert_channel.send_first_le_i_frame(4, SAMPLE_PACKET) - assertThat(le_dut_channel).emits( - L2capMatchers.PacketPayloadRawData(b'\x19\x26\x08\x17')) + assertThat(le_dut_channel).emits(L2capMatchers.PacketPayloadRawData(b'\x19\x26\x08\x17')) cert_channel.disconnect_and_verify() le_cert_channel.disconnect_and_verify() diff --git a/system/gd/l2cap/le/cert/le_l2cap_test.py b/system/gd/l2cap/le/cert/le_l2cap_test.py index 9edc753e29..05e582e0b3 100644 --- a/system/gd/l2cap/le/cert/le_l2cap_test.py +++ b/system/gd/l2cap/le/cert/le_l2cap_test.py @@ -43,28 +43,19 @@ class LeL2capTest(GdBaseTestClass): self.dut_l2cap = PyLeL2cap(self.dut) self.cert_l2cap = CertLeL2cap(self.cert) self.dut_address = common.BluetoothAddressWithType( - address=common.BluetoothAddress( - address=bytes(b'0D:05:04:03:02:01')), - type=common.RANDOM_DEVICE_ADDRESS) + address=common.BluetoothAddress(address=bytes(b'0D:05:04:03:02:01')), type=common.RANDOM_DEVICE_ADDRESS) self.cert_address = common.BluetoothAddressWithType( - address=common.BluetoothAddress( - address=bytes(b'55:11:FF:AA:33:22')), - type=common.RANDOM_DEVICE_ADDRESS) - self.cert_l2cap._device.hci_le_acl_manager.SetInitiatorAddress( - self.cert_address) + address=common.BluetoothAddress(address=bytes(b'55:11:FF:AA:33:22')), type=common.RANDOM_DEVICE_ADDRESS) + self.cert_l2cap._device.hci_le_acl_manager.SetInitiatorAddress(self.cert_address) private_policy = le_acl_manager_facade.PrivacyPolicy( - address_policy=le_acl_manager_facade.AddressPolicy. - USE_RESOLVABLE_ADDRESS, + address_policy=le_acl_manager_facade.AddressPolicy.USE_RESOLVABLE_ADDRESS, address_with_type=common.BluetoothAddressWithType( - address=common.BluetoothAddress( - address=bytes(b'00:00:00:00:00:00')), + address=common.BluetoothAddress(address=bytes(b'00:00:00:00:00:00')), type=common.RANDOM_DEVICE_ADDRESS), - rotation_irk= - b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + rotation_irk=b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', minimum_rotation_time=(7 * 60 * 1000), maximum_rotation_time=(15 * 60 * 1000)) - self.cert_l2cap._device.hci_le_acl_manager.SetPrivacyPolicyForInitiatorAddress( - private_policy) + self.cert_l2cap._device.hci_le_acl_manager.SetPrivacyPolicyForInitiatorAddress(private_policy) def teardown_test(self): self.cert_l2cap.close() @@ -76,8 +67,7 @@ class LeL2capTest(GdBaseTestClass): gap_name = hci_packets.GapData() gap_name.data_type = hci_packets.GapDataType.COMPLETE_LOCAL_NAME gap_name.data = list(bytes(b'Im_The_DUT')) - gap_data = le_advertising_facade.GapDataMsg( - data=bytes(gap_name.Serialize())) + gap_data = le_advertising_facade.GapDataMsg(data=bytes(gap_name.Serialize())) config = le_advertising_facade.AdvertisingConfig( advertisement=[gap_data], random_address=self.dut_address.address, @@ -86,14 +76,11 @@ class LeL2capTest(GdBaseTestClass): event_type=le_advertising_facade.AdvertisingEventType.ADV_IND, address_type=common.RANDOM_DEVICE_ADDRESS, peer_address_type=common.PUBLIC_DEVICE_ADDRESS, - peer_address=common.BluetoothAddress( - address=bytes(b'00:00:00:00:00:00')), + peer_address=common.BluetoothAddress(address=bytes(b'00:00:00:00:00:00')), channel_map=7, - filter_policy=le_advertising_facade.AdvertisingFilterPolicy. - ALL_DEVICES) + filter_policy=le_advertising_facade.AdvertisingFilterPolicy.ALL_DEVICES) request = le_advertising_facade.CreateAdvertiserRequest(config=config) - create_response = self.dut.hci_le_advertising_manager.CreateAdvertiser( - request) + create_response = self.dut.hci_le_advertising_manager.CreateAdvertiser(request) self.cert_l2cap.connect_le_acl(self.dut_address) def _set_link_from_dut_and_open_channel(self, @@ -107,8 +94,7 @@ class LeL2capTest(GdBaseTestClass): gap_name = hci_packets.GapData() gap_name.data_type = hci_packets.GapDataType.COMPLETE_LOCAL_NAME gap_name.data = list(bytes(b'Im_The_DUT')) - gap_data = le_advertising_facade.GapDataMsg( - data=bytes(gap_name.Serialize())) + gap_data = le_advertising_facade.GapDataMsg(data=bytes(gap_name.Serialize())) config = le_advertising_facade.AdvertisingConfig( advertisement=[gap_data], random_address=self.cert_address.address, @@ -117,42 +103,28 @@ class LeL2capTest(GdBaseTestClass): event_type=le_advertising_facade.AdvertisingEventType.ADV_IND, address_type=common.RANDOM_DEVICE_ADDRESS, peer_address_type=common.PUBLIC_DEVICE_ADDRESS, - peer_address=common.BluetoothAddress( - address=bytes(b'00:00:00:00:00:00')), + peer_address=common.BluetoothAddress(address=bytes(b'00:00:00:00:00:00')), channel_map=7, - filter_policy=le_advertising_facade.AdvertisingFilterPolicy. - ALL_DEVICES) + filter_policy=le_advertising_facade.AdvertisingFilterPolicy.ALL_DEVICES) request = le_advertising_facade.CreateAdvertiserRequest(config=config) - create_response = self.cert.hci_le_advertising_manager.CreateAdvertiser( - request) - response_future = self.dut_l2cap.connect_coc_to_cert( - self.cert_address, psm) + create_response = self.cert.hci_le_advertising_manager.CreateAdvertiser(request) + response_future = self.dut_l2cap.connect_coc_to_cert(self.cert_address, psm) self.cert_l2cap.wait_for_connection() # TODO: Currently we can only connect by using Dynamic channel API. Use fixed channel instead. - cert_channel = self.cert_l2cap.verify_and_respond_open_channel_from_remote( - psm) + cert_channel = self.cert_l2cap.verify_and_respond_open_channel_from_remote(psm) dut_channel = response_future.get_channel() return (dut_channel, cert_channel) - def _open_channel_from_cert(self, - signal_id=1, - scid=0x0101, - psm=0x33, - mtu=1000, - mps=100, - initial_credit=6): + def _open_channel_from_cert(self, signal_id=1, scid=0x0101, psm=0x33, mtu=1000, mps=100, initial_credit=6): dut_channel = self.dut_l2cap.register_coc(self.cert_address, psm) - cert_channel = self.cert_l2cap.open_channel(signal_id, psm, scid, mtu, - mps, initial_credit) + cert_channel = self.cert_l2cap.open_channel(signal_id, psm, scid, mtu, mps, initial_credit) return (dut_channel, cert_channel) def _open_channel_from_dut(self, psm=0x33): - response_future = self.dut_l2cap.connect_coc_to_cert( - self.cert_address, psm) - cert_channel = self.cert_l2cap.verify_and_respond_open_channel_from_remote( - psm) + response_future = self.dut_l2cap.connect_coc_to_cert(self.cert_address, psm) + cert_channel = self.cert_l2cap.verify_and_respond_open_channel_from_remote(psm) dut_channel = response_future.get_channel() return (dut_channel, cert_channel) @@ -173,8 +145,7 @@ class LeL2capTest(GdBaseTestClass): self._setup_link_from_cert() (dut_channel, cert_channel) = self._open_fixed_channel(4) cert_channel.send(SAMPLE_PACKET) - assertThat(dut_channel).emits( - L2capMatchers.PacketPayloadRawData(b'\x19\x26\x08\x17')) + assertThat(dut_channel).emits(L2capMatchers.PacketPayloadRawData(b'\x19\x26\x08\x17')) def test_connect_from_dut_and_open_dynamic_channel(self): """ @@ -182,9 +153,7 @@ class LeL2capTest(GdBaseTestClass): """ self._set_link_from_dut_and_open_channel() - @metadata( - pts_test_id="L2CAP/LE/CPU/BV-01-C", - pts_test_name="Send Connection Parameter Update Request") + @metadata(pts_test_id="L2CAP/LE/CPU/BV-01-C", pts_test_name="Send Connection Parameter Update Request") def test_send_connection_parameter_update_request(self): """ Verify that the IUT is able to send the connection parameter update Request to Lower Tester when acting as a slave device. @@ -194,12 +163,9 @@ class LeL2capTest(GdBaseTestClass): self._setup_link_from_cert() self._open_channel_from_dut() self.dut_l2cap.update_connection_parameter() - assertThat(self.cert_l2cap.get_control_channel()).emits( - L2capMatchers.LeConnectionParameterUpdateRequest()) + assertThat(self.cert_l2cap.get_control_channel()).emits(L2capMatchers.LeConnectionParameterUpdateRequest()) - @metadata( - pts_test_id="L2CAP/LE/CPU/BV-02-C", - pts_test_name="Accept Connection Parameter Update Request") + @metadata(pts_test_id="L2CAP/LE/CPU/BV-02-C", pts_test_name="Accept Connection Parameter Update Request") def test_accept_connection_parameter_update_request(self): """ Verify that the IUT is able to receive and handle a request for connection parameter update when acting as a master device. @@ -207,15 +173,12 @@ class LeL2capTest(GdBaseTestClass): """ self._set_link_from_dut_and_open_channel() self.cert_l2cap.get_control_channel().send( - l2cap_packets.ConnectionParameterUpdateRequestBuilder( - 2, 0x10, 0x10, 0x0a, 0x64)) + l2cap_packets.ConnectionParameterUpdateRequestBuilder(2, 0x10, 0x10, 0x0a, 0x64)) assertThat(self.cert_l2cap.get_control_channel()).emits( L2capMatchers.LeConnectionParameterUpdateResponse( l2cap_packets.ConnectionParameterUpdateResponseResult.ACCEPTED)) - @metadata( - pts_test_id="L2CAP/LE/CPU/BI-01-C", - pts_test_name="Reject Connection Parameter Update Parameters") + @metadata(pts_test_id="L2CAP/LE/CPU/BI-01-C", pts_test_name="Reject Connection Parameter Update Parameters") def test_reject_connection_parameter_update_parameters(self): """ Verify that the IUT is able to reject a request for connection parameter update with illegal parameters. @@ -223,25 +186,20 @@ class LeL2capTest(GdBaseTestClass): """ self._set_link_from_dut_and_open_channel() self.cert_l2cap.get_control_channel().send( - l2cap_packets.ConnectionParameterUpdateRequestBuilder( - 2, 0x10, 0x10, 512, 0x64)) + l2cap_packets.ConnectionParameterUpdateRequestBuilder(2, 0x10, 0x10, 512, 0x64)) assertThat(self.cert_l2cap.get_control_channel()).emits( L2capMatchers.LeConnectionParameterUpdateResponse( l2cap_packets.ConnectionParameterUpdateResponseResult.REJECTED)) - @metadata( - pts_test_id="L2CAP/LE/CPU/BI-02-C", - pts_test_name="Reject Connection Parameter Update Request") + @metadata(pts_test_id="L2CAP/LE/CPU/BI-02-C", pts_test_name="Reject Connection Parameter Update Request") def test_reject_connection_parameter_update_request(self): """ Verify that the IUT is able to reject a request for connection parameter update in slave mode. """ self._setup_link_from_cert() self.cert_l2cap.get_control_channel().send( - l2cap_packets.ConnectionParameterUpdateRequestBuilder( - 2, 0x10, 0x10, 0x0a, 0x64)) - assertThat(self.cert_l2cap.get_control_channel()).emits( - L2capMatchers.LeCommandReject()) + l2cap_packets.ConnectionParameterUpdateRequestBuilder(2, 0x10, 0x10, 0x0a, 0x64)) + assertThat(self.cert_l2cap.get_control_channel()).emits(L2capMatchers.LeCommandReject()) @metadata(pts_test_id="L2CAP/COS/CFC/BV-01-C", pts_test_name="Segmentation") def test_segmentation(self): @@ -249,28 +207,23 @@ class LeL2capTest(GdBaseTestClass): Verify that the IUT can send data segments which are larger than the LE frame size. """ self._setup_link_from_cert() - (dut_channel, cert_channel) = self._open_channel_from_cert( - mtu=1000, mps=102) + (dut_channel, cert_channel) = self._open_channel_from_cert(mtu=1000, mps=102) dut_channel.send(b'hello' * 20 + b'world') # The first LeInformation packet contains 2 bytes of SDU size. # The packet is divided into first 100 bytes from 'hellohello....' # and remaining 5 bytes 'world' assertThat(cert_channel).emits( - L2capMatchers.FirstLeIFrame(b'hello' * 20, sdu_size=105), - L2capMatchers.Data(b'world')).inOrder() + L2capMatchers.FirstLeIFrame(b'hello' * 20, sdu_size=105), L2capMatchers.Data(b'world')).inOrder() - @metadata( - pts_test_id="L2CAP/COS/CFC/BV-02-C", pts_test_name="No Segmentation") + @metadata(pts_test_id="L2CAP/COS/CFC/BV-02-C", pts_test_name="No Segmentation") def test_no_segmentation(self): """ Verify that the IUT can send data segments which do not require segmentation. """ self._setup_link_from_cert() - (dut_channel, cert_channel) = self._open_channel_from_cert( - mtu=1000, mps=202) + (dut_channel, cert_channel) = self._open_channel_from_cert(mtu=1000, mps=202) dut_channel.send(b'hello' * 40) - assertThat(cert_channel).emits( - L2capMatchers.FirstLeIFrame(b'hello' * 40, sdu_size=200)) + assertThat(cert_channel).emits(L2capMatchers.FirstLeIFrame(b'hello' * 40, sdu_size=200)) def test_no_segmentation_dut_is_master(self): """ @@ -278,8 +231,7 @@ class LeL2capTest(GdBaseTestClass): """ (dut_channel, cert_channel) = self._set_link_from_dut_and_open_channel() dut_channel.send(b'hello' * 40) - assertThat(cert_channel).emits( - L2capMatchers.FirstLeIFrame(b'hello' * 40, sdu_size=200)) + assertThat(cert_channel).emits(L2capMatchers.FirstLeIFrame(b'hello' * 40, sdu_size=200)) @metadata(pts_test_id="L2CAP/COS/CFC/BV-03-C", pts_test_name="Reassembling") def test_reassembling(self): @@ -289,14 +241,11 @@ class LeL2capTest(GdBaseTestClass): self._setup_link_from_cert() (dut_channel, cert_channel) = self._open_channel_from_cert() sdu_size_for_two_sample_packet = 8 - cert_channel.send_first_le_i_frame(sdu_size_for_two_sample_packet, - SAMPLE_PACKET) + cert_channel.send_first_le_i_frame(sdu_size_for_two_sample_packet, SAMPLE_PACKET) cert_channel.send(SAMPLE_PACKET) - assertThat(dut_channel).emits( - L2capMatchers.PacketPayloadRawData(b'\x19\x26\x08\x17' * 2)) + assertThat(dut_channel).emits(L2capMatchers.PacketPayloadRawData(b'\x19\x26\x08\x17' * 2)) - @metadata( - pts_test_id="L2CAP/COS/CFC/BV-04-C", pts_test_name="Data Receiving") + @metadata(pts_test_id="L2CAP/COS/CFC/BV-04-C", pts_test_name="Data Receiving") def test_data_receiving(self): """ Verify that the IUT can receive unsegmented data correctly. @@ -304,8 +253,7 @@ class LeL2capTest(GdBaseTestClass): self._setup_link_from_cert() (dut_channel, cert_channel) = self._open_channel_from_cert() cert_channel.send_first_le_i_frame(4, SAMPLE_PACKET) - assertThat(dut_channel).emits( - L2capMatchers.PacketPayloadRawData(b'\x19\x26\x08\x17')) + assertThat(dut_channel).emits(L2capMatchers.PacketPayloadRawData(b'\x19\x26\x08\x17')) def test_data_receiving_dut_is_master(self): """ @@ -313,42 +261,31 @@ class LeL2capTest(GdBaseTestClass): """ (dut_channel, cert_channel) = self._set_link_from_dut_and_open_channel() cert_channel.send_first_le_i_frame(4, SAMPLE_PACKET) - assertThat(dut_channel).emits( - L2capMatchers.PacketPayloadRawData(b'\x19\x26\x08\x17')) + assertThat(dut_channel).emits(L2capMatchers.PacketPayloadRawData(b'\x19\x26\x08\x17')) - @metadata( - pts_test_id="L2CAP/COS/CFC/BV-05-C", - pts_test_name="Multiple Channels with Interleaved Data Streams") + @metadata(pts_test_id="L2CAP/COS/CFC/BV-05-C", pts_test_name="Multiple Channels with Interleaved Data Streams") def test_multiple_channels_with_interleaved_data_streams(self): """ Verify that an IUT can create multiple channels and receives data streams on the channels when the streams are interleaved. """ self._setup_link_from_cert() - (dut_channel_x, cert_channel_x) = self._open_channel_from_cert( - signal_id=1, scid=0x0103, psm=0x33) - (dut_channel_y, cert_channel_y) = self._open_channel_from_cert( - signal_id=2, scid=0x0105, psm=0x35) - (dut_channel_z, cert_channel_z) = self._open_channel_from_cert( - signal_id=3, scid=0x0107, psm=0x37) + (dut_channel_x, cert_channel_x) = self._open_channel_from_cert(signal_id=1, scid=0x0103, psm=0x33) + (dut_channel_y, cert_channel_y) = self._open_channel_from_cert(signal_id=2, scid=0x0105, psm=0x35) + (dut_channel_z, cert_channel_z) = self._open_channel_from_cert(signal_id=3, scid=0x0107, psm=0x37) cert_channel_y.send_first_le_i_frame(4, SAMPLE_PACKET) cert_channel_z.send_first_le_i_frame(4, SAMPLE_PACKET) cert_channel_y.send_first_le_i_frame(4, SAMPLE_PACKET) cert_channel_z.send_first_le_i_frame(4, SAMPLE_PACKET) cert_channel_y.send_first_le_i_frame(4, SAMPLE_PACKET) # TODO: We should assert two events in order, but it got stuck - assertThat(dut_channel_y).emits( - L2capMatchers.PacketPayloadRawData(b'\x19\x26\x08\x17'), - at_least_times=3) + assertThat(dut_channel_y).emits(L2capMatchers.PacketPayloadRawData(b'\x19\x26\x08\x17'), at_least_times=3) assertThat(dut_channel_z).emits( L2capMatchers.PacketPayloadRawData(b'\x19\x26\x08\x17'), L2capMatchers.PacketPayloadRawData(b'\x19\x26\x08\x17')).inOrder() cert_channel_z.send_first_le_i_frame(4, SAMPLE_PACKET) - assertThat(dut_channel_z).emits( - L2capMatchers.PacketPayloadRawData(b'\x19\x26\x08\x17')) + assertThat(dut_channel_z).emits(L2capMatchers.PacketPayloadRawData(b'\x19\x26\x08\x17')) - @metadata( - pts_test_id="L2CAP/LE/REJ/BI-01-C", - pts_test_name="Reject Unknown Command in LE Signaling Channel") + @metadata(pts_test_id="L2CAP/LE/REJ/BI-01-C", pts_test_name="Reject Unknown Command in LE Signaling Channel") def test_reject_unknown_command_in_le_sigling_channel(self): """ Verify that the IUT is able to reject unknown command. @@ -356,41 +293,30 @@ class LeL2capTest(GdBaseTestClass): self._setup_link_from_cert() self.cert_l2cap.get_control_channel().send( l2cap_packets.InformationRequestBuilder( - 2, l2cap_packets.InformationRequestInfoType. - EXTENDED_FEATURES_SUPPORTED)) - assertThat(self.cert_l2cap.get_control_channel()).emits( - L2capMatchers.LeCommandReject()) + 2, l2cap_packets.InformationRequestInfoType.EXTENDED_FEATURES_SUPPORTED)) + assertThat(self.cert_l2cap.get_control_channel()).emits(L2capMatchers.LeCommandReject()) - @metadata( - pts_test_id="L2CAP/LE/REJ/BI-02-C", - pts_test_name="Command Reject – Reserved PDU Codes") + @metadata(pts_test_id="L2CAP/LE/REJ/BI-02-C", pts_test_name="Command Reject – Reserved PDU Codes") def test_command_reject_reserved_pdu_codes(self): """ Verify that an IUT receiving a PDU with a reserved command code sends a command reject. """ self._setup_link_from_cert() - self.cert_l2cap.get_control_channel().send( - l2cap_packets.MoveChannelRequestBuilder(2, 0, 0)) - assertThat(self.cert_l2cap.get_control_channel()).emits( - L2capMatchers.LeCommandReject()) + self.cert_l2cap.get_control_channel().send(l2cap_packets.MoveChannelRequestBuilder(2, 0, 0)) + assertThat(self.cert_l2cap.get_control_channel()).emits(L2capMatchers.LeCommandReject()) - @metadata( - pts_test_id="L2CAP/LE/CFC/BV-01-C", - pts_test_name="LE Credit Based Connection Request - Legacy Peer") + @metadata(pts_test_id="L2CAP/LE/CFC/BV-01-C", pts_test_name="LE Credit Based Connection Request - Legacy Peer") def test_le_credit_based_connection_request_legacy_peer(self): """ Verify that an IUT sending an LE Credit Based Connection Request to a legacy peer and receiving a Command Reject does not establish the channel. """ self._setup_link_from_cert() - response_future = self.dut_l2cap.connect_coc_to_cert( - self.cert_address, psm=0x33) + response_future = self.dut_l2cap.connect_coc_to_cert(self.cert_address, psm=0x33) self.cert_l2cap.verify_and_reject_open_channel_from_remote(psm=0x33) - assertThat(response_future.get_status()).isNotEqualTo( - LeCreditBasedConnectionResponseResult.SUCCESS) + assertThat(response_future.get_status()).isNotEqualTo(LeCreditBasedConnectionResponseResult.SUCCESS) @metadata( - pts_test_id="L2CAP/LE/CFC/BV-02-C", - pts_test_name="LE Credit Based Connection Request on Supported LE_PSM") + pts_test_id="L2CAP/LE/CFC/BV-02-C", pts_test_name="LE Credit Based Connection Request on Supported LE_PSM") def test_le_credit_based_connection_request_on_supported_le_psm(self): """ Verify that an IUT sending an LE Credit Based Connection Request to a peer will establish the channel upon receiving the LE Credit Based Connection Response. @@ -398,12 +324,10 @@ class LeL2capTest(GdBaseTestClass): self._setup_link_from_cert() (dut_channel, cert_channel) = self._open_channel_from_dut() cert_channel.send_first_le_i_frame(4, SAMPLE_PACKET) - assertThat(dut_channel).emits( - L2capMatchers.PacketPayloadRawData(b'\x19\x26\x08\x17')) + assertThat(dut_channel).emits(L2capMatchers.PacketPayloadRawData(b'\x19\x26\x08\x17')) @metadata( - pts_test_id="L2CAP/LE/CFC/BV-03-C", - pts_test_name="LE Credit Based Connection Response on Supported LE_PSM") + pts_test_id="L2CAP/LE/CFC/BV-03-C", pts_test_name="LE Credit Based Connection Response on Supported LE_PSM") def test_credit_based_connection_response_on_supported_le_psm(self): """ Verify that an IUT receiving a valid LE Credit Based Connection Request from a peer will send an LE Credit Based Connection Response and establish the channel. @@ -411,68 +335,51 @@ class LeL2capTest(GdBaseTestClass): self._setup_link_from_cert() (dut_channel, cert_channel) = self._open_channel_from_cert() dut_channel.send(b'hello') - assertThat(cert_channel).emits( - L2capMatchers.FirstLeIFrame(b'hello', sdu_size=5)) + assertThat(cert_channel).emits(L2capMatchers.FirstLeIFrame(b'hello', sdu_size=5)) @metadata( - pts_test_id="L2CAP/LE/CFC/BV-04-C", - pts_test_name= - "LE Credit Based Connection Request on an Unsupported LE_PSM") + pts_test_id="L2CAP/LE/CFC/BV-04-C", pts_test_name="LE Credit Based Connection Request on an Unsupported LE_PSM") def test_credit_based_connection_request_on_an_unsupported_le_psm(self): """ Verify that an IUT sending an LE Credit Based Connection Request on an unsupported LE_PSM will not establish a channel upon receiving an LE Credit Based Connection Response refusing the connection. """ self._setup_link_from_cert() - response_future = self.dut_l2cap.connect_coc_to_cert( - self.cert_address, psm=0x33) + response_future = self.dut_l2cap.connect_coc_to_cert(self.cert_address, psm=0x33) self.cert_l2cap.verify_and_respond_open_channel_from_remote( - psm=0x33, - result=LeCreditBasedConnectionResponseResult.LE_PSM_NOT_SUPPORTED) - assertThat(response_future.get_status()).isEqualTo( - LeCreditBasedConnectionResponseResult.LE_PSM_NOT_SUPPORTED) + psm=0x33, result=LeCreditBasedConnectionResponseResult.LE_PSM_NOT_SUPPORTED) + assertThat(response_future.get_status()).isEqualTo(LeCreditBasedConnectionResponseResult.LE_PSM_NOT_SUPPORTED) @metadata( - pts_test_id="L2CAP/LE/CFC/BV-05-C", - pts_test_name="LE Credit Based Connection Request - unsupported LE_PSM") + pts_test_id="L2CAP/LE/CFC/BV-05-C", pts_test_name="LE Credit Based Connection Request - unsupported LE_PSM") def test_credit_based_connection_request_unsupported_le_psm(self): """ Verify that an IUT receiving an LE Credit Based Connection Request on an unsupported LE_PSM will respond with an LE Credit Based Connection Response refusing the connection. """ self._setup_link_from_cert() self.cert_l2cap.get_control_channel().send( - l2cap_packets.LeCreditBasedConnectionRequestBuilder( - 1, 0x34, 0x0101, 2000, 1000, 1000)) + l2cap_packets.LeCreditBasedConnectionRequestBuilder(1, 0x34, 0x0101, 2000, 1000, 1000)) assertThat(self.cert_l2cap.get_control_channel()).emits( L2capMatchers.CreditBasedConnectionResponse( - result=LeCreditBasedConnectionResponseResult. - LE_PSM_NOT_SUPPORTED)) + result=LeCreditBasedConnectionResponseResult.LE_PSM_NOT_SUPPORTED)) - @metadata( - pts_test_id="L2CAP/LE/CFC/BV-06-C", - pts_test_name="Credit Exchange – Receiving Incremental Credits") + @metadata(pts_test_id="L2CAP/LE/CFC/BV-06-C", pts_test_name="Credit Exchange – Receiving Incremental Credits") def test_credit_exchange_receiving_incremental_credits(self): """ Verify the IUT handles flow control correctly, by handling the LE Flow Control Credit sent by the peer. """ self._setup_link_from_cert() - (dut_channel, - cert_channel) = self._open_channel_from_cert(initial_credit=0) + (dut_channel, cert_channel) = self._open_channel_from_cert(initial_credit=0) for _ in range(4): dut_channel.send(b'hello') cert_channel.send_credits(1) - assertThat(cert_channel).emits( - L2capMatchers.FirstLeIFrame(b'hello', sdu_size=5)) + assertThat(cert_channel).emits(L2capMatchers.FirstLeIFrame(b'hello', sdu_size=5)) cert_channel.send_credits(1) - assertThat(cert_channel).emits( - L2capMatchers.FirstLeIFrame(b'hello', sdu_size=5)) + assertThat(cert_channel).emits(L2capMatchers.FirstLeIFrame(b'hello', sdu_size=5)) cert_channel.send_credits(2) assertThat(cert_channel).emits( - L2capMatchers.FirstLeIFrame(b'hello', sdu_size=5), - L2capMatchers.FirstLeIFrame(b'hello', sdu_size=5)) + L2capMatchers.FirstLeIFrame(b'hello', sdu_size=5), L2capMatchers.FirstLeIFrame(b'hello', sdu_size=5)) - @metadata( - pts_test_id="L2CAP/LE/CFC/BV-07-C", - pts_test_name="Credit Exchange – Sending Credits") + @metadata(pts_test_id="L2CAP/LE/CFC/BV-07-C", pts_test_name="Credit Exchange – Sending Credits") def test_credit_exchange_sending_credits(self): """ Verify that the IUT sends LE Flow Control Credit to the peer. @@ -488,9 +395,7 @@ class LeL2capTest(GdBaseTestClass): cert_channel.send_first_le_i_frame(4, SAMPLE_PACKET) self.cert_l2cap.verify_le_flow_control_credit(cert_channel) - @metadata( - pts_test_id="L2CAP/LE/CFC/BV-08-C", - pts_test_name="Disconnection Request") + @metadata(pts_test_id="L2CAP/LE/CFC/BV-08-C", pts_test_name="Disconnection Request") def test_disconnection_request(self): """ Verify that the IUT can disconnect the channel. @@ -500,9 +405,7 @@ class LeL2capTest(GdBaseTestClass): dut_channel.close_channel() cert_channel.verify_disconnect_request() - @metadata( - pts_test_id="L2CAP/LE/CFC/BV-09-C", - pts_test_name="Disconnection Response") + @metadata(pts_test_id="L2CAP/LE/CFC/BV-09-C", pts_test_name="Disconnection Response") def test_disconnection_response(self): """ Verify that the IUT responds correctly to reception of a Disconnection Request. @@ -511,26 +414,19 @@ class LeL2capTest(GdBaseTestClass): (dut_channel, cert_channel) = self._open_channel_from_cert() cert_channel.disconnect_and_verify() - @metadata( - pts_test_id="L2CAP/LE/CFC/BV-10-C", - pts_test_name="Security - Insufficient Authentication – Initiator") + @metadata(pts_test_id="L2CAP/LE/CFC/BV-10-C", pts_test_name="Security - Insufficient Authentication – Initiator") def test_security_insufficient_authentication_initiator(self): """ Verify that the IUT does not establish the channel upon receipt of an LE Credit Based Connection Response indicating the connection was refused with Result “0x0005 – Connection Refused – Insufficient Authentication". """ self._setup_link_from_cert() - response_future = self.dut_l2cap.connect_coc_to_cert( - self.cert_address, psm=0x33) + response_future = self.dut_l2cap.connect_coc_to_cert(self.cert_address, psm=0x33) self.cert_l2cap.verify_and_respond_open_channel_from_remote( - psm=0x33, - result=LeCreditBasedConnectionResponseResult. - INSUFFICIENT_AUTHENTICATION) + psm=0x33, result=LeCreditBasedConnectionResponseResult.INSUFFICIENT_AUTHENTICATION) assertThat(response_future.get_status()).isEqualTo( LeCreditBasedConnectionResponseResult.INSUFFICIENT_AUTHENTICATION) - @metadata( - pts_test_id="L2CAP/LE/CFC/BV-11-C", - pts_test_name="Security - Insufficient Authentication – Responder") + @metadata(pts_test_id="L2CAP/LE/CFC/BV-11-C", pts_test_name="Security - Insufficient Authentication – Responder") def test_security_insufficient_authentication_responder(self): """ Verify that an IUT refuses to create a connection upon reception of an LE Credit Based Connection @@ -538,33 +434,23 @@ Request which fails to satisfy authentication requirements. """ self._setup_link_from_cert() psm = 0x33 - self.dut_l2cap.register_coc( - self.cert_address, psm, - SecurityLevel.AUTHENTICATED_PAIRING_WITH_ENCRYPTION) + self.dut_l2cap.register_coc(self.cert_address, psm, SecurityLevel.AUTHENTICATED_PAIRING_WITH_ENCRYPTION) self.cert_l2cap.open_channel_with_expected_result( - psm, - LeCreditBasedConnectionResponseResult.INSUFFICIENT_AUTHENTICATION) + psm, LeCreditBasedConnectionResponseResult.INSUFFICIENT_AUTHENTICATION) - @metadata( - pts_test_id="L2CAP/LE/CFC/BV-12-C", - pts_test_name="Security - Insufficient Authorization – Initiator") + @metadata(pts_test_id="L2CAP/LE/CFC/BV-12-C", pts_test_name="Security - Insufficient Authorization – Initiator") def test_security_insufficient_authorization_initiator(self): """ Verify that the IUT does not establish the channel upon receipt of an LE Credit Based Connection Response indicating the connection was refused with Result “0x0006 – Connection Refused – Insufficient Authorization”. """ self._setup_link_from_cert() - response_future = self.dut_l2cap.connect_coc_to_cert( - self.cert_address, psm=0x33) + response_future = self.dut_l2cap.connect_coc_to_cert(self.cert_address, psm=0x33) self.cert_l2cap.verify_and_respond_open_channel_from_remote( - psm=0x33, - result=LeCreditBasedConnectionResponseResult. - INSUFFICIENT_AUTHORIZATION) + psm=0x33, result=LeCreditBasedConnectionResponseResult.INSUFFICIENT_AUTHORIZATION) assertThat(response_future.get_status()).isEqualTo( LeCreditBasedConnectionResponseResult.INSUFFICIENT_AUTHORIZATION) - @metadata( - pts_test_id="L2CAP/LE/CFC/BV-13-C", - pts_test_name="Security - Insufficient Authorization – Responder") + @metadata(pts_test_id="L2CAP/LE/CFC/BV-13-C", pts_test_name="Security - Insufficient Authorization – Responder") def test_security_insufficient_authorization_responder(self): """ Verify that an IUT refuses to create a connection upon reception of an LE Credit Based Connection @@ -572,15 +458,11 @@ Request which fails to satisfy authentication requirements. """ self._setup_link_from_cert() psm = 0x33 - self.dut_l2cap.register_coc(self.cert_address, psm, - SecurityLevel.AUTHORIZATION) + self.dut_l2cap.register_coc(self.cert_address, psm, SecurityLevel.AUTHORIZATION) self.cert_l2cap.open_channel_with_expected_result( - psm, - LeCreditBasedConnectionResponseResult.INSUFFICIENT_AUTHORIZATION) + psm, LeCreditBasedConnectionResponseResult.INSUFFICIENT_AUTHORIZATION) - @metadata( - pts_test_id="L2CAP/LE/CFC/BV-14-C", - pts_test_name="Security - Insufficient Key Size – Initiator") + @metadata(pts_test_id="L2CAP/LE/CFC/BV-14-C", pts_test_name="Security - Insufficient Key Size – Initiator") def test_security_insufficient_key_size_initiator(self): """ Verify that the IUT does not establish the channel upon receipt of an @@ -589,19 +471,14 @@ Request which fails to satisfy authentication requirements. Encryption Key Size". """ self._setup_link_from_cert() - response_future = self.dut_l2cap.connect_coc_to_cert( - self.cert_address, psm=0x33) + response_future = self.dut_l2cap.connect_coc_to_cert(self.cert_address, psm=0x33) self.cert_l2cap.verify_and_respond_open_channel_from_remote( - psm=0x33, - result=LeCreditBasedConnectionResponseResult. - INSUFFICIENT_ENCRYPTION_KEY_SIZE) + psm=0x33, result=LeCreditBasedConnectionResponseResult.INSUFFICIENT_ENCRYPTION_KEY_SIZE) assertThat(response_future.get_status()).isEqualTo( - LeCreditBasedConnectionResponseResult. - INSUFFICIENT_ENCRYPTION_KEY_SIZE) + LeCreditBasedConnectionResponseResult.INSUFFICIENT_ENCRYPTION_KEY_SIZE) @metadata( - pts_test_id="L2CAP/LE/CFC/BV-15-C", - pts_test_name="Security - Insufficient Encryption Key Size – Responder") + pts_test_id="L2CAP/LE/CFC/BV-15-C", pts_test_name="Security - Insufficient Encryption Key Size – Responder") def test_security_insufficient_encryption_key_size_responder(self): """ Verify that an IUT refuses to create a connection upon receipt of an LE Credit Based Connection @@ -609,18 +486,13 @@ Request which fails to satisfy authentication requirements. """ self._setup_link_from_cert() psm = 0x33 - self.dut_l2cap.register_coc( - self.cert_address, psm, - SecurityLevel.AUTHENTICATED_PAIRING_WITH_128_BIT_KEY) + self.dut_l2cap.register_coc(self.cert_address, psm, SecurityLevel.AUTHENTICATED_PAIRING_WITH_128_BIT_KEY) self.cert_l2cap.open_channel_with_expected_result( - psm, LeCreditBasedConnectionResponseResult. - INSUFFICIENT_ENCRYPTION_KEY_SIZE) + psm, LeCreditBasedConnectionResponseResult.INSUFFICIENT_ENCRYPTION_KEY_SIZE) @metadata( pts_test_id="L2CAP/LE/CFC/BV-16-C", - pts_test_name= - "LE Credit Based Connection Request - refuse due to insufficient resources - Initiator" - ) + pts_test_name="LE Credit Based Connection Request - refuse due to insufficient resources - Initiator") def test_le_connection_request_insufficient_resources_initiator(self): """ Verify that an IUT sending an LE Credit Based Connection Request does @@ -629,94 +501,67 @@ Request which fails to satisfy authentication requirements. refused – no resources available". """ self._setup_link_from_cert() - response_future = self.dut_l2cap.connect_coc_to_cert( - self.cert_address, psm=0x33) + response_future = self.dut_l2cap.connect_coc_to_cert(self.cert_address, psm=0x33) self.cert_l2cap.verify_and_respond_open_channel_from_remote( - psm=0x33, - result=LeCreditBasedConnectionResponseResult.NO_RESOURCES_AVAILABLE) - assertThat(response_future.get_status()).isEqualTo( - LeCreditBasedConnectionResponseResult.NO_RESOURCES_AVAILABLE) + psm=0x33, result=LeCreditBasedConnectionResponseResult.NO_RESOURCES_AVAILABLE) + assertThat(response_future.get_status()).isEqualTo(LeCreditBasedConnectionResponseResult.NO_RESOURCES_AVAILABLE) @metadata( pts_test_id="L2CAP/LE/CFC/BV-18-C", - pts_test_name= - "LE Credit Based Connection Request - refused due to Invalid Source CID - Initiator" - ) + pts_test_name="LE Credit Based Connection Request - refused due to Invalid Source CID - Initiator") def test_request_refused_due_to_invalid_source_cid_initiator(self): """ Verify that an IUT sending an LE Credit Based Connection Request does not establish the channel upon receiving an LE Credit Based Connection Response refusing the connection with result "0x0009 – Connection refused – Invalid Source CID". """ self._setup_link_from_cert() - response_future = self.dut_l2cap.connect_coc_to_cert( - self.cert_address, psm=0x33) + response_future = self.dut_l2cap.connect_coc_to_cert(self.cert_address, psm=0x33) self.cert_l2cap.verify_and_respond_open_channel_from_remote( - psm=0x33, - result=LeCreditBasedConnectionResponseResult.INVALID_SOURCE_CID) - assertThat(response_future.get_status()).isEqualTo( - LeCreditBasedConnectionResponseResult.INVALID_SOURCE_CID) + psm=0x33, result=LeCreditBasedConnectionResponseResult.INVALID_SOURCE_CID) + assertThat(response_future.get_status()).isEqualTo(LeCreditBasedConnectionResponseResult.INVALID_SOURCE_CID) @metadata( pts_test_id="L2CAP/LE/CFC/BV-19-C", - pts_test_name= - "LE Credit Based Connection Request - refused due to source CID already allocated - Initiator" - ) - def test_request_refused_due_to_source_cid_already_allocated_initiator( - self): + pts_test_name="LE Credit Based Connection Request - refused due to source CID already allocated - Initiator") + def test_request_refused_due_to_source_cid_already_allocated_initiator(self): """ Verify that an IUT sending an LE Credit Based Connection Request does not establish the channel upon receiving an LE Credit Based Connection Response refusing the connection with result "0x000A – Connection refused – Source CID already allocated". """ self._setup_link_from_cert() - response_future = self.dut_l2cap.connect_coc_to_cert( - self.cert_address, psm=0x33) + response_future = self.dut_l2cap.connect_coc_to_cert(self.cert_address, psm=0x33) self.cert_l2cap.verify_and_respond_open_channel_from_remote( - psm=0x33, - result=LeCreditBasedConnectionResponseResult. - SOURCE_CID_ALREADY_ALLOCATED) + psm=0x33, result=LeCreditBasedConnectionResponseResult.SOURCE_CID_ALREADY_ALLOCATED) assertThat(response_future.get_status()).isEqualTo( LeCreditBasedConnectionResponseResult.SOURCE_CID_ALREADY_ALLOCATED) @metadata( pts_test_id="L2CAP/LE/CFC/BV-20-C", - pts_test_name= - "LE Credit Based Connection Response - refused due to Source CID already allocated - Responder" - ) - def test_request_refused_due_to_source_cid_already_allocated_responder( - self): + pts_test_name="LE Credit Based Connection Response - refused due to Source CID already allocated - Responder") + def test_request_refused_due_to_source_cid_already_allocated_responder(self): """ Verify that an IUT receiving an LE Credit Based Connection Request for a second channel will refuse the connection with result "0x000A - Connection refused – Source CID already allocated" if it receives a Source CID which is already in use. """ self._setup_link_from_cert() - (dut_channel, cert_channel) = self._open_channel_from_cert( - psm=0x33, scid=0x0101) + (dut_channel, cert_channel) = self._open_channel_from_cert(psm=0x33, scid=0x0101) self.dut_l2cap.register_coc(self.cert_address, psm=0x35) self.cert_l2cap.get_control_channel().send( - l2cap_packets.LeCreditBasedConnectionRequestBuilder( - 2, 0x35, 0x0101, 1000, 1000, 1000)) - assertThat(self.cert_l2cap.get_control_channel()).emits( - L2capMatchers.CreditBasedConnectionResponseUsedCid()) + l2cap_packets.LeCreditBasedConnectionRequestBuilder(2, 0x35, 0x0101, 1000, 1000, 1000)) + assertThat(self.cert_l2cap.get_control_channel()).emits(L2capMatchers.CreditBasedConnectionResponseUsedCid()) @metadata( pts_test_id="L2CAP/LE/CFC/BV-21-C", - pts_test_name= - "LE Credit Based Connection Request - refused due to Unacceptable Parameters - Initiator" - ) + pts_test_name="LE Credit Based Connection Request - refused due to Unacceptable Parameters - Initiator") def test_request_refused_due_to_unacceptable_parameters_initiator(self): """ Verify that an IUT sending an LE Credit Based Connection Request does not establish the channel upon receiving an LE Credit Based Connection Response refusing the connection with result "0x000B – Connection refused – Unacceptable Parameters". """ self._setup_link_from_cert() - response_future = self.dut_l2cap.connect_coc_to_cert( - self.cert_address, psm=0x33) + response_future = self.dut_l2cap.connect_coc_to_cert(self.cert_address, psm=0x33) self.cert_l2cap.verify_and_respond_open_channel_from_remote( - psm=0x33, - result=LeCreditBasedConnectionResponseResult.UNACCEPTABLE_PARAMETERS - ) + psm=0x33, result=LeCreditBasedConnectionResponseResult.UNACCEPTABLE_PARAMETERS) assertThat(response_future.get_status()).isEqualTo( LeCreditBasedConnectionResponseResult.UNACCEPTABLE_PARAMETERS) - @metadata( - pts_test_id="L2CAP/LE/CFC/BI-01-C", - pts_test_name="Credit Exchange – Exceed Initial Credits") + @metadata(pts_test_id="L2CAP/LE/CFC/BI-01-C", pts_test_name="Credit Exchange – Exceed Initial Credits") def test_credit_exchange_exceed_initial_credits(self): """ Verify that the IUT disconnects the LE Data Channel when the credit count exceeds 65535. diff --git a/system/gd/neighbor/cert/neighbor_test.py b/system/gd/neighbor/cert/neighbor_test.py index 7a8c60cac5..4080aaafe2 100644 --- a/system/gd/neighbor/cert/neighbor_test.py +++ b/system/gd/neighbor/cert/neighbor_test.py @@ -35,8 +35,7 @@ class NeighborTest(GdBaseTestClass): super().setup_test() self.cert_hci = PyHci(self.cert, acl_streaming=True) self.cert_hci.send_command_with_complete( - hci_packets.WriteScanEnableBuilder( - hci_packets.ScanEnable.INQUIRY_AND_PAGE_SCAN)) + hci_packets.WriteScanEnableBuilder(hci_packets.ScanEnable.INQUIRY_AND_PAGE_SCAN)) self.cert_name = b'Im_A_Cert' self.cert_address = self.cert_hci.read_own_address() self.cert_name += b'@' + self.cert_address.encode('utf8') @@ -50,11 +49,9 @@ class NeighborTest(GdBaseTestClass): padded_name = self.cert_name while len(padded_name) < 248: padded_name = padded_name + b'\0' - self.cert_hci.send_command_with_complete( - hci_packets.WriteLocalNameBuilder(padded_name)) + self.cert_hci.send_command_with_complete(hci_packets.WriteLocalNameBuilder(padded_name)) - assertThat(self.cert_hci.get_event_stream()).emits( - HciMatchers.CommandComplete(OpCode.WRITE_LOCAL_NAME)) + assertThat(self.cert_hci.get_event_stream()).emits(HciMatchers.CommandComplete(OpCode.WRITE_LOCAL_NAME)) def test_inquiry_from_dut(self): inquiry_msg = neighbor_facade.InquiryMsg( @@ -64,11 +61,8 @@ class NeighborTest(GdBaseTestClass): max_results=0) session = self.dut_neighbor.set_inquiry_mode(inquiry_msg) self.cert_hci.send_command_with_complete( - hci_packets.WriteScanEnableBuilder( - hci_packets.ScanEnable.INQUIRY_AND_PAGE_SCAN)) - assertThat(session).emits( - NeighborMatchers.InquiryResult(self.cert_address), - timeout=timedelta(seconds=10)) + hci_packets.WriteScanEnableBuilder(hci_packets.ScanEnable.INQUIRY_AND_PAGE_SCAN)) + assertThat(session).emits(NeighborMatchers.InquiryResult(self.cert_address), timeout=timedelta(seconds=10)) def test_inquiry_rssi_from_dut(self): inquiry_msg = neighbor_facade.InquiryMsg( @@ -78,11 +72,9 @@ class NeighborTest(GdBaseTestClass): max_results=0) session = self.dut_neighbor.set_inquiry_mode(inquiry_msg) self.cert_hci.send_command_with_complete( - hci_packets.WriteScanEnableBuilder( - hci_packets.ScanEnable.INQUIRY_AND_PAGE_SCAN)) + hci_packets.WriteScanEnableBuilder(hci_packets.ScanEnable.INQUIRY_AND_PAGE_SCAN)) assertThat(session).emits( - NeighborMatchers.InquiryResultwithRssi(self.cert_address), - timeout=timedelta(seconds=10)) + NeighborMatchers.InquiryResultwithRssi(self.cert_address), timeout=timedelta(seconds=10)) def test_inquiry_extended_from_dut(self): self._set_name() @@ -92,8 +84,7 @@ class NeighborTest(GdBaseTestClass): gap_data = list([gap_name]) self.cert_hci.send_command_with_complete( - hci_packets.WriteExtendedInquiryResponseBuilder( - hci_packets.FecRequired.NOT_REQUIRED, gap_data)) + hci_packets.WriteExtendedInquiryResponseBuilder(hci_packets.FecRequired.NOT_REQUIRED, gap_data)) inquiry_msg = neighbor_facade.InquiryMsg( inquiry_mode=neighbor_facade.DiscoverabilityMode.GENERAL, result_mode=neighbor_facade.ResultMode.EXTENDED, @@ -101,11 +92,9 @@ class NeighborTest(GdBaseTestClass): max_results=0) session = self.dut_neighbor.set_inquiry_mode(inquiry_msg) self.cert_hci.send_command_with_complete( - hci_packets.WriteScanEnableBuilder( - hci_packets.ScanEnable.INQUIRY_AND_PAGE_SCAN)) + hci_packets.WriteScanEnableBuilder(hci_packets.ScanEnable.INQUIRY_AND_PAGE_SCAN)) assertThat(session).emits( - NeighborMatchers.ExtendedInquiryResult(self.cert_address), - timeout=timedelta(seconds=10)) + NeighborMatchers.ExtendedInquiryResult(self.cert_address), timeout=timedelta(seconds=10)) def test_remote_name(self): self._set_name() diff --git a/system/gd/neighbor/cert/py_neighbor.py b/system/gd/neighbor/cert/py_neighbor.py index b21be76b24..7b31a08582 100644 --- a/system/gd/neighbor/cert/py_neighbor.py +++ b/system/gd/neighbor/cert/py_neighbor.py @@ -30,8 +30,7 @@ from neighbor.facade import facade_pb2 as neighbor_facade class InquirySession(Closable, IEventStream): def __init__(self, device, inquiry_msg): - self.inquiry_event_stream = EventStream( - device.neighbor.SetInquiryMode(inquiry_msg)) + self.inquiry_event_stream = EventStream(device.neighbor.SetInquiryMode(inquiry_msg)) def get_event_queue(self): return self.inquiry_event_stream.get_event_queue() @@ -43,12 +42,10 @@ class InquirySession(Closable, IEventStream): class GetRemoteNameSession(Closable): def __init__(self, device): - self.remote_name_stream = EventStream( - device.neighbor.GetRemoteNameEvents(empty_proto.Empty())) + self.remote_name_stream = EventStream(device.neighbor.GetRemoteNameEvents(empty_proto.Empty())) def verify_name(self, name): - assertThat(self.remote_name_stream).emits( - lambda msg: bytes(name) in msg.name, timeout=timedelta(seconds=10)) + assertThat(self.remote_name_stream).emits(lambda msg: bytes(name) in msg.name, timeout=timedelta(seconds=10)) def close(self): safeClose(self.remote_name_stream) @@ -72,9 +69,7 @@ class PyNeighbor(object): """ if self.remote_host_supported_features_notification_registered: return - msg = hci_facade.EventCodeMsg( - code=int(hci_packets.EventCode. - REMOTE_HOST_SUPPORTED_FEATURES_NOTIFICATION)) + msg = hci_facade.EventCodeMsg(code=int(hci_packets.EventCode.REMOTE_HOST_SUPPORTED_FEATURES_NOTIFICATION)) self.device.hci.RegisterEventHandler(msg) self.remote_host_supported_features_notification_registered = True @@ -85,7 +80,5 @@ class PyNeighbor(object): self._register_remote_host_supported_features_notification() self.device.neighbor.ReadRemoteName( neighbor_facade.RemoteNameRequestMsg( - address=remote_address.encode('utf8'), - page_scan_repetition_mode=1, - clock_offset=0x6855)) + address=remote_address.encode('utf8'), page_scan_repetition_mode=1, clock_offset=0x6855)) return GetRemoteNameSession(self.device) diff --git a/system/gd/security/cert/cert_security.py b/system/gd/security/cert/cert_security.py index b23fd010b0..b95e1244de 100644 --- a/system/gd/security/cert/cert_security.py +++ b/system/gd/security/cert/cert_security.py @@ -38,14 +38,10 @@ class CertSecurity(PySecurity): HCI commands following the Classic Pairing flows. """ _io_cap_lookup = { - IoCapabilities.DISPLAY_ONLY: - hci_packets.IoCapability.DISPLAY_ONLY, - IoCapabilities.DISPLAY_YES_NO_IO_CAP: - hci_packets.IoCapability.DISPLAY_YES_NO, - IoCapabilities.KEYBOARD_ONLY: - hci_packets.IoCapability.KEYBOARD_ONLY, - IoCapabilities.NO_INPUT_NO_OUTPUT: - hci_packets.IoCapability.NO_INPUT_NO_OUTPUT, + IoCapabilities.DISPLAY_ONLY: hci_packets.IoCapability.DISPLAY_ONLY, + IoCapabilities.DISPLAY_YES_NO_IO_CAP: hci_packets.IoCapability.DISPLAY_YES_NO, + IoCapabilities.KEYBOARD_ONLY: hci_packets.IoCapability.KEYBOARD_ONLY, + IoCapabilities.NO_INPUT_NO_OUTPUT: hci_packets.IoCapability.NO_INPUT_NO_OUTPUT, } _auth_req_lookup = { @@ -56,8 +52,7 @@ class CertSecurity(PySecurity): AuthenticationRequirements.DEDICATED_BONDING: hci_packets.AuthenticationRequirements.DEDICATED_BONDING, AuthenticationRequirements.DEDICATED_BONDING_MITM_PROTECTION: - hci_packets.AuthenticationRequirements. - DEDICATED_BONDING_MITM_PROTECTION, + hci_packets.AuthenticationRequirements.DEDICATED_BONDING_MITM_PROTECTION, AuthenticationRequirements.GENERAL_BONDING: hci_packets.AuthenticationRequirements.GENERAL_BONDING, AuthenticationRequirements.GENERAL_BONDING_MITM_PROTECTION: @@ -65,14 +60,10 @@ class CertSecurity(PySecurity): } _oob_present_lookup = { - OobDataPresent.NOT_PRESENT: - hci_packets.OobDataPresent.NOT_PRESENT, - OobDataPresent.P192_PRESENT: - hci_packets.OobDataPresent.P_192_PRESENT, - OobDataPresent.P256_PRESENT: - hci_packets.OobDataPresent.P_256_PRESENT, - OobDataPresent.P192_AND_256_PRESENT: - hci_packets.OobDataPresent.P_192_AND_256_PRESENT, + OobDataPresent.NOT_PRESENT: hci_packets.OobDataPresent.NOT_PRESENT, + OobDataPresent.P192_PRESENT: hci_packets.OobDataPresent.P_192_PRESENT, + OobDataPresent.P256_PRESENT: hci_packets.OobDataPresent.P_256_PRESENT, + OobDataPresent.P192_AND_256_PRESENT: hci_packets.OobDataPresent.P_192_AND_256_PRESENT, } _hci_event_stream = None @@ -97,23 +88,18 @@ class CertSecurity(PySecurity): self._device.wait_channel_ready() self._hci = PyHci(device) self._hci.register_for_events( - hci_packets.EventCode.LINK_KEY_REQUEST, - hci_packets.EventCode.IO_CAPABILITY_REQUEST, - hci_packets.EventCode.IO_CAPABILITY_RESPONSE, - hci_packets.EventCode.USER_PASSKEY_NOTIFICATION, - hci_packets.EventCode.USER_PASSKEY_REQUEST, - hci_packets.EventCode.USER_CONFIRMATION_REQUEST, + hci_packets.EventCode.LINK_KEY_REQUEST, hci_packets.EventCode.IO_CAPABILITY_REQUEST, + hci_packets.EventCode.IO_CAPABILITY_RESPONSE, hci_packets.EventCode.USER_PASSKEY_NOTIFICATION, + hci_packets.EventCode.USER_PASSKEY_REQUEST, hci_packets.EventCode.USER_CONFIRMATION_REQUEST, hci_packets.EventCode.REMOTE_HOST_SUPPORTED_FEATURES_NOTIFICATION, - hci_packets.EventCode.LINK_KEY_NOTIFICATION, - hci_packets.EventCode.SIMPLE_PAIRING_COMPLETE) + hci_packets.EventCode.LINK_KEY_NOTIFICATION, hci_packets.EventCode.SIMPLE_PAIRING_COMPLETE) self._hci_event_stream = self._hci.get_event_stream() def create_bond(self, address, type): """ Creates a bond from the cert perspective """ - logging.info("Cert: Creating bond to '%s' from '%s'" % - (str(address), str(self._device.address))) + logging.info("Cert: Creating bond to '%s' from '%s'" % (str(address), str(self._device.address))) # TODO(optedoblivion): Trigger connection to Send AuthenticationRequested def remove_bond(self, address): @@ -127,34 +113,28 @@ class CertSecurity(PySecurity): """ Set the IO Capabilities used for the cert """ - logging.info( - "Cert: setting IO Capabilities data to '%s'" % io_capabilities) - self._io_caps = self._io_cap_lookup.get( - io_capabilities, hci_packets.IoCapability.DISPLAY_YES_NO) + logging.info("Cert: setting IO Capabilities data to '%s'" % io_capabilities) + self._io_caps = self._io_cap_lookup.get(io_capabilities, hci_packets.IoCapability.DISPLAY_YES_NO) def set_authentication_requirements(self, auth_reqs): """ Establish authentication requirements for the stack """ - logging.info("Cert: setting Authentication Requirements data to '%s'" % - auth_reqs) - self._auth_reqs = self._auth_req_lookup.get( - auth_reqs, hci_packets.AuthenticationRequirements.GENERAL_BONDING) + logging.info("Cert: setting Authentication Requirements data to '%s'" % auth_reqs) + self._auth_reqs = self._auth_req_lookup.get(auth_reqs, hci_packets.AuthenticationRequirements.GENERAL_BONDING) def set_oob_data(self, data): """ Set the Out-of-band data for SSP pairing """ logging.info("Cert: setting OOB data present to '%s'" % data) - self._oob_data = self._oob_present_lookup.get( - data, hci_packets.OobDataPresent.NOT_PRESENT) + self._oob_data = self._oob_present_lookup.get(data, hci_packets.OobDataPresent.NOT_PRESENT) def send_ui_callback(self, address, callback_type, b, uid): """ Pretend to answer the pairing dailog as a user """ - logging.info( - "Cert: Send user input callback uid:%d; response: %s" % (uid, b)) + logging.info("Cert: Send user input callback uid:%d; response: %s" % (uid, b)) # TODO(optedoblivion): Make callback and set it to the module def enable_secure_simple_pairing(self): @@ -162,12 +142,9 @@ class CertSecurity(PySecurity): This is called when you want to enable SSP for testing """ logging.info("Cert: Sending WRITE_SIMPLE_PAIRING_MODE [True]") - self._enqueue_hci_command( - hci_packets.WriteSimplePairingModeBuilder( - hci_packets.Enable.ENABLED), True) + self._enqueue_hci_command(hci_packets.WriteSimplePairingModeBuilder(hci_packets.Enable.ENABLED), True) logging.info("Cert: Waiting for controller response") - assertThat(self._hci_event_stream).emits( - lambda msg: b'\x0e\x04\x01\x56\x0c' in msg.event) + assertThat(self._hci_event_stream).emits(lambda msg: b'\x0e\x04\x01\x56\x0c' in msg.event) def accept_pairing(self, dut_address, reply_boolean): """ @@ -176,42 +153,29 @@ class CertSecurity(PySecurity): logging.info("Cert: Waiting for LINK_KEY_REQUEST") assertThat(self._hci_event_stream).emits(HciMatchers.LinkKeyRequest()) logging.info("Cert: Sending LINK_KEY_REQUEST_NEGATIVE_REPLY") - self._enqueue_hci_command( - hci_packets.LinkKeyRequestNegativeReplyBuilder( - dut_address.decode('utf8')), True) + self._enqueue_hci_command(hci_packets.LinkKeyRequestNegativeReplyBuilder(dut_address.decode('utf8')), True) logging.info("Cert: Waiting for IO_CAPABILITY_REQUEST") - assertThat(self._hci_event_stream).emits( - HciMatchers.IoCapabilityRequest()) + assertThat(self._hci_event_stream).emits(HciMatchers.IoCapabilityRequest()) logging.info("Cert: Sending IO_CAPABILITY_REQUEST_REPLY") self._enqueue_hci_command( hci_packets.IoCapabilityRequestReplyBuilder( - dut_address.decode('utf8'), self._io_caps, self._oob_data, - self._auth_reqs), True) + dut_address.decode('utf8'), self._io_caps, self._oob_data, self._auth_reqs), True) logging.info("Cert: Waiting for USER_CONFIRMATION_REQUEST") - assertThat(self._hci_event_stream).emits( - HciMatchers.UserConfirmationRequest()) - logging.info( - "Cert: Sending Simulated User Response '%s'" % reply_boolean) + assertThat(self._hci_event_stream).emits(HciMatchers.UserConfirmationRequest()) + logging.info("Cert: Sending Simulated User Response '%s'" % reply_boolean) if reply_boolean: logging.info("Cert: Sending USER_CONFIRMATION_REQUEST_REPLY") - self._enqueue_hci_command( - hci_packets.UserConfirmationRequestReplyBuilder( - dut_address.decode('utf8')), True) + self._enqueue_hci_command(hci_packets.UserConfirmationRequestReplyBuilder(dut_address.decode('utf8')), True) logging.info("Cert: Waiting for LINK_KEY_NOTIFICATION") - assertThat(self._hci_event_stream).emits( - HciMatchers.LinkKeyNotification()) + assertThat(self._hci_event_stream).emits(HciMatchers.LinkKeyNotification()) logging.info("Cert: Waiting for SIMPLE_PAIRING_COMPLETE") - assertThat(self._hci_event_stream).emits( - HciMatchers.SimplePairingComplete()) + assertThat(self._hci_event_stream).emits(HciMatchers.SimplePairingComplete()) else: - logging.info( - "Cert: Sending USER_CONFIRMATION_REQUEST_NEGATIVE_REPLY") + logging.info("Cert: Sending USER_CONFIRMATION_REQUEST_NEGATIVE_REPLY") self._enqueue_hci_command( - hci_packets.UserConfirmationRequestNegativeReplyBuilder( - dut_address.decode('utf8')), True) + hci_packets.UserConfirmationRequestNegativeReplyBuilder(dut_address.decode('utf8')), True) logging.info("Cert: Waiting for SIMPLE_PAIRING_COMPLETE") - assertThat(self._hci_event_stream).emits( - HciMatchers.SimplePairingComplete()) + assertThat(self._hci_event_stream).emits(HciMatchers.SimplePairingComplete()) def on_user_input(self, dut_address, reply_boolean, expected_ui_event): """ diff --git a/system/gd/security/cert/le_security_test.py b/system/gd/security/cert/le_security_test.py index b1075505c6..cece318cf2 100644 --- a/system/gd/security/cert/le_security_test.py +++ b/system/gd/security/cert/le_security_test.py @@ -51,11 +51,9 @@ class LeSecurityTest(GdBaseTestClass): self.cert_security = PyLeSecurity(self.cert) self.dut_address = common.BluetoothAddressWithType( - address = common.BluetoothAddress(address=bytes(b'0D:05:04:03:02:01')), - type=common.RANDOM_DEVICE_ADDRESS) + address=common.BluetoothAddress(address=bytes(b'0D:05:04:03:02:01')), type=common.RANDOM_DEVICE_ADDRESS) self.cert_address = common.BluetoothAddressWithType( - address = common.BluetoothAddress(address=bytes(b'55:11:FF:AA:33:22')), - type=common.RANDOM_DEVICE_ADDRESS) + address=common.BluetoothAddress(address=bytes(b'55:11:FF:AA:33:22')), type=common.RANDOM_DEVICE_ADDRESS) def teardown_test(self): self.dut_security.close() @@ -67,8 +65,7 @@ class LeSecurityTest(GdBaseTestClass): gap_name = hci_packets.GapData() gap_name.data_type = hci_packets.GapDataType.COMPLETE_LOCAL_NAME gap_name.data = list(bytes(b'Im_The_CERT')) - gap_data = le_advertising_facade.GapDataMsg( - data=bytes(gap_name.Serialize())) + gap_data = le_advertising_facade.GapDataMsg(data=bytes(gap_name.Serialize())) config = le_advertising_facade.AdvertisingConfig( advertisement=[gap_data], random_address=self.cert_address.address, @@ -81,12 +78,9 @@ class LeSecurityTest(GdBaseTestClass): channel_map=7, filter_policy=le_advertising_facade.AdvertisingFilterPolicy.ALL_DEVICES) request = le_advertising_facade.CreateAdvertiserRequest(config=config) - create_response = self.cert.hci_le_advertising_manager.CreateAdvertiser( - request) + create_response = self.cert.hci_le_advertising_manager.CreateAdvertiser(request) - @metadata( - pts_test_id="SM/MAS/PROT/BV-01-C", - pts_test_name="SMP Time Out – IUT Initiator") + @metadata(pts_test_id="SM/MAS/PROT/BV-01-C", pts_test_name="SMP Time Out – IUT Initiator") def test_le_smp_timeout_iut_initiator(self): """ Verify that the IUT handles the lack of pairing response after 30 seconds when acting as initiator. @@ -94,5 +88,4 @@ class LeSecurityTest(GdBaseTestClass): self._prepare_cert_for_connection() self.dut.security.CreateBondLe(self.cert_address) self.dut_security.wait_for_bond_event( - expected_bond_event=BondMsgType.DEVICE_BOND_FAILED, - timeout=timedelta(seconds=35)) + expected_bond_event=BondMsgType.DEVICE_BOND_FAILED, timeout=timedelta(seconds=35)) diff --git a/system/gd/security/cert/security_test.py b/system/gd/security/cert/security_test.py index 377a7aceae..f32bccbe91 100644 --- a/system/gd/security/cert/security_test.py +++ b/system/gd/security/cert/security_test.py @@ -43,23 +43,17 @@ class SecurityTest(GdBaseTestClass): def setup_test(self): super().setup_test() - self.dut.neighbor.EnablePageScan( - neighbor_facade.EnableMsg(enabled=True)) - self.cert.neighbor.EnablePageScan( - neighbor_facade.EnableMsg(enabled=True)) + self.dut.neighbor.EnablePageScan(neighbor_facade.EnableMsg(enabled=True)) + self.cert.neighbor.EnablePageScan(neighbor_facade.EnableMsg(enabled=True)) self.dut.name = b'DUT Device' - self.dut.address = self.dut.hci_controller.GetMacAddress( - empty_proto.Empty()).address + self.dut.address = self.dut.hci_controller.GetMacAddress(empty_proto.Empty()).address self.cert.name = b'Cert Device' - self.cert.address = self.cert.hci_controller.GetMacAddress( - empty_proto.Empty()).address + self.cert.address = self.cert.hci_controller.GetMacAddress(empty_proto.Empty()).address # TODO(optedoblivion): Make this happen in PySecurity or GdDevice - self.dut.hci_controller.WriteLocalName( - controller_facade.NameMsg(name=self.dut.name)) - self.cert.hci_controller.WriteLocalName( - controller_facade.NameMsg(name=self.cert.name)) + self.dut.hci_controller.WriteLocalName(controller_facade.NameMsg(name=self.dut.name)) + self.cert.hci_controller.WriteLocalName(controller_facade.NameMsg(name=self.cert.name)) self.dut_security = PySecurity(self.dut) self.cert_security = CertSecurity(self.cert) @@ -70,18 +64,14 @@ class SecurityTest(GdBaseTestClass): super().teardown_test() # SSP Numeric Comparison test cases - def _run_ssp_numeric_comparison( - self, initiator, responder, init_ui_response, resp_ui_response, - expected_init_ui_event, expected_resp_ui_event, - expected_init_bond_event, expected_resp_bond_event): + def _run_ssp_numeric_comparison(self, initiator, responder, init_ui_response, resp_ui_response, + expected_init_ui_event, expected_resp_ui_event, expected_init_bond_event, + expected_resp_bond_event): initiator.enable_secure_simple_pairing() responder.enable_secure_simple_pairing() - initiator.create_bond( - responder.get_address(), - common.BluetoothAddressTypeEnum.PUBLIC_DEVICE_ADDRESS) + initiator.create_bond(responder.get_address(), common.BluetoothAddressTypeEnum.PUBLIC_DEVICE_ADDRESS) responder.accept_pairing(initiator.get_address(), resp_ui_response) - initiator.on_user_input(responder.get_address(), init_ui_response, - expected_init_ui_event) + initiator.on_user_input(responder.get_address(), init_ui_response, expected_init_ui_event) initiator.wait_for_bond_event(expected_init_bond_event) responder.wait_for_bond_event(expected_resp_bond_event) @@ -99,12 +89,10 @@ class SecurityTest(GdBaseTestClass): def test_dut_initiated_display_only_display_only(self): # Arrange self.dut_security.set_io_capabilities(IoCapabilities.DISPLAY_ONLY) - self.dut_security.set_authentication_requirements( - AuthenticationRequirements.DEDICATED_BONDING_MITM_PROTECTION) + self.dut_security.set_authentication_requirements(AuthenticationRequirements.DEDICATED_BONDING_MITM_PROTECTION) self.dut_security.set_oob_data(OobDataPresent.NOT_PRESENT) self.cert_security.set_io_capabilities(IoCapabilities.DISPLAY_ONLY) - self.cert_security.set_authentication_requirements( - AuthenticationRequirements.DEDICATED_BONDING_MITM_PROTECTION) + self.cert_security.set_authentication_requirements(AuthenticationRequirements.DEDICATED_BONDING_MITM_PROTECTION) self.cert_security.set_oob_data(OobDataPresent.NOT_PRESENT) # Act and Assert @@ -121,14 +109,11 @@ class SecurityTest(GdBaseTestClass): # display_yes_no + display_only is JustWorks no confirmation def test_dut_initiated_display_yes_no_display_only(self): # Arrange - self.dut_security.set_io_capabilities( - IoCapabilities.DISPLAY_YES_NO_IO_CAP) - self.dut_security.set_authentication_requirements( - AuthenticationRequirements.DEDICATED_BONDING_MITM_PROTECTION) + self.dut_security.set_io_capabilities(IoCapabilities.DISPLAY_YES_NO_IO_CAP) + self.dut_security.set_authentication_requirements(AuthenticationRequirements.DEDICATED_BONDING_MITM_PROTECTION) self.dut_security.set_oob_data(OobDataPresent.NOT_PRESENT) self.cert_security.set_io_capabilities(IoCapabilities.DISPLAY_ONLY) - self.cert_security.set_authentication_requirements( - AuthenticationRequirements.DEDICATED_BONDING_MITM_PROTECTION) + self.cert_security.set_authentication_requirements(AuthenticationRequirements.DEDICATED_BONDING_MITM_PROTECTION) self.cert_security.set_oob_data(OobDataPresent.NOT_PRESENT) # Act and Assert @@ -146,12 +131,10 @@ class SecurityTest(GdBaseTestClass): def test_dut_initiated_no_input_no_output_display_only(self): # Arrange self.dut_security.set_io_capabilities(IoCapabilities.NO_INPUT_NO_OUTPUT) - self.dut_security.set_authentication_requirements( - AuthenticationRequirements.DEDICATED_BONDING_MITM_PROTECTION) + self.dut_security.set_authentication_requirements(AuthenticationRequirements.DEDICATED_BONDING_MITM_PROTECTION) self.dut_security.set_oob_data(OobDataPresent.NOT_PRESENT) self.cert_security.set_io_capabilities(IoCapabilities.DISPLAY_ONLY) - self.cert_security.set_authentication_requirements( - AuthenticationRequirements.DEDICATED_BONDING_MITM_PROTECTION) + self.cert_security.set_authentication_requirements(AuthenticationRequirements.DEDICATED_BONDING_MITM_PROTECTION) self.cert_security.set_oob_data(OobDataPresent.NOT_PRESENT) # Act and Assert @@ -169,13 +152,10 @@ class SecurityTest(GdBaseTestClass): def test_dut_initiated_display_only_display_yes_no(self): # Arrange self.dut_security.set_io_capabilities(IoCapabilities.DISPLAY_ONLY) - self.dut_security.set_authentication_requirements( - AuthenticationRequirements.DEDICATED_BONDING_MITM_PROTECTION) + self.dut_security.set_authentication_requirements(AuthenticationRequirements.DEDICATED_BONDING_MITM_PROTECTION) self.dut_security.set_oob_data(OobDataPresent.NOT_PRESENT) - self.cert_security.set_io_capabilities( - IoCapabilities.DISPLAY_YES_NO_IO_CAP) - self.cert_security.set_authentication_requirements( - AuthenticationRequirements.DEDICATED_BONDING_MITM_PROTECTION) + self.cert_security.set_io_capabilities(IoCapabilities.DISPLAY_YES_NO_IO_CAP) + self.cert_security.set_authentication_requirements(AuthenticationRequirements.DEDICATED_BONDING_MITM_PROTECTION) self.cert_security.set_oob_data(OobDataPresent.NOT_PRESENT) # Act and Assert @@ -192,15 +172,11 @@ class SecurityTest(GdBaseTestClass): # display_yes_no + display_yes_no is JustWorks no confirmation def test_dut_initiated_display_yes_no_display_yes_no(self): # Arrange - self.dut_security.set_io_capabilities( - IoCapabilities.DISPLAY_YES_NO_IO_CAP) - self.dut_security.set_authentication_requirements( - AuthenticationRequirements.DEDICATED_BONDING_MITM_PROTECTION) + self.dut_security.set_io_capabilities(IoCapabilities.DISPLAY_YES_NO_IO_CAP) + self.dut_security.set_authentication_requirements(AuthenticationRequirements.DEDICATED_BONDING_MITM_PROTECTION) self.dut_security.set_oob_data(OobDataPresent.NOT_PRESENT) - self.cert_security.set_io_capabilities( - IoCapabilities.DISPLAY_YES_NO_IO_CAP) - self.cert_security.set_authentication_requirements( - AuthenticationRequirements.DEDICATED_BONDING_MITM_PROTECTION) + self.cert_security.set_io_capabilities(IoCapabilities.DISPLAY_YES_NO_IO_CAP) + self.cert_security.set_authentication_requirements(AuthenticationRequirements.DEDICATED_BONDING_MITM_PROTECTION) self.cert_security.set_oob_data(OobDataPresent.NOT_PRESENT) # Act and Assert @@ -218,13 +194,10 @@ class SecurityTest(GdBaseTestClass): def test_dut_initiated_no_input_no_output_display_yes_no(self): # Arrange self.dut_security.set_io_capabilities(IoCapabilities.NO_INPUT_NO_OUTPUT) - self.dut_security.set_authentication_requirements( - AuthenticationRequirements.DEDICATED_BONDING_MITM_PROTECTION) + self.dut_security.set_authentication_requirements(AuthenticationRequirements.DEDICATED_BONDING_MITM_PROTECTION) self.dut_security.set_oob_data(OobDataPresent.NOT_PRESENT) - self.cert_security.set_io_capabilities( - IoCapabilities.DISPLAY_YES_NO_IO_CAP) - self.cert_security.set_authentication_requirements( - AuthenticationRequirements.DEDICATED_BONDING_MITM_PROTECTION) + self.cert_security.set_io_capabilities(IoCapabilities.DISPLAY_YES_NO_IO_CAP) + self.cert_security.set_authentication_requirements(AuthenticationRequirements.DEDICATED_BONDING_MITM_PROTECTION) self.cert_security.set_oob_data(OobDataPresent.NOT_PRESENT) # Act and Assert @@ -242,13 +215,10 @@ class SecurityTest(GdBaseTestClass): def test_dut_initiated_no_input_no_output_keyboard_only(self): # Arrange self.dut_security.set_io_capabilities(IoCapabilities.NO_INPUT_NO_OUTPUT) - self.dut_security.set_authentication_requirements( - AuthenticationRequirements.DEDICATED_BONDING_MITM_PROTECTION) + self.dut_security.set_authentication_requirements(AuthenticationRequirements.DEDICATED_BONDING_MITM_PROTECTION) self.dut_security.set_oob_data(OobDataPresent.NOT_PRESENT) - self.cert_security.set_io_capabilities( - IoCapabilities.DISPLAY_YES_NO_IO_CAP) - self.cert_security.set_authentication_requirements( - AuthenticationRequirements.DEDICATED_BONDING_MITM_PROTECTION) + self.cert_security.set_io_capabilities(IoCapabilities.DISPLAY_YES_NO_IO_CAP) + self.cert_security.set_authentication_requirements(AuthenticationRequirements.DEDICATED_BONDING_MITM_PROTECTION) self.cert_security.set_oob_data(OobDataPresent.NOT_PRESENT) # Act and Assert @@ -266,13 +236,10 @@ class SecurityTest(GdBaseTestClass): def test_dut_initiated_keyboard_only_no_input_no_output(self): # Arrange self.dut_security.set_io_capabilities(IoCapabilities.KEYBOARD_ONLY) - self.dut_security.set_authentication_requirements( - AuthenticationRequirements.DEDICATED_BONDING_MITM_PROTECTION) + self.dut_security.set_authentication_requirements(AuthenticationRequirements.DEDICATED_BONDING_MITM_PROTECTION) self.dut_security.set_oob_data(OobDataPresent.NOT_PRESENT) - self.cert_security.set_io_capabilities( - IoCapabilities.NO_INPUT_NO_OUTPUT) - self.cert_security.set_authentication_requirements( - AuthenticationRequirements.DEDICATED_BONDING_MITM_PROTECTION) + self.cert_security.set_io_capabilities(IoCapabilities.NO_INPUT_NO_OUTPUT) + self.cert_security.set_authentication_requirements(AuthenticationRequirements.DEDICATED_BONDING_MITM_PROTECTION) self.cert_security.set_oob_data(OobDataPresent.NOT_PRESENT) # Act and Assert @@ -290,13 +257,10 @@ class SecurityTest(GdBaseTestClass): def test_dut_initiated_no_input_no_output_no_input_no_output(self): # Arrange self.dut_security.set_io_capabilities(IoCapabilities.NO_INPUT_NO_OUTPUT) - self.dut_security.set_authentication_requirements( - AuthenticationRequirements.DEDICATED_BONDING_MITM_PROTECTION) + self.dut_security.set_authentication_requirements(AuthenticationRequirements.DEDICATED_BONDING_MITM_PROTECTION) self.dut_security.set_oob_data(OobDataPresent.NOT_PRESENT) - self.cert_security.set_io_capabilities( - IoCapabilities.NO_INPUT_NO_OUTPUT) - self.cert_security.set_authentication_requirements( - AuthenticationRequirements.DEDICATED_BONDING_MITM_PROTECTION) + self.cert_security.set_io_capabilities(IoCapabilities.NO_INPUT_NO_OUTPUT) + self.cert_security.set_authentication_requirements(AuthenticationRequirements.DEDICATED_BONDING_MITM_PROTECTION) self.cert_security.set_oob_data(OobDataPresent.NOT_PRESENT) # Act and Assert @@ -310,6 +274,7 @@ class SecurityTest(GdBaseTestClass): expected_init_bond_event=BondMsgType.DEVICE_BONDED, expected_resp_bond_event=None) + ## Other permutations #def xtest_dut_initiated_display_only_display_only_local_user_deny(self) #def xtest_dut_initiated_display_only_display_only_remote_user_deny(self) diff --git a/system/gd/setup.py b/system/gd/setup.py index 714dfa2056..e7948042b3 100644 --- a/system/gd/setup.py +++ b/system/gd/setup.py @@ -55,9 +55,7 @@ def set_permissions_for_host_executables(outputs): current_mode = os.stat(file).st_mode new_mode = current_mode | stat.S_IEXEC os.chmod(file, new_mode) - log.log( - log.INFO, "Changed file mode of %s from %s to %s" % - (file, oct(current_mode), oct(new_mode))) + log.log(log.INFO, "Changed file mode of %s from %s to %s" % (file, oct(current_mode), oct(new_mode))) class InstallLocalPackagesForInstallation(install): @@ -98,17 +96,11 @@ def main(): description="""Bluetooth Cert Tests Package""", # Include root package so that bluetooth_packets_python3.so can be # included as well - packages=[''] + find_packages(exclude=[ - 'acts_framework', 'acts_framework.*', 'llvm_binutils', - 'llvm_binutils.*' - ]), + packages=[''] + + find_packages(exclude=['acts_framework', 'acts_framework.*', 'llvm_binutils', 'llvm_binutils.*']), install_requires=install_requires, package_data={ - '': - host_executables + [ - '*.so', 'lib64/*.so', 'target/*', 'llvm_binutils/bin/*', - 'llvm_binutils/lib64/*' - ], + '': host_executables + ['*.so', 'lib64/*.so', 'target/*', 'llvm_binutils/bin/*', 'llvm_binutils/lib64/*'], 'cert': ['all_test_cases'], }, cmdclass={ diff --git a/system/test/gen_coverage.py b/system/test/gen_coverage.py index f2658dcb6f..0ca3b733d6 100755 --- a/system/test/gen_coverage.py +++ b/system/test/gen_coverage.py @@ -70,8 +70,7 @@ COVERAGE_TESTS = [ ], }, { - "test_name": - "test-vendor_test_host", + "test_name": "test-vendor_test_host", "covered_files": [ "packages/modules/Bluetooth/system/vendor_libs/test_vendor_lib/include", "packages/modules/Bluetooth/system/vendor_libs/test_vendor_lib/src", @@ -154,9 +153,8 @@ def write_root_html_rows(f, tests): json_results = generate_coverage_json(test) test_totals = json_results['data'][0]['totals'] - f.write("<tr class='light-row'><td><pre><a href=\'" + - os.path.join(test_name, "index.html") + "\'>" + test_name + - "</a></pre></td>") + f.write("<tr class='light-row'><td><pre><a href=\'" + os.path.join(test_name, "index.html") + "\'>" + + test_name + "</a></pre></td>") for field_name in ['functions', 'instantiations', 'lines', 'regions']: field = test_totals[field_name] totals[field_name]['covered'] += field['covered'] @@ -180,8 +178,7 @@ def write_root_html_tail(f): def generate_root_html(tests): # Copy the css file from one of the coverage reports. - source_file = os.path.join( - os.path.join(WORKING_DIR, tests[0]['test_name']), "style.css") + source_file = os.path.join(os.path.join(WORKING_DIR, tests[0]['test_name']), "style.css") dest_file = os.path.join(WORKING_DIR, "style.css") shutil.copy2(source_file, dest_file) @@ -196,28 +193,23 @@ def get_profraw_for_test(test_name): test_root = get_native_test_root_or_die() test_cmd = os.path.join(os.path.join(test_root, test_name), test_name) if not os.path.isfile(test_cmd): - logging.error('The test ' + test_name + - ' does not exist, please compile first') + logging.error('The test ' + test_name + ' does not exist, please compile first') sys.exit(1) profraw_file_name = test_name + ".profraw" - profraw_path = os.path.join(WORKING_DIR, - os.path.join(test_name, profraw_file_name)) + profraw_path = os.path.join(WORKING_DIR, os.path.join(test_name, profraw_file_name)) llvm_env_var = "LLVM_PROFILE_FILE=\"" + profraw_path + "\"" test_cmd = llvm_env_var + " " + test_cmd logging.info('Generating profraw data for ' + test_name) logging.debug('cmd: ' + test_cmd) if subprocess.call(test_cmd, shell=True) != 0: - logging.error( - 'Test ' + test_name + - ' failed. Please fix the test before generating coverage.') + logging.error('Test ' + test_name + ' failed. Please fix the test before generating coverage.') sys.exit(1) if not os.path.isfile(profraw_path): logging.error( - 'Generating the profraw file failed. Did you remember to add the proper compiler flags to your build?' - ) + 'Generating the profraw file failed. Did you remember to add the proper compiler flags to your build?') sys.exit(1) return profraw_file_name @@ -249,16 +241,14 @@ def generate_coverage_html(test): test_profdata_file = os.path.join(test_working_dir, test_name + ".profdata") cmd = [ - os.path.join(get_android_root_or_die(), LLVM_COV), "show", - "-format=html", "-summary-only", "-show-line-counts-or-regions", - "-show-instantiation-summary", "-instr-profile=" + test_profdata_file, - "-path-equivalence=\"" + COVERAGE_ROOT + "\",\"" + - get_android_root_or_die() + "\"", "-output-dir=" + test_working_dir + os.path.join(get_android_root_or_die(), LLVM_COV), "show", "-format=html", "-summary-only", + "-show-line-counts-or-regions", "-show-instantiation-summary", "-instr-profile=" + test_profdata_file, + "-path-equivalence=\"" + COVERAGE_ROOT + "\",\"" + get_android_root_or_die() + "\"", + "-output-dir=" + test_working_dir ] # We have to have one object file not as an argument otherwise we can't specify source files. - test_cmd = os.path.join( - os.path.join(get_native_test_root_or_die(), test_name), test_name) + test_cmd = os.path.join(os.path.join(get_native_test_root_or_die(), test_name), test_name) cmd.append(test_cmd) # Filter out the specific files we want coverage for @@ -286,12 +276,10 @@ def generate_coverage_json(test): "-summary-only", "-show-region-summary", "-instr-profile=" + test_profdata_file, - "-path-equivalence=\"" + COVERAGE_ROOT + "\",\"" + - get_android_root_or_die() + "\"", + "-path-equivalence=\"" + COVERAGE_ROOT + "\",\"" + get_android_root_or_die() + "\"", ] - test_cmd = os.path.join( - os.path.join(get_native_test_root_or_die(), test_name), test_name) + test_cmd = os.path.join(os.path.join(get_native_test_root_or_die(), test_name), test_name) cmd.append(test_cmd) # Filter out the specific files we want coverage for @@ -325,8 +313,7 @@ def list_tests(): def main(): - parser = argparse.ArgumentParser( - description='Generate code coverage for enabled tests.') + parser = argparse.ArgumentParser(description='Generate code coverage for enabled tests.') parser.add_argument( '-l', '--list-tests', @@ -368,22 +355,11 @@ def main(): action='store_true', help='Write out summary results to json file in test directory.') - logging.basicConfig( - stream=sys.stderr, - level=logging.DEBUG, - format='%(levelname)s %(message)s') - logging.addLevelName( - logging.DEBUG, - "[\033[1;34m%s\033[0m]" % logging.getLevelName(logging.DEBUG)) - logging.addLevelName( - logging.INFO, - "[\033[1;34m%s\033[0m]" % logging.getLevelName(logging.INFO)) - logging.addLevelName( - logging.WARNING, - "[\033[1;31m%s\033[0m]" % logging.getLevelName(logging.WARNING)) - logging.addLevelName( - logging.ERROR, - "[\033[1;31m%s\033[0m]" % logging.getLevelName(logging.ERROR)) + logging.basicConfig(stream=sys.stderr, level=logging.DEBUG, format='%(levelname)s %(message)s') + logging.addLevelName(logging.DEBUG, "[\033[1;34m%s\033[0m]" % logging.getLevelName(logging.DEBUG)) + logging.addLevelName(logging.INFO, "[\033[1;34m%s\033[0m]" % logging.getLevelName(logging.INFO)) + logging.addLevelName(logging.WARNING, "[\033[1;31m%s\033[0m]" % logging.getLevelName(logging.WARNING)) + logging.addLevelName(logging.ERROR, "[\033[1;31m%s\033[0m]" % logging.getLevelName(logging.ERROR)) args = parser.parse_args() logging.debug("Args: " + str(args)) @@ -413,8 +389,7 @@ def main(): # Error if a test was specified but doesn't exist. if len(args.tests) != 0: for test_name in args.tests: - logging.error('\"' + test_name + - '\" was not found in the list of available tests.') + logging.error('\"' + test_name + '\" was not found in the list of available tests.') sys.exit(1) # Generate the info for the tests diff --git a/system/test/run_host_unit_tests.py b/system/test/run_host_unit_tests.py index 4b9e4bf457..bd7c1e33bd 100755 --- a/system/test/run_host_unit_tests.py +++ b/system/test/run_host_unit_tests.py @@ -52,8 +52,7 @@ def get_output_from_command(cmd): try: return subprocess.check_output(cmd).strip() except subprocess.CalledProcessError as e: - print 'Failed to call {cmd}, return code {code}'.format( - cmd=cmd, code=e.returncode) + print 'Failed to call {cmd}, return code {code}'.format(cmd=cmd, code=e.returncode) print e return None @@ -68,8 +67,7 @@ def get_android_root_or_die(): if os.path.isfile(soong_ui_bash_path): # Use value returned from Soong UI instead in case definition to TOP # changes in the future - value = get_output_from_command( - (soong_ui_bash_path, '--dumpvar-mode', '--abs', 'TOP')) + value = get_output_from_command((soong_ui_bash_path, '--dumpvar-mode', '--abs', 'TOP')) break parent_path = os.path.abspath(os.path.join(current_path, os.pardir)) if parent_path == current_path: @@ -87,9 +85,8 @@ def get_android_host_out_or_die(): value = os.environ.get('ANDROID_HOST_OUT') if not value: ANDROID_BUILD_TOP = get_android_root_or_die() - value = get_output_from_command( - (os.path.join(ANDROID_BUILD_TOP, SOONG_UI_BASH), '--dumpvar-mode', - '--abs', 'HOST_OUT')) + value = get_output_from_command((os.path.join(ANDROID_BUILD_TOP, SOONG_UI_BASH), '--dumpvar-mode', '--abs', + 'HOST_OUT')) if not value: print 'Cannot determine ANDROID_HOST_OUT' sys.exit(1) @@ -132,8 +129,7 @@ def get_test_cmd_or_die(test_root, test_name, enable_xml, test_filter): cmd = [test_path] if enable_xml: dist_dir = get_android_dist_dir_or_die() - log_output_path = os.path.join( - dist_dir, 'gtest/{0}_test_details.xml'.format(test_name)) + log_output_path = os.path.join(dist_dir, 'gtest/{0}_test_details.xml'.format(test_name)) cmd.append('--gtest_output=xml:{0}'.format(log_output_path)) if test_filter: cmd.append('--gtest_filter=%s' % test_filter) @@ -147,8 +143,7 @@ def build_target(target, num_tasks): if num_tasks > 1: build_cmd.append('-j' + str(num_tasks)) build_cmd.append(target) - p = subprocess.Popen( - build_cmd, cwd=ANDROID_BUILD_TOP, env=os.environ.copy()) + p = subprocess.Popen(build_cmd, cwd=ANDROID_BUILD_TOP, env=os.environ.copy()) return_code = p.wait() if return_code != 0: print 'BUILD FAILED, return code: {0}'.format(str(return_code)) @@ -167,9 +162,7 @@ def main(): nargs='?', const=True, default=False, - help= - 'Whether to output structured XML log output in out/dist/gtest directory' - ) + help='Whether to output structured XML log output in out/dist/gtest directory') parser.add_argument( '-j', type=int, @@ -179,17 +172,14 @@ def main(): default=-1, help='Number of tasks to run at the same time') parser.add_argument( - 'rest', - nargs=argparse.REMAINDER, - help='-- args, other gtest arguments for each individual test') + 'rest', nargs=argparse.REMAINDER, help='-- args, other gtest arguments for each individual test') args = parser.parse_args() build_target('MODULES-IN-system-bt', args.num_tasks) TEST_ROOT = get_native_test_root_or_die() test_results = [] for test in HOST_TESTS: - test_cmd = get_test_cmd_or_die(TEST_ROOT, test, args.enable_xml, - args.rest) + test_cmd = get_test_cmd_or_die(TEST_ROOT, test, args.enable_xml, args.rest) if subprocess.call(test_cmd) != 0: test_results.append(False) else: diff --git a/system/tools/scripts/btsnoop_live.py b/system/tools/scripts/btsnoop_live.py index 00b45fdda1..a04dc19e96 100644 --- a/system/tools/scripts/btsnoop_live.py +++ b/system/tools/scripts/btsnoop_live.py @@ -94,8 +94,7 @@ def get_file_time(): Obtain current time in file time format for display """ date_time = datetime.now() - file_time = FILETIME_EPOCH_DELTA + ( - timegm(date_time.timetuple()) * HUNDREDS_OF_NANOSECONDS) + file_time = FILETIME_EPOCH_DELTA + (timegm(date_time.timetuple()) * HUNDREDS_OF_NANOSECONDS) file_time = file_time + (date_time.microsecond * 10) return file_time @@ -189,8 +188,7 @@ def init_live_import(conn_str, config_str): print(dllName + " loaded successfully") result = live_import.InitializeLiveImport( - conn_str.encode('ascii', 'ignore'), config_str.encode( - 'ascii', 'ignore'), byref(success)) + conn_str.encode('ascii', 'ignore'), config_str.encode('ascii', 'ignore'), byref(success)) if (result < 0): print("Live Import Init failed") return None @@ -261,8 +259,7 @@ def main(): if data_frag is not None: snoop_data += data_frag - print("Bytes received %d Olen %d ilen %d flags %d" % - (len(snoop_data), olen, ilen, flags)) + print("Bytes received %d Olen %d ilen %d flags %d" % (len(snoop_data), olen, ilen, flags)) packet_type = struct.unpack(">B", snoop_data[0:1])[0] if packet_type == 1: drf = 1 @@ -283,9 +280,7 @@ def main(): drf = 8 isend = 1 - result = live_import.SendFrame(olen - 1, olen - 1, - snoop_data[1:olen], drf, isend, - timestamp) + result = live_import.SendFrame(olen - 1, olen - 1, snoop_data[1:olen], drf, isend, timestamp) if (result < 0): print("Send frame failed") except KeyboardInterrupt: diff --git a/system/tools/scripts/btsnooz.py b/system/tools/scripts/btsnooz.py index a29e718d7b..5f68f01ddb 100755 --- a/system/tools/scripts/btsnooz.py +++ b/system/tools/scripts/btsnooz.py @@ -93,23 +93,19 @@ def decode_snooz_v1(decompressed, last_timestamp_ms): first_timestamp_ms = last_timestamp_ms + 0x00dcddb30f2f8000 offset = 0 while offset < len(decompressed): - length, delta_time_ms, type = struct.unpack_from( - '=HIb', decompressed, offset) + length, delta_time_ms, type = struct.unpack_from('=HIb', decompressed, offset) offset += 7 + length - 1 first_timestamp_ms -= delta_time_ms # Second pass does the actual writing out to stdout. offset = 0 while offset < len(decompressed): - length, delta_time_ms, type = struct.unpack_from( - '=HIb', decompressed, offset) + length, delta_time_ms, type = struct.unpack_from('=HIb', decompressed, offset) first_timestamp_ms += delta_time_ms offset += 7 sys.stdout.write(struct.pack('>II', length, length)) sys.stdout.write(struct.pack('>II', type_to_direction(type), 0)) - sys.stdout.write( - struct.pack('>II', (first_timestamp_ms >> 32), - (first_timestamp_ms & 0xFFFFFFFF))) + sys.stdout.write(struct.pack('>II', (first_timestamp_ms >> 32), (first_timestamp_ms & 0xFFFFFFFF))) sys.stdout.write(type_to_hci(type)) sys.stdout.write(decompressed[offset:offset + length - 1]) offset += length - 1 @@ -124,23 +120,19 @@ def decode_snooz_v2(decompressed, last_timestamp_ms): first_timestamp_ms = last_timestamp_ms + 0x00dcddb30f2f8000 offset = 0 while offset < len(decompressed): - length, packet_length, delta_time_ms, snooz_type = struct.unpack_from( - '=HHIb', decompressed, offset) + length, packet_length, delta_time_ms, snooz_type = struct.unpack_from('=HHIb', decompressed, offset) offset += 9 + length - 1 first_timestamp_ms -= delta_time_ms # Second pass does the actual writing out to stdout. offset = 0 while offset < len(decompressed): - length, packet_length, delta_time_ms, snooz_type = struct.unpack_from( - '=HHIb', decompressed, offset) + length, packet_length, delta_time_ms, snooz_type = struct.unpack_from('=HHIb', decompressed, offset) first_timestamp_ms += delta_time_ms offset += 9 sys.stdout.write(struct.pack('>II', packet_length, length)) sys.stdout.write(struct.pack('>II', type_to_direction(snooz_type), 0)) - sys.stdout.write( - struct.pack('>II', (first_timestamp_ms >> 32), - (first_timestamp_ms & 0xFFFFFFFF))) + sys.stdout.write(struct.pack('>II', (first_timestamp_ms >> 32), (first_timestamp_ms & 0xFFFFFFFF))) sys.stdout.write(type_to_hci(snooz_type)) sys.stdout.write(decompressed[offset:offset + length - 1]) offset += length - 1 diff --git a/system/tools/scripts/dump_hearingaid_audio.py b/system/tools/scripts/dump_hearingaid_audio.py index 81cd78d98e..fd3f064e2f 100755 --- a/system/tools/scripts/dump_hearingaid_audio.py +++ b/system/tools/scripts/dump_hearingaid_audio.py @@ -54,14 +54,11 @@ DEBUG_DATA = "DEBUG_DATA" AUDIO_DATA_B = "AUDIO_DATA_B" # Debug packet header struct -header_list_str = [ - "Event Processed", "Number Packet Nacked By Slave", - "Number Packet Nacked By Master" -] +header_list_str = ["Event Processed", "Number Packet Nacked By Slave", "Number Packet Nacked By Master"] # Debug frame information structs data_list_str = [ - "Event Number", "Overrun", "Underrun", "Skips", "Rendered Audio Frame", - "First PDU Option", "Second PDU Option", "Third PDU Option" + "Event Number", "Overrun", "Underrun", "Skips", "Rendered Audio Frame", "First PDU Option", "Second PDU Option", + "Third PDU Option" ] AUDIO_CONTROL_POINT_UUID = "f0d4de7e4a88476c9d9f1937b0996cc0" @@ -90,14 +87,12 @@ def parse_acl_ha_debug_buffer(data, result): return version, data = unpack_data(data, 1) - update_audio_data(CONNECTION_HANDLE, result[CONNECTION_HANDLE], - DEBUG_VERSION, str(version)) + update_audio_data(CONNECTION_HANDLE, result[CONNECTION_HANDLE], DEBUG_VERSION, str(version)) debug_str = result[TIMESTAMP_TIME_FORMAT] for p in range(3): byte_data, data = unpack_data(data, 1) - debug_str = debug_str + ", " + header_list_str[p] + "=" + str( - byte_data).rjust(3) + debug_str = debug_str + ", " + header_list_str[p] + "=" + str(byte_data).rjust(3) if full_debug: debug_str = debug_str + "\n" + "|".join(data_list_str) + "\n" @@ -110,22 +105,15 @@ def parse_acl_ha_debug_buffer(data, result): p = base + counter byte_data, data = unpack_data(data, 1) if p == 1: - data_list_content.append( - str(byte_data & 0x03).rjust(len(data_list_str[p]))) - data_list_content.append( - str((byte_data >> 2) & 0x03).rjust( - len(data_list_str[p + 1]))) - data_list_content.append( - str((byte_data >> 4) & 0x0f).rjust( - len(data_list_str[p + 2]))) + data_list_content.append(str(byte_data & 0x03).rjust(len(data_list_str[p]))) + data_list_content.append(str((byte_data >> 2) & 0x03).rjust(len(data_list_str[p + 1]))) + data_list_content.append(str((byte_data >> 4) & 0x0f).rjust(len(data_list_str[p + 2]))) base = 2 else: - data_list_content.append( - str(byte_data).rjust(len(data_list_str[p]))) + data_list_content.append(str(byte_data).rjust(len(data_list_str[p]))) debug_str = debug_str + "|".join(data_list_content) + "\n" - update_audio_data(CONNECTION_HANDLE, result[CONNECTION_HANDLE], DEBUG_DATA, - debug_str) + update_audio_data(CONNECTION_HANDLE, result[CONNECTION_HANDLE], DEBUG_DATA, debug_str) def parse_acl_ha_audio_data(data, result): @@ -134,8 +122,7 @@ def parse_acl_ha_audio_data(data, result): return # Remove audio packet number audio_data_b = data[1:] - update_audio_data(CONNECTION_HANDLE, result[CONNECTION_HANDLE], - AUDIO_DATA_B, audio_data_b) + update_audio_data(CONNECTION_HANDLE, result[CONNECTION_HANDLE], AUDIO_DATA_B, audio_data_b) def parse_acl_ha_audio_type(data, result): @@ -151,8 +138,7 @@ def parse_acl_ha_audio_type(data, result): audio_type = "Media" else: audio_type = "Unknown" - update_audio_data(CONNECTION_HANDLE, result[CONNECTION_HANDLE], AUDIO_TYPE, - audio_type) + update_audio_data(CONNECTION_HANDLE, result[CONNECTION_HANDLE], AUDIO_TYPE, audio_type) def parse_acl_ha_codec(data, result): @@ -167,10 +153,8 @@ def parse_acl_ha_codec(data, result): else: codec = "Unknown" sample_rate = "Unknown" - update_audio_data(CONNECTION_HANDLE, result[CONNECTION_HANDLE], CODEC, - codec) - update_audio_data(CONNECTION_HANDLE, result[CONNECTION_HANDLE], SAMPLE_RATE, - sample_rate) + update_audio_data(CONNECTION_HANDLE, result[CONNECTION_HANDLE], CODEC, codec) + update_audio_data(CONNECTION_HANDLE, result[CONNECTION_HANDLE], SAMPLE_RATE, sample_rate) parse_acl_ha_audio_type(data, result) @@ -178,14 +162,12 @@ def parse_acl_ha_audio_control_cmd(data, result): """This function parses HA audio control cmd is start/stop.""" control_cmd, data = unpack_data(data, 1) if control_cmd == 0x01: - update_audio_data(CONNECTION_HANDLE, result[CONNECTION_HANDLE], START, - True) - update_audio_data(CONNECTION_HANDLE, result[CONNECTION_HANDLE], - TIMESTAMP_STR_FORMAT, result[TIMESTAMP_STR_FORMAT]) + update_audio_data(CONNECTION_HANDLE, result[CONNECTION_HANDLE], START, True) + update_audio_data(CONNECTION_HANDLE, result[CONNECTION_HANDLE], TIMESTAMP_STR_FORMAT, + result[TIMESTAMP_STR_FORMAT]) parse_acl_ha_codec(data, result) elif control_cmd == 0x02: - update_audio_data(CONNECTION_HANDLE, result[CONNECTION_HANDLE], START, - False) + update_audio_data(CONNECTION_HANDLE, result[CONNECTION_HANDLE], START, False) #----------------------------------------------------------------------- @@ -209,8 +191,7 @@ def parse_acl_att_long_uuid(data, result): long_uuid = "".join(long_uuid_list) # Check long_uuid is AUDIO_CONTROL_POINT uuid to get the attr_handle. if long_uuid == AUDIO_CONTROL_POINT_UUID: - update_audio_data(CONNECTION_HANDLE, result[CONNECTION_HANDLE], - AUDIO_CONTROL_ATTR_HANDLE, attr_handle) + update_audio_data(CONNECTION_HANDLE, result[CONNECTION_HANDLE], AUDIO_CONTROL_ATTR_HANDLE, attr_handle) def parse_acl_opcode(data, result): @@ -276,8 +257,7 @@ def parse_hci_evt_peer_address(data, result): if len(data) < 6: return for p in range(0, 6): - peer_address_list.append("{0:02x}".format( - struct.unpack(">B", data[p])[0])) + peer_address_list.append("{0:02x}".format(struct.unpack(">B", data[p])[0])) # Check the address is empty or not. if peer_address_list == address_empty_list: del peer_address_list[:] @@ -287,8 +267,7 @@ def parse_hci_evt_peer_address(data, result): peer_address_list.reverse() peer_address = "_".join(peer_address_list) update_audio_data("", "", PEER_ADDRESS, peer_address) - update_audio_data(PEER_ADDRESS, peer_address, CONNECTION_HANDLE, - result[CONNECTION_HANDLE]) + update_audio_data(PEER_ADDRESS, peer_address, CONNECTION_HANDLE, result[CONNECTION_HANDLE]) def parse_hci_evt_code(data, result): @@ -350,8 +329,7 @@ def parse_packet(btsnoop_file): return False if packet_flag != 2 and drop == 0: packet_result[IS_SENT] = (packet_flag == 0) - packet_result[TIMESTAMP_STR_FORMAT], packet_result[ - TIMESTAMP_TIME_FORMAT] = convert_time_str(timestamp) + packet_result[TIMESTAMP_STR_FORMAT], packet_result[TIMESTAMP_TIME_FORMAT] = convert_time_str(timestamp) parse_packet_data(packet_data, packet_result) else: return False @@ -375,12 +353,10 @@ def dump_audio_data(data): if folder is not None: if not os.path.exists(folder): os.makedirs(folder) - audio_file_name = os.path.join(folder, - "-".join(file_name_list) + file_type) + audio_file_name = os.path.join(folder, "-".join(file_name_list) + file_type) if data.has_key(DEBUG_VERSION): file_prefix = "debug_ver_" + data[DEBUG_VERSION] + "-" - debug_file_name = os.path.join( - folder, file_prefix + "-".join(file_name_list) + ".txt") + debug_file_name = os.path.join(folder, file_prefix + "-".join(file_name_list) + ".txt") else: audio_file_name = "-".join(file_name_list) + file_type if data.has_key(DEBUG_VERSION): @@ -391,23 +367,19 @@ def dump_audio_data(data): if data.has_key(AUDIO_DATA_B): with open(audio_file_name, "wb+") as audio_file: audio_file.write(data[AUDIO_DATA_B]) - sys.stdout.write( - "Finished to dump Audio File: %s\n\n" % audio_file_name) + sys.stdout.write("Finished to dump Audio File: %s\n\n" % audio_file_name) else: sys.stdout.write("Fail to dump Audio File: %s\n" % audio_file_name) sys.stdout.write("There isn't any Hearing Aid audio data.\n\n") if simple_debug: - sys.stdout.write( - "Start to dump audio %s Debug File\n" % audio_file_name) + sys.stdout.write("Start to dump audio %s Debug File\n" % audio_file_name) if data.has_key(DEBUG_DATA): with open(debug_file_name, "wb+") as debug_file: debug_file.write(data[DEBUG_DATA]) - sys.stdout.write( - "Finished to dump Debug File: %s\n\n" % debug_file_name) + sys.stdout.write("Finished to dump Debug File: %s\n\n" % debug_file_name) else: - sys.stdout.write( - "Fail to dump audio %s Debug File\n" % audio_file_name) + sys.stdout.write("Fail to dump audio %s Debug File\n" % audio_file_name) sys.stdout.write("There isn't any Hearing Aid debug data.\n\n") @@ -534,11 +506,9 @@ def convert_time_str(timestamp): def set_config(): """This function is for set config by flag and check the argv is correct.""" - argv_parser = argparse.ArgumentParser( - description="Extracts Hearing Aid audio data from BTSNOOP.") + argv_parser = argparse.ArgumentParser(description="Extracts Hearing Aid audio data from BTSNOOP.") argv_parser.add_argument("BTSNOOP", help="BLUETOOTH BTSNOOP file.") - argv_parser.add_argument( - "-f", "--folder", help="select output folder.", dest="folder") + argv_parser.add_argument("-f", "--folder", help="select output folder.", dest="folder") argv_parser.add_argument( "-c1", "--connection-handle1", @@ -574,17 +544,9 @@ def set_config(): dest="audio_control_attr_handle", type=int) argv_parser.add_argument( - "-d", - "--debug", - help="dump full debug buffer content.", - dest="full_debug", - default="False") + "-d", "--debug", help="dump full debug buffer content.", dest="full_debug", default="False") argv_parser.add_argument( - "-sd", - "--simple-debug", - help="dump debug buffer header content.", - dest="simple_debug", - default="False") + "-sd", "--simple-debug", help="dump debug buffer header content.", dest="simple_debug", default="False") arg = argv_parser.parse_args() if arg.folder is not None: @@ -598,19 +560,16 @@ def set_config(): exit(1) if not (arg.no_start.lower() == "true" or arg.no_start.lower() == "false"): - argv_parser.error( - "-ns/--no-start arg is invalid, it should be true/false.") + argv_parser.error("-ns/--no-start arg is invalid, it should be true/false.") exit(1) if arg.connection_handle1 is not None: fake_name = "ConnectionHandle" + str(arg.connection_handle1) update_audio_data("", "", PEER_ADDRESS, fake_name) - update_audio_data(PEER_ADDRESS, fake_name, CONNECTION_HANDLE, - arg.connection_handle1) + update_audio_data(PEER_ADDRESS, fake_name, CONNECTION_HANDLE, arg.connection_handle1) if arg.no_start.lower() == "true": update_audio_data(PEER_ADDRESS, fake_name, START, True) - update_audio_data(PEER_ADDRESS, fake_name, TIMESTAMP_STR_FORMAT, - "Unknown") + update_audio_data(PEER_ADDRESS, fake_name, TIMESTAMP_STR_FORMAT, "Unknown") update_audio_data(PEER_ADDRESS, fake_name, CODEC, arg.codec) update_audio_data(PEER_ADDRESS, fake_name, SAMPLE_RATE, "Unknown") update_audio_data(PEER_ADDRESS, fake_name, AUDIO_TYPE, "Unknown") @@ -618,12 +577,10 @@ def set_config(): if arg.connection_handle2 is not None: fake_name = "ConnectionHandle" + str(arg.connection_handle2) update_audio_data("", "", PEER_ADDRESS, fake_name) - update_audio_data(PEER_ADDRESS, fake_name, CONNECTION_HANDLE, - arg.connection_handle2) + update_audio_data(PEER_ADDRESS, fake_name, CONNECTION_HANDLE, arg.connection_handle2) if arg.no_start.lower() == "true": update_audio_data(PEER_ADDRESS, fake_name, START, True) - update_audio_data(PEER_ADDRESS, fake_name, TIMESTAMP_STR_FORMAT, - "Unknown") + update_audio_data(PEER_ADDRESS, fake_name, TIMESTAMP_STR_FORMAT, "Unknown") update_audio_data(PEER_ADDRESS, fake_name, CODEC, arg.codec) update_audio_data(PEER_ADDRESS, fake_name, SAMPLE_RATE, "Unknown") update_audio_data(PEER_ADDRESS, fake_name, AUDIO_TYPE, "Unknown") @@ -653,14 +610,12 @@ def main(): with open(btsnoop_file_name, "rb") as btsnoop_file: identification = btsnoop_file.read(8) if identification != "btsnoop\0": - sys.stderr.write( - "Check identification fail. It is not correct btsnoop file.") + sys.stderr.write("Check identification fail. It is not correct btsnoop file.") exit(1) ver, data_link = struct.unpack(">II", btsnoop_file.read(4 + 4)) if (ver != 1) or (data_link != 1002): - sys.stderr.write( - "Check ver or dataLink fail. It is not correct btsnoop file.") + sys.stderr.write("Check ver or dataLink fail. It is not correct btsnoop file.") exit(1) while True: diff --git a/system/tools/scripts/dump_metrics_ascii.py b/system/tools/scripts/dump_metrics_ascii.py index 20d413285b..0adb278322 100755 --- a/system/tools/scripts/dump_metrics_ascii.py +++ b/system/tools/scripts/dump_metrics_ascii.py @@ -33,10 +33,8 @@ def compile_proto(proto_path, output_dir): if not protoc: protoc = find_executable('protoc') if not protoc: - logging.error( - "Cannot find Protobuf compiler (>=3.0.0), please install" - "protobuf-compiler package. Prefer copying from <top>/prebuilts/tools" - ) + logging.error("Cannot find Protobuf compiler (>=3.0.0), please install" + "protobuf-compiler package. Prefer copying from <top>/prebuilts/tools") logging.error(" prebuilts/tools/linux-x86_64/protoc/bin/protoc") logging.error("If prebuilts are not available, use apt-get:") logging.error(" sudo apt-get install protobuf-compiler") @@ -54,11 +52,7 @@ def compile_proto(proto_path, output_dir): input_dir = os.path.dirname(proto_path) output_filename = os.path.basename(proto_path).replace('.proto', '_pb2.py') output_path = os.path.join(output_dir, output_filename) - protoc_command = [ - protoc, - '-I=%s' % (input_dir), - '--python_out=%s' % (output_dir), proto_path - ] + protoc_command = [protoc, '-I=%s' % (input_dir), '--python_out=%s' % (output_dir), proto_path] if subprocess.call(protoc_command, stderr=subprocess.STDOUT) != 0: logging.error("Fail to compile proto") return None @@ -82,8 +76,7 @@ def compile_import_proto(output_dir, proto_path): try: output_module = import_module(output_module_name) except ImportError: - logging.error( - "Cannot import generated py-proto %s" % (output_module_name)) + logging.error("Cannot import generated py-proto %s" % (output_module_name)) return output_module @@ -130,8 +123,7 @@ def main(): logging.info("Usage: " + sys.argv[0] + " <path_to_metric_proto>") logging.info("Requires Protobuf compiler, protoc, version >=3.0.0") sys.exit(0) - bluetooth_proto_module = compile_import_proto(tempfile.gettempdir(), - sys.argv[1]) + bluetooth_proto_module = compile_import_proto(tempfile.gettempdir(), sys.argv[1]) if not bluetooth_proto_module: logging.error("Cannot compile " + sys.argv[1]) sys.exit(1) diff --git a/system/tools/scripts/yapf_checker.py b/system/tools/scripts/yapf_checker.py index f6dd2c9d25..62a753e7d7 100755 --- a/system/tools/scripts/yapf_checker.py +++ b/system/tools/scripts/yapf_checker.py @@ -23,9 +23,7 @@ PYTHONPATH_KEY = 'PYTHONPATH' COMMIT_ID_ENV_KEY = 'PREUPLOAD_COMMIT' ANDROID_BUILD_TOP_KEY = 'ANDROID_BUILD_TOP' DEFAULT_YAPF_DIR = 'external/yapf' -GIT_COMMAND = [ - 'git', 'diff-tree', '--no-commit-id', '--name-only', '--diff-filter=d' -] +GIT_COMMAND = ['git', 'diff-tree', '--no-commit-id', '--name-only', '--diff-filter=d'] def main(): @@ -47,8 +45,7 @@ def main(): # Gather changed Python files commit_id = os.environ[COMMIT_ID_ENV_KEY] full_git_command = GIT_COMMAND + ['-r', commit_id] - files = subprocess.check_output(full_git_command).decode( - 'utf-8').splitlines() + files = subprocess.check_output(full_git_command).decode('utf-8').splitlines() full_files = [os.path.abspath(f) for f in files if f.endswith('.py')] if not full_files: return @@ -58,32 +55,20 @@ def main(): yapf_binary = os.path.join(yapf_dir, 'yapf') # Run YAPF - full_yapf_command = [ - "%s=$%s:%s" % (PYTHONPATH_KEY, PYTHONPATH_KEY, yapf_dir), 'python3', - yapf_binary, '-d', '-p' - ] + full_files + full_yapf_command = ["%s=$%s:%s" % (PYTHONPATH_KEY, PYTHONPATH_KEY, yapf_dir), 'python3', yapf_binary, '-d', '-p' + ] + full_files environment = os.environ.copy() environment[PYTHONPATH_KEY] = environment[PYTHONPATH_KEY] + ":" + yapf_dir - result = subprocess.run( - full_yapf_command[1:], - env=environment, - stderr=subprocess.STDOUT, - stdout=subprocess.PIPE) + result = subprocess.run(full_yapf_command[1:], env=environment, stderr=subprocess.STDOUT, stdout=subprocess.PIPE) if result.returncode != 0 or result.stdout: logging.error(result.stdout.decode('utf-8').strip()) logging.error('INVALID FORMATTING, return code %d', result.returncode) - logging.error('To re-run the format command:\n\n' - ' %s\n' % ' '.join(full_yapf_command)) - yapf_inplace_format = ' '.join([ - "%s=$%s:%s" % (PYTHONPATH_KEY, PYTHONPATH_KEY, - yapf_dir), 'python3', yapf_binary, '-p', '-i' - ] + full_files) - logging.error('If this is a legitimate format error, please run:\n\n' - ' %s\n' % yapf_inplace_format) - logging.error( - 'CAVEAT: Currently, this format the entire Python file if you modify even part of it' - ) + logging.error('To re-run the format command:\n\n' ' %s\n' % ' '.join(full_yapf_command)) + yapf_inplace_format = ' '.join( + ["%s=$%s:%s" % (PYTHONPATH_KEY, PYTHONPATH_KEY, yapf_dir), 'python3', yapf_binary, '-p', '-i'] + full_files) + logging.error('If this is a legitimate format error, please run:\n\n' ' %s\n' % yapf_inplace_format) + logging.error('CAVEAT: Currently, this format the entire Python file if you modify even part of it') exit(1) diff --git a/system/vendor_libs/test_vendor_lib/scripts/hci_socket.py b/system/vendor_libs/test_vendor_lib/scripts/hci_socket.py index 6833eeb8f5..43be9f2309 100644 --- a/system/vendor_libs/test_vendor_lib/scripts/hci_socket.py +++ b/system/vendor_libs/test_vendor_lib/scripts/hci_socket.py @@ -200,15 +200,10 @@ class HCI_Event_Extended_Inquiry_Result(Packet): bind_layers(HCI_Event_Hdr, HCI_Event_Inquiry_Result, code=0x02) bind_layers(HCI_Event_Hdr, HCI_Event_Connection_Complete, code=0x03) bind_layers(HCI_Event_Hdr, HCI_Event_Remote_Name_Request_Complete, code=0x07) -bind_layers( - HCI_Event_Hdr, HCI_Event_Read_Remote_Supported_Features_Complete, code=0x0b) -bind_layers( - HCI_Event_Hdr, - HCI_Event_Read_Remote_Version_Information_Complete, - code=0x0c) +bind_layers(HCI_Event_Hdr, HCI_Event_Read_Remote_Supported_Features_Complete, code=0x0b) +bind_layers(HCI_Event_Hdr, HCI_Event_Read_Remote_Version_Information_Complete, code=0x0c) bind_layers(HCI_Event_Hdr, HCI_Event_Read_Clock_Offset_Complete, code=0x1c) -bind_layers( - HCI_Event_Hdr, HCI_Event_Read_Remote_Extended_Features_Complete, code=0x23) +bind_layers(HCI_Event_Hdr, HCI_Event_Read_Remote_Extended_Features_Complete, code=0x23) bind_layers(HCI_Event_Hdr, HCI_Event_Extended_Inquiry_Result, code=0x2f) """ END SCAPY stuff""" @@ -272,8 +267,7 @@ class HCISocket(SuperSocket): self.done_ = True print('Rx: type_byte ' + hex(type_byte[0])) # Read the Payload - payload = self.rx_bytes( - payload_length) if payload_length != 0 else b'' + payload = self.rx_bytes(payload_length) if payload_length != 0 else b'' packet_bytes = type_byte + header + payload packet = HCI_Hdr(packet_bytes) print('Rx: ' + packet.__repr__()) @@ -312,8 +306,7 @@ class HCIShell(cmd.Cmd): address = split_args[0] if len(split_args) > 0 else 'NULL' timeout = int(split_args[1]) if len(split_args) > 1 else 2 num_responses = 0 - connect = HCI_Hdr(type='Command') / HCI_Command_Hdr( - opcode=0x0405) / HCI_Cmd_Create_Connection(addr=address) + connect = HCI_Hdr(type='Command') / HCI_Command_Hdr(opcode=0x0405) / HCI_Cmd_Create_Connection(addr=address) self._hci.send(connect) status = None while status == None: @@ -333,16 +326,13 @@ class HCIShell(cmd.Cmd): connection_complete = self._hci.get_packet() if connection_complete == False: continue - if (connection_complete[HCI_Hdr].type == HCI_Hdr(type='Event').type - ) and (connection_complete[HCI_Event_Hdr].code == 0x3): - status = connection_complete[ - HCI_Event_Connection_Complete].status + if (connection_complete[HCI_Hdr].type == HCI_Hdr(type='Event').type) and ( + connection_complete[HCI_Event_Hdr].code == 0x3): + status = connection_complete[HCI_Event_Connection_Complete].status if status != 0: - print('Connection complete with failed status = ' + - str(status)) + print('Connection complete with failed status = ' + str(status)) return - handle = connection_complete[ - HCI_Event_Connection_Complete].handle + handle = connection_complete[HCI_Event_Connection_Complete].handle print('Connection established with handle ' + str(handle)) connection_complete.show() hexdump(connection_complete) @@ -352,31 +342,17 @@ class HCIShell(cmd.Cmd): l2cap_req = self._hci.get_packet() if l2cap_req == False: continue - if (l2cap_req[HCI_Hdr].type == HCI_Hdr(type='ACL Data').type) and ( - l2cap_req[L2CAP_Hdr].cid == L2CAP_Hdr(cid='control').cid - ) and (l2cap_req[L2CAP_CmdHdr].code == L2CAP_CmdHdr(code='info_req') - .code) and (l2cap_req[L2CAP_InfoReq].type == L2CAP_InfoReq( - type='FEAT_MASK').type): - print('Send Features packet' + HCI_Hdr( - type='ACL Data' - ) / HCI_ACL_Hdr( - handle=l2cap_req[HCI_ACL_Hdr].handle, PB=0, BC=2, len=16) / - L2CAP_Hdr(len=12, cid='control') / L2CAP_CmdHdr( - code='info_resp', id=146, len=8) / L2CAP_InfoResp( - type=l2cap_req[L2CAP_InfoResp].type, - result='success', - data=b'\xb8\x00\x00\x00').__repr__()) + if (l2cap_req[HCI_Hdr].type == HCI_Hdr(type='ACL Data').type) and (l2cap_req[L2CAP_Hdr].cid == L2CAP_Hdr( + cid='control').cid) and (l2cap_req[L2CAP_CmdHdr].code == L2CAP_CmdHdr(code='info_req').code) and ( + l2cap_req[L2CAP_InfoReq].type == L2CAP_InfoReq(type='FEAT_MASK').type): + print('Send Features packet' + + HCI_Hdr(type='ACL Data') / HCI_ACL_Hdr(handle=l2cap_req[HCI_ACL_Hdr].handle, PB=0, BC=2, len=16) / + L2CAP_Hdr(len=12, cid='control') / L2CAP_CmdHdr(code='info_resp', id=146, len=8) / L2CAP_InfoResp( + type=l2cap_req[L2CAP_InfoResp].type, result='success', data=b'\xb8\x00\x00\x00').__repr__()) self._hci.send( - HCI_Hdr(type='ACL Data') / HCI_ACL_Hdr( - handle=l2cap_req[HCI_ACL_Hdr].handle, - PB=0, - BC=2, - len=16) / - L2CAP_Hdr(len=12, cid='control') / L2CAP_CmdHdr( - code='info_resp', id=146, len=8) / L2CAP_InfoResp( - type=l2cap_req[L2CAP_InfoResp].type, - result='success', - data=b'\xb8\x00\x00\x00')) + HCI_Hdr(type='ACL Data') / HCI_ACL_Hdr(handle=l2cap_req[HCI_ACL_Hdr].handle, PB=0, BC=2, len=16) / + L2CAP_Hdr(len=12, cid='control') / L2CAP_CmdHdr(code='info_resp', id=146, len=8) / L2CAP_InfoResp( + type=l2cap_req[L2CAP_InfoResp].type, result='success', data=b'\xb8\x00\x00\x00')) def do_le_scan(self, args): """Arguments: enable (0 or 1), filter duplicates (0 or 1) Print the scan responses from reachable devices @@ -385,9 +361,8 @@ class HCIShell(cmd.Cmd): split_args = args.split() enable = int(split_args[0]) if len(split_args) > 0 else 1 filter_dups = int(split_args[1]) if len(split_args) > 1 else 1 - set_scan_enable = HCI_Hdr(type=1) / HCI_Command_Hdr( - opcode=0x200c) / HCI_Cmd_LE_Set_Scan_Enable( - enable=enable, filter_dups=filter_dups) + set_scan_enable = HCI_Hdr(type=1) / HCI_Command_Hdr(opcode=0x200c) / HCI_Cmd_LE_Set_Scan_Enable( + enable=enable, filter_dups=filter_dups) print('Tx: ' + set_scan_enable.__repr__()) self._hci.send(set_scan_enable) @@ -399,9 +374,8 @@ class HCIShell(cmd.Cmd): scan_time = int(split_args[0]) if len(split_args) > 0 else 0 max_responses = int(split_args[1]) if len(split_args) > 1 else 0 num_responses = 0 - inquiry = HCI_Hdr(type='Command') / HCI_Command_Hdr( - opcode=0x0401) / HCI_Cmd_Inquiry( - length=scan_time, max_responses=max_responses) + inquiry = HCI_Hdr(type='Command') / HCI_Command_Hdr(opcode=0x0401) / HCI_Cmd_Inquiry( + length=scan_time, max_responses=max_responses) print('Tx: ' + inquiry.__repr__()) self._hci.send(inquiry) @@ -441,8 +415,7 @@ def main(argv): else: hci_shell = HCIShell(hci) hci_shell.prompt = '$ ' - hci_shell.cmdloop('Welcome to the RootCanal HCI Console \n' + - 'Type \'help\' for more information.') + hci_shell.cmdloop('Welcome to the RootCanal HCI Console \n' + 'Type \'help\' for more information.') if __name__ == '__main__': diff --git a/system/vendor_libs/test_vendor_lib/scripts/link_layer_socket.py b/system/vendor_libs/test_vendor_lib/scripts/link_layer_socket.py index e9779cb6db..d1268e9288 100644 --- a/system/vendor_libs/test_vendor_lib/scripts/link_layer_socket.py +++ b/system/vendor_libs/test_vendor_lib/scripts/link_layer_socket.py @@ -92,8 +92,7 @@ class LinkLayerSocket(object): while not self.done_: raw_bytes = b'' while len(raw_bytes) < size and not self.done_: - more_raw_bytes = self._socket.recv( - min(size - len(raw_bytes), 2048)) + more_raw_bytes = self._socket.recv(min(size - len(raw_bytes), 2048)) if more_raw_bytes: raw_bytes += more_raw_bytes return raw_bytes @@ -110,15 +109,12 @@ class LinkLayerSocket(object): payload_length |= header[2] << 16 payload_length |= header[3] << 24 print('Rx: type_byte ' + hex(header[4])) - print('Rx: from ' + hex(header[5]) + ':' + hex(header[6]) + ':' + - hex(header[7]) + ':' + hex(header[8]) + ':' + hex(header[9]) + - ':' + hex(header[10])) - print('Rx: to ' + hex(header[11]) + ':' + hex(header[12]) + ':' + - hex(header[13]) + ':' + hex(header[14]) + ':' + - hex(header[15]) + ':' + hex(header[16])) + print('Rx: from ' + hex(header[5]) + ':' + hex(header[6]) + ':' + hex(header[7]) + ':' + hex(header[8]) + + ':' + hex(header[9]) + ':' + hex(header[10])) + print('Rx: to ' + hex(header[11]) + ':' + hex(header[12]) + ':' + hex(header[13]) + ':' + hex(header[14]) + + ':' + hex(header[15]) + ':' + hex(header[16])) # Read the Payload - payload = self.rx_bytes( - payload_length) if payload_length != 0 else b'' + payload = self.rx_bytes(payload_length) if payload_length != 0 else b'' packet_bytes = header + payload self.packets_.put(packet_bytes) @@ -191,9 +187,8 @@ def main(argv): else: link_layer_shell = LinkLayerShell(link_layer) link_layer_shell.prompt = '$ ' - link_layer_shell.cmdloop( - 'Welcome to the RootCanal LinkLayer Console \n' + - 'Type \'help\' for more information.') + link_layer_shell.cmdloop('Welcome to the RootCanal LinkLayer Console \n' + + 'Type \'help\' for more information.') if __name__ == '__main__': diff --git a/system/vendor_libs/test_vendor_lib/scripts/send_simple_commands.py b/system/vendor_libs/test_vendor_lib/scripts/send_simple_commands.py index b7b0670f8a..72f3e18c86 100644 --- a/system/vendor_libs/test_vendor_lib/scripts/send_simple_commands.py +++ b/system/vendor_libs/test_vendor_lib/scripts/send_simple_commands.py @@ -212,8 +212,7 @@ def main(argv): else: raw_port_shell = RawPortShell(raw_port) raw_port_shell.prompt = '$ ' - raw_port_shell.cmdloop('Welcome to the RootCanal Console \n' + - 'Type \'help\' for more information.') + raw_port_shell.cmdloop('Welcome to the RootCanal Console \n' + 'Type \'help\' for more information.') if __name__ == '__main__': diff --git a/system/vendor_libs/test_vendor_lib/scripts/simple_link_layer_socket.py b/system/vendor_libs/test_vendor_lib/scripts/simple_link_layer_socket.py index 89552d9eae..5ce2a3594d 100644 --- a/system/vendor_libs/test_vendor_lib/scripts/simple_link_layer_socket.py +++ b/system/vendor_libs/test_vendor_lib/scripts/simple_link_layer_socket.py @@ -189,8 +189,7 @@ def main(argv): else: raw_port_shell = RawPortShell(raw_port) raw_port_shell.prompt = '$ ' - raw_port_shell.cmdloop('Welcome to the RootCanal Console \n' + - 'Type \'help\' for more information.') + raw_port_shell.cmdloop('Welcome to the RootCanal Console \n' + 'Type \'help\' for more information.') if __name__ == '__main__': diff --git a/system/vendor_libs/test_vendor_lib/scripts/simple_stack.py b/system/vendor_libs/test_vendor_lib/scripts/simple_stack.py index 52472e9e7d..5139c50bce 100644 --- a/system/vendor_libs/test_vendor_lib/scripts/simple_stack.py +++ b/system/vendor_libs/test_vendor_lib/scripts/simple_stack.py @@ -230,8 +230,7 @@ def main(argv): else: raw_port_shell = RawPortShell(raw_port) raw_port_shell.prompt = "$ " - raw_port_shell.cmdloop("Welcome to the RootCanal Console \n" + - 'Type \'help\' for more information.') + raw_port_shell.cmdloop("Welcome to the RootCanal Console \n" + 'Type \'help\' for more information.') if __name__ == "__main__": diff --git a/system/vendor_libs/test_vendor_lib/scripts/test_channel.py b/system/vendor_libs/test_vendor_lib/scripts/test_channel.py index 79b19b1bbb..f0d534fafd 100644 --- a/system/vendor_libs/test_vendor_lib/scripts/test_channel.py +++ b/system/vendor_libs/test_vendor_lib/scripts/test_channel.py @@ -100,8 +100,7 @@ class TestChannel(object): args_size = len(args) self.lint_command(name, args, name_size, args_size) encoded_name = chr(name_size) + name - encoded_args = chr(args_size) + ''.join( - chr(len(arg)) + arg for arg in args) + encoded_args = chr(args_size) + ''.join(chr(len(arg)) + arg for arg in args) command = encoded_name + encoded_args if self._closed: return @@ -280,8 +279,7 @@ def main(argv): else: test_channel_shell = TestChannelShell(test_channel) test_channel_shell.prompt = '$ ' - test_channel_shell.cmdloop('Welcome to the RootCanal Console \n' + - 'Type \'help\' for more information.') + test_channel_shell.cmdloop('Welcome to the RootCanal Console \n' + 'Type \'help\' for more information.') if __name__ == '__main__': |