puppeteer.js 8.9 KB

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