summaryrefslogtreecommitdiff
path: root/test/testenv.cc
blob: 56701a42642402b3bc005b29c0704b834ad14f2a (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
38
39
40
41
42
43
44
#include "testenv.hh"

#include <cstdlib>
#include <optional>
#include <string>

void TestEnv::setenv(std::string const& name, std::string const& value) {
  saveenv(name);

  // NOLINTNEXTLINE(misc-include-cleaner)
  ::setenv(name.c_str(), value.c_str(), 1);
}

void TestEnv::unsetenv(std::string const& name) {
  saveenv(name);

  // NOLINTNEXTLINE(misc-include-cleaner)
  ::unsetenv(name.c_str());
}

void TestEnv::TearDown() {
  for (auto const& pair : env_) {
    if (pair.second.has_value()) {
      // NOLINTNEXTLINE(misc-include-cleaner)
      ::setenv(pair.first.c_str(), pair.second->c_str(), 1);
    } else {
      // NOLINTNEXTLINE(misc-include-cleaner)
      ::unsetenv(pair.first.c_str());
    }
  }
}

void TestEnv::saveenv(std::string const& name) {
  auto it = env_.find(name);
  if (it != env_.end())
    return;

  auto* str = getenv(name.c_str());
  if (str == nullptr) {
    env_.emplace(name, std::nullopt);
  } else {
    env_.emplace(name, str);
  }
}