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