blob: 73d13592f4fac4b66a9181a75b0a50239d80ab4e [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
4#include <filesystem>
5#include <string>
6#include <string_view>
7
8#include <gtest/gtest.h>
9
Ed Tanous5575efb2024-01-30 09:25:03 -080010struct TemporaryFileHandle
Ed Tanous7a6f0032024-01-28 09:49:03 -080011{
Ed Tanous5575efb2024-01-30 09:25:03 -080012 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};