下面列出了org.junit.runners.Suite#org.junit.runner.manipulation.Filter 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
protected static List<TestRequest> getTestRequests(String folderName, Filter filter) {
List<TestRequest> requests = new ArrayList<>();
getTestClasses(folderName).forEach(testClass -> {
try {
new BlockJUnit4ClassRunner(testClass).getDescription().getChildren()
.forEach(description -> {
if (filter.shouldRun(description)) {
TestRequest request = new TestRequest(description);
request.setTestRunUUID(TestUUID.getTestUUID());
requests.add(request);
}
});
} catch (InitializationError e) {
LOGGER.log(e);
}
});
return requests;
}
/** Test that a custom filter with bundle is created */
@Test
public void testFromBundle_customFilterWithBundle() {
Bundle b = new Bundle();
b.putString(RunnerArgs.ARGUMENT_FILTER, CustomTestFilterTakesBundle.class.getName());
b.putString(CustomTestFilterTakesBundle.class.getName(), "test");
RunnerArgs args =
new RunnerArgs.Builder()
.fromBundle(InstrumentationRegistry.getInstrumentation(), b)
.build();
assertEquals("Mismatch in number of filters created", 1, args.filters.size());
Filter filter = args.filters.get(0);
assertTrue("Filter not of correct type", filter instanceof CustomTestFilterTakesBundle);
CustomTestFilterTakesBundle customTestFilterTakesBundle = (CustomTestFilterTakesBundle) filter;
assertEquals("Filter not of correct type", "test", customTestFilterTakesBundle.getTest());
}
@Override
public List<TestUnit> findTestUnits(final Class<?> clazz) {
final Runner runner = AdaptedJUnitTestUnit.createRunner(clazz);
if (isExcluded(runner) || isNotARunnableTest(runner, clazz.getName()) || !isIncluded(clazz)) {
return Collections.emptyList();
}
if (Filterable.class.isAssignableFrom(runner.getClass())
&& !shouldTreatAsOneUnit(clazz, runner)) {
final List<TestUnit> filteredUnits = splitIntoFilteredUnits(runner.getDescription());
return filterUnitsByMethod(filteredUnits);
} else {
return Collections.<TestUnit> singletonList(new AdaptedJUnitTestUnit(
clazz, Optional.<Filter> empty()));
}
}
private Optional<Filter> createFilter(final Class<?> clazz, final String method) {
final Description d = Description.createTestDescription(clazz, method);
final Filter f = new Filter() {
@Override
public boolean shouldRun(final Description description) {
return d.toString().equals(description.toString());
}
@Override
public String describe() {
return null;
}
};
return Optional.ofNullable(f);
}
/**
* Simulates test sharding with the given filters and test descriptions, for a
* set of test descriptions that is in a different order in every test shard.
*
* @param filters a list of filters, one per test shard
* @param descriptions a list of test descriptions
* @return a mapping from each filter to the descriptions of the tests that would be run
* by the shard associated with that filter.
*/
protected static Map<Filter, List<Description>> simulateSelfRandomizingTestRun(
List<Filter> filters, List<Description> descriptions) {
if (descriptions.isEmpty()) {
return new HashMap<>();
}
Deque<Description> mutatingDescriptions = new LinkedList<>(descriptions);
Map<Filter, List<Description>> descriptionsRun = new HashMap<>();
for (Filter filter : filters) {
// rotate the queue so that each filter gets the descriptions in a different order
mutatingDescriptions.addLast(mutatingDescriptions.pollFirst());
for (Description description : descriptions) {
if (filter.shouldRun(description)) {
addDescriptionForFilterToMap(descriptionsRun, filter, description);
}
}
}
return descriptionsRun;
}
@Test
public void testCreateShardingFilter_defaultStrategy() {
List<Description> descriptions = ShardingFilterTestCase.createGenericTestCaseDescriptions(6);
RoundRobinShardingFilter expectedFilter = new RoundRobinShardingFilter(descriptions, 0, 5);
when(mockShardingEnvironment.getShardIndex()).thenReturn(0);
when(mockShardingEnvironment.getTotalShards()).thenReturn(5);
when(mockShardingEnvironment.getTestShardingStrategy()).thenReturn(null);
ShardingFilters shardingFilters = new ShardingFilters(mockShardingEnvironment,
ShardingFilters.ShardingStrategy.ROUND_ROBIN);
Filter filter = shardingFilters.createShardingFilter(descriptions);
assertThat(filter).isInstanceOf(RoundRobinShardingFilter.class);
RoundRobinShardingFilter shardingFilter = (RoundRobinShardingFilter) filter;
assertThat(shardingFilter.testToShardMap).isEqualTo(expectedFilter.testToShardMap);
assertThat(shardingFilter.shardIndex).isEqualTo(expectedFilter.shardIndex);
assertThat(shardingFilter.totalShards).isEqualTo(expectedFilter.totalShards);
}
@Test
public void HavaRunner_supports_the_JUnit_filter_API_even_when_the_test_contains_scenarios() {
HavaRunner havaRunner = new HavaRunner(TestClassWithScenarios.class);
havaRunner.filter(new Filter() {
public boolean shouldRun(Description description) {
throw new UnsupportedOperationException("HavaRunner should not call this method");
}
public String describe() {
return String.format("Method HavaRunner_should_run_only_this_method(%s)", TestClassWithScenarios.class.getName());
}
});
run(havaRunner);
assertEquals(Sets.newHashSet("first scenario", "second scenario"), TestClassWithScenarios.filteredTestCalledForScenarios);
assertEquals(Sets.newHashSet(), TestClassWithScenarios.rejectedTestCalledForScenarios);
}
private void initExecutions() {
if (executions.isEmpty()) {
try {
Runner descriptionProvider = createRunnerFor(Arrays.asList(target), Collections.<Filter>emptyList());
templateDescription = descriptionProvider.getDescription();
} catch (InitializationError initializationError) {
throw UncheckedException.throwAsUncheckedException(initializationError);
}
createExecutions();
for (Execution execution : executions) {
execution.init(target, templateDescription);
}
}
}
private void runEnabledTests(RunNotifier nested) {
if (enabledTests.isEmpty()) {
return;
}
Runner runner;
try {
runner = createExecutionRunner();
} catch (Throwable t) {
runner = new CannotExecuteRunner(getDisplayName(), target, t);
}
try {
if (!disabledTests.isEmpty()) {
((Filterable) runner).filter(new Filter() {
@Override
public boolean shouldRun(Description description) {
return !disabledTests.contains(description);
}
@Override
public String describe() {
return "disabled tests";
}
});
}
} catch (NoTestsRemainException e) {
return;
}
runner.run(nested);
}
private void initExecutions() {
if (executions.isEmpty()) {
try {
Runner descriptionProvider = createRunnerFor(Arrays.asList(target), Collections.<Filter>emptyList());
templateDescription = descriptionProvider.getDescription();
} catch (InitializationError initializationError) {
throw UncheckedException.throwAsUncheckedException(initializationError);
}
createExecutions();
for (Execution execution : executions) {
execution.init(target, templateDescription);
}
}
}
private void runEnabledTests(RunNotifier nested) {
if (enabledTests.isEmpty()) {
return;
}
Runner runner;
try {
runner = createExecutionRunner();
} catch (Throwable t) {
runner = new CannotExecuteRunner(getDisplayName(), target, t);
}
try {
if (!disabledTests.isEmpty()) {
((Filterable) runner).filter(new Filter() {
@Override
public boolean shouldRun(Description description) {
return !disabledTests.contains(description);
}
@Override
public String describe() {
return "disabled tests";
}
});
}
} catch (NoTestsRemainException e) {
return;
}
runner.run(nested);
}
private void addFilter(Filter filter) {
try {
filter(filter);
} catch (NoTestsRemainException ex) {
System.out.println("No tests remain exception: " + ex);
}
}
/**
* Describes the list of filters.
*
* @param filters
* the filters to describe, must not be {@code null}
* @param title
* the title for the filters, may be {@code null}
* @return
* the description for the given filters, never {@code null}
*/
private String describeFilters(final List<Filter> filters, final String title) {
assert filters != null;
final StringBuilder description = new StringBuilder();
if (!filters.isEmpty()) {
description.append(" (").append(title).append(" filters:");
for (final Filter filter : filters) {
description.append(' ').append(filter.describe());
}
description.append(')');
}
return description.toString();
}
private void initExecutions() {
if (executions.isEmpty()) {
try {
Runner descriptionProvider = createRunnerFor(Arrays.asList(target), Collections.<Filter>emptyList());
templateDescription = descriptionProvider.getDescription();
} catch (InitializationError initializationError) {
throw UncheckedException.throwAsUncheckedException(initializationError);
}
createExecutions();
for (Execution execution : executions) {
execution.init(target, templateDescription);
}
}
}
private void runEnabledTests(RunNotifier nested) {
if (enabledTests.isEmpty()) {
return;
}
Runner runner;
try {
runner = createExecutionRunner();
} catch (Throwable t) {
runner = new CannotExecuteRunner(getDisplayName(), target, t);
}
try {
if (!disabledTests.isEmpty()) {
((Filterable) runner).filter(new Filter() {
@Override
public boolean shouldRun(Description description) {
return !disabledTests.contains(description);
}
@Override
public String describe() {
return "disabled tests";
}
});
}
} catch (NoTestsRemainException e) {
return;
}
runner.run(nested);
}
private void initExecutions() {
if (executions.isEmpty()) {
try {
Runner descriptionProvider = createRunnerFor(Arrays.asList(target), Collections.<Filter>emptyList());
templateDescription = descriptionProvider.getDescription();
} catch (InitializationError initializationError) {
throw UncheckedException.throwAsUncheckedException(initializationError);
}
createExecutions();
for (Execution execution : executions) {
execution.init(target, templateDescription);
}
}
}
private void runEnabledTests(RunNotifier nested) {
if (enabledTests.isEmpty()) {
return;
}
Runner runner;
try {
runner = createExecutionRunner();
} catch (Throwable t) {
runner = new CannotExecuteRunner(getDisplayName(), target, t);
}
try {
if (!disabledTests.isEmpty()) {
((Filterable) runner).filter(new Filter() {
@Override
public boolean shouldRun(Description description) {
return !disabledTests.contains(description);
}
@Override
public String describe() {
return "disabled tests";
}
});
}
} catch (NoTestsRemainException e) {
return;
}
runner.run(nested);
}
private static Request parseRequest(TestClass testClass, Filter filter) throws IOException, ClassNotFoundException {
List<From> froms = groupAnnotations(testClass, From.class, Froms.class);
List<Test> tests = groupAnnotations(testClass, Test.class, Tests.class);
List<Class<?>> classes = new ArrayList<>();
for (From from : froms) {
URL location = from.value().getProtectionDomain().getCodeSource().getLocation();
try (InputStream is = location.openStream(); JarInputStream jis = new JarInputStream(is)) {
while (true) {
JarEntry entry = jis.getNextJarEntry();
if (entry == null) {
break;
} else if (entry.getName().endsWith("Test.class")) {
classes.add(Class.forName(entry.getName().replace(".class", "").replace('/', '.')));
}
}
}
}
for (Test test : tests) {
classes.add(test.value());
}
return Request.classes(classes.stream()
.filter(c -> Modifier.isPublic(c.getModifiers()) && !Modifier.isAbstract(c.getModifiers()))
.filter(c -> !c.getSimpleName().startsWith("Abstract")).toArray(Class[]::new))
.filterWith(filter);
}
public static Filter methodNameContains(final String substring) {
return new Filter() {
@Override
public boolean shouldRun(Description description) {
return description.getDisplayName().contains(substring);
}
@Override
public String describe() {
return null;
}
};
}
public static Filter methodNameContains(final String substring) {
return new Filter() {
@Override
public boolean shouldRun(Description description) {
return description.getDisplayName().contains(substring);
}
@Override
public String describe() {
return null;
}
};
}
private static String createName(final Class<?> clazz,
final Optional<Filter> filter) {
if (filter.isPresent()) {
return filter.get().describe();
} else {
return clazz.getName();
}
}
boolean isAvaiable(Filter filter) {
synchronized (childrenLock) {
List<FrameworkMethod> children = new ArrayList<FrameworkMethod>(getFilteredChildren());
for (FrameworkMethod method : children) {
if (shouldRun(filter, method)) {
return true;
}
}
}
return false;
}
private boolean shouldRun(Filter filter, FrameworkMethod each) {
if (filter.shouldRun(describeChild(each))) {
return true;
}
String testDescribe = PinpointPluginTestUtils.getTestDescribe(each.getMethod());
return testDescribe.equals(filter.describe());
}
private boolean shouldRun(Filter filter, Runner each) {
if (filter.shouldRun(describeChild(each))) {
return true;
}
if (each instanceof PinpointPluginTestRunner) {
return ((PinpointPluginTestRunner) each).isAvaiable(filter);
}
return false;
}
public AndFilter(Filter filter1, Filter filter2) {
if (filter1 == null || filter2 == null) {
throw new NullPointerException();
}
this.filter1 = filter1;
this.filter2 = filter2;
}
private Filter getShardingFilter(Description... topLevelSuites) {
Collection<Description> tests = new LinkedList<>();
for (Description suite : topLevelSuites) {
collectTests(suite, tests);
}
shardingEnvironment.touchShardFile();
return shardingFilters.createShardingFilter(tests);
}
private void addTestSuite(TestSuiteNode parentSuite, Description suiteDescription) {
TestSuiteNode suite = new TestSuiteNode(suiteDescription);
for (Description childDesc : suiteDescription.getChildren()) {
if (childDesc.isTest()) {
addTestCase(suite, childDesc);
} else {
addTestSuite(suite, childDesc);
}
}
// Empty suites are pruned when sharding.
if (shardingFilter == Filter.ALL || !suite.getChildren().isEmpty()) {
parentSuite.addTestSuite(suite);
testsMap.put(suiteDescription, suite);
}
}
protected static final List<Filter> createFilters(List<Description> descriptions, int numShards,
ShardingFilterFactory factory) {
List<Filter> filters = new ArrayList<>();
for (int shardIndex = 0; shardIndex < numShards; shardIndex++) {
filters.add(factory.createFilter(descriptions, shardIndex, numShards));
}
return filters;
}
/**
* Simulates test sharding with the given filters and test descriptions.
*
* @param filters a list of filters, one per test shard
* @param descriptions a list of test descriptions
* @return a mapping from each filter to the descriptions of the tests that would be run
* by the shard associated with that filter.
*/
protected static Map<Filter, List<Description>> simulateTestRun(List<Filter> filters,
List<Description> descriptions) {
Map<Filter, List<Description>> descriptionsRun = new HashMap<>();
for (Filter filter : filters) {
for (Description description : descriptions) {
if (filter.shouldRun(description)) {
addDescriptionForFilterToMap(descriptionsRun, filter, description);
}
}
}
return descriptionsRun;
}
/**
* Tests that the sharding is complete (each test is run at least once) and
* partitioned (each test is run at most once) -- in other words, that
* each test is run exactly once. This is a requirement of all test
* sharding functions.
*/
protected static void assertShardingIsCompleteAndPartitioned(List<Filter> filters,
List<Description> descriptions) {
Map<Filter, List<Description>> run = simulateTestRun(filters, descriptions);
assertThatCollectionContainsExactlyElementsInList(getAllValuesInMap(run), descriptions);
run = simulateSelfRandomizingTestRun(filters, descriptions);
assertThatCollectionContainsExactlyElementsInList(getAllValuesInMap(run), descriptions);
}