1 // SPDX-License-Identifier: Apache-2.0 2 // SPDX-FileCopyrightText: Copyright OpenBMC Authors 3 #pragma once 4 #include <unistd.h> 5 6 #include <cstdlib> 7 #include <filesystem> 8 #include <string> 9 #include <string_view> 10 11 #include <gtest/gtest.h> 12 13 struct TemporaryFileHandle 14 { 15 std::filesystem::path path; 16 std::string stringPath; 17 18 // Creates a temporary file with the contents provided, removes it on 19 // destruction. TemporaryFileHandleTemporaryFileHandle20 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 26 // NOLINTNEXTLINE(misc-include-cleaner) 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 ~TemporaryFileHandleTemporaryFileHandle39 ~TemporaryFileHandle() 40 { 41 std::filesystem::remove(path); 42 } 43 }; 44