summaryrefslogtreecommitdiff
path: root/include/file_test_utilities.hpp
blob: b12fbca621a9dd214047136ef69939ff7a8cc21b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright OpenBMC Authors
#pragma once
#include <unistd.h>

#include <filesystem>
#include <string>
#include <string_view>

#include <gtest/gtest.h>

struct TemporaryFileHandle
{
    std::filesystem::path path;
    std::string stringPath;

    // Creates a temporary file with the contents provided, removes it on
    // destruction.
    explicit TemporaryFileHandle(std::string_view sampleData) :
        path(std::filesystem::temp_directory_path() /
             "bmcweb_http_response_test_XXXXXXXXXXX")
    {
        stringPath = path.string();

        // NOLINTNEXTLINE(misc-include-cleaner)
        int fd = mkstemp(stringPath.data());
        EXPECT_GT(fd, 0);
        EXPECT_EQ(write(fd, sampleData.data(), sampleData.size()),
                  sampleData.size());
        close(fd);
    }

    TemporaryFileHandle(const TemporaryFileHandle&) = delete;
    TemporaryFileHandle(TemporaryFileHandle&&) = delete;
    TemporaryFileHandle& operator=(const TemporaryFileHandle&) = delete;
    TemporaryFileHandle& operator=(TemporaryFileHandle&&) = delete;

    ~TemporaryFileHandle()
    {
        std::filesystem::remove(path);
    }
};