puppeteer.js 7.4 KB

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