blob: 1d555090a1aa8d8ad87f6a552a45a63b7bd2596c [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
6#include <cstdlib>
Ed Tanous7a6f0032024-01-28 09:49:03 -08007#include <filesystem>
8#include <string>
9#include <string_view>
10
11#include <gtest/gtest.h>
12
Ed Tanous5575efb2024-01-30 09:25:03 -080013struct TemporaryFileHandle
Ed Tanous7a6f0032024-01-28 09:49:03 -080014{
Ed Tanous5575efb2024-01-30 09:25:03 -080015 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 Tanousd7857202025-01-28 15:32:26 -080026 // NOLINTNEXTLINE(misc-include-cleaner)
Ed Tanous5575efb2024-01-30 09:25:03 -080027 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};