Ed Tanous | 40e9b92 | 2024-09-10 13:50:16 -0700 | [diff] [blame] | 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // SPDX-FileCopyrightText: Copyright OpenBMC Authors |
Ed Tanous | 7a6f003 | 2024-01-28 09:49:03 -0800 | [diff] [blame] | 3 | #pragma once |
| 4 | #include <filesystem> |
| 5 | #include <string> |
| 6 | #include <string_view> |
| 7 | |
| 8 | #include <gtest/gtest.h> |
| 9 | |
Ed Tanous | 5575efb | 2024-01-30 09:25:03 -0800 | [diff] [blame] | 10 | struct TemporaryFileHandle |
Ed Tanous | 7a6f003 | 2024-01-28 09:49:03 -0800 | [diff] [blame] | 11 | { |
Ed Tanous | 5575efb | 2024-01-30 09:25:03 -0800 | [diff] [blame] | 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 | }; |