How to use staticRunPlans method in stryker-parent

Best JavaScript code snippet using stryker-parent

mutant-test-planner.ts

Source:mutant-test-planner.ts Github

copy

Full Screen

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;...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const staticRunPlans = require('stryker-parent').staticRunPlans;2staticRunPlans([3 {4 },5 {6 }7]);8module.exports = function (config) {9 config.set({10 { pattern: 'src/**/*.js', mutated: true, included: false },11 });12};13{14}15module.exports = function(config) {16 config.set({17 });18};

Full Screen

Using AI Code Generation

copy

Full Screen

1const { staticRunPlans } = require('stryker-parent');2const { run } = require('stryker');3const runOptions = {4};5staticRunPlans(run, runOptions).then(result => {6 console.log(result);7});8const { staticRunPlans } = require('stryker-parent');9const { run } = require('stryker');10const runOptions = {11};12staticRunPlans(run, runOptions).then(result => {13 console.log(result);14});15const { staticRunPlans } = require('stryker-parent');16const { run } = require('stryker');17const runOptions = {18};19staticRunPlans(run, runOptions).then(result => {20 console.log(result);21});22const { staticRunPlans } = require('stryker-parent');23const { run } = require('stryker');24const runOptions = {25};26staticRunPlans(run, runOptions).then(result

Full Screen

Using AI Code Generation

copy

Full Screen

1const { staticRunPlans } = require('stryker-parent');2const path = require('path');3const plan = {4 config: {5 },6 testRunnerOptions: {7 mochaOptions: {8 }9 }10};11staticRunPlans({12 basePath: path.resolve(__dirname, 'test-projects', 'angular-1.x')13});14[2018-06-29 10:00:24.604] [INFO] Stryker - 0 Mutant(s) generated15[2018-06-29 10:00:24.604] [INFO] Stryker - 0 Mutant(s) tested (0 survived)16[2018-06-29 10:00:24.604] [INFO] Stryker - 0 Mutant(s) generated17[2018-06-29 10:00:24.604] [INFO] Stryker - 0 Mutant(s) tested (0 survived)18[2018-06-29 10:00:24.604] [INFO] Stryker - 0 Mutant(s) generated19[2018-06-29 10:00:24.604] [INFO] Stryker - 0 Mutant(s) tested (0 survived)

Full Screen

Using AI Code Generation

copy

Full Screen

1var stryker = require('stryker-parent');2var test = stryker.staticRunPlans({3});4console.log('test', test);5test.then(function (result) {6 console.log('result', result);7});8var stryker = require('stryker-parent');9var test = stryker.staticRunPlans({10});11console.log('test', test);12test.then(function (result) {13 console.log('result', result);14});15module.exports = function (config) {16 config.set({17 });18};19module.exports = function (config) {20 config.set({21 });22};23module.exports = function (config) {24 config.set({

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run stryker-parent automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful