blob: bd11a90d8ddafdd6d6b0939799e10228fe86ed55 [file] [log] [blame]
Ed Tanous7a6f0032024-01-28 09:49:03 -08001#pragma once
2#include <filesystem>
3#include <string>
4#include <string_view>
5
6#include <gtest/gtest.h>
7
Ed Tanous5575efb2024-01-30 09:25:03 -08008struct TemporaryFileHandle
Ed Tanous7a6f0032024-01-28 09:49:03 -08009{
Ed Tanous5575efb2024-01-30 09:25:03 -080010 std::filesystem::path path;
11 std::string stringPath;
12
13 // Creates a temporary file with the contents provided, removes it on
14 // destruction.
15 explicit TemporaryFileHandle(std::string_view sampleData) :
16 path(std::filesystem::temp_directory_path() /
17 "bmcweb_http_response_test_XXXXXXXXXXX")
18 {
19 stringPath = path.string();
20
21 int fd = mkstemp(stringPath.data());
22 EXPECT_GT(fd, 0);
23 EXPECT_EQ(write(fd, sampleData.data(), sampleData.size()),
24 sampleData.size());
25 close(fd);
26 }
27
28 TemporaryFileHandle(const TemporaryFileHandle&) = delete;
29 TemporaryFileHandle(TemporaryFileHandle&&) = delete;
30 TemporaryFileHandle& operator=(const TemporaryFileHandle&) = delete;
31 TemporaryFileHandle& operator=(TemporaryFileHandle&&) = delete;
32
33 ~TemporaryFileHandle()
34 {
35 std::filesystem::remove(path);
36 }
37};