puppeteer.js 8.0 KB

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