List of usage examples for java.lang.reflect Constructor getDeclaringClass
@Override
public Class<T> getDeclaringClass()
From source file:org.eclipse.wb.internal.core.utils.reflect.ReflectionUtils.java
/** * @return the string presentation {@link Constructor} that uses short class names. *//*from w ww . ja v a2 s . c om*/ public static String getShortConstructorString(Constructor<?> constructor) { if (constructor == null) { return "<null-constructor>"; } StringBuilder buffer = new StringBuilder(); buffer.append(getShortName(constructor.getDeclaringClass())); buffer.append('('); // append parameters { Class<?>[] parameters = constructor.getParameterTypes(); for (int i = 0; i < parameters.length; i++) { Class<?> parameterType = parameters[i]; if (i != 0) { buffer.append(','); } buffer.append(getShortName(parameterType)); } } // close buffer.append(')'); return buffer.toString(); }
From source file:hu.bme.mit.sette.common.tasks.TestSuiteRunner.java
private void analyzeOne(Snippet snippet, File[] binaryDirectories) throws Exception { String snippetClassName = snippet.getContainer().getJavaClass().getName(); String snippetMethodName = snippet.getMethod().getName(); String testClassName = snippet.getContainer().getJavaClass().getName() + "_" + snippet.getMethod().getName() + "_Tests"; logger.debug("Snippet: {}#{}()", snippetClassName, snippetMethodName); logger.debug("Tests: {}", testClassName); // create JaCoCo runtime and instrumenter IRuntime runtime = new LoggerRuntime(); Instrumenter instrumenter = new Instrumenter(runtime); // start runtime RuntimeData data = new RuntimeData(); runtime.startup(data);//from w w w.ja va 2 s . co m // create class loader JaCoCoClassLoader classLoader = new JaCoCoClassLoader(binaryDirectories, instrumenter, getSnippetProject().getClassLoader()); // load test class // snippet class and other dependencies will be loaded and instrumented // on the fly Class<?> testClass = classLoader.loadClass(testClassName); TestCase testClassInstance = (TestCase) testClass.newInstance(); // invoke test methods // TODO separate collect and invoke for (Method m : testClass.getDeclaredMethods()) { if (m.isSynthetic()) { // skip synthetic method continue; } if (m.getName().startsWith("test")) { logger.trace("Invoking: " + m.getName()); try { m.invoke(testClassInstance); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof NullPointerException || cause instanceof ArrayIndexOutOfBoundsException || cause instanceof AssertionFailedError) { logger.warn(cause.getClass().getName() + ": " + m.getDeclaringClass().getName() + "." + m.getName()); } else { logger.error("Exception: " + m.getDeclaringClass().getName() + "." + m.getName()); } logger.debug(e.getMessage(), e); } } else { logger.warn("Not test method: {}", m.getName()); } } // collect data ExecutionDataStore executionData = new ExecutionDataStore(); SessionInfoStore sessionInfos = new SessionInfoStore(); data.collect(executionData, sessionInfos, false); runtime.shutdown(); // get classes to analyse // store string to avoid the mess up between the different class loaders Set<String> javaClasses = new HashSet<>(); javaClasses.add(snippetClassName); for (Constructor<?> inclConstructor : snippet.getIncludedConstructors()) { javaClasses.add(inclConstructor.getDeclaringClass().getName()); } for (Method inclMethod : snippet.getIncludedMethods()) { javaClasses.add(inclMethod.getDeclaringClass().getName()); } // TODO inner classes are not handled well enough // TODO anonymous classes can also have anonymous classes -> recursion Set<String> toAdd = new HashSet<>(); for (String javaClass : javaClasses) { int i = 1; while (true) { // guess anonymous classes, like ClassName$1, ClassName$2 etc. try { classLoader.loadClass(javaClass + "$" + i); toAdd.add(javaClass + "$" + i); i++; } catch (ClassNotFoundException e) { // bad guess, no more anonymous classes on this level break; } } } javaClasses.addAll(toAdd); // analyse classes CoverageBuilder coverageBuilder = new CoverageBuilder(); Analyzer analyzer = new Analyzer(executionData, coverageBuilder); for (String javaClassName : javaClasses) { logger.trace("Analysing: {}", javaClassName); analyzer.analyzeClass(classLoader.readBytes(javaClassName), javaClassName); } // TODO remove debug // new File("D:/SETTE/!DUMP/" + getTool().getName()).mkdirs(); // PrintStream out = new PrintStream("D:/SETTE/!DUMP/" // + getTool().getName() + "/" + testClassName + ".out"); Map<String, Triple<TreeSet<Integer>, TreeSet<Integer>, TreeSet<Integer>>> coverageInfo = new HashMap<>(); for (final IClassCoverage cc : coverageBuilder.getClasses()) { String file = cc.getPackageName() + '/' + cc.getSourceFileName(); file = file.replace('\\', '/'); if (!coverageInfo.containsKey(file)) { coverageInfo.put(file, Triple.of(new TreeSet<Integer>(), new TreeSet<Integer>(), new TreeSet<Integer>())); } // out.printf("Coverage of class %s%n", cc.getName()); // // printCounter(out, "instructions", // cc.getInstructionCounter()); // printCounter(out, "branches", cc.getBranchCounter()); // printCounter(out, "lines", cc.getLineCounter()); // printCounter(out, "methods", cc.getMethodCounter()); // printCounter(out, "complexity", cc.getComplexityCounter()); for (int l = cc.getFirstLine(); l <= cc.getLastLine(); l++) { switch (cc.getLine(l).getStatus()) { case ICounter.FULLY_COVERED: coverageInfo.get(file).getLeft().add(l); break; case ICounter.PARTLY_COVERED: coverageInfo.get(file).getMiddle().add(l); break; case ICounter.NOT_COVERED: coverageInfo.get(file).getRight().add(l); break; } } } // create coverage XML SnippetCoverageXml coverageXml = new SnippetCoverageXml(); coverageXml.setToolName(getTool().getName()); coverageXml.setSnippetProjectElement( new SnippetProjectElement(getSnippetProjectSettings().getBaseDirectory().getCanonicalPath())); coverageXml.setSnippetElement( new SnippetElement(snippet.getContainer().getJavaClass().getName(), snippet.getMethod().getName())); coverageXml.setResultType(ResultType.S); for (Entry<String, Triple<TreeSet<Integer>, TreeSet<Integer>, TreeSet<Integer>>> entry : coverageInfo .entrySet()) { TreeSet<Integer> full = entry.getValue().getLeft(); TreeSet<Integer> partial = entry.getValue().getMiddle(); TreeSet<Integer> not = entry.getValue().getRight(); FileCoverageElement fce = new FileCoverageElement(); fce.setName(entry.getKey()); fce.setFullyCoveredLines(StringUtils.join(full, ' ')); fce.setPartiallyCoveredLines(StringUtils.join(partial, ' ')); fce.setNotCoveredLines(StringUtils.join(not, ' ')); coverageXml.getCoverage().add(fce); } coverageXml.validate(); // TODO needs more documentation File coverageFile = RunnerProjectUtils.getSnippetCoverageFile(getRunnerProjectSettings(), snippet); Serializer serializer = new Persister(new AnnotationStrategy(), new Format("<?xml version=\"1.0\" encoding= \"UTF-8\" ?>")); serializer.write(coverageXml, coverageFile); // TODO move HTML generation to another file/phase File htmlFile = RunnerProjectUtils.getSnippetHtmlFile(getRunnerProjectSettings(), snippet); String htmlTitle = getTool().getName() + " - " + snippetClassName + '.' + snippetMethodName + "()"; StringBuilder htmlData = new StringBuilder(); htmlData.append("<!DOCTYPE html>\n"); htmlData.append("<html lang=\"hu\">\n"); htmlData.append("<head>\n"); htmlData.append(" <meta charset=\"utf-8\" />\n"); htmlData.append(" <title>" + htmlTitle + "</title>\n"); htmlData.append(" <style type=\"text/css\">\n"); htmlData.append(" .code { font-family: 'Consolas', monospace; }\n"); htmlData.append(" .code .line { border-bottom: 1px dotted #aaa; white-space: pre; }\n"); htmlData.append(" .code .green { background-color: #CCFFCC; }\n"); htmlData.append(" .code .yellow { background-color: #FFFF99; }\n"); htmlData.append(" .code .red { background-color: #FFCCCC; }\n"); htmlData.append(" .code .line .number {\n"); htmlData.append(" display: inline-block;\n"); htmlData.append(" width:50px;\n"); htmlData.append(" text-align:right;\n"); htmlData.append(" margin-right:5px;\n"); htmlData.append(" }\n"); htmlData.append(" </style>\n"); htmlData.append("</head>\n"); htmlData.append("\n"); htmlData.append("<body>\n"); htmlData.append(" <h1>" + htmlTitle + "</h1>\n"); for (FileCoverageElement fce : coverageXml.getCoverage()) { htmlData.append(" <h2>" + fce.getName() + "</h2>\n"); htmlData.append(" \n"); File src = new File(getSnippetProject().getSettings().getSnippetSourceDirectory(), fce.getName()); List<String> srcLines = FileUtils.readLines(src); SortedSet<Integer> full = linesToSortedSet(fce.getFullyCoveredLines()); SortedSet<Integer> partial = linesToSortedSet(fce.getPartiallyCoveredLines()); SortedSet<Integer> not = linesToSortedSet(fce.getNotCoveredLines()); htmlData.append(" <div class=\"code\">\n"); int i = 1; for (String srcLine : srcLines) { String divClass = getLineDivClass(i, full, partial, not); htmlData.append(" <div class=\"" + divClass + "\"><div class=\"number\">" + i + "</div> " + srcLine + "</div>\n"); i++; } htmlData.append(" </div>\n\n"); } // htmlData.append(" <div class=\"line\"><div class=\"number\">1</div> package samplesnippets;</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">2</div> </div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">3</div> import hu.bme.mit.sette.annotations.SetteIncludeCoverage;</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">4</div> import hu.bme.mit.sette.annotations.SetteNotSnippet;</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">5</div> import hu.bme.mit.sette.annotations.SetteRequiredStatementCoverage;</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">6</div> import hu.bme.mit.sette.annotations.SetteSnippetContainer;</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">7</div> import samplesnippets.inputs.SampleContainer_Inputs;</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">8</div> </div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">9</div> @SetteSnippetContainer(category = "X1",</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">10</div> goal = "Sample // snippet container",</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">11</div> inputFactoryContainer = SampleContainer_Inputs.class)</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">12</div> public final class SampleContainer {</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">13</div> private SampleContainer() {</div>\n"); // htmlData.append(" <div class=\"line red\"><div class=\"number\">14</div> throw new UnsupportedOperationException("Static // class");</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">15</div> }</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">16</div> </div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">17</div> @SetteRequiredStatementCoverage(value = 100)</div>\n"); // htmlData.append(" <div class=\"line green\"><div class=\"number\">18</div> public static boolean snippet(int x) {</div>\n"); // htmlData.append(" <div class=\"line yellow\"><div class=\"number\">19</div> if (20 * x + 2 == 42) {</div>\n"); // htmlData.append(" <div class=\"line green\"><div class=\"number\">20</div> return true;</div>\n"); // htmlData.append(" <div class=\"line green\"><div class=\"number\">21</div> } else {</div>\n"); // htmlData.append(" <div class=\"line green\"><div class=\"number\">22</div> return false;</div>\n"); // htmlData.append(" <div class=\"line green\"><div class=\"number\">23</div> }</div>\n"); // htmlData.append(" <div class=\"line green\"><div class=\"number\">24</div> }</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">25</div> }</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">26</div> </div>\n"); htmlData.append("</body>\n"); htmlData.append("</html>\n"); FileUtils.write(htmlFile, htmlData); }
From source file:org.evosuite.setup.TestClusterGenerator.java
/** * If we try to get deterministic tests, we must not include these * constructors/* w w w .jav a 2 s. c o m*/ * * @param c * @return */ private static boolean isForbiddenNonDeterministicCall(Constructor<?> c) { if (!Properties.REPLACE_CALLS) return false; // Date default constructor uses current time if (c.getDeclaringClass().equals(Date.class)) { if (c.getParameterTypes().length == 0) return true; } // Random without seed parameter is...random if (c.getDeclaringClass().equals(Random.class)) { if (c.getParameterTypes().length == 0) return true; } return false; }
From source file:org.evosuite.setup.TestClusterGenerator.java
public static boolean canUse(Constructor<?> c) { if (c.isSynthetic()) { return false; }//from w w w .ja v a 2s .c om // synthetic constructors are OK if (Modifier.isAbstract(c.getDeclaringClass().getModifiers())) return false; // TODO we could enable some methods from Object, like getClass //if (c.getDeclaringClass().equals(java.lang.Object.class)) // return false;// handled here to avoid printing reasons if (c.getDeclaringClass().equals(java.lang.Thread.class)) return false;// handled here to avoid printing reasons if (c.getDeclaringClass().isAnonymousClass()) return false; if (c.getDeclaringClass().isLocalClass()) { logger.debug("Skipping constructor of local class {}", c.getName()); return false; } if (c.getDeclaringClass().isMemberClass() && !canUse(c.getDeclaringClass())) return false; if (!Properties.USE_DEPRECATED && c.getAnnotation(Deprecated.class) != null) { logger.debug("Skipping deprecated constructor {}", c.getName()); return false; } if (isForbiddenNonDeterministicCall(c)) { return false; } if (Modifier.isPublic(c.getModifiers())) { makeAccessible(c); return true; } // If default access rights, then check if this class is in the same package as the target class if (!Modifier.isPrivate(c.getModifiers())) { // && !Modifier.isProtected(c.getModifiers())) { String packageName = ClassUtils.getPackageName(c.getDeclaringClass()); if (packageName.equals(Properties.CLASS_PREFIX)) { makeAccessible(c); return true; } } return false; }
From source file:org.jgentleframework.reflection.metadata.DefinitionImpl.java
@Override public Class<?> getOwnerClass() { if (isInterpretedOfClass()) { return (Class<?>) this.getKey(); } else if (isInterpretedOfConstructor()) { Constructor<?> constructor = (Constructor<?>) this.getKey(); return constructor.getDeclaringClass(); } else if (isInterpretedOfField()) { Field field = (Field) this.getKey(); return field.getDeclaringClass(); } else if (isInterpretedOfMethod()) { Method method = (Method) this.getKey(); return method.getDeclaringClass(); } else {//from w w w .j ava2s . c o m if (log.isWarnEnabled()) { log.warn("This definition is not interpreted from anything"); } return null; } }
From source file:org.springframework.beans.factory.support.ConstructorResolver.java
protected Constructor<?> getUserDeclaredConstructor(Constructor<?> constructor) { Class<?> declaringClass = constructor.getDeclaringClass(); Class<?> userClass = ClassUtils.getUserClass(declaringClass); if (userClass != declaringClass) { try {//from w ww. j a v a 2 s . c o m return userClass.getDeclaredConstructor(constructor.getParameterTypes()); } catch (NoSuchMethodException ex) { // No equivalent constructor on user class (superclass)... // Let's proceed with the given constructor as we usually would. } } return constructor; }
From source file:com.quirklabs.authorise.ProxyAwareLocalVariableTableParameterNameDiscoverer.java
public String[] getParameterNames(Constructor ctor) { String[] paramNames = this.parameterNamesCache.get(ctor); if (paramNames == null) { try {//from w ww . j av a 2s .co m paramNames = visitConstructor(ctor).getParameterNames(); if (paramNames != null) { this.parameterNamesCache.put(ctor, paramNames); } } catch (IOException ex) { // We couldn't load the class file, which is not fatal as it // simply means this method of discovering parameter names won't work. if (logger.isDebugEnabled()) { logger.debug("IOException whilst attempting to read '.class' file for class [" + ctor.getDeclaringClass().getName() + "] - unable to determine parameter names for constructor: " + ctor, ex); } } } return paramNames; }
From source file:com.gh.bmd.jrt.android.v4.core.LoaderInvocation.java
private RoutineLoaderCallbacks<OUTPUT> createCallbacks(@Nonnull final Context loaderContext, @Nonnull final LoaderManager loaderManager, @Nullable final RoutineLoader<INPUT, OUTPUT> loader, @Nonnull final List<? extends INPUT> inputs, final int loaderId) { final Logger logger = mLogger; final Object[] args = mArgs; final Constructor<? extends ContextInvocation<INPUT, OUTPUT>> constructor = mConstructor; final ContextInvocation<INPUT, OUTPUT> invocation; try {/* www . j a v a 2 s.c o m*/ logger.dbg("creating a new instance of class [%d]: %s", loaderId, constructor.getDeclaringClass()); invocation = constructor.newInstance(args); invocation.onContext(loaderContext.getApplicationContext()); } catch (final RoutineException e) { logger.err(e, "error creating the invocation instance [%d]", loaderId); throw e; } catch (final Throwable t) { logger.err(t, "error creating the invocation instance [%d]", loaderId); throw new InvocationException(t); } final RoutineLoader<INPUT, OUTPUT> callbacksLoader = (loader != null) ? loader : new RoutineLoader<INPUT, OUTPUT>(loaderContext, invocation, args, inputs, mOrderType, logger); return new RoutineLoaderCallbacks<OUTPUT>(loaderManager, callbacksLoader, logger); }
From source file:com.basistech.rosette.apimodel.ModelTest.java
private Object createObject(Constructor ctor) { Object o;//w ww . j a v a2s .c om int argSize = ctor.getParameterTypes().length; Class[] parameterTypes = ctor.getParameterTypes(); Object[] args = new Object[argSize]; for (int i = 0; i < argSize; i++) { try { args[i] = createObjectForType(parameterTypes[i], ctor.getGenericParameterTypes()[i]); } catch (Throwable e) { e.printStackTrace(); fail(String.format("Unable to create object %s %d %s %s", ctor, i, parameterTypes[i], ctor.getGenericParameterTypes()[i])); return null; } } try { o = ctor.newInstance(args); } catch (Throwable t) { if (!Options.class.equals(ctor.getDeclaringClass())) { t.printStackTrace(); fail(String.format("Unable to create object for %s", ctor)); } return null; } return o; }
From source file:org.evosuite.testsuite.SearchStatistics.java
/** {@inheritDoc} */ @Override/*from www. j a v a 2 s .co m*/ public void minimized(Chromosome chromosome) { TestSuiteChromosome best = (TestSuiteChromosome) chromosome; StatisticEntry entry = statistics.get(statistics.size() - 1); entry.tests = best.getTests(); // TODO: Remember which lines were covered // This information is in ExecutionTrace.coverage entry.size_minimized = best.size(); entry.length_minimized = best.totalLengthOfTestCases(); entry.minimized_time = System.currentTimeMillis(); entry.coverage = new HashSet<Integer>(); entry.coveredIntraMethodPairs = 0; entry.coveredInterMethodPairs = 0; entry.coveredIntraClassPairs = 0; entry.coveredParameterPairs = 0; entry.aliasingIntraMethodPairs = 0; entry.aliasingInterMethodPairs = 0; entry.aliasingIntraClassPairs = 0; entry.aliasingParameterPairs = 0; entry.coveredAliasIntraMethodPairs = 0; entry.coveredAliasInterMethodPairs = 0; entry.coveredAliasIntraClassPairs = 0; entry.coveredAliasParameterPairs = 0; // TODO isn't this more or less copy-paste of // BranchCoverageSuiteFitness.getFitness()? // DONE To make this work for other criteria too, it would be perfect if // one // could ask every suite fitness how many goals were covered logger.debug("Calculating coverage of best individual with fitness " + chromosome.getFitness()); Map<Integer, Double> true_distance = new HashMap<Integer, Double>(); Map<Integer, Double> false_distance = new HashMap<Integer, Double>(); Map<Integer, Integer> predicate_count = new HashMap<Integer, Integer>(); Set<String> covered_methods = new HashSet<String>(); Map<String, Set<Class<?>>> implicitTypesOfExceptions = new HashMap<String, Set<Class<?>>>(); Map<String, Set<Class<?>>> explicitTypesOfExceptions = new HashMap<String, Set<Class<?>>>(); Map<TestCase, Map<Integer, Boolean>> isExceptionExplicit = new HashMap<TestCase, Map<Integer, Boolean>>(); Set<DefUseCoverageTestFitness> coveredDUGoals = new HashSet<DefUseCoverageTestFitness>(); if (ArrayUtil.contains(Properties.CRITERION, Properties.Criterion.DEFUSE) || Properties.ANALYSIS_CRITERIA.toUpperCase().contains("DEFUSE")) { for (DefUseCoverageTestFitness goal : DefUseCoverageFactory.getDUGoals()) { if (goal.isInterMethodPair()) entry.numInterMethodPairs++; else if (goal.isIntraClassPair()) entry.numIntraClassPairs++; else if (goal.isParameterGoal()) entry.numParameterPairs++; else entry.numIntraMethodPairs++; if (goal.isAlias()) { if (goal.isInterMethodPair()) entry.aliasingInterMethodPairs++; else if (goal.isIntraClassPair()) entry.aliasingIntraClassPairs++; else if (goal.isParameterGoal()) entry.aliasingParameterPairs++; else entry.aliasingIntraMethodPairs++; } } entry.numDefinitions = DefUsePool.getDefCounter(); entry.numUses = DefUsePool.getUseCounter(); entry.numDefUsePairs = DefUseCoverageFactory.getDUGoals().size(); } logger.debug("Calculating line coverage"); for (TestChromosome test : best.tests) { ExecutionResult result = executeTest(test, entry.className); ExecutionTrace trace = result.getTrace(); entry.coverage.addAll(getCoveredLines(trace, entry.className)); isExceptionExplicit.put(test.getTestCase(), result.explicitExceptions); if (ArrayUtil.contains(Properties.CRITERION, Properties.Criterion.DEFUSE) || Properties.ANALYSIS_CRITERIA.toUpperCase().contains("DEFUSE")) { for (DefUseCoverageTestFitness goal : DefUseCoverageFactory.getDUGoals()) { if (coveredDUGoals.contains(goal)) continue; if (goal.isCovered(result)) { coveredDUGoals.add(goal); if (goal.isInterMethodPair()) { entry.coveredInterMethodPairs++; if (goal.isAlias()) { entry.coveredAliasInterMethodPairs++; } } else if (goal.isIntraClassPair()) { entry.coveredIntraClassPairs++; if (goal.isAlias()) { entry.coveredAliasIntraClassPairs++; } } else if (goal.isParameterGoal()) { entry.coveredParameterPairs++; if (goal.isAlias()) { entry.coveredAliasParameterPairs++; } } else { entry.coveredIntraMethodPairs++; if (goal.isAlias()) { entry.coveredAliasIntraMethodPairs++; } } } } } for (String method : trace.getCoveredMethods()) { if (method.startsWith(Properties.TARGET_CLASS) || method.startsWith(Properties.TARGET_CLASS + '$')) covered_methods.add(method); } // covered_methods.addAll(trace.getCoveredMethods()); for (Entry<Integer, Double> e : trace.getTrueDistances().entrySet()) { if (!predicate_count.containsKey(e.getKey())) predicate_count.put(e.getKey(), 1); else predicate_count.put(e.getKey(), predicate_count.get(e.getKey()) + 1); if (!true_distance.containsKey(e.getKey()) || true_distance.get(e.getKey()) > e.getValue()) { true_distance.put(e.getKey(), e.getValue()); } } for (Entry<Integer, Double> e : trace.getFalseDistances().entrySet()) { if (!predicate_count.containsKey(e.getKey())) predicate_count.put(e.getKey(), 1); else predicate_count.put(e.getKey(), predicate_count.get(e.getKey()) + 1); if (!false_distance.containsKey(e.getKey()) || false_distance.get(e.getKey()) > e.getValue()) { false_distance.put(e.getKey(), e.getValue()); } } } for (TestCase test : entry.results.keySet()) { Map<Integer, Throwable> exceptions = entry.results.get(test); //iterate on the indexes of the statements that resulted in an exception for (Integer i : exceptions.keySet()) { Throwable t = exceptions.get(i); if (t instanceof SecurityException && Properties.SANDBOX) continue; if (i >= test.size()) { // Timeouts are put after the last statement if the process was forcefully killed continue; } String methodName = ""; boolean sutException = false; if (test.getStatement(i) instanceof MethodStatement) { MethodStatement ms = (MethodStatement) test.getStatement(i); Method method = ms.getMethod().getMethod(); methodName = method.getName() + Type.getMethodDescriptor(method); if (method.getDeclaringClass().equals(Properties.getTargetClass())) sutException = true; } else if (test.getStatement(i) instanceof ConstructorStatement) { ConstructorStatement cs = (ConstructorStatement) test.getStatement(i); Constructor<?> constructor = cs.getConstructor().getConstructor(); methodName = "<init>" + Type.getConstructorDescriptor(constructor); if (constructor.getDeclaringClass().equals(Properties.getTargetClass())) sutException = true; } boolean notDeclared = !test.getStatement(i).getDeclaredExceptions().contains(t.getClass()); if (notDeclared && sutException) { /* * we need to distinguish whether it is explicit (ie "throw" in the code, eg for validating * input for pre-condition) or implicit ("likely" a real fault). */ /* * FIXME: need to find a way to calculate it */ boolean isExplicit = isExceptionExplicit.get(test).containsKey(i) && isExceptionExplicit.get(test).get(i); if (isExplicit) { if (!explicitTypesOfExceptions.containsKey(methodName)) explicitTypesOfExceptions.put(methodName, new HashSet<Class<?>>()); explicitTypesOfExceptions.get(methodName).add(t.getClass()); } else { if (!implicitTypesOfExceptions.containsKey(methodName)) implicitTypesOfExceptions.put(methodName, new HashSet<Class<?>>()); implicitTypesOfExceptions.get(methodName).add(t.getClass()); } } } } int num_covered = 0; entry.error_branches = BranchPool.getNumArtificialBranches(); for (Integer key : predicate_count.keySet()) { // logger.info("Key: "+key); double df = true_distance.get(key); double dt = false_distance.get(key); Branch b = BranchPool.getBranch(key); if (!b.getClassName().startsWith(Properties.TARGET_CLASS) && !b.getClassName().startsWith(Properties.TARGET_CLASS + '$')) continue; //if (!b.isInstrumented()) { if (df == 0.0) num_covered++; if (dt == 0.0) num_covered++; //} if (b.isInstrumented()) { // entry.error_branches++; if (df == 0.0) entry.error_branches_covered++; if (dt == 0.0) entry.error_branches_covered++; } } for (String methodName : CFGMethodAdapter.getMethodsPrefix(Properties.TARGET_CLASS)) { boolean allArtificial = true; int splitPoint = methodName.lastIndexOf("."); String cName = methodName.substring(0, splitPoint); String mName = methodName.substring(splitPoint + 1); boolean hasBranches = false; for (Branch b : BranchPool.retrieveBranchesInMethod(cName, mName)) { hasBranches = true; if (!b.isInstrumented()) { allArtificial = false; break; } } if (hasBranches && allArtificial) { entry.error_branchless_methods++; if (covered_methods.contains(methodName)) { entry.error_branchless_methods_covered++; } } } int coveredBranchlessMethods = 0; for (String branchlessMethod : BranchPool.getBranchlessMethodsMemberClasses(Properties.TARGET_CLASS)) { if (covered_methods.contains(branchlessMethod)) coveredBranchlessMethods++; } entry.covered_branches = num_covered; // + covered branchless methods? entry.covered_methods = covered_methods.size(); entry.covered_branchless_methods = coveredBranchlessMethods; //BranchCoverageSuiteFitness f = new BranchCoverageSuiteFitness(); /* if (Properties.CRITERION == Properties.Criterion.DEFUSE || Properties.ANALYSIS_CRITERIA.contains("DefUse")) { entry.coveredIntraMethodPairs = DefUseCoverageSuiteFitness.mostCoveredGoals.get(DefUsePairType.INTRA_METHOD); entry.coveredInterMethodPairs = DefUseCoverageSuiteFitness.mostCoveredGoals.get(DefUsePairType.INTER_METHOD); entry.coveredIntraClassPairs = DefUseCoverageSuiteFitness.mostCoveredGoals.get(DefUsePairType.INTRA_CLASS); entry.coveredParameterPairs = DefUseCoverageSuiteFitness.mostCoveredGoals.get(DefUsePairType.PARAMETER); } */ //System.out.println(covered_methods); // DONE make this work for other criteria too. this will only work for // branch coverage - see searchStarted()/Finished() // entry.total_goals = 2 * entry.total_branches + // entry.branchless_methods; - moved to searchStarted() // entry.covered_goals = num_covered; - moved to searchFinished() // for(String e : CFGMethodAdapter.branchless_methods) { // for (String e : CFGMethodAdapter.methods) { // for (String e : BranchPool.getBranchlessMethods()) { // if (covered_methods.contains(e)) { // logger.info("Covered method: " + e); // entry.covered_goals++; // } else { // logger.info("Method is not covered: " + e); // } /* * logger.debug("Covered methods: " + covered_methods.size() + "/" + * entry.total_methods); for (String method : covered_methods) { * logger.debug("Covered method: " + method); } */ // } String s = calculateCoveredBranchesBitString(best); entry.goalCoverage = s; entry.explicitMethodExceptions = getNumExceptions(explicitTypesOfExceptions); entry.explicitTypeExceptions = getNumClassExceptions(explicitTypesOfExceptions); entry.implicitMethodExceptions = getNumExceptions(implicitTypesOfExceptions); entry.implicitTypeExceptions = getNumClassExceptions(implicitTypesOfExceptions); entry.implicitExceptions = implicitTypesOfExceptions; entry.explicitExceptions = explicitTypesOfExceptions; }