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 "gtest/gtest.h"
16 #include "pw_kvs/crc16_checksum.h"
17 #include "pw_kvs/fake_flash_memory.h"
18 #include "pw_kvs/flash_partition_with_stats.h"
19 #include "pw_kvs/key_value_store.h"
20 
21 namespace pw::kvs {
22 namespace {
23 
24 using std::byte;
25 
26 #ifndef PW_KVS_FUZZ_ITERATIONS
27 #define PW_KVS_FUZZ_ITERATIONS 2
28 #endif  // PW_KVS_FUZZ_ITERATIONS
29 constexpr int kFuzzIterations = PW_KVS_FUZZ_ITERATIONS;
30 
31 constexpr size_t kMaxEntries = 256;
32 constexpr size_t kMaxUsableSectors = 256;
33 
34 // 4 x 4k sectors, 16 byte alignment
35 FakeFlashMemoryBuffer<4 * 1024, 6> test_flash(16);
36 
37 FlashPartitionWithStatsBuffer<kMaxUsableSectors> test_partition(
38     &test_flash, 0, test_flash.sector_count());
39 
40 ChecksumCrc16 checksum;
41 
42 class EmptyInitializedKvs : public ::testing::Test {
43  protected:
44   // For KVS magic value always use a random 32 bit integer rather than a
45   // human readable 4 bytes. See pw_kvs/format.h for more information.
EmptyInitializedKvs()46   EmptyInitializedKvs()
47       : kvs_(&test_partition, {.magic = 0x873a9b50, .checksum = &checksum}) {
48     test_partition.Erase(0, test_partition.sector_count());
49     ASSERT_EQ(OkStatus(), kvs_.Init());
50   }
51 
52   KeyValueStoreBuffer<kMaxEntries, kMaxUsableSectors> kvs_;
53 };
54 
TEST_F(EmptyInitializedKvs,Put_VaryingKeysAndValues)55 TEST_F(EmptyInitializedKvs, Put_VaryingKeysAndValues) {
56   char value[] =
57       "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"  // 52
58       "34567890123";  // 64 (with final \0);
59   static_assert(sizeof(value) == 64);
60 
61   test_partition.ResetCounters();
62 
63   for (int i = 0; i < kFuzzIterations; ++i) {
64     for (unsigned key_size = 1; key_size < sizeof(value); ++key_size) {
65       for (unsigned value_size = 0; value_size < sizeof(value); ++value_size) {
66         ASSERT_EQ(OkStatus(),
67                   kvs_.Put(std::string_view(value, key_size),
68                            std::as_bytes(std::span(value, value_size))));
69       }
70     }
71   }
72 
73   test_partition.SaveStorageStats(kvs_, "fuzz Put_VaryingKeysAndValues");
74 }
75 
76 }  // namespace
77 }  // namespace pw::kvs
78