puppeteer.js 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. try {
  2. require( 'puppeteer' );
  3. } catch {
  4. console.log( 'Error: Can\'t find Puppeteer. Run `npm install --prefix test`.' );
  5. process.exit( 0 );
  6. }
  7. const puppeteer = require( 'puppeteer' );
  8. const handler = require( 'serve-handler' );
  9. const http = require( 'http' );
  10. const pixelmatch = require( 'pixelmatch' );
  11. const jimp = require( 'jimp' );
  12. const fs = require( 'fs' );
  13. const port = 1234;
  14. const pixelThreshold = 0.1; // threshold error in one pixel
  15. const maxFailedPixels = 0.05; // total failed pixels
  16. const networkTimeout = 600;
  17. const networkTax = 2000; // additional timeout for resources size
  18. const pageSizeMinTax = 1.0; // in mb, when networkTax = 0
  19. const pageSizeMaxTax = 5.0; // in mb, when networkTax = networkTax
  20. const renderTimeout = 1200;
  21. const maxAttemptId = 3; // progresseve attempts
  22. const progressFunc = n => 1 + n;
  23. const width = 400;
  24. const height = 250;
  25. const viewScale = 2;
  26. const jpgQuality = 95;
  27. const exceptionList = [
  28. 'index',
  29. 'css3d_youtube', // video tag not deterministic enough
  30. 'webaudio_visualizer', // audio can't be analyzed without proper audio hook
  31. 'webgl_loader_texture_lottie', // not sure why this fails
  32. 'webgl_loader_texture_pvrtc', // not supported in CI, useless
  33. 'webgl_materials_envmaps_parallax', // empty for some reason
  34. 'webgl_raymarching_reflect', // exception for Github Actions
  35. 'webgl_test_memory2', // gives fatal error in puppeteer
  36. 'webgl_tiled_forward', // exception for Github Actions
  37. 'webgl_video_kinect', // video tag not deterministic enough
  38. 'webgl_worker_offscreencanvas', // in a worker, not robust
  39. ].concat( ( process.platform === "win32" ) ? [
  40. 'webgl_effects_ascii' // windows fonts not supported
  41. ] : [] );
  42. console.green = ( msg ) => console.log( `\x1b[32m${ msg }\x1b[37m` );
  43. console.red = ( msg ) => console.log( `\x1b[31m${ msg }\x1b[37m` );
  44. console.null = () => {};
  45. /* Launch server */
  46. const server = http.createServer( ( req, resp ) => handler( req, resp ) );
  47. server.listen( port, async () => await pup );
  48. server.on( 'SIGINT', () => process.exit( 1 ) );
  49. /* Launch browser */
  50. const pup = puppeteer.launch( {
  51. headless: ! process.env.VISIBLE,
  52. args: [
  53. '--use-gl=swiftshader',
  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: width * viewScale, height: height * viewScale } );
  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. const threeJsBuild = fs.readFileSync( 'build/three.module.js', 'utf8' )
  65. .replace( /Math\.random\(\) \* 0xffffffff/g, 'Math._random() * 0xffffffff' );
  66. await page.setRequestInterception( true );
  67. page.on( 'console', msg => ( msg.text().slice( 0, 8 ) === 'Warning.' ) ? console.null( msg.text() ) : {} );
  68. page.on( 'request', async ( request ) => {
  69. if ( request.url() === 'http://localhost:1234/build/three.module.js' ) {
  70. await request.respond( {
  71. status: 200,
  72. contentType: 'application/javascript; charset=utf-8',
  73. body: threeJsBuild
  74. } );
  75. } else {
  76. await request.continue();
  77. }
  78. } );
  79. page.on( 'response', async ( response ) => {
  80. try {
  81. await response.buffer().then( buffer => pageSize += buffer.length );
  82. } catch ( e ) {
  83. console.null( `Warning. Wrong request. \n${ e }` );
  84. }
  85. } );
  86. /* Find files */
  87. const isMakeScreenshot = process.argv[ 2 ] == '--make';
  88. const isExactList = process.argv.length > ( 2 + isMakeScreenshot );
  89. const exactList = process.argv.slice( isMakeScreenshot ? 3 : 2 )
  90. .map( f => f.replace( '.html', '' ) );
  91. const files = fs.readdirSync( './examples' )
  92. .filter( s => s.slice( - 5 ) === '.html' )
  93. .map( s => s.slice( 0, s.length - 5 ) )
  94. .filter( f => isExactList ? exactList.includes( f ) : ! exceptionList.includes( f ) );
  95. /* Loop for each file, with CI parallelism */
  96. let pageSize, file, attemptProgress;
  97. let failedScreenshots = [];
  98. const isParallel = 'CI' in process.env;
  99. const beginId = isParallel ? Math.floor( parseInt( process.env.CI.slice( 0, 1 ) ) * files.length / 4 ) : 0;
  100. const endId = isParallel ? Math.floor( ( parseInt( process.env.CI.slice( - 1 ) ) + 1 ) * files.length / 4 ) : files.length;
  101. for ( let id = beginId; id < endId; ++ id ) {
  102. /* At least 3 attempts before fail */
  103. let attemptId = isMakeScreenshot ? 1.5 : 0;
  104. while ( attemptId < maxAttemptId ) {
  105. /* Load target page */
  106. file = files[ id ];
  107. attemptProgress = progressFunc( attemptId );
  108. pageSize = 0;
  109. try {
  110. await page.goto( `http://localhost:${ port }/examples/${ file }.html`, {
  111. waitUntil: 'networkidle2',
  112. timeout: networkTimeout * attemptProgress
  113. } );
  114. } catch {
  115. console.null( 'Warning. Network timeout exceeded...' );
  116. }
  117. try {
  118. /* Render page */
  119. await page.evaluate( cleanPage );
  120. await page.evaluate( async ( pageSize, pageSizeMinTax, pageSizeMaxTax, networkTax, renderTimeout, attemptProgress ) => {
  121. /* Resource timeout */
  122. let resourcesSize = Math.min( 1, ( pageSize / 1024 / 1024 - pageSizeMinTax ) / pageSizeMaxTax );
  123. await new Promise( resolve => setTimeout( resolve, networkTax * resourcesSize * attemptProgress ) );
  124. /* Resolve render promise */
  125. window._renderStarted = true;
  126. await new Promise( function ( resolve ) {
  127. performance._now = performance._now || performance.now;
  128. let renderStart = performance._now();
  129. let waitingLoop = setInterval( function () {
  130. let renderEcceded = ( performance._now() - renderStart > renderTimeout * attemptProgress );
  131. if ( window._renderFinished || 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( `Something completely wrong. 'Network timeout' is small for your machine. file: ${ file } \n${ e }` );
  144. failedScreenshots.push( file );
  145. continue;
  146. } else {
  147. console.log( 'Another attempt..' );
  148. await new Promise( resolve => setTimeout( resolve, networkTimeout * attemptProgress ) );
  149. }
  150. }
  151. if ( isMakeScreenshot ) {
  152. /* Make screenshots */
  153. attemptId = maxAttemptId;
  154. let bitmap = ( await jimp.read( await page.screenshot() ) )
  155. .scale( 1 / viewScale ).quality( jpgQuality )
  156. .write( `./examples/screenshots/${ file }.jpg` ).bitmap;
  157. console.green( `file: ${ file } generated` );
  158. } else if ( fs.existsSync( `./examples/screenshots/${ file }.jpg` ) ) {
  159. /* Diff screenshots */
  160. let actual = ( await jimp.read( await page.screenshot() ) ).scale( 1 / viewScale ).quality( jpgQuality ).bitmap;
  161. let expected = ( await jimp.read( fs.readFileSync( `./examples/screenshots/${ file }.jpg` ) ) ).bitmap;
  162. let diff = actual;
  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( `Something completely wrong. Image sizes does not match in file: ${ file }` );
  174. failedScreenshots.push( file );
  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. console.red( `ERROR! Diff wrong in ${ numFailedPixels.toFixed( 3 ) } of pixels in file: ${ file }` );
  185. failedScreenshots.push( file );
  186. continue;
  187. } else {
  188. console.log( 'Another attempt...' );
  189. }
  190. }
  191. } else {
  192. attemptId = maxAttemptId;
  193. console.log( `Warning! Screenshot not exists: ${ file }` );
  194. continue;
  195. }
  196. }
  197. }
  198. /* Finish */
  199. if ( failedScreenshots.length ) {
  200. if ( failedScreenshots.length > 1 ) {
  201. console.red( 'List of failed screenshots: ' + failedScreenshots.join( ' ' ) );
  202. } else {
  203. console.red( `If you sure that all is right, try to run \`npm run make-screenshot ${ failedScreenshots[ 0 ] }\`` );
  204. }
  205. console.red( `TEST FAILED! ${ failedScreenshots.length } from ${ endId - beginId } screenshots not pass.` );
  206. } else if ( ! isMakeScreenshot ) {
  207. console.green( `TEST PASSED! ${ endId - beginId } screenshots correctly rendered.` );
  208. }
  209. setTimeout( () => {
  210. server.close();
  211. browser.close();
  212. process.exit( failedScreenshots.length );
  213. }, 300 );
  214. } );