puppeteer.js 9.2 KB

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