puppeteer.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. import chalk from 'chalk';
  2. import puppeteer, { BrowserFetcher } from 'puppeteer-core';
  3. import express from 'express';
  4. import path from 'path';
  5. import pixelmatch from 'pixelmatch';
  6. import jimp from 'jimp';
  7. import * as fs from 'fs/promises';
  8. import fetch from 'node-fetch';
  9. /* CONFIG VARIABLES START */
  10. const idleTime = 9; // 9 seconds - for how long there should be no network requests
  11. const parseTime = 6; // 6 seconds per megabyte
  12. const exceptionList = [
  13. // video tag not deterministic enough
  14. 'css3d_youtube',
  15. 'webgl_video_kinect',
  16. 'webgl_video_panorama_equirectangular',
  17. 'webaudio_visualizer', // audio can't be analyzed without proper audio hook
  18. 'webgl_effects_ascii', // blink renders text differently in every platform
  19. 'webxr_ar_lighting', // webxr
  20. 'webgl_worker_offscreencanvas', // in a worker, not robust
  21. // TODO: most of these can be fixed just by increasing idleTime and parseTime
  22. 'webgl_lensflares',
  23. 'webgl_lines_sphere',
  24. 'webgl_loader_imagebitmap',
  25. 'webgl_loader_texture_lottie',
  26. 'webgl_loader_texture_pvrtc',
  27. 'webgl_morphtargets_face',
  28. 'webgl_nodes_materials_standard',
  29. 'webgl_postprocessing_crossfade',
  30. 'webgl_raymarching_reflect',
  31. 'webgl_renderer_pathtracer',
  32. 'webgl_shadowmap_progressive',
  33. 'webgl_test_memory2',
  34. 'webgl_tiled_forward'
  35. ];
  36. /* CONFIG VARIABLES END */
  37. const PLATFORMS = {
  38. linux: 'linux',
  39. mac: 'mac',
  40. mac_arm: 'mac_am64',
  41. win32: 'win',
  42. win64: 'win64'
  43. };
  44. const OMAHA_PROXY = 'https://omahaproxy.appspot.com/all.json';
  45. const chromiumChannel = 'stable'; // stable -> beta -> dev -> canary (Mac and Windows) -> canary_asan (Windows)
  46. const port = 1234;
  47. const pixelThreshold = 0.1; // threshold error in one pixel
  48. const maxFailedPixels = 0.05; // at most 5% failed pixels
  49. const networkTimeout = 90; // 90 seconds, set to 0 to disable
  50. const renderTimeout = 4.5; // 4.5 seconds, set to 0 to disable
  51. const numAttempts = 2; // perform 2 attempts before failing
  52. const numCIJobs = 8; // GitHub Actions run the script in 8 threads
  53. const width = 400;
  54. const height = 250;
  55. const viewScale = 2;
  56. const jpgQuality = 95;
  57. console.red = msg => console.log( chalk.red( msg ) );
  58. console.yellow = msg => console.log( chalk.yellow( msg ) );
  59. console.green = msg => console.log( chalk.green( msg ) );
  60. let browser;
  61. /* Launch server */
  62. const app = express();
  63. app.use( express.static( path.resolve() ) );
  64. const server = app.listen( port, main );
  65. process.on( 'SIGINT', () => close() );
  66. async function main() {
  67. /* Find files */
  68. const isMakeScreenshot = process.argv[ 2 ] === '--make';
  69. const exactList = process.argv.slice( isMakeScreenshot ? 3 : 2 )
  70. .map( f => f.replace( '.html', '' ) );
  71. const isExactList = exactList.length !== 0;
  72. let files = ( await fs.readdir( 'examples' ) )
  73. .filter( s => s.slice( - 5 ) === '.html' && s !== 'index.html' )
  74. .map( s => s.slice( 0, s.length - 5 ) )
  75. .filter( f => isExactList ? exactList.includes( f ) : ! exceptionList.includes( f ) );
  76. if ( isExactList ) {
  77. for ( const file of exactList ) {
  78. if ( ! files.includes( file ) ) {
  79. console.log( `Warning! Unrecognised example name: ${ file }` );
  80. }
  81. }
  82. }
  83. /* CI parallelism */
  84. if ( 'CI' in process.env ) {
  85. const CI = parseInt( process.env.CI );
  86. files = files.slice(
  87. Math.floor( CI * files.length / numCIJobs ),
  88. Math.floor( ( CI + 1 ) * files.length / numCIJobs )
  89. );
  90. }
  91. /* Download browser */
  92. const { executablePath } = await downloadLatestChromium();
  93. /* Launch browser */
  94. const flags = [ '--hide-scrollbars', '--enable-unsafe-webgpu' ];
  95. flags.push( '--enable-features=Vulkan', '--use-gl=swiftshader', '--use-angle=swiftshader', '--use-vulkan=swiftshader', '--use-webgpu-adapter=swiftshader' );
  96. // 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' );
  97. const viewport = { width: width * viewScale, height: height * viewScale };
  98. browser = await puppeteer.launch( {
  99. executablePath,
  100. headless: ! process.env.VISIBLE,
  101. args: flags,
  102. defaultViewport: viewport,
  103. handleSIGINT: false
  104. } );
  105. // this line is intended to stop the script if the browser (in headful mode) is closed by user (while debugging)
  106. // browser.on( 'targetdestroyed', target => ( target.type() === 'other' ) ? close() : null );
  107. // for some reason it randomly stops the script after about ~30 screenshots processed
  108. /* Prepare injections */
  109. const cleanPage = await fs.readFile( 'test/e2e/clean-page.js', 'utf8' );
  110. const injection = await fs.readFile( 'test/e2e/deterministic-injection.js', 'utf8' );
  111. const build = ( await fs.readFile( 'build/three.module.js', 'utf8' ) ).replace( /Math\.random\(\) \* 0xffffffff/g, 'Math._random() * 0xffffffff' );
  112. /* Prepare page */
  113. const errorMessagesCache = [];
  114. const page = ( await browser.pages() )[ 0 ];
  115. await preparePage( page, injection, build, errorMessagesCache );
  116. /* Loop for each file */
  117. const failedScreenshots = [];
  118. for ( const file of files ) await makeAttempt( page, failedScreenshots, cleanPage, isMakeScreenshot, file );
  119. /* Finish */
  120. const list = failedScreenshots.join( ' ' );
  121. if ( isMakeScreenshot && failedScreenshots.length ) {
  122. console.red( 'List of failed screenshots: ' + list );
  123. 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.` );
  124. console.red( `${ failedScreenshots.length } from ${ files.length } screenshots have not generated succesfully.` );
  125. } else if ( isMakeScreenshot && ! failedScreenshots.length ) {
  126. console.green( `${ files.length } screenshots succesfully generated.` );
  127. } else if ( failedScreenshots.length ) {
  128. console.red( 'List of failed screenshots: ' + list );
  129. 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.` );
  130. console.red( `TEST FAILED! ${ failedScreenshots.length } from ${ files.length } screenshots have not rendered correctly.` );
  131. } else {
  132. console.green( `TEST PASSED! ${ files.length } screenshots rendered correctly.` );
  133. }
  134. setTimeout( close, 300, failedScreenshots.length );
  135. }
  136. async function downloadLatestChromium() {
  137. const browserFetcher = new BrowserFetcher( { path: 'test/e2e/chromium' } );
  138. const os = PLATFORMS[ browserFetcher.platform() ];
  139. const revisions = await ( await fetch( OMAHA_PROXY ) ).json();
  140. const omahaRevisionInfo = revisions.find( revs => revs.os === os ).versions.find( version => version.channel === chromiumChannel );
  141. let revision = omahaRevisionInfo.branch_base_position;
  142. while ( ! ( await browserFetcher.canDownload( revision ) ) ) {
  143. revision = String( revision - 1 );
  144. }
  145. let revisionInfo = browserFetcher.revisionInfo( revision );
  146. if ( revisionInfo.local === true ) {
  147. console.log( 'Latest Chromium has been already downloaded.' );
  148. } else {
  149. console.log( 'Downloading latest Chromium...' );
  150. revisionInfo = await browserFetcher.download( revision );
  151. console.log( 'Downloaded.' );
  152. }
  153. console.log( `Using Chromium ${ omahaRevisionInfo.current_version } (revision ${ revision }, ${ revisionInfo.url }), ${ chromiumChannel } channel on ${ os }` );
  154. return revisionInfo;
  155. }
  156. async function preparePage( page, injection, build, errorMessages ) {
  157. /* let page.file, page.pageSize, page.error */
  158. await page.evaluateOnNewDocument( injection );
  159. await page.setRequestInterception( true );
  160. page.on( 'console', async msg => {
  161. const type = msg.type();
  162. if ( type !== 'warning' && type !== 'error' ) {
  163. return;
  164. }
  165. const file = page.file;
  166. if ( file === undefined ) {
  167. return;
  168. }
  169. const args = await Promise.all( msg.args().map( async arg => {
  170. try {
  171. return await arg.executionContext().evaluate( arg => arg instanceof Error ? arg.message : arg, arg );
  172. } catch (e) { // Execution context might have been already destroyed
  173. return arg;
  174. }
  175. } ) );
  176. let text = args.join( ' ' ); // https://github.com/puppeteer/puppeteer/issues/3397#issuecomment-434970058
  177. text = text.trim();
  178. if ( text === '' ) return;
  179. text = file + ': ' + text.replace( /\[\.WebGL-(.+?)\] /g, '' );
  180. if ( errorMessages.includes( text ) ) {
  181. return;
  182. }
  183. if ( text.includes( 'Unable to access the camera/webcam' ) ) {
  184. return;
  185. }
  186. errorMessages.push( text );
  187. if ( type === 'warning' ) {
  188. console.yellow( text );
  189. } else {
  190. page.error = text;
  191. }
  192. } );
  193. page.on( 'response', async ( response ) => {
  194. try {
  195. if ( response.status === 200 ) {
  196. await response.buffer().then( buffer => page.pageSize += buffer.length );
  197. }
  198. } catch {}
  199. } );
  200. page.on( 'request', async ( request ) => {
  201. if ( request.url() === `http://localhost:${ port }/build/three.module.js` ) {
  202. await request.respond( {
  203. status: 200,
  204. contentType: 'application/javascript; charset=utf-8',
  205. body: build
  206. } );
  207. } else {
  208. await request.continue();
  209. }
  210. } );
  211. }
  212. async function makeAttempt( page, failedScreenshots, cleanPage, isMakeScreenshot, file, attemptID = 0 ) {
  213. try {
  214. page.file = file;
  215. page.pageSize = 0;
  216. page.error = undefined;
  217. /* Load target page */
  218. try {
  219. await page.goto( `http://localhost:${ port }/examples/${ file }.html`, {
  220. waitUntil: 'networkidle0',
  221. timeout: networkTimeout * 1000
  222. } );
  223. } catch ( e ) {
  224. throw new Error( `Error happened while loading file ${ file }: ${ e }` );
  225. }
  226. try {
  227. /* Render page */
  228. await page.evaluate( cleanPage );
  229. await page.waitForNetworkIdle( {
  230. timeout: networkTimeout * 1000,
  231. idleTime: idleTime * 1000
  232. } );
  233. await page.evaluate( async ( renderTimeout, parseTime ) => {
  234. await new Promise( resolve => setTimeout( resolve, parseTime ) );
  235. /* Resolve render promise */
  236. window._renderStarted = true;
  237. await new Promise( function ( resolve, reject ) {
  238. const renderStart = performance._now();
  239. const waitingLoop = setInterval( function () {
  240. const renderTimeoutExceeded = ( renderTimeout > 0 ) && ( performance._now() - renderStart > 1000 * renderTimeout );
  241. if ( renderTimeoutExceeded ) {
  242. clearInterval( waitingLoop );
  243. reject( 'Render timeout exceeded' );
  244. } else if ( window._renderFinished ) {
  245. clearInterval( waitingLoop );
  246. resolve();
  247. }
  248. }, 10 );
  249. } );
  250. }, renderTimeout, page.pageSize / 1024 / 1024 * parseTime * 1000 );
  251. } catch ( e ) {
  252. if ( ! e.message.includes( 'Render timeout exceeded' ) ) {
  253. throw new Error( `Error happened while rendering file ${ file }: ${ e }` );
  254. } /* else { // This can mean that the example doesn't use requestAnimationFrame loop
  255. console.yellow( `Render timeout exceeded in file ${ file }` );
  256. } */
  257. }
  258. const screenshot = ( await jimp.read( await page.screenshot() ) ).scale( 1 / viewScale ).quality( jpgQuality );
  259. if ( page.error !== undefined ) throw new Error( page.error );
  260. if ( isMakeScreenshot ) {
  261. /* Make screenshots */
  262. await screenshot.writeAsync( `examples/screenshots/${ file }.jpg` );
  263. console.green( `Screenshot generated for file ${ file }` );
  264. } else {
  265. /* Diff screenshots */
  266. let expected;
  267. try {
  268. expected = await jimp.read( `examples/screenshots/${ file }.jpg` );
  269. } catch {
  270. throw new Error( `Screenshot does not exist: ${ file }` );
  271. }
  272. const actual = screenshot.bitmap;
  273. const diff = screenshot.clone();
  274. let numFailedPixels;
  275. try {
  276. numFailedPixels = pixelmatch( expected.bitmap.data, actual.data, diff.bitmap.data, actual.width, actual.height, {
  277. threshold: pixelThreshold,
  278. alpha: 0.2,
  279. diffMask: process.env.FORCE_COLOR === '0',
  280. diffColor: process.env.FORCE_COLOR === '0' ? [ 255, 255, 255 ] : [ 255, 0, 0 ]
  281. } );
  282. } catch {
  283. throw new Error( `Image sizes does not match in file: ${ file }` );
  284. }
  285. numFailedPixels /= actual.width * actual.height;
  286. /* Print results */
  287. const percFailedPixels = 100 * numFailedPixels;
  288. if ( numFailedPixels < maxFailedPixels ) {
  289. console.green( `Diff ${ percFailedPixels.toFixed( 1 ) }% in file: ${ file }` );
  290. } else {
  291. throw new Error( `Diff wrong in ${ percFailedPixels.toFixed( 1 ) }% of pixels in file: ${ file }` );
  292. }
  293. }
  294. } catch ( e ) {
  295. if ( attemptID === numAttempts - 1 ) {
  296. console.red( e );
  297. failedScreenshots.push( file );
  298. } else {
  299. console.yellow( `${ e }, another attempt...` );
  300. await makeAttempt( page, failedScreenshots, cleanPage, isMakeScreenshot, file, attemptID + 1 );
  301. }
  302. }
  303. }
  304. function close( exitCode = 1 ) {
  305. console.log( 'Closing...' );
  306. if ( browser !== undefined ) browser.close();
  307. server.close();
  308. process.exit( exitCode );
  309. }