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,
37 0xff, 0xff, 0xff};
38
39 // Hardware Error event with code 0x43.
40 const std::vector<uint8_t> kHardwareErrorEvent = {0x10, 0x01, 0x43};
41
TEST_F(InvalidPacketHandlerTest,DefaultHandler)42 TEST_F(InvalidPacketHandlerTest, DefaultHandler) {
43 // Validate that the default invalid packet handler causes
44 // an abort when an invalid packet is received.
45 ASSERT_DEATH(controller_.HandleCommand(std::make_shared<std::vector<uint8_t>>(
46 kInvalidCommandPacket)),
47 "");
48 }
49
TEST_F(InvalidPacketHandlerTest,RegisteredHandler)50 TEST_F(InvalidPacketHandlerTest, RegisteredHandler) {
51 static struct {
52 uint32_t id;
53 InvalidPacketReason reason;
54 std::vector<uint8_t> bytes;
55 } invalid_packet;
56
57 static std::vector<uint8_t> hci_event;
58
59 // Validate that the registered invalid packet handler is correctly
60 // invoked when an invalid packet is received.
61 controller_.RegisterInvalidPacketHandler(
62 [&](uint32_t id, InvalidPacketReason reason, std::string,
63 std::vector<uint8_t> const& bytes) {
64 invalid_packet.id = id;
65 invalid_packet.reason = reason;
66 invalid_packet.bytes = bytes;
67 });
68
69 controller_.RegisterEventChannel(
70 [&](std::shared_ptr<std::vector<uint8_t>> packet) {
71 hci_event = std::vector<uint8_t>(*packet);
72 });
73
74 controller_.HandleCommand(
75 std::make_shared<std::vector<uint8_t>>(kInvalidCommandPacket));
76 ASSERT_EQ(invalid_packet.id, controller_.id_);
77 ASSERT_EQ(invalid_packet.reason, InvalidPacketReason::kParseError);
78 ASSERT_EQ(invalid_packet.bytes, kInvalidCommandPacket);
79 ASSERT_EQ(hci_event, kHardwareErrorEvent);
80 }
81
82 } // namespace rootcanal
83