puppeteer.js 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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 injection = fs.readFileSync( 'test/diff/deterministic-injection.js', 'utf8' );
  61. await page.evaluateOnNewDocument( injection );
  62. page.on( 'console', msg => ( msg.text().slice( 0, 8 ) === 'Warning.' ) ? console.null( msg.text() ) : {} );
  63. page.on( 'response', async ( response ) => {
  64. try {
  65. await response.buffer().then( buffer => pageSize += buffer.length );
  66. } catch ( e ) {
  67. console.null( `Warning. Wrong request. \n${ e }` );
  68. }
  69. } );
  70. /* Find files */
  71. const exactList = process.argv.slice( 2 ).map( f => f.replace( '.html', '' ) );
  72. const files = fs.readdirSync( './examples' )
  73. .filter( s => s.slice( - 5 ) === '.html' )
  74. .map( s => s.slice( 0, s.length - 5 ) )
  75. .filter( f => ( process.argv.length > 2 ) ? exactList.includes( f ) : ! exceptionList.includes( f ) );
  76. /* Loop for each file, with CI parallelism */
  77. let pageSize, file, attemptProgress;
  78. let failedScreenshots = 0;
  79. const isParallel = 'CI' in process.env;
  80. const beginId = isParallel ? Math.floor( parseInt( process.env.CI.slice( 0, 1 ) ) * files.length / 4 ) : 0;
  81. const endId = isParallel ? Math.floor( ( parseInt( process.env.CI.slice( - 1 ) ) + 1 ) * files.length / 4 ) : files.length;
  82. for ( let id = beginId; id < endId; ++ id ) {
  83. /* At least 3 attempts before fail */
  84. let attemptId = process.env.MAKE ? 1 : 0;
  85. while ( attemptId < maxAttemptId ) {
  86. /* Load target page */
  87. file = files[ id ];
  88. attemptProgress = progressFunc( attemptId );
  89. pageSize = 0;
  90. global.gc();
  91. global.gc();
  92. try {
  93. await page.goto( `http://localhost:${ port }/examples/${ file }.html`, {
  94. waitUntil: 'networkidle2',
  95. timeout: networkTimeout * attemptProgress
  96. } );
  97. } catch {
  98. console.null( 'Warning. Network timeout exceeded...' );
  99. }
  100. try {
  101. await page.evaluate( async ( pageSize, pageSizeMinTax, pageSizeMaxTax, networkTax, renderTimeout, attemptProgress ) => {
  102. /* Prepare page */
  103. let button = document.getElementById( 'startButton' );
  104. if ( button ) {
  105. button.click();
  106. }
  107. let style = document.createElement( 'style' );
  108. style.type = 'text/css';
  109. style.innerHTML = `body { font size: 0 !important; }
  110. #info, button, input, body > div.dg.ac, body > div.lbl { display: none !important; }`;
  111. let head = document.getElementsByTagName( 'head' );
  112. if ( head.length > 0 ) {
  113. head[ 0 ].appendChild( style );
  114. }
  115. let canvas = document.getElementsByTagName( 'canvas' );
  116. for ( let i = 0; i < canvas.length; ++ i ) {
  117. if ( canvas[ i ].height === 48 ) {
  118. canvas[ i ].style.display = 'none';
  119. }
  120. }
  121. let resourcesSize = Math.min( 1, ( pageSize / 1024 / 1024 - pageSizeMinTax ) / pageSizeMaxTax );
  122. await new Promise( resolve => setTimeout( resolve, networkTax * resourcesSize * attemptProgress ) );
  123. /* Resolve render promise */
  124. window.chromeRenderStarted = true;
  125. await new Promise( function ( resolve ) {
  126. if ( typeof performance.wow === 'undefined' ) {
  127. performance.wow = performance.now;
  128. }
  129. let renderStart = performance.wow();
  130. let waitingLoop = setInterval( function () {
  131. let renderEcceded = ( performance.wow() - renderStart > renderTimeout * window.chromeMaxFrameId * attemptProgress );
  132. if ( window.chromeRenderFinished || renderEcceded ) {
  133. if ( renderEcceded ) {
  134. console.log( 'Warning. Render timeout exceeded...' );
  135. }
  136. clearInterval( waitingLoop );
  137. resolve();
  138. }
  139. }, 0 );
  140. } );
  141. }, pageSize, pageSizeMinTax, pageSizeMaxTax, networkTax, renderTimeout, attemptProgress );
  142. } catch ( e ) {
  143. if ( ++ attemptId === maxAttemptId ) {
  144. console.red( `WTF? 'Network timeout' is small for your machine. file: ${ file } \n${ e }` );
  145. ++ failedScreenshots;
  146. continue;
  147. } else {
  148. console.log( 'Another attempt..' );
  149. await new Promise( resolve => setTimeout( resolve, networkTimeout * attemptProgress ) );
  150. }
  151. }
  152. /* Make or diff? */
  153. if ( process.env.MAKE ) {
  154. /* Make screenshots */
  155. attemptId = maxAttemptId;
  156. await page.screenshot( { path: `./examples/screenshots/${ file }.png` } );
  157. console.green( `file: ${ file } generated` );
  158. } else if ( fs.existsSync( `./examples/screenshots/${ file }.png` ) ) {
  159. /* Diff screenshots */
  160. let actual = png.sync.read( await page.screenshot() );
  161. let expected = png.sync.read( fs.readFileSync( `./examples/screenshots/${ file }.png` ) );
  162. let diff = new png( { width: actual.width, height: actual.height } );
  163. let numFailedPixels;
  164. try {
  165. numFailedPixels = pixelmatch( expected.data, actual.data, diff.data, actual.width, actual.height, {
  166. threshold: pixelThreshold,
  167. alpha: 0.2,
  168. diffMask: process.env.FORCE_COLOR === '0',
  169. diffColor: process.env.FORCE_COLOR === '0' ? [ 255, 255, 255 ] : [ 255, 0, 0 ]
  170. } );
  171. } catch {
  172. attemptId = maxAttemptId;
  173. console.red( `ERROR! Image sizes does not match in file: ${ file }` );
  174. ++ failedScreenshots;
  175. continue;
  176. }
  177. numFailedPixels /= actual.width * actual.height;
  178. /* Print results */
  179. if ( numFailedPixels < maxFailedPixels ) {
  180. attemptId = maxAttemptId;
  181. console.green( `diff: ${ numFailedPixels.toFixed( 3 ) }, file: ${ file }` );
  182. } else {
  183. if ( ++ attemptId === maxAttemptId ) {
  184. printImage( diff, console );
  185. console.red( `ERROR! Diff wrong in ${ numFailedPixels.toFixed( 3 ) } of pixels in file: ${ file }` );
  186. ++ failedScreenshots;
  187. continue;
  188. } else {
  189. console.log( 'Another attempt...' );
  190. }
  191. }
  192. } else {
  193. attemptId = maxAttemptId;
  194. console.red( `ERROR! Screenshot not exists: ${ file }` );
  195. ++ failedScreenshots;
  196. continue;
  197. }
  198. }
  199. }
  200. /* Finish */
  201. if ( failedScreenshots ) {
  202. console.red( `TEST FAILED! ${ failedScreenshots } from ${ endId - beginId } screenshots not pass.` );
  203. process.exit( 1 );
  204. } else if ( ! process.env.MAKE ) {
  205. console.green( `TEST PASSED! ${ endId - beginId } screenshots correctly rendered.` );
  206. }
  207. await browser.close();
  208. } );