diff --git a/cribro-core/build.gradle.kts b/cribro-core/build.gradle.kts index ac15906..af70854 100644 --- a/cribro-core/build.gradle.kts +++ b/cribro-core/build.gradle.kts @@ -5,7 +5,7 @@ plugins { id("cribro.publish") } -description = "Git diff parsing, JaCoCo report reading, and the PIT interceptor shared by the cribro Gradle and Maven plugins" +description = "Git diff parsing, JaCoCo report reading, and the PIT interceptor shared by the cribro Gradle and Maven plugins; not an API, as its classes change with each plugin release" dependencies { // PIT supplies these classes when it loads the interceptor; the jar has no runtime dependency. diff --git a/cribro-core/src/main/java/io/github/cribrodev/EquivalentMarkers.java b/cribro-core/src/main/java/io/github/cribrodev/EquivalentMarkers.java new file mode 100644 index 0000000..4fd2597 --- /dev/null +++ b/cribro-core/src/main/java/io/github/cribrodev/EquivalentMarkers.java @@ -0,0 +1,211 @@ +/* + * Copyright (C) 2026 cribro contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.github.cribrodev; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * The {@code mutant: equivalent} markers of one source line, such as {@code // mutant: equivalent + * RemoveConditionalMutator_EQUAL_ELSE#2 -- annotate only receives class and array types}. + * + *

A marker names one or more mutants of the line it sits on, by the ids the mutation report + * prints, separated by commas, and gives the reason after {@code --}. A marker starts at a comment + * opener, a {@code //} or a {@code /} followed by one or more {@code *}, where that opener starts a + * comment or lies inside a line comment, even where the line comment only quotes the syntax. Any + * other text, such as a string or anything inside a block comment, starts no marker. The reason + * runs to the end of the comment the marker is in or of the line, whichever comes first, except + * that a {@code /*} marker inside a line comment ends at the first {@code *}{@code /} before that. + * An id may name the mutator with its package, as PIT does, and the package is dropped. + * + *

Each line is read with the whole file around it, as {@link SourceFileKey#regions} splits it, + * so a line inside a text block, a Kotlin raw string, or a block comment opened on an earlier line + * is read as part of it. + */ +final class EquivalentMarkers { + + /** + * The start of a marker: a comment opener, then {@code mutant: equivalent}. The run of {@code *} + * after a {@code /} is matched possessively, so a long run takes linear time. + */ + private static final Pattern START = + Pattern.compile("(//|/\\*++)\\s*mutant:\\s*equivalent(?![\\w-])"); + + /** The {@code --} that ends the ids and starts the reason, with whitespace on both sides. */ + private static final Pattern REASON = Pattern.compile("\\s--\\s"); + + /** One id, as the report prints it: any run of characters but whitespace and commas. */ + private static final Pattern ID = Pattern.compile("[^\\s,]+"); + + /** How a marker is written, for a reader whose marker does not parse. */ + static final String FORM = "// mutant: equivalent -- "; + + private final Map reasons; + private final List problems; + private final String code; + private final String text; + + private EquivalentMarkers( + Map reasons, List problems, String code, String text) { + this.reasons = reasons; + this.problems = problems; + this.code = code; + this.text = text; + } + + /** + * Reads the markers of each line of a file, which may hold none. + * + * @param lines every line of the file, from the first + * @param kotlin whether the file is Kotlin, whose strings hold {@code ${...}} templates + * @return the markers of each line, in the order of the lines + */ + static List parse(List lines, boolean kotlin) { + SourceFileKey.Region[] regions = SourceFileKey.regions(String.join("\n", lines), kotlin); + List parsed = new ArrayList<>(lines.size()); + int start = 0; + for (String line : lines) { + parsed.add(parse(line, Arrays.copyOfRange(regions, start, start + line.length()))); + start += line.length() + 1; + } + return parsed; + } + + /** + * Reads the markers of a file that has one line. + * + * @param kotlin whether the line is Kotlin, whose strings hold {@code ${...}} templates + */ + static EquivalentMarkers parse(String line, boolean kotlin) { + return parse(List.of(line), kotlin).get(0); + } + + /** + * Reads the markers of one line. + * + * @param regions the region each character of the line lies in + */ + private static EquivalentMarkers parse(String line, SourceFileKey.Region[] regions) { + Map reasons = new LinkedHashMap<>(); + List problems = new ArrayList<>(); + StringBuilder code = new StringBuilder(); + Matcher start = START.matcher(line); + int copied = 0; + int from = 0; + while (from < line.length() && start.find(from)) { + if (!opensMarker(regions[start.start()])) { + from = start.start() + 1; + continue; + } + int bodyEnd = start.end(); + int markerEnd; + if (regions[start.start()] == SourceFileKey.Region.LINE_COMMENT) { + while (bodyEnd < line.length() && regions[bodyEnd] == SourceFileKey.Region.LINE_COMMENT) { + bodyEnd++; + } + markerEnd = bodyEnd; + // A /* inside a line comment opens no comment, so its marker ends at the first */. + int close = start.group(1).equals("//") ? -1 : line.indexOf("*/", start.end()); + if (close >= 0 && close + 2 <= bodyEnd) { + bodyEnd = close; + markerEnd = close + 2; + } + } else { + while (bodyEnd < line.length() && regions[bodyEnd] == SourceFileKey.Region.BLOCK_COMMENT) { + bodyEnd++; + } + markerEnd = bodyEnd; + while (markerEnd < line.length() + && regions[markerEnd] == SourceFileKey.Region.BLOCK_COMMENT_END) { + markerEnd++; + } + } + code.append(line, copied, start.start()); + copied = markerEnd; + from = markerEnd; + if (!readBody(line.substring(start.end(), bodyEnd), reasons)) { + problems.add("the marker does not parse; write it as " + FORM); + } + } + code.append(line.substring(Math.min(copied, line.length()))); + return new EquivalentMarkers(reasons, problems, code.toString().strip(), line.strip()); + } + + /** Returns whether a marker may start at a comment opener that lies in the given region. */ + private static boolean opensMarker(SourceFileKey.Region region) { + return region == SourceFileKey.Region.LINE_COMMENT + || region == SourceFileKey.Region.BLOCK_COMMENT_START; + } + + /** + * Adds the ids the body of one marker names, each with its reason, and returns whether the body + * holds at least one id, the {@code --}, and a reason. + */ + private static boolean readBody(String body, Map reasons) { + Matcher separator = REASON.matcher(body); + if (!separator.find()) { + return false; + } + String reason = body.substring(separator.end()).strip(); + String[] ids = body.substring(0, separator.start()).split(",", -1); + if (reason.isEmpty()) { + return false; + } + List named = new ArrayList<>(); + for (String id : ids) { + String trimmed = id.strip(); + if (!ID.matcher(trimmed).matches()) { + return false; + } + int hash = trimmed.indexOf('#'); + int packageEnd = trimmed.lastIndexOf('.', hash < 0 ? trimmed.length() : hash); + String name = trimmed.substring(packageEnd + 1); + if (name.isEmpty() || name.startsWith("#")) { + return false; + } + named.add(name); + } + for (String id : named) { + reasons.putIfAbsent(id, reason); + } + return true; + } + + /** Returns the reason given for each id the markers name, in the order they name them. */ + Map reasons() { + return reasons; + } + + /** Returns a sentence for each marker that does not parse. */ + List problems() { + return problems; + } + + /** Returns the line without its markers, stripped, as the lists of mutants quote it. */ + String code() { + return code; + } + + /** Returns the line with its markers, stripped, as the list of markers to correct quotes it. */ + String text() { + return text; + } +} diff --git a/cribro-core/src/main/java/io/github/cribrodev/MutantsFile.java b/cribro-core/src/main/java/io/github/cribrodev/MutantsFile.java index e597ce8..799b22f 100644 --- a/cribro-core/src/main/java/io/github/cribrodev/MutantsFile.java +++ b/cribro-core/src/main/java/io/github/cribrodev/MutantsFile.java @@ -27,9 +27,10 @@ * Writes and reads the mutants of one PIT run as a text file, one mutant per line. * *

A line holds tab-separated fields: the status PIT gave the mutant, the mutated class, the - * method, the source file the class records, the line number, the description, and then the tests - * PIT recorded as covering the mutant, one per field. A tab or a line break inside a field is - * written as a space. + * method, its descriptor, the source file the class records, the line number, the mutator, the + * index of the first instruction the mutant changes, the description, and then the tests PIT + * recorded as covering the mutant, one per field. A tab or a line break inside a field is written + * as a space. * *

The PIT listener in {@code io.github.cribrodev.pitest} writes the file inside the PIT * process and the build reads it, so this class depends on nothing but the JDK. @@ -52,8 +53,11 @@ public static final class Mutant { private final String status; private final String mutatedClass; private final String method; + private final String methodDescriptor; private final String sourceFile; private final int lineNumber; + private final String mutator; + private final int firstIndex; private final String description; private final List tests; @@ -61,15 +65,21 @@ public Mutant( String status, String mutatedClass, String method, + String methodDescriptor, String sourceFile, int lineNumber, + String mutator, + int firstIndex, String description, List tests) { this.status = status; this.mutatedClass = mutatedClass; this.method = method; + this.methodDescriptor = methodDescriptor; this.sourceFile = sourceFile; this.lineNumber = lineNumber; + this.mutator = mutator; + this.firstIndex = firstIndex; this.description = description; this.tests = tests; } @@ -88,6 +98,11 @@ public String method() { return method; } + /** Returns the descriptor of the method, such as {@code (I)Z}. */ + public String methodDescriptor() { + return methodDescriptor; + } + public String sourceFile() { return sourceFile; } @@ -96,6 +111,23 @@ public int lineNumber() { return lineNumber; } + /** + * Returns the mutator as PIT names it, such as {@code + * org.pitest.mutationtest.engine.gregor.mutators.RemoveConditionalMutator_EQUAL_ELSE}. + */ + public String mutator() { + return mutator; + } + + /** + * Returns the index of the first instruction the mutant changes, counted from the start of its + * method; of two mutants in one method, the one with the lower index comes first in its + * bytecode. + */ + public int firstIndex() { + return firstIndex; + } + public String description() { return description; } @@ -106,6 +138,9 @@ public List tests() { } } + /** The fields every line holds before the tests. */ + private static final int FIXED_FIELDS = 9; + private MutantsFile() {} /** Returns the line the file holds for one mutant, without the line break. */ @@ -114,8 +149,11 @@ public static String line(Mutant mutant) { fields.add(mutant.status()); fields.add(mutant.mutatedClass()); fields.add(mutant.method()); + fields.add(mutant.methodDescriptor()); fields.add(mutant.sourceFile()); fields.add(Integer.toString(mutant.lineNumber())); + fields.add(mutant.mutator()); + fields.add(Integer.toString(mutant.firstIndex())); fields.add(mutant.description()); fields.addAll(mutant.tests()); List cleaned = new ArrayList<>(); @@ -133,8 +171,9 @@ public static List read(Path file) throws IOException { continue; } String[] fields = line.split("\t", -1); - if (fields.length < 6) { - throw new IOException("Fewer than 6 fields in " + file + " line: " + line); + if (fields.length < FIXED_FIELDS) { + throw new IOException( + "Fewer than " + FIXED_FIELDS + " fields in " + file + " line: " + line); } mutants.add( new Mutant( @@ -142,9 +181,12 @@ public static List read(Path file) throws IOException { fields[1], fields[2], fields[3], - Integer.parseInt(fields[4]), - fields[5], - List.copyOf(Arrays.asList(fields).subList(6, fields.length)))); + fields[4], + Integer.parseInt(fields[5]), + fields[6], + Integer.parseInt(fields[7]), + fields[8], + List.copyOf(Arrays.asList(fields).subList(FIXED_FIELDS, fields.length)))); } return mutants; } diff --git a/cribro-core/src/main/java/io/github/cribrodev/PitestRun.java b/cribro-core/src/main/java/io/github/cribrodev/PitestRun.java index fc015b6..307da5a 100644 --- a/cribro-core/src/main/java/io/github/cribrodev/PitestRun.java +++ b/cribro-core/src/main/java/io/github/cribrodev/PitestRun.java @@ -346,6 +346,7 @@ public static String report( repository, sourceDirs, ChangedLinesFile.readPaths(changedLines.toPath()), + ChangedLinesFile.read(changedLines.toPath()), withBytecode.isFile() ? ChangedLinesFile.read(withBytecode.toPath()) : null); return report.writeAndRender( repository, diff --git a/cribro-core/src/main/java/io/github/cribrodev/PitestSurvivors.java b/cribro-core/src/main/java/io/github/cribrodev/PitestSurvivors.java index 720f7ea..bc76ddf 100644 --- a/cribro-core/src/main/java/io/github/cribrodev/PitestSurvivors.java +++ b/cribro-core/src/main/java/io/github/cribrodev/PitestSurvivors.java @@ -31,6 +31,8 @@ import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; +import java.util.function.BiConsumer; +import java.util.function.Predicate; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; @@ -45,11 +47,17 @@ * NON_VIABLE} for a mutant the JVM would not load, says nothing about the tests and is counted * under its own name. * - *

Each line is printed once, with its source text, every live mutant on it, the number of tests - * PIT recorded as reaching it, and the few of them that reach the most live mutants of the report. + *

The list of live mutants prints each line once, with its source text, the live mutants on it + * that no marker acknowledges, the number of tests PIT recorded as reaching them, and the few of + * those tests that reach the most live mutants of the report. * A parameterized or dynamic test counts as one test, and its name lists the invocations that * reach the line, such as {@code CoreQuidemTest.test[1-3, 33]}. The mutants and their tests come * from the {@link MutantsFile} the PIT listener writes. + * + *

A live mutant that an {@link EquivalentMarkers equivalent marker} on its changed line names is + * counted as it is and listed apart, with the reason, rather than among the live mutants. A marker + * on a changed line that does not parse, or has an id that names no live mutant of the line, is + * listed too. */ public final class PitestSurvivors { @@ -64,7 +72,8 @@ public final class PitestSurvivors { + " - the tests miss behavior the change defines: add or strengthen a test," + " next to the tests named for its line\n" + " - no caller can observe the difference, so the mutant is equivalent:" - + " say so in the pull request\n" + + " add // mutant: equivalent -- to its line, where is the text in" + + " brackets after the mutant, and say so in the pull request\n" + " - you cannot tell: report it as unresolved"; /** @@ -78,6 +87,20 @@ public final class PitestSurvivors { + " or the tests that do failed under PIT, which leaves them out silently; pit.log beside" + " the report names each test that failed."; + /** + * What the reader of a report with a marker to correct does with it. + * + *

A marker records a verdict on the code its line held when the marker was written, so a + * marker the run cannot match asks for the line to be judged again rather than for the marker to + * be deleted unread. + */ + static final String MARKERS_TO_CORRECT = + "For each marker listed, judge the mutants of its line again against the code as it is now:" + + " correct an id that names no mutant, remove an id whose mutant is not live, and complete" + + " a marker that does not parse. An id of a mutator this run did not use, such as" + + " RemoveConditionalMutator_EQUAL_ELSE in a run with DEFAULTS, names no mutant here:" + + " keep it, and check it in a run with the mutator group it was written for."; + /** * Why a changed line can have no mutant, for a reader who expected one. * @@ -97,15 +120,26 @@ public final class PitestSurvivors { private static final class Mutant { private final String description; private final String method; + private final String id; + private final String reason; private final Map>> tests; /** + * @param id the id that names the mutant in a marker, as {@link PitestSurvivors#ids} returns it + * @param reason the reason the marker on its line gives, or null where no marker names it * @param tests the short name of each test that reaches the mutant, with the invocations of * it PIT named; the set is empty for a test PIT names with no invocation */ - Mutant(String description, String method, Map>> tests) { + Mutant( + String description, + String method, + String id, + String reason, + Map>> tests) { this.description = description; this.method = method; + this.id = id; + this.reason = reason; this.tests = tests; } @@ -117,26 +151,50 @@ String method() { return method; } + String id() { + return id; + } + + String reason() { + return reason; + } + Map>> tests() { return tests; } } - /** The live mutants of one source line, and the tests that reach it. */ + /** + * One changed line of the report: its live mutants and the tests that reach them, the live + * mutants a marker acknowledges, and what is wrong with the markers on it. + */ private static final class Line { private final int number; private final String source; + private final String text; private final List mutants; + private final List acknowledged; + private final List markerProblems; private final Map>> tests; + /** + * @param source the line without its markers, as the lists of mutants quote it + * @param text the line as written, as the list of markers to correct quotes it + */ Line( int number, String source, + String text, List mutants, + List acknowledged, + List markerProblems, Map>> tests) { this.number = number; this.source = source; + this.text = text; this.mutants = mutants; + this.acknowledged = acknowledged; + this.markerProblems = markerProblems; this.tests = tests; } @@ -148,16 +206,30 @@ String source() { return source; } + String text() { + return text; + } + + /** Returns the live mutants no marker acknowledges. */ List mutants() { return mutants; } + List acknowledged() { + return acknowledged; + } + + List markerProblems() { + return markerProblems; + } + + /** Returns the tests that reach the mutants {@link #mutants()} returns. */ Map>> tests() { return tests; } } - /** The live mutants of one source file. */ + /** The lines of one source file that one part of the report lists. */ private static final class FileMutants { private final String path; private final List lines; @@ -177,6 +249,7 @@ List lines() { return lines; } + /** Returns the number of live mutants no marker acknowledges. */ int mutantCount() { return mutantCount; } @@ -188,12 +261,20 @@ int mutantCount() { private final int total; private final int mutatedLines; private final int linesWithBytecode; + private final int acknowledgedCount; private final List files; + private final List acknowledgedFiles; + private final List markerProblemFiles; /** * @param mutatedLines the number of changed lines that carry at least one mutant * @param linesWithBytecode the number of changed lines with bytecode, or -1 where the run did not * record them + * @param files the files with live mutants no marker acknowledges, each with those lines alone + * @param acknowledgedFiles the files with live mutants a marker acknowledges, each with those + * lines alone + * @param markerProblemFiles the files with a marker that does not parse or has an id naming no + * live mutant of its line, each with those lines alone */ private PitestSurvivors( String scope, @@ -202,7 +283,9 @@ private PitestSurvivors( int total, int mutatedLines, int linesWithBytecode, - List files) { + List files, + List acknowledgedFiles, + List markerProblemFiles) { this.scope = scope; this.testOrder = testOrder; this.statusCounts = statusCounts; @@ -210,6 +293,13 @@ private PitestSurvivors( this.mutatedLines = mutatedLines; this.linesWithBytecode = linesWithBytecode; this.files = files; + this.acknowledgedFiles = acknowledgedFiles; + this.markerProblemFiles = markerProblemFiles; + this.acknowledgedCount = + acknowledgedFiles.stream() + .flatMap(file -> file.lines().stream()) + .mapToInt(line -> line.acknowledged().size()) + .sum(); } /** @@ -224,6 +314,9 @@ private PitestSurvivors( * @param paths the repository-relative path of each changed file, keyed by {@link * SourceFileKey}, as the {@link ChangedLinesFile} of the run records them; a Kotlin file may * lie in a directory that does not follow its package, so its key alone finds no file + * @param changedLines the changed lines, keyed by {@link SourceFileKey}, as the {@link + * ChangedLinesFile} of the run records them; a {@code mutant: equivalent} marker is read + * only on these lines * @param linesWithBytecode the changed lines with bytecode that hold code, as {@link * CodeLines#holdsCode} decides, keyed by {@link SourceFileKey}, as the run records them in * the file {@link ChangedLinesFile#WITH_BYTECODE} names, or null @@ -236,6 +329,7 @@ public static PitestSurvivors read( File repository, List sourceRoots, Map paths, + Map> changedLines, Map> linesWithBytecode) throws IOException { Set withBytecode = new HashSet<>(); @@ -243,23 +337,12 @@ public static PitestSurvivors read( linesWithBytecode.forEach( (key, lines) -> lines.forEach(line -> withBytecode.add(key + ":" + line))); } - if (!mutantsFile.isFile()) { - return new PitestSurvivors( - scope, - Comparator.naturalOrder(), - new LinkedHashMap<>(), - 0, - 0, - linesWithBytecode == null ? -1 : withBytecode.size(), - new ArrayList<>()); - } - List reported = MutantsFile.read(mutantsFile.toPath()); + List reported = + mutantsFile.isFile() ? MutantsFile.read(mutantsFile.toPath()) : List.of(); Set mutated = new HashSet<>(); Map statusCounts = new LinkedHashMap<>(); - Map>> byFile = new HashMap<>(); - // Every mutant of a line names the tests that reach the line, so the same test names repeat - // once per mutant, and each is shortened once. - Map shortTestNames = new HashMap<>(); + // Every mutant of the run, whatever its status, since a marker may name a killed one. + Map>> byFile = new HashMap<>(); for (MutantsFile.Mutant mutant : reported) { statusCounts.merge(mutant.status(), 1, Integer::sum); int packageEnd = mutant.mutatedClass().lastIndexOf('.'); @@ -268,29 +351,26 @@ public static PitestSurvivors read( packageEnd < 0 ? "" : mutant.mutatedClass().substring(0, packageEnd).replace('.', '/'), mutant.sourceFile()); mutated.add(relative + ":" + mutant.lineNumber()); - if (!isLive(mutant.status())) { - continue; - } - Map>> tests = new TreeMap<>(); - for (String test : mutant.tests()) { - TestName name = shortTestNames.computeIfAbsent(test, PitestSurvivors::shortTestName); - NavigableSet> invocations = - tests.computeIfAbsent(name.name(), unused -> new TreeSet<>(INVOCATION_ORDER)); - if (!name.invocation().isEmpty()) { - invocations.add(name.invocation()); - } - } - String description = - (mutant.status().equals("NO_COVERAGE") ? "no test reaches it: " : "survived: ") - + DESCRIPTION_SUFFIX.matcher(mutant.description()).replaceFirst(""); byFile .computeIfAbsent(relative, unused -> new TreeMap<>()) .computeIfAbsent(mutant.lineNumber(), unused -> new ArrayList<>()) - .add(new Mutant(description, readableMethod(mutant.method()), tests)); + .add(mutant); } + // A marker on a changed line that carries no mutant names no mutant, and the report says so. + changedLines.forEach( + (key, lines) -> { + TreeMap> file = + byFile.computeIfAbsent(key, unused -> new TreeMap<>()); + lines.forEach(line -> file.computeIfAbsent(line, unused -> new ArrayList<>())); + }); + // Every mutant of a line names the tests that reach the line, so the same test names repeat + // once per mutant, and each is shortened once. + Map shortTestNames = new HashMap<>(); SourceLines sourceLines = SourceLines.under(repository); List files = new ArrayList<>(); - for (Map.Entry>> file : byFile.entrySet()) { + List acknowledgedFiles = new ArrayList<>(); + List markerProblemFiles = new ArrayList<>(); + for (Map.Entry>> file : byFile.entrySet()) { String known = paths.get(file.getKey()); File source = known != null && new File(repository, known).isFile() @@ -298,38 +378,39 @@ public static PitestSurvivors read( : locate(sourceRoots, file.getKey()); String path = source == null ? file.getKey() : SourceLines.relativize(repository, source); + List markers = + EquivalentMarkers.parse( + source == null ? List.of() : sourceLines.lines(path), + path.endsWith(".kt")); List lines = new ArrayList<>(); - for (Map.Entry> line : file.getValue().entrySet()) { + for (Map.Entry> line : file.getValue().entrySet()) { int number = line.getKey(); - Map>> tests = new TreeMap<>(); - for (Mutant mutant : line.getValue()) { - mutant - .tests() - .forEach( - (name, invocations) -> - tests - .computeIfAbsent(name, unused -> new TreeSet<>(INVOCATION_ORDER)) - .addAll(invocations)); - } - lines.add( - new Line( + Line read = + readLine( number, - source == null ? "" : sourceLines.get(path, number).trim(), + number >= 1 && number <= markers.size() + ? markers.get(number - 1) + : EquivalentMarkers.parse("", false), line.getValue(), - tests)); + shortTestNames); + if (read != null) { + lines.add(read); + } } - files.add(new FileMutants(path, lines)); + addLines(files, path, lines, line -> !line.mutants().isEmpty()); + addLines(acknowledgedFiles, path, lines, line -> !line.acknowledged().isEmpty()); + addLines(markerProblemFiles, path, lines, line -> !line.markerProblems().isEmpty()); } - files.sort( - Comparator.comparingInt(FileMutants::mutantCount) - .reversed() - .thenComparing(FileMutants::path)); + Comparator byPath = Comparator.comparing(FileMutants::path); + files.sort(Comparator.comparingInt(FileMutants::mutantCount).reversed().thenComparing(byPath)); + acknowledgedFiles.sort(byPath); + markerProblemFiles.sort(byPath); // A line most of the suite reaches is reached by tests unrelated to the change, so the tests // named for it are the ones that reach the most live mutants of the whole report. Map liveMutantsReached = new HashMap<>(); - for (TreeMap> lines : byFile.values()) { - for (List mutants : lines.values()) { - for (Mutant mutant : mutants) { + for (FileMutants file : files) { + for (Line line : file.lines()) { + for (Mutant mutant : line.mutants()) { mutant.tests().keySet().forEach(test -> liveMutantsReached.merge(test, 1, Integer::sum)); } } @@ -348,7 +429,203 @@ public static PitestSurvivors read( reported.size(), mutated.size(), linesWithBytecode == null ? -1 : withBytecode.size(), - files); + files, + acknowledgedFiles, + markerProblemFiles); + } + + /** + * Returns one line of the report, or null where the line has no live mutant and no marker. + * + * @param markers the markers of the line, read from the working tree, and none where the working + * tree cannot show the line + * @param mutants every mutant PIT reported on the line, whatever its status + */ + private static Line readLine( + int number, + EquivalentMarkers markers, + List mutants, + Map shortTestNames) { + Map ids = ids(mutants); + Map byId = new HashMap<>(); + ids.forEach((mutant, id) -> byId.put(id, mutant)); + List live = new ArrayList<>(); + List acknowledged = new ArrayList<>(); + for (MutantsFile.Mutant mutant : mutants) { + if (!isLive(mutant.status())) { + continue; + } + String id = ids.get(mutant); + String reason = markers.reasons().get(id); + Mutant row = + new Mutant( + (mutant.status().equals("NO_COVERAGE") ? "no test reaches it: " : "survived: ") + + DESCRIPTION_SUFFIX.matcher(mutant.description()).replaceFirst(""), + readableMethod(mutant.method()), + id, + reason, + tests(mutant, shortTestNames)); + (reason == null ? live : acknowledged).add(row); + } + List problems = new ArrayList<>(markers.problems()); + for (String id : markers.reasons().keySet()) { + MutantsFile.Mutant named = byId.get(id); + if (named == null) { + problems.add(id + ": no mutant on the line has this id"); + } else if (named.status().equals("KILLED")) { + problems.add(id + ": the tests kill this mutant, so it is not equivalent"); + } else if (!isLive(named.status())) { + problems.add(id + ": PIT reports this mutant as " + named.status()); + } + } + if (!problems.isEmpty()) { + // The reader corrects the marker from the report alone, so the line's ids follow its + // problems, killed ones included, since the report lists those nowhere else. + problems.add( + ids.isEmpty() + ? "PIT generated no mutant on the line" + : "the line has " + + ids.entrySet().stream() + .map( + entry -> + entry.getValue() + + " (" + + entry.getKey().status() + + ")") + .collect(Collectors.joining(", "))); + } + if (live.isEmpty() && acknowledged.isEmpty() && problems.isEmpty()) { + return null; + } + Map>> tests = new TreeMap<>(); + for (Mutant mutant : live) { + mutant + .tests() + .forEach( + (name, invocations) -> + tests + .computeIfAbsent(name, unused -> new TreeSet<>(INVOCATION_ORDER)) + .addAll(invocations)); + } + return new Line(number, markers.code(), markers.text(), live, acknowledged, problems, tests); + } + + /** + * Returns the short name of each test PIT recorded as covering the mutant, with the invocations + * of it PIT named. + */ + private static Map>> tests( + MutantsFile.Mutant mutant, Map shortTestNames) { + Map>> tests = new TreeMap<>(); + for (String test : mutant.tests()) { + TestName name = shortTestNames.computeIfAbsent(test, PitestSurvivors::shortTestName); + NavigableSet> invocations = + tests.computeIfAbsent(name.name(), unused -> new TreeSet<>(INVOCATION_ORDER)); + if (!name.invocation().isEmpty()) { + invocations.add(name.invocation()); + } + } + return tests; + } + + /** Adds a file with the lines that pass the filter, where any does. */ + private static void addLines( + List files, String path, List lines, Predicate filter) { + List kept = lines.stream().filter(filter).collect(Collectors.toList()); + if (!kept.isEmpty()) { + files.add(new FileMutants(path, kept)); + } + } + + /** + * Returns the id of each mutant of one line: the simple name of its mutator, such as {@code + * RemoveConditionalMutator_EQUAL_ELSE}, followed by {@code #} and a number where the mutator + * made more than one mutant on the line. + * + *

The numbers count the mutants of that mutator from 1, by method name and descriptor, then by + * the class that declares the method, then by the first instruction each changes, then by its + * description. A run of digits in a method or class name compares as a number, so + * {@code lambda$run$9} comes before {@code lambda$run$10}, and a lambda added earlier in the + * class, which renumbers the later ones, leaves their order as it was. javac emits the jumps of + * {@code a || b} in source order, so on such a line {@code #1} is a mutant of {@code a} and + * {@code #2} one of {@code b}. The numbers count mutants of every status, so an id stays the + * same when a test starts killing another mutant of the line. The map iterates in the order of + * the mutator names and then of the numbers. + */ + static Map ids(List mutants) { + Map> byMutator = new TreeMap<>(); + for (MutantsFile.Mutant mutant : mutants) { + byMutator + .computeIfAbsent(simpleMutatorName(mutant.mutator()), unused -> new ArrayList<>()) + .add(mutant); + } + // A mutant is a key by identity: the class does not override equals. + Map ids = new LinkedHashMap<>(); + byMutator.forEach( + (mutator, same) -> { + if (same.size() == 1) { + ids.put(same.get(0), mutator); + return; + } + same.sort( + Comparator.comparing(MutantsFile.Mutant::method, PitestSurvivors::compareNames) + .thenComparing(MutantsFile.Mutant::methodDescriptor) + .thenComparing(MutantsFile.Mutant::mutatedClass, PitestSurvivors::compareNames) + .thenComparingInt(MutantsFile.Mutant::firstIndex) + .thenComparing(MutantsFile.Mutant::description)); + for (int i = 0; i < same.size(); i++) { + ids.put(same.get(i), mutator + "#" + (i + 1)); + } + }); + return ids; + } + + /** + * Compares two names character by character, except that a run of ASCII digits in both compares + * first by its length and then by its digits, so {@code a$9} sorts before {@code a$10}. + */ + private static int compareNames(String a, String b) { + int i = 0; + int j = 0; + while (i < a.length() && j < b.length()) { + if (isDigit(a.charAt(i)) && isDigit(b.charAt(j))) { + int iEnd = digitsEnd(a, i); + int jEnd = digitsEnd(b, j); + int byLength = Integer.compare(iEnd - i, jEnd - j); + if (byLength != 0) { + return byLength; + } + int byDigits = a.substring(i, iEnd).compareTo(b.substring(j, jEnd)); + if (byDigits != 0) { + return byDigits; + } + i = iEnd; + j = jEnd; + } else if (a.charAt(i) != b.charAt(j)) { + return Character.compare(a.charAt(i), b.charAt(j)); + } else { + i++; + j++; + } + } + return Integer.compare(a.length() - i, b.length() - j); + } + + private static boolean isDigit(char c) { + return c >= '0' && c <= '9'; + } + + /** Returns the index after the run of ASCII digits that starts at {@code at}. */ + private static int digitsEnd(String text, int at) { + while (at < text.length() && isDigit(text.charAt(at))) { + at++; + } + return at; + } + + /** Returns the mutator name without its package, as an id names it. */ + private static String simpleMutatorName(String mutator) { + return mutator.substring(mutator.lastIndexOf('.') + 1); } /** @@ -427,6 +704,11 @@ String render(DiffCoverageReport.Limits limits, List fullReportPaths) { .append(changedLines(linesWithBytecode >= 0 ? linesWithBytecode : mutatedLines)) .append(": ") .append(counts()); + if (acknowledgedCount > 0) { + out.append("; ") + .append(acknowledgedCount) + .append(" of the live ones acknowledged as equivalent"); + } } int liveLines = files.stream().mapToInt(file -> file.lines().size()).sum(); if (liveLines > 0) { @@ -435,35 +717,9 @@ String render(DiffCoverageReport.Limits limits, List fullReportPaths) { if (total > 0 && statusCounts.getOrDefault("NO_COVERAGE", 0) == total) { out.append("\n\n").append(NOTHING_REACHED); } - int filesLeft = limits.files; - int rowsLeft = limits.lines; - int filesShown = 0; - for (FileMutants file : files) { - if (filesLeft == 0 || rowsLeft == 0) { - break; - } - filesLeft--; - filesShown++; - out.append("\n\n ").append(file.path()); - int allowed = Math.min(limits.linesPerFile, rowsLeft); - int shown = 0; - for (Line line : file.lines()) { - if (shown == allowed) { - break; - } - shown++; - appendLine(out, line); - } - rowsLeft -= shown; - if (shown < file.lines().size()) { - int more = file.lines().size() - shown; - out.append("\n ").append(more).append(more == 1 ? " more line" : " more lines"); - } - } - if (filesShown < files.size()) { - int more = files.size() - filesShown; - out.append("\n\n ").append(more).append(more == 1 ? " more file" : " more files"); - } + // The console limits hold for the whole report, so the sections spend one budget in turn. + int[] budget = {limits.files, limits.lines}; + appendFiles(out, files, limits.linesPerFile, budget, this::appendLine); if (liveLines > 0) { out.append("\n\nLive mutants on ") .append(liveLines) @@ -474,6 +730,21 @@ String render(DiffCoverageReport.Limits limits, List fullReportPaths) { .append("\n\n") .append(WHAT_TO_DO); } + if (!markerProblemFiles.isEmpty()) { + out.append("\n\nMarkers to correct:"); + appendFiles( + out, markerProblemFiles, limits.linesPerFile, budget, PitestSurvivors::appendProblems); + out.append("\n\n").append(MARKERS_TO_CORRECT); + } + if (!acknowledgedFiles.isEmpty()) { + out.append("\n\nLive mutants acknowledged as equivalent:"); + appendFiles( + out, + acknowledgedFiles, + limits.linesPerFile, + budget, + PitestSurvivors::appendAcknowledged); + } // The note explains a changed line with no mutant. Where the run did not record the lines with // bytecode, any changed line may lack one, so the note goes only with a report that already // asks the reader to act: a mutant survived, or none was generated. @@ -537,10 +808,65 @@ private String counts() { return String.join(", ", parts); } + /** + * Appends the files of one section, as many as the budget allows. + * + * @param budget the files and the lines the console may still show, spent by this call + */ + private static void appendFiles( + StringBuilder out, + List files, + int linesPerFile, + int[] budget, + BiConsumer lineWriter) { + int filesShown = 0; + for (FileMutants file : files) { + if (budget[0] == 0 || budget[1] == 0) { + break; + } + budget[0]--; + filesShown++; + out.append("\n\n ").append(file.path()); + int allowed = Math.min(linesPerFile, budget[1]); + int shown = 0; + for (Line line : file.lines()) { + if (shown == allowed) { + break; + } + shown++; + lineWriter.accept(out, line); + } + budget[1] -= shown; + if (shown < file.lines().size()) { + int more = file.lines().size() - shown; + out.append("\n ").append(more).append(more == 1 ? " more line" : " more lines"); + } + } + if (filesShown < files.size()) { + int more = files.size() - filesShown; + out.append("\n\n ").append(more).append(more == 1 ? " more file" : " more files"); + } + } + + private static void appendProblems(StringBuilder out, Line line) { + out.append("\n ").append(line.number()).append(": ").append(line.text()); + for (String problem : line.markerProblems()) { + out.append("\n ").append(problem); + } + } + + private static void appendAcknowledged(StringBuilder out, Line line) { + out.append("\n ").append(line.number()).append(": ").append(line.source()); + for (Mutant mutant : line.acknowledged()) { + appendMutant(out, mutant); + out.append("\n reason: ").append(mutant.reason()); + } + } + private void appendLine(StringBuilder out, Line line) { out.append("\n ").append(line.number()).append(": ").append(line.source()); for (Mutant mutant : line.mutants()) { - out.append("\n ").append(mutant.description()).append(", in ").append(mutant.method()); + appendMutant(out, mutant); } if (!line.tests().isEmpty()) { List tests = new ArrayList<>(line.tests().keySet()); @@ -555,6 +881,16 @@ private void appendLine(StringBuilder out, Line line) { } } + private static void appendMutant(StringBuilder out, Mutant mutant) { + out.append("\n ") + .append(mutant.description()) + .append(", in ") + .append(mutant.method()) + .append(" [") + .append(mutant.id()) + .append(']'); + } + /** Returns the method name as a reader finds it in the source. */ static String readableMethod(String method) { if (method.equals("")) { diff --git a/cribro-core/src/main/java/io/github/cribrodev/SourceFileKey.java b/cribro-core/src/main/java/io/github/cribrodev/SourceFileKey.java index b54cdd0..65ad935 100644 --- a/cribro-core/src/main/java/io/github/cribrodev/SourceFileKey.java +++ b/cribro-core/src/main/java/io/github/cribrodev/SourceFileKey.java @@ -20,6 +20,8 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.InvalidPathException; +import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; @@ -139,6 +141,87 @@ static String declaredPackage(String text, boolean kotlin) { return at < 0 ? null : name.toString(); } + /** Whether a character of a Java or Kotlin source lies in a comment, and in which kind. */ + enum Region { + /** Code, whitespace, a string or character literal, or a Kotlin name in backticks. */ + CODE, + /** A line comment, from its {@code //} to the end of its line. */ + LINE_COMMENT, + /** The first character of a block comment, the {@code /} of its {@code /*}. */ + BLOCK_COMMENT_START, + /** + * A character of a block comment other than its first and the {@code *}{@code /} that closes + * it, a nested Kotlin comment included. + */ + BLOCK_COMMENT, + /** A character of the {@code *}{@code /} that closes a block comment. */ + BLOCK_COMMENT_END + } + + /** + * Returns the region each character of a Java or Kotlin source lies in, by the lexical rules of + * the language, so a comment opener inside a literal opens no comment. A Java text is split after + * its Unicode escapes are replaced, and each character of an escape gets the region of the + * character it stands for. The code of a Kotlin template is split as code, so a comment in it is + * a comment. A text block, a raw string, or a block comment that never closes runs to the end of + * the text, and any other literal that never closes to the end of its line. + */ + static Region[] regions(String text, boolean kotlin) { + Region[] regions = new Region[text.length()]; + if (kotlin) { + fill(text, 0, text.length(), true, regions); + return regions; + } + int[] origin = new int[text.length() + 1]; + String read = translateUnicodeEscapes(text, origin); + Region[] readRegions = new Region[read.length()]; + fill(read, 0, read.length(), false, readRegions); + for (int at = 0; at < read.length(); at++) { + Arrays.fill(regions, origin[at], origin[at + 1], readRegions[at]); + } + return regions; + } + + /** Sets the region of each character from {@code from} to {@code to}, the code of a text. */ + private static void fill(String text, int from, int to, boolean kotlin, Region[] regions) { + Arrays.fill(regions, from, to, Region.CODE); + int dollars = 0; + int at = from; + while (at < to) { + char c = text.charAt(at); + int next; + if (text.startsWith("//", at)) { + next = skipLineComment(text, at); + Arrays.fill(regions, at, Math.min(next, to), Region.LINE_COMMENT); + } else if (text.startsWith("/*", at)) { + next = skipBlockComment(text, at, kotlin); + Arrays.fill(regions, at + 1, next < 0 ? to : Math.min(next, to), Region.BLOCK_COMMENT); + regions[at] = Region.BLOCK_COMMENT_START; + if (next >= 0 && next <= to) { + Arrays.fill(regions, next - 2, next, Region.BLOCK_COMMENT_END); + } + } else if (c == '"' || c == '\'') { + List templates = new ArrayList<>(); + next = skipLiteral(text, at, kotlin, dollars, templates); + if (next < 0) { + if (!text.startsWith("\"\"\"", at)) { + next = skipLineComment(text, at); + } + } else { + for (int[] template : templates) { + fill(text, template[0], template[1], kotlin, regions); + } + } + } else if (kotlin && c == '`') { + next = skipIdentifier(text, at); + } else { + next = at + 1; + } + dollars = c == '$' ? dollars + 1 : 0; + at = next < 0 ? to : Math.max(next, at + 1); + } + } + /** * Returns the text with each Unicode escape replaced by the character it stands for, as javac * reads a source before it splits it into tokens (JLS ยง3.3). A backslash begins an escape only @@ -146,6 +229,18 @@ static String declaredPackage(String text, boolean kotlin) { * none. A backslash and {@code u} that no four hexadecimal digits follow stay as they are. */ private static String translateUnicodeEscapes(String text) { + return translateUnicodeEscapes(text, null); + } + + /** + * Returns the text with each Unicode escape replaced, as {@link #translateUnicodeEscapes(String)} + * does. + * + * @param origin receives, for each character of the result, the index in {@code text} where it + * starts, and after the last of them the length of {@code text}; it holds at least {@code + * text.length() + 1} elements, or is null where only the result matters + */ + private static String translateUnicodeEscapes(String text, int[] origin) { StringBuilder out = new StringBuilder(text.length()); int backslashes = 0; int at = 0; @@ -157,6 +252,9 @@ private static String translateUnicodeEscapes(String text) { digits++; } if (digits > at + 1 && isHex(text, digits, digits + 4)) { + if (origin != null) { + origin[out.length()] = at; + } out.append((char) Integer.parseInt(text, digits, digits + 4, 16)); at = digits + 4; backslashes = 0; @@ -164,9 +262,15 @@ private static String translateUnicodeEscapes(String text) { } } backslashes = c == '\\' ? backslashes + 1 : 0; + if (origin != null) { + origin[out.length()] = at; + } out.append(c); at++; } + if (origin != null) { + origin[out.length()] = text.length(); + } return out.toString(); } @@ -415,6 +519,18 @@ private static int skipBalanced(String text, int at, char open, char close, bool * of a Kotlin string */ private static int skipLiteral(String text, int at, boolean kotlin, int dollars) { + return skipLiteral(text, at, kotlin, dollars, null); + } + + /** + * Returns the index after the literal that opens at {@code at}, as {@link #skipLiteral(String, + * int, boolean, int)} does. + * + * @param templateCode receives the start and the end of the code of each template the literal + * holds, the text between its braces; null where only the end of the literal matters + */ + private static int skipLiteral( + String text, int at, boolean kotlin, int dollars, List templateCode) { char quote = text.charAt(at); boolean multiline = quote == '"' && text.startsWith("\"\"\"", at); boolean escapes = !(kotlin && multiline); @@ -438,10 +554,14 @@ private static int skipLiteral(String text, int at, boolean kotlin, int dollars) at += 2; run = 0; } else if (c == '{' && templates && run >= prefix) { + int open = at; at = skipBalanced(text, at, '{', '}', true); if (at < 0) { return -1; } + if (templateCode != null) { + templateCode.add(new int[] {open + 1, at - 1}); + } run = 0; } else { run = c == '$' ? run + 1 : 0; diff --git a/cribro-core/src/main/java/io/github/cribrodev/SourceLines.java b/cribro-core/src/main/java/io/github/cribrodev/SourceLines.java index 8595886..253a65d 100644 --- a/cribro-core/src/main/java/io/github/cribrodev/SourceLines.java +++ b/cribro-core/src/main/java/io/github/cribrodev/SourceLines.java @@ -86,6 +86,17 @@ String get(String path, int number) { return text.decoded ? text.line(number) : ""; } + /** + * Returns every line of a file as the working tree holds it, or no line where the file cannot be + * read or decoded, as {@link #get} treats it. + * + * @param path repository-relative path, as a git diff spells it + */ + List lines(String path) { + Text text = text(path); + return text.decoded ? text.lines : List.of(); + } + /** * Returns one line with each byte sequence that is not UTF-8 replaced by {@code U+FFFD}, or an * empty string where the file cannot be read or has no such line. diff --git a/cribro-core/src/main/java/io/github/cribrodev/pitest/MutantsFileListenerFactory.java b/cribro-core/src/main/java/io/github/cribrodev/pitest/MutantsFileListenerFactory.java index 79f4e25..c898e35 100644 --- a/cribro-core/src/main/java/io/github/cribrodev/pitest/MutantsFileListenerFactory.java +++ b/cribro-core/src/main/java/io/github/cribrodev/pitest/MutantsFileListenerFactory.java @@ -75,8 +75,11 @@ public void handleMutationResult(ClassMutationResults results) { result.getStatus().name(), details.getClassName().asJavaName(), details.getMethod(), + details.getId().getLocation().getMethodDesc(), details.getFilename(), details.getLineNumber(), + details.getMutator(), + details.getFirstIndex(), details.getDescription(), result.getCoveringTests()))); out.write('\n'); diff --git a/cribro-core/src/test/java/io/github/cribrodev/EquivalentMarkersTest.java b/cribro-core/src/test/java/io/github/cribrodev/EquivalentMarkersTest.java new file mode 100644 index 0000000..adcc0e0 --- /dev/null +++ b/cribro-core/src/test/java/io/github/cribrodev/EquivalentMarkersTest.java @@ -0,0 +1,474 @@ +/* + * Copyright (C) 2026 cribro contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.github.cribrodev; + +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; + +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; + +class EquivalentMarkersTest { + + private static final String MALFORMED = + "the marker does not parse; write it as " + EquivalentMarkers.FORM; + + private static EquivalentMarkers java(String line) { + return EquivalentMarkers.parse(line, false); + } + + private static EquivalentMarkers kotlin(String line) { + return EquivalentMarkers.parse(line, true); + } + + @Test + void aLineCommentGivesEachIdItNamesTheReasonThatRunsToTheEndOfTheLine() { + EquivalentMarkers markers = + java( + " if (a || b) { // mutant: equivalent NegateConditionalsMutator#2," + + " RemoveConditionalMutator_EQUAL_ELSE -- b is false, see https://x/1 // more"); + + assertAll( + () -> + assertEquals( + Map.of( + "NegateConditionalsMutator#2", "b is false, see https://x/1 // more", + "RemoveConditionalMutator_EQUAL_ELSE", "b is false, see https://x/1 // more"), + markers.reasons(), + "reasons"), + () -> assertEquals(List.of(), markers.problems(), "problems"), + () -> assertEquals("if (a || b) {", markers.code(), "code")); + } + + @Test + void aBlockCommentEndsTheReasonAndKeepsTheCodeAfterIt() { + EquivalentMarkers markers = + java("if (a /* mutant: equivalent MathMutator -- a is never 0 */ > 0) { // done"); + + assertAll( + () -> assertEquals(Map.of("MathMutator", "a is never 0"), markers.reasons(), "reasons"), + () -> assertEquals("if (a > 0) { // done", markers.code(), "code")); + } + + @Test + void anIdWithThePackageOfItsMutatorNamesTheMutatorAlone() { + assertEquals( + Map.of("RemoveConditionalMutator_EQUAL_ELSE#1", "why"), + java("// mutant: equivalent" + + " org.pitest.mutationtest.engine.gregor.mutators." + + "RemoveConditionalMutator_EQUAL_ELSE#1 -- why") + .reasons()); + } + + @Test + void anIdMayHoldAnyCharacterButWhitespaceAndComma() { + assertEquals( + Map.of("remove-check", "why", "Kotlin$Null#2", "why", "Check#fast#2", "why"), + java("x(); // mutant: equivalent custom.remove-check, Kotlin$Null#2, custom.Check#fast#2" + + " -- why") + .reasons()); + } + + @Test + void aLongListOfIdsIsRead() { + StringBuilder line = new StringBuilder("x(); // mutant: equivalent M0"); + for (int i = 1; i < 5000; i++) { + line.append(", M").append(i); + } + line.append(" -- why"); + + assertEquals(5000, java(line.toString()).reasons().size(), "ids read from 5000 named"); + } + + @ParameterizedTest + @ValueSource( + strings = { + "return b; // mutant: equivalent", + "return b; // mutant: equivalent MathMutator", + "return b; // mutant: equivalent MathMutator --", + "return b; // mutant: equivalent -- why", + "return b; // mutant: equivalent Math Mutator -- why", + "return b; // mutant: equivalent MathMutator. -- why", + "return b; // mutant: equivalent pkg.#2 -- why", + "return b; // mutant: equivalent MathMutator, -- why", + "return b; // mutant: equivalent #2.MathMutator -- why", + "return b; // mutant: equivalent MathMutator -- ", + "return b; /* mutant: equivalent MathMutator -- */", + }) + void aMarkerThatDoesNotParseAcknowledgesNothingAndIsReported(String line) { + EquivalentMarkers markers = java(line); + + assertAll( + () -> assertEquals(Map.of(), markers.reasons(), "reasons"), + () -> assertEquals(List.of(MALFORMED), markers.problems(), "problems"), + () -> assertEquals("return b;", markers.code(), "code")); + } + + @ParameterizedTest + @ValueSource( + strings = { + "String s = \"// mutant: equivalent MathMutator -- why\";", + "String s = \"a\\\" // mutant: equivalent MathMutator -- why\";", + "x(); // mutant: equivalents MathMutator -- why", + "x(); // a mutant: equivalent? no", + "x(); /* see // mutant: equivalent MathMutator -- why */", + "x(); /* see * mutant: equivalent MathMutator -- why */", + "x(); /* see ** mutant: equivalent MathMutator -- why */", + "x() * mutant: equivalent MathMutator -- why", + "x(); // a * mutant: equivalent MathMutator -- why", + }) + void textThatIsNoMarkerIsLeftInTheCode(String line) { + EquivalentMarkers markers = java(line); + + assertAll( + () -> assertEquals(Map.of(), markers.reasons(), "reasons"), + () -> assertEquals(List.of(), markers.problems(), "problems"), + () -> assertEquals(line, markers.code(), "code")); + } + + @ParameterizedTest + @ValueSource( + strings = { + "s(\"a\\\"b\"); // mutant: equivalent MathMutator -- why", + "c('\"'); // mutant: equivalent MathMutator -- why", + "c('\\''); s(\"x\"); // mutant: equivalent MathMutator -- why", + "/* don't say \"a */ y(); // mutant: equivalent MathMutator -- why", + "s(\"x\") /* mutant: equivalent MathMutator -- why */;", + "s(\"${\"); // mutant: equivalent MathMutator -- why", + }) + void aMarkerAfterALiteralThatClosesOnTheLineCountsInJava(String line) { + assertEquals(Map.of("MathMutator", "why"), java(line).reasons(), line); + } + + @ParameterizedTest + @ValueSource( + strings = { + "val s = \"\"\"a\"b\"\"\" // mutant: equivalent MathMutator -- why", + "val s = \"\"\"C:\\\"\"\" // mutant: equivalent MathMutator -- why", + "val s = \"\"\"a\"\"\"\" // mutant: equivalent MathMutator -- why", + "val s = \"${'\"'}\" // mutant: equivalent MathMutator -- why", + "val s = \"${f(\"}\")}\" // mutant: equivalent MathMutator -- why", + "val s = \"$x\" // mutant: equivalent MathMutator -- why", + }) + void aMarkerAfterAKotlinStringThatClosesOnTheLineCounts(String line) { + assertEquals(Map.of("MathMutator", "why"), kotlin(line).reasons(), line); + } + + @Test + void aKotlinNameInBackticksMayHoldAQuote() { + assertEquals( + Map.of("MathMutator", "why"), + kotlin("fun `doesn't change`(x: Int) = x + 1 // mutant: equivalent MathMutator -- why") + .reasons()); + } + + @Test + void aKotlinBlockCommentEndsAtTheCloseThatMatchesItsOpen() { + String line = "/* a /* b */ \" */ x() // mutant: equivalent MathMutator -- why"; + assertAll( + () -> assertEquals(Map.of("MathMutator", "why"), kotlin(line).reasons(), "Kotlin"), + () -> assertEquals(Map.of(), java(line).reasons(), "Java, whose comments do not nest")); + } + + /** Returns the reasons each line of the file gives, one map per line. */ + private static List> reasons(boolean kotlin, String... lines) { + return EquivalentMarkers.parse(List.of(lines), kotlin).stream() + .map(EquivalentMarkers::reasons) + .collect(Collectors.toList()); + } + + @Test + void aJavaTextBlockIsALiteralOnEveryLineItSpans() { + assertEquals( + List.of(Map.of(), Map.of(), Map.of("MathMutator", "why")), + reasons( + false, + "int n = \"\"\"", + " // mutant: equivalent MathMutator -- data", + " \"\"\".length() + 1; // mutant: equivalent MathMutator -- why")); + } + + @Test + void anEscapedQuoteDoesNotCloseAJavaTextBlock() { + assertEquals( + List.of(Map.of(), Map.of(), Map.of(), Map.of("MathMutator", "why")), + reasons( + false, + "String s = \"\"\"", + " a \\\"\"\" b", + " \"\"\";", + "return s.length() + 1; // mutant: equivalent MathMutator -- why")); + } + + @Test + void aKotlinRawStringAndItsTemplatesSpanLines() { + assertEquals( + List.of(Map.of(), Map.of(), Map.of(), Map.of(), Map.of("MathMutator", "why")), + reasons( + true, + "val s = \"\"\"${f(", + " \"// mutant: equivalent MathMutator -- a string in a template\")", + "} // mutant: equivalent MathMutator -- data", + " // mutant: equivalent MathMutator -- data", + "\"\"\".length + 1 // mutant: equivalent MathMutator -- why")); + } + + @Test + void aKotlinStringWithADollarPrefixOpensATemplateOnlyAfterAsManyDollars() { + assertEquals( + List.of(Map.of("MathMutator", "one"), Map.of("MathMutator", "two")), + reasons( + true, + "val s = $$\"\"\"a ${ b\"\"\" // mutant: equivalent MathMutator -- one", + "fun g() = x + 1 // mutant: equivalent MathMutator -- two")); + } + + @Test + void aStringInDoubleQuotesThatDoesNotCloseEndsWithItsLine() { + assertEquals( + List.of(Map.of(), Map.of("MathMutator", "why")), + reasons(false, "s(\"a", "x(); // mutant: equivalent MathMutator -- why")); + } + + @ParameterizedTest + @ValueSource( + strings = { + "val s = \"\"\"// mutant: equivalent MathMutator -- why\"\"\"", + "val s = \"${x} // mutant: equivalent MathMutator -- why\"", + "val s = \"${x}// mutant: equivalent MathMutator -- why\"", + "val s = \"\"\"${x}// mutant: equivalent MathMutator -- why\"\"\"", + "val s = \"${x}/* mutant: equivalent MathMutator -- why */\"", + }) + void aMarkerInsideAKotlinStringIsNoMarker(String line) { + EquivalentMarkers markers = kotlin(line); + + assertAll( + () -> assertEquals(Map.of(), markers.reasons(), "reasons"), + () -> assertEquals(List.of(), markers.problems(), "problems"), + () -> assertEquals(line, markers.code(), "code")); + } + + @ParameterizedTest + @ValueSource( + strings = { + "x(); // diff-coverage: ignore -- r // mutant: equivalent MathMutator -- why", + "x(); // see /* mutant: equivalent MathMutator -- why */", + "x(); /* mutant: equivalent MathMutator -- why", + "x(); /** mutant: equivalent MathMutator -- why */", + "x(); /*** mutant: equivalent MathMutator -- why", + }) + void aMarkerStartsWhereACommentOpensOrInsideALineComment(String line) { + assertEquals(Map.of("MathMutator", "why"), java(line).reasons(), line); + } + + @ParameterizedTest + @CsvSource( + delimiter = '|', + value = { + "x(); // mutant: equivalent MathMutator -- why */ y | why */ y | x();", + "x(); // see /* mutant: equivalent MathMutator -- why */ y(); | why | x(); // see y();", + "x(); // see /* mutant: equivalent MathMutator -- why | why | x(); // see", + }) + void aMarkerInALineCommentEndsAtTheEndOfTheLineOrAtTheFirstCloseAfterASlashStar( + String line, String reason, String code) { + EquivalentMarkers markers = java(line); + + assertAll( + () -> assertEquals(Map.of("MathMutator", reason), markers.reasons(), "reasons"), + () -> assertEquals(code, markers.code(), "code")); + } + + @Test + void textInsideABlockCommentStartsNoMarker() { + List markers = + EquivalentMarkers.parse( + List.of( + "/**", + " * such as {@code // mutant: equivalent MathMutator#2 -- b is checked}, or", + " * {@code /* mutant: equivalent} without an id.", + " * mutant: equivalent MathMutator -- why", + " ** mutant: equivalent VoidMethodCallMutator -- two", + " * mutant: equivalent MathMutator -- why */ x = a + b;"), + false); + + assertAll( + () -> + assertEquals( + List.of(Map.of(), Map.of(), Map.of(), Map.of(), Map.of(), Map.of()), + markers.stream().map(EquivalentMarkers::reasons).collect(Collectors.toList()), + "reasons"), + () -> + assertEquals( + List.of(List.of(), List.of(), List.of(), List.of(), List.of(), List.of()), + markers.stream().map(EquivalentMarkers::problems).collect(Collectors.toList()), + "problems")); + } + + @Test + void aMarkerOnALaterLineIsReadAtTheColumnsOfThatLine() { + assertEquals( + List.of(Map.of(), Map.of("MathMutator", "two"), Map.of("MathMutator", "three")), + reasons( + false, + "s(\"abc", + "/* mutant: equivalent MathMutator -- two */ x();", + "/* mutant: equivalent MathMutator -- three */ y();")); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void aQuoteInALineCommentOpensNoLiteral(boolean kotlin) { + assertEquals( + List.of(Map.of(), Map.of("MathMutator", "why")), + reasons(kotlin, "// see \"\"\" and it's", "x(); // mutant: equivalent MathMutator -- why")); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void aTextBlockThatNeverClosesIsALiteralToTheEndOfTheFile(boolean kotlin) { + assertEquals( + List.of(Map.of(), Map.of()), + reasons(kotlin, "s = \"\"\"", " // mutant: equivalent MathMutator -- data")); + } + + @Test + void aQuoteWrittenAsAUnicodeEscapeOpensAndClosesAJavaString() { + assertEquals( + List.of(Map.of(), Map.of("MathMutator", "why"), Map.of()), + reasons( + false, + "int n = x + \\u0022// mutant: equivalent MathMutator -- data\\u0022.length();", + "s(\"a\\u0022); // mutant: equivalent MathMutator -- why", + "s(\"a\\\\u0022 // mutant: equivalent MathMutator -- data\");")); + } + + @Test + void aUnicodeEscapeInKotlinIsReadAsWritten() { + assertEquals( + Map.of("MathMutator", "why"), + kotlin("val n = x + \\u0022// mutant: equivalent MathMutator -- why").reasons()); + } + + @Test + void aCommentInTheCodeOfAKotlinTemplateIsAComment() { + assertEquals( + List.of( + Map.of(), + Map.of("MathMutator", "line"), + Map.of("NegateConditionalsMutator", "block"), + Map.of(), + Map.of()), + reasons( + true, + "fun f(x: Int) = \"${", + " x + 1 // mutant: equivalent MathMutator -- line", + "}\" + \"${x /* mutant: equivalent NegateConditionalsMutator -- block */}\" + \"${", + " \"// mutant: equivalent MathMutator -- a string in a template\"}\"", + "val s = \"${x /* mutant: equivalent MathMutator -- the string never closes */}")); + } + + @Test + void aKotlinStringWithTwoDollarsBeforeItsQuoteTakesNoTemplateAfterOneDollar() { + assertEquals( + Map.of(), + kotlin("val t = $$\"${x /* mutant: equivalent MathMutator -- no template */}\"").reasons()); + } + + @Test + void aJavaStringHoldsNoTemplate() { + assertEquals( + Map.of(), + java("s(\"${x /* mutant: equivalent MathMutator -- data */}\");").reasons()); + } + + @Test + void aJavaBlockCommentClosedByAUnicodeEscapeEndsTheMarkerThere() { + EquivalentMarkers markers = java("int n = x + 1 /* mutant: equivalent MathMutator -- \\u002a/;"); + + assertAll( + () -> assertEquals(Map.of(), markers.reasons(), "reasons"), + () -> assertEquals(List.of(MALFORMED), markers.problems(), "problems"), + () -> assertEquals("int n = x + 1 ;", markers.code(), "code")); + } + + @Test + void aMarkerInANestedKotlinCommentRunsToTheOutermostClose() { + EquivalentMarkers markers = kotlin("/* mutant: equivalent MathMutator -- a /* b */ c */ y()"); + + assertAll( + () -> assertEquals(Map.of("MathMutator", "a /* b */ c"), markers.reasons(), "reasons"), + () -> assertEquals("y()", markers.code(), "code")); + } + + @Test + void aMarkerInAJavaCommentRunsToTheFirstClose() { + EquivalentMarkers markers = java("/* mutant: equivalent MathMutator -- a /* b */ c */ y()"); + + assertAll( + () -> assertEquals(Map.of("MathMutator", "a /* b"), markers.reasons(), "reasons"), + () -> assertEquals("c */ y()", markers.code(), "code")); + } + + @Test + void aJavaLineCommentEndedByAUnicodeEscapeEndsTheMarkerThere() { + EquivalentMarkers markers = + java("x(); // mutant: equivalent MathMutator -- why \\u000a y(); // mutant: equivalent" + + " NegateConditionalsMutator -- because"); + + assertAll( + () -> + assertEquals( + Map.of("MathMutator", "why", "NegateConditionalsMutator", "because"), + markers.reasons(), + "reasons"), + () -> assertEquals("x(); \\u000a y();", markers.code(), "code")); + } + + @Test + void aSlashStarMarkerInAJavaLineCommentEndedByAUnicodeEscapeEndsAtTheEscape() { + EquivalentMarkers markers = + java("x(); // see /* mutant: equivalent MathMutator -- why \\u000a y(); /* z */"); + + assertAll( + () -> assertEquals(Map.of("MathMutator", "why"), markers.reasons(), "reasons"), + () -> assertEquals("x(); // see \\u000a y(); /* z */", markers.code(), "code")); + } + + @Test + void aLongRunOfStarsIsReadInLinearTime() { + String line = "/*" + "*".repeat(200000) + "/"; + + EquivalentMarkers markers = + assertTimeoutPreemptively(Duration.ofSeconds(2), () -> java(line), "200000 stars"); + assertEquals(Map.of(), markers.reasons()); + } + + @Test + void manyMarkerTextsInsideABlockCommentAreReadInLinearTime() { + String line = "/* x" + " // mutant: equivalent".repeat(100000) + " */"; + + EquivalentMarkers markers = + assertTimeoutPreemptively(Duration.ofSeconds(2), () -> java(line), "100000 openers"); + assertEquals(Map.of(), markers.reasons()); + } +} diff --git a/cribro-core/src/test/java/io/github/cribrodev/MutantsFileTest.java b/cribro-core/src/test/java/io/github/cribrodev/MutantsFileTest.java index 26a43ea..e2647b5 100644 --- a/cribro-core/src/test/java/io/github/cribrodev/MutantsFileTest.java +++ b/cribro-core/src/test/java/io/github/cribrodev/MutantsFileTest.java @@ -17,6 +17,8 @@ import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.nio.file.Files; @@ -37,8 +39,11 @@ void aMutantWithItsTestsReadsBackUnchanged() throws IOException { "SURVIVED", "com.x.A$Inner", "m", + "(I)Z", "A.java", 12, + "org.pitest.mutationtest.engine.gregor.mutators.NegateConditionalsMutator", + 7, "negated conditional", List.of("com.x.T.a(com.x.T)", "com.x.T.b(com.x.T)")); Path file = directory.resolve(MutantsFile.NAME); @@ -52,8 +57,15 @@ void aMutantWithItsTestsReadsBackUnchanged() throws IOException { () -> assertEquals("SURVIVED", back.status(), "status"), () -> assertEquals("com.x.A$Inner", back.mutatedClass(), "mutatedClass"), () -> assertEquals("m", back.method(), "method"), + () -> assertEquals("(I)Z", back.methodDescriptor(), "methodDescriptor"), () -> assertEquals("A.java", back.sourceFile(), "sourceFile"), () -> assertEquals(12, back.lineNumber(), "lineNumber"), + () -> + assertEquals( + "org.pitest.mutationtest.engine.gregor.mutators.NegateConditionalsMutator", + back.mutator(), + "mutator"), + () -> assertEquals(7, back.firstIndex(), "firstIndex"), () -> assertEquals("negated conditional", back.description(), "description"), () -> assertEquals( @@ -63,9 +75,39 @@ void aMutantWithItsTestsReadsBackUnchanged() throws IOException { @Test void aTabInADescriptionIsWrittenAsASpace() { assertEquals( - "KILLED\tcom.x.A\tm\tA.java\t3\tremoved call to a b", + "KILLED\tcom.x.A\tm\t()V\tA.java\t3\tVoidMethodCallMutator\t0\tremoved call to a b", MutantsFile.line( new MutantsFile.Mutant( - "KILLED", "com.x.A", "m", "A.java", 3, "removed call to a\tb", List.of()))); + "KILLED", + "com.x.A", + "m", + "()V", + "A.java", + 3, + "VoidMethodCallMutator", + 0, + "removed call to a\tb", + List.of()))); + } + + @Test + void aMutantNoTestReachesReadsBackWithNoTests() throws IOException { + Path file = directory.resolve(MutantsFile.NAME); + Files.writeString( + file, "SURVIVED\tcom.x.A\tm\t()V\tA.java\t3\tMathMutator\t0\treplaced math\n"); + + assertEquals(List.of(), MutantsFile.read(file).get(0).tests()); + } + + @Test + void aLineWithoutADescriptionIsRefusedWithTheFileAndTheLine() throws IOException { + Path file = directory.resolve(MutantsFile.NAME); + String line = "SURVIVED\tcom.x.A\tm\t()V\tA.java\t3\tMathMutator\t0"; + Files.writeString(file, line + "\n"); + + IOException refused = assertThrows(IOException.class, () -> MutantsFile.read(file)); + assertAll( + () -> assertTrue(refused.getMessage().contains(file.toString()), refused.getMessage()), + () -> assertTrue(refused.getMessage().contains(line), refused.getMessage())); } } diff --git a/cribro-core/src/test/java/io/github/cribrodev/PitestRunTest.java b/cribro-core/src/test/java/io/github/cribrodev/PitestRunTest.java index 9327b24..302b1e7 100644 --- a/cribro-core/src/test/java/io/github/cribrodev/PitestRunTest.java +++ b/cribro-core/src/test/java/io/github/cribrodev/PitestRunTest.java @@ -157,7 +157,7 @@ void theReportQuotesAMutatedFileFromThePathTheChangedLinesFileNames() throws IOE Files.createDirectories(reportDir); Files.writeString( reportDir.resolve("mutants.tsv"), - "SURVIVED\tdemo.math.CalcKt\ttwo\tCalc.kt\t3\treplaced int return with 0" + "SURVIVED\tdemo.math.CalcKt\ttwo\t()I\tCalc.kt\t3\tPrimitiveReturnsMutator\t0\treplaced int return with 0" + " for demo/math/CalcKt::two\n"); String report = diff --git a/cribro-core/src/test/java/io/github/cribrodev/PitestSurvivorsTest.java b/cribro-core/src/test/java/io/github/cribrodev/PitestSurvivorsTest.java index 6d31d6b..86d315e 100644 --- a/cribro-core/src/test/java/io/github/cribrodev/PitestSurvivorsTest.java +++ b/cribro-core/src/test/java/io/github/cribrodev/PitestSurvivorsTest.java @@ -24,9 +24,11 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.TreeSet; import java.util.stream.Stream; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; @@ -48,20 +50,41 @@ class PitestSurvivorsTest { + " - the tests miss behavior the change defines: add or strengthen a test," + " next to the tests named for its line\n" + " - no caller can observe the difference, so the mutant is equivalent:" - + " say so in the pull request\n" + + " add // mutant: equivalent -- to its line, where is the text in" + + " brackets after the mutant, and say so in the pull request\n" + " - you cannot tell: report it as unresolved"; @TempDir Path repository; /** * Returns the mutants.tsv line for a mutant in method {@code m} of the given class of package - * {@code com.x}, covered by the given tests of class {@code com.x.T}. + * {@code com.x}, covered by the given tests of class {@code com.x.T}. The mutator is named after + * the description, so {@code negated conditional} is made by {@code NegatedConditional}, and the + * mutant changes the instruction at index 0. */ private static String mutation( String status, String className, String file, int line, String description, String... tests) { + return mutation(status, className, file, line, mutatorOf(description), 0, description, tests); + } + + /** + * Returns the mutants.tsv line for a mutant in method {@code m} of the given class of package + * {@code com.x}, made by a mutator of package {@code org.pitest.mutators} that changes the + * instruction at the given index, and covered by the given tests of class {@code com.x.T}. + */ + private static String mutation( + String status, + String className, + String file, + int line, + String mutator, + int index, + String description, + String... tests) { StringBuilder out = new StringBuilder( - status + "\tcom.x." + className + "\tm\t" + file + "\t" + line + "\t" + description + status + "\tcom.x." + className + "\tm\t()V\t" + file + "\t" + line + + "\torg.pitest.mutators." + mutator + "\t" + index + "\t" + description + " for com/x/" + className + "::m"); for (String test : tests) { out.append("\tcom.x.").append(test).append("(com.x.T)"); @@ -69,6 +92,15 @@ private static String mutation( return out.toString(); } + /** Returns the mutator name the one-argument {@code mutation} gives a description. */ + private static String mutatorOf(String description) { + StringBuilder name = new StringBuilder(); + for (String word : description.split(" ")) { + name.append(Character.toUpperCase(word.charAt(0))).append(word.substring(1)); + } + return name.toString(); + } + /** Writes the mutants to mutants.tsv and returns the path. */ private Path mutantsFile(String... mutations) throws IOException { Path file = repository.resolve("mutants.tsv"); @@ -118,6 +150,7 @@ private PitestSurvivors read( repository.toFile(), List.of(new File("absent"), sources.toFile()), paths, + Map.of(), withBytecode); } @@ -133,6 +166,7 @@ private PitestSurvivors runWithoutMutantsFile(Map> withByte repository.toFile(), List.of(repository.toFile()), Map.of(), + Map.of(), withBytecode); } @@ -157,7 +191,7 @@ void aPathTheChangedLinesFileNamesIsQuotedRatherThanTheFileUnderARoot() throws I + "\n" + " gen/A.java\n" + " 2: g2\n" - + " survived: removed call, in m\n" + + " survived: removed call, in m [RemovedCall]\n" + "\n" + "Live mutants on 1 line in 1 file." + LIVE_FOOTER, @@ -176,7 +210,7 @@ void aPathTheChangedLinesFileNamesThatNoLongerExistsFallsBackToTheRoots() throws + "\n" + " src/com/x/A.java\n" + " 2: a2\n" - + " survived: removed call, in m\n" + + " survived: removed call, in m [RemovedCall]\n" + "\n" + "Live mutants on 1 line in 1 file." + LIVE_FOOTER, @@ -196,11 +230,11 @@ void aMutantInTheDefaultPackageIsFoundByItsFileNameUnderARoot() throws IOExcepti + "\n" + " src/D.java\n" + " 1: d1\n" - + " survived: removed call, in m\n" + + " survived: removed call, in m [RemovedCall]\n" + "\n" + "Live mutants on 1 line in 1 file." + LIVE_FOOTER, - run("SURVIVED\tD\tm\tD.java\t1\tremoved call for D::m") + run("SURVIVED\tD\tm\t()V\tD.java\t1\tRemovedCall\t0\tremoved call for D::m") .render(DiffCoverageReport.Limits.NONE, List.of())); } } @@ -214,12 +248,12 @@ void liveMutantsAreGroupedByFileAndLineWithTheTestsThatReachThem() throws IOExce + "\n" + " src/com/x/A.java\n" + " 2: a2\n" - + " survived: negated conditional, in m\n" - + " survived: removed call, in m\n" + + " survived: negated conditional, in m [NegatedConditional]\n" + + " survived: removed call, in m [RemovedCall]\n" + " reached by 1 test:\n" + " T.t1\n" + " 4: a4\n" - + " no test reaches it: replaced return value with null, in m\n" + + " no test reaches it: replaced return value with null, in m [ReplacedReturnValueWithNull]\n" + "\n" + "Live mutants on 2 lines in 1 file." + LIVE_FOOTER, run( @@ -346,7 +380,7 @@ void aRunInWhichNoTestReachedAnyLineSaysWhyThatCanHappen() throws IOException { + "\n" + " src/com/x/A.java\n" + " 1: a1\n" - + " no test reaches it: removed call, in m\n" + + " no test reaches it: removed call, in m [RemovedCall]\n" + "\n" + "Live mutants on 1 line in 1 file." + LIVE_FOOTER, @@ -363,13 +397,13 @@ void theFileWithMoreLiveMutantsComesFirst() throws IOException { + "\n" + " src/com/x/B.java\n" + " 1: b1\n" - + " survived: removed call, in m\n" + + " survived: removed call, in m [RemovedCall]\n" + " 2: b2\n" - + " survived: removed call, in m\n" + + " survived: removed call, in m [RemovedCall]\n" + "\n" + " src/com/x/A.java\n" + " 1: a1\n" - + " survived: removed call, in m\n" + + " survived: removed call, in m [RemovedCall]\n" + "\n" + "Live mutants on 3 lines in 2 files." + LIVE_FOOTER, run( @@ -388,7 +422,7 @@ void theTotalLineLimitEndsTheReportAfterTheLinesItAllows() throws IOException { + "\n" + " src/com/x/B.java\n" + " 1: b1\n" - + " survived: removed call, in m\n" + + " survived: removed call, in m [RemovedCall]\n" + " 1 more line\n" + "\n" + " 1 more file\n" @@ -443,7 +477,7 @@ void theTestsNamedFirstAreTheOnesReachingTheMostLiveMutants() throws IOException + "\n" + " src/com/x/A.java\n" + " 1: a1\n" - + " survived: removed call, in m\n" + + " survived: removed call, in m [RemovedCall]\n" + " reached by 5 tests, among them:\n" + " T.d\n" + " T.e\n" @@ -451,7 +485,7 @@ void theTestsNamedFirstAreTheOnesReachingTheMostLiveMutants() throws IOException + "\n" + " src/com/x/B.java\n" + " 1: b1\n" - + " survived: removed call, in m\n" + + " survived: removed call, in m [RemovedCall]\n" + " reached by 2 tests:\n" + " T.d\n" + " T.e\n" @@ -476,15 +510,15 @@ void theInvocationsOfOneTestShareARowAndCountAsOneTest() throws IOException { + "\n" + " src/com/x/A.java\n" + " 1: a1\n" - + " survived: removed call, in m\n" - + " survived: negated conditional, in m\n" + + " survived: removed call, in m [RemovedCall]\n" + + " survived: negated conditional, in m [NegatedConditional]\n" + " reached by 2 tests:\n" + " U.q\n" + " T.p[1-3, 10, 33]\n" + "\n" + " src/com/x/B.java\n" + " 1: b1\n" - + " survived: removed call, in m\n" + + " survived: removed call, in m [RemovedCall]\n" + " reached by 1 test:\n" + " U.q\n" + "\n" @@ -541,7 +575,7 @@ void theLimitsCutLinesAndFilesAndTheReportNamesTheFullOne() throws IOException { + "\n" + " src/com/x/A.java\n" + " 1: a1\n" - + " survived: removed call, in m\n" + + " survived: removed call, in m [RemovedCall]\n" + " 1 more line\n" + "\n" + " 1 more file\n" @@ -569,6 +603,7 @@ void aRunThatWroteNoReportSaysNoMutantWasAnalyzed() throws IOException { repository.toFile(), List.of(repository.toFile()), Map.of(), + Map.of(), null); assertEquals( @@ -603,6 +638,7 @@ void aSourceFileThatIsNotUtf8LeavesTheLineUnquoted() throws IOException { repository.toFile(), List.of(sources.toFile()), Map.of(), + Map.of(), Map.of()); assertEquals( @@ -612,7 +648,7 @@ void aSourceFileThatIsNotUtf8LeavesTheLineUnquoted() throws IOException { + "\n" + " src/com/x/A.java\n" + " 1: \n" - + " survived: removed call, in m\n" + + " survived: removed call, in m [RemovedCall]\n" + "\n" + "Live mutants on 1 line in 1 file." + LIVE_FOOTER, @@ -629,6 +665,563 @@ void aConstructorIsNamedAsSuch() { assertEquals("a constructor", PitestSurvivors.readableMethod("")); } + @Nested + class TheEquivalentMarker { + + private static final String SCOPE = + "Mutation testing of changed lines against origin/master (abc), all tests\n"; + + /** + * Returns the mutants.tsv line for a mutant of the given class of package {@code com.x}, in + * file A.java, made by a mutator of package {@code org.pitest.mutators}, covered by no test. + */ + private String row( + String status, + String className, + String method, + String descriptor, + int line, + String mutator, + int index, + String description) { + return status + "\tcom.x." + className + "\t" + method + "\t" + descriptor + "\tA.java\t" + + line + "\torg.pitest.mutators." + mutator + "\t" + index + "\t" + description; + } + + /** + * Reads a run whose only source is com/x/A.java with the given text, and every line of which + * is a changed line with bytecode. + */ + private PitestSurvivors runOn(String source, String... mutations) throws IOException { + Set changed = new TreeSet<>(); + for (int line = 1; line <= source.split("\n").length; line++) { + changed.add(line); + } + return runOn("A.java", changed, source, mutations); + } + + /** + * Reads a run whose only source is the given file of package com.x, with the given text, whose + * changed lines with bytecode are the given ones. + */ + private PitestSurvivors runOn( + String fileName, Set changed, String source, String... mutations) + throws IOException { + return runOn(Map.of(fileName, source), Map.of(fileName, changed), mutations); + } + + /** + * Reads a run whose sources are the given files of package com.x, each with its text, and whose + * changed lines with bytecode are the given ones of each file. + */ + private PitestSurvivors runOn( + Map sourceOf, Map> changedOf, String... mutations) + throws IOException { + Path sources = repository.resolve("src"); + Files.createDirectories(sources.resolve("com/x")); + for (Map.Entry file : sourceOf.entrySet()) { + Files.writeString(sources.resolve("com/x/" + file.getKey()), file.getValue()); + } + Map> changed = new HashMap<>(); + changedOf.forEach((fileName, lines) -> changed.put("com/x/" + fileName, lines)); + return PitestSurvivors.read( + "against origin/master (abc), all tests", + mutantsFile(mutations).toFile(), + repository.toFile(), + List.of(sources.toFile()), + Map.of(), + changed, + changed); + } + + @Test + void aKilledMutantKeepsItsNumberSoTheLiveOneKeepsItsId() throws IOException { + assertEquals( + SCOPE + + " 2 mutants on 1 of 1 changed line: 1 killed, 1 survived, 0 not reached by any test;" + + " 1 of the live ones acknowledged as equivalent\n" + + "\n" + + "Live mutants acknowledged as equivalent:\n" + + "\n" + + " src/com/x/A.java\n" + + " 1: x();\n" + + " survived: replaced math, in m [MathMutator#2]\n" + + " reason: why", + runOn( + "x(); // mutant: equivalent MathMutator#2 -- why\n", + mutation("KILLED", "A", "A.java", 1, "MathMutator", 3, "replaced math"), + mutation("SURVIVED", "A", "A.java", 1, "MathMutator", 7, "replaced math")) + .render(DiffCoverageReport.Limits.NONE, List.of())); + } + + @Test + void aMutantNoTestReachesIsAcknowledgedAsASurvivorIs() throws IOException { + assertEquals( + SCOPE + + " 1 mutant on 1 of 1 changed line: 0 killed, 0 survived, 1 not reached by any test;" + + " 1 of the live ones acknowledged as equivalent\n" + + "\n" + + PitestSurvivors.NOTHING_REACHED + + "\n\n" + + "Live mutants acknowledged as equivalent:\n" + + "\n" + + " src/com/x/A.java\n" + + " 1: x();\n" + + " no test reaches it: replaced math, in m [MathMutator]\n" + + " reason: why", + runOn( + "x(); // mutant: equivalent MathMutator -- why\n", + mutation("NO_COVERAGE", "A", "A.java", 1, "MathMutator", 0, "replaced math")) + .render(DiffCoverageReport.Limits.NONE, List.of())); + } + + @Test + void aMarkerWithOneIdThatNamesNoMutantIsListedAndItsOtherIdsStillAcknowledge() + throws IOException { + assertEquals( + SCOPE + + " 1 mutant on 1 of 1 changed line: 0 killed, 1 survived, 0 not reached by any test;" + + " 1 of the live ones acknowledged as equivalent\n" + + "\n" + + "Markers to correct:\n" + + "\n" + + " src/com/x/A.java\n" + + " 1: x(); // mutant: equivalent MathMutator, VoidMethodCallMutator -- why\n" + + " VoidMethodCallMutator: no mutant on the line has this id\n" + + " the line has MathMutator (SURVIVED)\n" + + "\n" + + PitestSurvivors.MARKERS_TO_CORRECT + + "\n\n" + + "Live mutants acknowledged as equivalent:\n" + + "\n" + + " src/com/x/A.java\n" + + " 1: x();\n" + + " survived: replaced math, in m [MathMutator]\n" + + " reason: why", + runOn( + "x(); // mutant: equivalent MathMutator, VoidMethodCallMutator -- why\n", + mutation("SURVIVED", "A", "A.java", 1, "MathMutator", 0, "replaced math")) + .render(DiffCoverageReport.Limits.NONE, List.of())); + } + + @Test + void aMarkerOnALineTheChangeLeavesIsNotRead() throws IOException { + assertEquals( + SCOPE + + " no mutant: PIT generated none on the 1 changed line\n\n" + + PitestSurvivors.AVOIDED_CALLS, + runOn("A.java", Set.of(2), "x(); // mutant: equivalent MathMutator -- why\ny();\n") + .render(DiffCoverageReport.Limits.NONE, List.of())); + } + + @Test + void aKotlinFileIsReadByTheRulesOfKotlin() throws IOException { + // Kotlin block comments nest, so the comment ends at the second close and the marker after + // it counts; read as Java, the quote after the first close would open a string. + assertEquals( + SCOPE + + " 1 mutant on 1 of 1 changed line: 0 killed, 1 survived, 0 not reached by any test;" + + " 1 of the live ones acknowledged as equivalent\n" + + "\n" + + "Live mutants acknowledged as equivalent:\n" + + "\n" + + " src/com/x/A.kt\n" + + " 1: /* a /* b */ \" */ x()\n" + + " survived: replaced math, in m [MathMutator]\n" + + " reason: why", + runOn( + "A.kt", + Set.of(1), + "/* a /* b */ \" */ x() // mutant: equivalent MathMutator -- why\n", + mutation("SURVIVED", "A", "A.kt", 1, "MathMutator", 0, "replaced math")) + .render(DiffCoverageReport.Limits.NONE, List.of())); + } + + @Test + void anAcknowledgedMutantLeavesTheListOfWorkAndStaysInTheCounts() throws IOException { + assertEquals( + SCOPE + + " 3 mutants on 1 of 1 changed line: 0 killed, 3 survived, 0 not reached by any test;" + + " 1 of the live ones acknowledged as equivalent\n" + + " ordered by live mutants per file, then by line\n" + + "\n" + + " src/com/x/A.java\n" + + " 1: if (a || b) {\n" + + " survived: removed conditional, in m [RemoveConditionalMutator_EQUAL_ELSE#2]\n" + + " survived: negated conditional, in m [NegateConditionalsMutator]\n" + + " reached by 1 test:\n" + + " T.t1\n" + + "\n" + + "Live mutants on 1 line in 1 file." + + LIVE_FOOTER + + "\n\n" + + "Live mutants acknowledged as equivalent:\n" + + "\n" + + " src/com/x/A.java\n" + + " 1: if (a || b) {\n" + + " survived: removed conditional, in m [RemoveConditionalMutator_EQUAL_ELSE#1]\n" + + " reason: a is checked before", + runOn( + "if (a || b) { // mutant: equivalent RemoveConditionalMutator_EQUAL_ELSE#1 --" + + " a is checked before\n", + mutation( + "SURVIVED", "A", "A.java", 1, "RemoveConditionalMutator_EQUAL_ELSE", 6, + "removed conditional", "T.t1"), + mutation( + "SURVIVED", "A", "A.java", 1, "RemoveConditionalMutator_EQUAL_ELSE", 4, + "removed conditional", "T.t2"), + mutation( + "SURVIVED", "A", "A.java", 1, "NegateConditionalsMutator", 4, + "negated conditional", "T.t1")) + .render(DiffCoverageReport.Limits.NONE, List.of()), + "#1 is the mutant of the lower instruction index whatever the order PIT reports them in," + + " and only the live mutants left in the list name the tests that reach them"); + } + + @Test + void whereEveryLiveMutantIsAcknowledgedTheReportAsksForNothing() throws IOException { + assertEquals( + SCOPE + + " 1 mutant on 1 of 1 changed line: 0 killed, 1 survived, 0 not reached by any test;" + + " 1 of the live ones acknowledged as equivalent\n" + + "\n" + + "Live mutants acknowledged as equivalent:\n" + + "\n" + + " src/com/x/A.java\n" + + " 1: x();\n" + + " survived: replaced math, in m [MathMutator]\n" + + " reason: why", + runOn( + "x(); // mutant: equivalent MathMutator -- why\n", + mutation("SURVIVED", "A", "A.java", 1, "MathMutator", 0, "replaced math")) + .render(DiffCoverageReport.Limits.NONE, List.of())); + } + + @Test + void numbersFollowTheMethodItsDescriptorTheClassAndTheIndexNotTheOrderPitReports() + throws IOException { + // Each pair of rows differs in one key, PIT reports the row that sorts second first, and the + // descriptions sort the other way, so only the key under test can give the expected numbers. + assertEquals( + SCOPE + + " 8 mutants on 4 of 4 changed lines: 0 killed, 8 survived, 0 not reached by any test\n" + + " ordered by live mutants per file, then by line\n" + + "\n" + + " src/com/x/A.java\n" + + " 1: by method\n" + + " survived: a, in m [MathMutator#2]\n" + + " survived: b, in a lambda in m [MathMutator#1]\n" + + " 2: by descriptor\n" + + " survived: a, in m [MathMutator#2]\n" + + " survived: b, in m [MathMutator#1]\n" + + " 3: by class\n" + + " survived: a, in m [MathMutator#2]\n" + + " survived: b, in m [MathMutator#1]\n" + + " 4: by index\n" + + " survived: a, in m [MathMutator#2]\n" + + " survived: b, in m [MathMutator#1]\n" + + "\n" + + "Live mutants on 4 lines in 1 file." + + LIVE_FOOTER, + runOn( + "by method\nby descriptor\nby class\nby index\n", + row("SURVIVED", "A", "m", "()V", 1, "MathMutator", 0, "a"), + row("SURVIVED", "A", "lambda$m$0", "()V", 1, "MathMutator", 0, "b"), + row("SURVIVED", "A", "m", "(J)V", 2, "MathMutator", 0, "a"), + row("SURVIVED", "A", "m", "(I)V", 2, "MathMutator", 0, "b"), + row("SURVIVED", "A$B", "m", "()V", 3, "MathMutator", 0, "a"), + row("SURVIVED", "A", "m", "()V", 3, "MathMutator", 0, "b"), + row("SURVIVED", "A", "m", "()V", 4, "MathMutator", 7, "a"), + row("SURVIVED", "A", "m", "()V", 4, "MathMutator", 3, "b")) + .render(DiffCoverageReport.Limits.NONE, List.of())); + } + + @Test + void numbersOrderMethodAndClassNamesWithEachRunOfDigitsAsANumber() throws IOException { + // javac numbers lambdas and anonymous classes with one counter per class, so a lambda added + // above both renumbers $8 and $9 to $9 and $10, and their order has to stay the same. Lines 1 + // and 3 report their pair in reverse order and lines 2 and 4 in order, because sorting two + // mutants compares them in one direction only. + assertEquals( + SCOPE + + " 8 mutants on 4 of 4 changed lines: 0 killed, 8 survived, 0 not reached by any test\n" + + " ordered by live mutants per file, then by line\n" + + "\n" + + " src/com/x/A.java\n" + + " 1: more digits in a method\n" + + " survived: a, in a lambda in m [MathMutator#2]\n" + + " survived: b, in a lambda in m [MathMutator#1]\n" + + " 2: more digits in a class\n" + + " survived: b, in m [MathMutator#1]\n" + + " survived: a, in m [MathMutator#2]\n" + + " 3: as many digits\n" + + " survived: a, in a lambda in m [MathMutator#2]\n" + + " survived: b, in a lambda in m [MathMutator#1]\n" + + " 4: one class name starts the other\n" + + " survived: b, in m [MathMutator#1]\n" + + " survived: a, in m [MathMutator#2]\n" + + "\n" + + "Live mutants on 4 lines in 1 file." + + LIVE_FOOTER, + runOn( + "more digits in a method\nmore digits in a class\nas many digits\n" + + "one class name starts the other\n", + row("SURVIVED", "A", "lambda$m$10", "()V", 1, "MathMutator", 0, "a"), + row("SURVIVED", "A", "lambda$m$9", "()V", 1, "MathMutator", 0, "b"), + row("SURVIVED", "A$9", "m", "()V", 2, "MathMutator", 0, "b"), + row("SURVIVED", "A$10", "m", "()V", 2, "MathMutator", 0, "a"), + row("SURVIVED", "A", "lambda$m$19", "()V", 3, "MathMutator", 0, "a"), + row("SURVIVED", "A", "lambda$m$18", "()V", 3, "MathMutator", 0, "b"), + row("SURVIVED", "A", "m", "()V", 4, "MathMutator", 0, "b"), + row("SURVIVED", "A$1", "m", "()V", 4, "MathMutator", 0, "a")) + .render(DiffCoverageReport.Limits.NONE, List.of())); + } + + @Test + void aMarkerThatAcknowledgesNoLiveMutantIsListedWithTheIdsOfItsLine() throws IOException { + assertEquals( + SCOPE + + " 8 mutants on 6 of 7 changed lines: 2 killed (1 timed out), 5 survived," + + " 0 not reached by any test, 1 NON_VIABLE;" + + " 1 of the live ones acknowledged as equivalent\n" + + " ordered by live mutants per file, then by line\n" + + "\n" + + " src/com/x/A.java\n" + + " 1: x();\n" + + " survived: removed conditional, in m [RemoveConditionalMutator_EQUAL_ELSE#1]\n" + + " survived: removed conditional, in m [RemoveConditionalMutator_EQUAL_ELSE#2]\n" + + " 3: z();\n" + + " survived: replaced math, in m [MathMutator]\n" + + " 7: t();\n" + + " survived: replaced math, in m [MathMutator]\n" + + "\n" + + "Live mutants on 3 lines in 1 file." + + LIVE_FOOTER + + "\n\n" + + "Markers to correct:\n" + + "\n" + + " src/com/x/A.java\n" + + " 1: x(); // mutant: equivalent RemoveConditionalMutator_EQUAL_ELSE -- one of two\n" + + " RemoveConditionalMutator_EQUAL_ELSE: no mutant on the line has this id\n" + + " the line has RemoveConditionalMutator_EQUAL_ELSE#1 (SURVIVED)," + + " RemoveConditionalMutator_EQUAL_ELSE#2 (SURVIVED)\n" + + " 2: y(); /* mutant: equivalent */ // mutant: equivalent VoidMethodCallMutator" + + " -- was untested\n" + + " the marker does not parse; write it as" + + " // mutant: equivalent -- \n" + + " VoidMethodCallMutator: the tests kill this mutant, so it is not equivalent\n" + + " the line has VoidMethodCallMutator (KILLED)\n" + + " 3: z(); // mutant: equivalent\n" + + " the marker does not parse; write it as" + + " // mutant: equivalent -- \n" + + " the line has MathMutator (SURVIVED)\n" + + " 4: w(); // mutant: equivalent MathMutator -- gone\n" + + " MathMutator: no mutant on the line has this id\n" + + " PIT generated no mutant on the line\n" + + " 6: u(); // mutant: equivalent MathMutator, NegateConditionalsMutator -- slow\n" + + " MathMutator: PIT reports this mutant as TIMED_OUT\n" + + " NegateConditionalsMutator: PIT reports this mutant as NON_VIABLE\n" + + " the line has MathMutator (TIMED_OUT), NegateConditionalsMutator (NON_VIABLE)\n" + + "\n" + + PitestSurvivors.MARKERS_TO_CORRECT + + "\n\n" + + "Live mutants acknowledged as equivalent:\n" + + "\n" + + " src/com/x/A.java\n" + + " 5: v();\n" + + " survived: replaced math, in m [MathMutator]\n" + + " reason: still holds" + + "\n\n" + + PitestSurvivors.AVOIDED_CALLS, + runOn( + "x(); // mutant: equivalent RemoveConditionalMutator_EQUAL_ELSE -- one of two\n" + + "y(); /* mutant: equivalent */ // mutant: equivalent VoidMethodCallMutator" + + " -- was untested\n" + + "z(); // mutant: equivalent\n" + + "w(); // mutant: equivalent MathMutator -- gone\n" + + "v(); // mutant: equivalent MathMutator -- still holds\n" + + "u(); // mutant: equivalent MathMutator, NegateConditionalsMutator -- slow\n" + + "t();\n", + mutation( + "SURVIVED", "A", "A.java", 1, "RemoveConditionalMutator_EQUAL_ELSE", 4, + "removed conditional"), + mutation( + "SURVIVED", "A", "A.java", 1, "RemoveConditionalMutator_EQUAL_ELSE", 6, + "removed conditional"), + mutation("KILLED", "A", "A.java", 2, "VoidMethodCallMutator", 0, "removed call"), + mutation("SURVIVED", "A", "A.java", 3, "MathMutator", 0, "replaced math"), + mutation("SURVIVED", "A", "A.java", 5, "MathMutator", 0, "replaced math"), + mutation("TIMED_OUT", "A", "A.java", 6, "MathMutator", 0, "replaced math"), + mutation( + "NON_VIABLE", "A", "A.java", 6, "NegateConditionalsMutator", 0, + "negated conditional"), + mutation("SURVIVED", "A", "A.java", 7, "MathMutator", 0, "replaced math")) + .render(DiffCoverageReport.Limits.NONE, List.of())); + } + + @Test + void theConsoleLimitsHoldAcrossTheLiveListTheMarkersAndTheAcknowledgedMutants() + throws IOException { + assertEquals( + SCOPE + + " 3 mutants on 3 of 3 changed lines: 1 killed, 2 survived, 0 not reached by any test;" + + " 1 of the live ones acknowledged as equivalent\n" + + " ordered by live mutants per file, then by line\n" + + "\n" + + " src/com/x/A.java\n" + + " 1: x();\n" + + " survived: replaced math, in m [MathMutator]\n" + + "\n" + + "Live mutants on 1 line in 1 file." + + LIVE_FOOTER + + "\n\n" + + "Markers to correct:\n" + + "\n" + + " 1 more file\n" + + "\n" + + PitestSurvivors.MARKERS_TO_CORRECT + + "\n\n" + + "Live mutants acknowledged as equivalent:\n" + + "\n" + + " 1 more file", + runOn( + "x();\n" + + "y(); // mutant: equivalent VoidMethodCallMutator -- was untested\n" + + "v(); // mutant: equivalent MathMutator -- still holds\n", + mutation("SURVIVED", "A", "A.java", 1, "MathMutator", 0, "replaced math"), + mutation("KILLED", "A", "A.java", 2, "VoidMethodCallMutator", 0, "removed call"), + mutation("SURVIVED", "A", "A.java", 3, "MathMutator", 0, "replaced math")) + .render(new DiffCoverageReport.Limits(10, 10, 1), List.of())); + } + + @Test + void theMarkersAndTheAcknowledgedMutantsAreListedInTheOrderOfTheirPaths() throws IOException { + String source = + "x(); // mutant: equivalent MathMutator -- why\n" + + "y(); // mutant: equivalent VoidMethodCallMutator -- gone\n"; + assertEquals( + SCOPE + + " 2 mutants on 2 of 4 changed lines: 0 killed, 2 survived, 0 not reached by any test;" + + " 2 of the live ones acknowledged as equivalent\n" + + "\n" + + "Markers to correct:\n" + + "\n" + + " src/com/x/A.java\n" + + " 2: y(); // mutant: equivalent VoidMethodCallMutator -- gone\n" + + " VoidMethodCallMutator: no mutant on the line has this id\n" + + " PIT generated no mutant on the line\n" + + "\n" + + " src/com/x/C.java\n" + + " 2: y(); // mutant: equivalent VoidMethodCallMutator -- gone\n" + + " VoidMethodCallMutator: no mutant on the line has this id\n" + + " PIT generated no mutant on the line\n" + + "\n" + + PitestSurvivors.MARKERS_TO_CORRECT + + "\n\n" + + "Live mutants acknowledged as equivalent:\n" + + "\n" + + " src/com/x/A.java\n" + + " 1: x();\n" + + " survived: replaced math, in m [MathMutator]\n" + + " reason: why\n" + + "\n" + + " src/com/x/C.java\n" + + " 1: x();\n" + + " survived: replaced math, in m [MathMutator]\n" + + " reason: why\n" + + "\n" + + PitestSurvivors.AVOIDED_CALLS, + runOn( + Map.of("C.java", source, "A.java", source), + Map.of("C.java", Set.of(1, 2), "A.java", Set.of(1, 2)), + mutation("SURVIVED", "C", "C.java", 1, "MathMutator", 0, "replaced math"), + mutation("SURVIVED", "A", "A.java", 1, "MathMutator", 0, "replaced math")) + .render(DiffCoverageReport.Limits.NONE, List.of())); + } + + @Test + void theMarkersCutByTheConsoleLimitsAreCountedInLinesAndFiles() throws IOException { + String source = + "x(); // mutant: equivalent\ny(); // mutant: equivalent\nz(); // mutant: equivalent\n"; + assertEquals( + SCOPE + + " no mutant: PIT generated none on the 9 changed lines\n" + + "\n" + + "Markers to correct:\n" + + "\n" + + " src/com/x/A.java\n" + + " 1: x(); // mutant: equivalent\n" + + " the marker does not parse; write it as" + + " // mutant: equivalent -- \n" + + " PIT generated no mutant on the line\n" + + " 2 more lines\n" + + "\n" + + " 2 more files\n" + + "\n" + + PitestSurvivors.MARKERS_TO_CORRECT + + "\n\n" + + PitestSurvivors.AVOIDED_CALLS, + runOn( + Map.of("A.java", source, "B.java", source, "C.java", source), + Map.of( + "A.java", Set.of(1, 2, 3), + "B.java", Set.of(1, 2, 3), + "C.java", Set.of(1, 2, 3))) + .render(new DiffCoverageReport.Limits(1, 1, 10), List.of())); + } + + @Test + void aMutantOnALineTheWorkingTreeNoLongerHasIsListedWithoutAMarker() throws IOException { + assertEquals( + SCOPE + + " 1 mutant on 1 of 1 changed line: 0 killed, 1 survived, 0 not reached by any test\n" + + " ordered by live mutants per file, then by line\n" + + "\n" + + " src/com/x/A.java\n" + + " 3: \n" + + " survived: replaced math, in m [MathMutator]\n" + + "\n" + + "Live mutants on 1 line in 1 file." + + LIVE_FOOTER, + runOn( + "A.java", + Set.of(3), + "x(); // mutant: equivalent MathMutator -- why\n", + mutation("SURVIVED", "A", "A.java", 3, "MathMutator", 0, "replaced math")) + .render(DiffCoverageReport.Limits.NONE, List.of())); + } + + @Test + void aMutantOfAFileNoSourceRootHoldsIsListedWithoutAMarker() throws IOException { + assertEquals( + SCOPE + + " 2 mutants on 2 of 2 changed lines: 0 killed, 2 survived, 0 not reached by any test;" + + " 1 of the live ones acknowledged as equivalent\n" + + " ordered by live mutants per file, then by line\n" + + "\n" + + " com/x/B.java\n" + + " 1: \n" + + " survived: replaced math, in m [MathMutator]\n" + + "\n" + + "Live mutants on 1 line in 1 file." + + LIVE_FOOTER + + "\n\n" + + "Live mutants acknowledged as equivalent:\n" + + "\n" + + " src/com/x/A.java\n" + + " 1: x();\n" + + " survived: replaced math, in m [MathMutator]\n" + + " reason: why", + runOn( + "A.java", + Set.of(1), + "x(); // mutant: equivalent MathMutator -- why\n", + mutation("SURVIVED", "A", "A.java", 1, "MathMutator", 0, "replaced math"), + mutation("SURVIVED", "B", "B.java", 1, "MathMutator", 0, "replaced math")) + .render(DiffCoverageReport.Limits.NONE, List.of())); + } + } + @Nested class TestNames { diff --git a/cribro-core/src/test/java/io/github/cribrodev/pitest/MutantsFileListenerFactoryTest.java b/cribro-core/src/test/java/io/github/cribrodev/pitest/MutantsFileListenerFactoryTest.java index 7d75e29..5348def 100644 --- a/cribro-core/src/test/java/io/github/cribrodev/pitest/MutantsFileListenerFactoryTest.java +++ b/cribro-core/src/test/java/io/github/cribrodev/pitest/MutantsFileListenerFactoryTest.java @@ -45,7 +45,7 @@ private static MutationResult result( Location location = new Location(ClassName.fromString("com.x.A"), "m", "()V"); MutationDetails details = new MutationDetails( - new MutationIdentifier(location, 0, "NEGATE_CONDITIONALS"), + new MutationIdentifier(location, 3, "NEGATE_CONDITIONALS"), "A.java", description, line, @@ -68,8 +68,10 @@ void everyMutantIsWrittenWithItsCoveringTests() { listener.runEnd(); assertEquals( - "SURVIVED\tcom.x.A\tm\tA.java\t7\tnegated conditional\tcom.x.T.a(com.x.T)\n" - + "KILLED\tcom.x.A\tm\tA.java\t8\tremoved call\tcom.x.T.b(com.x.T)\n", + "SURVIVED\tcom.x.A\tm\t()V\tA.java\t7\tNEGATE_CONDITIONALS\t3\tnegated conditional" + + "\tcom.x.T.a(com.x.T)\n" + + "KILLED\tcom.x.A\tm\t()V\tA.java\t8\tNEGATE_CONDITIONALS\t3\tremoved call" + + "\tcom.x.T.b(com.x.T)\n", out.toString()); } diff --git a/cribro-gradle-plugin/src/main/resources/io/github/cribrodev/guide.md b/cribro-gradle-plugin/src/main/resources/io/github/cribrodev/guide.md index fbf1af0..02b079b 100644 --- a/cribro-gradle-plugin/src/main/resources/io/github/cribrodev/guide.md +++ b/cribro-gradle-plugin/src/main/resources/io/github/cribrodev/guide.md @@ -80,9 +80,30 @@ PIT changes one instruction at a time on the changed lines and runs the tests ag survives marks a changed line whose behavior no test asserts. For each live mutant, decide which case it is: - the tests miss behavior the change defines: add or strengthen a test next to the tests the report names for that line; -- no caller can observe the difference: the mutant is equivalent, so say so in the pull request; +- no caller can observe the difference: the mutant is equivalent, so mark it on its line and say so in the pull request; - you cannot tell: report it as unresolved. +The report ends each mutant with its id in brackets, such as `[RemoveConditionalMutator_EQUAL_ELSE#2]`: the PIT mutator, +with a number where the mutator made more than one mutant on the line. The number counts them by method and, within a +method, in bytecode order, so on `a || b` the mutant of `a` comes first. Record an equivalent mutant on its line with +`// mutant: equivalent -- `, where `` is the text in the brackets, or with +`/* ... */` where the line goes on after it; several ids are separated by commas. Put the marker last on its line: the +reason of a `//` marker runs to the end of the line, so a `// diff-coverage: ignore` after it becomes part of the +reason. The marker counts where it starts a comment or sits anywhere later in a line comment, even where that text only +quotes the syntax; one inside a string literal or in the text of a block comment, such as a Javadoc paragraph, does not +count. The mutant leaves the list of live mutants and stays in the counts, the line with the counts ends with how many +live mutants are acknowledged, such as `; 1 of the live ones acknowledged as equivalent`, and the report lists the +mutant under `Live mutants acknowledged as equivalent` with the reason every time the line is changed again; +`survivors.txt` holds the whole list when the console cuts it. The number depends on the other mutants the same mutator +makes on the line, so when the line changes, check that each acknowledged id still names the mutant its reason is about. + +A marker is read only on a changed line. A marker that does not parse, or that has an id naming no mutant of its line or +a mutant that is not live (the tests killed it, or PIT gave it another status, such as `NON_VIABLE`), is listed under +`Markers to correct` with its line as written, followed by every id the line has and its status. Where an id names a +mutant that is not live, or no mutant, the code or the tests have likely changed since the verdict, so judge the line +again. A marker that names a mutator of a stronger group, such as `RemoveConditionalMutator_*`, names nothing in a run +with `DEFAULTS`: keep it, and check it in a run with the group it was written for. + The report opens with the number of mutants and of the changed lines with bytecode that carry one, such as `8 mutants on 7 of 24 changed lines`. Mutation testing checks nothing on the other changed lines, whatever their coverage. A parameterized test is named once per line, with the invocations that reach it, such as `CoreQuidemTest.test[1-3, 33]`. diff --git a/cribro-gradle-plugin/src/test/java/io/github/cribrodev/KotlinBuildTest.java b/cribro-gradle-plugin/src/test/java/io/github/cribrodev/KotlinBuildTest.java index c1dd637..4add88d 100644 --- a/cribro-gradle-plugin/src/test/java/io/github/cribrodev/KotlinBuildTest.java +++ b/cribro-gradle-plugin/src/test/java/io/github/cribrodev/KotlinBuildTest.java @@ -52,8 +52,11 @@ class KotlinBuildTest { * {@code next} or {@code log}. The file lies at the root of {@code src/main/kotlin} and declares a * package, so its directory does not follow it. The closing brace of {@code log} carries the * method's return instruction and holds no code. + * + * @param comment the text that ends line 4, the {@code if} of {@code max}, after a space, or an + * empty string for none */ - private void writeBuild() throws IOException { + private void writeBuild(String comment) throws IOException { Files.writeString( build.resolve("settings.gradle"), "plugins { id '" + CribroSettingsPlugin.ID + "' }\nrootProject.name = 'demo'\n", @@ -79,7 +82,7 @@ testImplementation platform('org.junit:junit-bom:5.14.4') package demo.math fun max(a: Int, b: Int): Int { - if (a > b) { + if (a > b) {%s return a } return b @@ -92,7 +95,8 @@ fun next(a: Int): Int { fun log(a: Int) { println(a) } - """); + """ + .formatted(comment.isEmpty() ? "" : " " + comment)); write( "src/test/kotlin/demo/math/CalcTest.kt", """ @@ -136,7 +140,7 @@ private void git(String... arguments) throws IOException, InterruptedException { @Test void aKotlinFileIsMeasuredByThePackageItDeclaresRatherThanItsDirectory() throws Exception { - writeBuild(); + writeBuild(""); commitAsChange(); BuildResult result = @@ -165,6 +169,35 @@ void aKotlinFileIsMeasuredByThePackageItDeclaresRatherThanItsDirectory() throws () -> assertContains(output, "no test reaches it: Replaced integer addition with subtraction, in next")); } + @Test + void aMarkerNamingTheIdPitPrintsAcknowledgesTheMutant() throws Exception { + writeBuild( + "// mutant: equivalent ConditionalsBoundaryMutator -- max returns a or b, which are equal" + + " where > and >= differ"); + commitAsChange(); + + BuildResult result = + GradleRunner.create() + .withProjectDir(build.toFile()) + .withPluginClasspath() + .withArguments("--quiet", "test", "pitestDiff", "-Pcribro.diffBase=HEAD~1") + .build(); + + String output = result.getOutput(); + assertAll( + () -> assertContains(output, "; 1 of the live ones acknowledged as equivalent\n"), + () -> + assertContains( + output, + "Live mutants acknowledged as equivalent:\n" + + "\n" + + " src/main/kotlin/Calc.kt\n" + + " 4: if (a > b) {\n" + + " survived: changed conditional boundary, in max" + + " [ConditionalsBoundaryMutator]\n" + + " reason: max returns a or b, which are equal where > and >= differ\n")); + } + /** Returns the number the first group of {@code regex} captures in the output. */ private static int number(String output, String regex) { Matcher matcher = Pattern.compile(regex).matcher(output); diff --git a/cribro-maven-plugin/src/main/resources/io/github/cribrodev/maven/guide.md b/cribro-maven-plugin/src/main/resources/io/github/cribrodev/maven/guide.md index b5447a6..c52e98c 100644 --- a/cribro-maven-plugin/src/main/resources/io/github/cribrodev/maven/guide.md +++ b/cribro-maven-plugin/src/main/resources/io/github/cribrodev/maven/guide.md @@ -85,9 +85,30 @@ PIT changes one instruction at a time on the changed lines and runs the tests ag survives marks a changed line whose behavior no test asserts. For each live mutant, decide which case it is: - the tests miss behavior the change defines: add or strengthen a test next to the tests the report names for that line; -- no caller can observe the difference: the mutant is equivalent, so say so in the pull request; +- no caller can observe the difference: the mutant is equivalent, so mark it on its line and say so in the pull request; - you cannot tell: report it as unresolved. +The report ends each mutant with its id in brackets, such as `[RemoveConditionalMutator_EQUAL_ELSE#2]`: the PIT mutator, +with a number where the mutator made more than one mutant on the line. The number counts them by method and, within a +method, in bytecode order, so on `a || b` the mutant of `a` comes first. Record an equivalent mutant on its line with +`// mutant: equivalent -- `, where `` is the text in the brackets, or with +`/* ... */` where the line goes on after it; several ids are separated by commas. Put the marker last on its line: the +reason of a `//` marker runs to the end of the line, so a `// diff-coverage: ignore` after it becomes part of the +reason. The marker counts where it starts a comment or sits anywhere later in a line comment, even where that text only +quotes the syntax; one inside a string literal or in the text of a block comment, such as a Javadoc paragraph, does not +count. The mutant leaves the list of live mutants and stays in the counts, the line with the counts ends with how many +live mutants are acknowledged, such as `; 1 of the live ones acknowledged as equivalent`, and the report lists the +mutant under `Live mutants acknowledged as equivalent` with the reason every time the line is changed again; +`survivors.txt` holds the whole list when the console cuts it. The number depends on the other mutants the same mutator +makes on the line, so when the line changes, check that each acknowledged id still names the mutant its reason is about. + +A marker is read only on a changed line. A marker that does not parse, or that has an id naming no mutant of its line or +a mutant that is not live (the tests killed it, or PIT gave it another status, such as `NON_VIABLE`), is listed under +`Markers to correct` with its line as written, followed by every id the line has and its status. Where an id names a +mutant that is not live, or no mutant, the code or the tests have likely changed since the verdict, so judge the line +again. A marker that names a mutator of a stronger group, such as `RemoveConditionalMutator_*`, names nothing in a run +with `DEFAULTS`: keep it, and check it in a run with the group it was written for. + The report opens with the number of mutants and of the changed lines with bytecode that carry one, such as `8 mutants on 7 of 24 changed lines`. Mutation testing checks nothing on the other changed lines, whatever their coverage. A parameterized test is named once per line, with the invocations that reach it, such as `CoreQuidemTest.test[1-3, 33]`.