puppeteer.js 9.2 KB

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