From 0b3b350ac6df71cd701440877a2720682f86dab0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A7=9C=E5=B0=8F=E6=9E=97?= Date: Fri, 22 Aug 2025 10:33:21 +0800 Subject: [PATCH 1/3] =?UTF-8?q?=E4=BF=AE=E5=A4=8Dwatcher=E6=8E=A5=E5=8F=A3?= =?UTF-8?q?=E5=B7=B2=E7=9F=A5bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Change-Id: Idf4a730352169da7a7f8f563c0c45b5208fa1ad1 Signed-off-by: 姜小林 --- .../mod_fs/class_watcher/fs_file_watcher.cpp | 88 ++- .../mod_fs/class_watcher/fs_file_watcher.h | 17 +- .../mod_fs/class_watcher/fs_watch_entity.h | 2 +- .../src/mod_fs/class_watcher/fs_watcher.cpp | 4 +- .../class_watcher/watcher_data_cache.cpp | 50 +- .../mod_fs/class_watcher/watcher_data_cache.h | 7 +- .../js/src/mod_fs/properties/watcher_core.cpp | 4 +- interfaces/test/unittest/js/BUILD.gn | 1 + .../fs_file_watcher_mock_test.cpp | 661 ++++++++++++++++-- .../class_watcher/fs_watcher_mock_test.cpp | 8 +- .../class_watcher/watcher_data_cache_test.cpp | 228 ++++++ .../unittest/js/mod_fs/mock/unistd_mock.cpp | 21 + .../unittest/js/mod_fs/mock/unistd_mock.h | 2 + .../properties/watcher_core_mock_test.cpp | 2 +- 14 files changed, 926 insertions(+), 169 deletions(-) create mode 100644 interfaces/test/unittest/js/mod_fs/class_watcher/watcher_data_cache_test.cpp diff --git a/interfaces/kits/js/src/mod_fs/class_watcher/fs_file_watcher.cpp b/interfaces/kits/js/src/mod_fs/class_watcher/fs_file_watcher.cpp index 0f5af1e1e..079e6cfb0 100644 --- a/interfaces/kits/js/src/mod_fs/class_watcher/fs_file_watcher.cpp +++ b/interfaces/kits/js/src/mod_fs/class_watcher/fs_file_watcher.cpp @@ -28,9 +28,10 @@ namespace OHOS::FileManagement::ModuleFileIO { using namespace std; -int32_t FsFileWatcher::GetNotifyId() +bool FsFileWatcher::TryInitNotify() { - return notifyFd_; + lock_guard lock(notifyMutex_); + return notifyFd_ >= 0 || InitNotify(); } bool FsFileWatcher::InitNotify() @@ -60,7 +61,7 @@ int32_t FsFileWatcher::StartNotify(shared_ptr info) return EIO; } - auto [isWatched, wd] = dataCache_.FindWatchedWd(info->fileName, info->events); + auto [isWatched, wd, events] = dataCache_.FindWatchedEvents(info->fileName, info->events); if (isWatched && wd > 0) { info->wd = wd; return ERRNO_NOERR; @@ -68,7 +69,7 @@ int32_t FsFileWatcher::StartNotify(shared_ptr info) uint32_t watchEvents = 0; if (wd != -1) { - watchEvents = dataCache_.GetFileEvents(info->fileName) | info->events; + watchEvents = events | info->events; } else { watchEvents = info->events; } @@ -107,6 +108,7 @@ int32_t FsFileWatcher::CloseNotifyFd() if (!dataCache_.HasWatcherInfo()) { run_ = false; + WakeupThread(); closeRet = close(notifyFd_); if (closeRet != 0) { HILOGE("Failed to stop notify close fd errCode:%{public}d", errno); @@ -118,7 +120,6 @@ int32_t FsFileWatcher::CloseNotifyFd() HILOGE("Failed to close eventfd errCode:%{public}d", errno); } eventFd_ = -1; - DestroyTaskThead(); } closed_ = false; @@ -127,13 +128,12 @@ int32_t FsFileWatcher::CloseNotifyFd() int32_t FsFileWatcher::CloseNotifyFdLocked() { - { - lock_guard lock(readMutex_); - closed_ = true; - if (reading_) { - HILOGE("Close while reading"); - return ERRNO_NOERR; - } + scoped_lock lock(readMutex_, notifyMutex_); + closed_ = true; + if (reading_) { + HILOGE("Close while reading"); + closed_ = false; + return ERRNO_NOERR; } return CloseNotifyFd(); } @@ -152,6 +152,7 @@ int32_t FsFileWatcher::StopNotify(shared_ptr info) uint32_t remainingEvents = RemoveWatcherInfo(info); if (remainingEvents > 0) { + // There are still events remaining to be listened for. if (access(info->fileName.c_str(), F_OK) == 0) { return NotifyToWatchNewEvents(info->fileName, info->wd, remainingEvents); } @@ -159,6 +160,7 @@ int32_t FsFileWatcher::StopNotify(shared_ptr info) return ERRNO_NOERR; } + // No events remain to be listened for, and proceed to the file watch removal process. int32_t oldWd = -1; { lock_guard lock(readMutex_); @@ -173,13 +175,13 @@ int32_t FsFileWatcher::StopNotify(shared_ptr info) int32_t rmErr = errno; if (access(info->fileName.c_str(), F_OK) == 0) { HILOGE("Failed to stop notify errCode:%{public}d", rmErr); - dataCache_.RemoveFileWatcher(info->fileName); + dataCache_.RemoveWatchedEvents(info->fileName); CloseNotifyFdLocked(); return rmErr; } } - dataCache_.RemoveFileWatcher(info->fileName); + dataCache_.RemoveWatchedEvents(info->fileName); return CloseNotifyFdLocked(); } @@ -189,6 +191,7 @@ void FsFileWatcher::ReadNotifyEvent() int32_t index = 0; char buf[BUF_SIZE] = { 0 }; struct inotify_event *event = nullptr; + int32_t eventSize = static_cast(sizeof(struct inotify_event)); do { len = read(notifyFd_, &buf, sizeof(buf)); @@ -200,8 +203,19 @@ void FsFileWatcher::ReadNotifyEvent() while (index < len) { event = reinterpret_cast(buf + index); + if ((len - index) < eventSize) { + HILOGE( + "out of bounds access, len:%{public}d, index: %{public}d, inotify: %{public}d", len, index, eventSize); + break; + } + if (event->len > (static_cast(len - index - eventSize))) { + HILOGE("out of bounds access, index: %{public}d, inotify: %{public}d, " + "event :%{public}u, len: %{public}d", + index, eventSize, event->len, len); + break; + } NotifyEvent(event); - index += sizeof(struct inotify_event) + static_cast(event->len); + index += eventSize + static_cast(event->len); } } @@ -215,11 +229,9 @@ void FsFileWatcher::ReadNotifyEventLocked() } reading_ = true; } - ReadNotifyEvent(); - { - lock_guard lock(readMutex_); + scoped_lock lock(readMutex_, notifyMutex_); reading_ = false; if (closed_) { HILOGE("Close after read"); @@ -231,10 +243,9 @@ void FsFileWatcher::ReadNotifyEventLocked() void FsFileWatcher::AsyncGetNotifyEvent() { - lock_guard lock(taskMutex_); - if (!taskRunning_) { - taskRunning_ = true; - taskThead_ = thread(&FsFileWatcher::GetNotifyEvent, this); + bool expected = false; + if (taskRunning_.compare_exchange_strong(expected, true)) { + taskThread_ = thread(&FsFileWatcher::GetNotifyEvent, this); } } @@ -271,7 +282,10 @@ void FsFileWatcher::GetNotifyEvent() HILOGE("Failed to poll NotifyFd, errno=%{public}d", errno); break; } + // Ignore cases where poll returns 0 (timeout) or EINTR (interrupted system call) } + DestroyTaskThread(); + HILOGD("The task has been completed."); } bool FsFileWatcher::AddWatcherInfo(shared_ptr info) @@ -301,7 +315,7 @@ void FsFileWatcher::NotifyEvent(const struct inotify_event *event) auto [matched, fileName, watcherInfos] = dataCache_.FindWatcherInfos(event->wd, event->mask); if (!matched) { - HILOGE("Cannot find matched watcherInfos"); + // ignore unmatched event return; } @@ -323,23 +337,27 @@ bool FsFileWatcher::CheckEventValid(uint32_t event) } } -void FsFileWatcher::DestroyTaskThead() +void FsFileWatcher::DestroyTaskThread() { - if (taskThead_.joinable()) { - if (taskThead_.get_id() != std::this_thread::get_id()) { - taskThead_.join(); - } else { - taskThead_.detach(); + bool expected = true; + if (taskRunning_.compare_exchange_strong(expected, false)) { + run_ = false; + dataCache_.ClearCache(); + + if (taskThread_.joinable()) { + taskThread_.detach(); } } +} - { - lock_guard lock(taskMutex_); - if (taskRunning_) { - taskRunning_ = false; - run_ = false; +void FsFileWatcher::WakeupThread() +{ + if (taskRunning_ && eventFd_ >= 0 && taskThread_.joinable()) { + uint64_t val = 1; + auto ret = write(eventFd_, &val, sizeof(val)); + if (ret != sizeof(val)) { + HILOGE("WakeupThread failed! errno: %{public}d", errno); } } - dataCache_.ClearCache(); } } // namespace OHOS::FileManagement::ModuleFileIO diff --git a/interfaces/kits/js/src/mod_fs/class_watcher/fs_file_watcher.h b/interfaces/kits/js/src/mod_fs/class_watcher/fs_file_watcher.h index 57b83d331..2a114cb13 100644 --- a/interfaces/kits/js/src/mod_fs/class_watcher/fs_file_watcher.h +++ b/interfaces/kits/js/src/mod_fs/class_watcher/fs_file_watcher.h @@ -33,11 +33,9 @@ constexpr int32_t BUF_SIZE = 1024; class FsFileWatcher : public Singleton { public: - int32_t GetNotifyId(); - bool InitNotify(); + bool TryInitNotify(); int32_t StartNotify(shared_ptr info); int32_t StopNotify(shared_ptr info); - void GetNotifyEvent(); void AsyncGetNotifyEvent(); bool AddWatcherInfo(shared_ptr info); bool CheckEventValid(uint32_t event); @@ -49,6 +47,8 @@ public: FsFileWatcher &operator=(const FsFileWatcher &) = delete; private: + bool InitNotify(); + void GetNotifyEvent(); uint32_t RemoveWatcherInfo(shared_ptr info); void NotifyEvent(const struct inotify_event *event); int32_t CloseNotifyFd(); @@ -56,18 +56,19 @@ private: int32_t NotifyToWatchNewEvents(const string &fileName, int32_t wd, uint32_t watchEvents); void ReadNotifyEvent(); void ReadNotifyEventLocked(); - void DestroyTaskThead(); + void DestroyTaskThread(); + void WakeupThread(); private: static constexpr int32_t pollTimeoutMs = 500; - mutex taskMutex_; mutex readMutex_; + mutex notifyMutex_; - atomic taskRunning_ = false; - thread taskThead_; + atomic taskRunning_ { false }; + thread taskThread_; - bool run_ = false; + atomic run_ { false }; bool reading_ = false; bool closed_ = false; int32_t notifyFd_ = -1; diff --git a/interfaces/kits/js/src/mod_fs/class_watcher/fs_watch_entity.h b/interfaces/kits/js/src/mod_fs/class_watcher/fs_watch_entity.h index 83184bb48..534c0fae8 100644 --- a/interfaces/kits/js/src/mod_fs/class_watcher/fs_watch_entity.h +++ b/interfaces/kits/js/src/mod_fs/class_watcher/fs_watch_entity.h @@ -43,7 +43,7 @@ struct WatcherInfo { }; struct FsWatchEntity { - std::shared_ptr watherInfo; + std::shared_ptr watcherInfo; }; } // namespace OHOS::FileManagement::ModuleFileIO diff --git a/interfaces/kits/js/src/mod_fs/class_watcher/fs_watcher.cpp b/interfaces/kits/js/src/mod_fs/class_watcher/fs_watcher.cpp index f761620fa..bc31ed3f9 100644 --- a/interfaces/kits/js/src/mod_fs/class_watcher/fs_watcher.cpp +++ b/interfaces/kits/js/src/mod_fs/class_watcher/fs_watcher.cpp @@ -48,7 +48,7 @@ FsResult FsWatcher::Stop() HILOGE("Failed to get watchEntity when stop."); return FsResult::Error(EINVAL); } - int ret = FsFileWatcher::GetInstance().StopNotify(watchEntity->watherInfo); + int ret = FsFileWatcher::GetInstance().StopNotify(watchEntity->watcherInfo); if (ret != ERRNO_NOERR) { HILOGE("Failed to stopNotify errno:%{public}d", errno); return FsResult::Error(ret); @@ -63,7 +63,7 @@ FsResult FsWatcher::Start() return FsResult::Error(EINVAL); } - shared_ptr info = watchEntity->watherInfo; + shared_ptr info = watchEntity->watcherInfo; int ret = FsFileWatcher::GetInstance().StartNotify(info); if (ret != ERRNO_NOERR) { HILOGE("Failed to startNotify."); diff --git a/interfaces/kits/js/src/mod_fs/class_watcher/watcher_data_cache.cpp b/interfaces/kits/js/src/mod_fs/class_watcher/watcher_data_cache.cpp index 83b5e2a51..03b63a1ae 100644 --- a/interfaces/kits/js/src/mod_fs/class_watcher/watcher_data_cache.cpp +++ b/interfaces/kits/js/src/mod_fs/class_watcher/watcher_data_cache.cpp @@ -30,7 +30,6 @@ bool WatcherDataCache::AddWatcherInfo(std::shared_ptr info) } } watcherInfoCache_.push_back(info); - wdFileNameCache_[info->fileName] = std::make_pair(info->wd, info->events); return true; } @@ -48,56 +47,39 @@ uint32_t WatcherDataCache::RemoveWatcherInfo(std::shared_ptr info) remainingEvents |= iter->events; } } - return remainingEvents; } -bool WatcherDataCache::RemoveFileWatcher(const std::string &fileName) +void WatcherDataCache::RemoveWatchedEvents(const std::string &fileName) { std::lock_guard lock(cacheMutex_); - - auto iter = wdFileNameCache_.find(fileName); - if (iter == wdFileNameCache_.end()) { - return false; - } - wdFileNameCache_.erase(iter); - - watcherInfoCache_.erase(std::remove_if(watcherInfoCache_.begin(), watcherInfoCache_.end(), - [&fileName](const std::shared_ptr &info) { - return info->fileName == fileName; - }), watcherInfoCache_.end()); - - return true; + wdFileNameCache_.erase(fileName); } -std::tuple WatcherDataCache::FindWatchedWd(const std::string &fileName, uint32_t event) +std::tuple WatcherDataCache::FindWatchedEvents(const std::string &fileName, uint32_t event) { std::lock_guard lock(cacheMutex_); int32_t wd = -1; + uint32_t events = 0; auto iter = wdFileNameCache_.find(fileName); if (iter == wdFileNameCache_.end()) { - return { false, wd }; + return { false, wd, events }; } wd = iter->second.first; - if ((iter->second.second & event) == event) { - return { true, wd }; + events = iter->second.second; + if ((iter->second.second & event) != event) { + return { false, wd, events }; } - return { false, wd }; + return { true, wd, events }; } -bool WatcherDataCache::UpdateWatchedEvents(const std::string &fileName, int32_t wd, uint32_t events) +void WatcherDataCache::UpdateWatchedEvents(const std::string &fileName, int32_t wd, uint32_t events) { std::lock_guard lock(cacheMutex_); - auto iter = wdFileNameCache_.find(fileName); - if (iter == wdFileNameCache_.end()) { - return false; - } - - iter->second = std::make_pair(wd, events); - return true; + wdFileNameCache_[fileName] = std::make_pair(wd, events); } static bool CheckIncludeEvent(uint32_t mask, uint32_t event) @@ -136,16 +118,6 @@ std::tuple>> Watcher return { !matchedInfos.empty(), fileName, matchedInfos }; } -uint32_t WatcherDataCache::GetFileEvents(const std::string &fileName) -{ - std::lock_guard lock(cacheMutex_); - auto iter = wdFileNameCache_.find(fileName); - if (iter == wdFileNameCache_.end()) { - return 0; - } - return iter->second.second; -} - bool WatcherDataCache::HasWatcherInfo() const { std::lock_guard lock(cacheMutex_); diff --git a/interfaces/kits/js/src/mod_fs/class_watcher/watcher_data_cache.h b/interfaces/kits/js/src/mod_fs/class_watcher/watcher_data_cache.h index e18d584f1..df6ac98a8 100644 --- a/interfaces/kits/js/src/mod_fs/class_watcher/watcher_data_cache.h +++ b/interfaces/kits/js/src/mod_fs/class_watcher/watcher_data_cache.h @@ -29,12 +29,11 @@ class WatcherDataCache { public: bool AddWatcherInfo(std::shared_ptr info); uint32_t RemoveWatcherInfo(std::shared_ptr info); - bool RemoveFileWatcher(const std::string &fileName); - std::tuple FindWatchedWd(const std::string &fileName, uint32_t event); - bool UpdateWatchedEvents(const std::string &fileName, int32_t wd, uint32_t events); + void RemoveWatchedEvents(const std::string &fileName); + std::tuple FindWatchedEvents(const std::string &fileName, uint32_t event); + void UpdateWatchedEvents(const std::string &fileName, int32_t wd, uint32_t events); std::tuple>> FindWatcherInfos( int32_t wd, uint32_t eventMask); - uint32_t GetFileEvents(const std::string &fileName); bool HasWatcherInfo() const; void ClearCache(); diff --git a/interfaces/kits/js/src/mod_fs/properties/watcher_core.cpp b/interfaces/kits/js/src/mod_fs/properties/watcher_core.cpp index 2b78a7c91..d622ff9b8 100644 --- a/interfaces/kits/js/src/mod_fs/properties/watcher_core.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/watcher_core.cpp @@ -28,7 +28,7 @@ using namespace std; static FsResult InstantiateWatcher() { - if (FsFileWatcher::GetInstance().GetNotifyId() < 0 && !FsFileWatcher::GetInstance().InitNotify()) { + if (!FsFileWatcher::GetInstance().TryInitNotify()) { HILOGE("Failed to get notifyId or initnotify fail"); return FsResult::Error(errno); } @@ -96,7 +96,7 @@ FsResult WatcherCore::DoCreateWatcher( return FsResult::Error(EIO); } - watchEntity->watherInfo = info; + watchEntity->watcherInfo = info; bool ret = FsFileWatcher::GetInstance().AddWatcherInfo(info); if (!ret) { diff --git a/interfaces/test/unittest/js/BUILD.gn b/interfaces/test/unittest/js/BUILD.gn index ca5d5eabe..5606c4743 100644 --- a/interfaces/test/unittest/js/BUILD.gn +++ b/interfaces/test/unittest/js/BUILD.gn @@ -249,6 +249,7 @@ ohos_unittest("ani_file_fs_test") { "mod_fs/class_stat/fs_stat_test.cpp", "mod_fs/class_stream/fs_stream_test.cpp", "mod_fs/class_tasksignal/fs_task_signal_test.cpp", + "mod_fs/class_watcher/watcher_data_cache_test.cpp", "mod_fs/properties/access_core_test.cpp", "mod_fs/properties/close_core_test.cpp", "mod_fs/properties/copy_core_test.cpp", diff --git a/interfaces/test/unittest/js/mod_fs/class_watcher/fs_file_watcher_mock_test.cpp b/interfaces/test/unittest/js/mod_fs/class_watcher/fs_file_watcher_mock_test.cpp index fe585ef71..446b5ac10 100644 --- a/interfaces/test/unittest/js/mod_fs/class_watcher/fs_file_watcher_mock_test.cpp +++ b/interfaces/test/unittest/js/mod_fs/class_watcher/fs_file_watcher_mock_test.cpp @@ -80,105 +80,120 @@ void FsFileWatcherMockTest::TearDown(void) inline const int32_t EXPECTED_WD = 100; inline const int32_t UNEXPECTED_WD = 200; +inline const int32_t INITIALIZED_NOTIFYFD = 1; +inline const int32_t UNINITIALIZED_NOTIFYFD = -1; +inline const int32_t INITIALIZED_EVENTFD = 1; +inline const int32_t UNINITIALIZED_EVENTFD = -1; /** - * @tc.name: FsFileWatcherMockTest_GetNotifyId_001 - * @tc.desc: Test function of FsFileWatcher::GetNotifyId interface. + * @tc.name: FsFileWatcherMockTest_TryInitNotify_001 + * @tc.desc: Test function of FsFileWatcher::TryInitNotify interface SUCCESS When notifyFd_ has initialed. * @tc.size: SMALL * @tc.type: FUNC * @tc.level Level 0 */ -HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_GetNotifyId_001, testing::ext::TestSize.Level0) +HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_TryInitNotify_001, testing::ext::TestSize.Level0) { - GTEST_LOG_(INFO) << "FsFileWatcherMockTest-begin FsFileWatcherMockTest_GetNotifyId_001"; + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-begin FsFileWatcherMockTest_TryInitNotify_001"; // Prepare test condition FsFileWatcher &watcher = FsFileWatcher::GetInstance(); - int32_t expected = -1; + watcher.notifyFd_ = INITIALIZED_NOTIFYFD; + // Set mock behaviors + auto eventfdMock = EventfdMock::GetMock(); + auto inotifyMock = InotifyMock::GetMock(); + EXPECT_CALL(*inotifyMock, inotify_init()).Times(0); + EXPECT_CALL(*eventfdMock, eventfd(testing::_, testing::_)).Times(0); // Do testing - int32_t result = watcher.GetNotifyId(); + bool result = watcher.TryInitNotify(); // Verify results - EXPECT_EQ(result, expected); - GTEST_LOG_(INFO) << "FsFileWatcherMockTest-end FsFileWatcherMockTest_GetNotifyId_001"; + testing::Mock::VerifyAndClearExpectations(inotifyMock.get()); + testing::Mock::VerifyAndClearExpectations(eventfdMock.get()); + EXPECT_TRUE(result); + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-end FsFileWatcherMockTest_TryInitNotify_001"; } /** - * @tc.name: FsFileWatcherMockTest_InitNotify_001 - * @tc.desc: Test function of FsFileWatcher::InitNotify interface for SUCCESS. + * @tc.name: FsFileWatcherMockTest_TryInitNotify_002 + * @tc.desc: Test function of FsFileWatcher::TryInitNotify interface for SUCCESS when InitNotify success. * @tc.size: MEDIUM * @tc.type: FUNC * @tc.level Level 0 */ -HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_InitNotify_001, testing::ext::TestSize.Level0) +HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_TryInitNotify_002, testing::ext::TestSize.Level0) { - GTEST_LOG_(INFO) << "FsFileWatcherMockTest-begin FsFileWatcherMockTest_InitNotify_001"; + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-begin FsFileWatcherMockTest_TryInitNotify_002"; // Prepare test condition FsFileWatcher &watcher = FsFileWatcher::GetInstance(); // Set mock behaviors auto eventfdMock = EventfdMock::GetMock(); auto inotifyMock = InotifyMock::GetMock(); - EXPECT_CALL(*inotifyMock, inotify_init()).Times(1).WillOnce(testing::Return(1)); - EXPECT_CALL(*eventfdMock, eventfd(testing::_, testing::_)).Times(1).WillOnce(testing::Return(2)); + EXPECT_CALL(*inotifyMock, inotify_init()).Times(1).WillOnce(testing::Return(INITIALIZED_NOTIFYFD)); + EXPECT_CALL(*eventfdMock, eventfd(testing::_, testing::_)).Times(1).WillOnce(testing::Return(INITIALIZED_EVENTFD)); // Do testing - bool result = watcher.InitNotify(); + bool result = watcher.TryInitNotify(); // Verify results testing::Mock::VerifyAndClearExpectations(inotifyMock.get()); testing::Mock::VerifyAndClearExpectations(eventfdMock.get()); EXPECT_TRUE(result); - EXPECT_EQ(watcher.notifyFd_, 1); - EXPECT_EQ(watcher.eventFd_, 2); - GTEST_LOG_(INFO) << "FsFileWatcherMockTest-end FsFileWatcherMockTest_InitNotify_001"; + EXPECT_EQ(watcher.notifyFd_, INITIALIZED_NOTIFYFD); + EXPECT_EQ(watcher.eventFd_, INITIALIZED_EVENTFD); + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-end FsFileWatcherMockTest_TryInitNotify_002"; } /** - * @tc.name: FsFileWatcherMockTest_InitNotify_002 - * @tc.desc: Test function of FsFileWatcher::InitNotify interface for FAILURE when inotify_init fails. + * @tc.name: FsFileWatcherMockTest_TryInitNotify_003 + * @tc.desc: Test function of FsFileWatcher::TryInitNotify interface for FAILURE when inotify_init fails. * @tc.size: MEDIUM * @tc.type: FUNC * @tc.level Level 1 */ -HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_InitNotify_002, testing::ext::TestSize.Level1) +HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_TryInitNotify_003, testing::ext::TestSize.Level1) { - GTEST_LOG_(INFO) << "FsFileWatcherMockTest-begin FsFileWatcherMockTest_InitNotify_002"; + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-begin FsFileWatcherMockTest_TryInitNotify_003"; // Prepare test condition FsFileWatcher &watcher = FsFileWatcher::GetInstance(); // Set mock behaviors auto inotifyMock = InotifyMock::GetMock(); - EXPECT_CALL(*inotifyMock, inotify_init()).Times(1).WillOnce(testing::SetErrnoAndReturn(EIO, -1)); + EXPECT_CALL(*inotifyMock, inotify_init()) + .Times(1) + .WillOnce(testing::SetErrnoAndReturn(EIO, UNINITIALIZED_NOTIFYFD)); // Do testing - bool result = watcher.InitNotify(); + bool result = watcher.TryInitNotify(); // Verify results testing::Mock::VerifyAndClearExpectations(inotifyMock.get()); EXPECT_FALSE(result); - EXPECT_EQ(watcher.notifyFd_, -1); - GTEST_LOG_(INFO) << "FsFileWatcherMockTest-end FsFileWatcherMockTest_InitNotify_002"; + EXPECT_EQ(watcher.notifyFd_, UNINITIALIZED_NOTIFYFD); + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-end FsFileWatcherMockTest_TryInitNotify_003"; } /** - * @tc.name: FsFileWatcherMockTest_InitNotify_003 - * @tc.desc: Test function of FsFileWatcher::InitNotify interface for FAILURE when eventfd fails. + * @tc.name: FsFileWatcherMockTest_TryInitNotify_004 + * @tc.desc: Test function of FsFileWatcher::TryInitNotify interface for FAILURE when eventfd fails. * @tc.size: MEDIUM * @tc.type: FUNC * @tc.level Level 1 */ -HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_InitNotify_003, testing::ext::TestSize.Level1) +HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_TryInitNotify_004, testing::ext::TestSize.Level1) { - GTEST_LOG_(INFO) << "FsFileWatcherMockTest-begin FsFileWatcherMockTest_InitNotify_003"; + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-begin FsFileWatcherMockTest_TryInitNotify_004"; // Prepare test condition FsFileWatcher &watcher = FsFileWatcher::GetInstance(); // Set mock behaviors auto inotifyMock = InotifyMock::GetMock(); auto eventfdMock = EventfdMock::GetMock(); - EXPECT_CALL(*inotifyMock, inotify_init()).Times(1).WillOnce(testing::Return(1)); - EXPECT_CALL(*eventfdMock, eventfd(testing::_, testing::_)).Times(1).WillOnce(testing::SetErrnoAndReturn(EIO, -1)); + EXPECT_CALL(*inotifyMock, inotify_init()).Times(1).WillOnce(testing::Return(INITIALIZED_NOTIFYFD)); + EXPECT_CALL(*eventfdMock, eventfd(testing::_, testing::_)) + .Times(1) + .WillOnce(testing::SetErrnoAndReturn(EIO, UNINITIALIZED_EVENTFD)); // Do testing - bool result = watcher.InitNotify(); + bool result = watcher.TryInitNotify(); // Verify results testing::Mock::VerifyAndClearExpectations(inotifyMock.get()); testing::Mock::VerifyAndClearExpectations(eventfdMock.get()); EXPECT_FALSE(result); - EXPECT_EQ(watcher.notifyFd_, 1); - EXPECT_EQ(watcher.eventFd_, -1); - GTEST_LOG_(INFO) << "FsFileWatcherMockTest-end FsFileWatcherMockTest_InitNotify_003"; + EXPECT_EQ(watcher.notifyFd_, INITIALIZED_NOTIFYFD); + EXPECT_EQ(watcher.eventFd_, UNINITIALIZED_EVENTFD); + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-end FsFileWatcherMockTest_TryInitNotify_004"; } /** @@ -197,7 +212,7 @@ HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_StartNotify_001, testing:: info->events = IN_CREATE | IN_DELETE; // Prepare test condition FsFileWatcher &watcher = FsFileWatcher::GetInstance(); - watcher.notifyFd_ = 1; + watcher.notifyFd_ = INITIALIZED_NOTIFYFD; // Set mock behaviors auto inotifyMock = InotifyMock::GetMock(); EXPECT_CALL(*inotifyMock, inotify_add_watch(testing::_, testing::_, testing::_)) @@ -230,8 +245,9 @@ HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_StartNotify_002, testing:: info->wd = EXPECTED_WD; // Prepare test condition FsFileWatcher &watcher = FsFileWatcher::GetInstance(); - watcher.notifyFd_ = 1; + watcher.notifyFd_ = INITIALIZED_NOTIFYFD; watcher.dataCache_.AddWatcherInfo(info); + watcher.dataCache_.UpdateWatchedEvents(info->fileName, info->wd, info->events); // Set mock behaviors auto inotifyMock = InotifyMock::GetMock(); EXPECT_CALL(*inotifyMock, inotify_add_watch(testing::_, testing::_, testing::_)).Times(0); @@ -274,7 +290,7 @@ HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_StartNotify_004, testing:: GTEST_LOG_(INFO) << "FsFileWatcherMockTest-begin FsFileWatcherMockTest_StartNotify_004"; // Prepare test condition FsFileWatcher &watcher = FsFileWatcher::GetInstance(); - watcher.notifyFd_ = -1; + watcher.notifyFd_ = UNINITIALIZED_NOTIFYFD; // Build test parameters auto info = std::make_shared(nullptr); info->fileName = "fakePath/FsFileWatcherMockTest_StartNotify_004"; @@ -298,7 +314,7 @@ HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_StartNotify_005, testing:: GTEST_LOG_(INFO) << "FsFileWatcherMockTest-begin FsFileWatcherMockTest_StartNotify_005"; // Prepare test condition FsFileWatcher &watcher = FsFileWatcher::GetInstance(); - watcher.notifyFd_ = 1; + watcher.notifyFd_ = INITIALIZED_NOTIFYFD; // Build test parameters auto info = std::make_shared(nullptr); info->fileName = "fakePath/FsFileWatcherMockTest_StartNotify_005"; @@ -332,7 +348,7 @@ HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_StartNotify_006, testing:: info->events = IN_CREATE; // Prepare test condition FsFileWatcher &watcher = FsFileWatcher::GetInstance(); - watcher.notifyFd_ = 1; + watcher.notifyFd_ = INITIALIZED_NOTIFYFD; auto cachedInfo = std::make_shared(nullptr); cachedInfo->fileName = "fakePath/FsFileWatcherMockTest_StartNotify_006"; cachedInfo->events = IN_DELETE; @@ -352,6 +368,39 @@ HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_StartNotify_006, testing:: GTEST_LOG_(INFO) << "FsFileWatcherMockTest-end FsFileWatcherMockTest_StartNotify_006"; } +/** + * @tc.name: FsFileWatcherMockTest_StartNotify_007 + * @tc.desc: Test function of FsFileWatcher::StartNotify interface for SUCCESS fileName already watched but events + * unmatched. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 0 + */ +HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_StartNotify_007, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-begin FsFileWatcherMockTest_StartNotify_007"; + // Prepare test parameters + auto info = std::make_shared(nullptr); + info->fileName = "fakePath/FsFileWatcherMockTest_StartNotify_007"; + info->events = IN_CREATE; + // Prepare test condition + FsFileWatcher &watcher = FsFileWatcher::GetInstance(); + watcher.notifyFd_ = INITIALIZED_NOTIFYFD; + watcher.dataCache_.UpdateWatchedEvents(info->fileName, EXPECTED_WD, IN_DELETE); + // Set mock behaviors + auto inotifyMock = InotifyMock::GetMock(); + EXPECT_CALL(*inotifyMock, inotify_add_watch(testing::_, testing::_, testing::_)) + .Times(1) + .WillOnce(testing::Return(EXPECTED_WD)); + // Do testing + int32_t result = watcher.StartNotify(info); + // Verify results + testing::Mock::VerifyAndClearExpectations(inotifyMock.get()); + EXPECT_EQ(result, ERRNO_NOERR); + EXPECT_EQ(info->wd, EXPECTED_WD); + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-end FsFileWatcherMockTest_StartNotify_007"; +} + /** * @tc.name: FsFileWatcherMockTest_StopNotify_001 * @tc.desc: Test function of FsFileWatcher::StopNotify interface for SUCCESS. @@ -369,7 +418,7 @@ HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_StopNotify_001, testing::e info->wd = EXPECTED_WD; // Prepare test condition FsFileWatcher &watcher = FsFileWatcher::GetInstance(); - watcher.notifyFd_ = 1; + watcher.notifyFd_ = INITIALIZED_NOTIFYFD; watcher.dataCache_.AddWatcherInfo(info); // Set mock behaviors auto unistdMock = UnistdMock::GetMock(); @@ -417,7 +466,7 @@ HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_StopNotify_003, testing::e GTEST_LOG_(INFO) << "FsFileWatcherMockTest-begin FsFileWatcherMockTest_StopNotify_003"; // Prepare test condition FsFileWatcher &watcher = FsFileWatcher::GetInstance(); - watcher.notifyFd_ = -1; + watcher.notifyFd_ = UNINITIALIZED_NOTIFYFD; // Prepare test parameters auto info = std::make_shared(nullptr); info->fileName = "fakePath/FsFileWatcherMockTest_StopNotify_003"; @@ -447,7 +496,7 @@ HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_StopNotify_004, testing::e info->wd = EXPECTED_WD; // Prepare test condition FsFileWatcher &watcher = FsFileWatcher::GetInstance(); - watcher.notifyFd_ = 1; + watcher.notifyFd_ = INITIALIZED_NOTIFYFD; watcher.dataCache_.AddWatcherInfo(info); // Set mock behaviors auto unistdMock = UnistdMock::GetMock(); @@ -483,7 +532,7 @@ HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_StopNotify_005, testing::e info->wd = EXPECTED_WD; // Prepare test condition FsFileWatcher &watcher = FsFileWatcher::GetInstance(); - watcher.notifyFd_ = 1; + watcher.notifyFd_ = INITIALIZED_NOTIFYFD; watcher.dataCache_.AddWatcherInfo(info); // Set rm watch fail condition watcher.closed_ = true; @@ -521,7 +570,7 @@ HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_StopNotify_006, testing::e info->wd = EXPECTED_WD; // Prepare test condition FsFileWatcher &watcher = FsFileWatcher::GetInstance(); - watcher.notifyFd_ = 1; + watcher.notifyFd_ = INITIALIZED_NOTIFYFD; watcher.dataCache_.AddWatcherInfo(info); // Set having remainingEvents condition auto remainingInfo = std::make_shared(nullptr); @@ -562,7 +611,7 @@ HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_StopNotify_007, testing::e info->wd = EXPECTED_WD; // Prepare test condition FsFileWatcher &watcher = FsFileWatcher::GetInstance(); - watcher.notifyFd_ = 1; + watcher.notifyFd_ = INITIALIZED_NOTIFYFD; watcher.dataCache_.AddWatcherInfo(info); // Set having remainingEvents condition auto remainingInfo = std::make_shared(nullptr); @@ -606,7 +655,7 @@ HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_StopNotify_008, testing::e info->wd = EXPECTED_WD; // Prepare test condition FsFileWatcher &watcher = FsFileWatcher::GetInstance(); - watcher.notifyFd_ = 1; + watcher.notifyFd_ = INITIALIZED_NOTIFYFD; watcher.dataCache_.AddWatcherInfo(info); // Set having remainingEvents condition auto remainingInfo = std::make_shared(nullptr); @@ -650,7 +699,7 @@ HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_StopNotify_009, testing::e info->wd = EXPECTED_WD; // Prepare test condition FsFileWatcher &watcher = FsFileWatcher::GetInstance(); - watcher.notifyFd_ = 1; + watcher.notifyFd_ = INITIALIZED_NOTIFYFD; watcher.dataCache_.AddWatcherInfo(info); // Set having remainingEvents condition auto remainingInfo = std::make_shared(nullptr); @@ -693,23 +742,24 @@ HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_StopNotify_010, testing::e info->wd = EXPECTED_WD; // Prepare test condition FsFileWatcher &watcher = FsFileWatcher::GetInstance(); - watcher.notifyFd_ = 1; - watcher.eventFd_ = 1; + watcher.notifyFd_ = INITIALIZED_NOTIFYFD; + watcher.eventFd_ = INITIALIZED_EVENTFD; watcher.dataCache_.AddWatcherInfo(info); // Set mock behaviors auto unistdMock = UnistdMock::GetMock(); auto inotifyMock = InotifyMock::GetMock(); EXPECT_CALL(*unistdMock, access(testing::_, testing::_)).Times(0); - EXPECT_CALL(*unistdMock, close(testing::_)).Times(2).WillRepeatedly(testing::Return(EIO)); + EXPECT_CALL(*unistdMock, close(testing::_)).Times(2).WillRepeatedly(testing::SetErrnoAndReturn(EIO, -1)); EXPECT_CALL(*inotifyMock, inotify_rm_watch(testing::_, testing::_)).Times(1).WillOnce(testing::Return(0)); // Do testing int32_t result = watcher.StopNotify(info); // Verify results testing::Mock::VerifyAndClearExpectations(unistdMock.get()); testing::Mock::VerifyAndClearExpectations(inotifyMock.get()); - EXPECT_EQ(result, EIO); - EXPECT_EQ(watcher.notifyFd_, -1); - EXPECT_EQ(watcher.eventFd_, -1); + EXPECT_EQ(result, -1); + EXPECT_EQ(errno, EIO); + EXPECT_EQ(watcher.notifyFd_, UNINITIALIZED_NOTIFYFD); + EXPECT_EQ(watcher.eventFd_, UNINITIALIZED_EVENTFD); GTEST_LOG_(INFO) << "FsFileWatcherMockTest-end FsFileWatcherMockTest_StopNotify_010"; } @@ -750,8 +800,8 @@ HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_GetNotifyEvent_002, testin // Prepare test condition FsFileWatcher &watcher = FsFileWatcher::GetInstance(); watcher.run_ = false; - watcher.notifyFd_ = 1; - watcher.eventFd_ = 2; + watcher.notifyFd_ = INITIALIZED_NOTIFYFD; + watcher.eventFd_ = INITIALIZED_EVENTFD; // Set mock behaviors auto pollMock = PollMock::GetMock(); EXPECT_CALL(*pollMock, poll(testing::_, testing::_, testing::_)) @@ -782,8 +832,8 @@ HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_GetNotifyEvent_003, testin // Prepare test condition FsFileWatcher &watcher = FsFileWatcher::GetInstance(); watcher.run_ = false; - watcher.notifyFd_ = 1; - watcher.eventFd_ = 2; + watcher.notifyFd_ = INITIALIZED_NOTIFYFD; + watcher.eventFd_ = INITIALIZED_EVENTFD; // Set mock behaviors auto pollMock = PollMock::GetMock(); EXPECT_CALL(*pollMock, poll(testing::_, testing::_, testing::_)) @@ -814,8 +864,8 @@ HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_GetNotifyEvent_004, testin // Prepare test condition FsFileWatcher &watcher = FsFileWatcher::GetInstance(); watcher.run_ = false; - watcher.notifyFd_ = 1; - watcher.eventFd_ = 2; + watcher.notifyFd_ = INITIALIZED_NOTIFYFD; + watcher.eventFd_ = INITIALIZED_EVENTFD; watcher.closed_ = true; // Avoid calling ReadNotifyEvent // Set mock behaviors auto pollMock = PollMock::GetMock(); @@ -847,8 +897,8 @@ HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_GetNotifyEvent_005, testin // Prepare test condition FsFileWatcher &watcher = FsFileWatcher::GetInstance(); watcher.run_ = false; - watcher.notifyFd_ = 1; - watcher.eventFd_ = 2; + watcher.notifyFd_ = INITIALIZED_NOTIFYFD; + watcher.eventFd_ = INITIALIZED_EVENTFD; // Set mock behaviors auto pollMock = PollMock::GetMock(); EXPECT_CALL(*pollMock, poll(testing::_, testing::_, testing::_)) @@ -878,8 +928,8 @@ HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_GetNotifyEvent_006, testin // Prepare test condition FsFileWatcher &watcher = FsFileWatcher::GetInstance(); watcher.run_ = false; - watcher.notifyFd_ = 1; - watcher.eventFd_ = 2; + watcher.notifyFd_ = INITIALIZED_NOTIFYFD; + watcher.eventFd_ = INITIALIZED_EVENTFD; // Set mock behaviors auto pollMock = PollMock::GetMock(); EXPECT_CALL(*pollMock, poll(testing::_, testing::_, testing::_)) @@ -910,8 +960,8 @@ HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_GetNotifyEvent_007, testin // Prepare test condition FsFileWatcher &watcher = FsFileWatcher::GetInstance(); watcher.run_ = false; - watcher.notifyFd_ = 1; - watcher.eventFd_ = 2; + watcher.notifyFd_ = INITIALIZED_NOTIFYFD; + watcher.eventFd_ = INITIALIZED_EVENTFD; // Set mock behaviors auto pollMock = PollMock::GetMock(); EXPECT_CALL(*pollMock, poll(testing::_, testing::_, testing::_)) @@ -1058,6 +1108,60 @@ HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_ReadNotifyEvent_003, testi GTEST_LOG_(INFO) << "FsFileWatcherMockTest-end FsFileWatcherMockTest_ReadNotifyEvent_003"; } +/** + * @tc.name: FsFileWatcherMockTest_ReadNotifyEvent_004 + * @tc.desc: Test function of FsFileWatcher::ReadNotifyEvent interface for FAILURE when read incomplete event struct. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 0 + */ +HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_ReadNotifyEvent_004, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-begin FsFileWatcherMockTest_ReadNotifyEvent_004"; + // Prepare test condition + FsFileWatcher &watcher = FsFileWatcher::GetInstance(); + int32_t len = static_cast(sizeof(struct inotify_event)); + // Set mock behaviors + auto unistdMock = UnistdMock::GetMock(); + EXPECT_CALL(*unistdMock, read(testing::_, testing::_, testing::_)).Times(1).WillOnce(testing::Return(len - 1)); + // Do testing + watcher.ReadNotifyEvent(); + // Verify results + testing::Mock::VerifyAndClearExpectations(unistdMock.get()); + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-end FsFileWatcherMockTest_ReadNotifyEvent_004"; +} + +/** + * @tc.name: FsFileWatcherMockTest_ReadNotifyEvent_005 + * @tc.desc: Test function of FsFileWatcher::ReadNotifyEvent interface for FAILURE when read incomplete event struct. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 0 + */ +HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_ReadNotifyEvent_005, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-begin FsFileWatcherMockTest_ReadNotifyEvent_005"; + // Prepare test condition + FsFileWatcher &watcher = FsFileWatcher::GetInstance(); + int32_t len = static_cast(sizeof(struct inotify_event)); + auto data = "FsFileWatcherMockTest_ReadNotifyEvent_005"; + uint32_t dataLen = strlen(data); + // Set mock behaviors + auto unistdMock = UnistdMock::GetMock(); + EXPECT_CALL(*unistdMock, read(testing::_, testing::_, testing::_)) + .Times(1) + .WillOnce(testing::DoAll(testing::Invoke([dataLen](int, void *buf, size_t) { + auto *event = reinterpret_cast(buf); + event->len = dataLen; + }), + testing::Return(len + static_cast(dataLen) - 1))); + // Do testing + watcher.ReadNotifyEvent(); + // Verify results + testing::Mock::VerifyAndClearExpectations(unistdMock.get()); + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-end FsFileWatcherMockTest_ReadNotifyEvent_005"; +} + /** * @tc.name: FsFileWatcherMockTest_NotifyEvent_001 * @tc.desc: Test function of FsFileWatcher::NotifyEvent interface for SUCCESS when valid event without filename. @@ -1079,6 +1183,7 @@ HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_NotifyEvent_001, testing:: info->wd = EXPECTED_WD; FsFileWatcher &watcher = FsFileWatcher::GetInstance(); watcher.dataCache_.AddWatcherInfo(info); + watcher.dataCache_.UpdateWatchedEvents(info->fileName, info->wd, info->events); // Set mock behaviors EXPECT_CALL(*callback, InvokeCallback(testing::_, testing::_, testing::_)).Times(1); // Do testing @@ -1124,6 +1229,7 @@ HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_NotifyEvent_002, testing:: info->wd = EXPECTED_WD; FsFileWatcher &watcher = FsFileWatcher::GetInstance(); watcher.dataCache_.AddWatcherInfo(info); + watcher.dataCache_.UpdateWatchedEvents(info->fileName, info->wd, info->events); // Set mock behaviors EXPECT_CALL(*callback, InvokeCallback(testing::_, testing::_, testing::_)).Times(1); // Do testing @@ -1173,6 +1279,7 @@ HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_NotifyEvent_004, testing:: info->wd = UNEXPECTED_WD; // Not matched wd FsFileWatcher &watcher = FsFileWatcher::GetInstance(); watcher.dataCache_.AddWatcherInfo(info); + watcher.dataCache_.UpdateWatchedEvents(info->fileName, info->wd, info->events); // Set mock behaviors EXPECT_CALL(*callback, InvokeCallback(testing::_, testing::_, testing::_)).Times(0); // Do testing @@ -1299,23 +1406,431 @@ HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_RemoveWatcherInfo_001, tes } /** - * @tc.name: FsFileWatcherMockTest_DestroyTaskThead_001 - * @tc.desc: Test function of FsFileWatcher::DestroyTaskThead interface when taskRunning is true. + * @tc.name: FsFileWatcherMockTest_DestroyTaskThread_001 + * @tc.desc: Test function of FsFileWatcher::DestroyTaskThread interface when taskRunning is true. * @tc.size: SMALL * @tc.type: FUNC * @tc.level Level 1 */ -HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_DestroyTaskThead_001, testing::ext::TestSize.Level1) +HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_DestroyTaskThread_001, testing::ext::TestSize.Level1) { - GTEST_LOG_(INFO) << "FsFileWatcherMockTest-begin FsFileWatcherMockTest_DestroyTaskThead_001"; + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-begin FsFileWatcherMockTest_DestroyTaskThread_001"; // Prepare test condition FsFileWatcher &watcher = FsFileWatcher::GetInstance(); watcher.taskRunning_ = true; + watcher.run_ = true; // Do testing - watcher.DestroyTaskThead(); + watcher.DestroyTaskThread(); // Verify results EXPECT_FALSE(watcher.taskRunning_); - GTEST_LOG_(INFO) << "FsFileWatcherMockTest-end FsFileWatcherMockTest_DestroyTaskThead_001"; + EXPECT_FALSE(watcher.run_); + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-end FsFileWatcherMockTest_DestroyTaskThread_001"; +} + +/** + * @tc.name: FsFileWatcherMockTest_DestroyTaskThread_002 + * @tc.desc: Test function of FsFileWatcher::DestroyTaskThread interface when taskRunning is true and taskThread_ is + * joinable. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_DestroyTaskThread_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-begin FsFileWatcherMockTest_DestroyTaskThread_002"; + // Prepare test condition + std::atomic keepAlive(false); + std::thread mockThread([&]() { + keepAlive = true; + while (keepAlive) { + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } + }); + // Wait for mockThread to start (ensure keepAlive is set to true, prevent thread from exiting early) + while (!keepAlive) { + std::this_thread::yield(); + } + FsFileWatcher &watcher = FsFileWatcher::GetInstance(); + watcher.taskThread_ = std::move(mockThread); + watcher.taskRunning_ = true; + watcher.run_ = true; + // Do testing + watcher.DestroyTaskThread(); + // Verify results + EXPECT_FALSE(watcher.taskRunning_); + EXPECT_FALSE(watcher.run_); + // Cleanup resources + keepAlive = false; + if (watcher.taskThread_.joinable()) { + watcher.taskThread_.join(); + } + watcher.taskThread_ = std::thread(); + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-end FsFileWatcherMockTest_DestroyTaskThread_002"; +} + +/** + * @tc.name: FsFileWatcherMockTest_DestroyTaskThread_003 + * @tc.desc: Test function of FsFileWatcher::DestroyTaskThread interface when taskRunning is false. + * @tc.size: SMALL + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_DestroyTaskThread_003, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-begin FsFileWatcherMockTest_DestroyTaskThread_003"; + // Prepare test condition + FsFileWatcher &watcher = FsFileWatcher::GetInstance(); + watcher.taskRunning_ = false; + watcher.run_ = true; + // Do testing + watcher.DestroyTaskThread(); + // Verify results + EXPECT_FALSE(watcher.taskRunning_); + EXPECT_TRUE(watcher.run_); + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-end FsFileWatcherMockTest_DestroyTaskThread_003"; +} + +/** + * @tc.name: FsFileWatcherMockTest_WakeupThread_001 + * @tc.desc: Test function of FsFileWatcher::WakeupThread interface SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_WakeupThread_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-begin FsFileWatcherMockTest_WakeupThread_001"; + // Prepare test condition + std::atomic keepAlive(false); + std::thread mockThread([&]() { + keepAlive = true; + while (keepAlive) { + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } + }); + // Wait for mockThread to start (ensure keepAlive is set to true, prevent thread from exiting early) + while (!keepAlive) { + std::this_thread::yield(); + } + FsFileWatcher &watcher = FsFileWatcher::GetInstance(); + watcher.taskThread_ = std::move(mockThread); + watcher.taskRunning_ = true; + watcher.eventFd_ = INITIALIZED_EVENTFD; + // Set mock behaviors + auto unistdMock = UnistdMock::GetMock(); + EXPECT_CALL(*unistdMock, write(testing::_, testing::_, testing::_)) + .Times(1) + .WillOnce(testing::Return(sizeof(uint64_t))); + // Do testing + watcher.WakeupThread(); + // Verify results + testing::Mock::VerifyAndClearExpectations(unistdMock.get()); + EXPECT_TRUE(watcher.taskRunning_); + EXPECT_EQ(watcher.eventFd_, INITIALIZED_EVENTFD); + // Cleanup resources + keepAlive = false; + if (watcher.taskThread_.joinable()) { + watcher.taskThread_.join(); + } + watcher.taskThread_ = std::thread(); + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-end FsFileWatcherMockTest_WakeupThread_001"; +} + +/** + * @tc.name: FsFileWatcherMockTest_WakeupThread_002 + * @tc.desc: Test function of FsFileWatcher::WakeupThread interface FAILURE when taskRunning_ is false. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_WakeupThread_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-begin FsFileWatcherMockTest_WakeupThread_002"; + // Prepare test condition + FsFileWatcher &watcher = FsFileWatcher::GetInstance(); + watcher.taskRunning_ = false; + watcher.eventFd_ = INITIALIZED_EVENTFD; + // Set mock behaviors + auto unistdMock = UnistdMock::GetMock(); + EXPECT_CALL(*unistdMock, write(testing::_, testing::_, testing::_)).Times(0); + // Do testing + watcher.WakeupThread(); + // Verify results + testing::Mock::VerifyAndClearExpectations(unistdMock.get()); + EXPECT_FALSE(watcher.taskRunning_); + EXPECT_EQ(watcher.eventFd_, INITIALIZED_EVENTFD); + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-end FsFileWatcherMockTest_WakeupThread_002"; +} + +/** + * @tc.name: FsFileWatcherMockTest_WakeupThread_003 + * @tc.desc: Test function of FsFileWatcher::WakeupThread interface FAILURE when eventFd_ < 0. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_WakeupThread_003, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-begin FsFileWatcherMockTest_WakeupThread_002"; + // Prepare test condition + FsFileWatcher &watcher = FsFileWatcher::GetInstance(); + watcher.taskRunning_ = true; + watcher.eventFd_ = UNINITIALIZED_EVENTFD; + // Set mock behaviors + auto unistdMock = UnistdMock::GetMock(); + EXPECT_CALL(*unistdMock, write(testing::_, testing::_, testing::_)).Times(0); + // Do testing + watcher.WakeupThread(); + // Verify results + testing::Mock::VerifyAndClearExpectations(unistdMock.get()); + EXPECT_TRUE(watcher.taskRunning_); + EXPECT_EQ(watcher.eventFd_, UNINITIALIZED_EVENTFD); + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-end FsFileWatcherMockTest_WakeupThread_002"; +} + +/** + * @tc.name: FsFileWatcherMockTest_WakeupThread_004 + * @tc.desc: Test function of FsFileWatcher::WakeupThread interface FAILURE when eventFd_ < 0. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_WakeupThread_004, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-begin FsFileWatcherMockTest_WakeupThread_002"; + // Prepare test condition + FsFileWatcher &watcher = FsFileWatcher::GetInstance(); + watcher.taskRunning_ = true; + watcher.eventFd_ = INITIALIZED_EVENTFD; + watcher.taskThread_ = std::thread(); + // Set mock behaviors + auto unistdMock = UnistdMock::GetMock(); + EXPECT_CALL(*unistdMock, write(testing::_, testing::_, testing::_)).Times(0); + // Do testing + watcher.WakeupThread(); + // Verify results + testing::Mock::VerifyAndClearExpectations(unistdMock.get()); + EXPECT_TRUE(watcher.taskRunning_); + EXPECT_EQ(watcher.eventFd_, INITIALIZED_EVENTFD); + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-end FsFileWatcherMockTest_WakeupThread_002"; +} + +/** + * @tc.name: FsFileWatcherMockTest_WakeupThread_005 + * @tc.desc: Test function of FsFileWatcher::WakeupThread interface SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_WakeupThread_005, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-begin FsFileWatcherMockTest_WakeupThread_001"; + // Prepare test condition + std::atomic keepAlive(false); + std::thread mockThread([&]() { + keepAlive = true; + while (keepAlive) { + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } + }); + // Wait for mockThread to start (ensure keepAlive is set to true, prevent thread from exiting early) + while (!keepAlive) { + std::this_thread::yield(); + } + FsFileWatcher &watcher = FsFileWatcher::GetInstance(); + watcher.taskThread_ = std::move(mockThread); + watcher.taskRunning_ = true; + watcher.eventFd_ = INITIALIZED_EVENTFD; + // Set mock behaviors + auto unistdMock = UnistdMock::GetMock(); + EXPECT_CALL(*unistdMock, write(testing::_, testing::_, testing::_)) + .Times(1) + .WillOnce(testing::SetErrnoAndReturn(EIO, -1)); + // Do testing + watcher.WakeupThread(); + // Verify results + testing::Mock::VerifyAndClearExpectations(unistdMock.get()); + EXPECT_TRUE(watcher.taskRunning_); + EXPECT_EQ(watcher.eventFd_, INITIALIZED_EVENTFD); + EXPECT_EQ(errno, EIO); + // Cleanup resources + keepAlive = false; + if (watcher.taskThread_.joinable()) { + watcher.taskThread_.join(); + } + watcher.taskThread_ = std::thread(); + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-end FsFileWatcherMockTest_WakeupThread_001"; +} + +/** + * @tc.name: FsFileWatcherMockTest_CloseNotifyFdLocked_001 + * @tc.desc: Test function of FsFileWatcher::CloseNotifyFdLocked interface when reading_ is true. + * @tc.size: SMALL + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_CloseNotifyFdLocked_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-begin FsFileWatcherMockTest_CloseNotifyFdLocked_001"; + // Prepare test condition + FsFileWatcher &watcher = FsFileWatcher::GetInstance(); + watcher.reading_ = true; + // Do testing + auto ret = watcher.CloseNotifyFdLocked(); + // Verify results + EXPECT_FALSE(watcher.closed_); + EXPECT_EQ(ret, ERRNO_NOERR); + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-end FsFileWatcherMockTest_CloseNotifyFdLocked_001"; +} + +/** + * @tc.name: FsFileWatcherMockTest_CloseNotifyFdLocked_002 + * @tc.desc: Test function of FsFileWatcher::CloseNotifyFdLocked interface when CloseNotifyFd return ERRNO_NOERR. + * @tc.size: SMALL + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_CloseNotifyFdLocked_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-begin FsFileWatcherMockTest_CloseNotifyFdLocked_002"; + // Prepare test condition + FsFileWatcher &watcher = FsFileWatcher::GetInstance(); + watcher.reading_ = false; + // Set mock behaviors + auto unistdMock = UnistdMock::GetMock(); + EXPECT_CALL(*unistdMock, write(testing::_, testing::_, testing::_)).Times(0); + EXPECT_CALL(*unistdMock, close(testing::_)).Times(2).WillRepeatedly(testing::Return(0)); + // Do testing + auto ret = watcher.CloseNotifyFdLocked(); + // Verify results + testing::Mock::VerifyAndClearExpectations(unistdMock.get()); + EXPECT_FALSE(watcher.closed_); + EXPECT_EQ(ret, ERRNO_NOERR); + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-end FsFileWatcherMockTest_CloseNotifyFdLocked_002"; +} + +/** + * @tc.name: FsFileWatcherMockTest_CloseNotifyFd_001 + * @tc.desc: Test function of FsFileWatcher::CloseNotifyFd interface SUCCESS when HasWatcherInfo is true. + * @tc.size: SMALL + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_CloseNotifyFd_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-begin FsFileWatcherMockTest_CloseNotifyFd_001"; + // Prepare test condition + auto info = std::make_shared(nullptr); + info->fileName = "fakePath/FsFileWatcherMockTest_CloseNotifyFd_001"; + info->events = IN_CREATE | IN_DELETE; + info->wd = EXPECTED_WD; + FsFileWatcher &watcher = FsFileWatcher::GetInstance(); + watcher.run_ = true; + watcher.closed_ = true; + watcher.notifyFd_ = INITIALIZED_NOTIFYFD; + watcher.eventFd_ = INITIALIZED_EVENTFD; + watcher.dataCache_.AddWatcherInfo(info); + // Set mock behaviors + auto unistdMock = UnistdMock::GetMock(); + EXPECT_CALL(*unistdMock, write(testing::_, testing::_, testing::_)).Times(0); + EXPECT_CALL(*unistdMock, close(testing::_)).Times(0); + // Do testing + auto ret = watcher.CloseNotifyFd(); + // Verify results + testing::Mock::VerifyAndClearExpectations(unistdMock.get()); + EXPECT_TRUE(watcher.run_); + EXPECT_FALSE(watcher.closed_); + EXPECT_EQ(watcher.notifyFd_, INITIALIZED_NOTIFYFD); + EXPECT_EQ(watcher.eventFd_, INITIALIZED_EVENTFD); + EXPECT_EQ(ret, ERRNO_NOERR); + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-end FsFileWatcherMockTest_CloseNotifyFd_001"; +} + +/** + * @tc.name: FsFileWatcherMockTest_CloseNotifyFd_002 + * @tc.desc: Test function of FsFileWatcher::CloseNotifyFd interface SUCCESS when HasWatcherInfo is false. + * @tc.size: SMALL + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_CloseNotifyFd_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-begin FsFileWatcherMockTest_CloseNotifyFd_002"; + // Prepare test condition + FsFileWatcher &watcher = FsFileWatcher::GetInstance(); + watcher.run_ = true; + watcher.closed_ = true; + watcher.notifyFd_ = INITIALIZED_NOTIFYFD; + watcher.eventFd_ = INITIALIZED_EVENTFD; + // Set mock behaviors + auto unistdMock = UnistdMock::GetMock(); + EXPECT_CALL(*unistdMock, write(testing::_, testing::_, testing::_)).Times(0); + EXPECT_CALL(*unistdMock, close(testing::_)).Times(2).WillRepeatedly(testing::Return(0)); + // Do testing + auto ret = watcher.CloseNotifyFd(); + // Verify results + testing::Mock::VerifyAndClearExpectations(unistdMock.get()); + EXPECT_FALSE(watcher.run_); + EXPECT_FALSE(watcher.closed_); + EXPECT_EQ(watcher.notifyFd_, UNINITIALIZED_NOTIFYFD); + EXPECT_EQ(watcher.eventFd_, UNINITIALIZED_NOTIFYFD); + EXPECT_EQ(ret, ERRNO_NOERR); + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-end FsFileWatcherMockTest_CloseNotifyFd_002"; +} + +/** + * @tc.name: FsFileWatcherMockTest_CloseNotifyFd_003 + * @tc.desc: Test function of FsFileWatcher::CloseNotifyFd interface FAILURE when close notifyFd_ and eventFd_ fails. + * @tc.size: SMALL + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_CloseNotifyFd_003, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-begin FsFileWatcherMockTest_CloseNotifyFd_003"; + // Prepare test condition + FsFileWatcher &watcher = FsFileWatcher::GetInstance(); + watcher.run_ = true; + watcher.closed_ = true; + watcher.notifyFd_ = INITIALIZED_NOTIFYFD; + watcher.eventFd_ = INITIALIZED_EVENTFD; + // Set mock behaviors + auto unistdMock = UnistdMock::GetMock(); + EXPECT_CALL(*unistdMock, write(testing::_, testing::_, testing::_)).Times(0); + EXPECT_CALL(*unistdMock, close(testing::_)).Times(2).WillRepeatedly(testing::SetErrnoAndReturn(EIO, -1)); + // Do testing + auto ret = watcher.CloseNotifyFd(); + // Verify results + testing::Mock::VerifyAndClearExpectations(unistdMock.get()); + EXPECT_FALSE(watcher.run_); + EXPECT_FALSE(watcher.closed_); + EXPECT_EQ(watcher.notifyFd_, UNINITIALIZED_NOTIFYFD); + EXPECT_EQ(watcher.eventFd_, UNINITIALIZED_EVENTFD); + EXPECT_EQ(ret, -1); + EXPECT_EQ(errno, EIO); + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-end FsFileWatcherMockTest_CloseNotifyFd_003"; +} + +/** + * @tc.name: FsFileWatcherMockTest_AsyncGetNotifyEvent_001 + * @tc.desc: Test function of FsFileWatcher::AsyncGetNotifyEvent interface SUCCESS. + * @tc.size: SMALL + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_AsyncGetNotifyEvent_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-begin FsFileWatcherMockTest_AsyncGetNotifyEvent_001"; + // Prepare test condition + FsFileWatcher &watcher = FsFileWatcher::GetInstance(); + watcher.run_ = true; + watcher.taskRunning_ = false; + // Do testing + watcher.AsyncGetNotifyEvent(); + // Verify results + EXPECT_TRUE(watcher.run_); + EXPECT_TRUE(watcher.taskRunning_); + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-end FsFileWatcherMockTest_AsyncGetNotifyEvent_001"; } } // namespace Test diff --git a/interfaces/test/unittest/js/mod_fs/class_watcher/fs_watcher_mock_test.cpp b/interfaces/test/unittest/js/mod_fs/class_watcher/fs_watcher_mock_test.cpp index 6894647ea..5be1fde4e 100644 --- a/interfaces/test/unittest/js/mod_fs/class_watcher/fs_watcher_mock_test.cpp +++ b/interfaces/test/unittest/js/mod_fs/class_watcher/fs_watcher_mock_test.cpp @@ -112,7 +112,7 @@ HWTEST_F(FsWatcherMockTest, FsWatcherTest_Start_001, testing::ext::TestSize.Leve auto watchEntity = CreateUniquePtr(); FsWatcher fsWatcher(std::move(watchEntity)); std::shared_ptr info = std::make_shared(nullptr); - fsWatcher.GetWatchEntity()->watherInfo = info; + fsWatcher.GetWatchEntity()->watcherInfo = info; // Prepare test condition for FsFileWatcher FsFileWatcher &watcher = FsFileWatcher::GetInstance(); watcher.notifyFd_ = 1; // Valid notifyFd @@ -165,7 +165,7 @@ HWTEST_F(FsWatcherMockTest, FsWatcherTest_Start_003, testing::ext::TestSize.Leve auto watchEntity = CreateUniquePtr(); FsWatcher fsWatcher(std::move(watchEntity)); std::shared_ptr info = std::make_shared(nullptr); - fsWatcher.GetWatchEntity()->watherInfo = info; + fsWatcher.GetWatchEntity()->watcherInfo = info; // Prepare test condition for FsFileWatcher FsFileWatcher &watcher = FsFileWatcher::GetInstance(); watcher.notifyFd_ = -1; // Invalid notifyFd @@ -192,7 +192,7 @@ HWTEST_F(FsWatcherMockTest, FsWatcherTest_Stop_001, testing::ext::TestSize.Level auto watchEntity = CreateUniquePtr(); FsWatcher fsWatcher(std::move(watchEntity)); std::shared_ptr info = std::make_shared(nullptr); - fsWatcher.GetWatchEntity()->watherInfo = info; + fsWatcher.GetWatchEntity()->watcherInfo = info; // Prepare test condition for FsFileWatcher FsFileWatcher &watcher = FsFileWatcher::GetInstance(); watcher.notifyFd_ = 1; @@ -247,7 +247,7 @@ HWTEST_F(FsWatcherMockTest, FsWatcherTest_Stop_003, testing::ext::TestSize.Level auto watchEntity = CreateUniquePtr(); FsWatcher fsWatcher(std::move(watchEntity)); std::shared_ptr info = std::make_shared(nullptr); - fsWatcher.GetWatchEntity()->watherInfo = info; + fsWatcher.GetWatchEntity()->watcherInfo = info; // Prepare test condition for FsFileWatcher FsFileWatcher &watcher = FsFileWatcher::GetInstance(); watcher.notifyFd_ = -1; // Invalid notifyFd diff --git a/interfaces/test/unittest/js/mod_fs/class_watcher/watcher_data_cache_test.cpp b/interfaces/test/unittest/js/mod_fs/class_watcher/watcher_data_cache_test.cpp new file mode 100644 index 000000000..0c4d2f200 --- /dev/null +++ b/interfaces/test/unittest/js/mod_fs/class_watcher/watcher_data_cache_test.cpp @@ -0,0 +1,228 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include +#include + +#include "filemgmt_libhilog.h" +#include "watcher_data_cache.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace Test { + +class WatcherDataCacheTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void WatcherDataCacheTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void WatcherDataCacheTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void WatcherDataCacheTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; + errno = 0; // Reset errno +} + +void WatcherDataCacheTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +inline const int32_t EXPECTED_WD = 100; +inline const int32_t UNEXPECTED_WD = 200; +inline const uint32_t EXPECTED_EVENTS = IN_ACCESS | IN_CREATE; + +/** + * @tc.name: WatcherDataCacheTest_RemoveWatchedEvents_001 + * @tc.desc: Test function of WatcherDataCache::RemoveWatchedEvents SUCCESS. + * @tc.size: SMALL + * @tc.type: FUNC + * @tc.level Level 0 + */ +HWTEST_F(WatcherDataCacheTest, WatcherDataCacheTest_RemoveWatchedEvents_001, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "WatcherDataCacheTest-begin WatcherDataCacheTest_RemoveWatchedEvents_001"; + // Prepare test condition + WatcherDataCache cache; + auto fileName = "WatcherDataCacheTest_RemoveWatchedEvents_001"; + cache.wdFileNameCache_[fileName] = std::make_pair(EXPECTED_WD, IN_ACCESS); + // Do testing + cache.RemoveWatchedEvents(fileName); + // Verify results + EXPECT_TRUE(cache.wdFileNameCache_.empty()); + GTEST_LOG_(INFO) << "WatcherDataCacheTest-end WatcherDataCacheTest_RemoveWatchedEvents_001"; +} + +/** + * @tc.name: WatcherDataCacheTest_RemoveWatchedEvents_002 + * @tc.desc: Test function of WatcherDataCache::RemoveWatchedEvents SUCCESS when key(fileName) not exist. + * @tc.size: SMALL + * @tc.type: FUNC + * @tc.level Level 0 + */ +HWTEST_F(WatcherDataCacheTest, WatcherDataCacheTest_RemoveWatchedEvents_002, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "WatcherDataCacheTest-begin WatcherDataCacheTest_RemoveWatchedEvents_002"; + // Prepare test condition + WatcherDataCache cache; + auto fileName = "WatcherDataCacheTest_RemoveWatchedEvents_002"; + cache.wdFileNameCache_[fileName] = std::make_pair(EXPECTED_WD, IN_ACCESS); + // Do testing + cache.RemoveWatchedEvents("fileName_not_exist"); + // Verify results + EXPECT_EQ(cache.wdFileNameCache_.size(), 1); + cache.wdFileNameCache_.clear(); + GTEST_LOG_(INFO) << "WatcherDataCacheTest-end WatcherDataCacheTest_RemoveWatchedEvents_002"; +} + +/** + * @tc.name: WatcherDataCacheTest_UpdateWatchedEvents_001 + * @tc.desc: Test function of WatcherDataCache::UpdateWatchedEvents SUCCESS when key(fileName) exist. + * @tc.size: SMALL + * @tc.type: FUNC + * @tc.level Level 0 + */ +HWTEST_F(WatcherDataCacheTest, WatcherDataCacheTest_UpdateWatchedEvents_001, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "WatcherDataCacheTest-begin WatcherDataCacheTest_UpdateWatchedEvents_001"; + // Prepare test condition + WatcherDataCache cache; + auto fileName = "WatcherDataCacheTest_UpdateWatchedEvents_001"; + cache.wdFileNameCache_[fileName] = std::make_pair(UNEXPECTED_WD, IN_DELETE); + // Do testing + cache.UpdateWatchedEvents(fileName, EXPECTED_WD, EXPECTED_EVENTS); + // Verify results + EXPECT_EQ(cache.wdFileNameCache_.size(), 1); + EXPECT_EQ(cache.wdFileNameCache_[fileName].first, EXPECTED_WD); + EXPECT_EQ(cache.wdFileNameCache_[fileName].second, EXPECTED_EVENTS); + cache.wdFileNameCache_.clear(); + GTEST_LOG_(INFO) << "WatcherDataCacheTest-end WatcherDataCacheTest_UpdateWatchedEvents_001"; +} + +/** + * @tc.name: WatcherDataCacheTest_UpdateWatchedEvents_002 + * @tc.desc: Test function of WatcherDataCache::UpdateWatchedEvents SUCCESS when key(fileName) not exist. + * @tc.size: SMALL + * @tc.type: FUNC + * @tc.level Level 0 + */ +HWTEST_F(WatcherDataCacheTest, WatcherDataCacheTest_UpdateWatchedEvents_002, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "WatcherDataCacheTest-begin " + "WatcherWatcherDataCacheTest_UpdateWatchedEvents_002DataCacheTest_UpdateWatchedEvents_001"; + // Prepare test condition + WatcherDataCache cache; + auto fileName = "WatcherDataCacheTest_UpdateWatchedEvents_002"; + // Do testing + cache.UpdateWatchedEvents(fileName, EXPECTED_WD, EXPECTED_EVENTS); + // Verify results + EXPECT_EQ(cache.wdFileNameCache_.size(), 1); + EXPECT_EQ(cache.wdFileNameCache_[fileName].first, EXPECTED_WD); + EXPECT_EQ(cache.wdFileNameCache_[fileName].second, EXPECTED_EVENTS); + cache.wdFileNameCache_.clear(); + GTEST_LOG_(INFO) << "WatcherDataCacheTest-end WatcherDataCacheTest_UpdateWatchedEvents_002"; +} + +/** + * @tc.name: WatcherDataCacheTest_FindWatchedEvents_001 + * @tc.desc: Test function of WatcherDataCache::FindWatchedEvents SUCCESS + * @tc.size: SMALL + * @tc.type: FUNC + * @tc.level Level 0 + */ +HWTEST_F(WatcherDataCacheTest, WatcherDataCacheTest_FindWatchedEvents_001, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "WatcherDataCacheTest-begin WatcherDataCacheTest_FindWatchedEvents_001"; + // Prepare test condition + WatcherDataCache cache; + auto fileName = "WatcherDataCacheTest_FindWatchedEvents_001"; + cache.wdFileNameCache_[fileName] = std::make_pair(EXPECTED_WD, EXPECTED_EVENTS); + // Do testing + auto [isWatched, wd, events] = cache.FindWatchedEvents(fileName, IN_ACCESS); + // Verify results + EXPECT_TRUE(isWatched); + EXPECT_EQ(wd, EXPECTED_WD); + EXPECT_EQ(events, EXPECTED_EVENTS); + cache.wdFileNameCache_.clear(); + GTEST_LOG_(INFO) << "WatcherDataCacheTest-end WatcherDataCacheTest_FindWatchedEvents_001"; +} + +/** + * @tc.name: WatcherDataCacheTest_FindWatchedEvents_002 + * @tc.desc: Test function of WatcherDataCache::FindWatchedEvents FAILURE when key(fileName) not exist + * @tc.size: SMALL + * @tc.type: FUNC + * @tc.level Level 0 + */ +HWTEST_F(WatcherDataCacheTest, WatcherDataCacheTest_FindWatchedEvents_002, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "WatcherDataCacheTest-begin WatcherDataCacheTest_FindWatchedEvents_002"; + // Prepare test condition + WatcherDataCache cache; + auto fileName = "WatcherDataCacheTest_FindWatchedEvents_002"; + // Do testing + auto [isWatched, wd, events] = cache.FindWatchedEvents(fileName, IN_ACCESS); + // Verify results + EXPECT_FALSE(isWatched); + EXPECT_EQ(wd, -1); + EXPECT_EQ(events, 0); + cache.wdFileNameCache_.clear(); + GTEST_LOG_(INFO) << "WatcherDataCacheTest-end WatcherDataCacheTest_FindWatchedEvents_002"; +} + +/** + * @tc.name: WatcherDataCacheTest_FindWatchedEvents_003 + * @tc.desc: Test function of WatcherDataCache::FindWatchedEvents FAILURE when event unmatched + * @tc.size: SMALL + * @tc.type: FUNC + * @tc.level Level 0 + */ +HWTEST_F(WatcherDataCacheTest, WatcherDataCacheTest_FindWatchedEvents_003, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "WatcherDataCacheTest-begin WatcherDataCacheTest_FindWatchedEvents_003"; + // Prepare test condition + WatcherDataCache cache; + auto fileName = "WatcherDataCacheTest_FindWatchedEvents_003"; + cache.wdFileNameCache_[fileName] = std::make_pair(EXPECTED_WD, IN_DELETE); + // Do testing + auto [isWatched, wd, events] = cache.FindWatchedEvents(fileName, IN_ACCESS); + // Verify results + EXPECT_FALSE(isWatched); + EXPECT_EQ(wd, EXPECTED_WD); + EXPECT_EQ(events, IN_DELETE); + cache.wdFileNameCache_.clear(); + GTEST_LOG_(INFO) << "WatcherDataCacheTest-end WatcherDataCacheTest_FindWatchedEvents_003"; +} + +} // namespace Test +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS diff --git a/interfaces/test/unittest/js/mod_fs/mock/unistd_mock.cpp b/interfaces/test/unittest/js/mod_fs/mock/unistd_mock.cpp index cda59d9bf..0d05f8b64 100644 --- a/interfaces/test/unittest/js/mod_fs/mock/unistd_mock.cpp +++ b/interfaces/test/unittest/js/mod_fs/mock/unistd_mock.cpp @@ -121,5 +121,26 @@ ssize_t read(int fd, void *buf, size_t count) return realRead(fd, buf, count); } +ssize_t write(int fd, const void *buf, size_t count) +{ + if (UnistdMock::IsMockable()) { + return UnistdMock::GetMock()->write(fd, buf, count); + } + + static ssize_t (*realWrite)(int fd, const void *buf, size_t count) = []() { + auto func = (ssize_t(*)(int, const void *, size_t))dlsym(RTLD_NEXT, "write"); + if (!func) { + GTEST_LOG_(ERROR) << "Failed to resolve real write: " << dlerror(); + } + return func; + }(); + + if (!realWrite) { + return 0; + } + + return realWrite(fd, buf, count); +} + } // extern "C" #endif \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/mock/unistd_mock.h b/interfaces/test/unittest/js/mod_fs/mock/unistd_mock.h index ec6f961e1..3771b1424 100644 --- a/interfaces/test/unittest/js/mod_fs/mock/unistd_mock.h +++ b/interfaces/test/unittest/js/mod_fs/mock/unistd_mock.h @@ -30,6 +30,7 @@ public: virtual int access(const char *, int) = 0; virtual int close(int) = 0; virtual ssize_t read(int, void *, size_t) = 0; + virtual ssize_t write(int, const void *, size_t) = 0; }; class UnistdMock : public IUnistdMock { @@ -37,6 +38,7 @@ public: MOCK_METHOD(int, access, (const char *, int), (override)); MOCK_METHOD(int, close, (int), (override)); MOCK_METHOD(ssize_t, read, (int, void *, size_t), (override)); + MOCK_METHOD(ssize_t, write, (int, const void *, size_t), (override)); public: static std::shared_ptr GetMock(); diff --git a/interfaces/test/unittest/js/mod_fs/properties/watcher_core_mock_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/watcher_core_mock_test.cpp index 680a2ce32..f9695cfb0 100644 --- a/interfaces/test/unittest/js/mod_fs/properties/watcher_core_mock_test.cpp +++ b/interfaces/test/unittest/js/mod_fs/properties/watcher_core_mock_test.cpp @@ -101,7 +101,7 @@ HWTEST_F(WatcherCoreMockTest, WatcherCoreMockTest_DoCreateWatcher_001, testing:: /** * @tc.name: WatcherCoreMockTest_DoCreateWatcher_002 - * @tc.desc: Test function of WatcherCore::DoCreateWatcher interface for FAILURE when InitNotify fails. + * @tc.desc: Test function of WatcherCore::DoCreateWatcher interface for FAILURE when TryInitNotify fails. * @tc.size: MEDIUM * @tc.type: FUNC * @tc.level Level 1 -- Gitee From cda83987397349d5148a1c01e68c4f68d4df470d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A7=9C=E5=B0=8F=E6=9E=97?= Date: Thu, 28 Aug 2025 10:25:35 +0800 Subject: [PATCH 2/3] =?UTF-8?q?=E6=A0=B9=E6=8D=AE=E6=A3=80=E8=A7=86?= =?UTF-8?q?=E6=84=8F=E8=A7=81=E8=BF=9B=E8=A1=8C=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Change-Id: Id1e30d0a595a03a7329832c03a928429ba780678 Signed-off-by: 姜小林 --- .../mod_fs/class_watcher/fs_file_watcher.cpp | 36 ++++-- .../mod_fs/class_watcher/fs_file_watcher.h | 5 +- interfaces/test/unittest/js/BUILD.gn | 1 + .../mod_fs/class_file/fs_file_mock_test.cpp | 45 ++++--- .../mod_fs/class_stat/fs_stat_mock_test.cpp | 15 +-- .../class_stream/fs_stream_mock_test.cpp | 4 + .../fs_file_watcher_mock_test.cpp | 43 ++++--- .../class_watcher/fs_watcher_mock_test.cpp | 2 + .../class_watcher/watcher_data_cache_test.cpp | 31 +++-- .../properties/close_core_mock_test.cpp | 82 ++++++++++++ .../js/mod_fs/properties/close_core_test.cpp | 119 +++++++----------- .../mod_fs/properties/copy_core_mock_test.cpp | 18 +-- .../properties/copy_file_core_mock_test.cpp | 48 +++---- .../properties/create_stream_core_test.cpp | 60 ++++----- .../properties/fdopen_stream_core_test.cpp | 76 +++++------ .../js/mod_fs/properties/lstat_core_test.cpp | 9 +- .../js/mod_fs/properties/mock/system_mock.cpp | 117 ++++++++++++++++- .../js/mod_fs/properties/mock/system_mock.h | 23 ++-- .../mod_fs/properties/stat_core_mock_test.cpp | 4 +- .../properties/trans_listener_mock_test.cpp | 3 +- .../properties/watcher_core_mock_test.cpp | 2 + .../properties/xattr_core_mock_test.cpp | 40 +++--- .../js/mod_statvfs/statvfs_core_test.cpp | 6 +- 23 files changed, 495 insertions(+), 294 deletions(-) create mode 100644 interfaces/test/unittest/js/mod_fs/properties/close_core_mock_test.cpp diff --git a/interfaces/kits/js/src/mod_fs/class_watcher/fs_file_watcher.cpp b/interfaces/kits/js/src/mod_fs/class_watcher/fs_file_watcher.cpp index 079e6cfb0..70a0d9d3e 100644 --- a/interfaces/kits/js/src/mod_fs/class_watcher/fs_file_watcher.cpp +++ b/interfaces/kits/js/src/mod_fs/class_watcher/fs_file_watcher.cpp @@ -120,6 +120,7 @@ int32_t FsFileWatcher::CloseNotifyFd() HILOGE("Failed to close eventfd errCode:%{public}d", errno); } eventFd_ = -1; + HILOGD("NotifyFd and eventFd have been closed"); } closed_ = false; @@ -182,16 +183,18 @@ int32_t FsFileWatcher::StopNotify(shared_ptr info) } dataCache_.RemoveWatchedEvents(info->fileName); - return CloseNotifyFdLocked(); + auto ret = CloseNotifyFdLocked(); + HILOGD("Close notifyFd and eventFd ret: %{public}d", ret); + return ret; } void FsFileWatcher::ReadNotifyEvent() { int32_t len = 0; - int32_t index = 0; + uint32_t index = 0; char buf[BUF_SIZE] = { 0 }; struct inotify_event *event = nullptr; - int32_t eventSize = static_cast(sizeof(struct inotify_event)); + uint32_t eventSize = static_cast(sizeof(struct inotify_event)); do { len = read(notifyFd_, &buf, sizeof(buf)); @@ -201,21 +204,25 @@ void FsFileWatcher::ReadNotifyEvent() } } while (len < 0); - while (index < len) { + while (len > 0 && index < len) { event = reinterpret_cast(buf + index); + + // Incomplete data: remaining bytes less than event struct size if ((len - index) < eventSize) { HILOGE( - "out of bounds access, len:%{public}d, index: %{public}d, inotify: %{public}d", len, index, eventSize); + "Out of bounds access, len:%{public}d, index: %{public}u, inotify: %{public}u", len, index, eventSize); break; } - if (event->len > (static_cast(len - index - eventSize))) { - HILOGE("out of bounds access, index: %{public}d, inotify: %{public}d, " - "event :%{public}u, len: %{public}d", + + // Incomplete data: remaining bytes less than (event struct size + event->len) + if (event->len > len - index - eventSize) { + HILOGE("Out of bounds access, index: %{public}u, inotify: %{public}u, event :%{public}u, len: %{public}d", index, eventSize, event->len, len); break; } + NotifyEvent(event); - index += eventSize + static_cast(event->len); + index += eventSize + event->len; } } @@ -316,6 +323,7 @@ void FsFileWatcher::NotifyEvent(const struct inotify_event *event) auto [matched, fileName, watcherInfos] = dataCache_.FindWatcherInfos(event->wd, event->mask); if (!matched) { // ignore unmatched event + HILOGD("Cannot find matched watcherInfos"); return; } @@ -353,11 +361,13 @@ void FsFileWatcher::DestroyTaskThread() void FsFileWatcher::WakeupThread() { if (taskRunning_ && eventFd_ >= 0 && taskThread_.joinable()) { - uint64_t val = 1; - auto ret = write(eventFd_, &val, sizeof(val)); - if (ret != sizeof(val)) { - HILOGE("WakeupThread failed! errno: %{public}d", errno); + ssize_t ret = write(eventFd_, &wakeupSignal, sizeof(wakeupSignal)); + if (ret != sizeof(wakeupSignal)) { + HILOGE("WakeupThread failed! write ret: %{public}zd, errno: %{public}d", ret, errno); } + } else { + HILOGE("Cannot wakeup thread! taskRunning: %{public}d, eventFd_: %{public}d, taskThread joinable: %{public}d", + static_cast(taskRunning_), eventFd_, static_cast(taskThread_.joinable())); } } } // namespace OHOS::FileManagement::ModuleFileIO diff --git a/interfaces/kits/js/src/mod_fs/class_watcher/fs_file_watcher.h b/interfaces/kits/js/src/mod_fs/class_watcher/fs_file_watcher.h index 2a114cb13..f51f414ba 100644 --- a/interfaces/kits/js/src/mod_fs/class_watcher/fs_file_watcher.h +++ b/interfaces/kits/js/src/mod_fs/class_watcher/fs_file_watcher.h @@ -61,6 +61,7 @@ private: private: static constexpr int32_t pollTimeoutMs = 500; + static constexpr uint64_t wakeupSignal = 1; mutex readMutex_; mutex notifyMutex_; @@ -69,8 +70,8 @@ private: thread taskThread_; atomic run_ { false }; - bool reading_ = false; - bool closed_ = false; + atomic reading_ { false }; + atomic closed_ { false }; int32_t notifyFd_ = -1; int32_t eventFd_ = -1; WatcherDataCache dataCache_; diff --git a/interfaces/test/unittest/js/BUILD.gn b/interfaces/test/unittest/js/BUILD.gn index 5606c4743..368bb6062 100644 --- a/interfaces/test/unittest/js/BUILD.gn +++ b/interfaces/test/unittest/js/BUILD.gn @@ -157,6 +157,7 @@ ohos_unittest("ani_file_fs_mock_test") { "mod_fs/mock/poll_mock.cpp", "mod_fs/mock/unistd_mock.cpp", "mod_fs/properties/access_core_mock_test.cpp", + "mod_fs/properties/close_core_mock_test.cpp", "mod_fs/properties/copy_core_mock_test.cpp", "mod_fs/properties/copy_file_core_mock_test.cpp", "mod_fs/properties/create_randomaccessfile_core_mock_test.cpp", diff --git a/interfaces/test/unittest/js/mod_fs/class_file/fs_file_mock_test.cpp b/interfaces/test/unittest/js/mod_fs/class_file/fs_file_mock_test.cpp index 90cc1f29f..c3c3bd1fc 100644 --- a/interfaces/test/unittest/js/mod_fs/class_file/fs_file_mock_test.cpp +++ b/interfaces/test/unittest/js/mod_fs/class_file/fs_file_mock_test.cpp @@ -33,7 +33,7 @@ public: void SetUp(); void TearDown(); static inline shared_ptr uvMock = nullptr; - static inline shared_ptr sys = nullptr; + // static inline shared_ptr sys = nullptr; std::unique_ptr fileEntity; std::unique_ptr fsFile; }; @@ -41,10 +41,9 @@ public: void FsFileMockTest::SetUpTestCase(void) { GTEST_LOG_(INFO) << "SetUpTestCase"; + SystemMock::EnableMock(); uvMock = std::make_shared(); Uvfs::ins = uvMock; - sys = std::make_shared(); - System::ins = sys; } void FsFileMockTest::TearDownTestCase(void) @@ -52,14 +51,13 @@ void FsFileMockTest::TearDownTestCase(void) GTEST_LOG_(INFO) << "TearDownTestCase"; Uvfs::ins = nullptr; uvMock = nullptr; - System::ins = nullptr; - sys = nullptr; + SystemMock::DisableMock(); } void FsFileMockTest::SetUp(void) { GTEST_LOG_(INFO) << "SetUp"; - + fileEntity = std::make_unique(); const int fdValue = 3; const bool isClosed = false; @@ -86,10 +84,10 @@ HWTEST_F(FsFileMockTest, FsFileMockTest_GetPath_001, testing::ext::TestSize.Leve GTEST_LOG_(INFO) << "FsFileMockTest-begin FsFileMockTest_GetPath_001"; uv_fs_t mock_req; - mock_req.ptr = const_cast("/data/test/file_test.txt"); + mock_req.ptr = const_cast("/data/test/file_test.txt"); EXPECT_CALL(*uvMock, uv_fs_realpath(_, _, _, _)) - .WillOnce(Invoke([&](uv_loop_t*, uv_fs_t* req, const char*, uv_fs_cb) { + .WillOnce(Invoke([&](uv_loop_t *, uv_fs_t *req, const char *, uv_fs_cb) { *req = mock_req; return 0; })); @@ -187,10 +185,10 @@ HWTEST_F(FsFileMockTest, FsFileMockTest_GetName_006, testing::ext::TestSize.Leve GTEST_LOG_(INFO) << "FsFileMockTest-begin FsFileMockTest_GetName_006"; uv_fs_t mock_req; - mock_req.ptr = const_cast("/file_test.txt"); + mock_req.ptr = const_cast("/file_test.txt"); EXPECT_CALL(*uvMock, uv_fs_realpath(_, _, _, _)) - .WillOnce(Invoke([&](uv_loop_t*, uv_fs_t* req, const char*, uv_fs_cb) { + .WillOnce(Invoke([&](uv_loop_t *, uv_fs_t *req, const char *, uv_fs_cb) { *req = mock_req; return 0; })); @@ -212,10 +210,10 @@ HWTEST_F(FsFileMockTest, FsFileMockTest_GetParent_007, testing::ext::TestSize.Le GTEST_LOG_(INFO) << "FsFileMockTest-begin FsFileMockTest_GetParent_007"; uv_fs_t mock_req; - mock_req.ptr = const_cast("/test/dir_test"); + mock_req.ptr = const_cast("/test/dir_test"); EXPECT_CALL(*uvMock, uv_fs_realpath(_, _, _, _)) - .WillOnce(Invoke([&](uv_loop_t*, uv_fs_t* req, const char*, uv_fs_cb) { + .WillOnce(Invoke([&](uv_loop_t *, uv_fs_t *req, const char *, uv_fs_cb) { *req = mock_req; return 0; })); @@ -237,10 +235,10 @@ HWTEST_F(FsFileMockTest, FsFileMockTest_GetName_008, testing::ext::TestSize.Leve GTEST_LOG_(INFO) << "FsFileMockTest-begin FsFileMockTest_GetName_008"; uv_fs_t mock_req; - mock_req.ptr = const_cast("file_test.txt"); + mock_req.ptr = const_cast("file_test.txt"); EXPECT_CALL(*uvMock, uv_fs_realpath(_, _, _, _)) - .WillOnce(Invoke([&](uv_loop_t*, uv_fs_t* req, const char*, uv_fs_cb) { + .WillOnce(Invoke([&](uv_loop_t *, uv_fs_t *req, const char *, uv_fs_cb) { *req = mock_req; return 0; })); @@ -262,10 +260,10 @@ HWTEST_F(FsFileMockTest, FsFileMockTest_GetParent_009, testing::ext::TestSize.Le GTEST_LOG_(INFO) << "FsFileMockTest-begin FsFileMockTest_GetParent_009"; uv_fs_t mock_req; - mock_req.ptr = const_cast("dir_test"); + mock_req.ptr = const_cast("dir_test"); EXPECT_CALL(*uvMock, uv_fs_realpath(_, _, _, _)) - .WillOnce(Invoke([&](uv_loop_t*, uv_fs_t* req, const char*, uv_fs_cb) { + .WillOnce(Invoke([&](uv_loop_t *, uv_fs_t *req, const char *, uv_fs_cb) { *req = mock_req; return 0; })); @@ -285,9 +283,10 @@ HWTEST_F(FsFileMockTest, FsFileMockTest_GetParent_009, testing::ext::TestSize.Le HWTEST_F(FsFileMockTest, FsFileMockTest_Lock_010, testing::ext::TestSize.Level1) { GTEST_LOG_(INFO) << "FsFileMockTest-begin FsFileMockTest_Lock_010"; - + auto sys = SystemMock::GetMock(); EXPECT_CALL(*sys, flock(_, _)).WillOnce(Return(1)); auto result = fsFile->Lock(true); + testing::Mock::VerifyAndClearExpectations(sys.get()); EXPECT_EQ(result.IsSuccess(), true); GTEST_LOG_(INFO) << "FsFileMockTest-end FsFileMockTest_Lock_010"; @@ -304,8 +303,10 @@ HWTEST_F(FsFileMockTest, FsFileMockTest_Lock_011, testing::ext::TestSize.Level1) { GTEST_LOG_(INFO) << "FsFileMockTest-begin FsFileMockTest_Lock_011"; + auto sys = SystemMock::GetMock(); EXPECT_CALL(*sys, flock(_, _)).WillOnce(Return(-1)); auto result = fsFile->Lock(false); + testing::Mock::VerifyAndClearExpectations(sys.get()); EXPECT_EQ(result.IsSuccess(), false); GTEST_LOG_(INFO) << "FsFileMockTest-end FsFileMockTest_Lock_011"; @@ -322,8 +323,10 @@ HWTEST_F(FsFileMockTest, FsFileMockTest_TryLock_012, testing::ext::TestSize.Leve { GTEST_LOG_(INFO) << "FsFileMockTest-begin FsFileMockTest_TryLock_012"; + auto sys = SystemMock::GetMock(); EXPECT_CALL(*sys, flock(_, _)).WillOnce(Return(1)); auto result = fsFile->TryLock(true); + testing::Mock::VerifyAndClearExpectations(sys.get()); EXPECT_EQ(result.IsSuccess(), true); GTEST_LOG_(INFO) << "FsFileMockTest-end FsFileMockTest_TryLock_012"; @@ -340,8 +343,10 @@ HWTEST_F(FsFileMockTest, FsFileMockTest_TryLock_013, testing::ext::TestSize.Leve { GTEST_LOG_(INFO) << "FsFileMockTest-begin FsFileMockTest_TryLock_013"; + auto sys = SystemMock::GetMock(); EXPECT_CALL(*sys, flock(_, _)).WillOnce(Return(-1)); auto result = fsFile->TryLock(false); + testing::Mock::VerifyAndClearExpectations(sys.get()); EXPECT_EQ(result.IsSuccess(), false); GTEST_LOG_(INFO) << "FsFileMockTest-end FsFileMockTest_TryLock_013"; @@ -358,8 +363,10 @@ HWTEST_F(FsFileMockTest, FsFileMockTest_UnLock_014, testing::ext::TestSize.Level { GTEST_LOG_(INFO) << "FsFileMockTest-begin FsFileMockTest_UnLock_014"; + auto sys = SystemMock::GetMock(); EXPECT_CALL(*sys, flock(_, _)).WillOnce(Return(1)); auto result = fsFile->UnLock(); + testing::Mock::VerifyAndClearExpectations(sys.get()); EXPECT_EQ(result.IsSuccess(), true); GTEST_LOG_(INFO) << "FsFileMockTest-end FsFileMockTest_UnLock_014"; @@ -376,11 +383,13 @@ HWTEST_F(FsFileMockTest, FsFileMockTest_UnLock_015, testing::ext::TestSize.Level { GTEST_LOG_(INFO) << "FsFileMockTest-begin FsFileMockTest_UnLock_015"; + auto sys = SystemMock::GetMock(); EXPECT_CALL(*sys, flock(_, _)).WillOnce(Return(-1)); auto result = fsFile->UnLock(); + testing::Mock::VerifyAndClearExpectations(sys.get()); EXPECT_EQ(result.IsSuccess(), false); GTEST_LOG_(INFO) << "FsFileMockTest-end FsFileMockTest_UnLock_015"; } -} \ No newline at end of file +} // namespace OHOS::FileManagement::ModuleFileIO::Test \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/class_stat/fs_stat_mock_test.cpp b/interfaces/test/unittest/js/mod_fs/class_stat/fs_stat_mock_test.cpp index 2de8331e0..74cbaf84a 100644 --- a/interfaces/test/unittest/js/mod_fs/class_stat/fs_stat_mock_test.cpp +++ b/interfaces/test/unittest/js/mod_fs/class_stat/fs_stat_mock_test.cpp @@ -32,21 +32,18 @@ public: static void TearDownTestCase(void); void SetUp(); void TearDown(); - static inline shared_ptr sys = nullptr; }; void FsStatMockTest::SetUpTestCase(void) { GTEST_LOG_(INFO) << "SetUpTestCase"; - sys = make_shared(); - System::ins = sys; + SystemMock::EnableMock(); } void FsStatMockTest::TearDownTestCase(void) { GTEST_LOG_(INFO) << "TearDownTestCase"; - System::ins = nullptr; - sys = nullptr; + SystemMock::DisableMock(); } void FsStatMockTest::SetUp(void) @@ -82,8 +79,10 @@ HWTEST_F(FsStatMockTest, FsStatMockTest_GetLocation_001, testing::ext::TestSize. statEntity->fileInfo_->path.get()[99] = '\0'; fsStat = make_unique(move(statEntity)); + auto sys = SystemMock::GetMock(); EXPECT_CALL(*sys, getxattr(_, _, _, _)).WillOnce(Return(1)); EXPECT_EQ(fsStat->GetLocation(), 1); + testing::Mock::VerifyAndClearExpectations(sys.get()); GTEST_LOG_(INFO) << "FsStatMockTes-end FsStatMockTest_GetLocation_001"; } @@ -104,15 +103,17 @@ HWTEST_F(FsStatMockTest, FsStatMockTest_GetLocation_002, testing::ext::TestSize. statEntity = make_unique(); statEntity->fileInfo_ = make_unique(); statEntity->fileInfo_->isPath = false; - const int fdValue = 3; //模拟fd为3 + const int fdValue = 3; // 模拟fd为3 const bool isClosed = false; statEntity->fileInfo_->fdg = make_unique(fdValue, isClosed); fsStat = make_unique(move(statEntity)); + auto sys = SystemMock::GetMock(); EXPECT_CALL(*sys, fgetxattr(_, _, _, _)).WillOnce(Return(1)); EXPECT_EQ(fsStat->GetLocation(), 1); + testing::Mock::VerifyAndClearExpectations(sys.get()); GTEST_LOG_(INFO) << "FsStatMockTes-end FsStatMockTest_GetLocation_002"; } -} \ No newline at end of file +} // namespace OHOS::FileManagement::ModuleFileIO::Test \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/class_stream/fs_stream_mock_test.cpp b/interfaces/test/unittest/js/mod_fs/class_stream/fs_stream_mock_test.cpp index 5641bd86b..79eb1db42 100644 --- a/interfaces/test/unittest/js/mod_fs/class_stream/fs_stream_mock_test.cpp +++ b/interfaces/test/unittest/js/mod_fs/class_stream/fs_stream_mock_test.cpp @@ -32,6 +32,10 @@ public: { CMock::EnableMock(); int32_t fd = open(g_streamFilePath.c_str(), CREATE | O_RDWR, 0644); + if (fd < 0) { + GTEST_LOG_(ERROR) << "Open test file failed! ret: " << fd << ", errno: " << errno; + ASSERT_TRUE(false); + } close(fd); }; static void TearDownTestCase() diff --git a/interfaces/test/unittest/js/mod_fs/class_watcher/fs_file_watcher_mock_test.cpp b/interfaces/test/unittest/js/mod_fs/class_watcher/fs_file_watcher_mock_test.cpp index 446b5ac10..d472a26df 100644 --- a/interfaces/test/unittest/js/mod_fs/class_watcher/fs_file_watcher_mock_test.cpp +++ b/interfaces/test/unittest/js/mod_fs/class_watcher/fs_file_watcher_mock_test.cpp @@ -18,6 +18,7 @@ #include #include +#include #include "eventfd_mock.h" #include "filemgmt_libhilog.h" @@ -44,6 +45,7 @@ public: void FsFileWatcherMockTest::SetUpTestCase(void) { GTEST_LOG_(INFO) << "SetUpTestCase"; + prctl(PR_SET_NAME, "FsFileWatcherMockTest"); EventfdMock::EnableMock(); InotifyMock::EnableMock(); PollMock::EnableMock(); @@ -87,7 +89,7 @@ inline const int32_t UNINITIALIZED_EVENTFD = -1; /** * @tc.name: FsFileWatcherMockTest_TryInitNotify_001 - * @tc.desc: Test function of FsFileWatcher::TryInitNotify interface SUCCESS When notifyFd_ has initialed. + * @tc.desc: Test function of FsFileWatcher::TryInitNotify interface for SUCCESS When notifyFd_ has initialed. * @tc.size: SMALL * @tc.type: FUNC * @tc.level Level 0 @@ -1133,7 +1135,7 @@ HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_ReadNotifyEvent_004, testi /** * @tc.name: FsFileWatcherMockTest_ReadNotifyEvent_005 - * @tc.desc: Test function of FsFileWatcher::ReadNotifyEvent interface for FAILURE when read incomplete event struct. + * @tc.desc: Test function of FsFileWatcher::ReadNotifyEvent interface for FAILURE when read incomplete event data. * @tc.size: MEDIUM * @tc.type: FUNC * @tc.level Level 0 @@ -1464,7 +1466,6 @@ HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_DestroyTaskThread_002, tes if (watcher.taskThread_.joinable()) { watcher.taskThread_.join(); } - watcher.taskThread_ = std::thread(); GTEST_LOG_(INFO) << "FsFileWatcherMockTest-end FsFileWatcherMockTest_DestroyTaskThread_002"; } @@ -1492,7 +1493,7 @@ HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_DestroyTaskThread_003, tes /** * @tc.name: FsFileWatcherMockTest_WakeupThread_001 - * @tc.desc: Test function of FsFileWatcher::WakeupThread interface SUCCESS. + * @tc.desc: Test function of FsFileWatcher::WakeupThread interface for SUCCESS. * @tc.size: MEDIUM * @tc.type: FUNC * @tc.level Level 1 @@ -1532,13 +1533,12 @@ HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_WakeupThread_001, testing: if (watcher.taskThread_.joinable()) { watcher.taskThread_.join(); } - watcher.taskThread_ = std::thread(); GTEST_LOG_(INFO) << "FsFileWatcherMockTest-end FsFileWatcherMockTest_WakeupThread_001"; } /** * @tc.name: FsFileWatcherMockTest_WakeupThread_002 - * @tc.desc: Test function of FsFileWatcher::WakeupThread interface FAILURE when taskRunning_ is false. + * @tc.desc: Test function of FsFileWatcher::WakeupThread interface for FAILURE when taskRunning_ is false. * @tc.size: MEDIUM * @tc.type: FUNC * @tc.level Level 1 @@ -1564,14 +1564,14 @@ HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_WakeupThread_002, testing: /** * @tc.name: FsFileWatcherMockTest_WakeupThread_003 - * @tc.desc: Test function of FsFileWatcher::WakeupThread interface FAILURE when eventFd_ < 0. + * @tc.desc: Test function of FsFileWatcher::WakeupThread interface for FAILURE when eventFd_ < 0. * @tc.size: MEDIUM * @tc.type: FUNC * @tc.level Level 1 */ HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_WakeupThread_003, testing::ext::TestSize.Level1) { - GTEST_LOG_(INFO) << "FsFileWatcherMockTest-begin FsFileWatcherMockTest_WakeupThread_002"; + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-begin FsFileWatcherMockTest_WakeupThread_003"; // Prepare test condition FsFileWatcher &watcher = FsFileWatcher::GetInstance(); watcher.taskRunning_ = true; @@ -1585,19 +1585,19 @@ HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_WakeupThread_003, testing: testing::Mock::VerifyAndClearExpectations(unistdMock.get()); EXPECT_TRUE(watcher.taskRunning_); EXPECT_EQ(watcher.eventFd_, UNINITIALIZED_EVENTFD); - GTEST_LOG_(INFO) << "FsFileWatcherMockTest-end FsFileWatcherMockTest_WakeupThread_002"; + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-end FsFileWatcherMockTest_WakeupThread_003"; } /** * @tc.name: FsFileWatcherMockTest_WakeupThread_004 - * @tc.desc: Test function of FsFileWatcher::WakeupThread interface FAILURE when eventFd_ < 0. + * @tc.desc: Test function of FsFileWatcher::WakeupThread interface for FAILURE when taskThread_ is not joinable. * @tc.size: MEDIUM * @tc.type: FUNC * @tc.level Level 1 */ HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_WakeupThread_004, testing::ext::TestSize.Level1) { - GTEST_LOG_(INFO) << "FsFileWatcherMockTest-begin FsFileWatcherMockTest_WakeupThread_002"; + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-begin FsFileWatcherMockTest_WakeupThread_004"; // Prepare test condition FsFileWatcher &watcher = FsFileWatcher::GetInstance(); watcher.taskRunning_ = true; @@ -1612,19 +1612,19 @@ HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_WakeupThread_004, testing: testing::Mock::VerifyAndClearExpectations(unistdMock.get()); EXPECT_TRUE(watcher.taskRunning_); EXPECT_EQ(watcher.eventFd_, INITIALIZED_EVENTFD); - GTEST_LOG_(INFO) << "FsFileWatcherMockTest-end FsFileWatcherMockTest_WakeupThread_002"; + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-end FsFileWatcherMockTest_WakeupThread_004"; } /** * @tc.name: FsFileWatcherMockTest_WakeupThread_005 - * @tc.desc: Test function of FsFileWatcher::WakeupThread interface SUCCESS. + * @tc.desc: Test function of FsFileWatcher::WakeupThread interface for FAILURE when write fails. * @tc.size: MEDIUM * @tc.type: FUNC * @tc.level Level 1 */ HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_WakeupThread_005, testing::ext::TestSize.Level1) { - GTEST_LOG_(INFO) << "FsFileWatcherMockTest-begin FsFileWatcherMockTest_WakeupThread_001"; + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-begin FsFileWatcherMockTest_WakeupThread_005"; // Prepare test condition std::atomic keepAlive(false); std::thread mockThread([&]() { @@ -1658,8 +1658,7 @@ HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_WakeupThread_005, testing: if (watcher.taskThread_.joinable()) { watcher.taskThread_.join(); } - watcher.taskThread_ = std::thread(); - GTEST_LOG_(INFO) << "FsFileWatcherMockTest-end FsFileWatcherMockTest_WakeupThread_001"; + GTEST_LOG_(INFO) << "FsFileWatcherMockTest-end FsFileWatcherMockTest_WakeupThread_005"; } /** @@ -1711,7 +1710,7 @@ HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_CloseNotifyFdLocked_002, t /** * @tc.name: FsFileWatcherMockTest_CloseNotifyFd_001 - * @tc.desc: Test function of FsFileWatcher::CloseNotifyFd interface SUCCESS when HasWatcherInfo is true. + * @tc.desc: Test function of FsFileWatcher::CloseNotifyFd interface for SUCCESS when HasWatcherInfo is true. * @tc.size: SMALL * @tc.type: FUNC * @tc.level Level 1 @@ -1748,7 +1747,7 @@ HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_CloseNotifyFd_001, testing /** * @tc.name: FsFileWatcherMockTest_CloseNotifyFd_002 - * @tc.desc: Test function of FsFileWatcher::CloseNotifyFd interface SUCCESS when HasWatcherInfo is false. + * @tc.desc: Test function of FsFileWatcher::CloseNotifyFd interface for SUCCESS when HasWatcherInfo is false. * @tc.size: SMALL * @tc.type: FUNC * @tc.level Level 1 @@ -1780,7 +1779,8 @@ HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_CloseNotifyFd_002, testing /** * @tc.name: FsFileWatcherMockTest_CloseNotifyFd_003 - * @tc.desc: Test function of FsFileWatcher::CloseNotifyFd interface FAILURE when close notifyFd_ and eventFd_ fails. + * @tc.desc: Test function of FsFileWatcher::CloseNotifyFd interface for FAILURE when close notifyFd_ and eventFd_ + * fails. * @tc.size: SMALL * @tc.type: FUNC * @tc.level Level 1 @@ -1813,7 +1813,7 @@ HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_CloseNotifyFd_003, testing /** * @tc.name: FsFileWatcherMockTest_AsyncGetNotifyEvent_001 - * @tc.desc: Test function of FsFileWatcher::AsyncGetNotifyEvent interface SUCCESS. + * @tc.desc: Test function of FsFileWatcher::AsyncGetNotifyEvent interface for SUCCESS. * @tc.size: SMALL * @tc.type: FUNC * @tc.level Level 1 @@ -1830,6 +1830,9 @@ HWTEST_F(FsFileWatcherMockTest, FsFileWatcherMockTest_AsyncGetNotifyEvent_001, t // Verify results EXPECT_TRUE(watcher.run_); EXPECT_TRUE(watcher.taskRunning_); + if (watcher.taskThread_.joinable()) { + watcher.taskThread_.join(); + } GTEST_LOG_(INFO) << "FsFileWatcherMockTest-end FsFileWatcherMockTest_AsyncGetNotifyEvent_001"; } diff --git a/interfaces/test/unittest/js/mod_fs/class_watcher/fs_watcher_mock_test.cpp b/interfaces/test/unittest/js/mod_fs/class_watcher/fs_watcher_mock_test.cpp index 5be1fde4e..30042270a 100644 --- a/interfaces/test/unittest/js/mod_fs/class_watcher/fs_watcher_mock_test.cpp +++ b/interfaces/test/unittest/js/mod_fs/class_watcher/fs_watcher_mock_test.cpp @@ -17,6 +17,7 @@ #include #include +#include #include "file_utils.h" #include "filemgmt_libhilog.h" @@ -42,6 +43,7 @@ public: void FsWatcherMockTest::SetUpTestCase(void) { GTEST_LOG_(INFO) << "SetUpTestCase"; + prctl(PR_SET_NAME, "FsWatcherMockTest"); InotifyMock::EnableMock(); UnistdMock::EnableMock(); } diff --git a/interfaces/test/unittest/js/mod_fs/class_watcher/watcher_data_cache_test.cpp b/interfaces/test/unittest/js/mod_fs/class_watcher/watcher_data_cache_test.cpp index 0c4d2f200..999062ac8 100644 --- a/interfaces/test/unittest/js/mod_fs/class_watcher/watcher_data_cache_test.cpp +++ b/interfaces/test/unittest/js/mod_fs/class_watcher/watcher_data_cache_test.cpp @@ -62,7 +62,7 @@ inline const uint32_t EXPECTED_EVENTS = IN_ACCESS | IN_CREATE; /** * @tc.name: WatcherDataCacheTest_RemoveWatchedEvents_001 - * @tc.desc: Test function of WatcherDataCache::RemoveWatchedEvents SUCCESS. + * @tc.desc: Test function of WatcherDataCache::RemoveWatchedEvents for SUCCESS. * @tc.size: SMALL * @tc.type: FUNC * @tc.level Level 0 @@ -72,7 +72,7 @@ HWTEST_F(WatcherDataCacheTest, WatcherDataCacheTest_RemoveWatchedEvents_001, tes GTEST_LOG_(INFO) << "WatcherDataCacheTest-begin WatcherDataCacheTest_RemoveWatchedEvents_001"; // Prepare test condition WatcherDataCache cache; - auto fileName = "WatcherDataCacheTest_RemoveWatchedEvents_001"; + auto fileName = "fakePath/WatcherDataCacheTest_RemoveWatchedEvents_001"; cache.wdFileNameCache_[fileName] = std::make_pair(EXPECTED_WD, IN_ACCESS); // Do testing cache.RemoveWatchedEvents(fileName); @@ -83,7 +83,7 @@ HWTEST_F(WatcherDataCacheTest, WatcherDataCacheTest_RemoveWatchedEvents_001, tes /** * @tc.name: WatcherDataCacheTest_RemoveWatchedEvents_002 - * @tc.desc: Test function of WatcherDataCache::RemoveWatchedEvents SUCCESS when key(fileName) not exist. + * @tc.desc: Test function of WatcherDataCache::RemoveWatchedEvents for SUCCESS when key(fileName) not exist. * @tc.size: SMALL * @tc.type: FUNC * @tc.level Level 0 @@ -93,7 +93,7 @@ HWTEST_F(WatcherDataCacheTest, WatcherDataCacheTest_RemoveWatchedEvents_002, tes GTEST_LOG_(INFO) << "WatcherDataCacheTest-begin WatcherDataCacheTest_RemoveWatchedEvents_002"; // Prepare test condition WatcherDataCache cache; - auto fileName = "WatcherDataCacheTest_RemoveWatchedEvents_002"; + auto fileName = "fakePath/WatcherDataCacheTest_RemoveWatchedEvents_002"; cache.wdFileNameCache_[fileName] = std::make_pair(EXPECTED_WD, IN_ACCESS); // Do testing cache.RemoveWatchedEvents("fileName_not_exist"); @@ -105,7 +105,7 @@ HWTEST_F(WatcherDataCacheTest, WatcherDataCacheTest_RemoveWatchedEvents_002, tes /** * @tc.name: WatcherDataCacheTest_UpdateWatchedEvents_001 - * @tc.desc: Test function of WatcherDataCache::UpdateWatchedEvents SUCCESS when key(fileName) exist. + * @tc.desc: Test function of WatcherDataCache::UpdateWatchedEvents for SUCCESS when key(fileName) exist. * @tc.size: SMALL * @tc.type: FUNC * @tc.level Level 0 @@ -115,7 +115,7 @@ HWTEST_F(WatcherDataCacheTest, WatcherDataCacheTest_UpdateWatchedEvents_001, tes GTEST_LOG_(INFO) << "WatcherDataCacheTest-begin WatcherDataCacheTest_UpdateWatchedEvents_001"; // Prepare test condition WatcherDataCache cache; - auto fileName = "WatcherDataCacheTest_UpdateWatchedEvents_001"; + auto fileName = "fakePath/WatcherDataCacheTest_UpdateWatchedEvents_001"; cache.wdFileNameCache_[fileName] = std::make_pair(UNEXPECTED_WD, IN_DELETE); // Do testing cache.UpdateWatchedEvents(fileName, EXPECTED_WD, EXPECTED_EVENTS); @@ -129,18 +129,17 @@ HWTEST_F(WatcherDataCacheTest, WatcherDataCacheTest_UpdateWatchedEvents_001, tes /** * @tc.name: WatcherDataCacheTest_UpdateWatchedEvents_002 - * @tc.desc: Test function of WatcherDataCache::UpdateWatchedEvents SUCCESS when key(fileName) not exist. + * @tc.desc: Test function of WatcherDataCache::UpdateWatchedEvents for SUCCESS when key(fileName) not exist. * @tc.size: SMALL * @tc.type: FUNC * @tc.level Level 0 */ HWTEST_F(WatcherDataCacheTest, WatcherDataCacheTest_UpdateWatchedEvents_002, testing::ext::TestSize.Level0) { - GTEST_LOG_(INFO) << "WatcherDataCacheTest-begin " - "WatcherWatcherDataCacheTest_UpdateWatchedEvents_002DataCacheTest_UpdateWatchedEvents_001"; + GTEST_LOG_(INFO) << "WatcherDataCacheTest-begin WatcherDataCacheTest_UpdateWatchedEvents_002"; // Prepare test condition WatcherDataCache cache; - auto fileName = "WatcherDataCacheTest_UpdateWatchedEvents_002"; + auto fileName = "fakePath/WatcherDataCacheTest_UpdateWatchedEvents_002"; // Do testing cache.UpdateWatchedEvents(fileName, EXPECTED_WD, EXPECTED_EVENTS); // Verify results @@ -153,7 +152,7 @@ HWTEST_F(WatcherDataCacheTest, WatcherDataCacheTest_UpdateWatchedEvents_002, tes /** * @tc.name: WatcherDataCacheTest_FindWatchedEvents_001 - * @tc.desc: Test function of WatcherDataCache::FindWatchedEvents SUCCESS + * @tc.desc: Test function of WatcherDataCache::FindWatchedEvents for SUCCESS. * @tc.size: SMALL * @tc.type: FUNC * @tc.level Level 0 @@ -163,7 +162,7 @@ HWTEST_F(WatcherDataCacheTest, WatcherDataCacheTest_FindWatchedEvents_001, testi GTEST_LOG_(INFO) << "WatcherDataCacheTest-begin WatcherDataCacheTest_FindWatchedEvents_001"; // Prepare test condition WatcherDataCache cache; - auto fileName = "WatcherDataCacheTest_FindWatchedEvents_001"; + auto fileName = "fakePath/WatcherDataCacheTest_FindWatchedEvents_001"; cache.wdFileNameCache_[fileName] = std::make_pair(EXPECTED_WD, EXPECTED_EVENTS); // Do testing auto [isWatched, wd, events] = cache.FindWatchedEvents(fileName, IN_ACCESS); @@ -177,7 +176,7 @@ HWTEST_F(WatcherDataCacheTest, WatcherDataCacheTest_FindWatchedEvents_001, testi /** * @tc.name: WatcherDataCacheTest_FindWatchedEvents_002 - * @tc.desc: Test function of WatcherDataCache::FindWatchedEvents FAILURE when key(fileName) not exist + * @tc.desc: Test function of WatcherDataCache::FindWatchedEvents for FAILURE when key(fileName) not exist. * @tc.size: SMALL * @tc.type: FUNC * @tc.level Level 0 @@ -187,7 +186,7 @@ HWTEST_F(WatcherDataCacheTest, WatcherDataCacheTest_FindWatchedEvents_002, testi GTEST_LOG_(INFO) << "WatcherDataCacheTest-begin WatcherDataCacheTest_FindWatchedEvents_002"; // Prepare test condition WatcherDataCache cache; - auto fileName = "WatcherDataCacheTest_FindWatchedEvents_002"; + auto fileName = "fakePath/WatcherDataCacheTest_FindWatchedEvents_002"; // Do testing auto [isWatched, wd, events] = cache.FindWatchedEvents(fileName, IN_ACCESS); // Verify results @@ -200,7 +199,7 @@ HWTEST_F(WatcherDataCacheTest, WatcherDataCacheTest_FindWatchedEvents_002, testi /** * @tc.name: WatcherDataCacheTest_FindWatchedEvents_003 - * @tc.desc: Test function of WatcherDataCache::FindWatchedEvents FAILURE when event unmatched + * @tc.desc: Test function of WatcherDataCache::FindWatchedEvents for FAILURE when event unmatched. * @tc.size: SMALL * @tc.type: FUNC * @tc.level Level 0 @@ -210,7 +209,7 @@ HWTEST_F(WatcherDataCacheTest, WatcherDataCacheTest_FindWatchedEvents_003, testi GTEST_LOG_(INFO) << "WatcherDataCacheTest-begin WatcherDataCacheTest_FindWatchedEvents_003"; // Prepare test condition WatcherDataCache cache; - auto fileName = "WatcherDataCacheTest_FindWatchedEvents_003"; + auto fileName = "fakePath/WatcherDataCacheTest_FindWatchedEvents_003"; cache.wdFileNameCache_[fileName] = std::make_pair(EXPECTED_WD, IN_DELETE); // Do testing auto [isWatched, wd, events] = cache.FindWatchedEvents(fileName, IN_ACCESS); diff --git a/interfaces/test/unittest/js/mod_fs/properties/close_core_mock_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/close_core_mock_test.cpp new file mode 100644 index 000000000..8ca014309 --- /dev/null +++ b/interfaces/test/unittest/js/mod_fs/properties/close_core_mock_test.cpp @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include + +#include "close_core.h" +#include "mock/uv_fs_mock.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +using namespace std; +class CloseCoreMockTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + static inline std::shared_ptr uvMock = nullptr; +}; + +void CloseCoreMockTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; + prctl(PR_SET_NAME, "CloseCoreMockTest"); + uvMock = std::make_shared(); + Uvfs::ins = uvMock; +} + +void CloseCoreMockTest::TearDownTestCase(void) +{ + Uvfs::ins = nullptr; + uvMock = nullptr; + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void CloseCoreMockTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; + errno = 0; // Reset errno +} + +void CloseCoreMockTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: CloseCoreMockTest_DoClose_001 + * @tc.desc: Test function of CloseCore::DoClose interface for FAILURE when uv_fs_close fails. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CloseCoreMockTest, CloseCoreMockTest_DoClose_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CloseCoreMockTest-begin CloseCoreMockTest_DoClose_001"; + EXPECT_CALL(*uvMock, uv_fs_close(testing::_, testing::_, testing::_, testing::_)) + .Times(1) + .WillOnce(testing::Return(UV_EBADF)); + auto ret = CloseCore::DoClose(1); + EXPECT_FALSE(ret.IsSuccess()); + GTEST_LOG_(INFO) << "CloseCoreMockTest-end CloseCoreMockTest_DoClose_001"; +} + +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/properties/close_core_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/close_core_test.cpp index f61b20fcb..b81b4440b 100644 --- a/interfaces/test/unittest/js/mod_fs/properties/close_core_test.cpp +++ b/interfaces/test/unittest/js/mod_fs/properties/close_core_test.cpp @@ -1,17 +1,17 @@ /* -* Copyright (c) 2025 Huawei Device Co., Ltd. -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ #include #include "close_core.h" @@ -28,6 +28,10 @@ public: static void SetUpTestCase(void) { int32_t fd = open(FILE_PATH, CREATE | O_RDWR, 0644); + if (fd < 0) { + GTEST_LOG_(ERROR) << "Open test file failed! ret: " << fd << ", errno: " << errno; + ASSERT_TRUE(false); + } close(fd); }; static void TearDownTestCase() @@ -39,12 +43,12 @@ public: }; /** -* @tc.name: DoCloseTestFd_0001 -* @tc.desc: Test function of DoClose() interface for invalid arguments. -* @tc.size: MEDIUM -* @tc.type: FUNC -* @tc.level Level 1 -*/ + * @tc.name: DoCloseTestFd_0001 + * @tc.desc: Test function of DoClose() interface for invalid arguments. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ HWTEST_F(CloseCoreTest, DoCloseTestFd_0001, testing::ext::TestSize.Level1) { GTEST_LOG_(INFO) << "CloseCoreTest-begin DoCloseTestFd_0001"; @@ -54,23 +58,22 @@ HWTEST_F(CloseCoreTest, DoCloseTestFd_0001, testing::ext::TestSize.Level1) auto err = ret.GetError(); EXPECT_EQ(err.GetErrNo(), 13900020); - GTEST_LOG_(INFO) << "CloseCoreTest-end DoCloseTestFd_0001"; } /** -* @tc.name: DoCloseTestFd_0002 -* @tc.desc: Test function of DoClose() interface for sucess. -* @tc.size: MEDIUM -* @tc.type: FUNC -* @tc.level Level 1 -*/ + * @tc.name: DoCloseTestFd_0002 + * @tc.desc: Test function of DoClose() interface for sucess. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ HWTEST_F(CloseCoreTest, DoCloseTestFd_0002, testing::ext::TestSize.Level1) { GTEST_LOG_(INFO) << "CloseCoreTest-begin DoCloseTestFd_0002"; int32_t fd = open(FILE_PATH, O_RDWR); - if (fd <= 0) { - close(fd); + if (fd < 0) { + GTEST_LOG_(ERROR) << "Open test file failed! ret: " << fd << ", errno: " << errno; ASSERT_TRUE(false); } @@ -78,8 +81,8 @@ HWTEST_F(CloseCoreTest, DoCloseTestFd_0002, testing::ext::TestSize.Level1) EXPECT_TRUE(ret.IsSuccess()); int32_t fdEnd = open(FILE_PATH, O_RDWR); - if (fdEnd <= 0) { - close(fdEnd); + if (fdEnd < 0) { + GTEST_LOG_(ERROR) << "Open test file failed! ret: " << fdEnd << ", errno: " << errno; ASSERT_TRUE(false); } EXPECT_EQ(fdEnd, fd); @@ -91,38 +94,12 @@ HWTEST_F(CloseCoreTest, DoCloseTestFd_0002, testing::ext::TestSize.Level1) } /** -* @tc.name: DoCloseTestFd_0003 -* @tc.desc: Test function of DoClose() interface for failed. -* @tc.size: MEDIUM -* @tc.type: FUNC -* @tc.level Level 1 -*/ -HWTEST_F(CloseCoreTest, DoCloseTestFd_0003, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "CloseCoreTest-begin DoCloseTestFd_0003"; - int32_t fd = open(FILE_PATH, O_RDWR); - if (fd <= 0) { - close(fd); - ASSERT_TRUE(false); - } - auto ret = CloseCore::DoClose(fd); - EXPECT_TRUE(ret.IsSuccess()); - - ret = CloseCore::DoClose(fd); - EXPECT_FALSE(ret.IsSuccess()); - auto err = ret.GetError(); - EXPECT_EQ(err.GetErrNo(), 13900008); - - GTEST_LOG_(INFO) << "CloseCoreTest-end DoCloseTestFd_0003"; -} - -/** -* @tc.name: DoCloseTestFile_0001 -* @tc.desc: Test function of DoClose() interface for success. -* @tc.size: MEDIUM -* @tc.type: FUNC -* @tc.level Level 1 -*/ + * @tc.name: DoCloseTestFile_0001 + * @tc.desc: Test function of DoClose() interface for success. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ HWTEST_F(CloseCoreTest, DoCloseTestFile_0001, testing::ext::TestSize.Level1) { GTEST_LOG_(INFO) << "CloseCoreTest-begin DoCloseTestFile_0001"; @@ -138,12 +115,12 @@ HWTEST_F(CloseCoreTest, DoCloseTestFile_0001, testing::ext::TestSize.Level1) } /** -* @tc.name: DoCloseTestFile_0002 -* @tc.desc: Test function of DoClose() interface for failed get fd. -* @tc.size: MEDIUM -* @tc.type: FUNC -* @tc.level Level 1 -*/ + * @tc.name: DoCloseTestFile_0002 + * @tc.desc: Test function of DoClose() interface for failed get fd. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ HWTEST_F(CloseCoreTest, DoCloseTestFile_0002, testing::ext::TestSize.Level1) { GTEST_LOG_(INFO) << "CloseCoreTest-begin DoCloseTestFile_0002"; @@ -163,6 +140,6 @@ HWTEST_F(CloseCoreTest, DoCloseTestFile_0002, testing::ext::TestSize.Level1) GTEST_LOG_(INFO) << "CloseCoreTest-end DoCloseTestFile_0002"; } -} -} -} \ No newline at end of file +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/properties/copy_core_mock_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/copy_core_mock_test.cpp index 104552554..053b6cc9c 100644 --- a/interfaces/test/unittest/js/mod_fs/properties/copy_core_mock_test.cpp +++ b/interfaces/test/unittest/js/mod_fs/properties/copy_core_mock_test.cpp @@ -17,7 +17,6 @@ #include #include #include -#include #include "copy_core.h" #include "inotify_mock.h" @@ -46,11 +45,13 @@ public: static const string destFile; private: + // rwxr-xr-x static constexpr mode_t permission0755 = 0755; + // rw-r--r-- static constexpr mode_t permission0644 = 0644; }; -const string CopyCoreMockTest::testDir = "/data/test"; +const string CopyCoreMockTest::testDir = "/data/test/CopyCoreMockTest"; const string CopyCoreMockTest::srcDir = testDir + "/src"; const string CopyCoreMockTest::destDir = testDir + "/dest"; const string CopyCoreMockTest::srcFile = srcDir + "/src.txt"; @@ -64,7 +65,8 @@ void CopyCoreMockTest::SetUpTestCase(void) mkdir(destDir.c_str(), permission0755); int32_t fd = open(srcFile.c_str(), O_CREAT | O_RDWR, permission0644); if (fd < 0) { - EXPECT_TRUE(false); + GTEST_LOG_(ERROR) << "Open test file failed! ret: " << fd << ", errno: " << errno; + ASSERT_TRUE(false); } close(fd); uvMock = std::make_shared(); @@ -170,7 +172,8 @@ HWTEST_F(CopyCoreMockTest, CopyCoreMockTest_CopySubDir_001, testing::ext::TestSi string subFile = subDir + "/sub_file.txt"; int fd = open(subFile.c_str(), O_CREAT | O_RDWR, permission0644); if (fd < 0) { - EXPECT_TRUE(false); + GTEST_LOG_(ERROR) << "Open test file failed! ret: " << fd << ", errno: " << errno; + ASSERT_TRUE(false); } close(fd); @@ -208,7 +211,8 @@ HWTEST_F(CopyCoreMockTest, CopyCoreMockTest_CopySubDir_002, testing::ext::TestSi string subFile = subDir + "/sub_file.txt"; int fd = open(subFile.c_str(), O_CREAT | O_RDWR, permission0644); if (fd < 0) { - EXPECT_TRUE(false); + GTEST_LOG_(ERROR) << "Open test file failed! ret: " << fd << ", errno: " << errno; + ASSERT_TRUE(false); } close(fd); @@ -247,8 +251,8 @@ HWTEST_F(CopyCoreMockTest, CopyCoreMockTest_CopySubDir_003, testing::ext::TestSi string subFile = subDir + "/sub_file.txt"; int fd = open(subFile.c_str(), O_CREAT | O_RDWR, permission0644); if (fd < 0) { - GTEST_LOG_(INFO) << "Open test file failed! ret: " << fd << ", errno: " << errno; - EXPECT_TRUE(false); + GTEST_LOG_(ERROR) << "Open test file failed! ret: " << fd << ", errno: " << errno; + ASSERT_TRUE(false); } close(fd); diff --git a/interfaces/test/unittest/js/mod_fs/properties/copy_file_core_mock_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/copy_file_core_mock_test.cpp index 0988ca22a..9371a60cd 100644 --- a/interfaces/test/unittest/js/mod_fs/properties/copy_file_core_mock_test.cpp +++ b/interfaces/test/unittest/js/mod_fs/properties/copy_file_core_mock_test.cpp @@ -29,7 +29,7 @@ public: static void TearDownTestCase(void); void SetUp(); void TearDown(); - static inline shared_ptr uvfs = nullptr; + static inline shared_ptr uvfs = nullptr; }; void CopyFileCoreMockTest::SetUpTestCase(void) @@ -116,7 +116,7 @@ HWTEST_F(CopyFileCoreMockTest, CopyFileCoreMockTest_DoCopyFile_005, testing::ext FileInfo dest; src.isPath = false; dest.isPath = true; - int fd = open("test.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); + int fd = open("CopyFileCoreMockTest_DoCopyFile_005.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); ASSERT_NE(fd, -1); src.fdg = make_unique(fd); @@ -124,7 +124,6 @@ HWTEST_F(CopyFileCoreMockTest, CopyFileCoreMockTest_DoCopyFile_005, testing::ext auto res = CopyFileCore::DoCopyFile(src, dest); EXPECT_EQ(res.IsSuccess(), false); - close(fd); GTEST_LOG_(INFO) << "CopyFileCoreMockTest-end CopyFileCoreMockTest_DoCopyFile_005"; } @@ -144,7 +143,7 @@ HWTEST_F(CopyFileCoreMockTest, CopyFileCoreMockTest_DoCopyFile_006, testing::ext FileInfo dest; src.isPath = false; dest.isPath = true; - int fd = open("test.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); + int fd = open("CopyFileCoreMockTest_DoCopyFile_006.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); ASSERT_NE(fd, -1); src.fdg = make_unique(fd); @@ -152,7 +151,6 @@ HWTEST_F(CopyFileCoreMockTest, CopyFileCoreMockTest_DoCopyFile_006, testing::ext auto res = CopyFileCore::DoCopyFile(src, dest); EXPECT_EQ(res.IsSuccess(), true); - close(fd); GTEST_LOG_(INFO) << "CopyFileCoreMockTest-end CopyFileCoreMockTest_DoCopyFile_006"; } @@ -172,16 +170,17 @@ HWTEST_F(CopyFileCoreMockTest, CopyFileCoreMockTest_DoCopyFile_007, testing::ext FileInfo dest; src.isPath = false; dest.isPath = false; - int fd = open("test.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); - ASSERT_NE(fd, -1); - src.fdg = make_unique(fd); - dest.fdg = make_unique(fd); + int srcFd = open("CopyFileCoreMockTest_DoCopyFile_007_src.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); + ASSERT_NE(srcFd, -1); + int destFd = open("CopyFileCoreMockTest_DoCopyFile_007_dest.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); + ASSERT_NE(destFd, -1); + src.fdg = make_unique(srcFd); + dest.fdg = make_unique(destFd); EXPECT_CALL(*uvfs, uv_fs_ftruncate(_, _, _, _, _)).Times(1).WillOnce(Return(-1)); auto res = CopyFileCore::DoCopyFile(src, dest); EXPECT_EQ(res.IsSuccess(), false); - close(fd); GTEST_LOG_(INFO) << "CopyFileCoreMockTest-end CopyFileCoreMockTest_DoCopyFile_007"; } @@ -201,7 +200,7 @@ HWTEST_F(CopyFileCoreMockTest, CopyFileCoreMockTest_DoCopyFile_008, testing::ext FileInfo dest; src.isPath = false; dest.isPath = false; - int fd = open("test.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); + int fd = open("CopyFileCoreMockTest_DoCopyFile_008.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); ASSERT_NE(fd, -1); src.fdg = make_unique(fd); dest.fdg = make_unique(); @@ -210,7 +209,6 @@ HWTEST_F(CopyFileCoreMockTest, CopyFileCoreMockTest_DoCopyFile_008, testing::ext auto res = CopyFileCore::DoCopyFile(src, dest); EXPECT_EQ(res.IsSuccess(), false); - close(fd); GTEST_LOG_(INFO) << "CopyFileCoreMockTest-end CopyFileCoreMockTest_DoCopyFile_008"; } @@ -231,8 +229,8 @@ HWTEST_F(CopyFileCoreMockTest, CopyFileCoreMockTest_DoCopyFile_009, testing::ext src.isPath = false; dest.isPath = false; - int srcfd = open("src.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); - int destfd = open("dest.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); + int srcfd = open("CopyFileCoreMockTest_DoCopyFile_009_src.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); + int destfd = open("CopyFileCoreMockTest_DoCopyFile_009_dest.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); ASSERT_NE(srcfd, -1); ASSERT_NE(destfd, -1); src.fdg = make_unique(srcfd); @@ -242,8 +240,6 @@ HWTEST_F(CopyFileCoreMockTest, CopyFileCoreMockTest_DoCopyFile_009, testing::ext auto res = CopyFileCore::DoCopyFile(src, dest); EXPECT_EQ(res.IsSuccess(), true); - close(srcfd); - close(destfd); GTEST_LOG_(INFO) << "CopyFileCoreMockTest-end CopyFileCoreMockTest_DoCopyFile_009"; } @@ -264,9 +260,9 @@ HWTEST_F(CopyFileCoreMockTest, CopyFileCoreMockTest_DoCopyFile_0010, testing::ex src.isPath = false; dest.isPath = true; - int srcfd = open("src.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); + int srcfd = open("CopyFileCoreMockTest_DoCopyFile_0010.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); ASSERT_NE(srcfd, -1); - const char* data = "Hello, World!"; + const char *data = "Hello, World!"; ssize_t len = write(srcfd, data, strlen(data)); ASSERT_NE(len, -1); src.fdg = make_unique(srcfd); @@ -276,7 +272,6 @@ HWTEST_F(CopyFileCoreMockTest, CopyFileCoreMockTest_DoCopyFile_0010, testing::ex auto res = CopyFileCore::DoCopyFile(src, dest); EXPECT_EQ(res.IsSuccess(), false); - close(srcfd); GTEST_LOG_(INFO) << "CopyFileCoreMockTest-end CopyFileCoreMockTest_DoCopyFile_0010"; } @@ -297,9 +292,9 @@ HWTEST_F(CopyFileCoreMockTest, CopyFileCoreMockTest_DoCopyFile_0011, testing::ex src.isPath = false; dest.isPath = true; - int srcfd = open("src.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); + int srcfd = open("CopyFileCoreMockTest_DoCopyFile_0011.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); ASSERT_NE(srcfd, -1); - const char* data = "Hello, World!"; + const char *data = "Hello, World!"; ssize_t len = write(srcfd, data, strlen(data)); ASSERT_NE(len, -1); src.fdg = make_unique(srcfd); @@ -309,7 +304,6 @@ HWTEST_F(CopyFileCoreMockTest, CopyFileCoreMockTest_DoCopyFile_0011, testing::ex auto res = CopyFileCore::DoCopyFile(src, dest); EXPECT_EQ(res.IsSuccess(), false); - close(srcfd); GTEST_LOG_(INFO) << "CopyFileCoreMockTest-end CopyFileCoreMockTest_DoCopyFile_0011"; } @@ -330,9 +324,9 @@ HWTEST_F(CopyFileCoreMockTest, CopyFileCoreMockTest_DoCopyFile_0012, testing::ex src.isPath = false; dest.isPath = true; - int srcfd = open("src.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); + int srcfd = open("CopyFileCoreMockTest_DoCopyFile_0012.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); ASSERT_NE(srcfd, -1); - const char* data = "Hello, World!"; + const char *data = "Hello, World!"; ssize_t len = write(srcfd, data, strlen(data)); ASSERT_NE(len, -1); src.fdg = make_unique(srcfd); @@ -342,7 +336,6 @@ HWTEST_F(CopyFileCoreMockTest, CopyFileCoreMockTest_DoCopyFile_0012, testing::ex auto res = CopyFileCore::DoCopyFile(src, dest); EXPECT_EQ(res.IsSuccess(), true); - close(srcfd); GTEST_LOG_(INFO) << "CopyFileCoreMockTest-end CopyFileCoreMockTest_DoCopyFile_0012"; } @@ -363,9 +356,9 @@ HWTEST_F(CopyFileCoreMockTest, CopyFileCoreMockTest_DoCopyFile_0013, testing::ex src.isPath = false; dest.isPath = true; - int srcfd = open("src.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); + int srcfd = open("CopyFileCoreMockTest_DoCopyFile_0013.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); ASSERT_NE(srcfd, -1); - const char* data = "Hello, World!"; + const char *data = "Hello, World!"; ssize_t len = write(srcfd, data, strlen(data)); ASSERT_NE(len, -1); src.fdg = make_unique(srcfd); @@ -375,7 +368,6 @@ HWTEST_F(CopyFileCoreMockTest, CopyFileCoreMockTest_DoCopyFile_0013, testing::ex auto res = CopyFileCore::DoCopyFile(src, dest); EXPECT_EQ(res.IsSuccess(), false); - close(srcfd); GTEST_LOG_(INFO) << "CopyFileCoreMockTest-end CopyFileCoreMockTest_DoCopyFile_0013"; } diff --git a/interfaces/test/unittest/js/mod_fs/properties/create_stream_core_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/create_stream_core_test.cpp index 30e1ad522..8fa2b4155 100644 --- a/interfaces/test/unittest/js/mod_fs/properties/create_stream_core_test.cpp +++ b/interfaces/test/unittest/js/mod_fs/properties/create_stream_core_test.cpp @@ -1,17 +1,17 @@ /* -* Copyright (c) 2025 Huawei Device Co., Ltd. -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ #include #include "create_stream_core.h" @@ -27,6 +27,10 @@ public: static void SetUpTestCase(void) { int32_t fd = open(CREATE_STREAM_FILE_PATH, CREATE | O_RDWR, 0644); + if (fd < 0) { + GTEST_LOG_(ERROR) << "Open test file failed! ret: " << fd << ", errno: " << errno; + ASSERT_TRUE(false); + } close(fd); }; static void TearDownTestCase() @@ -37,12 +41,12 @@ public: void TearDown() {}; }; /** -* @tc.name: DoCreateStreamTest_0001 -* @tc.desc: Test function of DoCreateStream() interface for success. -* @tc.size: MEDIUM -* @tc.type: FUNC -* @tc.level Level 1 -*/ + * @tc.name: DoCreateStreamTest_0001 + * @tc.desc: Test function of DoCreateStream() interface for success. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ HWTEST_F(CreateStreamCoreTest, DoCreateStreamTest_0001, testing::ext::TestSize.Level1) { GTEST_LOG_(INFO) << "CreateStreamCoreTest-begin DoCreateStreamTest_0001"; @@ -58,12 +62,12 @@ HWTEST_F(CreateStreamCoreTest, DoCreateStreamTest_0001, testing::ext::TestSize.L } /** -* @tc.name: DoCreateStreamTest_0002 -* @tc.desc: Test function of DoCreateStream() interface for fail. -* @tc.size: MEDIUM -* @tc.type: FUNC -* @tc.level Level 1 -*/ + * @tc.name: DoCreateStreamTest_0002 + * @tc.desc: Test function of DoCreateStream() interface for fail. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ HWTEST_F(CreateStreamCoreTest, DoCreateStreamTest_0002, testing::ext::TestSize.Level1) { GTEST_LOG_(INFO) << "CreateStreamCoreTest-begin DoCreateStreamTest_0002"; @@ -76,6 +80,6 @@ HWTEST_F(CreateStreamCoreTest, DoCreateStreamTest_0002, testing::ext::TestSize.L GTEST_LOG_(INFO) << "CreateStreamCoreTest-end DoCreateStreamTest_0002"; } -} -} -} \ No newline at end of file +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/properties/fdopen_stream_core_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/fdopen_stream_core_test.cpp index f3be0e56b..0884505df 100644 --- a/interfaces/test/unittest/js/mod_fs/properties/fdopen_stream_core_test.cpp +++ b/interfaces/test/unittest/js/mod_fs/properties/fdopen_stream_core_test.cpp @@ -1,17 +1,17 @@ /* -* Copyright (c) 2025 Huawei Device Co., Ltd. -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ #include #include "fdopen_stream_core.h" @@ -38,18 +38,18 @@ public: }; /** -* @tc.name: DoFdopenStreamTest_0001 -* @tc.desc: Test function of DoFdopenStream() interface for success. -* @tc.size: MEDIUM -* @tc.type: FUNC -* @tc.level Level 1 -*/ + * @tc.name: DoFdopenStreamTest_0001 + * @tc.desc: Test function of DoFdopenStream() interface for success. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ HWTEST_F(FdopenStreamCoreTest, DoFdopenStreamTest_0001, testing::ext::TestSize.Level1) { GTEST_LOG_(INFO) << "FdopenStreamCoreTest-begin DoFdopenStreamTest_0001"; int32_t fd = open(FDOPEN_STREAM_FILE_PATH, O_RDWR); - if (fd <= 0) { - close(fd); + if (fd < 0) { + GTEST_LOG_(ERROR) << "Open test file failed! ret: " << fd << ", errno: " << errno; ASSERT_TRUE(false); } @@ -67,12 +67,12 @@ HWTEST_F(FdopenStreamCoreTest, DoFdopenStreamTest_0001, testing::ext::TestSize.L } /** -* @tc.name: DoFdopenStreamTest_0002 -* @tc.desc: Test function of DoFdopenStream() interface for fd < 0. -* @tc.size: MEDIUM -* @tc.type: FUNC -* @tc.level Level 1 -*/ + * @tc.name: DoFdopenStreamTest_0002 + * @tc.desc: Test function of DoFdopenStream() interface for fd < 0. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ HWTEST_F(FdopenStreamCoreTest, DoFdopenStreamTest_0002, testing::ext::TestSize.Level1) { GTEST_LOG_(INFO) << "FdopenStreamCoreTest-begin DoFdopenStreamTest_0002"; @@ -86,17 +86,17 @@ HWTEST_F(FdopenStreamCoreTest, DoFdopenStreamTest_0002, testing::ext::TestSize.L } /** -* @tc.name: DoFdopenStreamTest_0003 -* @tc.desc: Test function of DoFdopenStream() interface for fail. -* @tc.size: MEDIUM -* @tc.type: FUNC -* @tc.level Level 1 -*/ + * @tc.name: DoFdopenStreamTest_0003 + * @tc.desc: Test function of DoFdopenStream() interface for fail. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ HWTEST_F(FdopenStreamCoreTest, DoFdopenStreamTest_0003, testing::ext::TestSize.Level1) { int32_t fd = open(FDOPEN_STREAM_FILE_PATH, O_RDWR); - if (fd <= 0) { - close(fd); + if (fd < 0) { + GTEST_LOG_(ERROR) << "Open test file failed! ret: " << fd << ", errno: " << errno; ASSERT_TRUE(false); } @@ -112,6 +112,6 @@ HWTEST_F(FdopenStreamCoreTest, DoFdopenStreamTest_0003, testing::ext::TestSize.L GTEST_LOG_(INFO) << "FdopenStreamCoreTest-end DoFdopenStreamTest_0003"; } -} -} -} \ No newline at end of file +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/properties/lstat_core_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/lstat_core_test.cpp index c40e99f2f..6229ce43c 100644 --- a/interfaces/test/unittest/js/mod_fs/properties/lstat_core_test.cpp +++ b/interfaces/test/unittest/js/mod_fs/properties/lstat_core_test.cpp @@ -34,7 +34,8 @@ void LstatCoreTest::SetUpTestCase(void) { GTEST_LOG_(INFO) << "SetUpTestCase"; int32_t fd = open("/data/test/lstat.txt", CREATE | O_RDWR, 0644); - if (fd <= 0) { + if (fd < 0) { + GTEST_LOG_(ERROR) << "Open test file failed! ret: " << fd << ", errno: " << errno; ASSERT_TRUE(false); } close(fd); @@ -66,7 +67,7 @@ void LstatCoreTest::TearDown(void) HWTEST_F(LstatCoreTest, LstatCoreTest_DoLstat_001, testing::ext::TestSize.Level1) { GTEST_LOG_(INFO) << "LstatCoreTest-begin LstatCoreTest_DoLstat_001"; - + auto res = LstatCore::DoLstat("/invalid/test/lstat.txt"); EXPECT_EQ(res.IsSuccess(), false); auto err = res.GetError(); @@ -85,10 +86,10 @@ HWTEST_F(LstatCoreTest, LstatCoreTest_DoLstat_001, testing::ext::TestSize.Level1 HWTEST_F(LstatCoreTest, LstatCoreTest_DoLstat_002, testing::ext::TestSize.Level1) { GTEST_LOG_(INFO) << "LstatCoreTest-begin LstatCoreTest_DoLstat_002"; - + auto res = LstatCore::DoLstat("/data/test/lstat.txt"); EXPECT_EQ(res.IsSuccess(), true); GTEST_LOG_(INFO) << "LstatCoreTest-end LstatCoreTest_DoLstat_002"; } -} \ No newline at end of file +} // namespace OHOS::FileManagement::ModuleFileIO::Test \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/properties/mock/system_mock.cpp b/interfaces/test/unittest/js/mod_fs/properties/mock/system_mock.cpp index 189edf925..c3b158339 100644 --- a/interfaces/test/unittest/js/mod_fs/properties/mock/system_mock.cpp +++ b/interfaces/test/unittest/js/mod_fs/properties/mock/system_mock.cpp @@ -15,26 +15,131 @@ #include "system_mock.h" -using namespace OHOS::FileManagement::ModuleFileIO; +#include +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace Test { + +thread_local std::shared_ptr SystemMock::systemMock = nullptr; +thread_local bool SystemMock::mockable = false; + +std::shared_ptr SystemMock::GetMock() +{ + if (systemMock == nullptr) { + systemMock = std::make_shared(); + } + return systemMock; +} + +void SystemMock::EnableMock() +{ + mockable = true; +} + +void SystemMock::DisableMock() +{ + systemMock = nullptr; + mockable = false; +} + +bool SystemMock::IsMockable() +{ + return mockable; +} + +} // namespace Test +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS + +#ifdef __cplusplus extern "C" { +using namespace OHOS::FileManagement::ModuleFileIO::Test; + int setxattr(const char *path, const char *name, const void *value, size_t size, int flags) { - return System::ins->setxattr(path, name, value, size, flags); + if (SystemMock::IsMockable()) { + return SystemMock::GetMock()->setxattr(path, name, value, size, flags); + } + + static int (*realSetxattr)(const char *, const char *, const void *, size_t, int) = []() { + auto func = (int (*)(const char *, const char *, const void *, size_t, int))dlsym(RTLD_NEXT, "setxattr"); + if (!func) { + GTEST_LOG_(ERROR) << "Failed to resolve real setxattr: " << dlerror(); + } + return func; + }(); + + if (!realSetxattr) { + return -1; + } + + return realSetxattr(path, name, value, size, flags); } ssize_t getxattr(const char *path, const char *name, void *value, size_t size) { - return System::ins->getxattr(path, name, value, size); + if (SystemMock::IsMockable()) { + return SystemMock::GetMock()->getxattr(path, name, value, size); + } + + static int (*realGetxattr)(const char *, const char *, void *, size_t) = []() { + auto func = (int (*)(const char *, const char *, void *, size_t))dlsym(RTLD_NEXT, "getxattr"); + if (!func) { + GTEST_LOG_(ERROR) << "Failed to resolve real getxattr: " << dlerror(); + } + return func; + }(); + + if (!realGetxattr) { + return -1; + } + + return realGetxattr(path, name, value, size); } int fgetxattr(int filedes, const char *name, void *value, size_t size) { - return System::ins->fgetxattr(filedes, name, value, size); + if (SystemMock::IsMockable()) { + return SystemMock::GetMock()->fgetxattr(filedes, name, value, size); + } + + static int (*realFgetxattr)(int, const char *, void *, size_t) = []() { + auto func = (int (*)(int, const char *, void *, size_t))dlsym(RTLD_NEXT, "fgetxattr"); + if (!func) { + GTEST_LOG_(ERROR) << "Failed to resolve real fgetxattr: " << dlerror(); + } + return func; + }(); + + if (!realFgetxattr) { + return -1; + } + + return realFgetxattr(filedes, name, value, size); } int flock(int fd, int operation) { - return System::ins->flock(fd, operation); + if (SystemMock::IsMockable()) { + return SystemMock::GetMock()->flock(fd, operation); + } + + static int (*realFlock)(int, int) = []() { + auto func = (int (*)(int, int))dlsym(RTLD_NEXT, "flock"); + if (!func) { + GTEST_LOG_(ERROR) << "Failed to resolve real flock: " << dlerror(); + } + return func; + }(); + + if (!realFlock) { + return -1; + } + + return realFlock(fd, operation); } -} \ No newline at end of file +} // extern "C" +#endif \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/properties/mock/system_mock.h b/interfaces/test/unittest/js/mod_fs/properties/mock/system_mock.h index dad578b09..ebb971a9e 100644 --- a/interfaces/test/unittest/js/mod_fs/properties/mock/system_mock.h +++ b/interfaces/test/unittest/js/mod_fs/properties/mock/system_mock.h @@ -20,27 +20,34 @@ #include #include -namespace OHOS::FileManagement::ModuleFileIO { +namespace OHOS::FileManagement::ModuleFileIO::Test { -class System { +class ISystem { public: - static inline std::shared_ptr ins = nullptr; - -public: - virtual ~System() = default; + virtual ~ISystem() = default; virtual int setxattr(const char *path, const char *name, const void *value, size_t size, int flags) = 0; virtual ssize_t getxattr(const char *path, const char *name, void *value, size_t size) = 0; virtual int fgetxattr(int filedes, const char *name, void *value, size_t size) = 0; virtual int flock(int fd, int operation) = 0; }; -class SystemMock : public System { +class SystemMock : public ISystem { public: MOCK_METHOD5(setxattr, int(const char *path, const char *name, const void *value, size_t size, int flags)); MOCK_METHOD4(getxattr, ssize_t(const char *path, const char *name, void *value, size_t size)); MOCK_METHOD4(fgetxattr, int(int filedes, const char *name, void *value, size_t size)); MOCK_METHOD2(flock, int(int fd, int operation)); + +public: + static std::shared_ptr GetMock(); + static void EnableMock(); + static void DisableMock(); + static bool IsMockable(); + +private: + static thread_local std::shared_ptr systemMock; + static thread_local bool mockable; }; -} // namespace OHOS::FileManagement::ModuleFileIO +} // namespace OHOS::FileManagement::ModuleFileIO::Test #endif // INTERFACES_TEST_UNITTEST_JS_MOD_FS_PROPERTIES_MOCK_SYSTEM_MOCK_H \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/properties/stat_core_mock_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/stat_core_mock_test.cpp index 2a3133bdb..b8e67585e 100644 --- a/interfaces/test/unittest/js/mod_fs/properties/stat_core_mock_test.cpp +++ b/interfaces/test/unittest/js/mod_fs/properties/stat_core_mock_test.cpp @@ -30,7 +30,7 @@ public: static void TearDownTestCase(void); void SetUp(); void TearDown(); - static inline shared_ptr uvfs = nullptr; + static inline shared_ptr uvfs = nullptr; }; void StatCoreMockTest::SetUpTestCase(void) @@ -139,7 +139,7 @@ HWTEST_F(StatCoreMockTest, StatCoreMockTest_DoStat_004, testing::ext::TestSize.L FileInfo fileinfo; fileinfo.path = std::make_unique(1); - fileinfo.fdg = std::make_unique(1); + fileinfo.fdg = std::make_unique(1, false); fileinfo.isPath = false; EXPECT_CALL(*uvfs, uv_fs_stat(_, _, _, _)).WillOnce(Return(-1)); diff --git a/interfaces/test/unittest/js/mod_fs/properties/trans_listener_mock_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/trans_listener_mock_test.cpp index 7a9d56704..376307c3e 100644 --- a/interfaces/test/unittest/js/mod_fs/properties/trans_listener_mock_test.cpp +++ b/interfaces/test/unittest/js/mod_fs/properties/trans_listener_mock_test.cpp @@ -167,7 +167,8 @@ void TransListenerCoreMockTest::SetUpTestCase(void) GTEST_LOG_(INFO) << "SetUpTestCase"; int32_t fd = open(g_path.c_str(), O_CREAT | O_RDWR, 0644); if (fd < 0) { - EXPECT_TRUE(false); + GTEST_LOG_(ERROR) << "Open test file failed! ret: " << fd << ", errno: " << errno; + ASSERT_TRUE(false); } close(fd); UnistdMock::EnableMock(); diff --git a/interfaces/test/unittest/js/mod_fs/properties/watcher_core_mock_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/watcher_core_mock_test.cpp index f9695cfb0..e9e20cf19 100644 --- a/interfaces/test/unittest/js/mod_fs/properties/watcher_core_mock_test.cpp +++ b/interfaces/test/unittest/js/mod_fs/properties/watcher_core_mock_test.cpp @@ -17,6 +17,7 @@ #include #include +#include #include "eventfd_mock.h" #include "filemgmt_libhilog.h" @@ -41,6 +42,7 @@ public: void WatcherCoreMockTest::SetUpTestCase(void) { GTEST_LOG_(INFO) << "SetUpTestCase"; + prctl(PR_SET_NAME, "WatcherCoreMockTest"); EventfdMock::EnableMock(); InotifyMock::EnableMock(); } diff --git a/interfaces/test/unittest/js/mod_fs/properties/xattr_core_mock_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/xattr_core_mock_test.cpp index e34ff3bdf..b52b1ad99 100644 --- a/interfaces/test/unittest/js/mod_fs/properties/xattr_core_mock_test.cpp +++ b/interfaces/test/unittest/js/mod_fs/properties/xattr_core_mock_test.cpp @@ -13,9 +13,6 @@ * limitations under the License. */ -#include -#include - #include #include #include @@ -30,38 +27,28 @@ using namespace std; class XattrCoreMockTest : public testing::Test { public: - static filesystem::path tempFilePath; static void SetUpTestCase(void); static void TearDownTestCase(void); void SetUp(); void TearDown(); - static inline shared_ptr sys = nullptr; }; -filesystem::path XattrCoreMockTest::tempFilePath; - void XattrCoreMockTest::SetUpTestCase(void) { GTEST_LOG_(INFO) << "SetUpTestCase"; - tempFilePath = "/data/local/tmp/xattr_test_file.txt"; - ofstream tempfile(tempFilePath); - tempfile << "Test content\n123\n456"; - tempfile.close(); - sys = make_shared(); - System::ins = sys; + SystemMock::EnableMock(); } void XattrCoreMockTest::TearDownTestCase(void) { + SystemMock::DisableMock(); GTEST_LOG_(INFO) << "TearDownTestCase"; - filesystem::remove(tempFilePath); - System::ins = nullptr; - sys = nullptr; } void XattrCoreMockTest::SetUp(void) { GTEST_LOG_(INFO) << "SetUp"; + errno = 0; } void XattrCoreMockTest::TearDown(void) @@ -80,12 +67,13 @@ HWTEST_F(XattrCoreMockTest, XattrCoreMockTest_DoSetXattr_001, testing::ext::Test { GTEST_LOG_(INFO) << "XattrCoreMockTest-begin XattrCoreMockTest_DoSetXattr_001"; - string path = tempFilePath.string(); + string path = "fakePath/XattrCoreMockTest_DoSetXattr_001"; string key = "test_key"; string value = "test_value"; - + auto sys = SystemMock::GetMock(); EXPECT_CALL(*sys, setxattr(_, _, _, _, _)).WillOnce(SetErrnoAndReturn(EIO, -1)); auto ret = XattrCore::DoSetXattr(path, key, value); + testing::Mock::VerifyAndClearExpectations(sys.get()); EXPECT_FALSE(ret.IsSuccess()); GTEST_LOG_(INFO) << "XattrCoreMockTest-end XattrCoreMockTest_DoSetXattr_001"; @@ -102,12 +90,14 @@ HWTEST_F(XattrCoreMockTest, XattrCoreMockTest_DoSetXattr_002, testing::ext::Test { GTEST_LOG_(INFO) << "XattrCoreMockTest-begin XattrCoreMockTest_DoSetXattr_002"; - string path = tempFilePath.string(); + string path = "fakePath/XattrCoreMockTest_DoSetXattr_002"; string key = "test_key"; string value = "test_value"; + auto sys = SystemMock::GetMock(); EXPECT_CALL(*sys, setxattr(_, _, _, _, _)).WillOnce(Return(0)); auto ret = XattrCore::DoSetXattr(path, key, value); + testing::Mock::VerifyAndClearExpectations(sys.get()); EXPECT_TRUE(ret.IsSuccess()); GTEST_LOG_(INFO) << "XattrCoreMockTest-end XattrCoreMockTest_DoSetXattr_002"; @@ -124,11 +114,13 @@ HWTEST_F(XattrCoreMockTest, XattrCoreMockTest_DoGetXattr_001, testing::ext::Test { GTEST_LOG_(INFO) << "XattrCoreMockTest-begin XattrCoreMockTest_DoGetXattr_001"; - string path = tempFilePath.string(); + string path = "fakePath/XattrCoreMockTest_DoGetXattr_001"; string key = "test_key"; + auto sys = SystemMock::GetMock(); EXPECT_CALL(*sys, getxattr(_, _, _, _)).WillRepeatedly(SetErrnoAndReturn(EIO, -1)); auto ret = XattrCore::DoGetXattr(path, key); + testing::Mock::VerifyAndClearExpectations(sys.get()); EXPECT_TRUE(ret.IsSuccess()); GTEST_LOG_(INFO) << "XattrCoreMockTest-end XattrCoreMockTest_DoGetXattr_001"; @@ -145,11 +137,13 @@ HWTEST_F(XattrCoreMockTest, XattrCoreMockTest_DoGetXattr_002, testing::ext::Test { GTEST_LOG_(INFO) << "XattrCoreMockTest-begin XattrCoreMockTest_DoGetXattr_002"; - string path = tempFilePath.string(); + string path = "fakePath/XattrCoreMockTest_DoGetXattr_002"; string key = "test_key"; + auto sys = SystemMock::GetMock(); EXPECT_CALL(*sys, getxattr(_, _, _, _)).WillOnce(Return(1)).WillOnce(SetErrnoAndReturn(EIO, -1)); auto ret = XattrCore::DoGetXattr(path, key); + testing::Mock::VerifyAndClearExpectations(sys.get()); EXPECT_FALSE(ret.IsSuccess()); GTEST_LOG_(INFO) << "XattrCoreMockTest-end XattrCoreMockTest_DoGetXattr_002"; @@ -166,11 +160,13 @@ HWTEST_F(XattrCoreMockTest, XattrCoreMockTest_DoGetXattr_003, testing::ext::Test { GTEST_LOG_(INFO) << "XattrCoreMockTest-begin XattrCoreMockTest_DoGetXattr_003"; - string path = tempFilePath.string(); + string path = "fakePath/XattrCoreMockTest_DoGetXattr_003"; string key = "test_key"; + auto sys = SystemMock::GetMock(); EXPECT_CALL(*sys, getxattr(_, _, _, _)).WillOnce(Return(1)).WillOnce(Return(1)); auto ret = XattrCore::DoGetXattr(path, key); + testing::Mock::VerifyAndClearExpectations(sys.get()); EXPECT_TRUE(ret.IsSuccess()); GTEST_LOG_(INFO) << "XattrCoreMockTest-end XattrCoreMockTest_DoGetXattr_003"; diff --git a/interfaces/test/unittest/js/mod_statvfs/statvfs_core_test.cpp b/interfaces/test/unittest/js/mod_statvfs/statvfs_core_test.cpp index 82316d884..b79107179 100644 --- a/interfaces/test/unittest/js/mod_statvfs/statvfs_core_test.cpp +++ b/interfaces/test/unittest/js/mod_statvfs/statvfs_core_test.cpp @@ -36,8 +36,8 @@ void StatvFsCoreTest::SetUpTestCase(void) { GTEST_LOG_(INFO) << "SetUpTestCase"; int32_t fd = open("/data/test/statvfs.txt", O_CREAT | O_RDWR, 0644); - if (fd <= 0) { - close(fd); + if (fd < 0) { + GTEST_LOG_(ERROR) << "Open test file failed! ret: " << fd << ", errno: " << errno; ASSERT_TRUE(false); } close(fd); @@ -139,4 +139,4 @@ HWTEST_F(StatvFsCoreTest, StatvFsCoreTest_DoGetTotalSize_004, testing::ext::Test GTEST_LOG_(INFO) << "StatvFsCoreTest-end StatvFsCoreTest_DoGetTotalSize_004"; } -} \ No newline at end of file +} // namespace OHOS::FileManagement::ModuleFileIO::Test \ No newline at end of file -- Gitee From 4e1e7d94c92ee819f050d2b6164cf2402051fdd6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A7=9C=E5=B0=8F=E6=9E=97?= Date: Mon, 1 Sep 2025 14:56:12 +0800 Subject: [PATCH 3/3] =?UTF-8?q?=E6=A0=B9=E6=8D=AE=E6=A3=80=E8=A7=86?= =?UTF-8?q?=E6=84=8F=E8=A7=81=E8=BF=9B=E8=A1=8C=E8=B0=83=E6=95=B42?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Change-Id: I6e87719d8afe04258791d861f3921ec647eefbae Signed-off-by: 姜小林 --- .../js/mod_fs/class_file/fs_file_mock_test.cpp | 1 - .../js/mod_fs/class_stat/fs_stat_mock_test.cpp | 4 +++- .../js/mod_fs/properties/close_core_mock_test.cpp | 12 +++++++++++- 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/interfaces/test/unittest/js/mod_fs/class_file/fs_file_mock_test.cpp b/interfaces/test/unittest/js/mod_fs/class_file/fs_file_mock_test.cpp index c3c3bd1fc..ee3215fc0 100644 --- a/interfaces/test/unittest/js/mod_fs/class_file/fs_file_mock_test.cpp +++ b/interfaces/test/unittest/js/mod_fs/class_file/fs_file_mock_test.cpp @@ -33,7 +33,6 @@ public: void SetUp(); void TearDown(); static inline shared_ptr uvMock = nullptr; - // static inline shared_ptr sys = nullptr; std::unique_ptr fileEntity; std::unique_ptr fsFile; }; diff --git a/interfaces/test/unittest/js/mod_fs/class_stat/fs_stat_mock_test.cpp b/interfaces/test/unittest/js/mod_fs/class_stat/fs_stat_mock_test.cpp index 74cbaf84a..77813f9b4 100644 --- a/interfaces/test/unittest/js/mod_fs/class_stat/fs_stat_mock_test.cpp +++ b/interfaces/test/unittest/js/mod_fs/class_stat/fs_stat_mock_test.cpp @@ -56,6 +56,8 @@ void FsStatMockTest::TearDown(void) GTEST_LOG_(INFO) << "TearDown"; } +inline const int32_t EXPECTED_FD = 1; + /** * @tc.name: FsStatMockTest_GetLocation_001 * @tc.desc: Test function of GetLocation() interface for SUCCESS. @@ -103,7 +105,7 @@ HWTEST_F(FsStatMockTest, FsStatMockTest_GetLocation_002, testing::ext::TestSize. statEntity = make_unique(); statEntity->fileInfo_ = make_unique(); statEntity->fileInfo_->isPath = false; - const int fdValue = 3; // 模拟fd为3 + const int fdValue = EXPECTED_FD; const bool isClosed = false; statEntity->fileInfo_->fdg = make_unique(fdValue, isClosed); fsStat = make_unique(move(statEntity)); diff --git a/interfaces/test/unittest/js/mod_fs/properties/close_core_mock_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/close_core_mock_test.cpp index 8ca014309..8c9eafcfe 100644 --- a/interfaces/test/unittest/js/mod_fs/properties/close_core_mock_test.cpp +++ b/interfaces/test/unittest/js/mod_fs/properties/close_core_mock_test.cpp @@ -59,6 +59,8 @@ void CloseCoreMockTest::TearDown(void) GTEST_LOG_(INFO) << "TearDown"; } +inline const int32_t EXPECTED_FD = 1; + /** * @tc.name: CloseCoreMockTest_DoClose_001 * @tc.desc: Test function of CloseCore::DoClose interface for FAILURE when uv_fs_close fails. @@ -69,11 +71,19 @@ void CloseCoreMockTest::TearDown(void) HWTEST_F(CloseCoreMockTest, CloseCoreMockTest_DoClose_001, testing::ext::TestSize.Level1) { GTEST_LOG_(INFO) << "CloseCoreMockTest-begin CloseCoreMockTest_DoClose_001"; + + // Prepare test parameters + int fd = EXPECTED_FD; + // Set mock behaviors EXPECT_CALL(*uvMock, uv_fs_close(testing::_, testing::_, testing::_, testing::_)) .Times(1) .WillOnce(testing::Return(UV_EBADF)); - auto ret = CloseCore::DoClose(1); + // Do testing + auto ret = CloseCore::DoClose(fd); + // Verify results EXPECT_FALSE(ret.IsSuccess()); + testing::Mock::VerifyAndClearExpectations(uvMock.get()); + GTEST_LOG_(INFO) << "CloseCoreMockTest-end CloseCoreMockTest_DoClose_001"; } -- Gitee