1 //
2 // Copyright (C) 2021 The Android Open Source Project
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 //      http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 //
16 
17 #include <libsnapshot/snapshot.h>
18 
19 #include <unordered_set>
20 
21 #include <android-base/file.h>
22 #include <gtest/gtest.h>
23 #include <libsnapshot/snapshot_writer.h>
24 #include <payload_consumer/file_descriptor.h>
25 
26 namespace android::snapshot {
27 class CompressedSnapshotWriterTest : public ::testing::Test {
28   public:
29     static constexpr size_t BLOCK_SIZE = 4096;
30 };
31 
TEST_F(CompressedSnapshotWriterTest,ReadAfterWrite)32 TEST_F(CompressedSnapshotWriterTest, ReadAfterWrite) {
33     TemporaryFile cow_device_file{};
34     android::snapshot::CowOptions options{.block_size = BLOCK_SIZE};
35     android::snapshot::CompressedSnapshotWriter snapshot_writer{options};
36     ASSERT_TRUE(snapshot_writer.SetCowDevice(android::base::unique_fd{cow_device_file.fd}));
37     ASSERT_TRUE(snapshot_writer.Initialize());
38     std::vector<unsigned char> buffer;
39     buffer.resize(BLOCK_SIZE);
40     std::fill(buffer.begin(), buffer.end(), 123);
41 
42     ASSERT_TRUE(snapshot_writer.AddRawBlocks(0, buffer.data(), buffer.size()));
43     ASSERT_TRUE(snapshot_writer.Finalize());
44     auto cow_reader = snapshot_writer.OpenReader();
45     ASSERT_NE(cow_reader, nullptr);
46     ASSERT_TRUE(snapshot_writer.AddRawBlocks(1, buffer.data(), buffer.size()));
47     ASSERT_TRUE(snapshot_writer.AddRawBlocks(2, buffer.data(), buffer.size()));
48     ASSERT_TRUE(snapshot_writer.Finalize());
49     // After wrigin some data, if we call OpenReader() again, writes should
50     // be visible to the newly opened reader. update_engine relies on this
51     // behavior for verity writes.
52     cow_reader = snapshot_writer.OpenReader();
53     ASSERT_NE(cow_reader, nullptr);
54     std::vector<unsigned char> read_back;
55     read_back.resize(buffer.size());
56     cow_reader->Seek(BLOCK_SIZE, SEEK_SET);
57     const auto bytes_read = cow_reader->Read(read_back.data(), read_back.size());
58     ASSERT_EQ((size_t)(bytes_read), BLOCK_SIZE);
59     ASSERT_EQ(read_back, buffer);
60 }
61 
62 }  // namespace android::snapshot
63