org.pitest.classinfo.ClassName Java Examples

The following examples show how to use org.pitest.classinfo.ClassName. 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: LineMapperTest.java    From pitest with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldMapAllLinesWhenMethodContainsThreeMultiLineBlocks()
    throws Exception {
  final Map<BlockLocation, Set<Integer>> actual = analyse(ThreeMultiLineBlocks.class);

  final Location l = Location.location(
      ClassName.fromClass(ThreeMultiLineBlocks.class),
      MethodName.fromString("foo"), "(I)I");

  assertThat(actual.get(BlockLocation.blockLocation(l, 0))).contains(5, 6);
  assertThat(actual.get(BlockLocation.blockLocation(l, 1))).contains(7);
  assertThat(actual.get(BlockLocation.blockLocation(l, 2))).contains(8,9);
  assertThat(actual.get(BlockLocation.blockLocation(l, 3))).contains(10);
  assertThat(actual.get(BlockLocation.blockLocation(l, 4))).contains(12,13);
  assertThat(actual.get(BlockLocation.blockLocation(l, 5))).contains(14);
}
 
Example #2
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 #3
Source File: MutationMetaData.java    From pitest with Apache License 2.0 6 votes vote down vote up
public Collection<ClassMutationResults> toClassResults() {
  this.mutations.sort(comparator());
  final List<ClassMutationResults> cmrs = new ArrayList<>();
  final List<MutationResult> buffer = new ArrayList<>();
  ClassName cn = null;
  for (final MutationResult each : this.mutations) {
    if ((cn != null) && !each.getDetails().getClassName().equals(cn)) {
      cmrs.add(new ClassMutationResults(buffer));
      buffer.clear();
    }
    cn = each.getDetails().getClassName();
    buffer.add(each);
  }
  if (!buffer.isEmpty()) {
    cmrs.add(new ClassMutationResults(buffer));
  }
  return cmrs;

}
 
Example #4
Source File: CoverageProcessSystemTest.java    From pitest with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCalculateCoverageForSmallMethodThatThrowsException()
    throws IOException, InterruptedException, ExecutionException {
  final List<CoverageResult> coveredClasses = runCoverageForTest(TestsClassWithException.class);
  assertThat(coveredClasses).anyMatch(coverageFor(CoveredBeforeExceptionTestee.class));

  final ClassName throwsException = ClassName
      .fromClass(ThrowsExceptionTestee.class);

  assertThat(coveredClasses).anyMatch(coverageFor(BlockLocation.blockLocation(
      Location.location(throwsException, this.foo, "()V"), 0)));

      assertThat(coveredClasses).anyMatch(coverageFor(BlockLocation.blockLocation(
      Location.location(throwsException,
          MethodName.fromString("throwsException"), "()V"), 0)));

}
 
Example #5
Source File: InfiniteForLoopFilterFactoryTest.java    From pitest with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldMatchRealInfiniteLoopFromJodaTimeMutants() {      
  Location l1 = Location.location(ClassName.fromString("org.joda.time.field.BaseDateTimeField")
      , MethodName.fromString("set")
      , "(Lorg/joda/time/ReadablePartial;I[II)[I");
  checkFiltered(ClassName.fromString("BaseDateTimeFieldMutated"),forLocation(l1));
  
  checkNotFiltered(ClassName.fromString("LocalDate"),"withPeriodAdded");
  checkFiltered(ClassName.fromString("LocalDateMutated"),"withPeriodAdded");
  
  checkNotFiltered(ClassName.fromString("MonthDay"),"withPeriodAdded");
  checkFiltered(ClassName.fromString("MonthDayMutated"),"withPeriodAdded");
  
  checkFiltered(ClassName.fromString("BaseChronologyMutated"),"validate");
  checkFiltered(ClassName.fromString("BaseChronologyMutated2"),"set");
  
  Location l = Location.location(ClassName.fromString("org.joda.time.MonthDay")
      , MethodName.fromString("withPeriodAdded")
      , "(Lorg/joda/time/ReadablePeriod;I)Lorg/joda/time/MonthDay;");
  checkFiltered(ClassName.fromString("MonthDayMutated2"),forLocation(l));
}
 
Example #6
Source File: CoverageMinion.java    From pitest with Apache License 2.0 6 votes vote down vote up
private static List<TestUnit> getTestsFromParent(
    final SafeDataInputStream dis, final CoverageOptions paramsFromParent)
    throws IOException {
  final List<ClassName> classes = receiveTestClassesFromParent(dis);
  Collections.sort(classes); // ensure classes loaded in a consistent order

  final Configuration testPlugin = createTestPlugin(paramsFromParent);
  verifyEnvironment(testPlugin);

  final List<TestUnit> tus = discoverTests(testPlugin, classes);

  final DependencyFilter filter = new DependencyFilter(
      new DependencyExtractor(new ClassPathByteArraySource(),
          paramsFromParent.getDependencyAnalysisMaxDistance()),
      paramsFromParent.getFilter());
  final List<TestUnit> filteredTus = filter
      .filterTestsByDependencyAnalysis(tus);

  LOG.info("Dependency analysis reduced number of potential tests by "
      + (tus.size() - filteredTus.size()));
  return filteredTus;

}
 
Example #7
Source File: MutatingClassVisitor.java    From pitest with Apache License 2.0 6 votes vote down vote up
@Override
public MethodVisitor visitMethod(final int access, final String methodName,
    final String methodDescriptor, final String signature,
    final String[] exceptions) {

  final MethodMutationContext methodContext = new MethodMutationContext(
      this.context, Location.location(
          ClassName.fromString(this.context.getClassInfo().getName()),
          MethodName.fromString(methodName), methodDescriptor));

  final MethodVisitor methodVisitor = this.cv.visitMethod(access, methodName,
      methodDescriptor, signature, exceptions);

  final MethodInfo info = new MethodInfo()
  .withOwner(this.context.getClassInfo()).withAccess(access)
  .withMethodName(methodName).withMethodDescriptor(methodDescriptor);

  if (this.filter.test(info)) {
    return this.visitMethodForMutation(methodContext, info, methodVisitor);
  } else {
    return methodVisitor;
  }

}
 
Example #8
Source File: MethodRecordTest.java    From pitest-descartes with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static MutationResult mutation(DetectionStatus status, String mutant) {
    return new MutationResult(
            new MutationDetails(
                    new MutationIdentifier(
                    new Location(
                            ClassName.fromString("AClass"),
                            MethodName.fromString("aMethod"),
                            "()I"),
                            1,
                            mutant),
                    "path/to/file",
                    "Mutation description",
                    1,
                    0),
            new MutationStatusTestPair(1, status, null));
}
 
Example #9
Source File: DefaultCodeHistoryTest.java    From pitest with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldTreatClassesWithModifiedParentAsChanged() {
  final long currentHash = 42;
  final ClassName foo = ClassName.fromString("foo");

  final ClassInfo parent = ClassInfoMother.make("parent");
  final ClassIdentifier currentId = new ClassIdentifier(currentHash, foo);
  final ClassInfo currentFoo = ClassInfoMother.make(currentId, parent);

  final ClassInfo modifiedParent = ClassInfoMother.make(new ClassIdentifier(
      parent.getHash().longValue() + 1, ClassName.fromString("parent")));
  final ClassInfo modifiedFoo = ClassInfoMother.make(currentId,
      modifiedParent);

  setCurrentClassPath(currentFoo);

  this.historicClassPath.put(foo, makeHistory(modifiedFoo));

  assertTrue(this.testee.hasClassChanged(foo));
}
 
Example #10
Source File: IncrementalAnalyserTest.java    From pitest with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldStartPreviousKilledMutationsAtAStatusOfNotStartedWhenTestHasChanged() {
  final MutationDetails md = makeMutation("foo");
  final String killingTest = "fooTest";
  setHistoryForAllMutationsTo(DetectionStatus.KILLED, killingTest);

  final Collection<TestInfo> tests = Collections.singleton(new TestInfo(
          "TEST_CLASS", killingTest, 0, Optional.empty(), 0));
  when(this.coverage.getTestsForClass(any(ClassName.class)))
          .thenReturn(tests);
  when(this.history.hasClassChanged(ClassName.fromString("clazz"))).thenReturn(
          false);
  when(this.history.hasClassChanged(ClassName.fromString("TEST_CLASS")))
          .thenReturn(true);

  final Collection<MutationResult> actual = this.testee.analyse(singletonList(md));

  assertThat(actual, hasItem(withStatus(NOT_STARTED)));
  assertThat(logCatcher.logEntries,
          hasItems(
                  "Incremental analysis set 1 mutations to a status of NOT_STARTED",
                  "Incremental analysis reduced number of mutations by 0"
          ));
}
 
Example #11
Source File: ForEachLoopFilter.java    From pitest with Apache License 2.0 6 votes vote down vote up
private static SequenceQuery<AbstractInsnNode> conditionalAtStart() {
  final Slot<LabelNode> loopStart = Slot.create(LabelNode.class);
  final Slot<LabelNode> loopEnd = Slot.create(LabelNode.class);
  return QueryStart
      .any(AbstractInsnNode.class)
      .zeroOrMore(QueryStart.match(anyInstruction()))
      .then(aMethodCallReturningAnIterator().and(mutationPoint()))
      .then(opCode(Opcodes.ASTORE))
      .then(aLabelNode(loopStart.write()))
      .then(opCode(Opcodes.ALOAD))
      .then(methodCallTo(ClassName.fromString("java/util/Iterator"), "hasNext").and(mutationPoint()))
      .then(aConditionalJump().and(jumpsTo(loopEnd.write())).and(mutationPoint()))
      .then(opCode(Opcodes.ALOAD))
      .then(methodCallTo(ClassName.fromString("java/util/Iterator"), "next").and(mutationPoint()))
      .zeroOrMore(QueryStart.match(anyInstruction()))
      .then(opCode(Opcodes.GOTO).and(jumpsTo(loopStart.read())))
      .then(labelNode(loopEnd.read()))
      .zeroOrMore(QueryStart.match(anyInstruction()));
}
 
Example #12
Source File: InfiniteLoopBaseTest.java    From pitest with Apache License 2.0 6 votes vote down vote up
void checkFiltered(ClassName clazz, Predicate<MethodTree> method) {
  boolean testedSomething = false;
  for (final Compiler each : Compiler.values()) {
    final Optional<MethodTree> mt = parseMethodFromCompiledResource(clazz, each,
        method);
    if (mt.isPresent()) {
      assertThat(testee().infiniteLoopMatcher()
          .matches(mt.get().instructions()))
              .describedAs("With " + each
                  + " compiler did not match as expected " + toString(mt.get()))
              .isTrue();
      testedSomething = true;
    }
  }
  if (!testedSomething) {
    fail("No samples found for test");
  }
}
 
Example #13
Source File: ObjectOutputStreamHistoryStoreTest.java    From pitest with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldRecordAndRetrieveResults() {
    final HierarchicalClassId foo = new HierarchicalClassId(
        new ClassIdentifier(0, ClassName.fromString("foo")), "");
    recordClassPathWithTestee(foo);

    final MutationResult mr = new MutationResult(
        MutationTestResultMother.createDetails("foo"),
        new MutationStatusTestPair(1, DetectionStatus.KILLED, "testName"));

    this.testee.recordResult(mr);

    final Reader reader = new StringReader(this.output.toString());
    this.testee = new ObjectOutputStreamHistoryStore(this.writerFactory,
        Optional.ofNullable(reader));
    this.testee.initialize();
    final Map<MutationIdentifier, MutationStatusTestPair> expected = new HashMap<>();
    expected.put(mr.getDetails().getId(), mr.getStatusTestPair());
    assertEquals(expected, this.testee.getHistoricResults());
}
 
Example #14
Source File: InstructionTrackingMethodVisitorTest.java    From pitest with Apache License 2.0 5 votes vote down vote up
private MethodNode makeTree(final Class<?> clazz, final String name) {
  final ClassReader reader = new ClassReader(this.byteSource.getBytes(
      ClassName.fromClass(clazz).asJavaName()).get());
  final ClassNode tree = new ClassNode();
  reader.accept(tree, 0);
  for (final Object m : tree.methods) {
    final MethodNode mn = (MethodNode) m;
    if (mn.name.equals(name)) {
      return mn;
    }
  }
  throw new RuntimeException("Method " + name + " not found in " + clazz);
}
 
Example #15
Source File: LineMapperTest.java    From pitest with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldIncludeLastLinesConstructorsInBlock() throws Exception {
  final Map<BlockLocation, Set<Integer>> actual = analyse(LastLineOfContructorCheck.class);
  final Location l = Location.location(
      ClassName.fromClass(LastLineOfContructorCheck.class),
      MethodName.fromString("<init>"), "()V");

  assertThat(actual.get(BlockLocation.blockLocation(l, 1))).contains(6);
}
 
Example #16
Source File: MutationMetaDataTest.java    From pitest with Apache License 2.0 5 votes vote down vote up
private MutationResult makeResult(String clazz, String method) {
  final Location location = Location.location(ClassName.fromString(clazz),
      MethodName.fromString(method), "()V");
  final MutationDetails md = aMutationDetail().withId(
      aMutationId().withLocation(location)).build();
  final MutationResult mr = new MutationResult(md,
      MutationStatusTestPair.notAnalysed(0, DetectionStatus.KILLED));
  return mr;
}
 
Example #17
Source File: MutationTestMinion.java    From pitest with Apache License 2.0 5 votes vote down vote up
private static List<TestUnit> findTestsForTestClasses(
    final ClassLoader loader, final Collection<ClassName> testClasses,
    final Configuration pitConfig) {
  final Collection<Class<?>> tcs = testClasses.stream().flatMap(ClassName.nameToClass(loader)).collect(Collectors.toList());
  final FindTestUnits finder = new FindTestUnits(pitConfig);
  return finder.findTestUnitsForAllSuppliedClasses(tcs);
}
 
Example #18
Source File: MutationTestBuilderTest.java    From pitest with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldCreateMultipleTestUnitsWhenUnitSizeIsLessThanNumberOfMutations() {
  makeTesteeWithUnitSizeOf(1);
  when(this.source.createMutations(any(ClassName.class))).thenReturn(
      Arrays.asList(createDetails("foo"), createDetails("foo"),
          createDetails("foo")));
  final List<MutationAnalysisUnit> actual = this.testee
      .createMutationTestUnits(Arrays.asList(ClassName.fromString("foo")));
  assertEquals(3, actual.size());
}
 
Example #19
Source File: MutationTestUnitTest.java    From pitest with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReportWhenMutationsNotCoveredByAnyTest() throws Exception {
  addMutation();
  this.tests.add(ClassName.fromString("foo"));
  final MutationMetaData actual = this.testee.call();
  final MutationResult expected = new MutationResult(this.mutations.get(0),
      MutationStatusTestPair.notAnalysed(0, DetectionStatus.NO_COVERAGE));
  assertThat(actual.getMutations()).contains(expected);
}
 
Example #20
Source File: CoverageDataTest.java    From pitest with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldProvideAccessToClassData() {
  final Collection<ClassName> classes = Arrays.asList(ClassName
      .fromString("foo"));
  this.testee.getClassInfo(classes);
  verify(this.code).getClassInfo(classes);
}
 
Example #21
Source File: EqualsPerformanceShortcutFilterTest.java    From pitest with Apache License 2.0 5 votes vote down vote up
private void assertFiltersNMutations(Class<?> muteee, int n) {
  final List<MutationDetails> mutations = this.mutator
      .findMutations(ClassName.fromClass(muteee));

  this.testee.begin(forClass(muteee));
  final Collection<MutationDetails> actual = this.testee.intercept(mutations,
      this.mutator);
  this.testee.end();

  assertThat(actual).hasSize(mutations.size() - n);
}
 
Example #22
Source File: LineMapperTest.java    From pitest with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldI() throws Exception {
  final Map<BlockLocation, Set<Integer>> actual = analyse(ThreeBlocks2.class);
  final Location l = Location.location(ClassName.fromClass(ThreeBlocks2.class),
      MethodName.fromString("foo"), "(I)I");
  assertThat(actual.get(BlockLocation.blockLocation(l, 0))).containsOnly(108);
  assertThat(actual.get(BlockLocation.blockLocation(l, 1))).containsOnly(109);
  assertThat(actual.get(BlockLocation.blockLocation(l, 2))).containsOnly(111);
}
 
Example #23
Source File: MutationSourceTest.java    From pitest with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldAssignTestsFromPrioritiserToMutant() {
  final List<TestInfo> expected = makeTestInfos(0);
  final List<MutationDetails> mutations = makeMutations("foo");

  when(this.prioritiser.assignTests(any(MutationDetails.class))).thenReturn(
      expected);
  when(this.mutater.findMutations(any(ClassName.class)))
  .thenReturn(mutations);
  final MutationDetails actual = this.testee.createMutations(this.foo)
      .iterator().next();
  assertEquals(expected, actual.getTestsInOrder());
}
 
Example #24
Source File: NameCachingRoot.java    From pitest with Apache License 2.0 5 votes vote down vote up
@Override
public InputStream getData(String name) throws IOException {
  final Collection<String> names = classNames();
  if (!names.contains(ClassName.fromString(name).asJavaName())) {
    return null;
  }
  return this.child.getData(name);
}
 
Example #25
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 #26
Source File: CoverageData.java    From pitest with Apache License 2.0 5 votes vote down vote up
@Override
public BigInteger getCoverageIdForClass(final ClassName clazz) {
  final Map<ClassLine, Set<TestInfo>> coverage = getLineCoverageForClassName(clazz);
  if (coverage.isEmpty()) {
    return BigInteger.ZERO;
  }

  return generateCoverageNumber(coverage);
}
 
Example #27
Source File: MutationDiscoveryTest.java    From pitest with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldFilterMutantsInTryCatchFinallyCompiledWithEcj() {
  this.data.setDetectInlinedCode(true);

  final ClassName clazz = ClassName.fromString("trywithresources/TryCatchFinallyExample_ecj");
  final Collection<MutationDetails> actual = findMutants(clazz);
  assertThat(actual).hasSize(3);
}
 
Example #28
Source File: InfiniteIteratorLoopFilterTest.java    From pitest with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotFilterMutationsInMethodsThatAppearToAlreadyHaveInfiniteLoops() {
  final GregorMutater mutator = createMutator(RemoveIncrementsMutator.REMOVE_INCREMENTS_MUTATOR);
  // our analysis incorrectly identifies some loops as infinite - must skip these
  final List<MutationDetails> mutations = mutator.findMutations(ClassName.fromClass(DontFilterMyAlreadyInfiniteLoop.class));
  assertThat(mutations).hasSize(1);

  this.testee.begin(forClass(DontFilterMyAlreadyInfiniteLoop.class));
  final Collection<MutationDetails> actual = this.testee.intercept(mutations, mutator);
  this.testee.end();

  assertThat(actual).hasSize(1);
}
 
Example #29
Source File: FilterTester.java    From pitest with Apache License 2.0 5 votes vote down vote up
private Sample sampleForClass(Class<?> clazz) {
  final ClassloaderByteArraySource source = ClassloaderByteArraySource.fromContext();
  final Sample s = new Sample();
  s.className = ClassName.fromClass(clazz);
  s.clazz = ClassTree.fromBytes(source.getBytes(clazz.getName()).get());
  s.compiler = "current";
  return s;
}
 
Example #30
Source File: InfiniteIteratorLoopFilter.java    From pitest with Apache License 2.0 5 votes vote down vote up
private static SequenceQuery<AbstractInsnNode> inifniteIteratorLoop() {
  final Slot<LabelNode> loopStart = Slot.create(LabelNode.class);

  return QueryStart
      .any(AbstractInsnNode.class)
      .then(methodCallThatReturns(ClassName.fromString("java/util/Iterator")))
      .then(opCode(Opcodes.ASTORE))
      .zeroOrMore(QueryStart.match(anyInstruction()))
      .then(aJump())
      .then(aLabelNode(loopStart.write()))
      .oneOrMore(doesNotBreakIteratorLoop())
      .then(jumpsTo(loopStart.read()))
      // can't currently deal with loops with conditionals that cause additional jumps back
      .zeroOrMore(QueryStart.match(jumpsTo(loopStart.read()).negate()));
}