puppeteer.js 9.6 KB

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