xref: /aosp_15_r20/external/libbrillo/brillo/blkdev_utils/loop_device_test.cc (revision 1a96fba65179ea7d3f56207137718607415c5953)
1 // Copyright 2018 The Chromium OS Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include <brillo/blkdev_utils/loop_device_fake.h>
6 
7 #include <base/files/file_util.h>
8 #include <gtest/gtest.h>
9 
10 namespace brillo {
11 
TEST(LoopDeviceTest,GeneralTest)12 TEST(LoopDeviceTest, GeneralTest) {
13   base::FilePath loop_backing_file;
14   base::CreateTemporaryFile(&loop_backing_file);
15   fake::FakeLoopDeviceManager loop_manager;
16 
17   // Create a new device
18   std::unique_ptr<LoopDevice> device =
19       loop_manager.AttachDeviceToFile(loop_backing_file);
20   std::unique_ptr<LoopDevice> device1 =
21       loop_manager.AttachDeviceToFile(loop_backing_file);
22   std::unique_ptr<LoopDevice> device2 =
23       loop_manager.AttachDeviceToFile(loop_backing_file);
24 
25   EXPECT_TRUE(device->IsValid());
26   EXPECT_TRUE(device1->IsValid());
27   EXPECT_TRUE(device2->IsValid());
28 
29   std::vector<std::unique_ptr<LoopDevice>> attached_devices =
30       loop_manager.GetAttachedDevices();
31 
32   // Expect 3 devices
33   EXPECT_EQ(attached_devices.size(), 3);
34 
35   device2->SetName("Loopy");
36 
37   std::unique_ptr<LoopDevice> device1_copy =
38       loop_manager.GetAttachedDeviceByNumber(1);
39   EXPECT_TRUE(device1_copy->IsValid());
40   EXPECT_EQ(device1->GetDevicePath(), device1_copy->GetDevicePath());
41   EXPECT_EQ(device1->GetBackingFilePath(), device1_copy->GetBackingFilePath());
42 
43   std::unique_ptr<LoopDevice> device2_copy =
44       loop_manager.GetAttachedDeviceByName("Loopy");
45   EXPECT_TRUE(device2_copy->IsValid());
46   EXPECT_EQ(device2->GetDevicePath(), device2_copy->GetDevicePath());
47   EXPECT_EQ(device2->GetBackingFilePath(), device2_copy->GetBackingFilePath());
48 
49   // Check double detach
50   EXPECT_TRUE(device->Detach());
51   EXPECT_TRUE(device1->Detach());
52   EXPECT_FALSE(device1_copy->Detach());
53   EXPECT_TRUE(device2->Detach());
54   EXPECT_FALSE(device2_copy->Detach());
55 }
56 
57 }  // namespace brillo
58