puppeteer.js 9.1 KB

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