org.pitest.functional.FCollection Java Examples

The following examples show how to use org.pitest.functional.FCollection. 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: CoverageData.java    From pitest with Apache License 2.0 6 votes vote down vote up
private Map<ClassLine, Set<TestInfo>> convertInstructionCoverageToLineCoverageForClass(
    ClassName clazz) {
  final List<Entry<InstructionLocation, Set<TestInfo>>> tests = FCollection.filter(
      this.instructionCoverage.entrySet(), isFor(clazz));

  final Map<ClassLine, Set<TestInfo>> linesToTests = new LinkedHashMap<>(
      0);

  for (final Entry<InstructionLocation, Set<TestInfo>> each : tests) {
    for (final int line : getLinesForBlock(each.getKey().getBlockLocation())) {
      final Set<TestInfo> tis = getLineTestSet(clazz, linesToTests, each, line);
      tis.addAll(each.getValue());
    }
  }

  this.lineCoverage.put(clazz, linesToTests);
  return linesToTests;
}
 
Example #2
Source File: GregorMutater.java    From pitest with Apache License 2.0 6 votes vote down vote up
@Override
public Mutant getMutation(final MutationIdentifier id) {

  final ClassContext context = new ClassContext();
  context.setTargetMutation(Optional.ofNullable(id));

  final Optional<byte[]> bytes = this.byteSource.getBytes(id.getClassName()
      .asJavaName());

  final ClassReader reader = new ClassReader(bytes.get());
  final ClassWriter w = new ComputeClassWriter(this.byteSource,
      this.computeCache, FrameOptions.pickFlags(bytes.get()));
  final MutatingClassVisitor mca = new MutatingClassVisitor(w, context,
      filterMethods(), FCollection.filter(this.mutators,
          isMutatorFor(id)));
  reader.accept(mca, ClassReader.EXPAND_FRAMES);

  final List<MutationDetails> details = context.getMutationDetails(context
      .getTargetMutation().get());

  return new Mutant(details.get(0), w.toByteArray());

}
 
Example #3
Source File: FilterTester.java    From pitest with Apache License 2.0 6 votes vote down vote up
public void assertFiltersMutationsFromMutator(String id, Class<?> clazz) {
  final Sample s = sampleForClass(clazz);
  final GregorMutater mutator = mutateFromClassLoader();
  final List<MutationDetails> mutations = mutator.findMutations(s.className);
  final Collection<MutationDetails> actual = filter(s.clazz, mutations, mutator);

  final SoftAssertions softly = new SoftAssertions();
  checkHasNMutants(1, s, softly, mutations);

  final List<MutationDetails> filteredOut = FCollection.filter(mutations, notIn(actual));

  softly.assertThat(filteredOut).describedAs("No mutants filtered").isNotEmpty();
  softly.assertThat(filteredOut).have(mutatedBy(id));
  softly.assertAll();

}
 
Example #4
Source File: AbstractPitAggregationReportMojo.java    From pitest with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private List<File> getCompiledDirs(final MavenProject project)
    throws Exception {
  final List<String> sourceRoots = new ArrayList<>();
  for (final Object artifactObj : FCollection
      .filter(project.getPluginArtifactMap().values(), new DependencyFilter(
          new PluginServices(this.getClass().getClassLoader())))) {

    final Artifact artifact = (Artifact) artifactObj;
    sourceRoots.add(artifact.getFile().getAbsolutePath());
  }
  return convertToRootDirs(project.getTestClasspathElements(),
      Arrays.asList(project.getBuild().getOutputDirectory(),
          project.getBuild().getTestOutputDirectory()),
      sourceRoots);
}
 
Example #5
Source File: FeatureSelector.java    From pitest with Apache License 2.0 6 votes vote down vote up
public List<T> selectFeatures(List<FeatureSetting> features, Collection<T> filters) {
  final List<T> factories = new ArrayList<>(filters);
  final Map<String, Collection<T>> featureMap = FCollection.bucket(factories, byFeatureName());

  final List<T> active = FCollection.filter(factories, isOnByDefault());

  for ( final FeatureSetting each : features ) {
    final Collection<T> providers = featureMap.get(each.feature());
    if ((providers == null) || providers.isEmpty()) {
      throw new IllegalArgumentException("Pitest and its installed plugins do not recognise the feature " + each.feature());
    }

    if (each.addsFeature()) {
      active.addAll(providers);
    }

    if (each.removesFeature()) {
      active.removeAll(providers);
    }
  }

  return active;
}
 
Example #6
Source File: BasePitMojoTest.java    From pitest with Apache License 2.0 6 votes vote down vote up
@Override
protected void setUp() throws Exception {
  super.setUp();
  MockitoAnnotations.initMocks(this);
  this.classPath = new ArrayList<>(FCollection.map(
      ClassPath.getClassPathElementsAsFiles(), fileToString()));
  when(this.project.getTestClasspathElements()).thenReturn(this.classPath);
  when(this.project.getPackaging()).thenReturn("jar");
  
  final Build build = new Build();
  build.setOutputDirectory("");
  
  when(this.project.getBuild()).thenReturn(build);
  
  when(this.plugins.findToolClasspathPlugins()).thenReturn(
      Collections.emptyList());
  when(this.plugins.findClientClasspathPlugins()).thenReturn(
      Collections.emptyList());
}
 
Example #7
Source File: RunnerSuiteFinder.java    From pitest with Apache License 2.0 6 votes vote down vote up
@Override
public List<Class<?>> apply(final Class<?> a) {
  try {
    final Runner runner = AdaptedJUnitTestUnit.createRunner(a);

    final List<Description> allChildren = new ArrayList<>();
    flattenChildren(allChildren, runner.getDescription());

    final List<Description> suites = FCollection.filter(allChildren,
        Prelude.or(isSuiteMethodRunner(runner), isSuite()));
    final Set<Class<?>> classes = suites.stream().flatMap(descriptionToTestClass()).collect(Collectors.toSet());

    classes.remove(a);
    return new ArrayList<>(classes);
  } catch (final RuntimeException ex) {
    // some runners (looking at you spock) can throw a runtime exception
    // when the getDescription method is called.
    return Collections.emptyList();
  }

}
 
Example #8
Source File: ClassInfo.java    From pitest with Apache License 2.0 5 votes vote down vote up
public ClassInfo(final ClassPointer superClass,
    final ClassPointer outerClass, final ClassInfoBuilder builder) {
  this.superClass = superClass;
  this.outerClass = outerClass;
  this.id = builder.id;
  this.access = builder.access;
  this.codeLines = builder.codeLines;
  this.annotations = FCollection.map(builder.annotations,
      ClassName.stringToClassName());
  this.sourceFile = builder.sourceFile;
  this.classAnnotationValues = builder.classAnnotationValues;
}
 
Example #9
Source File: CoverageDataTest.java    From pitest with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnUniqueTestsForClassWhenSomeTestsCoverClass() {
  this.testee.calculateClassCoverage(makeCoverageResult("foo", "fooTest", 0,
      1));
  this.testee.calculateClassCoverage(makeCoverageResult("foo", "fooTest", 0,
      2));
  this.testee.calculateClassCoverage(makeCoverageResult("foo", "fooTest2", 0,
      2));
  assertEquals(Arrays.asList("fooTest", "fooTest2"), FCollection.map(
      this.testee.getTestsForClass(this.foo), testInfoToString()));
}
 
Example #10
Source File: SmartSourceLocator.java    From pitest with Apache License 2.0 5 votes vote down vote up
public SmartSourceLocator(final Collection<File> roots) {
  final Collection<File> childDirs = FCollection.flatMap(roots,
      collectChildren(0));
  childDirs.addAll(roots);

  final Function<File, SourceLocator> fileToSourceLocator = a -> new DirectorySourceLocator(a);
  this.children = FCollection.map(childDirs, fileToSourceLocator);
}
 
Example #11
Source File: SettingsFactory.java    From pitest with Apache License 2.0 5 votes vote down vote up
private Iterable<MutationResultListenerFactory> findListeners() {
  final Iterable<? extends MutationResultListenerFactory> listeners = this.plugins
      .findListeners();
  final Collection<MutationResultListenerFactory> matches = FCollection
      .filter(listeners, nameMatches(this.options.getOutputFormats()));
  if (matches.size() < this.options.getOutputFormats().size()) {
    throw new PitError("Unknown listener requested in "
        + String.join(",", this.options.getOutputFormats()));
  }
  return matches;
}
 
Example #12
Source File: MutationTestBuilder.java    From pitest with Apache License 2.0 5 votes vote down vote up
public List<MutationAnalysisUnit> createMutationTestUnits(
    final Collection<ClassName> codeClasses) {
  final List<MutationAnalysisUnit> tus = new ArrayList<>();

  final List<MutationDetails> mutations = FCollection.flatMap(codeClasses,
      classToMutations());

  mutations.sort(comparing(MutationDetails::getId));

  final Collection<MutationResult> analysedMutations = this.analyser
      .analyse(mutations);

  final Collection<MutationDetails> needAnalysis = analysedMutations.stream()
      .filter(statusNotKnown())
      .map(resultToDetails())
      .collect(Collectors.toList());

  final List<MutationResult> analysed = FCollection.filter(analysedMutations,
      Prelude.not(statusNotKnown()));

  if (!analysed.isEmpty()) {
    tus.add(makePreAnalysedUnit(analysed));
  }

  if (!needAnalysis.isEmpty()) {
    for (final Collection<MutationDetails> ms : this.grouper.groupMutations(
        codeClasses, needAnalysis)) {
      tus.add(makeUnanalysedUnit(ms));
    }
  }

  tus.sort(new AnalysisPriorityComparator());
  return tus;
}
 
Example #13
Source File: DependencyExtractor.java    From pitest with Apache License 2.0 5 votes vote down vote up
public Collection<String> extractCallDependenciesForPackages(
    final String clazz, final Predicate<String> targetPackages)
        throws IOException {
  final Set<String> allDependencies = extractCallDependencies(clazz,
      new IgnoreCoreClasses());
  return FCollection.filter(allDependencies,
      and(asJVMNamePredicate(targetPackages), notSuppliedClass(clazz)));
}
 
Example #14
Source File: InfiniteLoopFilter.java    From pitest with Apache License 2.0 5 votes vote down vote up
@Override
public Collection<MutationDetails> intercept(
    Collection<MutationDetails> mutations, Mutater m) {
  final Map<Location,Collection<MutationDetails>> buckets = FCollection.bucket(mutations, mutationToLocation());

  final List<MutationDetails> willTimeout = new ArrayList<>();
  for (final Entry<Location, Collection<MutationDetails>> each : buckets.entrySet() ) {
    willTimeout.addAll(findTimeoutMutants(each.getKey(), each.getValue(), m));
  }
  mutations.removeAll(willTimeout);
  return mutations;
}
 
Example #15
Source File: MojoToReportOptionsConverter.java    From pitest with Apache License 2.0 5 votes vote down vote up
public static Collection<String> findOccupiedPackagesIn(File dir) {
  if (dir.exists()) {
    DirectoryClassPathRoot root = new DirectoryClassPathRoot(dir);
    Set<String> occupiedPackages = new HashSet<>();
    FCollection.mapTo(root.classNames(), classToPackageGlob(),
        occupiedPackages);
    return occupiedPackages;
  }
  return Collections.emptyList();
}
 
Example #16
Source File: BasicTestUnitFinder.java    From pitest with Apache License 2.0 5 votes vote down vote up
private InstantiationStrategy findInstantiationStrategy(final Class<?> clazz) {
  final List<InstantiationStrategy> strategies = FCollection.filter(
      this.instantiationStrategies, canInstantiate(clazz));
  if (strategies.isEmpty()) {
    throw new PitError("Cannot instantiate " + clazz);
  } else {
    return strategies.get(0);
  }
}
 
Example #17
Source File: FilterTester.java    From pitest with Apache License 2.0 5 votes vote down vote up
public void assertFiltersMutationAtNLocations(int n, Sample s, GregorMutater mutator) {
  final List<MutationDetails> mutations = mutator.findMutations(s.className);
  final Collection<MutationDetails> actual = filter(s.clazz, mutations, mutator);

  final Set<Loc> originalLocations = new LinkedHashSet<>();
  FCollection.mapTo(mutations, toLocation(s.clazz), originalLocations);

  final Set<Loc> filteredLocations = new LinkedHashSet<>();
  FCollection.mapTo(actual, toLocation(s.clazz), filteredLocations);

  assertThat(filteredLocations)
  .describedAs("Expected to filter %d locations from the %d in %s", n, originalLocations.size(), s.clazz.toString())
  .hasSize(originalLocations.size() - n);

}
 
Example #18
Source File: ScmMojo.java    From pitest with Apache License 2.0 5 votes vote down vote up
private Set<ScmFileStatus> makeStatusSet() {
  if ((this.include == null) || this.include.isEmpty()) {
    return new HashSet<>(Arrays.asList(
        ScmStatus.ADDED.getStatus(), ScmStatus.MODIFIED.getStatus()));
  }
  final Set<ScmFileStatus> s = new HashSet<>();
  FCollection.mapTo(this.include, stringToMavenScmStatus(), s);
  return s;
}
 
Example #19
Source File: EqualsPerformanceShortcutFilter.java    From pitest with Apache License 2.0 5 votes vote down vote up
@Override
public Collection<MutationDetails> intercept(
    Collection<MutationDetails> mutations, Mutater m) {
 final List<MutationDetails> doNotTouch = FCollection.filter(mutations, inEqualsMethod().negate());
 if (doNotTouch.size() != mutations.size()) {
   final List<MutationDetails> inEquals = FCollection.filter(mutations, inEqualsMethod());
   final List<MutationDetails> filtered = filter(inEquals, m);
   doNotTouch.addAll(filtered);
 }
 return doNotTouch;
}
 
Example #20
Source File: DefaultGrouper.java    From pitest with Apache License 2.0 5 votes vote down vote up
@Override
public List<List<MutationDetails>> groupMutations(
    final Collection<ClassName> codeClasses,
    final Collection<MutationDetails> mutations) {
  final Map<ClassName, Collection<MutationDetails>> bucketed = FCollection
      .bucket(mutations, byClass());
  final List<List<MutationDetails>> chunked = new ArrayList<>();
  for (final Collection<MutationDetails> each : bucketed.values()) {
    shrinkToMaximumUnitSize(chunked, each);
  }

  return chunked;
}
 
Example #21
Source File: DefaultGrouper.java    From pitest with Apache License 2.0 5 votes vote down vote up
private void shrinkToMaximumUnitSize(
    final List<List<MutationDetails>> chunked,
    final Collection<MutationDetails> each) {
  if (this.unitSize > 0) {
    for (final List<MutationDetails> ms : FCollection.splitToLength(
        this.unitSize, each)) {
      chunked.add(ms);
    }
  } else {
    chunked.add(new ArrayList<>(each));
  }
}
 
Example #22
Source File: DefaultBuildVerifier.java    From pitest with Apache License 2.0 5 votes vote down vote up
@Override
public void verify(final CodeSource code) {
  final Collection<ClassInfo> codeClasses = FCollection.filter(code.getCode(), isNotSynthetic());

  if (hasMutableCode(codeClasses)) {
    checkAtLeastOneClassHasLineNumbers(codeClasses);
    codeClasses.forEach(throwErrorIfHasNoSourceFile());
  }
}
 
Example #23
Source File: DefaultBuildVerifier.java    From pitest with Apache License 2.0 5 votes vote down vote up
private void checkAtLeastOneClassHasLineNumbers(
    final Collection<ClassInfo> codeClasses) {
  // perform only a weak check for line numbers as
  // some jvm languages are not guaranteed to produce them for all classes
  if (!FCollection.contains(codeClasses, aClassWithLineNumbers())) {
    throw new PitHelpError(Help.NO_LINE_NUMBERS);
  }
}
 
Example #24
Source File: MutationStatisticsPrecursor.java    From pitest with Apache License 2.0 5 votes vote down vote up
public MutationStatistics toStatistics() {
  final Iterable<Score> scores = getScores();
  final long totalMutations = FCollection.fold(addTotals(), 0L, scores);
  final long totalDetected = FCollection
      .fold(addDetectedTotals(), 0L, scores);
  final long totalWithCoverage = FCollection.fold(addCoveredTotals(), 0L, scores);
  return new MutationStatistics(scores, totalMutations, totalDetected, totalWithCoverage,
      this.numberOfTestsRun);
}
 
Example #25
Source File: KotlinInterceptor.java    From pitest-kotlin with Apache License 2.0 5 votes vote down vote up
@Override
public Collection<MutationDetails> intercept(
    Collection<MutationDetails> mutations, Mutater m) {
  if(!isKotlinClass) {
    return mutations;
  }
  return FCollection.filter(mutations, isKotlinJunkMutation(currentClass).negate());
}
 
Example #26
Source File: AnnotatedLineFactory.java    From pitest with Apache License 2.0 5 votes vote down vote up
public List<Line> convert(final Reader source) throws IOException {
  try {
    final InputStreamLineIterable lines = new InputStreamLineIterable(source);
    return FCollection.map(lines, stringToAnnotatedLine());
  } finally {
    source.close();
  }

}
 
Example #27
Source File: CoverageData.java    From pitest with Apache License 2.0 5 votes vote down vote up
public CoverageData(final CodeSource code, final LineMap lm, Map<InstructionLocation, Set<TestInfo>> instructionCoverage) {
  this.instructionCoverage = instructionCoverage;
  this.code = code;
  this.lm = lm;
  this.classesForFile = FCollection.bucket(this.code.getCode(),
      keyFromClassInfo());
}
 
Example #28
Source File: CoverageData.java    From pitest with Apache License 2.0 5 votes vote down vote up
private BigInteger generateCoverageNumber(
    final Map<ClassLine, Set<TestInfo>> coverage) {
  BigInteger coverageNumber = BigInteger.ZERO;
  final Set<ClassName> testClasses = new HashSet<>();
  FCollection.flatMapTo(coverage.values(), testsToClassName(), testClasses);

  for (final ClassInfo each : this.code.getClassInfo(testClasses)) {
    coverageNumber = coverageNumber.add(each.getDeepHash());
  }

  return coverageNumber;
}
 
Example #29
Source File: ClassTree.java    From pitest with Apache License 2.0 5 votes vote down vote up
public List<MethodTree> methods() {
  if (this.lazyMethods != null) {
    return this.lazyMethods;
  }
  this.lazyMethods = FCollection.map(this.rawNode.methods, toTree(name()));
  return this.lazyMethods;
}
 
Example #30
Source File: DefaultCoverageGenerator.java    From pitest with Apache License 2.0 5 votes vote down vote up
private void gatherCoverageData(final Collection<ClassInfo> tests,
    final CoverageData coverage) throws IOException, InterruptedException,
    ExecutionException {

  final List<String> filteredTests = FCollection
      .map(tests, classInfoToName());

  final Consumer<CoverageResult> handler = resultProcessor(coverage);

  final SocketFinder sf = new SocketFinder();
  final ServerSocket socket = sf.getNextAvailableServerSocket();

  final CoverageProcess process = new CoverageProcess(ProcessArgs
      .withClassPath(this.code.getClassPath()).andBaseDir(this.workingDir)
      .andLaunchOptions(this.launchOptions).andStderr(logInfo())
      .andStdout(captureStandardOutIfVerbose()), this.coverageOptions,
      socket, filteredTests, handler);

  process.start();

  final ExitCode exitCode = process.waitToDie();

  if (exitCode == ExitCode.JUNIT_ISSUE) {
    LOG.severe("Error generating coverage. Please check that your classpath contains modern JUnit 4 or PIT test plugin for other test tool "
            + "(JUnit 5, TestNG, ...) is enabled.");
    throw new PitError(
        "Coverage generation minion exited abnormally. Please check the classpath and/or enable test plugin for used test tool.");
  } else if (!exitCode.isOk()) {
    LOG.severe("Coverage generator Minion exited abnormally due to "
        + exitCode);
    throw new PitError("Coverage generation minion exited abnormally!");
  } else {
    LOG.fine("Coverage generator Minion exited ok");
  }
}