puppeteer.js 8.9 KB

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