• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2020 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_rpc/channel.h"
16 
17 #include <cstddef>
18 
19 #include "gtest/gtest.h"
20 #include "pw_rpc/internal/packet.h"
21 #include "pw_rpc/internal/test_utils.h"
22 
23 namespace pw::rpc::internal {
24 namespace {
25 
TEST(ChannelOutput,Name)26 TEST(ChannelOutput, Name) {
27   class NameTester : public ChannelOutput {
28    public:
29     NameTester(const char* name) : ChannelOutput(name) {}
30     Status Send(std::span<const std::byte>) override { return OkStatus(); }
31   };
32 
33   EXPECT_STREQ("hello_world", NameTester("hello_world").name());
34   EXPECT_EQ(nullptr, NameTester(nullptr).name());
35 }
36 
37 constexpr Packet kTestPacket(
38     PacketType::RESPONSE, 23, 42, 100, 0, {}, Status::NotFound());
39 const size_t kReservedSize = 2 /* type */ + 2 /* channel */ + 5 /* service */ +
40                              5 /* method */ + 2 /* payload key */ +
41                              2 /* status (if not OK) */;
42 
43 enum class ChannelId {
44   kOne = 1,
45   kTwo = 2,
46 };
47 
TEST(Channel,Create_FromEnum)48 TEST(Channel, Create_FromEnum) {
49   constexpr rpc::Channel one = Channel::Create<ChannelId::kOne>(nullptr);
50   constexpr rpc::Channel two = Channel::Create<ChannelId::kTwo>(nullptr);
51   static_assert(one.id() == 1);
52   static_assert(two.id() == 2);
53 }
54 
TEST(Channel,TestPacket_ReservedSizeMatchesMinEncodedSizeBytes)55 TEST(Channel, TestPacket_ReservedSizeMatchesMinEncodedSizeBytes) {
56   EXPECT_EQ(kReservedSize, kTestPacket.MinEncodedSizeBytes());
57 }
58 
TEST(ExtractChannelId,ValidPacket)59 TEST(ExtractChannelId, ValidPacket) {
60   std::byte buffer[64] = {};
61   Result<ConstByteSpan> result = kTestPacket.Encode(buffer);
62   ASSERT_EQ(result.status(), OkStatus());
63 
64   Result<uint32_t> channel_id = ExtractChannelId(*result);
65   ASSERT_EQ(channel_id.status(), OkStatus());
66   EXPECT_EQ(*channel_id, 23u);
67 }
68 
TEST(ExtractChannelId,InvalidPacket)69 TEST(ExtractChannelId, InvalidPacket) {
70   constexpr std::byte buffer[64] = {std::byte{1}, std::byte{2}};
71 
72   Result<uint32_t> channel_id = ExtractChannelId(buffer);
73 
74   EXPECT_EQ(channel_id.status(), Status::DataLoss());
75 }
76 
77 }  // namespace
78 }  // namespace pw::rpc::internal
79