Spicy
utils.h
1 // Copyright (c) 2020-2021 by the Zeek Project. See LICENSE for details.
2 
3 #pragma once
4 
5 #include <unistd.h>
6 
7 #include <cstdlib>
8 #include <fstream>
9 #include <sstream>
10 #include <streambuf>
11 #include <string>
12 #include <vector>
13 
14 #include <hilti/rt/context.h>
15 #include <hilti/rt/doctest.h>
16 #include <hilti/rt/filesystem.h>
17 #include <hilti/rt/util.h>
18 
19 namespace hilti::rt::test {
20 // RAII helper to maintain a temporary file
22 public:
23  explicit TemporaryFile() {
24  std::string path = hilti::rt::filesystem::temp_directory_path() / "hilti-rt-tests-XXXXXX";
25 
26  auto fd = ::mkstemp(path.data());
27  REQUIRE_NE(fd, -1);
28  ::close(fd);
29 
30  _path = path;
31  }
32 
33  std::vector<std::string> lines() const {
34  auto file = std::ifstream(_path);
35 
36  std::string line;
37  std::vector<std::string> lines;
38  while ( std::getline(file, line) )
39  lines.push_back(line);
40 
41  return lines;
42  }
43 
44  const auto& path() const { return _path; }
45 
46  ~TemporaryFile() {
47  if ( hilti::rt::filesystem::exists(_path) )
48  hilti::rt::filesystem::remove_all(_path);
49  }
50 
51 private:
52  hilti::rt::filesystem::path _path;
53 };
54 
55 // RAII helper to redirect output.
56 class CaptureIO {
57 public:
58  CaptureIO(std::ostream& stream) : _old(stream.rdbuf(_buffer.rdbuf())), _stream(&stream) {}
59  ~CaptureIO() { _stream->rdbuf(_old); }
60 
61  auto str() const { return _buffer.str(); }
62 
63 private:
64  std::stringstream _buffer = std::stringstream{};
65  std::streambuf* _old = nullptr;
66  std::ostream* _stream = nullptr;
67 };
68 
69 // RAII helper to maintain a controlled context in tests.
70 class TestContext {
71 public:
72  TestContext(Context* current) {
73  _prev = context::detail::current();
74  context::detail::current() = current;
75  }
76 
77  ~TestContext() { context::detail::current() = _prev; }
78 
79 private:
80  Context* _prev = nullptr;
81 };
82 
83 } // namespace hilti::rt::test
Definition: utils.h:19
Definition: utils.h:21
Definition: utils.h:56
Definition: utils.h:70
Definition: context.h:24