Best JavaScript code snippet using stryker-parent
mutant-test-planner.ts
Source:mutant-test-planner.ts
1import path from 'path';2import { TestResult } from '@stryker-mutator/api/test-runner';3import { MutantRunPlan, MutantTestPlan, PlanKind, Mutant, StrykerOptions, MutantStatus, MutantEarlyResultPlan } from '@stryker-mutator/api/core';4import { commonTokens, tokens } from '@stryker-mutator/api/plugin';5import { Logger } from '@stryker-mutator/api/logging';6import { I, notEmpty } from '@stryker-mutator/util';7import { coreTokens } from '../di/index.js';8import { StrictReporter } from '../reporters/strict-reporter.js';9import { Sandbox } from '../sandbox/index.js';10import { objectUtils } from '../utils/object-utils.js';11import { optionsPath } from '../utils/index.js';12import { Project } from '../fs/project.js';13import { IncrementalDiffer, toRelativeNormalizedFileName } from './incremental-differ.js';14import { TestCoverage } from './test-coverage.js';15/**16 * The factor by which hit count from dry run is multiplied to calculate the hit limit for a mutant.17 * This is intentionally a high value to prevent false positives.18 *19 * For example, a property testing library might execute a failing scenario multiple times to determine the smallest possible counterexample.20 * @see https://jsverify.github.io/#minimal-counterexample21 */22const HIT_LIMIT_FACTOR = 100;23/**24 * Responsible for determining the tests to execute for each mutant, as well as other run option specific details25 *26 */27export class MutantTestPlanner {28 public static readonly inject = tokens(29 coreTokens.testCoverage,30 coreTokens.incrementalDiffer,31 coreTokens.reporter,32 coreTokens.sandbox,33 coreTokens.project,34 coreTokens.timeOverheadMS,35 commonTokens.options,36 commonTokens.logger37 );38 private readonly timeSpentAllTests: number;39 constructor(40 private readonly testCoverage: I<TestCoverage>,41 private readonly incrementalDiffer: IncrementalDiffer,42 private readonly reporter: StrictReporter,43 private readonly sandbox: I<Sandbox>,44 private readonly project: I<Project>,45 private readonly timeOverheadMS: number,46 private readonly options: StrykerOptions,47 private readonly logger: Logger48 ) {49 this.timeSpentAllTests = calculateTotalTime(this.testCoverage.testsById.values());50 }51 public async makePlan(mutants: readonly Mutant[]): Promise<readonly MutantTestPlan[]> {52 const mutantsDiff = await this.incrementalDiff(mutants);53 const mutantPlans = mutantsDiff.map((mutant) => this.planMutant(mutant));54 this.reporter.onMutationTestingPlanReady({ mutantPlans });55 this.warnAboutSlow(mutantPlans);56 return mutantPlans;57 }58 private planMutant(mutant: Mutant): MutantTestPlan {59 const isStatic = this.testCoverage.hasStaticCoverage(mutant.id);60 if (mutant.status) {61 // If this mutant was already ignored, early result62 return this.createMutantEarlyResultPlan(mutant, {63 isStatic,64 coveredBy: mutant.coveredBy,65 killedBy: mutant.killedBy,66 status: mutant.status,67 statusReason: mutant.statusReason,68 });69 } else if (this.testCoverage.hasCoverage) {70 // If there was coverage information (coverageAnalysis not "off")71 const tests = this.testCoverage.testsByMutantId.get(mutant.id) ?? [];72 const coveredBy = toTestIds(tests);73 if (!isStatic || (this.options.ignoreStatic && coveredBy.length)) {74 // If not static, or it was "hybrid" (both static and perTest coverage) and ignoreStatic is on.75 // Only run covered tests with mutant active during runtime76 const netTime = calculateTotalTime(tests);77 return this.createMutantRunPlan(mutant, { netTime, coveredBy, isStatic, testFilter: coveredBy });78 } else if (this.options.ignoreStatic) {79 // Static (w/o perTest coverage) and ignoreStatic is on -> Ignore.80 return this.createMutantEarlyResultPlan(mutant, {81 status: MutantStatus.Ignored,82 statusReason: 'Static mutant (and "ignoreStatic" was enabled)',83 isStatic,84 coveredBy,85 });86 } else {87 // Static (or hybrid) and `ignoreStatic` is off -> run all tests88 return this.createMutantRunPlan(mutant, { netTime: this.timeSpentAllTests, isStatic, coveredBy });89 }90 } else {91 // No coverage information exists, all tests need to run92 return this.createMutantRunPlan(mutant, { netTime: this.timeSpentAllTests });93 }94 }95 private createMutantEarlyResultPlan(96 mutant: Mutant,97 {98 isStatic,99 status,100 statusReason,101 coveredBy,102 killedBy,103 }: { isStatic: boolean | undefined; status: MutantStatus; statusReason?: string; coveredBy?: string[]; killedBy?: string[] }104 ): MutantEarlyResultPlan {105 return {106 plan: PlanKind.EarlyResult,107 mutant: {108 ...mutant,109 status,110 static: isStatic,111 statusReason,112 coveredBy,113 killedBy,114 },115 };116 }117 private createMutantRunPlan(118 mutant: Mutant,119 {120 netTime,121 testFilter,122 isStatic,123 coveredBy,124 }: { netTime: number; testFilter?: string[] | undefined; isStatic?: boolean | undefined; coveredBy?: string[] | undefined }125 ): MutantRunPlan {126 const { disableBail, timeoutMS, timeoutFactor } = this.options;127 const timeout = timeoutFactor * netTime + timeoutMS + this.timeOverheadMS;128 const hitCount = this.testCoverage.hitsByMutantId.get(mutant.id);129 const hitLimit = hitCount === undefined ? undefined : hitCount * HIT_LIMIT_FACTOR;130 return {131 plan: PlanKind.Run,132 netTime,133 mutant: {134 ...mutant,135 coveredBy,136 static: isStatic,137 },138 runOptions: {139 // Copy over relevant mutant fields, we don't want to copy over "static" and "coveredBy", test runners should only care about the testFilter140 activeMutant: {141 id: mutant.id,142 fileName: mutant.fileName,143 location: mutant.location,144 mutatorName: mutant.mutatorName,145 replacement: mutant.replacement,146 },147 mutantActivation: testFilter ? 'runtime' : 'static',148 timeout,149 testFilter,150 sandboxFileName: this.sandbox.sandboxFileFor(mutant.fileName),151 hitLimit,152 disableBail,153 reloadEnvironment: !testFilter,154 },155 };156 }157 private warnAboutSlow(mutantPlans: readonly MutantTestPlan[]) {158 if (!this.options.ignoreStatic && objectUtils.isWarningEnabled('slow', this.options.warnings)) {159 // Only warn when the estimated time to run all static mutants exceeds 40%160 // ... and when the average performance impact of a static mutant is estimated to be twice that (or more) of a non-static mutant161 const ABSOLUTE_CUT_OFF_PERUNAGE = 0.4;162 const RELATIVE_CUT_OFF_FACTOR = 2;163 const zeroIfNaN = (n: number) => (isNaN(n) ? 0 : n);164 const runPlans = mutantPlans.filter(isRunPlan);165 const staticRunPlans = runPlans.filter(({ mutant }) => mutant.static);166 const runTimeRunPlans = runPlans.filter(({ mutant }) => !mutant.static);167 const estimatedTimeForStaticMutants = staticRunPlans.reduce((acc, { netTime }) => acc + netTime, 0);168 const estimatedTimeForRunTimeMutants = runTimeRunPlans.reduce((acc, { netTime }) => acc + netTime, 0);169 const estimatedTotalTime = estimatedTimeForRunTimeMutants + estimatedTimeForStaticMutants;170 const avgTimeForAStaticMutant = zeroIfNaN(estimatedTimeForStaticMutants / staticRunPlans.length);171 const avgTimeForARunTimeMutant = zeroIfNaN(estimatedTimeForRunTimeMutants / runTimeRunPlans.length);172 const relativeTimeForStaticMutants = estimatedTimeForStaticMutants / estimatedTotalTime;173 const absoluteCondition = relativeTimeForStaticMutants >= ABSOLUTE_CUT_OFF_PERUNAGE;174 const relativeCondition = avgTimeForAStaticMutant >= RELATIVE_CUT_OFF_FACTOR * avgTimeForARunTimeMutant;175 if (relativeCondition && absoluteCondition) {176 const percentage = (perunage: number) => Math.round(perunage * 100);177 this.logger.warn(178 `Detected ${staticRunPlans.length} static mutants (${percentage(179 staticRunPlans.length / runPlans.length180 )}% of total) that are estimated to take ${percentage(181 relativeTimeForStaticMutants182 )}% of the time running the tests!\n You might want to enable "ignoreStatic" to ignore these static mutants for your next run. \n For more information about static mutants visit: https://stryker-mutator.io/docs/mutation-testing-elements/static-mutants.\n (disable "${optionsPath(183 'warnings',184 'slow'185 )}" to ignore this warning)`186 );187 }188 }189 }190 private async incrementalDiff(currentMutants: readonly Mutant[]): Promise<readonly Mutant[]> {191 const { incrementalReport } = this.project;192 if (incrementalReport) {193 const currentFiles = await this.readAllOriginalFiles(194 currentMutants,195 this.testCoverage.testsById.values(),196 Object.keys(incrementalReport.files),197 Object.keys(incrementalReport.testFiles ?? {})198 );199 const diffedMutants = this.incrementalDiffer.diff(currentMutants, this.testCoverage, incrementalReport, currentFiles);200 return diffedMutants;201 }202 return currentMutants;203 }204 private async readAllOriginalFiles(205 ...thingsWithFileNamesOrFileNames: Array<Iterable<string | { fileName?: string }>>206 ): Promise<Map<string, string>> {207 const uniqueFileNames = [208 ...new Set(209 thingsWithFileNamesOrFileNames210 .flatMap((container) => [...container].map((thing) => (typeof thing === 'string' ? thing : thing.fileName)))211 .filter(notEmpty)212 .map((fileName) => path.resolve(fileName))213 ),214 ];215 const result = await Promise.all(216 uniqueFileNames.map(async (fileName) => {217 const originalContent = await this.project.files.get(fileName)?.readOriginal();218 if (originalContent) {219 return [toRelativeNormalizedFileName(fileName), originalContent] as const;220 } else {221 return undefined;222 }223 })224 );225 return new Map(result.filter(notEmpty));226 }227}228function calculateTotalTime(testResults: Iterable<TestResult>): number {229 let total = 0;230 for (const test of testResults) {231 total += test.timeSpentMs;232 }233 return total;234}235function toTestIds(testResults: Iterable<TestResult>): string[] {236 const result = [];237 for (const test of testResults) {238 result.push(test.id);239 }240 return result;241}242export function isEarlyResult(mutantPlan: MutantTestPlan): mutantPlan is MutantEarlyResultPlan {243 return mutantPlan.plan === PlanKind.EarlyResult;244}245export function isRunPlan(mutantPlan: MutantTestPlan): mutantPlan is MutantRunPlan {246 return mutantPlan.plan === PlanKind.Run;...
recurring.js
Source:recurring.js
...42 intervalCount: 1,43 });44 console.log('edited recurring schedule:', editedSchedule);45}46async function runPlans() {47 const createdPlan = await r.createPlan({48 businessId: exampleBusinessId,49 referenceId: exampleReferenceId,50 customerId: exampleCustomerId,51 recurringAction: 'PAYMENT',52 currency: 'IDR',53 amount: 1000,54 paymentMethods: [55 {56 paymentMethodId: examplePaymentMethodId,57 rank: 1,58 },59 ],60 scheduleId: scheduleId,61 immediateActionType: null,62 notification_config: {63 recurring_created: ['SMS'],64 recurring_succeeded: ['SMS'],65 recurring_failed: ['SMS'],66 },67 failedCycleAction: 'STOP',68 metadata: null,69 });70 planId = createdPlan.id;71 console.log('created recurring plan:', createdPlan);72 const plan = await r.getPlan({73 id: createdPlan.id,74 businessId: exampleBusinessId,75 });76 console.log('recurring plan:', plan);77 const editedPlan = await r.editPlan({78 id: plan.id,79 businessId: exampleBusinessId,80 amount: 1000,81 });82 console.log('edited recurring plan:', editedPlan);83 /** This is commented out to allow cycle "edit" and "cancel" actions */84 // const deactivatedPlan = await r.deactivatePlan({85 // id: plan.id,86 // businessId: exampleBusinessId,87 // });88 // console.log('deactivated recurring plan:', deactivatedPlan);89}90async function runCycles() {91 const response = await r.getAllCycles({92 planId: planId,93 businessId: exampleBusinessId,94 limit: 2,95 });96 console.log('recurring cycles:', response.data);97 console.log('has more recurring cycles:', response.has_more);98 const cycle = await r.getCycle({99 id: response.data[0].id,100 planId: planId,101 businessId: exampleBusinessId,102 });103 console.log('recurring cycle:', cycle);104 const editedCycle = await r.editCycle({105 id: cycle.id,106 planId: planId,107 businessId: exampleBusinessId,108 amount: 1000,109 currency: 'IDR',110 scheduledTimestamp: scheduledTimestamp,111 });112 console.log('edited recurring cycle:', editedCycle);113 const canceledCycle = await r.cancelCycle({114 id: cycle.id,115 planId: cycle.plan_id,116 businessId: exampleBusinessId,117 });118 console.log('canceled recurring cycle:', canceledCycle);119}120(async function() {121 try {122 await runSchedules();123 await runPlans();124 await runCycles();125 } catch (e) {126 console.error(e);127 process.exit(1);128 }...
runPlan.js
Source:runPlan.js
1import { toLocalDate } from "../../date";2import { maestroClient } from "../../services/maestroApi";3const runPlanObjectMapper = (runPlan) => ({4 id: runPlan.id,5 runPlanFile: runPlan.run_plan_file,6 title: runPlan.title,7 createdAt: toLocalDate(runPlan.created_at),8 updatedAt: toLocalDate(runPlan.updated_at)9});10export const fetchRunPlans = async () => {11 const res = await maestroClient.get("/api/run_plans");12 const runPlans = res.data.map(runPlanObjectMapper);13 return runPlans;14};15/**16 *17 * @param {string} runPlanId18 * @returns runPlan object19 */20export const fetchRunPlanById = async (runPlanId) => {21 const res = await maestroClient.get(`/api/run_plan/${runPlanId}`);22 const runPlans = runPlanObjectMapper(res.data);23 return runPlans;24};25/**26 *27 * @param {String} title Title for test plan28 * @param {file} file test plan Jmeter jmx file29 * @returns {runPlan} test plan object with id30 */31export const createRunPlan = async ({ title, runPlan }) => {32 const formData = new FormData();33 formData.append("run_plan_file", runPlan);34 formData.append("title", title);35 const config = {36 headers: {37 "content-type": "multipart/form-data"38 }39 };40 const res = await maestroClient.post(`/api/run_plan`, formData, config);41 const runPlanObject = runPlanObjectMapper(res.data);42 return runPlanObject;...
Using AI Code Generation
1var runPlans = require('stryker-parent').runPlans;2var config = require('./stryker.conf.js');3runPlans(config);4module.exports = function (config) {5 config.set({6 });7};8var runPlans = require('stryker-parent').runPlans;9var config = require('../../stryker.conf.js');10runPlans(config);11var runPlans = require('stryker-parent').runPlans;12var config = require('../../stryker.conf.js');13runPlans(config);14var runPlans = require('stryker-parent').runPlans;15var config = require('../../stryker.conf.js');16runPlans(config);
Using AI Code Generation
1var Stryker = require('stryker-parent');2var stryker = new Stryker();3stryker.runPlans();4var Stryker = require('stryker-parent');5var stryker = new Stryker();6stryker.runPlans();7var Stryker = require('stryker-parent');8var stryker = new Stryker();9stryker.runPlans();10var Stryker = require('stryker-parent');11var stryker = new Stryker();12stryker.runPlans();13var Stryker = require('stryker-parent');14var stryker = new Stryker();15stryker.runPlans();16var Stryker = require('stryker-parent');17var stryker = new Stryker();18stryker.runPlans();19var Stryker = require('stryker-parent');20var stryker = new Stryker();21stryker.runPlans();22var Stryker = require('stryker-parent');23var stryker = new Stryker();24stryker.runPlans();25var Stryker = require('stryker-parent');26var stryker = new Stryker();27stryker.runPlans();28var Stryker = require('stryker-parent');29var stryker = new Stryker();30stryker.runPlans();31var Stryker = require('stryker-parent');32var stryker = new Stryker();33stryker.runPlans();
Using AI Code Generation
1var runPlans = require('stryker-parent').runPlans;2runPlans({ 3});4module.exports = function(config) {5 config.set({6 });7};8module.exports = function(config) {9 config.set({10 });11};12module.exports = function(config) {13 config.set({14 });15};16module.exports = function(config) {17 config.set({18 });19};20module.exports = function(config) {21 config.set({22 });23};24module.exports = function(config) {25 config.set({26 });27};28module.exports = function(config) {29 config.set({30 });31};32module.exports = function(config) {33 config.set({34 });35};36module.exports = function(config) {37 config.set({38 });39};40module.exports = function(config) {41 config.set({42 });43};44module.exports = function(config)
Using AI Code Generation
1var runPlans = require('stryker-parent').runPlans;2runPlans('test', 'test');3var runPlans = require('stryker-parent').runPlans;4runPlans('test', 'test');5var runPlans = require('stryker-parent').runPlans;6runPlans('test', 'test');7var runPlans = require('stryker-parent').runPlans;8runPlans('test', 'test');9var runPlans = require('stryker-parent').runPlans;10runPlans('test', 'test');11var runPlans = require('stryker-parent').runPlans;12runPlans('test', 'test');13var runPlans = require('stryker-parent').runPlans;14runPlans('test', 'test');15var runPlans = require('stryker-parent').runPlans;16runPlans('test', 'test');17var runPlans = require('stryker-parent').runPlans;18runPlans('test', 'test');
Using AI Code Generation
1var stryker = require('stryker-parent');2var path = require('path');3var fs = require('fs');4var test = require('./test');5var testFiles = fs.readdirSync(path.join(__dirname, 'test', 'unit'));6var testFiles = testFiles.map(function (file) {7 return path.join(__dirname, 'test', 'unit', file);8});9var config = {10 { pattern: 'src/**/*.js', mutated: true, included: false },11 { pattern: 'test/**/*.js', mutated: false, included: false }12};13stryker.runPlans(config).then(function (result) {14 console.log('Done!');15 process.exit(result.status);16});
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!!