1 // Copyright 2022 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/packet_meta.h"
16
17 #include "pw_fuzzer/fuzztest.h"
18 #include "pw_rpc/internal/packet.h"
19 #include "pw_unit_test/framework.h"
20
21 namespace pw::rpc {
22 namespace {
23
24 using namespace fuzzer;
25
FromBufferDecodesValidMinimalPacket(uint32_t channel_id,uint32_t service_id,uint32_t method_id)26 void FromBufferDecodesValidMinimalPacket(uint32_t channel_id,
27 uint32_t service_id,
28 uint32_t method_id) {
29 internal::Packet packet;
30 packet.set_channel_id(channel_id);
31 packet.set_service_id(service_id);
32 packet.set_type(internal::pwpb::PacketType::RESPONSE);
33 packet.set_method_id(method_id);
34
35 std::byte buffer[128];
36 Result<ConstByteSpan> encode_result = packet.Encode(buffer);
37 ASSERT_EQ(encode_result.status(), OkStatus());
38
39 Result<PacketMeta> decode_result = PacketMeta::FromBuffer(*encode_result);
40 ASSERT_EQ(decode_result.status(), OkStatus());
41 EXPECT_EQ(decode_result->channel_id(), channel_id);
42 EXPECT_EQ(decode_result->service_id(), internal::WrapServiceId(service_id));
43 EXPECT_TRUE(decode_result->destination_is_client());
44 }
45
TEST(PacketMeta,FromBufferDecodesValidMinimalPacketConst)46 TEST(PacketMeta, FromBufferDecodesValidMinimalPacketConst) {
47 const uint32_t kChannelId = 12;
48 const uint32_t kServiceId = 0xdeadbeef;
49 const uint32_t kMethodId = 44;
50 FromBufferDecodesValidMinimalPacket(kChannelId, kServiceId, kMethodId);
51 }
52
53 FUZZ_TEST(PacketMeta, FromBufferDecodesValidMinimalPacket)
54 .WithDomains(NonZero<uint32_t>(), NonZero<uint32_t>(), NonZero<uint32_t>());
55
TEST(PacketMeta,FromBufferFailsOnIncompletePacket)56 TEST(PacketMeta, FromBufferFailsOnIncompletePacket) {
57 internal::Packet packet;
58
59 std::byte buffer[128];
60 Result<ConstByteSpan> encode_result = packet.Encode(buffer);
61 ASSERT_EQ(encode_result.status(), OkStatus());
62
63 Result<PacketMeta> decode_result = PacketMeta::FromBuffer(*encode_result);
64 ASSERT_EQ(decode_result.status(), Status::DataLoss());
65 }
66
67 } // namespace
68 } // namespace pw::rpc
69