#include <folly/Exception.h>
#include <folly/File.h>
#include <folly/FileUtil.h>
+#include <folly/String.h>
namespace folly {
namespace test {
return std::string(buf.get(), size);
}
+static std::map<std::string, std::string> getEnvVarMap() {
+ std::map<std::string, std::string> data;
+ for (auto it = environ; *it != nullptr; ++it) {
+ std::string key, value;
+ split("=", *it, key, value);
+ if (key.empty()) {
+ continue;
+ }
+ CHECK(!data.count(key)) << "already contains: " << key;
+ data.emplace(move(key), move(value));
+ }
+ return data;
+}
+
+EnvVarSaver::EnvVarSaver() {
+ saved_ = getEnvVarMap();
+}
+
+EnvVarSaver::~EnvVarSaver() {
+ for (const auto& kvp : getEnvVarMap()) {
+ if (saved_.count(kvp.first)) {
+ continue;
+ }
+ PCHECK(0 == unsetenv(kvp.first.c_str()));
+ }
+ for (const auto& kvp : saved_) {
+ PCHECK(0 == setenv(kvp.first.c_str(), kvp.second.c_str(), (int)true));
+ }
+}
+
} // namespace test
} // namespace folly
#include <system_error>
#include <boost/algorithm/string.hpp>
+#include <folly/Memory.h>
#include <glog/logging.h>
#include <gtest/gtest.h>
}
}
+class EnvVarSaverTest : public testing::Test {};
+
+TEST_F(EnvVarSaverTest, ExampleNew) {
+ auto key = "hahahahaha";
+ EXPECT_EQ(nullptr, getenv(key));
+
+ auto saver = make_unique<EnvVarSaver>();
+ PCHECK(0 == setenv(key, "blah", true));
+ EXPECT_EQ("blah", std::string{getenv(key)});
+ saver = nullptr;
+ EXPECT_EQ(nullptr, getenv(key));
+}
+
+TEST_F(EnvVarSaverTest, ExampleExisting) {
+ auto key = "USER";
+ EXPECT_NE(nullptr, getenv(key));
+ auto value = std::string{getenv(key)};
+
+ auto saver = make_unique<EnvVarSaver>();
+ PCHECK(0 == setenv(key, "blah", true));
+ EXPECT_EQ("blah", std::string{getenv(key)});
+ saver = nullptr;
+ EXPECT_TRUE(value == getenv(key));
+}
+
+TEST_F(EnvVarSaverTest, ExampleDeleting) {
+ auto key = "USER";
+ EXPECT_NE(nullptr, getenv(key));
+ auto value = std::string{getenv(key)};
+
+ auto saver = make_unique<EnvVarSaver>();
+ PCHECK(0 == unsetenv(key));
+ EXPECT_EQ(nullptr, getenv(key));
+ saver = nullptr;
+ EXPECT_TRUE(value == getenv(key));
+}
+
int main(int argc, char *argv[]) {
testing::InitGoogleTest(&argc, argv);
gflags::ParseCommandLineFlags(&argc, &argv, true);