scoped_set_env_test.cc
Go to the documentation of this file.
1 // Copyright 2019 The Abseil Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #ifdef _WIN32
16 #include <windows.h>
17 #endif
18 
19 #include "gtest/gtest.h"
21 
22 namespace {
23 
25 
26 std::string GetEnvVar(const char* name) {
27 #ifdef _WIN32
28  char buf[1024];
29  auto get_res = GetEnvironmentVariableA(name, buf, sizeof(buf));
30  if (get_res >= sizeof(buf)) {
31  return "TOO_BIG";
32  }
33 
34  if (get_res == 0) {
35  return "UNSET";
36  }
37 
38  return std::string(buf, get_res);
39 #else
40  const char* val = ::getenv(name);
41  if (val == nullptr) {
42  return "UNSET";
43  }
44 
45  return val;
46 #endif
47 }
48 
49 TEST(ScopedSetEnvTest, SetNonExistingVarToString) {
50  EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "UNSET");
51 
52  {
53  ScopedSetEnv scoped_set("SCOPED_SET_ENV_TEST_VAR", "value");
54 
55  EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "value");
56  }
57 
58  EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "UNSET");
59 }
60 
61 TEST(ScopedSetEnvTest, SetNonExistingVarToNull) {
62  EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "UNSET");
63 
64  {
65  ScopedSetEnv scoped_set("SCOPED_SET_ENV_TEST_VAR", nullptr);
66 
67  EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "UNSET");
68  }
69 
70  EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "UNSET");
71 }
72 
73 TEST(ScopedSetEnvTest, SetExistingVarToString) {
74  ScopedSetEnv scoped_set("SCOPED_SET_ENV_TEST_VAR", "value");
75  EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "value");
76 
77  {
78  ScopedSetEnv scoped_set("SCOPED_SET_ENV_TEST_VAR", "new_value");
79 
80  EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "new_value");
81  }
82 
83  EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "value");
84 }
85 
86 TEST(ScopedSetEnvTest, SetExistingVarToNull) {
87  ScopedSetEnv scoped_set("SCOPED_SET_ENV_TEST_VAR", "value");
88  EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "value");
89 
90  {
91  ScopedSetEnv scoped_set("SCOPED_SET_ENV_TEST_VAR", nullptr);
92 
93  EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "UNSET");
94  }
95 
96  EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "value");
97 }
98 
99 } // namespace
char buf[N]
char name[1]
Definition: mutex.cc:296
TEST(Symbolize, Unimplemented)


abseil_cpp
Author(s):
autogenerated on Wed Jun 19 2019 19:19:57