puppeteer.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  1. import chalk from 'chalk';
  2. import puppeteer from 'puppeteer-core';
  3. import { install, computeExecutablePath/*, resolveBuildId*/, detectBrowserPlatform } from '@puppeteer/browsers';
  4. import express from 'express';
  5. import path from 'path';
  6. import pixelmatch from 'pixelmatch';
  7. import jimp from 'jimp';
  8. import * as fs from 'fs/promises';
  9. class PromiseQueue {
  10. constructor( func, ...args ) {
  11. this.func = func.bind( this, ...args );
  12. this.promises = [];
  13. }
  14. add( ...args ) {
  15. const promise = this.func( ...args );
  16. this.promises.push( promise );
  17. promise.then( () => this.promises.splice( this.promises.indexOf( promise ), 1 ) );
  18. }
  19. async waitForAll() {
  20. while ( this.promises.length > 0 ) {
  21. await Promise.all( this.promises );
  22. }
  23. }
  24. }
  25. /* CONFIG VARIABLES START */
  26. const idleTime = 9; // 9 seconds - for how long there should be no network requests
  27. const parseTime = 6; // 6 seconds per megabyte
  28. const exceptionList = [
  29. // video tag isn't deterministic enough?
  30. 'css3d_youtube',
  31. 'webgl_materials_video',
  32. 'webgl_video_kinect',
  33. 'webgl_video_panorama_equirectangular',
  34. 'webaudio_visualizer', // audio can't be analyzed without proper audio hook
  35. // WebXR also isn't determinstic enough?
  36. 'webxr_ar_lighting',
  37. 'webxr_vr_sandbox',
  38. 'webxr_vr_video',
  39. 'webxr_xr_ballshooter',
  40. 'webgl_worker_offscreencanvas', // in a worker, not robust
  41. // Windows-Linux text rendering differences
  42. // TODO: Fix these by e.g. disabling text rendering altogether -- this can also fix a bunch of 0.1%-0.2% examples
  43. 'css3d_periodictable',
  44. 'misc_controls_pointerlock',
  45. 'misc_uv_tests',
  46. 'webgl_camera_logarithmicdepthbuffer',
  47. 'webgl_effects_ascii',
  48. 'webgl_geometry_extrude_shapes',
  49. 'webgl_interactive_lines',
  50. 'webgl_loader_collada_kinematics',
  51. 'webgl_loader_ldraw',
  52. 'webgl_loader_pdb',
  53. 'webgl_modifier_simplifier',
  54. 'webgl_multiple_canvases_circle',
  55. 'webgl_multiple_elements_text',
  56. // Unknown
  57. // TODO: most of these can be fixed just by increasing idleTime and parseTime
  58. 'webgl_animation_skinning_blending',
  59. 'webgl_buffergeometry_glbufferattribute',
  60. 'webgl_clipping_advanced',
  61. 'webgl_lensflares',
  62. 'webgl_lights_spotlights',
  63. 'webgl_loader_imagebitmap',
  64. 'webgl_loader_texture_lottie',
  65. 'webgl_loader_texture_pvrtc',
  66. 'webgl_materials_alphahash',
  67. 'webgl_materials_blending',
  68. 'webgl_mirror',
  69. 'webgl_morphtargets_face',
  70. 'webgl_nodes_materials_standard',
  71. 'webgl_postprocessing_crossfade',
  72. 'webgl_postprocessing_dof2',
  73. 'webgl_raymarching_reflect',
  74. 'webgl_renderer_pathtracer',
  75. 'webgl_shadowmap',
  76. 'webgl_shadowmap_progressive',
  77. 'webgl_test_memory2',
  78. 'webgl_tiled_forward',
  79. 'webgl2_volume_instancing',
  80. 'webgl_points_dynamic',
  81. // TODO: implement determinism for setTimeout and setInterval
  82. // could it fix some examples from above?
  83. 'physics_rapier_instancing',
  84. // Awaiting for WebGPU support
  85. 'webgpu_audio_processing',
  86. 'webgpu_backdrop',
  87. 'webgpu_backdrop_area',
  88. 'webgpu_clearcoat',
  89. 'webgpu_compute',
  90. 'webgpu_cubemap_adjustments',
  91. 'webgpu_cubemap_dynamic',
  92. 'webgpu_cubemap_mix',
  93. 'webgpu_depth_texture',
  94. 'webgpu_equirectangular',
  95. 'webgpu_instance_mesh',
  96. 'webgpu_instance_uniform',
  97. 'webgpu_lights_custom',
  98. 'webgpu_lights_ies_spotlight',
  99. 'webgpu_lights_phong',
  100. 'webgpu_lights_selective',
  101. 'webgpu_loader_gltf',
  102. 'webgpu_loader_gltf_compressed',
  103. 'webgpu_loader_gltf_iridescence',
  104. 'webgpu_loader_gltf_sheen',
  105. 'webgpu_materials',
  106. 'webgpu_materials_video',
  107. 'webgpu_morphtargets',
  108. 'webgpu_occlusion',
  109. 'webgpu_particles',
  110. 'webgpu_rtt',
  111. 'webgpu_sandbox',
  112. 'webgpu_shadowmap',
  113. 'webgpu_skinning',
  114. 'webgpu_skinning_instancing',
  115. 'webgpu_skinning_points',
  116. 'webgpu_sprites',
  117. 'webgpu_tsl_editor',
  118. 'webgpu_video_panorama'
  119. ];
  120. /* CONFIG VARIABLES END */
  121. const chromiumChannel = 'stable'; // stable -- beta -- dev -- canary -- latest
  122. const installedBrowsersDir = 'test/e2e/chromium';
  123. const port = 1234;
  124. const pixelThreshold = 0.1; // threshold error in one pixel
  125. const maxDifferentPixels = 0.3; // at most 0.3% different pixels
  126. const networkTimeout = 5; // 5 minutes, set to 0 to disable
  127. const renderTimeout = 5; // 5 seconds, set to 0 to disable
  128. const numAttempts = 2; // perform 2 attempts before failing
  129. const numPages = 8; // use 8 browser pages
  130. const numCIJobs = 4; // GitHub Actions run the script in 4 threads
  131. const width = 400;
  132. const height = 250;
  133. const viewScale = 2;
  134. const jpgQuality = 95;
  135. console.red = msg => console.log( chalk.red( msg ) );
  136. console.yellow = msg => console.log( chalk.yellow( msg ) );
  137. console.green = msg => console.log( chalk.green( msg ) );
  138. let browser, platform;
  139. /* Launch server */
  140. const app = express();
  141. app.use( express.static( path.resolve() ) );
  142. const server = app.listen( port, main );
  143. process.on( 'SIGINT', () => close() );
  144. async function main() {
  145. /* Create output directory */
  146. try { await fs.rm( 'test/e2e/output-screenshots', { recursive: true, force: true } ); } catch {}
  147. try { await fs.mkdir( 'test/e2e/output-screenshots' ); } catch {}
  148. /* Find files */
  149. const isMakeScreenshot = process.argv[ 2 ] === '--make';
  150. const exactList = process.argv.slice( isMakeScreenshot ? 3 : 2 )
  151. .map( f => f.replace( '.html', '' ) );
  152. const isExactList = exactList.length !== 0;
  153. let files = ( await fs.readdir( 'examples' ) )
  154. .filter( s => s.slice( - 5 ) === '.html' && s !== 'index.html' )
  155. .map( s => s.slice( 0, s.length - 5 ) )
  156. .filter( f => isExactList ? exactList.includes( f ) : ! exceptionList.includes( f ) );
  157. if ( isExactList ) {
  158. for ( const file of exactList ) {
  159. if ( ! files.includes( file ) ) {
  160. console.log( `Warning! Unrecognised example name: ${ file }` );
  161. }
  162. }
  163. }
  164. /* CI parallelism */
  165. if ( 'CI' in process.env ) {
  166. const CI = parseInt( process.env.CI );
  167. files = files.slice(
  168. Math.floor( CI * files.length / numCIJobs ),
  169. Math.floor( ( CI + 1 ) * files.length / numCIJobs )
  170. );
  171. }
  172. /* Download browser */
  173. const executablePath = await downloadLatestChromium();
  174. /* Launch browser */
  175. const flags = [ '--hide-scrollbars', '--enable-gpu' ];
  176. // flags.push( '--enable-unsafe-webgpu', '--enable-features=Vulkan', '--use-gl=swiftshader', '--use-angle=swiftshader', '--use-vulkan=swiftshader', '--use-webgpu-adapter=swiftshader' );
  177. // if ( process.platform === 'linux' ) flags.push( '--enable-features=Vulkan,UseSkiaRenderer', '--use-vulkan=native', '--disable-vulkan-surface', '--disable-features=VaapiVideoDecoder', '--ignore-gpu-blocklist', '--use-angle=vulkan' );
  178. const viewport = { width: width * viewScale, height: height * viewScale };
  179. browser = await puppeteer.launch( {
  180. executablePath,
  181. headless: process.env.VISIBLE ? false : 'new',
  182. args: flags,
  183. defaultViewport: viewport,
  184. handleSIGINT: false,
  185. protocolTimeout: 0
  186. } );
  187. // this line is intended to stop the script if the browser (in headful mode) is closed by user (while debugging)
  188. // browser.on( 'targetdestroyed', target => ( target.type() === 'other' ) ? close() : null );
  189. // for some reason it randomly stops the script after about ~30 screenshots processed
  190. /* Prepare injections */
  191. const cleanPage = await fs.readFile( 'test/e2e/clean-page.js', 'utf8' );
  192. const injection = await fs.readFile( 'test/e2e/deterministic-injection.js', 'utf8' );
  193. const build = ( await fs.readFile( 'build/three.module.js', 'utf8' ) ).replace( /Math\.random\(\) \* 0xffffffff/g, 'Math._random() * 0xffffffff' );
  194. /* Prepare pages */
  195. const errorMessagesCache = [];
  196. const pages = await browser.pages();
  197. while ( pages.length < numPages && pages.length < files.length ) pages.push( await browser.newPage() );
  198. for ( const page of pages ) await preparePage( page, injection, build, errorMessagesCache );
  199. /* Loop for each file */
  200. const failedScreenshots = [];
  201. const queue = new PromiseQueue( makeAttempt, pages, failedScreenshots, cleanPage, isMakeScreenshot );
  202. for ( const file of files ) queue.add( file );
  203. await queue.waitForAll();
  204. /* Finish */
  205. failedScreenshots.sort();
  206. const list = failedScreenshots.join( ' ' );
  207. if ( isMakeScreenshot && failedScreenshots.length ) {
  208. console.red( 'List of failed screenshots: ' + list );
  209. console.red( `If you are sure that everything is correct, try to run "npm run make-screenshot ${ list }". If this does not help, try increasing idleTime and parseTime variables in /test/e2e/puppeteer.js file. If this also does not help, add remaining screenshots to the exception list.` );
  210. console.red( `${ failedScreenshots.length } from ${ files.length } screenshots have not generated succesfully.` );
  211. } else if ( isMakeScreenshot && ! failedScreenshots.length ) {
  212. console.green( `${ files.length } screenshots succesfully generated.` );
  213. } else if ( failedScreenshots.length ) {
  214. console.red( 'List of failed screenshots: ' + list );
  215. console.red( `If you are sure that everything is correct, try to run "npm run make-screenshot ${ list }". If this does not help, try increasing idleTime and parseTime variables in /test/e2e/puppeteer.js file. If this also does not help, add remaining screenshots to the exception list.` );
  216. console.red( `TEST FAILED! ${ failedScreenshots.length } from ${ files.length } screenshots have not rendered correctly.` );
  217. } else {
  218. console.green( `TEST PASSED! ${ files.length } screenshots rendered correctly.` );
  219. }
  220. setTimeout( close, 300, failedScreenshots.length );
  221. }
  222. async function downloadLatestChromium() {
  223. platform = detectBrowserPlatform();
  224. const revision = '1108766'; //await resolveBuildId( 'chromium', platform, chromiumChannel );
  225. // the Chromium snapshots server doesn't work properly currently so fix the revision
  226. const options = { browser: 'chromium', buildId: revision, cacheDir: path.resolve( installedBrowsersDir ) };
  227. console.log( `Using Chromium r${ revision }, ${ chromiumChannel } channel on ${ platform }` );
  228. console.log( 'Downloading...' );
  229. await install( options );
  230. console.log( 'Downloaded.' );
  231. return computeExecutablePath( options );
  232. }
  233. async function preparePage( page, injection, build, errorMessages ) {
  234. /* let page.file, page.pageSize, page.error */
  235. await page.evaluateOnNewDocument( injection );
  236. await page.setRequestInterception( true );
  237. page.on( 'console', async msg => {
  238. const type = msg.type();
  239. if ( type !== 'warning' && type !== 'error' ) {
  240. return;
  241. }
  242. const file = page.file;
  243. if ( file === undefined ) {
  244. return;
  245. }
  246. const args = await Promise.all( msg.args().map( async arg => {
  247. try {
  248. return await arg.executionContext().evaluate( arg => arg instanceof Error ? arg.message : arg, arg );
  249. } catch ( e ) { // Execution context might have been already destroyed
  250. return arg;
  251. }
  252. } ) );
  253. let text = args.join( ' ' ); // https://github.com/puppeteer/puppeteer/issues/3397#issuecomment-434970058
  254. text = text.trim();
  255. if ( text === '' ) return;
  256. text = file + ': ' + text.replace( /\[\.WebGL-(.+?)\] /g, '' );
  257. if ( text === `${ file }: JSHandle@error` ) {
  258. text = `${ file }: Unknown error`;
  259. }
  260. if ( text.includes( 'Unable to access the camera/webcam' ) ) {
  261. return;
  262. }
  263. if ( errorMessages.includes( text ) ) {
  264. return;
  265. }
  266. errorMessages.push( text );
  267. if ( type === 'warning' ) {
  268. console.yellow( text );
  269. } else {
  270. page.error = text;
  271. }
  272. } );
  273. page.on( 'response', async ( response ) => {
  274. try {
  275. if ( response.status === 200 ) {
  276. await response.buffer().then( buffer => page.pageSize += buffer.length );
  277. }
  278. } catch {}
  279. } );
  280. page.on( 'request', async ( request ) => {
  281. if ( request.url() === `http://localhost:${ port }/build/three.module.js` ) {
  282. await request.respond( {
  283. status: 200,
  284. contentType: 'application/javascript; charset=utf-8',
  285. body: build
  286. } );
  287. } else {
  288. await request.continue();
  289. }
  290. } );
  291. }
  292. async function makeAttempt( pages, failedScreenshots, cleanPage, isMakeScreenshot, file, attemptID = 0 ) {
  293. const page = await new Promise( ( resolve, reject ) => {
  294. const interval = setInterval( () => {
  295. for ( const page of pages ) {
  296. if ( page.file === undefined ) {
  297. page.file = file; // acquire lock
  298. clearInterval( interval );
  299. resolve( page );
  300. break;
  301. }
  302. }
  303. }, 100 );
  304. } );
  305. try {
  306. page.pageSize = 0;
  307. page.error = undefined;
  308. /* Load target page */
  309. try {
  310. await page.goto( `http://localhost:${ port }/examples/${ file }.html`, {
  311. waitUntil: 'networkidle0',
  312. timeout: networkTimeout * 60000
  313. } );
  314. } catch ( e ) {
  315. throw new Error( `Error happened while loading file ${ file }: ${ e }` );
  316. }
  317. try {
  318. /* Render page */
  319. await page.evaluate( cleanPage );
  320. await page.waitForNetworkIdle( {
  321. timeout: networkTimeout * 60000,
  322. idleTime: idleTime * 1000
  323. } );
  324. await page.evaluate( async ( renderTimeout, parseTime ) => {
  325. await new Promise( resolve => setTimeout( resolve, parseTime ) );
  326. /* Resolve render promise */
  327. window._renderStarted = true;
  328. await new Promise( function ( resolve, reject ) {
  329. const renderStart = performance._now();
  330. const waitingLoop = setInterval( function () {
  331. const renderTimeoutExceeded = ( renderTimeout > 0 ) && ( performance._now() - renderStart > 1000 * renderTimeout );
  332. if ( renderTimeoutExceeded ) {
  333. clearInterval( waitingLoop );
  334. reject( 'Render timeout exceeded' );
  335. } else if ( window._renderFinished ) {
  336. clearInterval( waitingLoop );
  337. resolve();
  338. }
  339. }, 10 );
  340. } );
  341. }, renderTimeout, page.pageSize / 1024 / 1024 * parseTime * 1000 );
  342. } catch ( e ) {
  343. if ( ! e.message.includes( 'Render timeout exceeded' ) ) {
  344. throw new Error( `Error happened while rendering file ${ file }: ${ e }` );
  345. } /* else { // This can mean that the example doesn't use requestAnimationFrame loop
  346. console.yellow( `Render timeout exceeded in file ${ file }` );
  347. } */ // TODO: fix this
  348. }
  349. const screenshot = ( await jimp.read( await page.screenshot() ) ).scale( 1 / viewScale ).quality( jpgQuality );
  350. if ( page.error !== undefined ) throw new Error( page.error );
  351. if ( isMakeScreenshot ) {
  352. /* Make screenshots */
  353. await screenshot.writeAsync( `examples/screenshots/${ file }.jpg` );
  354. console.green( `Screenshot generated for file ${ file }` );
  355. } else {
  356. /* Diff screenshots */
  357. let expected;
  358. try {
  359. expected = ( await jimp.read( `examples/screenshots/${ file }.jpg` ) ).quality( jpgQuality );
  360. } catch {
  361. await screenshot.writeAsync( `test/e2e/output-screenshots/${ platform }-${ file }-actual.jpg` );
  362. throw new Error( `Screenshot does not exist: ${ file }` );
  363. }
  364. const actual = screenshot.bitmap;
  365. const diff = screenshot.clone();
  366. let numDifferentPixels;
  367. try {
  368. numDifferentPixels = pixelmatch( expected.bitmap.data, actual.data, diff.bitmap.data, actual.width, actual.height, {
  369. threshold: pixelThreshold,
  370. alpha: 0.2
  371. } );
  372. } catch {
  373. await screenshot.writeAsync( `test/e2e/output-screenshots/${ platform }-${ file }-actual.jpg` );
  374. await expected.writeAsync( `test/e2e/output-screenshots/${ platform }-${ file }-expected.jpg` );
  375. throw new Error( `Image sizes does not match in file: ${ file }` );
  376. }
  377. /* Print results */
  378. const differentPixels = numDifferentPixels / ( actual.width * actual.height ) * 100;
  379. if ( differentPixels < maxDifferentPixels ) {
  380. console.green( `Diff ${ differentPixels.toFixed( 1 ) }% in file: ${ file }` );
  381. } else {
  382. await screenshot.writeAsync( `test/e2e/output-screenshots/${ platform }-${ file }-actual.jpg` );
  383. await expected.writeAsync( `test/e2e/output-screenshots/${ platform }-${ file }-expected.jpg` );
  384. await diff.writeAsync( `test/e2e/output-screenshots/${ platform }-${ file }-diff.jpg` );
  385. throw new Error( `Diff wrong in ${ differentPixels.toFixed( 1 ) }% of pixels in file: ${ file }` );
  386. }
  387. }
  388. } catch ( e ) {
  389. if ( attemptID === numAttempts - 1 ) {
  390. console.red( e );
  391. failedScreenshots.push( file );
  392. } else {
  393. console.yellow( `${ e }, another attempt...` );
  394. this.add( file, attemptID + 1 );
  395. }
  396. }
  397. page.file = undefined; // release lock
  398. }
  399. function close( exitCode = 1 ) {
  400. console.log( 'Closing...' );
  401. if ( browser !== undefined ) browser.close();
  402. server.close();
  403. process.exit( exitCode );
  404. }
粤ICP备19079148号