2265e514f6f5844b2ae934ecbe62d4c3d6bd754b
[folly.git] / folly / experimental / test / EnvUtilTest.cpp
1 /*
2  * Copyright 2017 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <folly/experimental/EnvUtil.h>
18
19 #include <system_error>
20
21 #include <boost/algorithm/string.hpp>
22 #include <glog/logging.h>
23
24 #include <folly/Memory.h>
25 #include <folly/portability/Fcntl.h>
26 #include <folly/portability/GTest.h>
27 #include <folly/portability/Stdlib.h>
28
29 using namespace folly;
30 using namespace folly::test;
31
32 class EnvVarSaverTest : public testing::Test {};
33
34 TEST_F(EnvVarSaverTest, ExampleNew) {
35   auto key = "hahahahaha";
36   EXPECT_EQ(nullptr, getenv(key));
37
38   PCHECK(0 == setenv(key, "", true));
39   EXPECT_STREQ("", getenv(key));
40   PCHECK(0 == unsetenv(key));
41   EXPECT_EQ(nullptr, getenv(key));
42
43   auto saver = make_unique<EnvVarSaver>();
44   PCHECK(0 == setenv(key, "blah", true));
45   EXPECT_EQ("blah", std::string{getenv(key)});
46   saver = nullptr;
47   EXPECT_EQ(nullptr, getenv(key));
48 }
49
50 TEST_F(EnvVarSaverTest, ExampleExisting) {
51   auto key = "PATH";
52   EXPECT_NE(nullptr, getenv(key));
53   auto value = std::string{getenv(key)};
54
55   auto saver = make_unique<EnvVarSaver>();
56   PCHECK(0 == setenv(key, "blah", true));
57   EXPECT_EQ("blah", std::string{getenv(key)});
58   saver = nullptr;
59   EXPECT_TRUE(value == getenv(key));
60 }
61
62 TEST_F(EnvVarSaverTest, ExampleDeleting) {
63   auto key = "PATH";
64   EXPECT_NE(nullptr, getenv(key));
65   auto value = std::string{getenv(key)};
66
67   auto saver = make_unique<EnvVarSaver>();
68   PCHECK(0 == unsetenv(key));
69   EXPECT_EQ(nullptr, getenv(key));
70   saver = nullptr;
71   EXPECT_TRUE(value == getenv(key));
72 }