puppeteer.js 7.5 KB

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