From 1b965d547a6fc24fc5d20809ff3b3839fd2f4f37 Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Mon, 30 Nov 2026 11:47:57 +0300 Subject: [PATCH] Mutate the main variant's artifact where java-test-fixtures puts it on the test classpath In a module that applies java-test-fixtures, Gradle puts the module's artifact, by default the jar task's archive, on the test runtime classpath in place of build/classes/java/main. pitestDiff passed PIT only the main classes directories as --mutableCodePaths, so PIT found none of the changed classes on the classpath the tests run with, and every such module reported: no mutant: no changed line has bytecode PIT may mutate Apache JMeter applies java-test-fixtures to its core, components, and jorphan modules, among others, and pitestDiff found no mutant in them. pitestDiff now passes PIT the entries of the test runtime classpath that hold the main classes: the main classes directories, and the artifacts the test runtime classpath configuration resolves to whose component is this project and whose variant is the project's main variant, the one with the capability :. That covers the jar task's archive and any other file runtimeElements publishes, such as a fat jar or a jar a Copy task writes. The test fixtures' jar carries the capability :-test-fixtures and is left out. Naming the jar task instead was rejected: a build that replaces the runtimeElements artifact puts another file on the classpath. PitestDiffMojo already maps each reactor artifact to its output directory, whatever built it. Where the test runtime classpath holds neither, the task fails before PIT starts. Given an empty --mutableCodePaths, PIT falls back to DefaultCodePathPredicate, which admits every class directory whose path does not end in test-classes or bin-test, so it would mutate build/classes/java/test. User-visible: pitestDiff reports the mutants of a module that applies java-test-fixtures, where 1.2.0 reported "no mutant: no changed line has bytecode PIT may mutate". pitestDiff fails where sourceSets.test.runtimeClasspath holds neither the main classes directories nor the project's own jar resolved through testRuntimeClasspath, where 1.2.0 finished with "no mutant: no changed line has bytecode PIT may mutate". The failure is: "Found none of the main classes on the test runtime classpath of . The classpath holds neither the directories [
] nor the project's own jar resolved through configurations.testRuntimeClasspath, such as the one java-test-fixtures puts there, so PIT would have no class to mutate. Add the directories to sourceSets.test.runtimeClasspath, the classpath pitestDiff runs the tests with under PIT. PIT then mutates the main classes even where the tests load them from another file, such as a jar added with files(...)." Co-Authored-By: Claude Opus 5.5 --- .../java/io/github/cribrodev/PitestRun.java | 7 +- .../io/github/cribrodev/CribroPlugin.java | 35 +++ .../io/github/cribrodev/PitestDiffTask.java | 51 +++- .../resources/io/github/cribrodev/guide.md | 7 + .../cribrodev/PitestDiffMainClassesTest.java | 264 ++++++++++++++++++ 5 files changed, 360 insertions(+), 4 deletions(-) create mode 100644 cribro-gradle-plugin/src/test/java/io/github/cribrodev/PitestDiffMainClassesTest.java diff --git a/cribro-core/src/main/java/io/github/cribrodev/PitestRun.java b/cribro-core/src/main/java/io/github/cribrodev/PitestRun.java index fc015b6..523a44d 100644 --- a/cribro-core/src/main/java/io/github/cribrodev/PitestRun.java +++ b/cribro-core/src/main/java/io/github/cribrodev/PitestRun.java @@ -127,7 +127,10 @@ public PitestRun targetTests(String targetTests) { return this; } - /** The class directories PIT may mutate; a glob cannot reach a class outside them. */ + /** + * The classpath entries, class directories or jars, that hold the classes PIT may mutate; a glob + * cannot reach a class outside them. + */ public PitestRun mutableCodePaths(List mutableCodePaths) { this.mutableCodePaths = List.copyOf(mutableCodePaths); return this; @@ -194,7 +197,7 @@ public List arguments() throws IOException { options.put("reportDir", reportDir.getAbsolutePath()); options.put("targetClasses", String.join(",", targetClasses)); options.put("targetTests", targetTests == null ? ALL_TESTS : targetTests); - // Only these directories are mutated, so a glob cannot reach a test class of the same name. + // Only these entries are mutated, so a glob cannot reach a test class of the same name. options.put("mutableCodePaths", paths(mutableCodePaths)); options.put("sourceDirs", paths(sourceDirs)); options.put("classPathFile", classPathFile.getAbsolutePath()); 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 4b96232..8c22a57 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 @@ -30,6 +30,8 @@ import org.gradle.api.Project; import org.gradle.api.artifacts.Configuration; import org.gradle.api.artifacts.ModuleVersionIdentifier; +import org.gradle.api.artifacts.ResolvableDependencies; +import org.gradle.api.artifacts.result.ResolvedArtifactResult; import org.gradle.api.artifacts.result.ResolvedComponentResult; import org.gradle.api.attributes.Attribute; import org.gradle.api.attributes.Category; @@ -386,6 +388,7 @@ && compareVersions(jacoco.getToolVersion(), JACOCO_VERSION) < 0) { project.files( (Callable) () -> missingLauncher(project, testRuntime, t))); task.getMainClassesDirs().from(main.getOutput().getClassesDirs()); + task.getMainArtifacts().from(mainVariantArtifacts(testRuntime)); task.getMainSourceDirs().from((Callable>) () -> sourceDirs(main)); task.getReportDir() .set(project.getLayout().getBuildDirectory().dir("reports/pitest-diff")); @@ -421,6 +424,38 @@ && compareVersions(jacoco.getToolVersion(), JACOCO_VERSION) < 0) { return overrides; } + /** + * Returns the files of this project's main variant, the one with the capability {@code + * :}, that {@code configuration} resolves to, such as the jar {@code + * java-test-fixtures} puts on the test runtime classpath, whatever task builds it. The test + * fixtures' jar is left out: its variant carries the capability {@code + * :-test-fixtures}. + */ + private static Provider> mainVariantArtifacts(Configuration configuration) { + ResolvableDependencies incoming = configuration.getIncoming(); + return incoming + .getArtifacts() + .getResolvedArtifacts() + .zip( + incoming.getResolutionResult().getRootComponent(), + (artifacts, root) -> { + ModuleVersionIdentifier self = root.getModuleVersion(); + List files = new ArrayList<>(); + for (ResolvedArtifactResult artifact : artifacts) { + if (artifact.getId().getComponentIdentifier().equals(root.getId()) + && self != null + && artifact.getVariant().getCapabilities().stream() + .anyMatch( + c -> + c.getGroup().equals(self.getGroup()) + && c.getName().equals(self.getName()))) { + files.add(artifact.getFile()); + } + } + return files; + }); + } + /** * Returns the JUnit Platform launcher matching the engine on the test runtime classpath, or * nothing where the tests do not run on the JUnit Platform or bring a launcher of their own. 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 80628b1..64935cc 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 @@ -22,7 +22,10 @@ import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; +import java.util.LinkedHashSet; import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; import javax.inject.Inject; import org.gradle.api.DefaultTask; import org.gradle.api.GradleException; @@ -78,10 +81,23 @@ public abstract class PitestDiffTask extends DefaultTask { @Classpath public abstract ConfigurableFileCollection getTestRuntimeClasspath(); - /** The main classes, the only code PIT mutates; they are on the test runtime classpath too. */ + /** + * The directories of the main classes, which PIT mutates where the test runtime classpath holds + * them. + */ @Internal public abstract ConfigurableFileCollection getMainClassesDirs(); + /** + * The artifacts of this project's main variant, the one with the capability {@code + * :}, that the test runtime classpath resolves to, such as the jar that {@code + * java-test-fixtures} puts there in place of the main classes directories. PIT mutates + * those the test runtime classpath holds; where the collection is empty, it mutates only the + * {@link #getMainClassesDirs() directories}. + */ + @Internal + public abstract ConfigurableFileCollection getMainArtifacts(); + /** The main source directories, where the report finds the text of a mutated line. */ @Internal public abstract ConfigurableFileCollection getMainSourceDirs(); @@ -154,6 +170,32 @@ public boolean hasTargetClasses() throws IOException { .isEmpty(); } + /** + * Returns the entries of the test runtime classpath that hold the main classes: their + * directories and the artifacts of the project's main variant, whichever the classpath holds. PIT + * mutates a class only where it finds it in one of these entries of the classpath the tests run + * with. + */ + private List mutableCodePaths() { + Set main = new LinkedHashSet<>(getMainClassesDirs().getFiles()); + main.addAll(getMainArtifacts().getFiles()); + return getTestRuntimeClasspath().getFiles().stream() + .filter(main::contains) + .collect(Collectors.toList()); + } + + private String noMainClassesMessage() { + return "Found none of the main classes on the test runtime classpath of " + + getPath() + + ". The classpath holds neither the directories " + + getMainClassesDirs().getFiles() + + " nor the project's own jar resolved through configurations.testRuntimeClasspath, such" + + " as the one java-test-fixtures puts there, so PIT would have no class to mutate. Add the" + + " directories to sourceSets.test.runtimeClasspath, the classpath pitestDiff runs the" + + " tests with under PIT. PIT then mutates the main classes even where the tests load" + + " them from another file, such as a jar added with files(...)."; + } + @TaskAction public void run() throws IOException { Path changedLines = getChangedLinesFile().get().getAsFile().toPath(); @@ -163,12 +205,17 @@ public void run() throws IOException { getFileSystemOperations().delete(spec -> spec.delete(reportDir)); Files.createDirectories(reportDir.toPath()); File log = new File(reportDir, PitestRun.LOG); + List mutableCodePaths = mutableCodePaths(); + // PIT given no code path falls back to a default that also admits the test classes. + if (mutableCodePaths.isEmpty()) { + throw new GradleException(noMainClassesMessage()); + } PitestRun pit = new PitestRun() .targetClasses(ChangedLinesFile.targetClasses(ChangedLinesFile.read(changedLines).keySet())) .reportDir(reportDir) .targetTests(getTargetTests().getOrNull()) - .mutableCodePaths(List.copyOf(getMainClassesDirs().getFiles())) + .mutableCodePaths(mutableCodePaths) .sourceDirs(List.copyOf(getMainSourceDirs().getFiles())) .classPath(List.copyOf(getTestRuntimeClasspath().getFiles())) .jvmArgs(getTestJvmArgs().get()) diff --git a/cribro-gradle-plugin/src/main/resources/io/github/cribrodev/guide.md b/cribro-gradle-plugin/src/main/resources/io/github/cribrodev/guide.md index fbf1af0..27d30c1 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 @@ -147,4 +147,11 @@ it, and it needs an Arcmutate licence file, `arcmutate-licence.txt`, at the repo 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. +- PIT mutates the main classes where `sourceSets.test.runtimeClasspath` holds them: in the main classes directories, or + in an artifact with the project's own capability `:` that `configurations.testRuntimeClasspath` + resolves to, such as the jar `java-test-fixtures` puts there, whatever task builds it. A file added with `files(...)` + is not resolved by the configuration and does not count. Where the classpath holds neither, the task fails with + `Found none of the main classes on the test runtime classpath of `. Add the directories to + `sourceSets.test.runtimeClasspath`. PIT then mutates the main classes even where the tests load them from another + file, such as the `jar` task's archive added with `files(...)`. - Do not run two Gradle builds in the same project at once. diff --git a/cribro-gradle-plugin/src/test/java/io/github/cribrodev/PitestDiffMainClassesTest.java b/cribro-gradle-plugin/src/test/java/io/github/cribrodev/PitestDiffMainClassesTest.java new file mode 100644 index 0000000..1c496b7 --- /dev/null +++ b/cribro-gradle-plugin/src/test/java/io/github/cribrodev/PitestDiffMainClassesTest.java @@ -0,0 +1,264 @@ +/* + * 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 static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import org.gradle.testkit.runner.GradleRunner; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** + * {@code pitestDiff} mutates the main classes where the test runtime classpath holds them: as their + * directories, or as an artifact of the project's main variant, such as the jar Gradle puts there + * in their place in a module that applies {@code java-test-fixtures}, whatever task builds it. + * + *

The builds resolve JUnit from Maven Central, so the tests need the network, as {@link + * KotlinBuildTest} does. + */ +class PitestDiffMainClassesTest { + + /** Drops the main classes directories from the test runtime classpath. */ + private static final String TEST_CLASSPATH_WITHOUT_MAIN = + "sourceSets.test.runtimeClasspath =" + + " files(sourceSets.test.output, configurations.testRuntimeClasspath)\n"; + + private static final String TEST_FIXTURES = "id 'java-library'; id 'java-test-fixtures'"; + + private static final String SURVIVOR = "survived: changed conditional boundary, in max"; + + private static final String NO_MAIN_CLASSES = + "Found none of the main classes on the test runtime classpath of :pitestDiff"; + + /** The main classes directory as the failure message prints it, with the platform separator. */ + private static final String MAIN_CLASSES_DIR = + Path.of("build", "classes", "java", "main").toString(); + + @TempDir Path build; + + /** + * Writes a one-class build whose only test covers one branch of {@code max}, with {@code plugins} + * in its {@code plugins} block and {@code buildScript} at the end of {@code build.gradle}, and + * commits it on top of an empty base, so every line of it is a changed line. + */ + private void writeBuild(String plugins, String buildScript) + throws IOException, InterruptedException { + write( + "settings.gradle", + "plugins { id '" + CribroSettingsPlugin.ID + "' }\nrootProject.name = 'demo'\n"); + write( + "build.gradle", + """ + plugins { %s } + repositories { mavenCentral() } + dependencies { + testImplementation platform('org.junit:junit-bom:5.14.4') + testImplementation 'org.junit.jupiter:junit-jupiter' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' + } + test { useJUnitPlatform() } + """ + .formatted(plugins) + + buildScript); + write( + "src/main/java/demo/Calc.java", + """ + package demo; + + public class Calc { + public static int max(int a, int b) { + if (a > b) { + return a; + } + return b; + } + } + """); + write( + "src/test/java/demo/CalcTest.java", + """ + package demo; + + import static org.junit.jupiter.api.Assertions.assertEquals; + + import org.junit.jupiter.api.Test; + + class CalcTest { + @Test + void maxOfTwoAndOneIsTwo() { + assertEquals(2, Calc.max(2, 1)); + } + } + """); + git("init", "-q", "--initial-branch=main"); + git("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "base"); + git("add", "-A"); + git("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "-m", "change"); + } + + private void write(String path, String text) throws IOException { + Path file = build.resolve(path); + Files.createDirectories(file.getParent()); + Files.writeString(file, text, UTF_8); + } + + private void git(String... arguments) throws IOException, InterruptedException { + List command = new ArrayList<>(); + command.add("git"); + command.addAll(List.of(arguments)); + Process process = + new ProcessBuilder(command).directory(build.toFile()).redirectErrorStream(true).start(); + String output = new String(process.getInputStream().readAllBytes(), UTF_8); + assertEquals(0, process.waitFor(), () -> String.join(" ", command) + "\n" + output); + } + + private GradleRunner pitestDiff() { + return GradleRunner.create() + .withProjectDir(build.toFile()) + .withPluginClasspath() + .withArguments("--quiet", "pitestDiff", "-Pcribro.diffBase=HEAD~1"); + } + + @Test + void theMainClassesDirectoriesAreMutatedWhereTheTestClasspathHoldsThem() throws Exception { + writeBuild("id 'java-library'", ""); + + assertContains(pitestDiff().build().getOutput(), SURVIVOR); + } + + @Test + void theJarTasksArchiveIsMutatedWhereTestFixturesPutItOnTheTestClasspath() throws Exception { + writeBuild(TEST_FIXTURES, ""); + + assertContains(pitestDiff().build().getOutput(), SURVIVOR); + } + + @Test + void theTestFixturesJarIsNotAMainArtifact() throws Exception { + writeBuild( + TEST_FIXTURES, + """ + tasks.register('mainArtifacts') { + def files = tasks.named('pitestDiff').flatMap { it.mainArtifacts.elements } + doLast { println 'main artifacts: ' + files.get()*.asFile*.name.sort() } + } + """); + + String output = + GradleRunner.create() + .withProjectDir(build.toFile()) + .withPluginClasspath() + .withArguments("--quiet", "mainArtifacts") + .build() + .getOutput(); + assertContains(output, "main artifacts: [demo.jar]"); + } + + @Test + void aJarOfAnotherTaskIsMutatedWhereRuntimeElementsPublishesIt() throws Exception { + writeBuild( + TEST_FIXTURES, + """ + def fatJar = tasks.register('fatJar', Jar) { archiveClassifier = 'all'; from sourceSets.main.output } + configurations.runtimeElements.outgoing.artifacts.clear() + configurations.runtimeElements.outgoing.artifact(fatJar) + """); + + assertContains(pitestDiff().build().getOutput(), SURVIVOR); + } + + @Test + void aJarACopyTaskWritesIsMutatedWhereRuntimeElementsPublishesIt() throws Exception { + writeBuild( + TEST_FIXTURES, + """ + def copied = tasks.register('copiedJar', Copy) { from(tasks.named('jar')); into(layout.buildDirectory.dir('copied')) } + configurations.runtimeElements.outgoing.artifacts.clear() + configurations.runtimeElements.outgoing.artifact(layout.buildDirectory.file('copied/demo.jar')) { builtBy copied } + """); + + assertContains(pitestDiff().build().getOutput(), SURVIVOR); + } + + @Test + void aTestClasspathWithoutTheMainClassesFailsTheTask() throws Exception { + writeBuild("id 'java-library'", TEST_CLASSPATH_WITHOUT_MAIN); + + assertNoMainClassesFailure(pitestDiff().buildAndFail().getOutput()); + } + + @Test + void aJarAddedAsAFileWithoutTheDirectoriesFailsTheTask() throws Exception { + writeBuild( + "id 'java-library'", + "sourceSets.test.runtimeClasspath = files(sourceSets.test.output," + + " configurations.testRuntimeClasspath, tasks.named('jar'))\n"); + + assertNoMainClassesFailure(pitestDiff().buildAndFail().getOutput()); + } + + @Test + void theMainClassesAreMutatedWhereTheDirectoriesFollowAJarAddedAsAFile() throws Exception { + writeBuild( + "id 'java-library'", + "sourceSets.test.runtimeClasspath = files(sourceSets.test.output," + + " configurations.testRuntimeClasspath, tasks.named('jar')," + + " sourceSets.main.output.classesDirs)\n"); + + String output = pitestDiff().build().getOutput(); + assertContains(output, SURVIVOR); + assertContains(output, ": 2 killed, "); + } + + @Test + void theJarTasksArchiveIsMutatedWhenTheConfigurationCacheIsReused() throws Exception { + writeBuild(TEST_FIXTURES, ""); + GradleRunner cached = + pitestDiff() + .withArguments( + "pitestDiff", "-Pcribro.diffBase=HEAD~1", "--configuration-cache"); + cached.build(); + + String output = cached.build().getOutput(); + assertContains(output, "Reusing configuration cache."); + assertContains(output, SURVIVOR); + } + + private static void assertNoMainClassesFailure(String output) { + assertContains(output, NO_MAIN_CLASSES + ". The classpath holds neither the directories ["); + assertContains( + output, + MAIN_CLASSES_DIR + + "] nor the project's own jar resolved through configurations.testRuntimeClasspath," + + " such as the one java-test-fixtures puts there,"); + assertContains( + output, + "Add the directories to sourceSets.test.runtimeClasspath, the classpath pitestDiff runs" + + " the tests with under PIT. PIT then mutates the main classes even where the tests" + + " load them from another file, such as a jar added with files(...)."); + } + + private static void assertContains(String output, String expected) { + assertTrue(output.contains(expected), () -> "expected:\n" + expected + "\nin:\n" + output); + } +}