Rework envMock
Instead of mocking all the functions, only mock std::getenv.
Now each test only needs to provide an EnvImpl that delegate calls to
mockEnv in order to inject dependencies on std::getenv. This for several
reasons:
1. Any call to env::getEnv() will be calling the real implementation of
the C++ code, and testing real code is better than testing mocks.
2. It is easier to write a fake class that takes a config string which
can greatly simplify test cases.
3. We can now write unit tests that ensure the number of times
std::getenv gets called (should be once, but multiple times right now).
Tested: unit tests still pass
Signed-off-by: Kun Yi <kunyi731@gmail.com>
Change-Id: I3e5aff7fa5d025de1b8ae798af43b97d31151ab9
diff --git a/env.cpp b/env.cpp
index 8dbb679..318009f 100644
--- a/env.cpp
+++ b/env.cpp
@@ -16,64 +16,18 @@
#include "env.hpp"
-#include "hwmon.hpp"
-
#include <cstdlib>
-#include <fstream>
+#include <string>
namespace env
{
-std::string getEnv(const char* key)
+const char* EnvImpl::get(const char* key) const
{
- auto value = std::getenv(key);
- return (value) ? std::string(value) : std::string();
+ return std::getenv(key);
}
-std::string getEnv(const char* prefix, const SensorSet::key_type& sensor)
-{
- std::string key;
-
- key.assign(prefix);
- key.append(1, '_');
- key.append(sensor.first);
- key.append(sensor.second);
-
- return getEnv(key.c_str());
-}
-
-std::string getEnv(const char* prefix, const std::string& type,
- const std::string& id)
-{
- SensorSet::key_type sensor{type, id};
- return getEnv(prefix, sensor);
-}
-
-std::string getIndirectID(std::string path, const std::string& fileSuffix,
- const SensorSet::key_type& sensor)
-{
- std::string content;
-
- path.append(sensor.first);
- path.append(sensor.second);
- path.append(1, '_');
- path.append(fileSuffix);
-
- std::ifstream handle(path.c_str());
- if (!handle.fail())
- {
- content.assign((std::istreambuf_iterator<char>(handle)),
- (std::istreambuf_iterator<char>()));
-
- if (!content.empty())
- {
- // remove the newline
- content.pop_back();
- }
- }
-
- return content;
-}
+EnvImpl env_impl;
} // namespace env