xref: /aosp_15_r20/external/pigweed/pw_fuzzer/examples/fuzztest/metrics_unittest.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 "metrics.h"
16 
17 #include <algorithm>
18 
19 #include "pw_unit_test/framework.h"
20 
21 namespace pw::fuzzer::examples {
22 
23 // DOCSTAG: [pwfuzzer_examples_fuzztest-metrics_unittest]
TEST(MetricsTest,SerializeAndDeserialize)24 TEST(MetricsTest, SerializeAndDeserialize) {
25   std::array<std::byte, Metrics::kMaxSerializedSize> buffer;
26 
27   // Add and copy the names only.
28   Metrics src, dst;
29   EXPECT_TRUE(src.SetValue("one", 0).ok());
30   EXPECT_TRUE(src.SetValue("two", 0).ok());
31   EXPECT_TRUE(src.SetValue("three", 0).ok());
32   EXPECT_TRUE(dst.SetMetrics(src.GetMetrics()).ok());
33 
34   // Modify the values.
35   EXPECT_TRUE(src.SetValue("one", 1).ok());
36   EXPECT_TRUE(src.SetValue("two", 2).ok());
37   EXPECT_TRUE(src.SetValue("three", 3).ok());
38 
39   // Transfer the data and check.
40   EXPECT_TRUE(src.Serialize(buffer).ok());
41   EXPECT_TRUE(dst.Deserialize(buffer).ok());
42   EXPECT_EQ(dst.GetValue("one").value_or(0), 1U);
43   EXPECT_EQ(dst.GetValue("two").value_or(0), 2U);
44   EXPECT_EQ(dst.GetValue("three").value_or(0), 3U);
45 }
46 
TEST(MetricsTest,DeserializeDoesNotCrash)47 TEST(MetricsTest, DeserializeDoesNotCrash) {
48   std::array<std::byte, Metrics::kMaxSerializedSize> buffer;
49   std::fill(buffer.begin(), buffer.end(), std::byte(0x5C));
50 
51   // Just make sure this does not crash.
52   Metrics dst;
53   dst.Deserialize(buffer).IgnoreError();
54 }
55 // DOCSTAG: [pwfuzzer_examples_fuzztest-metrics_unittest]
56 
57 }  // namespace pw::fuzzer::examples
58