move calls to cstdlib::getenv to env::getEnv
Wrapped the cstdlib::getenv() call into env::getEnv
so that it can be tested by mocking the env namespace,
by just dropping in test_env.cpp which implements those
methods and tying them a singleton upon which we can set
expectations.
Note: regardless of the approach taken to mock this, wrapping
this method is a good fix.
Change-Id: I65d22da08fc3dd76e6860f728c54e6c847ed07de
Signed-off-by: Patrick Venture <venture@google.com>
diff --git a/env.cpp b/env.cpp
index 09dd985..6841987 100644
--- a/env.cpp
+++ b/env.cpp
@@ -22,23 +22,23 @@
namespace env {
+std::string getEnv(const char* key)
+{
+ auto value = std::getenv(key);
+ return (value) ? std::string(value) : std::string();
+}
+
std::string getEnv(
const char* prefix, const SensorSet::key_type& sensor)
{
std::string key;
- std::string value;
key.assign(prefix);
key.append(1, '_');
key.append(sensor.first);
key.append(sensor.second);
- auto env = getenv(key.c_str());
- if (env)
- {
- value.assign(env);
- }
- return value;
+ return getEnv(key.c_str());
}
std::string getEnv(
diff --git a/env.hpp b/env.hpp
index 50a9fdb..fa23888 100644
--- a/env.hpp
+++ b/env.hpp
@@ -8,6 +8,16 @@
/** @brief Reads an environment variable
*
+ * Reads the environment for that key
+ *
+ * @param[in] key - the key
+ *
+ * @return string - the env var value
+ */
+std::string getEnv(const char* key);
+
+/** @brief Reads an environment variable
+ *
* Reads <prefix>_<sensor.first><sensor.second>
*
* @param[in] prefix - the variable prefix
diff --git a/mainloop.cpp b/mainloop.cpp
index 99c8020..37c2316 100644
--- a/mainloop.cpp
+++ b/mainloop.cpp
@@ -287,8 +287,8 @@
{
// Get list of return codes for removing sensors on device
std::string deviceRmRCs;
- auto devRmRCs = getenv("REMOVERCS");
- if (devRmRCs)
+ auto devRmRCs = env::getEnv("REMOVERCS");
+ if (!devRmRCs.empty())
{
deviceRmRCs.assign(devRmRCs);
}
@@ -534,10 +534,10 @@
}
{
- auto interval = getenv("INTERVAL");
- if (interval)
+ auto interval = env::getEnv("INTERVAL");
+ if (!interval.empty())
{
- _interval = strtoull(interval, NULL, 10);
+ _interval = strtoull(interval.c_str(), NULL, 10);
}
}
}
diff --git a/targets.hpp b/targets.hpp
index fe256a3..02bdd4f 100644
--- a/targets.hpp
+++ b/targets.hpp
@@ -103,8 +103,8 @@
if (fs::exists(sysfsFullPath))
{
auto useTarget = true;
- auto tmEnv = getenv("TARGET_MODE");
- if (tmEnv)
+ auto tmEnv = env::getEnv("TARGET_MODE");
+ if (!tmEnv.empty())
{
std::string mode{tmEnv};
std::transform(mode.begin(), mode.end(), mode.begin(), toupper);