Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 872
dimo414 Avatar asked Jul 13 '26 21:07

dimo414


1 Answers

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".
like image 142
Thomas Dickey Avatar answered Jul 16 '26 15:07

Thomas Dickey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!