puppeteer.js 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. /**
  2. * @author munrocket / https://twitter.com/munrocket_twit
  3. */
  4. try {
  5. require( 'puppeteer' );
  6. } catch {
  7. console.log( 'Error: Can\'t find Puppeteer. Run `npm install --prefix test`.' );
  8. process.exit( 0 );
  9. }
  10. const puppeteer = require( 'puppeteer' );
  11. const handler = require( 'serve-handler' );
  12. const http = require( 'http' );
  13. const pixelmatch = require( 'pixelmatch' );
  14. const printImage = require( 'image-output' );
  15. const jimp = require( 'jimp' );
  16. const fs = require( 'fs' );
  17. const port = 1234;
  18. const pixelThreshold = 0.1; // threshold error in one pixel
  19. const maxFailedPixels = 0.05; // total failed pixels
  20. const networkTimeout = 600;
  21. const networkTax = 2000; // additional timeout for resources size
  22. const pageSizeMinTax = 1.0; // in mb, when networkTax = 0
  23. const pageSizeMaxTax = 5.0; // in mb, when networkTax = networkTax
  24. const renderTimeout = 1200;
  25. const maxAttemptId = 3; // progresseve attempts
  26. const progressFunc = n => 1 + n;
  27. const width = 400;
  28. const height = 250;
  29. const viewScale = 2;
  30. const jpgQuality = 95;
  31. const exceptionList = [
  32. 'index',
  33. 'css3d_youtube', // video tag not deterministic enough
  34. 'webaudio_visualizer', // audio can't be analyzed without proper audio hook
  35. 'webgl_kinect', // video tag not deterministic enough
  36. 'webgl_loader_texture_pvrtc', // not supported in CI, useless
  37. 'webgl_materials_envmaps_parallax', // empty for some reason
  38. 'webgl_raymarching_reflect', // exception for Github Actions
  39. 'webgl_test_memory2', // gives fatal error in puppeteer
  40. 'webgl_tiled_forward', // exception for Github Actions
  41. 'webgl_worker_offscreencanvas', // in a worker, not robust
  42. ].concat( ( process.platform === "win32" ) ? [
  43. 'webgl_effects_ascii' // windows fonts not supported
  44. ] : [] );
  45. console.green = ( msg ) => console.log( `\x1b[32m${ msg }\x1b[37m` );
  46. console.red = ( msg ) => console.log( `\x1b[31m${ msg }\x1b[37m` );
  47. console.null = () => {};
  48. /* Launch server */
  49. const server = http.createServer( ( req, resp ) => handler( req, resp ) );
  50. server.listen( port, async () => await pup );
  51. server.on( 'SIGINT', () => process.exit( 1 ) );
  52. /* Launch browser */
  53. const pup = puppeteer.launch( {
  54. headless: ! process.env.VISIBLE,
  55. args: [
  56. '--use-gl=swiftshader',
  57. '--no-sandbox',
  58. '--enable-surface-synchronization'
  59. ]
  60. } ).then( async browser => {
  61. /* Prepare page */
  62. const page = ( await browser.pages() )[ 0 ];
  63. await page.setViewport( { width: width * viewScale, height: height * viewScale } );
  64. const cleanPage = fs.readFileSync( 'test/e2e/clean-page.js', 'utf8' );
  65. const injection = fs.readFileSync( 'test/e2e/deterministic-injection.js', 'utf8' );
  66. await page.evaluateOnNewDocument( injection );
  67. page.on( 'console', msg => ( msg.text().slice( 0, 8 ) === 'Warning.' ) ? console.null( msg.text() ) : {} );
  68. page.on( 'response', async ( response ) => {
  69. try {
  70. await response.buffer().then( buffer => pageSize += buffer.length );
  71. } catch ( e ) {
  72. console.null( `Warning. Wrong request. \n${ e }` );
  73. }
  74. } );
  75. /* Find files */
  76. const exactList = process.argv.slice( 2 ).map( f => f.replace( '.html', '' ) );
  77. const files = fs.readdirSync( './examples' )
  78. .filter( s => s.slice( - 5 ) === '.html' )
  79. .map( s => s.slice( 0, s.length - 5 ) )
  80. .filter( f => ( process.argv.length > 2 ) ? exactList.includes( f ) : ! exceptionList.includes( f ) );
  81. /* Loop for each file, with CI parallelism */
  82. let pageSize, file, attemptProgress;
  83. let failedScreenshots = [];
  84. const isParallel = 'CI' in process.env;
  85. const beginId = isParallel ? Math.floor( parseInt( process.env.CI.slice( 0, 1 ) ) * files.length / 4 ) : 0;
  86. const endId = isParallel ? Math.floor( ( parseInt( process.env.CI.slice( - 1 ) ) + 1 ) * files.length / 4 ) : files.length;
  87. for ( let id = beginId; id < endId; ++ id ) {
  88. /* At least 3 attempts before fail */
  89. let attemptId = process.env.MAKE ? 1.5 : 0;
  90. while ( attemptId < maxAttemptId ) {
  91. /* Load target page */
  92. file = files[ id ];
  93. attemptProgress = progressFunc( attemptId );
  94. pageSize = 0;
  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. performance.wow = performance.wow || performance.now;
  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.push( file );
  131. continue;
  132. } else {
  133. console.log( 'Another attempt..' );
  134. await new Promise( resolve => setTimeout( resolve, networkTimeout * attemptProgress ) );
  135. }
  136. }
  137. if ( process.env.MAKE ) {
  138. /* Make screenshots */
  139. attemptId = maxAttemptId;
  140. let bitmap = ( await jimp.read( await page.screenshot() ) )
  141. .scale( 1 / viewScale ).quality( jpgQuality )
  142. .write( `./examples/screenshots/${ file }.jpg` ).bitmap;
  143. printImage( bitmap, console );
  144. console.green( `file: ${ file } generated` );
  145. } else if ( fs.existsSync( `./examples/screenshots/${ file }.jpg` ) ) {
  146. /* Diff screenshots */
  147. let actual = ( await jimp.read( await page.screenshot() ) ).scale( 1 / viewScale ).quality( jpgQuality ).bitmap;
  148. let expected = ( await jimp.read( fs.readFileSync( `./examples/screenshots/${ file }.jpg` ) ) ).bitmap;
  149. let diff = actual;
  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.push( file );
  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.push( file );
  174. continue;
  175. } else {
  176. console.log( 'Another attempt...' );
  177. }
  178. }
  179. } else {
  180. attemptId = maxAttemptId;
  181. console.log( `Warning! Screenshot not exists: ${ file }` );
  182. continue;
  183. }
  184. }
  185. }
  186. /* Finish */
  187. if ( failedScreenshots.length ) {
  188. if ( failedScreenshots.length > 1 ) {
  189. console.red( 'List of failed screenshots: ' + failedScreenshots.join( ' ' ) );
  190. } else {
  191. console.red( `If you sure that all is right, try to run \`npm run make-screenshot ${ failedScreenshots[ 0 ] }\`` );
  192. }
  193. console.red( `TEST FAILED! ${ failedScreenshots.length } from ${ endId - beginId } screenshots not pass.` );
  194. } else if ( ! process.env.MAKE ) {
  195. console.green( `TEST PASSED! ${ endId - beginId } screenshots correctly rendered.` );
  196. }
  197. setTimeout( () => {
  198. server.close();
  199. browser.close();
  200. process.exit( failedScreenshots.length );
  201. }, 300 );
  202. } );