puppeteer.js 7.6 KB

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