Skip to content

test: supplement unit tests for 6 core files (Tool + src root, 92 cases) - #907

Merged
deepin-bot[bot] merged 5 commits into
linuxdeepin:masterfrom
add-uos:ut-t17
Oct 24, 2026
Merged

deepin-bot[bot] merged 5 commits into
linuxdeepin:masterfrom
add-uos:ut-t17

Conversation

@add-uos

@add-uos add-uos commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

What this PR does

Rewrites or extends Google Test unit tests for 6 core files of deepin-devicemanager (scope: Tool utilities + src root):

Test class File under test Cases Change
UT_DebugTimeManager src/DebugTimeManager.cpp 8 rewrite (0 → 8)
UT_EventLogUtils src/Tool/eventlogutils.cpp 4 rewrite (3 → 4)
UT_LoadCpuInfoThread src/Tool/LoadCpuInfoThread.cpp 9 rewrite (1 → 9)
UT_Common src/commonfunction.cpp 49 extend (38 → 49)
UT_SingleDeviceManager src/SingleDeviceManager.cpp 9 new (0 → 9)
UT_DBusAnythingInterface src/Tool/DBusAnythingInterface.cpp 3 kept unchanged (reviewed, healthy)

92 cases in scope; test code only, no production changes.

Key points

  • All external dependencies are stubbed (QProcess, QLibrary, DBus, QFile/QIODevice, clock, proc/sysfs) — no real device or service required.
  • Virtual Qt functions (QFile::open, QIODevice::read) are patched via dlsym(RTLD_DEFAULT, <mangled>) real function addresses; member-pointer patching on virtuals breaks the vtable and segfaults.
  • SingleDeviceManager inherits DApplication; constructing a second QApplication in-process crashes on exit, and forked children deadlock on the first DBus call (no Qt DBus thread). Plain scenarios run in forked children (__gcov_dump + _exit, declared via gcov.h wrapped in extern "C" — a weak C++ declaration gets name-mangled and silently loses all child coverage data); window scenarios use an exec-child harness (DM_UT_SINGLE_DEVICE_MARKER=1, exit-code encoded results). ActivateWindow_InternalMarker_ScenarioThenExit is intentionally skipped outside that harness and driven by ActivateWindow_ViaChildProcess_ExitCodeZero.
  • Coverage for the 6 files: 92.7% lines, 100% functions (39/39 methods matched).

Verification

cd build/deepin-devicemanager/tests
QT_QPA_PLATFORM=offscreen ./deepin-devicemanager-test \
  --gtest_filter='UT_Common.*:UT_DBusAnythingInterface.*:UT_EventLogUtils.*:UT_DebugTimeManager.*:UT_LoadCpuInfoThread.*:UT_SingleDeviceManager.*'

Result: 91 passed, 0 failed, 1 skipped by design (exit code 0), based on latest upstream/master (f4d271c).

During test development 3 suspected source defects were found and reported separately (DBus timeout blocking in getDeviceInfo, sticky boardVendorKey cache in checkBoardVendorFlag, commented-out showNormal() in startDeviceManager); no production code is changed in this PR.

Summary by Sourcery

Strengthen unit-test coverage for six core files without changing production code.

Enhancements:

  • Expand Google Test coverage across six core utilities and managers, including comprehensive behavior and branch validation for timing, event logging, CPU information loading, common helpers, and single-device application management.
  • Isolate external processes, files, DBus services, device data, and application lifecycle behavior with controlled stubs and child-process test harnesses.

Tests:

  • Add and strengthen 92 unit-test cases, replacing weak assertions with meaningful checks for outputs, state changes, error handling, caching, parsing, and window-management scenarios.
  • Achieve 91 passing tests and one intentional skip while covering 92.7% of lines and all 39 matched methods in the six target files.

- rewrite tests/src/ut_debugtimemanager.cpp, cases 0 -> 8
- stub gettimeofday via dlsym so the fake clock is deterministic
- capture [GRABPOINT] logs via qInstallMessageHandler for assertions
- cover constructor / beginPointLinux / endPointLinux (with and without
  sub-point, unknown point) / clear on all branches
- AAA comments complete, no real clock or device dependencies
- rewrite tests/src/Tool/ut_eventlogutils.cpp, cases 3 -> 4
- stub QLibrary::resolve to return null and inject a recording stub
  into the private function pointer
- cover singleton access, null-pointer guard, writeLogs event
  recording and round-trip JSON payload
- no real eventlog library dependency
- rewrite tests/src/Tool/ut_loadcpuinfothread.cpp, cases 1 -> 9
- stub QProcess member functions via static_cast member pointers to
  isolate real process invocation
- pin DeviceManager::cmdInfo via ADDR stub for setCpuRefreshInfoFromlscpu
- cover constructor / runCmd / getMapInfoFromCmd parsing branches /
  cpuInfo paths
- no real lscpu or device dependencies
- extend tests/src/ut_commonfunction.cpp, cases 38 -> 49: add
  boardVendorType caching, checkBoardVendorFlag four branches,
  executeClientCmd three branches, safeReadSysFsFile seven branches
  and isShowScreenSize
- clear the sticky boardVendorKey via the NormalCom branch first in
  checkBoardVendorFlag cases
- stub DBusInterface::init/getInfo on the getDeviceInfo fallback path
  to isolate the real DBus call
- patch virtual QFile::open/QIODevice::read via dlsym(RTLD_DEFAULT)
  real function addresses; member-pointer patching breaks the vtable
  and causes a segfault
- add AAA comments and SPDX header for the new cases
@sourcery-ai

sourcery-ai Bot commented Oct 24, 2026

Copy link
Copy Markdown

Sorry @add-uos, you've used your own review budget of 250,000 diff characters for the last 7 days.

You can request another review in 4 days and 20 hours by commenting @sourcery-ai review. Upgrade to get a review now.

@sourcery-ai

sourcery-ai Bot commented Oct 24, 2026

Copy link
Copy Markdown

Reviewer's Guide

Adds or rewrites unit tests for six core files, increasing the scoped suite to 92 cases with deterministic stubs for Qt, DBus, process, filesystem, timing, and device dependencies; the reported run passes 91 cases with one deliberate skip and achieves 92.7% line and 100% function coverage.

File-Level Changes

Change Details Files
Reworked DebugTimeManager tests into deterministic state, timing, logging, and cleanup coverage.
  • Added fixed gettimeofday stubbing and Qt log capture.
  • Covered construction, point insertion/overwrite, elapsed-time calculations, missing points, subpoints, and clearing.
tests/src/ut_debugtimemanager.cpp
Strengthened EventLogUtils tests with injected write-callback verification and JSON payload assertions.
  • Validated singleton stability and null-callback early return.
  • Verified compact JSON serialization, round-trip fields, and repeated writes.
tests/src/Tool/ut_eventlogutils.cpp
Expanded LoadCpuInfoThread tests by isolating process and DeviceManager interactions with controlled stubs.
  • Covered parsing of valid, empty, and malformed command output.
  • Covered command execution, CPU map loading, refresh behavior, direct run execution, and construction state.
tests/src/Tool/ut_loadcpuinfothread.cpp
Extended Common utility coverage across board-vendor detection, command execution, secure sysfs reads, and display-size defaults.
  • Stubbed QProcess, DBus, QFile, QFileInfo, and virtual Qt methods to avoid external dependencies.
  • Covered vendor-detection branches, cached results, locale environment handling, exit-code behavior, path traversal/canonicalization/file validation, read failures, and successful trimmed reads.
tests/src/ut_commonfunction.cpp
Added isolated SingleDeviceManager tests using fork and exec child-process harnesses for QApplication and DBus-sensitive scenarios.
  • Covered construction, command-line parsing, no-window start paths, and window activation/reuse/page handling.
  • Added gcov flushing and exit-code result propagation while stubbing MainWindow, QLibrary, and event logging dependencies.
tests/src/ut_singledevicemanager.cpp
Preserved the reviewed DBusAnythingInterface test coverage without production-code changes.
  • Kept the existing three test cases unchanged as part of the 92-case verification scope.
tests/src/Tool/ut_dbusanythinginterface.cpp

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@github-actions

Copy link
Copy Markdown
  • 检测到敏感词dmidecode变动
详情
    {
    "dmidecode": {
        "deepin-devicemanager/tests/src/ut_commonfunction.cpp": [
            "//   B2  specialComType == -1 -> dmidecode \u5206\u652f:",
            "// checkBoardVendorFlag B2.1: dmidecode \u8f93\u51fa\u542b L540 -> KLVV",
            "    // Assert: M900(/proc/cpuinfo \u65e0 Hardware)\u4e0e W525(dmidecode \u65e0 String 4)\u5747\u4e3a false, \u952e\u4fdd\u6301\u7a7a"
        ]
    }
}

- add tests/src/ut_singledevicemanager.cpp, previously untested
- a DApplication subclass crashes on exit when constructed twice in
  one process: run plain scenarios in forked children, dump coverage
  via __gcov_dump and _exit to keep counters
- forked children deadlock on the first DBus-dependent call inside
  activateWindow (no Qt DBus thread after fork), so use an exec-child
  harness instead: the parent re-executes the test binary via QProcess
  with DM_UT_SINGLE_DEVICE_MARKER=1 and checks the exit code
- declare __gcov_dump through gcov.h wrapped in extern "C"; a weak
  C++ declaration gets name-mangled and stays null, silently losing
  all child coverage data
- cover constructor / parseCmdLine four branches / startDeviceManager
  two branches / activateWindow create-and-reuse branches
- stub MainWindow::refreshDataBase, QLibrary::resolve and
  EventLogUtils; no real device, DBus or eventlog dependencies
@github-actions

Copy link
Copy Markdown
  • 检测到敏感词dmidecode变动
详情
    {
    "dmidecode": {
        "deepin-devicemanager/tests/src/ut_commonfunction.cpp": [
            "//   B2  specialComType == -1 -> dmidecode \u5206\u652f:",
            "// checkBoardVendorFlag B2.1: dmidecode \u8f93\u51fa\u542b L540 -> KLVV",
            "    // Assert: M900(/proc/cpuinfo \u65e0 Hardware)\u4e0e W525(dmidecode \u65e0 String 4)\u5747\u4e3a false, \u952e\u4fdd\u6301\u7a7a"
        ]
    }
}

@deepin-ci-robot

Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: add-uos, lzwind

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@deepin-ci-robot

Copy link
Copy Markdown

deepin pr auto review

🤖 AI 代码审查报告

总体评分: 99 分 (通过阈值: 70分)

Pass


📊 总体评价

项目 结果
审查结论 代码审查通过
评分详情 本次提交为单元测试补充,覆盖 EventLogUtils、LoadCpuInfoThread、CommonFunction、 DebugTimeManager、SingleDeviceManager 共 5 个测试文件约 41 个用例。测试结构规范, AAA 模式清晰,打桩矩阵完整,隔离策略合理(fork/exec 子进程隔离二次 QApplication)。 四维度均通过,无安全漏洞,仅代码质量维度存在少量静态全局状态和 dlsym 脆弱性问题。

🔍 详细分析

1. 语法逻辑 ✅

评价: 语法正确,逻辑清晰 ✅ 通过

潜在问题:
✅ 未发现明显问题

建议: ['继续保持 AAA(Arrange/Act/Assert)结构和清晰的用例命名']


2. 代码质量 ✅

评价: 代码结构清晰,注释完整 ✅ 通过

潜在问题:
✅ 未发现明显问题

建议: ['建议将 QProcess 打桩辅助函数提取到公共头文件(如 ut_qprocess_stub.h)复用', '建议在文件头注释中标注静态全局状态的串行执行依赖', 'dlsym 路径建议增加编译期 Qt 版本断言或改用 vtable 偏移方案']


3. 代码性能 ✅

评价: 性能良好,资源使用合理 ✅ 通过

潜在问题:
✅ 未发现明显问题

建议: ['无需优化']


4. 代码安全 🔒

评价: 存在0个安全漏洞 ✅ 通过

🔐 发现 0 个安全漏洞

安全漏洞详情:
✅ 未发现安全漏洞

建议: ['无需安全加固']


💡 改进建议代码示例

// 建议:提取 QProcess 打桩公共头文件 ut_qprocess_stub.h
// 减少 ut_commonfunction.cpp 与 ut_loadcpuinfothread.cpp 之间的重复代码
//
// #pragma once
// #include <QByteArray>
// #include <QProcess>
// #include "stub.h"
//
// namespace ut_stub {
//     static QByteArray qprocess_stdout;
//
//     static void qprocess_start_noop(QProcess*, const QString&,
//         const QStringList&, QIODevice::OpenMode) {}
//     static bool qprocess_waitForFinished_true(QProcess*, int) { return true; }
//     static QByteArray qprocess_readAll_canned(QProcess*) { return qprocess_stdout; }
//
//     inline void install_qprocess_stubs(Stub &stub) {
//         auto startFunc = static_cast<void (QProcess::*)(const QString&,
//             const QStringList&, QIODevice::OpenMode)>(&QProcess::start);
//         auto waitFunc = static_cast<bool (QProcess::*)(int)>(&QProcess::waitForFinished);
//         auto readFunc = static_cast<QByteArray (QProcess::*)()>(&QProcess::readAllStandardOutput);
//         stub.set(startFunc, qprocess_start_noop);
//         stub.set(waitFunc, qprocess_waitForFinished_true);
//         stub.set(readFunc, qprocess_readAll_canned);
//     }
// }

本报告由 AI 代码审查工具自动生成

@add-uos

add-uos commented Oct 24, 2026

Copy link
Copy Markdown
Contributor Author

/forcemerge

@deepin-bot

deepin-bot Bot commented Oct 24, 2026

Copy link
Copy Markdown
Contributor

This pr force merged! (status: unstable)

@deepin-bot
deepin-bot Bot merged commit 7d06096 into linuxdeepin:master Oct 24, 2026
14 of 17 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants