All files / ext.wikilambda.app/store/stores testResults.js

99.1% Statements 332/335
90.16% Branches 55/61
100% Functions 16/16
99.1% Lines 332/335

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 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 330 331 332 333 334 335 336103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 314x 314x 314x 314x 314x 314x 314x 314x 62x 62x 62x 62x 1x 1x 61x 61x 62x 26x 14x 62x 314x 314x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 304x 304x 304x 304x 304x 304x 304x 304x 50x 50x 304x 304x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 307x 307x 307x 307x 307x 307x 56x 56x 56x 56x 92x 92x 92x 49x 92x 56x 56x 56x 56x 56x 56x 56x 56x 307x 307x 103x 103x 103x 103x 103x 103x 103x 103x 103x 275x 275x 275x 275x 275x 13x 13x 13x 13x 5x 5x 5x 4x 4x 4x 1x 4x 4x 4x 3x 3x 4x 5x 13x 275x 275x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 277x 277x 277x 277x 277x 338x 338x 338x 57x 57x 57x 57x 57x 338x 338x 57x 57x 338x 277x 277x 277x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 26x 52x 52x 2x 2x 1x 1x 1x 1x 2x 2x 50x 50x 26x 26x 15x 15x 15x 1x 1x 14x 14x 15x 7x 7x 14x 14x 15x 1x 1x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 12x 12x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 12x 12x 12x 12x 12x 13x 1x       1x 1x 1x 1x 1x 1x 13x 13x 13x 13x 13x 13x 13x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 28x 14x 14x 14x 14x 14x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 49x 49x 103x 103x 103x 103x 103x 103x 103x 103x 7x 7x 7x 7x 7x 103x 103x  
/*!
 * WikiLambda Vue editor: Pinia store for storing, retrieving, and running test runners.
 *
 * @copyright 2020– Abstract Wikipedia team; see AUTHORS.txt
 * @license MIT
 */
'use strict';
 
const Constants = require( '../../Constants.js' );
const { performTests } = require( '../../utils/apiUtils.js' );
const { isTruthyOrEqual } = require( '../../utils/typeUtils.js' );
const { extractZIDs, hybridToCanonical } = require( '../../utils/schemata.js' );
 
module.exports = {
	state: {
		zTesterResults: {},
		zTesterMetadata: {},
		testResultsPromises: {}
	},
 
	getters: {
		/**
		 * Retrieves the result of running a specific set of Function, Test
		 * and Implementation. These results are stored in the state with keys
		 * with the format "<function id>:<test id>:<implementation id>".
		 *
		 * @param {Object} state
		 * @return {Function}
		 */
		getZTesterResult: function ( state ) {
			/**
			 * @param {string} zFunctionId
			 * @param {string} zTesterId
			 * @param {string} zImplementationId
			 *
			 * @return {boolean}
			 */
			const findZTesterResults = ( zFunctionId, zTesterId, zImplementationId ) => {
				const key = `${ zFunctionId }:${ zTesterId }:${ zImplementationId }`;
 
				const testResultErrors = this.getErrors( Constants.ERROR_IDS.TEST_RESULTS );
				if ( testResultErrors.length > 0 ) {
					return false;
				}
 
				const result = state.zTesterResults[ key ];
				return result && (
					result === Constants.Z_BOOLEAN_TRUE ||
					( typeof result === 'object' && result[ Constants.Z_BOOLEAN_IDENTITY ] === Constants.Z_BOOLEAN_TRUE )
				);
			};
			return findZTesterResults;
		},
 
		/**
		 * Retrieve metadata (e.g. duration), for a specific test.
		 *
		 * Test are identified by a zFunctionId, zTesterId, and zImplementationId.
		 *
		 * @param {Object} state
		 * @return {Function}
		 */
		getZTesterMetadata: function ( state ) {
			/**
			 * @param {string} zFunctionId
			 * @param {string} zTesterId
			 * @param {string} zImplementationId
			 *
			 * @return {Object|undefined} metadata
			 */
			const findZTesterMetadata = ( zFunctionId, zTesterId, zImplementationId ) => {
				const key = `${ zFunctionId }:${ zTesterId }:${ zImplementationId }`;
				return state.zTesterMetadata[ key ];
			};
			return findZTesterMetadata;
		},
 
		/**
		 * Retrieve percentage of test that passed.
		 * This getter takes into consideration all the tests of a specific zId
		 *
		 * @param {Object} state
		 * @return {Function}
		 */
		getZTesterPercentage: function ( state ) {
			/**
			 * @param {string} zid
			 *
			 * @return {Object}
			 */
			const calculateZTesterPercentage = ( zid ) => {
				const results = Object.keys( state.zTesterResults )
					.filter( ( key ) => key.includes( zid ) && state.zTesterResults[ key ] !== undefined );
				const total = results.length;
				const passing = results.filter( ( key ) => {
					const result = state.zTesterResults[ key ];
					return result && (
						result === Constants.Z_BOOLEAN_TRUE ||
							( typeof result === 'object' && result[ Constants.Z_BOOLEAN_IDENTITY ] === Constants.Z_BOOLEAN_TRUE )
					);
				} ).length;
				const percentage = Math.round( ( passing / total ) * 100 ) || 0;
 
				return {
					total: total,
					passing: passing,
					percentage: percentage
				};
			};
			return calculateZTesterPercentage;
		},
 
		/**
		 * Returns the Zids of the passing and connected tests for the given functionZid
		 *
		 * @param {Object} state
		 * @return {Function}
		 */
		getPassingTestZids: function ( state ) {
			/**
			 * @param {string} functionZid
			 * @return {Array}
			 */
			const findPassingTestZids = ( functionZid ) => {
				const connected = this.getConnectedObjects( functionZid, Constants.Z_FUNCTION_TESTERS );
				const zids = [];
 
				for ( const key in state.zTesterResults ) {
					const parts = key.split( ':' );
					// Filter out tests for other functions
					if ( parts[ 0 ] === functionZid ) {
						const result = state.zTesterResults[ key ];
						const passing = result && (
							result === Constants.Z_BOOLEAN_TRUE ||
							( typeof result === 'object' && result[ Constants.Z_BOOLEAN_IDENTITY ] === Constants.Z_BOOLEAN_TRUE )
						);
						// If test passes, return zid
						if ( passing && connected.includes( parts[ 1 ] ) ) {
							zids.push( parts[ 1 ] );
						}
					}
				}
				return [ ...new Set( zids ) ];
			};
			return findPassingTestZids;
		},
 
		/**
		 * Filters the passing test ZIDs and returns an array of valid renderer tests.
		 * A valid renderer test is well-formed and has a call to the renderer function
		 * directly under the Test call key/Z20K1.
		 *
		 * @return {Function}
		 */
		getValidRendererTests: function () {
			/**
			 * @param {string} rendererZid
			 * @return {Array}
			 */
			const findValidRendererTests = ( rendererZid ) => {
				const passingTestZids = this.getPassingTestZids( rendererZid );
				return passingTestZids
					.map( ( zid ) => {
						const zobject = this.getStoredObject( zid );
						return {
							zid,
							zobject: zobject ? zobject[ Constants.Z_PERSISTENTOBJECT_VALUE ] : undefined
						};
					} )
					.filter( ( test ) => isTruthyOrEqual( test.zobject, [
						Constants.Z_TESTER_CALL,
						Constants.Z_FUNCTION_CALL_FUNCTION
					], rendererZid ) );
			};
			return findValidRendererTests;
		}
	},
 
	actions: {
		/**
		 * Triggers a test API call and updates the test results, handles the test pending state
		 * and also define the error state and message if test returns errors
		 *
		 * @param {Object} payload
		 * @param {string} payload.zFunctionId The ZID of the Function we're for which running these
		 * @param {string[]} payload.zTesters The ZIDs (or if unsaved the full ZObjects) of the Testers to run
		 * @param {string[]} payload.zImplementations The ZIDs (or if unsaved the full ZObjects) of the
		 *   Implementations to run
		 * @param {boolean} payload.nocache Whether to tell the Orchestrator to cache these results
		 * @param {boolean} payload.clearPreviousResults Whether to clear the previous results from the Pinia store
		 * @param {AbortSignal} payload.signal The AbortSignal to cancel the request
		 *
		 * @return {Promise}
		 */
		getTestResults: function ( payload ) {
			/**
			 * Loop through the given array of ZIDs and if a ZID is for the object currently being edited, or for a new
			 * object, replace it with a JSON representation of the full persistent object (if editing existing object)
			 * or inner object (if new object). This is required to be able to see proper test results while changing
			 * implementations and testers.
			 *
			 * @param {Array} items - List of implementations or testers
			 * @return {Array}
			 */
			function replaceCurrentObjectWithFullJSONObject( items ) {
				return ( items || [] ).map( ( item ) => {
					// if the item is the current object replace it
					if ( !this.getViewMode && item === this.getCurrentZObjectId ) {
						let zobject = this.getJsonObject( Constants.STORED_OBJECTS.MAIN );
						if ( item === Constants.NEW_ZID_PLACEHOLDER ) {
							// If this object is not yet persisted, pass only the inner object to the API, as otherwise
							// the API will complain about the placeholder ID Z0 not existing.
							zobject = zobject[ Constants.Z_PERSISTENTOBJECT_VALUE ];
						}
						return JSON.stringify( hybridToCanonical( JSON.parse( JSON.stringify( zobject ) ) ) );
					}
 
					return item;
				} ).filter( ( item ) => !!item );
			}
 
			// If function ZID is empty, exit
			if ( !payload.zFunctionId ) {
				return Promise.resolve();
			}
 
			// Clear previous results and make sure that the call is triggered
			if ( payload.clearPreviousResults ) {
				this.clearZTesterResults( payload.zFunctionId );
			}
 
			// If this API for this functionZid is already running, return promise
			if ( payload.zFunctionId in this.testResultsPromises ) {
				return this.testResultsPromises[ payload.zFunctionId ];
			}
 
			this.clearErrors( Constants.ERROR_IDS.TEST_RESULTS );
 
			// (T358089) Encode any '|' characters of ZObjects so that they can be recovered after the API.
			const implementations = replaceCurrentObjectWithFullJSONObject.call( this, payload.zImplementations )
				.map( ( a ) => a.replace( /\|/g, '🪈' ) );
			const testers = replaceCurrentObjectWithFullJSONObject.call( this, payload.zTesters )
				.map( ( a ) => a.replace( /\|/g, '🪈' ) );
 
			const testResultsPromise = performTests( {
				functionZid: payload.zFunctionId,
				nocache: payload.nocache,
				language: this.getUserLangCode,
				implementations,
				testers,
				signal: payload.signal
			} ).then( ( results ) => {
				const zids = [];
				results.forEach( ( testResult ) => {
					const result = hybridToCanonical( JSON.parse( testResult.validateStatus ) );
					const metadata = hybridToCanonical( JSON.parse( testResult.testMetadata ) );
					const key = `${ testResult.zFunctionId || Constants.NEW_ZID_PLACEHOLDER }:` +
					`${ testResult.zTesterId || Constants.NEW_ZID_PLACEHOLDER }:` +
					`${ testResult.zImplementationId || Constants.NEW_ZID_PLACEHOLDER }`;
 
					// Collect zids
					zids.push( testResult.zTesterId );
					zids.push( testResult.zImplementationId );
					zids.push( ...extractZIDs( result ) );
					zids.push( ...extractZIDs( metadata ) );
 
					// Store result
					this.setZTesterResult( { key, result, metadata } );
				} );
 
				// Make sure that all returned Zids are in library.js
				this.fetchZids( { zids: [ ...new Set( zids ) ] } );
				this.setTestResultsPromise( { functionZid: payload.zFunctionId } );
			} ).catch( ( error ) => {
				if ( error.code === 'abort' ) {
					this.clearZTesterResults( payload.zFunctionId );
					return;
				}
				this.setError( {
					errorId: Constants.ERROR_IDS.TEST_RESULTS,
					errorType: Constants.ERROR_TYPES.ERROR,
					errorMessage: error.messageOrFallback( 'wikilambda-unknown-test-error-message' )
				} );
				this.setTestResultsPromise( { functionZid: payload.zFunctionId } );
			} );
 
			this.setTestResultsPromise( {
				functionZid: payload.zFunctionId,
				promise: testResultsPromise
			} );
			return testResultsPromise;
		},
 
		/**
		 * Set or unset the unresolved promise to the testResults API call for a given functionZid.
		 *
		 * @param {Object} payload
		 * @param {string} payload.functionZid
		 * @param {Promise} payload.promise
		 */
		setTestResultsPromise: function ( payload ) {
			if ( 'promise' in payload ) {
				this.testResultsPromises[ payload.functionZid ] = payload.promise;
			} else {
				// Set as a resolved Promise if the tests for this function have been fetched
				this.testResultsPromises[ payload.functionZid ] = Promise.resolve();
			}
		},
 
		/**
		 * Set the result of a specific test
		 *
		 * @param {Object} result
		 * @param {string} result.key
		 * @param {boolean} result.result
		 * @param {Object} result.metadata
		 */
		setZTesterResult: function ( result ) {
			this.zTesterResults[ result.key ] = result.result;
			this.zTesterMetadata[ result.key ] = result.metadata;
		},
 
		/**
		 * Clear all the test results and metadata
		 *
		 * @param {string} functionZid
		 */
		clearZTesterResults: function ( functionZid ) {
			this.zTesterResults = {};
			this.zTesterMetadata = {};
			// Clear Promise
			delete this.testResultsPromises[ functionZid ];
		}
	}
};