How can I unit/integration test a program's ANSI escape code behavior?

青春壹個敷衍的年華 提交于 2019-12-20 03:08:46

问题


I've started adding some coloring and other functionality (line resets, etc.) to my application and would like to have some unit tests covering the behavior.

I know I could just assert that the output contains the appropriate \e[... codes, but that's brittle. For one, it would fail if it were swapped to \033 or otherwise refactored in trivial but not identical ways.

More to the point however, testing the sequence of characters doesn't really do what I want. I want to assert or verify that the behavior hasn't changed (or even works at all in a particular environment).

Is there any reasonable way to test the result of an ANSI escape sequence? For instance, can I programatically inspect the contents of a terminal / tty?


回答1:


Yes and no: as a rule, terminal programs do not provide a way to retrieve the contents of the screen, e.g., in response to an escape sequence, because allowing that is considered insecure (if you happen to run a program that does this without your knowledge).

However, some terminal programs allow you to print the screen contents. xterm can do this, for instance. You can configure it to print to a file, and use escape sequences for the colors and video attributes which are on the screen. Unlike your test-program, those escape sequences are printed line-by-line, rather than jumping around the screen.

From the manual, the relevant resources are

   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.   

and

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


来源:https://stackoverflow.com/questions/35134298/how-can-i-unit-integration-test-a-programs-ansi-escape-code-behavior

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!