如何对程序的ANSI转义码行为进行单元/集成测试?

时间:2016-02-01 15:31:36

标签: java testing posix ansi-escape

我已经开始在我的应用程序中添加一些着色和其他功能(行重置等),并希望进行一些覆盖行为的单元测试。

我知道我可以断言输出包含适当的\e[...代码,但这很脆弱。例如,如果它被交换到\033或者以微不足道但不相同的方式进行重构,则会失败。

更重要的是,测试字符序列并不能真正做到我想要的。我想声明或验证行为没有改变(甚至在特定环境中都可以工作)。

有没有合理的方法来测试ANSI转义序列的结果?例如,我可以以编程方式检查终端/ tty的内容吗?

1 个答案:

答案 0 :(得分:1)

是和否:作为一项规则,终端程序不提供检索屏幕内容的方法,例如,响应转义序列,因为允许将其视为不安全(如果你碰巧在你不知情的情况下运行了一个程序。

但是,某些终端程序允许您打印屏幕内容。例如,xterm可以做到这一点。您可以将其配置为打印到文件,并使用转义序列来显示屏幕上的颜色和视频属性。与您的测试程序不同,这些转义序列是逐行打印的,而不是在屏幕上跳跃。

来自manual,相关资源是

   printerCommand (class PrinterCommand)                                    
           Specifies  a  shell command to which xterm-dev will open a pipe  
           when the first MC  (Media  Copy)  command  is  initiated.   The  
           default is an empty string, i.e., “”.  If the resource value is  
           given as an empty string, the printer is disabled.   

   printAttributes (class PrintAttributes)
           Specifies whether to print graphic attributes  along  with  the
           text.   A  real  DEC  VTxxx  terminal will print the underline,
           highlighting codes but your printer may not handle these.

           o   "0" disables the attributes.

           o   "1" prints the normal set of attributes  (bold,  underline,
               inverse and blink) as VT100-style control sequences.

           o   "2" prints ANSI color attributes as well.

           The default is "1".