puppeteer.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. import puppeteer from 'puppeteer';
  2. import express from 'express';
  3. import path from 'path';
  4. import pixelmatch from 'pixelmatch';
  5. import { Jimp } from 'jimp';
  6. import * as fs from 'fs/promises';
  7. const exceptionList = [
  8. // Take too long
  9. 'webgpu_parallax_uv', // 11 min
  10. 'webgpu_cubemap_adjustments', // 9 min
  11. 'webgl_loader_lwo', // 8 min
  12. 'webgpu_cubemap_mix', // 2 min
  13. 'webgl_loader_texture_ultrahdr', // 1 min
  14. 'webgl_marchingcubes', // 1 min
  15. 'webgl_materials_cubemap_dynamic', // 1 min
  16. 'webgl_materials_displacementmap', // 1 min
  17. 'webgl_materials_envmaps_hdr', // 1 min
  18. 'webgpu_water', // 1 min
  19. // Needs investigation
  20. 'physics_rapier_instancing',
  21. 'webgl_shadowmap',
  22. 'webgl_postprocessing_dof2',
  23. 'webgl_postprocessing_glitch',
  24. 'webgl_video_kinect',
  25. 'webgl_worker_offscreencanvas',
  26. 'webgpu_backdrop_water',
  27. 'webgpu_lightprobe_cubecamera',
  28. 'webgpu_portal',
  29. 'webgpu_postprocessing_ao',
  30. 'webgpu_postprocessing_dof',
  31. 'webgpu_postprocessing_ssgi',
  32. 'webgpu_postprocessing_sss',
  33. 'webgpu_postprocessing_traa',
  34. 'webgpu_reflection',
  35. 'webgpu_texturegrad',
  36. 'webgpu_tsl_vfx_flames',
  37. // Need more time to render
  38. 'css3d_mixed',
  39. 'webgl_loader_3dtiles',
  40. 'webgl_loader_texture_lottie',
  41. 'webgl_morphtargets_face',
  42. 'webgl_renderer_pathtracer',
  43. 'webgl_shadowmap_progressive',
  44. 'webgpu_materials_matcap',
  45. 'webgpu_morphtargets_face',
  46. 'webgpu_shadowmap_progressive',
  47. // Video hangs the CI?
  48. 'css3d_youtube',
  49. 'webgpu_materials_video',
  50. // Timeout
  51. 'webgl_test_memory2',
  52. // Webcam
  53. 'webgl_materials_video_webcam',
  54. 'webgl_morphtargets_webcam',
  55. // WebGL device lost
  56. 'webgpu_materialx_noise',
  57. 'webgpu_portal',
  58. 'webgpu_shadowmap',
  59. // WebGPU needed
  60. 'webgpu_compute_audio',
  61. 'webgpu_compute_birds',
  62. 'webgpu_compute_cloth',
  63. 'webgpu_compute_particles_fluid',
  64. 'webgpu_compute_reduce',
  65. 'webgpu_compute_sort_bitonic',
  66. 'webgpu_compute_texture',
  67. 'webgpu_compute_texture_3d',
  68. 'webgpu_compute_texture_pingpong',
  69. 'webgpu_compute_water',
  70. 'webgpu_hdr',
  71. 'webgpu_lights_tiled',
  72. 'webgpu_materials',
  73. 'webgpu_multiple_canvas',
  74. 'webgpu_particles',
  75. 'webgpu_struct_drawindirect',
  76. 'webgpu_tsl_editor',
  77. 'webgpu_tsl_interoperability',
  78. 'webgpu_tsl_vfx_linkedparticles',
  79. 'webgpu_tsl_wood'
  80. ];
  81. /* Configuration */
  82. const port = 1234;
  83. const pixelThreshold = 0.1; // threshold error in one pixel
  84. const maxDifferentPixels = 0.3; // at most 0.3% different pixels
  85. const idleTime = 2; // 2 seconds - for how long there should be no network requests
  86. const parseTime = 1; // 1 second per megabyte
  87. const networkTimeout = 5; // 5 minutes, set to 0 to disable
  88. const renderTimeout = 5; // 5 seconds, set to 0 to disable
  89. const numAttempts = 2; // perform 2 attempts before failing
  90. const numCIJobs = 5; // GitHub Actions run the script in 5 threads
  91. const width = 400;
  92. const height = 250;
  93. const viewScale = 2;
  94. const jpgQuality = 95;
  95. console.red = msg => console.log( `\x1b[31m${msg}\x1b[39m` );
  96. console.green = msg => console.log( `\x1b[32m${msg}\x1b[39m` );
  97. console.yellow = msg => console.log( `\x1b[33m${msg}\x1b[39m` );
  98. let browser;
  99. /* Launch server */
  100. const app = express();
  101. app.use( express.static( path.resolve() ) );
  102. const server = app.listen( port, main );
  103. process.on( 'SIGINT', () => close() );
  104. async function main() {
  105. /* Create output directory */
  106. try { await fs.rm( 'test/e2e/output-screenshots', { recursive: true, force: true } ); } catch {}
  107. try { await fs.mkdir( 'test/e2e/output-screenshots' ); } catch {}
  108. /* Find files */
  109. let isMakeScreenshot = false;
  110. let isWebGPU = false;
  111. let argvIndex = 2;
  112. if ( process.argv[ argvIndex ] === '--webgpu' ) {
  113. isWebGPU = true;
  114. argvIndex ++;
  115. }
  116. if ( process.argv[ argvIndex ] === '--make' ) {
  117. isMakeScreenshot = true;
  118. argvIndex ++;
  119. }
  120. const exactList = process.argv.slice( argvIndex )
  121. .map( f => f.replace( '.html', '' ) );
  122. const isExactList = exactList.length !== 0;
  123. let files = ( await fs.readdir( 'examples' ) )
  124. .filter( s => s.slice( - 5 ) === '.html' && s !== 'index.html' )
  125. .map( s => s.slice( 0, s.length - 5 ) )
  126. .filter( f => isExactList ? exactList.includes( f ) : ! exceptionList.includes( f ) );
  127. if ( isExactList ) {
  128. for ( const file of exactList ) {
  129. if ( ! files.includes( file ) ) {
  130. console.log( `Warning! Unrecognised example name: ${ file }` );
  131. }
  132. }
  133. }
  134. if ( isWebGPU ) files = files.filter( f => f.includes( 'webgpu_' ) );
  135. /* CI parallelism */
  136. if ( 'CI' in process.env ) {
  137. const CI = parseInt( process.env.CI );
  138. files = files.slice(
  139. Math.floor( CI * files.length / numCIJobs ),
  140. Math.floor( ( CI + 1 ) * files.length / numCIJobs )
  141. );
  142. }
  143. /* Launch browser */
  144. const flags = [
  145. '--hide-scrollbars',
  146. '--use-angle=swiftshader',
  147. '--enable-unsafe-swiftshader',
  148. '--no-sandbox'
  149. ];
  150. const viewport = { width: width * viewScale, height: height * viewScale };
  151. browser = await puppeteer.launch( {
  152. headless: process.env.VISIBLE ? false : 'new',
  153. args: flags,
  154. defaultViewport: viewport,
  155. handleSIGINT: false,
  156. protocolTimeout: 0,
  157. userDataDir: './.puppeteer_profile'
  158. } );
  159. /* Prepare injections */
  160. const buildInjection = ( code ) => code.replace( /Math\.random\(\) \* 0xffffffff/g, 'Math._random() * 0xffffffff' );
  161. const cleanPage = await fs.readFile( 'test/e2e/clean-page.js', 'utf8' );
  162. const injection = await fs.readFile( 'test/e2e/deterministic-injection.js', 'utf8' );
  163. const builds = {
  164. 'three.core.js': buildInjection( await fs.readFile( 'build/three.core.js', 'utf8' ) ),
  165. 'three.module.js': buildInjection( await fs.readFile( 'build/three.module.js', 'utf8' ) ),
  166. 'three.webgpu.js': buildInjection( await fs.readFile( 'build/three.webgpu.js', 'utf8' ) )
  167. };
  168. /* Prepare page */
  169. const errorMessagesCache = [];
  170. const page = await browser.newPage();
  171. await preparePage( page, injection, builds, errorMessagesCache );
  172. /* Loop for each file */
  173. const failedScreenshots = [];
  174. for ( const file of files ) {
  175. await makeAttempt( page, failedScreenshots, cleanPage, isMakeScreenshot, file );
  176. }
  177. /* Finish */
  178. failedScreenshots.sort();
  179. const list = failedScreenshots.join( ' ' );
  180. if ( isMakeScreenshot && failedScreenshots.length ) {
  181. console.red( 'List of failed screenshots: ' + list );
  182. console.red( `If you are sure that everything is correct, try to run "npm run make-screenshot ${ list }". If this does not help, add remaining screenshots to the exception list.` );
  183. console.red( `${ failedScreenshots.length } from ${ files.length } screenshots have not generated successfully.` );
  184. } else if ( isMakeScreenshot && ! failedScreenshots.length ) {
  185. console.green( `${ files.length } screenshots successfully generated.` );
  186. } else if ( failedScreenshots.length ) {
  187. console.red( 'List of failed screenshots: ' + list );
  188. console.red( `If you are sure that everything is correct, try to run "npm run make-screenshot ${ list }". If this does not help, add remaining screenshots to the exception list.` );
  189. console.red( `TEST FAILED! ${ failedScreenshots.length } from ${ files.length } screenshots have not rendered correctly.` );
  190. } else {
  191. console.green( `TEST PASSED! ${ files.length } screenshots rendered correctly.` );
  192. }
  193. setTimeout( close, 300, failedScreenshots.length );
  194. }
  195. async function preparePage( page, injection, builds, errorMessages ) {
  196. await page.evaluateOnNewDocument( injection );
  197. await page.setRequestInterception( true );
  198. page.on( 'console', async msg => {
  199. const type = msg.type();
  200. const file = page.file;
  201. if ( file === undefined ) {
  202. return;
  203. }
  204. const args = await Promise.all( msg.args().map( async arg => {
  205. try {
  206. return await arg.executionContext().evaluate( arg => arg instanceof Error ? arg.message : arg, arg );
  207. } catch ( e ) { // Execution context might have been already destroyed
  208. return arg;
  209. }
  210. } ) );
  211. let text = args.join( ' ' ); // https://github.com/puppeteer/puppeteer/issues/3397#issuecomment-434970058
  212. text = text.trim();
  213. if ( text === '' ) return;
  214. text = file + ': ' + text.replace( /\[\.WebGL-(.+?)\] /g, '' );
  215. if ( text === `${ file }: JSHandle@error` ) {
  216. text = `${ file }: Unknown error`;
  217. }
  218. if ( errorMessages.includes( text ) ) {
  219. return;
  220. }
  221. errorMessages.push( text );
  222. if ( type === 'warning' ) {
  223. console.yellow( text );
  224. } else if ( type === 'error' ) {
  225. page.error = text;
  226. } else {
  227. console.log( `[Browser] ${text}` );
  228. }
  229. } );
  230. page.on( 'response', async ( response ) => {
  231. try {
  232. if ( response.status === 200 ) {
  233. await response.buffer().then( buffer => page.pageSize += buffer.length );
  234. }
  235. } catch {}
  236. } );
  237. page.on( 'request', async ( request ) => {
  238. const url = request.url();
  239. for ( const build in builds ) {
  240. if ( url === `http://localhost:${ port }/build/${ build }` ) {
  241. await request.respond( {
  242. status: 200,
  243. contentType: 'application/javascript; charset=utf-8',
  244. body: builds[ build ]
  245. } );
  246. return;
  247. }
  248. }
  249. await request.continue();
  250. } );
  251. }
  252. async function makeAttempt( page, failedScreenshots, cleanPage, isMakeScreenshot, file, attemptID = 0 ) {
  253. try {
  254. page.file = file;
  255. page.pageSize = 0;
  256. page.error = undefined;
  257. /* Load target page */
  258. try {
  259. await page.goto( `http://localhost:${ port }/examples/${ file }.html`, {
  260. waitUntil: 'networkidle0',
  261. timeout: networkTimeout * 60000
  262. } );
  263. } catch ( e ) {
  264. throw new Error( `Error happened while loading file ${ file }: ${ e }` );
  265. }
  266. try {
  267. /* Render page */
  268. await page.evaluate( cleanPage );
  269. await page.waitForNetworkIdle( {
  270. timeout: networkTimeout * 60000,
  271. idleTime: idleTime * 1000
  272. } );
  273. await page.evaluate( async ( renderTimeout, parseTime ) => {
  274. await new Promise( resolve => setTimeout( resolve, parseTime ) );
  275. /* Resolve render promise */
  276. window._renderStarted = true;
  277. await new Promise( function ( resolve, reject ) {
  278. const renderStart = performance._now();
  279. const waitingLoop = setInterval( function () {
  280. const renderTimeoutExceeded = ( renderTimeout > 0 ) && ( performance._now() - renderStart > 1000 * renderTimeout );
  281. if ( renderTimeoutExceeded ) {
  282. clearInterval( waitingLoop );
  283. reject( 'Render timeout exceeded' );
  284. } else if ( window._renderFinished ) {
  285. clearInterval( waitingLoop );
  286. resolve();
  287. }
  288. }, 100 );
  289. } );
  290. }, renderTimeout, page.pageSize / 1024 / 1024 * parseTime * 1000 );
  291. } catch ( e ) {
  292. if ( e.includes && e.includes( 'Render timeout exceeded' ) === false ) {
  293. throw new Error( `Error happened while rendering file ${ file }: ${ e }` );
  294. } /* else { // This can mean that the example doesn't use requestAnimationFrame loop
  295. console.yellow( `Render timeout exceeded in file ${ file }` );
  296. } */ // TODO: fix this
  297. }
  298. const screenshot = ( await Jimp.read( await page.screenshot(), { quality: jpgQuality } ) ).scale( 1 / viewScale );
  299. if ( page.error !== undefined ) throw new Error( page.error );
  300. if ( isMakeScreenshot ) {
  301. /* Make screenshots */
  302. await screenshot.write( `examples/screenshots/${ file }.jpg` );
  303. console.green( `Screenshot generated for file ${ file }` );
  304. } else {
  305. /* Diff screenshots */
  306. let expected;
  307. try {
  308. expected = ( await Jimp.read( `examples/screenshots/${ file }.jpg`, { quality: jpgQuality } ) );
  309. } catch {
  310. await screenshot.write( `test/e2e/output-screenshots/${ file }-actual.jpg` );
  311. throw new Error( `Screenshot does not exist: ${ file }` );
  312. }
  313. const actual = screenshot.bitmap;
  314. const diff = screenshot.clone();
  315. let numDifferentPixels;
  316. try {
  317. numDifferentPixels = pixelmatch( expected.bitmap.data, actual.data, diff.bitmap.data, actual.width, actual.height, {
  318. threshold: pixelThreshold,
  319. alpha: 0.2
  320. } );
  321. } catch {
  322. await screenshot.write( `test/e2e/output-screenshots/${ file }-actual.jpg` );
  323. await expected.write( `test/e2e/output-screenshots/${ file }-expected.jpg` );
  324. throw new Error( `Image sizes does not match in file: ${ file }` );
  325. }
  326. /* Print results */
  327. const differentPixels = numDifferentPixels / ( actual.width * actual.height ) * 100;
  328. if ( differentPixels < maxDifferentPixels ) {
  329. console.green( `Diff ${ differentPixels.toFixed( 1 ) }% in file: ${ file }` );
  330. } else {
  331. await screenshot.write( `test/e2e/output-screenshots/${ file }-actual.jpg` );
  332. await expected.write( `test/e2e/output-screenshots/${ file }-expected.jpg` );
  333. await diff.write( `test/e2e/output-screenshots/${ file }-diff.jpg` );
  334. throw new Error( `Diff wrong in ${ differentPixels.toFixed( 1 ) }% of pixels in file: ${ file }` );
  335. }
  336. }
  337. } catch ( e ) {
  338. if ( attemptID === numAttempts - 1 ) {
  339. console.red( e );
  340. failedScreenshots.push( file );
  341. } else {
  342. console.yellow( `${ e }, another attempt...` );
  343. await makeAttempt( page, failedScreenshots, cleanPage, isMakeScreenshot, file, attemptID + 1 );
  344. }
  345. } finally {
  346. page.file = undefined; // release lock
  347. }
  348. }
  349. function close( exitCode = 1 ) {
  350. console.log( 'Closing...' );
  351. browser.close();
  352. server.close();
  353. process.exit( exitCode );
  354. }
粤ICP备19079148号