1 /*
2  * Copyright 2024 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <gtest/gtest.h>
18 
19 #include "log.h"
20 #include "model/controller/dual_mode_controller.h"
21 
22 namespace rootcanal {
23 
24 using namespace bluetooth::hci;
25 
26 class InvalidPacketHandlerTest : public ::testing::Test {
27 public:
28   InvalidPacketHandlerTest() = default;
29   ~InvalidPacketHandlerTest() override = default;
30 
31 protected:
32   DualModeController controller_;
33 };
34 
35 // Set Event Mask command with missing parameters.
36 const std::vector<uint8_t> kInvalidCommandPacket = {0x01, 0x0C, 0x03, 0xff, 0xff, 0xff};
37 
38 // Hardware Error event with code 0x43.
39 const std::vector<uint8_t> kHardwareErrorEvent = {0x10, 0x01, 0x43};
40 
TEST_F(InvalidPacketHandlerTest,DefaultHandler)41 TEST_F(InvalidPacketHandlerTest, DefaultHandler) {
42   // Validate that the default invalid packet handler causes
43   // an abort when an invalid packet is received.
44   ASSERT_DEATH(
45           controller_.HandleCommand(std::make_shared<std::vector<uint8_t>>(kInvalidCommandPacket)),
46           "");
47 }
48 
TEST_F(InvalidPacketHandlerTest,RegisteredHandler)49 TEST_F(InvalidPacketHandlerTest, RegisteredHandler) {
50   static struct {
51     uint32_t id;
52     InvalidPacketReason reason;
53     std::vector<uint8_t> bytes;
54   } invalid_packet;
55 
56   static std::vector<uint8_t> hci_event;
57 
58   // Validate that the registered invalid packet handler is correctly
59   // invoked when an invalid packet is received.
60   controller_.RegisterInvalidPacketHandler([&](uint32_t id, InvalidPacketReason reason, std::string,
61                                                std::vector<uint8_t> const& bytes) {
62     invalid_packet.id = id;
63     invalid_packet.reason = reason;
64     invalid_packet.bytes = bytes;
65   });
66 
67   controller_.RegisterEventChannel([&](std::shared_ptr<std::vector<uint8_t>> packet) {
68     hci_event = std::vector<uint8_t>(*packet);
69   });
70 
71   controller_.HandleCommand(std::make_shared<std::vector<uint8_t>>(kInvalidCommandPacket));
72   ASSERT_EQ(invalid_packet.id, controller_.id_);
73   ASSERT_EQ(invalid_packet.reason, InvalidPacketReason::kParseError);
74   ASSERT_EQ(invalid_packet.bytes, kInvalidCommandPacket);
75   ASSERT_EQ(hci_event, kHardwareErrorEvent);
76 }
77 
78 }  // namespace rootcanal
79