How to use oldTestKeys method in stryker-parent

Best JavaScript code snippet using stryker-parent

incremental-differ.ts

Source:incremental-differ.ts Github

copy

Full Screen

1import path from 'path';2import { diff_match_patch as DiffMatchPatch } from 'diff-match-patch';3import chalk from 'chalk';4import { schema, Mutant, Position, Location, MutantStatus, StrykerOptions, FileDescriptions, MutateDescription } from '@stryker-mutator/api/core';5import { Logger } from '@stryker-mutator/api/logging';6import { TestResult, TestStatus } from '@stryker-mutator/api/test-runner';7import { I, normalizeFileName, normalizeLineEndings, notEmpty } from '@stryker-mutator/util';8import { TestDefinition } from 'mutation-testing-report-schema';9import { commonTokens } from '@stryker-mutator/api/plugin';10import { DiffChange, DiffStatisticsCollector } from './diff-statistics-collector.js';11import { TestCoverage } from './test-coverage.js';12/**13 * The 'diff match patch' high-performant 'diffing' of files.14 * @see https://github.com/google/diff-match-patch15 */16const diffMatchPatch = new DiffMatchPatch();17/**18 * This class is responsible for calculating the diff between a run and a previous run based on the incremental report.19 *20 * Since the ids of tests and mutants can differ across reports (they are only unique within 1 report), this class21 * identifies mutants and tests by attributes that make them unique:22 * - Mutant: file name, mutator name, location and replacement23 * - Test: test name, test file name (if present) and location (if present).24 *25 * We're storing these identifiers in local variables (maps and sets) as strings.26 * We should move to 'records' for these when they come available: https://github.com/tc39/proposal-record-tuple27 *28 * A mutant result from the previous run is reused if the following conditions were met:29 * - The location of the mutant refers to a piece of code that didn't change30 * - If mutant was killed:31 * - The culprit test wasn't changed32 * - If the mutant survived:33 * - No test was added34 *35 * It uses google's "diff-match-patch" project to calculate the new locations for tests and mutants, see link.36 * @link https://github.com/google/diff-match-patch37 */38export class IncrementalDiffer {39 public mutantStatisticsCollector: DiffStatisticsCollector | undefined;40 public testStatisticsCollector: DiffStatisticsCollector | undefined;41 private readonly mutateDescriptionByRelativeFileName: Map<string, MutateDescription>;42 public static inject = [commonTokens.logger, commonTokens.options, commonTokens.fileDescriptions] as const;43 constructor(private readonly logger: Logger, private readonly options: StrykerOptions, fileDescriptions: FileDescriptions) {44 this.mutateDescriptionByRelativeFileName = new Map(45 Object.entries(fileDescriptions).map(([name, description]) => [toRelativeNormalizedFileName(name), description.mutate])46 );47 }48 private isInMutatedScope(relativeFileName: string, mutant: schema.MutantResult): boolean {49 const mutate = this.mutateDescriptionByRelativeFileName.get(relativeFileName);50 return mutate === true || (Array.isArray(mutate) && mutate.some((range) => locationIncluded(range, mutant.location)));51 }52 public diff(53 currentMutants: readonly Mutant[],54 testCoverage: I<TestCoverage>,55 incrementalReport: schema.MutationTestResult,56 currentRelativeFiles: Map<string, string>57 ): readonly Mutant[] {58 const { files, testFiles } = incrementalReport;59 const mutantStatisticsCollector = new DiffStatisticsCollector();60 const testStatisticsCollector = new DiffStatisticsCollector();61 // Expose the collectors for unit testing purposes62 this.mutantStatisticsCollector = mutantStatisticsCollector;63 this.testStatisticsCollector = testStatisticsCollector;64 // Collect what we can reuse, while correcting for diff in the locations65 const reusableMutantsByKey = collectReusableMutantsByKey(this.logger);66 const { byId: oldTestsById, byKey: oldTestInfoByKey } = collectReusableTestInfo(this.logger);67 // Collect some helper maps and sets68 const { oldCoverageByMutantKey: oldCoverageTestKeysByMutantKey, oldKilledByMutantKey: oldKilledTestKeysByMutantKey } =69 collectOldKilledAndCoverageMatrix();70 const oldTestKeys = new Set([...oldTestsById.values()].map(({ key }) => key));71 const newTestKeys = new Set(72 [...testCoverage.testsById].map(([, test]) => testToIdentifyingKey(test, toRelativeNormalizedFileName(test.fileName)))73 );74 // Create a dictionary to more easily get test information75 const testInfoByKey = collectCurrentTestInfo();76 // Mark which tests are added77 for (const [key, { relativeFileName }] of testInfoByKey) {78 if (!oldTestKeys.has(key)) {79 testStatisticsCollector.count(relativeFileName, 'added');80 }81 }82 // Make sure that tests that didn't run this time around aren't forgotten83 for (const [84 testKey,85 {86 test: { name, location },87 relativeFileName,88 },89 ] of oldTestInfoByKey) {90 if (!testInfoByKey.has(testKey)) {91 const test: TestResult = {92 status: TestStatus.Success,93 id: testKey,94 name,95 startPosition: location?.start,96 timeSpentMs: 0,97 fileName: path.resolve(relativeFileName),98 };99 testInfoByKey.set(testKey, { test, relativeFileName: relativeFileName });100 testCoverage.addTest(test);101 }102 }103 // Done with preparations, time to map over the mutants104 let reusedMutantCount = 0;105 const currentMutantKeys = new Set<string>();106 const mutants = currentMutants.map((mutant) => {107 const relativeFileName = toRelativeNormalizedFileName(mutant.fileName);108 const mutantKey = mutantToIdentifyingKey(mutant, relativeFileName);109 currentMutantKeys.add(mutantKey);110 if (!mutant.status && !this.options.force) {111 const oldMutant = reusableMutantsByKey.get(mutantKey);112 if (oldMutant) {113 const coveringTests = testCoverage.forMutant(mutant.id);114 const killedByTestKeys = oldKilledTestKeysByMutantKey.get(mutantKey);115 if (mutantCanBeReused(mutant, oldMutant, mutantKey, coveringTests, killedByTestKeys)) {116 reusedMutantCount++;117 const { status, statusReason, testsCompleted } = oldMutant;118 return {119 ...mutant,120 status,121 statusReason,122 testsCompleted,123 coveredBy: [...(coveringTests ?? [])].map(({ id }) => id),124 killedBy: testKeysToId(killedByTestKeys),125 };126 }127 } else {128 mutantStatisticsCollector.count(relativeFileName, 'added');129 }130 }131 return mutant;132 });133 // Make sure that old mutants that didn't run this time around aren't forgotten134 for (const [mutantKey, oldResult] of reusableMutantsByKey) {135 // Do an additional check to see if the mutant is in mutated range.136 //137 // For example:138 // ```diff139 // - return a || b;140 // + return a && b;141 // ```142 // The conditional expression mutator here decides to _not_ mutate b to `false` the second time around. (even though the text of "b" itself didn't change)143 // Not doing this additional check would result in a sticky mutant that is never removed144 if (!currentMutantKeys.has(mutantKey) && !this.isInMutatedScope(oldResult.relativeFileName, oldResult)) {145 const coverage = oldCoverageTestKeysByMutantKey.get(mutantKey) ?? [];146 const killed = oldKilledTestKeysByMutantKey.get(mutantKey) ?? [];147 const coveredBy = testKeysToId(coverage);148 const killedBy = testKeysToId(killed);149 const reusedMutant = {150 ...oldResult,151 id: mutantKey,152 fileName: path.resolve(oldResult.relativeFileName),153 replacement: oldResult.replacement ?? oldResult.mutatorName,154 coveredBy,155 killedBy,156 };157 mutants.push(reusedMutant);158 testCoverage.addCoverage(reusedMutant.id, coveredBy);159 }160 }161 if (this.logger.isInfoEnabled()) {162 const testInfo = testCoverage.hasCoverage ? `\n\tTests:\t\t${testStatisticsCollector.createTotalsReport()}` : '';163 this.logger.info(164 `Incremental report:\n\tMutants:\t${mutantStatisticsCollector.createTotalsReport()}` +165 testInfo +166 `\n\tResult:\t\t${chalk.yellowBright(reusedMutantCount)} of ${currentMutants.length} mutant result(s) are reused.`167 );168 }169 if (this.logger.isDebugEnabled()) {170 const lineSeparator = '\n\t\t';171 const noChanges = 'No changes';172 const detailedMutantSummary = `${lineSeparator}${mutantStatisticsCollector.createDetailedReport().join(lineSeparator) || noChanges}`;173 const detailedTestsSummary = `${lineSeparator}${testStatisticsCollector.createDetailedReport().join(lineSeparator) || noChanges}`;174 this.logger.debug(`Detailed incremental report:\n\tMutants: ${detailedMutantSummary}\n\tTests: ${detailedTestsSummary}`);175 }176 return mutants;177 function testKeysToId(testKeys: Iterable<string> | undefined) {178 return [...(testKeys ?? [])]179 .map((id) => testInfoByKey.get(id))180 .filter(notEmpty)181 .map(({ test: { id } }) => id);182 }183 function collectReusableMutantsByKey(log: Logger) {184 return new Map(185 Object.entries(files).flatMap(([fileName, oldFile]) => {186 const relativeFileName = toRelativeNormalizedFileName(fileName);187 const currentFileSource = currentRelativeFiles.get(relativeFileName);188 if (currentFileSource) {189 log.trace('Diffing %s', relativeFileName);190 const { results, removeCount } = performFileDiff(oldFile.source, currentFileSource, oldFile.mutants);191 mutantStatisticsCollector.count(relativeFileName, 'removed', removeCount);192 return results.map((m) => [193 mutantToIdentifyingKey(m, relativeFileName),194 {195 ...m,196 relativeFileName,197 },198 ]);199 }200 mutantStatisticsCollector.count(relativeFileName, 'removed', oldFile.mutants.length);201 // File has since been deleted, these mutants are not reused202 return [];203 })204 );205 }206 function collectReusableTestInfo(log: Logger) {207 const byId = new Map<string, { relativeFileName: string; test: TestDefinition; key: string }>();208 const byKey = new Map<string, TestInfo>();209 Object.entries(testFiles ?? {}).forEach(([fileName, oldTestFile]) => {210 const relativeFileName = toRelativeNormalizedFileName(fileName);211 const currentFileSource = currentRelativeFiles.get(relativeFileName);212 if (currentFileSource !== undefined && oldTestFile.source !== undefined) {213 log.trace('Diffing %s', relativeFileName);214 const locatedTests = closeLocations(oldTestFile);215 const { results, removeCount } = performFileDiff(oldTestFile.source, currentFileSource, locatedTests);216 testStatisticsCollector.count(relativeFileName, 'removed', removeCount);217 results.forEach((test) => {218 const key = testToIdentifyingKey(test, relativeFileName);219 const testInfo = { key, test, relativeFileName };220 byId.set(test.id, testInfo);221 byKey.set(key, testInfo);222 });223 } else {224 // No sources to compare, we should do our best with the info we do have225 oldTestFile.tests.map((test) => {226 const key = testToIdentifyingKey(test, relativeFileName);227 const testInfo = { key, test, relativeFileName };228 byId.set(test.id, testInfo);229 byKey.set(key, testInfo);230 });231 }232 });233 return { byId, byKey };234 }235 function collectOldKilledAndCoverageMatrix() {236 const oldCoverageByMutantKey = new Map<string, Set<string>>();237 const oldKilledByMutantKey = new Map<string, Set<string>>();238 for (const [key, mutant] of reusableMutantsByKey) {239 const killedRow = new Set(mutant.killedBy?.map((testId) => oldTestsById.get(testId)?.key).filter(notEmpty));240 const coverageRow = new Set(mutant.coveredBy?.map((testId) => oldTestsById.get(testId)?.key).filter(notEmpty));241 killedRow.forEach((killed) => coverageRow.add(killed));242 oldCoverageByMutantKey.set(key, coverageRow);243 oldKilledByMutantKey.set(key, killedRow);244 }245 return { oldCoverageByMutantKey, oldKilledByMutantKey };246 }247 function collectCurrentTestInfo() {248 const byTestKey = new Map<string, { relativeFileName: string; test: TestResult }>();249 for (const testResult of testCoverage.testsById.values()) {250 const relativeFileName = toRelativeNormalizedFileName(testResult.fileName);251 const key = testToIdentifyingKey(testResult, relativeFileName);252 const info = { relativeFileName, test: testResult, key: key };253 byTestKey.set(key, info);254 }255 return byTestKey;256 }257 function mutantCanBeReused(258 mutant: Mutant,259 oldMutant: schema.MutantResult,260 mutantKey: string,261 coveringTests: ReadonlySet<TestResult> | undefined,262 oldKillingTests: Set<string> | undefined263 ): boolean {264 if (!testCoverage.hasCoverage) {265 // This is the best we can do when the test runner didn't report coverage.266 // We assume that all mutant test results can be reused,267 // End users can use --force to force retesting of certain mutants268 return true;269 }270 if (oldMutant.status === MutantStatus.Ignored) {271 // Was previously ignored, but not anymore, we need to run it now272 return false;273 }274 const testsDiff = diffTestCoverage(mutant.id, oldCoverageTestKeysByMutantKey.get(mutantKey), coveringTests);275 if (oldMutant.status === MutantStatus.Killed) {276 if (oldKillingTests) {277 for (const killingTest of oldKillingTests) {278 if (testsDiff.get(killingTest) === 'same') {279 return true;280 }281 }282 }283 // Killing tests has changed or no longer exists284 return false;285 }286 for (const action of testsDiff.values()) {287 if (action === 'added') {288 // A non-killed mutant got a new test, we need to run it289 return false;290 }291 }292 // A non-killed mutant did not get new tests, no need to rerun it293 return true;294 }295 /**296 * Determines if there is a diff between old test coverage and new test coverage.297 */298 function diffTestCoverage(299 mutantId: string,300 oldCoveringTestKeys: Set<string> | undefined,301 newCoveringTests: ReadonlySet<TestResult> | undefined302 ): Map<string, DiffAction> {303 const result = new Map<string, DiffAction>();304 if (newCoveringTests) {305 for (const newTest of newCoveringTests) {306 const key = testToIdentifyingKey(newTest, toRelativeNormalizedFileName(newTest.fileName));307 result.set(key, oldCoveringTestKeys?.has(key) ? 'same' : 'added');308 }309 }310 if (oldCoveringTestKeys) {311 const isStatic = testCoverage.hasStaticCoverage(mutantId);312 for (const oldTestKey of oldCoveringTestKeys) {313 if (!result.has(oldTestKey)) {314 // Static mutants might not have covering tests, but the test might still exist315 if (isStatic && newTestKeys.has(oldTestKey)) {316 result.set(oldTestKey, 'same');317 } else {318 result.set(oldTestKey, 'removed');319 }320 }321 }322 }323 return result;324 }325 }326}327/**328 * Finds the diff of mutants and tests. Removes mutants / tests that no longer exist (changed or removed). Updates locations of mutants or tests that do still exist.329 * @param oldCode The old code to use for the diff330 * @param newCode The new (current) code to use for the diff331 * @param items The mutants or tests to be looked . These will be treated as immutable.332 * @returns A list of items with updated locations, without items that are changed.333 */334function performFileDiff<T extends { location: Location }>(oldCode: string, newCode: string, items: T[]): { results: T[]; removeCount: number } {335 const oldSourceNormalized = normalizeLineEndings(oldCode);336 const currentSrcNormalized = normalizeLineEndings(newCode);337 const diffChanges = diffMatchPatch.diff_main(oldSourceNormalized, currentSrcNormalized);338 const toDo = new Set(items.map((m) => ({ ...m, location: deepClone(m.location) })));339 const [added, removed] = [1, -1];340 const done: T[] = [];341 const currentPosition: Position = { column: 0, line: 0 };342 let removeCount = 0;343 for (const [change, text] of diffChanges) {344 if (toDo.size === 0) {345 // There are more changes, but nothing left to update.346 break;347 }348 const offset = calculateOffset(text);349 if (change === added) {350 for (const test of toDo) {351 const { location } = test;352 if (gte(currentPosition, location.start) && gte(location.end, currentPosition)) {353 // This item cannot be reused, code was added here354 removeCount++;355 toDo.delete(test);356 } else {357 locationAdd(location, offset, currentPosition.line === location.start.line);358 }359 }360 positionMove(currentPosition, offset);361 } else if (change === removed) {362 for (const item of toDo) {363 const {364 location: { start },365 } = item;366 const endOffset = positionMove({ ...currentPosition }, offset);367 if (gte(endOffset, start)) {368 // This item cannot be reused, the code it covers has changed369 removeCount++;370 toDo.delete(item);371 } else {372 locationAdd(item.location, negate(offset), currentPosition.line === start.line);373 }374 }375 } else {376 positionMove(currentPosition, offset);377 toDo.forEach((item) => {378 const { end } = item.location;379 if (gte(currentPosition, end)) {380 // We're done with this item, it can be reused381 toDo.delete(item);382 done.push(item);383 }384 });385 }386 }387 done.push(...toDo);388 return { results: done, removeCount };389}390/**391 * A greater-than-equals implementation for positions392 */393function gte(a: Position, b: Position) {394 return a.line > b.line || (a.line === b.line && a.column >= b.column);395}396function locationIncluded(haystack: Location, needle: Location) {397 const startIncluded = gte(needle.start, haystack.start);398 const endIncluded = gte(haystack.end, needle.end);399 return startIncluded && endIncluded;400}401function deepClone(loc: Location): Location {402 return { start: { ...loc.start }, end: { ...loc.end } };403}404/**405 * Reduces a mutant to a string that identifies the mutant across reports.406 * Consists of the relative file name, mutator name, replacement, and location407 */408function mutantToIdentifyingKey(409 { mutatorName, replacement, location: { start, end } }: Pick<Mutant, 'location' | 'mutatorName'> & { replacement?: string },410 relativeFileName: string411) {412 return `${relativeFileName}@${start.line}:${start.column}-${end.line}:${end.column}\n${mutatorName}: ${replacement}`;413}414function testToIdentifyingKey(415 { name, location, startPosition }: Pick<schema.TestDefinition, 'location' | 'name'> & Pick<TestResult, 'startPosition'>,416 relativeFileName: string | undefined417) {418 startPosition = startPosition ?? location?.start ?? { line: 0, column: 0 };419 return `${relativeFileName}@${startPosition.line}:${startPosition.column}\n${name}`;420}421export function toRelativeNormalizedFileName(fileName: string | undefined): string {422 return normalizeFileName(path.relative(process.cwd(), fileName ?? ''));423}424function calculateOffset(text: string): Position {425 const pos: Position = { line: 0, column: 0 };426 for (const char of text) {427 if (char === '\n') {428 pos.line++;429 pos.column = 0;430 } else {431 pos.column++;432 }433 }434 return pos;435}436function positionMove(pos: Position, diff: Position): Position {437 pos.line += diff.line;438 if (diff.line === 0) {439 pos.column += diff.column;440 } else {441 pos.column = diff.column;442 }443 return pos;444}445function locationAdd({ start, end }: Location, { line, column }: Position, currentLine: boolean) {446 start.line += line;447 if (currentLine) {448 start.column += column;449 }450 end.line += line;451 if (line === 0 && currentLine) {452 end.column += column;453 }454}455function negate({ line, column }: Position): Position {456 return { line: -1 * line, column: -1 * column };457}458interface TestInfo {459 relativeFileName: string;460 test: TestDefinition;461 key: string;462}463type DiffAction = DiffChange | 'same';464/**465 * Sets the end position of each test to the start position of the next test.466 * This is an educated guess and necessary.467 * If a test has no location, it is assumed it spans the entire file (line 0 to Infinity)468 *469 * Knowing the end location of tests is necessary in order to know if the test was changed.470 */471function closeLocations(testFile: schema.TestFile): LocatedTest[] {472 const locatedTests: LocatedTest[] = [];473 const openEndedTests: OpenEndedTest[] = [];474 testFile.tests.forEach((test) => {475 if (testHasLocation(test)) {476 if (isClosed(test)) {477 locatedTests.push(test);478 } else {479 openEndedTests.push(test);480 }481 } else {482 locatedTests.push({ ...test, location: { start: { line: 0, column: 0 }, end: { line: Number.POSITIVE_INFINITY, column: 0 } } });483 }484 });485 if (openEndedTests.length) {486 // Sort the opened tests in order to close their locations487 openEndedTests.sort((a, b) => a.location.start.line - b.location.start.line);488 const startPositions = uniqueStartPositions(openEndedTests);489 let currentPositionIndex = 0;490 let currentPosition = startPositions[currentPositionIndex];491 openEndedTests.forEach((test) => {492 if (currentPosition && test.location.start.line === currentPosition.line && test.location.start.column === currentPosition.column) {493 currentPositionIndex++;494 currentPosition = startPositions[currentPositionIndex];495 }496 if (currentPosition) {497 locatedTests.push({ ...test, location: { start: test.location.start, end: currentPosition } });498 }499 });500 // Don't forget about the last test501 const lastTest = openEndedTests[openEndedTests.length - 1];502 locatedTests.push({ ...lastTest, location: { start: lastTest.location.start, end: { line: Number.POSITIVE_INFINITY, column: 0 } } });503 }504 return locatedTests;505}506/**507 * Determines the unique start positions of a sorted list of tests in order508 */509function uniqueStartPositions(sortedTests: OpenEndedTest[]) {510 let current: Position | undefined;511 const startPositions = sortedTests.reduce<Position[]>((collector, { location: { start } }) => {512 if (!current || current.line !== start.line || current.column !== start.column) {513 current = start;514 collector.push(current);515 }516 return collector;517 }, []);518 return startPositions;519}520function testHasLocation(test: schema.TestDefinition): test is OpenEndedTest {521 return !!test.location?.start;522}523function isClosed(test: Required<schema.TestDefinition>): test is LocatedTest {524 return !!test.location.end;525}526type LocatedTest = schema.TestDefinition & { location: Location };...

Full Screen

Full Screen

release.js

Source:release.js Github

copy

Full Screen

1//2// mdn-bcd-collector: release.js3// Script to perform a new mdn-bcd-collector release4//5// © Gooborg Studios, Google LLC6// See the LICENSE file for copyright details7//8import chalk from 'chalk-template';9import enquirer from 'enquirer';10import esMain from 'es-main';11import fs from 'fs-extra';12import {Listr} from 'listr2';13import prettier from 'prettier';14import yargs from 'yargs';15import {hideBin} from 'yargs/helpers';16import {exec} from './scripts.js';17const currentVersion = (18 await fs.readJson(new URL('./package.json', import.meta.url))19).version;20const prepare = () => {21 return [22 {23 title: 'Checking for Git',24 task: () => {25 try {26 exec('git --version');27 } catch (e) {28 throw new Error(29 chalk`{red This script depends on {bold git}. Please {bold install} git using the following instructions:} {blue https://git-scm.com/book/en/v2/Getting-Started-Installing-Git}`30 );31 }32 }33 },34 {35 title: 'Checking for GitHub CLI',36 task: () => {37 try {38 exec('gh --version');39 } catch (e) {40 throw new Error(41 chalk`{red This script depends on the {bold GitHub CLI}. Please {bold install} the CLI using the following instructions:} {blue https://cli.github.com/}`42 );43 }44 },45 skip: (ctx) => ctx.skipPR46 },47 {48 title: 'Checking git status',49 task: () => {50 const changes = exec('git status -s');51 if (changes.length) {52 throw new Error(53 chalk`{red You currently have {bold uncommitted changes}. Please {bold commit} or {bold stash} your changes and try again.}`54 );55 }56 }57 },58 {59 title: 'Fetching from remote',60 task: () => exec('git fetch --all'),61 skip: (ctx) => ctx.skipFetch62 }63 ];64};65const getNewVersion = async (ctx, task) => {66 const versionParts = currentVersion.split('.').map((x) => Number(x));67 const newVersions = [68 `${versionParts[0] + 1}.0.0`,69 `${versionParts[0]}.${versionParts[1] + 1}.0`,70 `${versionParts[0]}.${versionParts[1]}.${versionParts[2] + 1}`71 ];72 if (ctx.skipPrompt) {73 ctx.newVersion = newVersions[2];74 return;75 }76 ctx.newVersion = await task.prompt([77 {78 type: 'select',79 name: 'newVersion',80 message: 'How should we bump the version?',81 choices: [82 {83 message: chalk`Major {blue (${newVersions[0]})}`,84 name: newVersions[0]85 },86 {87 message: chalk`Minor {blue (${newVersions[1]})}`,88 name: newVersions[1]89 },90 {91 message: chalk`Patch {blue (${newVersions[2]})}`,92 name: newVersions[2]93 },94 {95 message: chalk`{yellow Cancel}`,96 name: 'cancel'97 }98 ],99 initial: 2100 }101 ]);102 if (ctx.newVersion === 'cancel') {103 throw new Error(chalk`{yellow Release cancelled by user}`);104 }105};106const simplifyTestChangesList = (el, _, list) => {107 const parts = el.split('.');108 let p = '';109 for (let i = 0; i < parts.length - 1; i++) {110 p += (i > 0 ? '.' : '') + parts[i];111 if (list.includes(p)) {112 return false;113 }114 }115 return true;116};117const getTestChanges = () => {118 return [119 {120 title: 'Checkout last release',121 task: async () => {122 exec(`git checkout v${currentVersion}`);123 exec('npm install');124 }125 },126 {127 title: 'Build tests from last release',128 task: async () => {129 exec('npm run build');130 await fs.rename(131 new URL('./tests.json', import.meta.url),132 new URL('./tests.old.json', import.meta.url)133 );134 }135 },136 {137 title: 'Checkout current release',138 task: async () => {139 // npm install or build could have resulted in local changes, use140 // --force to throw those away.141 exec('git checkout --force origin/main');142 exec('npm install');143 }144 },145 {146 title: 'Build tests from current release',147 task: () => exec('npm run build')148 },149 {150 title: 'Compare tests',151 task: async (ctx) => {152 const oldTests = await fs.readJson(153 new URL('./tests.old.json', import.meta.url)154 );155 const newTests = await fs.readJson(156 new URL('./tests.json', import.meta.url)157 );158 const oldTestKeys = Object.keys(oldTests);159 const newTestKeys = Object.keys(newTests);160 const added = newTestKeys161 .filter((k) => !oldTestKeys.includes(k))162 .filter(simplifyTestChangesList);163 const removed = oldTestKeys164 .filter((k) => !newTestKeys.includes(k))165 .filter(simplifyTestChangesList);166 let changed = [];167 for (const t of newTestKeys.filter((k) => oldTestKeys.includes(k))) {168 if (oldTests[t].code != newTests[t].code) {169 changed.push(t);170 }171 }172 changed = changed.filter(simplifyTestChangesList);173 ctx.testChanges = '\n';174 if (added.length) {175 ctx.testChanges +=176 '#### Added\n\n' + added.map((x) => '- ' + x).join('\n') + '\n';177 }178 if (removed.length) {179 ctx.testChanges +=180 '#### Removed\n\n' + removed.map((x) => '- ' + x).join('\n') + '\n';181 }182 if (changed.length) {183 ctx.testChanges +=184 '#### Changed\n\n' + changed.map((x) => '- ' + x).join('\n') + '\n';185 }186 }187 },188 {189 title: 'Cleanup',190 task: async () =>191 await fs.rm(new URL('./tests.old.json', import.meta.url))192 }193 ];194};195const getGitChanges = async (ctx) => {196 const commits = String(197 exec(`git log --pretty=format:%s v${currentVersion}..origin/main`)198 ).split('\n');199 ctx.commits = commits200 .filter((summary) => !summary.startsWith('Bump '))201 .map(202 (summary) =>203 `- ${summary.replaceAll('<', '&lt;').replaceAll('>', '&gt;')}`204 )205 .map((summary) =>206 // Link to pull requests207 summary.replace(208 /\(#(\d+)\)/g,209 '([#$1](https://github.com/foolip/mdn-bcd-collector/pull/$1))'210 )211 )212 .join('\n');213};214const doChangelogUpdate = async (ctx) => {215 const filepath = new URL('./CHANGELOG.md', import.meta.url);216 const changelog = await fs.readFile(filepath, 'utf8');217 const idx = changelog.indexOf('##');218 let newChangelog =219 changelog.substring(0, idx) +220 `## v${ctx.newVersion}\n\n` +221 (ctx.testChanges === '\n' ? '' : '### Test Changes\n' + ctx.testChanges) +222 '\n### Commits\n\n' +223 ctx.commits +224 '\n\n' +225 changelog.substring(idx, changelog.length);226 newChangelog = prettier.format(newChangelog, {parser: 'markdown'});227 await fs.writeFile(filepath, newChangelog, 'utf8');228};229const doVersionBump = async (newVersion) => {230 exec(`npm version --no-git-tag-version ${newVersion}`);231};232const prepareBranch = async (ctx) => {233 ctx.branchName = `release-${ctx.newVersion}`;234 // Create and checkout branch235 exec(`git branch ${ctx.branchName}`);236 exec(`git checkout ${ctx.branchName}`);237 // Commit238 exec('git add package.json package-lock.json CHANGELOG.md');239 exec(240 `git commit -m "Release ${ctx.newVersion}" -m "Generated by release.js."`241 );242};243const createPR = async (ctx) => {244 exec(`git push --set-upstream origin ${ctx.branchName}`);245 exec('gh pr create -f');246};247const main = async () => {248 const {argv} = yargs(hideBin(process.argv))249 .parserConfiguration({250 'boolean-negation': false251 })252 .option('no-fetch', {253 describe: "Don't fetch remote",254 type: 'boolean',255 default: false256 })257 .option('no-prompt', {258 describe: "Don't prompt about anything, assume defaults",259 type: 'boolean',260 default: false261 })262 .option('no-pr', {263 describe: "Don't create a pull request",264 type: 'boolean',265 default: false266 });267 const tasks = new Listr(268 [269 {270 title: 'Check prerequesites',271 task: (_, task) => task.newListr(prepare())272 },273 {274 title: 'Get new version number',275 task: getNewVersion276 },277 {278 title: 'Get test changes',279 task: (_, task) => task.newListr(getTestChanges())280 },281 {282 title: 'Get commits',283 task: getGitChanges284 },285 {286 title: 'Update changelog',287 task: doChangelogUpdate288 },289 {290 title: 'Bump version number',291 task: async (ctx) => await doVersionBump(ctx.newVersion)292 },293 {294 title: 'Get confirmation to continue',295 task: async (ctx, task) => {296 const confirm = await task.prompt([297 {298 type: 'confirm',299 name: 'confirm',300 message: `Ready to release ${ctx.newVersion}?`,301 initial: true302 }303 ]);304 if (!confirm) {305 throw new Error(306 chalk`{yellow Release cancelled by user, reverting package[-lock.json] changes (changelog retained)}`307 );308 }309 },310 rollback: async () => await doVersionBump(currentVersion),311 skip: (ctx) => ctx.skipPrompt312 },313 {314 title: 'Prepare release branch',315 task: prepareBranch316 },317 {318 title: 'Create pull request',319 task: createPR,320 skip: (ctx) => ctx.skipPR321 }322 ],323 {324 showErrorMessage: true,325 // Mitigates https://github.com/cenk1cenk2/listr2/issues/631326 injectWrapper: {enquirer},327 ctx: {328 skipFetch: argv['no-fetch'],329 skipPrompt: argv['no-prompt'],330 skipPR: argv['no-pr']331 }332 }333 );334 try {335 await tasks.run();336 } catch (e) {337 console.error(e);338 }339 // Restore original head when finished340 try {341 exec('git switch -');342 } catch (e) {343 // Don't worry if the command fails344 }345};346/* c8 ignore start */347if (esMain(import.meta)) {348 await main();349}...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var oldTestKeys = require('stryker-parent').oldTestKeys;2var newTestKeys = require('stryker-parent').newTestKeys;3var newTestKeys = require('stryker-parent').newTestKeys;4var oldTestKeys = require('stryker-parent').oldTestKeys;5var newTestKeys = require('stryker-parent').newTestKeys;6var newTestKeys = require('stryker-parent').newTestKeys;7var oldTestKeys = require('stryker-parent').oldTestKeys;8var newTestKeys = require('stryker-parent').newTestKeys;9var newTestKeys = require('stryker-parent').newTestKeys;10var oldTestKeys = require('stryker-parent').oldTestKeys;11var newTestKeys = require('stryker-parent').newTestKeys;12var newTestKeys = require('stryker-parent').newTestKeys;13var oldTestKeys = require('stryker-parent').oldTestKeys;14var newTestKeys = require('stryker-parent').newTestKeys;15var newTestKeys = require('stryker-parent').newTestKeys;16var oldTestKeys = require('stryker-parent').oldTestKeys;17var newTestKeys = require('stryker-parent').newTestKeys;

Full Screen

Using AI Code Generation

copy

Full Screen

1var oldTestKeys = require('stryker-parent').oldTestKeys;2var newTestKeys = require('stryker-parent').newTestKeys;3var getTestKeys = require('stryker-parent').getTestKeys;4var getTestKeys2 = require('stryker-parent').getTestKeys2;5var getTestKeys3 = require('stryker-parent').getTestKeys3;6var getTestKeys4 = require('stryker-parent').getTestKeys4;7var getTestKeys5 = require('stryker-parent').getTestKeys5;8var getTestKeys6 = require('stryker-parent').getTestKeys6;9var getTestKeys7 = require('stryker-parent').getTestKeys7;10var getTestKeys8 = require('stryker-parent').getTestKeys8;11var getTestKeys9 = require('stryker-parent').getTestKeys9;12var getTestKeys10 = require('stryker-parent').getTestKeys10;13var getTestKeys11 = require('stryker-parent').getTestKeys11;14var getTestKeys12 = require('stryker-parent').getTestKeys12;15var getTestKeys13 = require('stryker-parent').getTestKeys13;16var getTestKeys14 = require('stryker-parent').getTestKeys14;17var getTestKeys15 = require('stry

Full Screen

Using AI Code Generation

copy

Full Screen

1var oldTestKeys = require('stryker-parent').oldTestKeys;2var testKeys = oldTestKeys();3console.log(testKeys);4var newTestKeys = require('stryker-parent').newTestKeys;5var testKeys = newTestKeys();6console.log(testKeys);7var oldTestKeys = require('stryker-parent').oldTestKeys;8var testKeys = oldTestKeys();9console.log(testKeys);10var newTestKeys = require('stryker-parent').newTestKeys;11var testKeys = newTestKeys();12console.log(testKeys);13var oldTestKeys = require('stryker-parent').oldTestKeys;14var testKeys = oldTestKeys();15console.log(testKeys);16var newTestKeys = require('stryker-parent').newTestKeys;17var testKeys = newTestKeys();18console.log(testKeys);19[2019-01-16 10:55:47.258] [INFO] Stryker - 0 Mutant(s) generated20[2019-01-16 10:55:47.258] [INFO] Stryker - 0 Mutant(s) tested (0 survived)21[2019-01-16 10:55:47.258] [INFO] Stryker - 0 Mutant(s) generated22[2019-01-16 10:55:47.258] [INFO] Stryker - 0 Mutant(s) tested (0 survived)

Full Screen

Using AI Code Generation

copy

Full Screen

1var oldTestKeys = require('stryker-parent').oldTestKeys;2var newTestKeys = require('stryker-parent').newTestKeys;3var oldTestKeys = require('stryker-parent').oldTestKeys;4var newTestKeys = require('stryker-parent').newTestKeys;5var oldTestKeys = require('stryker-parent').oldTestKeys;6var newTestKeys = require('stryker-parent').newTestKeys;7var oldTestKeys = require('stryker-parent').oldTestKeys;8var newTestKeys = require('stryker-parent').newTestKeys;9var oldTestKeys = require('stryker-parent').oldTestKeys;10var newTestKeys = require('stryker-parent').newTestKeys;11var oldTestKeys = require('stryker-parent').oldTestKeys;12var newTestKeys = require('stryker-parent').newTestKeys;13var oldTestKeys = require('stryker-parent').oldTestKeys;14var newTestKeys = require('stryker-parent').newTestKeys;15var oldTestKeys = require('stryker-parent').oldTestKeys;16var newTestKeys = require('stryker-parent').newTestKeys;17var oldTestKeys = require('stryker-parent').oldTestKeys;18var newTestKeys = require('stryker-parent').newTestKeys;19var oldTestKeys = require('stryker-parent').oldTestKeys;20var newTestKeys = require('stryker-parent').newTestKeys;21var oldTestKeys = require('stryker-parent').oldTestKeys;22var newTestKeys = require('stryker-parent').newTestKeys;23var oldTestKeys = require('stryker-parent').oldTestKeys;24var newTestKeys = require('stryker-parent').newTestKeys;25var oldTestKeys = require('stryker-parent').oldTestKeys;26var newTestKeys = require('stryker-parent').newTestKeys;27var oldTestKeys = require('stryker-parent').oldTestKeys;28var newTestKeys = require('stry

Full Screen

Using AI Code Generation

copy

Full Screen

1function oldTestKeys() {2 return ['old', 'test', 'keys'];3}4function newTestKeys() {5 return ['new', 'test', 'keys'];6}7exports.testKeys = require('./test').testKeys;8exports.testKeys = require('./test').testKeys;9module.exports = function(config) {10 config.set({11 jest: {12 config: require('./jest.config'),13 },14 });15};16module.exports = {17 transform: {18 },19};20const { testKeys: oldTestKeys } = require('stryker-parent');21const { testKeys: newTestKeys } = require('stryker-child');22describe('Test', () => {23 it('should test', () => {24 expect(oldTestKeys()).toEqual(['old', 'test', 'keys']);25 expect(newTestKeys()).toEqual(['new', 'test', 'keys']);26 });27});28const { testKeys: oldTestKeys } = require('stryker-parent');29const { testKeys: newTestKeys } = require('stryker-child');30describe('Test', () => {31 it('should test', () => {32 expect(oldTestKeys()).toEqual(['old', 'test', 'keys']);33 expect(newTestKeys()).toEqual(['new', 'test', 'keys']);34 });35});

Full Screen

Using AI Code Generation

copy

Full Screen

1const oldTestKeys = require('stryker-parent').oldTestKeys;2const testKeys = oldTestKeys();3console.log(testKeys);4const oldTestKeys = require('stryker-parent').oldTestKeys;5const testKeys = oldTestKeys();6console.log(testKeys);7const oldTestKeys = require('stryker-parent').oldTestKeys;8const testKeys = oldTestKeys();9console.log(testKeys);10const oldTestKeys = require('stryker-parent').oldTestKeys;11const testKeys = oldTestKeys();12console.log(testKeys);13const oldTestKeys = require('stryker-parent').oldTestKeys;14const testKeys = oldTestKeys();15console.log(testKeys);16const oldTestKeys = require('stryker-parent').oldTestKeys;17const testKeys = oldTestKeys();18console.log(testKeys);

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