All files / ext.wikilambda.edit/store/modules zTesterResults.js

97.59% Statements 81/83
80.35% Branches 45/56
100% Functions 23/23
97.59% Lines 81/83

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                  16x 16x 16x 16x                       22x   44x 2x 2x     1x   2x     42x   44x       16x                                     32x 42x   42x 1x     41x 41x                                 24x 34x       34x                       8x 32x 93x   32x 32x 52x 52x       32x   32x                                         1x 1x   1x 5x   5x 4x 4x         4x 3x       1x   1x                         24x 12x     12x                         44x 44x                 6x 6x   6x                 19x 19x                                         12x         12x 5x       12x 1x     11x   11x         22x   11x         22x     11x           10x                         10x 10x 42x 42x 42x         42x 42x 42x 42x     42x       10x 4x   7x 7x 7x     11x       11x        
/*!
 * WikiLambda Vue editor: Module for storing, retrieving, and running test runners.
 *
 * @copyright 2020– Abstract Wikipedia team; see AUTHORS.txt
 * @license MIT
 */
 
/* eslint-disable no-implicit-globals */
 
const Constants = require( '../../Constants.js' ),
	apiUtils = require( '../../mixins/api.js' ).methods,
	hybridToCanonical = require( '../../mixins/schemata.js' ).methods.hybridToCanonical,
	extractZIDs = require( '../../mixins/schemata.js' ).methods.extractZIDs;
 
/**
 * 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 {Object} context
 * @param {Array} items - List of implementations or testers
 * @return {Array}
 */
function replaceCurrentObjectWithFullJSONObject( context, items ) {
	return ( items || [] ).map( function ( item ) {
		// if the item is the current object replace it
		if ( !context.getters.getViewMode && item === context.getters.getCurrentZObjectId ) {
			let zobject = context.getters.getZObjectAsJson;
			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( function ( item ) {
		return !!item;
	} );
}
 
module.exports = exports = {
	state: {
		zTesterResults: {},
		zTesterMetadata: {},
		testResultsPromises: {},
		errorState: false,
		errorMessage: ''
	},
	getters: {
		getZTesterResults: function ( state ) {
			/**
			 * Retrieve the result value zTester a specific set of Function, tester and implementation.
			 *
			 * @param {string} zFunctionId
			 * @param {string} zTesterId
			 * @param {string} zImplementationId
			 *
			 * @return {boolean}
			 */
			return function ( zFunctionId, zTesterId, zImplementationId ) {
				const key = zFunctionId + ':' + zTesterId + ':' + zImplementationId;
 
				if ( state.errorState ) {
					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 ) );
			};
		},
		getZTesterMetadata: function ( state ) {
			/**
			 * Retrieve metadata (e.g. duration), for a specific test.
			 *
			 * Test are identified by a zFunctionId, zTesterId, and zImplementationId.
			 *
			 * @param {string} zFunctionId
			 * @param {string} zTesterId
			 * @param {string} zImplementationId
			 *
			 * @return {Object} metadata
			 */
			return function ( zFunctionId, zTesterId, zImplementationId ) {
				const key = zFunctionId + ':' + zTesterId + ':' + zImplementationId;
 
				// TODO (T314267): Check for and handle state.errorState = true
 
				return state.zTesterMetadata[ key ];
			};
		},
		getZTesterPercentage: function ( state ) {
			/**
			 * Retrieve percentage of test that passed.
			 * This getter takes into consideration all the tests of a specific zId
			 *
			 * @param {string} zid
			 *
			 * @return {Object}
			 */
			return function ( zid ) {
				const results = Object.keys( state.zTesterResults ).filter( function ( key ) {
						return key.includes( zid ) && state.zTesterResults[ key ] !== undefined;
					} ),
					total = results.length,
					passing = results.filter( function ( 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,
					percentage = Math.round( ( passing / total ) * 100 ) || 0;
 
				return {
					total: total,
					passing: passing,
					percentage: percentage
				};
			};
		},
		/**
		 * Returns the Zids of the passing and connected tests for the given functionZid
		 *
		 * @param {Object} state
		 * @param {Object} getters
		 * @return {Function}
		 */
		getPassingTestZids: function ( state, getters ) {
			/**
			 * @param {string} functionZid
			 * @return {Array}
			 */
			function getPassingTestsForFunction( functionZid ) {
 
				const connected = getters.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 getPassingTestsForFunction;
		}
	},
	mutations: {
		/**
		 * Set or unset the unresolved promise to the testResults API call for a given functionZid.
		 *
		 * @param {Object} state
		 * @param {Object} payload
		 * @param {string} payload.functionZid
		 * @param {Promise} payload.promise
		 */
		setTestResultsPromise: function ( state, payload ) {
			if ( 'promise' in payload ) {
				state.testResultsPromises[ payload.functionZid ] = payload.promise;
			} else {
				// Set as a resolved Promise if the tests for this function have been fetched
				state.testResultsPromises[ payload.functionZid ] = Promise.resolve();
			}
		},
		/**
		 * Set the result of a specific test
		 *
		 * @param {Object} state
		 * @param {Object} result
		 * @param {string} result.key
		 * @param {boolean} result.result
		 * @param {Object} result.metadata
		 */
		setZTesterResult: function ( state, result ) {
			state.zTesterResults[ result.key ] = result.result;
			state.zTesterMetadata[ result.key ] = result.metadata;
		},
		/**
		 * Clear all the test results and metadata
		 *
		 * @param {Object} state
		 * @param {string} functionZid
		 */
		clearZTesterResults: function ( state, functionZid ) {
			state.zTesterResults = {};
			state.zTesterMetadata = {};
			// Clear Promise
			delete state.testResultsPromises[ functionZid ];
		},
		/**
		 * Set the error state and message
		 *
		 * @param {Object} state
		 * @param {Object} error
		 */
		setErrorState: function ( state, error ) {
			state.errorState = !!error;
			state.errorMessage = error.toString();
		}
	},
	actions: {
		/**
		 * Triggers a test API call and updates the test results, handles the test pending state
		 * and also define the error state and meessage if test returns errors
		 *
		 * @param {Object} context
		 * @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 Vuex store
		 *
		 * @return {Promise|void}
		 */
		getTestResults: function ( context, payload ) {
			// If function ZID is empty, exit
			Iif ( !payload.zFunctionId ) {
				return;
			}
 
			// Clear previous results and make sure that the call is triggered
			if ( payload.clearPreviousResults ) {
				context.commit( 'clearZTesterResults', payload.zFunctionId );
			}
 
			// If this API for this functionZid is already running, return promise
			if ( payload.zFunctionId in context.state.testResultsPromises ) {
				return context.state.testResultsPromises[ payload.zFunctionId ];
			}
 
			context.commit( 'setErrorState', false );
 
			const implementations = replaceCurrentObjectWithFullJSONObject(
				context,
				payload.zImplementations
			).map( ( a ) => {
				// (T358089) Encode any '|' characters of ZObjects so that they can be recovered after the API.
				return a.replace( '|', '🪈' );
			} );
			const testers = replaceCurrentObjectWithFullJSONObject(
				context,
				payload.zTesters
			).map( ( a ) => {
				// (T358089) Encode any '|' characters of ZObjects so that they can be recovered after the API.
				return a.replace( '|', '🪈' );
			} );
 
			const testResultsPromise = apiUtils.performTests( {
				functionZid: payload.zFunctionId,
				nocache: payload.nocache,
				implementations,
				testers
			} ).then( ( results ) => {
				Iif ( !Array.isArray( results ) &&
						results[ Constants.Z_RESPONSEENVELOPE_METADATA ] !== Constants.Z_NOTHING ) {
					throw new Error(
						results[
							Constants.Z_RESPONSEENVELOPE_METADATA
						][
							Constants.Z_ERROR_VALUE
						][
							Constants.Z_STRING_VALUE
						]
					);
				}
 
				const zids = [];
				results.forEach( function ( 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( status ) );
					zids.push( ...extractZIDs( metadata ) );
 
					// Store result
					context.commit( 'setZTesterResult', { key, result, metadata } );
				} );
 
				// Make sure that all returned Zids are in library.js
				context.dispatch( 'fetchZids', { zids: [ ...new Set( zids ) ] } );
				context.commit( 'setTestResultsPromise', { functionZid: payload.zFunctionId } );
			} ).catch( ( error ) => {
				const errorMessage = error.error ? ( error.error.message || error.error.info ) : undefined;
				context.commit( 'setErrorState', errorMessage || error );
				context.commit( 'setTestResultsPromise', { functionZid: payload.zFunctionId } );
			} );
 
			context.commit( 'setTestResultsPromise', {
				functionZid: payload.zFunctionId,
				promise: testResultsPromise
			} );
			return testResultsPromise;
		}
	}
};