puppeteer.js 9.0 KB

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