https://mooseframework.inl.gov
Loading...
Searching...
No Matches
MooseUnitUtils.C
Go to the documentation of this file.
1//* This file is part of the MOOSE framework
2//* https://mooseframework.inl.gov
3//*
4//* All rights reserved, see COPYRIGHT for full restrictions
5//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
6//*
7//* Licensed under LGPL 2.1, please see LICENSE for details
8//* https://www.gnu.org/licenses/lgpl-2.1.html
9
10#include "MooseUnitUtils.h"
11
12#include <random>
13
14namespace
15{
16std::filesystem::path
17generatePath()
18{
19 static const std::string chars = "abcdefghijklmnopqrstuvwxyz0123456789";
20 static thread_local std::mt19937 generator{std::random_device{}()};
21 std::uniform_int_distribution<std::size_t> distribution(0, chars.size() - 1);
22 std::string result;
23 // Ten base-36 characters provide more than 3e15 possible paths.
24 constexpr std::size_t random_name_length = 10;
25 result.reserve(random_name_length);
26 while (result.size() < random_name_length)
27 result += chars[distribution(generator)];
28 return std::filesystem::temp_directory_path() / std::filesystem::path("mooseunit." + result);
29}
30}
31
32namespace Moose::UnitUtils
33{
34TempFile::TempFile() : _path(generatePath()) {}
35
37{
38 std::error_code ec;
39 std::filesystem::remove(path(), ec);
40}
41
42ScopedTestDirectory::ScopedTestDirectory(const std::vector<std::filesystem::path> & inputs)
43 : _original_path(std::filesystem::current_path()), _path(createPath())
44{
45 try
46 {
47 for (const auto & input : inputs)
48 std::filesystem::copy(
49 input, _path / input.filename(), std::filesystem::copy_options::recursive);
50 std::filesystem::current_path(_path);
51 }
52 catch (...)
53 {
54 std::error_code ec;
55 std::filesystem::remove_all(_path, ec);
56 throw;
57 }
58}
59
61{
62 std::error_code ec;
63 std::filesystem::current_path(_original_path, ec);
64 if (!ec)
65 std::filesystem::remove_all(_path, ec);
66}
67
68std::filesystem::path
70{
71 while (true)
72 {
73 const auto path = generatePath();
74 if (std::filesystem::create_directory(path))
75 return path;
76 }
77}
78
79}
const std::filesystem::path _original_path
Working directory to restore upon destruction.
static std::filesystem::path createPath()
ScopedTestDirectory(const std::vector< std::filesystem::path > &inputs)
const std::filesystem::path _path
Unique temporary working directory.
const std::filesystem::path & path() const
const std::filesystem::path & path() const