puppeteer.js 9.5 KB

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