puppeteer.js 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. /**
  2. * @author munrocket / https://github.com/munrocket
  3. */
  4. const puppeteer = require( 'puppeteer' );
  5. const handler = require( 'serve-handler' );
  6. const http = require( 'http' );
  7. const pixelmatch = require( 'pixelmatch' );
  8. const printImage = require( 'image-output' );
  9. const png = require( 'pngjs' ).PNG;
  10. const fs = require( 'fs' );
  11. const port = 1234;
  12. const pixelThreshold = 0.2; // threshold error in one pixel
  13. const maxFailedPixels = 0.05; // total failed pixels
  14. const exceptionList = [
  15. 'index',
  16. 'css3d_youtube', // video tag not deterministic enough
  17. 'webgl_kinect', // same here
  18. 'webaudio_visualizer', // audio can't be analyzed without proper audio hook
  19. 'webgl_loader_texture_pvrtc', // not supported in CI, useless
  20. 'webgl_materials_envmaps_parallax',
  21. 'webgl_test_memory2', // gives fatal error in puppeteer
  22. 'webgl_worker_offscreencanvas', // in a worker, not robust
  23. 'webgl2_multisampled_renderbuffers'
  24. ].concat( ( process.platform === "win32" ) ? [
  25. 'webgl_effects_ascii' // windows fonts not supported
  26. ] : [] );
  27. const networkTimeout = 600;
  28. const networkTax = 2000; // additional timeout for resources size
  29. const pageSizeMinTax = 1.0; // in mb, when networkTax = 0
  30. const pageSizeMaxTax = 5.0; // in mb, when networkTax = networkTax
  31. const renderTimeout = 1200;
  32. const maxAttemptId = 3; // progresseve attempts
  33. const progressFunc = n => 1 + n;
  34. console.green = ( msg ) => console.log( `\x1b[32m${ msg }\x1b[37m` );
  35. console.red = ( msg ) => console.log( `\x1b[31m${ msg }\x1b[37m` );
  36. console.null = () => {};
  37. /* Launch server */
  38. const server = http.createServer( ( req, resp ) => handler( req, resp ) );
  39. server.listen( port, async () => await pup );
  40. server.on( 'SIGINT', () => process.exit( 1 ) );
  41. /* Launch puppeteer with WebGL support in Linux */
  42. const pup = puppeteer.launch( {
  43. headless: ! process.env.VISIBLE,
  44. args: [
  45. '--use-gl=swiftshader',
  46. '--no-sandbox',
  47. '--enable-surface-synchronization'
  48. ]
  49. } ).then( async browser => {
  50. /* Prepare page */
  51. const page = ( await browser.pages() )[ 0 ];
  52. await page.setViewport( { width: 800, height: 600 } );
  53. const cleanPage = fs.readFileSync( 'test/e2e/clean-page.js', 'utf8' );
  54. const injection = fs.readFileSync( 'test/e2e/deterministic-injection.js', 'utf8' );
  55. await page.evaluateOnNewDocument( injection );
  56. page.on( 'console', msg => ( msg.text().slice( 0, 8 ) === 'Warning.' ) ? console.null( msg.text() ) : {} );
  57. page.on( 'response', async ( response ) => {
  58. try {
  59. await response.buffer().then( buffer => pageSize += buffer.length );
  60. } catch ( e ) {
  61. console.null( `Warning. Wrong request. \n${ e }` );
  62. }
  63. } );
  64. /* Find files */
  65. const exactList = process.argv.slice( 2 ).map( f => f.replace( '.html', '' ) );
  66. const files = fs.readdirSync( './examples' )
  67. .filter( s => s.slice( - 5 ) === '.html' )
  68. .map( s => s.slice( 0, s.length - 5 ) )
  69. .filter( f => ( process.argv.length > 2 ) ? exactList.includes( f ) : ! exceptionList.includes( f ) );
  70. /* Loop for each file, with CI parallelism */
  71. let pageSize, file, attemptProgress;
  72. let failedScreenshots = [];
  73. const isParallel = 'CI' in process.env;
  74. const beginId = isParallel ? Math.floor( parseInt( process.env.CI.slice( 0, 1 ) ) * files.length / 4 ) : 0;
  75. const endId = isParallel ? Math.floor( ( parseInt( process.env.CI.slice( - 1 ) ) + 1 ) * files.length / 4 ) : files.length;
  76. for ( let id = beginId; id < endId; ++ id ) {
  77. /* At least 3 attempts before fail */
  78. let attemptId = process.env.MAKE ? 1 : 0;
  79. while ( attemptId < maxAttemptId ) {
  80. /* Load target page */
  81. file = files[ id ];
  82. attemptProgress = progressFunc( attemptId );
  83. pageSize = 0;
  84. global.gc();
  85. global.gc();
  86. try {
  87. await page.goto( `http://localhost:${ port }/examples/${ file }.html`, {
  88. waitUntil: 'networkidle2',
  89. timeout: networkTimeout * attemptProgress
  90. } );
  91. } catch {
  92. console.null( 'Warning. Network timeout exceeded...' );
  93. }
  94. try {
  95. /* Render page */
  96. await page.evaluate( cleanPage );
  97. await page.evaluate( async ( pageSize, pageSizeMinTax, pageSizeMaxTax, networkTax, renderTimeout, attemptProgress ) => {
  98. /* Resource timeout */
  99. let resourcesSize = Math.min( 1, ( pageSize / 1024 / 1024 - pageSizeMinTax ) / pageSizeMaxTax );
  100. await new Promise( resolve => setTimeout( resolve, networkTax * resourcesSize * attemptProgress ) );
  101. /* Resolve render promise */
  102. window.chromeRenderStarted = true;
  103. await new Promise( function ( resolve ) {
  104. if ( typeof performance.wow === 'undefined' ) {
  105. performance.wow = performance.now;
  106. }
  107. let renderStart = performance.wow();
  108. let waitingLoop = setInterval( function () {
  109. let renderEcceded = ( performance.wow() - renderStart > renderTimeout * attemptProgress );
  110. if ( window.chromeRenderFinished || renderEcceded ) {
  111. if ( renderEcceded ) {
  112. console.log( 'Warning. Render timeout exceeded...' );
  113. }
  114. clearInterval( waitingLoop );
  115. resolve();
  116. }
  117. }, 0 );
  118. } );
  119. }, pageSize, pageSizeMinTax, pageSizeMaxTax, networkTax, renderTimeout, attemptProgress );
  120. } catch ( e ) {
  121. if ( ++ attemptId === maxAttemptId ) {
  122. console.red( `WTF? 'Network timeout' is small for your machine. file: ${ file } \n${ e }` );
  123. failedScreenshots.push( file );
  124. continue;
  125. } else {
  126. console.log( 'Another attempt..' );
  127. await new Promise( resolve => setTimeout( resolve, networkTimeout * attemptProgress ) );
  128. }
  129. }
  130. /* Make or diff? */
  131. if ( process.env.MAKE ) {
  132. /* Make screenshots */
  133. attemptId = maxAttemptId;
  134. await page.screenshot( { path: `./examples/screenshots/${ file }.png` } );
  135. printImage( png.sync.read( fs.readFileSync( `./examples/screenshots/${ file }.png` ) ), console );
  136. console.green( `file: ${ file } generated` );
  137. } else if ( fs.existsSync( `./examples/screenshots/${ file }.png` ) ) {
  138. /* Diff screenshots */
  139. let actual = png.sync.read( await page.screenshot() );
  140. let expected = png.sync.read( fs.readFileSync( `./examples/screenshots/${ file }.png` ) );
  141. let diff = new png( { width: actual.width, height: actual.height } );
  142. let numFailedPixels;
  143. try {
  144. numFailedPixels = pixelmatch( expected.data, actual.data, diff.data, actual.width, actual.height, {
  145. threshold: pixelThreshold,
  146. alpha: 0.2,
  147. diffMask: process.env.FORCE_COLOR === '0',
  148. diffColor: process.env.FORCE_COLOR === '0' ? [ 255, 255, 255 ] : [ 255, 0, 0 ]
  149. } );
  150. } catch {
  151. attemptId = maxAttemptId;
  152. console.red( `ERROR! Image sizes does not match in file: ${ file }` );
  153. failedScreenshots.push( file );
  154. continue;
  155. }
  156. numFailedPixels /= actual.width * actual.height;
  157. /* Print results */
  158. if ( numFailedPixels < maxFailedPixels ) {
  159. attemptId = maxAttemptId;
  160. console.green( `diff: ${ numFailedPixels.toFixed( 3 ) }, file: ${ file }` );
  161. } else {
  162. if ( ++ attemptId === maxAttemptId ) {
  163. printImage( diff, console );
  164. console.red( `ERROR! Diff wrong in ${ numFailedPixels.toFixed( 3 ) } of pixels in file: ${ file }` );
  165. failedScreenshots.push( file );
  166. continue;
  167. } else {
  168. console.log( 'Another attempt...' );
  169. }
  170. }
  171. } else {
  172. attemptId = maxAttemptId;
  173. console.null( `Warning! Screenshot not exists: ${ file }` );
  174. continue;
  175. }
  176. }
  177. }
  178. /* Finish */
  179. if ( failedScreenshots.length ) {
  180. if ( failedScreenshots.length > 1 ) {
  181. console.red( 'List of failed screenshots: ' + failedScreenshots.join(' ') );
  182. } else {
  183. console.red( `If you sure that all is right, try to run \`npm run make-screenshot ${ failedScreenshots[ 0 ] }\`` );
  184. }
  185. console.red( `TEST FAILED! ${ failedScreenshots.length } from ${ endId - beginId } screenshots not pass.` );
  186. } else if ( ! process.env.MAKE ) {
  187. console.green( `TEST PASSED! ${ endId - beginId } screenshots correctly rendered.` );
  188. }
  189. browser.close();
  190. server.close();
  191. process.exit( failedScreenshots.length );
  192. } );