-
Notifications
You must be signed in to change notification settings - Fork 134
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
New checkJUnitDependencies task #837
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
addac0a
New checkJUnitDependencies task
iamdanfox ee46328
README note.
iamdanfox 8022b05
Add generated changelog entries
iamdanfox 082bfda
Trivial logs
iamdanfox 608aadb
Higher quality error messages
iamdanfox 85f649e
Improve errors more
iamdanfox bcda925
Also prompt people to fully exclude old junit when possible
iamdanfox ca240d8
integration tests
iamdanfox ce06878
Re-order
iamdanfox 6d50afb
Merge remote-tracking branch 'origin/develop' into dfox/check-junit4
iamdanfox File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
type: improvement | ||
improvement: | ||
description: A new `checkJUnitDependencies` task detects misconfigured JUnit dependencies | ||
which could result in some tests silently not running. | ||
links: | ||
- https://github.com/palantir/gradle-baseline/pull/837 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
171 changes: 171 additions & 0 deletions
171
gradle-baseline-java/src/main/groovy/com/palantir/baseline/tasks/CheckJUnitDependencies.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,171 @@ | ||
/* | ||
* (c) Copyright 2019 Palantir Technologies Inc. All rights reserved. | ||
* | ||
* 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 com.palantir.baseline.tasks; | ||
|
||
import com.google.common.base.Preconditions; | ||
import com.palantir.baseline.plugins.BaselineTesting; | ||
import java.io.File; | ||
import java.io.IOException; | ||
import java.nio.file.Files; | ||
import java.util.Optional; | ||
import java.util.function.Predicate; | ||
import java.util.stream.Stream; | ||
import org.gradle.api.DefaultTask; | ||
import org.gradle.api.artifacts.ModuleVersionIdentifier; | ||
import org.gradle.api.plugins.JavaPluginConvention; | ||
import org.gradle.api.tasks.SourceSet; | ||
import org.gradle.api.tasks.TaskAction; | ||
import org.gradle.api.tasks.testing.Test; | ||
|
||
public class CheckJUnitDependencies extends DefaultTask { | ||
|
||
public CheckJUnitDependencies() { | ||
setGroup("Verification"); | ||
setDescription("Ensures the correct JUnit4/5 dependencies are present, otherwise tests may silently not run"); | ||
} | ||
|
||
@TaskAction | ||
public final void validateDependencies() { | ||
getProject().getConvention() | ||
.getPlugin(JavaPluginConvention.class) | ||
.getSourceSets() | ||
.forEach(ss -> { | ||
if (ss.getName().equals("main")) { | ||
return; | ||
} | ||
|
||
Optional<Test> maybeTestTask = BaselineTesting.getTestTaskForSourceSet(getProject(), ss); | ||
if (!maybeTestTask.isPresent()) { | ||
// source set doesn't have a test task, e.g. 'schema' | ||
return; | ||
} | ||
Test task = maybeTestTask.get(); | ||
|
||
getProject().getLogger().info( | ||
"Analyzing source set {} with task {}", | ||
ss.getName(), task.getName()); | ||
validateSourceSet(ss, task); | ||
}); | ||
} | ||
|
||
private void validateSourceSet(SourceSet ss, Test task) { | ||
boolean junitJupiterIsPresent = hasDep( | ||
ss.getRuntimeClasspathConfigurationName(), CheckJUnitDependencies::isJunitJupiter); | ||
|
||
// If some testing library happens to provide the junit-jupiter-api, then users might start using the | ||
// org.junit.jupiter.api.Test annotation, but as JUnit4 knows nothing about these, they'll silently not run | ||
// unless the user has wired up the dependency correctly. | ||
if (sourceSetMentionsJUnit5Api(ss)) { | ||
String implementation = ss.getImplementationConfigurationName(); | ||
Preconditions.checkState( | ||
BaselineTesting.useJUnitPlatformEnabled(task), | ||
"Some tests mention JUnit5, but the '" + task.getName() + "' task does not have " | ||
+ "useJUnitPlatform() enabled. This means tests may be silently not running! Please " | ||
+ "add the following:\n\n" | ||
+ " " + implementation + " 'org.junit.jupiter:junit-jupiter'\n"); | ||
} | ||
|
||
// When doing an incremental migration to JUnit5, a project may have some JUnit4 and some JUnit5 tests at the | ||
// same time. It's crucial that they have the vintage engine set up correctly, otherwise tests may silently | ||
// not run! | ||
if (sourceSetMentionsJUnit4(ss)) { | ||
if (BaselineTesting.useJUnitPlatformEnabled(task)) { // people might manually enable this | ||
String testRuntimeOnly = ss.getRuntimeConfigurationName() + "Only"; | ||
Preconditions.checkState( | ||
junitJupiterIsPresent, | ||
"Tests may be silently not running! Some tests still use JUnit4, but Gradle has " | ||
+ "been set to use JUnit Platform. " | ||
+ "To ensure your old JUnit4 tests still run, please add the following:\n\n" | ||
+ " " + testRuntimeOnly + " 'org.junit.jupiter:junit-jupiter'\n\n" | ||
+ "Otherwise they will silently not run."); | ||
|
||
boolean vintageEngineExists = hasDep( | ||
ss.getRuntimeClasspathConfigurationName(), CheckJUnitDependencies::isVintageEngine); | ||
Preconditions.checkState( | ||
vintageEngineExists, | ||
"Tests may be silently not running! Some tests still use JUnit4, but Gradle has " | ||
+ "been set to use JUnit Platform. " | ||
+ "To ensure your old JUnit4 tests still run, please add the following:\n\n" | ||
+ " " + testRuntimeOnly + " 'org.junit.vintage:junit-vintage-engine'\n\n" | ||
+ "Otherwise they will silently not run."); | ||
} else { | ||
Preconditions.checkState( | ||
!junitJupiterIsPresent, | ||
"Tests may be silently not running! Please remove " | ||
+ "'org.junit.jupiter:junit-jupiter' dependency " | ||
+ "because tests use JUnit4 and useJUnitPlatform() is not enabled."); | ||
} | ||
} else { | ||
String compileClasspath = ss.getCompileClasspathConfigurationName(); | ||
boolean compilingAgainstOldJunit = hasDep(compileClasspath, CheckJUnitDependencies::isJunit4); | ||
Preconditions.checkState( | ||
!compilingAgainstOldJunit, | ||
"Extraneous dependency on JUnit4 (no test mentions JUnit4 classes). Please exclude " | ||
+ "this from compilation to ensure developers don't accidentally re-introduce it, e.g.\n\n" | ||
+ " configurations." + compileClasspath + ".exclude module: 'junit'\n\n"); | ||
} | ||
|
||
// sourcesets might also contain Spock classes, but we don't have any special validation for these. | ||
} | ||
|
||
private boolean hasDep(String configurationName, Predicate<ModuleVersionIdentifier> spec) { | ||
return getProject().getConfigurations() | ||
.getByName(configurationName) | ||
.getIncoming() | ||
.getResolutionResult() | ||
.getAllComponents() | ||
.stream() | ||
.anyMatch(component -> spec.test(component.getModuleVersion())); | ||
} | ||
|
||
private boolean sourceSetMentionsJUnit4(SourceSet ss) { | ||
return !ss.getAllSource() | ||
.filter(file -> fileContainsSubstring(file, l -> | ||
l.contains("org.junit.Test") | ||
|| l.contains("org.junit.runner") | ||
|| l.contains("org.junit.ClassRule"))) | ||
.isEmpty(); | ||
} | ||
|
||
private boolean sourceSetMentionsJUnit5Api(SourceSet ss) { | ||
return !ss.getAllSource() | ||
.filter(file -> fileContainsSubstring(file, l -> l.contains("org.junit.jupiter.api."))) | ||
.isEmpty(); | ||
} | ||
|
||
private boolean fileContainsSubstring(File file, Predicate<String> substring) { | ||
try (Stream<String> lines = Files.lines(file.toPath())) { | ||
boolean hit = lines.anyMatch(substring::test); | ||
getProject().getLogger().debug("[{}] {}", hit ? "hit" : "miss", file); | ||
return hit; | ||
} catch (IOException e) { | ||
throw new RuntimeException("Unable to check file " + file, e); | ||
} | ||
} | ||
|
||
private static boolean isJunitJupiter(ModuleVersionIdentifier dep) { | ||
return "org.junit.jupiter".equals(dep.getGroup()) && "junit-jupiter".equals(dep.getName()); | ||
} | ||
|
||
private static boolean isVintageEngine(ModuleVersionIdentifier dep) { | ||
return "org.junit.vintage".equals(dep.getGroup()) && "junit-vintage-engine".equals(dep.getName()); | ||
} | ||
|
||
private static boolean isJunit4(ModuleVersionIdentifier dep) { | ||
return "junit".equals(dep.getGroup()) && "junit".equals(dep.getName()); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This might ding quite a lot of projects, but I think the consistency is probably worth it.