From 94f867944d0f36ad77a488ab35f5555bf3c09c01 Mon Sep 17 00:00:00 2001
From: xuxuepeng <xuxuepeng1@huawei.com>
Date: Fri, 14 Feb 2025 14:48:25 +0800
Subject: [PATCH 195/198] Add some unit tests for sandbox and shim controller

Signed-off-by: xuxuepeng <xuxuepeng1@huawei.com>
---
 src/daemon/sandbox/sandbox.h                  |   2 +-
 .../shim/controller/shim_controller.cc        |   5 +
 test/sandbox/controller/shim/CMakeLists.txt   |   2 +
 .../controller/shim/shim_controller_ut.cc     | 123 +++++++++++++++++-
 test/sandbox/sandbox/CMakeLists.txt           |   5 +
 test/sandbox/sandbox/sandbox_ut.cc            |  64 ++++++++-
 6 files changed, 196 insertions(+), 5 deletions(-)

diff --git a/src/daemon/sandbox/sandbox.h b/src/daemon/sandbox/sandbox.h
index 9007ea16..0aeec826 100644
--- a/src/daemon/sandbox/sandbox.h
+++ b/src/daemon/sandbox/sandbox.h
@@ -118,6 +118,7 @@ public:
     auto UpdateStatsInfo(const StatsInfo &info) -> StatsInfo;
     void SetNetworkReady(bool ready);
     void SetNetworkMode(const std::string &networkMode);
+    void SetSandboxConfig(const runtime::v1::PodSandboxConfig &config);
     auto FindAvailableVsockPort(uint32_t &port) -> bool;
     void ReleaseVsockPort(uint32_t port);
     auto CleanupSandboxFiles(Errors &error) -> bool;
@@ -162,7 +163,6 @@ private:
     auto LoadMetadata(Errors &error) -> bool;
     void LoadNetworkSetting();
 
-    void SetSandboxConfig(const runtime::v1::PodSandboxConfig &config);
     void SetNetworkSettings(const std::string &settings, Errors &error);
     auto CreateHostname(bool shareHost, Errors &error) -> bool;
     auto CreateHosts(bool shareHost, Errors &error) -> bool;
diff --git a/src/daemon/sandbox/shim/controller/shim_controller.cc b/src/daemon/sandbox/shim/controller/shim_controller.cc
index 7e4338f6..563a2f3d 100644
--- a/src/daemon/sandbox/shim/controller/shim_controller.cc
+++ b/src/daemon/sandbox/shim/controller/shim_controller.cc
@@ -289,6 +289,11 @@ bool ShimController::Create(const std::string &sandboxId,
 
 std::unique_ptr<ControllerSandboxInfo> ShimController::Start(const std::string &sandboxId, Errors &error)
 {
+    if (m_cb == nullptr || m_cb->container.start == nullptr) {
+        ERROR("Unimplemented callback");
+        error.SetError("Unimplemented callback");
+        return nullptr;
+    }
     std::unique_ptr<ControllerSandboxInfo> sandboxInfo(new ControllerSandboxInfo());
     auto requestWrapper = makeUniquePtrCStructWrapper<container_start_request>(free_container_start_request);
     if (requestWrapper == nullptr) {
diff --git a/test/sandbox/controller/shim/CMakeLists.txt b/test/sandbox/controller/shim/CMakeLists.txt
index 069312c9..18f989f1 100644
--- a/test/sandbox/controller/shim/CMakeLists.txt
+++ b/test/sandbox/controller/shim/CMakeLists.txt
@@ -28,6 +28,7 @@ add_executable(${EXE}
 
 target_include_directories(${EXE} PUBLIC
     ${GTEST_INCLUDE_DIR}
+    ${CMAKE_CURRENT_SOURCE_DIR}/../../../include
     ${CMAKE_CURRENT_SOURCE_DIR}/../../../../src/daemon/common
     ${CMAKE_CURRENT_SOURCE_DIR}/../../../../src/daemon/common/cri
     ${CMAKE_CURRENT_SOURCE_DIR}/../../../../src/daemon/common/cri/v1
@@ -52,6 +53,7 @@ target_include_directories(${EXE} PUBLIC
     ${CMAKE_BINARY_DIR}/grpc/src/api/services/cri/v1
 )
 
+set_target_properties(${EXE} PROPERTIES LINK_FLAGS "-Wl,--wrap,isula_common_calloc_s")
 target_link_libraries(${EXE} ${GTEST_BOTH_LIBRARIES} ${GMOCK_LIBRARY} ${GMOCK_MAIN_LIBRARY} ${CMAKE_THREAD_LIBS_INIT} ${ISULA_LIBUTILS_LIBRARY} libutils_ut -lgrpc++ -lprotobuf -lcrypto -lyajl -lz)
 target_link_libraries(${EXE} -Wl,--as-needed ${ISULAD_ABSL_USED_TARGETS})
 add_test(NAME ${EXE} COMMAND ${EXE} --gtest_output=xml:${EXE}-Results.xml)
diff --git a/test/sandbox/controller/shim/shim_controller_ut.cc b/test/sandbox/controller/shim/shim_controller_ut.cc
index 75a51797..d85a87b2 100644
--- a/test/sandbox/controller/shim/shim_controller_ut.cc
+++ b/test/sandbox/controller/shim/shim_controller_ut.cc
@@ -21,6 +21,12 @@
 #include "image_api_mock.h"
 #include "service_container_api_mock.h"
 #include "shim_controller.h"
+#include "mock.h"
+
+extern "C" {
+    DECLARE_WRAPPER(isula_common_calloc_s, void *, (size_t size));
+    DEFINE_WRAPPER(isula_common_calloc_s, void *, (size_t size), (size));
+}
 
 class ShimControllerTest : public testing::Test {
 protected:
@@ -76,6 +82,32 @@ TEST_F(ShimControllerTest, CreateTestFailed)
     EXPECT_FALSE(m_contoller->Create(DUMMY_SANDBOX_ID, *params, err));
 }
 
+TEST_F(ShimControllerTest, CreateTestContainerCallbackNullPtrError)
+{
+    Errors err;
+    std::unique_ptr<sandbox::ControllerCreateParams> params = CreateTestCreateParams();
+    // shim controller create needs linux config.
+    (void)params->config->mutable_linux();
+    (void)params->config->mutable_linux()->mutable_resources();
+    auto callback = get_service_executor();
+    auto tmp_create = callback->container.create;
+    callback->container.create = nullptr;
+    EXPECT_FALSE(m_contoller->Create(DUMMY_SANDBOX_ID, *params, err));
+    callback->container.create = tmp_create;
+}
+
+TEST_F(ShimControllerTest, CreateTestContainerCallocError)
+{
+    Errors err;
+    std::unique_ptr<sandbox::ControllerCreateParams> params = CreateTestCreateParams();
+    // shim controller create needs linux config.
+    (void)params->config->mutable_linux();
+    (void)params->config->mutable_linux()->mutable_resources();
+    MOCK_SET(isula_common_calloc_s, nullptr);
+    EXPECT_FALSE(m_contoller->Create(DUMMY_SANDBOX_ID, *params, err));
+    MOCK_CLEAR(isula_common_calloc_s);
+}
+
 /************* Unit tests for Start *************/
 TEST_F(ShimControllerTest, StartTestSucceed)
 {
@@ -99,7 +131,6 @@ TEST_F(ShimControllerTest, StartTestSucceed)
     EXPECT_EQ(ret->pid, 1234);
 }
 
-/************* Unit tests for Start *************/
 TEST_F(ShimControllerTest, StartTestFailed)
 {
     Errors err;
@@ -108,6 +139,24 @@ TEST_F(ShimControllerTest, StartTestFailed)
     EXPECT_EQ(ret, nullptr);
 }
 
+TEST_F(ShimControllerTest, StartTestContainerCallbackNullPtrError)
+{
+    Errors err;
+    auto callback = get_service_executor();
+    auto tmp_start = callback->container.start;
+    callback->container.start = nullptr;
+    EXPECT_FALSE(m_contoller->Start(DUMMY_SANDBOX_ID, err));
+    callback->container.start = tmp_start;
+}
+
+TEST_F(ShimControllerTest, StartTestContainerCallocError)
+{
+    Errors err;
+    MOCK_SET(isula_common_calloc_s, nullptr);
+    EXPECT_FALSE(m_contoller->Start(DUMMY_SANDBOX_ID, err));
+    MOCK_CLEAR(isula_common_calloc_s);
+}
+
 /************* Unit tests for Stop *************/
 TEST_F(ShimControllerTest, StopTestSucceed)
 {
@@ -123,6 +172,24 @@ TEST_F(ShimControllerTest, StopTestFailed)
     EXPECT_FALSE(m_contoller->Stop(DUMMY_SANDBOX_ID, 0, err));
 }
 
+TEST_F(ShimControllerTest, StopTestContainerCallbackNullPtrError)
+{
+    Errors err;
+    auto callback = get_service_executor();
+    auto tmp_stop = callback->container.stop;
+    callback->container.stop = nullptr;
+    EXPECT_FALSE(m_contoller->Stop(DUMMY_SANDBOX_ID, 0, err));
+    callback->container.stop = tmp_stop;
+}
+
+TEST_F(ShimControllerTest, StopTestContainerCallocError)
+{
+    Errors err;
+    MOCK_SET(isula_common_calloc_s, nullptr);
+    EXPECT_FALSE(m_contoller->Stop(DUMMY_SANDBOX_ID, 0, err));
+    MOCK_CLEAR(isula_common_calloc_s);
+}
+
 /************* Unit tests for Status *************/
 TEST_F(ShimControllerTest, StatusTestSucceed)
 {
@@ -167,3 +234,57 @@ TEST_F(ShimControllerTest, ShutdownTestFailed)
     EXPECT_CALL(*m_containerCallbackMock, ContainerRemove).Times(1).WillOnce(testing::Return(1));
     EXPECT_FALSE(m_contoller->Shutdown(DUMMY_SANDBOX_ID, err));
 }
+
+TEST_F(ShimControllerTest, ShutdownTestContainerCallbackNullPtrError)
+{
+    Errors err;
+    auto callback = get_service_executor();
+    auto tmp_remove = callback->container.remove;
+    callback->container.remove = nullptr;
+    EXPECT_FALSE(m_contoller->Shutdown(DUMMY_SANDBOX_ID, err));
+    callback->container.remove = tmp_remove;
+}
+
+TEST_F(ShimControllerTest, ShutdownTestContainerCallocError)
+{
+    Errors err;
+    MOCK_SET(isula_common_calloc_s, nullptr);
+    EXPECT_FALSE(m_contoller->Shutdown(DUMMY_SANDBOX_ID, err));
+    MOCK_CLEAR(isula_common_calloc_s);
+}
+
+/*********** Unit tests for Platform ***********/
+TEST_F(ShimControllerTest, PlatformTestSucceed)
+{
+    Errors err;
+    // Not support yet
+    std::unique_ptr<sandbox::ControllerPlatformInfo> ret = m_contoller->Platform(DUMMY_SANDBOX_ID, err);
+    EXPECT_EQ(ret, nullptr);
+}
+
+/*********** Unit tests for Update ***********/
+TEST_F(ShimControllerTest, UpdateTestSucceed)
+{
+    Errors err;
+    // Shim Controller update is always true
+    EXPECT_TRUE(m_contoller->Update(nullptr, nullptr, err));
+}
+
+/*********** Unit tests for UpdateNetworkSettings ***********/
+TEST_F(ShimControllerTest, UpdateNetworkSettingsTestCallbackNullPtrError)
+{
+    Errors err;
+    auto callback = get_service_executor();
+    auto tmp_update_network_settings = callback->container.update_network_settings;
+    callback->container.update_network_settings = nullptr;
+    EXPECT_FALSE(m_contoller->UpdateNetworkSettings(DUMMY_SANDBOX_ID, "networkSettings", err));
+    callback->container.update_network_settings = tmp_update_network_settings;
+}
+
+TEST_F(ShimControllerTest, UpdateNetworkSettingsTestContainerCallocError)
+{
+    Errors err;
+    MOCK_SET(isula_common_calloc_s, nullptr);
+    EXPECT_FALSE(m_contoller->UpdateNetworkSettings(DUMMY_SANDBOX_ID, "networkSettings", err));
+    MOCK_CLEAR(isula_common_calloc_s);
+}
diff --git a/test/sandbox/sandbox/CMakeLists.txt b/test/sandbox/sandbox/CMakeLists.txt
index 358633dc..3a249f90 100644
--- a/test/sandbox/sandbox/CMakeLists.txt
+++ b/test/sandbox/sandbox/CMakeLists.txt
@@ -29,7 +29,9 @@ add_executable(${EXE}
     ${CMAKE_CURRENT_SOURCE_DIR}/../../../src/utils/cpputils/transform.cc
     ${CMAKE_CURRENT_SOURCE_DIR}/../../../src/utils/cpputils/cxxutils.cc
     ${CMAKE_CURRENT_SOURCE_DIR}/../../../src/daemon/sandbox/sandbox.cc
+    ${CMAKE_CURRENT_SOURCE_DIR}/../../../src/daemon/sandbox/sandbox_ops.cc
     ${CMAKE_CURRENT_SOURCE_DIR}/../../../src/daemon/sandbox/controller_manager.cc
+    ${CMAKE_CURRENT_SOURCE_DIR}/../../../src/daemon/sandbox/sandbox_manager.cc
     ${CMAKE_CURRENT_SOURCE_DIR}/../../../src/daemon/common/id_name_manager.c
     ${CMAKE_CURRENT_SOURCE_DIR}/../../../src/daemon/config/isulad_config.c
     ${CMAKE_CURRENT_SOURCE_DIR}/../../../test/sandbox/controller/controller_common.cc
@@ -43,6 +45,7 @@ target_include_directories(${EXE} PUBLIC
     ${GTEST_INCLUDE_DIR}
     ${sandbox_dir}
     ${CMAKE_CURRENT_SOURCE_DIR}/../../../test/mocks
+    ${CMAKE_CURRENT_SOURCE_DIR}/../../include
     ${CMAKE_CURRENT_SOURCE_DIR}/../../../src/daemon/common
     ${CMAKE_CURRENT_SOURCE_DIR}/../../../src/daemon/config
     ${CMAKE_CURRENT_SOURCE_DIR}/../../../src/daemon/entry/cri
@@ -54,10 +57,12 @@ target_include_directories(${EXE} PUBLIC
     ${CMAKE_CURRENT_SOURCE_DIR}/../../../src/daemon/sandbox
     ${CMAKE_CURRENT_SOURCE_DIR}/../../../src/daemon/common
     ${CMAKE_CURRENT_SOURCE_DIR}/../../../src/utils/cpputils
+    ${CMAKE_CURRENT_SOURCE_DIR}/../../../src/utils/cutils
     ${CMAKE_BINARY_DIR}/grpc/src/api/services/cri
     ${CMAKE_BINARY_DIR}/grpc/src/api/services/cri/v1
 )
 
+set_target_properties(${EXE} PROPERTIES LINK_FLAGS "-Wl,--wrap,util_file_exists -Wl,--wrap,mount")
 target_link_libraries(${EXE} ${GTEST_BOTH_LIBRARIES} ${GMOCK_LIBRARY} ${GMOCK_MAIN_LIBRARY} ${CMAKE_THREAD_LIBS_INIT} ${ISULA_LIBUTILS_LIBRARY} libutils_ut -lgrpc -lgrpc++ -lprotobuf -lcrypto -lyajl -lz)
 target_link_libraries(${EXE} -Wl,--as-needed ${ISULAD_ABSL_USED_TARGETS})
 add_test(NAME ${EXE} COMMAND ${EXE} --gtest_output=xml:${EXE}-Results.xml)
diff --git a/test/sandbox/sandbox/sandbox_ut.cc b/test/sandbox/sandbox/sandbox_ut.cc
index dd84d8fb..7534d67a 100644
--- a/test/sandbox/sandbox/sandbox_ut.cc
+++ b/test/sandbox/sandbox/sandbox_ut.cc
@@ -14,8 +14,22 @@
  */
 
 #include <gtest/gtest.h>
-
+#include <fstream>
 #include "sandbox.h"
+#include "sandbox_ops.h"
+#include "mock.h"
+#include "utils_file.h"
+
+extern "C" {
+    DECLARE_WRAPPER(util_file_exists, bool, (const char * path));
+    DEFINE_WRAPPER(util_file_exists, bool, (const char * path), (path));
+    DECLARE_WRAPPER(mount, int, (const char *__special_file, const char *__dir,
+		  const char *__fstype, unsigned long int __rwflag,
+		  const void *__data));
+    DEFINE_WRAPPER(mount, int, (const char *__special_file, const char *__dir,
+		  const char *__fstype, unsigned long int __rwflag,
+		  const void *__data), (__special_file, __dir, __fstype, __rwflag, __data));
+}
 
 namespace sandbox {
 
@@ -39,8 +53,10 @@ TEST_F(SandboxTest, TestDefaultGetters)
     std::string sandbox_statedir = statedir + "/" + id;
     std::string name = "test";
     RuntimeInfo info = {"runc", "shim", "kuasar"};
+    std::shared_ptr<runtime::v1::PodSandboxConfig> pod_config = std::make_shared<runtime::v1::PodSandboxConfig>();
+    pod_config->set_hostname("test");
 
-    auto sandbox = new Sandbox(id, rootdir, statedir, name, info);
+    auto sandbox = std::unique_ptr<Sandbox>(new Sandbox(id, rootdir, statedir, name, info));
     ASSERT_NE(sandbox, nullptr);
 
     ASSERT_EQ(sandbox->IsReady(), false);
@@ -57,6 +73,8 @@ TEST_F(SandboxTest, TestDefaultGetters)
     ASSERT_EQ(sandbox->GetStatsInfo().cpuUseNanos, 0);
     ASSERT_EQ(sandbox->GetNetworkReady(), false);
     ASSERT_STREQ(sandbox->GetNetMode().c_str(), DEFAULT_NETMODE.c_str());
+    sandbox->SetSandboxConfig(*pod_config);
+    ASSERT_STREQ(sandbox->GetMutableSandboxConfig()->hostname().c_str(), pod_config->hostname().c_str());
 }
 
 TEST_F(SandboxTest, TestGettersAndSetters)
@@ -66,7 +84,7 @@ TEST_F(SandboxTest, TestGettersAndSetters)
     std::string statedir = "/test2/statedir";
     std::string mode = "host";
 
-    auto sandbox = new Sandbox(id, rootdir, statedir);
+    auto sandbox = std::unique_ptr<Sandbox>(new Sandbox(id, rootdir, statedir));
     ASSERT_NE(sandbox, nullptr);
 
     sandbox->SetNetMode(mode);
@@ -93,4 +111,44 @@ TEST_F(SandboxTest, TestGettersAndSetters)
     EXPECT_TRUE(sandbox->GetNetworkReady());
 }
 
+TEST_F(SandboxTest, TestCreateDefaultResolveConf)
+{
+    std::string id = "34567890";
+    std::string rootdir = "/tmp/test3/rootdir";
+    std::string statedir = "/tmp/test3/statedir";
+    std::string name = "test";
+    RuntimeInfo info = {"runc", "shim", "kuasar"};
+    std::string host_nework = "host";
+    Errors error;
+
+    auto sandbox = std::unique_ptr<Sandbox>(new Sandbox(id, rootdir, statedir, name, info, host_nework));
+    ASSERT_NE(sandbox, nullptr);
+    MOCK_SET(util_file_exists, false);
+    MOCK_SET(mount, 0);
+    sandbox->PrepareSandboxDirs(error);
+    ASSERT_TRUE(error.Empty());
+    MOCK_CLEAR(util_file_exists);
+    MOCK_CLEAR(mount);
+    const std::string RESOLVE_CONF = "\nnameserver 8.8.8.8\nnameserver 8.8.4.4\n";
+    std::string RESOLVE_PATH = rootdir + "/" + id + "/resolv.conf";
+    ASSERT_TRUE(util_file_exists(RESOLVE_PATH.c_str()));
+    std::ifstream f(RESOLVE_PATH);
+    std::string line;
+    std::string content = "";
+    while (std::getline(f, line)) {
+        content += line;
+        content +="\n";
+    }
+    f.close();
+    ASSERT_STREQ(RESOLVE_CONF.c_str(), content.c_str());
+    sandbox->CleanupSandboxDirs();
+    ASSERT_FALSE(util_file_exists(RESOLVE_PATH.c_str()));
+}
+
+TEST_F(SandboxTest, TestSandboxOpsOnExitFailed)
+{
+    ASSERT_EQ(sandbox_on_sandbox_exit(nullptr, 0), -1);
+    ASSERT_EQ(sandbox_on_sandbox_exit("12345678", 0), -1);
+}
+
 }
\ No newline at end of file
-- 
2.34.1

