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

Bazel test调用基于gnuplot后端的二进制文件时绘图失败如何解决?

问题描述

通过sh_test定义的Bazel测试调用一个以Gnuplot为后端(基于Matplot++实现)的二进制文件时,出现Qt平台插件初始化错误。直接运行该二进制文件可正常显示绘图,但执行bazel test时抛出如下错误:

qt.qpa.xcb: could not connect to display
qt.qpa.plugin: Could not load the Qt platform plugin "xcb" in "" even though it was found.
This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem.

Available platform plugins are: eglfs, linuxfb, minimal, minimalegl, offscreen, vnc, wayland-egl, wayland, wayland-xcomposite-egl, wayland-xcomposite-glx, xcb.

已尝试以下操作但未解决:

  • 设置--strategy和--spawn_strategy为local
  • 设置--test_strategy为standalone
  • 为sh_test配置local=True

需要修复该错误,实现正常显示绘图或让测试以无头模式运行。

解决方案

方案一:让Bazel测试访问X显示(正常显示绘图)

Bazel默认测试沙盒会隔离环境,即使设置本地策略,也可能未正确传递X显示相关变量,可通过以下方式处理:

  1. 显式传递DISPLAY环境变量
    在sh_test定义中添加env属性,直接传递系统的DISPLAY变量:

    sh_test(
        name = "your_test_name",
        srcs = ["your_test_script.sh"],
        env = {
            "DISPLAY": "$(DISPLAY)",
        },
        local = True,
    )
    

    也可在运行测试时通过命令行临时传递:

    bazel test --test_env=DISPLAY=$DISPLAY //path/to:your_test_name
    
  2. 禁用沙盒(仅本地调试用)
    运行测试时关闭沙盒隔离,避免环境变量被截断:

    bazel test --no-sandbox //path/to:your_test_name
    

    注意:禁用沙盒会降低测试隔离性,仅适合本地调试场景。

方案二:以无头模式运行测试(无需显示绘图)

如果不需要实际显示绘图,仅需验证程序逻辑或生成图像文件,可配置Qt使用无头渲染后端:

  1. 指定Qt使用offscreen平台插件
    在sh_test的env中添加对应配置:

    sh_test(
        name = "your_test_name",
        srcs = ["your_test_script.sh"],
        env = {
            "QT_QPA_PLATFORM": "offscreen",
        },
    )
    

    或者在测试脚本中调用二进制时临时设置环境变量:

    QT_QPA_PLATFORM=offscreen ./path/to/your_binary
    
  2. 在代码层配置Matplot++无头输出
    修改二进制代码,让Matplot++直接生成图像文件而非尝试创建GUI窗口:

    #include <matplot/matplot.h>
    int main() {
        matplot::gcf()->set_visible(false); // 禁用窗口显示
        // 执行绘图逻辑...
        matplot::save("test_output.png"); // 将图像保存到文件
        return 0;
    }
    

额外排查点

  • 检查Qt平台插件路径:如果Bazel未正确识别Qt插件目录,可通过QT_PLUGIN_PATH指定路径:
    bazel test --test_env=QT_PLUGIN_PATH=/path/to/qt/plugins //path/to:your_test_name
    
  • 系统依赖检查:确保本地已安装xcb相关依赖库(如libxcb-xinerama0、libxcb-randr0等),部分Linux发行版可能缺少这些库导致插件加载失败。

内容的提问来源于stack exchange,提问作者Amin Ya

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 00:43:13