2222'use strict' ;
2323const common = require ( '../common' ) ;
2424const assert = require ( 'assert' ) ;
25+ const util = require ( 'util' ) ;
2526
2627const [ , , modeArgv , sectionArgv ] = process . argv ;
2728
@@ -54,19 +55,36 @@ function parent() {
5455 test ( '*-test' , true , 'abc-test' ) ;
5556}
5657
57- function test ( environ , shouldWrite , section ) {
58+ function test ( environ , shouldWrite , section , forceColors = false ) {
5859 let expectErr = '' ;
5960 const expectOut = 'ok\n' ;
6061
6162 const spawn = require ( 'child_process' ) . spawn ;
6263 const child = spawn ( process . execPath , [ __filename , 'child' , section ] , {
63- env : Object . assign ( process . env , { NODE_DEBUG : environ } )
64+ env : Object . assign ( process . env , {
65+ NODE_DEBUG : environ ,
66+ FORCE_COLOR : forceColors ? 'true' : 'false'
67+ } )
6468 } ) ;
6569
6670 if ( shouldWrite ) {
67- expectErr =
68- `${ section . toUpperCase ( ) } ${ child . pid } : this { is: 'a' } /debugging/\n${
69- section . toUpperCase ( ) } ${ child . pid } : num=1 str=a obj={"foo":"bar"}\n`;
71+ if ( forceColors ) {
72+ const { colors, styles } = util . inspect ;
73+ const addCodes = ( arr ) => [ `\x1B[${ arr [ 0 ] } m` , `\x1B[${ arr [ 1 ] } m` ] ;
74+ const num = addCodes ( colors [ styles . number ] ) ;
75+ const str = addCodes ( colors [ styles . string ] ) ;
76+ const regexp = addCodes ( colors [ styles . regexp ] ) ;
77+ const start = `${ section . toUpperCase ( ) } ${ num [ 0 ] } ${ child . pid } ${ num [ 1 ] } ` ;
78+ const debugging = `${ regexp [ 0 ] } /debugging/${ regexp [ 1 ] } ` ;
79+ expectErr =
80+ `${ start } : this { is: ${ str [ 0 ] } 'a'${ str [ 1 ] } } ${ debugging } \n` +
81+ `${ start } : num=1 str=a obj={"foo":"bar"}\n` ;
82+ } else {
83+ const start = `${ section . toUpperCase ( ) } ${ child . pid } ` ;
84+ expectErr =
85+ `${ start } : this { is: 'a' } /debugging/\n` +
86+ `${ start } : num=1 str=a obj={"foo":"bar"}\n` ;
87+ }
7088 }
7189
7290 let err = '' ;
@@ -85,12 +103,20 @@ function test(environ, shouldWrite, section) {
85103 assert ( ! c ) ;
86104 assert . strictEqual ( err , expectErr ) ;
87105 assert . strictEqual ( out , expectOut ) ;
106+ // Run the test again, this time with colors enabled.
107+ if ( ! forceColors ) {
108+ test ( environ , shouldWrite , section , true ) ;
109+ }
88110 } ) ) ;
89111}
90112
91113
92114function child ( section ) {
93- const util = require ( 'util' ) ;
115+ const tty = require ( 'tty' ) ;
116+ // Make sure we check for colors, no matter of the stream's default.
117+ Object . defineProperty ( process . stderr , 'hasColors' , {
118+ value : tty . WriteStream . prototype . hasColors
119+ } ) ;
94120 const debug = util . debuglog ( section ) ;
95121 debug ( 'this' , { is : 'a' } , / d e b u g g i n g / ) ;
96122 debug ( 'num=%d str=%s obj=%j' , 1 , 'a' , { foo : 'bar' } ) ;
0 commit comments