首页 > 解决方案 > 在无头 linux 服务器上获取系统剪贴板的内容以进行自动化测试

问题描述

我正在尝试通过 docker 在无头 linux 系统上运行一些 selenium 案例,其中“用户”单击将文本复制到系统剪贴板的按钮。运行此代码时,我收到一条错误消息,提示“未设置 X11 DISPLAY 变量,但该程序执行了需要它的操作。” 我现在正在使用 xvfb 运行该案例,以解决缺少 X11 Display 变量的问题,但代码仍然无法正常工作。现在,当我尝试访问系统剪贴板的内容时,我得到了一个空指针。

这是我正在运行以获取复制文本的代码。

String copied = null;

    try {

        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        Transferable transferable = clipboard.getContents(null);
        DataFlavor[] availableFlavors = clipboard.getAvailableDataFlavors();

        if ( transferable != null && transferable.isDataFlavorSupported(DataFlavor.stringFlavor) ) {
            copied = (String)transferable.getTransferData(DataFlavor.stringFlavor);
        } else {
            System.out.println("Could not find a suitable flavor.");
            if ( transferable.getTransferDataFlavors().length == 0 ) {
                System.out.println("no supported flavors");
            }
            for ( DataFlavor availableFlav : availableFlavors ) {
                System.out.println("availableFlav = " + availableFlav);
            }
            for ( DataFlavor flavaflav : transferable.getTransferDataFlavors() ) {
                System.out.println("transferDataFlavor = " + flavaflav);
            }
        }

    // I am not sure what could cause the below exceptions to happen, but we should just fail the case if they occur.
    } catch (IOException e) {
        e.printStackTrace();
        fail("IOException while fetching copied text.");
    } catch (UnsupportedFlavorException e) {
        e.printStackTrace();
        fail("UnsupportedFlavorException while fetching copied text.");
    }

    return copied;

使用 xvfb 运行此代码会产生以下输出:

Could not find a suitable flavor.
no supported flavors

然后抛出 NullPointerException。

有没有办法伪造在这个无头 linux 服务器中实际工作的系统剪贴板?什么可能导致在 xvfb 中运行的系统剪贴板没有复制任何内容?

标签: awtclipboardcopy-pasteheadlessxvfb

解决方案


推荐阅读