Java Code Examples for org.pitest.functional.FCollection

The following examples show how to use org.pitest.functional.FCollection. These examples are extracted from open source projects. 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 Project: pitest   Source File: BasePitMojoTest.java    License: 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 2
Source Project: pitest   Source File: AbstractPitAggregationReportMojo.java    License: 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 3
Source Project: pitest   Source File: CoverageData.java    License: 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 4
Source Project: pitest   Source File: FilterTester.java    License: 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 5
Source Project: pitest   Source File: GregorMutater.java    License: 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 6
Source Project: pitest   Source File: FeatureSelector.java    License: 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 7
Source Project: pitest   Source File: RunnerSuiteFinder.java    License: 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 Project: pitest-kotlin   Source File: KotlinInterceptor.java    License: 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 9
Source Project: pitest   Source File: SmartSourceLocator.java    License: 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 10
Source Project: pitest   Source File: ScmMojo.java    License: 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 11
Source Project: pitest   Source File: SettingsFactory.java    License: 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 Project: pitest   Source File: CompoundInterceptorFactory.java    License: Apache License 2.0 5 votes vote down vote up
public MutationInterceptor createInterceptor(
    ReportOptions data,
    ClassByteArraySource source) {
  final List<MutationInterceptor> interceptors = FCollection.map(this.features.getActiveFeatures(),
      toInterceptor(this.features, data, source));
  return new CompoundMutationInterceptor(interceptors);
}
 
Example 13
Source Project: pitest   Source File: MutationTestBuilder.java    License: 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 14
Source Project: pitest   Source File: DependencyExtractor.java    License: Apache License 2.0 5 votes vote down vote up
public Collection<String> extractCallDependenciesForPackages(
    final String clazz, final Predicate<String> targetPackages,
    final Predicate<DependencyAccess> doNotTraverse) throws IOException {
  final Set<String> allDependencies = extractCallDependencies(clazz,
      doNotTraverse);
  return FCollection.filter(allDependencies, targetPackages);
}
 
Example 15
Source Project: pitest   Source File: CodeSourceAggregator.java    License: Apache License 2.0 5 votes vote down vote up
private Predicate<String> createClassPredicate() {
  final Collection<String> classes = new HashSet<>();
  for (final File buildOutputDirectory : this.compiledCodeDirectories) {
    if (buildOutputDirectory.exists()) {
      final DirectoryClassPathRoot dcRoot = new DirectoryClassPathRoot(buildOutputDirectory);
      classes.addAll(FCollection.map(dcRoot.classNames(), toPredicate()));
    }
  }
  return Prelude.or(FCollection.map(classes, Glob.toGlobPredicate()));
}
 
Example 16
Source Project: pitest   Source File: DependencyExtractor.java    License: 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 17
Source Project: pitest   Source File: InfiniteLoopFilter.java    License: 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 18
Source Project: pitest   Source File: MojoToReportOptionsConverter.java    License: 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 19
Source Project: pitest   Source File: BasicTestUnitFinder.java    License: 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 20
Source Project: pitest   Source File: EqualsPerformanceShortcutFilter.java    License: 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 21
Source Project: pitest   Source File: DefaultGrouper.java    License: 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 22
Source Project: pitest   Source File: DefaultGrouper.java    License: 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 23
Source Project: pitest   Source File: DefaultBuildVerifier.java    License: 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 24
Source Project: pitest   Source File: DefaultBuildVerifier.java    License: 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 25
Source Project: pitest   Source File: MutationStatisticsPrecursor.java    License: 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 26
Source Project: pitest   Source File: CoverageData.java    License: 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 27
Source Project: pitest   Source File: CoverageData.java    License: 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 28
Source Project: pitest   Source File: DefaultCoverageGenerator.java    License: 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");
  }
}
 
Example 29
Source Project: pitest   Source File: ClassTree.java    License: 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 Project: pitest   Source File: AnnotatedLineFactory.java    License: 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();
  }

}