puppeteer.js 8.1 KB

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