blob: b12fbca621a9dd214047136ef69939ff7a8cc21b [file] [log] [blame]
Ed Tanous40e9b922024-09-10 13:50:16 -07001// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright OpenBMC Authors
Ed Tanous7a6f0032024-01-28 09:49:03 -08003#pragma once
Ed Tanousd7857202025-01-28 15:32:26 -08004#include <unistd.h>
5
Ed Tanous7a6f0032024-01-28 09:49:03 -08006#include <filesystem>
7#include <string>
8#include <string_view>
9
10#include <gtest/gtest.h>
11
Ed Tanous5575efb2024-01-30 09:25:03 -080012struct TemporaryFileHandle
Ed Tanous7a6f0032024-01-28 09:49:03 -080013{
Ed Tanous5575efb2024-01-30 09:25:03 -080014 std::filesystem::path path;
15 std::string stringPath;
16
17 // Creates a temporary file with the contents provided, removes it on
18 // destruction.
19 explicit TemporaryFileHandle(std::string_view sampleData) :
20 path(std::filesystem::temp_directory_path() /
21 "bmcweb_http_response_test_XXXXXXXXXXX")
22 {
23 stringPath = path.string();
24
Ed Tanousd7857202025-01-28 15:32:26 -080025 // NOLINTNEXTLINE(misc-include-cleaner)
Ed Tanous5575efb2024-01-30 09:25:03 -080026 int fd = mkstemp(stringPath.data());
27 EXPECT_GT(fd, 0);
28 EXPECT_EQ(write(fd, sampleData.data(), sampleData.size()),
29 sampleData.size());
30 close(fd);
31 }
32
33 TemporaryFileHandle(const TemporaryFileHandle&) = delete;
34 TemporaryFileHandle(TemporaryFileHandle&&) = delete;
35 TemporaryFileHandle& operator=(const TemporaryFileHandle&) = delete;
36 TemporaryFileHandle& operator=(TemporaryFileHandle&&) = delete;
37
38 ~TemporaryFileHandle()
39 {
40 std::filesystem::remove(path);
41 }
42};