Merge branch 'tizen' into security-manager
[platform/core/test/security-tests.git] / src / common / tests_common.cpp
index 3095243..2332abb 100644 (file)
@@ -22,6 +22,7 @@
  */
 
 #include "tests_common.h"
+#include <fcntl.h>
 #include <sys/mman.h>
 #include <sys/stat.h>
 #include <sys/types.h>
@@ -173,3 +174,63 @@ int files_compare(int fd1, int fd2)
 
     return result;
 }
+
+void mkdirSafe(const std::string &path, mode_t mode)
+{
+    RUNNER_ASSERT_ERRNO_MSG(0 == mkdir(path.c_str(), mode) || errno == EEXIST,
+                            "mkdir for <" << path << "> with mode <" << mode << "> failed");
+}
+
+void mktreeSafe(const std::string &path, mode_t mode)
+{
+    // Create subsequent parent directories
+    // Assume that path is absolute - i.e. starts with '/'
+    for (size_t pos = 0; (pos = path.find("/", pos + 1)) != std::string::npos; )
+        mkdirSafe(path.substr(0, pos).c_str(), mode);
+
+    mkdirSafe(path, mode);
+}
+
+void creatSafe(const std::string &path, mode_t mode)
+{
+    RUNNER_ASSERT_ERRNO_MSG(-1 != creat(path.c_str(), mode),
+                            "creat for <" << path << "> with mode <" << mode << "> failed");
+}
+
+void symlinkSafe(const std::string &targetPath, const std::string &linkPath)
+{
+    RUNNER_ASSERT_ERRNO_MSG(0 == symlink(targetPath.c_str(), linkPath.c_str()),
+                            "symlink for <" << linkPath << "> to <" << targetPath << "> failed");
+}
+
+void removeDir(const std::string &path)
+{
+    DIR *d = opendir(path.c_str());
+
+    if (nullptr == d) {
+        RUNNER_ASSERT_ERRNO_MSG(errno == ENOENT, "opendir of <" << path << "> failed");
+        return;
+    }
+
+    struct dirent *dirEntry;
+    while (nullptr != (dirEntry = readdir(d))) {
+        std::string entryName(dirEntry->d_name);
+        if (entryName == "." || entryName == "..")
+            continue;
+
+        std::string entryPath(path + "/" + entryName);
+        struct stat st;
+
+        RUNNER_ASSERT_ERRNO_MSG(0 == lstat(entryPath.c_str(), &st),
+                                "stat for <" << entryPath << "> failed");
+        if (S_ISDIR(st.st_mode))
+            removeDir(entryPath);
+        else
+            RUNNER_ASSERT_ERRNO_MSG(0 == unlink(entryPath.c_str()),
+                                    "unlink for <" << entryPath << "> failed");
+    }
+
+    closedir(d);
+
+    RUNNER_ASSERT_ERRNO_MSG(0 == rmdir(path.c_str()), "rmdir for <" << path << "> failed");
+}