puppeteer.js 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. try {
  2. require( 'puppeteer' );
  3. } catch {
  4. console.log( 'Error: Can\'t find Puppeteer. Run `npm install --prefix test`.' );
  5. process.exit( 0 );
  6. }
  7. const puppeteer = require( 'puppeteer' );
  8. const handler = require( 'serve-handler' );
  9. const http = require( 'http' );
  10. const pixelmatch = require( 'pixelmatch' );
  11. const jimp = require( 'jimp' );
  12. const fs = require( 'fs' );
  13. const port = 1234;
  14. const pixelThreshold = 0.1; // threshold error in one pixel
  15. const maxFailedPixels = 0.05; // total failed pixels
  16. const networkTimeout = 600;
  17. const networkTax = 2000; // additional timeout for resources size
  18. const pageSizeMinTax = 1.0; // in mb, when networkTax = 0
  19. const pageSizeMaxTax = 5.0; // in mb, when networkTax = networkTax
  20. const renderTimeout = 1200;
  21. const maxAttemptId = 3; // progresseve attempts
  22. const progressFunc = n => 1 + n;
  23. const width = 400;
  24. const height = 250;
  25. const viewScale = 2;
  26. const jpgQuality = 95;
  27. const exceptionList = [
  28. 'index',
  29. 'css3d_youtube', // video tag not deterministic enough
  30. 'webaudio_visualizer', // audio can't be analyzed without proper audio hook
  31. 'webgl_loader_texture_lottie', // not sure why this fails
  32. 'webgl_loader_texture_pvrtc', // not supported in CI, useless
  33. 'webgl_materials_envmaps_parallax', // empty for some reason
  34. 'webgl_materials_standard_nodes', // puppeteer does not support import maps yet
  35. 'webgl_raymarching_reflect', // exception for Github Actions
  36. 'webgl_test_memory2', // gives fatal error in puppeteer
  37. 'webgl_tiled_forward', // exception for Github Actions
  38. 'webgl_video_kinect', // video tag not deterministic enough
  39. 'webgl_worker_offscreencanvas', // in a worker, not robust
  40. // webxr
  41. 'webxr_ar_lighting',
  42. // webgpu
  43. 'webgpu_compute',
  44. 'webgpu_instance_uniform',
  45. 'webgpu_lights_selective',
  46. 'webgpu_materials',
  47. 'webgpu_rtt',
  48. 'webgpu_sandbox'
  49. ].concat( ( process.platform === 'win32' ) ? [
  50. 'webgl_effects_ascii' // windows fonts not supported
  51. ] : [] );
  52. console.green = ( msg ) => console.log( `\x1b[32m${ msg }\x1b[37m` );
  53. console.red = ( msg ) => console.log( `\x1b[31m${ msg }\x1b[37m` );
  54. console.null = () => {};
  55. /* Launch server */
  56. const server = http.createServer( ( req, resp ) => handler( req, resp ) );
  57. server.listen( port, async () => await pup );
  58. server.on( 'SIGINT', () => process.exit( 1 ) );
  59. /* Launch browser */
  60. const pup = puppeteer.launch( {
  61. headless: ! process.env.VISIBLE,
  62. args: [
  63. '--use-gl=swiftshader',
  64. '--no-sandbox',
  65. '--enable-surface-synchronization'
  66. ]
  67. } ).then( async browser => {
  68. /* Prepare page */
  69. const page = ( await browser.pages() )[ 0 ];
  70. await page.setViewport( { width: width * viewScale, height: height * viewScale } );
  71. const cleanPage = fs.readFileSync( 'test/e2e/clean-page.js', 'utf8' );
  72. const injection = fs.readFileSync( 'test/e2e/deterministic-injection.js', 'utf8' );
  73. await page.evaluateOnNewDocument( injection );
  74. const threeJsBuild = fs.readFileSync( 'build/three.module.js', 'utf8' )
  75. .replace( /Math\.random\(\) \* 0xffffffff/g, 'Math._random() * 0xffffffff' );
  76. await page.setRequestInterception( true );
  77. page.on( 'console', msg => ( msg.text().slice( 0, 8 ) === 'Warning.' ) ? console.null( msg.text() ) : {} );
  78. page.on( 'request', async ( request ) => {
  79. if ( request.url() === 'http://localhost:1234/build/three.module.js' ) {
  80. await request.respond( {
  81. status: 200,
  82. contentType: 'application/javascript; charset=utf-8',
  83. body: threeJsBuild
  84. } );
  85. } else {
  86. await request.continue();
  87. }
  88. } );
  89. page.on( 'response', async ( response ) => {
  90. try {
  91. await response.buffer().then( buffer => pageSize += buffer.length );
  92. } catch ( e ) {
  93. console.null( `Warning. Wrong request. \n${ e }` );
  94. }
  95. } );
  96. /* Find files */
  97. const isMakeScreenshot = process.argv[ 2 ] == '--make';
  98. const isExactList = process.argv.length > ( 2 + isMakeScreenshot );
  99. const exactList = process.argv.slice( isMakeScreenshot ? 3 : 2 )
  100. .map( f => f.replace( '.html', '' ) );
  101. const files = fs.readdirSync( './examples' )
  102. .filter( s => s.slice( - 5 ) === '.html' )
  103. .map( s => s.slice( 0, s.length - 5 ) )
  104. .filter( f => isExactList ? exactList.includes( f ) : ! exceptionList.includes( f ) );
  105. /* Loop for each file, with CI parallelism */
  106. let pageSize, file, attemptProgress;
  107. const failedScreenshots = [];
  108. const isParallel = 'CI' in process.env;
  109. const beginId = isParallel ? Math.floor( parseInt( process.env.CI.slice( 0, 1 ) ) * files.length / 4 ) : 0;
  110. const endId = isParallel ? Math.floor( ( parseInt( process.env.CI.slice( - 1 ) ) + 1 ) * files.length / 4 ) : files.length;
  111. for ( let id = beginId; id < endId; ++ id ) {
  112. /* At least 3 attempts before fail */
  113. let attemptId = isMakeScreenshot ? 1.5 : 0;
  114. while ( attemptId < maxAttemptId ) {
  115. /* Load target page */
  116. file = files[ id ];
  117. attemptProgress = progressFunc( attemptId );
  118. pageSize = 0;
  119. try {
  120. await page.goto( `http://localhost:${ port }/examples/${ file }.html`, {
  121. waitUntil: 'networkidle2',
  122. timeout: networkTimeout * attemptProgress
  123. } );
  124. } catch {
  125. console.null( 'Warning. Network timeout exceeded...' );
  126. }
  127. try {
  128. /* Render page */
  129. await page.evaluate( cleanPage );
  130. await page.evaluate( async ( pageSize, pageSizeMinTax, pageSizeMaxTax, networkTax, renderTimeout, attemptProgress ) => {
  131. /* Resource timeout */
  132. const resourcesSize = Math.min( 1, ( pageSize / 1024 / 1024 - pageSizeMinTax ) / pageSizeMaxTax );
  133. await new Promise( resolve => setTimeout( resolve, networkTax * resourcesSize * attemptProgress ) );
  134. /* Resolve render promise */
  135. window._renderStarted = true;
  136. await new Promise( function ( resolve ) {
  137. performance._now = performance._now || performance.now;
  138. const renderStart = performance._now();
  139. const waitingLoop = setInterval( function () {
  140. const renderEcceded = ( performance._now() - renderStart > renderTimeout * attemptProgress );
  141. if ( window._renderFinished || renderEcceded ) {
  142. if ( renderEcceded ) {
  143. console.log( 'Warning. Render timeout exceeded...' );
  144. }
  145. clearInterval( waitingLoop );
  146. resolve();
  147. }
  148. }, 0 );
  149. } );
  150. }, pageSize, pageSizeMinTax, pageSizeMaxTax, networkTax, renderTimeout, attemptProgress );
  151. } catch ( e ) {
  152. if ( ++ attemptId === maxAttemptId ) {
  153. console.red( `Something completely wrong. 'Network timeout' is small for your machine. file: ${ file } \n${ e }` );
  154. failedScreenshots.push( file );
  155. continue;
  156. } else {
  157. console.log( 'Another attempt..' );
  158. await new Promise( resolve => setTimeout( resolve, networkTimeout * attemptProgress ) );
  159. }
  160. }
  161. if ( isMakeScreenshot ) {
  162. /* Make screenshots */
  163. attemptId = maxAttemptId;
  164. ( await jimp.read( await page.screenshot() ) )
  165. .scale( 1 / viewScale ).quality( jpgQuality )
  166. .write( `./examples/screenshots/${ file }.jpg` );
  167. console.green( `file: ${ file } generated` );
  168. } else if ( fs.existsSync( `./examples/screenshots/${ file }.jpg` ) ) {
  169. /* Diff screenshots */
  170. const actual = ( await jimp.read( await page.screenshot() ) ).scale( 1 / viewScale ).quality( jpgQuality ).bitmap;
  171. const expected = ( await jimp.read( fs.readFileSync( `./examples/screenshots/${ file }.jpg` ) ) ).bitmap;
  172. const diff = actual;
  173. let numFailedPixels;
  174. try {
  175. numFailedPixels = pixelmatch( expected.data, actual.data, diff.data, actual.width, actual.height, {
  176. threshold: pixelThreshold,
  177. alpha: 0.2,
  178. diffMask: process.env.FORCE_COLOR === '0',
  179. diffColor: process.env.FORCE_COLOR === '0' ? [ 255, 255, 255 ] : [ 255, 0, 0 ]
  180. } );
  181. } catch {
  182. attemptId = maxAttemptId;
  183. console.red( `Something completely wrong. Image sizes does not match in file: ${ file }` );
  184. failedScreenshots.push( file );
  185. continue;
  186. }
  187. numFailedPixels /= actual.width * actual.height;
  188. /* Print results */
  189. if ( numFailedPixels < maxFailedPixels ) {
  190. attemptId = maxAttemptId;
  191. console.green( `diff: ${ numFailedPixels.toFixed( 3 ) }, file: ${ file }` );
  192. } else {
  193. if ( ++ attemptId === maxAttemptId ) {
  194. console.red( `ERROR! Diff wrong in ${ numFailedPixels.toFixed( 3 ) } of pixels in file: ${ file }` );
  195. failedScreenshots.push( file );
  196. continue;
  197. } else {
  198. console.log( 'Another attempt...' );
  199. }
  200. }
  201. } else {
  202. attemptId = maxAttemptId;
  203. console.log( `Warning! Screenshot not exists: ${ file }` );
  204. continue;
  205. }
  206. }
  207. }
  208. /* Finish */
  209. if ( failedScreenshots.length ) {
  210. if ( failedScreenshots.length > 1 ) {
  211. console.red( 'List of failed screenshots: ' + failedScreenshots.join( ' ' ) );
  212. } else {
  213. console.red( `If you sure that all is right, try to run \`npm run make-screenshot ${ failedScreenshots[ 0 ] }\`` );
  214. }
  215. console.red( `TEST FAILED! ${ failedScreenshots.length } from ${ endId - beginId } screenshots not pass.` );
  216. } else if ( ! isMakeScreenshot ) {
  217. console.green( `TEST PASSED! ${ endId - beginId } screenshots correctly rendered.` );
  218. }
  219. setTimeout( () => {
  220. server.close();
  221. browser.close();
  222. process.exit( failedScreenshots.length );
  223. }, 300 );
  224. } );