diff --git a/cribro-core/build.gradle.kts b/cribro-core/build.gradle.kts index 8af0c54..ac15906 100644 --- a/cribro-core/build.gradle.kts +++ b/cribro-core/build.gradle.kts @@ -11,6 +11,8 @@ dependencies { // PIT supplies these classes when it loads the interceptor; the jar has no runtime dependency. compileOnly(libs.pitest.entry) testImplementation(libs.pitest.entry) + // The tests split --jvmArgs with PIT's own parser. + testImplementation(libs.pitest.command.line) } // The plugins read these at run time, and the Gradle plugin's jar carries this file with the classes. diff --git a/cribro-core/src/main/java/io/github/cribrodev/ChangedLinesFile.java b/cribro-core/src/main/java/io/github/cribrodev/ChangedLinesFile.java index ef72874..ac47303 100644 --- a/cribro-core/src/main/java/io/github/cribrodev/ChangedLinesFile.java +++ b/cribro-core/src/main/java/io/github/cribrodev/ChangedLinesFile.java @@ -55,6 +55,21 @@ public final class ChangedLinesFile { */ public static final String PITEST_PROPERTY = "cribro.pitest.changedLines"; + /** + * The system property naming the repository the paths of the file are relative to, set on the + * JVM that runs PIT beside {@link #PITEST_PROPERTY}, so that the interceptor reads each changed + * file where the build reads it. + */ + public static final String REPOSITORY_PROPERTY = "cribro.pitest.repository"; + + /** + * The name of the file, in PIT's report directory, that holds the run's changed lines that hold + * code, as {@link CodeLines#holdsCode} decides, and emit bytecode in a class PIT may mutate. + * The PIT interceptor writes it in this class's format, and the mutation report counts the + * changed lines from it. + */ + public static final String WITH_BYTECODE = "changed-lines-with-bytecode.txt"; + private ChangedLinesFile() {} /** diff --git a/cribro-core/src/main/java/io/github/cribrodev/CodeLines.java b/cribro-core/src/main/java/io/github/cribrodev/CodeLines.java new file mode 100644 index 0000000..b3f4da2 --- /dev/null +++ b/cribro-core/src/main/java/io/github/cribrodev/CodeLines.java @@ -0,0 +1,73 @@ +/* + * 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.regex.Pattern; + +/** + * Decides whether a line with bytecode holds code of its own, for every report that counts changed + * or exposed lines: the diff coverage block, the exposed-code block, and the mutation summary. + * + *

A line whose text {@link #isOnlyBracesSeparatorsAndElse is only braces, separators, and + * else}, that carries no branch, and that starts no method holds no code of its own. The compiler + * gives such a line an instruction of the statement it closes: the jump over an {@code else} + * block, the jump back to a loop's condition, a method's implicit return. Whether that + * instruction ran is reported by the lines and branches of that statement, so counting the brace as + * well would count the statement twice. A method or a lambda with an empty body has its only + * instruction on its closing brace, which is the method's first line, so that line holds code. A + * line that carries a branch holds code whatever its text, so that the branch totals keep every + * decision the compiler emitted. + * + *

This class is loaded both by the build and by the PIT process, so it depends on nothing but + * the JDK. + */ +public final class CodeLines { + + /** A comment on a source line: a block comment, one left open at the end, or a line comment. */ + private static final Pattern COMMENT = Pattern.compile("/\\*.*?\\*/|/\\*.*|//.*"); + + /** Braces, closing parentheses, semicolons, commas, whitespace, and the keyword else, alone. */ + private static final Pattern BRACES_SEPARATORS_AND_ELSE = + Pattern.compile("(?:[\\s{}),;]|\\belse\\b)+"); + + private CodeLines() {} + + /** + * Returns whether a line with bytecode holds code of its own. + * + * @param carriesBranch whether an instruction of the line is a branch the report counts + * @param startsMethod whether the line is the first line of a method or a lambda body + * @param source the text of the line, or an empty string where the working tree cannot show it + */ + public static boolean holdsCode(boolean carriesBranch, boolean startsMethod, String source) { + return carriesBranch || startsMethod || !isOnlyBracesSeparatorsAndElse(source); + } + + /** + * Returns whether the source line holds only braces, closing parentheses, semicolons, commas, + * and the keyword {@code else} once its comments are removed, such as }, + * } else {, });, or ) {. + * + *

A line with anything else on it gives {@code false}, such as } else if (b) {, + * } catch (E e) {, or } finally {. An empty line, a comment alone, and + * a line the working tree cannot show give {@code false} too: their text says nothing about the + * instructions the compiler put on them. + */ + static boolean isOnlyBracesSeparatorsAndElse(String source) { + String code = COMMENT.matcher(source).replaceAll(" ").strip(); + return !code.isEmpty() && BRACES_SEPARATORS_AND_ELSE.matcher(code).matches(); + } +} diff --git a/cribro-core/src/main/java/io/github/cribrodev/DiffCoverageReport.java b/cribro-core/src/main/java/io/github/cribrodev/DiffCoverageReport.java index 0930139..8a9e87f 100644 --- a/cribro-core/src/main/java/io/github/cribrodev/DiffCoverageReport.java +++ b/cribro-core/src/main/java/io/github/cribrodev/DiffCoverageReport.java @@ -21,6 +21,7 @@ import java.util.List; import java.util.regex.Pattern; import java.util.stream.Collectors; +import java.util.stream.Stream; /** How much of a change a test run executed, file by file. */ final class DiffCoverageReport { @@ -94,7 +95,10 @@ String describe() { static final class FileCoverage { final String path; - /** Changed lines of this file that emit bytecode, executed or not. */ + /** + * Changed lines of this file that emit bytecode and hold code, as {@link CodeLines#holdsCode} + * decides, executed or not. + */ int executableLines; /** Changed lines of this file the run executed. */ @@ -185,7 +189,10 @@ boolean isSpent() { } } - /** The total printed where the change reached no line of this module that emits bytecode. */ + /** + * The total printed where no changed line of this module both emits bytecode and holds code, as + * {@link CodeLines#holdsCode} decides. + */ static final String NO_EXECUTABLE_LINES = "Total: no changed executable lines under this module's source roots."; @@ -194,7 +201,10 @@ boolean isSpent() { /** Changed files under a source root that no report read here mentions. */ final List notInAnyReport = new ArrayList<>(); - /** Changed files whose changed lines emit no bytecode, such as comments and declarations. */ + /** + * Changed files whose changed lines emit no bytecode, such as comments and declarations, or hold + * no code of their own, such as a closing brace. + */ final List nothingExecutable = new ArrayList<>(); /** @@ -240,6 +250,10 @@ private DiffCoverageReport() {} * source file and gives no way to tell them apart. Each path is still printed, so that neither * changed file leaves the report. * + *

A line that holds no code of its own, as {@link CodeLines#holdsCode} decides from its + * branches, from whether JaCoCo reports it as the first line of a method, and from its {@link + * SourceLines#lenient} text, counts towards no total and is not a row. + * * @param changed the files in the order the lists that name nothing to do print them, which * {@link ChangedLines#underSourceRoots} orders by path * @param sources the working tree the uncovered lines are quoted from @@ -260,6 +274,12 @@ static DiffCoverageReport measure( if (counters == null) { continue; } + if (!CodeLines.holdsCode( + counters.totalBranches > 0, + lines.startsMethod(key, number), + sources.lenient(path, number))) { + continue; + } file.executableLines++; if (counters.isExecuted()) { file.executedLines++; @@ -336,11 +356,36 @@ int executableLines() { return measured.stream().mapToInt(file -> file.executableLines).sum(); } - /** Returns how many changed lines the run left unexecuted or took a branch of only one way. */ + /** + * Returns how many changed lines the run left uncovered, acknowledged or not: the sum of {@link + * #notExecutedLines()} and {@link #untakenBranchLines()}. + */ int uncoveredLines() { + return notExecutedLines() + untakenBranchLines(); + } + + /** + * Returns how many changed lines the run did not execute, acknowledged or not, which is the + * executable total less the executed one. + * + *

A line nothing ran counts here even where it has branches, since nothing took them either. + */ + int notExecutedLines() { + return (int) uncoveredRows().filter(line -> !line.executed()).count(); + } + + /** + * Returns how many changed lines the run executed without taking every branch outcome, + * acknowledged or not. + */ + int untakenBranchLines() { + return (int) uncoveredRows().filter(AffectedLine::executed).count(); + } + + /** Returns every uncovered changed line, whether it is work or acknowledged. */ + private Stream uncoveredRows() { return measured.stream() - .mapToInt(file -> file.affected.size() + file.acknowledged.size()) - .sum(); + .flatMap(file -> Stream.concat(file.affected.stream(), file.acknowledged.stream())); } /** Returns how many of the uncovered lines a comment in the source acknowledges. */ @@ -413,12 +458,24 @@ String render(String scope, boolean filtered, List staleSources, Limits appendBranches(out, coveredBranches(), totalBranches()); out.append('.'); // Every uncovered line counts here, printed or not: the executed share alone reports a line - // whose condition went one way as covered. + // whose condition went one way as covered. The two groups split the total, so a reader matches + // the not-executed group against the executed share and the other group against the branch + // pair. Acknowledged lines are counted in their group like any other, and the closing clause + // says how many of the total they are. + int uncovered = uncoveredLines(); out.append("\nUncovered changed code: ") - .append(uncoveredLines()) - .append(uncoveredLines() == 1 ? " line" : " lines"); + .append(uncovered) + .append(uncovered == 1 ? " line" : " lines"); + if (uncovered > 0) { + // Both groups are printed even at zero, so that the line keeps one shape between runs. + out.append(" (") + .append(notExecutedLines()) + .append(" not executed, ") + .append(untakenBranchLines()) + .append(" with an untaken branch)"); + } if (acknowledgedLines() > 0) { - out.append(" (").append(acknowledgedLines()).append(" acknowledged)"); + out.append(", ").append(acknowledgedLines()).append(" of them acknowledged"); } return out.toString(); } diff --git a/cribro-core/src/main/java/io/github/cribrodev/ExposedCode.java b/cribro-core/src/main/java/io/github/cribrodev/ExposedCode.java index 865f1af..2894bf0 100644 --- a/cribro-core/src/main/java/io/github/cribrodev/ExposedCode.java +++ b/cribro-core/src/main/java/io/github/cribrodev/ExposedCode.java @@ -15,7 +15,9 @@ */ package io.github.cribrodev; +import com.sun.source.tree.AnnotatedTypeTree; import com.sun.source.tree.AnnotationTree; +import com.sun.source.tree.ArrayTypeTree; import com.sun.source.tree.BlockTree; import com.sun.source.tree.CaseTree; import com.sun.source.tree.ClassTree; @@ -29,9 +31,12 @@ import com.sun.source.tree.MemberSelectTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.MethodTree; +import com.sun.source.tree.NewClassTree; +import com.sun.source.tree.ParameterizedTypeTree; import com.sun.source.tree.StatementTree; import com.sun.source.tree.SwitchTree; import com.sun.source.tree.Tree; +import com.sun.source.tree.VariableTree; import com.sun.source.tree.WhileLoopTree; import com.sun.source.util.JavacTask; import com.sun.source.util.SourcePositions; @@ -43,6 +48,7 @@ import java.nio.file.Files; import java.util.ArrayDeque; import java.util.ArrayList; +import java.util.Collections; import java.util.Deque; import java.util.LinkedHashMap; import java.util.List; @@ -80,12 +86,24 @@ *

Sources are parsed with the javac of the running JDK, without resolving a symbol, so a call is * matched by its simple name and every overload of that name counts. Where the JVM has no javac, * nothing is found. + * + *

A region names its method by the signature as the source spells it, without annotations and + * type arguments: {@code helper(int)}, {@code helper(List, String...)}. The names of the enclosing + * classes come first, as in {@code Builder.build()}, except the name of the class a file holds + * alone at its top level; an anonymous class is named after its supertype, as in {@code (anonymous + * Runnable).run()}, and a constructor is {@code new} and its class, as in {@code new Builder(int)}. + * Where two methods of a file get one name, such as overloads that differ in the bound of a type + * variable or methods of two local classes, each name ends with the line its declaration starts on, + * as in {@code f(T) at line 12}. Two such methods whose declarations start on one line still share + * a name. */ final class ExposedCode { /** Unchanged lines of one method that a change reaches through the lines named as triggers. */ static final class Region { final String path; + + /** The name of the method, as the class comment of {@link ExposedCode} spells it. */ final String method; /** The changed lines that route control here, or the call sites for a called method. */ @@ -286,10 +304,144 @@ boolean touches(Tree tree, NavigableSet changed) { return start > 0 && end >= start && !changed.subSet(start, true, end, true).isEmpty(); } + /** + * Returns the name of each method of the file, as the class comment of {@link ExposedCode} + * spells it. + */ + private Map signatures() { + Map signatures = new LinkedHashMap<>(); + boolean alone = + unit.getTypeDecls().stream().filter(ClassTree.class::isInstance).count() == 1; + new TreeScanner() { + /** The names of the enclosing classes, innermost first. */ + private final Deque classes = new ArrayDeque<>(); + + /** The name of the anonymous class whose body is scanned next. */ + private String anonymous; + + @Override + public Void visitNewClass(NewClassTree tree, Void unused) { + scan(tree.getEnclosingExpression(), unused); + scan(tree.getIdentifier(), unused); + scan(tree.getTypeArguments(), unused); + scan(tree.getArguments(), unused); + if (tree.getClassBody() != null) { + anonymous = "(anonymous " + typeName(tree.getIdentifier()) + ")"; + scan(tree.getClassBody(), unused); + } + return null; + } + + @Override + public Void visitClass(ClassTree tree, Void unused) { + String name = tree.getSimpleName().toString(); + classes.push(name.isEmpty() ? anonymous : name); + try { + return super.visitClass(tree, unused); + } finally { + classes.pop(); + } + } + + @Override + public Void visitMethod(MethodTree tree, Void unused) { + signatures.put(tree, signature(tree, classes, alone)); + return super.visitMethod(tree, unused); + } + }.scan(unit, null); + Map uses = new TreeMap<>(); + signatures.values().forEach(name -> uses.merge(name, 1L, Long::sum)); + signatures.replaceAll( + (method, name) -> uses.get(name) > 1 ? name + " at line " + startLine(method) : name); + return signatures; + } + + /** + * Returns the signature of a method as the class comment of {@link ExposedCode} spells it. + * + * @param classes the names of the enclosing classes, innermost first, as the class comment of + * {@link ExposedCode} spells them + * @param alone whether the outermost class is the only top-level class of the file, whose name + * the signature leaves out + */ + private String signature(MethodTree method, Deque classes, boolean alone) { + List owners = new ArrayList<>(classes); + Collections.reverse(owners); + String outermost = owners.get(0); + if (alone) { + owners.remove(0); + } + StringBuilder out = new StringBuilder(); + String name = method.getName().toString(); + if (name.equals("")) { + out.append("new "); + name = owners.isEmpty() ? outermost : owners.remove(owners.size() - 1); + } + for (String owner : owners) { + out.append(owner).append('.'); + } + out.append(name).append('('); + List parameters = method.getParameters(); + for (int i = 0; i < parameters.size(); i++) { + if (i > 0) { + out.append(", "); + } + out.append(parameterType(parameters.get(i))); + } + return out.append(')').toString(); + } + + /** + * Returns the type of a parameter as {@link #typeName(Tree)} spells it, with {@code ...} for + * the last array dimension of a variable-arity parameter. + */ + private String parameterType(VariableTree parameter) { + String type = typeName(parameter.getType()); + // javac reads String... as String[], and ends the type's span at the ... it read. + if (source(parameter.getType()).endsWith("...")) { + return type.substring(0, type.length() - "[]".length()) + "..."; + } + return type; + } + + /** Returns a type as the source spells it, without annotations and type arguments. */ + private String typeName(Tree type) { + if (type instanceof AnnotatedTypeTree) { + return typeName(((AnnotatedTypeTree) type).getUnderlyingType()); + } + if (type instanceof ParameterizedTypeTree) { + return typeName(((ParameterizedTypeTree) type).getType()); + } + if (type instanceof ArrayTypeTree) { + return typeName(((ArrayTypeTree) type).getType()) + "[]"; + } + if (type instanceof MemberSelectTree) { + MemberSelectTree member = (MemberSelectTree) type; + return typeName(member.getExpression()) + "." + member.getIdentifier(); + } + return type.toString(); + } + + /** Returns the source text of a tree, or an empty string where its position is unknown. */ + private String source(Tree tree) { + long start = positions.getStartPosition(unit, tree); + long end = positions.getEndPosition(unit, tree); + if (start < 0 || end < start) { + return ""; + } + try { + CharSequence text = unit.getSourceFile().getCharContent(true); + return text.subSequence((int) start, (int) end).toString(); + } catch (IOException e) { + return ""; + } + } + /** Returns the regions of this file, own control flow first, then the called methods. */ List exposed(String path, NavigableSet changed) { Map own = new LinkedHashMap<>(); Map> byName = new TreeMap<>(); + Map signatures = signatures(); List calls = new ArrayList<>(); new TreeScanner() { private final Deque methods = new ArrayDeque<>(); @@ -393,7 +545,7 @@ private void expose(int trigger, List statements) { return; } Region region = - own.computeIfAbsent(method, key -> new Region(path, key.getName().toString(), false)); + own.computeIfAbsent(method, key -> new Region(path, signatures.get(key), false)); region.triggers.add(trigger); for (StatementTree statement : statements) { addLines(statement, region.lines); @@ -428,7 +580,7 @@ private void expose(int trigger, List statements) { called.computeIfAbsent( callee, key -> { - Region body = new Region(path, key.getName().toString(), true); + Region body = new Region(path, signatures.get(key), true); for (StatementTree statement : key.getBody().getStatements()) { addLines(statement, body.lines); } diff --git a/cribro-core/src/main/java/io/github/cribrodev/ExposedCodeReport.java b/cribro-core/src/main/java/io/github/cribrodev/ExposedCodeReport.java index a03d072..77e55e3 100644 --- a/cribro-core/src/main/java/io/github/cribrodev/ExposedCodeReport.java +++ b/cribro-core/src/main/java/io/github/cribrodev/ExposedCodeReport.java @@ -57,8 +57,9 @@ private ExposedCodeReport(ExposedCode exposed) { } /** - * Measures the exposed lines against the run's counters; a method with no line that emits - * bytecode is left out. + * Measures the exposed lines against the run's counters. A line that holds no code of its own, + * as {@link CodeLines#holdsCode} decides, counts towards no total and is not a row, as in the + * diff coverage block, and a method with no line that emits bytecode and holds code is left out. * * @param keys the {@link SourceFileKey} of each changed file by its path, the key the coverage * block looks the same counters up by @@ -77,6 +78,12 @@ static ExposedCodeReport measure( if (counters == null) { continue; } + if (!CodeLines.holdsCode( + counters.totalBranches > 0, + lines.startsMethod(key, number), + sources.lenient(region.path, number))) { + continue; + } method.executableLines++; if (counters.isExecuted()) { method.executedLines++; @@ -101,8 +108,9 @@ static ExposedCodeReport measure( } /** - * Returns the block the report prints after its total: an empty string where the change exposes - * nothing that emits bytecode, or one line saying so where this JVM has no javac to look with. + * Returns the block the report prints after its total: an empty string where no exposed line both + * emits bytecode and holds code, as {@link CodeLines#holdsCode} decides, or, where this JVM has no + * javac to parse the sources with, one line that says none was looked for. * * @param scope what the run covered, such as the test task and its filter * @param filtered whether the run was narrowed to some of the tests @@ -143,7 +151,7 @@ String render( if (region.called) { out.append(", whole body, called from "); } else { - out.append(" lines ") + out.append(", lines ") .append(region.lines.first()) .append('-') .append(region.lines.last()) diff --git a/cribro-core/src/main/java/io/github/cribrodev/JacocoLines.java b/cribro-core/src/main/java/io/github/cribrodev/JacocoLines.java index 9970b8e..556eee4 100644 --- a/cribro-core/src/main/java/io/github/cribrodev/JacocoLines.java +++ b/cribro-core/src/main/java/io/github/cribrodev/JacocoLines.java @@ -23,6 +23,8 @@ import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Set; +import java.util.TreeSet; import java.util.function.Predicate; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamConstants; @@ -86,6 +88,7 @@ public String toString() { /** Collects the counters of a run that the caller has analyzed itself. */ public static final class Builder { private final Map> bySourceFile = new HashMap<>(); + private final Map> methodLines = new HashMap<>(); /** * Records that the run knows the source file, so that a file whose lines all emit no bytecode @@ -111,15 +114,27 @@ public Builder line( return this; } + /** + * Records the first line of a method, lambda body included, as the {@code line} attribute of + * JaCoCo's {@code } element carries it. + */ + public Builder method(String sourceFileKey, int firstLine) { + methodLines.computeIfAbsent(sourceFileKey, unused -> new TreeSet<>()).add(firstLine); + return this; + } + public JacocoLines build() { - return new JacocoLines(bySourceFile); + return new JacocoLines(bySourceFile, methodLines); } } private final Map> bySourceFile; + private final Map> methodLines; - private JacocoLines(Map> bySourceFile) { + private JacocoLines( + Map> bySourceFile, Map> methodLines) { this.bySourceFile = bySourceFile; + this.methodLines = methodLines; } /** @@ -166,6 +181,9 @@ private static void readReport(XMLStreamReader xml, Predicate wanted, Bu String packageName = null; // The key of the source file being read, or null outside a source file the caller wants. String sourceFile = null; + // The key of the source file the class being read was compiled from, or null where the caller + // does not want that file or the class records none. + String classSourceFile = null; while (xml.hasNext()) { if (xml.next() != XMLStreamConstants.START_ELEMENT) { continue; @@ -174,6 +192,22 @@ private static void readReport(XMLStreamReader xml, Predicate wanted, Bu case "package": packageName = xml.getAttributeValue(null, "name"); sourceFile = null; + classSourceFile = null; + break; + case "class": + String sourceFileName = xml.getAttributeValue(null, "sourcefilename"); + classSourceFile = + sourceFileName == null ? null : SourceFileKey.of(packageName, sourceFileName); + if (classSourceFile != null && !wanted.test(classSourceFile)) { + classSourceFile = null; + } + break; + case "method": + // JaCoCo leaves the attribute out for a method compiled without line numbers. + int firstLine = attribute(xml, "line"); + if (classSourceFile != null && firstLine > 0) { + builder.method(classSourceFile, firstLine); + } break; case "sourcefile": String key = SourceFileKey.of(packageName, xml.getAttributeValue(null, "name")); @@ -204,6 +238,16 @@ Counters get(String sourceFileKey, int line) { return lines == null ? null : lines.get(line); } + /** + * Returns whether the line is the first line of a method or a lambda body of the given source + * file, as the {@code line} attribute of JaCoCo's {@code } element carries it: the first + * line that holds an instruction, which for an empty body is its closing brace. + */ + boolean startsMethod(String sourceFileKey, int line) { + Set lines = methodLines.get(sourceFileKey); + return lines != null && lines.contains(line); + } + /** Returns whether any report read here mentions the given package-qualified source path. */ boolean covers(String sourceFileKey) { return bySourceFile.containsKey(sourceFileKey); @@ -211,17 +255,19 @@ boolean covers(String sourceFileKey) { @Override public boolean equals(Object other) { - return other instanceof JacocoLines && bySourceFile.equals(((JacocoLines) other).bySourceFile); + return other instanceof JacocoLines + && bySourceFile.equals(((JacocoLines) other).bySourceFile) + && methodLines.equals(((JacocoLines) other).methodLines); } @Override public int hashCode() { - return bySourceFile.hashCode(); + return Objects.hash(bySourceFile, methodLines); } @Override public String toString() { - return bySourceFile.toString(); + return bySourceFile + " methods " + methodLines; } private static Counters larger(Counters first, Counters second) { diff --git a/cribro-core/src/main/java/io/github/cribrodev/PitestJvmArgs.java b/cribro-core/src/main/java/io/github/cribrodev/PitestJvmArgs.java index 10103a1..473b30a 100644 --- a/cribro-core/src/main/java/io/github/cribrodev/PitestJvmArgs.java +++ b/cribro-core/src/main/java/io/github/cribrodev/PitestJvmArgs.java @@ -16,8 +16,11 @@ package io.github.cribrodev; import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; /** * The arguments of the JVM that runs the tests, split into those PIT's {@code --jvmArgs} can pass @@ -25,21 +28,46 @@ */ public final class PitestJvmArgs { + /** Why an argument with whitespace, a quote, or a {@code #} is left out. */ + static final String ARGUMENT_FILE = + "the java launcher splits a line of the argument file the test JVM starts with at" + + " whitespace, removes its quotes, and ends it at a # (hcoles/pitest#1511)"; + + /** Why an argument with a {@code {} that no later {@code }} closes is left out. */ + static final String BRACE_LEFT_OPEN = + "PIT's --jvmArgs joins an argument with a { that no } closes to the argument after it"; + + /** Why an argument with a comma and a brace of its own is left out. */ + static final String OWN_BRACE = + "PIT's --jvmArgs splits at a comma outside braces and removes every brace once a comma is" + + " inside them"; + private final String value; - private final List leftOut; + private final Map> leftOut; - private PitestJvmArgs(String value, List leftOut) { + private PitestJvmArgs(String value, Map> leftOut) { this.value = value; this.leftOut = leftOut; } - /** Returns the arguments joined with commas, for {@code --jvmArgs}. */ + /** + * Returns the arguments joined with commas, for {@code --jvmArgs}, with an argument that contains + * a comma enclosed in braces. + */ public String value() { return value; } /** Returns the arguments PIT cannot pass whole, which the test JVM under PIT runs without. */ public List leftOut() { + return leftOut.values().stream().flatMap(List::stream).collect(Collectors.toList()); + } + + /** + * Returns the arguments of {@link #leftOut()} keyed by the reason they are left out, a clause + * that follows "since", with the reasons in the order of the first argument each one applies to. + */ + public Map> leftOutByReason() { return leftOut; } @@ -51,9 +79,22 @@ public List leftOut() { * {@code jvmArgs} into the task's system properties, so the arguments the test JVM gets are the * JVM arguments, the system properties, and the heap limit together. * - *

PIT splits {@code --jvmArgs} at commas and the minion command line at whitespace, so an - * argument containing either would reach the test JVM broken, as a stray main class name at - * worst. Such an argument is left out and listed in {@link #leftOut()}. + *

PIT splits {@code --jvmArgs} at each comma outside braces, where a {@code {} opens braces + * that the next {@code }} closes, then removes every brace from every argument once any comma was + * inside braces. An argument with a comma is therefore passed in braces, unless it or a passed + * argument contains a brace of its own, which PIT would remove. An argument that leaves braces + * open would join the next one, and is left out. + * + *

PIT writes each argument unquoted on a line of the argument file the test JVM starts with + * (hcoles/pitest#1511). The {@code java} launcher splits that line at whitespace, removes the + * quotes {@code "} and {@code '}, and reads the rest of the line after a {@code #} as a comment, + * so an argument with any of these would reach the test JVM changed, as a stray main class name + * at worst. + * + *

An argument PIT cannot pass whole is left out, under the first of these reasons that applies + * to it in {@link #leftOutByReason()}: the argument file, a brace left open, a brace of its own, + * a brace in a passed argument. An argument that starts with {@code @} names an argument file, + * which PIT reads into the test JVM's own without its {@code --add-modules} lines. * * @param maxHeapSize the heap limit, such as a Gradle test task's {@code maxHeapSize}, or null * where none is set @@ -67,15 +108,68 @@ public static PitestJvmArgs of( if (maxHeapSize != null) { arguments.add("-Xmx" + maxHeapSize); } + // A passed argument without a comma keeps its braces only while no comma is in braces. + List braced = + arguments.stream().filter(a -> isPlain(a) && hasBrace(a)).collect(Collectors.toList()); List passed = new ArrayList<>(); - List leftOut = new ArrayList<>(); + Map> leftOut = new LinkedHashMap<>(); for (String argument : arguments) { - if (argument.contains(",") || argument.chars().anyMatch(Character::isWhitespace)) { - leftOut.add(argument); - } else { + String reason; + if (isPlain(argument)) { passed.add(argument); + continue; + } else if (changedByArgumentFile(argument)) { + reason = ARGUMENT_FILE; + } else if (leavesBraceOpen(argument)) { + reason = BRACE_LEFT_OPEN; + } else if (hasBrace(argument)) { + reason = OWN_BRACE; + } else if (!braced.isEmpty()) { + reason = otherBrace(braced); + } else { + passed.add("{" + argument + "}"); + continue; } + leftOut.computeIfAbsent(reason, r -> new ArrayList<>()).add(argument); } - return new PitestJvmArgs(String.join(",", passed), List.copyOf(leftOut)); + Map> byReason = new LinkedHashMap<>(); + leftOut.forEach((reason, left) -> byReason.put(reason, List.copyOf(left))); + return new PitestJvmArgs(String.join(",", passed), Collections.unmodifiableMap(byReason)); + } + + /** + * Returns why an argument with a comma and no brace is left out, where the passed arguments in + * {@code braced} have braces that PIT would remove. + */ + static String otherBrace(List braced) { + return "PIT's --jvmArgs splits at a comma outside braces, and a comma inside braces would make" + + " it remove the braces of " + + String.join(" ", braced); + } + + /** + * Returns whether PIT passes the argument as it is: one with no comma, no whitespace, quote, or + * {@code #}, which the argument file changes, and no brace left open. + */ + private static boolean isPlain(String argument) { + return !argument.contains(",") + && !changedByArgumentFile(argument) + && !leavesBraceOpen(argument); + } + + /** Returns whether a {@code {} in the argument opens braces that no later {@code }} closes. */ + private static boolean leavesBraceOpen(String argument) { + return argument.lastIndexOf('{') > argument.lastIndexOf('}'); + } + + /** Returns whether the {@code java} launcher reads the argument back changed from its file. */ + private static boolean changedByArgumentFile(String argument) { + return argument + .chars() + .anyMatch(c -> Character.isWhitespace(c) || c == '"' || c == '\'' || c == '#'); + } + + private static boolean hasBrace(String argument) { + return argument.indexOf('{') >= 0 || argument.indexOf('}') >= 0; } } 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 8e0b4c2..fc015b6 100644 --- a/cribro-core/src/main/java/io/github/cribrodev/PitestRun.java +++ b/cribro-core/src/main/java/io/github/cribrodev/PitestRun.java @@ -63,16 +63,27 @@ public final class PitestRun { */ public static final String ALL_TESTS = "~.*"; + /** + * The PIT mutator group a run uses where the build names none. + * + *

{@code STRONGER} adds to {@code DEFAULTS} a mutator of switch statements and the mutators + * that replace an equality or ordering check with {@code true}; a test kills one of the latter + * only by running the check where it is false. PIT mutates only the changed lines, so the extra + * mutants add little to the run. + */ + public static final String DEFAULT_MUTATORS = "STRONGER"; + private List targetClasses = List.of(); private File reportDir; private File changedLines; + private File repository; private String sourceEncoding; private String targetTests; private List mutableCodePaths = List.of(); private List sourceDirs = List.of(); private List classPath = List.of(); private String jvmArgs = ""; - private String mutators = "DEFAULTS"; + private String mutators = DEFAULT_MUTATORS; private int threads = 1; private int timeoutConst = 4000; private final Map extraOptions = new LinkedHashMap<>(); @@ -95,6 +106,15 @@ public PitestRun changedLines(File changedLines) { return this; } + /** + * The repository the paths of {@link #changedLines} are relative to, where PIT's filter reads the + * changed files. Required. + */ + public PitestRun repository(File repository) { + this.repository = repository; + return this; + } + /** The charset the build compiles the sources in, which PIT reads them in too. Required. */ public PitestRun sourceEncoding(String sourceEncoding) { this.sourceEncoding = sourceEncoding; @@ -206,15 +226,20 @@ public List arguments() throws IOException { } /** - * Returns the system properties the PIT JVM starts with: the {@link ChangedLinesFile} for PIT's - * filter, and the {@code file.encoding} PIT reads the classpath file of {@link #arguments()} in. + * Returns the system properties the PIT JVM starts with: the {@link ChangedLinesFile} and the + * repository for PIT's filter, and the {@code file.encoding} PIT reads the classpath file of + * {@link #arguments()} in. */ public Map systemProperties() { if (changedLines == null) { throw new IllegalStateException("changedLines is not set"); } + if (repository == null) { + throw new IllegalStateException("repository is not set"); + } Map properties = new LinkedHashMap<>(); properties.put(ChangedLinesFile.PITEST_PROPERTY, changedLines.getAbsolutePath()); + properties.put(ChangedLinesFile.REPOSITORY_PROPERTY, repository.getAbsolutePath()); properties.put("file.encoding", FILE_ENCODING); return properties; } @@ -242,25 +267,39 @@ public static List plugins(String property) { } /** - * Returns the line naming the JVM arguments PIT ran the tests without, or null where there are - * none. + * Returns the lines naming the JVM arguments PIT ran the tests without, or null where there are + * none: a line per reason, followed by each of its arguments on a line of its own, indented, so + * that an argument holding whitespace reads as one. A carriage return or line feed inside an + * argument is printed as {@code \r} or {@code \n}, so it cannot start the next argument's + * line; a backslash is printed as it is, as a Windows path holds one. * + * @param leftOut the arguments keyed by why they are left out, such as {@link + * PitestJvmArgs#leftOutByReason()} returns * @param source what the arguments came from, such as {@code the test task} */ - public static String leftOutMessage(List leftOut, String source) { + public static String leftOutMessage(Map> leftOut, String source) { if (leftOut.isEmpty()) { return null; } - return "PIT ran the tests without these JVM arguments of " - + source - + ", since it splits arguments at commas and whitespace: " - + String.join(" ", leftOut); + return leftOut.entrySet().stream() + .map( + reason -> + "PIT ran the tests without these JVM arguments of " + + source + + ", since " + + reason.getKey() + + ":\n " + + reason.getValue().stream() + .map(arg -> arg.replace("\r", "\\r").replace("\n", "\\n")) + .collect(Collectors.joining("\n "))) + .collect(Collectors.joining("\n")); } /** * Returns the message of a PIT run that failed: its exit code and the end of {@link #LOG}. * - * @param leftOut the line {@link #leftOutMessage} returned, or null + * @param leftOut the lines naming the arguments left out, such as {@link #leftOutMessage} + * returns, or null */ public static String failureMessage(int exitCode, File repository, File log, String leftOut) throws IOException { @@ -297,13 +336,17 @@ public static String report( throws IOException { String header = ChangedLinesFile.readHeader(changedLines.toPath()); String tests = targetTests != null ? "tests matching " + targetTests : "all tests"; + // PIT before 1.11, which cribro.pitestVersion can select, never calls the interceptor method + // that writes this file. + File withBytecode = new File(reportDir, ChangedLinesFile.WITH_BYTECODE); PitestSurvivors report = PitestSurvivors.read( (header == null ? "against an unknown base" : header) + ", " + tests, new File(reportDir, MutantsFile.NAME), repository, sourceDirs, - ChangedLinesFile.readPaths(changedLines.toPath())); + ChangedLinesFile.readPaths(changedLines.toPath()), + withBytecode.isFile() ? ChangedLinesFile.read(withBytecode.toPath()) : null); return report.writeAndRender( repository, new File(reportDir, "survivors.txt"), 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 f4a215c..720f7ea 100644 --- a/cribro-core/src/main/java/io/github/cribrodev/PitestSurvivors.java +++ b/cribro-core/src/main/java/io/github/cribrodev/PitestSurvivors.java @@ -17,13 +17,17 @@ import java.io.File; import java.io.IOException; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; +import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.NavigableSet; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; @@ -36,13 +40,16 @@ * *

A mutant is live when its status is {@code SURVIVED} or {@code NO_COVERAGE}: the tests that * reached its line passed anyway, or no test reached it. {@code KILLED}, {@code TIMED_OUT}, and - * {@code MEMORY_ERROR} mean the tests noticed the mutant and are counted as killed. Any other - * status, such as {@code NON_VIABLE} for a mutant the JVM would not load, says nothing about the - * tests and is counted under its own name. + * {@code MEMORY_ERROR} mean the tests noticed the mutant and are counted as killed, and the count + * names how many of them timed out or ran out of memory. Any other status, such as {@code + * 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 mutants and their tests come from the {@link MutantsFile} the PIT listener writes. + * 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. */ public final class PitestSurvivors { @@ -90,9 +97,13 @@ public final class PitestSurvivors { private static final class Mutant { private final String description; private final String method; - private final Set tests; + private final Map>> tests; - Mutant(String description, String method, Set tests) { + /** + * @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) { this.description = description; this.method = method; this.tests = tests; @@ -106,7 +117,7 @@ String method() { return method; } - Set tests() { + Map>> tests() { return tests; } } @@ -116,9 +127,13 @@ private static final class Line { private final int number; private final String source; private final List mutants; - private final Set tests; + private final Map>> tests; - Line(int number, String source, List mutants, Set tests) { + Line( + int number, + String source, + List mutants, + Map>> tests) { this.number = number; this.source = source; this.mutants = mutants; @@ -137,7 +152,7 @@ List mutants() { return mutants; } - Set tests() { + Map>> tests() { return tests; } } @@ -171,18 +186,29 @@ int mutantCount() { private final Comparator testOrder; private final Map statusCounts; private final int total; + private final int mutatedLines; + private final int linesWithBytecode; private final List files; + /** + * @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 + */ private PitestSurvivors( String scope, Comparator testOrder, Map statusCounts, int total, + int mutatedLines, + int linesWithBytecode, List files) { this.scope = scope; this.testOrder = testOrder; this.statusCounts = statusCounts; this.total = total; + this.mutatedLines = mutatedLines; + this.linesWithBytecode = linesWithBytecode; this.files = files; } @@ -198,40 +224,62 @@ 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 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 + * where the run wrote no such file; the report then counts the lines that carry a mutant + * and gives no total */ public static PitestSurvivors read( String scope, File mutantsFile, File repository, List sourceRoots, - Map paths) + Map paths, + Map> linesWithBytecode) throws IOException { + Set withBytecode = new HashSet<>(); + if (linesWithBytecode != null) { + linesWithBytecode.forEach( + (key, lines) -> lines.forEach(line -> withBytecode.add(key + ":" + line))); + } if (!mutantsFile.isFile()) { return new PitestSurvivors( - scope, Comparator.naturalOrder(), new LinkedHashMap<>(), 0, new ArrayList<>()); + scope, + Comparator.naturalOrder(), + new LinkedHashMap<>(), + 0, + 0, + linesWithBytecode == null ? -1 : withBytecode.size(), + new ArrayList<>()); } List reported = MutantsFile.read(mutantsFile.toPath()); + 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<>(); + Map shortTestNames = new HashMap<>(); for (MutantsFile.Mutant mutant : reported) { statusCounts.merge(mutant.status(), 1, Integer::sum); - if (!isLive(mutant.status())) { - continue; - } - Set tests = new TreeSet<>(); - mutant.tests() - .forEach( - test -> - tests.add( - shortTestNames.computeIfAbsent(test, PitestSurvivors::shortTestName))); int packageEnd = mutant.mutatedClass().lastIndexOf('.'); String relative = SourceFileKey.of( 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(""); @@ -253,8 +301,16 @@ public static PitestSurvivors read( List lines = new ArrayList<>(); for (Map.Entry> line : file.getValue().entrySet()) { int number = line.getKey(); - Set tests = new TreeSet<>(); - line.getValue().forEach(mutant -> tests.addAll(mutant.tests())); + 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( number, @@ -274,7 +330,7 @@ public static PitestSurvivors read( for (TreeMap> lines : byFile.values()) { for (List mutants : lines.values()) { for (Mutant mutant : mutants) { - mutant.tests().forEach(test -> liveMutantsReached.merge(test, 1, Integer::sum)); + mutant.tests().keySet().forEach(test -> liveMutantsReached.merge(test, 1, Integer::sum)); } } } @@ -282,7 +338,17 @@ public static PitestSurvivors read( Comparator.comparingInt(test -> liveMutantsReached.getOrDefault(test, 0)) .reversed() .thenComparing(Comparator.naturalOrder()); - return new PitestSurvivors(scope, testOrder, statusCounts, reported.size(), files); + // A line that carries a mutant has bytecode, so the total counts it whether the run recorded + // the line or not. + withBytecode.addAll(mutated); + return new PitestSurvivors( + scope, + testOrder, + statusCounts, + reported.size(), + mutated.size(), + linesWithBytecode == null ? -1 : withBytecode.size(), + files); } /** @@ -338,9 +404,29 @@ String render(DiffCoverageReport.Limits limits, List fullReportPaths) { StringBuilder out = new StringBuilder(); out.append("Mutation testing of changed lines ").append(scope).append('\n'); if (total == 0) { - out.append(" no mutant: PIT generated none on the changed lines"); + out.append(" no mutant: "); + if (linesWithBytecode < 0) { + out.append("PIT generated none on the changed lines"); + } else if (linesWithBytecode == 0) { + out.append("no changed line has bytecode PIT may mutate"); + } else { + out.append("PIT generated none on the ") + .append(linesWithBytecode) + .append(' ') + .append(changedLines(linesWithBytecode)); + } } else { - out.append(" ").append(total).append(total == 1 ? " mutant: " : " mutants: ").append(counts()); + out.append(" ") + .append(total) + .append(total == 1 ? " mutant on " : " mutants on ") + .append(mutatedLines); + if (linesWithBytecode >= 0) { + out.append(" of ").append(linesWithBytecode); + } + out.append(' ') + .append(changedLines(linesWithBytecode >= 0 ? linesWithBytecode : mutatedLines)) + .append(": ") + .append(counts()); } int liveLines = files.stream().mapToInt(file -> file.lines().size()).sum(); if (liveLines > 0) { @@ -388,7 +474,12 @@ String render(DiffCoverageReport.Limits limits, List fullReportPaths) { .append("\n\n") .append(WHAT_TO_DO); } - if (liveLines > 0 || total == 0) { + // 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. + boolean unmutatedLine = + linesWithBytecode < 0 ? liveLines > 0 || total == 0 : mutatedLines < linesWithBytecode; + if (unmutatedLine) { out.append("\n\n").append(AVOIDED_CALLS); } if (!fullReportPaths.isEmpty()) { @@ -400,21 +491,46 @@ String render(DiffCoverageReport.Limits limits, List fullReportPaths) { return out.toString(); } - /** The statuses that mean a test noticed the mutant. */ - private static final Set KILLED = Set.of("KILLED", "TIMED_OUT", "MEMORY_ERROR"); + /** Returns the noun that follows a count of changed lines. */ + private static String changedLines(int count) { + return count == 1 ? "changed line" : "changed lines"; + } + + /** + * The statuses that mean a test noticed the mutant, each with the words that name its share of + * the killed count, or null for {@code KILLED}, whose share is the rest. + */ + private static final Map KILLED = killedStatuses(); + + private static Map killedStatuses() { + Map statuses = new LinkedHashMap<>(); + statuses.put("KILLED", null); + statuses.put("TIMED_OUT", "timed out"); + statuses.put("MEMORY_ERROR", "out of memory"); + return statuses; + } - /** Returns the status counts, killed first, in the words the report uses. */ + /** + * Returns the status counts, killed first, in the words the report uses. The killed count names + * how many of its mutants timed out or ran out of memory, where any did. + */ private String counts() { int killed = 0; - for (String status : KILLED) { - killed += statusCounts.getOrDefault(status, 0); + List shares = new ArrayList<>(); + for (Map.Entry status : KILLED.entrySet()) { + int count = statusCounts.getOrDefault(status.getKey(), 0); + killed += count; + if (status.getValue() != null && count > 0) { + shares.add(count + " " + status.getValue()); + } } List parts = new ArrayList<>(); - parts.add(killed + " killed"); + parts.add( + killed + " killed" + (shares.isEmpty() ? "" : " (" + String.join(", ", shares) + ")")); parts.add(statusCounts.getOrDefault("SURVIVED", 0) + " survived"); parts.add(statusCounts.getOrDefault("NO_COVERAGE", 0) + " not reached by any test"); for (Map.Entry entry : statusCounts.entrySet()) { - if (!isLive(entry.getKey()) && !KILLED.contains(entry.getKey())) { + if (!isLive(entry.getKey()) && !KILLED.containsKey(entry.getKey())) { parts.add(entry.getValue() + " " + entry.getKey()); } } @@ -427,14 +543,14 @@ private void appendLine(StringBuilder out, Line line) { out.append("\n ").append(mutant.description()).append(", in ").append(mutant.method()); } if (!line.tests().isEmpty()) { - List tests = new ArrayList<>(line.tests()); + List tests = new ArrayList<>(line.tests().keySet()); tests.sort(testOrder); out.append("\n reached by ") .append(tests.size()) .append(tests.size() == 1 ? " test" : " tests") .append(tests.size() > TESTS_SHOWN ? ", among them:" : ":"); for (String test : tests.subList(0, Math.min(TESTS_SHOWN, tests.size()))) { - out.append("\n ").append(test); + out.append("\n ").append(test).append(invocations(line.tests().get(test))); } } } @@ -451,52 +567,231 @@ static String readableMethod(String method) { return lambda.matches() ? "a lambda in " + lambda.group(1) : method; } + /** + * A test as the report names it: the short name of the test, and the index of the invocation, + * where the name PIT recorded carries one. + */ + static final class TestName { + private final String name; + private final List invocation; + + TestName(String name, List invocation) { + this.name = name; + this.invocation = invocation; + } + + String name() { + return name; + } + + /** + * Returns the index of the invocation as the test engine numbers it, one number per level where + * invocations nest, as dynamic tests in a dynamic container do; empty for a test with no + * invocation. + */ + List invocation() { + return invocation; + } + + /** Returns the name the report prints for this invocation alone, such as {@code T.m[3]}. */ + @Override + public String toString() { + return invocation.isEmpty() ? name : name + "[" + index(invocation) + "]"; + } + } + /** * Returns {@code Class.method} for a test PIT names {@code pkg.Class.method(pkg.Class)}, and * {@code Class$Nested.method} for a JUnit Platform test, which PIT names by its unique id, such as * {@code pkg.Class.[engine:junit-jupiter]/[class:pkg.Class]/[nested-class:Nested]/[test-template: - * method(int)]/[test-template-invocation:#3]}. The invocations of one parameterized test collapse - * into one name. A JUnit Platform id with no class segment this method knows is returned whole, + * method(int)]/[test-template-invocation:#3]}. + * + *

Each segment of a unique id is read after its value is decoded. A class segment, such as + * {@code class}, {@code class-template}, Vintage's {@code runner}, or Spock's {@code spec}, + * starts the name afresh; a nested class segment adds {@code $Nested}. An index is a number of at + * most nine digits with no leading zero, the shape {@link #INDEX} matches. A segment whose value + * is {@code #} and an index is one level of the invocation, outer level first, here {@code 3}, so + * an invocation of a class template stays in the invocation of the classes nested in it; {@code + * #} and a number of another shape adds nothing. A segment whose value is an index alone is one + * level too once a segment has named the method, as Spock's {@code iteration} under its {@code + * feature} is. After the first class segment, the last segment of any other value names the + * method, cut at its parameter list: Jupiter's {@code method} or {@code test-template}, Spock's + * {@code feature}, Kotest's {@code test}, or Vintage's {@code test}, whose value is a JUnit 4 + * description such as {@code method[3](pkg.Class)} and whose index in brackets ends the + * invocation. Kotest's names are free text read by these shapes: a nested Kotest test is named by + * its innermost test alone, a test named {@code 404} is named so only where no test above it + * named the method, and one named {@code #1} reads as an invocation. A JUnit 4 parameterized test + * that PIT runs itself is named {@code pkg.Class.method[3](pkg.Class)}, with its index in + * brackets too. A JUnit Platform id with no class segment this method knows is returned whole, * since cutting it at dots would produce a name no test has. */ - static String shortTestName(String name) { + static TestName shortTestName(String name) { + if (!name.contains("[engine:")) { + int paren = name.lastIndexOf('('); + String testClass = + paren >= 0 && name.endsWith(")") ? name.substring(paren + 1, name.length() - 1) : null; + if (testClass != null && name.startsWith(testClass + ".")) { + TestName method = junit4Method(name.substring(testClass.length() + 1, paren)); + return new TestName( + testClass.substring(testClass.lastIndexOf('.') + 1) + "." + method.name(), + method.invocation()); + } + TestName method = junit4Method(paren < 0 ? name : name.substring(0, paren)); + String qualified = method.name(); + int methodStart = qualified.lastIndexOf('.'); + int classStart = qualified.lastIndexOf('.', methodStart - 1); + return new TestName(qualified.substring(classStart + 1), method.invocation()); + } Matcher segment = PLATFORM_SEGMENT.matcher(name); - if (name.contains("[engine:")) { - StringBuilder shortName = new StringBuilder(); - String method = null; - while (segment.find()) { - String type = segment.group(1); - String value = segment.group(2); - if (CLASS_SEGMENTS.contains(type)) { - shortName.setLength(0); - shortName.append(value.substring(value.lastIndexOf('.') + 1)); - } else if (type.equals("nested-class")) { - shortName.append('$').append(value); - } else if (method == null && METHOD_SEGMENTS.contains(type)) { - int paren = value.indexOf('('); - method = paren < 0 ? value : value.substring(0, paren); + StringBuilder shortName = new StringBuilder(); + String method = null; + List invocation = new ArrayList<>(); + while (segment.find()) { + String type = segment.group(1); + String value = decode(segment.group(2)); + Matcher index = INVOCATION_INDEX.matcher(value); + if (CLASS_SEGMENTS.contains(type)) { + shortName.setLength(0); + shortName.append(value.substring(value.lastIndexOf('.') + 1)); + method = null; + } else if (NESTED_CLASS_SEGMENTS.contains(type)) { + shortName.append('$').append(value); + } else if (index.matches() + && (value.startsWith("#") || method != null && index.group(1).matches(INDEX))) { + if (index.group(1).matches(INDEX)) { + invocation.add(Integer.valueOf(index.group(1))); } + } else if (shortName.length() > 0) { + int paren = value.lastIndexOf('('); + method = paren < 0 ? value : value.substring(0, paren); } - if (shortName.length() == 0) { - return name; + } + if (shortName.length() == 0) { + return new TestName(name, List.of()); + } + if (method == null) { + return new TestName(shortName.toString(), List.copyOf(invocation)); + } + TestName junit4 = junit4Method(method); + invocation.addAll(junit4.invocation()); + return new TestName(shortName + "." + junit4.name(), List.copyOf(invocation)); + } + + /** + * Returns a JUnit 4 method name without the index in brackets that ends it, such as {@code m} + * and {@code 3} for {@code m[3]}; a name with no such index is returned whole. + */ + private static TestName junit4Method(String method) { + Matcher index = JUNIT4_INDEX.matcher(method); + return index.matches() + ? new TestName(index.group(1), List.of(Integer.valueOf(index.group(2)))) + : new TestName(method, List.of()); + } + + /** + * Returns the value of a unique-id segment with its {@code %XX} escapes decoded. The JUnit + * Platform escapes {@code %}, {@code +}, and the characters that delimit segments, so a value + * holds no other {@code %} and no {@code +}; a value that is not escaped that way is returned as + * it is. + */ + private static String decode(String value) { + try { + return URLDecoder.decode(value, StandardCharsets.UTF_8); + } catch (IllegalArgumentException e) { + return value; + } + } + + /** + * Returns the invocations of one test in brackets, such as {@code [1-3, 33]}, with each run of + * consecutive indexes as a range; empty for a test with no invocation. + */ + static String invocations(NavigableSet> invocations) { + if (invocations.isEmpty()) { + return ""; + } + List parts = new ArrayList<>(); + List first = null; + List last = null; + for (List invocation : invocations) { + if (last != null && follows(last, invocation)) { + last = invocation; + continue; + } + if (first != null) { + parts.add(range(first, last)); } - return method == null ? shortName.toString() : shortName + "." + method; + first = invocation; + last = invocation; } - int paren = name.indexOf('('); - String qualified = paren < 0 ? name : name.substring(0, paren); - int methodStart = qualified.lastIndexOf('.'); - int classStart = qualified.lastIndexOf('.', methodStart - 1); - return qualified.substring(classStart + 1); + parts.add(range(first, last)); + return "[" + String.join(", ", parts) + "]"; } - private static final Pattern PLATFORM_SEGMENT = Pattern.compile("\\[([a-z-]+):([^\\]]*)\\]"); + /** Returns whether the invocation comes right after the previous one of the same level. */ + private static boolean follows(List previous, List invocation) { + int depth = invocation.size(); + return previous.size() == depth + && previous.subList(0, depth - 1).equals(invocation.subList(0, depth - 1)) + && previous.get(depth - 1) + 1 == invocation.get(depth - 1); + } + + private static String range(List first, List last) { + return first.equals(last) ? index(first) : index(first) + "-" + last.get(last.size() - 1); + } + + /** Returns the index of an invocation, its levels separated by {@code /}, such as {@code 2/5}. */ + private static String index(List invocation) { + return invocation.stream().map(String::valueOf).collect(Collectors.joining("/")); + } + + /** Orders invocations by their indexes, as numbers, outer level first. */ + private static final Comparator> INVOCATION_ORDER = + (a, b) -> { + for (int i = 0; i < Math.min(a.size(), b.size()); i++) { + int order = Integer.compare(a.get(i), b.get(i)); + if (order != 0) { + return order; + } + } + return Integer.compare(a.size(), b.size()); + }; + + /** + * The digits of an invocation index: a decimal with no leading zero and at most 9 digits, so it + * always fits an {@code int}. A JUnit 4 name can hold any text in brackets, such as an 11-digit + * parameter, and the name keeps what does not match. + */ + private static final String INDEX = "(0|[1-9]\\d{0,8})"; + + /** + * The value of a JUnit Platform segment naming one invocation, such as Jupiter's {@code #3} or + * Spock's {@code 3} after a feature. A {@code #} number that {@link #INDEX} does not match, such as + * one too long for an {@code int}, adds no level to the invocation and names no method. + */ + private static final Pattern INVOCATION_INDEX = Pattern.compile("#?(\\d+)"); - /** Segments naming a test class: Jupiter's, Vintage's, and Spock's. */ - private static final Set CLASS_SEGMENTS = Set.of("class", "runner", "spec"); + /** A JUnit 4 parameterized test method with its default name, such as {@code pkg.C.m[3]}. */ + private static final Pattern JUNIT4_INDEX = Pattern.compile("(.*)\\[" + INDEX + "\\]"); - /** Segments naming a test method: Jupiter's, Vintage's, and jqwik's. */ - private static final Set METHOD_SEGMENTS = - Set.of("method", "test-template", "test-factory", "test", "property"); + private static final Pattern PLATFORM_SEGMENT = Pattern.compile("\\[([a-z-]+):([^\\]]*)\\]"); + + /** + * Segments whose value is the binary name of a test class: Jupiter's, including those of a class + * template and of a nested class named in full, Vintage's, and Spock's. + */ + private static final Set CLASS_SEGMENTS = + Set.of( + "class", + "class-template", + "fq-nested-class", + "fq-nested-class-template", + "runner", + "spec"); + + /** Segments whose value is the simple name of a class nested in the class before it. */ + private static final Set NESTED_CLASS_SEGMENTS = + Set.of("nested-class", "nested-class-template"); /** Returns the first file under the source roots with this relative path, or null. */ private static File locate(List sourceRoots, String path) { 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 6148367..b54cdd0 100644 --- a/cribro-core/src/main/java/io/github/cribrodev/SourceFileKey.java +++ b/cribro-core/src/main/java/io/github/cribrodev/SourceFileKey.java @@ -101,15 +101,20 @@ static String of(File repository, String path, String relativeToRoot) { *

Only comments and annotations, Java package annotations and Kotlin file annotations alike, * may precede the declaration, and in Kotlin a {@code #!} line before them, so the text is * scanned rather than searched: a string literal or a comment further down that spells {@code - * package} names no package. A text declares none only where the scan ends at the end of the - * text, at an empty declaration {@code ;}, or at an identifier other than {@code package}, such - * as {@code import} or {@code class}; any other character there leaves the declaration unread. + * package} names no package. The scan splits the text into tokens by the rules of the language, + * so a quote, a bracket, or a comment opener inside a literal or a comment ends nothing. A text + * declares none only where the scan ends at the end of the text, at an empty declaration {@code + * ;}, or at an identifier other than {@code package}, such as {@code import} or {@code class}; + * any other character there leaves the declaration unread. * - * @param kotlin whether the text is Kotlin, which may open with a {@code #!} line and whose block - * comments nest, so that a comment holding another ends at the matching close rather than the - * first + * @param kotlin whether the text is Kotlin, which may open with a {@code #!} line, whose block + * comments nest, and whose strings hold templates; a Java text is scanned after its Unicode + * escapes are replaced, as javac reads it */ static String declaredPackage(String text, boolean kotlin) { + if (!kotlin) { + text = translateUnicodeEscapes(text); + } int at = text.startsWith("") ? 1 : 0; if (kotlin && text.startsWith("#!", at)) { at = skipLineComment(text, at); @@ -122,60 +127,70 @@ static String declaredPackage(String text, boolean kotlin) { return ""; } if (!text.startsWith("package", at)) { - char c = text.charAt(at); + int c = text.codePointAt(at); return Character.isJavaIdentifierStart(c) || c == ';' ? "" : null; } at += "package".length(); - if (at < text.length() && Character.isJavaIdentifierPart(text.charAt(at))) { + if (at < text.length() && Character.isJavaIdentifierPart(text.codePointAt(at))) { return ""; } StringBuilder name = new StringBuilder(); - while (true) { - at = skipSpaceAndComments(text, at, kotlin); - if (at < 0 || at >= text.length()) { - return null; - } - int start = at; - if (text.charAt(at) == '`') { - int end = text.indexOf('`', at + 1); - if (end < 0) { - return null; - } - name.append(text, at + 1, end); - at = end + 1; - } else { - if (!Character.isJavaIdentifierStart(text.charAt(at))) { - return null; + at = skipQualifiedName(text, skipSpaceAndComments(text, at, kotlin), kotlin, name); + return at < 0 ? null : name.toString(); + } + + /** + * 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 + * where an even number of backslashes precede it, and a character an escape produces begins + * none. A backslash and {@code u} that no four hexadecimal digits follow stay as they are. + */ + private static String translateUnicodeEscapes(String text) { + StringBuilder out = new StringBuilder(text.length()); + int backslashes = 0; + int at = 0; + while (at < text.length()) { + char c = text.charAt(at); + if (c == '\\' && backslashes % 2 == 0) { + int digits = at + 1; + while (digits < text.length() && text.charAt(digits) == 'u') { + digits++; } - while (at < text.length() && Character.isJavaIdentifierPart(text.charAt(at))) { - at++; + if (digits > at + 1 && isHex(text, digits, digits + 4)) { + out.append((char) Integer.parseInt(text, digits, digits + 4, 16)); + at = digits + 4; + backslashes = 0; + continue; } - name.append(text, start, at); - } - at = skipSpaceAndComments(text, at, kotlin); - if (at < 0) { - return null; } - if (at < text.length() && text.charAt(at) == '.') { - name.append('.'); - at++; - continue; + backslashes = c == '\\' ? backslashes + 1 : 0; + out.append(c); + at++; + } + return out.toString(); + } + + /** Returns whether the text holds ASCII hexadecimal digits from {@code from} to {@code to}. */ + private static boolean isHex(String text, int from, int to) { + if (to > text.length()) { + return false; + } + for (int at = from; at < to; at++) { + if ("0123456789abcdefABCDEF".indexOf(text.charAt(at)) < 0) { + return false; } - return name.toString(); } + return true; } /** * Returns the index of the first character after the whitespace, comments, and annotations at * {@code at}, or -1 where one of them never ends. - * - * @param nestedComments whether a block comment may hold another, as in Kotlin */ - private static int skipSpaceCommentsAndAnnotations( - String text, int at, boolean nestedComments) { - at = skipSpaceAndComments(text, at, nestedComments); + private static int skipSpaceCommentsAndAnnotations(String text, int at, boolean kotlin) { + at = skipSpaceAndComments(text, at, kotlin); while (at >= 0 && at < text.length() && text.charAt(at) == '@') { - at = skipSpaceAndComments(text, skipAnnotation(text, at + 1, nestedComments), nestedComments); + at = skipSpaceAndComments(text, skipAnnotation(text, at + 1, kotlin), kotlin); } return at; } @@ -183,6 +198,8 @@ private static int skipSpaceCommentsAndAnnotations( /** * Returns the index of the first character after the whitespace and comments at {@code at}, or -1 * where {@code at} is -1 or a comment never ends. + * + * @param nestedComments whether a block comment may hold another, as in Kotlin */ private static int skipSpaceAndComments(String text, int at, boolean nestedComments) { while (at >= 0 && at < text.length()) { @@ -235,108 +252,201 @@ private static int skipBlockComment(String text, int at, boolean nested) { } /** - * Returns the index after the annotation whose name starts at {@code at}, or -1 where a comment - * or the arguments never end: a Kotlin use-site target such as {@code file:}, a qualified name, - * and the arguments in parentheses or, for a Kotlin annotation list, in brackets. Whitespace and - * comments may stand between these parts. + * Returns the index after the annotation whose name starts at {@code at}, or -1 where a comment, + * the name, or the arguments never end: a Kotlin use-site target such as {@code file:}, a + * qualified name, Kotlin type arguments in angle brackets, and the arguments in parentheses or, + * for a Kotlin annotation list, the annotations in brackets. Whitespace and comments may stand + * between these parts and around each dot of the name. */ - private static int skipAnnotation(String text, int at, boolean nestedComments) { - at = skipSpaceAndComments(text, at, nestedComments); - while (at >= 0) { - while (at < text.length() - && (Character.isJavaIdentifierPart(text.charAt(at)) || text.charAt(at) == '.')) { - at++; + private static int skipAnnotation(String text, int at, boolean kotlin) { + at = skipSpaceAndComments(text, at, kotlin); + while (at >= 0 && at < text.length()) { + if (text.charAt(at) == '[') { + return skipBalanced(text, at, '[', ']', kotlin); + } + int end = skipQualifiedName(text, at, kotlin, null); + int next = skipSpaceAndComments(text, end, kotlin); + if (kotlin && next >= 0 && next < text.length() && text.charAt(next) == '<') { + end = skipTypeArguments(text, next); + next = skipSpaceAndComments(text, end, true); } - int next = skipSpaceAndComments(text, at, nestedComments); if (next < 0) { return -1; } - if (next >= text.length()) { - return at; - } - char c = text.charAt(next); - if (c == ':') { - at = skipSpaceAndComments(text, next + 1, nestedComments); + if (next < text.length() && text.charAt(next) == ':') { + at = skipSpaceAndComments(text, next + 1, kotlin); continue; } - if (c == '(') { - return skipBalanced(text, next, '(', ')', nestedComments); + if (next < text.length() && text.charAt(next) == '(') { + return skipBalanced(text, next, '(', ')', kotlin); } - if (c == '[') { - return skipBalanced(text, next, '[', ']', nestedComments); + return end; + } + return at; + } + + /** + * Returns the index after the Kotlin type arguments that open at {@code at}, or -1 where the + * angle brackets never close. The {@code >} of a function type's {@code ->} closes none, and a + * comment between them is skipped. + */ + private static int skipTypeArguments(String text, int at) { + int depth = 0; + while (at >= 0 && at < text.length()) { + char c = text.charAt(at); + if (text.startsWith("//", at)) { + at = skipLineComment(text, at); + } else if (text.startsWith("/*", at)) { + at = skipBlockComment(text, at, true); + } else if (text.startsWith("->", at)) { + at += 2; + } else { + if (c == '<') { + depth++; + } else if (c == '>' && --depth == 0) { + return at + 1; + } + at++; } - return at; } return -1; } + /** + * Returns the index after the qualified name at {@code at}, or -1 where {@code at} is -1, no + * identifier starts there or after a dot, or a comment or a backticked identifier never ends. + * Whitespace and comments may stand around each dot. + * + * @param name receives the identifiers joined by dots, without backticks; null where only the end + * of the name matters + */ + private static int skipQualifiedName( + String text, int at, boolean kotlin, StringBuilder name) { + while (true) { + int end = skipIdentifier(text, at); + if (end <= at) { + return -1; + } + if (name != null) { + boolean backticked = text.charAt(at) == '`'; + name.append(text, backticked ? at + 1 : at, backticked ? end - 1 : end); + } + int dot = skipSpaceAndComments(text, end, kotlin); + if (dot < 0) { + return -1; + } + if (dot >= text.length() || text.charAt(dot) != '.') { + return end; + } + if (name != null) { + name.append('.'); + } + at = skipSpaceAndComments(text, dot + 1, kotlin); + } + } + + /** + * Returns the index after the identifier or the backticked name at {@code at}: {@code at} itself + * where neither starts there, and -1 where {@code at} is -1 or the backticks never close. + */ + private static int skipIdentifier(String text, int at) { + if (at < 0 || at >= text.length()) { + return at; + } + if (text.charAt(at) == '`') { + int close = text.indexOf('`', at + 1); + return close < 0 ? -1 : close + 1; + } + int end = at; + while (end < text.length()) { + int c = text.codePointAt(end); + if (end == at ? !Character.isJavaIdentifierStart(c) : !Character.isJavaIdentifierPart(c)) { + break; + } + end += Character.charCount(c); + } + return end; + } + /** * Returns the index after the bracket that closes the one at {@code at}, or -1 where none does. - * A comment or a string or character literal between them is skipped, so a bracket in it does - * not count. + * A comment, a string or character literal, or a Kotlin identifier in backticks between them is + * skipped, so a bracket in it does not count. */ - private static int skipBalanced( - String text, int at, char open, char close, boolean nestedComments) { + private static int skipBalanced(String text, int at, char open, char close, boolean kotlin) { int depth = 0; - while (at < text.length()) { + int dollars = 0; + while (at >= 0 && at < text.length()) { char c = text.charAt(at); - if (c == open) { - depth++; - } else if (c == close) { - depth--; - if (depth == 0) { - return at + 1; - } - } else if (text.startsWith("//", at)) { + if (text.startsWith("//", at)) { at = skipLineComment(text, at); - continue; } else if (text.startsWith("/*", at)) { - at = skipBlockComment(text, at, nestedComments); - if (at < 0) { - return -1; - } - continue; + at = skipBlockComment(text, at, kotlin); } else if (c == '"' || c == '\'') { - at = skipLiteral(text, at); - if (at < 0) { - return -1; + at = skipLiteral(text, at, kotlin, dollars); + } else if (kotlin && c == '`') { + at = skipIdentifier(text, at); + } else { + if (c == open) { + depth++; + } else if (c == close && --depth == 0) { + return at + 1; } - continue; + at++; } - at++; + dollars = c == '$' ? dollars + 1 : 0; } return -1; } /** - * Returns the index after the literal that opens at {@code at}, or -1 where it never closes. A - * Kotlin raw string ends at the last quote of the first run of three or more, so the quotes - * before the last three belong to its text. + * Returns the index after the literal that opens at {@code at}, or -1 where it never closes. + * + *

A backslash escapes the character after it, except in a Kotlin raw string. A Java text block + * or a Kotlin raw string ends at the last quote of the first run of three or more unescaped + * quotes. In a Kotlin raw string, the quotes before the last three of that run belong to the + * string. A Java source that compiles has no quote right after the closing delimiter of a text + * block, so ending a text block at the last quote of the run reads every such source. In a + * Kotlin string, a brace right after at least as many dollar signs as stand before the opening + * quote, and at least one, opens a template, which ends at the matching brace and may hold + * literals and comments of its own. + * + * @param dollars the number of dollar signs right before the opening quote, the template prefix + * of a Kotlin string */ - private static int skipLiteral(String text, int at) { + private static int skipLiteral(String text, int at, boolean kotlin, int dollars) { char quote = text.charAt(at); - if (quote == '"' && text.startsWith("\"\"\"", at)) { - int end = text.indexOf("\"\"\"", at + 3); - if (end < 0) { - return -1; - } - end += 3; - while (end < text.length() && text.charAt(end) == '"') { - end++; - } - return end; - } - at++; + boolean multiline = quote == '"' && text.startsWith("\"\"\"", at); + boolean escapes = !(kotlin && multiline); + boolean templates = kotlin && quote == '"'; + int prefix = Math.max(1, dollars); + int run = 0; + at += multiline ? 3 : 1; while (at < text.length()) { char c = text.charAt(at); - if (c == '\\') { - at += 2; - continue; + if (multiline && text.startsWith("\"\"\"", at)) { + at += 3; + while (at < text.length() && text.charAt(at) == '"') { + at++; + } + return at; } - if (c == quote) { + if (!multiline && c == quote) { return at + 1; } - at++; + if (c == '\\' && escapes) { + at += 2; + run = 0; + } else if (c == '{' && templates && run >= prefix) { + at = skipBalanced(text, at, '{', '}', true); + if (at < 0) { + return -1; + } + run = 0; + } else { + run = c == '$' ? run + 1 : 0; + at++; + } } return -1; } 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 ad2ee41..8595886 100644 --- a/cribro-core/src/main/java/io/github/cribrodev/SourceLines.java +++ b/cribro-core/src/main/java/io/github/cribrodev/SourceLines.java @@ -15,33 +15,59 @@ */ package io.github.cribrodev; +import java.io.BufferedReader; import java.io.File; import java.io.IOException; +import java.io.InputStreamReader; +import java.io.UncheckedIOException; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.InvalidPathException; import java.nio.file.Path; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; /** - * The text of the working tree's sources, read at most once per file. + * The text of the working tree's sources, read as UTF-8 and kept, so each file is read on its + * first lookup only. * *

The report quotes a line beside its counters, so that the reader sees the code to test without * opening the file, and reads the same text to decide whether the line carries an ignore marker. + * Whether a line holds code is decided from its {@link #lenient} text. The build and the PIT + * process both read the text through this class, so the class depends on nothing but the JDK. */ public final class SourceLines { private final File repositoryRoot; - private final Map> byPath = new HashMap<>(); + private final Map byPath = new HashMap<>(); + + /** The lines of one file, and whether every byte of it decoded as UTF-8. */ + private static final class Text { + static final Text NONE = new Text(List.of(), false); + + final List lines; + final boolean decoded; + + Text(List lines, boolean decoded) { + this.lines = lines; + this.decoded = decoded; + } + + String line(int number) { + return number >= 1 && number <= lines.size() ? lines.get(number - 1) : ""; + } + } private SourceLines(File repositoryRoot) { this.repositoryRoot = repositoryRoot; } /** Returns the text of the files under the given repository, each read as it is asked for. */ - static SourceLines under(File repositoryRoot) { + public static SourceLines under(File repositoryRoot) { return new SourceLines(repositoryRoot); } @@ -56,15 +82,48 @@ static SourceLines under(File repositoryRoot) { * @param number 1-based line number, as JaCoCo numbers lines */ String get(String path, int number) { - List lines = byPath.computeIfAbsent(path, this::read); - return number >= 1 && number <= lines.size() ? lines.get(number - 1) : ""; + Text text = text(path); + return text.decoded ? text.line(number) : ""; } - private List read(String path) { + /** + * 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. + * + *

A file in another charset that encodes each ASCII character as its single ASCII byte, such + * as ISO-8859-1 or windows-1252, keeps its ASCII characters this way, which is all a reader of + * braces, separators, and keywords needs. A UTF-16 file does not. + * + * @param path repository-relative path, as a git diff spells it + * @param number 1-based line number + */ + public String lenient(String path, int number) { + return text(path).line(number); + } + + private Text text(String path) { + return byPath.computeIfAbsent(path, this::read); + } + + private Text read(String path) { + Path file; + try { + file = repositoryRoot.toPath().resolve(path); + } catch (InvalidPathException e) { + return Text.NONE; + } try { - return Files.readAllLines(repositoryRoot.toPath().resolve(path)); - } catch (IOException | InvalidPathException e) { - return List.of(); + return new Text(Files.readAllLines(file), true); + } catch (CharacterCodingException e) { + try (BufferedReader reader = + new BufferedReader( + new InputStreamReader(Files.newInputStream(file), StandardCharsets.UTF_8))) { + return new Text(reader.lines().collect(Collectors.toList()), false); + } catch (IOException | UncheckedIOException again) { + return Text.NONE; + } + } catch (IOException e) { + return Text.NONE; } } diff --git a/cribro-core/src/main/java/io/github/cribrodev/pitest/ChangedLinesFilter.java b/cribro-core/src/main/java/io/github/cribrodev/pitest/ChangedLinesFilter.java index 7c2d53e..d918f0a 100644 --- a/cribro-core/src/main/java/io/github/cribrodev/pitest/ChangedLinesFilter.java +++ b/cribro-core/src/main/java/io/github/cribrodev/pitest/ChangedLinesFilter.java @@ -15,19 +15,39 @@ */ package io.github.cribrodev.pitest; +import io.github.cribrodev.ChangedFile; +import io.github.cribrodev.ChangedLinesFile; +import io.github.cribrodev.CodeLines; +import io.github.cribrodev.SourceFileKey; +import io.github.cribrodev.SourceLines; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.file.Path; +import java.util.ArrayList; import java.util.Collection; +import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.NavigableSet; +import java.util.TreeMap; +import java.util.TreeSet; import java.util.stream.Collectors; -import io.github.cribrodev.SourceFileKey; +import java.util.stream.Stream; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.LineNumberNode; +import org.objectweb.asm.tree.MethodNode; import org.pitest.bytecode.analysis.ClassTree; +import org.pitest.classpath.CodeSource; import org.pitest.mutationtest.build.InterceptorType; import org.pitest.mutationtest.build.MutationInterceptor; import org.pitest.mutationtest.engine.Mutater; import org.pitest.mutationtest.engine.MutationDetails; /** - * Drops every mutant whose line the branch did not change. + * Drops every mutant whose line the branch did not change, and records which changed lines have + * bytecode and hold code. * *

A mutant is matched to its source file through the package of its class and the file name * the class records, which is how a {@link io.github.cribrodev.ChangedLinesFile} keys its @@ -36,17 +56,32 @@ * *

The filter runs in PIT's pre-scan as well as in the main scan. A dropped mutant costs no test * run, and where no mutant is left on any changed line, PIT skips its coverage pass and writes no - * report. + * report. Each scan starts by writing the changed lines with bytecode to the file {@link + * ChangedLinesFile#WITH_BYTECODE} names, so the file exists even where PIT writes no report. */ final class ChangedLinesFilter implements MutationInterceptor { private final Map> changed; + private final Map paths; + private final SourceLines sources; + private final Path withBytecode; /** * @param changed the changed line numbers, keyed by {@link SourceFileKey} + * @param paths the repository-relative path of each changed file, keyed by {@link + * SourceFileKey} + * @param sources the working tree the paths are relative to + * @param withBytecode the file to write the changed lines with bytecode that hold code to */ - ChangedLinesFilter(Map> changed) { + ChangedLinesFilter( + Map> changed, + Map paths, + SourceLines sources, + Path withBytecode) { this.changed = changed; + this.paths = paths; + this.sources = sources; + this.withBytecode = withBytecode; } @Override @@ -54,6 +89,90 @@ public InterceptorType type() { return InterceptorType.PRE_SCAN_FILTER; } + /** PIT calls this once per scan with the classes it may mutate, before it scans the first. */ + @Override + public void initialise(CodeSource code) { + try { + writeLinesWithBytecode(code.codeTrees()); + } catch (IOException e) { + throw new UncheckedIOException("Cannot write " + withBytecode, e); + } + } + + /** + * Writes the changed lines that a method of one of the classes records in its line table and + * that hold code, in the {@link ChangedLinesFile} format. + * + *

A line holds code where {@link CodeLines#holdsCode} says so, given whether the line is the + * first line of a method and the line's text as {@link SourceLines#lenient} reads it, as the + * coverage reports read it. Every line is passed as carrying + * no branch: PIT, like JaCoCo, leaves out the branches the compiler generates, such as the null + * check javac puts on the closing brace of a try-with-resources block, and a branch PIT keeps + * carries a mutant, which {@link io.github.cribrodev.PitestSurvivors} counts on its line. + * + *

The lines of a bridge method and of a synthetic method other than a lambda body are left + * out: the compiler generated that code. JaCoCo leaves them out of a Java class too, but keeps + * some synthetic code of a Kotlin class, such as a {@code $default} method, and leaves out some + * code this method counts, such as a private empty constructor, so the two counts can differ. + */ + void writeLinesWithBytecode(Stream classes) throws IOException { + Map> found = new TreeMap<>(); + Map> methodStarts = new HashMap<>(); + classes.forEach( + tree -> { + ClassNode node = tree.rawNode(); + if (node.sourceFile == null) { + return; + } + int packageEnd = node.name.lastIndexOf('/'); + String key = + SourceFileKey.of( + packageEnd < 0 ? "" : node.name.substring(0, packageEnd), node.sourceFile); + NavigableSet lines = changed.get(key); + if (lines == null) { + return; + } + for (MethodNode method : node.methods) { + if (!isWritten(method)) { + continue; + } + int firstLine = Integer.MAX_VALUE; + for (AbstractInsnNode instruction : method.instructions) { + if (instruction instanceof LineNumberNode) { + int line = ((LineNumberNode) instruction).line; + firstLine = Math.min(firstLine, line); + if (lines.contains(line)) { + found.computeIfAbsent(key, unused -> new TreeSet<>()).add(line); + } + } + } + methodStarts.computeIfAbsent(key, unused -> new TreeSet<>()).add(firstLine); + } + }); + List files = new ArrayList<>(); + found.forEach( + (key, lines) -> { + String path = paths.get(key); + NavigableSet code = new TreeSet<>(); + for (int line : lines) { + if (CodeLines.holdsCode( + false, methodStarts.get(key).contains(line), sources.lenient(path, line))) { + code.add(line); + } + } + files.add(new ChangedFile(path, key, code)); + }); + ChangedLinesFile.write(withBytecode, List.of(), files); + } + + /** Returns whether the source holds the code of the method, rather than the compiler alone. */ + private static boolean isWritten(MethodNode method) { + if ((method.access & Opcodes.ACC_BRIDGE) != 0) { + return false; + } + return (method.access & Opcodes.ACC_SYNTHETIC) == 0 || method.name.startsWith("lambda$"); + } + @Override public void begin(ClassTree clazz) {} diff --git a/cribro-core/src/main/java/io/github/cribrodev/pitest/ChangedLinesFilterFactory.java b/cribro-core/src/main/java/io/github/cribrodev/pitest/ChangedLinesFilterFactory.java index 12163d0..7d7d9e1 100644 --- a/cribro-core/src/main/java/io/github/cribrodev/pitest/ChangedLinesFilterFactory.java +++ b/cribro-core/src/main/java/io/github/cribrodev/pitest/ChangedLinesFilterFactory.java @@ -16,6 +16,8 @@ package io.github.cribrodev.pitest; import io.github.cribrodev.ChangedLinesFile; +import io.github.cribrodev.SourceLines; +import java.io.File; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.file.Path; @@ -28,18 +30,22 @@ /** * Creates a {@link ChangedLinesFilter} over the {@link ChangedLinesFile} that the system property - * {@value #PROPERTY} names. + * {@value #PROPERTY} names, reading the changed files under the repository that {@value + * #REPOSITORY} names. * *

PIT finds this factory through {@link java.util.ServiceLoader} on its own classpath. Whatever - * puts the factory there also sets the property: the Gradle {@code pitestDiff} task and the Maven - * goal {@code cribro:pitest-diff} do both. The feature is on by default so that the caller need not - * also pass {@code --features}, and a missing property fails the run rather than letting it mutate - * every line of the target classes. + * puts the factory there also sets both properties, as the Gradle {@code pitestDiff} task and the + * Maven goal {@code cribro:pitest-diff} do. The feature is on by default so that the caller need + * not also pass {@code --features}, and either property missing fails the run rather than letting + * it mutate every line of the target classes. The filter writes the changed lines with bytecode to + * PIT's report directory. */ public final class ChangedLinesFilterFactory implements MutationInterceptorFactory { private static final String PROPERTY = ChangedLinesFile.PITEST_PROPERTY; + private static final String REPOSITORY = ChangedLinesFile.REPOSITORY_PROPERTY; + @Override public String description() { return "Keeps only the mutants on lines the branch changed"; @@ -59,12 +65,26 @@ public MutationInterceptor createInterceptor(InterceptorParameters params) { throw new IllegalStateException( "System property " + PROPERTY + " is not set; it must name the changed-lines file"); } + String repository = System.getProperty(REPOSITORY); + if (repository == null) { + throw new IllegalStateException( + "System property " + + REPOSITORY + + " is not set; it must name the repository the changed-lines file's paths are" + + " relative to"); + } Map> lines; + Map paths; try { lines = ChangedLinesFile.read(Path.of(file)); + paths = ChangedLinesFile.readPaths(Path.of(file)); } catch (IOException e) { throw new UncheckedIOException("Cannot read the changed-lines file " + file, e); } - return new ChangedLinesFilter(lines); + return new ChangedLinesFilter( + lines, + paths, + SourceLines.under(new File(repository)), + Path.of(params.data().getReportDir()).resolve(ChangedLinesFile.WITH_BYTECODE)); } } diff --git a/cribro-core/src/test/java/io/github/cribrodev/CodeLinesTest.java b/cribro-core/src/test/java/io/github/cribrodev/CodeLinesTest.java new file mode 100644 index 0000000..fe144ff --- /dev/null +++ b/cribro-core/src/test/java/io/github/cribrodev/CodeLinesTest.java @@ -0,0 +1,99 @@ +/* + * 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.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.params.provider.Arguments.argumentSet; + +import java.util.stream.Stream; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +/** + * A line with bytecode holds code of its own unless its text is only braces, closing parentheses, + * semicolons, commas, and else, and it carries no branch and starts no method. + */ +class CodeLinesTest { + + static Stream bracesSeparatorsAndElse() { + return Stream.of( + argumentSet("a closing brace", "}"), + argumentSet("an opening brace", "{"), + argumentSet("an indented brace", " }"), + argumentSet("an else between braces", "} else {"), + argumentSet("an else between braces without spaces", "}else{"), + argumentSet("a lambda that ends a call", "});"), + argumentSet("a lambda followed by another argument", "}),"), + argumentSet("the end of a wrapped condition", ") {"), + argumentSet("a brace and a line comment", "} // end of the loop"), + argumentSet("a brace and a block comment", "} /* loop */"), + argumentSet("a brace and an unclosed block comment", "} /* the loop"), + argumentSet( + "a brace and the ignore marker", "} // diff-coverage: ignore -- defensive safeguard")); + } + + @ParameterizedTest + @MethodSource("bracesSeparatorsAndElse") + void bracesSeparatorsAndElseAloneAreRecognized(String source) { + assertTrue( + CodeLines.isOnlyBracesSeparatorsAndElse(source), + () -> "isOnlyBracesSeparatorsAndElse(\"" + source + "\")"); + } + + static Stream code() { + return Stream.of( + argumentSet("an else if", "} else if (b) {"), + argumentSet("a catch", "} catch (IOException e) {"), + argumentSet("a finally", "} finally {"), + argumentSet("the condition of a do loop", "} while (more);"), + argumentSet("a call on what a lambda argument built", "}).run();"), + argumentSet("the last argument of a wrapped call", "elseValue)"), + argumentSet("a brace inside a string", "String close = \"}\";"), + argumentSet("a comment alone", "// end of the loop"), + argumentSet("an empty line", ""), + argumentSet("whitespace alone", " ")); + } + + @ParameterizedTest + @MethodSource("code") + void anythingElseOrNothingIsNot(String source) { + assertFalse( + CodeLines.isOnlyBracesSeparatorsAndElse(source), + () -> "isOnlyBracesSeparatorsAndElse(\"" + source + "\")"); + } + + static Stream lines() { + return Stream.of( + argumentSet("a brace", false, false, "}", false), + argumentSet("a brace that carries a branch", true, false, "}", true), + argumentSet("a brace that starts a method", false, true, "}", true), + argumentSet("a statement", false, false, "x();", true), + argumentSet("a line the working tree cannot show", false, false, "", true)); + } + + @ParameterizedTest + @MethodSource("lines") + void aBraceHoldsCodeOnlyWhereItCarriesABranchOrStartsAMethod( + boolean carriesBranch, boolean startsMethod, String source, boolean holdsCode) { + assertEquals( + holdsCode, + CodeLines.holdsCode(carriesBranch, startsMethod, source), + () -> "holdsCode(" + carriesBranch + ", " + startsMethod + ", \"" + source + "\")"); + } +} diff --git a/cribro-core/src/test/java/io/github/cribrodev/DiffCoverageReportTest.java b/cribro-core/src/test/java/io/github/cribrodev/DiffCoverageReportTest.java index 2ee5073..732c966 100644 --- a/cribro-core/src/test/java/io/github/cribrodev/DiffCoverageReportTest.java +++ b/cribro-core/src/test/java/io/github/cribrodev/DiffCoverageReportTest.java @@ -23,6 +23,7 @@ import io.github.cribrodev.DiffCoverageReport.Limits; import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; @@ -76,10 +77,21 @@ private static String line( /** Reads a report holding the given {@code } elements for Sample.java. */ private JacocoLines report(String lines) throws IOException { + return report("", lines); + } + + /** + * Reads a report holding the given {@code } elements of a class compiled from + * Sample.java, and the given {@code } elements of Sample.java. + */ + private JacocoLines report(String methods, String lines) throws IOException { Path file = directory.resolve("jacocoTestReport.xml"); Files.writeString( file, "" + + "" + + methods + + "" + "" + lines + ""); @@ -244,6 +256,120 @@ void onlyTheFilesTheCountsCameFromAreNamedAsMeasured() throws IOException { } } + @Nested + class LinesThatHoldNoCode { + + @Test + void aBraceIsNeitherARowNorCountedInTheTotals() throws IOException { + writeSource("Sample.java", "if (a) {", " x();", "} else {", " y();", "}"); + DiffCoverageReport result = + measure( + List.of(changed(SAMPLE, 1, 2, 3, 4, 5)), + report( + line(1, 4, 1, 1) + + line(2, 0, 0, 0) + + line(3, 0, 0, 0) + + line(4, 4, 0, 0) + + line(5, 4, 0, 0))); + assertLinesMatch( + List.of( + "Diff coverage " + SCOPE, + " ordered by uncovered changed lines, then uncovered branches", + "", + " " + SAMPLE, + " 2/3 changed lines executed, 1/2 branches covered", + " uncovered changed code:", + " 1: 1 of 2 branches covered: if (a) {", + " 2: not executed: x();", + "", + "Total: 2/3 changed lines executed, 1/2 branches covered.", + "Uncovered changed code: 2 lines (1 not executed, 1 with an untaken branch)"), + result.render(SCOPE, false, List.of(), Limits.NONE).lines().toList()); + } + + @Test + void theClosingBraceOfAMethodWithAnEmptyBodyIsMeasured() throws IOException { + writeSource("Sample.java", "void noop() {", "}", "void run() {", " x();", "}"); + DiffCoverageReport result = + measure( + List.of(changed(SAMPLE, 1, 2, 3, 4, 5)), + report( + "" + + "", + line(2, 0, 0, 0) + line(4, 0, 0, 0) + line(5, 0, 0, 0))); + assertLinesMatch( + List.of( + "Diff coverage " + SCOPE, + " ordered by uncovered changed lines, then uncovered branches", + "", + " " + SAMPLE, + " 0/2 changed lines executed", + " uncovered changed code:", + " 2: not executed: }", + " 4: not executed: x();", + "", + "Total: 0/2 changed lines executed.", + "Uncovered changed code: 2 lines (2 not executed, 0 with an untaken branch)"), + result.render(SCOPE, false, List.of(), Limits.NONE).lines().toList()); + } + + @Test + void aBraceOfAFileThatIsNotUtf8IsNeitherARowNorCounted() throws IOException { + Path file = directory.resolve(SAMPLE); + Files.createDirectories(file.getParent()); + Files.write( + file, "// \u00a9 2020 Acme\nx();\n}\n".getBytes(StandardCharsets.ISO_8859_1)); + assertLinesMatch( + List.of( + "Diff coverage " + SCOPE, + " ordered by uncovered changed lines, then uncovered branches", + "", + " " + SAMPLE, + " 0/1 changed lines executed", + " uncovered changed code:", + " 2: not executed", + "", + "Total: 0/1 changed lines executed.", + "Uncovered changed code: 1 line (1 not executed, 0 with an untaken branch)"), + measure(List.of(changed(SAMPLE, 2, 3)), report(line(2, 0, 0, 0) + line(3, 0, 0, 0))) + .render(SCOPE, false, List.of(), Limits.NONE) + .lines() + .toList()); + } + + @Test + void aBraceThatCarriesABranchIsMeasuredLikeAnyLine() throws IOException { + writeSource("Sample.java", "}"); + String rendered = + measure(List.of(changed(SAMPLE, 1)), report(line(1, 4, 1, 1))) + .render(SCOPE, false, List.of(), Limits.NONE); + assertAll( + () -> + assertEquals( + List.of(" 1: 1 of 2 branches covered: }"), rows(rendered), "rows"), + () -> + assertEquals( + "Total: 1/1 changed lines executed, 1/2 branches covered.", + onlyLineStartingWith(rendered, "Total: "))); + } + + @Test + void aFileWhoseChangedLinesAreAllBracesHasNoExecutableChangedLines() throws IOException { + writeSource("Sample.java", "}", "} else {"); + DiffCoverageReport result = + measure(List.of(changed(SAMPLE, 1, 2)), report(line(1, 0, 0, 0) + line(2, 4, 0, 0))); + assertLinesMatch( + List.of( + "Diff coverage " + SCOPE, + "", + " Changed files with no executable changed lines:", + " " + SAMPLE, + "", + DiffCoverageReport.NO_EXECUTABLE_LINES), + result.render(SCOPE, false, List.of(), Limits.NONE).lines().toList()); + } + } + @Nested class FilesThatCannotBeMeasured { @@ -338,7 +464,8 @@ void aLineMarkedInACommentIsListedUnderTheAcknowledgedHeadingRatherThanAsWork() " 1: not executed: throw new AssertionError(); " + IGNORE, "", "Total: 0/1 changed lines executed.", - "Uncovered changed code: 1 line (1 acknowledged)"), + "Uncovered changed code: 1 line (1 not executed, 0 with an untaken branch), 1 of them" + + " acknowledged"), result.render(SCOPE, false, List.of(), Limits.NONE).lines().toList()); } @@ -426,7 +553,8 @@ void aFileWithBothKindsOfUncoveredLineIsDescribedInBothLists() throws IOExceptio " 1: not executed: throw new AssertionError(); " + IGNORE, "", "Total: 0/2 changed lines executed.", - "Uncovered changed code: 2 lines (1 acknowledged)"), + "Uncovered changed code: 2 lines (2 not executed, 0 with an untaken branch), 1 of" + + " them acknowledged"), result.render(SCOPE, false, List.of(), Limits.NONE).lines().toList()); } @@ -451,10 +579,23 @@ void theWorkListSpendsTheBudgetBeforeTheAcknowledgedListSeesIt() throws IOExcept () -> assertFalse(rendered.contains("Acknowledged"), rendered), () -> assertEquals( - "Uncovered changed code: 3 lines (1 acknowledged)", + "Uncovered changed code: 3 lines (3 not executed, 0 with an untaken branch), 1 of" + + " them acknowledged", onlyLineStartingWith(rendered, "Uncovered changed code: "))); } + @Test + void anAcknowledgedLineIsCountedInItsGroupAndAmongTheAcknowledged() throws IOException { + writeSource("Sample.java", "if (a) { " + IGNORE, "return 1;"); + String rendered = + measure(List.of(changed(SAMPLE, 1, 2)), report(line(1, 4, 1, 1) + line(2, 0, 0, 0))) + .render(SCOPE, false, List.of(), Limits.NONE); + assertEquals( + "Uncovered changed code: 2 lines (1 not executed, 1 with an untaken branch), 1 of them" + + " acknowledged", + onlyLineStartingWith(rendered, "Uncovered changed code: ")); + } + @Test void theAcknowledgedFilesPastTheFileCapAreReplacedByTheirCount() throws IOException { writeSource("First.java", "a(); " + IGNORE); @@ -511,7 +652,7 @@ void aMeasuredFileRendersItsCountsAndOneRowPerUncoveredLine() throws IOException " 3: not executed; 0 of 2 branches covered: if (b) {", "", "Total: 1/3 changed lines executed, 1/4 branches covered.", - "Uncovered changed code: 3 lines"), + "Uncovered changed code: 3 lines (2 not executed, 1 with an untaken branch)"), result.render(SCOPE, false, List.of(), Limits.NONE).lines().toList()); } @@ -533,7 +674,7 @@ void aLineNeitherExecutedNorFullyBranchedTakesOneRowCarryingBothCounts() throws "rows"), () -> assertEquals( - "Uncovered changed code: 1 line", + "Uncovered changed code: 1 line (1 not executed, 0 with an untaken branch)", onlyLineStartingWith(rendered, "Uncovered changed code: "))); } @@ -656,10 +797,19 @@ void theUncoveredTotalCountsTheRowsRatherThanTheUnexecutedLines() throws IOExcep onlyLineStartingWith(rendered, "Total: ")), () -> assertEquals( - "Uncovered changed code: 2 lines", + "Uncovered changed code: 2 lines (1 not executed, 1 with an untaken branch)", onlyLineStartingWith(rendered, "Uncovered changed code: "))); } + @Test + void anExecutedLineWithAnUntakenBranchCountsInTheBranchGroupAlone() throws IOException { + DiffCoverageReport result = measure(List.of(changed(SAMPLE, 10)), report(line(10, 4, 1, 1))); + assertEquals( + "Uncovered changed code: 1 line (0 not executed, 1 with an untaken branch)", + onlyLineStartingWith( + result.render(SCOPE, false, List.of(), Limits.NONE), "Uncovered changed code: ")); + } + @Test void aChangeWithEveryLineCoveredReportsNoUncoveredCode() throws IOException { String rendered = diff --git a/cribro-core/src/test/java/io/github/cribrodev/ExposedCodeReportTest.java b/cribro-core/src/test/java/io/github/cribrodev/ExposedCodeReportTest.java index 89066f5..c82faa8 100644 --- a/cribro-core/src/test/java/io/github/cribrodev/ExposedCodeReportTest.java +++ b/cribro-core/src/test/java/io/github/cribrodev/ExposedCodeReportTest.java @@ -41,7 +41,10 @@ class ExposedCodeReportTest { private static final String SAMPLE = ROOT + "/p/Sample.java"; private static final String SAMPLE_TEST = "lib/src/test/java/p/SampleTest.java"; - /** A case label changed at line 7 exposes lines 8-11; {@code helper} is called from line 9. */ + /** + * A case label changed at line 7 exposes lines 8-11; the call at line 9 matches both overloads of + * {@code helper} by name. + */ private static final String SOURCE = """ package p; @@ -65,6 +68,9 @@ int helper(int c) { int twice = c * 2; return twice; } + int helper(String c) { + return c.length(); + } } """; @@ -92,7 +98,8 @@ private static String line( /** * Renders the block for the change of line 7 of Sample.java and line 5 of SampleTest.java, - * against a run that took one branch of line 8, never reached line 9, and ran the helper whole. + * against a run that took one branch of line 8, never reached line 9, ran {@code helper(int)} + * whole, and never ran {@code helper(String)}. */ private String render(String scope, boolean filtered, Limits limits) throws IOException { write(SAMPLE, SOURCE); @@ -108,6 +115,7 @@ private String render(String scope, boolean filtered, Limits limits) throws IOEx + line(11, 1, 0, 0) + line(19, 4, 0, 0) + line(20, 2, 0, 0) + + line(23, 0, 0, 0) + ""); ExposedCode exposed = ExposedCode.find(directory.toFile(), changed, List.of(ROOT)); return ExposedCodeReport.measure( @@ -138,12 +146,15 @@ void anUnfilteredRunListsWhatItLeftUncoveredAndHowToRunTheChangesTests() throws " test a gap below where those inputs can reach it", "", " lib/src/main/java/p/Sample.java", - " run lines 8-11, reached through the conditions changed at line 7", + " run(int, int), lines 8-11, reached through the conditions changed at line 7", " 2/3 lines executed, 1/2 branches covered", " 8: 1 of 2 branches covered: if (c > 0) {", " 9: not executed: out = helper(c);", - " helper, whole body, called from line 9", + " helper(int), whole body, called from line 9", " 2/2 lines executed", + " helper(String), whole body, called from line 9", + " 0/1 lines executed", + " 23: not executed: return c.length();", "", " The counts include every test the run executed, and older tests may reach", " this code under the old conditions. To list only what the change's own tests leave" @@ -183,16 +194,86 @@ void theLimitsCutTheMethodsAndTheRowsEachOneShows() throws IOException { assertLinesMatch( List.of( ">> header >>", - " run lines 8-11, reached through the conditions changed at line 7", + " run(int, int), lines 8-11, reached through the conditions changed at line 7", " 2/3 lines executed, 1/2 branches covered", " 8: 1 of 2 branches covered: if (c > 0) {", " 1 more line in the full report", "", - " 1 more exposed method in the full report", + " 2 more exposed methods in the full report", ">> tail >>"), render(":lib:test", false, new Limits(1, 1, 50)).lines().toList()); } + @Test + void aBraceLineIsNeitherARowNorCountedUnlessItCarriesABranchOrIsTheBodyOfAnEmptyLambda() + throws IOException { + write( + SAMPLE, + """ + package p; + class Sample { + int run(int x) { + if (x > 0) { + x++; + later(() -> { + }); + } else { + x--; + } + while (x > 9) { + x--; + } + return x; + } + void later(Runnable r) {} + } + """); + Path xml = directory.resolve("jacoco.xml"); + Files.writeString( + xml, + "" + + "" + + "" + + "" + + "" + + line(4, 4, 1, 1) + + line(5, 0, 0, 0) + + line(6, 0, 0, 0) + + line(7, 0, 0, 0) + + line(8, 0, 0, 0) + + line(9, 2, 0, 0) + + line(10, 2, 1, 1) + + line(11, 4, 1, 1) + + line(12, 0, 0, 0) + + line(13, 0, 0, 0) + + line(14, 2, 0, 0) + + ""); + ExposedCode exposed = + ExposedCode.find( + directory.toFile(), Map.of(SAMPLE, new TreeSet<>(List.of(4, 11))), List.of(ROOT)); + + assertLinesMatch( + List.of( + ">> header >>", + " " + SAMPLE, + " run\\S* lines 5-13, reached through the conditions changed at lines 4, 11", + " 2/6 lines executed, 1/2 branches covered", + " 5: not executed: x++;", + " 6: not executed: later(() -> {", + " 7: not executed: });", + " 10: 1 of 2 branches covered: }", + " 12: not executed: x--;", + ">> tail >>"), + ExposedCodeReport.measure( + exposed, + Map.of(SAMPLE, "p/Sample.java"), + JacocoLines.read(List.of(xml.toFile())), + SourceLines.under(directory.toFile())) + .render(":lib:test", false, tests -> "", Limits.NONE) + .lines() + .toList()); + } + @Test void consecutiveLinesPrintAsARange() { assertEquals( diff --git a/cribro-core/src/test/java/io/github/cribrodev/ExposedCodeTest.java b/cribro-core/src/test/java/io/github/cribrodev/ExposedCodeTest.java index b9937c4..b00b23b 100644 --- a/cribro-core/src/test/java/io/github/cribrodev/ExposedCodeTest.java +++ b/cribro-core/src/test/java/io/github/cribrodev/ExposedCodeTest.java @@ -123,7 +123,7 @@ int run(int state, int c) { } """; write(SAMPLE, source); - assertExposed(source, List.of("run under [7]")); + assertExposed(source, List.of("run(int, int) under [7]")); } @Test @@ -152,7 +152,7 @@ int run(int state, int c) { } """; write(SAMPLE, source); - assertExposed(source, List.of("run under [6]")); + assertExposed(source, List.of("run(int, int) under [6]")); } @Test @@ -176,7 +176,7 @@ int run(int c) { } """; write(SAMPLE, source); - assertExposed(source, List.of("run under [5]")); + assertExposed(source, List.of("run(int) under [5]")); } @Test @@ -205,7 +205,7 @@ int run(int c) { } """; write(SAMPLE, source); - assertExposed(source, List.of("run under [5, 9, 14, 15]")); + assertExposed(source, List.of("run(int) under [5, 9, 14, 15]")); } @Test @@ -262,7 +262,7 @@ int edited(int c) { } """; write(SAMPLE, source); - assertExposed(source, List.of("helper called from [5]", "viaThis called from [5]")); + assertExposed(source, List.of("helper(int) called from [5]", "viaThis(int) called from [5]")); } @Test @@ -283,7 +283,180 @@ int helper(int c) { } """; write(SAMPLE, source); - assertExposed(source, List.of("run under [4]", "helper called from [5]")); + assertExposed(source, List.of("run(int) under [4]", "helper(int) called from [5]")); + } + + @Test + void eachOverloadACallReachesIsNamedByItsParameterTypes() throws IOException { + String source = + """ + package p; + import java.util.List; + class Sample { + void run() { + helper(1); // changed + } + void helper(int c) { + int a = c; // exposed + } + void helper(String s) { + String b = s; // exposed + } + void helper(String... parts) { + int d = parts.length; // exposed + } + void helper(java.util.@Nullable List<@Nullable String> items, int[] counts) { + int e = counts.length; // exposed + } + void helper(int[]... grids) { + int f = grids.length; // exposed + } + void helper(long @Nullable [] @Nullable ... rows) { + int g = rows.length; // exposed + } + void helper(@Doc(url = "http://x") char /* c */ ... /* chars */ cs) { + int h = cs.length; // exposed + } + void helper(byte @Doc("...") [] bytes) { + int l = bytes.length; // exposed + } + void helper(Outer.Inner inner) { + Object i = inner; // exposed + } + void helper(T t) { + Object j = t; // exposed + } + void helper(T t) { + Object k = t; // exposed + } + } + """; + write(SAMPLE, source); + assertExposed( + source, + List.of( + "helper(int) called from [5]", + "helper(String) called from [5]", + "helper(String...) called from [5]", + "helper(java.util.List, int[]) called from [5]", + "helper(int[]...) called from [5]", + "helper(long[]...) called from [5]", + "helper(char...) called from [5]", + "helper(byte[]) called from [5]", + "helper(Outer.Inner) called from [5]", + "helper(T) at line 34 called from [5]", + "helper(T) at line 37 called from [5]")); + } + + @Test + void eachDeclarationOfAFileHoldingOneTopLevelClassGetsANameOfItsOwn() throws IOException { + String source = + """ + package p; + class Sample { + int value; + Sample(int c) { + if (c > 0) { // changed + value = c; // exposed + } // exposed + } + void start() { + build(); Builder(); m(1); x(); // changed + new Runnable() { + public void run() { + if (value > 0) { // changed + value--; // exposed + } // exposed + } + }; + new Runnable() { + public void run() { + if (value < 0) { // changed + value++; // exposed + } // exposed + } + }; + class L { + void x() { + int a = 1; // exposed + } + } + } + void other() { + class L { + void x() { + int b = 2; // exposed + } + } + } + void Builder() { + int d = 4; // exposed + } + static class Builder { + Builder() { + if (Sample.class != null) { // changed + build(); // exposed + } // exposed + } + void build() { + int e = 5; // exposed + } + } + enum Mode { + A { + void m(int c) { + int f = c; // exposed + } + }, + B { + void m(int c) { + int g = c; // exposed + } + }; + void m(int c) {} + } + } + """; + write(SAMPLE, source); + assertExposed( + source, + List.of( + "new Sample(int) under [5]", + "(anonymous Runnable).run() at line 12 under [13]", + "(anonymous Runnable).run() at line 19 under [20]", + "new Builder() under [43]", + "Builder.build() called from [10, 44]", + "Builder() called from [10]", + "Mode.(anonymous Mode).m(int) at line 53 called from [10]", + "Mode.(anonymous Mode).m(int) at line 58 called from [10]", + "L.x() at line 26 called from [10]", + "L.x() at line 33 called from [10]")); + } + + @Test + void aFileHoldingTwoTopLevelClassesNamesEachMethodWithItsOutermostClass() throws IOException { + String source = + """ + package p; + class Sample { + void run() { + y(1); // changed + } + static class Bar { + void y(int c) { + int a = c; // exposed + } + } + } + class Bar { + void y(int c) { + int b = c; // exposed + } + } + """; + write(SAMPLE, source); + assertExposed( + source, List.of("Sample.Bar.y(int) called from [4]", "Bar.y(int) called from [4]")); } @Test diff --git a/cribro-core/src/test/java/io/github/cribrodev/JacocoLinesTest.java b/cribro-core/src/test/java/io/github/cribrodev/JacocoLinesTest.java index 39e446f..b561463 100644 --- a/cribro-core/src/test/java/io/github/cribrodev/JacocoLinesTest.java +++ b/cribro-core/src/test/java/io/github/cribrodev/JacocoLinesTest.java @@ -138,6 +138,23 @@ void aSourceFileTheReportMentionsIsCovered() throws IOException { assertTrue(read("").covers(KEY)); } + @Test + void theFirstLineOfAMethodIsRecordedAgainstTheSourceFileOfItsClass() throws IOException { + File file = new File(directory.toFile(), "methods.xml"); + Files.writeString( + file.toPath(), + "" + + "" + + "" + + "" + + ""); + JacocoLines lines = JacocoLines.read(List.of(file)); + assertAll( + () -> assertTrue(lines.startsMethod(KEY, 7), "startsMethod(7)"), + () -> assertFalse(lines.startsMethod(KEY, 8), "startsMethod(8)"), + () -> assertFalse(lines.startsMethod(KEY, 0), "startsMethod(0)")); + } + /** JaCoCo names the default package with an empty string, which no key spells out. */ @Test void aSourceFileInTheDefaultPackageIsKeyedByItsNameAlone() throws IOException { diff --git a/cribro-core/src/test/java/io/github/cribrodev/PitestJvmArgsTest.java b/cribro-core/src/test/java/io/github/cribrodev/PitestJvmArgsTest.java index 23daee1..2f24543 100644 --- a/cribro-core/src/test/java/io/github/cribrodev/PitestJvmArgsTest.java +++ b/cribro-core/src/test/java/io/github/cribrodev/PitestJvmArgsTest.java @@ -15,11 +15,18 @@ */ package io.github.cribrodev; +import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; +import java.util.ArrayList; import java.util.List; import java.util.Map; +import joptsimple.OptionParser; +import joptsimple.OptionSpec; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.pitest.mutationtest.commandline.CommaAwareArgsProcessor; /** * The test JVM under PIT gets the JVM arguments, the system properties, and the heap limit of the @@ -31,6 +38,13 @@ */ class PitestJvmArgsTest { + /** Returns the arguments that the PIT on the test classpath makes of a {@code --jvmArgs} value. */ + private static List pitSplit(String value) { + OptionParser parser = new OptionParser(); + OptionSpec jvmArgs = parser.accepts("jvmArgs").withRequiredArg(); + return new CommaAwareArgsProcessor(jvmArgs).values(parser.parse("--jvmArgs", value)); + } + @Test void systemPropertiesReachTheTestJvm() { assertEquals( @@ -44,12 +58,40 @@ void aTaskWithNoHeapLimitPassesNone() { assertEquals("-Da=1", PitestJvmArgs.of(List.of(), Map.of("a", 1), null).value()); } - /** PIT would split the value into two arguments and pass the test JVM both halves. */ @Test - void anArgumentWithACommaIsLeftOut() { + void anArgumentWithACommaReachesTheTestJvmWhole() { PitestJvmArgs args = PitestJvmArgs.of(List.of("-ea"), Map.of("packages", "a,b"), null); - assertEquals("-ea", args.value()); - assertEquals(List.of("-Dpackages=a,b"), args.leftOut()); + assertAll( + () -> assertEquals(List.of("-ea", "-Dpackages=a,b"), pitSplit(args.value())), + () -> assertEquals(List.of(), args.leftOut(), "leftOut")); + } + + /** PIT would remove the argument's own braces and pass {@code -Dpattern=a,b}. */ + @ParameterizedTest + @ValueSource(strings = {"{a,b}", "a,b}"}) + void anArgumentWithACommaAndABraceIsLeftOut(String pattern) { + PitestJvmArgs args = PitestJvmArgs.of(List.of("-ea"), Map.of("pattern", pattern), null); + assertAll( + () -> assertEquals(List.of("-ea"), pitSplit(args.value())), + () -> assertEquals(List.of("-Dpattern=" + pattern), args.leftOut(), "leftOut")); + } + + /** PIT removes the braces of every argument once it finds a comma inside braces. */ + @ParameterizedTest + @ValueSource(strings = {"-Dx={y}", "-Dd=}"}) + void aBraceInAnotherArgumentLeavesAnArgumentWithACommaOut(String braced) { + PitestJvmArgs args = PitestJvmArgs.of(List.of(braced), Map.of("packages", "a,b"), null); + assertAll( + () -> assertEquals(List.of(braced), pitSplit(args.value())), + () -> assertEquals(List.of("-Dpackages=a,b"), args.leftOut(), "leftOut")); + } + + @Test + void anArgumentWithACommaAndWhitespaceIsLeftOut() { + PitestJvmArgs args = PitestJvmArgs.of(List.of("-ea"), Map.of("packages", "a, b"), null); + assertAll( + () -> assertEquals(List.of("-ea"), pitSplit(args.value())), + () -> assertEquals(List.of("-Dpackages=a, b"), args.leftOut(), "leftOut")); } /** @@ -63,4 +105,57 @@ void anArgumentWithWhitespaceIsLeftOut() { assertEquals("", args.value()); assertEquals(List.of("-Djunit.jupiter.execution.timeout.default=5 m"), args.leftOut()); } + + /** + * The {@code java} launcher drops the quotes of a line in an argument file and reads what follows + * a {@code #} as a comment. + */ + @Test + void anArgumentWithAQuoteOrAHashIsLeftOut() { + List changed = List.of("-Dq=\"x\"", "-Dq='x'", "-Dh=a#b", "-Dh=a#b,c"); + PitestJvmArgs args = PitestJvmArgs.of(changed, Map.of(), null); + assertAll( + () -> assertEquals("", args.value(), "value"), + () -> assertEquals(changed, args.leftOut(), "leftOut")); + } + + /** The launcher treats a backslash outside quotes as an ordinary character. */ + @Test + void anArgumentWithABackslashIsPassed() { + PitestJvmArgs args = + PitestJvmArgs.of(List.of("-Dd=C:\\dir\\x", "-Dp=a\\b,c"), Map.of(), null); + assertAll( + () -> assertEquals(List.of("-Dd=C:\\dir\\x", "-Dp=a\\b,c"), pitSplit(args.value())), + () -> assertEquals(List.of(), args.leftOut(), "leftOut")); + } + + /** PIT would read the comma after the open brace as inside it and join the heap limit to it. */ + @Test + void anArgumentThatLeavesABraceOpenIsLeftOut() { + PitestJvmArgs args = PitestJvmArgs.of(List.of("-Dx={"), Map.of(), "1g"); + assertAll( + () -> assertEquals(List.of("-Xmx1g"), pitSplit(args.value())), + () -> assertEquals(List.of("-Dx={"), args.leftOut(), "leftOut")); + } + + @Test + void everyPassedArgumentComesOutOfPitsSplitAsItWent() { + List arguments = + List.of( + "-ea", "-Da={b}", "-Dc=}{", "-Dd=}", "-De={", "-Df=g{h}i", "-Dj=a,b", "-Dk=@x", + "-Xmx1g"); + PitestJvmArgs args = PitestJvmArgs.of(arguments, Map.of(), null); + List passed = new ArrayList<>(arguments); + passed.removeAll(args.leftOut()); + assertEquals(passed, pitSplit(args.value()), "leftOut " + args.leftOut()); + } + + /** A brace in an argument that is left out anyway does not keep a comma out of braces. */ + @Test + void aBraceInALeftOutArgumentStillLetsACommaThrough() { + PitestJvmArgs args = PitestJvmArgs.of(List.of("-Dx={\"y\"}"), Map.of("p", "a,b"), null); + assertAll( + () -> assertEquals(List.of("-Dp=a,b"), pitSplit(args.value())), + () -> assertEquals(List.of("-Dx={\"y\"}"), args.leftOut(), "leftOut")); + } } 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 628466d..9327b24 100644 --- a/cribro-core/src/test/java/io/github/cribrodev/PitestRunTest.java +++ b/cribro-core/src/test/java/io/github/cribrodev/PitestRunTest.java @@ -15,8 +15,10 @@ */ 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.assertLinesMatch; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.File; @@ -25,6 +27,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.util.List; +import java.util.Map; import java.util.TreeSet; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -42,6 +45,7 @@ private PitestRun pit(List classPath) { .targetClasses(List.of("demo.Calc")) .reportDir(directory.resolve("report").toFile()) .changedLines(directory.resolve("changed-lines.txt").toFile()) + .repository(directory.toFile()) .sourceEncoding("UTF-8") .classPath(classPath); } @@ -65,6 +69,56 @@ void pitLeavesItsOwnLaunchClasspathOffTheTestsClasspath() throws IOException { assertEquals("false", option(arguments(List.of()), "includeLaunchClasspath")); } + @Test + void eachLeftOutArgumentIsNamedWithTheReasonThatLeftItOut() { + PitestJvmArgs args = + PitestJvmArgs.of( + List.of("-Dq=\"x\"", "-Dt=5 m", "-Dx={a,b}", "-Do={", "-Dh=a#b", "-Dd=}"), + Map.of("p", "a,b"), + null); + assertEquals( + "PIT ran the tests without these JVM arguments of the test task, since the java launcher" + + " splits a line of the argument file the test JVM starts with at whitespace, removes" + + " its quotes, and ends it at a # (hcoles/pitest#1511):\n" + + " -Dq=\"x\"\n" + + " -Dt=5 m\n" + + " -Dh=a#b\n" + + "PIT ran the tests without these JVM arguments of the test task, since PIT's" + + " --jvmArgs splits at a comma outside braces and removes every brace once a comma is" + + " inside them:\n" + + " -Dx={a,b}\n" + + "PIT ran the tests without these JVM arguments of the test task, since PIT's" + + " --jvmArgs joins an argument with a { that no } closes to the argument after it:\n" + + " -Do={\n" + + "PIT ran the tests without these JVM arguments of the test task, since PIT's" + + " --jvmArgs splits at a comma outside braces, and a comma inside braces would make it" + + " remove the braces of -Dd=}:\n" + + " -Dp=a,b", + PitestRun.leftOutMessage(args.leftOutByReason(), "the test task")); + } + + @Test + void aLineBreakInsideALeftOutArgumentIsPrintedAsAnEscape() { + String reason = "the reason"; + assertEquals( + "PIT ran the tests without these JVM arguments of the test task, since the reason:\n" + + " -Dp=a b\\n -Dq=c d\\r\\n\n" + + " -Dw=C:\\tmp", + PitestRun.leftOutMessage( + Map.of(reason, List.of("-Dp=a b\n -Dq=c d\r\n", "-Dw=C:\\tmp")), "the test task"), + "one argument holding a line break must not read as two, and a backslash stays as it is"); + } + + @Test + void noArgumentLeftOutNeedsNoLine() { + assertNull(PitestRun.leftOutMessage(Map.of(), "the test task")); + } + + @Test + void aRunThatNamesNoMutatorsUsesTheStrongerGroup() throws IOException { + assertEquals("STRONGER", option(arguments(List.of()), "mutators")); + } + @Test void aRunWithNoTestGlobNamesEveryTestByARegularExpression() throws IOException { assertEquals( @@ -170,11 +224,26 @@ void aRunWithoutASourceEncodingIsRefused() { } @Test - void pitsFilterGetsTheChangedLinesFile() { - File changedLines = directory.resolve("changed-lines.txt").toFile(); + void pitsFilterGetsTheChangedLinesFileAndTheRepository() { + Map properties = pit(List.of()).systemProperties(); + + assertAll( + () -> + assertEquals( + directory.resolve("changed-lines.txt").toFile().getAbsolutePath(), + properties.get(ChangedLinesFile.PITEST_PROPERTY), + ChangedLinesFile.PITEST_PROPERTY), + () -> + assertEquals( + directory.toFile().getAbsolutePath(), + properties.get(ChangedLinesFile.REPOSITORY_PROPERTY), + ChangedLinesFile.REPOSITORY_PROPERTY)); + } - assertEquals( - changedLines.getAbsolutePath(), - pit(List.of()).systemProperties().get(ChangedLinesFile.PITEST_PROPERTY)); + @Test + void aRunWithoutARepositoryIsRefused() { + PitestRun pit = pit(List.of()).repository(null); + + assertThrows(IllegalStateException.class, pit::systemProperties); } } 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 7d8170f..6d31d6b 100644 --- a/cribro-core/src/test/java/io/github/cribrodev/PitestSurvivorsTest.java +++ b/cribro-core/src/test/java/io/github/cribrodev/PitestSurvivorsTest.java @@ -15,7 +15,10 @@ */ 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.assertTrue; +import static org.junit.jupiter.params.provider.Arguments.argumentSet; import java.io.File; import java.io.IOException; @@ -23,9 +26,14 @@ import java.nio.file.Path; import java.util.List; import java.util.Map; +import java.util.Set; +import java.util.stream.Stream; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; /** * The report prints each live mutant under its file and line, with the line's source text and the @@ -41,9 +49,7 @@ class PitestSurvivorsTest { + " 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" - + " - you cannot tell: report it as unresolved\n" - + "\n" - + "PIT generates no mutant on a line that calls a logging library."; + + " - you cannot tell: report it as unresolved"; @TempDir Path repository; @@ -70,9 +76,12 @@ private Path mutantsFile(String... mutations) throws IOException { return file; } - /** Reads a run whose sources are com/x/A.java and com/x/B.java, each with five lines. */ + /** + * Reads a run whose sources are com/x/A.java and com/x/B.java, each with five lines, and whose + * changed lines with bytecode are the lines of its mutants. + */ private PitestSurvivors run(String... mutations) throws IOException { - return run(Map.of(), mutations); + return read(Map.of(), Map.of(), mutations); } /** @@ -80,6 +89,25 @@ private PitestSurvivors run(String... mutations) throws IOException { * root {@code src}, with the changed-lines file naming the given path for each key. */ private PitestSurvivors run(Map paths, String... mutations) throws IOException { + return read(paths, Map.of(), mutations); + } + + /** + * Reads a run whose sources are com/x/A.java and com/x/B.java, each with five lines, and which + * recorded the given changed lines with bytecode, or wrote no such record where null. + */ + private PitestSurvivors runRecording( + Map> withBytecode, String... mutations) throws IOException { + return read(Map.of(), withBytecode, mutations); + } + + /** + * Reads a run whose sources are com/x/A.java and com/x/B.java, each with five lines, under the + * root {@code src}. + */ + private PitestSurvivors read( + Map paths, Map> withBytecode, String... mutations) + throws IOException { Path sources = repository.resolve("src"); Files.createDirectories(sources.resolve("com/x")); Files.writeString(sources.resolve("com/x/A.java"), "a1\n a2\na3\na4\na5\n"); @@ -89,7 +117,23 @@ private PitestSurvivors run(Map paths, String... mutations) thro mutantsFile(mutations).toFile(), repository.toFile(), List.of(new File("absent"), sources.toFile()), - paths); + paths, + withBytecode); + } + + /** + * Reads a run that wrote no mutants.tsv, as PIT does where it generated no mutant on the changed + * lines, and which recorded the given changed lines with bytecode. + */ + private PitestSurvivors runWithoutMutantsFile(Map> withBytecode) + throws IOException { + return PitestSurvivors.read( + "against origin/master (abc), all tests", + repository.resolve("absent/mutants.tsv").toFile(), + repository.toFile(), + List.of(repository.toFile()), + Map.of(), + withBytecode); } /** Writes a file of the repository. */ @@ -108,7 +152,7 @@ void aPathTheChangedLinesFileNamesIsQuotedRatherThanTheFileUnderARoot() throws I write("gen/A.java", "g1\ng2\n"); assertEquals( "Mutation testing of changed lines against origin/master (abc), all tests\n" - + " 1 mutant: 0 killed, 1 survived, 0 not reached by any test\n" + + " 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" + " gen/A.java\n" @@ -127,7 +171,7 @@ void aPathTheChangedLinesFileNamesIsQuotedRatherThanTheFileUnderARoot() throws I void aPathTheChangedLinesFileNamesThatNoLongerExistsFallsBackToTheRoots() throws IOException { assertEquals( "Mutation testing of changed lines against origin/master (abc), all tests\n" - + " 1 mutant: 0 killed, 1 survived, 0 not reached by any test\n" + + " 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" @@ -147,7 +191,7 @@ void aMutantInTheDefaultPackageIsFoundByItsFileNameUnderARoot() throws IOExcepti write("src/D.java", "d1\n"); assertEquals( "Mutation testing of changed lines against origin/master (abc), all tests\n" - + " 1 mutant: 0 killed, 1 survived, 0 not reached by any test\n" + + " 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/D.java\n" @@ -165,7 +209,7 @@ void aMutantInTheDefaultPackageIsFoundByItsFileNameUnderARoot() throws IOExcepti void liveMutantsAreGroupedByFileAndLineWithTheTestsThatReachThem() throws IOException { assertEquals( "Mutation testing of changed lines against origin/master (abc), all tests\n" - + " 4 mutants: 1 killed, 2 survived, 1 not reached by any test\n" + + " 4 mutants on 3 of 3 changed lines: 1 killed, 2 survived, 1 not reached by any test\n" + " ordered by live mutants per file, then by line\n" + "\n" + " src/com/x/A.java\n" @@ -190,7 +234,8 @@ void liveMutantsAreGroupedByFileAndLineWithTheTestsThatReachThem() throws IOExce void aTimeoutCountsAsKilledAndANonViableMutantIsCountedApart() throws IOException { assertEquals( "Mutation testing of changed lines against origin/master (abc), all tests\n" - + " 3 mutants: 2 killed, 0 survived, 0 not reached by any test, 1 NON_VIABLE", + + " 3 mutants on 3 of 3 changed lines: 2 killed (1 timed out), 0 survived, 0 not reached by any test," + + " 1 NON_VIABLE", run( mutation("KILLED", "A", "A.java", 1, "removed call"), mutation("TIMED_OUT", "A", "A.java", 2, "negated conditional"), @@ -198,11 +243,101 @@ void aTimeoutCountsAsKilledAndANonViableMutantIsCountedApart() throws IOExceptio .render(DiffCoverageReport.Limits.NONE, List.of())); } + @Test + void theKilledCountNamesTheTimeoutsAndTheMemoryErrorsAmongIt() throws IOException { + assertEquals( + "Mutation testing of changed lines against origin/master (abc), all tests\n" + + " 4 mutants on 4 of 4 changed lines: 4 killed (2 timed out, 1 out of memory), 0 survived," + + " 0 not reached by any test", + run( + mutation("MEMORY_ERROR", "A", "A.java", 1, "removed call"), + mutation("TIMED_OUT", "A", "A.java", 2, "negated conditional"), + mutation("KILLED", "A", "A.java", 3, "negated conditional"), + mutation("TIMED_OUT", "A", "A.java", 4, "negated conditional")) + .render(DiffCoverageReport.Limits.NONE, List.of())); + } + + @Nested + class TheChangedLineCount { + + @Test + void countsTheLinesWithAMutantAmongTheChangedLinesWithBytecode() throws IOException { + assertEquals( + "Mutation testing of changed lines against origin/master (abc), all tests\n" + + " 3 mutants on 2 of 4 changed lines: 3 killed, 0 survived," + + " 0 not reached by any test\n" + + "\n" + + "PIT generates no mutant on a line that calls a logging library.", + runRecording( + Map.of("com/x/A.java", Set.of(1, 2, 3), "com/x/B.java", Set.of(1)), + mutation("KILLED", "A", "A.java", 1, "removed call"), + mutation("KILLED", "A", "A.java", 1, "negated conditional"), + mutation("KILLED", "B", "B.java", 1, "removed call")) + .render(DiffCoverageReport.Limits.NONE, List.of())); + } + + @Test + void aMutatedLineTheRunDidNotRecordStillCountsAsALineWithBytecode() throws IOException { + assertEquals( + "Mutation testing of changed lines against origin/master (abc), all tests\n" + + " 1 mutant on 1 of 2 changed lines: 1 killed, 0 survived," + + " 0 not reached by any test\n" + + "\n" + + "PIT generates no mutant on a line that calls a logging library.", + runRecording( + Map.of("com/x/A.java", Set.of(1)), + mutation("KILLED", "A", "A.java", 2, "removed call")) + .render(DiffCoverageReport.Limits.NONE, List.of())); + } + + @Test + void withoutTheRecordedLinesOnlyTheLinesWithAMutantAreCounted() throws IOException { + assertEquals( + "Mutation testing of changed lines against origin/master (abc), all tests\n" + + " 3 mutants on 2 changed lines: 3 killed, 0 survived, 0 not reached by any test", + runRecording( + null, + mutation("KILLED", "A", "A.java", 1, "removed call"), + mutation("KILLED", "A", "A.java", 1, "negated conditional"), + mutation("KILLED", "A", "A.java", 2, "removed call")) + .render(DiffCoverageReport.Limits.NONE, List.of())); + } + + @Test + void withoutTheRecordedLinesASurvivorStillGetsTheNoteOnUnmutatedLines() throws IOException { + String report = + runRecording(null, mutation("SURVIVED", "A", "A.java", 1, "removed call", "T.p")) + .render(DiffCoverageReport.Limits.NONE, List.of()); + assertTrue( + report.endsWith("PIT generates no mutant on a line that calls a logging library."), + report); + } + + @Test + void aRunWithNoMutantCountsTheChangedLinesWithBytecode() throws IOException { + assertEquals( + "Mutation testing of changed lines against origin/master (abc), all tests\n" + + " no mutant: PIT generated none on the 2 changed lines\n" + + "\n" + + "PIT generates no mutant on a line that calls a logging library.", + runWithoutMutantsFile(Map.of("com/x/A.java", Set.of(1, 2))) + .render(DiffCoverageReport.Limits.NONE, List.of())); + } + + @Test + void aRunWhoseChangedLinesHaveNoBytecodeSaysSo() throws IOException { + assertEquals( + "Mutation testing of changed lines against origin/master (abc), all tests\n" + + " no mutant: no changed line has bytecode PIT may mutate", + runWithoutMutantsFile(Map.of()).render(DiffCoverageReport.Limits.NONE, List.of())); + } + } + @Test void aRunInWhichNoTestReachedAnyLineSaysWhyThatCanHappen() throws IOException { assertEquals( "Mutation testing of changed lines against origin/master (abc), all tests\n" - + " 1 mutant: 0 killed, 0 survived, 1 not reached by any test\n" + + " 1 mutant on 1 of 1 changed line: 0 killed, 0 survived, 1 not reached by any test\n" + " ordered by live mutants per file, then by line\n" + "\n" + "No test reached any of the changed lines. Either no test of this module exercises this" @@ -223,7 +358,7 @@ void aRunInWhichNoTestReachedAnyLineSaysWhyThatCanHappen() throws IOException { void theFileWithMoreLiveMutantsComesFirst() throws IOException { assertEquals( "Mutation testing of changed lines against origin/master (abc), all tests\n" - + " 3 mutants: 0 killed, 3 survived, 0 not reached by any test\n" + + " 3 mutants on 3 of 3 changed lines: 0 killed, 3 survived, 0 not reached by any test\n" + " ordered by live mutants per file, then by line\n" + "\n" + " src/com/x/B.java\n" @@ -248,7 +383,7 @@ void theFileWithMoreLiveMutantsComesFirst() throws IOException { void theTotalLineLimitEndsTheReportAfterTheLinesItAllows() throws IOException { assertEquals( "Mutation testing of changed lines against origin/master (abc), all tests\n" - + " 3 mutants: 0 killed, 3 survived, 0 not reached by any test\n" + + " 3 mutants on 3 of 3 changed lines: 0 killed, 3 survived, 0 not reached by any test\n" + " ordered by live mutants per file, then by line\n" + "\n" + " src/com/x/B.java\n" @@ -303,7 +438,7 @@ void showAllPrintsTheWholeReport() throws IOException { void theTestsNamedFirstAreTheOnesReachingTheMostLiveMutants() throws IOException { assertEquals( "Mutation testing of changed lines against origin/master (abc), all tests\n" - + " 2 mutants: 0 killed, 2 survived, 0 not reached by any test\n" + + " 2 mutants on 2 of 2 changed lines: 0 killed, 2 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" @@ -328,11 +463,80 @@ void theTestsNamedFirstAreTheOnesReachingTheMostLiveMutants() throws IOException .render(DiffCoverageReport.Limits.NONE, List.of())); } + /** + * T.p reaches two live mutants through five invocations, and U.q reaches three live mutants, so + * U.q is named first only where each invocation of T.p does not count as a test of its own. + */ + @Test + void theInvocationsOfOneTestShareARowAndCountAsOneTest() throws IOException { + assertEquals( + "Mutation testing of changed lines against origin/master (abc), all tests\n" + + " 3 mutants on 2 of 2 changed lines: 0 killed, 3 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: a1\n" + + " survived: removed call, in m\n" + + " survived: negated conditional, in m\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" + + " reached by 1 test:\n" + + " U.q\n" + + "\n" + + "Live mutants on 2 lines in 2 files." + LIVE_FOOTER, + run( + mutation( + "SURVIVED", "A", "A.java", 1, "removed call", + "T.p[33]", "T.p[2]", "T.p[10]", "T.p[1]", "U.q"), + mutation("SURVIVED", "A", "A.java", 1, "negated conditional", "T.p[3]", "U.q"), + mutation("SURVIVED", "B", "B.java", 1, "removed call", "U.q")) + .render(DiffCoverageReport.Limits.NONE, List.of())); + } + + /** A range joins the invocations of one container and stops where the container changes. */ + @Test + void consecutiveNestedInvocationsShareARange() throws IOException { + String report = + run( + mutation( + "SURVIVED", "A", "A.java", 1, "removed call", + dynamic(2, 5), dynamic(2, 6), dynamic(2, 7), dynamic(3, 1))) + .render(DiffCoverageReport.Limits.NONE, List.of()); + assertTrue(report.contains("\n FooTest.cases[2/5-7, 3/1]\n"), report); + } + + /** + * A test factory that returns a dynamic test beside a dynamic container gives one test an + * invocation at each of two levels. + */ + @Test + void invocationsAtTwoLevelsAreListedApart() throws IOException { + String report = + run( + mutation( + "SURVIVED", "A", "A.java", 1, "removed call", + dynamic(2, 1), + "com.x.FooTest.[engine:junit-jupiter]/[class:com.x.FooTest]" + + "/[test-factory:cases()]/[dynamic-test:#2]")) + .render(DiffCoverageReport.Limits.NONE, List.of()); + assertTrue(report.contains("\n FooTest.cases[2, 2/1]\n"), report); + } + + private static String dynamic(int container, int test) { + return "com.x.FooTest.[engine:junit-jupiter]/[class:com.x.FooTest]/[test-factory:cases()]" + + "/[dynamic-container:#" + container + "]/[dynamic-test:#" + test + "]"; + } + @Test void theLimitsCutLinesAndFilesAndTheReportNamesTheFullOne() throws IOException { assertEquals( "Mutation testing of changed lines against origin/master (abc), all tests\n" - + " 3 mutants: 0 killed, 3 survived, 0 not reached by any test\n" + + " 3 mutants on 3 of 3 changed lines: 0 killed, 3 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" @@ -364,7 +568,8 @@ void aRunThatWroteNoReportSaysNoMutantWasAnalyzed() throws IOException { build.resolve("mutants.tsv").toFile(), repository.toFile(), List.of(repository.toFile()), - Map.of()); + Map.of(), + null); assertEquals( "Mutation testing of changed lines against origin/master (abc), all tests\n" @@ -397,11 +602,12 @@ void aSourceFileThatIsNotUtf8LeavesTheLineUnquoted() throws IOException { mutantsFile(mutation("SURVIVED", "A", "A.java", 1, "removed call")).toFile(), repository.toFile(), List.of(sources.toFile()), + Map.of(), Map.of()); assertEquals( "Mutation testing of changed lines against origin/master (abc), all tests\n" - + " 1 mutant: 0 killed, 1 survived, 0 not reached by any test\n" + + " 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" @@ -430,51 +636,283 @@ class TestNames { void aJUnit4TestIsNamedByClassAndMethod() { assertEquals( "FooTest.bar", - PitestSurvivors.shortTestName("com.x.FooTest.bar(com.x.FooTest)")); + PitestSurvivors.shortTestName("com.x.FooTest.bar(com.x.FooTest)").toString()); } - /** The invocations of a parameterized test share one name, so they count as one test. */ + /** {@code @Parameters(name = "{0}")} puts the parameter in brackets, whatever its digits. */ @Test - void aJUnitPlatformTestIsNamedByItsClassesAndMethod() { - assertEquals( - "PgBufferedOutputStreamTest$ZeroTests.bufferFlushedOnlyWhenFull", - PitestSurvivors.shortTestName( - "org.postgresql.util.internal.PgBufferedOutputStreamTest." - + "[engine:junit-jupiter]/[class:org.postgresql.util.internal.PgBufferedOutputStreamTest]" - + "/[nested-class:ZeroTests]/[test-template:bufferFlushedOnlyWhenFull(int, int)]" - + "/[test-template-invocation:#38]")); + void aNumberInBracketsThatIsNoIndexStaysInTheName() { + PitestSurvivors.TestName name = + PitestSurvivors.shortTestName("com.x.FooTest.bar[12345678901](com.x.FooTest)"); + assertAll( + () -> assertEquals("FooTest.bar[12345678901]", name.name(), "name"), + () -> assertEquals(List.of(), name.invocation(), "invocation")); + } + + @Test + void aNumberWithALeadingZeroInBracketsStaysInTheName() { + PitestSurvivors.TestName name = + PitestSurvivors.shortTestName("com.x.FooTest.bar[007](com.x.FooTest)"); + assertAll( + () -> assertEquals("FooTest.bar[007]", name.name(), "name"), + () -> assertEquals(List.of(), name.invocation(), "invocation")); } @Test - void aJupiterTestMethodIsNamedByClassAndMethod() { + void theFirstJUnit4IndexIsZero() { assertEquals( - "FooTest.bar", - PitestSurvivors.shortTestName( - "com.x.FooTest.[engine:junit-jupiter]/[class:com.x.FooTest]/[method:bar()]")); + List.of(0), + PitestSurvivors.shortTestName("com.x.FooTest.bar[0](com.x.FooTest)").invocation()); } @Test - void aJUnitVintageTestIsNamedByRunnerClassAndMethod() { + void aTenDigitNumberInBracketsIsNoIndex() { assertEquals( - "FooTest.bar", - PitestSurvivors.shortTestName( - "com.x.FooTest.[engine:junit-vintage]/[runner:com.x.FooTest]" - + "/[test:bar(com.x.FooTest)]")); + "FooTest.bar[2147483648]", + PitestSurvivors.shortTestName("com.x.FooTest.bar[2147483648](com.x.FooTest)").toString()); } - /** Cut at dots, this id would name {@code example]/[case:first}, which is no test. */ @Test - void aJUnitPlatformIdWithNoKnownClassSegmentIsKeptWhole() { - String id = "com.x.Suite.[engine:other]/[container:com.x.example]/[case:first]"; - assertEquals(id, PitestSurvivors.shortTestName(id)); + void aNineDigitNumberInBracketsIsAnIndex() { + assertEquals( + List.of(123456789), + PitestSurvivors.shortTestName("com.x.FooTest.bar[123456789](com.x.FooTest)") + .invocation()); } @Test - void aJUnitPlatformClassLevelIdIsNamedByItsClass() { + void aJUnit4ParameterizedTestIsNamedByClassMethodAndIndex() { assertEquals( - "FooTest", - PitestSurvivors.shortTestName( - "com.x.FooTest.[engine:junit-jupiter]/[class:com.x.FooTest]")); + "FooTest.bar[3]", + PitestSurvivors.shortTestName("com.x.FooTest.bar[3](com.x.FooTest)").toString()); + } + + /** + * {@code @Parameters(name = "{index}: fib({0})")} puts parentheses and a dot in the brackets, so + * the method name ends at the parenthesis that opens the class name. + */ + @Test + void aJUnit4NameWithParenthesesAndADotKeepsThemInTheName() { + PitestSurvivors.TestName name = + PitestSurvivors.shortTestName("com.x.FibTest.test[0: fib(1.5)](com.x.FibTest)"); + assertAll( + () -> assertEquals("FibTest.test[0: fib(1.5)]", name.name(), "name"), + () -> assertEquals(List.of(), name.invocation(), "invocation")); + } + + @Test + void aNameThatEndsInAnOpenParenthesisIsCutThere() { + assertEquals("FooTest.bar", PitestSurvivors.shortTestName("com.x.FooTest.bar(").toString()); + } + + @Test + void aNameWithNoParenthesisIsNamedByClassAndMethod() { + assertEquals("FooTest.bar", PitestSurvivors.shortTestName("com.x.FooTest.bar").toString()); + } + + static Stream platformIds() { + return Stream.of( + argumentSet( + "Jupiter method", + "com.x.FooTest.[engine:junit-jupiter]/[class:com.x.FooTest]/[method:bar()]", + "FooTest.bar", + List.of()), + argumentSet( + "Jupiter class", + "com.x.FooTest.[engine:junit-jupiter]/[class:com.x.FooTest]", + "FooTest", + List.of()), + argumentSet( + "Jupiter method with an array parameter", + "com.x.FooTest.[engine:junit-jupiter]/[class:com.x.FooTest]" + + "/[method:bar(java.lang.String%5B%5D)]", + "FooTest.bar", + List.of()), + argumentSet( + "Jupiter test template in a nested class", + "org.postgresql.util.internal.PgBufferedOutputStreamTest." + + "[engine:junit-jupiter]/[class:org.postgresql.util.internal.PgBufferedOutputStreamTest]" + + "/[nested-class:ZeroTests]/[test-template:bufferFlushedOnlyWhenFull(int, int)]" + + "/[test-template-invocation:#38]", + "PgBufferedOutputStreamTest$ZeroTests.bufferFlushedOnlyWhenFull", + List.of(38)), + argumentSet( + "Jupiter method of a nested class inherited from another class", + "com.x.FooTest.[engine:junit-jupiter]/[class:com.x.FooTest]" + + "/[fq-nested-class:com.x.Base$Inner]/[method:bar()]", + "Base$Inner.bar", + List.of()), + argumentSet( + "Jupiter dynamic test in a dynamic container", + "com.x.FooTest.[engine:junit-jupiter]/[class:com.x.FooTest]" + + "/[test-factory:cases()]/[dynamic-container:#2]/[dynamic-test:#5]", + "FooTest.cases", + List.of(2, 5)), + argumentSet( + "Jupiter dynamic test whose index does not fit an int", + "com.x.FooTest.[engine:junit-jupiter]/[class:com.x.FooTest]" + + "/[test-factory:cases()]/[dynamic-test:#12345678901]", + "FooTest.cases", + List.of()), + argumentSet( + "Jupiter method of a class template", + "com.x.FooTest.[engine:junit-jupiter]/[class-template:com.x.FooTest]" + + "/[class-template-invocation:#2]/[method:bar()]", + "FooTest.bar", + List.of(2)), + argumentSet( + "Jupiter test template of a class template", + "com.x.FooTest.[engine:junit-jupiter]/[class-template:com.x.FooTest]" + + "/[class-template-invocation:#2]/[test-template:bar(int)]" + + "/[test-template-invocation:#3]", + "FooTest.bar", + List.of(2, 3)), + argumentSet( + "Jupiter method of a nested class template", + "com.x.Outer.[engine:junit-jupiter]/[class:com.x.Outer]" + + "/[nested-class-template:Inner]/[class-template-invocation:#1]/[method:bar()]", + "Outer$Inner.bar", + List.of(1)), + argumentSet( + "Jupiter method of a nested class template inherited from another class", + "com.x.Outer.[engine:junit-jupiter]/[class:com.x.Outer]" + + "/[fq-nested-class-template:com.x.Base$Inner]/[class-template-invocation:#1]" + + "/[method:bar()]", + "Base$Inner.bar", + List.of(1)), + argumentSet( + "Jupiter method of a nested class inherited from another class, in a class template", + "com.x.Sub.[engine:junit-jupiter]/[class-template:com.x.Sub]" + + "/[class-template-invocation:#2]/[fq-nested-class:com.x.Base$Inner]/[method:m()]", + "Base$Inner.m", + List.of(2)), + argumentSet( + "Jupiter method of a nested class template inherited from another class, in a class" + + " template", + "com.x.Sub.[engine:junit-jupiter]/[class-template:com.x.Sub]" + + "/[class-template-invocation:#2]/[fq-nested-class-template:com.x.Base$Inner]" + + "/[class-template-invocation:#1]/[method:m()]", + "Base$Inner.m", + List.of(2, 1)), + argumentSet( + "Spock feature", + "com.x.FooSpec.[engine:spock]/[spec:com.x.FooSpec]/[feature:$spock_feature_0_1]", + "FooSpec.$spock_feature_0_1", + List.of()), + argumentSet( + "Spock iteration of a data-driven feature", + "com.x.FooSpec.[engine:spock]/[spec:com.x.FooSpec]/[feature:$spock_feature_0_1]" + + "/[iteration:2]", + "FooSpec.$spock_feature_0_1", + List.of(2)), + argumentSet( + "Kotest test whose name is a number", + "com.x.HttpSpec.[engine:kotest]/[spec:com.x.HttpSpec]/[test:404]", + "HttpSpec.404", + List.of()), + argumentSet( + "Kotest test named by a number inside a named test", + "com.x.HttpSpec.[engine:kotest]/[spec:com.x.HttpSpec]/[test:status]/[test:5]", + "HttpSpec.status", + List.of(5)), + argumentSet( + "Kotest test named by a number with a leading zero inside a named test", + "com.x.HttpSpec.[engine:kotest]/[spec:com.x.HttpSpec]/[test:status]/[test:007]", + "HttpSpec.007", + List.of()), + argumentSet( + "Kotest sibling of the test named 007", + "com.x.HttpSpec.[engine:kotest]/[spec:com.x.HttpSpec]/[test:status]/[test:008]", + "HttpSpec.008", + List.of()), + argumentSet( + "Kotest test nested in a named test", + "com.x.HttpSpec.[engine:kotest]/[spec:com.x.HttpSpec]/[test:a]/[test:works]", + "HttpSpec.works", + List.of()), + argumentSet( + "Kotest test named # and a number", + "com.x.HttpSpec.[engine:kotest]/[spec:com.x.HttpSpec]/[test:#1]", + "HttpSpec", + List.of(1)), + argumentSet( + "Kotest test named # and a number with a leading zero, inside a named test", + "com.x.HttpSpec.[engine:kotest]/[spec:com.x.HttpSpec]/[test:status]/[test:#007]", + "HttpSpec.status", + List.of()), + argumentSet( + "Kotest test named by a ten-digit number inside a named test", + "com.x.HttpSpec.[engine:kotest]/[spec:com.x.HttpSpec]/[test:status]" + + "/[test:1234567890]", + "HttpSpec.1234567890", + List.of()), + argumentSet( + "Spock first iteration of a data-driven feature", + "com.x.FooSpec.[engine:spock]/[spec:com.x.FooSpec]/[feature:$spock_feature_0_1]" + + "/[iteration:0]", + "FooSpec.$spock_feature_0_1", + List.of(0)), + argumentSet( + "Jupiter method whose name holds a percent sign that starts no escape", + "com.x.FooTest.[engine:junit-jupiter]/[class:com.x.FooTest]/[method:bar%zz()]", + "FooTest.bar%zz", + List.of()), + argumentSet( + "jqwik property", + "com.x.FooTest.[engine:jqwik]/[class:com.x.FooTest]/[property:prop()]", + "FooTest.prop", + List.of()), + argumentSet( + "Vintage method", + "com.x.FooTest.[engine:junit-vintage]/[runner:com.x.FooTest]" + + "/[test:bar(com.x.FooTest)]", + "FooTest.bar", + List.of()), + argumentSet( + "Vintage method of a class in a suite", + "com.x.AllTests.[engine:junit-vintage]/[runner:com.x.AllTests]" + + "/[runner:com.x.FooTest]/[test:bar(com.x.FooTest)]", + "FooTest.bar", + List.of()), + argumentSet( + "Vintage parameterized method", + "com.x.FooTest.[engine:junit-vintage]/[runner:com.x.FooTest]" + + "/[test:%5B0%5D]/[test:bar%5B0%5D(com.x.FooTest)]", + "FooTest.bar", + List.of(0)), + argumentSet( + "Vintage parameterized method with a named invocation", + "com.x.FooTest.[engine:junit-vintage]/[runner:com.x.FooTest]" + + "/[test:%5Bfirst%5D]/[test:bar%5Bfirst%5D(com.x.FooTest)]", + "FooTest.bar[first]", + List.of()), + argumentSet( + "Vintage parameterized method with a slash and a percent sign in its invocation", + "com.x.FooTest.[engine:junit-vintage]/[runner:com.x.FooTest]" + + "/[test:%5Ba%2Fb%25%5D]/[test:bar%5Ba%2Fb%25%5D(com.x.FooTest)]", + "FooTest.bar[a/b%]", + List.of()), + argumentSet( + "Vintage parameterized method whose invocation name holds parentheses", + "com.x.FibTest.[engine:junit-vintage]/[runner:com.x.FibTest]" + + "/[test:%5B0%3A fib%281%29%5D]/[test:test%5B0%3A fib%281%29%5D(com.x.FibTest)]", + "FibTest.test[0: fib(1)]", + List.of()), + argumentSet( + "an engine with no class segment", + "com.x.Suite.[engine:other]/[container:com.x.example]/[case:first]", + "com.x.Suite.[engine:other]/[container:com.x.example]/[case:first]", + List.of())); + } + + @ParameterizedTest + @MethodSource("platformIds") + void aJUnitPlatformIdIsNamedByItsClassesAndMethodAndListsItsInvocation( + String id, String name, List invocation) { + PitestSurvivors.TestName actual = PitestSurvivors.shortTestName(id); + assertAll( + () -> assertEquals(name, actual.name(), "name"), + () -> assertEquals(invocation, actual.invocation(), "invocation")); } } } diff --git a/cribro-core/src/test/java/io/github/cribrodev/SourceFileKeyTest.java b/cribro-core/src/test/java/io/github/cribrodev/SourceFileKeyTest.java index 7f74091..f6ead16 100644 --- a/cribro-core/src/test/java/io/github/cribrodev/SourceFileKeyTest.java +++ b/cribro-core/src/test/java/io/github/cribrodev/SourceFileKeyTest.java @@ -97,6 +97,18 @@ static Stream preambles() { "a raw string argument that ends in a quote", "@file:JvmName(\"\"\"a\"\"\"\")\npackage demo\n", true), + argumentSet( + "a raw string argument that starts with a quote", + "@file:JvmName(\"\"\"\"x\"\"\")\npackage demo\n", + true), + argumentSet( + "a backslash before the closing quotes of a raw string argument", + "@file:JvmName(\"\"\"C:\\\"\"\")\npackage demo\n", + true), + argumentSet( + "a dollar sign and a brace in a Java string argument", + "@Deprecated(since = \"${\" + \")\")\npackage demo;\n", + false), argumentSet( "a bracket in a block comment in Kotlin arguments", "@file:Suppress(/* ) */ \"X\")\npackage demo\n", @@ -119,7 +131,128 @@ static Stream preambles() { argumentSet( "nested brackets in the arguments", "@file:Suppress(names = [(\"a\")])\npackage demo\n", - true)); + true), + argumentSet( + "spaces around a dot in a Kotlin annotation name", + "@file:kotlin . jvm.JvmName(\"U\")\npackage demo\nfun f() = 1\n", + true), + argumentSet( + "spaces around a dot in a Java annotation name", + "@java.lang . Deprecated\npackage demo;\n", + false), + argumentSet( + "comments around a dot in an annotation name", + "@java/* a */./* b */lang.Deprecated\npackage demo;\n", + false), + argumentSet( + "a backticked annotation name", "@file:`Suppress`(\"x\")\npackage demo\n", true), + argumentSet( + "a supplementary letter in an annotation name", + "@Ann\uD835\uDC65\npackage demo;\n", + false), + argumentSet( + "spaced qualified names in an annotation list", + "@file : [kotlin /* c */ . jvm . JvmMultifileClass Suppress(\"y\")]\npackage demo\n", + true), + argumentSet( + "an escaped quote run in a text block argument", + "@Deprecated(since = \"\"\"\n a\\\"\"\"b\"\"\")\npackage demo;\n", + false), + argumentSet( + "an escaped backslash that ends a text block argument", + "@Deprecated(since = \"\"\"\n a\\\\\"\"\")\npackage demo;\n", + false), + argumentSet( + "a quote in a character argument", + "@Deprecated(since = \"\" + '\"' + \")\")\npackage demo;\n", + false), + argumentSet( + "an escaped apostrophe in a character argument", + "@Deprecated(since = \"\" + '\\'' + \")\")\npackage demo;\n", + false), + argumentSet( + "a string template holding a brace in a string", + "@file:Suppress(\"${\"}\"}\")\npackage demo\n", + true), + argumentSet( + "a string template holding a bracket in a string", + "@file:Suppress(\"${\")\"}\")\npackage demo\n", + true), + argumentSet( + "a string template holding a quote in a character", + "@file:Suppress(\"${'\"'}\")\npackage demo\n", + true), + argumentSet( + "a string template holding a nested comment with a brace and a quote", + "@file:Suppress(\"${/* /* } */ \" */ 1}\")\npackage demo\n", + true), + argumentSet( + "a raw string template holding a raw string", + "@file:Suppress(\"\"\"${\"\"\")\"\"\"}\"\"\")\npackage demo\n", + true), + argumentSet( + "a string template after two dollar signs", + "@file:Suppress(\"$${\")\"}\")\npackage demo\n", + true), + argumentSet( + "an escaped dollar sign before a brace", + "@file:Suppress(\"\\${)\")\npackage demo\n", + true), + argumentSet( + "a dollar sign and a brace in a two-dollar string", + "@file:Suppress($$\"${)\")\npackage demo\n", + true), + argumentSet( + "a string template in a two-dollar string", + "@file:Suppress($$\"$$${\")\"}\")\npackage demo\n", + true), + argumentSet( + "a Unicode escape for the at sign", "\\u0040Deprecated\npackage demo;\n", false), + argumentSet( + "Unicode escapes in the keyword and the name", + "\\u0070ackage d\\uuu0065mo;\n", + false), + argumentSet( + "a Unicode escape that ends a block comment", "/* \\u002a/\npackage demo;\n", false), + argumentSet( + "a Unicode escape after two backslashes that ends a block comment", + "/* \\\\\\u002a/ package demo; */\npackage not.this;\n", + false), + argumentSet( + "hexadecimal digits after a backslash with no u in a block comment", + "/* C:\\002a/ */\npackage demo;\n", + false), + argumentSet( + "a backslash and u with no hexadecimal digits in a line comment", + "// \\uzzzz\npackage demo;\n", + false), + argumentSet("a Unicode escape that ends the text", "package dem\\u006f", false), + argumentSet( + "a backslash and u that end the text", "package demo;\n// \\u", false), + argumentSet( + "type arguments in a Kotlin annotation", + "@file:Foo Unit>(\"x\")\npackage demo\n", + true), + argumentSet( + "nested type arguments in a Kotlin annotation", + "@file:Foo>(\"x\")\npackage demo\n", + true), + argumentSet( + "a block comment holding a bracket in type arguments", + "@file:Foo */>(\"x\")\npackage demo\n", + true), + argumentSet( + "a line comment holding a bracket in type arguments", + "@file:Foo\n>(\"x\")\npackage demo\n", + true), + argumentSet( + "a bracket in a backticked argument", "@file:JvmName(`c)d`)\npackage demo\n", true), + argumentSet( + "a quote in a backticked argument", "@file:JvmName(`a\"b`)\npackage demo\n", true), + argumentSet( + "an escaped backslash before u in a block comment", + "/* \\\\u002a/ package not.this; */\npackage demo;\n", + false)); } @ParameterizedTest @@ -149,7 +282,9 @@ static Stream names() { "an annotated declaration after the name", "package demo\n@Ann(\"${\"(\"}\")\nclass A\n", "demo"), - argumentSet("an identifier with digits and underscores", "package a_1.b2;\n", "a_1.b2")); + argumentSet("an identifier with digits and underscores", "package a_1.b2;\n", "a_1.b2"), + argumentSet( + "a supplementary letter in a segment", "package d\uD835\uDC65;\n", "d\uD835\uDC65")); } @ParameterizedTest @@ -189,6 +324,14 @@ static Stream unreadableTexts() { argumentSet("an unterminated string argument", "@file:JvmName(\"X)\npackage demo\n"), argumentSet( "an unterminated raw string argument", "@file:JvmName(\"\"\"X\"Y)\npackage demo\n"), + argumentSet( + "a raw string argument that ends the text", "@file:JvmName(\"\"\"a\"\"\""), + argumentSet( + "an unterminated string template", "@file:Suppress(\"${\")\npackage demo\n"), + argumentSet( + "an unterminated backticked argument", "@file:JvmName(`c)\npackage demo\n"), + argumentSet( + "unterminated type arguments", "@file:Foo unicodeEscapes() { + return Stream.of(argumentSet("Java", false, "x"), argumentSet("Kotlin", true, "y")); + } + + @ParameterizedTest + @MethodSource("unicodeEscapes") + void aUnicodeEscapeIsReadAsTheCharacterItStandsForOnlyInJava(boolean kotlin, String expected) { + String text = "// \\u000a package x;\npackage y;\n"; + assertEquals( + expected, SourceFileKey.declaredPackage(text, kotlin), declaredPackageOf(text, kotlin)); + } + static Stream shebangLine() { return Stream.of(argumentSet("Java", false, null), argumentSet("Kotlin", true, "demo")); } diff --git a/cribro-core/src/test/java/io/github/cribrodev/SourceLinesTest.java b/cribro-core/src/test/java/io/github/cribrodev/SourceLinesTest.java index 8cc6fce..3196eaf 100644 --- a/cribro-core/src/test/java/io/github/cribrodev/SourceLinesTest.java +++ b/cribro-core/src/test/java/io/github/cribrodev/SourceLinesTest.java @@ -15,10 +15,12 @@ */ package io.github.cribrodev; +import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.File; import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import org.junit.jupiter.api.Assumptions; @@ -86,6 +88,23 @@ void aFileThisJvmCannotDecodeHasNoText() throws IOException { assertEquals("", workingTree().get(PATH, 1)); } + @Test + void theLenientTextOfAFileThatIsNotUtf8KeepsItsAsciiCharacters() throws IOException { + Path file = directory.resolve(PATH); + Files.createDirectories(file.getParent()); + Files.write(file, "class A {\n} // \u00a9\n".getBytes(StandardCharsets.ISO_8859_1)); + SourceLines sources = workingTree(); + assertAll( + () -> assertEquals("} // \ufffd", sources.lenient(PATH, 2), "lenient(PATH, 2)"), + () -> assertEquals("", sources.get(PATH, 2), "get(PATH, 2)")); + } + + @Test + void theLenientTextOfAUtf8FileIsTheLineAsItIs() throws IOException { + write("class A {", "} // \u00a9"); + assertEquals("} // \u00a9", workingTree().lenient(PATH, 2)); + } + /** * A report quotes many lines of the same file, and each read of a source file competes with the * test run that produced the report for the same disk. diff --git a/cribro-core/src/test/java/io/github/cribrodev/pitest/ChangedLinesFilterTest.java b/cribro-core/src/test/java/io/github/cribrodev/pitest/ChangedLinesFilterTest.java index eab3de4..a1ac53e 100644 --- a/cribro-core/src/test/java/io/github/cribrodev/pitest/ChangedLinesFilterTest.java +++ b/cribro-core/src/test/java/io/github/cribrodev/pitest/ChangedLinesFilterTest.java @@ -20,6 +20,12 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import io.github.cribrodev.ChangedLinesFile; +import io.github.cribrodev.SourceLines; +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.ArrayList; import java.util.List; @@ -27,7 +33,16 @@ import java.util.NavigableSet; import java.util.ServiceLoader; import java.util.TreeSet; +import java.util.stream.Stream; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.InsnNode; +import org.objectweb.asm.tree.LabelNode; +import org.objectweb.asm.tree.LineNumberNode; +import org.objectweb.asm.tree.MethodNode; +import org.pitest.bytecode.analysis.ClassTree; import org.pitest.classinfo.ClassName; import org.pitest.mutationtest.build.InterceptorType; import org.pitest.mutationtest.build.MutationInterceptorFactory; @@ -43,7 +58,10 @@ class ChangedLinesFilterTest { private static final ChangedLinesFilter FILTER = new ChangedLinesFilter( - Map.of("com/x/A.java", lines(10, 11), "B.java", lines(5))); + Map.of("com/x/A.java", lines(10, 11), "B.java", lines(5)), + Map.of("com/x/A.java", "src/com/x/A.java", "B.java", "src/B.java"), + SourceLines.under(new File("unused")), + Path.of("unused")); private static NavigableSet lines(Integer... numbers) { return new TreeSet<>(List.of(numbers)); @@ -98,21 +116,226 @@ void pitFindsTheFactoryThroughServiceLoader() { () -> "registered factories: " + factories); } + @Test + void theFactoryRefusesToStartWithoutTheRepository() { + String changedLines = System.setProperty(ChangedLinesFile.PITEST_PROPERTY, "changed-lines.txt"); + String repository = System.clearProperty(ChangedLinesFile.REPOSITORY_PROPERTY); + try { + IllegalStateException e = + assertThrows( + IllegalStateException.class, + () -> new ChangedLinesFilterFactory().createInterceptor(null)); + assertTrue( + e.getMessage().contains(ChangedLinesFile.REPOSITORY_PROPERTY), + () -> "the message must name the missing property: " + e.getMessage()); + } finally { + restore(ChangedLinesFile.PITEST_PROPERTY, changedLines); + restore(ChangedLinesFile.REPOSITORY_PROPERTY, repository); + } + } + /** Without the file, the factory would have no lines to keep, and PIT would mutate every line. */ @Test - void theFactoryRefusesToStartWithoutTheChangedLinesFile() { - String previous = System.clearProperty(ChangedLinesFile.PITEST_PROPERTY); + void theFactoryRefusesToStartWithoutTheChangedLinesFile(@TempDir Path dir) { + String changedLines = System.clearProperty(ChangedLinesFile.PITEST_PROPERTY); + String repository = + System.setProperty(ChangedLinesFile.REPOSITORY_PROPERTY, dir.toString()); try { - assertThrows( - IllegalStateException.class, - () -> new ChangedLinesFilterFactory().createInterceptor(null)); + IllegalStateException e = + assertThrows( + IllegalStateException.class, + () -> new ChangedLinesFilterFactory().createInterceptor(null)); + assertTrue( + e.getMessage().contains(ChangedLinesFile.PITEST_PROPERTY), + () -> "the message must name the missing property: " + e.getMessage()); } finally { - if (previous != null) { - System.setProperty(ChangedLinesFile.PITEST_PROPERTY, previous); - } + restore(ChangedLinesFile.PITEST_PROPERTY, changedLines); + restore(ChangedLinesFile.REPOSITORY_PROPERTY, repository); } } + private static void restore(String property, String value) { + if (value == null) { + System.clearProperty(property); + } else { + System.setProperty(property, value); + } + } + + /** Returns a class compiled from the given file, with the given methods. */ + private static ClassTree compiled(String name, String sourceFile, MethodNode... methods) { + ClassNode node = new ClassNode(); + node.name = name; + node.sourceFile = sourceFile; + node.methods.addAll(List.of(methods)); + return new ClassTree(node); + } + + /** Returns a method whose line table records the given lines. */ + private static MethodNode method(String name, int access, Integer... lines) { + MethodNode method = new MethodNode(access, name, "()V", null, null); + for (int line : lines) { + LabelNode label = new LabelNode(); + method.instructions.add(label); + method.instructions.add(new LineNumberNode(line, label)); + method.instructions.add(new InsnNode(Opcodes.NOP)); + } + return method; + } + + @Test + void theLinesWithBytecodeAreTheChangedLinesTheCompilerDidNotGenerate(@TempDir Path dir) + throws IOException { + Path withBytecode = dir.resolve("changed-lines-with-bytecode.txt"); + new ChangedLinesFilter( + Map.of("com/x/A.java", lines(10, 12, 13, 14, 15)), + Map.of("com/x/A.java", "src/com/x/A.java"), + SourceLines.under(dir.toFile()), + withBytecode) + .writeLinesWithBytecode( + Stream.of( + compiled( + "com/x/A", + "A.java", + method("m", Opcodes.ACC_PUBLIC, 10, 11), + method("m", Opcodes.ACC_BRIDGE | Opcodes.ACC_SYNTHETIC, 12), + method("access$000", Opcodes.ACC_STATIC | Opcodes.ACC_SYNTHETIC, 13)), + compiled( + "com/x/A$Inner", + "A.java", + method("lambda$m$0", Opcodes.ACC_PRIVATE | Opcodes.ACC_SYNTHETIC, 14)), + compiled("com/y/A", "A.java", method("m", Opcodes.ACC_PUBLIC, 15)))); + + assertEquals( + Map.of("com/x/A.java", lines(10, 14)), + ChangedLinesFile.read(withBytecode), + "lines with bytecode"); + assertEquals( + Map.of("com/x/A.java", "src/com/x/A.java"), ChangedLinesFile.readPaths(withBytecode)); + } + + @Test + void aClassInTheDefaultPackageRecordsItsLinesUnderItsFileName(@TempDir Path dir) + throws IOException { + Path withBytecode = dir.resolve("changed-lines-with-bytecode.txt"); + new ChangedLinesFilter( + Map.of("B.java", lines(5)), + Map.of("B.java", "src/B.java"), + SourceLines.under(dir.toFile()), + withBytecode) + .writeLinesWithBytecode( + Stream.of(compiled("B", "B.java", method("m", Opcodes.ACC_PUBLIC, 5)))); + + assertEquals(Map.of("B.java", lines(5)), ChangedLinesFile.read(withBytecode)); + } + + /** Writes a file under the directory and returns the directory. */ + private static Path write(Path dir, String path, String text) throws IOException { + Path file = dir.resolve(path); + Files.createDirectories(file.getParent()); + Files.writeString(file, text); + return dir; + } + + @Test + void aLineOfBracesAndElseIsLeftOutUnlessItStartsAMethod(@TempDir Path dir) throws IOException { + write( + dir, + "lib/src/main/java/com/x/A.java", + """ + package com.x; + class A { + void f(boolean b) { + if (b) { + x(); + } else { + y(); + } + } + void g() { + } + } + """); + Path withBytecode = dir.resolve("changed-lines-with-bytecode.txt"); + new ChangedLinesFilter( + Map.of("com/x/A.java", lines(4, 5, 6, 7, 8, 9, 10, 11)), + Map.of("com/x/A.java", "lib/src/main/java/com/x/A.java"), + SourceLines.under(dir.toFile()), + withBytecode) + .writeLinesWithBytecode( + Stream.of( + compiled( + "com/x/A", + "A.java", + method("f", Opcodes.ACC_PUBLIC, 4, 5, 6, 7, 9), + method("g", Opcodes.ACC_PUBLIC, 11)))); + + assertEquals(Map.of("com/x/A.java", lines(4, 5, 7, 11)), ChangedLinesFile.read(withBytecode)); + } + + @Test + void aBraceLineOfAFileThatIsNotUtf8IsLeftOut(@TempDir Path dir) throws IOException { + Path file = dir.resolve("src/com/x/A.java"); + Files.createDirectories(file.getParent()); + Files.write( + file, + ("// \u00a9 2020 Acme\n" + + "package com.x;\n" + + "class A {\n" + + " void f(boolean b) {\n" + + " if (b) {\n" + + " x();\n" + + " }\n" + + " }\n" + + "}\n") + .getBytes(StandardCharsets.ISO_8859_1)); + Path withBytecode = dir.resolve("changed-lines-with-bytecode.txt"); + new ChangedLinesFilter( + Map.of("com/x/A.java", lines(5, 6, 7)), + Map.of("com/x/A.java", "src/com/x/A.java"), + SourceLines.under(dir.toFile()), + withBytecode) + .writeLinesWithBytecode( + Stream.of(compiled("com/x/A", "A.java", method("f", Opcodes.ACC_PUBLIC, 5, 6, 7)))); + + assertEquals(Map.of("com/x/A.java", lines(5, 6)), ChangedLinesFile.read(withBytecode)); + } + + /** + * The directory {@code other} holds a file of the same name and package whose line 4 holds code, + * so reading it would keep line 4. + */ + @Test + void theTextIsReadFromTheFileTheChangedLinesFileNames(@TempDir Path dir) throws IOException { + write(dir, "other/src/main/kotlin/A.kt", "package com.x\nfun f() {\n x()\n y()\n"); + write(dir, "lib/src/main/kotlin/A.kt", "package com.x\nfun f() {\n x()\n}\n"); + Path withBytecode = dir.resolve("changed-lines-with-bytecode.txt"); + new ChangedLinesFilter( + Map.of("com/x/A.kt", lines(3, 4)), + Map.of("com/x/A.kt", "lib/src/main/kotlin/A.kt"), + SourceLines.under(dir.toFile()), + withBytecode) + .writeLinesWithBytecode( + Stream.of(compiled("com/x/AKt", "A.kt", method("f", Opcodes.ACC_PUBLIC, 3, 4)))); + + assertEquals(Map.of("com/x/A.kt", lines(3)), ChangedLinesFile.read(withBytecode)); + } + + @Test + void aChangedFileWithNoLineWithBytecodeLeavesTheFileEmpty(@TempDir Path dir) + throws IOException { + Path withBytecode = dir.resolve("changed-lines-with-bytecode.txt"); + new ChangedLinesFilter( + Map.of("com/x/A.java", lines(3)), + Map.of("com/x/A.java", "src/com/x/A.java"), + SourceLines.under(dir.toFile()), + withBytecode) + .writeLinesWithBytecode( + Stream.of(compiled("com/x/A", "A.java", method("m", Opcodes.ACC_PUBLIC, 4)))); + + assertEquals(Map.of(), ChangedLinesFile.read(withBytecode)); + } + @Test void aNestedClassIsMatchedThroughTheFileItRecords() { assertEquals(List.of(10), kept("com.x.A$Inner", "A.java", 10)); diff --git a/cribro-gradle-plugin/src/main/java/io/github/cribrodev/CribroGuideTask.java b/cribro-gradle-plugin/src/main/java/io/github/cribrodev/CribroGuideTask.java index 23b0691..9f3104c 100644 --- a/cribro-gradle-plugin/src/main/java/io/github/cribrodev/CribroGuideTask.java +++ b/cribro-gradle-plugin/src/main/java/io/github/cribrodev/CribroGuideTask.java @@ -65,9 +65,15 @@ void print() { getVersion().get(), getGradleCommand().get(), getProjectPaths().get(), - Map.of( - "pitestVersion", CribroPlugin.pitestVersion(), - "jacocoVersion", CribroPlugin.JACOCO_VERSION))); + values())); + } + + /** Returns the value of each {@code {{name}}} in the guide other than {@code {{gradlew}}}. */ + static Map values() { + return Map.of( + "pitestVersion", CribroPlugin.pitestVersion(), + "pitestMutators", PitestRun.DEFAULT_MUTATORS, + "jacocoVersion", CribroPlugin.JACOCO_VERSION); } /** diff --git a/cribro-gradle-plugin/src/main/java/io/github/cribrodev/CribroPlugin.java b/cribro-gradle-plugin/src/main/java/io/github/cribrodev/CribroPlugin.java index fc4f36e..4b96232 100644 --- a/cribro-gradle-plugin/src/main/java/io/github/cribrodev/CribroPlugin.java +++ b/cribro-gradle-plugin/src/main/java/io/github/cribrodev/CribroPlugin.java @@ -47,6 +47,7 @@ import org.gradle.testing.jacoco.plugins.JacocoPluginExtension; import org.gradle.testing.jacoco.plugins.JacocoTaskExtension; import org.gradle.testing.jacoco.tasks.JacocoReport; +import org.gradle.util.GradleVersion; /** * Adds {@code diffCoverage}, {@code changedLines}, and {@code pitestDiff} to every project that @@ -251,9 +252,19 @@ private static Runnable configure(Project project) { project.getExtensions().getByType(JacocoPluginExtension.class); // The JaCoCo that Gradle bundles lags behind the JDKs that tests run on, so a build that // names no version of its own gets one that reads current class files. + String bundled = bundledJacocoVersion(JacocoPlugin.class); if (jacocoVersion != null) { jacoco.setToolVersion(jacocoVersion); - } else if (JacocoPlugin.DEFAULT_JACOCO_VERSION.equals(jacoco.getToolVersion()) + } else if (bundled == null) { + project + .getLogger() + .info( + "cribro left the JaCoCo version at {}, since Gradle {} has no public" + + " JacocoPlugin.DEFAULT_JACOCO_VERSION to tell its default from a version" + + " the build chose; set cribro.jacocoVersion to choose one", + jacoco.getToolVersion(), + GradleVersion.current().getVersion()); + } else if (bundled.equals(jacoco.getToolVersion()) && compareVersions(jacoco.getToolVersion(), JACOCO_VERSION) < 0) { jacoco.setToolVersion(JACOCO_VERSION); } @@ -357,7 +368,7 @@ && compareVersions(jacoco.getToolVersion(), JACOCO_VERSION) < 0) { providers.provider( () -> PitestJvmArgs.of(t.getJvmArgs(), t.getSystemProperties(), t.getMaxHeapSize())); task.getTestJvmArgs().set(jvmArgs.map(PitestJvmArgs::value)); - task.getLeftOutJvmArgs().set(jvmArgs.map(PitestJvmArgs::leftOut)); + task.getLeftOutJvmArgs().set(jvmArgs.map(PitestJvmArgs::leftOutByReason)); // PIT runs the tests on the JVM the `test` task runs them on. task.getJavaLauncher().set(t.getJavaLauncher()); task.getPitestClasspath().from(pitest); @@ -380,7 +391,11 @@ && compareVersions(jacoco.getToolVersion(), JACOCO_VERSION) < 0) { .set(project.getLayout().getBuildDirectory().dir("reports/pitest-diff")); task.getRepositoryRoot().set(repositoryRoot); task.getTargetTests().set(providers.gradleProperty("cribro.pitestTargetTests")); - task.getMutators().set(providers.gradleProperty("cribro.pitestMutators").orElse("DEFAULTS")); + task.getMutators() + .set( + providers + .gradleProperty("cribro.pitestMutators") + .orElse(PitestRun.DEFAULT_MUTATORS)); task.getThreads() .set( intProperty( @@ -449,6 +464,24 @@ private static File pluginJar() { } } + /** + * Returns the JaCoCo version that the Gradle running this build bundles, or null where {@code + * jacocoPlugin} has no public {@code DEFAULT_JACOCO_VERSION} field. + * + *

{@link JacocoPlugin#DEFAULT_JACOCO_VERSION} is a compile-time constant, so javac replaces a + * direct reference to it with the value from the Gradle that compiles cribro. The field is read + * reflectively so that the value comes from the Gradle that runs the build. + * + * @param jacocoPlugin {@link JacocoPlugin}, or another class in a test + */ + static String bundledJacocoVersion(Class jacocoPlugin) { + try { + return (String) jacocoPlugin.getField("DEFAULT_JACOCO_VERSION").get(null); + } catch (ReflectiveOperationException e) { + return null; + } + } + /** Compares dotted numeric versions; a non-numeric part, as in a snapshot, counts as 0. */ static int compareVersions(String a, String b) { String[] left = a.split("[.-]"); diff --git a/cribro-gradle-plugin/src/main/java/io/github/cribrodev/PitestDiffTask.java b/cribro-gradle-plugin/src/main/java/io/github/cribrodev/PitestDiffTask.java index e3536e4..80628b1 100644 --- a/cribro-gradle-plugin/src/main/java/io/github/cribrodev/PitestDiffTask.java +++ b/cribro-gradle-plugin/src/main/java/io/github/cribrodev/PitestDiffTask.java @@ -30,7 +30,7 @@ import org.gradle.api.file.DirectoryProperty; import org.gradle.api.file.FileSystemOperations; import org.gradle.api.file.RegularFileProperty; -import org.gradle.api.provider.ListProperty; +import org.gradle.api.provider.MapProperty; import org.gradle.api.provider.Property; import org.gradle.api.tasks.Classpath; import org.gradle.api.tasks.Input; @@ -90,9 +90,12 @@ public abstract class PitestDiffTask extends DefaultTask { @Input public abstract Property getTestJvmArgs(); - /** The test task's JVM arguments that PIT cannot pass, which the console output names. */ + /** + * The test task's JVM arguments that PIT cannot pass, keyed by why, which the console output + * names. + */ @Input - public abstract ListProperty getLeftOutJvmArgs(); + public abstract MapProperty> getLeftOutJvmArgs(); /** A PIT glob for the tests allowed to kill a mutant; unset, every test is. */ @Input @@ -131,7 +134,10 @@ public abstract class PitestDiffTask extends DefaultTask { @OutputDirectory public abstract DirectoryProperty getReportDir(); - /** The directory the printed paths are relative to. */ + /** + * The directory the printed paths are relative to, and the one PIT's filter reads the changed + * files under. + */ @Internal public abstract DirectoryProperty getRepositoryRoot(); @@ -170,6 +176,7 @@ public void run() throws IOException { .threads(getThreads().get()) .timeoutConst(getTimeoutConst().get()) .changedLines(changedLines.toFile()) + .repository(getRepositoryRoot().get().getAsFile()) // javac compiles in the Gradle JVM's charset where the build sets no encoding. .sourceEncoding(Charset.defaultCharset().name()); List arguments = pit.arguments(); 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 c4bd46d..fbf1af0 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 @@ -15,28 +15,46 @@ which can differ from the directory: pgjdbc's `pgjdbc/` directory is `:postgresq ```text Diff coverage against origin/master (95aa87fb8), from :postgresql:test --tests *PgBufferedOutputStreamTest a filtered run leaves the rest of the change looking unexecuted + ordered by uncovered changed lines, then uncovered branches pgjdbc/src/main/java/org/postgresql/util/internal/PgBufferedOutputStream.java 6/7 changed lines executed, 3/4 branches covered uncovered changed code: 167: 1 of 2 branches covered: if (len < 0) { 168: not executed: throw new IllegalArgumentException("len must be non-negative, got " + len); + +Total: 6/7 changed lines executed, 3/4 branches covered. +Uncovered changed code: 2 lines (1 not executed, 1 with an untaken branch) ``` Each uncovered line is a test you have not written yet, or a line you can justify leaving untested. The counts reflect only the tests that ran: after a run filtered with `--tests`, run the module's whole suite before you treat a line as untested. The whole report is in `/build/reports/diff-coverage/test.txt`. -If an uncovered line is unreachable or not worth a test, mark it with `// diff-coverage: ignore -- `. It stays -counted as uncovered and leaves the list of work. +The `Uncovered changed code` line counts the uncovered changed lines in two groups. A line that no test executed is in +the first group, whether or not it has branches, so that group is the changed lines the total leaves unexecuted. A line +that ran and left a branch outcome untaken is in the second. + +A changed line that holds only braces, closing parentheses, semicolons, commas, and `else`, such as `}`, `} else {`, or +`});`, counts towards no total and is not listed. The instruction the compiler puts on such a line belongs to the +statement it closes, and the lines and branches of that statement show whether it ran. Two kinds of such line are still +measured: the closing brace of a method or a lambda with an empty body, which holds its only instruction, and a line +that carries a branch. The block that follows the total leaves out the same lines. The mutation testing report leaves +them out of its count of changed lines too, and counts such a line where a mutant is on it. + +If an uncovered line is unreachable or not worth a test, mark it with `// diff-coverage: ignore -- `. It leaves +the list of work and stays in the counts, and the `Uncovered changed code` line ends with how many of the uncovered +lines are acknowledged: +`Uncovered changed code: 2 lines (1 not executed, 1 with an untaken branch), 1 of them acknowledged`. ### Unchanged code the change routes new inputs to A changed `case` label, a changed condition of an `if` or a loop, and a call on a changed line can send new inputs to lines nobody edited: the statements the label falls through to, the branches the condition guards, the body of a method -of the same file that the call reaches. The block after the total lists those methods and the lines and branches of them -the run did not cover. The change does not owe them a test, but they now run under conditions the old tests may never -have set up. +of the same file that the call reaches. The block after the total lists those methods, each by its name and parameter +types, such as `helper(int)` or `Builder.build()` for a method of a nested class, and the lines and branches of them the +run did not cover. The change does not owe them a test, but they now run under conditions the old tests may never have +set up. After a run of the whole suite, old tests execute most of that code under the old conditions, so the block ends with the `--tests` arguments that run only the test methods the change added or edited. Run those: what is left @@ -65,6 +83,18 @@ survives marks a changed line whose behavior no test asserts. For each live muta - no caller can observe the difference: the mutant is equivalent, so say so in the pull request; - you cannot tell: report it as unresolved. +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]`. +The numbers are the indexes JUnit gives the invocations, the ones a default display name shows in brackets. Where +invocations nest, as for a dynamic test in a dynamic container or a parameterized method of a `@ParameterizedClass` +class, each level gives its index, outer level first, separated by `/`: `FooTest.cases[2/5]` is the fifth child of the +factory's second child, dynamic tests and containers counted together. A JUnit 4 parameterized test is grouped this way +when its name ends in a whole number of at most nine digits in brackets, with no sign or leading zero, such as the +default `FooTest.bar[3]`. A `@Parameters(name = ...)` name of that shape, such as `{0}` with integer parameters, is +grouped too, and the numbers printed are then those parameters; any other name gets a row of its own, so invocations +whose names are the same share one. + `pitestDiff` is not part of `test`, and a surviving mutant never fails the build. It costs one run of the target tests plus a partial run per mutant, so narrow `-Pcribro.pitestTargetTests` to the test classes that exercise the change (comma-separated, globs allowed). The task is skipped when the branch changed no line in the module's main sources. @@ -90,7 +120,7 @@ stacked change, pass the parent branch: `-Pcribro.diffBase=`. | `-Pcribro.diffCoverageShowAll` | off | Prints the whole coverage report to the console | | `-Pcribro.diffCoverageMaxFiles=`, `-Pcribro.diffCoverageMaxLinesPerFile=`, `-Pcribro.diffCoverageMaxLines=` | `10`, `10`, `50` | How much of the coverage report the console shows | | `-Pcribro.pitestTargetTests=` | every test (`~.*`) | Tests allowed to kill a mutant | -| `-Pcribro.pitestMutators=` | `DEFAULTS` | PIT mutator group: `DEFAULTS`, `STRONGER`, or `ALL` | +| `-Pcribro.pitestMutators=` | `{{pitestMutators}}` | PIT mutator group: `DEFAULTS`, `STRONGER`, or `ALL` | | `-Pcribro.pitestThreads=` | half the cores | Mutants analyzed in parallel | | `-Pcribro.pitestTimeoutConst=` | `4000` | Time PIT adds to a test's normal run before it calls a mutant a timeout | | `-Pcribro.pitestShowAll` | off | Prints the whole mutation report to the console | @@ -111,8 +141,10 @@ it, and it needs an Arcmutate licence file, `arcmutate-licence.txt`, at the repo - PIT runs only the tests of the module whose code it mutates. A mutant that only another module's tests kill is reported as surviving. -- PIT splits JVM arguments at commas and whitespace. The task leaves such arguments of the test task out and names them - in its output; a test that depends on one may fail under PIT and drop out. +- PIT cannot pass a JVM argument that contains whitespace, a quote, or a `#`, nor one that leaves a `{` open, + nor one with a comma when it has a brace, or when another argument PIT passes has one. + The task leaves such arguments of the test task out and names them in its output; a test that depends on one may fail + under PIT and drop out. - PIT runs JUnit Jupiter tests one at a time, whatever the build sets for parallel execution. - PIT runs only the `test` task's tests, not those of other `Test` tasks such as integration tests. - Do not run two Gradle builds in the same project at once. diff --git a/cribro-gradle-plugin/src/test/java/io/github/cribrodev/CribroGuideTaskTest.java b/cribro-gradle-plugin/src/test/java/io/github/cribrodev/CribroGuideTaskTest.java index 78d6277..50a2589 100644 --- a/cribro-gradle-plugin/src/test/java/io/github/cribrodev/CribroGuideTaskTest.java +++ b/cribro-gradle-plugin/src/test/java/io/github/cribrodev/CribroGuideTaskTest.java @@ -15,8 +15,12 @@ */ package io.github.cribrodev; +import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import java.io.IOException; +import java.io.InputStream; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Test; @@ -136,4 +140,16 @@ void aBuildWithNoJavaProjectIsToldNoProjectHasTheTasks() { CribroGuideTask.render( "Run {{gradlew}}.\n", "1.2.3", "./gradlew", List.of(), Map.of())); } + + @Test + void theShippedGuideHasAValueForEveryPlaceholder() throws IOException { + String template; + try (InputStream in = CribroGuideTask.class.getResourceAsStream("guide.md")) { + template = new String(in.readAllBytes(), UTF_8); + } + String guide = + CribroGuideTask.render( + template, "1.2.3", "./gradlew", List.of(":app"), CribroGuideTask.values()); + assertFalse(guide.contains("{{"), guide); + } } diff --git a/cribro-gradle-plugin/src/test/java/io/github/cribrodev/CribroPluginTest.java b/cribro-gradle-plugin/src/test/java/io/github/cribrodev/CribroPluginTest.java index 44f4905..f40eb8a 100644 --- a/cribro-gradle-plugin/src/test/java/io/github/cribrodev/CribroPluginTest.java +++ b/cribro-gradle-plugin/src/test/java/io/github/cribrodev/CribroPluginTest.java @@ -16,6 +16,7 @@ package io.github.cribrodev; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; @@ -23,20 +24,22 @@ import java.nio.file.Files; import java.nio.file.Path; import java.util.List; +import java.util.Map; import java.util.stream.Collectors; import org.gradle.api.Project; import org.gradle.api.tasks.SourceSet; import org.gradle.api.tasks.SourceSetContainer; import org.gradle.testfixtures.ProjectBuilder; +import org.gradle.testing.jacoco.plugins.JacocoPlugin; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; /** * The plugin measures the directories of the main source set that hold Java or Kotlin sources, - * puts the PIT plugins a build names on PIT's classpath, and replaces Gradle's bundled JaCoCo only - * with a newer one, so the version comparison decides whether a build on a future Gradle is - * downgraded. + * puts the PIT plugins a build names on PIT's classpath, runs PIT with the {@code STRONGER} mutator + * group where the build names none, and replaces Gradle's bundled JaCoCo only with a newer one, so + * the version comparison decides whether a build on a future Gradle is downgraded. */ class CribroPluginTest { @@ -178,6 +181,34 @@ void theNamedPluginsJoinPitOnItsClasspath() throws IOException { } } + @Test + void pitestDiffUsesTheStrongerGroupWhereTheBuildNamesNone() throws IOException { + Project project = javaProject(""); + + assertEquals( + "STRONGER", + project.getTasks().named("pitestDiff", PitestDiffTask.class).get().getMutators().get()); + } + + @Test + void pitestDiffGetsTheTestTasksLeftOutArgumentsWithTheirReasons() throws IOException { + Project project = javaProject(""); + project + .getTasks() + .named("test", org.gradle.api.tasks.testing.Test.class) + .get() + .jvmArgs("-Dq=a b"); + + assertEquals( + Map.of(PitestJvmArgs.ARGUMENT_FILE, List.of("-Dq=a b")), + project + .getTasks() + .named("pitestDiff", PitestDiffTask.class) + .get() + .getLeftOutJvmArgs() + .get()); + } + @Test void aLaterPatchIsNewer() { assertTrue(CribroPlugin.compareVersions("0.8.13", "0.8.16") < 0); @@ -198,4 +229,15 @@ void aSnapshotComparesByItsNumbers() { void aNewerBundledVersionIsKept() { assertTrue(CribroPlugin.compareVersions("0.9.1", "0.8.16") > 0); } + + @Test + void aGradleWithNoBundledJacocoFieldGivesNoVersion() { + assertNull(CribroPlugin.bundledJacocoVersion(Object.class)); + } + + @Test + void theBundledJacocoVersionIsTheFieldOfTheGradleThatRuns() { + assertEquals( + JacocoPlugin.DEFAULT_JACOCO_VERSION, CribroPlugin.bundledJacocoVersion(JacocoPlugin.class)); + } } 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 96275c3..c1dd637 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 @@ -25,6 +25,8 @@ import java.nio.file.Path; import java.util.ArrayList; import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import org.gradle.testkit.runner.BuildResult; import org.gradle.testkit.runner.GradleRunner; import org.junit.jupiter.api.Test; @@ -47,8 +49,9 @@ class KotlinBuildTest { /** * Writes a one-file Kotlin build whose only test covers one branch of {@code max} and never calls - * {@code next}. The file lies at the root of {@code src/main/kotlin} and declares a package, so - * its directory does not follow it. + * {@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. */ private void writeBuild() throws IOException { Files.writeString( @@ -85,6 +88,10 @@ fun max(a: Int, b: Int): Int { fun next(a: Int): Int { return a + 1 } + + fun log(a: Int) { + println(a) + } """); write( "src/test/kotlin/demo/math/CalcTest.kt", @@ -142,14 +149,29 @@ void aKotlinFileIsMeasuredByThePackageItDeclaresRatherThanItsDirectory() throws String output = result.getOutput(); assertAll( () -> assertContains(output, " src/main/kotlin/Calc.kt\n "), - () -> assertContains(output, " 2/4 changed lines executed, 1/2 branches covered"), + () -> assertContains(output, " 2/5 changed lines executed, 1/2 branches covered"), () -> assertContains(output, " 4: 1 of 2 branches covered: if (a > b) {"), () -> assertContains(output, " 7: not executed: return b"), () -> assertContains(output, " 11: not executed: return a + 1"), + () -> assertContains(output, " 15: not executed: println(a)"), + () -> assertContains(output, " of 5 changed lines: "), + () -> + assertEquals( + number(output, "Total: \\d+/(\\d+) changed lines executed"), + number(output, "mutants? on \\d+ of (\\d+) changed lines: "), + "changed lines in the mutation summary, which has to leave out the brace lines that" + + " the diff coverage total leaves out"), () -> assertContains(output, "survived: changed conditional boundary, in max"), () -> assertContains(output, "no test reaches it: Replaced integer addition with subtraction, in next")); } + /** 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); + assertTrue(matcher.find(), () -> "expected a match of " + regex + " in:\n" + output); + return Integer.parseInt(matcher.group(1)); + } + private static void assertContains(String output, String expected) { assertTrue(output.contains(expected), () -> "expected:\n" + expected + "\nin:\n" + output); } diff --git a/cribro-gradle-plugin/src/test/java/io/github/cribrodev/OlderGradleTest.java b/cribro-gradle-plugin/src/test/java/io/github/cribrodev/OlderGradleTest.java new file mode 100644 index 0000000..0d125cd --- /dev/null +++ b/cribro-gradle-plugin/src/test/java/io/github/cribrodev/OlderGradleTest.java @@ -0,0 +1,92 @@ +/* + * 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 java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import org.gradle.testkit.runner.BuildResult; +import org.gradle.testkit.runner.GradleRunner; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** + * On a Gradle whose bundled JaCoCo is older than cribro's, a build that names no JaCoCo version + * gets cribro's, and a build that names one keeps it. + * + *

TestKit downloads that Gradle distribution, so the tests need the network. + */ +class OlderGradleTest { + + /** + * A Gradle that runs on every JDK the CI matrix tests with, and whose bundled JaCoCo, 0.8.14, is + * older than both {@link CribroPlugin#JACOCO_VERSION} and the 0.8.15 that the Gradle compiling + * cribro bundles. + */ + static final String GRADLE_VERSION = "9.6.1"; + + @TempDir Path build; + + @Test + void aBuildThatNamesNoJacocoVersionGetsCribros() throws IOException { + String output = + run( + """ + plugins { id 'java' } + tasks.register('noop') + gradle.projectsEvaluated { println "toolVersion=${jacoco.toolVersion}" } + """); + + assertEquals("toolVersion=" + CribroPlugin.JACOCO_VERSION, output); + } + + @Test + void aJacocoVersionTheBuildNamesIsKept() throws IOException { + String output = + run( + """ + plugins { id 'java'; id 'jacoco' } + jacoco { toolVersion = '0.8.12' } + tasks.register('noop') + gradle.projectsEvaluated { println "toolVersion=${jacoco.toolVersion}" } + """); + + assertEquals( + "toolVersion=0.8.12", + output, + "a version the build names is kept, though it is older than cribro's and the bundled one"); + } + + /** Runs {@code noop} on {@link #GRADLE_VERSION} with cribro applied, and returns the output. */ + private String run(String buildScript) throws IOException { + Files.writeString( + build.resolve("settings.gradle"), + "plugins { id '" + CribroSettingsPlugin.ID + "' }\nrootProject.name = 'demo'\n", + UTF_8); + Files.writeString(build.resolve("build.gradle"), buildScript, UTF_8); + BuildResult result = + GradleRunner.create() + .withGradleVersion(GRADLE_VERSION) + .withProjectDir(build.toFile()) + .withPluginClasspath() + .withArguments("--quiet", "noop") + .build(); + return result.getOutput().strip(); + } +} diff --git a/cribro-maven-plugin/build.gradle.kts b/cribro-maven-plugin/build.gradle.kts index dbef37e..39b2d69 100644 --- a/cribro-maven-plugin/build.gradle.kts +++ b/cribro-maven-plugin/build.gradle.kts @@ -88,6 +88,11 @@ tasks.named("generateMavenPluginDescriptor") { dependsOn(":cribro-core:versions") } +// The tests read the parameter defaults from the descriptor, where Maven reads them. +dependencies { + testRuntimeOnly(files(tasks.named("generateMavenPluginDescriptor"))) +} + // The integration tests run a real Maven, which resolves cribro from it-repository, and Maven // Central for everything else. val mavenDistribution = configurations.dependencyScope("mavenDistribution") diff --git a/cribro-maven-plugin/src/main/java/io/github/cribrodev/maven/CoverageReport.java b/cribro-maven-plugin/src/main/java/io/github/cribrodev/maven/CoverageReport.java index 46381df..7af2486 100644 --- a/cribro-maven-plugin/src/main/java/io/github/cribrodev/maven/CoverageReport.java +++ b/cribro-maven-plugin/src/main/java/io/github/cribrodev/maven/CoverageReport.java @@ -47,8 +47,10 @@ import org.jacoco.core.analysis.IClassCoverage; import org.jacoco.core.analysis.ICounter; import org.jacoco.core.analysis.ILine; +import org.jacoco.core.analysis.IMethodCoverage; import org.jacoco.core.analysis.IPackageCoverage; import org.jacoco.core.analysis.ISourceFileCoverage; +import org.jacoco.core.analysis.ISourceNode; import org.jacoco.core.data.ExecutionDataReader; import org.jacoco.core.data.ExecutionDataStore; import org.jacoco.core.data.SessionInfo; @@ -338,10 +340,26 @@ private JacocoLines analyze( return lines(bundle); } - /** Returns the counters of every line the XML report of the bundle lists. */ + /** + * Returns the counters of every line, and the first line of every method, that the XML report of + * the bundle lists. + */ static JacocoLines lines(IBundleCoverage bundle) { JacocoLines.Builder lines = new JacocoLines.Builder(); for (IPackageCoverage packageCoverage : bundle.getPackages()) { + for (IClassCoverage classCoverage : packageCoverage.getClasses()) { + if (classCoverage.getSourceFileName() == null) { + continue; + } + String key = + SourceFileKey.of(packageCoverage.getName(), classCoverage.getSourceFileName()); + for (IMethodCoverage method : classCoverage.getMethods()) { + // The XML report leaves out the line of a method compiled without line numbers. + if (method.getFirstLine() != ISourceNode.UNKNOWN_LINE) { + lines.method(key, method.getFirstLine()); + } + } + } for (ISourceFileCoverage sourceFile : packageCoverage.getSourceFiles()) { String key = SourceFileKey.of(packageCoverage.getName(), sourceFile.getName()); lines.sourceFile(key); diff --git a/cribro-maven-plugin/src/main/java/io/github/cribrodev/maven/GuideMojo.java b/cribro-maven-plugin/src/main/java/io/github/cribrodev/maven/GuideMojo.java index 3824ed4..7ed2538 100644 --- a/cribro-maven-plugin/src/main/java/io/github/cribrodev/maven/GuideMojo.java +++ b/cribro-maven-plugin/src/main/java/io/github/cribrodev/maven/GuideMojo.java @@ -17,6 +17,7 @@ import static java.nio.charset.StandardCharsets.UTF_8; +import io.github.cribrodev.PitestRun; import io.github.cribrodev.Versions; import java.io.File; import java.io.IOException; @@ -60,16 +61,23 @@ public void execute() { extClassPath, System.getProperty("user.home")), modules, - Map.of( - "pitestVersion", - Versions.pitest(), - "pitestJunit5PluginVersion", - Versions.pitestJunit5Plugin(), - "jacocoVersion", - Versions.jacoco()))); + values())); System.out.flush(); } + /** Returns the value of each {@code {{name}}} in the guide other than {@code {{mvn}}}. */ + static Map values() { + return Map.of( + "pitestVersion", + Versions.pitest(), + "pitestJunit5PluginVersion", + Versions.pitestJunit5Plugin(), + "pitestMutators", + PitestRun.DEFAULT_MUTATORS, + "jacocoVersion", + Versions.jacoco()); + } + /** * Returns the guide for this build. * diff --git a/cribro-maven-plugin/src/main/java/io/github/cribrodev/maven/PitestDiffMojo.java b/cribro-maven-plugin/src/main/java/io/github/cribrodev/maven/PitestDiffMojo.java index 0f24b62..9a874c6 100644 --- a/cribro-maven-plugin/src/main/java/io/github/cribrodev/maven/PitestDiffMojo.java +++ b/cribro-maven-plugin/src/main/java/io/github/cribrodev/maven/PitestDiffMojo.java @@ -100,6 +100,9 @@ threadSafe = true) public class PitestDiffMojo extends AbstractMojo { + /** The surefire execution whose configuration PIT runs the tests with, as messages name it. */ + private static final String DEFAULT_TEST = "surefire's default-test"; + @Parameter(defaultValue = "${project}", readonly = true) private MavenProject project; @@ -117,7 +120,7 @@ public class PitestDiffMojo extends AbstractMojo { private String targetTests; /** The PIT mutator group: {@code DEFAULTS}, {@code STRONGER}, or {@code ALL}. */ - @Parameter(property = "cribro.pitestMutators", defaultValue = "DEFAULTS") + @Parameter(property = "cribro.pitestMutators", defaultValue = PitestRun.DEFAULT_MUTATORS) private String mutators; /** Mutants analyzed in parallel; unset uses half the cores. */ @@ -285,9 +288,7 @@ private void run() systemProperties( surefire, session.getUserProperties(), project.getBasedir(), localRepository()), null); - List leftOut = new ArrayList<>(unresolved); - leftOut.addAll(jvmArgs.leftOut()); - String leftOutMessage = PitestRun.leftOutMessage(leftOut, "surefire's default-test"); + String leftOutMessage = leftOutMessage(unresolved, jvmArgs.leftOutByReason()); PitestRun pit = new PitestRun() @@ -306,6 +307,7 @@ private void run() : Math.max(1, Runtime.getRuntime().availableProcessors() / 2)) .timeoutConst(timeoutConst) .changedLines(changedLines) + .repository(repository) .sourceEncoding(sourceEncoding(project.getProperties())); addTestSelection(pit, tests, excluded, surefire); @@ -493,6 +495,23 @@ static List argLineArguments( return arguments; } + /** + * Returns the lines naming the JVM arguments of surefire's default-test that PIT ran the tests + * without, as {@link PitestRun#leftOutMessage} lays them out, or null where there are none. + * + * @param unresolved the arguments with an {@code @{name}} the project does not define + * @param split the other arguments PIT cannot pass whole, keyed by why, as {@link + * PitestJvmArgs#leftOutByReason()} returns them + */ + static String leftOutMessage(List unresolved, Map> split) { + Map> leftOut = new LinkedHashMap<>(); + if (!unresolved.isEmpty()) { + leftOut.put("they name an @{property} the project does not define", unresolved); + } + leftOut.putAll(split); + return PitestRun.leftOutMessage(leftOut, DEFAULT_TEST); + } + /** * Returns the process that runs PIT with surefire's working directory and environment, its * output going to the log. 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 a63e124..b5447a6 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 @@ -15,12 +15,16 @@ Once the build has run the tests, it prints a block like this before its summary ```text Diff coverage against origin/main (95aa87fb8), from the tests of guava-tests -Dtest=ImmutableListTest a filtered run leaves the rest of the change looking unexecuted + ordered by uncovered changed lines, then uncovered branches guava/src/com/google/common/collect/ImmutableList.java 6/7 changed lines executed, 3/4 branches covered uncovered changed code: 167: 1 of 2 branches covered: if (len < 0) { 168: not executed: throw new IllegalArgumentException("len must be non-negative, got " + len); + +Total: 6/7 changed lines executed, 3/4 branches covered. +Uncovered changed code: 2 lines (1 not executed, 1 with an untaken branch) ``` Each uncovered line is a test you have not written yet, or a line you can justify leaving untested. To run some of the @@ -31,16 +35,30 @@ module in the build, so `-am` matters when the tests live in a module of their o `target/cribro/diff-coverage.txt` of each module whose main sources the change touched, which can be a module other than ``. -If an uncovered line is unreachable or not worth a test, mark it with `// diff-coverage: ignore -- `. It stays -counted as uncovered and leaves the list of work. +The `Uncovered changed code` line counts the uncovered changed lines in two groups. A line that no test executed is in +the first group, whether or not it has branches, so that group is the changed lines the total leaves unexecuted. A line +that ran and left a branch outcome untaken is in the second. + +A changed line that holds only braces, closing parentheses, semicolons, commas, and `else`, such as `}`, `} else {`, or +`});`, counts towards no total and is not listed. The instruction the compiler puts on such a line belongs to the +statement it closes, and the lines and branches of that statement show whether it ran. Two kinds of such line are still +measured: the closing brace of a method or a lambda with an empty body, which holds its only instruction, and a line +that carries a branch. The block that follows the total leaves out the same lines. The mutation testing report leaves +them out of its count of changed lines too, and counts such a line where a mutant is on it. + +If an uncovered line is unreachable or not worth a test, mark it with `// diff-coverage: ignore -- `. It leaves +the list of work and stays in the counts, and the `Uncovered changed code` line ends with how many of the uncovered +lines are acknowledged: +`Uncovered changed code: 2 lines (1 not executed, 1 with an untaken branch), 1 of them acknowledged`. ### Unchanged code the change routes new inputs to A changed `case` label, a changed condition of an `if` or a loop, and a call on a changed line can send new inputs to -lines nobody edited: the statements the label falls through to, the branches the condition guards, the body of a -method of the same file that the call reaches. The block after the total lists those methods and the lines and -branches of them the run did not cover. The change does not owe them a test, but they now run under conditions the old -tests may never have set up. +lines nobody edited: the statements the label falls through to, the branches the condition guards, the body of a method +of the same file that the call reaches. The block after the total lists those methods, each by its name and parameter +types, such as `helper(int)` or `Builder.build()` for a method of a nested class, and the lines and branches of them the +run did not cover. The change does not owe them a test, but they now run under conditions the old tests may never have +set up. After a run of the whole suite, old tests execute most of that code under the old conditions, so the block ends with the `-Dtest` arguments that run only the test methods the change added or edited under the module's own `src` @@ -70,6 +88,18 @@ survives marks a changed line whose behavior no test asserts. For each live muta - no caller can observe the difference: the mutant is equivalent, so say so in the pull request; - you cannot tell: report it as unresolved. +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]`. +The numbers are the indexes JUnit gives the invocations, the ones a default display name shows in brackets. Where +invocations nest, as for a dynamic test in a dynamic container or a parameterized method of a `@ParameterizedClass` +class, each level gives its index, outer level first, separated by `/`: `FooTest.cases[2/5]` is the fifth child of the +factory's second child, dynamic tests and containers counted together. A JUnit 4 parameterized test is grouped this way +when its name ends in a whole number of at most nine digits in brackets, with no sign or leading zero, such as the +default `FooTest.bar[3]`. A `@Parameters(name = ...)` name of that shape, such as `{0}` with integer parameters, is +grouped too, and the numbers printed are then those parameters; any other name gets a row of its own, so invocations +whose names are the same share one. + `cribro:pitest-diff` is not part of `test`, and a surviving mutant never fails the build. It costs one run of the target tests plus a partial run per mutant, so narrow `-Dcribro.pitestTargetTests` to the test classes that exercise the change (comma-separated, globs allowed). A module mutates its own changed classes and those of the modules it tests @@ -103,7 +133,7 @@ Pass a property with `-D`, or set it in `.mvn/maven.config` or in the ``, `-Dcribro.diffCoverageMaxLinesPerFile=`, `-Dcribro.diffCoverageMaxLines=` | `10`, `10`, `50` | How much of the coverage report the console shows | | `-Dcribro.pitestTargetTests=` | surefire's includes | Tests allowed to kill a mutant | -| `-Dcribro.pitestMutators=` | `DEFAULTS` | PIT mutator group: `DEFAULTS`, `STRONGER`, or `ALL` | +| `-Dcribro.pitestMutators=` | `{{pitestMutators}}` | PIT mutator group: `DEFAULTS`, `STRONGER`, or `ALL` | | `-Dcribro.pitestThreads=` | half the cores | Mutants analyzed in parallel | | `-Dcribro.pitestTimeoutConst=` | `4000` | Time PIT adds to a test's normal run before it calls a mutant a timeout | | `-Dcribro.pitestShowAll` | off | Prints the whole mutation report to the console | @@ -127,8 +157,10 @@ it, and it needs an Arcmutate licence file, `arcmutate-licence.txt`, at the repo reads that agent's file. - Only surefire's `default-test` execution is measured; failsafe and other surefire executions are not. - A module whose tests run in Maven's own JVM (`forkCount=0`) records no coverage, and the report says so. -- PIT splits JVM arguments at commas and whitespace. The goal leaves such arguments out and names them in its output; - a test that depends on one may fail under PIT and drop out. +- PIT cannot pass a JVM argument that contains whitespace, a quote, or a `#`, nor one that leaves a `{` open, + nor one with a comma when it has a brace, or when another argument PIT passes has one. + The goal leaves such arguments out and names them in its output; a test that depends on one may fail under PIT and + drop out. - PIT runs JUnit Jupiter tests one at a time, whatever surefire sets for parallel execution. - `cribro:pitest-diff` has no overall time limit, and surefire's `forkedProcessTimeoutInSeconds` does not bound it. A test that hangs before any mutant runs keeps PIT waiting until the build is stopped; `cribro.pitestTimeoutConst` diff --git a/cribro-maven-plugin/src/test/java/io/github/cribrodev/maven/CoverageReportTest.java b/cribro-maven-plugin/src/test/java/io/github/cribrodev/maven/CoverageReportTest.java index 101c7be..36ca5c9 100644 --- a/cribro-maven-plugin/src/test/java/io/github/cribrodev/maven/CoverageReportTest.java +++ b/cribro-maven-plugin/src/test/java/io/github/cribrodev/maven/CoverageReportTest.java @@ -29,12 +29,15 @@ import io.github.cribrodev.JacocoLines; import org.apache.maven.project.MavenProject; import org.jacoco.core.analysis.ICounter; +import org.jacoco.core.analysis.ISourceNode; import org.jacoco.core.data.ExecutionData; import org.jacoco.core.data.ExecutionDataStore; import org.jacoco.core.data.ExecutionDataWriter; import org.jacoco.core.data.SessionInfo; import org.jacoco.core.internal.analysis.BundleCoverageImpl; +import org.jacoco.core.internal.analysis.ClassCoverageImpl; import org.jacoco.core.internal.analysis.CounterImpl; +import org.jacoco.core.internal.analysis.MethodCoverageImpl; import org.jacoco.core.internal.analysis.PackageCoverageImpl; import org.jacoco.core.internal.analysis.SourceFileCoverageImpl; import org.junit.jupiter.api.Test; @@ -129,6 +132,26 @@ void theLinesOfAnAnalyzedBundleCarryTheCountersTheXmlReportWrites() { assertEquals(ICounter.EMPTY, sample.getLine(4).getStatus(), "status of line 4"); } + /** A method compiled without line numbers has no first line, and the XML report gives none. */ + @Test + void theFirstLineOfEachMethodIsRecordedAgainstTheSourceFileOfItsClass() { + MethodCoverageImpl noop = new MethodCoverageImpl("noop", "()V", null); + noop.increment(CounterImpl.getInstance(1, 0), CounterImpl.COUNTER_0_0, 7); + MethodCoverageImpl withoutLines = new MethodCoverageImpl("generated", "()V", null); + withoutLines.increment( + CounterImpl.getInstance(1, 0), CounterImpl.COUNTER_0_0, ISourceNode.UNKNOWN_LINE); + ClassCoverageImpl sample = new ClassCoverageImpl("com/example/Sample", 0, false); + sample.setSourceFileName("Sample.java"); + sample.addMethod(noop); + sample.addMethod(withoutLines); + PackageCoverageImpl packageCoverage = + new PackageCoverageImpl("com/example", List.of(sample), List.of()); + + assertEquals( + new JacocoLines.Builder().method("com/example/Sample.java", 7).build(), + CoverageReport.lines(new BundleCoverageImpl("bundle", List.of(packageCoverage)))); + } + /** JaCoCo names the default package with an empty string. */ @Test void aSourceFileInTheDefaultPackageIsKeyedByItsNameAlone() { diff --git a/cribro-maven-plugin/src/test/java/io/github/cribrodev/maven/GuideMojoTest.java b/cribro-maven-plugin/src/test/java/io/github/cribrodev/maven/GuideMojoTest.java index a3123b0..d3eb3c4 100644 --- a/cribro-maven-plugin/src/test/java/io/github/cribrodev/maven/GuideMojoTest.java +++ b/cribro-maven-plugin/src/test/java/io/github/cribrodev/maven/GuideMojoTest.java @@ -15,11 +15,16 @@ */ package io.github.cribrodev.maven; +import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import java.io.IOException; +import java.io.InputStream; +import java.util.List; import org.junit.jupiter.api.Test; -/** The command the guide tells the reader to run. */ +/** The guide, and the command it tells the reader to run. */ class GuideMojoTest { @Test @@ -40,4 +45,14 @@ void aPathWithASpaceIsQuoted() { "mvn -Dmaven.ext.class.path='/opt/my tools/cribro-maven.jar'", GuideMojo.mavenCommand("mvn", "/opt/my tools/cribro-maven.jar", "/home/u")); } + + @Test + void theShippedGuideHasAValueForEveryPlaceholder() throws IOException { + String template; + try (InputStream in = GuideMojo.class.getResourceAsStream("guide.md")) { + template = new String(in.readAllBytes(), UTF_8); + } + String guide = GuideMojo.render(template, "1.2.3", "mvn", List.of(":app"), GuideMojo.values()); + assertFalse(guide.contains("{{"), guide); + } } diff --git a/cribro-maven-plugin/src/test/java/io/github/cribrodev/maven/MavenIntegrationTest.java b/cribro-maven-plugin/src/test/java/io/github/cribrodev/maven/MavenIntegrationTest.java index 9dbc362..970880e 100644 --- a/cribro-maven-plugin/src/test/java/io/github/cribrodev/maven/MavenIntegrationTest.java +++ b/cribro-maven-plugin/src/test/java/io/github/cribrodev/maven/MavenIntegrationTest.java @@ -418,7 +418,7 @@ void pitRunsTheTestsOfAnotherModuleWithSurefiresSystemProperties() throws Except pit, "Skipped: -am builds lib only for the modules -pl names; add it to -pl to run PIT on its" + " tests."); - assertContains(pit, "2 mutants: 2 killed"); + assertContains(pit, "2 mutants on 1 of 1 changed line: 2 killed"); Path survivors = root.resolve("lib-tests/target/cribro/pitest-diff/survivors.txt"); assertTrue(Files.isRegularFile(survivors), () -> survivors + " after the run"); } diff --git a/cribro-maven-plugin/src/test/java/io/github/cribrodev/maven/PitestDiffMojoTest.java b/cribro-maven-plugin/src/test/java/io/github/cribrodev/maven/PitestDiffMojoTest.java index 8746b95..4a7b260 100644 --- a/cribro-maven-plugin/src/test/java/io/github/cribrodev/maven/PitestDiffMojoTest.java +++ b/cribro-maven-plugin/src/test/java/io/github/cribrodev/maven/PitestDiffMojoTest.java @@ -19,6 +19,7 @@ import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -27,6 +28,7 @@ import java.io.BufferedReader; import java.io.File; import java.io.IOException; +import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringReader; import java.nio.charset.Charset; @@ -51,6 +53,7 @@ import org.apache.maven.model.Plugin; import org.apache.maven.model.PluginExecution; import org.apache.maven.project.MavenProject; +import org.codehaus.plexus.util.xml.Xpp3Dom; import org.codehaus.plexus.util.xml.Xpp3DomBuilder; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -63,6 +66,50 @@ class PitestDiffMojoTest { @TempDir Path testClasses; + @Test + void anArgumentWithAnUndefinedPropertyIsNamedApartFromTheSplitOnes() { + assertEquals( + "PIT ran the tests without these JVM arguments of surefire's default-test, since they name" + + " an @{property} the project does not define:\n" + + " @{absent}\n" + + "PIT ran the tests without these JVM arguments of surefire's default-test, since PIT" + + " splits them:\n" + + " -Da=b,{c}", + PitestDiffMojo.leftOutMessage( + List.of("@{absent}"), Map.of("PIT splits them", List.of("-Da=b,{c}")))); + } + + @Test + void noArgumentLeftOutNeedsNoLine() { + assertNull(PitestDiffMojo.leftOutMessage(List.of(), Map.of())); + } + + /** The default is read from the plugin descriptor, which is where Maven reads it. */ + @Test + void aBuildThatNamesNoMutatorsGetsTheStrongerGroup() throws Exception { + Xpp3Dom plugin; + try (InputStream descriptor = + PitestDiffMojo.class.getResourceAsStream("/META-INF/maven/plugin.xml")) { + assertNotNull(descriptor, "META-INF/maven/plugin.xml on the test classpath"); + plugin = Xpp3DomBuilder.build(new InputStreamReader(descriptor, UTF_8)); + } + assertEquals( + "cribro-maven-plugin", + plugin.getChild("artifactId").getValue(), + "the plugin of the first META-INF/maven/plugin.xml on the test classpath"); + Xpp3Dom pitestDiff = null; + for (Xpp3Dom mojo : plugin.getChild("mojos").getChildren("mojo")) { + if (mojo.getChild("goal").getValue().equals("pitest-diff")) { + pitestDiff = mojo; + } + } + assertNotNull(pitestDiff, "the pitest-diff goal in the plugin descriptor"); + + assertEquals( + "STRONGER", + pitestDiff.getChild("configuration").getChild("mutators").getAttribute("default-value")); + } + @ParameterizedTest(name = "{0}") @ValueSource( strings = { diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 8ace4f0..9d3ac56 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -17,6 +17,7 @@ junit-bom = "org.junit:junit-bom:5.14.4" junit-jupiter = { module = "org.junit.jupiter:junit-jupiter" } junit-platform-launcher = { module = "org.junit.platform:junit-platform-launcher" } pitest-entry = { module = "org.pitest:pitest-entry", version.ref = "pitest" } +pitest-command-line = { module = "org.pitest:pitest-command-line", version.ref = "pitest" } jacoco-agent = { module = "org.jacoco:org.jacoco.agent", version.ref = "jacoco" } jacoco-core = { module = "org.jacoco:org.jacoco.core", version.ref = "jacoco" } jacoco-report = { module = "org.jacoco:org.jacoco.report", version.ref = "jacoco" }