xref: /openbmc/bmcweb/include/file_test_utilities.hpp (revision d2ec1bd7a0267cfd259615b979a4a2119f09a7d6)
1 // SPDX-License-Identifier: Apache-2.0
2 // SPDX-FileCopyrightText: Copyright OpenBMC Authors
3 #pragma once
4 #include <filesystem>
5 #include <string>
6 #include <string_view>
7 
8 #include <gtest/gtest.h>
9 
10 struct TemporaryFileHandle
11 {
12     std::filesystem::path path;
13     std::string stringPath;
14 
15     // Creates a temporary file with the contents provided, removes it on
16     // destruction.
17     explicit TemporaryFileHandle(std::string_view sampleData) :
18         path(std::filesystem::temp_directory_path() /
19              "bmcweb_http_response_test_XXXXXXXXXXX")
20     {
21         stringPath = path.string();
22 
23         int fd = mkstemp(stringPath.data());
24         EXPECT_GT(fd, 0);
25         EXPECT_EQ(write(fd, sampleData.data(), sampleData.size()),
26                   sampleData.size());
27         close(fd);
28     }
29 
30     TemporaryFileHandle(const TemporaryFileHandle&) = delete;
31     TemporaryFileHandle(TemporaryFileHandle&&) = delete;
32     TemporaryFileHandle& operator=(const TemporaryFileHandle&) = delete;
33     TemporaryFileHandle& operator=(TemporaryFileHandle&&) = delete;
34 
35     ~TemporaryFileHandle()
36     {
37         std::filesystem::remove(path);
38     }
39 };
40