Specs
Beautiful C++ Test Framework
Loading...
Searching...
No Matches
SnowhouseExceptionHandler.h
Go to the documentation of this file.
1#pragma once
2
3#include <Specs/API.h>
5#include <snowhouse/snowhouse.h>
6#include <string_format.h>
7
8#include <filesystem>
9#include <fstream>
10#include <optional>
11#include <string>
12
14
16 std::optional<std::filesystem::path> WalkUpToFindFilePath(const std::string& path) {
17 // Given the provided path,
18 // return it if it exists.
19 //
20 // Else, walk up parent folders and return the first one that exists.
21 if (std::filesystem::exists(path)) return path;
22
23 std::filesystem::path currentPath = std::filesystem::current_path();
24 if (std::filesystem::exists(currentPath / path)) return currentPath / path;
25
26 while (currentPath.has_parent_path()) {
27 currentPath = currentPath.parent_path();
28 if (std::filesystem::exists(currentPath / path)) return currentPath / path;
29 }
30
31 return std::nullopt;
32 }
33
34 std::string ReadLineFromFile(const std::string& filename, unsigned int linenumber) {
35 auto path = WalkUpToFindFilePath(filename);
36 if (!path.has_value()) return "";
37
38 std::ifstream file(path.value());
39 if (!file.is_open()) return "";
40
41 std::string line;
42 unsigned int currentLineNumber = 0;
43 while (std::getline(file, line)) {
44 currentLineNumber++;
45 if (currentLineNumber == linenumber) {
46 // trim whitespace from front of line and then return it
47 line.erase(line.begin(), std::find_if(line.begin(), line.end(), [](int ch) {
48 return !std::isspace(ch);
49 }));
50 return line;
51 }
52 }
53
54 return "";
55 }
56
57 public:
59 std::exception_ptr* exception, IExceptionMessageCallbackFn* failureMessageCallback
60 ) override {
61 try {
62 std::rethrow_exception(*exception);
63 } catch (const snowhouse::AssertionException& e) {
64 if (failureMessageCallback) {
65 SpecExceptionMessage failureMessage{string_format(
66 "{}\n[{}:{}] {}", e.what(), e.file(), e.line(),
67 ReadLineFromFile(e.file(), e.line())
68 )};
69 failureMessageCallback->invoke(&failureMessage);
70 }
71 return true;
72 } catch (...) {
73 return false;
74 }
75 }
76 };
77}
bool handle_exception(std::exception_ptr *exception, IExceptionMessageCallbackFn *failureMessageCallback) override
ILocalSpecExceptionHandler::LocalSpecExceptionFailureMessageCallbackFn IExceptionMessageCallbackFn
Definition API.h:391