How to use mutantEarlyResultPlan 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

progress-reporter.spec.ts

Source:progress-reporter.spec.ts Github

copy

Full Screen

...36 sut.onMutationTestingPlanReady(37 factory.mutationTestingPlanReadyEvent({38 mutantPlans: [39 // Ignored mutant40 factory.mutantEarlyResultPlan({ mutant: factory.ignoredMutantTestCoverage({ id: '1' }) }),41 // Run test 1, takes 10ms42 factory.mutantRunPlan({43 mutant: factory.mutantTestCoverage({ id: '2' }),44 runOptions: factory.mutantRunOptions({ testFilter: ['1'] }),45 netTime: 10,46 }),47 // Run test 2, takes 5ms48 factory.mutantRunPlan({49 mutant: factory.mutantTestCoverage({ id: '3' }),50 runOptions: factory.mutantRunOptions({ testFilter: ['2'] }),51 netTime: 5,52 }),53 // Run all tests, takes 115ms54 factory.mutantRunPlan({55 mutant: factory.mutantTestCoverage({ id: '4' }),56 runOptions: factory.mutantRunOptions({ testFilter: undefined, reloadEnvironment: true }),57 netTime: 15,58 }),59 ],60 })61 );62 expect(progressBarConstructorStub).calledWithMatch(progressBarContent, { total: 115 + 5 + 10 });63 });64 });65 describe('onMutantTested()', () => {66 let progressBarTickTokens: any;67 beforeEach(() => {68 sut.onDryRunCompleted(69 factory.dryRunCompletedEvent({70 result: factory.completeDryRunResult({71 tests: [factory.testResult({ id: '1', timeSpentMs: 10 }), factory.testResult({ id: '2', timeSpentMs: 5 })],72 }),73 timing: factory.runTiming({ net: 15, overhead: 100 }),74 })75 );76 sut.onMutationTestingPlanReady(77 factory.mutationTestingPlanReadyEvent({78 mutantPlans: [79 // Ignored mutant80 factory.mutantEarlyResultPlan({ mutant: factory.ignoredMutantTestCoverage({ id: '1' }) }),81 // Run test 1, takes 10ms82 factory.mutantRunPlan({83 mutant: factory.mutantTestCoverage({ id: '2' }),84 runOptions: factory.mutantRunOptions({ testFilter: ['1'] }),85 netTime: 10,86 }),87 // Run test 2, takes 5ms88 factory.mutantRunPlan({89 mutant: factory.mutantTestCoverage({ id: '3' }),90 runOptions: factory.mutantRunOptions({ testFilter: ['2'] }),91 netTime: 5,92 }),93 // Run all tests, takes 115ms94 factory.mutantRunPlan({95 mutant: factory.mutantTestCoverage({ id: '4' }),96 runOptions: factory.mutantRunOptions({ testFilter: undefined, reloadEnvironment: true }),97 netTime: 15,98 }),99 ],100 })101 );102 });103 it('should tick the ProgressBar with 1 tested mutant, 0 survived when status is not "Survived"', () => {104 sut.onMutantTested(factory.killedMutantResult({ id: '2' }));105 progressBarTickTokens = { total: 130, tested: 1, survived: 0 };106 sinon.assert.calledWithMatch(progressBar.tick, 10, progressBarTickTokens);107 });108 it('should not tick the ProgressBar the result did not yield any ticks', () => {109 progressBar.total = 130;110 sut.onMutantTested(factory.ignoredMutantResult({ id: '1' })); // ignored mutant111 progressBarTickTokens = { total: 130, tested: 0, survived: 0 };112 sinon.assert.notCalled(progressBar.tick);113 sinon.assert.calledWithMatch(progressBar.render, progressBarTickTokens);114 });115 it('should tick the ProgressBar with 1 survived mutant when status is "Survived"', () => {116 sut.onMutantTested(factory.survivedMutantResult({ id: '4', static: true }));117 progressBarTickTokens = { total: 130, tested: 1, survived: 1 };118 sinon.assert.calledWithMatch(progressBar.tick, 115, progressBarTickTokens);119 });120 });121 describe('ProgressBar estimated time for 3 mutants', () => {122 beforeEach(() => {123 sut.onDryRunCompleted(124 factory.dryRunCompletedEvent({125 result: factory.completeDryRunResult({126 tests: [factory.testResult({ id: '1', timeSpentMs: 10 }), factory.testResult({ id: '2', timeSpentMs: 5 })],127 }),128 timing: factory.runTiming({ net: 15, overhead: 100 }),129 })130 );131 sut.onMutationTestingPlanReady(132 factory.mutationTestingPlanReadyEvent({133 mutantPlans: [134 // Ignored mutant135 factory.mutantEarlyResultPlan({ mutant: factory.ignoredMutantTestCoverage({ id: '1' }) }),136 // Run test 1, takes 10ms137 factory.mutantRunPlan({138 mutant: factory.mutantTestCoverage({ id: '2' }),139 runOptions: factory.mutantRunOptions({ testFilter: ['1'] }),140 netTime: 10,141 }),142 // Run test 2, takes 5ms143 factory.mutantRunPlan({144 mutant: factory.mutantTestCoverage({ id: '3' }),145 runOptions: factory.mutantRunOptions({ testFilter: ['2'] }),146 netTime: 5,147 }),148 // Run all tests, takes 115ms149 factory.mutantRunPlan({...

Full Screen

Full Screen

mutant-test-plan.ts

Source:mutant-test-plan.ts Github

copy

Full Screen

1import * as schema from 'mutation-testing-report-schema/api';2import { MutantRunOptions } from '../test-runner/index.js';3import { MutantTestCoverage } from './mutant.js';4/**5 * Represents a plan to test a mutant. Can either be an early result (an ignored mutant for example) or a plan to test a mutant in a test runner6 */7export type MutantTestPlan = MutantEarlyResultPlan | MutantRunPlan;8/**9 * The test plans that belong to a mutant.10 */11export enum PlanKind {12 /**13 * Early result plan, mutant does not have to be checked or run.14 */15 EarlyResult = 'EarlyResult',16 /**17 * Run plan, mutant will have to be checked and run.18 */19 Run = 'Run',20}21/**22 * Represents an mutant early result plan.23 */24export interface MutantEarlyResultPlan {25 plan: PlanKind.EarlyResult;26 /**27 * The mutant that already has a final status.28 */29 mutant: MutantTestCoverage & { status: schema.MutantStatus };30}31/**32 * Represents a mutant test plan.33 */34export interface MutantRunPlan {35 plan: PlanKind.Run;36 /**37 * The mutant that has to be tested.38 */39 mutant: MutantTestCoverage;40 /**41 * The run options that will be used to test this mutant42 */43 runOptions: MutantRunOptions;44 /**45 * Estimated net time to run this mutant when it would survive in ms (which should be the worst case).46 * This is used as input to calculate the runOptions.timeout47 */48 netTime: number;...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { mutantEarlyResultPlan } = require('stryker-parent');2mutantEarlyResultPlan();3const { mutantEarlyResultPlan } = require('stryker-parent');4mutantEarlyResultPlan();5module.exports = function(config) {6 config.set({7 });8};9module.exports = {10 mutantEarlyResultPlan: function() {11 console.log('Mutant Early Result Plan');12 }13};14const { mutantEarlyResultPlan } = require('./stryker-parent');15mutantEarlyResultPlan();16module.exports = function(config) {17 config.set({18 });19};20module.exports = {21 mutantEarlyResultPlan: function() {22 console.log('Mutant Early Result Plan');23 }24};

Full Screen

Using AI Code Generation

copy

Full Screen

1const { mutantEarlyResultPlan } = require('stryker-parent');2mutantEarlyResultPlan({3 jest: {4 config: require('./jest.config.js'),5 },6});7module.exports = {8};9{10}

Full Screen

Using AI Code Generation

copy

Full Screen

1const mutantEarlyResultPlan = require('stryker-parent').mutantEarlyResultPlan;2mutantEarlyResultPlan({3});4const mutantEarlyResultPlan = require('stryker-parent').mutantEarlyResultPlan;5mutantEarlyResultPlan({6});7const mutantEarlyResultPlan = require('stryker-parent').mutantEarlyResultPlan;8mutantEarlyResultPlan({9});10const mutantEarlyResultPlan = require('stryker-parent').mutantEarlyResultPlan;11mutantEarlyResultPlan({12});

Full Screen

Using AI Code Generation

copy

Full Screen

1const mutantEarlyResultPlan = require('stryker-parent').mutantEarlyResultPlan;2const result = mutantEarlyResultPlan('test');3console.log(result);4const mutantEarlyResultPlan = require('stryker-parent').mutantEarlyResultPlan;5const result = mutantEarlyResultPlan('test', 'testReason');6console.log(result);7const mutantEarlyResultPlan = require('stryker-parent').mutantEarlyResultPlan;8const result = mutantEarlyResultPlan('test', 'testReason', 'testDescription');9console.log(result);10const mutantEarlyResultPlan = require('stryker-parent').mutantEarlyResultPlan;11const result = mutantEarlyResultPlan('test', 'testReason', 'testDescription', 'testStatus');12console.log(result);13const mutantEarlyResultPlan = require('stryker-parent').mutantEarlyResultPlan;14const result = mutantEarlyResultPlan('test', 'testReason', 'testDescription', 'testStatus', 'testStatusDescription');15console.log(result);16const mutantEarlyResultPlan = require('stryker-parent').mutantEarlyResultPlan;17const result = mutantEarlyResultPlan('test', 'testReason', 'testDescription', 'testStatus',

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