summaryrefslogtreecommitdiff
path: root/test/testdir.cc
blob: d5aef229e15ff2b96d1db5376b0ad553085d2be4 (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
#include "testdir.hh"

#include <cstdlib>
#include <filesystem>
#include <format>
#include <gtest/gtest.h>
#include <system_error>

namespace {

std::filesystem::path mktmpdir() {
  std::error_code ec;
  auto base = std::filesystem::temp_directory_path(ec);
  if (ec)
    return {};
  for (int i = 0; i < 10; ++i) {
    auto name = std::format(
        "{}-{}",
        ::testing::UnitTest::GetInstance()->current_test_info()->name(),
        rand());
    auto tmpdir = base / name;
    if (std::filesystem::exists(tmpdir))
      continue;
    if (std::filesystem::create_directory(tmpdir, ec))
      return tmpdir;
  }
  return {};
}

}  // namespace

TestDir::TestDir() : path_(mktmpdir()) {}

TestDir::~TestDir() {
  if (!path_.empty())
    std::filesystem::remove_all(path_);
}