Skip to content

test: add unit tests for cpickermanager, cscreenshotwidget and dbusnotify - #61

Closed
add-uos wants to merge 1 commit into
linuxdeepin:masterfrom
add-uos:ut-cpickermanager-screenshot-dbusnotify
Closed

add-uos wants to merge 1 commit into
linuxdeepin:masterfrom
add-uos:ut-cpickermanager-screenshot-dbusnotify

Conversation

@add-uos

@add-uos add-uos commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

What

Add GoogleTest unit tests for the core manager and DBus classes:

  • autotests/src/test_CPickerManager.cpp — 27 cases
  • autotests/src/test_CScreenshotWidget.cpp — 9 cases
  • autotests/src/test_DBusNotify.cpp — 22 cases

Part of a 3-part series upstreaming unit tests for deepin-picker.

Why

Extend test coverage to the screenshot manager, the per-screen screenshot widget and the DBus notification helper.

Notes

  • These sources are discovered automatically by the CMake test framework (file(GLOB test_*.cpp), BUILD_TESTS=ON) introduced in the framework PR (test: add CMake unit test framework and tests for utils/settings/desktopinfo #59).
  • Under the default qmake build (deepin-picker.pro) these files are not referenced, so this PR does not affect the existing build and introduces no compile errors.
  • Each PR in the series is independent and can be merged in any order; the tests build once the opt-in CMake framework is present.

Verification

  • qmake build (qmake6 && make) succeeds; the test sources are not compiled by it (no test_*.o produced).
  • With the CMake framework present, all 58 cases pass with Qt6/DTK6.

Summary by Sourcery

Expand automated unit-test coverage across the picker manager, screenshot widget, and DBus notification components.

Enhancements:

  • Add GoogleTest coverage for picker management, screenshot widget behavior, and DBus notification APIs, including event handling, screenshot operations, notification calls, synchronous replies, and property-change processing.

Tests:

  • Introduce unit tests for CPickerManager, CScreenshotWidget, and DBusNotify under the opt-in CMake test framework.

…tify

Add GoogleTest unit tests for the core manager and DBus classes:
- CPickerManager: 27 cases (launch mode, mouse handling, screen mapping)
- CScreenshotWidget: 9 cases (pixmap storage, key/wheel/paint events)
- DBusNotify: 22 cases (dbus message construction and sending)

These sources are picked up automatically by the opt-in CMake test
framework (BUILD_TESTS=ON, file(GLOB test_*.cpp)). Under the default
qmake build they are not referenced by deepin-picker.pro, so this PR
does not affect the existing build.

Verified: all 58 cases pass with Qt6/DTK6 once the framework is present.
@deepin-ci-robot

Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is NOT APPROVED

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

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

@sourcery-ai

sourcery-ai Bot commented Aug 25, 2026

Copy link
Copy Markdown

Reviewer's Guide

Adds 58 GoogleTest cases for CPickerManager, CScreenshotWidget, and DBusNotify, using Qt application fixtures and stubext-based isolation to exercise core control flow, DBus interactions, widget behavior, and documented platform/defect limitations; the tests are picked up only by the opt-in CMake framework and do not affect qmake builds.

File-Level Changes

Change Details Files
Add CPickerManager unit coverage using GoogleTest fixtures and stubext interception of Qt, screen, timer, cursor, and application APIs.
  • Exercise construction, cleanup, launch state, mouse handling, screenshot acquisition, cursor updates, screen-widget initialization, desktop-pixmap caching, and auto-update paths.
  • Cover X11 behavior directly and document Wayland/static-environment limitations and known source defects.
  • Use QApplication-backed tests with shared setup/reset logic and real QScreen discovery where required.
autotests/src/test_CPickerManager.cpp
Add CScreenshotWidget behavioral tests around widget state, input events, and painting.
  • Verify overlay window flags, pixmap storage/retrieval for valid and null pixmaps, Escape handling, non-Escape handling, and wheel-event safety.
  • Test paint behavior for an out-of-bounds cursor and null pixmap; leave the null-parent inside-rect crash scenario disabled as defect documentation.
autotests/src/test_CScreenshotWidget.cpp
Add DBusNotify unit tests with QCoreApplication and stubbed QDBusConnection/interface calls.
  • Verify notification interface naming, constructor parent/connect behavior, destructor disconnect behavior, and pending replies for notification API methods.
  • Validate synchronous GetServerInformation output extraction and preservation of outputs for error or insufficient replies.
  • Invoke the private property-change handler with varied messages to cover early-return and unmatched-property paths.
autotests/src/test_DBusNotify.cpp
Integrate the new tests as opt-in CMake-discovered sources without changing the default qmake build.
  • Rely on the existing file(GLOB test_*.cpp) test discovery when BUILD_TESTS=ON.
  • Keep the sources unreferenced by deepin-picker.pro, preserving the existing qmake compilation path.
autotests/src/test_CPickerManager.cpp
autotests/src/test_CScreenshotWidget.cpp
autotests/src/test_DBusNotify.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
  • 检测到敏感词unset变动
详情
    {
    "unset": {
        "autotests/src/test_CPickerManager.cpp": {
            "b": [
                "    qunsetenv(\"XDG_SESSION_TYPE\");"
            ]
        }
    }
}

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 6 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="autotests/src/test_DBusNotify.cpp" line_range="16-21" />
<code_context>
+#include "dbusnotify.h"
+#include "stubext.h"
+
+// Qt5 QDBusConnection::connect 7-arg (non-const, non-static)
+// bool connect(service, path, interface, name, signature, receiver, slot)
+using DbusConnect7 = bool (QDBusConnection::*)(
+    const QString&, const QString&, const QString&,
+    const QString&, const QString&,
+    QObject*, const char*);
+using DbusDisconnect7 = bool (QDBusConnection::*)(
+    const QString&, const QString&, const QString&,
</code_context>
<issue_to_address>
**issue (bug_risk):** The QtDBus `connect` and `disconnect` overloads are const member functions in Qt6, but these aliases declare non-const member-function pointers. The `static_cast` therefore fails to compile when the CMake tests are built with the Qt6 configuration described in the PR.

**Triggers:** When BUILD_TESTS is enabled with Qt6.

**Suggested fix:** Declare both aliases as const member-function pointers, for example `bool (QDBusConnection::*)(...) const`.
</issue_to_address>

### Comment 2
<location path="autotests/src/test_CPickerManager.cpp" line_range="257-270" />
<code_context>
+    delete mgr;
+}
+
+TEST_F(CPickerManagerTest, Constructor_OnWayland_ScalesShadowWithoutRatio) {
+    // Arrange — stub isWaylandPlatform to return true via environment variable
+    // isWaylandPlatform uses static QProcessEnvironment, so we stub it at a lower level
+    stub.set_lamda(static_cast<qreal(QGuiApplication::*)() const>(&QGuiApplication::devicePixelRatio),
+                   []() -> qreal { __DBG_STUB_INVOKE__ return 2.0; });
+
+    // Act
+    CPickerManager *mgr = new CPickerManager();
+
+    // Assert — constructor completed; on Wayland, scaled() is called with just (w, h)
+    EXPECT_EQ(g_quitCallCount, 0);
+    EXPECT_NE(mgr, nullptr);
+
+    delete mgr;
+}
+
</code_context>
<issue_to_address>
**issue (testing):** Changing `devicePixelRatio()` to return 2.0 does not make `isWaylandPlatform()` return true; that method reads the session environment. On an X11 test runner, both this test and the delayed-focus test execute the X11 path, so the Wayland branches they claim to cover are never exercised.

**Triggers:** When the tests run on an X11 or offscreen environment, which is the ordinary CI configuration.

**Suggested fix:** Run the Wayland cases in a separate process with controlled environment variables, or stub `isWaylandPlatform()` directly if the test framework supports private-method stubbing.
</issue_to_address>

### Comment 3
<location path="autotests/src/test_CPickerManager.cpp" line_range="367-387" />
<code_context>
+TEST_F(CPickerManagerTest, IsWaylandPlatform_StaticCacheLimitation) {
</code_context>
<issue_to_address>
**issue (testing):** The test changes `XDG_SESSION_TYPE` and then unconditionally removes it, rather than restoring its previous value. If the test process started with that variable set, the test permanently changes the environment for later tests and makes their platform-dependent behavior order-dependent.

**Triggers:** When the test runner already has `XDG_SESSION_TYPE` set, including a real Wayland environment.

**Suggested fix:** Save the original value and restore it after the test, and avoid relying on process-global static environment caching for branch coverage.
</issue_to_address>

### Comment 4
<location path="autotests/src/test_DBusNotify.cpp" line_range="189-212" />
<code_context>
+    EXPECT_TRUE(disconnectCalled);
+}
+
+TEST_F(DBusNotifyTest, Destructor_WhenDestroyed_DisconnectsWithCorrectParams) {
+    // Arrange
+    QString capturedIface;
+    QString capturedSignal;
+    stubConnectSimple();
+    auto fnD = static_cast<DbusDisconnect7>(&QDBusConnection::disconnect);
+    stub.set_lamda(fnD, [&capturedIface, &capturedSignal](
+            QDBusConnection*, const QString&, const QString&,
+            const QString& iface, const QString& name,
+            const QString&, QObject*, const char*) -> bool {
+        capturedIface = iface;
+        capturedSignal = name;
+        return true;
+    });
+
+    // Act
+    {
+        DBusNotify notify(nullptr);
+    }
+
+    // Assert
</code_context>
<issue_to_address>
**issue (bug_risk):** The destructor test captures only the interface and signal name, not the slot string passed to `QDBusConnection::disconnect`. It therefore passes even though the implementation disconnects `propertyChanged(QDBusMessage)` while the constructor connects `__propertyChanged__(QDBusMessage)`, leaving the registered signal connection active.

**Triggers:** When validating the destructor's cleanup behavior.

**Suggested fix:** Capture and assert the receiver and slot arguments, requiring the disconnect call to use `SLOT(__propertyChanged__(QDBusMessage))`.
</issue_to_address>

### Comment 5
<location path="autotests/src/test_DBusNotify.cpp" line_range="438-445" />
<code_context>
+
+TEST_F(DBusNotifyTest, PropertyChanged_TwoArgs_EarlyReturnNoCrash) {
+    // Arrange
+    stubConnectSimple();
+    stubDisconnectSimple();
+    DBusNotify notify(nullptr);
+    QDBusMessage msg = QDBusMessage::createSignal("/path",
+                                                   "org.freedesktop.Notifications", "test");
+    QList<QVariant> args;
+    args << QString("org.freedesktop.Notifications") << QVariantMap();
+    msg.setArguments(args);
+
+    // Act
</code_context>
<issue_to_address>
**issue (testing):** The property-change tests put a `QVariantMap` directly into the message arguments, while `__propertyChanged__` reads argument 1 as a `QDBusArgument` and converts it with `qdbus_cast<QVariantMap>`. The tests therefore do not supply the DBus wire representation consumed by the slot and cannot validate changed-property decoding or notification behavior.

**Triggers:** When the slot receives a real DBus signal encoded as `sa{sv}as`.

**Suggested fix:** Construct argument 1 as a `QDBusArgument` containing the dictionary, or invoke the slot with the same encoded argument type that QtDBus delivers.
</issue_to_address>

### Comment 6
<location path="autotests/src/test_CPickerManager.cpp" line_range="440-456" />
<code_context>
+    EXPECT_TRUE(grabWindowCalled);
+}
+
+TEST_F(CPickerManagerTest, GetScreenShotPixmap_OnX11_GrabsWindow) {
+    // Arrange — on X11 (current CI env), getScreenShotPixmap uses grabWindow
+    bool grabWindowCalled = false;
+    stub.set_lamda(static_cast<QPixmap(QScreen::*)(WId, int, int, int, int)>(&QScreen::grabWindow),
+                  [&grabWindowCalled](QScreen *, WId, int, int, int, int) -> QPixmap {
+        __DBG_STUB_INVOKE__
+        grabWindowCalled = true;
+        return QPixmap(200, 200);
+    });
+
+    CPickerManager mgr;
+
+    // Act
+    mgr.handleMouseMove();
+
+    // Assert — on X11, grabWindow IS called
+    EXPECT_TRUE(grabWindowCalled);
+}
+
</code_context>
<issue_to_address>
**issue (testing):** The test calls the public `handleMouseMove()` path but never provides a screen from `screenAt()` or a widget mapping for that screen. With the fixture's default `screenAt()` stub returning null, `autoUpdate()` returns before the per-screen `getScreenShotPixmap()` path, so `grabWindowCalled` only observes the desktop-grab path.

**Triggers:** When the default fixture stubs are used, as in this test.

**Suggested fix:** Stub `screenAt()` to return a real screen and arrange a corresponding screenshot widget, then assert the grab made by `getScreenShotPixmap()` separately from the desktop capture.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines +16 to +21
// Qt5 QDBusConnection::connect 7-arg (non-const, non-static)
// bool connect(service, path, interface, name, signature, receiver, slot)
using DbusConnect7 = bool (QDBusConnection::*)(
const QString&, const QString&, const QString&,
const QString&, const QString&,
QObject*, const char*);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (bug_risk): The QtDBus connect and disconnect overloads are const member functions in Qt6, but these aliases declare non-const member-function pointers. The static_cast therefore fails to compile when the CMake tests are built with the Qt6 configuration described in the PR.

Triggers: When BUILD_TESTS is enabled with Qt6.

Suggested fix: Declare both aliases as const member-function pointers, for example bool (QDBusConnection::*)(...) const.

Comment on lines +257 to +270
TEST_F(CPickerManagerTest, Constructor_OnWayland_ScalesShadowWithoutRatio) {
// Arrange — stub isWaylandPlatform to return true via environment variable
// isWaylandPlatform uses static QProcessEnvironment, so we stub it at a lower level
stub.set_lamda(static_cast<qreal(QGuiApplication::*)() const>(&QGuiApplication::devicePixelRatio),
[]() -> qreal { __DBG_STUB_INVOKE__ return 2.0; });

// Act
CPickerManager *mgr = new CPickerManager();

// Assert — constructor completed; on Wayland, scaled() is called with just (w, h)
EXPECT_EQ(g_quitCallCount, 0);
EXPECT_NE(mgr, nullptr);

delete mgr;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (testing): Changing devicePixelRatio() to return 2.0 does not make isWaylandPlatform() return true; that method reads the session environment. On an X11 test runner, both this test and the delayed-focus test execute the X11 path, so the Wayland branches they claim to cover are never exercised.

Triggers: When the tests run on an X11 or offscreen environment, which is the ordinary CI configuration.

Suggested fix: Run the Wayland cases in a separate process with controlled environment variables, or stub isWaylandPlatform() directly if the test framework supports private-method stubbing.

Comment on lines +367 to +387
TEST_F(CPickerManagerTest, IsWaylandPlatform_StaticCacheLimitation) {
// Arrange — isWaylandPlatform() uses static QProcessEnvironment that caches on first call.
// After the first CPickerManager construction (in earlier tests), the env is already cached.
// qputenv("XDG_SESSION_TYPE", "wayland") has no effect after caching.
// This test documents the limitation: Wayland code paths require separate process.
qputenv("XDG_SESSION_TYPE", "wayland");
bool grabWindowCalled = false;
stub.set_lamda(static_cast<QPixmap(QScreen::*)(WId, int, int, int, int)>(&QScreen::grabWindow),
[&grabWindowCalled](QScreen *, WId, int, int, int, int) -> QPixmap {
__DBG_STUB_INVOKE__
grabWindowCalled = true;
return QPixmap(100, 100);
});

CPickerManager mgr;
mgr.handleMouseMove();

// Assert — static cache means X11 path still active despite env change
EXPECT_TRUE(grabWindowCalled);
qunsetenv("XDG_SESSION_TYPE");
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (testing): The test changes XDG_SESSION_TYPE and then unconditionally removes it, rather than restoring its previous value. If the test process started with that variable set, the test permanently changes the environment for later tests and makes their platform-dependent behavior order-dependent.

Triggers: When the test runner already has XDG_SESSION_TYPE set, including a real Wayland environment.

Suggested fix: Save the original value and restore it after the test, and avoid relying on process-global static environment caching for branch coverage.

Comment on lines +189 to +212
TEST_F(DBusNotifyTest, Destructor_WhenDestroyed_DisconnectsWithCorrectParams) {
// Arrange
QString capturedIface;
QString capturedSignal;
stubConnectSimple();
auto fnD = static_cast<DbusDisconnect7>(&QDBusConnection::disconnect);
stub.set_lamda(fnD, [&capturedIface, &capturedSignal](
QDBusConnection*, const QString&, const QString&,
const QString& iface, const QString& name,
const QString&, QObject*, const char*) -> bool {
capturedIface = iface;
capturedSignal = name;
return true;
});

// Act
{
DBusNotify notify(nullptr);
}

// Assert
EXPECT_EQ(capturedIface, QString("org.freedesktop.DBus.Properties"));
EXPECT_EQ(capturedSignal, QString("PropertiesChanged"));
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (bug_risk): The destructor test captures only the interface and signal name, not the slot string passed to QDBusConnection::disconnect. It therefore passes even though the implementation disconnects propertyChanged(QDBusMessage) while the constructor connects __propertyChanged__(QDBusMessage), leaving the registered signal connection active.

Triggers: When validating the destructor's cleanup behavior.

Suggested fix: Capture and assert the receiver and slot arguments, requiring the disconnect call to use SLOT(__propertyChanged__(QDBusMessage)).

Comment on lines +438 to +445
stubConnectSimple();
stubDisconnectSimple();
DBusNotify notify(nullptr);
QDBusMessage msg = QDBusMessage::createSignal("/path",
"org.freedesktop.Notifications", "test");
QList<QVariant> args;
args << QString("org.freedesktop.Notifications") << QVariantMap();
msg.setArguments(args);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (testing): The property-change tests put a QVariantMap directly into the message arguments, while __propertyChanged__ reads argument 1 as a QDBusArgument and converts it with qdbus_cast<QVariantMap>. The tests therefore do not supply the DBus wire representation consumed by the slot and cannot validate changed-property decoding or notification behavior.

Triggers: When the slot receives a real DBus signal encoded as sa{sv}as.

Suggested fix: Construct argument 1 as a QDBusArgument containing the dictionary, or invoke the slot with the same encoded argument type that QtDBus delivers.

Comment on lines +440 to +456
TEST_F(CPickerManagerTest, GetScreenShotPixmap_OnX11_GrabsWindow) {
// Arrange — on X11 (current CI env), getScreenShotPixmap uses grabWindow
bool grabWindowCalled = false;
stub.set_lamda(static_cast<QPixmap(QScreen::*)(WId, int, int, int, int)>(&QScreen::grabWindow),
[&grabWindowCalled](QScreen *, WId, int, int, int, int) -> QPixmap {
__DBG_STUB_INVOKE__
grabWindowCalled = true;
return QPixmap(200, 200);
});

CPickerManager mgr;

// Act
mgr.handleMouseMove();

// Assert — on X11, grabWindow IS called
EXPECT_TRUE(grabWindowCalled);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (testing): The test calls the public handleMouseMove() path but never provides a screen from screenAt() or a widget mapping for that screen. With the fixture's default screenAt() stub returning null, autoUpdate() returns before the per-screen getScreenShotPixmap() path, so grabWindowCalled only observes the desktop-grab path.

Triggers: When the default fixture stubs are used, as in this test.

Suggested fix: Stub screenAt() to return a real screen and arrange a corresponding screenshot widget, then assert the grab made by getScreenShotPixmap() separately from the desktop capture.

@add-uos add-uos closed this Sep 14, 2026
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.

2 participants