Best JavaScript code snippet using fast-check-monorepo
suite-base.js
Source:suite-base.js
1//2// Copyright (c) Microsoft and contributors. All rights reserved.3//4// Licensed under the Apache License, Version 2.0 (the "License");5// you may not use this file except in compliance with the License.6// You may obtain a copy of the License at7// http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12//13// See the License for the specific language governing permissions and14// limitations under the License.15//16var fs = require('fs');17var os = require('os');18var path = require('path');19var sinon = require('sinon');20var _ = require('underscore');21var util = require('util');22var uuid = require('uuid');23var msRest = require('ms-rest');24var msRestAzure = require('ms-rest-azure');25var FileTokenCache = require('../../lib/util/fileTokenCache');26var MockTokenCache = require('./mock-token-cache');27var nockHelper = require('./nock-helper');28var ResourceManagementClient = require('../../lib/services/resourceManagement/lib/resource/resourceManagementClient');29var async = require('async');30var adal = require('adal-node');31var DEFAULT_ADAL_CLIENT_ID = '04b07795-8ddb-461a-bbee-02f9e1bf7b46';32/**33 * @class34 * Initializes a new instance of the SuiteBase class.35 * @constructor36 *37 * @param {object} mochaSuiteObject - The mocha suite object38 *39 * @param {string} testPrefix - The prefix to use for the test suite40 *41 * @param {Array} env - (Optional) Array of environment variables required by the test42 * Example:43 * [44 * { requiresToken: true },45 * { name: 'AZURE_ARM_TEST_LOCATION', defaultValue: 'West US' },46 * { name: 'AZURE_AD_TEST_PASSWORD'},47 * ];48 */49function SuiteBase(mochaSuiteObject, testPrefix, env) {50 this.mochaSuiteObject = mochaSuiteObject;51 this.testPrefix = this.normalizeTestName(testPrefix);52 this.mockServerClient;53 this.currentTest = '';54 //Recording info55 this.setRecordingsDirectory(__dirname + '/../recordings/' + this.testPrefix + '/');56 this.suiteRecordingsFile = this.getRecordingsDirectory() + 'suite.' + this.testPrefix + '.nock.js';57 this.recordingsFile = __dirname + '/../recordings/' + this.testPrefix + '.nock.js';58 //test modes59 this.isMocked = !process.env.NOCK_OFF;60 this.isRecording = process.env.AZURE_NOCK_RECORD;61 this.isPlayback = !process.env.NOCK_OFF && !process.env.AZURE_NOCK_RECORD;62 //authentication info63 this.subscriptionId = process.env['AZURE_SUBSCRIPTION_ID'] || 'subscription-id';64 this.clientId = process.env['CLIENT_ID'] || DEFAULT_ADAL_CLIENT_ID;65 this.domain = process.env['DOMAIN'] || 'domain';66 this.username = process.env['AZURE_USERNAME'] || 'username@example.com';67 this.password = process.env['AZURE_PASSWORD'] || 'dummypassword';68 this.secret = process.env['APPLICATION_SECRET'] || 'dummysecret';69 this.tokenCache = new adal.MemoryCache();70 this._setCredentials();71 //subscriptionId should be recorded for playback72 if (!env) {73 env = [];74 }75 env.push('AZURE_SUBSCRIPTION_ID');76 // Normalize environment77 this.normalizeEnvironment(env);78 this.validateEnvironment();79 //track & restore generated uuids to be used as part of request url, like a RBAC role assignment name80 this.uuidsGenerated = [];81 this.currentUuid = 0;82 this.randomTestIdsGenerated = [];83 this.numberOfRandomTestIdGenerated = 0;84 this.mockVariables = {};85 //stub necessary methods if in playback mode86 this._stubMethods();87}88_.extend(SuiteBase.prototype, {89 _setCredentials: function() {90 if (!this.isPlayback) {91 if (process.env['SKIP_CREDENTIAL_CHECK']) {92 let token = process.env['AZURE_ACCESS_TOKEN'] || 'token';93 this.credentials = new msRest.TokenCredentials('token');94 } else if ((process.env['AZURE_PASSWORD'] && process.env['APPLICATION_SECRET']) ||95 (!process.env['AZURE_PASSWORD'] && !process.env['APPLICATION_SECRET'])) {96 throw new Error('You must either set the envt. variables \'AZURE_USERNAME\' ' +97 'and \'AZURE_PASSWORD\' for running tests as a user or set the ' +98 'envt. variable \'CLIENT_ID\' and \'APPLICATION_SECRET\' ' +99 'for running tests as a service-principal, but not both.');100 }101 if (process.env['AZURE_PASSWORD']) {102 this.credentials = this._createUserCredentials();103 } else if (process.env['APPLICATION_SECRET']) {104 this.credentials = this._createApplicationCredentials();105 }106 } else {107 //The type of credential object does not matter in playback mode as authentication108 //header is not recorded. Hence we always default to UsertokenCredentials.109 this.credentials = this._createUserCredentials();110 }111 },112 /**113 * Creates the UserTokenCredentials object.114 *115 * @returns {ms-rest-azure.UserTokenCredentials} The user token credentials object.116 */117 _createUserCredentials: function() {118 if(process.env['AZURE_ENVIRONMENT'] && process.env['AZURE_ENVIRONMENT'].toUpperCase() === 'DOGFOOD') {119 var df = {120 name: 'Dogfood',121 portalUrl: 'https://windows.azure-test.net/',122 activeDirectoryEndpointUrl: 'https://login.windows-ppe.net/',123 activeDirectoryResourceId: 'https://management.core.windows.net/',124 managementEndpointUrl: 'https://management-preview.core.windows-int.net/',125 resourceManagerEndpointUrl: 'https://api-dogfood.resources.windows-int.net/'126 };127 var env = msRestAzure.AzureEnvironment.add(df);128 return new msRestAzure.UserTokenCredentials(this.clientId, this.domain, this.username,129 this.password, { 'tokenCache': this.tokenCache, 'environment': env });130 }131 132 return new msRestAzure.UserTokenCredentials(this.clientId, this.domain, this.username,133 this.password, { 'tokenCache': this.tokenCache });134 },135 /**136 * Creates the ApplicationTokenCredentials object.137 *138 * @returns {ms-rest-azure.ApplicationTokenCredentials} The application token credentials object.139 */140 _createApplicationCredentials: function() {141 if(process.env['AZURE_ENVIRONMENT'] && process.env['AZURE_ENVIRONMENT'].toUpperCase() === 'DOGFOOD') {142 var df = {143 name: 'Dogfood',144 portalUrl: 'https://windows.azure-test.net/',145 activeDirectoryEndpointUrl: 'https://login.windows-ppe.net/',146 activeDirectoryResourceId: 'https://management.core.windows.net/',147 managementEndpointUrl: 'https://management-preview.core.windows-int.net/',148 resourceManagerEndpointUrl: 'https://api-dogfood.resources.windows-int.net/'149 };150 var env = msRestAzure.AzureEnvironment.add(df); 151 return new msRestAzure.ApplicationTokenCredentials(this.clientId, this.domain, this.secret, {152 'tokenCache': this.tokenCache,153 'environment': env154 });155 }156 157 return new msRestAzure.ApplicationTokenCredentials(this.clientId, this.domain, this.secret, {158 'tokenCache': this.tokenCache159 });160 },161 /**162 * Creates a ResourceManagementClient and sets it as a property of the suite.163 */164 _setupResourceManagementClient: function() {165 if (!this.resourceManagement) {166 this.resourceManagement = new ResourceManagementClient(this.credentials, this.subscriptionId);167 }168 if (this.isPlayback) {169 this.resourceManagement.longRunningOperationRetryTimeout = 0;170 }171 },172 /**173 * Creates a new ResourceGroup with the specified name and location.174 *175 * @param {string} groupName - The resourcegroup name176 * @param {string} location - The location177 *178 * @returns {function} callback(err, result) - It contains error and result for the create request.179 */180 createResourcegroup: function(groupName, location, callback) {181 console.log('Creating Resource Group: \'' + groupName + '\' at location: \'' + location + '\'');182 this._setupResourceManagementClient();183 return this.resourceManagement.resourceGroups.createOrUpdate(groupName, {184 'location': location185 }, callback);186 },187 /**188 * Deletes the specified ResourceGroup.189 *190 * @param {string} groupName - The resourcegroup name191 *192 * @returns {function} callback(err, result) - It contains error and result for the delete request.193 */194 deleteResourcegroup: function(groupName, callback) {195 console.log('Deleting Resource Group: ' + groupName);196 if (!this.resourceManagement) {197 this._setupResourceManagementClient();198 }199 return this.resourceManagement.resourceGroups.deleteMethod(groupName, callback);200 },201 /**202 * Provides the recordings directory for the test suite203 *204 * @returns {string} The test recordings directory205 */206 getRecordingsDirectory: function() {207 return this.recordingsDirectory;208 },209 /**210 * Sets the recordings directory for the test suite211 *212 * @param {string} dir The test recordings directory213 */214 setRecordingsDirectory: function(dir) {215 if (!fs.existsSync(dir)) {216 fs.mkdirSync(dir);217 }218 this.recordingsDirectory = dir;219 },220 /**221 * Provides the curent test recordings file222 *223 * @returns {string} The curent test recordings file224 */225 getTestRecordingsFile: function() {226 this.testRecordingsFile = this.getRecordingsDirectory() +227 this.normalizeTestName(this.currentTest) + ".nock.js";228 return this.testRecordingsFile;229 },230 normalizeTestName: function(str) {231 return str.replace(/[{}\[\]'";\(\)#@~`!%&\^\$\+=,\/\\?<>\|\*:]/ig, '').replace(/(\s+)/ig, '_');232 },233 normalizeEnvironment: function(env) {234 this.requiredEnvironment = env.map(function(env) {235 if (typeof(env) === 'string') {236 return {237 name: env,238 secure: false239 };240 } else {241 return env;242 }243 });244 },245 validateEnvironment: function() {246 if (this.isPlayback) {247 return;248 }249 var messages = [];250 var missing = [];251 this.requiredEnvironment.forEach(function(e) {252 if (!process.env[e.name] && !e.defaultValue) {253 missing.push(e.name);254 }255 });256 if (missing.length > 0) {257 messages.push('This test requires the following environment variables which are not set: ' +258 missing.join(', '));259 }260 if (messages.length > 0) {261 throw new Error(messages.join(os.EOL));262 }263 },264 setEnvironmentDefaults: function() {265 this.requiredEnvironment.forEach(function(env) {266 if (env.defaultValue && !process.env[env.name]) {267 process.env[env.name] = env.defaultValue;268 }269 });270 },271 /**272 * Provides the curent suite recordings file273 *274 * @returns {string} The curent suite recordings file275 */276 getSuiteRecordingsFile: function() {277 return this.suiteRecordingsFile;278 },279 /**280 * Performs the specified actions before executing the suite. Records the random test ids and uuids generated during the281 * suite setup and restores them in playback282 *283 * @param {function} callback A hook to provide the steps to execute during setup suite284 */285 setupSuite: function(callback, isAsyncSetUp) {286 if (this.isMocked) {287 process.env.AZURE_ENABLE_STRICT_SSL = false;288 }289 if (this.isPlayback) {290 // retrive suite level recorded testids and uuids if any291 var nocked = require(this.getSuiteRecordingsFile());292 if (nocked.randomTestIdsGenerated) {293 this.randomTestIdsGenerated = nocked.randomTestIdsGenerated();294 }295 if (nocked.uuidsGenerated) {296 this.uuidsGenerated = nocked.uuidsGenerated();297 }298 if (nocked.mockVariables) {299 this.mockVariables = nocked.mockVariables();300 }301 if (nocked.setEnvironment) {302 nocked.setEnvironment();303 }304 this.subscriptionId = process.env['AZURE_SUBSCRIPTION_ID'];305 this.originalTokenCache = this.tokenCache;306 this.tokenCache = new MockTokenCache();307 } else {308 this.setEnvironmentDefaults();309 }310 var self = this;311 async.series([312 function(firstCallback) {313 if (isAsyncSetUp) {314 callback(function() {315 firstCallback(null);316 });317 } else {318 callback();319 firstCallback(null);320 }321 },322 function(secondCallback) {323 //write the suite level testids and uuids to a suite recordings file324 if (self.isMocked && self.isRecording) {325 self.writeRecordingHeader(self.getSuiteRecordingsFile());326 fs.appendFileSync(self.getSuiteRecordingsFile(), '];\n');327 self.writeGeneratedUuids(self.getSuiteRecordingsFile());328 self.writeGeneratedRandomTestIds(self.getSuiteRecordingsFile());329 self.writeMockVariables(self.getSuiteRecordingsFile());330 }331 secondCallback(null);332 }333 ],334 function(err, results) {335 if (err) {336 throw err;337 }338 });339 },340 /**341 * Performs the specified async actions before executing the suite. Records the random test ids and uuids generated during the342 * suite setup and restores them in playback343 *344 * @param {function} callback A hook to provide the steps to execute during setup suite345 */346 setupSuiteAsync: function(callback) {347 this.setupSuite(callback, true);348 },349 /**350 * Performs the specified actions after executing the suite.351 *352 * @param {function} callback A hook to provide the steps to execute after the suite has completed execution353 */354 teardownSuite: function(callback) {355 if (this.isMocked) {356 delete process.env.AZURE_ENABLE_STRICT_SSL;357 }358 callback();359 },360 /**361 * Performs the specified actions before executing the test. Restores the random test ids and uuids in362 * playback mode. Creates a new recording file for every test.363 *364 * @param {function} callback A hook to provide the steps to execute before the test starts execution365 */366 setupTest: function(callback) {367 this.currentTest = this.mochaSuiteObject.currentTest.fullTitle();368 this.numberOfRandomTestIdGenerated = 0;369 this.currentUuid = 0;370 nockHelper.nockHttp();371 if (this.isMocked && this.isRecording) {372 // nock recording373 this.writeRecordingHeader();374 nockHelper.nock.recorder.rec(true);375 }376 if (this.isPlayback) {377 // nock playback378 var nocked = require(this.getTestRecordingsFile());379 if (nocked.randomTestIdsGenerated) {380 this.randomTestIdsGenerated = nocked.randomTestIdsGenerated();381 }382 if (nocked.uuidsGenerated) {383 this.uuidsGenerated = nocked.uuidsGenerated();384 }385 if (nocked.mockVariables) {386 this.mockVariables = nocked.mockVariables();387 }388 if (nocked.setEnvironment) {389 nocked.setEnvironment();390 }391 this.originalTokenCache = this.tokenCache;392 this.tokenCache = new MockTokenCache();393 if (nocked.scopes.length === 1) {394 nocked.scopes[0].forEach(function(createScopeFunc) {395 createScopeFunc(nockHelper.nock);396 });397 } else {398 throw new Error('It appears the ' + this.getTestRecordingsFile() + ' file has more tests than there are mocked tests. ' +399 'You may need to re-generate it.');400 }401 }402 callback();403 },404 /**405 * Performs the specified actions after executing the test. Writes the generated uuids and test ids during406 * the test to the recorded file.407 *408 * @param {function} callback A hook to provide the steps to execute after the test has completed execution409 */410 baseTeardownTest: function(callback) {411 if (this.isMocked) {412 if (this.isRecording) {413 // play nock recording414 var scope = '[';415 var lineWritten;416 nockHelper.nock.recorder.play().forEach(function(line) {417 if (line.indexOf('nock') >= 0) {418 // apply fixups of nock generated mocks419 // do not filter on body as they usual have time related stamps420 line = line.replace(/(\.post\('.*?')\s*,\s*"[^]+[^\\]"\)/, '.filteringRequestBody(function (path) { return \'*\';})\n$1, \'*\')');421 line = line.replace(/(\.get\('.*?')\s*,\s*"[^]+[^\\]"\)/, '.filteringRequestBody(function (path) { return \'*\';})\n$1, \'*\')');422 line = line.replace(/(\.put\('.*?')\s*,\s*"[^]+[^\\]"\)/, '.filteringRequestBody(function (path) { return \'*\';})\n$1, \'*\')');423 line = line.replace(/(\.delete\('.*?')\s*,\s*"[^]+[^\\]"\)/, '.filteringRequestBody(function (path) { return \'*\';})\n$1, \'*\')');424 line = line.replace(/(\.merge\('.*?')\s*,\s*"[^]+[^\\]"\)/, '.filteringRequestBody(function (path) { return \'*\';})\n$1, \'*\')');425 line = line.replace(/(\.patch\('.*?')\s*,\s*"[^]+[^\\]"\)/, '.filteringRequestBody(function (path) { return \'*\';})\n$1, \'*\')');426 // put deployment have a timestamp in the url427 line = line.replace(/(\.put\('\/deployment-templates\/\d{8}T\d{6}')/,428 '.filteringPath(/\\/deployment-templates\\/\\d{8}T\\d{6}/, \'/deployment-templates/timestamp\')\n.put(\'/deployment-templates/timestamp\'');429 // Requests to logging service contain timestamps in url query params, filter them out too430 line = line.replace(/(\.get\('.*\/microsoft.insights\/eventtypes\/management\/values\?api-version=[0-9-]+)[^)]+\)/,431 '.filteringPath(function (path) { return path.slice(0, path.indexOf(\'&\')); })\n$1\')');432 if (line.match(/\/oauth2\/token\//ig) === null &&433 line.match(/login\.windows\.net/ig) === null && 434 line.match(/login\.windows-ppe\.net/ig) === null &&435 line.match(/login\.microsoftonline\.com/ig) === null &&436 line.match(/login\.chinacloudapi\.cn/ig) === null &&437 line.match(/login\.microsoftonline\.de/ig) === null) {438 scope += (lineWritten ? ',\n' : '') + 'function (nock) { \n' +439 'var result = ' + line + ' return result; }';440 lineWritten = true;441 }442 }443 });444 scope += ']];';445 fs.appendFileSync(this.getTestRecordingsFile(), scope);446 this.writeGeneratedUuids();447 this.writeGeneratedRandomTestIds();448 this.writeMockVariables();449 nockHelper.nock.recorder.clear();450 } else {451 //playback mode452 this.tokenCache = this.originalTokenCache;453 nockHelper.nock.cleanAll();454 }455 }456 nockHelper.unNockHttp();457 callback();458 },459 /**460 * Writes the generated uuids to the specified file.461 *462 * @param {string} filename (Optional) The file name to which the uuids need to be added463 * If the filename is not provided then it will get the current test recording file.464 */465 writeGeneratedUuids: function(filename) {466 if (this.uuidsGenerated.length > 0) {467 var uuids = this.uuidsGenerated.map(function(uuid) {468 return '\'' + uuid + '\'';469 }).join(',');470 var content = util.format('\n exports.uuidsGenerated = function() { return [%s];};', uuids);471 filename = filename || this.getTestRecordingsFile();472 fs.appendFileSync(filename, content);473 this.uuidsGenerated.length = 0;474 }475 },476 /**477 * Writes the generated random test ids to the specified file.478 *479 * @param {string} filename (Optional) The file name to which the random test ids need to be added480 * If the filename is not provided then it will get the current test recording file.481 */482 writeGeneratedRandomTestIds: function(filename) {483 if (this.randomTestIdsGenerated.length > 0) {484 var ids = this.randomTestIdsGenerated.map(function(id) {485 return '\'' + id + '\'';486 }).join(',');487 var content = util.format('\n exports.randomTestIdsGenerated = function() { return [%s];};', ids);488 filename = filename || this.getTestRecordingsFile();489 fs.appendFileSync(filename, content);490 this.randomTestIdsGenerated.length = 0;491 }492 },493 /**494 * Writes the mock variables to the specified file495 *496 * @param {string} filename (Optional) The file name to which the mock variables need to be added497 * If the filename is not provided then it will get the current test recording file.498 */499 writeMockVariables: function(filename) {500 if (this.mockVariables && Object.keys(this.mockVariables).length > 0) {501 var mockVariablesObject = JSON.stringify(this.mockVariables);502 var content = util.format('\n exports.mockVariables = function() { return %s; };', mockVariablesObject);503 filename = filename || this.getTestRecordingsFile();504 fs.appendFileSync(filename, content);505 this.mockVariables = {};506 }507 },508 /**509 * Writes the recording header to the specified file.510 *511 * @param {string} filename (Optional) The file name to which the recording header needs to be added512 * If the filename is not provided then it will get the current test recording file.513 */514 writeRecordingHeader: function(filename) {515 var template = fs.readFileSync(path.join(__dirname, 'preamble.template'), {516 encoding: 'utf8'517 });518 filename = filename || this.getTestRecordingsFile();519 let compiledTemplateFunction = _.template(template);520 let data = compiledTemplateFunction({ requiredEnvironment: this.requiredEnvironment });521 fs.writeFileSync(filename, data);522 },523 /**524 * Generates an unique identifier using a prefix, based on a currentList and repeatable or not depending on the isMocked flag.525 *526 * @param {string} prefix The prefix to use in the identifier.527 * @param {array} currentList The current list of identifiers.528 * @return {string} A new unique identifier.529 */530 generateId: function(prefix, currentList) {531 if (!currentList) {532 currentList = [];533 }534 var newNumber;535 //record or live536 if (!this.isPlayback) {537 newNumber = this.generateRandomId(prefix, currentList);538 //record539 if (this.isMocked) {540 this.randomTestIdsGenerated[this.numberOfRandomTestIdGenerated++] = newNumber;541 }542 } else {543 //playback544 if (this.randomTestIdsGenerated && this.randomTestIdsGenerated.length > 0) {545 newNumber = this.randomTestIdsGenerated[this.numberOfRandomTestIdGenerated++];546 } else {547 //some test might not have recorded generated ids, so we fall back to the old sequential logic548 newNumber = prefix + (currentList.length + 1);549 }550 }551 currentList.push(newNumber);552 return newNumber;553 },554 /**555 * Generates a Guid. It will save the Guid to the recording file if in 'Record' mode or556 * retrieve the guid from the recording file if in 'Playback' mode.557 * @return {string} A new Guid.558 */559 generateGuid: function() {560 var newGuid;561 //record or live562 if (!this.isPlayback) {563 newGuid = uuid.v4();564 //record565 if (this.isMocked) {566 this.uuidsGenerated[this.currentUuid++] = newGuid;567 }568 } else {569 //playback570 if (this.uuidsGenerated && this.uuidsGenerated.length > 0) {571 newGuid = this.uuidsGenerated[this.currentUuid++];572 }573 }574 return newGuid;575 },576 /**577 * Saves the mock variable with the specified name to the recording file when the test is run578 * in 'Record' mode or keeps it in memory when the test is run in 'Live' mode.579 */580 saveMockVariable: function(mockVariableName, mockVariable) {581 //record or live582 if (!this.isPlayback) {583 this.mockVariables[mockVariableName] = mockVariable;584 }585 },586 /**587 * Gets the mock variable with the specified name. Returns undefined if the variable name is not present.588 * @return {object} A mock variable.589 */590 getMockVariable: function(mockVariableName) {591 return this.mockVariables[mockVariableName];592 },593 /**594 * A helper function to handle wrapping an existing method in sinon.595 *596 * @param {ojbect} sinonObj either sinon or a sinon sandbox instance597 * @param {object} object The object containing the method to wrap598 * @param {string} property property name of method to wrap599 * @param {function (function)} setup function that receives the original function,600 * returns new function that runs when method is called.601 * @return {object} The created stub.602 */603 wrap: function(sinonObj, object, property, setup) {604 var original = object[property];605 return sinonObj.stub(object, property, setup(original));606 },607 /**608 * A helper function to generate a random id.609 *610 * @param {string} prefix A prefix for the generated random id611 * @param {array} currentList The list that contains the generated random ids612 * (This ensures that there are no duplicates in the list)613 * @return {string} The generated random nmumber.614 */615 generateRandomId: function(prefix, currentList) {616 var newNumber;617 while (true) {618 newNumber = prefix + Math.floor(Math.random() * 10000);619 if (!currentList || currentList.indexOf(newNumber) === -1) {620 break;621 }622 }623 return newNumber;624 },625 /**626 * Stubs certain methods to make them work in playback mode.627 */628 _stubMethods: function() {629 if (this.isPlayback) {630 if (msRestAzure.UserTokenCredentials.prototype.signRequest.restore) {631 msRestAzure.UserTokenCredentials.prototype.signRequest.restore();632 }633 sinon.stub(msRestAzure.UserTokenCredentials.prototype, 'signRequest').callsFake(function(webResource, callback) {634 return callback(null);635 });636 if (msRestAzure.ApplicationTokenCredentials.prototype.signRequest.restore) {637 msRestAzure.ApplicationTokenCredentials.prototype.signRequest.restore();638 }639 sinon.stub(msRestAzure.ApplicationTokenCredentials.prototype, 'signRequest').callsFake(function(webResource, callback) {640 return callback(null);641 });642 if (this.createResourcegroup.restore) {643 this.createResourcegroup.restore();644 }645 sinon.stub(this, 'createResourcegroup').callsFake(function(groupName, location, callback) {646 return callback(null);647 });648 if (this.deleteResourcegroup.restore) {649 this.deleteResourcegroup.restore();650 }651 sinon.stub(this, 'deleteResourcegroup').callsFake(function(groupName, callback) {652 return callback(null);653 });654 }655 }656});...
ModelRunner.ts
Source:ModelRunner.ts
...84 const then = (p: Promise<void>, c: () => Promise<void> | undefined) => p.then(c);85 const setupProducer = {86 then: (fun: SetupFun<Model, Real, Promise<void>>) => {87 const out = s();88 if (isAsyncSetup(out)) return out.then(fun);89 else return fun(out);90 },91 };92 const runAsync = async (cmd: AsyncCommand<Model, Real, CheckAsync>, m: Model, r: Real) => {93 if (await cmd.check(m)) await cmd.run(m, r);94 };95 return await genericModelRun(setupProducer, cmds, defaultPromise, runAsync, then);96};97/**98 * Run synchronous commands over a `Model` and the `Real` system99 *100 * Throw in case of inconsistency101 *102 * @param s - Initial state provider...
Using AI Code Generation
1const { isAsyncSetup } = require('fast-check');2const { isAsyncSetup } = require('fast-check/lib/types/property/AsyncProperty');3const { isAsyncSetup } = require('fast-check/lib/types/property/AsyncProperty.js');4const { isAsyncSetup } = require('fast-check');5const { isAsyncSetup } = require('fast-check/lib/types/property/AsyncProperty');6const { isAsyncSetup } = require('fast-check/lib/types/property/AsyncProperty.js');7const { isAsyncSetup } = require('fast-check');8const { isAsyncSetup } = require('fast-check/lib/types/property/AsyncProperty');9const { isAsyncSetup } = require('fast-check/lib/types/property/AsyncProperty.js');10const { isAsyncSetup } = require('fast-check');11const { isAsyncSetup } = require('fast-check/lib/types/property/AsyncProperty');12const { isAsyncSetup } = require('fast-check/lib/types/property/AsyncProperty.js');13const { isAsyncSetup } = require('fast-check');14const { isAsyncSetup } = require('fast-check/lib/types/property/AsyncProperty');15const { isAsyncSetup } = require('fast-check/lib/types/property/AsyncProperty.js');16const { isAsyncSetup } = require('fast-check');17const { isAsyncSetup } = require('fast-check/lib/types/property/AsyncProperty');18const { isAsyncSetup } = require('fast-check/lib/types/property/AsyncProperty.js');19const { isAsyncSetup } = require('fast-check');20const { isAsyncSetup } = require('fast-check/lib/types/property/AsyncProperty');21const { isAsyncSetup } = require('fast-check/lib/types/property/AsyncProperty.js');
Using AI Code Generation
1const { isAsyncSetup } = require('fast-check');2const { isAsyncSetup } = require('fast-check/lib/check/arbitrary/AsyncSetupWrapper.js');3const { isAsyncSetup } = require('fast-check');4const { isAsyncSetup } = require('fast-check/lib/check/arbitrary/AsyncSetupWrapper.js');5const { isAsyncSetup } = require('fast-check');6const { isAsyncSetup } = require('fast-check/lib/check/arbitrary/AsyncSetupWrapper.js');7const { isAsyncSetup } = require('fast-check');8const { isAsyncSetup } = require('fast-check/lib/check/arbitrary/AsyncSetupWrapper.js');9const { isAsyncSetup } = require('fast-check');10const { isAsyncSetup } = require('fast-check/lib/check/arbitrary/AsyncSetupWrapper.js');11const { isAsyncSetup } = require('fast-check');12const { isAsyncSetup } = require('fast-check/lib/check/arbitrary/AsyncSetupWrapper.js');13const { isAsyncSetup } = require('fast-check');14const { isAsyncSetup } = require('fast-check/lib/check/arbitrary/AsyncSetupWrapper.js');15const { isAsyncSetup } = require('fast-check');16const { isAsyncSetup } = require('fast-check/lib/check/arbitrary/AsyncSetupWrapper.js');17const { isAsyncSetup } = require('fast-check');18const { isAsyncSetup } = require('fast-check/lib/check/arbitrary/AsyncSetupWrapper.js');19const { is
Using AI Code Generation
1const fc = require('fast-check');2const { isAsyncSetup } = require('fast-check/lib/check/arbitrary/definition/AsyncSetupWrapper');3const asyncSetupArb = fc.asyncProperty(fc.integer(), fc.integer(), async (a, b) => {4 const sum = a + b;5 return sum;6});7const syncSetupArb = fc.property(fc.integer(), fc.integer(), (a, b) => {8 const sum = a + b;9 return sum;10});11console.log('asyncSetupArb is async setup? : ', isAsyncSetup(asyncSetupArb));12console.log('syncSetupArb is async setup? : ', isAsyncSetup(syncSetupArb));
Using AI Code Generation
1const { check } = require('fast-check');2const isAsyncSetup = require('fast-check/lib/check/runner/Runner.js').isAsyncSetup;3const asyncSetup = async () => {4 console.log('asyncSetup');5 return 1;6};7const setup = () => {8 console.log('setup');9 return 1;10};11const property = async (a) => {12 console.log('property');13 return true;14};15(async () => {16 await check(property, { asyncSetup, setup });17})();18const { check } = require('fast-check');19const isAsyncSetup = require('fast-check/lib/check/runner/Runner.js').isAsyncSetup;20const asyncSetup = async () => {21 console.log('asyncSetup');22 return 1;23};24const setup = () => {25 console.log('setup');26 return 1;27};28const property = (a) => {29 console.log('property');30 return true;31};32(async () => {33 await check(property, { asyncSetup, setup });34})();35const { check } = require('fast-check');36const isAsyncSetup = require('fast-check/lib/check/runner/Runner.js').isAsyncSetup;37const asyncSetup = async () => {38 console.log('asyncSetup');39 return 1;40};41const setup = () => {42 console.log('setup');43 return 1;44};45const property = (a) => {46 console.log('property');47 return true;48};49(async () => {50 await check(property, { asyncSetup, setup });51})();52const { check } = require('fast-check');53const isAsyncSetup = require('fast-check/lib/check/runner/Runner.js').isAsyncSetup;54const asyncSetup = async () => {55 console.log('asyncSetup');56 return 1;57};58const setup = () => {59 console.log('setup');60 return 1;61};62const property = (a) => {63 console.log('property');64 return true;
Using AI Code Generation
1const fc = require('fast-check');2const assert = require('assert');3const setup = async () => {4 return 1;5};6const teardown = async () => {7 return 1;8};9const prop = async (n) => {10 return n > 0;11};12fc.assert(13 fc.property(fc.nat(), prop),14 { asyncBefore: setup, asyncAfter: teardown }15);16const setup2 = async () => {17 return 1;18};19const teardown2 = async () => {20 return 1;21};22const prop2 = async (n) => {23 return n > 0;24};25fc.assert(26 fc.property(fc.nat(), prop2),27 { asyncBefore: setup2, asyncAfter: teardown2 }28);29const setup3 = async () => {30 return 1;31};32const teardown3 = async () => {33 return 1;34};35const prop3 = async (n) => {36 return n > 0;37};38fc.assert(39 fc.property(fc.nat(), prop3),40 { asyncBefore: setup3, asyncAfter: teardown3 }41);42const setup4 = async () => {43 return 1;44};45const teardown4 = async () => {46 return 1;47};48const prop4 = async (n) => {49 return n > 0;50};51fc.assert(52 fc.property(fc.nat(), prop4),53 { asyncBefore: setup4, asyncAfter: teardown4 }54);55const setup5 = async () => {56 return 1;57};58const teardown5 = async () => {59 return 1;60};61const prop5 = async (n) => {62 return n > 0;63};64fc.assert(65 fc.property(fc.nat(), prop5),66 { asyncBefore: setup5, asyncAfter: teardown5 }67);68const setup6 = async () => {69 return 1;70};
Using AI Code Generation
1const { isAsyncSetup } = require('fast-check');2const isAsync = isAsyncSetup();3if (isAsync) {4 console.log('isAsync is true');5} else {6 console.log('isAsync is false');7}8const { isAsyncSetup } = require('fast-check');9const isAsync = isAsyncSetup();10if (isAsync) {11 console.log('isAsync is true');12} else {13 console.log('isAsync is false');14}15const { isAsyncSetup } = require('fast-check');16const isAsync = isAsyncSetup();17if (isAsync) {18 console.log('isAsync is true');19} else {20 console.log('isAsync is false');21}22const { isAsyncSetup } = require('fast-check');23const isAsync = isAsyncSetup();24if (isAsync) {25 console.log('isAsync is true');26} else {27 console.log('isAsync is false');28}29const { isAsyncSetup } = require('fast-check');30const isAsync = isAsyncSetup();31if (isAsync) {32 console.log('isAsync is true');33} else {34 console.log('isAsync is false');35}36const { isAsyncSetup } = require('fast-check');37const isAsync = isAsyncSetup();38if (isAsync) {39 console.log('isAsync is true');40} else {41 console.log('isAsync is false');42}43const { isAsyncSetup } = require('fast-check');44const isAsync = isAsyncSetup();45if (isAsync) {
Using AI Code Generation
1const { isAsyncSetup } = require('fast-check');2const myFunction = async () => {3 return 42;4};5describe('myFunction', () => {6 isAsyncSetup(() => {7 it('should return 42', async () => {8 const result = await myFunction();9 expect(result).toBe(42);10 });11 });12});13const { isAsyncSetup } = require('fast-check');14const myFunction = async () => {15 throw new Error('oops');16};17describe('myFunction', () => {18 isAsyncSetup(() => {19 it('should throw an error', async () => {20 try {21 await myFunction();22 } catch (error) {23 expect(error.message).toBe('oops');24 }25 });26 });27});28const { isAsyncSetup } = require('fast-check');29const myFunction = async () => {30 throw new Error('oops');31};32describe('myFunction', () => {33 isAsyncSetup(() => {34 it('should throw an error', async () => {35 await expect(myFunction()).rejects.toThrow('oops');36 });37 });38});39const { isAsyncSetup } = require('fast-check');40const myFunction = async () => {41 throw new Error('oops');42};43describe('myFunction', () => {44 isAsyncSetup(() => {45 it('should throw an error', async () => {46 await expect(myFunction()).rejects.toThrowErrorMatchingSnapshot();47 });48 });49});
Using AI Code Generation
1import fc from 'fast-check';2import { isAsyncSetup } from 'fast-check-monorepo';3const asyncSetup = async () => {4 return {foo: 'foo'};5};6const isAsyncSetupFunction = isAsyncSetup(asyncSetup);7if (isAsyncSetupFunction) {8 fc.assert(9 fc.property(10 fc.integer(),11 fc.integer(),12 async (a, b) => {13 const {foo} = await asyncSetup();14 return a + b === b + a;15 }16 );17} else {18 console.log('asyncSetup is not an async setup function');19}
Using AI Code Generation
1const { isAsyncSetup } = require("fast-check");2const { setup } = require("./test2");3test("test3", () => {4 expect(isAsyncSetup(setup)).toBe(true);5});6 ✓ test3 (8ms)
Using AI Code Generation
1const { isAsyncSetup } = require('fast-check-monorepo');2const setup = isAsyncSetup(async () => {3 console.log('setup called');4 return { foo: 'bar' };5});6const teardown = isAsyncSetup(async setupResult => {7 console.log('teardown called');8 console.log('setupResult:', setupResult);9});10describe('test3', () => {11 beforeAll(setup);12 afterAll(teardown);13 it('test3 test 1', async () => {14 console.log('test3 test 1');15 });16 it('test3 test 2', async () => {17 console.log('test3 test 2');18 });19});20const { isAsyncSetup } = require('fast-check-monorepo');21const setup = isAsyncSetup(async () => {22 console.log('setup called');23 return { foo: 'bar' };24});25const teardown = isAsyncSetup(async setupResult => {26 console.log('teardown called');27 console.log('setupResult:', setupResult);28});29describe('test4', () => {30 beforeAll(setup);31 afterAll(teardown);32 it('test4 test 1', async () => {33 console.log('test4 test 1');34 });35 it('test4 test 2', async () => {36 console.log('test4 test 2');37 });38});
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!