org.junit.runner.manipulation.Filter Java Examples

The following examples show how to use org.junit.runner.manipulation.Filter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FilterTest.java    From havarunner with MIT License 6 votes vote down vote up
@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);
}
 
Example #2
Source File: RunnerArgsTest.java    From android-test with Apache License 2.0 6 votes vote down vote up
/** 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());
}
 
Example #3
Source File: LambdaTestSuite.java    From lambda-selenium with MIT License 6 votes vote down vote up
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;
}
 
Example #4
Source File: ShardingFiltersTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #5
Source File: ShardingFilterTestCase.java    From bazel with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #6
Source File: JUnitCustomRunnerTestUnitFinder.java    From pitest with Apache License 2.0 6 votes vote down vote up
@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()));
  }
}
 
Example #7
Source File: AdaptedJUnitTestUnitTest.java    From pitest with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #8
Source File: AndFilter.java    From bazel with Apache License 2.0 5 votes vote down vote up
public AndFilter(Filter filter1, Filter filter2) {
  if (filter1 == null || filter2 == null) {
    throw new NullPointerException();
  }
  this.filter1 = filter1;
  this.filter2 = filter2;
}
 
Example #9
Source File: AbstractMultiTestRunner.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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);
}
 
Example #10
Source File: PinpointPluginTestSuite.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #11
Source File: PinpointPluginTestRunner.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
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());
}
 
Example #12
Source File: PinpointPluginTestRunner.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #13
Source File: AbstractMultiTestRunner.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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);
}
 
Example #14
Source File: WycheproofRunner.java    From wycheproof with Apache License 2.0 5 votes vote down vote up
private void addFilter(Filter filter) {
  try {
    filter(filter);
  } catch (NoTestsRemainException ex) {
    System.out.println("No tests remain exception: " + ex);
  }
}
 
Example #15
Source File: ExternalTests.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
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);

}
 
Example #16
Source File: FilterRegistry.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 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();
}
 
Example #17
Source File: AbstractMultiTestRunner.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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);
        }
    }
}
 
Example #18
Source File: AbstractMultiTestRunner.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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);
}
 
Example #19
Source File: TestSuiteModel.java    From bazel with Apache License 2.0 5 votes vote down vote up
private Filter getShardingFilter(Description... topLevelSuites) {
  Collection<Description> tests = new LinkedList<>();
  for (Description suite : topLevelSuites) {
    collectTests(suite, tests);
  }
  shardingEnvironment.touchShardFile();
  return shardingFilters.createShardingFilter(tests);
}
 
Example #20
Source File: TestSuiteModel.java    From bazel with Apache License 2.0 5 votes vote down vote up
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);
  }
}
 
Example #21
Source File: ShardingFilterTestCase.java    From bazel with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #22
Source File: ShardingFilterTestCase.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #23
Source File: ShardingFilterTestCase.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #24
Source File: ShardingFilterTestCase.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * Tests that sharding is stable for the given filters, regardless of the
 * ordering of the descriptions.  This is useful for verifying that sharding
 * works with self-randomizing test suites, and a requirement of all test
 * sharding functions.
 */
protected static void assertShardingIsStable(
    List<Filter> filters, List<Description> descriptions) {
  Map<Filter, List<Description>> run1 = simulateTestRun(filters, descriptions);
  Map<Filter, List<Description>> run2 = simulateTestRun(filters, descriptions);
  assertThat(run2).isEqualTo(run1);

  Map<Filter, List<Description>> randomizedRun1 =
      simulateSelfRandomizingTestRun(filters, descriptions);
  Map<Filter, List<Description>> randomizedRun2 =
      simulateSelfRandomizingTestRun(filters, descriptions);
  assertThat(randomizedRun2).isEqualTo(randomizedRun1);
}
 
Example #25
Source File: ShardingFilterTestCase.java    From bazel with Apache License 2.0 5 votes vote down vote up
private static void addDescriptionForFilterToMap(
    Map<Filter, List<Description>> descriptionsRun, Filter filter, Description description) {
  List<Description> descriptions = descriptionsRun.get(filter);
  if (descriptions == null) {
    descriptions = new ArrayList<>();
    descriptionsRun.put(filter, descriptions);
  }
  descriptions.add(description);
}
 
Example #26
Source File: ShardingFilterTestCase.java    From bazel with Apache License 2.0 5 votes vote down vote up
private static Collection<Description> getAllValuesInMap(Map<Filter, List<Description>> map) {
  Collection<Description> allDescriptions = new ArrayList<>();
  for (List<Description> descriptions : map.values()) {
    allDescriptions.addAll(descriptions);
  }
  return allDescriptions;
}
 
Example #27
Source File: RoundRobinShardingFilterTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
public void testShardingIsBalanced() {
  Map<Filter, List<Description>> run1 = simulateTestRun(FILTERS_1, GENERIC_TEST_DESCRIPTIONS);
  assertThat(run1.get(FILTERS_1.get(0))).hasSize(2);
  assertThat(run1.get(FILTERS_1.get(1))).hasSize(2);
  assertThat(run1.get(FILTERS_1.get(2))).hasSize(2);

  Map<Filter, List<Description>> run2 = simulateTestRun(FILTERS_2, GENERIC_TEST_DESCRIPTIONS);
  assertThat(run2.get(FILTERS_2.get(0))).hasSize(2);
  assertThat(run2.get(FILTERS_2.get(1))).hasSize(2);
  assertThat(run2.get(FILTERS_2.get(2))).hasSize(1);
  assertThat(run2.get(FILTERS_2.get(3))).hasSize(1);
}
 
Example #28
Source File: ShardingFiltersTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateShardingFilter_customStrategy() {
  List<Description> descriptions = ShardingFilterTestCase.createGenericTestCaseDescriptions(6);

  when(mockShardingEnvironment.getShardIndex()).thenReturn(0);
  when(mockShardingEnvironment.getTotalShards()).thenReturn(5);
  when(mockShardingEnvironment.getTestShardingStrategy()).thenReturn(
      "com.google.testing.junit.runner.sharding.ShardingFiltersTest$TestFilterFactory");

  ShardingFilters shardingFilters = new ShardingFilters(mockShardingEnvironment);
  Filter filter = shardingFilters.createShardingFilter(descriptions);

  assertThat(filter.getClass().getCanonicalName())
      .isEqualTo("com.google.testing.junit.runner.sharding.ShardingFiltersTest.TestFilter");
}
 
Example #29
Source File: DataProviderRunnerTest.java    From junit-dataprovider with Apache License 2.0 5 votes vote down vote up
@Test
public void testFilterShould() throws Exception {
    // Given:
    Filter filter = Filter.ALL;

    // When:
    underTest.filter(filter);

    // Then:
    assertThat(underTest.getDescription().getChildren()).isNotEmpty();
}
 
Example #30
Source File: FilterTest.java    From havarunner with MIT License 5 votes vote down vote up
@Test
public void HavaRunner_supports_the_JUnit_filter_API() {
    HavaRunner havaRunner = new HavaRunner(TestClass.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)", TestClass.class.getName());
        }
    });
    run(havaRunner);
    assertTrue(TestClass.filteredTestCalled);
    assertFalse(TestClass.rejectedTestCalled);
}