puppeteer.js 7.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/**
 * @author munrocket / https://github.com/munrocket
 */

const puppeteer = require( 'puppeteer' );
const handler = require( 'serve-handler' );
const http = require( 'http' );
const pixelmatch = require( 'pixelmatch' );
const printImage = require( 'image-output' );
const png = require( 'pngjs' ).PNG;
const fs = require( 'fs' );

const port = 1234;
const pixelThreshold = 0.2;
const maxFailedPixels = 0.05;
const networkTimeout = 600;
17
const networkTax = 2000;                   // additional timeout for resources size
18 19 20 21 22 23 24 25
const pageSizeMinTax = 1.0;                // in mb, when networkTax = 0
const pageSizeMaxTax = 5.0;                // in mb, when networkTax = networkTax
const renderTimeout = 1200;
const maxAttemptId = 3;                    // progresseve attempts

const exceptionList = [

	'index',
26
	'webgl_loader_texture_pvrtc',            // not supported in CI, useless
27 28 29 30 31 32
	'webgl_materials_envmaps_parallax',
	'webgl_test_memory2',                    // gives fatal error in puppeteer
	'webgl_worker_offscreencanvas',          // in a worker, not robust

].concat( ( process.platform === "win32" ) ? [

33
	'webgl_effects_ascii'                    // windows fonts not supported
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329

] : [] );

console.green = ( msg ) => console.log( `\x1b[32m${ msg }\x1b[37m` );
console.red = ( msg ) => console.log( `\x1b[31m${ msg }\x1b[37m` );
console.null = ( msg ) => {};


/* Launch server */

const server = http.createServer( ( request, response ) => {

	return handler( request, response );

} );
server.listen( port, async () => {

	try {

		await pup;

	} catch ( e ) {

		console.error( e );

	} finally {

		server.close();

	}

} );
server.on( 'SIGINT', () => process.exit( 1 ) );


/* Launch puppeteer with WebGL support in Linux */

const pup = puppeteer.launch( {
	headless: !process.env.VISIBLE,
	args: [
		'--use-gl=egl',
		'--no-sandbox',
		'--enable-surface-synchronization'
	]
} ).then( async browser => {


	/* Prepare page */

	const page = ( await browser.pages() )[ 0 ];
	await page.setViewport( { width: 800, height: 600 } );

	const injection = fs.readFileSync( 'test/diff/deterministic-injection.js', 'utf8' );
	await page.evaluateOnNewDocument( injection );

	page.on( 'console', msg => ( msg.text().slice( 0, 8 ) === 'Warning.' ) ? console.null( msg.text() ) : {} );
	page.on( 'response', async ( response ) => {

		try {

			await response.buffer().then( buffer => pageSize += buffer.length );

		} catch ( e ) {

			console.null( `Warning. Wrong request. \n${ e }` );

		}

	} );


	/* Find files */

	const exactList = process.argv.slice(2).map( f => f.replace( '.html', '' ) );

	const files = fs.readdirSync( './examples' )
		.filter( s => s.slice( - 5 ) === '.html' )
		.map( s => s.slice( 0, s.length - 5 ) )
		.filter( f => ( process.argv.length > 2 ) ? exactList.includes( f ) : !exceptionList.includes( f ) );


	/* Loop for each file, with CI parallelism */

	let pageSize, file;
	let failedScreenshots = 0;
	const isParallel = 'CI' in process.env;
	const beginId = isParallel ? Math.floor( parseInt( process.env.CI.slice( 0, 1 ) ) * files.length / 4 ) : 0;
	const endId = isParallel ? Math.floor( ( parseInt( process.env.CI.slice( - 1 ) ) + 1 ) * files.length / 4 ) : files.length;

	for ( let id = beginId; id < endId; ++ id ) {


		/* At least 3 attempts before fail */

		let attemptId = process.env.MAKE ? 1 : 0;

		while ( attemptId < maxAttemptId ) {


			/* Load target page */

			file = files[ id ];
			pageSize = 0;
			global.gc();
			global.gc();

			try {

				await page.goto( `http://localhost:${ port }/examples/${ file }.html`, {
					waitUntil: 'networkidle2',
					timeout: networkTimeout * ( 1 + attemptId )
				} );

			} catch {

				console.null( 'Warning. Network timeout exceeded...' );

			}


			try {

				await page.evaluate( async ( pageSize, pageSizeMinTax, pageSizeMaxTax, networkTax, renderTimeout, attemptId ) => {


					/* Prepare page */

					let button = document.getElementById( 'startButton' );
					if ( button ) {

						button.click();

					}

					let style = document.createElement( 'style' );
					style.type = 'text/css';
					style.innerHTML = `body { font size: 0 !important; }
							#info, button, input, body > div.dg.ac, body > div.lbl { display: none !important; }`;
					document.getElementsByTagName( 'head' )[ 0 ].appendChild( style );

					let canvas = document.getElementsByTagName( 'canvas' );
					for ( let i = 0; i < canvas.length; ++ i ) {

						if ( canvas[i].height === 48 ) {

							canvas[i].style.display = 'none';

						}

					}

					let resourcesSize = Math.min( 1, ( pageSize / 1024 / 1024 - pageSizeMinTax ) / pageSizeMaxTax );
					await new Promise( resolve => setTimeout( resolve, networkTax * resourcesSize * ( 1 + attemptId ) ) );


					/* Resolve render promise */

					window.chromeRenderStarted = true;
					await new Promise( function( resolve ) {

						let renderStart = performance.wow();
						let waitingLoop = setInterval( function() {

							let renderEcceded = ( performance.wow() - renderStart > renderTimeout * window.chromeMaxFrameId  * ( 1 + attemptId ) );
							if ( window.chromeRenderFinished || renderEcceded ) {

								if ( renderEcceded ) {

									console.log( 'Warning. Render timeout exceeded...' );

								}
								clearInterval( waitingLoop );
								resolve();

							}

						}, 0 );

					} );

				}, pageSize, pageSizeMinTax, pageSizeMaxTax, networkTax, renderTimeout, attemptId );

			} catch ( e ) {

				if ( ++ attemptId === maxAttemptId ) {

					console.red( `WTF? 'Network timeout' is small for your machine. file: ${ file } \n${ e }` );
					++ failedScreenshots;
					continue;

				} else {

					console.log( 'Another attempt..' );
					await new Promise( resolve => setTimeout( resolve, networkTimeout * ( 1 + attemptId ) ) );

				}

			}


			/* Make or diff? */

			if ( process.env.MAKE ) {


				/* Make screenshots */

				attemptId = maxAttemptId;
				await page.screenshot( { path: `./examples/screenshots/${ file }.png` } );
				console.green( `file: ${ file } generated` );


			} else if ( fs.existsSync( `./examples/screenshots/${ file }.png` ) ) {


				/* Diff screenshots */

				let actual = png.sync.read( await page.screenshot() );
				let expected = png.sync.read( fs.readFileSync( `./examples/screenshots/${ file }.png` ) );
				let diff = new png( { width: actual.width, height: actual.height } );

				let numFailedPixels;
				try {

					numFailedPixels = pixelmatch( expected.data, actual.data, diff.data, actual.width, actual.height, {
						threshold: pixelThreshold,
						alpha: 0.2,
						diffMask: process.env.FORCE_COLOR === '0',
						diffColor: process.env.FORCE_COLOR === '0' ? [255, 255, 255] : [255, 0, 0]
					} );

				} catch {

					attemptId = maxAttemptId;
					console.red( `ERROR! Image sizes does not match in file: ${ file }` );
					++ failedScreenshots;
					continue;

				}
				numFailedPixels /= actual.width * actual.height;


				/* Print results */

				if ( numFailedPixels < maxFailedPixels ) {

					attemptId = maxAttemptId;
					console.green( `diff: ${ numFailedPixels.toFixed( 3 ) }, file: ${ file }` );

				} else {

					if ( ++ attemptId === maxAttemptId ) {

						printImage(diff, console);
						console.red( `ERROR! Diff wrong in ${ numFailedPixels.toFixed( 3 ) } of pixels in file: ${ file }` );
						++ failedScreenshots;
						continue;

					} else {

						console.log( 'Another attempt...' );

					}

				}

			} else {

				attemptId = maxAttemptId;
				console.red( `ERROR! Screenshot not exists: ${ file }` );
				++ failedScreenshots;
				continue;

			}

		}

	}


	/* Finish */

	if ( failedScreenshots ) {

		console.red( `TEST FAILED! ${ failedScreenshots } from ${ endId - beginId } screenshots not pass.` );
		process.exit( 1 );

	} else if ( !process.env.MAKE ) {

		console.green( `TEST PASSED! ${ endId - beginId } screenshots correctly rendered.` );

	}

	await browser.close();

} );