test: Mock out interface lookups
This will make it possible to do interface lookups inside of our classes
during testing without depending on real interfaces existing.
Change-Id: I4c273d6961fa4229401fb25a0e5eb06af5b59ca4
Signed-off-by: William A. Kennington III <wak@google.com>
diff --git a/test/mock_syscall.cpp b/test/mock_syscall.cpp
index 28ebed2..d6338c5 100644
--- a/test/mock_syscall.cpp
+++ b/test/mock_syscall.cpp
@@ -5,6 +5,11 @@
#include <sys/socket.h>
#include <sys/types.h>
+#include <cstring>
+#include <map>
+#include <stdexcept>
+#include <string>
+
#define MAX_IFADDRS 5
int debugging = false;
@@ -28,6 +33,20 @@
return;
}
+std::map<std::string, int> mock_if_nametoindex;
+std::map<int, std::string> mock_if_indextoname;
+
+void mock_addIF(const std::string& name, int idx)
+{
+ if (idx == 0)
+ {
+ throw std::invalid_argument("Bad interface index");
+ }
+
+ mock_if_nametoindex[name] = idx;
+ mock_if_indextoname[idx] = name;
+}
+
void mock_addIP(const char* name, const char* addr, const char* mask,
unsigned int flags)
{
@@ -66,3 +85,30 @@
return -1;
return (0);
}
+
+unsigned if_nametoindex(const char* ifname)
+{
+ auto it = mock_if_nametoindex.find(ifname);
+ if (it == mock_if_nametoindex.end())
+ {
+ errno = ENXIO;
+ return 0;
+ }
+ return it->second;
+}
+
+char* if_indextoname(unsigned ifindex, char* ifname)
+{
+ if (ifindex == 0)
+ {
+ errno = ENXIO;
+ return NULL;
+ }
+ auto it = mock_if_indextoname.find(ifindex);
+ if (it == mock_if_indextoname.end())
+ {
+ // TODO: Return ENXIO once other code is mocked out
+ return std::strcpy(ifname, "invalid");
+ }
+ return std::strcpy(ifname, it->second.c_str());
+}