Skip to content

test(editor,widgets): extend TextEdit and Window tests, fix crashes - #500

Merged
pengfeixx merged 1 commit into
linuxdeepin:masterfrom
pengfeixx:test/ut-textedit-window-ext
Aug 3, 2026
Merged

test(editor,widgets): extend TextEdit and Window tests, fix crashes#500
pengfeixx merged 1 commit into
linuxdeepin:masterfrom
pengfeixx:test/ut-textedit-window-ext

Conversation

@pengfeixx

@pengfeixx pengfeixx commented Aug 3, 2026

Copy link
Copy Markdown
Contributor

Add stub for slotCanRedoChanged to 134 test locations preventing SEGV. Remove QTest::qWait calls that process stale queued events.

Log: 扩充TextEdit和Window测试,修复批量测试崩溃
Influence: 提升函数覆盖率至98.7%,消除全量测试SEGV崩溃

Summary by Sourcery

Increase test coverage for TextEdit, Window, and several widget components while addressing crashes caused by missing redo stubs and unsafe event processing in bulk runs.

Bug Fixes:

  • Stub TextEdit::slotCanRedoChanged alongside slotCanUndoChanged across many tests to prevent segmentation faults from unhandled undo/redo signals during test execution.
  • Avoid use of QTest::qWait / event loop processing in new tests where it could deliver stale or unsafe queued events, preventing test-run crashes related to deferred deletes and uninitialized settings.

Enhancements:

  • Refactor and centralize helper creation for TextEdit-in-Window test setups, and introduce gesture state helpers to reliably drive Qt gesture state machines in tests.
  • Introduce defensive event-filter utilities within tests to block problematic DeferredDelete processing and safely exercise asynchronous lambdas without destabilizing the global QApplication state.

Tests:

  • Add comprehensive unit tests to cover previously untested TextEdit behaviors, gestures, input methods, selection, marking, and context/right-click menus.
  • Add new Window tests to exercise key event handling, drag/print/position logic, search bars, printing helpers, and AI assistant configuration paths, including various internal lambdas.
  • Extend DDropdownMenu, BottomBar, ColorSelectWdg, and EditorApplication tests to cover menu interaction, encoding/highlight lambdas, color selection callbacks, and application lifecycle behavior.
  • Remove obsolete or fully commented-out tests in TextEdit and Window suites that provided no coverage and could mask real issues.

@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.

Sorry @pengfeixx, you have reached your weekly rate limit of 500000 diff characters.

Please try again later or upgrade to continue using Sourcery

@pengfeixx
pengfeixx force-pushed the test/ut-textedit-window-ext branch from 3365311 to 6c8213a Compare August 3, 2026 01:28
@sourcery-ai

sourcery-ai Bot commented Aug 3, 2026

Copy link
Copy Markdown

Reviewer's Guide

Extends TextEdit, Window, BottomBar, DDropdownMenu, ColorSelectWdg, and EditorApplication tests to cover previously-uncovered functions and UI-connected lambdas, adds undo/redo stubs to many TextEdit tests to avoid crashes, removes obsolete/commented tests, and introduces targeted stubs and event filters to prevent SEGVs and flaky behaviour during bulk test runs.

File-Level Changes

Change Details Files
Add stubs and wiring for TextEdit undo/redo signals and extend TextEdit tests to cover numerous previously-uncovered input, gesture, drag/drop, menu, marking, and helper functions while avoiding crashes from deferred events.
  • Introduce stub_slotCanRedoChanged and hook both undo/redo slots via Stub in a large number of TextEdit tests to prevent SEGV when QUndoStack signals fire.
  • Add new includes and helper functions (makeEditorInWindow, forceGestureState) to build fully initialised TextEdit instances hosted in Window and to drive protected gesture state for QGesture-based tests.
  • Replace commented-out or missing tests with new UT_Textedit_Uncovered cases that exercise text case conversion, wheel/scroll, gesture handling, drag/drop, context/right-click menus, input method handling, multi-insert/delete, comment detection, mark/selection operations, eventFilter, highlight, and mark-replace index calculations.
  • Adjust existing mark-related tests (e.g., updateMark) to use different cursor positions/signs to drive additional branches in TextEdit’s internal logic.
tests/src/editor/ut_textedit.cpp
Extend Window widget tests to cover event handlers, printing workflow, position remember/save, search keyword helpers, AI assistant config, bar switching slots, constructor and popup lambdas, and tab text-change handling, while cleaning out obsolete commented tests.
  • Remove large blocks of fully commented-out Window tests for jump line bar, print dialog, position save, tab close, title focus, and keyPressEvent variants.
  • Add focused UT_Window_* tests for keyPressEvent, dragEnterEvent, updateSizeMode, keyReleaseEvent, popupPrintDialog (including its DPrintPreview lambdas), remberPositionSave, keyword getters, multi-doc printing, invalid-char save confirmation, current-open-file path resolution, AI assistant config load/query, and slots that switch focus between find/replace bars and line-number display.
  • Introduce UT_DeferredDeleteBlocker event filter and various stubs (doPrint, notifications, QDialog::exec) to safely exercise asynchronous and dialog-related code paths without triggering crashes from DeferredDelete or heavy I/O.
  • Drive constructor and addTabWithWrapper-connected lambdas by explicitly invoking find/replace bar updateSearchKeyword and textChanged-related paths on wrappers and editors.
tests/src/widgets/ut_window.cpp
Increase coverage of DDropdownMenu by testing menu request handling, current text retrieval, encode/highlight factory menu lambdas, and constructor size-mode reaction while keeping menu popups non-blocking via stubs.
  • Remove unused/commented eventFilter test and add new tests for slotRequestMenu, getCurrentText, createEncodeMenu’s triggered lambda, createHighLightMenu’s no-highlight and QActionGroup-triggered lambdas, and constructor’s DGuiApplicationHelper::sizeModeChanged lambda.
  • Stub QMenu::exec to avoid blocking dialogs and verify that slotRequestMenu and factory menus react correctly to signal emissions without UI interaction.
tests/src/widgets/ut_ddropdownmenu.cpp
Extend BottomBar tests to cover format menu handling, focus-change slot, and constructor-connected encoding/highlighting menu lambdas using controlled wrappers and stubs.
  • Add stubs for EditWrapper::getFileLoading and reloadFileHighlight to safely exercise BottomBar’s encoding and highlighting change lambdas without touching real file-loading or highlighter infrastructure.
  • Introduce tests for onFormatMenuTrigged early-return behaviour with null and unchanged actions, for slotSetTextEditFocus via a real Window emitting pressEsc, and for constructor lambdas on m_pEncodeMenu and m_pHighlightMenu currentActionChanged signals.
  • Reuse existing BottomBar fixtures while ensuring only a single Window is constructed in this test group to avoid static-anchors lifetime issues mentioned in comments.
tests/src/widgets/ut_bottombar.cpp
Increase ColorSelectWdg coverage by exercising initWidget’s button and color-label click lambdas and verifying selection and signal emission behaviour.
  • Add tests that click the default color button to ensure sigColorSelected is emitted via the connected lambda.
  • Add tests that simulate mouse press on non-default ColorLabel entries, asserting that selection is shifted away from the initially selected label and that sigColorSelected is emitted once.
tests/src/widgets/ut_colorselectwidget.cpp
Add a dedicated test file to cover EditorApplication’s destructor and pressSpace QTimer lambda without destabilising the global QApplication lifecycle.
  • Introduce ut_zz_editorapplication_extra.cpp with tests that create an EditorApplication instance, call pressSpace on a QPushButton to exercise its singleShot(80ms) lambda, and prepare destructor coverage using deleteLater plus a StartManager::instance stub that returns nullptr.
  • Order the file with a ut_zz_ prefix so it runs late in the test suite, and rely on deleteLater rather than direct delete to avoid breaking later QWidget usage in the same process.
tests/src/ut_zz_editorapplication_extra.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

@pengfeixx
pengfeixx force-pushed the test/ut-textedit-window-ext branch 6 times, most recently from e6758e8 to dfe267c Compare August 3, 2026 01:54
Add stub for slotCanRedoChanged to 134 test locations preventing SEGV.
Remove QTest::qWait calls that process stale queued events.

Log: 扩充TextEdit和Window测试,修复批量测试崩溃
Influence: 提升函数覆盖率至98.7%,消除全量测试SEGV崩溃
@pengfeixx
pengfeixx force-pushed the test/ut-textedit-window-ext branch from dfe267c to cd244be Compare August 3, 2026 01:54
@deepin-ci-robot

Copy link
Copy Markdown

deepin pr auto review

★ 总体评分:40分

■ 【总体评价】

代码补充了大量单元测试用例,有效提升了测试覆盖率,但存在通过硬编码内存偏移量修改私有成员的危险操作
逻辑上存在严重隐患因内存越界风险扣25分,且代码质量一般扣10分

■ 【详细分析】

  • 1.语法逻辑(存在严重错误)✕

tests/src/editor/ut_textedit.cppuncovered_helpers 命名空间中,forceGestureState 函数使用硬编码偏移量 124 直接修改 QGesture 的私有成员状态。这种做法依赖于特定的编译器和 Qt 版本的内存布局,一旦环境变化将导致写入错误地址,引发段错误。
潜在问题:跨平台或 Qt 版本升级时导致内存越界写入;指针 g 未做空指针检查可能导致空指针解引用。
建议:移除 forceGestureState 函数,使用 Qt 提供的公共 API 或 Mock 框架来模拟手势状态;若必须访问私有成员,应使用友元类或 Qt 的元对象系统,并增加空指针校验。

  • 2.代码质量(一般)✕

tests/src/editor/ut_textedit.cpp 中,大量测试用例重复插入了相同的 Stub 代码来拦截 slotCanUndoChangedslotCanRedoChanged,造成严重的代码冗余。此外,UT_DeferredDeleteBlocker 全局拦截 DeferredDelete 事件,虽然注释说明了原因,但会导致测试期间所有 deleteLater 对象无法销毁。
潜在问题:代码重复度高,维护成本高;全局事件拦截可能导致测试用例间的状态污染和内存泄漏。
建议:将重复的 Stub 逻辑提取到测试夹具的 SetUp() 方法中;优化 UT_DeferredDeleteBlocker 的作用范围,仅在必要时安装,并在测试结束后及时移除。

  • 3.代码性能(无性能问题)✓

测试代码主要涉及对象创建、信号触发和断言,不存在复杂的算法或高频轮询,对测试执行效率影响较小。
建议:保持现有测试结构,关注测试用例的独立性。

  • 4.代码安全(存在 1 个安全漏洞)✕

漏洞对比统计:新增漏洞 1 个,减少漏洞 0 个,持平 0 个
代码中存在直接操作内存偏移的危险操作,可能导致进程崩溃。

  • 安全漏洞1(高危):内存越界写入 在 tests/src/editor/ut_textedit.cppforceGestureState 函数中,通过 (char *)g->d_func() + 124 硬编码偏移量修改私有数据,未校验指针有效性和内存布局,触发方式为直接调用该函数,危害是导致内存破坏和拒绝服务 ——非常重要

  • 建议:删除 forceGestureState 函数,改用安全的 Qt 公共接口或测试专用的 Mock 对象来设置手势状态。

■ 【改进建议代码示例】

// tests/src/editor/ut_textedit.cpp

// 移除危险的 forceGestureState 函数,改用事件驱动或 Mock 方式
// 如果 QTapGesture 无法直接设置状态,可以通过发送底层事件来触发状态改变

namespace uncovered_helpers {

static TextEdit *makeEditorInWindow(Window *&win)
{
    win = new Window();
    win->addBlankTab(QString());
    return win->currentWrapper()->textEditor();
}

// 安全的手势状态触发方式示例(具体实现取决于被测代码对手势状态的消费逻辑)
// 如果必须测试特定状态,建议使用 gmock 等框架 mock QGesture

} // namespace uncovered_helpers

// 在测试用例中,避免使用 forceGestureState
TEST(UT_Textedit_Uncovered, tapGestureTriggered)
{
    Window *win = nullptr;
    TextEdit *edit = makeEditorInWindow(win);
    
    // 创建手势对象并正常触发,不强制修改内部状态
    QTapGesture *tap = new QTapGesture;
    // 假设可以通过其他方式触发状态更新,或仅测试默认状态下的行为
    edit->tapGestureTriggered(tap);
    delete tap;

    win->deleteLater();
}

// 针对 UT_DeferredDeleteBlocker 的优化建议
class UT_DeferredDeleteBlocker : public QObject
{
public:
    bool eventFilter(QObject *, QEvent *e) override
    {
        return e->type() == QEvent::DeferredDelete;
    }
};

// 在测试用例中确保安装和移除配对
TEST(UT_Window_updateSizeMode, updateSizeMode_FindBarVisible)
{
    Window *w = new Window();
    UT_DeferredDeleteBlocker blocker;
    qApp->installEventFilter(&blocker); // 安装
    w->show();
    w->addBlankTab();
    w->currentWrapper()->textEditor()->setPlainText("hello world");

    w->popupFindBar();

    w->updateSizeMode();
    qApp->removeEventFilter(&blocker); // 确保移除

    w->deleteLater();
}

@deepin-ci-robot

Copy link
Copy Markdown

@pengfeixx: The following test failed, say /retest to rerun all failed tests or /retest-required to rerun all mandatory failed tests:

Test name Commit Details Required Rerun command
github-pr-review-ci cd244be link true /test github-pr-review-ci

Full PR test history. Your PR dashboard.

Details

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes/test-infra repository. I understand the commands that are listed here.

@deepin-ci-robot

Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: lzwind, pengfeixx

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

@pengfeixx
pengfeixx merged commit 5490cbf into linuxdeepin:master Aug 3, 2026
16 of 20 checks passed
@pengfeixx
pengfeixx deleted the test/ut-textedit-window-ext branch August 3, 2026 01:59
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