xref: /aosp_15_r20/external/pigweed/pw_bluetooth_sapphire/host/l2cap/fake_channel_test.cc (revision 61c4878ac05f98d0ceed94b57d316916de578985)
1 // Copyright 2023 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14 
15 #include "pw_bluetooth_sapphire/internal/host/l2cap/fake_channel_test.h"
16 
17 #include "pw_bluetooth_sapphire/internal/host/common/log.h"
18 #include "pw_bluetooth_sapphire/internal/host/testing/test_helpers.h"
19 
20 namespace bt::l2cap::testing {
21 
SetUp()22 void FakeChannelTest::SetUp() {}
23 
CreateFakeChannel(const ChannelOptions & options)24 std::unique_ptr<FakeChannel> FakeChannelTest::CreateFakeChannel(
25     const ChannelOptions& options) {
26   auto fake_chan = std::make_unique<FakeChannel>(
27       options.id,
28       options.remote_id,
29       options.conn_handle,
30       options.link_type,
31       ChannelInfo::MakeBasicMode(options.mtu, options.mtu));
32   fake_chan_ = fake_chan->AsWeakPtr();
33   return fake_chan;
34 }
35 
Expect(const ByteBuffer & expected)36 bool FakeChannelTest::Expect(const ByteBuffer& expected) {
37   return ExpectAfterMaybeReceiving(std::nullopt, expected);
38 }
39 
ReceiveAndExpect(const ByteBuffer & packet,const ByteBuffer & expected_response)40 bool FakeChannelTest::ReceiveAndExpect(const ByteBuffer& packet,
41                                        const ByteBuffer& expected_response) {
42   return ExpectAfterMaybeReceiving(packet.view(), expected_response);
43 }
44 
ExpectAfterMaybeReceiving(std::optional<BufferView> packet,const ByteBuffer & expected)45 bool FakeChannelTest::ExpectAfterMaybeReceiving(
46     std::optional<BufferView> packet, const ByteBuffer& expected) {
47   if (!fake_chan().is_alive()) {
48     bt_log(ERROR, "testing", "no channel, failing!");
49     return false;
50   }
51 
52   bool success = false;
53   auto cb = [&expected, &success](auto cb_packet) {
54     success = ContainersEqual(expected, *cb_packet);
55   };
56 
57   fake_chan()->SetSendCallback(cb, dispatcher());
58   if (packet.has_value()) {
59     fake_chan()->Receive(packet.value());
60   }
61   RunUntilIdle();
62 
63   return success;
64 }
65 
66 }  // namespace bt::l2cap::testing
67