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;...
Using AI Code Generation
1const runTimeRunPlans = require('stryker-parent').runTimeRunPlans;2const runTimeRunPlans = require('stryker-parent').runTimeRunPlans;3runTimeRunPlans('test.js');4const runTimeRunPlans = require('stryker-parent').runTimeRunPlans;5runTimeRunPlans('test.js');6const runTimeRunPlans = require('stryker-parent').runTimeRunPlans;7runTimeRunPlans('test.js');8const runTimeRunPlans = require('stryker-parent').runTimeRunPlans;9runTimeRunPlans('test.js');10const runTimeRunPlans = require('stryker-parent').runTimeRunPlans;11runTimeRunPlans('test.js');12const runTimeRunPlans = require('stryker-parent').runTimeRunPlans;13runTimeRunPlans('test.js');14const runTimeRunPlans = require('stryker-parent').runTimeRunPlans;15runTimeRunPlans('test.js');16const runTimeRunPlans = require('stryker-parent').runTimeRunPlans;17runTimeRunPlans('test.js');18const runTimeRunPlans = require('stryker-parent').runTimeRunPlans;19runTimeRunPlans('test.js');20const runTimeRunPlans = require('stryker-parent').runTimeRunPlans;21runTimeRunPlans('test.js');
Using AI Code Generation
1var stryker = require('stryker-parent');2var options = {3 karma: {4 config: {5 }6 }7};8var strykerApi = new stryker.api.Stryker(options);9strykerApi.runMutationTest().then(function (result) {10 console.log(result);11});12[2017-09-19 15:40:36.633] [ERROR] StrykerCli - SyntaxError: Unexpected token import13at exports.runInThisContext (vm.js:53:16)14at Module._compile (module.js:373:25)15at Object.Module._extensions..js (module.js:416:10)16at Module.load (module.js:343:32)17at Function.Module._load (module.js:300:12)18at Module.require (module.js:353:17)19at require (internal/module.js:12:17)20at Object.<anonymous> (/Users/*****/****/node_modules/stryker/src/Stryker.js:1:64)21at Module._compile (module.js:409:26)22at Object.Module._extensions..js (module.js:416:10)23at Module.load (module.js:343:32)24at Function.Module._load (module.js:300:12)25at Module.require (module.js:353:17)26at require (internal/module.js:12:17)27at Object.<anonymous> (/Users/*****/****/node_modules/stryker/src/index.js:1:65)28at Module._compile (module.js:409:26)29at Object.Module._extensions..js (module.js:416:10)30at Module.load (module.js:343:32)31at Function.Module._load (module
Using AI Code Generation
1const { runTimeRunPlans } = require('stryker-parent');2const { runTimeRunPlans } = require('stryker-parent');3const { runTimeRunPlans } = require('stryker-parent');4const { runTimeRunPlans } = require('stryker-parent');5const { runTimeRunPlans } = require('stryker-parent');6const { runTimeRunPlans } = require('stryker-parent');7const { runTimeRunPlans } = require('stryker-parent');8const { runTimeRunPlans } = require('stryker-parent');9const { runTimeRunPlans } = require('stryker-parent');10const { runTimeRunPlans } = require('stryker-parent');11const { runTimeRunPlans } = require('stryker-parent');12const { runTimeRunPlans } = require('stryker-parent');13const { runTimeRunPlans } = require('stryker-parent');14const { runTimeRunPlans } = require('stryker-parent');
Using AI Code Generation
1var stryker = require('stryker-parent');2var config = {3};4stryker.runTimeRunPlans(config).then(function(){5 console.log("done");6});7module.exports = function (config) {8 config.set({9 preprocessors: {10 },11 });12};13module.exports = function (config) {14 config.set({15 preprocessors: {16 },17 });18};19module.exports = function (config) {20 config.set({21 preprocessors: {22 },23 });24};25module.exports = function (config) {26 config.set({27 preprocessors: {28 },
Using AI Code Generation
1var Stryker = require('stryker-parent').Stryker;2var stryker = new Stryker();3stryker.runTimeRunPlans(1, 2, 3, 4, 5, 6);4var Stryker = require('./lib/Stryker');5module.exports = Stryker;6function Stryker() {7 this.runTimeRunPlans = function() {8 console.log(arguments);9 }10}11module.exports = Stryker;12module.exports = {13 output: {14 },15 module: {16 loaders: [{17 query: {18 }19 }]20 }21};22module.exports = function(config) {23 config.set({24 preprocessors: {25 },26 webpack: {27 output: {28 },29 module: {30 loaders: [{31 query: {32 }33 }]34 }35 },36 webpackMiddleware: {37 },38 })39};40import { expect } from 'chai';41import { add } from '../src/main.js';42describe('add', () => {43 it('
Using AI Code Generation
1const { runTimeRunPlans } = require('stryker-parent');2const { run } = require('stryker');3const { StrykerOptions } = require('stryker-api/core');4const { ConfigReader } = require('stryker-api/config');5const { getLogger } = require('stryker-api/logging');6const log = getLogger('test');7const strykerOptions = new StrykerOptions(new ConfigReader().readConfig());8const runPlans = runTimeRunPlans(strykerOptions);9run(strykerOptions, runPlans)10 .then(() => log.info('Done!'))11 .catch(error => {12 log.error('An error occurred', error);13 process.exitCode = 1;14 });
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!!