问题
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