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 |
Ed Tanous | d785720 | 2025-01-28 15:32:26 -0800 | [diff] [blame] | 4 | #include <unistd.h> |
| 5 | |
| 6 | #include <cstdlib> |
Ed Tanous | 7a6f003 | 2024-01-28 09:49:03 -0800 | [diff] [blame] | 7 | #include <filesystem> |
| 8 | #include <string> |
| 9 | #include <string_view> |
| 10 | |
| 11 | #include <gtest/gtest.h> |
| 12 | |
Ed Tanous | 5575efb | 2024-01-30 09:25:03 -0800 | [diff] [blame] | 13 | struct TemporaryFileHandle |
Ed Tanous | 7a6f003 | 2024-01-28 09:49:03 -0800 | [diff] [blame] | 14 | { |
Ed Tanous | 5575efb | 2024-01-30 09:25:03 -0800 | [diff] [blame] | 15 | std::filesystem::path path; |
| 16 | std::string stringPath; |
| 17 | |
| 18 | // Creates a temporary file with the contents provided, removes it on |
| 19 | // destruction. |
| 20 | explicit TemporaryFileHandle(std::string_view sampleData) : |
| 21 | path(std::filesystem::temp_directory_path() / |
| 22 | "bmcweb_http_response_test_XXXXXXXXXXX") |
| 23 | { |
| 24 | stringPath = path.string(); |
| 25 | |
Ed Tanous | d785720 | 2025-01-28 15:32:26 -0800 | [diff] [blame] | 26 | // NOLINTNEXTLINE(misc-include-cleaner) |
Ed Tanous | 5575efb | 2024-01-30 09:25:03 -0800 | [diff] [blame] | 27 | int fd = mkstemp(stringPath.data()); |
| 28 | EXPECT_GT(fd, 0); |
| 29 | EXPECT_EQ(write(fd, sampleData.data(), sampleData.size()), |
| 30 | sampleData.size()); |
| 31 | close(fd); |
| 32 | } |
| 33 | |
| 34 | TemporaryFileHandle(const TemporaryFileHandle&) = delete; |
| 35 | TemporaryFileHandle(TemporaryFileHandle&&) = delete; |
| 36 | TemporaryFileHandle& operator=(const TemporaryFileHandle&) = delete; |
| 37 | TemporaryFileHandle& operator=(TemporaryFileHandle&&) = delete; |
| 38 | |
| 39 | ~TemporaryFileHandle() |
| 40 | { |
| 41 | std::filesystem::remove(path); |
| 42 | } |
| 43 | }; |