stc
Loading...
Searching...
No Matches
TestFile.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <filesystem>
4#include <fstream>
5
6namespace stc::testutil {
7
15struct TestFile {
16 std::filesystem::path file;
17
18 [[nodiscard("Discarding this object will immediately delete the file")]]
19 TestFile(const std::filesystem::path& f, bool create = false) : file(f) {
20 if (std::filesystem::exists(file) && !std::filesystem::is_regular_file(f)) {
21 throw std::runtime_error(
22 "The file you supplied to TestFile exists, and is not a regular file. "
23 "This utility is only compatible with standard files. "
24 "If you were trying to take ownership of a directory, use TestDirectory instead."
25 );
26 }
27 deleteFile();
28
29 if (create) {
30 std::ofstream of(f);
31 if (!of) {
32 throw std::runtime_error(
33 "Failed to open test file. Do you have dir permissions?"
34 );
35 }
36 }
37 }
39 deleteFile();
40 }
41 void deleteFile() {
42 if (std::filesystem::exists(file)) {
43 std::filesystem::remove(file);
44 }
45 }
46};
47
48}
Definition CaptureStream.hpp:6
Definition TestFile.hpp:15
std::filesystem::path file
Definition TestFile.hpp:16
~TestFile()
Definition TestFile.hpp:38
TestFile(const std::filesystem::path &f, bool create=false)
Definition TestFile.hpp:19
void deleteFile()
Definition TestFile.hpp:41