puppeteer.js 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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. global.gc();
  86. global.gc();
  87. try {
  88. await page.goto( `http://localhost:${ port }/examples/${ file }.html`, {
  89. waitUntil: 'networkidle2',
  90. timeout: networkTimeout * attemptProgress
  91. } );
  92. } catch {
  93. console.null( 'Warning. Network timeout exceeded...' );
  94. }
  95. try {
  96. /* Render page */
  97. await page.evaluate( cleanPage );
  98. await page.evaluate( async ( pageSize, pageSizeMinTax, pageSizeMaxTax, networkTax, renderTimeout, attemptProgress ) => {
  99. /* Resource timeout */
  100. let resourcesSize = Math.min( 1, ( pageSize / 1024 / 1024 - pageSizeMinTax ) / pageSizeMaxTax );
  101. await new Promise( resolve => setTimeout( resolve, networkTax * resourcesSize * attemptProgress ) );
  102. /* Resolve render promise */
  103. window.chromeRenderStarted = true;
  104. await new Promise( function ( resolve ) {
  105. if ( typeof performance.wow === 'undefined' ) {
  106. performance.wow = performance.now;
  107. }
  108. let renderStart = performance.wow();
  109. let waitingLoop = setInterval( function () {
  110. let renderEcceded = ( performance.wow() - renderStart > renderTimeout * attemptProgress );
  111. if ( window.chromeRenderFinished || renderEcceded ) {
  112. if ( renderEcceded ) {
  113. console.log( 'Warning. Render timeout exceeded...' );
  114. }
  115. clearInterval( waitingLoop );
  116. resolve();
  117. }
  118. }, 0 );
  119. } );
  120. }, pageSize, pageSizeMinTax, pageSizeMaxTax, networkTax, renderTimeout, attemptProgress );
  121. } catch ( e ) {
  122. if ( ++ attemptId === maxAttemptId ) {
  123. console.red( `WTF? 'Network timeout' is small for your machine. file: ${ file } \n${ e }` );
  124. failedScreenshots.push( file );
  125. continue;
  126. } else {
  127. console.log( 'Another attempt..' );
  128. await new Promise( resolve => setTimeout( resolve, networkTimeout * attemptProgress ) );
  129. }
  130. }
  131. /* Make or diff? */
  132. if ( process.env.MAKE ) {
  133. /* Make screenshots */
  134. attemptId = maxAttemptId;
  135. await page.screenshot( { path: `./examples/screenshots/${ file }.png` } );
  136. printImage( png.sync.read( fs.readFileSync( `./examples/screenshots/${ file }.png` ) ), console );
  137. console.green( `file: ${ file } generated` );
  138. } else if ( fs.existsSync( `./examples/screenshots/${ file }.png` ) ) {
  139. /* Diff screenshots */
  140. let actual = png.sync.read( await page.screenshot() );
  141. let expected = png.sync.read( fs.readFileSync( `./examples/screenshots/${ file }.png` ) );
  142. let diff = new png( { width: actual.width, height: actual.height } );
  143. let numFailedPixels;
  144. try {
  145. numFailedPixels = pixelmatch( expected.data, actual.data, diff.data, actual.width, actual.height, {
  146. threshold: pixelThreshold,
  147. alpha: 0.2,
  148. diffMask: process.env.FORCE_COLOR === '0',
  149. diffColor: process.env.FORCE_COLOR === '0' ? [ 255, 255, 255 ] : [ 255, 0, 0 ]
  150. } );
  151. } catch {
  152. attemptId = maxAttemptId;
  153. console.red( `ERROR! Image sizes does not match in file: ${ file }` );
  154. failedScreenshots.push( file );
  155. continue;
  156. }
  157. numFailedPixels /= actual.width * actual.height;
  158. /* Print results */
  159. if ( numFailedPixels < maxFailedPixels ) {
  160. attemptId = maxAttemptId;
  161. console.green( `diff: ${ numFailedPixels.toFixed( 3 ) }, file: ${ file }` );
  162. } else {
  163. if ( ++ attemptId === maxAttemptId ) {
  164. printImage( diff, console );
  165. console.red( `ERROR! Diff wrong in ${ numFailedPixels.toFixed( 3 ) } of pixels in file: ${ file }` );
  166. failedScreenshots.push( file );
  167. continue;
  168. } else {
  169. console.log( 'Another attempt...' );
  170. }
  171. }
  172. } else {
  173. attemptId = maxAttemptId;
  174. console.null( `Warning! Screenshot not exists: ${ file }` );
  175. continue;
  176. }
  177. }
  178. }
  179. /* Finish */
  180. if ( failedScreenshots.length ) {
  181. if ( failedScreenshots.length > 1 ) {
  182. console.red( 'List of failed screenshots: ' + failedScreenshots.join(' ') );
  183. } else {
  184. console.red( `If you sure that all is right, try to run \`npm run make-screenshot ${ failedScreenshots[ 0 ] }\`` );
  185. }
  186. console.red( `TEST FAILED! ${ failedScreenshots.length } from ${ endId - beginId } screenshots not pass.` );
  187. } else if ( ! process.env.MAKE ) {
  188. console.green( `TEST PASSED! ${ endId - beginId } screenshots correctly rendered.` );
  189. }
  190. browser.close();
  191. server.close();
  192. process.exit( failedScreenshots.length );
  193. } );