private boolean allTestsFiltered(Runner runner, List<Filter> filters) { LinkedList<Description> queue = new LinkedList<Description>(); queue.add(runner.getDescription()); while (!queue.isEmpty()) { Description description = queue.removeFirst(); queue.addAll(description.getChildren()); boolean run = true; for (Filter filter : filters) { if (!filter.shouldRun(description)) { run = false; break; } } if (run) { return false; } } return true; }
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; }
private static void execute( Class<?> testClass, Notifier notifier, Filter filter ) throws TestSetFailedException { final int classModifiers = testClass.getModifiers(); if ( !isAbstract( classModifiers ) && !isInterface( classModifiers ) ) { Request request = aClass( testClass ); if ( filter != null ) { request = request.filterWith( filter ); } Runner runner = request.getRunner(); if ( countTestsInRunner( runner.getDescription() ) != 0 ) { executeInPlayContext( runner, notifier ); } } }
@Override public void filter(final Filter raw) throws NoTestsRemainException { super.filter(new Filter() { @Override public boolean shouldRun(Description description) { String testDisplay = StringUtils.substringBefore(description.getDisplayName(), " "); if (testDisplay != description.getDisplayName()) { description = Description.createTestDescription(description.getTestClass(), testDisplay); } return raw.shouldRun(description); } @Override public String describe() { return raw.describe(); } }); }
private void assertFilterLeavesTestUnscathed(Class<?> testClass) { Request oneClass = Request.aClass(testClass); Request filtered = oneClass.filterWith(new Filter() { @Override public boolean shouldRun(Description description) { return true; } @Override public String describe() { return "Everything"; } }); int filterCount = filtered.getRunner().testCount(); int coreCount = oneClass.getRunner().testCount(); assertEquals("Counts match up in " + testClass, coreCount, filterCount); }
@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)) { List<TestUnit> filteredUnits = splitIntoFilteredUnits(runner.getDescription()); return filterUnitsByMethod(filteredUnits); } else { return Collections.<TestUnit> singletonList(new AdaptedJUnitTestUnit( clazz, Option.<Filter> none())); } }
private Option<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 Option.some(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 (!executionsInitialized) { 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); } executionsInitialized = true; } }
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 populateDescriptionRunningMap(Description description, Map<Description, Boolean> accumulator, Filter filter) { if(description.isTest()) { Boolean shouldRunStatus = filter.shouldRun(description); accumulator.put(description, shouldRunStatus); return; } List<Description> children = description.getChildren(); for(Description d : children) { populateDescriptionRunningMap(d, accumulator, filter); } }
public Filter getFilter() { return new Filter() { @Override public boolean shouldRun(Description description) { return Boolean.TRUE.equals(context.get(description)); } @Override public String describe() { return "RTest Filter"; } @Override public void apply(Object child) throws NoTestsRemainException { if(child instanceof Filterable) { Filterable filterableChild = (Filterable) child; filterableChild.filter(this); } } }; //return Filter.matchMethodDescription(desiredDescription); /*return new Filter() { @Override public boolean shouldRun(Description description) { return (toRun.contains(description)); } @Override public String describe() { return "RTest methods filter"; } };*/ }
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(); }
/** * The defines the tree of tests that will be run. */ @Override public Description getDescription() { ensureInit(); if (filter != Filter.ALL || sorter != null) { suiteDescription = rebuildDescriptionByFilter(suiteDescription); } return suiteDescription; }
private static boolean filterAppliesToAny(Description d, Filter f) { if (f.shouldRun(d)) { return true; } for (Description c : d.getChildren()) { if (filterAppliesToAny(c, f)) { return true; } } return false; }
/** * Initialise all data members. Needed as a lot of work gets done before * constructor completes. */ private void ensureInit() { if (suiteDescription == null) { suiteDescription = Description.createSuiteDescription(getTestClass().getJavaClass()); descriptions = new IdentityHashMap<>(); checksByMethod = new ConcurrentHashMap<>(); finder = new PotentialAssignmentFinder(getTestClass()); constraints = new ConstraintFinder(getTestClass(), this::reportError); filter = Filter.ALL; } }
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); } } }
/** * Creates a {@link org.junit.experimental.categories.Categories.CategoryFilter} given a * {@link FilterFactoryParams} argument. * * @param params Parameters needed to create the {@link Filter} */ public Filter createFilter(FilterFactoryParams params) throws FilterNotCreatedException { try { return createFilter(parseCategories(params.getArgs())); } catch (ClassNotFoundException e) { throw new FilterNotCreatedException(e); } }
@Override public Runner getRunner() { try { Runner runner = fRequest.getRunner(); fFilter.apply(runner); return runner; } catch (NoTestsRemainException e) { return new ErrorReportingRunner(Filter.class, new Exception(String .format("No tests found matching %s from %s", fFilter .describe(), fRequest.toString()))); } }
/** * Creates a {@link Filter}. * * A filter specification is of the form "package.of.FilterFactory=args-to-filter-factory" or * "package.of.FilterFactory". * * @param filterSpec The filter specification */ public static Filter createFilterFromFilterSpec(Description description, String filterSpec) throws FilterFactory.FilterNotCreatedException { String[] tuple; if (filterSpec.contains("=")) { tuple = filterSpec.split("=", 2); } else { tuple = new String[]{ filterSpec, "" }; } return createFilter(tuple[0], new FilterFactoryParams(tuple[1])); }
/** * Creates a {@link Filter}. * * @param filterFactoryFqcn The fully qualified class name of the {@link FilterFactory} * @param params The arguments to the {@link FilterFactory} */ public static Filter createFilter(String filterFactoryFqcn, FilterFactoryParams params) throws FilterFactory.FilterNotCreatedException { FilterFactory filterFactory = createFilterFactory(filterFactoryFqcn); return filterFactory.createFilter(params); }
@Test public void shouldCreateFilter() throws Exception { FilterFactoryParams params = new FilterFactoryParams( CategoryFilterFactoryStub.class.getName()); Filter filter = categoryFilterFactory.createFilter(params); assertThat(filter, instanceOf(DummyFilter.class)); }
@Test public void filterSingleMethodFromOldTestClass() throws Exception { final Description method = Description.createTestDescription( TwoOldTests.class, "testOne"); Filter filter = Filter.matchMethodDescription(method); JUnit38ClassRunner child = new JUnit38ClassRunner(TwoOldTests.class); child.filter(filter); assertEquals(1, child.testCount()); }
private static Filter notThisMethodName(final String methodName) { return new Filter() { @Override public boolean shouldRun(Description description) { return description.getMethodName() == null || !description.getMethodName().equals(methodName); } @Override public String describe() { return "don't run method name: " + methodName; } }; }
@Test public void testSuiteFiltering() throws Exception { Runner runner = Request.aClass(ExampleSuite.class).getRunner(); Filter filter = notThisMethodName("test1"); try { filter.apply(runner); } catch (NoTestsRemainException e) { return; } fail("Expected 'NoTestsRemainException' due to complete filtering"); }
@Test public void testSuiteFilteringWithUnmodifyableChildList() throws Exception { Runner runner = Request.aClass(ExampleSuiteWithUnmodifyableChildList.class) .getRunner(); Filter filter = notThisMethodName("test1"); try { filter.apply(runner); } catch (NoTestsRemainException e) { return; } fail("Expected 'NoTestsRemainException' due to complete filtering"); }
public FilteredRunner(Class<?> klass) throws Throwable { super(klass); filter(new Filter() { @Override public boolean shouldRun(Description description) { return !description.getDisplayName().contains("skip"); } @Override public String describe() { return "skip methods containing the word 'skip'"; } }); }
@Test(expected = NoTestsRemainException.class) public void filteringAwayEverythingThrowsException() throws NoTestsRemainException { Filterable runner = (Filterable) Request.aClass(OneTimeSetup.class).getRunner(); runner.filter(new Filter() { @Override public boolean shouldRun(Description description) { return false; } @Override public String describe() { return null; } }); }
@Test public void intersectAll() { NamedFilter a = new NamedFilter("a"); assertSame(a, a.intersect(Filter.ALL)); assertSame(a, Filter.ALL.intersect(a)); assertSame(Filter.ALL, Filter.ALL.intersect(Filter.ALL)); }
@Test public void shouldParseFilterArgWithEqualsSyntax() throws Exception { jUnitCommandLineParseResult.parseOptions(new String[]{ "--filter=" + IncludeCategories.class.getName() + "=" + DummyCategory0.class.getName() }); Filter filter = jUnitCommandLineParseResult.getFilter(); assertThat(filter.describe(), startsWith("includes ")); }
@Test public void shouldParseFilterArgInWhichValueIsASeparateArg() throws Exception { jUnitCommandLineParseResult.parseOptions(new String[]{ "--filter", IncludeCategories.class.getName() + "=" + DummyCategory0.class.getName() }); Filter filter = jUnitCommandLineParseResult.getFilter(); assertThat(filter.describe(), startsWith("includes ")); }
@Test public void shouldCreateFilterWithArguments() throws Exception { Filter filter = FilterFactories.createFilterFromFilterSpec( createSuiteDescription(testName.getMethodName()), ExcludeCategories.class.getName() + "=" + DummyCategory.class.getName()); assertThat(filter.describe(), startsWith("excludes ")); }