You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GitHub Action中pytest-qt测试PyQt6应用遇段错误求助

解决GitHub Action中PyQt6+pytest-qt段错误问题

核心修复步骤

  • 不要混用手动Xvfb启动与xvfb-run:你的配置同时手动启动Xvfb又调用xvfb-run,会导致虚拟显示器进程冲突,是段错误的主要诱因。
  • 移除手动设置的DISPLAY环境变量:xvfb-run会自动管理DISPLAY变量,手动设置会引发环境冲突。
  • 避免用sudo安装Python依赖:sudo pip会将包安装到系统Python环境,与setup-python配置的独立环境不一致,导致库加载路径错误。
  • 不要手动创建QApplication实例:pytest-qt的qtbot已自动提供全局唯一的QApplication实例,重复创建会触发Qt的单例冲突。

修改后的GitHub Action配置

name: unit-tests
run-name: Run unit tests after push by @${{ github.actor }}
on:
  push:
    branches: [ master ]
jobs:
  unit-test:
    runs-on: ${{ matrix.os }}
    strategy:
      matrix:
        os : [ubuntu-latest]
        python-version: [ "3.9" ]
    steps:
      - uses: actions/checkout@v3
      - name: Set up Python ${{ matrix.python-version }}
        uses: actions/setup-python@v4
        with:
          python-version: ${{ matrix.python-version }}
      - name: Install dependencies
        run: |
          sudo apt update
          sudo apt install -y libxkbcommon-x11-0 libxcb-icccm4 libxcb-image0 libxcb-keysyms1 libxcb-randr0 libxcb-render-util0 libxcb-xinerama0 libxcb-xfixes0 x11-utils libegl1 xvfb qt6-base-dev
          pip install --upgrade pip
          pip install -r requirements.txt
      - name: Test with pytest
        run: |
          chmod +x ./test.sh
          xvfb-run --auto-servernum ./test.sh

优化后的测试代码

import pytest
from PyQt6 import QtCore
from PyQt6.QtWidgets import QMainWindow, QPushButton


class DummyApp(QMainWindow):
    def __init__(self):
        super().__init__()
        self.button = QPushButton("Click me", self)
        self.button.clicked.connect(self.on_button_click)

    def on_button_click(self):
        self.button.setText("Clicked!")

@pytest.fixture
def app(qtbot):
    # 直接使用pytest-qt自动创建的QApplication,无需手动实例化
    window = DummyApp()
    window.show()
    qtbot.addWidget(window)
    yield window
    window.close()

def test_button_click(app, qtbot):
    qtbot.mouseClick(app.button, QtCore.Qt.MouseButton.LeftButton)
    assert app.button.text() == "Clicked!"

错误原因解析

  1. 虚拟显示器冲突:手动启动Xvfb后再用xvfb-run,会生成多个独立的虚拟显示进程,Qt无法正确绑定到有效显示设备,引发段错误。
  2. 权限与环境不一致:sudo执行测试会切换到root用户,环境变量(如Python路径、库搜索路径)与runner默认用户不一致,导致PyQt加载底层Qt库时出现权限或路径错误。
  3. QApplication单例冲突:Qt严格要求一个进程只能存在一个QApplication实例,手动创建会与pytest-qt自动初始化的实例冲突,触发内存访问错误。

内容的提问来源于stack exchange,提问作者Leo Li

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 07:43:13