puppeteer.js 9.3 KB

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