puppeteer.js 13 KB

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