diff --git a/.travis/travis-dhell.sh b/.travis/travis-dhell.sh
index ec83f6fc1..639e607ca 100755
--- a/.travis/travis-dhell.sh
+++ b/.travis/travis-dhell.sh
@@ -4,11 +4,10 @@ DPSOT_VERSION=${1}
cd dspot
git clone https://github.com/STAMP-project/dhell.git
-cd dhell
-java -jar ../target/dspot-${DSPOT_VERSION}-jar-with-dependencies.jar --path-to-properties dhell.dspot --iteration 1 --amplifiers MethodAdd --test eu.stamp_project.examples.dhell.HelloAppTest
+java -jar target/dspot-${DSPOT_VERSION}-jar-with-dependencies.jar --absolute-path-to-project-root dhell/ --iteration 1 --amplifiers MethodDuplicationAmplifier --test eu.stamp_project.examples.dhell.HelloAppTest
-if [ -f dspot-out/eu/stamp_project/examples/dhell/HelloAppTest.java ]; then
+if [ -f target/dspot/output/eu/stamp_project/examples/dhell/HelloAppTest.java ]; then
exit 0
else
exit 1
diff --git a/dspot-maven/pom.xml b/dspot-maven/pom.xml
index c0ef81bf4..fe65c9935 100644
--- a/dspot-maven/pom.xml
+++ b/dspot-maven/pom.xml
@@ -66,7 +66,7 @@
eu.stamp-projectdspot
- ${project.version}
+ 2.2.1
diff --git a/dspot-prettifier/pom.xml b/dspot-prettifier/pom.xml
index 68272477f..c7ffc2938 100644
--- a/dspot-prettifier/pom.xml
+++ b/dspot-prettifier/pom.xml
@@ -73,7 +73,7 @@
eu.stamp-projectdspot
- ${project.version}
+ 2.2.1
diff --git a/dspot/pom.xml b/dspot/pom.xml
index 1e0fc4fe8..b2fd5aa22 100644
--- a/dspot/pom.xml
+++ b/dspot/pom.xml
@@ -121,7 +121,7 @@
org.apache.cxfcxf-common-utilities2.4.1
-
+
@@ -182,6 +182,12 @@
test
+
+ info.picocli
+ picocli
+ 4.0.4
+
+
diff --git a/dspot/src/main/java/eu/stamp_project/Main.java b/dspot/src/main/java/eu/stamp_project/Main.java
index 35f28eba3..18bc3184c 100644
--- a/dspot/src/main/java/eu/stamp_project/Main.java
+++ b/dspot/src/main/java/eu/stamp_project/Main.java
@@ -1,103 +1,254 @@
package eu.stamp_project;
+import eu.stamp_project.automaticbuilder.AutomaticBuilder;
import eu.stamp_project.automaticbuilder.maven.DSpotPOMCreator;
+import eu.stamp_project.dspot.amplifier.Amplifier;
+import eu.stamp_project.dspot.assertiongenerator.assertiongenerator.AssertionGeneratorUtils;
import eu.stamp_project.dspot.input_ampl_distributor.InputAmplDistributor;
-import eu.stamp_project.utils.collector.CollectorConfig;
+import eu.stamp_project.dspot.selector.TestSelector;
+import eu.stamp_project.test_framework.TestFramework;
+import eu.stamp_project.utils.*;
+import eu.stamp_project.utils.collector.Collector;
import eu.stamp_project.dspot.DSpot;
+import eu.stamp_project.utils.collector.CollectorFactory;
import eu.stamp_project.utils.compilation.DSpotCompiler;
-import eu.stamp_project.utils.options.JSAPOptions;
+import eu.stamp_project.utils.compilation.TestCompiler;
+import eu.stamp_project.utils.execution.TestRunner;
+import eu.stamp_project.utils.options.AmplifierEnum;
+import eu.stamp_project.utils.options.check.Checker;
+import eu.stamp_project.utils.options.check.InputErrorException;
import eu.stamp_project.utils.report.output.Output;
import eu.stamp_project.utils.program.InputConfiguration;
-import eu.stamp_project.utils.RandomHelper;
import eu.stamp_project.utils.report.GlobalReport;
import eu.stamp_project.utils.report.error.ErrorReportImpl;
import eu.stamp_project.utils.report.output.OutputReportImpl;
import eu.stamp_project.utils.report.output.selector.TestSelectorReportImpl;
+import eu.stamp_project.utils.smtp.EmailSender;
import eu.stamp_project.utils.test_finder.TestFinder;
import org.apache.commons.io.FileUtils;
+import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import picocli.CommandLine;
import spoon.reflect.declaration.CtType;
+import spoon.reflect.factory.Factory;
import java.io.File;
import java.io.IOException;
+import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
+import java.util.Objects;
import java.util.stream.Collectors;
+import static eu.stamp_project.utils.AmplificationHelper.PATH_SEPARATOR;
+
/**
* Created by Benjamin DANGLOT benjamin.danglot@inria.fr on 2/9/17
*/
public class Main {
- public static final GlobalReport GLOBAL_REPORT =
- new GlobalReport(new OutputReportImpl(), new ErrorReportImpl(), new TestSelectorReportImpl());
-
- private static final Logger LOGGER = LoggerFactory.getLogger(Main.class);
-
- public static void main(String[] args) {
- try {
- FileUtils.forceDelete(new File("target/dspot/"));
- } catch (Exception ignored) {
-
- }
- JSAPOptions.parse(args);
- run();
- }
-
- public static void run() {
- RandomHelper.setSeedRandom(InputConfiguration.get().getSeed());
- createOutputDirectories();
- final long startTime = System.currentTimeMillis();
-
- final TestFinder testFinder = new TestFinder(
- Arrays.stream(InputConfiguration.get().getExcludedClasses().split(",")).collect(Collectors.toList()),
- Arrays.stream(InputConfiguration.get().getExcludedTestCases().split(",")).collect(Collectors.toList())
- );
- final DSpotCompiler compiler = DSpotCompiler.createDSpotCompiler(
- InputConfiguration.get(),
- InputConfiguration.get().getDependencies()
- );
- InputConfiguration.get().setFactory(compiler.getLauncher().getFactory());
-
- final List> testClassesToBeAmplified = testFinder.findTestClasses(InputConfiguration.get().getTestClasses());
- final List testMethodsToBeAmplifiedNames = InputConfiguration.get().getTestCases();
- final InputAmplDistributor inputAmplDistributor = InputConfiguration.get().getBudgetizer().getInputAmplDistributor();
- Output output = new Output(InputConfiguration.get().getAbsolutePathToProjectRoot(), InputConfiguration.get().getOutputDirectory());
- final DSpot dspot = new DSpot(
- testFinder,
- compiler,
- InputConfiguration.get().getSelector(),
- inputAmplDistributor,
- output,
- InputConfiguration.get().getNbIteration(),
- InputConfiguration.get().shouldGenerateAmplifiedTestClass()
- );
-
- final List> amplifiedTestClasses = dspot.amplify(testClassesToBeAmplified, testMethodsToBeAmplifiedNames);
- LOGGER.info("Amplification {}.", amplifiedTestClasses.isEmpty() ? "failed" : "succeed");
- final long elapsedTime = System.currentTimeMillis() - startTime;
- LOGGER.info("Elapsed time {} ms", elapsedTime);
- // global report handling
- Main.GLOBAL_REPORT.output();
- Main.GLOBAL_REPORT.reset();
- DSpotPOMCreator.delete();
- // Send info collected.
- CollectorConfig.getInstance().getInformationCollector().sendInfo();
- }
-
- public static void createOutputDirectories() {
- final File outputDirectory = new File(InputConfiguration.get().getOutputDirectory());
- try {
- if (InputConfiguration.get().shouldClean() && outputDirectory.exists()) {
- FileUtils.forceDelete(outputDirectory);
- }
- if (!outputDirectory.exists()) {
- FileUtils.forceMkdir(outputDirectory);
- }
- } catch (IOException ignored) {
- // ignored
- }
- }
+ public static final GlobalReport GLOBAL_REPORT =
+ new GlobalReport(new OutputReportImpl(), new ErrorReportImpl(), new TestSelectorReportImpl());
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(Main.class);
+
+ public static boolean verbose;
+
+ public static void main(String[] args) {
+ InputConfiguration inputConfiguration = new InputConfiguration();
+ final CommandLine commandLine = new CommandLine(inputConfiguration);
+ try {
+ commandLine.parseArgs(args);
+ } catch (Exception e) {
+ e.printStackTrace();
+ commandLine.usage(System.err);
+ return;
+ }
+ if (commandLine.isUsageHelpRequested()) {
+ commandLine.usage(System.out);
+ return;
+ }
+ if (commandLine.isVersionHelpRequested()) {
+ commandLine.printVersionHelp(System.out);
+ return;
+ }
+ if (inputConfiguration.shouldRunExample()) {
+ inputConfiguration.configureExample();
+ }
+ try {
+ Checker.preChecking(inputConfiguration);
+ } catch (InputErrorException e) {
+ e.printStackTrace();
+ commandLine.usage(System.err);
+ return;
+ }
+ Main.verbose = inputConfiguration.isVerbose();
+ run(inputConfiguration);
+ }
+
+ public static void run(InputConfiguration inputConfiguration) {
+ final long startTime = System.currentTimeMillis();
+ final TestFinder testFinder = new TestFinder(
+ Arrays.stream(inputConfiguration.getExcludedClasses().split(",")).collect(Collectors.toList()),
+ Arrays.stream(inputConfiguration.getExcludedTestCases().split(",")).collect(Collectors.toList())
+ );
+ final AutomaticBuilder automaticBuilder = inputConfiguration.getBuilderEnum().getAutomaticBuilder(inputConfiguration);
+ final String dependencies = completeDependencies(inputConfiguration, automaticBuilder);
+ final DSpotCompiler compiler = DSpotCompiler.createDSpotCompiler(
+ inputConfiguration,
+ dependencies
+ );
+ initHelpers(inputConfiguration, compiler.getLauncher().getFactory());
+ inputConfiguration.setFactory(compiler.getLauncher().getFactory());
+ final EmailSender emailSender = new EmailSender(
+ inputConfiguration.getSmtpUsername(),
+ inputConfiguration.getSmtpPassword(),
+ inputConfiguration.getSmtpHost(),
+ inputConfiguration.getSmtpPort(),
+ inputConfiguration.isSmtpAuth(),
+ inputConfiguration.getSmtpTls()
+ );
+ final Collector collector = CollectorFactory.build(inputConfiguration, emailSender);
+ collector.reportInitInformation(
+ inputConfiguration.getAmplifiers(),
+ inputConfiguration.getSelector(),
+ inputConfiguration.getNbIteration(),
+ inputConfiguration.isGregorMode(),
+ !inputConfiguration.isGregorMode(),
+ inputConfiguration.getNumberParallelExecutionProcessors()
+ );
+ final List> testClassesToBeAmplified = testFinder.findTestClasses(inputConfiguration.getTestClasses());
+ final List testMethodsToBeAmplifiedNames = inputConfiguration.getTestCases();
+ final TestSelector testSelector = inputConfiguration.getSelector().buildSelector(automaticBuilder, inputConfiguration);
+ final List amplifiers = inputConfiguration
+ .getAmplifiers()
+ .stream()
+ .map(AmplifierEnum::getAmplifier)
+ .filter(Objects::nonNull)
+ .collect(Collectors.toList());
+ final InputAmplDistributor inputAmplDistributor = inputConfiguration
+ .getInputAmplDistributor()
+ .getInputAmplDistributor(inputConfiguration.getMaxTestAmplified(), amplifiers);
+ final Output output = new Output(
+ inputConfiguration.getAbsolutePathToProjectRoot(),
+ inputConfiguration.getOutputDirectory(),
+ collector
+
+ );
+ final DSpot dspot = new DSpot(
+ inputConfiguration.getDelta(),
+ testFinder,
+ compiler,
+ testSelector,
+ inputAmplDistributor,
+ output,
+ inputConfiguration.getNbIteration(),
+ inputConfiguration.shouldGenerateAmplifiedTestClass(),
+ automaticBuilder
+ );
+
+ Checker.postChecking(inputConfiguration);
+
+ // starting amplification
+ final List> amplifiedTestClasses = dspot.amplify(testClassesToBeAmplified, testMethodsToBeAmplifiedNames);
+ LOGGER.info("Amplification {}.", amplifiedTestClasses.isEmpty() ? "failed" : "succeed");
+ final long elapsedTime = System.currentTimeMillis() - startTime;
+ LOGGER.info("Elapsed time {} ms", elapsedTime);
+ // global report handling
+ Main.GLOBAL_REPORT.output(inputConfiguration.getOutputDirectory());
+ DSpotCache.reset();
+ Main.GLOBAL_REPORT.reset();
+ AmplificationHelper.reset();
+ DSpotPOMCreator.delete();
+ // Send info collected.
+ collector.sendInfo();
+ }
+
+ private static void initHelpers(InputConfiguration configuration, Factory factory){
+ TestFramework.init(factory);
+ AmplificationHelper.init(
+ configuration.getTimeOutInMs(),
+ configuration.shouldGenerateAmplifiedTestClass(),
+ configuration.shouldKeepOriginalTestMethods()
+ );
+ RandomHelper.setSeedRandom(configuration.getSeed());
+ createOutputDirectories(configuration);
+ DSpotCache.init(configuration.getCacheSize());
+ TestCompiler.init(
+ configuration.getNumberParallelExecutionProcessors(),
+ configuration.shouldExecuteTestsInParallel(),
+ configuration.getAbsolutePathToProjectRoot(),
+ configuration.getClasspathClassesProject(),
+ configuration.getTimeOutInMs()
+ );
+ DSpotUtils.init(
+ configuration.withComment(),
+ configuration.getOutputDirectory(),
+ configuration.getFullClassPathWithExtraDependencies(),
+ configuration.getAbsolutePathToProjectRoot()
+ );
+ initSystemProperties(configuration.getSystemProperties());
+ AssertionGeneratorUtils.init(configuration.shouldAllowPathInAssertion());
+ CloneHelper.init(configuration.shouldExecuteTestsInParallel());
+ TestRunner.init(
+ configuration.getAbsolutePathToProjectRoot(),
+ configuration.getPreGoalsTestExecution(),
+ configuration.shouldUseMavenToExecuteTest()
+ );
+ }
+
+ private static void initSystemProperties(String systemProperties) {
+ if (!systemProperties.isEmpty()) {
+ Arrays.stream(systemProperties.split(","))
+ .forEach(systemProperty -> {
+ String[] keyValueInArray = systemProperty.split("=");
+ System.getProperties().put(keyValueInArray[0], keyValueInArray[1]);
+ });
+ }
+ }
+
+ public static String completeDependencies(InputConfiguration configuration,
+ AutomaticBuilder automaticBuilder) {
+ String dependencies = configuration.getDependencies();
+ final String additionalClasspathElements = configuration.getAdditionalClasspathElements();
+ final String absolutePathToProjectRoot = configuration.getAbsolutePathToProjectRoot();
+ if (dependencies.isEmpty()) {
+ dependencies = automaticBuilder.compileAndBuildClasspath();
+ configuration.setDependencies(dependencies);
+ }
+// TODO checks this. Since we support different Test Support, we may not need to add artificially junit in the classpath
+ if (!dependencies.contains("junit" + File.separator + "junit" + File.separator + "4")) {
+ dependencies = Test.class
+ .getProtectionDomain()
+ .getCodeSource()
+ .getLocation()
+ .getFile() +
+ AmplificationHelper.PATH_SEPARATOR + dependencies;
+ }
+ if (!additionalClasspathElements.isEmpty()) {
+ String pathToAdditionalClasspathElements = additionalClasspathElements;
+ if (!Paths.get(additionalClasspathElements).isAbsolute()) {
+ pathToAdditionalClasspathElements =
+ DSpotUtils.shouldAddSeparator.apply(absolutePathToProjectRoot + additionalClasspathElements);
+ }
+ dependencies += PATH_SEPARATOR + pathToAdditionalClasspathElements;
+ }
+ return dependencies;
+ }
+
+ public static void createOutputDirectories(InputConfiguration configuration) {
+ final File outputDirectory = new File(configuration.getOutputDirectory());
+ try {
+ if (configuration.shouldClean() && outputDirectory.exists()) {
+ FileUtils.forceDelete(outputDirectory);
+ }
+ if (!outputDirectory.exists()) {
+ FileUtils.forceMkdir(outputDirectory);
+ }
+ } catch (IOException ignored) {
+ // ignored
+ }
+ }
}
\ No newline at end of file
diff --git a/dspot/src/main/java/eu/stamp_project/automaticbuilder/AutomaticBuilder.java b/dspot/src/main/java/eu/stamp_project/automaticbuilder/AutomaticBuilder.java
index 98d40f60a..39744fdc7 100644
--- a/dspot/src/main/java/eu/stamp_project/automaticbuilder/AutomaticBuilder.java
+++ b/dspot/src/main/java/eu/stamp_project/automaticbuilder/AutomaticBuilder.java
@@ -9,6 +9,8 @@
*/
public interface AutomaticBuilder {
+ void setAbsolutePathToProjectRoot(String absolutePathToProjectRoot);
+
String compileAndBuildClasspath();
void compile();
diff --git a/dspot/src/main/java/eu/stamp_project/automaticbuilder/AutomaticBuilderFactory.java b/dspot/src/main/java/eu/stamp_project/automaticbuilder/AutomaticBuilderFactory.java
deleted file mode 100644
index 96d9efcc0..000000000
--- a/dspot/src/main/java/eu/stamp_project/automaticbuilder/AutomaticBuilderFactory.java
+++ /dev/null
@@ -1,37 +0,0 @@
-package eu.stamp_project.automaticbuilder;
-
-
-import eu.stamp_project.automaticbuilder.gradle.GradleAutomaticBuilder;
-import eu.stamp_project.automaticbuilder.maven.MavenAutomaticBuilder;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Created by Daniele Gagliardi
- * daniele.gagliardi@eng.it
- * on 14/07/17.
- */
-public class AutomaticBuilderFactory {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(AutomaticBuilderFactory.class);
-
- public static AutomaticBuilder getAutomaticBuilder(String builderType) {
- AutomaticBuilder automaticBuilder;
- if (builderType == null) {
- LOGGER.warn("No automatic builder specified in configuration, going to default.");
- LOGGER.info("Default: provided Maven automatic builder.");
- automaticBuilder = new MavenAutomaticBuilder();
- } else if (builderType.toUpperCase().contains("GRADLE")) {
- LOGGER.info("Selected Gradle automatic builder.");
- automaticBuilder = new GradleAutomaticBuilder();
- } else if (builderType.toUpperCase().contains("MAVEN")) {
- LOGGER.info("Selected Maven automatic builder.");
- automaticBuilder = new MavenAutomaticBuilder();
- } else {
- LOGGER.warn(builderType + ": unknown automatic builder specified in configuration, going to default.");
- LOGGER.info("Default: provided Maven automatic builder.");
- automaticBuilder = new MavenAutomaticBuilder();
- }
- return automaticBuilder;
- }
-}
diff --git a/dspot/src/main/java/eu/stamp_project/automaticbuilder/gradle/GradleAutomaticBuilder.java b/dspot/src/main/java/eu/stamp_project/automaticbuilder/gradle/GradleAutomaticBuilder.java
index ad7dbad72..d8f2d70b6 100644
--- a/dspot/src/main/java/eu/stamp_project/automaticbuilder/gradle/GradleAutomaticBuilder.java
+++ b/dspot/src/main/java/eu/stamp_project/automaticbuilder/gradle/GradleAutomaticBuilder.java
@@ -1,5 +1,6 @@
package eu.stamp_project.automaticbuilder.gradle;
+import eu.stamp_project.Main;
import eu.stamp_project.automaticbuilder.AutomaticBuilder;
import eu.stamp_project.utils.program.InputConfiguration;
import org.gradle.tooling.BuildLauncher;
@@ -25,16 +26,30 @@
*/
public class GradleAutomaticBuilder implements AutomaticBuilder {
+ @Override
+ public void setAbsolutePathToProjectRoot(String absolutePathToProjectRoot) {
+ this.absolutePathToProjectRoot = absolutePathToProjectRoot;
+ }
+
private static final Logger LOGGER = LoggerFactory.getLogger(GradleAutomaticBuilder.class);
private static final String JAVA_PROJECT_CLASSPATH = "gjp_cp"; // Gradle Java Project classpath file
private GradleInjector gradleInjector;
- public GradleAutomaticBuilder() {
+ private String absolutePathToProjectRoot;
+
+ public GradleAutomaticBuilder(InputConfiguration configuration) {
+ this.absolutePathToProjectRoot = configuration.getAbsolutePathToProjectRoot();
this.gradleInjector = new GradleInjector(
- InputConfiguration.get().getAbsolutePathToProjectRoot()
- + File.separator + GradleInjector.GRADLE_BUILD_FILE
+ this.absolutePathToProjectRoot + File.separator + GradleInjector.GRADLE_BUILD_FILE,
+ !configuration.isGregorMode(),
+ configuration.getFilter(),
+ configuration.getPitVersion(),
+ configuration.getTimeOutInMs(),
+ configuration.getJVMArgs(),
+ configuration.getExcludedClasses(),
+ configuration.getAdditionalClasspathElements()
);
}
@@ -52,15 +67,15 @@ public void compile() {
@Override
public String buildClasspath() {
try {
- final File classpathFile = new File(InputConfiguration.get().getAbsolutePathToProjectRoot() + File.separator + "build/classpath.txt");
+ final File classpathFile = new File(this.absolutePathToProjectRoot + File.separator + "build/classpath.txt");
if (!classpathFile.exists()) {
LOGGER.info("Classpath file for Gradle project doesn't exist, starting to build it...");
LOGGER.info("Injecting Gradle task to print project classpath on stdout...");
- this.gradleInjector.injectPrintClasspathTask(InputConfiguration.get().getAbsolutePathToProjectRoot());
+ this.gradleInjector.injectPrintClasspathTask(this.absolutePathToProjectRoot);
LOGGER.info("Retrieving project classpath...");
this.runTasks(false, GradleInjector.WRITE_CLASSPATH_TASK);
LOGGER.info("Writing project classpath on file " + JAVA_PROJECT_CLASSPATH + "...");
- this.gradleInjector.resetOriginalGradleBuildFile(InputConfiguration.get().getAbsolutePathToProjectRoot());
+ this.gradleInjector.resetOriginalGradleBuildFile(this.absolutePathToProjectRoot);
}
try (BufferedReader buffer = new BufferedReader(new FileReader(classpathFile))) {
final String collect = buffer
@@ -89,18 +104,18 @@ public void runPit() {
public void runPit(CtType>... testClasses) {
try {
LOGGER.info("Injecting Gradle task to run Pit...");
- this.gradleInjector.injectPitTask(InputConfiguration.get().getAbsolutePathToProjectRoot(), testClasses);
+ this.gradleInjector.injectPitTask(this.absolutePathToProjectRoot, testClasses);
LOGGER.info("Running Pit...");
runTasks(true, CMD_PIT_MUTATION_COVERAGE);
} catch (Exception e) {
e.printStackTrace();
} finally {
- this.gradleInjector.resetOriginalGradleBuildFile(InputConfiguration.get().getAbsolutePathToProjectRoot());
+ this.gradleInjector.resetOriginalGradleBuildFile(this.absolutePathToProjectRoot);
}
}
protected void runTasks(boolean skipTest, String... tasks) {
- ProjectConnection connection = GradleConnector.newConnector().forProjectDirectory(new File(InputConfiguration.get().getAbsolutePathToProjectRoot())).connect();
+ ProjectConnection connection = GradleConnector.newConnector().forProjectDirectory(new File(this.absolutePathToProjectRoot)).connect();
LOGGER.info("Run gradle tasks: {}", String.join(" ", tasks));
try {
final BuildLauncher buildLauncher = connection.newBuild()
@@ -108,7 +123,7 @@ protected void runTasks(boolean skipTest, String... tasks) {
if (skipTest) {
buildLauncher.withArguments(ARGUMENTS_SKIP_COMPILE_TEST);
}
- if (InputConfiguration.get().isVerbose()) {
+ if (Main.verbose) {
buildLauncher.setStandardError(System.err);
buildLauncher.setStandardOutput(System.out);
}
diff --git a/dspot/src/main/java/eu/stamp_project/automaticbuilder/gradle/GradleInjector.java b/dspot/src/main/java/eu/stamp_project/automaticbuilder/gradle/GradleInjector.java
index 0219c3c0f..83108adf2 100644
--- a/dspot/src/main/java/eu/stamp_project/automaticbuilder/gradle/GradleInjector.java
+++ b/dspot/src/main/java/eu/stamp_project/automaticbuilder/gradle/GradleInjector.java
@@ -1,6 +1,5 @@
package eu.stamp_project.automaticbuilder.gradle;
-import eu.stamp_project.utils.program.InputConfiguration;
import eu.stamp_project.utils.AmplificationHelper;
import eu.stamp_project.utils.DSpotUtils;
import org.jetbrains.annotations.NotNull;
@@ -37,14 +36,41 @@ public class GradleInjector {
private File originalGradleBuildFile;
- public GradleInjector(String absolutePathToOriginalGradleBuildFile) {
+ private boolean isDescartesMode;
+
+ private String filter;
+
+ private String pitVersion;
+
+ private int timeoutMs;
+
+ private String JVMArgs;
+
+ private String excludedClasses;
+
+ private String additionalClasspathElements;
+
+ public GradleInjector(String absolutePathToOriginalGradleBuildFile,
+ boolean isDescartesMode,
+ String filter,
+ String pitVersion,
+ int timeoutMs,
+ String JVMArgs,
+ String excludedClasses,
+ String additionalClasspathElements) {
+ this.isDescartesMode = isDescartesMode;
+ this.filter = filter;
+ this.pitVersion = pitVersion;
+ this.timeoutMs = timeoutMs;
+ this.JVMArgs = JVMArgs;
+ this.excludedClasses = excludedClasses;
+ this.additionalClasspathElements = additionalClasspathElements;
this.originalGradleBuildFile = new File(absolutePathToOriginalGradleBuildFile);
if (!this.originalGradleBuildFile.exists()) {
throw new RuntimeException(absolutePathToOriginalGradleBuildFile + " does not exists!");
}
}
-
void injectPrintClasspathTask(String pathToRootOfProject) throws IOException {
String originalGradleBuildFilename = pathToRootOfProject + File.separator + GRADLE_BUILD_FILE;
File gradleBuildFile = new File(originalGradleBuildFilename);
@@ -211,7 +237,7 @@ private String getDependenciesForBuildscript() {
@NotNull
private String getDependenciesToPITAndOrDescartes() {
return " classpath 'info.solidsoft.gradle.pitest:gradle-pitest-plugin:1.3.0'" + AmplificationHelper.LINE_SEPARATOR +
- (InputConfiguration.get().isDescartesMode() ? " pitest 'eu.stamp-project:descartes:1.2.4'" : "") + AmplificationHelper.LINE_SEPARATOR;
+ (this.isDescartesMode ? " pitest 'eu.stamp-project:descartes:1.2.4'" : "") + AmplificationHelper.LINE_SEPARATOR;
}
@NotNull
@@ -239,23 +265,23 @@ private String wrapWithSingleQuote(String option) {
private String getPitTaskOptions(CtType>... testClasses) {
return AmplificationHelper.LINE_SEPARATOR + "pitest {" + AmplificationHelper.LINE_SEPARATOR +
- (InputConfiguration.get().getFilter() != null && !InputConfiguration.get().getFilter().isEmpty() ?
- " " + OPT_TARGET_CLASSES + "['" + InputConfiguration.get().getFilter() + "']" + AmplificationHelper.LINE_SEPARATOR : "" ) +
+ (this.filter != null && !this.filter.isEmpty() ?
+ " " + OPT_TARGET_CLASSES + "['" + this.filter + "']" + AmplificationHelper.LINE_SEPARATOR : "" ) +
" " + OPT_WITH_HISTORY + "true" + AmplificationHelper.LINE_SEPARATOR +
" " + OPT_VALUE_REPORT_DIR + AmplificationHelper.LINE_SEPARATOR +
" " + OPT_VALUE_FORMAT + AmplificationHelper.LINE_SEPARATOR +
- " " + OPT_PIT_VERSION + this.wrapWithSingleQuote(InputConfiguration.get().getPitVersion()) + AmplificationHelper.LINE_SEPARATOR +
- " " + PROPERTY_VALUE_TIMEOUT + " = " + InputConfiguration.get().getTimeOutInMs() + AmplificationHelper.LINE_SEPARATOR +
- (!InputConfiguration.get().getJVMArgs().isEmpty() ?
+ " " + OPT_PIT_VERSION + this.wrapWithSingleQuote(this.pitVersion) + AmplificationHelper.LINE_SEPARATOR +
+ " " + PROPERTY_VALUE_TIMEOUT + " = " + this.timeoutMs + AmplificationHelper.LINE_SEPARATOR +
+ (!this.JVMArgs.isEmpty() ?
" " + PROPERTY_VALUE_JVM_ARGS + " = [" +
- Arrays.stream(InputConfiguration.get().getJVMArgs().split(",")).map(this::wrapWithSingleQuote).collect(Collectors.joining(",")) + "]"
+ Arrays.stream(this.JVMArgs.split(",")).map(this::wrapWithSingleQuote).collect(Collectors.joining(",")) + "]"
+ AmplificationHelper.LINE_SEPARATOR : "") +
(testClasses != null ? " " + OPT_TARGET_TESTS + "['" + Arrays.stream(testClasses).map(DSpotUtils::ctTypeToFullQualifiedName).collect(Collectors.joining(",")) + "']" + AmplificationHelper.LINE_SEPARATOR : "") +
- (!InputConfiguration.get().getAdditionalClasspathElements().isEmpty() ?
- " " + OPT_ADDITIONAL_CP_ELEMENTS + "['" + InputConfiguration.get().getAdditionalClasspathElements() + "']" + AmplificationHelper.LINE_SEPARATOR : "") +
- " " + (InputConfiguration.get().isDescartesMode() ? OPT_MUTATION_ENGINE : OPT_MUTATORS + VALUE_MUTATORS_ALL) + AmplificationHelper.LINE_SEPARATOR +
- (!InputConfiguration.get().getExcludedClasses().isEmpty() ?
- " " + OPT_EXCLUDED_CLASSES + "['" + InputConfiguration.get().getExcludedClasses() + "']" + AmplificationHelper.LINE_SEPARATOR : "") +
+ (!this.additionalClasspathElements.isEmpty() ?
+ " " + OPT_ADDITIONAL_CP_ELEMENTS + "['" + this.additionalClasspathElements + "']" + AmplificationHelper.LINE_SEPARATOR : "") +
+ " " + (isDescartesMode ? OPT_MUTATION_ENGINE : OPT_MUTATORS + VALUE_MUTATORS_ALL) + AmplificationHelper.LINE_SEPARATOR +
+ (!this.excludedClasses.isEmpty() ?
+ " " + OPT_EXCLUDED_CLASSES + "['" + this.excludedClasses + "']" + AmplificationHelper.LINE_SEPARATOR : "") +
"}" + AmplificationHelper.LINE_SEPARATOR;
}
diff --git a/dspot/src/main/java/eu/stamp_project/automaticbuilder/maven/DSpotPOMCreator.java b/dspot/src/main/java/eu/stamp_project/automaticbuilder/maven/DSpotPOMCreator.java
index bc39d7e1f..80e65839a 100644
--- a/dspot/src/main/java/eu/stamp_project/automaticbuilder/maven/DSpotPOMCreator.java
+++ b/dspot/src/main/java/eu/stamp_project/automaticbuilder/maven/DSpotPOMCreator.java
@@ -85,18 +85,73 @@ public class DSpotPOMCreator {
private static final String DSPOT_PARALLEL_POM_FILE = ".dspot_parallel_";
- public static void createNewPom() {
- new DSpotPOMCreator(true)._innerCreatePom();
- new DSpotPOMCreator(false)._innerCreatePom();
+ public static boolean isCurrentlyJUnit5;
+
+ /*
+ This boolean is redundant with InputConfiguration.isJUnit5(), but it allows to create two pom directly.
+ We build two DSpotPOMCreator with true and false, and generate two different pom.
+ In this, way, we reuse the same code to generate.
+ We do that because at the moment we generate the pom, we do not if we amplify JUnit5 tests or JUnit4.
+ Then, we use InputConfiguration.isJUnit5() to know which pom must be used.
+ */
+ private boolean isJUnit5;
+
+ private String absolutePathToProjectRoot;
+
+ private boolean shouldExecuteTestsInParallel;
+
+ private boolean shouldUseMavenToExecuteTest;
+
+ private boolean isDescartesMode;
+
+ private String pitVersion;
+
+ private String descartesVersion;
+
+ private String additionalClasspathElements;
+
+ private String JVMArgs;
+
+ private String excludedClasses;
+
+ private String descartesMutators;
+
+ private String filter;
+
+ private int timeOutInMs;
+
+ private DSpotPOMCreator(InputConfiguration configuration, boolean isJUnit5) {
+ this.isJUnit5 = isJUnit5;
+ if (configuration != null) {
+ this.absolutePathToProjectRoot = configuration.getAbsolutePathToProjectRoot();
+ this.shouldUseMavenToExecuteTest = configuration.shouldUseMavenToExecuteTest();
+ this.shouldExecuteTestsInParallel = configuration.shouldExecuteTestsInParallel();
+ this.isDescartesMode = !configuration.isGregorMode();
+ this.pitVersion = configuration.getPitVersion();
+ this.descartesVersion = configuration.getDescartesVersion();
+ this.additionalClasspathElements = configuration.getAdditionalClasspathElements();
+ this.JVMArgs = configuration.getJVMArgs();
+ this.excludedClasses = configuration.getExcludedClasses();
+ this.descartesMutators = configuration.getDescartesMutators();
+ this.filter = configuration.getFilter();
+ this.timeOutInMs = configuration.getTimeOutInMs();
+ }
}
- public static String createNewPomForComputingClassPathWithParallelExecution() {
- return new DSpotPOMCreator(InputConfiguration.get().isJUnit5())._createNewPomForComputingClassPathWithParallelExecution();
+ public static void createNewPom(InputConfiguration configuration) {
+ new DSpotPOMCreator(configuration, true)._innerCreatePom();
+ new DSpotPOMCreator(configuration, false)._innerCreatePom();
+ }
+
+ // TODO
+ public static String createNewPomForComputingClassPathWithParallelExecution(boolean isJUnit5, InputConfiguration configuration) {
+ return new DSpotPOMCreator(configuration, isJUnit5).
+ _createNewPomForComputingClassPathWithParallelExecution();
}
public static void delete() {
- new DSpotPOMCreator(true)._delete();
- new DSpotPOMCreator(false)._delete();
+ new DSpotPOMCreator(null, true)._delete();
+ new DSpotPOMCreator(null, false)._delete();
}
private void _delete() {
@@ -113,7 +168,7 @@ public String _createNewPomForComputingClassPathWithParallelExecution() {
final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
- final Document document = docBuilder.parse(InputConfiguration.get().getAbsolutePathToProjectRoot() + POM_FILE);
+ final Document document = docBuilder.parse(this.absolutePathToProjectRoot + POM_FILE);
final Node root = findSpecificNodeFromGivenRoot(document.getFirstChild(), PROJECT);
@@ -124,7 +179,7 @@ public String _createNewPomForComputingClassPathWithParallelExecution() {
final TransformerFactory transformerFactory = TransformerFactory.newInstance();
final Transformer transformer = transformerFactory.newTransformer();
final DOMSource source = new DOMSource(document);
- String newPomFilename = InputConfiguration.get().getAbsolutePathToProjectRoot() + DSpotPOMCreator.getParallelPOMName();
+ String newPomFilename = this.absolutePathToProjectRoot + DSpotPOMCreator.getParallelPOMName();
final StreamResult result = new StreamResult(new File(newPomFilename));
transformer.transform(source, result);
@@ -143,7 +198,7 @@ private void addSurefirePluginConfiguration(Document document, Node root) {
final Element version = document.createElement("version");
version.setTextContent("2.22.0");
surefirePlugin.appendChild(version);
- if (InputConfiguration.get().isJUnit5()) {
+ if (this.isJUnit5) {
final Node dependencies = findOrCreateGivenNode(document, surefirePlugin, DEPENDENCIES);
Element dependency;
if (!hasDependencyByArtifactId(dependencies, "junit-platform-surefire-provider")) {
@@ -238,11 +293,11 @@ private boolean hasArtifactId(Node node, String artifactId) {
while (currentChild != null && !"artifactId".equals(currentChild.getNodeName())) {
currentChild = currentChild.getNextSibling();
}
- return currentChild == null? false: currentChild.getTextContent().equals(artifactId);
+ return currentChild != null && currentChild.getTextContent().equals(artifactId);
}
public static String getParallelPOMName() {
- return DSPOT_PARALLEL_POM_FILE + (InputConfiguration.get().isJUnit5() ? SUFFIX_JUNIT5 : "") + POM_FILE;
+ return DSPOT_PARALLEL_POM_FILE + (isCurrentlyJUnit5 ? SUFFIX_JUNIT5 : "") + POM_FILE;
}
private Node findChildByArtifactId(Node node, String artifactId) {
@@ -258,38 +313,26 @@ private boolean hasDependencyByArtifactId(Node dependencies, String artifactId)
}
public static String getPOMName() {
- return DSPOT_POM_FILE + (InputConfiguration.get().isJUnit5() ? SUFFIX_JUNIT5 : "") + POM_FILE;
+ return DSPOT_POM_FILE + (isCurrentlyJUnit5 ? SUFFIX_JUNIT5 : "") + POM_FILE;
}
private String _getPOMName() {
return DSPOT_POM_FILE + (this.isJUnit5 ? SUFFIX_JUNIT5 : "") + POM_FILE;
}
- /*
- This boolean is redundant with InputConfiguration.isJUnit5(), but it allows to create two pom directly.
- We build two DSpotPOMCreator with true and false, and generate two different pom.
- In this, way, we reuse the same code to generate.
- We do that because at the moment we generate the pom, we do not if we amplify JUnit5 tests or JUnit4.
- Then, we use InputConfiguration.isJUnit5() to know which pom must be used.
- */
- private boolean isJUnit5;
-
- private DSpotPOMCreator(boolean isJUnit5) {
- this.isJUnit5 = isJUnit5;
- }
private void _innerCreatePom() {
try {
final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
- final Document document = docBuilder.parse(InputConfiguration.get().getAbsolutePathToProjectRoot() + POM_FILE);
+ final Document document = docBuilder.parse(this.absolutePathToProjectRoot + POM_FILE);
final Node root = findSpecificNodeFromGivenRoot(document.getFirstChild(), PROJECT);
// CONFIGURATION TO RUN INSTRUMENTED TEST
configureForInstrumentedTests(document, root);
- if (InputConfiguration.get().shouldExecuteTestsInParallel() && InputConfiguration.get().shouldUseMavenToExecuteTest()) {
+ if (this.shouldExecuteTestsInParallel && this.shouldUseMavenToExecuteTest) {
//Add JUnit4/5 dependencies for parallel execution
//Add Surefire plugin configuration for parallel execution
addJUnitDependencies(document, root);
@@ -305,7 +348,7 @@ private void _innerCreatePom() {
final TransformerFactory transformerFactory = TransformerFactory.newInstance();
final Transformer transformer = transformerFactory.newTransformer();
final DOMSource source = new DOMSource(document);
- final StreamResult result = new StreamResult(new File(InputConfiguration.get().getAbsolutePathToProjectRoot() + this._getPOMName()));
+ final StreamResult result = new StreamResult(new File(this.absolutePathToProjectRoot + this._getPOMName()));
transformer.transform(source, result);
} catch (Exception e) {
throw new RuntimeException(e);
@@ -402,11 +445,11 @@ private Element createBuild(Document document) {
final Element plugins = document.createElement(PLUGINS);
// PIT PLUGIN
- final Element pluginPit = createPlugin(document, GROUP_ID_PIT, ARTIFACT_ID_PIT, VERSION);
+ final Element pluginPit = createPlugin(document, GROUP_ID_PIT, ARTIFACT_ID_PIT, this.pitVersion);
final Element configuration = createConfiguration(document);
pluginPit.appendChild(configuration);
- if (InputConfiguration.get().isDescartesMode() || this.isJUnit5) {
+ if (this.isDescartesMode || this.isJUnit5) {
final Element dependencies = createDependencies(document);
pluginPit.appendChild(dependencies);
}
@@ -440,8 +483,8 @@ private Element createPlugin(Document document,
plugin.appendChild(artifactId);
if (!versionValue.isEmpty()) {
- final Element version = document.createElement(versionValue);
- version.setTextContent(InputConfiguration.get().getPitVersion());
+ final Element version = document.createElement(VERSION);
+ version.setTextContent(versionValue);
plugin.appendChild(version);
}
@@ -484,11 +527,11 @@ private Element createExecution(Document document, String idValue, String phaseV
private Element createDependencies(Document document) {
final Element dependencies = document.createElement(DEPENDENCIES);
- if (InputConfiguration.get().isDescartesMode()) {
+ if (this.isDescartesMode) {
final Element dependency = createDependency(document,
GROUP_ID_DESCARTES,
ARTIFACT_ID_DESCARTES,
- InputConfiguration.get().getDescartesVersion()
+ this.descartesVersion
);
dependencies.appendChild(dependency);
}
@@ -545,7 +588,7 @@ private Element createDependency(Document document,
private static final String REPORT_DIRECTORY = "reportsDirectory";
- public static final String REPORT_DIRECTORY_VALUE = "target/pit-reports";
+ public static final String REPORT_DIRECTORY_VALUE = "target/pit-reports/";
private static final String TIME_OUT = "timeoutConstant";
@@ -555,17 +598,17 @@ private Element createConfiguration(Document document) {
final Element configuration = document.createElement(CONFIGURATION);
final Element mutationEngine = document.createElement(MUTATION_ENGINE);
- mutationEngine.setTextContent(InputConfiguration.get().isDescartesMode() ? MUTATION_ENGINE_DESCARTES : MUTATION_ENGINE_GREGOR);
+ mutationEngine.setTextContent(this.isDescartesMode ? MUTATION_ENGINE_DESCARTES : MUTATION_ENGINE_GREGOR);
configuration.appendChild(mutationEngine);
final Element outputFormats = document.createElement(OUTPUT_FORMATS);
appendValuesToGivenNode(document, outputFormats, DSpotPOMCreator.outputFormats);
configuration.appendChild(outputFormats);
- if (InputConfiguration.get().getFilter() != null &&
- !InputConfiguration.get().getFilter().isEmpty()) {
+ if (this.filter != null &&
+ !this.filter.isEmpty()) {
final Element targetClasses = document.createElement(TARGET_CLASSES);
- targetClasses.setTextContent(InputConfiguration.get().getFilter());
+ targetClasses.setTextContent(this.filter);
configuration.appendChild(targetClasses);
}
@@ -574,31 +617,31 @@ private Element createConfiguration(Document document) {
configuration.appendChild(reportsDirectory);
final Element timeOut = document.createElement(TIME_OUT);
- timeOut.setTextContent(String.valueOf(InputConfiguration.get().getTimeOutInMs()));
+ timeOut.setTextContent(String.valueOf(this.timeOutInMs));
configuration.appendChild(timeOut);
- if (!InputConfiguration.get().getAdditionalClasspathElements().isEmpty()) {
+ if (!this.additionalClasspathElements.isEmpty()) {
final Element additionalClasspathElements = document.createElement(ADDITIONAL_CLASSPATH_ELEMENTS);
- appendValuesToGivenNode(document, additionalClasspathElements, InputConfiguration.get().getAdditionalClasspathElements().split(","));
+ appendValuesToGivenNode(document, additionalClasspathElements, this.additionalClasspathElements.split(","));
configuration.appendChild(additionalClasspathElements);
}
- if (!InputConfiguration.get().getJVMArgs().isEmpty()) {
+ if (!this.JVMArgs.isEmpty()) {
final Element jvmArgs = document.createElement(JVM_ARGS);
- appendValuesToGivenNode(document, jvmArgs, InputConfiguration.get().getJVMArgs().split(","));
+ appendValuesToGivenNode(document, jvmArgs, this.JVMArgs.split(","));
configuration.appendChild(jvmArgs);
}
- if (!InputConfiguration.get().getExcludedClasses().isEmpty()) {
+ if (!this.excludedClasses.isEmpty()) {
final Element excludedTestClasses = document.createElement(EXCLUDED_TEST_CLASSES);
- appendValuesToGivenNode(document, excludedTestClasses, InputConfiguration.get().getExcludedClasses().split(","));
+ appendValuesToGivenNode(document, excludedTestClasses, this.excludedClasses.split(","));
configuration.appendChild(excludedTestClasses);
}
- if (!InputConfiguration.get().getDescartesMutators().isEmpty() || !InputConfiguration.get().isDescartesMode()) {
+ if (!this.descartesMutators.isEmpty() || !this.isDescartesMode) {
final Element mutators = document.createElement(MUTATORS);
- if (!InputConfiguration.get().getDescartesMutators().isEmpty() && InputConfiguration.get().isDescartesMode()) {
- appendValuesToGivenNode(document, mutators, InputConfiguration.get().getDescartesMutators().split(","));
+ if (!this.descartesMutators.isEmpty() && this.isDescartesMode) {
+ appendValuesToGivenNode(document, mutators, this.descartesMutators.split(","));
} else {
appendValuesToGivenNode(document, mutators, GREGOR_MUTATORS);
}
diff --git a/dspot/src/main/java/eu/stamp_project/automaticbuilder/maven/MavenAutomaticBuilder.java b/dspot/src/main/java/eu/stamp_project/automaticbuilder/maven/MavenAutomaticBuilder.java
index 75b0522b3..a2571876d 100644
--- a/dspot/src/main/java/eu/stamp_project/automaticbuilder/maven/MavenAutomaticBuilder.java
+++ b/dspot/src/main/java/eu/stamp_project/automaticbuilder/maven/MavenAutomaticBuilder.java
@@ -1,5 +1,6 @@
package eu.stamp_project.automaticbuilder.maven;
+import eu.stamp_project.Main;
import eu.stamp_project.automaticbuilder.AutomaticBuilder;
import eu.stamp_project.utils.program.InputConfiguration;
import eu.stamp_project.utils.DSpotUtils;
@@ -16,7 +17,6 @@
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
-import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Optional;
@@ -40,10 +40,21 @@ public class MavenAutomaticBuilder implements AutomaticBuilder {
private String classpath = null;
- private boolean hasGeneratePom = false;
+ private String absolutePathToProjectRoot;
- public MavenAutomaticBuilder() {
- delete(false);
+ private String mavenHome;
+
+ private boolean shouldExecuteTestsInParallel;
+
+ public void setAbsolutePathToProjectRoot(String absolutePathToProjectRoot) {
+ this.absolutePathToProjectRoot = absolutePathToProjectRoot;
+ }
+
+ public MavenAutomaticBuilder(InputConfiguration configuration) {
+ this.shouldExecuteTestsInParallel = configuration.shouldExecuteTestsInParallel();
+ DSpotPOMCreator.createNewPom(configuration);
+ this.absolutePathToProjectRoot = configuration.getAbsolutePathToProjectRoot();
+ this.mavenHome = buildMavenHome(configuration);
}
@Override
@@ -56,7 +67,7 @@ public String compileAndBuildClasspath() {
"dependency:build-classpath",
"-Dmdep.outputFile=" + "target/dspot/classpath"
);
- final File classpathFile = new File(InputConfiguration.get().getAbsolutePathToProjectRoot() + "/target/dspot/classpath");
+ final File classpathFile = new File(this.absolutePathToProjectRoot + "/target/dspot/classpath");
try (BufferedReader buffer = new BufferedReader(new FileReader(classpathFile))) {
this.classpath = buffer.lines().collect(Collectors.joining());
} catch (Exception e) {
@@ -68,15 +79,15 @@ public String compileAndBuildClasspath() {
private int computeClasspath(String... goals) {
final String pomPathname;
- if (InputConfiguration.get().shouldExecuteTestsInParallel()) {
- DSpotPOMCreator.createNewPomForComputingClassPathWithParallelExecution();
- pomPathname = InputConfiguration.get().getAbsolutePathToProjectRoot()
+ if (shouldExecuteTestsInParallel) {
+ // TODO
+ DSpotPOMCreator.createNewPomForComputingClassPathWithParallelExecution(false, null);
+ pomPathname = this.absolutePathToProjectRoot
+ DSpotPOMCreator.getParallelPOMName();
- this.hasGeneratePom = true;
LOGGER.info("Using {} to run maven.", pomPathname);
return _runGoals(true, pomPathname, goals);
} else {
- pomPathname = InputConfiguration.get().getAbsolutePathToProjectRoot() + DSpotPOMCreator.POM_FILE;
+ pomPathname = this.absolutePathToProjectRoot + DSpotPOMCreator.POM_FILE;
LOGGER.info("Using {} to run maven.", pomPathname);
return _runGoals(false, pomPathname, goals);
}
@@ -96,7 +107,7 @@ public void compile() {
public String buildClasspath() {
if (this.classpath == null) {
try {
- final File classpathFile = new File(InputConfiguration.get().getAbsolutePathToProjectRoot() + "/target/dspot/classpath");
+ final File classpathFile = new File(this.absolutePathToProjectRoot + "/target/dspot/classpath");
if (!classpathFile.exists()) {
this.runGoals(false,
"dependency:build-classpath",
@@ -113,46 +124,15 @@ public String buildClasspath() {
return this.classpath;
}
- private boolean shouldDeleteGeneratedPom() {
- return hasGeneratePom ||
- new File(InputConfiguration.get().getAbsolutePathToProjectRoot() + "/" + DSpotPOMCreator.getPOMName()).exists();
- }
-
- private void delete(boolean displayError) {
- if (this.shouldDeleteGeneratedPom()) {
- this.hasGeneratePom = false;
- try {
- if (InputConfiguration.get().shouldExecuteTestsInParallel()) {
- if (new File(InputConfiguration.get().getAbsolutePathToProjectRoot() + "/" + DSpotPOMCreator.getParallelPOMName()).exists()) {
- FileUtils.forceDelete(
- new File(InputConfiguration.get().getAbsolutePathToProjectRoot() + "/" + DSpotPOMCreator.getParallelPOMName()));
- }
- }
- if (InputConfiguration.get().shouldUseMavenToExecuteTest()){
- if (new File(InputConfiguration.get().getAbsolutePathToProjectRoot() + "/" + DSpotPOMCreator.getPOMName()).exists()) {
- FileUtils.forceDelete(
- new File(InputConfiguration.get().getAbsolutePathToProjectRoot() + "/" + DSpotPOMCreator.getPOMName()));
- }
- }
- } catch (IOException e) {
- if (displayError) {
- LOGGER.warn("Something bad happened when trying to delete {}.", DSpotPOMCreator.getPOMName());
- e.printStackTrace();
- LOGGER.warn("Ignoring, moving forward...");
- }
- }
- }
- }
-
@Override
public void reset() {
- delete(true);
+ // empty
}
@Override
public void runPit(CtType>... testClasses) {
try {
- FileUtils.deleteDirectory(new File(InputConfiguration.get().getAbsolutePathToProjectRoot() + "/target/pit-reports"));
+ FileUtils.deleteDirectory(new File(this.absolutePathToProjectRoot + "/target/pit-reports"));
} catch (Exception ignored) {
}
@@ -179,15 +159,11 @@ public void runPit() {
}
private int runGoals(boolean specificPom, String... goals) {
- if (specificPom && !new File(InputConfiguration.get().getAbsolutePathToProjectRoot() + DSpotPOMCreator.getPOMName()).exists()) {
- DSpotPOMCreator.createNewPom();
- this.hasGeneratePom = true;
- }
- final String pomPathname = InputConfiguration.get().getAbsolutePathToProjectRoot()
- + (specificPom ? DSpotPOMCreator.getPOMName() : DSpotPOMCreator.POM_FILE);
+ final String pomPathname = this.absolutePathToProjectRoot + "/" + (
+ specificPom ? DSpotPOMCreator.getPOMName() : DSpotPOMCreator.POM_FILE);
LOGGER.info("Using {} to run maven.", pomPathname);
return _runGoals(specificPom, pomPathname, goals);
- }
+ }
private int _runGoals(boolean specificPom, final String pomPathname, String... goals) {
InvocationRequest request = new DefaultInvocationRequest();
@@ -210,11 +186,10 @@ private int _runGoals(boolean specificPom, final String pomPathname, String... g
request.setProperties(properties);
Invoker invoker = new DefaultInvoker();
- final String mavenHome = this.buildMavenHome();
LOGGER.info("Using {} for maven home", mavenHome);
invoker.setMavenHome(new File(mavenHome));
LOGGER.info(String.format("run maven: %s/bin/mvn %s", mavenHome, String.join(" ", goals)));
- if (InputConfiguration.get().isVerbose()) {
+ if (Main.verbose) {
invoker.setOutputHandler(System.out::println);
invoker.setErrorHandler(System.err::println);
} else {
@@ -233,11 +208,10 @@ public String getOutputDirectoryPit() {
return DSpotPOMCreator.REPORT_DIRECTORY_VALUE;
}
- private String buildMavenHome() {
- InputConfiguration configuration = InputConfiguration.get();
+ private String buildMavenHome(InputConfiguration configuration) {
String mavenHome = null;
- if (configuration != null) {
- if (!configuration.getMavenHome().isEmpty()) {
+ if (configuration != null ) {
+ if (configuration.getMavenHome() != null && !configuration.getMavenHome().isEmpty()) {
mavenHome = configuration.getMavenHome();
} else {
mavenHome = getMavenHome(envVariable -> System.getenv().get(envVariable) != null,
diff --git a/dspot/src/main/java/eu/stamp_project/dspot/Amplification.java b/dspot/src/main/java/eu/stamp_project/dspot/Amplification.java
index e9841d70d..8f0632ee0 100644
--- a/dspot/src/main/java/eu/stamp_project/dspot/Amplification.java
+++ b/dspot/src/main/java/eu/stamp_project/dspot/Amplification.java
@@ -4,9 +4,6 @@
import eu.stamp_project.dspot.assertiongenerator.AssertionGenerator;
import eu.stamp_project.dspot.input_ampl_distributor.InputAmplDistributor;
import eu.stamp_project.dspot.selector.TestSelector;
-import eu.stamp_project.test_framework.TestFramework;
-import eu.stamp_project.testrunner.EntryPoint;
-import eu.stamp_project.utils.program.InputConfiguration;
import eu.stamp_project.utils.compilation.DSpotCompiler;
import eu.stamp_project.utils.compilation.TestCompiler;
import eu.stamp_project.utils.report.error.Error;
@@ -43,12 +40,13 @@ public class Amplification {
private int numberOfIteration;
- public Amplification(DSpotCompiler compiler,
+ public Amplification(double delta,
+ DSpotCompiler compiler,
TestSelector testSelector,
InputAmplDistributor inputAmplDistributor,
int numberOfIteration) {
this.compiler = compiler;
- this.assertionGenerator = new AssertionGenerator(InputConfiguration.get(), this.compiler);
+ this.assertionGenerator = new AssertionGenerator(delta, this.compiler);
this.testSelector = testSelector;
this.inputAmplDistributor = inputAmplDistributor;
this.globalNumberOfSelectedAmplification = 0;
@@ -65,12 +63,6 @@ public List> amplification(CtType> testClassToBeAmplified, List> amplification(CtType> testClassToBeAmplified, List> amplification(CtType> testClassToBeAmplified, List> amplifiedTests = new ArrayList<>();
for (int i = 0; i < testMethodsToBeAmplified.size(); i++) {
CtMethod test = testMethodsToBeAmplified.get(i);
LOGGER.info("Amplification of {}, ({}/{})", test.getSimpleName(), i + 1, testMethodsToBeAmplified.size());
- amplifiedTests.addAll(amplificationIteration(testClassToBeAmplified, test));
- this.globalNumberOfSelectedAmplification += amplifiedTests.size();
- LOGGER.info("{} amplified test methods has been selected to be kept. (global: {})", amplifiedTests.size(), this.globalNumberOfSelectedAmplification);
+ final List> amplifiedTestMethodsFromCurrentIteration = amplificationIteration(testClassToBeAmplified, test);
+ amplifiedTestMethodsToKeep.addAll(amplifiedTestMethodsFromCurrentIteration);
+ this.globalNumberOfSelectedAmplification += amplifiedTestMethodsToKeep.size();
+ LOGGER.info("{} amplified test methods has been selected to be kept. (global: {})", amplifiedTestMethodsFromCurrentIteration.size(), this.globalNumberOfSelectedAmplification);
}
- return amplifiedTests;
+ return amplifiedTestMethodsToKeep;
}
private List> amplificationIteration(CtType> testClassToBeAmplified, CtMethod test) {
@@ -213,8 +204,7 @@ public List> assertionsAmplification(CtType> classTest, List amplify(CtType> testClassToBeAmplified) {
@@ -82,6 +94,7 @@ public List> amplify(List> testClassesToBeAmplified, List testClassToBeAmplified : testClassesToBeAmplified) {
inputAmplDistributor.resetAmplifiers(testClassToBeAmplified);
Amplification testAmplification = new Amplification(
+ this.delta,
this.compiler,
this.testSelector,
this.inputAmplDistributor,
@@ -89,6 +102,14 @@ public List> amplify(List> testClassesToBeAmplified, List> testMethodsToBeAmplified =
testFinder.findTestMethods(testClassToBeAmplified, testMethodsToBeAmplifiedAsString);
+
+ // here, we base the execution mode to the first test method given.
+ // the user should provide whether JUnit3/4 OR JUnit5 but not both at the same time.
+ // TODO DSpot could be able to switch from one to another version of JUnit, but I believe that the ROI is not worth it.
+ final boolean jUnit5 = TestFramework.isJUnit5(testMethodsToBeAmplified.get(0));
+ EntryPoint.jUnit5Mode = jUnit5;
+ DSpotPOMCreator.isCurrentlyJUnit5 = jUnit5;
+
final CtType> amplifiedTestClass = this.amplify(testAmplification, testClassToBeAmplified, testMethodsToBeAmplified);
amplifiedTestClasses.add(amplifiedTestClass);
cleanAfterAmplificationOfOneTestClass(compiler, testClassToBeAmplified);
@@ -121,9 +142,11 @@ private CtType> amplify(Amplification testAmplification,
LOGGER.debug("OPTIMIZATION: GC invoked");
System.gc(); //Optimization: cleaning up heap before printing the amplified class
- InputConfiguration.get().getBuilder().reset();
+ this.automaticBuilder.reset();
try {
- Main.GLOBAL_REPORT.addTestSelectorReportForTestClass(testClassToBeAmplified, this.testSelector.report());
+ final TestSelectorElementReport report = this.testSelector.report();
+ this.output.reportSelectorInformation(report.getReportForCollector());
+ Main.GLOBAL_REPORT.addTestSelectorReportForTestClass(testClassToBeAmplified, report);
} catch (Exception e) {
e.printStackTrace();
LOGGER.error("Something bad happened during the report fot test-criterion.");
diff --git a/dspot/src/main/java/eu/stamp_project/dspot/amplifier/ArrayLiteralAmplifier.java b/dspot/src/main/java/eu/stamp_project/dspot/amplifier/ArrayLiteralAmplifier.java
index d4e181685..c23e126fd 100644
--- a/dspot/src/main/java/eu/stamp_project/dspot/amplifier/ArrayLiteralAmplifier.java
+++ b/dspot/src/main/java/eu/stamp_project/dspot/amplifier/ArrayLiteralAmplifier.java
@@ -1,7 +1,7 @@
package eu.stamp_project.dspot.amplifier;
import eu.stamp_project.test_framework.TestFramework;
-import eu.stamp_project.utils.program.InputConfiguration;
+
import org.apache.commons.lang3.SerializationUtils;
import spoon.reflect.code.*;
import spoon.reflect.declaration.CtAnnotation;
@@ -10,6 +10,7 @@
import spoon.reflect.factory.Factory;
import spoon.reflect.visitor.filter.TypeFilter;
import spoon.support.reflect.code.CtNewArrayImpl;
+
import java.lang.reflect.Array;
import java.util.*;
@@ -18,7 +19,7 @@
* abwogi@kth.se
* on 12/09/19
*/
-public class ArrayLiteralAmplifier extends AbstractLiteralAmplifier {
+public class ArrayLiteralAmplifier extends AbstractLiteralAmplifier {
@Override
protected String getSuffix() {
@@ -41,15 +42,15 @@ protected List> getOriginals(CtMethod> testMethod
public boolean matches(CtExpression candidate) {
// keep only literals and array literals
- if (! (candidate instanceof CtLiteral || candidate instanceof CtNewArrayImpl)) {
+ if (!(candidate instanceof CtLiteral || candidate instanceof CtNewArrayImpl)) {
return false;
}
// don't keep elements of arrays
- if(candidate.getParent() instanceof CtNewArrayImpl){
+ if (candidate.getParent() instanceof CtNewArrayImpl) {
return false;
}
- if(candidate instanceof CtLiteral) {
+ if (candidate instanceof CtLiteral) {
CtLiteral literal = (CtLiteral) candidate;
try {
@@ -63,7 +64,6 @@ public boolean matches(CtExpression candidate) {
return getNullClass(literal).isArray();
}
} catch (Exception e) {
-
// todo: maybe need a warning ?
return false;
}
@@ -85,19 +85,19 @@ private boolean isConcatenationOfLiteralInAssertion(CtLiteral literal) {
@Override
protected Set> amplify(CtExpression original, CtMethod> testMethod) {
- final Factory factory = InputConfiguration.get().getFactory();
+ final Factory factory = testMethod.getFactory();
Set> values = new HashSet<>();
// amplify an array set to null
- if(original instanceof CtLiteral && ((CtLiteral)original).getValue() == null) {
- String typeName = getNullClass((CtLiteral)original).getTypeName();
+ if (original instanceof CtLiteral && ((CtLiteral) original).getValue() == null) {
+ String typeName = getNullClass((CtLiteral) original).getTypeName();
String additionalElement = constructAdditionalElement(cropTypeName(typeName));
- String array = constructArray(typeName,additionalElement,false);
+ String array = constructArray(typeName, additionalElement, false);
CtExpression finalExpression = factory.createCodeSnippetExpression(array).compile();
// create an array with one element and an empty array
values.add(finalExpression);
- array = constructArray(typeName,"",true);
+ array = constructArray(typeName, "", true);
finalExpression = factory.createCodeSnippetExpression(array).compile();
values.add(finalExpression);
return values;
@@ -106,9 +106,9 @@ protected Set> amplify(CtExpression
List list = castedOriginal.getElements();
// amplify an empty array
- if(list.isEmpty()) {
+ if (list.isEmpty()) {
String additionalElement = constructAdditionalElement(cropTypeName(original.getType().getSimpleName()));
- String array = constructArray(original.getType().toString(),additionalElement,false);
+ String array = constructArray(original.getType().toString(), additionalElement, false);
CtExpression finalExpression = factory.createCodeSnippetExpression(array).compile();
// create an array with one element and a null literal
@@ -127,7 +127,7 @@ protected Set> amplify(CtExpression
// create array expressions that are modifications of the original array expression and a null literal
values.add(cloneAdd);
values.add(cloneSub);
- if(list.size()>1){
+ if (list.size() > 1) {
CtNewArray cloneEmpty = SerializationUtils.clone(castedOriginal);
cloneEmpty.setElements(Collections.EMPTY_LIST);
values.add(cloneEmpty);
@@ -137,27 +137,27 @@ protected Set> amplify(CtExpression
return values;
}
- private String cropTypeName(String name){
+ private String cropTypeName(String name) {
int index = name.indexOf("[");
- name = name.substring(0,index);
+ name = name.substring(0, index);
return name;
}
private String constructAdditionalElement(String type) {
type = type.toLowerCase();
- if(type.equals("int") || type.equals("integer") || type.equals("short") || type.equals("byte")){
+ if (type.equals("int") || type.equals("integer") || type.equals("short") || type.equals("byte")) {
return "1";
- } else if(type.equals("long")){
+ } else if (type.equals("long")) {
return "1L";
- } else if(type.equals("float")){
+ } else if (type.equals("float")) {
return "1.1F";
- } else if(type.equals("double")){
+ } else if (type.equals("double")) {
return "1.1";
- } else if(type.equals("boolean")){
+ } else if (type.equals("boolean")) {
return "true";
- } else if(type.equals("char") || type.equals("character")){
+ } else if (type.equals("char") || type.equals("character")) {
return "'a'";
- } else if(type.equals("string")){
+ } else if (type.equals("string")) {
return "\"a\"";
} else {
return "null";
@@ -166,18 +166,18 @@ private String constructAdditionalElement(String type) {
private String constructArray(String type, String additionalElement, boolean isEmpty) {
long dimensions;
- if(isEmpty){
+ if (isEmpty) {
dimensions = 1;
} else {
dimensions = type.chars().filter(num -> num == '[').count();
}
StringBuilder sb = new StringBuilder();
sb.append("new " + type);
- for(int i = 0;i> amplify(CtMethod> testMethod, int iteration) {
+ return Stream.empty();
+ }
+
+ @Override
+ public void reset(CtType> testClass) {
+
+ }
+}
diff --git a/dspot/src/main/java/eu/stamp_project/dspot/assertiongenerator/AssertionGenerator.java b/dspot/src/main/java/eu/stamp_project/dspot/assertiongenerator/AssertionGenerator.java
index ce6e433de..c4fa83330 100644
--- a/dspot/src/main/java/eu/stamp_project/dspot/assertiongenerator/AssertionGenerator.java
+++ b/dspot/src/main/java/eu/stamp_project/dspot/assertiongenerator/AssertionGenerator.java
@@ -8,7 +8,7 @@
import eu.stamp_project.utils.CloneHelper;
import eu.stamp_project.utils.compilation.DSpotCompiler;
import eu.stamp_project.utils.compilation.TestCompiler;
-import eu.stamp_project.utils.program.InputConfiguration;
+
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import spoon.reflect.declaration.CtMethod;
@@ -30,8 +30,6 @@ public class AssertionGenerator {
private static final Logger LOGGER = LoggerFactory.getLogger(AssertionGenerator.class);
- private InputConfiguration configuration;
-
private DSpotCompiler compiler;
private AssertionRemover assertionRemover;
@@ -40,8 +38,10 @@ public class AssertionGenerator {
private MethodReconstructor methodReconstructor;
- public AssertionGenerator(InputConfiguration configuration, DSpotCompiler compiler) {
- this.configuration = configuration;
+ private double delta;
+
+ public AssertionGenerator(double delta, DSpotCompiler compiler) {
+ this.delta = delta;
this.compiler = compiler;
this.assertionRemover = new AssertionRemover();
this.tryCatchFailGenerator = new TryCatchFailGenerator();
@@ -65,8 +65,8 @@ public List> assertionAmplification(CtType> testClass, List> assertPassingAndFailingTests(CtType testClass, List, List>> variableReadsAsserted) {
- this.configuration = configuration;
- this.factory = configuration.getFactory();
- this.observer = new Observer(originalClass,
- configuration,
+ this.delta = delta;
+ this.factory = compiler.getFactory();
+ this.observer = new Observer(
+ originalClass,
compiler,
variableReadsAsserted);
}
@@ -109,7 +109,7 @@ private CtMethod> buildTestWithAssert(CtMethod test, Map
test,
observations.get(id).getNotDeterministValues(),
observations.get(id).getObservationValues(),
- Double.parseDouble(configuration.getDelta())
+ this.delta
);
/* skip the current observation if it leads to
diff --git a/dspot/src/main/java/eu/stamp_project/dspot/assertiongenerator/assertiongenerator/methodreconstructor/AssertionSyntaxBuilder.java b/dspot/src/main/java/eu/stamp_project/dspot/assertiongenerator/assertiongenerator/methodreconstructor/AssertionSyntaxBuilder.java
index 5c3d6a230..80e87671d 100644
--- a/dspot/src/main/java/eu/stamp_project/dspot/assertiongenerator/assertiongenerator/methodreconstructor/AssertionSyntaxBuilder.java
+++ b/dspot/src/main/java/eu/stamp_project/dspot/assertiongenerator/assertiongenerator/methodreconstructor/AssertionSyntaxBuilder.java
@@ -6,7 +6,6 @@
import eu.stamp_project.test_framework.assertions.AssertEnum;
import eu.stamp_project.test_framework.TestFramework;
import eu.stamp_project.utils.TypeUtils;
-import eu.stamp_project.utils.program.InputConfiguration;
import spoon.reflect.code.CtExpression;
import spoon.reflect.code.CtInvocation;
import spoon.reflect.code.CtLiteral;
@@ -46,7 +45,7 @@ public static List buildAssert(CtMethod> testMethod,
Set notDeterministValues,
Map observations,
Double delta) {
- final Factory factory = InputConfiguration.get().getFactory();
+ final Factory factory = testMethod.getFactory();
final List invocations = new ArrayList<>();
for (String observationKey : observations.keySet()) {
if (!notDeterministValues.contains(observationKey)) {
diff --git a/dspot/src/main/java/eu/stamp_project/dspot/assertiongenerator/assertiongenerator/methodreconstructor/Observer.java b/dspot/src/main/java/eu/stamp_project/dspot/assertiongenerator/assertiongenerator/methodreconstructor/Observer.java
index 2aa740650..e436b21d6 100644
--- a/dspot/src/main/java/eu/stamp_project/dspot/assertiongenerator/assertiongenerator/methodreconstructor/Observer.java
+++ b/dspot/src/main/java/eu/stamp_project/dspot/assertiongenerator/assertiongenerator/methodreconstructor/Observer.java
@@ -10,7 +10,6 @@
import eu.stamp_project.utils.DSpotUtils;
import eu.stamp_project.utils.compilation.DSpotCompiler;
import eu.stamp_project.utils.compilation.TestCompiler;
-import eu.stamp_project.utils.program.InputConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import spoon.reflect.code.CtLocalVariable;
@@ -33,18 +32,14 @@ public class Observer {
private CtType originalClass;
- private InputConfiguration configuration;
-
private DSpotCompiler compiler;
private Map, List>> variableReadsAsserted;
public Observer(CtType originalClass,
- InputConfiguration configuration,
DSpotCompiler compiler,
Map, List>> variableReadsAsserted) {
this.originalClass = originalClass;
- this.configuration = configuration;
this.compiler = compiler;
this.variableReadsAsserted = variableReadsAsserted;
}
@@ -113,8 +108,7 @@ private Map compileRunTests(CtType clone, final List amplifiers;
- public AbstractInputAmplDistributor() {
- this.amplifiers = InputConfiguration.get().getAmplifiers();
- }
+ protected int maxNumTests;
- public AbstractInputAmplDistributor(List amplifiers) {
+ public AbstractInputAmplDistributor(int maxNumTests, List amplifiers) {
+ this.maxNumTests = maxNumTests;
this.amplifiers = amplifiers;
}
diff --git a/dspot/src/main/java/eu/stamp_project/dspot/input_ampl_distributor/RandomInputAmplDistributor.java b/dspot/src/main/java/eu/stamp_project/dspot/input_ampl_distributor/RandomInputAmplDistributor.java
index 04f9746b2..3d9fde4e3 100644
--- a/dspot/src/main/java/eu/stamp_project/dspot/input_ampl_distributor/RandomInputAmplDistributor.java
+++ b/dspot/src/main/java/eu/stamp_project/dspot/input_ampl_distributor/RandomInputAmplDistributor.java
@@ -23,12 +23,8 @@ public class RandomInputAmplDistributor extends AbstractInputAmplDistributor {
private static final Logger LOGGER = LoggerFactory.getLogger(RandomInputAmplDistributor.class);
- public RandomInputAmplDistributor() {
- super();
- }
-
- public RandomInputAmplDistributor(List amplifiers) {
- super(amplifiers);
+ public RandomInputAmplDistributor(int maxNumTests, List amplifiers) {
+ super(maxNumTests, amplifiers);
}
/**
@@ -72,7 +68,7 @@ public List> inputAmplify(List> testMethods, int i) {
public List> reduce(List> tests) {
final List> reducedTests = new ArrayList<>();
- final int maxNumTests = InputConfiguration.get().getMaxTestAmplified();
+
final int testsSize = tests.size();
if (testsSize > maxNumTests) {
Random random = new Random();
diff --git a/dspot/src/main/java/eu/stamp_project/dspot/input_ampl_distributor/SimpleInputAmplDistributor.java b/dspot/src/main/java/eu/stamp_project/dspot/input_ampl_distributor/SimpleInputAmplDistributor.java
index 07cccc6a5..ad342f577 100644
--- a/dspot/src/main/java/eu/stamp_project/dspot/input_ampl_distributor/SimpleInputAmplDistributor.java
+++ b/dspot/src/main/java/eu/stamp_project/dspot/input_ampl_distributor/SimpleInputAmplDistributor.java
@@ -1,7 +1,6 @@
package eu.stamp_project.dspot.input_ampl_distributor;
import eu.stamp_project.dspot.amplifier.Amplifier;
-import eu.stamp_project.utils.program.InputConfiguration;
import eu.stamp_project.utils.DSpotUtils;
import eu.stamp_project.utils.RandomHelper;
import org.slf4j.Logger;
@@ -24,11 +23,8 @@ public class SimpleInputAmplDistributor extends AbstractInputAmplDistributor {
private static final Logger LOGGER = LoggerFactory.getLogger(SimpleInputAmplDistributor.class);
- public SimpleInputAmplDistributor() {
- }
-
- public SimpleInputAmplDistributor(List amplifiers) {
- super(amplifiers);
+ public SimpleInputAmplDistributor(int maxNumTests, List amplifiers) {
+ super(maxNumTests, amplifiers);
}
/**
@@ -40,8 +36,8 @@ public SimpleInputAmplDistributor(List amplifiers) {
@Override
public List> inputAmplify(List> testMethods, int iteration) {
LOGGER.info("Amplification of inputs...");
- final int budget = InputConfiguration.get().getMaxTestAmplified();
- int totalBudget = InputConfiguration.get().getMaxTestAmplified();
+ final int budget = this.maxNumTests;
+ int totalBudget = this.maxNumTests;
// copy the amplifiers, we will remove amplifier that does not generate more test
final List amplifiers = new ArrayList<>(this.amplifiers);
// copy the test methods to be amplified
diff --git a/dspot/src/main/java/eu/stamp_project/dspot/input_ampl_distributor/TextualDistanceInputAmplDistributor.java b/dspot/src/main/java/eu/stamp_project/dspot/input_ampl_distributor/TextualDistanceInputAmplDistributor.java
index 1e774ec94..78a241cbb 100644
--- a/dspot/src/main/java/eu/stamp_project/dspot/input_ampl_distributor/TextualDistanceInputAmplDistributor.java
+++ b/dspot/src/main/java/eu/stamp_project/dspot/input_ampl_distributor/TextualDistanceInputAmplDistributor.java
@@ -14,7 +14,6 @@
import eu.stamp_project.dspot.amplifier.Amplifier;
import eu.stamp_project.utils.DSpotUtils;
-import eu.stamp_project.utils.program.InputConfiguration;
import spoon.reflect.declaration.CtMethod;
/**
@@ -26,12 +25,8 @@ public class TextualDistanceInputAmplDistributor extends AbstractInputAmplDistri
private static final Logger LOGGER = LoggerFactory.getLogger(TextualDistanceInputAmplDistributor.class);
- public TextualDistanceInputAmplDistributor() {
- super();
- }
-
- public TextualDistanceInputAmplDistributor(List amplifiers) {
- super(amplifiers);
+ public TextualDistanceInputAmplDistributor(int maxNumTests, List amplifiers) {
+ super(maxNumTests, amplifiers);
}
/**
@@ -67,7 +62,7 @@ public List> inputAmplify(List> testMethods, int i) {
}
/**
- * Reduces the number of amplified tests to a practical threshold (see {@link InputConfiguration#getMaxTestAmplified()}).
+ * Reduces the number of amplified tests to a practical threshold.
*
* The reduction aims at keeping a maximum of diversity. Because all the amplified tests come from the same
* original test, they have a lot in common.
@@ -80,7 +75,7 @@ public List> inputAmplify(List> testMethods, int i) {
*/
public List> reduce(List> tests) {
final List> reducedTests = new ArrayList<>();
- if (tests.size() > InputConfiguration.get().getMaxTestAmplified()) {
+ if (tests.size() > this.maxNumTests) {
LOGGER.warn("Too many tests have been generated: {}", tests.size());
final Map>> valuesToMethod = new HashMap<>();
for (CtMethod> test : tests) {
@@ -91,7 +86,7 @@ public List> reduce(List> tests) {
valuesToMethod.get(value).add(test);
}
final Long average = average(valuesToMethod.keySet());
- while (reducedTests.size() < InputConfiguration.get().getMaxTestAmplified()) {
+ while (reducedTests.size() < this.maxNumTests) {
final Long furthest = furthest(valuesToMethod.keySet(), average);
reducedTests.add(valuesToMethod.get(furthest).get(0));
if (valuesToMethod.get(furthest).isEmpty()) {
diff --git a/dspot/src/main/java/eu/stamp_project/dspot/selector/AbstractTestSelector.java b/dspot/src/main/java/eu/stamp_project/dspot/selector/AbstractTestSelector.java
new file mode 100644
index 000000000..fc3e6ca2b
--- /dev/null
+++ b/dspot/src/main/java/eu/stamp_project/dspot/selector/AbstractTestSelector.java
@@ -0,0 +1,37 @@
+package eu.stamp_project.dspot.selector;
+
+import eu.stamp_project.automaticbuilder.AutomaticBuilder;
+import eu.stamp_project.utils.program.InputConfiguration;
+
+import static eu.stamp_project.utils.AmplificationHelper.PATH_SEPARATOR;
+
+/**
+ * Created by Benjamin DANGLOT
+ * benjamin.danglot@inria.fr
+ * on 04/10/19
+ */
+public abstract class AbstractTestSelector implements TestSelector {
+
+ protected AutomaticBuilder automaticBuilder;
+
+ protected String targetClasses;
+
+ protected String classpath;
+
+ protected String pathToTestClasses;
+
+ protected String outputDirectory;
+
+ public AbstractTestSelector(AutomaticBuilder automaticBuilder,
+ InputConfiguration configuration) {
+ this.outputDirectory = configuration.getOutputDirectory();
+ this.automaticBuilder = automaticBuilder;
+ String classpath = automaticBuilder.buildClasspath();
+ if (!configuration.getAdditionalClasspathElements().isEmpty()) {
+ classpath += PATH_SEPARATOR + configuration.getProcessedAddtionalClasspathElements();
+ }
+ this.targetClasses = configuration.getClasspathClassesProject();
+ this.classpath = classpath;
+ this.pathToTestClasses = configuration.getPathToTestClasses();
+ }
+}
diff --git a/dspot/src/main/java/eu/stamp_project/dspot/selector/ChangeDetectorSelector.java b/dspot/src/main/java/eu/stamp_project/dspot/selector/ChangeDetectorSelector.java
index c1d5bf263..9fe239bce 100644
--- a/dspot/src/main/java/eu/stamp_project/dspot/selector/ChangeDetectorSelector.java
+++ b/dspot/src/main/java/eu/stamp_project/dspot/selector/ChangeDetectorSelector.java
@@ -2,6 +2,7 @@
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
+import eu.stamp_project.automaticbuilder.AutomaticBuilder;
import eu.stamp_project.automaticbuilder.maven.DSpotPOMCreator;
import eu.stamp_project.utils.report.output.selector.TestSelectorElementReport;
import eu.stamp_project.utils.report.output.selector.TestSelectorElementReportImpl;
@@ -16,6 +17,8 @@
import eu.stamp_project.utils.DSpotUtils;
import eu.stamp_project.utils.compilation.DSpotCompiler;
import eu.stamp_project.utils.execution.TestRunner;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import spoon.reflect.declaration.CtMethod;
import spoon.reflect.declaration.CtType;
@@ -30,7 +33,9 @@
* benjamin.danglot@inria.fr
* on 09/08/17
*/
-public class ChangeDetectorSelector implements TestSelector {
+public class ChangeDetectorSelector extends AbstractTestSelector {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(ChangeDetectorSelector.class);
private String pathToFirstVersionOfProgram;
@@ -40,22 +45,30 @@ public class ChangeDetectorSelector implements TestSelector {
private CtType> currentClassTestToBeAmplified;
- public ChangeDetectorSelector() {
- this.failurePerAmplifiedTest = new HashMap<>();
- }
+ private String secondVersionTargetClasses;
- @Override
- public boolean init() {
+ public ChangeDetectorSelector(AutomaticBuilder automaticBuilder, InputConfiguration configuration) {
+ super(automaticBuilder, configuration);
+ this.failurePerAmplifiedTest = new HashMap<>();
+ this.pathToFirstVersionOfProgram = configuration.getAbsolutePathToProjectRoot();
+ this.pathToSecondVersionOfProgram = configuration.getAbsolutePathToSecondVersionProjectRoot();
try {
- this.pathToFirstVersionOfProgram = InputConfiguration.get().getAbsolutePathToProjectRoot();
- this.pathToSecondVersionOfProgram = InputConfiguration.get().getAbsolutePathToSecondVersionProjectRoot();
- InputConfiguration.get().setAbsolutePathToProjectRoot(this.pathToSecondVersionOfProgram);
- DSpotPOMCreator.createNewPom();
- InputConfiguration.get().getBuilder().compile();
- InputConfiguration.get().setAbsolutePathToProjectRoot(this.pathToFirstVersionOfProgram);
+ this.automaticBuilder.setAbsolutePathToProjectRoot(this.pathToSecondVersionOfProgram);
+ configuration.setAbsolutePathToProjectRoot(this.pathToSecondVersionOfProgram);
+ this.secondVersionTargetClasses = configuration.getClasspathClassesProject();
+ DSpotPOMCreator.createNewPom(configuration);
+ this.automaticBuilder.compile();
} catch (Exception e) {
throw new RuntimeException(e);
+ } finally {
+ this.automaticBuilder.setAbsolutePathToProjectRoot(this.pathToFirstVersionOfProgram);
+ configuration.setAbsolutePathToProjectRoot(this.pathToFirstVersionOfProgram);
}
+ }
+
+ @Override
+ public boolean init() {
+
return true;
}
@@ -77,26 +90,26 @@ public List> selectToKeep(List> amplifiedTestToBeKept) {
CtType clone = this.currentClassTestToBeAmplified.clone();
clone.setParent(this.currentClassTestToBeAmplified.getParent());
this.currentClassTestToBeAmplified.getMethods().stream()
- .filter(TestFramework.get()::isTest)
+ .filter(TestFramework.get()::isTest)
.forEach(clone::removeMethod);
amplifiedTestToBeKept.forEach(clone::addMethod);
DSpotUtils.printCtTypeToGivenDirectory(clone, new File(DSpotCompiler.getPathToAmplifiedTestSrc()));
final String pathToAmplifiedTestSrc = DSpotCompiler.getPathToAmplifiedTestSrc();
- InputConfiguration.get().setAbsolutePathToProjectRoot(this.pathToSecondVersionOfProgram);
- DSpotCompiler.compile(
- InputConfiguration.get(),
+ this.automaticBuilder.setAbsolutePathToProjectRoot(this.pathToSecondVersionOfProgram);
+ if (!DSpotCompiler.compile(
pathToAmplifiedTestSrc,
- InputConfiguration.get().getFullClassPathWithExtraDependencies(),
- new File(this.pathToSecondVersionOfProgram + InputConfiguration.get().getPathToTestClasses())
- );
-
+ this.classpath + AmplificationHelper.PATH_SEPARATOR + this.secondVersionTargetClasses,
+ new File(this.pathToSecondVersionOfProgram + this.pathToTestClasses)
+ )) {
+ LOGGER.warn("Something went bad during the compilation of the amplified test methods using the second version.");
+ // add an error in the Main Global error report
+ }
final TestResult results;
try {
- InputConfiguration.get().setAbsolutePathToProjectRoot(this.pathToSecondVersionOfProgram);
results = TestRunner.run(
- InputConfiguration.get().getFullClassPathWithExtraDependencies(),
+ this.classpath + AmplificationHelper.PATH_SEPARATOR + this.secondVersionTargetClasses,
this.pathToSecondVersionOfProgram,
clone.getQualifiedName(),
amplifiedTestToBeKept.stream()
@@ -105,7 +118,7 @@ public List> selectToKeep(List> amplifiedTestToBeKept) {
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
- InputConfiguration.get().setAbsolutePathToProjectRoot(this.pathToFirstVersionOfProgram);
+ this.automaticBuilder.setAbsolutePathToProjectRoot(this.pathToFirstVersionOfProgram);
}
final List> amplifiedThatWillBeKept = new ArrayList<>();
if (!results.getFailingTests().isEmpty()) {
@@ -157,8 +170,7 @@ private TestClassJSON reportJson() {
}
TestClassJSON testClassJSON;
Gson gson = new GsonBuilder().setPrettyPrinting().create();
- final File file = new File(InputConfiguration.get().getOutputDirectory() + "/" +
- this.currentClassTestToBeAmplified.getQualifiedName() + "report.json");
+ final File file = new File(this.outputDirectory + "/" + this.currentClassTestToBeAmplified.getQualifiedName() + "report.json");
if (file.exists()) {
try {
testClassJSON = gson.fromJson(new FileReader(file), TestClassJSON.class);
diff --git a/dspot/src/main/java/eu/stamp_project/dspot/selector/JacocoCoverageSelector.java b/dspot/src/main/java/eu/stamp_project/dspot/selector/JacocoCoverageSelector.java
index 4eb7cac44..0ed661b32 100644
--- a/dspot/src/main/java/eu/stamp_project/dspot/selector/JacocoCoverageSelector.java
+++ b/dspot/src/main/java/eu/stamp_project/dspot/selector/JacocoCoverageSelector.java
@@ -2,13 +2,13 @@
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
+import eu.stamp_project.automaticbuilder.AutomaticBuilder;
import eu.stamp_project.utils.report.output.selector.TestSelectorElementReport;
import eu.stamp_project.utils.report.output.selector.TestSelectorElementReportImpl;
import eu.stamp_project.utils.report.output.selector.coverage.json.TestCaseJSON;
import eu.stamp_project.utils.report.output.selector.coverage.json.TestClassJSON;
import eu.stamp_project.testrunner.listener.Coverage;
import eu.stamp_project.testrunner.listener.CoveragePerTestMethod;
-import eu.stamp_project.utils.collector.CollectorConfig;
import eu.stamp_project.utils.program.InputConfiguration;
import eu.stamp_project.testrunner.EntryPoint;
import eu.stamp_project.utils.AmplificationHelper;
@@ -32,8 +32,6 @@
import java.util.function.Function;
import java.util.stream.Collectors;
-import static eu.stamp_project.utils.AmplificationHelper.PATH_SEPARATOR;
-
/**
* Created by Benjamin DANGLOT
* benjamin.danglot@inria.fr
@@ -49,6 +47,11 @@ public class JacocoCoverageSelector extends TakeAllSelector {
private TestSelectorElementReport lastReport;
+ public JacocoCoverageSelector(AutomaticBuilder automaticBuilder,
+ InputConfiguration configuration) {
+ super(automaticBuilder, configuration);
+ }
+
@Override
public boolean init() {
super.init();
@@ -60,15 +63,10 @@ public boolean init() {
public List> selectToAmplify(CtType> classTest, List> testsToBeAmplified) {
if (this.currentClassTestToBeAmplified == null) {
this.currentClassTestToBeAmplified = classTest;
- String classpath = InputConfiguration.get().getBuilder().buildClasspath();
- if (!InputConfiguration.get().getAdditionalClasspathElements().isEmpty()) {
- classpath += PATH_SEPARATOR + InputConfiguration.get().getProcessedAddtionalClasspathElements();
- }
- final String targetClasses = InputConfiguration.get().getClasspathClassesProject();
try {
this.initialCoverage = EntryPoint.runCoverage(
classpath + AmplificationHelper.PATH_SEPARATOR + targetClasses,
- targetClasses,
+ this.targetClasses,
this.currentClassTestToBeAmplified.getQualifiedName()
);
} catch (TimeoutException e) {
@@ -106,15 +104,10 @@ public List> selectToAmplify(CtType> classTest, List>
private CoveragePerTestMethod computeCoverageForGivenTestMethods(List> testsToBeAmplified) {
final String[] methodNames = testsToBeAmplified.stream().map(CtNamedElement::getSimpleName).toArray(String[]::new);
- String classpath = InputConfiguration.get().getBuilder().buildClasspath();
- if (!InputConfiguration.get().getAdditionalClasspathElements().isEmpty()) {
- classpath += PATH_SEPARATOR + InputConfiguration.get().getProcessedAddtionalClasspathElements();
- }
- final String targetClasses = InputConfiguration.get().getClasspathClassesProject();
try {
return EntryPoint.runCoveragePerTestMethods(
- classpath + AmplificationHelper.PATH_SEPARATOR + targetClasses,
- targetClasses,
+ this.classpath + AmplificationHelper.PATH_SEPARATOR + this.targetClasses,
+ this.targetClasses,
this.currentClassTestToBeAmplified.getQualifiedName(),
methodNames
);
@@ -198,20 +191,14 @@ public TestSelectorElementReport report() {
//ignored
}
DSpotUtils.printCtTypeToGivenDirectory(clone, new File(DSpotCompiler.getPathToAmplifiedTestSrc()));
-
- String classpath = InputConfiguration.get().getFullClassPathWithExtraDependencies();
- if (!InputConfiguration.get().getAdditionalClasspathElements().isEmpty()) {
- classpath += PATH_SEPARATOR + InputConfiguration.get().getProcessedAddtionalClasspathElements();
- }
-
- DSpotCompiler.compile(InputConfiguration.get(), DSpotCompiler.getPathToAmplifiedTestSrc(), classpath,
- new File(InputConfiguration.get().getAbsolutePathToTestClasses()));
-
- final String targetClasses = InputConfiguration.get().getClasspathClassesProject();
+ DSpotCompiler.compile(DSpotCompiler.getPathToAmplifiedTestSrc(),
+ this.classpath,
+ new File(this.pathToTestClasses)
+ );
try {
final Coverage coverageResults = EntryPoint.runCoverage(
- classpath,
- targetClasses,
+ this.classpath,
+ this.targetClasses,
this.currentClassTestToBeAmplified.getQualifiedName()
);
report.append("Amplified instruction coverage: ")
@@ -237,7 +224,7 @@ public TestSelectorElementReport report() {
private TestClassJSON jsonReport(Coverage coverageResults) {
TestClassJSON testClassJSON;
Gson gson = new GsonBuilder().setPrettyPrinting().create();
- final File file = new File(InputConfiguration.get().getOutputDirectory() + "/" +
+ final File file = new File(this.outputDirectory + "/" +
this.currentClassTestToBeAmplified.getQualifiedName() + "report.json");
if (file.exists()) {
try {
@@ -260,8 +247,8 @@ private TestClassJSON jsonReport(Coverage coverageResults) {
this.selectedToBeAmplifiedCoverageResultsMap.get(ctMethod.getSimpleName()).getInstructionsTotal()
)
);
-
- CollectorConfig.getInstance().getInformationCollector().reportSelectorInformation(testClassJSON.toString());
+// TODO
+// CollectorConfig.getInstance().getInformationCollector().reportSelectorInformation(testClassJSON.toString());
return testClassJSON;
}
}
diff --git a/dspot/src/main/java/eu/stamp_project/dspot/selector/PitMutantScoreSelector.java b/dspot/src/main/java/eu/stamp_project/dspot/selector/PitMutantScoreSelector.java
index 1b6f871e0..925edeb3a 100644
--- a/dspot/src/main/java/eu/stamp_project/dspot/selector/PitMutantScoreSelector.java
+++ b/dspot/src/main/java/eu/stamp_project/dspot/selector/PitMutantScoreSelector.java
@@ -18,10 +18,10 @@
import eu.stamp_project.utils.report.output.selector.mutant.json.TestClassJSON;
import eu.stamp_project.utils.Counter;
import eu.stamp_project.utils.DSpotUtils;
-import eu.stamp_project.utils.collector.CollectorConfig;
import eu.stamp_project.utils.program.InputConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import spoon.reflect.declaration.CtClass;
import spoon.reflect.declaration.CtMethod;
import spoon.reflect.declaration.CtType;
@@ -54,24 +54,35 @@ public enum OutputFormat {XML, CSV}
private TestSelectorElementReport lastReport;
- public PitMutantScoreSelector() {
- this(OutputFormat.XML);
- }
+ private CtClass> testClassTargetOne;
+
+ private boolean shouldTargetOneTestClass;
+
+ private String absolutePathToProjectRoot;
- public PitMutantScoreSelector(OutputFormat format) {
+ public PitMutantScoreSelector(AutomaticBuilder automaticBuilder,
+ InputConfiguration configuration) {
+ super(automaticBuilder, configuration);
+ this.absolutePathToProjectRoot = configuration.getAbsolutePathToProjectRoot();
+ this.shouldTargetOneTestClass = configuration.shouldTargetOneTestClass();
+ this.testClassTargetOne =
+ configuration.getTestClasses() == null || configuration.getTestClasses().isEmpty() ? null :
+ configuration.getFactory().Class().get(configuration.getTestClasses().get(0));
this.testThatKilledMutants = new HashMap<>();
- switch (format) {
- case XML:
- parser = new PitXMLResultParser();
- break;
- case CSV:
- parser = new PitCSVResultParser();
- break;
+ this.parser = new PitXMLResultParser();
+ final String pathPitResult = configuration.getPathPitResult();
+ if (pathPitResult == null || pathPitResult.isEmpty()) {
+ return;
+ }
+ PitMutantScoreSelector.OutputFormat originalFormat;
+ if (pathPitResult.toLowerCase().endsWith(".xml")) {
+ originalFormat = PitMutantScoreSelector.OutputFormat.XML;
+ } else if (pathPitResult.toLowerCase().endsWith(".csv")) {
+ originalFormat = PitMutantScoreSelector.OutputFormat.CSV;
+ } else {
+ LOGGER.warn("You specified the wrong Pit format. Skipping expert mode.");
+ originalFormat = PitMutantScoreSelector.OutputFormat.XML;
}
- }
-
- public PitMutantScoreSelector(String pathToOriginalResultOfPit, OutputFormat originalFormat, OutputFormat consecutiveFormat) {
- this(consecutiveFormat);
AbstractParser originalResultParser;
switch (originalFormat) {
case CSV:
@@ -81,27 +92,24 @@ public PitMutantScoreSelector(String pathToOriginalResultOfPit, OutputFormat ori
parser = originalResultParser = new PitXMLResultParser();
break;
}
- initOriginalPitResult(originalResultParser.parse(new File(pathToOriginalResultOfPit)));
+ initOriginalPitResult(originalResultParser.parse(new File(pathPitResult)));
}
@Override
public boolean init() {
if (this.originalKilledMutants == null) {
- final AutomaticBuilder automaticBuilder = InputConfiguration.get().getBuilder();
- if (InputConfiguration.get().shouldTargetOneTestClass()) {
- automaticBuilder.runPit(
- InputConfiguration.get().getFactory().Class().get(InputConfiguration.get().getTestClasses().get(0))
- );
+ if (shouldTargetOneTestClass) {
+ this.automaticBuilder.runPit(testClassTargetOne);
} else {
try {
- automaticBuilder.runPit();
+ this.automaticBuilder.runPit();
} catch (Throwable e) {
LOGGER.error(ErrorEnum.ERROR_ORIGINAL_MUTATION_SCORE.getMessage());
Main.GLOBAL_REPORT.addError(new Error(ErrorEnum.ERROR_ORIGINAL_MUTATION_SCORE, e));
return false;
}
}
- initOriginalPitResult(parser.parseAndDelete(InputConfiguration.get().getAbsolutePathToProjectRoot() + automaticBuilder.getOutputDirectoryPit()));
+ initOriginalPitResult(parser.parseAndDelete( this.absolutePathToProjectRoot + this.automaticBuilder.getOutputDirectoryPit()));
} else {
baselineKilledMutants = new ArrayList<>();
for(AbstractPitResult r : originalKilledMutants) {
@@ -122,9 +130,9 @@ private void initOriginalPitResult(List results) {
.filter(result -> result.getStateOfMutant() == AbstractPitResult.State.KILLED)
.collect(Collectors.toList());
LOGGER.info("The original test suite kill {} / {}", this.originalKilledMutants.size(), results.size());
- baselineKilledMutants = new ArrayList<>();
- for(AbstractPitResult r : originalKilledMutants) {
- baselineKilledMutants.add(r.clone());
+ this.baselineKilledMutants = new ArrayList<>();
+ for(AbstractPitResult r : this.originalKilledMutants) {
+ this.baselineKilledMutants.add(r.clone());
}
}
@@ -157,17 +165,18 @@ public List> selectToKeep(List> amplifiedTestToBeKept) {
//PIT cannot be executed on test classes containing parallel execution annotations
CloneHelper.removeParallelExecutionAnnotation(clone, amplifiedTestToBeKept);
DSpotUtils.printCtTypeToGivenDirectory(clone, new File(DSpotCompiler.getPathToAmplifiedTestSrc()));
- final AutomaticBuilder automaticBuilder = InputConfiguration.get().getBuilder();
- final String classpath = InputConfiguration.get().getBuilder()
+ final String classpath = this.automaticBuilder
.buildClasspath()
+ AmplificationHelper.PATH_SEPARATOR +
- InputConfiguration.get().getClasspathClassesProject()
+ this.targetClasses
+ AmplificationHelper.PATH_SEPARATOR + DSpotUtils.getAbsolutePathToDSpotDependencies();
- DSpotCompiler.compile(InputConfiguration.get(), DSpotCompiler.getPathToAmplifiedTestSrc(), classpath,
- new File(InputConfiguration.get().getAbsolutePathToTestClasses()));
-
- InputConfiguration.get().getBuilder().runPit(clone);
- final List results = parser.parseAndDelete(InputConfiguration.get().getAbsolutePathToProjectRoot() + automaticBuilder.getOutputDirectoryPit());
+ DSpotCompiler.compile(
+ DSpotCompiler.getPathToAmplifiedTestSrc(),
+ classpath,
+ new File(this.absolutePathToProjectRoot + "/" + this.pathToTestClasses)
+ );
+ this.automaticBuilder.runPit(clone);
+ final List results = parser.parseAndDelete(this.absolutePathToProjectRoot + automaticBuilder.getOutputDirectoryPit());
Set> selectedTests = new HashSet<>();
if (results != null) {
LOGGER.info("{} mutants has been generated ({})", results.size(), this.numberOfMutant);
@@ -269,7 +278,7 @@ private TestClassJSON reportJSONMutants() {
}
TestClassJSON testClassJSON;
Gson gson = new GsonBuilder().setPrettyPrinting().create();
- final File file = new File(InputConfiguration.get().getOutputDirectory() + "/" +
+ final File file = new File(this.outputDirectory + "/" +
this.currentClassTestToBeAmplified.getQualifiedName() + "report.json");
if (file.exists()) {
try {
@@ -312,7 +321,6 @@ private TestClassJSON reportJSONMutants() {
}
}
);
- CollectorConfig.getInstance().getInformationCollector().reportSelectorInformation(testClassJSON.toString());
return testClassJSON;
}
diff --git a/dspot/src/main/java/eu/stamp_project/dspot/selector/TakeAllSelector.java b/dspot/src/main/java/eu/stamp_project/dspot/selector/TakeAllSelector.java
index f3ce15808..41afab597 100644
--- a/dspot/src/main/java/eu/stamp_project/dspot/selector/TakeAllSelector.java
+++ b/dspot/src/main/java/eu/stamp_project/dspot/selector/TakeAllSelector.java
@@ -1,5 +1,7 @@
package eu.stamp_project.dspot.selector;
+import eu.stamp_project.automaticbuilder.AutomaticBuilder;
+import eu.stamp_project.utils.program.InputConfiguration;
import eu.stamp_project.utils.report.output.selector.TestSelectorElementReport;
import eu.stamp_project.utils.report.output.selector.TestSelectorElementReportImpl;
import spoon.reflect.declaration.CtMethod;
@@ -13,13 +15,14 @@
* benjamin.danglot@inria.fr
* on 08/08/17
*/
-public class TakeAllSelector implements TestSelector {
+public class TakeAllSelector extends AbstractTestSelector {
protected List> selectedAmplifiedTest;
protected CtType> currentClassTestToBeAmplified;
- public TakeAllSelector() {
+ public TakeAllSelector(AutomaticBuilder automaticBuilder, InputConfiguration configuration) {
+ super(automaticBuilder, configuration);
this.selectedAmplifiedTest = new ArrayList<>();
}
diff --git a/dspot/src/main/java/eu/stamp_project/test_framework/TestFramework.java b/dspot/src/main/java/eu/stamp_project/test_framework/TestFramework.java
index a1ef84c3b..986bdb285 100644
--- a/dspot/src/main/java/eu/stamp_project/test_framework/TestFramework.java
+++ b/dspot/src/main/java/eu/stamp_project/test_framework/TestFramework.java
@@ -10,7 +10,6 @@
import eu.stamp_project.utils.AmplificationHelper;
import eu.stamp_project.utils.DSpotCache;
import eu.stamp_project.utils.TypeUtils;
-import eu.stamp_project.utils.program.InputConfiguration;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -20,6 +19,7 @@
import spoon.reflect.declaration.CtElement;
import spoon.reflect.declaration.CtMethod;
import spoon.reflect.declaration.CtType;
+import spoon.reflect.factory.Factory;
import spoon.reflect.visitor.filter.TypeFilter;
import java.util.*;
@@ -37,7 +37,11 @@ public class TestFramework implements TestFrameworkSupport {
private static final Logger LOGGER = LoggerFactory.getLogger(TestFramework.class);
- private static final TestFramework _instance = new TestFramework();
+ private static TestFramework _instance;
+
+ public static void init(Factory factory) {
+ _instance = new TestFramework(factory);
+ }
private List testFrameworkSupportList;
@@ -45,7 +49,10 @@ public static TestFramework get() {
return _instance;
}
- private TestFramework() {
+ private Factory factory;
+
+ private TestFramework(Factory factory) {
+ this.factory = factory;
this.testFrameworkSupportList = new ArrayList<>();
this.testFrameworkSupportList.add(new JUnit3Support());
this.testFrameworkSupportList.add(new JUnit4Support());
@@ -198,9 +205,7 @@ public CtInvocation> buildInvocationToAssertion(CtMethod> testMethod, Assert
* We consider a class as test class if at least one of its method match {@link TestFramework#isTest(CtMethod)}
*/
public static Stream> getAllTestClassesAsStream() {
- return InputConfiguration.get()
- .getFactory()
- .Type()
+ return _instance.factory.Type()
.getAll()
.stream()
.filter(ctType ->
diff --git a/dspot/src/main/java/eu/stamp_project/test_framework/implementations/GoogleTruthTestFramework.java b/dspot/src/main/java/eu/stamp_project/test_framework/implementations/GoogleTruthTestFramework.java
index a91758f3e..1a9c801ee 100644
--- a/dspot/src/main/java/eu/stamp_project/test_framework/implementations/GoogleTruthTestFramework.java
+++ b/dspot/src/main/java/eu/stamp_project/test_framework/implementations/GoogleTruthTestFramework.java
@@ -2,7 +2,7 @@
import eu.stamp_project.test_framework.AbstractTestFrameworkDecorator;
import eu.stamp_project.test_framework.assertions.AssertEnum;
-import eu.stamp_project.utils.program.InputConfiguration;
+
import spoon.reflect.code.CtExpression;
import spoon.reflect.code.CtInvocation;
import spoon.reflect.declaration.CtElement;
@@ -26,7 +26,7 @@ public GoogleTruthTestFramework() {
@Override
public CtInvocation> buildInvocationToAssertion(CtMethod> testMethod, AssertEnum assertion, List arguments) {
- final Factory factory = InputConfiguration.get().getFactory();
+ final Factory factory = testMethod.getFactory();
//assertThat(actual)
final CtInvocation> assertThat = createAssertThat(arguments.get(arguments.size() - 1));
//isXXX(expected)
@@ -46,7 +46,7 @@ public CtInvocation> buildInvocationToAssertion(CtMethod> testMethod, Assert
@SuppressWarnings("unchecked")
private CtInvocation> createAssertThat(CtExpression> actual) {
- final Factory factory = InputConfiguration.get().getFactory();
+ final Factory factory = actual.getFactory();
final CtInvocation invocation = factory.createInvocation();
final CtExecutableReference executableReference = factory.Core().createExecutableReference();
executableReference.setStatic(true);
diff --git a/dspot/src/main/java/eu/stamp_project/test_framework/implementations/junit/JUnit4Support.java b/dspot/src/main/java/eu/stamp_project/test_framework/implementations/junit/JUnit4Support.java
index a701dbcc6..fe1b23127 100644
--- a/dspot/src/main/java/eu/stamp_project/test_framework/implementations/junit/JUnit4Support.java
+++ b/dspot/src/main/java/eu/stamp_project/test_framework/implementations/junit/JUnit4Support.java
@@ -1,7 +1,6 @@
package eu.stamp_project.test_framework.implementations.junit;
import eu.stamp_project.utils.AmplificationHelper;
-import eu.stamp_project.utils.program.InputConfiguration;
import spoon.reflect.code.CtExpression;
import spoon.reflect.code.CtLiteral;
import spoon.reflect.declaration.CtAnnotation;
@@ -46,7 +45,7 @@ protected String getFullQualifiedNameOfAnnotationIgnore() {
@Override
public CtMethod> prepareTestMethod(CtMethod> testMethod) {
final CtMethod> clone = super.prepareTestMethod(testMethod);
- final Factory factory = InputConfiguration.get().getFactory();
+ final Factory factory = testMethod.getFactory();
CtAnnotation testAnnotation = clone
.getAnnotations()
.stream()
diff --git a/dspot/src/main/java/eu/stamp_project/test_framework/implementations/junit/JUnitSupport.java b/dspot/src/main/java/eu/stamp_project/test_framework/implementations/junit/JUnitSupport.java
index a0e1aad9d..8ab8082a8 100644
--- a/dspot/src/main/java/eu/stamp_project/test_framework/implementations/junit/JUnitSupport.java
+++ b/dspot/src/main/java/eu/stamp_project/test_framework/implementations/junit/JUnitSupport.java
@@ -6,7 +6,6 @@
import eu.stamp_project.test_framework.assertions.AssertEnum;
import eu.stamp_project.testrunner.runner.Failure;
import eu.stamp_project.utils.DSpotUtils;
-import eu.stamp_project.utils.program.InputConfiguration;
import spoon.reflect.code.*;
import spoon.reflect.declaration.*;
import spoon.reflect.factory.Factory;
@@ -90,7 +89,7 @@ private boolean hasAnnotation(String fullQualifiedNameOfAnnotation, CtElement ca
*/
@Override
public CtInvocation> buildInvocationToAssertion(CtMethod> testMethod, AssertEnum assertion, List arguments) {
- final Factory factory = InputConfiguration.get().getFactory();
+ final Factory factory = testMethod.getFactory();
final CtInvocation invocation = factory.createInvocation();
final CtExecutableReference> executableReference = factory.Core().createExecutableReference();
executableReference.setStatic(true);
@@ -108,8 +107,7 @@ public CtInvocation> buildInvocationToAssertion(CtMethod> testMethod, Assert
public CtMethod> prepareTestMethod(CtMethod> testMethod) {
if (testMethod.getThrownTypes().isEmpty()) {
testMethod.addThrownType(
- InputConfiguration.get()
- .getFactory()
+ testMethod.getFactory()
.Type()
.createReference(Exception.class)
);
@@ -127,7 +125,7 @@ public CtMethod> prepareTestMethod(CtMethod> testMethod) {
@Override
public CtMethod> generateExpectedExceptionsBlock(CtMethod> test, Failure failure, int numberOfFail) {
- final Factory factory = InputConfiguration.get().getFactory();
+ final Factory factory = test.getFactory();
final String[] split = failure.fullQualifiedNameOfException.split("\\.");
final String simpleNameOfException = split[split.length - 1];
diff --git a/dspot/src/main/java/eu/stamp_project/utils/AmplificationHelper.java b/dspot/src/main/java/eu/stamp_project/utils/AmplificationHelper.java
index 21fc23cff..4a3f0fec6 100644
--- a/dspot/src/main/java/eu/stamp_project/utils/AmplificationHelper.java
+++ b/dspot/src/main/java/eu/stamp_project/utils/AmplificationHelper.java
@@ -2,8 +2,6 @@
import eu.stamp_project.test_framework.TestFramework;
import eu.stamp_project.testrunner.listener.TestResult;
-import eu.stamp_project.utils.program.InputConfiguration;
-import eu.stamp_project.utils.compilation.DSpotCompiler;
import org.apache.cxf.common.util.WeakIdentityHashMap;
import org.jetbrains.annotations.NotNull;
@@ -22,7 +20,6 @@
import spoon.reflect.visitor.filter.TypeFilter;
import java.text.DecimalFormat;
-import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
@@ -50,6 +47,18 @@ public class AmplificationHelper {
public static int timeOutInMs = 10000;
+ private static boolean shouldKeepOriginalTestMethods;
+
+ private static boolean shouldGenerateAmplifiedTestClass;
+
+ public static void init(int timeOutInMs,
+ boolean shouldGenerateAmplifiedTestClass,
+ boolean shouldKeepOriginalTestMethods) {
+ AmplificationHelper.timeOutInMs = timeOutInMs;
+ AmplificationHelper.shouldKeepOriginalTestMethods = shouldKeepOriginalTestMethods;
+ AmplificationHelper.shouldGenerateAmplifiedTestClass = shouldGenerateAmplifiedTestClass;
+ }
+
/**
* Link between an amplified test and its parent (i.e. the original test).
*/
@@ -78,7 +87,7 @@ public static CtType> createAmplifiedTest(List> ampTest, CtType>
classTest.getPackage().addType(currentTestClass);
methodToAdd.forEach(currentTestClass::addMethod);
// keep original test methods
- if (!InputConfiguration.get().shouldKeepOriginalTestMethods()) {
+ if (!shouldKeepOriginalTestMethods) {
classTest.getMethods().stream()
.filter(TestFramework.get()::isTest)
//.filter(AmplificationChecker::isTest)
@@ -90,7 +99,7 @@ public static CtType> createAmplifiedTest(List> ampTest, CtType>
public static CtType> renameTestClassUnderAmplification(CtType> classTest) {
final CtType> currentTestClass = classTest.clone();
// generate a new test class
- if (InputConfiguration.get().shouldGenerateAmplifiedTestClass()) {
+ if (shouldGenerateAmplifiedTestClass) {
final String amplifiedName = getAmplifiedName(classTest);
currentTestClass.setSimpleName(amplifiedName);
final CtTypeReference classTestReference = classTest.getReference();
@@ -230,14 +239,4 @@ public static CtMethod getTopParent(CtMethod test) {
}
return currentTest;
}
-
- @Deprecated
- public static String getClassPath(DSpotCompiler compiler, InputConfiguration configuration) {
- return Arrays.stream(new String[]{
- configuration.getAbsolutePathToClasses(),
- compiler.getBinaryOutputDirectory().getAbsolutePath(),
- compiler.getDependencies(),
- }
- ).collect(Collectors.joining(PATH_SEPARATOR));
- }
}
diff --git a/dspot/src/main/java/eu/stamp_project/utils/CloneHelper.java b/dspot/src/main/java/eu/stamp_project/utils/CloneHelper.java
index bb83cb881..cec400a38 100644
--- a/dspot/src/main/java/eu/stamp_project/utils/CloneHelper.java
+++ b/dspot/src/main/java/eu/stamp_project/utils/CloneHelper.java
@@ -1,7 +1,6 @@
package eu.stamp_project.utils;
import eu.stamp_project.test_framework.TestFramework;
-import eu.stamp_project.utils.program.InputConfiguration;
import spoon.reflect.declaration.CtAnnotation;
import spoon.reflect.declaration.CtMethod;
import spoon.reflect.declaration.CtType;
@@ -20,14 +19,19 @@
public class CloneHelper {
private static int cloneNumber = 1;
- final static Factory factory = InputConfiguration.get().getFactory();
public static void reset() {
cloneNumber = 1;
}
+ private static boolean shouldExecuteTestsInParallel;
+
+ public static void init(boolean shouldExecuteTestsInParallel) {
+ CloneHelper.shouldExecuteTestsInParallel = shouldExecuteTestsInParallel;
+ }
+
public static void addParallelExecutionAnnotation(CtType clone, List> tests) {
- if (InputConfiguration.get().shouldExecuteTestsInParallel()) {
+ if (shouldExecuteTestsInParallel) {
if (TestFramework.isJUnit5(tests.get(0))) {
addJUnit5ParallelExecutionAnnotation(clone);
} else {
@@ -66,6 +70,7 @@ private static void addJUnit4ParallelExecutionAnnotation(CtType clone) {
.filter(annotation -> annotation.toString().contains("RunWith"))
.findFirst().orElse(null);
if (existing_annotation == null) {
+ final Factory factory = clone.getFactory();
CtAnnotation annotation =
factory.Code().createAnnotation(factory.Code().createCtTypeReference(org.junit.runner.RunWith.class));
annotation.addValue("value", ParallelRunner.class);
@@ -78,6 +83,7 @@ private static void addJUnit5ParallelExecutionAnnotation(CtType clone) {
.filter(annotation -> annotation.toString().contains("Execution"))
.findFirst().orElse(null);
if (existing_annotation == null) {
+ final Factory factory = clone.getFactory();
CtAnnotation annotation =
factory.Code().createAnnotation(factory.Code().createCtTypeReference(org.junit.jupiter.api.parallel.Execution.class));
annotation.addValue("value", org.junit.jupiter.api.parallel.ExecutionMode.CONCURRENT);
diff --git a/dspot/src/main/java/eu/stamp_project/utils/DSpotCache.java b/dspot/src/main/java/eu/stamp_project/utils/DSpotCache.java
index 5e28d0841..f6b7a2bd8 100644
--- a/dspot/src/main/java/eu/stamp_project/utils/DSpotCache.java
+++ b/dspot/src/main/java/eu/stamp_project/utils/DSpotCache.java
@@ -7,27 +7,42 @@
import org.ehcache.config.builders.ResourcePoolsBuilder;
import eu.stamp_project.test_framework.TestFrameworkSupport;
-import eu.stamp_project.utils.program.ConstantsProperties;
public class DSpotCache {
- private static Cache frameworkCache;
- private static CacheManager cacheManager;
-
- static {
- cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
- .withCache("frameworkCache", CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class,
- TestFrameworkSupport.class, ResourcePoolsBuilder.heap(
- Long.parseLong(ConstantsProperties.CACHE_SIZE.getDefaultValue()))).build())
- .build(true);
+ private DSpotCache(long cacheSize) {
+ CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
+ .withCache("frameworkCache",
+ CacheConfigurationBuilder.newCacheConfigurationBuilder(
+ String.class,
+ TestFrameworkSupport.class,
+ ResourcePoolsBuilder.heap(cacheSize).build()
+ )
+ )
+ .build(true);
frameworkCache = cacheManager.getCache("frameworkCache", String.class, TestFrameworkSupport.class);
}
+ public static void init(long cacheSize) {
+ _instance = new DSpotCache(cacheSize);
+ }
+ private Cache frameworkCache;
+
+ private static DSpotCache _instance;
+
public static Cache getTestFrameworkCache() {
- return frameworkCache;
+ if (_instance == null) {
+ System.err.println("Must use at least one time init(long) method");
+ return null;
+ }
+ return _instance.frameworkCache;
}
public static void reset() {
- frameworkCache.clear();
+ if (_instance == null) {
+ System.err.println("Must use at least one time init(long) method");
+ } else {
+ _instance.frameworkCache.clear();
+ }
}
}
diff --git a/dspot/src/main/java/eu/stamp_project/utils/DSpotUtils.java b/dspot/src/main/java/eu/stamp_project/utils/DSpotUtils.java
index ad92c4510..f562e4faa 100644
--- a/dspot/src/main/java/eu/stamp_project/utils/DSpotUtils.java
+++ b/dspot/src/main/java/eu/stamp_project/utils/DSpotUtils.java
@@ -1,11 +1,10 @@
package eu.stamp_project.utils;
import eu.stamp_project.Main;
+import eu.stamp_project.utils.collector.Collector;
import eu.stamp_project.utils.compilation.DSpotCompiler;
-import eu.stamp_project.utils.program.InputConfiguration;
import eu.stamp_project.utils.report.error.Error;
import eu.stamp_project.utils.report.error.ErrorEnum;
-import eu.stamp_project.utils.collector.CollectorConfig;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -28,6 +27,8 @@
import java.util.function.Function;
import java.util.stream.Collectors;
+import static eu.stamp_project.utils.AmplificationHelper.PATH_SEPARATOR;
+
/**
* User: Simon Date: 18/05/16 Time: 16:10
*/
@@ -39,6 +40,25 @@ public class DSpotUtils {
private static StringBuilder progress = new StringBuilder(60);
+ private static boolean withComment;
+
+ private static String outputDirectory;
+
+ private static String fullClassPathWithExtraDependencies;
+
+ private static String absolutePathToProjectRoot;
+
+ public static void init(boolean withComment,
+ String outputDirectory,
+ String fullClassPathWithExtraDependencies,
+ String absolutePathToProjectRoot) {
+ DSpotUtils.withComment = withComment;
+ DSpotUtils.outputDirectory = outputDirectory;
+ DSpotUtils.fullClassPathWithExtraDependencies = fullClassPathWithExtraDependencies;
+ DSpotUtils.absolutePathToProjectRoot = absolutePathToProjectRoot;
+ DSpotUtils.copyPackageFromResources();
+ }
+
public static void printProgress(int done, int total) {
char[] workchars = {'|', '/', '-', '\\'};
String format = "\r%3d%% |%s ]%c";
@@ -65,7 +85,7 @@ public static void printCtTypeToGivenDirectory(CtType> type, File directory, b
Environment env = factory.getEnvironment();
env.setAutoImports(autoImports);
env.setNoClasspath(true);
- env.setCommentEnabled(InputConfiguration.get().withComment());
+ env.setCommentEnabled(DSpotUtils.withComment);
JavaOutputProcessor processor = new JavaOutputProcessor(new DefaultJavaPrettyPrinter(env));
processor.setFactory(factory);
processor.getEnvironment().setSourceOutputDirectory(directory);
@@ -80,8 +100,8 @@ static void printCtTypUsingToStringToGivenDirectory(CtType> type, File directo
LOGGER.warn("Something bad happened when trying to output {} in {}", type.getQualifiedName(), directory.getAbsolutePath());
LOGGER.warn("DSpot will now print the toString() in the given file instead of using Spoon...");
String directoryPathname = DSpotUtils.shouldAddSeparator.apply(directory.getAbsolutePath()) +
- type.getQualifiedName().substring(0, type.getQualifiedName().length() - type.getSimpleName().length()
- ).replaceAll("\\.", "/");
+ type.getQualifiedName().substring(0, type.getQualifiedName().length() - type.getSimpleName().length())
+ .replaceAll("\\.", "/");
try {
FileUtils.forceMkdir(new File(directoryPathname));
} catch (IOException e) {
@@ -101,7 +121,7 @@ static void printCtTypUsingToStringToGivenDirectory(CtType> type, File directo
We compile it.
If the compilation fails, we re-print it without imports, i.e. using full qualified names.
*/
- public static void printAndCompileToCheck(CtType> type, File directory) {
+ public static void printAndCompileToCheck(CtType> type, File directory, Collector collector) {
// get the existing amplified test class, if so
final String regex = File.separator.equals("/") ? "/" : "\\\\";
@@ -121,14 +141,14 @@ public static void printAndCompileToCheck(CtType> type, File directory) {
// compile
try {
- final boolean compile = DSpotCompiler.compile(InputConfiguration.get(), //FIXME: analyse for optimisation (36% total execution time)
+ final boolean compile = DSpotCompiler.compile(//FIXME: analyse for optimisation (36% total execution time)
pathname,
- InputConfiguration.get().getFullClassPathWithExtraDependencies(),
- new File(InputConfiguration.get().getOutputDirectory() + "/binaries/")
+ DSpotUtils.fullClassPathWithExtraDependencies,
+ new File(DSpotUtils.outputDirectory + "/binaries/")
);
if (!compile) {
try {
- FileUtils.forceDelete(new File(InputConfiguration.get().getOutputDirectory() + "/binaries/"));
+ FileUtils.forceDelete(new File(DSpotUtils.outputDirectory + "/binaries/"));
} catch (Exception ignored) {
}
@@ -137,7 +157,8 @@ public static void printAndCompileToCheck(CtType> type, File directory) {
LOGGER.warn("These problems can come from the fact your project use generated codes, such as Lombok annotations.");
printCtTypeToGivenDirectory(type, directory, false); //FIXME: analyse for optimisation (13% total execution time)
} else {
- CollectorConfig.getInstance().getInformationCollector().reportAmpTestPath(pathname);
+ // FIXME should not be here, this method should just print the amplified test class
+ collector.reportAmpTestPath(pathname);
}
} catch (Exception ignored) {
LOGGER.warn("Couldn't compile the final amplified test class.");
@@ -151,7 +172,12 @@ private static CtClass> getExistingClass(CtType> type, String pathname) {
launcher.getEnvironment().setNoClasspath(true);
launcher.addInputResource(pathname);
launcher.buildModel();
- return launcher.getFactory().Class().get(type.getQualifiedName());
+ CtClass
*
* @param testClass the test class to be compiled
* @param compiler the compiler
* @param testsToRun the test methods to be run, should be in testClass
- * @param configuration the configuration of the project
* @return an instance of {@link eu.stamp_project.testrunner.listener.TestResult}
* that contains the result of the execution of test methods if everything went fine, null otherwise.
* @throws AmplificationException in case the compilation failed or a timeout has been thrown.
*/
public static TestResult compileAndRun(CtType> testClass,
DSpotCompiler compiler,
- List> testsToRun,
- InputConfiguration configuration) throws AmplificationException {
- final String dependencies = configuration.getClasspathClassesProject()
- + AmplificationHelper.PATH_SEPARATOR + DSpotUtils.getAbsolutePathToDSpotDependencies();
- DSpotUtils.copyPackageFromResources();
- final String classPath = AmplificationHelper.getClassPath(compiler, configuration);
+ List> testsToRun) throws AmplificationException {
+ final String classPath = DSpotUtils.createPath(
+ _instance.classpathClassesProject,
+ compiler.getBinaryOutputDirectory().getAbsolutePath(),
+ compiler.getDependencies()
+ );
//Add parallel test execution support (JUnit4, JUnit5) for execution method (CMD, Maven)
- if (InputConfiguration.get().shouldExecuteTestsInParallel()) {
+ if (_instance.shouldExecuteTestsInParallel) {
CloneHelper.addParallelExecutionAnnotation (testClass, testsToRun);
//Create a junit-platform.properties for JUnit5 parallel execution
if (TestFramework.isJUnit5(testsToRun.get(0))) {
@@ -105,8 +134,7 @@ public static TestResult compileAndRun(CtType> testClass,
Properties props = new Properties();
props.setProperty("junit.jupiter.execution.parallel.enabled", "true");
props.setProperty("junit.jupiter.execution.parallel.config.strategy", "fixed");
- int numberProcessors = InputConfiguration.get().getNumberParallelExecutionProcessors();
- props.setProperty("junit.jupiter.execution.parallel.config.fixed.parallelism", Integer.toString(numberProcessors));
+ props.setProperty("junit.jupiter.execution.parallel.config.fixed.parallelism", Integer.toString(_instance.numberProcessors));
String rootPath = classPath.split(":")[0];
String junit5PropertiesPath = rootPath + "junit-platform.properties";
try {
@@ -128,8 +156,8 @@ public static TestResult compileAndRun(CtType> testClass,
}
}
- testsToRun = TestCompiler.compileAndDiscardUncompilableMethods(compiler, testClass, dependencies, testsToRun);
- EntryPoint.timeoutInMs = 1000 + (configuration.getTimeOutInMs() * testsToRun.size());
+ testsToRun = TestCompiler.compileAndDiscardUncompilableMethods(compiler, testClass, testsToRun);
+ EntryPoint.timeoutInMs = 1000 + (_instance.timeoutInMs * testsToRun.size());
if (testClass.getModifiers().contains(ModifierKind.ABSTRACT)) { // if the test class is abstract, we use one of its implementation
return TestRunner.runSubClassesForAbstractTestClass(testClass, testsToRun, classPath);
} else {
@@ -145,16 +173,14 @@ public static TestResult compileAndRun(CtType> testClass,
*
* @param compiler the compiler
* @param testClassToBeCompiled the test class to be compiled
- * @param dependencies the dependencies path, must be separated by the system path separator
* @return a list that contains uncompilable methods in testClassToBeCompiled
* @throws AmplificationException in case the compilation thrown an exception.
* This Exception is not thrown when the compilation fails but rather when the arguments are wrong.
*/
public static List> compileAndDiscardUncompilableMethods(DSpotCompiler compiler,
CtType> testClassToBeCompiled,
- String dependencies,
List> testsToRun) throws AmplificationException {
- final List> uncompilableMethod = compileAndDiscardUncompilableMethods(compiler, testClassToBeCompiled, dependencies, 0);
+ final List> uncompilableMethod = compileAndDiscardUncompilableMethods(compiler, testClassToBeCompiled, 0);
testsToRun.removeAll(uncompilableMethod);
uncompilableMethod.forEach(testClassToBeCompiled::removeMethod);
if (testsToRun.isEmpty()) {
@@ -165,11 +191,10 @@ public static List> compileAndDiscardUncompilableMethods(DSpotCompil
private static List> compileAndDiscardUncompilableMethods(DSpotCompiler compiler,
CtType> testClassToBeCompiled,
- String dependencies,
int numberOfTry) {
printJavaFileAndDeleteClassFile(compiler, testClassToBeCompiled);
- final List problems = compiler.compileAndReturnProblems(dependencies)
+ final List problems = compiler.compileAndReturnProblems(_instance.classpathToCompile)
.stream()
.filter(IProblem::isError)
.collect(Collectors.toList());
@@ -207,7 +232,7 @@ private static List> compileAndDiscardUncompilableMethods(DSpotCompi
);*/
methodsToRemoveInOriginalModel.forEach(testClassToBeCompiled::removeMethod);
final List> recursiveMethodToRemove =
- compileAndDiscardUncompilableMethods(compiler, testClassToBeCompiled, dependencies, numberOfTry + 1);
+ compileAndDiscardUncompilableMethods(compiler, testClassToBeCompiled, numberOfTry + 1);
methodsToRemoveInOriginalModel.addAll(recursiveMethodToRemove);
return new ArrayList<>(methodsToRemoveInOriginalModel);
}
@@ -255,4 +280,8 @@ private static void printJavaFileAndDeleteClassFile(DSpotCompiler compiler, CtTy
LOGGER.warn("An exception has been thrown when trying to delete old .class file {}, continue...", pathToDotClass);
}
}
+
+ public static void setTimeoutInMs(int timeoutInMs) {
+ _instance.timeoutInMs = timeoutInMs;
+ }
}
diff --git a/dspot/src/main/java/eu/stamp_project/utils/execution/TestRunner.java b/dspot/src/main/java/eu/stamp_project/utils/execution/TestRunner.java
index 8f07e4f00..f4d30642f 100644
--- a/dspot/src/main/java/eu/stamp_project/utils/execution/TestRunner.java
+++ b/dspot/src/main/java/eu/stamp_project/utils/execution/TestRunner.java
@@ -1,9 +1,9 @@
package eu.stamp_project.utils.execution;
+import eu.stamp_project.Main;
import eu.stamp_project.automaticbuilder.maven.DSpotPOMCreator;
import eu.stamp_project.dspot.AmplificationException;
import eu.stamp_project.testrunner.listener.TestResult;
-import eu.stamp_project.utils.program.InputConfiguration;
import eu.stamp_project.testrunner.EntryPoint;
import eu.stamp_project.utils.AmplificationHelper;
import eu.stamp_project.utils.DSpotUtils;
@@ -30,6 +30,19 @@ public class TestRunner {
private static final Logger LOGGER = LoggerFactory.getLogger(TestRunner.class);
+ private static String absolutePathToProjectRoot;
+
+ private static String preGoals;
+
+ private static boolean shouldUseMavenToExecuteTest;
+
+ public static void init(String absolutePathToProjectRoot, String preGoals, boolean shouldUseMavenToExecuteTest) {
+ TestRunner.absolutePathToProjectRoot = absolutePathToProjectRoot;
+ TestRunner.preGoals = preGoals;
+ TestRunner.shouldUseMavenToExecuteTest = shouldUseMavenToExecuteTest;
+ EntryPoint.verbose = Main.verbose;
+ }
+
public static TestResult runSubClassesForAbstractTestClass(CtType> testClass, List> testsToRun, String classPath) throws AmplificationException {
try {
return testClass.getFactory().Type()
@@ -64,7 +77,7 @@ public static TestResult runSubClassesForAbstractTestClass(CtType> testClass,
public static TestResult runGivenTestMethods(CtType> testClass, List> testsToRun, String classPath) throws AmplificationException {
try {
return TestRunner.run(classPath + AmplificationHelper.PATH_SEPARATOR + DSpotUtils.getAbsolutePathToDSpotDependencies(),
- InputConfiguration.get().getAbsolutePathToProjectRoot(),
+ absolutePathToProjectRoot,
testClass.getQualifiedName(),
testsToRun.stream()
.map(CtMethod::getSimpleName)
@@ -82,12 +95,13 @@ public static TestResult runGivenTestMethods(CtType> testClass, List deprecatedValuesToNewNames = new HashMap<>();
+ private final Amplifier amplifier;
- static {
- deprecatedValuesToNewNames.put("MethodAdd", "MethodDuplicationAmplifier");
- deprecatedValuesToNewNames.put("TestDataMutator", "FastLiteralAmplifier");
- deprecatedValuesToNewNames.put("MethodGeneratorAmplifier", "MethodAdderOnExistingObjectsAmplifier");
+ public Amplifier getAmplifier() {
+ return this.amplifier;
}
- private AmplifierEnum(Amplifier amplifier) {
+ AmplifierEnum(Amplifier amplifier) {
this.amplifier = amplifier;
}
-
- private static Amplifier stringToAmplifier(String amplifier) {
- try {
- if (deprecatedValuesToNewNames.containsKey(amplifier)) {
- JSAPOptions.LOGGER.warn("You are using an old name: " + amplifier + ".");
- JSAPOptions.LOGGER.warn("You should use the new name: " + deprecatedValuesToNewNames.get(amplifier) + ".");
- JSAPOptions.LOGGER.warn("The entry " + amplifier + " will be deleted very soon.");
- }
- return AmplifierEnum.valueOf(amplifier).amplifier;
- } catch (IllegalArgumentException e) {
- // should not happen since we checked values with Checker.checkEnumAndRemoveIfIncorrect
- throw new RuntimeException(e);
- }
- }
-
- public static List buildAmplifiersFromString(List amplifiersAsString) {
- if (amplifiersAsString.size() == 0 || "None".equals(amplifiersAsString.get(0))) {
- return Collections.emptyList();
- } else {
- return amplifiersAsString.stream()
- .map(AmplifierEnum::stringToAmplifier)
- .filter(Objects::nonNull)
- .collect(Collectors.toList());
- }
- }
}
diff --git a/dspot/src/main/java/eu/stamp_project/utils/options/AutomaticBuilderEnum.java b/dspot/src/main/java/eu/stamp_project/utils/options/AutomaticBuilderEnum.java
new file mode 100644
index 000000000..d812095c0
--- /dev/null
+++ b/dspot/src/main/java/eu/stamp_project/utils/options/AutomaticBuilderEnum.java
@@ -0,0 +1,30 @@
+package eu.stamp_project.utils.options;
+
+import eu.stamp_project.automaticbuilder.AutomaticBuilder;
+import eu.stamp_project.automaticbuilder.gradle.GradleAutomaticBuilder;
+import eu.stamp_project.automaticbuilder.maven.MavenAutomaticBuilder;
+import eu.stamp_project.utils.program.InputConfiguration;
+
+/**
+ * Created by Benjamin DANGLOT
+ * benjamin.danglot@inria.fr
+ * on 03/10/19
+ */
+public enum AutomaticBuilderEnum {
+
+ Maven() {
+ @Override
+ public AutomaticBuilder getAutomaticBuilder(InputConfiguration configuration) {
+ return new MavenAutomaticBuilder(configuration);
+ }
+ },
+ Gradle() {
+ @Override
+ public AutomaticBuilder getAutomaticBuilder(InputConfiguration configuration) {
+ return new GradleAutomaticBuilder(configuration);
+ }
+ };
+
+ public abstract AutomaticBuilder getAutomaticBuilder(InputConfiguration configuration);
+
+}
diff --git a/dspot/src/main/java/eu/stamp_project/utils/options/CollectorEnum.java b/dspot/src/main/java/eu/stamp_project/utils/options/CollectorEnum.java
index 7929d4fb1..d6d839007 100644
--- a/dspot/src/main/java/eu/stamp_project/utils/options/CollectorEnum.java
+++ b/dspot/src/main/java/eu/stamp_project/utils/options/CollectorEnum.java
@@ -1,23 +1,7 @@
package eu.stamp_project.utils.options;
-import eu.stamp_project.utils.collector.DspotInformationCollector;
-import eu.stamp_project.utils.collector.mongodb.MongodbCollector;
-import eu.stamp_project.utils.collector.NullCollector;
-
// Pick the correct collector based on JSAP input.
public enum CollectorEnum {
- NullCollector {
- @Override
- public DspotInformationCollector getCollector() {
- return new NullCollector();
- }
- },
- MongodbCollector {
- @Override
- public DspotInformationCollector getCollector() {
- return new MongodbCollector();
- }
- };
-
- public abstract DspotInformationCollector getCollector();
+ NullCollector,
+ MongodbCollector;
}
diff --git a/dspot/src/main/java/eu/stamp_project/utils/options/Configuration.java b/dspot/src/main/java/eu/stamp_project/utils/options/Configuration.java
deleted file mode 100644
index 1b472125e..000000000
--- a/dspot/src/main/java/eu/stamp_project/utils/options/Configuration.java
+++ /dev/null
@@ -1,315 +0,0 @@
-package eu.stamp_project.utils.options;
-
-import eu.stamp_project.dspot.amplifier.FastLiteralAmplifier;
-import eu.stamp_project.dspot.selector.JacocoCoverageSelector;
-import eu.stamp_project.dspot.selector.PitMutantScoreSelector;
-import eu.stamp_project.dspot.selector.TestSelector;
-import eu.stamp_project.utils.options.check.Checker;
-import eu.stamp_project.utils.program.InputConfiguration;
-import eu.stamp_project.utils.collector.CollectorConfig;
-import eu.stamp_project.utils.smtp.SmtpConfig;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.util.Collections;
-import java.util.List;
-import java.util.Properties;
-
-/**
- * Created by Benjamin DANGLOT
- * benjamin.danglot@inria.fr
- * on 28/05/19
- */
-public class Configuration {
- private static final Logger LOGGER = LoggerFactory.getLogger(Configuration.class);
-
- static void configureExample() {
- try {
- InputConfiguration.initialize("src/test/resources/test-projects/test-projects.properties");
- InputConfiguration.get().setNbIteration(1);
- InputConfiguration.get().setAmplifiers(Collections.singletonList(new FastLiteralAmplifier()));
- InputConfiguration.get().setSelector(new JacocoCoverageSelector());
- InputConfiguration.get().setBudgetizer(InputAmplDistributorEnum.RandomInputAmplDistributor);
- InputConfiguration.get().setTestClasses(Collections.singletonList("example.TestSuiteExample"));
- InputConfiguration.get().setTestCases(Collections.emptyList());
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- public static void configure(final String pathToPropertiesFile,
- final List amplifiers,
- final String selector,
- final String inputAmplDistributor,
- final String pitOutputFormat,
- final String pathPitResult,
- final String automaticBuilder,
- final String output,
- final int iteration,
- final long randomSeed,
- final int timeOut,
- final int maxTestAmplified,
- final boolean clean,
- final boolean verbose,
- final boolean workingDirectory,
- final boolean comment,
- final boolean generateNewTestClass,
- final boolean keepOriginalTestMethods,
- final boolean gregor,
- final boolean descartes,
- final boolean useMavenToExecuteTest,
- final boolean targetOneTestClass,
- final boolean allowPathInAssertion,
- final boolean executeTestsInParallel,
- final int numberParallelExecutionProcessors,
- final List testClasses,
- final List testCases,
- final String fullClasspath) {
-
- Checker.checkPathToPropertiesValue(pathToPropertiesFile);
- final Properties properties = loadProperties(pathToPropertiesFile);
- configure(
- properties,
- amplifiers,
- selector,
- inputAmplDistributor,
- pitOutputFormat,
- pathPitResult,
- automaticBuilder,
- output,
- iteration,
- randomSeed,
- timeOut,
- maxTestAmplified,
- clean,
- verbose,
- workingDirectory,
- comment,
- generateNewTestClass,
- keepOriginalTestMethods,
- gregor,
- descartes,
- useMavenToExecuteTest,
- targetOneTestClass,
- allowPathInAssertion,
- executeTestsInParallel,
- numberParallelExecutionProcessors,
- testClasses,
- testCases,
- fullClasspath
- );
- }
-
- public static void configure(Properties properties,
- final List amplifiers,
- final String selector,
- final String inputAmplDistributor,
- final String pitOutputFormat,
- final String pathPitResult,
- final String automaticBuilder,
- final String output,
- final int iteration,
- final long randomSeed,
- final int timeOut,
- final int maxTestAmplified,
- final boolean clean,
- final boolean verbose,
- final boolean workingDirectory,
- final boolean comment,
- final boolean generateNewTestClass,
- final boolean keepOriginalTestMethods,
- final boolean gregor,
- final boolean descartes,
- final boolean useMavenToExecuteTest,
- final boolean targetOneTestClass,
- final boolean allowPathInAssertion,
- final boolean executeTestsInParallel,
- final int numberParallelExecutionProcessors,
- final List testClasses,
- final List testCases,
- final String fullClasspath) {
- // pit output format
- PitMutantScoreSelector.OutputFormat consecutiveFormat;
- if (pitOutputFormat.toLowerCase().equals("xml")) {
- consecutiveFormat = PitMutantScoreSelector.OutputFormat.XML;
- } else if (pitOutputFormat.toLowerCase().equals("csv")) {
- consecutiveFormat = PitMutantScoreSelector.OutputFormat.CSV;
- } else {
- LOGGER.warn("You specified an invalid format. Forcing the Pit output format to XML.");
- consecutiveFormat = PitMutantScoreSelector.OutputFormat.XML;
- }
-
- Checker.preChecking(
- amplifiers,
- selector,
- inputAmplDistributor,
- properties
- );
-
- // expert test selector mode
- TestSelector testCriterion;
- if (pathPitResult != null) {
- if (!"PitMutantScoreSelector".equals(selector)) {
- LOGGER.warn("You specified a path to a mutations file but you did not specify the right test-criterion");
- LOGGER.warn("Forcing the Selector to PitMutantScoreSelector");
- }
- PitMutantScoreSelector.OutputFormat originalFormat;
- if (pathPitResult.toLowerCase().endsWith(".xml")) {
- originalFormat = PitMutantScoreSelector.OutputFormat.XML;
- } else if (pathPitResult.toLowerCase().endsWith(".csv")) {
- originalFormat = PitMutantScoreSelector.OutputFormat.CSV;
- } else {
- LOGGER.warn("You specified the wrong Pit format. Skipping expert mode.");
- originalFormat = PitMutantScoreSelector.OutputFormat.XML;
- }
- testCriterion = new PitMutantScoreSelector(pathPitResult, originalFormat, consecutiveFormat);
- } else {
- testCriterion = SelectorEnum.valueOf(selector).buildSelector();
- }
- //ExecuteTestsInParallel needs to be setup before initializing InputConfiguration
- //because it is required to compute the classpath of the MavenAutomaticBuilder
- InputConfiguration.initialize(properties, automaticBuilder, executeTestsInParallel, fullClasspath);
-
- if (InputConfiguration.get().getOutputDirectory().isEmpty()) {
-
- InputConfiguration.get().setOutputDirectory(output);
- }
-
- Checker.postChecking(properties);
-
- InputConfiguration.setUp(
- amplifiers,
- inputAmplDistributor,
- testCriterion,
- testClasses,
- testCases,
- iteration,
- randomSeed,
- timeOut,
- maxTestAmplified,
- clean,
- verbose,
- workingDirectory,
- comment,
- generateNewTestClass,
- keepOriginalTestMethods,
- gregor,
- descartes,
- useMavenToExecuteTest,
- targetOneTestClass,
- allowPathInAssertion,
- executeTestsInParallel,
- numberParallelExecutionProcessors
- );
- }
-
- public static void configure(final String pathToPropertiesFile,
- final List amplifiers,
- final String selector,
- final String inputAmplDistributor,
- final String pitOutputFormat,
- final String pathPitResult,
- final String automaticBuilder,
- final String output,
- final int iteration,
- final long randomSeed,
- final int timeOut,
- final int maxTestAmplified,
- final boolean clean,
- final boolean verbose,
- final boolean workingDirectory,
- final boolean comment,
- final boolean generateNewTestClass,
- final boolean keepOriginalTestMethods,
- final boolean gregor,
- final boolean descartes,
- final boolean useMavenToExecuteTest,
- final boolean targetOneTestClass,
- final boolean allowPathInAssertion,
- final boolean executeTestsInParallel,
- final int numberParallelExecutionProcessors,
- final List testClasses,
- final List testCases,
- final String fullClasspath,
- final String collector,
- final String mongoUrl,
- final String mongoDbname,
- final String mongoColname,
- final String repoSlug,
- final String repoBranch,
- final boolean restful,
- final String smtpUserName,
- final String smtpPassword,
- final String smtpHost,
- final String smtpPort,
- final boolean smtpAuth,
- final boolean smtpTls) {
-
- Checker.checkPathToPropertiesValue(pathToPropertiesFile);
- final Properties properties = loadProperties(pathToPropertiesFile);
- configure(properties,
- amplifiers,
- selector,
- inputAmplDistributor,
- pitOutputFormat,
- pathPitResult,
- automaticBuilder,
- output,
- iteration,
- randomSeed,
- timeOut,
- maxTestAmplified,
- clean,
- verbose,
- workingDirectory,
- comment,
- generateNewTestClass,
- keepOriginalTestMethods,
- gregor,
- descartes,
- useMavenToExecuteTest,
- targetOneTestClass,
- allowPathInAssertion,
- executeTestsInParallel,
- numberParallelExecutionProcessors,
- testClasses,
- testCases,
- fullClasspath);
-
- CollectorConfig collectorConfig = CollectorConfig.getInstance();
-
- collectorConfig.setMongoUrl(mongoUrl);
- collectorConfig.setMongoDbname(mongoDbname);
- collectorConfig.setMongoColname(mongoColname);
- collectorConfig.setRepoSlug(repoSlug);
- collectorConfig.setRepoBranch(repoBranch);
- collectorConfig.setRestful(restful);
- collectorConfig.setInformationCollector(collector);
-
- SmtpConfig smtpConfig = SmtpConfig.getInstance();
-
- smtpConfig.setSmtpUserName(smtpUserName);
- smtpConfig.setSmtpPassword(smtpPassword);
- smtpConfig.setSmtpHost(smtpHost);
- smtpConfig.setSmtpPort(smtpPort);
- smtpConfig.setSmtpAuth("" + smtpAuth);
- smtpConfig.setSmtpTls("" + smtpTls);
- }
-
- public static Properties loadProperties(String pathToPropertiesFile) {
- try {
- Properties properties = new Properties();
- if (pathToPropertiesFile == null || "".equals(pathToPropertiesFile)) {
- LOGGER.warn("You did not specify any path for the properties file. Using only default values.");
- } else {
- properties.load(new FileInputStream(pathToPropertiesFile));
- }
- return properties;
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
-}
diff --git a/dspot/src/main/java/eu/stamp_project/utils/options/InputAmplDistributorEnum.java b/dspot/src/main/java/eu/stamp_project/utils/options/InputAmplDistributorEnum.java
index 74014dcc7..2822c47ba 100644
--- a/dspot/src/main/java/eu/stamp_project/utils/options/InputAmplDistributorEnum.java
+++ b/dspot/src/main/java/eu/stamp_project/utils/options/InputAmplDistributorEnum.java
@@ -5,7 +5,6 @@
import eu.stamp_project.dspot.input_ampl_distributor.InputAmplDistributor;
import eu.stamp_project.dspot.input_ampl_distributor.RandomInputAmplDistributor;
-import java.util.Collections;
import java.util.List;
/**
@@ -17,51 +16,23 @@ public enum InputAmplDistributorEnum {
RandomInputAmplDistributor {
@Override
- public InputAmplDistributor getInputAmplDistributor() {
- return new RandomInputAmplDistributor();
- }
- @Override
- public InputAmplDistributor getInputAmplDistributor(Amplifier amplifier) {
- return new RandomInputAmplDistributor(Collections.singletonList(amplifier));
- }
- @Override
- public InputAmplDistributor getInputAmplDistributor(List amplifiers) {
- return new RandomInputAmplDistributor(amplifiers);
+ public InputAmplDistributor getInputAmplDistributor(int maxNumTest, List amplifiers) {
+ return new RandomInputAmplDistributor(maxNumTest, amplifiers);
}
},
TextualDistanceInputAmplDistributor {
@Override
- public InputAmplDistributor getInputAmplDistributor() {
- return new TextualDistanceInputAmplDistributor();
- }
- @Override
- public InputAmplDistributor getInputAmplDistributor(Amplifier amplifier) {
- return new TextualDistanceInputAmplDistributor(Collections.singletonList(amplifier));
- }
- @Override
- public InputAmplDistributor getInputAmplDistributor(List amplifiers) {
- return new TextualDistanceInputAmplDistributor(amplifiers);
+ public InputAmplDistributor getInputAmplDistributor(int maxNumTest, List amplifiers) {
+ return new TextualDistanceInputAmplDistributor(maxNumTest, amplifiers);
}
},
SimpleInputAmplDistributor {
@Override
- public InputAmplDistributor getInputAmplDistributor() {
- return new SimpleInputAmplDistributor();
- }
- @Override
- public InputAmplDistributor getInputAmplDistributor(Amplifier amplifier) {
- return new SimpleInputAmplDistributor(Collections.singletonList(amplifier));
- }
- @Override
- public InputAmplDistributor getInputAmplDistributor(List amplifiers) {
- return new SimpleInputAmplDistributor(amplifiers);
+ public InputAmplDistributor getInputAmplDistributor(int maxNumTest, List amplifiers) {
+ return new SimpleInputAmplDistributor(maxNumTest, amplifiers);
}
};
- public abstract InputAmplDistributor getInputAmplDistributor();
-
- public abstract InputAmplDistributor getInputAmplDistributor(Amplifier amplifier);
-
- public abstract InputAmplDistributor getInputAmplDistributor(List amplifiers);
+ public abstract InputAmplDistributor getInputAmplDistributor(int maxNumTest, List amplifiers);
}
diff --git a/dspot/src/main/java/eu/stamp_project/utils/options/JSAPOptions.java b/dspot/src/main/java/eu/stamp_project/utils/options/JSAPOptions.java
deleted file mode 100644
index 23605cba1..000000000
--- a/dspot/src/main/java/eu/stamp_project/utils/options/JSAPOptions.java
+++ /dev/null
@@ -1,595 +0,0 @@
-package eu.stamp_project.utils.options;
-
-import com.martiansoftware.jsap.Flagged;
-import com.martiansoftware.jsap.FlaggedOption;
-import com.martiansoftware.jsap.JSAP;
-import com.martiansoftware.jsap.JSAPException;
-import com.martiansoftware.jsap.JSAPResult;
-import com.martiansoftware.jsap.Parameter;
-import com.martiansoftware.jsap.Switch;
-import eu.stamp_project.utils.collector.CollectorConfig;
-import eu.stamp_project.dspot.selector.PitMutantScoreSelector;
-import eu.stamp_project.utils.options.check.Checker;
-import eu.stamp_project.utils.AmplificationHelper;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.*;
-import java.util.stream.Collectors;
-
-/**
- * Created by Benjamin DANGLOT
- * benjamin.danglot@inria.fr
- * on 1/17/17
- */
-public class JSAPOptions {
-
- static final Logger LOGGER = LoggerFactory.getLogger(JSAPOptions.class);
-
- private static final String SEPARATOR = AmplificationHelper.LINE_SEPARATOR + "\t\t - ";
-
- public static final JSAP options = initJSAP();
-
- /**
- * parse the command line argument
- * @param args command line arguments. Refer to the README on the github page or use --help command line option to display all the accepted arguments.
- * Otherwise, it returns false and DSpot will run normally, using the properties and the command line options.
- */
- public static void parse(String[] args) {
- JSAPResult jsapConfig = options.parse(args);
- if (!jsapConfig.success() || jsapConfig.getBoolean("help")) {
- System.err.println();
- for (Iterator> errs = jsapConfig.getErrorMessageIterator(); errs.hasNext(); ) {
- System.err.println("Error: " + errs.next());
- }
- showUsage();
- } else if (jsapConfig.getBoolean("example")) {
- Configuration.configureExample();
- return;
- }
-
- // getting first all the values of the command line.
- final String pathToProperties = jsapConfig.getString("path-to-properties");
- final List amplifiers = new ArrayList<>(Arrays.asList(jsapConfig.getStringArray("amplifiers")));
- final String testCriterion = jsapConfig.getString("test-criterion");
- final String inputAmplDistributor = jsapConfig.getString("input-ampl-distributor");
- final String pitOutputFormat = jsapConfig.getString("pit-output-format");
- final String pathPitResult = jsapConfig.getString("path-pit-result");
- final String automaticBuilder = jsapConfig.getString("automatic-builder");
- final String outputPath = jsapConfig.getString("output-path");
- final int iteration = jsapConfig.getInt("iteration");
- final long randomSeed = jsapConfig.getLong("random-seed");
- final int timeOut = jsapConfig.getInt("time-out");
- final int maxTestAmplified = jsapConfig.getInt("max-test-amplified");
- final boolean clean = jsapConfig.getBoolean("clean");
- final boolean verbose = jsapConfig.getBoolean("verbose");
- final boolean workingDirectory = jsapConfig.getBoolean("working-directory");
- final boolean withComment = jsapConfig.getBoolean("with-comment");
- final boolean generateNewTestClass = jsapConfig.getBoolean("generate-new-test-class");
- final boolean keepOriginalTestMethods = jsapConfig.getBoolean("keep-original-test-methods");
- final boolean gregor = jsapConfig.getBoolean("gregor");
- final boolean descartes = jsapConfig.getBoolean("descartes");
- final boolean useMavenToExeTest = jsapConfig.getBoolean("use-maven-to-exe-test");
- final boolean targetOneTestClass = jsapConfig.getBoolean("target-one-test-class");
- final boolean allowPathInAssertions = jsapConfig.getBoolean("allow-path-in-assertions");
- final int executeTestParallelWithNumberProcessors =
- jsapConfig.getInt("execute-test-parallel-with-number-processors") != 0 ?
- jsapConfig.getInt("execute-test-parallel-with-number-processors") : Runtime.getRuntime().availableProcessors();
- final boolean executeTestsInParallel = jsapConfig.userSpecified("execute-test-parallel-with-number-processors");
- final String fullClasspath = jsapConfig.getString("full-classpath");
- final String collector = jsapConfig.getString("collector");
- final String mongoUrl = jsapConfig.getString("mongo-url");
- final String mongoDbname = jsapConfig.getString("mongo-dbname");
- final String mongoColname = jsapConfig.getString("mongo-colname");
- final String repoSlug = jsapConfig.getString("repo-slug");
- final String repoBranch = jsapConfig.getString("repo-branch");
- final boolean restful = jsapConfig.getBoolean("restful");
- final String smtpUsername = jsapConfig.getString("smtp-username");
- final String smtpPassword = jsapConfig.getString("smtp-password");
- final String smtpHost = jsapConfig.getString("smtp-host");
- final String smtpPort = jsapConfig.getString("smtp-port");
- final boolean smtpAuth = jsapConfig.getBoolean("smtp-auth");
- final boolean smtpTls = jsapConfig.getBoolean("smtp-tls");
-
- // these values need to be checked when the factory is available
- // We check them in DSpot class since we have the codes that allow to check them easily
- // and thus, the Factory will be created.
- // Anyway, the verification in DSpot is not yet too late nor deep in the amplification's process.
- final List test = Arrays.asList(jsapConfig.getStringArray("test"));
- final List testCases = Arrays.asList(jsapConfig.getStringArray("test-cases"));
-
- Configuration.configure(
- pathToProperties,
- amplifiers,
- testCriterion,
- inputAmplDistributor,
- pitOutputFormat,
- pathPitResult,
- automaticBuilder,
- outputPath,
- iteration,
- randomSeed,
- timeOut,
- maxTestAmplified,
- clean,
- verbose,
- workingDirectory,
- withComment,
- generateNewTestClass,
- keepOriginalTestMethods,
- gregor,
- descartes,
- useMavenToExeTest,
- targetOneTestClass,
- allowPathInAssertions,
- executeTestsInParallel,
- executeTestParallelWithNumberProcessors,
- test,
- testCases,
- fullClasspath,
- collector,
- mongoUrl,
- mongoDbname,
- mongoColname,
- repoSlug,
- repoBranch,
- restful,
- smtpUsername,
- smtpPassword,
- smtpHost,
- smtpPort,
- smtpAuth,
- smtpTls
- );
-
- CollectorConfig.getInformationCollector().reportInitInformation(jsapConfig);
- }
-
- private static String helpForEnums(Class> enumClass) {
- return AmplificationHelper.LINE_SEPARATOR + "Possible values are: " +
- SEPARATOR + String.join(SEPARATOR, Checker.getPossibleValues(enumClass))
- + AmplificationHelper.LINE_SEPARATOR;
- }
-
- public static void showUsage() {
- System.err.println();
- System.err.println("Usage: java -jar target/dspot--jar-with-dependencies.jar");
- System.err.println(" " + options.getUsage());
- System.err.println();
- System.err.println(options.getHelp());
- System.exit(1);
- }
-
- private static JSAP initJSAP() {
- JSAP jsap = new JSAP();
-
- Switch help = new Switch("help");
- help.setDefault("false");
- help.setLongFlag("help");
- help.setShortFlag('h');
- help.setHelp("show this help");
-
- Switch example = new Switch("example");
- example.setDefault("false");
- example.setLongFlag("example");
- example.setShortFlag('e');
- example.setHelp("run the example of DSpot and leave");
-
- FlaggedOption pathToConfigFile = new FlaggedOption("path-to-properties");
- pathToConfigFile.setAllowMultipleDeclarations(false);
- pathToConfigFile.setLongFlag("path-to-properties");
- pathToConfigFile.setShortFlag('p');
- pathToConfigFile.setStringParser(JSAP.STRING_PARSER);
- pathToConfigFile.setUsageName("./path/to/myproject.properties");
- pathToConfigFile.setHelp("[mandatory] specify the path to the configuration file (format Java properties) of the target project (e.g. ./foo.properties).");
-
- FlaggedOption amplifiers = new FlaggedOption("amplifiers");
- amplifiers.setList(true);
- amplifiers.setLongFlag("amplifiers");
- amplifiers.setShortFlag('a');
- amplifiers.setStringParser(JSAP.STRING_PARSER);
- amplifiers.setUsageName("Amplifier");
- amplifiers.setDefault("None");
- amplifiers.setHelp("[optional] specify the list of amplifiers to use. By default, DSpot does not use any amplifiers (None) and applies only assertion amplification." + JSAPOptions.helpForEnums(AmplifierEnum.class));
-
- FlaggedOption iteration = new FlaggedOption("iteration");
- iteration.setDefault("3");
- iteration.setStringParser(JSAP.INTEGER_PARSER);
- iteration.setShortFlag('i');
- iteration.setLongFlag("iteration");
- iteration.setAllowMultipleDeclarations(false);
- iteration.setHelp("[optional] specify the number of amplification iterations. A larger number may help to improve the test criterion (e.g. a larger number of iterations may help to kill more mutants). This has an impact on the execution time: the more iterations, the longer DSpot runs.");
-
- FlaggedOption selector = new FlaggedOption("test-criterion");
- selector.setAllowMultipleDeclarations(false);
- selector.setLongFlag("test-criterion");
- selector.setShortFlag('s');
- selector.setStringParser(JSAP.STRING_PARSER);
- selector.setUsageName("PitMutantScoreSelector | JacocoCoverageSelector | TakeAllSelector |Â ChangeDetectorSelector");
- selector.setHelp("[optional] specify the test adequacy criterion to be maximized with amplification." + JSAPOptions.helpForEnums(SelectorEnum.class));
- selector.setDefault("PitMutantScoreSelector");
-
- FlaggedOption pitOutputFormat = new FlaggedOption("pit-output-format");
- pitOutputFormat.setAllowMultipleDeclarations(false);
- pitOutputFormat.setLongFlag("pit-output-format");
- pitOutputFormat.setStringParser(JSAP.STRING_PARSER);
- pitOutputFormat.setUsageName("XML | CSV");
- pitOutputFormat.setHelp("[optional] specify the Pit output format." + JSAPOptions.helpForEnums(PitMutantScoreSelector.OutputFormat.class));
- pitOutputFormat.setDefault("XML");
-
- FlaggedOption specificTestClass = new FlaggedOption("test");
- specificTestClass.setStringParser(JSAP.STRING_PARSER);
- specificTestClass.setShortFlag('t');
- specificTestClass.setList(true);
- specificTestClass.setAllowMultipleDeclarations(false);
- specificTestClass.setLongFlag("test");
- specificTestClass.setDefault("all");
- specificTestClass.setUsageName("my.package.MyClassTest | all");
- specificTestClass.setHelp("[optional] fully qualified names of test classes to be amplified. If the value is all, DSpot will amplify the whole test suite. You can also use regex to describe a set of test classes. By default, DSpot selects all the tests (value all).");
-
- FlaggedOption output = new FlaggedOption("output-path");
- output.setStringParser(JSAP.STRING_PARSER);
- output.setAllowMultipleDeclarations(false);
- output.setShortFlag('o');
- output.setLongFlag("output-path");
- output.setDefault("target/dspot/output");
- output.setHelp("[optional] specify the output folder");
-
- Switch cleanOutput = new Switch("clean");
- cleanOutput.setLongFlag("clean");
- cleanOutput.setDefault("false");
- cleanOutput.setHelp("[optional] if enabled, DSpot will remove the out directory if exists, else it will append the results to the exist files.");
-
- FlaggedOption mutantScore = new FlaggedOption("path-pit-result");
- mutantScore.setStringParser(JSAP.STRING_PARSER);
- mutantScore.setAllowMultipleDeclarations(false);
- mutantScore.setShortFlag('m');
- mutantScore.setLongFlag("path-pit-result");
- mutantScore.setUsageName("./path/to/mutations.csv");
- mutantScore.setHelp("[optional, expert mode] specify the path to the .xml or .csv of the original result of Pit Test. If you use this option the selector will be forced to PitMutantScoreSelector");
-
- Switch targetOneTestClass = new Switch("target-one-test-class");
- targetOneTestClass.setLongFlag("target-one-test-class");
- targetOneTestClass.setHelp("[optional, expert] enable this option will make DSpot computing the mutation score of only one test class (the first pass through --test command line option)");
- targetOneTestClass.setDefault("false");
-
-
- FlaggedOption testCases = new FlaggedOption("test-cases");
- testCases.setList(true);
- testCases.setAllowMultipleDeclarations(false);
- testCases.setLongFlag("test-cases");
- testCases.setShortFlag('c');
- testCases.setStringParser(JSAP.STRING_PARSER);
- testCases.setHelp("specify the test cases to amplify");
-
- FlaggedOption seed = new FlaggedOption("random-seed");
- seed.setStringParser(JSAP.LONG_PARSER);
- seed.setLongFlag("random-seed");
- seed.setUsageName("long integer");
- seed.setHelp("specify a seed for the random object (used for all randomized operation)");
- seed.setDefault("23");
-
- FlaggedOption timeOut = new FlaggedOption("time-out");
- timeOut.setStringParser(JSAP.INTEGER_PARSER);
- timeOut.setLongFlag("time-out");
- timeOut.setUsageName("long integer");
- timeOut.setHelp("specify the timeout value of the degenerated tests in millisecond");
- timeOut.setDefault("10000");
-
- FlaggedOption automaticBuilder = new FlaggedOption("automatic-builder");
- automaticBuilder.setStringParser(JSAP.STRING_PARSER);
- automaticBuilder.setLongFlag("automatic-builder");
- automaticBuilder.setUsageName("MavenBuilder | GradleBuilder");
- automaticBuilder.setHelp("[optional] specify the automatic builder to build the project");
- automaticBuilder.setDefault("");
-
- FlaggedOption mavenHome = new FlaggedOption("maven-home");
- mavenHome.setStringParser(JSAP.STRING_PARSER);
- mavenHome.setLongFlag("maven-home");
- mavenHome.setUsageName("path to maven home");
- mavenHome.setHelp("specify the path to the maven home");
-
- Switch verbose = new Switch("verbose");
- verbose.setLongFlag("verbose");
- verbose.setDefault("false");
- verbose.setHelp("Enable verbose mode of DSpot.");
-
- FlaggedOption maxTestAmplified = new FlaggedOption("max-test-amplified");
- maxTestAmplified.setStringParser(JSAP.INTEGER_PARSER);
- maxTestAmplified.setLongFlag("max-test-amplified");
- maxTestAmplified.setUsageName("integer");
- maxTestAmplified.setHelp("[optional] specify the maximum number of amplified tests that dspot keeps (before generating assertion)");
- maxTestAmplified.setDefault("200");
-
- FlaggedOption inputAmplDistributor = new FlaggedOption("input-ampl-distributor");
- inputAmplDistributor.setStringParser(JSAP.STRING_PARSER);
- inputAmplDistributor.setLongFlag("input-ampl-distributor");
- inputAmplDistributor.setUsageName("RandomInputAmplDistributor | TextualDistanceInputAmplDistributor | SimpleInputAmplDistributor");
- inputAmplDistributor.setHelp("[optional] specify a Input Amplification Distributor." + JSAPOptions.helpForEnums(InputAmplDistributorEnum.class));
- inputAmplDistributor.setDefault("RandomInputAmplDistributor");
-
- Switch withComment = new Switch("with-comment");
- withComment.setLongFlag("with-comment");
- withComment.setDefault("false");
- withComment.setHelp("Enable comment on amplified test: details steps of the Amplification.");
-
- Switch descartes = new Switch("descartes");
- descartes.setLongFlag("descartes");
- descartes.setDefault("true");
- descartes.setHelp("Enable the descartes engine for Pit Mutant Score Selector.");
-
- Switch gregor = new Switch("gregor");
- gregor.setLongFlag("gregor");
- gregor.setDefault("false");
- gregor.setHelp("Enable the gregor engine for Pit Mutant Score Selector.");
-
- Switch nominimize = new Switch("no-minimize");
- nominimize.setLongFlag("no-minimize");
- nominimize.setDefault("false");
- nominimize.setHelp("Disable the minimization of amplified tests.");
-
- Switch useWorkingDirectory = new Switch("working-directory");
- useWorkingDirectory.setLongFlag("working-directory");
- useWorkingDirectory.setDefault("false");
- useWorkingDirectory.setHelp("Enable this option to change working directory with the root of the project.");
-
- Switch generateNewTestClass = new Switch("generate-new-test-class");
- generateNewTestClass.setLongFlag("generate-new-test-class");
- generateNewTestClass.setDefault("false");
- generateNewTestClass.setHelp("Enable the creation of a new test class.");
-
- Switch keepOriginalTestMethods = new Switch("keep-original-test-methods");
- keepOriginalTestMethods.setLongFlag("keep-original-test-methods");
- keepOriginalTestMethods.setDefault("false");
- keepOriginalTestMethods.setHelp("If enabled, DSpot keeps original test methods of the amplified test class.");
-
- Switch useMavenToExecuteTests = new Switch("use-maven-to-exe-test");
- useMavenToExecuteTests.setLongFlag("use-maven-to-exe-test");
- useMavenToExecuteTests.setDefault("false");
- useMavenToExecuteTests.setHelp("If enabled, DSpot will use maven to execute the tests.");
-
- FlaggedOption executeTestParallel = new FlaggedOption("execute-test-parallel-with-number-processors");
- executeTestParallel.setLongFlag("execute-test-parallel-with-number-processors");
- executeTestParallel.setDefault("0");
- executeTestParallel.setStringParser(JSAP.INTEGER_PARSER);
- executeTestParallel.setAllowMultipleDeclarations(false);
- executeTestParallel.setHelp("[optional] If enabled, DSpot will execute the tests in parallel. For JUnit5 tests it will use the number of given processors (specify 0 to take the number of available core processors). For JUnit4 tests, it will use the number of available CPU processors (given number of processors is ignored).");
-
- /*
- This switch allows DSpot to generate assertion on string values that look like paths.
- */
- Switch allowPathInAssertions = new Switch("allow-path-in-assertions");
- allowPathInAssertions.setLongFlag("allow-path-in-assertions");
- allowPathInAssertions.setDefault("false");
- allowPathInAssertions.setHelp("If enabled, DSpot will generate assertions for values that seems like to be paths.");
-
- FlaggedOption fullClasspath = new FlaggedOption("full-classpath");
- fullClasspath.setLongFlag("full-classpath");
- fullClasspath.setRequired(false);
- fullClasspath.setAllowMultipleDeclarations(false);
- fullClasspath.setStringParser(JSAP.STRING_PARSER);
- fullClasspath.setHelp("[optional] specify the classpath of the project. If this option is used, DSpot won't use an AutomaticBuilder (e.g. Maven) to clean, compile and get the classpath of the project. " +
- "Please ensure that your project is in a good shape, i.e. clean and correctly compiled, sources and test sources.");
-
- FlaggedOption collector = new FlaggedOption("collector");
- collector.setStringParser(JSAP.STRING_PARSER);
- collector.setLongFlag("collector");
- collector.setUsageName("NullCollector | MongodbCollector");
- collector.setHelp("[optional] set a collector: MongodbCollector to send info to Mongodb at end process, NullCollector which does nothing.");
- collector.setDefault("NullCollector");
-
- FlaggedOption mongoUrl = new FlaggedOption("mongo-url");
- mongoUrl.setLongFlag("mongo-url");
- mongoUrl.setDefault("mongodb://localhost:27017");
- mongoUrl.setRequired(false);
- mongoUrl.setStringParser(JSAP.STRING_PARSER);
- mongoUrl.setAllowMultipleDeclarations(false);
- mongoUrl.setHelp("[optional] If valid url, DSpot will submit to Mongodb database. For default use mongodb://localhost:27017");
-
- FlaggedOption mongoDbname = new FlaggedOption("mongo-dbname");
- mongoDbname.setLongFlag("mongo-dbname");
- mongoDbname.setDefault("Dspot");
- mongoDbname.setRequired(false);
- mongoDbname.setStringParser(JSAP.STRING_PARSER);
- mongoDbname.setAllowMultipleDeclarations(false);
- mongoDbname.setHelp("[optional] If valid mongo-url provided, DSpot will submit to the provided database name.");
-
- FlaggedOption mongoColname = new FlaggedOption("mongo-colname");
- mongoColname.setLongFlag("mongo-colname");
- mongoColname.setDefault("AmpRecords");
- mongoColname.setRequired(false);
- mongoColname.setStringParser(JSAP.STRING_PARSER);
- mongoColname.setAllowMultipleDeclarations(false);
- mongoColname.setHelp("[optional] If valid mongo-url and mongo-dbname provided, DSpot will submit to the provided collection name.");
-
- FlaggedOption repoSlug = new FlaggedOption("repo-slug");
- repoSlug.setLongFlag("repo-slug");
- repoSlug.setDefault("UnknownSlug");
- repoSlug.setRequired(false);
- repoSlug.setStringParser(JSAP.STRING_PARSER);
- repoSlug.setAllowMultipleDeclarations(false);
- repoSlug.setHelp("[optional] slug of the repo for instance Stamp/Dspot,this is used by mongodb as a identifier for analyzed repo's submitted data ");
-
- FlaggedOption repoBranch = new FlaggedOption("repo-branch");
- repoBranch.setLongFlag("repo-branch");
- repoBranch.setDefault("UnknownBranch");
- repoBranch.setRequired(false);
- repoBranch.setStringParser(JSAP.STRING_PARSER);
- repoBranch.setAllowMultipleDeclarations(false);
- repoBranch.setHelp("[optional] branch name of the submitted repo,this is used by mongodb as a identifier for analyzed repo's submitted data");
-
- Switch restful = new Switch("restful");
- restful.setLongFlag("restful");
- restful.setDefault("false");
- restful.setHelp("If 1 or true will enable restful mode for web Interface. It will look for a pending document in Mongodb with the corresponding slug and branch provided instead of creating a completely new one.");
-
- FlaggedOption smtpUsername = new FlaggedOption("smtp-username");
- smtpUsername.setLongFlag("smtp-username");
- smtpUsername.setDefault("Unknown@gmail.com");
- smtpUsername.setRequired(false);
- smtpUsername.setStringParser(JSAP.STRING_PARSER);
- smtpUsername.setAllowMultipleDeclarations(false);
- smtpUsername.setHelp("Username for Gmail, used for submit email at end-process");
-
- FlaggedOption smtpPassword = new FlaggedOption("smtp-password");
- smtpPassword.setLongFlag("smtp-password");
- smtpPassword.setDefault("Unknown");
- smtpPassword.setRequired(false);
- smtpPassword.setStringParser(JSAP.STRING_PARSER);
- smtpPassword.setAllowMultipleDeclarations(false);
- smtpPassword.setHelp("password for Gmail, used for submit email at end-process");
-
- FlaggedOption smtpHost = new FlaggedOption("smtp-host");
- smtpHost.setLongFlag("smtp-host");
- smtpHost.setDefault("smtp.gmail.com");
- smtpHost.setRequired(false);
- smtpHost.setStringParser(JSAP.STRING_PARSER);
- smtpHost.setAllowMultipleDeclarations(false);
- smtpHost.setHelp("host server name , default: smtp.gmail.com");
-
- FlaggedOption smtpPort = new FlaggedOption("smtp-port");
- smtpPort.setLongFlag("smtp-port");
- smtpPort.setDefault("587");
- smtpPort.setRequired(false);
- smtpPort.setStringParser(JSAP.STRING_PARSER);
- smtpPort.setAllowMultipleDeclarations(false);
- smtpPort.setHelp("host server port , default : 587");
-
- Switch smtpAuth = new Switch("smtp-auth");
- smtpAuth.setLongFlag("smtp-auth");
- smtpAuth.setDefault("false");
- smtpAuth.setHelp("true , if the smtp host server require auth, which is usually the case");
-
- Switch smtpTls = new Switch("smtp-tls");
- smtpTls.setLongFlag("smtp-tls");
- smtpTls.setDefault("false");
- smtpTls.setHelp("true , if need secure tls transport.");
-
- try {
- jsap.registerParameter(pathToConfigFile);
- jsap.registerParameter(amplifiers);
- jsap.registerParameter(iteration);
- jsap.registerParameter(selector);
- jsap.registerParameter(pitOutputFormat);
- jsap.registerParameter(inputAmplDistributor);
- jsap.registerParameter(maxTestAmplified);
- jsap.registerParameter(specificTestClass);
- jsap.registerParameter(testCases);
- jsap.registerParameter(output);
- jsap.registerParameter(cleanOutput);
- jsap.registerParameter(mutantScore);
- jsap.registerParameter(targetOneTestClass);
- jsap.registerParameter(descartes);
- jsap.registerParameter(gregor);
- jsap.registerParameter(automaticBuilder);
- jsap.registerParameter(mavenHome);
- jsap.registerParameter(seed);
- jsap.registerParameter(timeOut);
- jsap.registerParameter(verbose);
- jsap.registerParameter(withComment);
- jsap.registerParameter(nominimize);
- jsap.registerParameter(useWorkingDirectory);
- jsap.registerParameter(generateNewTestClass);
- jsap.registerParameter(keepOriginalTestMethods);
- jsap.registerParameter(useMavenToExecuteTests);
- jsap.registerParameter(allowPathInAssertions);
- jsap.registerParameter(executeTestParallel);
- jsap.registerParameter(fullClasspath);
- jsap.registerParameter(collector);
- jsap.registerParameter(mongoUrl);
- jsap.registerParameter(mongoDbname);
- jsap.registerParameter(mongoColname);
- jsap.registerParameter(repoSlug);
- jsap.registerParameter(repoBranch);
- jsap.registerParameter(restful);
- jsap.registerParameter(smtpUsername);
- jsap.registerParameter(smtpPassword);
- jsap.registerParameter(smtpHost);
- jsap.registerParameter(smtpPort);
- jsap.registerParameter(smtpAuth);
- jsap.registerParameter(smtpTls);
- jsap.registerParameter(example);
- jsap.registerParameter(help);
- } catch (JSAPException e) {
- throw new RuntimeException(e);
- }
- return jsap;
- }
-
- private static String jsapParameterFormatToMojoParameterFormat(String jsapOptionFormatted) {
- StringBuilder mojoParameterFormat = new StringBuilder();
- for (int i = 0; i < jsapOptionFormatted.length(); i++) {
- if (jsapOptionFormatted.charAt(i) == '-') {
- mojoParameterFormat.append(Character.toUpperCase(jsapOptionFormatted.charAt(++i)));
- } else {
- mojoParameterFormat.append(jsapOptionFormatted.charAt(i));
- }
- }
- return mojoParameterFormat.toString();
- }
-
- private static String jsapSwitchOptionToMojoParameter(Switch jsapSwitch) {
- return "Boolean " +
- jsapParameterFormatToMojoParameterFormat(jsapSwitch.getLongFlag())
- + ";" + AmplificationHelper.LINE_SEPARATOR;
- }
-
- private static String jsapFlaggedOptionToMojoParameter(FlaggedOption flaggedOption) {
- String mojoParam = "";
- final String type;
- if (flaggedOption.getStringParser().equals(JSAP.STRING_PARSER)) {
- type = "String";
- } else if (flaggedOption.getStringParser().equals(JSAP.LONG_PARSER)) {
- type = "Long";
- } else {
- type = "Integer";
- }
- if (flaggedOption.isList()) {
- mojoParam += "List<" + type + "> ";
- } else {
- mojoParam += type + " ";
- }
- mojoParam += jsapParameterFormatToMojoParameterFormat(flaggedOption.getLongFlag()) + ";" + AmplificationHelper.LINE_SEPARATOR;
- return mojoParam;
- }
-
- private static String jsapParameterToMojoParameter(Parameter parameter) {
- String mojoParam = "";
- if (parameter.getHelp() != null) {
- mojoParam += "/**" + AmplificationHelper.LINE_SEPARATOR;
- mojoParam += Arrays.stream(
- parameter.getHelp().split(AmplificationHelper.LINE_SEPARATOR))
- .map(" *\t"::concat)
- .collect(Collectors.joining(AmplificationHelper.LINE_SEPARATOR)) +
- AmplificationHelper.LINE_SEPARATOR;
- mojoParam += " */" + AmplificationHelper.LINE_SEPARATOR;
- }
- mojoParam += "@Parameter(";
- if (parameter.getDefault() != null) {
- mojoParam += "defaultValue = \"" + parameter.getDefault()[0] + "\", ";
- }
- mojoParam += "property = \"" + ((Flagged) parameter).getLongFlag() + "\")" + AmplificationHelper.LINE_SEPARATOR;
- mojoParam += "private ";
- if (parameter instanceof FlaggedOption) {
- return mojoParam + jsapFlaggedOptionToMojoParameter((FlaggedOption) parameter);
- } else if (parameter instanceof Switch) {
- return mojoParam + jsapSwitchOptionToMojoParameter((Switch) parameter);
- } else {
- System.out.println("Unsupported class: " + parameter.getClass());
- return "";
- }
- }
-
- /**
- * Main to be used to generate the DSpotMojo properties from the JSAPOptions.
- * @param args not used
- */
- public static void main(String[] args) {
- final Iterator iterator = options.getIDMap().idIterator();
- while (iterator.hasNext()) {
- final Object id = iterator.next();
- System.out.println(jsapParameterToMojoParameter(options.getByID((String) id)));
- }
- }
-
-}
diff --git a/dspot/src/main/java/eu/stamp_project/utils/options/SelectorEnum.java b/dspot/src/main/java/eu/stamp_project/utils/options/SelectorEnum.java
index b3c30471a..8681b8675 100644
--- a/dspot/src/main/java/eu/stamp_project/utils/options/SelectorEnum.java
+++ b/dspot/src/main/java/eu/stamp_project/utils/options/SelectorEnum.java
@@ -1,37 +1,39 @@
package eu.stamp_project.utils.options;
+import eu.stamp_project.automaticbuilder.AutomaticBuilder;
import eu.stamp_project.dspot.selector.ChangeDetectorSelector;
import eu.stamp_project.dspot.selector.JacocoCoverageSelector;
import eu.stamp_project.dspot.selector.PitMutantScoreSelector;
import eu.stamp_project.dspot.selector.TakeAllSelector;
import eu.stamp_project.dspot.selector.TestSelector;
+import eu.stamp_project.utils.program.InputConfiguration;
public enum SelectorEnum {
PitMutantScoreSelector {
@Override
- public TestSelector buildSelector() {
- return new PitMutantScoreSelector();
+ public TestSelector buildSelector(AutomaticBuilder builder, InputConfiguration configuration) {
+ return new PitMutantScoreSelector(builder, configuration);
}
},
JacocoCoverageSelector {
@Override
- public TestSelector buildSelector() {
- return new JacocoCoverageSelector();
+ public TestSelector buildSelector(AutomaticBuilder builder, InputConfiguration configuration) {
+ return new JacocoCoverageSelector(builder, configuration);
}
},
TakeAllSelector {
@Override
- public TestSelector buildSelector() {
- return new TakeAllSelector();
+ public TestSelector buildSelector(AutomaticBuilder builder, InputConfiguration configuration) {
+ return new TakeAllSelector(builder, configuration);
}
},
ChangeDetectorSelector {
@Override
- public TestSelector buildSelector() {
- return new ChangeDetectorSelector();
+ public TestSelector buildSelector(AutomaticBuilder builder, InputConfiguration configuration) {
+ return new ChangeDetectorSelector(builder, configuration);
}
};
- public abstract TestSelector buildSelector();
+ public abstract TestSelector buildSelector(AutomaticBuilder builder, InputConfiguration configuration);
}
diff --git a/dspot/src/main/java/eu/stamp_project/utils/options/check/Checker.java b/dspot/src/main/java/eu/stamp_project/utils/options/check/Checker.java
index 958c6b4ac..48e54ee7a 100644
--- a/dspot/src/main/java/eu/stamp_project/utils/options/check/Checker.java
+++ b/dspot/src/main/java/eu/stamp_project/utils/options/check/Checker.java
@@ -3,10 +3,7 @@
import eu.stamp_project.Main;
import eu.stamp_project.utils.AmplificationHelper;
import eu.stamp_project.utils.DSpotUtils;
-import eu.stamp_project.utils.options.AmplifierEnum;
-import eu.stamp_project.utils.options.InputAmplDistributorEnum;
-import eu.stamp_project.utils.options.SelectorEnum;
-import eu.stamp_project.utils.program.ConstantsProperties;
+import eu.stamp_project.utils.program.InputConfiguration;
import eu.stamp_project.utils.report.error.Error;
import eu.stamp_project.utils.report.error.ErrorEnum;
import org.jetbrains.annotations.NotNull;
@@ -18,7 +15,6 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
-import java.util.Properties;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
@@ -35,50 +31,9 @@ public class Checker {
Checking algo
*/
- public static void preChecking(List amplifiers,
- String selector,
- String budgetizer,
- Properties properties) {
- Checker.checkEnum(AmplifierEnum.class, amplifiers, "amplifiers");
- Checker.checkEnum(SelectorEnum.class, selector, "test-criterion");
- Checker.checkEnum(InputAmplDistributorEnum.class, budgetizer, "budgetizer");
- Checker.checkProperties(properties);
- }
-
- public static void postChecking(Properties properties) {
- // we check now the binaries folders after the compilation
- Checker.checkBinariesFolders(properties);
- }
-
-
- /*
- PROPERTIES CHECK
- */
-
- public static void checkBinariesFolders(Properties properties) {
-
- String currentPath = DSpotUtils.shouldAddSeparator.apply(properties.getProperty(ConstantsProperties.PROJECT_ROOT_PATH.getName()));
- final String targetModulePropertyValue = DSpotUtils.shouldAddSeparator.apply(properties.getProperty(ConstantsProperties.MODULE.getName()));
- currentPath += targetModulePropertyValue != null ? targetModulePropertyValue : "";
-
- // binary folders: classes and test-classes
- Checker.checkPathPropertyValue(
- properties.getProperty(ConstantsProperties.SRC_CLASSES.getName()),
- ErrorEnum.ERROR_PATH_TO_SRC_CLASSES_PROPERTY,
- ConstantsProperties.SRC_CLASSES.getNaturalLanguageDesignation(),
- currentPath
- );
- Checker.checkPathPropertyValue(
- properties.getProperty(ConstantsProperties.TEST_CLASSES.getName()),
- ErrorEnum.ERROR_PATH_TO_TEST_CLASSES_PROPERTY,
- ConstantsProperties.TEST_CLASSES.getNaturalLanguageDesignation(),
- currentPath
- );
- }
-
- public static void checkProperties(Properties properties) {
+ public static void preChecking(InputConfiguration configuration) {
// project root is mandatory
- String currentPath = DSpotUtils.shouldAddSeparator.apply(properties.getProperty(ConstantsProperties.PROJECT_ROOT_PATH.getName()));
+ String currentPath = DSpotUtils.shouldAddSeparator.apply(configuration.getAbsolutePathToProjectRoot());
Checker.checkPathnameNotNullAndFileExist(
currentPath,
ErrorEnum.ERROR_PATH_TO_PROJECT_ROOT_PROPERTY,
@@ -86,46 +41,64 @@ public static void checkProperties(Properties properties) {
"The provided path to the root folder of your project is incorrect, the folder does not exist."
);
// target module
- final String targetModulePropertyValue = DSpotUtils.shouldAddSeparator.apply(properties.getProperty(ConstantsProperties.MODULE.getName()));
+ final String targetModulePropertyValue = DSpotUtils.shouldAddSeparator.apply(configuration.getTargetModule());
Checker.checkPathPropertyValue(
targetModulePropertyValue,
ErrorEnum.ERROR_PATH_TO_TARGET_MODULE_PROPERTY,
- ConstantsProperties.MODULE.getNaturalLanguageDesignation(),
+ "targeted module",
currentPath
);
currentPath += targetModulePropertyValue != null ? targetModulePropertyValue : "";
// source folders: src and testSrc
Checker.checkPathPropertyValue(
- properties.getProperty(ConstantsProperties.SRC_CODE.getName()),
+ configuration.getPathToSourceCode(),
ErrorEnum.ERROR_PATH_TO_SRC_PROPERTY,
- ConstantsProperties.SRC_CODE.getNaturalLanguageDesignation(),
+ "source folder",
currentPath
);
Checker.checkPathPropertyValue(
- properties.getProperty(ConstantsProperties.TEST_SRC_CODE.getName()),
+ configuration.getPathToTestSourceCode(),
ErrorEnum.ERROR_PATH_TO_TEST_SRC_PROPERTY,
- ConstantsProperties.TEST_SRC_CODE.getNaturalLanguageDesignation(),
+ "test source folder",
currentPath
);
// path to maven home
Checker.checkPathPropertyValue(
- properties.getProperty(ConstantsProperties.MAVEN_HOME.getName()),
+ configuration.getMavenHome(),
ErrorEnum.ERROR_PATH_TO_MAVEN_HOME,
- ConstantsProperties.MAVEN_HOME.getNaturalLanguageDesignation(),
+ "maven installation",
currentPath
);
- if (properties.getProperty(ConstantsProperties.DESCARTES_VERSION.getName()) != null) {
- checkIsACorrectVersion(properties.getProperty(ConstantsProperties.DESCARTES_VERSION.getName()));
- }
- if (properties.getProperty(ConstantsProperties.PIT_VERSION.getName()) != null) {
- checkIsACorrectVersion(properties.getProperty(ConstantsProperties.PIT_VERSION.getName()));
- }
+
+ checkIsACorrectVersion(configuration.getPitVersion());
+ checkIsACorrectVersion(configuration.getDescartesVersion());
// TODO check JVM args and System args
- checkJVMArgs(ConstantsProperties.JVM_ARGS.get(properties)); // no checks since it is a soft checks
- checkSystemProperties(ConstantsProperties.SYSTEM_PROPERTIES.get(properties));
+ checkJVMArgs(configuration.getJVMArgs()); // no checks since it is a soft checks
+ checkSystemProperties(configuration.getSystemProperties());
+ }
+
+ public static void postChecking(InputConfiguration configuration) {
+ // we check now the binaries folders after the compilation
+ String currentPath = DSpotUtils.shouldAddSeparator.apply(configuration.getAbsolutePathToProjectRoot());
+ final String targetModulePropertyValue = DSpotUtils.shouldAddSeparator.apply(configuration.getTargetModule());
+ currentPath += targetModulePropertyValue != null ? targetModulePropertyValue : "";
+
+ // binary folders: classes and test-classes
+ Checker.checkPathPropertyValue(
+ configuration.getPathToClasses(),
+ ErrorEnum.ERROR_PATH_TO_SRC_CLASSES_PROPERTY,
+ "binaries folder",
+ currentPath
+ );
+ Checker.checkPathPropertyValue(
+ configuration.getPathToClasses(),
+ ErrorEnum.ERROR_PATH_TO_TEST_CLASSES_PROPERTY,
+ "test binaries folder",
+ currentPath
+ );
}
// TODO must be enhanced.
@@ -180,7 +153,7 @@ private static void checkPathPropertyValue(final String propertyValue,
if (propertyValue != null) {
final String additionalMessage = "The provided path to the " + naturalLanguageDesignation + " of your project is incorrect, the folder does not exist."
+ AmplificationHelper.LINE_SEPARATOR + " This path should be either relative to the path pointed by "
- + ConstantsProperties.PROJECT_ROOT_PATH.getName() + " property "
+ + " --absolute-path-to-project-root command line option"
+ AmplificationHelper.LINE_SEPARATOR + "or an absolute path";
if (new File(propertyValue).isAbsolute()) {
Checker.checkFileExists(propertyValue, errorEnumInCaseOfError, additionalMessage);
@@ -197,7 +170,7 @@ private static void checkRelativePathPropertyValue(final String propertyValue,
if (propertyValue != null) {
final String additionalMessage = "The provided path to the " + naturalLanguageDesignation + " of your project is incorrect, the folder does not exist."
+ AmplificationHelper.LINE_SEPARATOR + " This path should be relative to the path pointed by "
- + ConstantsProperties.PROJECT_ROOT_PATH.getName() + " property.";
+ + " --absolute-path-to-project-root command line option.";
Checker.checkFileExists(rootPathProject + "/" + propertyValue, errorEnumInCaseOfError, additionalMessage);
}
}
diff --git a/dspot/src/main/java/eu/stamp_project/utils/program/ConstantsProperties.java b/dspot/src/main/java/eu/stamp_project/utils/program/ConstantsProperties.java
deleted file mode 100644
index 17be77be9..000000000
--- a/dspot/src/main/java/eu/stamp_project/utils/program/ConstantsProperties.java
+++ /dev/null
@@ -1,303 +0,0 @@
-package eu.stamp_project.utils.program;
-
-import eu.stamp_project.utils.AmplificationHelper;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.function.Function;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
-
-/**
- * Created by Benjamin DANGLOT
- * benjamin.danglot@inria.fr
- * on 02/06/18
- */
-public class ConstantsProperties {
-
- public static final InputConfigurationProperty PROJECT_ROOT_PATH =
- new InputConfigurationProperty(
- "project",
- "specify the path to the root of the project. " +
- "This path can be either absolute (recommended) or relative to the working directory of the DSpot process. " +
- "We consider as root of the project folder that contain the top-most parent in a multi-module project.",
- null,
- "project root"
- );
-
- public static final InputConfigurationProperty MODULE =
- new InputConfigurationProperty(
- "targetModule",
- "specify the module to be amplified. This value must be a relative path from the property " + PROJECT_ROOT_PATH.getName() + ". " +
- "If your project is multi-module, you must use this property because DSpot works at module level.",
- "",
- "targeted module"
- );
-
- public static final InputConfigurationProperty SRC_CODE =
- new InputConfigurationProperty(
- "src",
- "specify the relative path from " +
- PROJECT_ROOT_PATH.getName() + "/" + MODULE.getName() +
- " of the folder that contain sources (.java).",
- "src/main/java/",
- "source folder"
- );
-
- public static final InputConfigurationProperty TEST_SRC_CODE =
- new InputConfigurationProperty(
- "testSrc",
- "specify the relative path from " +
- PROJECT_ROOT_PATH.getName() + "/" + MODULE.getName() +
- " of the folder that contain test sources (.java).",
- "src/test/java/",
- "test source folder"
- );
-
- public static final InputConfigurationProperty SRC_CLASSES =
- new InputConfigurationProperty(
- "classes",
- "specify the relative path from " +
- PROJECT_ROOT_PATH.getName() + "/" + MODULE.getName() +
- " of the folder that contain binaries of the source program (.class).",
- "target/classes/",
- "binaries folder"
- );
-
- public static final InputConfigurationProperty TEST_CLASSES =
- new InputConfigurationProperty(
- "testClasses",
- "specify the relative path from " +
- PROJECT_ROOT_PATH.getName() + "/" + MODULE.getName() +
- " of the folder that contain binaries of the test source program (.class).",
- "target/test-classes/",
- "test binaries folder"
- );
-
- public static final InputConfigurationProperty ADDITIONAL_CP_ELEMENTS =
- new InputConfigurationProperty(
- "additionalClasspathElements",
- "specify additional classpath elements. (e.g. a jar file) " +
- "This value should be a list of relative paths from " +
- PROJECT_ROOT_PATH.getName() + "/" + MODULE.getName() + ". " +
- "Elements of the list must be separated by a comma \',\'.",
- ""
- );
-
- public static final InputConfigurationProperty SYSTEM_PROPERTIES =
- new InputConfigurationProperty(
- "systemProperties",
- "specify system properties. " +
- "This value should be a list of couple property;value, separated by a comma \',\'. " +
- "For example, systemProperties=admin=toto,passwd=tata. This define two system properties."
- ,
- ""
- );
-
- public static final InputConfigurationProperty PATH_TO_SECOND_VERSION =
- new InputConfigurationProperty(
- "pathToSecondVersion",
- "when using the ChangeDetectorSelector" +
- ", you must specify this property. " +
- "This property should have for value the path to the root of " +
- "the second version of the project. " +
- "It is recommended to give an absolute path",
- "",
- "path to second version",
- "folderPath"
- );
-
- public static final InputConfigurationProperty AUTOMATIC_BUILDER_NAME =
- new InputConfigurationProperty(
- "automaticBuilderName",
- "specify the type of automatic builder. " +
- "This properties is redundant with the command line option --automatic-builder. " +
- "It should have also the same value: (MavenBuilder | GradleBuilder). " +
- "This property has the priority over the command line.",
- ""
- );
-
- public static final InputConfigurationProperty OUTPUT_DIRECTORY =
- new InputConfigurationProperty(
- "outputDirectory",
- "specify a path folder for the output.",
- ""
- );
-
- public static final InputConfigurationProperty MAVEN_HOME =
- new InputConfigurationProperty(
- "mavenHome",
- "specify the maven home directory. " +
- "This property is redundant with the command line option --maven-home. " +
- "This property has the priority over the command line. " +
- "If this property is not specified, nor the command line option --maven-home, " +
- "DSpot will first look in both MAVEN_HOME and M2_HOME environment variables. " +
- "If these variables are not set, DSpot will look for a maven home at default locations " +
- "/usr/share/maven/, /usr/local/maven-3.3.9/ and /usr/share/maven3/.",
- "",
- "maven installation",
- "maven.home"
- );
-
- public static final InputConfigurationProperty MAVEN_PRE_GOALS =
- new InputConfigurationProperty(
- "mavenPreGoals",
- "specify pre goals to run before executing test with maven." +
- "This property will used as follow: the elements, separated by a comma," +
- "must be valid maven goals and they will be placed just before the \"test\" goal, e.g." +
- "maven.pre.goals=preGoal1,preGoal2 will give \"mvn preGoal1 preGoal2 test\"",
- "",
- "maven pre goals",
- "maven.pre.goals"
- );
-
- public static final InputConfigurationProperty DELTA_ASSERTS_FLOAT =
- new InputConfigurationProperty(
- "delta",
- "specify the delta value for the assertions of floating-point numbers. " +
- "If DSpot generates assertions for float, " +
- "it uses Assert.assertEquals(expected, actual, delta). " +
- "This property specify the delta value.",
- "0.1"
- );
-
- public static final InputConfigurationProperty PIT_FILTER_CLASSES_TO_KEEP =
- new InputConfigurationProperty(
- "pitFilterClassesToKeep",
- "specify the filter of classes to keep used by PIT. " +
- "This allow you restrict the scope of the mutation done by PIT.",
- "",
- "",
- "filter"
- );
-
- public static final InputConfigurationProperty PIT_VERSION =
- new InputConfigurationProperty(
- "pitVersion",
- "specify the version of PIT to use.",
- "1.4.0"
- );
-
- public static final InputConfigurationProperty DESCARTES_VERSION =
- new InputConfigurationProperty(
- "descartesVersion",
- "specify the version of pit-descartes to use.",
- "1.2.4"
- );
-
- public static final InputConfigurationProperty EXCLUDED_CLASSES =
- new InputConfigurationProperty(
- "excludedClasses",
- "specify the full qualified name of excluded test classes. " +
- "Each qualified name must be separated by a comma \',\'. " +
- "These classes won't be amplified, nor executed during the mutation analysis, " +
- "if the PitMutantScoreSelector is used." +
- "This property can be valued by a regex.",
- ""
- );
-
- public static final InputConfigurationProperty EXCLUDED_TEST_CASES =
- new InputConfigurationProperty(
- "excludedTestCases",
- "specify the list of test cases to be excluded. " +
- "Each is the name of a test case, separated by a comma \',\'.",
- ""
- );
-
- public static final InputConfigurationProperty JVM_ARGS =
- new InputConfigurationProperty(
- "jvmArgs",
- "specify JVM args to use when executing the test, PIT or other java process. " +
- "This arguments should be a list, separated by a comma \',\', "+
- "e.g. jvmArgs=Xmx2048m,-Xms1024m',-Dis.admin.user=admin,-Dis.admin.passwd=$2pRSid#",
- ""
- );
-
- public static final InputConfigurationProperty DESCARTES_MUTATORS =
- new InputConfigurationProperty(
- "descartesMutators",
- "specify the list of descartes mutators to be used separated by comma. Please refer to the descartes documentation for more details: https://github.com/STAMP-project/pitest-descartes",
- ""
- );
-
- public static final InputConfigurationProperty CACHE_SIZE =
- new InputConfigurationProperty(
- "cacheSize",
- "specify the size of the memory cache in terms of the number of store entries",
- "10000"
- );
-
-
-
- /**
- * main method to generate the documentation. This method will output the documentation on the standard output, in markdown format.
- * @param args unused
- */
- public static void main(String[] args) {
- final List inputConfigurationProperties = new ArrayList<>();
- inputConfigurationProperties.add(PROJECT_ROOT_PATH);
- inputConfigurationProperties.add(MODULE);
- inputConfigurationProperties.add(SRC_CODE);
- inputConfigurationProperties.add(TEST_SRC_CODE);
- inputConfigurationProperties.add(SRC_CLASSES);
- inputConfigurationProperties.add(TEST_CLASSES);
- inputConfigurationProperties.add(ADDITIONAL_CP_ELEMENTS);
- inputConfigurationProperties.add(SYSTEM_PROPERTIES);
- inputConfigurationProperties.add(OUTPUT_DIRECTORY);
- inputConfigurationProperties.add(DELTA_ASSERTS_FLOAT);
- inputConfigurationProperties.add(EXCLUDED_CLASSES);
- inputConfigurationProperties.add(EXCLUDED_TEST_CASES);
- inputConfigurationProperties.add(MAVEN_HOME);
- inputConfigurationProperties.add(MAVEN_PRE_GOALS);
- inputConfigurationProperties.add(PATH_TO_SECOND_VERSION);
- inputConfigurationProperties.add(AUTOMATIC_BUILDER_NAME);
- inputConfigurationProperties.add(PIT_VERSION);
- inputConfigurationProperties.add(JVM_ARGS);
- inputConfigurationProperties.add(PIT_FILTER_CLASSES_TO_KEEP);
- inputConfigurationProperties.add(DESCARTES_VERSION);
- inputConfigurationProperties.add(DESCARTES_MUTATORS);
- final String output = "* Required properties" +
- AmplificationHelper.LINE_SEPARATOR +
- getRequiredProperties.apply(inputConfigurationProperties)
- .map(InputConfigurationProperty::toString)
- .collect(Collectors.joining(AmplificationHelper.LINE_SEPARATOR)) +
- AmplificationHelper.LINE_SEPARATOR +
- "* Optional properties" +
- AmplificationHelper.LINE_SEPARATOR +
- getOptionalProperties.apply(inputConfigurationProperties)
- .map(InputConfigurationProperty::toString)
- .map(s -> s.replaceAll("i\\.e\\.", "_i.e._"))
- .map(s -> s.replaceAll("e\\.g\\.", "_e.g._"))
- .map(wrapOptionWithQuote)
- .collect(Collectors.joining(AmplificationHelper.LINE_SEPARATOR)) +
- AmplificationHelper.LINE_SEPARATOR +
- "You can find an example of properties file [here](https://github.com/STAMP-project/dspot/blob/master/dspot/src/test/resources/sample/sample.properties)).";
- System.out.println(output);
- }
-
- private final static Function wrapOptionWithQuote = s -> {
- final String[] split = s.split(" ");
- List wrappedSplit = new ArrayList<>();
- for (int i = 0; i < split.length; i++) {
- if (split[i].startsWith("--")) {
- if (split[i].endsWith(".")) {
- wrappedSplit.add("`" + split[i].substring(0, split[i].length() - 1) + "`.");
- } else {
- wrappedSplit.add("`" + split[i] + "`");
- if (i + 1 < split.length) {
- wrappedSplit.add("`" + split[i+1] + "`");
- }
- }
- } else {
- wrappedSplit.add(split[i]);
- }
- }
- return String.join(" ", wrappedSplit);
- };
-
- private final static Function, Stream> getRequiredProperties =
- properties -> properties.stream().filter(InputConfigurationProperty::isRequired);
-
- private final static Function, Stream> getOptionalProperties =
- properties -> properties.stream().filter(inputConfigurationProperty -> !inputConfigurationProperty.isRequired());
-}
diff --git a/dspot/src/main/java/eu/stamp_project/utils/program/InputConfiguration.java b/dspot/src/main/java/eu/stamp_project/utils/program/InputConfiguration.java
index 80dd956fc..3cf221b27 100644
--- a/dspot/src/main/java/eu/stamp_project/utils/program/InputConfiguration.java
+++ b/dspot/src/main/java/eu/stamp_project/utils/program/InputConfiguration.java
@@ -1,29 +1,20 @@
package eu.stamp_project.utils.program;
-import eu.stamp_project.Main;
-import eu.stamp_project.automaticbuilder.AutomaticBuilder;
-import eu.stamp_project.automaticbuilder.AutomaticBuilderFactory;
-import eu.stamp_project.dspot.amplifier.Amplifier;
import eu.stamp_project.dspot.selector.PitMutantScoreSelector;
-import eu.stamp_project.dspot.selector.TestSelector;
-import eu.stamp_project.utils.DSpotCache;
-import eu.stamp_project.utils.options.AmplifierEnum;
-import eu.stamp_project.utils.options.InputAmplDistributorEnum;
import eu.stamp_project.testrunner.EntryPoint;
import eu.stamp_project.utils.AmplificationHelper;
import eu.stamp_project.utils.DSpotUtils;
-import eu.stamp_project.utils.options.Configuration;
-import org.junit.Test;
+import eu.stamp_project.utils.options.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import picocli.CommandLine;
import spoon.reflect.factory.Factory;
import java.io.File;
-import java.nio.file.Paths;
+import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
-import java.util.Properties;
import java.util.stream.Collectors;
import static eu.stamp_project.utils.AmplificationHelper.PATH_SEPARATOR;
@@ -40,339 +31,530 @@ public class InputConfiguration {
private static final Logger LOGGER = LoggerFactory.getLogger(InputConfiguration.class);
- public static InputConfiguration get() {
- return InputConfiguration.instance;
- }
-
- /**
- * This method initialize the instance of the Singleton {@link InputConfiguration}.
- * You can retrieve this instance using {@link InputConfiguration#get()}
- * Build an InputConfiguration from a properties file, given as path.
- * This method will call the default constructor {@link InputConfiguration#InputConfiguration(String, String, String, String, String, String)}
- * Then, uses the properties to initialize other values.
- *
- * @param pathToPropertiesFile the path to the properties file. It is recommended to use an absolute path.
- * @return the new instance of the InputConfiguration
- */
- public static InputConfiguration initialize(String pathToPropertiesFile) {
- InputConfiguration.initialize(Configuration.loadProperties(pathToPropertiesFile));
- InputConfiguration.instance.configPath = pathToPropertiesFile;
- InputConfiguration.get().setBudgetizer(InputAmplDistributorEnum.RandomInputAmplDistributor);
- return InputConfiguration.instance;
- }
+ @CommandLine.Option(
+ names = "--absolute-path-to-project-root",
+ description = "Specify the path to the root of the project. " +
+ "This path must be absolute." +
+ "We consider as root of the project folder that contain the top-most parent in a multi-module project."
+ )
+ private String absolutePathToProjectRoot;
- /**
- * This method initialize the instance of the Singleton {@link InputConfiguration}.
- * You can retrieve this instance using {@link InputConfiguration#get()}
- * Build an InputConfiguration from a properties file, given as path.
- * This method will call the default constructor {@link InputConfiguration#InputConfiguration(String, String, String, String, String, String)}
- * Then, uses the properties to initialize other values.
- *
- * @param pathToPropertiesFile the path to the properties file. It is recommended to use an absolute path.
- * @param builderName the name of the builder. Can be either Maven or Gradle (not case sensitive).
- * @return the new instance of the InputConfiguration
- */
-// FIXME This method is not invoked from DSpot code and makes difficult to setup parallel execution classpath, so I commented it out
-// public static InputConfiguration initialize(String pathToPropertiesFile, String builderName) {
-// InputConfiguration.initialize(Configuration.loadProperties(pathToPropertiesFile), builderName);
-// InputConfiguration.instance.configPath = pathToPropertiesFile;
-// return InputConfiguration.instance;
-// }
- /**
- * This method initialize the instance of the Singleton {@link InputConfiguration}.
- * You can retrieve this instance using {@link InputConfiguration#get()}
- * Build an InputConfiguration from a properties file, given as path.
- * This method will call the default constructor {@link InputConfiguration#InputConfiguration(String, String, String, String, String, String)}
- * Then, uses the properties to initialize other values.
- * The given properties should have least values for :
- *
- *
{@link ConstantsProperties#PROJECT_ROOT_PATH}
- *
{@link ConstantsProperties#SRC_CODE}
- *
{@link ConstantsProperties#TEST_SRC_CODE}
- *
{@link ConstantsProperties#SRC_CLASSES}
- *
{@link ConstantsProperties#TEST_CLASSES}
- *
{@link ConstantsProperties#MODULE}, in case of multi module project
- *
- *
- * @param properties the properties. See {@link ConstantsProperties}
- * @return the new instance of the InputConfiguration
- */
- public static InputConfiguration initialize(Properties properties) {
- if (InputConfiguration.instance != null) {
- reset();
- }
- InputConfiguration.instance = new InputConfiguration(properties);
- InputConfiguration.instance.configPath = "";
- InputConfiguration.instance.setBuilderName(ConstantsProperties.AUTOMATIC_BUILDER_NAME.get(properties));
- InputConfiguration.instance.initializeBuilder(properties);
- return InputConfiguration.instance;
- }
+ @CommandLine.Option(
+ names = "--target-module",
+ defaultValue = "",
+ description = "Specify the module to be amplified. " +
+ "This value must be a relative path from value specified by --absolute-path-to-project-root command-line option. " +
+ "If your project is multi-module, you must use this property because DSpot works at module level."
+ )
+ private String targetModule;
- private static void reset() {
- LOGGER.warn("Erasing old instance of InputConfiguration");
- DSpotCache.reset();
- Main.GLOBAL_REPORT.reset();
- AmplificationHelper.reset();
- }
+ @CommandLine.Option(
+ names = "--relative-path-to-source-code",
+ defaultValue = "src/main/java/",
+ description = "Specify the relative path from --absolute-path-to-project-root/--target-module command-line options " +
+ "that points to the folder that contains sources (.java)."
+ )
+ private String pathToSourceCode;
- /**
- * This method initialize the instance of the Singleton {@link InputConfiguration}.
- * You can retrieve this instance using {@link InputConfiguration#get()}
- * Build an InputConfiguration from a properties file, given as path.
- * This method will call the default constructor {@link InputConfiguration#InputConfiguration(String, String, String, String, String, String)}
- * Then, uses the properties to initialize other values.
- * The given properties should have least values for :
- *
- *
{@link ConstantsProperties#PROJECT_ROOT_PATH}
- *
{@link ConstantsProperties#SRC_CODE}
- *
{@link ConstantsProperties#TEST_SRC_CODE}
- *
{@link ConstantsProperties#SRC_CLASSES}
- *
{@link ConstantsProperties#TEST_CLASSES}
- *
{@link ConstantsProperties#MODULE}, in case of multi module project
- *
- *
- * @param properties the properties. See {@link ConstantsProperties}
- * @param builderName the name of the builder. Can be either Maven or Gradle (not case sensitive).
- * @param executeTestsInParallel tell whether or not Dspot execute the test in parallel
- * @param fullClasspath classpath of the project, if null or empty, Dspot will use the AutomaticBuilder
- * @return the new instance of the InputConfiguration
- */
- public static InputConfiguration initialize(Properties properties,
- String builderName,
- boolean executeTestsInParallel,
- String fullClasspath) {
- if (InputConfiguration.instance != null) {
- reset();
- }
- InputConfiguration.instance = new InputConfiguration(properties);
- InputConfiguration.instance.configPath = "";
- final String builderNameProperties = ConstantsProperties.AUTOMATIC_BUILDER_NAME.get(properties);
- if (builderName == null || (builderName.isEmpty() && builderNameProperties.isEmpty())) {
- LOGGER.warn("No builder has been specified.");
- LOGGER.warn("Using Maven as a default builder.");
- LOGGER.warn("You can use the command-line option --automatic-builder");
- LOGGER.warn("or the properties " + ConstantsProperties.AUTOMATIC_BUILDER_NAME.getName() + " to configure it.");
- InputConfiguration.instance.setBuilderName("MAVEN");
- } else if (builderName.isEmpty()) {
- InputConfiguration.instance.setBuilderName(builderNameProperties);
- } else if (builderNameProperties.isEmpty()) {
- InputConfiguration.instance.setBuilderName(builderName);
- } else {
- LOGGER.warn("Conflicting values for automatic builder.");
- LOGGER.warn("{} from command-line", builderName);
- LOGGER.warn("{} from properties", builderNameProperties);
- LOGGER.warn("Using the value gave on the command-line {}", builderName);
- InputConfiguration.instance.setBuilderName(builderName);
- }
- InputConfiguration.instance.setExecuteTestsInParallel(executeTestsInParallel);
- InputConfiguration.instance.initializeBuilder(properties, fullClasspath);
- return InputConfiguration.instance;
- }
-
- private InputConfiguration(Properties properties) {
- // mandatory properties are used in the first constructor, except targetModule, which can be empty
- this(
- ConstantsProperties.PROJECT_ROOT_PATH.get(properties),
- ConstantsProperties.SRC_CODE.get(properties),
- ConstantsProperties.TEST_SRC_CODE.get(properties),
- ConstantsProperties.SRC_CLASSES.get(properties),
- ConstantsProperties.TEST_CLASSES.get(properties),
- ConstantsProperties.MODULE.get(properties)
- );
+ @CommandLine.Option(
+ names = "--relative-path-to-test-code",
+ defaultValue = "src/test/java/",
+ description = "Specify the relative path from --absolute-path-to-project-root/--target-module command-line options " +
+ "that points to the folder that contains test sources (.java)."
+ )
+ private String pathToTestSourceCode;
- this.setAbsolutePathToSecondVersionProjectRoot(new File(
- DSpotUtils.shouldAddSeparator.apply(
- ConstantsProperties.PATH_TO_SECOND_VERSION.get(properties)
- ) + targetModule
- ).getAbsolutePath()
- )
- .setBuilderName(ConstantsProperties.AUTOMATIC_BUILDER_NAME.get(properties));
-
- final String systemProperties = ConstantsProperties.SYSTEM_PROPERTIES.get(properties);
- if (!systemProperties.isEmpty()) {
- Arrays.stream(systemProperties.split(","))
- .forEach(systemProperty -> {
- String[] keyValueInArray = systemProperty.split("=");
- System.getProperties().put(keyValueInArray[0], keyValueInArray[1]);
- });
- }
+ @CommandLine.Option(
+ names = "--relative-path-to-classes",
+ defaultValue = "target/classes/",
+ description = "Specify the relative path from --absolute-path-to-project-root/--target-module command-line options " +
+ "that points to the folder that contains binaries of the source (.class)."
+ )
+ private String pathToClasses = "target/classes/";
+
+ @CommandLine.Option(
+ names = "--relative-path-to-test-classes",
+ defaultValue = "target/test-classes/",
+ description = "Specify the relative path from --absolute-path-to-project-root/--target-module command-line options " +
+ "that points to the folder that contains binaries of the test source (.class)."
+ )
+ private String pathToTestClasses = "target/test-classes/";
+
+ @CommandLine.Option(
+ names = "--path-to-additional-classpath-elements",
+ defaultValue = "",
+ description = "Specify additional classpath elements (e.g. a jar files). " +
+ "Elements of this list must be separated by a comma \',\'."
+ )
+ private String additionalClasspathElements = "";
- this.setOutputDirectory(ConstantsProperties.OUTPUT_DIRECTORY.get(properties))
- .setDelta(ConstantsProperties.DELTA_ASSERTS_FLOAT.get(properties))
- .setFilter(ConstantsProperties.PIT_FILTER_CLASSES_TO_KEEP.get(properties))
- .setDescartesVersion(ConstantsProperties.DESCARTES_VERSION.get(properties))
- .setExcludedClasses(ConstantsProperties.EXCLUDED_CLASSES.get(properties))
- .setPreGoalsTestExecution(ConstantsProperties.MAVEN_PRE_GOALS.get(properties))
- //.setTimeoutPit(ConstantsProperties.TIMEOUT_PIT.get(properties))
- .setJVMArgs(ConstantsProperties.JVM_ARGS.get(properties))
- .setDescartesMutators(ConstantsProperties.DESCARTES_MUTATORS.get(properties))
- .setPitVersion(ConstantsProperties.PIT_VERSION.get(properties))
- .setExcludedTestCases(ConstantsProperties.EXCLUDED_TEST_CASES.get(properties));
- }
+ @CommandLine.Option(
+ names = "--automatic-builder",
+ defaultValue = "Maven",
+ description = "Specify the automatic builder to be used. " +
+ "Valid values: ${COMPLETION-CANDIDATES}"
+ )
+ private AutomaticBuilderEnum automaticBuilder;
+
+ @CommandLine.Option(
+ names = {"--system-properties"},
+ defaultValue = "",
+ description = "Specify system properties. " +
+ "This value should be a list of couple property=value, separated by a comma \',\'. " +
+ "For example, systemProperties=admin=toto,passwd=tata. " +
+ "This defines two system properties."
+ )
+ private String systemProperties;
+
+ @CommandLine.Option(
+ names = "--absolute-path-to-second-version",
+ defaultValue = "",
+ description = "When using the ChangeDetectorSelector, you must specify this option. " +
+ "It should have for value the path to the root of the second version of the project. " +
+ "It is recommended to give an absolute path"
+ )
+ private String absolutePathToSecondVersionProjectRoot;
- private void initializeBuilder(Properties properties) {
- this.initializeBuilder(properties, "");
- }
+ @CommandLine.Option(
+ names = {"--output-path", "--output-directory"},
+ defaultValue = "target/dspot/output/",
+ description = "specify a path folder for the output."
+ )
+ private String outputDirectory = "target/dspot/output/";
+
+ @CommandLine.Option(
+ names = "--maven-home",
+ defaultValue = "",
+ description = "Specify the maven home directory. " +
+ "If it is not specified DSpot will first look in both MAVEN_HOME and M2_HOME environment variables. " +
+ "If these variables are not set, DSpot will look for a maven home at default locations " +
+ "/usr/share/maven/, /usr/local/maven-3.3.9/ and /usr/share/maven3/."
+ )
+ @Deprecated
+ private String mavenHome;
- private void initializeBuilder(Properties properties, String classpath) {
- this.setMavenHome(ConstantsProperties.MAVEN_HOME.get(properties));
- this.builder = AutomaticBuilderFactory.getAutomaticBuilder(this.getBuilderName());
+ @CommandLine.Option(
+ names = "--maven-pre-goals-test-execution",
+ defaultValue = "",
+ description = "Specify pre goals to run before executing test with maven." +
+ "It will be used as follow: the elements, separated by a comma," +
+ "must be valid maven goals and they will be placed just before the \"test\" goal, e.g." +
+ "--maven-pre-goals-test-execution preGoal1,preGoal2 will give \"mvn preGoal1 preGoal2 test\""
+ )
+ private String preGoalsTestExecution;
+
+ @CommandLine.Option(
+ names = "--delta",
+ defaultValue = "0.1",
+ description = "Specify the delta value for the assertions of floating-point numbers. " +
+ "If DSpot generates assertions for float, it uses Assert.assertEquals(expected, actual, delta). " +
+ "It specifies the delta value."
+ )
+ private double delta;
+
+ @CommandLine.Option(
+ names = "--pit-filter-classes-to-keep",
+ description = "Specify the filter of classes to keep used by PIT. " +
+ "This allow you restrict the scope of the mutation done by PIT. " +
+ "If this is not specified, DSpot will try to build on the " +
+ "fly a filter that takes into account the largest number of classes, e.g. the topest package. "
+ )
+ private String filter;
+ @CommandLine.Option(
+ names = "--pit-version",
+ defaultValue = "1.4.0",
+ description = "Specify the version of PIT to use."
+ )
+ private String pitVersion = "1.4.0";
+
+ @CommandLine.Option(
+ names = "--descartes-version",
+ defaultValue = "1.2.4",
+ description = "Specify the version of pit-descartes to use."
+ )
+ private String descartesVersion = "1.2.4";
+
+ @CommandLine.Option(
+ names = "--excluded-classes",
+ defaultValue = "",
+ description = "Specify the full qualified name of excluded test classes. " +
+ "Each qualified name must be separated by a comma \',\'. " +
+ "These classes won't be amplified, nor executed during the mutation analysis, " +
+ "if the PitMutantScoreSelector is used." +
+ "This option can be valued by a regex."
+ )
+ private String excludedClasses = "";
- if (classpath != null && !classpath.isEmpty()) {
- this.dependencies = classpath;
- } else {
- this.dependencies = this.builder.compileAndBuildClasspath();
- }
+ @CommandLine.Option(
+ names = "--excluded-test-cases",
+ defaultValue = "",
+ description = "Specify the list of test cases to be excluded. " +
+ "Each is the name of a test case, separated by a comma \',\'."
+ )
+ private String excludedTestCases;
- // TODO checks this. Since we support different Test Support, we may not need to add artificially junit in the classpath
- if (!this.dependencies.contains("junit" + File.separator + "junit" + File.separator + "4")) {
- this.dependencies = Test.class
- .getProtectionDomain()
- .getCodeSource()
- .getLocation()
- .getFile() +
- AmplificationHelper.PATH_SEPARATOR + this.dependencies;
- }
+ @CommandLine.Option(
+ names = "--jvm-args",
+ defaultValue = "",
+ description = "Specify JVM args to use when executing the test, PIT or other java process. " +
+ "This arguments should be a list, separated by a comma \',\', " +
+ "e.g. jvmArgs=Xmx2048m,-Xms1024m',-Dis.admin.user=admin,-Dis.admin.passwd=$2pRSid#"
+ )
+ private String JVMArgs = "";
- final String additionalClasspathElements = ConstantsProperties.ADDITIONAL_CP_ELEMENTS.get(properties);
- if (!additionalClasspathElements.isEmpty()) {
- String pathToAdditionalClasspathElements = additionalClasspathElements;
- if (!Paths.get(additionalClasspathElements).isAbsolute()) {
- pathToAdditionalClasspathElements =
- DSpotUtils.shouldAddSeparator.apply(this.absolutePathToProjectRoot +
- additionalClasspathElements
- );
- }
- this.dependencies += PATH_SEPARATOR + pathToAdditionalClasspathElements;
- }
- this.setAdditionalClasspathElements(ConstantsProperties.ADDITIONAL_CP_ELEMENTS.get(properties));
- }
+ @CommandLine.Option(
+ names = "--descartes-mutators",
+ defaultValue = "",
+ description = "Specify the list of descartes mutators to be used separated by comma. " +
+ "Please refer to the descartes documentation for more details: " +
+ "https://github.com/STAMP-project/pitest-descartes"
+ )
+ private String descartesMutators = "";
- /**
- * This constructor is a proxy for {@link InputConfiguration#InputConfiguration(String, String, String, String, String, String)} with
- * an empty target module
- *
- * @param pathToProjectRoot absolute or relative path to the root of the project.
- * @param pathToSource relative path from {@code pathToProjectRoot} to the folder that contains the program sources (.java).
- * @param pathToTestSource relative path from {@code pathToProjectRoot} to the folder that contains the test sources (.java).
- * @param pathToClasses relative path from {@code pathToProjectRoot} to the folder that contains the program binaries (.class).
- * @param pathToTestClasses relative path from {@code pathToProjectRoot} to the folder that contains the test binaries (.class).
- */
- private InputConfiguration(String pathToProjectRoot,
- String pathToSource,
- String pathToTestSource,
- String pathToClasses,
- String pathToTestClasses) {
- this(pathToProjectRoot,
- pathToSource,
- pathToTestSource,
- pathToClasses,
- pathToTestClasses,
- ""
- );
- }
+ @CommandLine.Option(
+ names = "--cache-size",
+ defaultValue = "10000",
+ description = "Specify the size of the memory cache in terms of the number of store entries"
+ )
+ private Long cacheSize;
+
+ @CommandLine.Option(
+ names = "--gregor-mode",
+ defaultValue = "false",
+ description = "Enable the gregor engine for Pit Mutant Score Selector."
+ )
+ private boolean gregorMode = false;
+
+ @CommandLine.Option(
+ names = "--use-working-directory",
+ defaultValue = "false",
+ description = "Enable this option to change working directory with the root of the project."
+ )
+ private boolean useWorkingDirectory;
+
+ @CommandLine.Option(
+ names = "--generate-new-test-class",
+ defaultValue = "false",
+ description = "Enable the creation of a new test class."
+ )
+ private boolean generateAmplifiedTestClass;
- /**
- * Default Constructor. This constructor takes as input the minimal parameters to run DSpot.
- *
- * @param pathToProjectRoot absolute or relative path to the root of the project.
- * @param pathToSource relative path from {@code pathToProjectRoot} to the folder that contains the program sources (.java).
- * @param pathToTestSource relative path from {@code pathToProjectRoot} to the folder that contains the test sources (.java).
- * @param pathToClasses relative path from {@code pathToProjectRoot} to the folder that contains the program binaries (.class).
- * @param pathToTestClasses relative path from {@code pathToProjectRoot} to the folder that contains the test binaries (.class).
- * @param targetModule relative path from {@code pathToProjectRoot} to the targeted sub-module. This argument can be empty ("") in case of single module project.
- */
- private InputConfiguration(String pathToProjectRoot,
- String pathToSource,
- String pathToTestSource,
- String pathToClasses,
- String pathToTestClasses,
- String targetModule) {
- this.setAbsolutePathToProjectRoot(new File(
- DSpotUtils.shouldAddSeparator.apply(
- pathToProjectRoot
- ) + targetModule
- ).getAbsolutePath()
- ).setPathToSourceCode(pathToSource)
- .setPathToTestSourceCode(pathToTestSource)
- .setPathToClasses(pathToClasses)
- .setPathToTestClasses(pathToTestClasses)
- .setTargetModule(targetModule)
- .setVerbose(true);
- // force here verbose mode, to have debug during the construction of the InputConfiguration
- // then it will take the command line value (default: false)
- }
-
- public static void setUp(List amplifiers, String inputAmplDistributor,
- TestSelector testCriterion, List testClasses,
- List testCases, int iteration,
- long seed, int timeOut,
- int maxTestAmplified, boolean clean,
- boolean verbose, boolean workingDirectory,
- boolean comment, boolean generateNewTestClass,
- boolean keepOriginalTestMethods, boolean gregor,
- boolean descartes, boolean useMavenToExecuteTest,
- boolean targetOneTestClass, boolean allowPathInAssertion,
- boolean executeTestsInParallel, int numberParallelExecutionProcessors) {
- InputConfiguration.get()
- .setAmplifiers(AmplifierEnum.buildAmplifiersFromString(amplifiers))
- .setNbIteration(iteration)
- .setTestClasses(testClasses)
- .setSelector(testCriterion)
- .setTestCases(testCases)
- .setSeed(seed)
- .setTimeOutInMs(timeOut)
- .setMaxTestAmplified(maxTestAmplified)
- .setBudgetizer(InputAmplDistributorEnum.valueOf(inputAmplDistributor))
- .setClean(clean)
- .setVerbose(verbose)
- .setUseWorkingDirectory(workingDirectory)
- .setWithComment(comment)
- .setGenerateAmplifiedTestClass(generateNewTestClass)
- .setKeepOriginalTestMethods(keepOriginalTestMethods)
- .setDescartesMode(descartes && !gregor)
- .setUseMavenToExecuteTest(useMavenToExecuteTest)
- .setTargetOneTestClass(targetOneTestClass)
- .setAllowPathInAssertion(allowPathInAssertion)
- .setExecuteTestsInParallel(executeTestsInParallel)
- .setNumberParallelExecutionProcessors(numberParallelExecutionProcessors);
- }
+ @CommandLine.Option(
+ names = "--keep-original-test-methods",
+ defaultValue = "false",
+ description = "If enabled, DSpot keeps original test methods of the amplified test class."
+ )
+ private boolean keepOriginalTestMethods;
+
+ @CommandLine.Option(
+ names = "--use-maven-to-exe-test",
+ defaultValue = "false",
+ description = "If enabled, DSpot will use maven to execute the tests."
+ )
+ private boolean useMavenToExecuteTest;
+
+ @CommandLine.Option(
+ names = "--execute-test-parallel",
+ defaultValue = "false",
+ description = "If enabled, DSpot will execute the tests in parallel. " +
+ "For JUnit5 tests it will use the number of given processors " +
+ "(specify 0 to take the number of available core processors). " +
+ "For JUnit4 tests, it will use the number of available CPU processors " +
+ "(given number of processors is ignored)."
+ )
+ private boolean executeTestsInParallel;
+
+ @CommandLine.Option(
+ names = "--nb-parallel-exe-processors",
+ defaultValue = "0",
+ description = "Specify the number of processor to use for the parallel execution." +
+ "0 will make DSpot use all processors available."
+ )
+ private int numberParallelExecutionProcessors;
+
+ @CommandLine.Option(
+ names = {"-i", "--iteration"},
+ defaultValue = "1",
+ description = "Specify the number of amplification iterations. " +
+ "A larger number may help to improve the test criterion " +
+ "(e.g. a larger number of iterations may help to kill more mutants). " +
+ "This has an impact on the execution time: the more iterations, the longer DSpot runs."
+ )
+ private int nbIteration;
+
+ @CommandLine.Option(
+ names = {"-a", "--amplifiers"},
+ defaultValue = "None",
+ split = ",",
+ description = "Specify the list of amplifiers to use. " +
+ "By default, DSpot does not use any amplifiers (None) and applies only assertion amplification. " +
+ "Valid values: ${COMPLETION-CANDIDATES}"
+ )
+ private List amplifiers;
+
+ @CommandLine.Option(
+ names = {"-t", "--test"},
+ split = ",",
+ defaultValue = "all",
+ description = "Fully qualified names of test classes to be amplified. " +
+ "If the value is all, DSpot will amplify the whole test suite. " +
+ "You can also use regex to describe a set of test classes. " +
+ "By default, DSpot selects all the tests."
+ )
+ private List testClasses;
+
+ @CommandLine.Option(
+ names = {"-s", "--test-criterion", "--test-selector"},
+ defaultValue = "PitMutantScoreSelector",
+ description = "Specify the test adequacy criterion to be maximized with amplification. " +
+ "Valid values: ${COMPLETION-CANDIDATES}"
+ )
+ private SelectorEnum selector;
+
+ @CommandLine.Option(
+ names = {"-c", "--cases", "--test-methods", "--test-cases"},
+ split = ",",
+ description = "Specify the test cases to amplify."
+ )
+ private List testCases = new ArrayList<>();
+
+ @CommandLine.Option(
+ names = {"--random-seed"},
+ defaultValue = "23",
+ description = "Specify a seed for the random object (used for all randomized operation)."
+ )
+ private long seed;
+
+ @CommandLine.Option(
+ names = {"--time-out"},
+ defaultValue = "10000",
+ description = "Specify the timeout value of the degenerated tests in millisecond."
+ )
+ private int timeOutInMs = 10000;
- /**
- * Paths project properties
- */
+ @CommandLine.Option(
+ names = {"--max-test-amplified"},
+ defaultValue = "200",
+ description = "Specify the maximum number of amplified tests that dspot keeps (before generating assertion)."
+ )
+ private Integer maxTestAmplified;
+
+ @CommandLine.Option(
+ names = {"--clean"},
+ defaultValue = "false",
+ description = "If enabled, DSpot will remove the out directory if exists, else it will append the results to the exist files."
+ )
+ private boolean clean;
+
+ @CommandLine.Option(
+ names = {"-v", "--verbose"},
+ defaultValue = "false",
+ description = "Enable verbose mode of DSpot."
+ )
+ private boolean verbose;
+
+ @CommandLine.Option(
+ names = {"--with-comment"},
+ defaultValue = "false",
+ description = "Enable comment on amplified test: details steps of the Amplification."
+ )
+ private boolean withComment;
+
+ @CommandLine.Option(
+ names = {"--allow-path-in-assertions"},
+ defaultValue = "false",
+ description = "If enabled, DSpot will generate assertions for values that seems like to be paths."
+ )
+ private boolean allowPathInAssertion;
+
+ @CommandLine.Option(
+ names = {"--target-one-test-class"},
+ defaultValue = "false",
+ description = "Enable this option will make DSpot computing the mutation score of only one test class (the first pass through --test command line option)."
+ )
+ private boolean targetOneTestClass;
+
+
+ @CommandLine.Option(
+ names = {"--full-classpath"},
+ defaultValue = "",
+ description = "Specify the classpath of the project. " +
+ "If this option is used, DSpot won't use an AutomaticBuilder (e.g. Maven) to clean, compile and get the classpath of the project. " +
+ "Please ensure that your project is in a good shape, i.e. clean and correctly compiled, sources and test sources."
+ )
+ private String dependencies = "";
+
+ @CommandLine.Option(
+ names = {"--input-ampl-distributor"},
+ defaultValue = "RandomInputAmplDistributor",
+ description = "Specify an input amplification distributor." +
+ "Valid values: ${COMPLETION-CANDIDATES}"
+ )
+ private InputAmplDistributorEnum inputAmplDistributor;
- private String absolutePathToProjectRoot;
+ @CommandLine.Option(
+ names = {"--example"},
+ defaultValue = "false",
+ description = "Run the example of DSpot and leave."
+ )
+ boolean example;
+
+ @CommandLine.Option(
+ names = {"--pit-output-format"},
+ defaultValue = "XML",
+ description = "Specify the Pit output format." +
+ "Valid values: ${COMPLETION-CANDIDATES}"
+ )
+ private PitMutantScoreSelector.OutputFormat pitOutputFormat;
+
+ @CommandLine.Option(
+ names = {"--path-pit-result"},
+ defaultValue = "",
+ description = "Specify the path to the .xml or .csv of the original result of Pit Test. " +
+ "If you use this option the selector will be forced to PitMutantScoreSelector."
+ )
+ private String pathPitResult = "";
+
+ /* DSpot-web related command line options. */
+
+ @CommandLine.Option(
+ names = {"--collector"},
+ defaultValue = "NullCollector",
+ description = "Set a collector: MongodbCollector to send info to Mongodb at end process, NullCollector which does nothing." +
+ "Valid values: ${COMPLETION-CANDIDATES}"
+ )
+ private CollectorEnum collector;
+
+ @CommandLine.Option(
+ names = {"--mongo-url"},
+ defaultValue = "mongodb://localhost:27017",
+ description = "If valid url, DSpot will submit to Mongodb database."
+ )
+ private String mongoUrl;
+
+ @CommandLine.Option(
+ names = {"--mongo-dbname"},
+ defaultValue = "Dspot",
+ description = "If a valid mongo-url is provided, DSpot will submit result to the database indicated by this name."
+ )
+ private String mongoDbName;
+
+ @CommandLine.Option(
+ names = {"--mongo-colname"},
+ defaultValue = "AmpRecords",
+ description = "If valid mongo-url and a mongo-dbname are provided, " +
+ "DSpot will submit result to the provided collection name.."
+ )
+ private String mongoColName;
+
+ @CommandLine.Option(
+ names = {"--repo-slug"},
+ defaultValue = "UnknownSlug",
+ description = "Slug of the repo for instance Stamp/Dspot. " +
+ "This is used by mongodb as a identifier for analyzed repo's submitted data."
+ )
+ private String repoSlug;
+
+ @CommandLine.Option(
+ names = {"--repo-branch"},
+ defaultValue = "UnknownBranch",
+ description = "Branch name of the submitted repo, " +
+ "This is used by mongodb as a identifier for analyzed repo's submitted data."
+ )
+ private String repoBranch;
+
+ @CommandLine.Option(
+ names = {"--restful"},
+ defaultValue = "false",
+ description = "If true, DSpot will enable restful mode for web Interface. " +
+ "It will look for a pending document in Mongodb with the corresponding slug and branch provided instead of creating a completely new one."
+ )
+ private boolean restFul;
+
+ @CommandLine.Option(
+ names = {"--smtp-username"},
+ defaultValue = "Unknown@gmail.com",
+ description = "Username for Gmail, used for submit email at end-process."
+ )
+ private String smtpUsername;
+
+ @CommandLine.Option(
+ names = {"--smtp-password"},
+ defaultValue = "Unknown",
+ description = "Password for Gmail, used for submit email at end-process."
+ )
+ private String smtpPassword;
+
+ @CommandLine.Option(
+ names = {"--smtp-host"},
+ defaultValue = "smtp.gmail.com",
+ description = "Host server name."
+ )
+ private String smtpHost;
+
+ @CommandLine.Option(
+ names = {"--smtp-port"},
+ defaultValue = "587",
+ description = "Host server port."
+ )
+ private String smtpPort;
+
+ @CommandLine.Option(
+ names = {"--smtp-auth"},
+ defaultValue = "false",
+ description = "Enable this if the smtp host server require auth."
+ )
+ private boolean smtpAuth;
+
+ @CommandLine.Option(
+ names = {"--smtp-tls"},
+ defaultValue = "false",
+ description = "Enable this if the smtp host server require secure tls transport."
+ )
+ private String smtpTls;
+
+ /* META command line options */
+
+ @CommandLine.Option(
+ names = {"--version"},
+ versionHelp = true,
+ description = "Display version info."
+ )
+ boolean versionInfoRequested;
+
+ @CommandLine.Option(
+ names = {"-h", "--help"},
+ usageHelp = true,
+ description = "Display this help message."
+ )
+ boolean usageHelpRequested;
- /**
- * This method return the absolute path to the project.
- * If the project is multi-modules, the returned path is the path to the specified targetModule properties
- *
- * @return absolute path to the project root
- */
public String getAbsolutePathToProjectRoot() {
return absolutePathToProjectRoot;
}
public InputConfiguration setAbsolutePathToProjectRoot(String absolutePathToProjectRoot) {
- this.absolutePathToProjectRoot = DSpotUtils.shouldAddSeparator.apply(absolutePathToProjectRoot);
+ this.absolutePathToProjectRoot = DSpotUtils.shouldAddSeparator.apply(
+ new File(absolutePathToProjectRoot).getAbsolutePath()
+ );
return this;
}
- private String targetModule;
-
public String getTargetModule() {
return targetModule;
}
public InputConfiguration setTargetModule(String targetModule) {
- this.targetModule = targetModule;
+ this.targetModule = DSpotUtils.shouldAddSeparator.apply(targetModule);
return this;
}
- private String pathToSourceCode;
+ // TODO
+ public String getPathToFolderToBeAmplified() {
+ return this.absolutePathToProjectRoot + this.targetModule;
+ }
public String getPathToSourceCode() {
return pathToSourceCode;
@@ -387,8 +569,6 @@ public InputConfiguration setPathToSourceCode(String pathToSourceCode) {
return this;
}
- private String pathToTestSourceCode;
-
public String getPathToTestSourceCode() {
return pathToTestSourceCode;
}
@@ -402,12 +582,6 @@ public String getAbsolutePathToTestSourceCode() {
return this.absolutePathToProjectRoot + this.getPathToTestSourceCode();
}
- /*
- Compilation and dependencies properties
- */
-
- private String pathToClasses;
-
public String getPathToClasses() {
return pathToClasses;
}
@@ -421,7 +595,6 @@ public String getAbsolutePathToClasses() {
return this.absolutePathToProjectRoot + this.getPathToClasses();
}
- private String pathToTestClasses;
public String getPathToTestClasses() {
return pathToTestClasses;
@@ -444,8 +617,6 @@ public String getClasspathClassesProject() {
return this.getAbsolutePathToClasses() + AmplificationHelper.PATH_SEPARATOR + this.getAbsolutePathToTestClasses();
}
- private String dependencies;
-
/**
* This method compute the path to all dependencies of the project, separated by the path separator of the System.
* The dependencies is compute by an implementation of a {@link eu.stamp_project.automaticbuilder.AutomaticBuilder}
@@ -462,12 +633,9 @@ public String getDependencies() {
public String getFullClassPathWithExtraDependencies() {
return this.getClasspathClassesProject() + AmplificationHelper.PATH_SEPARATOR +
this.getDependencies() + AmplificationHelper.PATH_SEPARATOR +
- DSpotUtils.getAbsolutePathToDSpotDependencies();
+ this.getAbsolutePathToProjectRoot() + DSpotUtils.PATH_TO_DSPOT_DEPENDENCIES;
}
- private String additionalClasspathElements = "";
-
-
public String getAdditionalClasspathElements() {
return additionalClasspathElements;
}
@@ -491,50 +659,24 @@ public InputConfiguration setAdditionalClasspathElements(String additionalClassp
return this;
}
- /*
- Builder properties
- */
-
- private String builderName;
-
- public String getBuilderName() {
- return builderName;
- }
-
- public InputConfiguration setBuilderName(String builderName) {
- this.builderName = builderName;
- return this;
- }
-
- @Deprecated
- private String mavenHome;
-
- @Deprecated
public InputConfiguration setMavenHome(String mavenHome) {
this.mavenHome = mavenHome;
return this;
}
- @Deprecated
public String getMavenHome() {
return mavenHome;
}
- private AutomaticBuilder builder;
-
- public AutomaticBuilder getBuilder() {
- return this.builder;
+ public AutomaticBuilderEnum getBuilderEnum() {
+ return this.automaticBuilder;
}
- public InputConfiguration setBuilder(AutomaticBuilder builder) {
- this.builder = builder;
+ public InputConfiguration setBuilderEnum(AutomaticBuilderEnum automaticBuilderEnum) {
+ this.automaticBuilder = automaticBuilderEnum;
return this;
}
- /*
- General properties
- */
-
private Factory factory;
public Factory getFactory() {
@@ -546,8 +688,6 @@ public InputConfiguration setFactory(Factory factory) {
return this;
}
- private String outputDirectory;
-
public InputConfiguration setOutputDirectory(String outputDirectory) {
this.outputDirectory = outputDirectory;
return this;
@@ -557,41 +697,15 @@ public String getOutputDirectory() {
return this.outputDirectory;
}
- @Deprecated
- private String configPath;
-
- @Deprecated
- public String getConfigPath() {
- return configPath;
- }
-
- @Deprecated
- public InputConfiguration setConfigPath(String configPath) {
- this.configPath = configPath;
- return this;
- }
-
- /*
- Assertions properties
- */
-
- private String delta;
-
- public String getDelta() {
+ public double getDelta() {
return delta;
}
- public InputConfiguration setDelta(String delta) {
+ public InputConfiguration setDelta(double delta) {
this.delta = delta;
return this;
}
- /*
- ChangeDetector properties
- */
-
- private String absolutePathToSecondVersionProjectRoot;
-
public String getAbsolutePathToSecondVersionProjectRoot() {
return absolutePathToSecondVersionProjectRoot;
}
@@ -602,12 +716,6 @@ public InputConfiguration setAbsolutePathToSecondVersionProjectRoot(String absol
return this;
}
- /*
- Amplification and Pit properties
- */
-
- private String excludedClasses = "";
-
public String getExcludedClasses() {
return excludedClasses;
}
@@ -617,8 +725,6 @@ public InputConfiguration setExcludedClasses(String excludedClasses) {
return this;
}
- private String excludedTestCases;
-
public String getExcludedTestCases() {
return excludedTestCases;
}
@@ -628,12 +734,6 @@ public InputConfiguration setExcludedTestCases(String excludedTestCases) {
return this;
}
- /*
- Pit properties
- */
-
- private String filter;
-
public String getFilter() {
return filter;
}
@@ -643,8 +743,6 @@ public InputConfiguration setFilter(String filter) {
return this;
}
- private String pitVersion;
-
public String getPitVersion() {
return pitVersion;
}
@@ -654,8 +752,6 @@ public InputConfiguration setPitVersion(String pitVersion) {
return this;
}
- private String descartesVersion;
-
public String getDescartesVersion() {
return descartesVersion;
}
@@ -665,8 +761,6 @@ public InputConfiguration setDescartesVersion(String descartesVersion) {
return this;
}
- private String JVMArgs = "";
-
public String getJVMArgs() {
return JVMArgs;
}
@@ -677,7 +771,13 @@ public InputConfiguration setJVMArgs(String JVMArgs) {
return this;
}
- private String descartesMutators = "";
+ public void setSystemProperties(String systemProperties) {
+ this.systemProperties = systemProperties;
+ }
+
+ public String getSystemProperties() {
+ return this.systemProperties;
+ }
public String getDescartesMutators() {
return descartesMutators;
@@ -688,50 +788,18 @@ public InputConfiguration setDescartesMutators(String descartesMutators) {
return this;
}
- private boolean descartesMode = true;
-
- public boolean isDescartesMode() {
- return descartesMode;
+ public boolean isGregorMode() {
+ return gregorMode;
}
- public InputConfiguration setDescartesMode(boolean descartesMode) {
- this.descartesMode = descartesMode;
- if (this.descartesMode) {
- this.setPitVersion("1.4.0"); // forcing pit version 1.4.0 to work with descartes
- } else if (this.getPitVersion() == null) {
- this.setPitVersion("1.4.0");
- }
- return this;
+ public void setGregorMode(boolean gregorMode) {
+ this.gregorMode = gregorMode;
}
- /*
- Inherited from old Configuration (from command line)
- */
-
- private List amplifiers = Collections.emptyList();
- private int nbIteration = 3;
- private List testClasses = Collections.singletonList("all");
- private TestSelector selector = new PitMutantScoreSelector();
- private List testCases = Collections.emptyList();
- private long seed = 23L;
- private int timeOutInMs = 10000;
- private Integer maxTestAmplified = 200;
- private boolean clean = false;
- private boolean minimize = false;
- private boolean verbose = false;
- private boolean useWorkingDirectory = false;
- private boolean withComment = false;
-
public boolean shouldUseWorkingDirectory() {
return useWorkingDirectory;
}
- /**
- * Side effect: assign the same value to {@link eu.stamp_project.testrunner.EntryPoint#workingDirectory}
- *
- * @param useWorkingDirectory of the verbose mode.
- * @return an instance of this InputConfiguration
- */
public InputConfiguration setUseWorkingDirectory(boolean useWorkingDirectory) {
this.useWorkingDirectory = useWorkingDirectory;
if (this.shouldUseWorkingDirectory()) {
@@ -744,23 +812,17 @@ public boolean isVerbose() {
return verbose;
}
- /**
- * Side effect: assign the same value to {@link eu.stamp_project.testrunner.EntryPoint#verbose}
- *
- * @param verbose value of the verbose mode.
- * @return an instance of this InputConfiguration
- */
public InputConfiguration setVerbose(boolean verbose) {
this.verbose = verbose;
EntryPoint.verbose = this.isVerbose();
return this;
}
- public List getAmplifiers() {
- return amplifiers;
+ public List getAmplifiers() {
+ return this.amplifiers;
}
- public InputConfiguration setAmplifiers(List amplifiers) {
+ public InputConfiguration setAmplifiers(List amplifiers) {
this.amplifiers = amplifiers;
return this;
}
@@ -788,15 +850,23 @@ public InputConfiguration addTestClasses(String testClass) {
return this;
}
- public TestSelector getSelector() {
- return selector;
- }
-
- public InputConfiguration setSelector(TestSelector selector) {
+ public InputConfiguration setSelector(SelectorEnum selector) {
this.selector = selector;
return this;
}
+ public String getPathPitResult() {
+ return this.pathPitResult;
+ }
+
+ public PitMutantScoreSelector.OutputFormat getPitOutputFormat() {
+ return this.pitOutputFormat;
+ }
+
+ public SelectorEnum getSelector() {
+ return this.selector;
+ }
+
public List getTestCases() {
return testCases;
}
@@ -831,7 +901,6 @@ public int getTimeOutInMs() {
public InputConfiguration setTimeOutInMs(int timeOutInMs) {
this.timeOutInMs = timeOutInMs;
- AmplificationHelper.timeOutInMs = timeOutInMs; // TODO should not be redundant
return this;
}
@@ -853,15 +922,6 @@ public InputConfiguration setClean(boolean clean) {
return this;
}
- public boolean shouldMinimize() {
- return minimize;
- }
-
- public InputConfiguration setMinimize(boolean minimize) {
- this.minimize = minimize;
- return this;
- }
-
public boolean withComment() {
return withComment;
}
@@ -871,26 +931,15 @@ public InputConfiguration setWithComment(boolean withComment) {
return this;
}
- private InputAmplDistributorEnum inputAmplDistributor;
-
- // TODO update after merging #888
- public InputAmplDistributorEnum getBudgetizer() {
+ public InputAmplDistributorEnum getInputAmplDistributor() {
return this.inputAmplDistributor;
}
- // TODO update after merging #888
- public InputConfiguration setBudgetizer(InputAmplDistributorEnum inputAmplDistributor) {
+ public InputConfiguration setInputAmplDistributor(InputAmplDistributorEnum inputAmplDistributor) {
this.inputAmplDistributor = inputAmplDistributor;
return this;
}
- private boolean generateAmplifiedTestClass;
-
- /**
- * @return If this is true, then DSpot will creates new test class with only amplified test methods.
- * This new test class will be named with "Ampl" as suffix or prefix depending of the name of the original test class:
- * e.g. MyClassTest will be AmplMyClassTest and TestMyClass will be TestMyClassAmpl
- */
public boolean shouldGenerateAmplifiedTestClass() {
return generateAmplifiedTestClass;
}
@@ -900,11 +949,6 @@ public InputConfiguration setGenerateAmplifiedTestClass(boolean generateAmplifie
return this;
}
- /**
- * This boolean say if we must use maven to execute the test. If not, the tests will be executed with a java command line
- */
- private boolean useMavenToExecuteTest = false;
-
public boolean shouldUseMavenToExecuteTest() {
return useMavenToExecuteTest;
}
@@ -914,11 +958,6 @@ public InputConfiguration setUseMavenToExecuteTest(boolean useMavenToExecuteTest
return this;
}
- /**
- * pre goals to run in case tests' execution done by maven
- */
- private String preGoalsTestExecution = "";
-
public String getPreGoalsTestExecution() {
return this.preGoalsTestExecution;
}
@@ -928,11 +967,6 @@ public InputConfiguration setPreGoalsTestExecution(String preGoalsTestExecution)
return this;
}
- /**
- * This boolean say if the outputs test class should also contain original test methods.
- */
- private boolean keepOriginalTestMethods = false;
-
public boolean shouldKeepOriginalTestMethods() {
return this.keepOriginalTestMethods;
}
@@ -942,21 +976,6 @@ public InputConfiguration setKeepOriginalTestMethods(boolean keepOriginalTestMet
return this;
}
- private boolean isJUnit5;
-
- /**
- * This boolean says if the current amplification is in JUnit5 or not.
- */
- public boolean isJUnit5() {
- return this.isJUnit5;
- }
-
- public void setJUnit5(boolean JUnit5) {
- isJUnit5 = JUnit5;
- }
-
- private boolean targetOneTestClass = false;
-
public boolean shouldTargetOneTestClass() {
return this.targetOneTestClass;
}
@@ -966,8 +985,6 @@ public InputConfiguration setTargetOneTestClass(boolean targetOneTestClass) {
return this;
}
- private boolean allowPathInAssertion = false;
-
public boolean shouldAllowPathInAssertion() {
return this.allowPathInAssertion;
}
@@ -977,12 +994,6 @@ public InputConfiguration setAllowPathInAssertion(boolean allowPathInAssertion)
return this;
}
- /**
- * This boolean say if we must use execute the test in parallel. If not, the tests will be executed sequentially
- */
- private boolean executeTestsInParallel = false;
- private int numberParallelExecutionProcessors = Runtime.getRuntime().availableProcessors();
-
public boolean shouldExecuteTestsInParallel() {
return executeTestsInParallel;
}
@@ -993,6 +1004,9 @@ public InputConfiguration setExecuteTestsInParallel(boolean executeTestsInParall
}
public int getNumberParallelExecutionProcessors() {
+ if (this.numberParallelExecutionProcessors == 0) {
+ this.numberParallelExecutionProcessors = Runtime.getRuntime().availableProcessors();
+ }
return numberParallelExecutionProcessors;
}
@@ -1001,4 +1015,83 @@ public InputConfiguration setNumberParallelExecutionProcessors(int numberParalle
return this;
}
+ public Long getCacheSize() {
+ return this.cacheSize;
+ }
+
+ public CollectorEnum getCollector() {
+ return this.collector;
+ }
+
+ public boolean shouldRunExample() {
+ return this.example;
+ }
+
+ public String getMongoUrl() {
+ return mongoUrl;
+ }
+
+ public String getMongoDbName() {
+ return mongoDbName;
+ }
+
+ public String getMongoColName() {
+ return mongoColName;
+ }
+
+ public String getRepoSlug() {
+ return repoSlug;
+ }
+
+ public String getRepoBranch() {
+ return repoBranch;
+ }
+
+ public boolean isRestFul() {
+ return restFul;
+ }
+
+ public String getSmtpUsername() {
+ return smtpUsername;
+ }
+
+ public String getSmtpPassword() {
+ return smtpPassword;
+ }
+
+ public String getSmtpHost() {
+ return smtpHost;
+ }
+
+ public String getSmtpPort() {
+ return smtpPort;
+ }
+
+ public boolean isSmtpAuth() {
+ return smtpAuth;
+ }
+
+ public String getSmtpTls() {
+ return smtpTls;
+ }
+
+ public void configureExample() {
+ try {
+ this.setAbsolutePathToProjectRoot("src/test/resources/test-projects/");
+ this.setNbIteration(1);
+ this.setAmplifiers(Collections.singletonList(AmplifierEnum.FastLiteralAmplifier));
+ this.setSelector(SelectorEnum.JacocoCoverageSelector);
+ this.setInputAmplDistributor(InputAmplDistributorEnum.RandomInputAmplDistributor);
+ this.setTestClasses(Collections.singletonList("example.TestSuiteExample"));
+ this.setTestCases(Collections.emptyList());
+ this.setVerbose(true);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public void setDependencies(String dependencies) {
+ this.dependencies =dependencies;
+ }
}
+
diff --git a/dspot/src/main/java/eu/stamp_project/utils/program/InputConfigurationProperty.java b/dspot/src/main/java/eu/stamp_project/utils/program/InputConfigurationProperty.java
deleted file mode 100644
index 593ebc5ae..000000000
--- a/dspot/src/main/java/eu/stamp_project/utils/program/InputConfigurationProperty.java
+++ /dev/null
@@ -1,100 +0,0 @@
-package eu.stamp_project.utils.program;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.Properties;
-
-/**
- * Created by Benjamin DANGLOT
- * benjamin.danglot@inria.fr
- * on 02/06/18
- */
-public class InputConfigurationProperty {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(InputConfigurationProperty.class);
-
- private final String name;
- private final String description;
- private final String defaultValue;
- private final String naturalLanguageDesignation;
- private final String oldName;
-
- public InputConfigurationProperty(String name, String description, String defaultValue) {
- this.name = name;
- this.description = description;
- this.defaultValue = defaultValue;
- this.naturalLanguageDesignation = "";
- this.oldName = "";
- }
-
- public InputConfigurationProperty(String name,
- String description,
- String defaultValue,
- String naturalLanguageDesignation) {
- this.name = name;
- this.description = description;
- this.defaultValue = defaultValue;
- this.naturalLanguageDesignation = naturalLanguageDesignation;
- this.oldName = "";
- }
-
- public InputConfigurationProperty(String name, String description, String defaultValue, String naturalLanguageDesignation, String oldName) {
- this.name = name;
- this.description = description;
- this.defaultValue = defaultValue;
- this.naturalLanguageDesignation = naturalLanguageDesignation;
- this.oldName = oldName;
- }
-
- public String getName() {
- return name;
- }
-
- public String getDescription() {
- return description;
- }
-
- public String getDefaultValue() {
- return defaultValue;
- }
-
- public String getNaturalLanguageDesignation() {
- return naturalLanguageDesignation;
- }
-
- public boolean isRequired() {
- return this.defaultValue == null;
- }
-
- private boolean hasDefaultValue() {
- return !isRequired() && !this.defaultValue.isEmpty();
- }
-
- public String get(Properties properties) {
- if (properties.containsKey(this.oldName)) {
- LOGGER.warn("You used the old name ({}) for {}.", this.oldName, this.getName());
- LOGGER.warn("The old name will be removed in future versions.");
- LOGGER.warn("Please, update your properties file.");
- return this.get(properties, this.oldName);
- } else {
- return this.get(properties, this.getName());
- }
- }
-
- private String get(Properties properties, String keyToUse) {
- if (!isRequired()) {
- return properties.getProperty(keyToUse, this.getDefaultValue());
- } else {
- return properties.getProperty(keyToUse);
- }
- }
-
- /**
- * @return This method return in markdown format a description of the Property
- */
- @Override
- public String toString() {
- return "\t* `" + this.name + "`: " + this.description + (this.hasDefaultValue() ? "(default: " + this.defaultValue + ")" : "");
- }
-}
diff --git a/dspot/src/main/java/eu/stamp_project/utils/report/GlobalReport.java b/dspot/src/main/java/eu/stamp_project/utils/report/GlobalReport.java
index 2c4905b7a..38c7aa437 100644
--- a/dspot/src/main/java/eu/stamp_project/utils/report/GlobalReport.java
+++ b/dspot/src/main/java/eu/stamp_project/utils/report/GlobalReport.java
@@ -31,10 +31,10 @@ public GlobalReport(OutputReport outputReport, ErrorReport errorReport, TestSele
/* REPORT METHODS */
@Override
- public void output() {
- this.testSelectorReport.output();
- this.errorReport.output();
- this.outputReport.output();
+ public void output(String outputDirectory) {
+ this.testSelectorReport.output(outputDirectory);
+ this.errorReport.output(outputDirectory);
+ this.outputReport.output(outputDirectory);
}
@Override
diff --git a/dspot/src/main/java/eu/stamp_project/utils/report/Report.java b/dspot/src/main/java/eu/stamp_project/utils/report/Report.java
index d4d9c389e..e940297cd 100644
--- a/dspot/src/main/java/eu/stamp_project/utils/report/Report.java
+++ b/dspot/src/main/java/eu/stamp_project/utils/report/Report.java
@@ -7,7 +7,7 @@
*/
public interface Report {
- public void output();
+ public void output(String outputDirectory);
public void reset();
diff --git a/dspot/src/main/java/eu/stamp_project/utils/report/error/ErrorEnum.java b/dspot/src/main/java/eu/stamp_project/utils/report/error/ErrorEnum.java
index 5fa373e69..102de28eb 100644
--- a/dspot/src/main/java/eu/stamp_project/utils/report/error/ErrorEnum.java
+++ b/dspot/src/main/java/eu/stamp_project/utils/report/error/ErrorEnum.java
@@ -1,8 +1,6 @@
package eu.stamp_project.utils.report.error;
import eu.stamp_project.utils.AmplificationHelper;
-import eu.stamp_project.utils.program.ConstantsProperties;
-import eu.stamp_project.utils.program.InputConfigurationProperty;
/**
* created by Benjamin DANGLOT
@@ -21,14 +19,14 @@ public enum ErrorEnum {
/*
ERRORS PROPERTIES
*/
- ERROR_PATH_TO_PROJECT_ROOT_PROPERTY(ConstantsProperties.PROJECT_ROOT_PATH),
- ERROR_PATH_TO_TARGET_MODULE_PROPERTY(ConstantsProperties.MODULE),
- ERROR_PATH_TO_SRC_PROPERTY(ConstantsProperties.SRC_CODE),
- ERROR_PATH_TO_TEST_SRC_PROPERTY(ConstantsProperties.TEST_SRC_CODE),
- ERROR_PATH_TO_SRC_CLASSES_PROPERTY(ConstantsProperties.SRC_CLASSES),
- ERROR_PATH_TO_TEST_CLASSES_PROPERTY(ConstantsProperties.TEST_CLASSES),
- ERROR_PATH_TO_SECOND_VERSION(ConstantsProperties.PATH_TO_SECOND_VERSION),
- ERROR_PATH_TO_MAVEN_HOME(ConstantsProperties.MAVEN_HOME),
+ ERROR_PATH_TO_PROJECT_ROOT_PROPERTY("project root", "--absolute-path-to-project-root"),
+ ERROR_PATH_TO_TARGET_MODULE_PROPERTY("targeted module", "--target-module"),
+ ERROR_PATH_TO_SRC_PROPERTY("source folder", "--relative-path-to-source-code"),
+ ERROR_PATH_TO_TEST_SRC_PROPERTY("test source folder", "--relative-path-to-test-code"),
+ ERROR_PATH_TO_SRC_CLASSES_PROPERTY("binaries folder", "--relative-path-to-classes"),
+ ERROR_PATH_TO_TEST_CLASSES_PROPERTY("test binaries folder", "--relative-path-to-test-classes"),
+ ERROR_PATH_TO_SECOND_VERSION("path to second version", "--absolute-path-to-second-version"),
+ ERROR_PATH_TO_MAVEN_HOME("maven installation", "--maven-home"),
ERROR_INVALID_VERSION("Invalid version"),
/*
@@ -58,15 +56,18 @@ public enum ErrorEnum {
// PitMutantScoreSelector
ERROR_ORIGINAL_MUTATION_SCORE("Something bad happened when DSpot tried to computed the original mutation score."
+ AmplificationHelper.LINE_SEPARATOR +
- "This is usually due to the value of the property " + ConstantsProperties.PIT_FILTER_CLASSES_TO_KEEP.getName() + "."
+ "This is usually due to the value of the command line option --pit-filter-classes-to-keep."
+ AmplificationHelper.LINE_SEPARATOR +
- ConstantsProperties.PIT_FILTER_CLASSES_TO_KEEP.getDescription()
+ "Specify the filter of classes to keep used by PIT. " +
+ "This allow you restrict the scope of the mutation done by PIT. " +
+ "If this is not specified, DSpot will try to build on the " +
+ "fly a filter that takes into account the largest number of classes, e.g. the topest package. "
+ AmplificationHelper.LINE_SEPARATOR +
"This is can be also due to a specific configuration of your test suite. If any test fails,"
+ AmplificationHelper.LINE_SEPARATOR +
"PIT (and so DSpot) won't be able to be executed. Please, check your environment variables,"
+ AmplificationHelper.LINE_SEPARATOR +
- "external files, etc. You can use " + ConstantsProperties.EXCLUDED_CLASSES + " and " + ConstantsProperties.EXCLUDED_TEST_CASES
+ "external files, etc. You can use --excluded-classes and --excluded-test-cases"
+ AmplificationHelper.LINE_SEPARATOR +
" to exclude respectively specific test classes ans test cases."
);
@@ -81,9 +82,8 @@ public String getMessage() {
this.message = message;
}
- ErrorEnum(InputConfigurationProperty property) {
- this.message =
- "There is a problem with the provided path to the "
- + property.getNaturalLanguageDesignation() + "(" + property.getName() + " property)";
+ ErrorEnum(String naturalDesignation, String name) {
+ this.message =" There is a problem with the provided path to the "
+ + naturalDesignation + "(" + name + " command-line)";
}
}
diff --git a/dspot/src/main/java/eu/stamp_project/utils/report/error/ErrorReportImpl.java b/dspot/src/main/java/eu/stamp_project/utils/report/error/ErrorReportImpl.java
index b6554934a..7b4b63e5a 100644
--- a/dspot/src/main/java/eu/stamp_project/utils/report/error/ErrorReportImpl.java
+++ b/dspot/src/main/java/eu/stamp_project/utils/report/error/ErrorReportImpl.java
@@ -1,7 +1,7 @@
package eu.stamp_project.utils.report.error;
import eu.stamp_project.utils.AmplificationHelper;
-import eu.stamp_project.utils.program.InputConfiguration;
+
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -50,7 +50,7 @@ private boolean hasError() {
}
@Override
- public void output() {
+ public void output(String outputDirectory) {
if (!hasError()) {
LOGGER.info("DSpot amplified your test suite without errors. (no errors report will be outputted)");
} else {
@@ -65,7 +65,7 @@ public void output() {
}
final String stringReport = report.toString();
LOGGER.warn(stringReport);
- try (FileWriter writer = new FileWriter(InputConfiguration.get().getOutputDirectory() + "/errors_report.txt", false)) {
+ try (FileWriter writer = new FileWriter(outputDirectory + "/errors_report.txt", false)) {
writer.write(stringReport);
} catch (IOException e) {
throw new RuntimeException(e);
diff --git a/dspot/src/main/java/eu/stamp_project/utils/report/output/Output.java b/dspot/src/main/java/eu/stamp_project/utils/report/output/Output.java
index 33fbe60e9..b9aeed617 100644
--- a/dspot/src/main/java/eu/stamp_project/utils/report/output/Output.java
+++ b/dspot/src/main/java/eu/stamp_project/utils/report/output/Output.java
@@ -5,6 +5,8 @@
import eu.stamp_project.Main;
import eu.stamp_project.utils.AmplificationHelper;
import eu.stamp_project.utils.DSpotUtils;
+import eu.stamp_project.utils.collector.Collector;
+import eu.stamp_project.utils.collector.NullCollector;
import eu.stamp_project.utils.json.ClassTimeJSON;
import eu.stamp_project.utils.json.ProjectTimeJSON;
import eu.stamp_project.utils.program.InputConfiguration;
@@ -29,7 +31,9 @@ public class Output {
private String outputPathDirectory;
- public Output(String absolutePathToProjectRoot, String outputDirectoryPath) {
+ private Collector collector;
+
+ public Output(String absolutePathToProjectRoot, String outputDirectoryPath, Collector collector) {
this.outputPathDirectory = outputDirectoryPath;
String splitter = File.separator.equals("/") ? "/" : "\\\\";
final String[] splittedPath = absolutePathToProjectRoot.split(splitter);
@@ -44,6 +48,7 @@ public Output(String absolutePathToProjectRoot, String outputDirectoryPath) {
} else {
this.projectTimeJSON = new ProjectTimeJSON(splittedPath[splittedPath.length - 1]);
}
+ this.collector = collector;
}
public CtType> output(CtType> testClassToBeAmplified, List> amplifiedTestMethods) {
@@ -62,7 +67,7 @@ public CtType> output(CtType> testClassToBeAmplified, List> ampl
);
// we try to compile the newly generated amplified test class (.java)
// if this fail, we re-print the java test class without imports
- DSpotUtils.printAndCompileToCheck(amplification, outputDirectory);
+ DSpotUtils.printAndCompileToCheck(amplification, outputDirectory, collector);
} else {
LOGGER.warn("DSpot could not obtain any amplified test method.");
LOGGER.warn("You can customize the following options: --amplifiers, --test-criterion, --iteration, --inputAmplDistributor etc, and retry with a new configuration.");
@@ -90,7 +95,15 @@ public void addClassTimeJSON(String qualifiedName, long elapsedTime) {
this.projectTimeJSON.add(new ClassTimeJSON(qualifiedName, elapsedTime));
}
+ public void reportSelectorInformation(String report) {
+ this.collector.reportSelectorInformation(report);
+ }
+
+ public static Output get(InputConfiguration configuration, Collector collector) {
+ return new Output(configuration.getAbsolutePathToProjectRoot(), configuration.getOutputDirectory(), collector);
+ }
+
public static Output get(InputConfiguration configuration) {
- return new Output(configuration.getAbsolutePathToProjectRoot(), configuration.getOutputDirectory());
+ return new Output(configuration.getAbsolutePathToProjectRoot(), configuration.getOutputDirectory(), new NullCollector());
}
}
diff --git a/dspot/src/main/java/eu/stamp_project/utils/report/output/OutputReportImpl.java b/dspot/src/main/java/eu/stamp_project/utils/report/output/OutputReportImpl.java
index 57e163bb8..38c4787ef 100644
--- a/dspot/src/main/java/eu/stamp_project/utils/report/output/OutputReportImpl.java
+++ b/dspot/src/main/java/eu/stamp_project/utils/report/output/OutputReportImpl.java
@@ -35,7 +35,7 @@ public void addPrintedTestClasses(String line) {
}
@Override
- public void output() {
+ public void output(String outputDirectory) {
LOGGER.info("The amplification ends up with {} amplified test methods over {} test classes.",
this.totalNumberOfAmplifiedTestMethods,
this.linesOfOutputtingAmplifiedTestClasses.size()
diff --git a/dspot/src/main/java/eu/stamp_project/utils/report/output/selector/TestSelectorElementReport.java b/dspot/src/main/java/eu/stamp_project/utils/report/output/selector/TestSelectorElementReport.java
index 8f1520cff..3b4e135e4 100644
--- a/dspot/src/main/java/eu/stamp_project/utils/report/output/selector/TestSelectorElementReport.java
+++ b/dspot/src/main/java/eu/stamp_project/utils/report/output/selector/TestSelectorElementReport.java
@@ -9,6 +9,8 @@
*/
public interface TestSelectorElementReport {
- public String output(CtType> testClass);
+ public String output(CtType> testClass, String outputDirectory);
+
+ public String getReportForCollector();
}
diff --git a/dspot/src/main/java/eu/stamp_project/utils/report/output/selector/TestSelectorElementReportImpl.java b/dspot/src/main/java/eu/stamp_project/utils/report/output/selector/TestSelectorElementReportImpl.java
index febd7a23e..fe775304a 100644
--- a/dspot/src/main/java/eu/stamp_project/utils/report/output/selector/TestSelectorElementReportImpl.java
+++ b/dspot/src/main/java/eu/stamp_project/utils/report/output/selector/TestSelectorElementReportImpl.java
@@ -2,7 +2,7 @@
import com.google.gson.GsonBuilder;
import eu.stamp_project.utils.DSpotUtils;
-import eu.stamp_project.utils.program.InputConfiguration;
+
import spoon.reflect.declaration.CtType;
import java.io.File;
@@ -28,10 +28,15 @@ public TestSelectorElementReportImpl(String textualReport, TestClassJSON testCla
}
@Override
- public String output(CtType> testClass) {
+ public String getReportForCollector() {
+ return this.testClassJSON.toString();
+ }
+
+ @Override
+ public String output(CtType> testClass, String outputDirectory) {
// 1 output the specific JSON file for the test class
final File outputJsonFile = new File(
- DSpotUtils.shouldAddSeparator.apply(InputConfiguration.get().getOutputDirectory()) +
+ DSpotUtils.shouldAddSeparator.apply(outputDirectory) +
testClass.getQualifiedName() + SUFFIX_PATH_TO_JSON_FILE
);
try (FileWriter writer = new FileWriter(outputJsonFile, false)) {
diff --git a/dspot/src/main/java/eu/stamp_project/utils/report/output/selector/TestSelectorReportImpl.java b/dspot/src/main/java/eu/stamp_project/utils/report/output/selector/TestSelectorReportImpl.java
index 6f95da5dd..762944b0a 100644
--- a/dspot/src/main/java/eu/stamp_project/utils/report/output/selector/TestSelectorReportImpl.java
+++ b/dspot/src/main/java/eu/stamp_project/utils/report/output/selector/TestSelectorReportImpl.java
@@ -2,7 +2,6 @@
import eu.stamp_project.utils.AmplificationHelper;
import eu.stamp_project.utils.DSpotUtils;
-import eu.stamp_project.utils.program.InputConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import spoon.reflect.declaration.CtType;
@@ -29,14 +28,16 @@ public TestSelectorReportImpl() {
}
@Override
- public void output() {
- final String allReports = this.testSelectorElementReportPerTestClass.keySet().stream()
- .filter(this.testSelectorElementReportPerTestClass::containsKey)
- .map(testClass -> this.testSelectorElementReportPerTestClass.get(testClass).output(testClass))
- .collect(Collectors.joining(AmplificationHelper.LINE_SEPARATOR));
+ public void output(String outputDirectory) {
+ final String allReports = this.testSelectorElementReportPerTestClass.keySet()
+ .stream()
+ .filter(testClass -> this.testSelectorElementReportPerTestClass.get(testClass) != null)
+ .map(testClass -> this.testSelectorElementReportPerTestClass.get(testClass).output(
+ testClass, outputDirectory)
+ ).collect(Collectors.joining(AmplificationHelper.LINE_SEPARATOR));
LOGGER.info("{}{}", AmplificationHelper.LINE_SEPARATOR, allReports);
final String reportPathName = DSpotUtils.shouldAddSeparator
- .apply(InputConfiguration.get().getOutputDirectory()) +
+ .apply(outputDirectory) +
"report.txt";
try (FileWriter writer = new FileWriter(reportPathName, false)) {
writer.write(allReports);
diff --git a/dspot/src/main/java/eu/stamp_project/utils/smtp/EmailSender.java b/dspot/src/main/java/eu/stamp_project/utils/smtp/EmailSender.java
index 7801063b8..040c56ba5 100644
--- a/dspot/src/main/java/eu/stamp_project/utils/smtp/EmailSender.java
+++ b/dspot/src/main/java/eu/stamp_project/utils/smtp/EmailSender.java
@@ -14,39 +14,41 @@
import javax.mail.internet.MimeMessage;
public class EmailSender implements Sender {
+
private static final Logger LOGGER = LoggerFactory.getLogger(EmailSender.class);
- private static final SmtpConfig smtpConfig = SmtpConfig.getInstance();
- private static EmailSender emailSender;
private String smtpUsername;
private String smtpPassword;
private String smtpHost;
private String smtpPort;
- private String smtpAuth;
+ private boolean smtpAuth;
private String smtpTls;
- public static EmailSender getInstance() {
- if (emailSender == null) {
- emailSender = new EmailSender();
- }
- return emailSender;
+ public EmailSender(String smtpUsername,
+ String smtpPassword,
+ String smtpHost,
+ String smtpPort,
+ boolean smtpAuth,
+ String smtpTls) {
+ this.smtpUsername = smtpUsername;
+ this.smtpPassword = smtpPassword;
+ this.smtpHost = smtpHost;
+ this.smtpPort = smtpPort;
+ this.smtpAuth = smtpAuth;
+ this.smtpTls = smtpTls;
}
- public void sendEmail(String messageText,String subject,String toUsers) {
- final String username = this.smtpConfig.getSmtpUserName();
- final String password = this.smtpConfig.getSmtpPassword();
- final String fromUser = username;
-
+ public void sendEmail(String messageText, String subject, String toUsers) {
Properties prop = new Properties();
- prop.put("mail.smtp.host", this.smtpConfig.getSmtpHost());
- prop.put("mail.smtp.port", this.smtpConfig.getSmtpPort());
- prop.put("mail.smtp.auth", this.smtpConfig.getSmtpAuth());
- prop.put("mail.smtp.starttls.enable", this.smtpConfig.getSmtpTls()); //TLS
+ prop.put("mail.smtp.host", this.smtpHost);
+ prop.put("mail.smtp.port", this.smtpPort);
+ prop.put("mail.smtp.auth", this.smtpAuth);
+ prop.put("mail.smtp.starttls.enable", this.smtpTls); //TLS
Session session = Session.getInstance(prop,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
- return new PasswordAuthentication(username,password);
+ return new PasswordAuthentication(smtpUsername,smtpPassword);
}
});
@@ -55,7 +57,7 @@ protected PasswordAuthentication getPasswordAuthentication() {
Message message = new MimeMessage(session);
// Set From: header field of the header.
- message.setFrom(new InternetAddress(fromUser));
+ message.setFrom(new InternetAddress(smtpUsername));
// Set To: header field of the header.
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(toUsers));
diff --git a/dspot/src/main/java/eu/stamp_project/utils/smtp/SmtpConfig.java b/dspot/src/main/java/eu/stamp_project/utils/smtp/SmtpConfig.java
deleted file mode 100644
index e60afc931..000000000
--- a/dspot/src/main/java/eu/stamp_project/utils/smtp/SmtpConfig.java
+++ /dev/null
@@ -1,76 +0,0 @@
-package eu.stamp_project.utils.smtp;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-// Used to collect output information from selector class.
-public class SmtpConfig {
-
- /* Initialization */
- private static SmtpConfig smtpConfig;
-
- private static final Logger LOGGER = LoggerFactory.getLogger(SmtpConfig.class);
-
- public static SmtpConfig getInstance() {
- if (smtpConfig == null ) {
- smtpConfig = new SmtpConfig();
- }
- return smtpConfig;
- }
-
- /* Variables and getters/setters */
- private static String smtpUserName;
- private static String smtpPassword;
- private static String smtpHost;
- private static String smptPort;
- private static String smtpAuth;
- private static String smtpTls;
-
- public void setSmtpUserName(String smtpUserName) {
- this.smtpUserName = smtpUserName;
- }
-
- public String getSmtpUserName() {
- return this.smtpUserName;
- }
-
- public void setSmtpPassword(String smtpPassword) {
- this.smtpPassword = smtpPassword;
- }
-
- public String getSmtpPassword() {
- return this.smtpPassword;
- }
-
- public void setSmtpHost(String smtpHost) {
- this.smtpHost = smtpHost;
- }
-
- public String getSmtpHost() {
- return this.smtpHost;
- }
-
- public void setSmtpPort(String smptPort) {
- this.smptPort = smptPort;
- }
-
- public String getSmtpPort() {
- return this.smptPort;
- }
-
- public void setSmtpAuth(String smtpAuth) {
- this.smtpAuth = smtpAuth;
- }
-
- public String getSmtpAuth() {
- return this.smtpAuth;
- }
-
- public void setSmtpTls(String smtpTls) {
- this.smtpTls = smtpTls;
- }
-
- public String getSmtpTls() {
- return this.smtpTls;
- }
-}
diff --git a/dspot/src/main/java/eu/stamp_project/utils/test_finder/TestFinder.java b/dspot/src/main/java/eu/stamp_project/utils/test_finder/TestFinder.java
index 1381c9920..d877c774d 100644
--- a/dspot/src/main/java/eu/stamp_project/utils/test_finder/TestFinder.java
+++ b/dspot/src/main/java/eu/stamp_project/utils/test_finder/TestFinder.java
@@ -41,7 +41,7 @@ public TestFinder(List excludedClasses, List excludedTestCases)
* Predicate that returns either the given ctType should be excluded or not.
*/
public final Predicate isNotExcluded = ctType ->
- InputConfiguration.get().getExcludedClasses().isEmpty() ||
+ this.excludedTestClasses.isEmpty() ||
this.excludedTestClasses.stream()
.map(Pattern::compile)
.map(pattern -> pattern.matcher(ctType.getQualifiedName()))
diff --git a/dspot/src/test/java/eu/stamp_project/AbstractTest.java b/dspot/src/test/java/eu/stamp_project/AbstractTest.java
deleted file mode 100644
index 390c46a4b..000000000
--- a/dspot/src/test/java/eu/stamp_project/AbstractTest.java
+++ /dev/null
@@ -1,30 +0,0 @@
-package eu.stamp_project;
-
-import eu.stamp_project.dspot.amplifier.value.ValueCreator;
-import eu.stamp_project.utils.program.InputConfiguration;
-import eu.stamp_project.utils.RandomHelper;
-import org.junit.Before;
-
-/**
- * Created by Benjamin DANGLOT
- * benjamin.danglot@inria.fr
- * on 1/31/17
- */
-public abstract class AbstractTest {
-
- public String getPathToPropertiesFile() {
- return "src/test/resources/sample/sample.properties";
- }
-
- @Before
- public void setUp() throws Exception {
- Utils.init(getPathToPropertiesFile());
- RandomHelper.setSeedRandom(72L);
- ValueCreator.count = 0;
- Utils.getInputConfiguration().setVerbose(true);
- Utils.getInputConfiguration().setMinimize(false);
- InputConfiguration.get().setGenerateAmplifiedTestClass(false);
- InputConfiguration.get().setKeepOriginalTestMethods(false);
- InputConfiguration.get().setAllowPathInAssertion(false);
- }
-}
diff --git a/dspot/src/test/java/eu/stamp_project/MainTest.java b/dspot/src/test/java/eu/stamp_project/MainTest.java
index 9bf5a7eb7..52cac9118 100644
--- a/dspot/src/test/java/eu/stamp_project/MainTest.java
+++ b/dspot/src/test/java/eu/stamp_project/MainTest.java
@@ -80,20 +80,13 @@ public void testMainWithMixedListOfTestClassesAndTestMethods() throws Exception
Main.main(new String[]{
"--clean",
"--verbose",
- "--path-to-properties", "src/test/resources/sample/sample.properties",
+ "--absolute-path-to-project-root", new File("src/test/resources/sample/").getAbsolutePath() + "/",
"--test-criterion", "TakeAllSelector",
- "--test", "fr.inria.sample.TestClassWithoutAssert:fr.inria.sample.TestClassWithAssert",
- "--test-cases", "test1:test:anOldTest",
- "--no-minimize"
+ "--test", "fr.inria.sample.TestClassWithoutAssert,fr.inria.sample.TestClassWithAssert",
+ "--test-cases", "test1,test,anOldTest"
});
// an amplification happened, w/e it is
- CtClass> amplifiedTestClass = InputConfiguration.get().getFactory().Class().get("fr.inria.sample.TestClassWithAssert");
- assertNotNull(amplifiedTestClass);
- assertFalse(amplifiedTestClass.getMethods().isEmpty());
-// assertTrue(amplifiedTestClass.getMethods().stream().anyMatch(ctMethod -> ctMethod.getSimpleName().contains("anOldTest"))); // this test come from the super class
- amplifiedTestClass = InputConfiguration.get().getFactory().Class().get("fr.inria.sample.TestClassWithoutAssert");
- assertNotNull(amplifiedTestClass);
- assertFalse(amplifiedTestClass.getMethods().isEmpty());
+ assertTrue(new File("target/dspot/output/fr/inria/sample/TestClassWithAssert.java").exists());
}
@Test
@@ -108,11 +101,11 @@ it should not output the second class since there is no amplification.
Main.main(new String[]{
"--verbose",
- "--path-to-properties", "src/test/resources/sample/sample.properties",
+ "--absolute-path-to-project-root", new File("src/test/resources/sample/").getAbsolutePath() + "/",
"--test-criterion", "PitMutantScoreSelector",
- "--test", "fr.inria.sample.TestClassWithoutAssert:fr.inria.filter.failing.FailingTest",
+ "--test", "fr.inria.sample.TestClassWithoutAssert,fr.inria.filter.failing.FailingTest",
"--path-pit-result", "src/test/resources/sample/mutations.csv",
- "--gregor",
+ "--gregor-mode",
"--output-path", "target/trash",
});
@@ -131,11 +124,11 @@ public void testMainWithPitScoreSelectorWithMavenToExecuteTests() throws Excepti
Main.main(new String[]{
"--verbose",
- "--path-to-properties", "src/test/resources/sample/sample.properties",
+ "--absolute-path-to-project-root", new File("src/test/resources/sample/").getAbsolutePath() + "/",
"--test-criterion", "PitMutantScoreSelector",
- "--test", "fr.inria.sample.TestClassWithoutAssert:fr.inria.filter.failing.FailingTest",
+ "--test", "fr.inria.sample.TestClassWithoutAssert,fr.inria.filter.failing.FailingTest",
"--path-pit-result", "src/test/resources/sample/mutations.csv",
- "--gregor",
+ "--gregor-mode",
"--output-path", "target/trash",
"--use-maven-to-exe-test"
});
@@ -154,11 +147,11 @@ public void testMainWithPitScoreSelectorJUnit5() throws Exception {
Main.main(new String[]{
"--verbose",
- "--path-to-properties", "src/test/resources/sample/sample.properties",
+ "--absolute-path-to-project-root", new File("src/test/resources/sample/").getAbsolutePath() + "/",
"--test-criterion", "PitMutantScoreSelector",
"--test", "fr.inria.sample.TestClassWithoutAssertJUnit5",
"--path-pit-result", "src/test/resources/sample/mutations.csv",
- "--gregor",
+ "--gregor-mode",
"--output-path", "target/trash",
});
@@ -172,14 +165,11 @@ public void testMainWithEmptyTestMethods() throws Exception {
Main.main(new String[]{
"--clean",
"--verbose",
- "--path-to-properties", "src/test/resources/test-projects/test-projects.properties",
+ "--absolute-path-to-project-root", new File("src/test/resources/test-projects/").getAbsolutePath() + "/",
"--test-criterion", "TakeAllSelector",
- "--test", "example.TestSuiteExample",
- "--no-minimize"
+ "--test", "example.TestSuiteExample"
});
- final CtClass> amplifiedTestClass = InputConfiguration.get().getFactory().Class().get("example.TestSuiteExample");
- assertNotNull(amplifiedTestClass);
- assertFalse(amplifiedTestClass.getMethods().isEmpty());
+ assertTrue(new File("target/dspot/output/example/TestSuiteExample.java").exists());
}
@Test
@@ -193,24 +183,22 @@ public void testOnParametrizedTestClass() throws Exception {
Main.main(new String[]{
"--clean",
"--verbose",
- "--path-to-properties", "src/test/resources/test-projects/test-projects.properties",
+ "--absolute-path-to-project-root", new File("src/test/resources/test-projects/").getAbsolutePath() + "/",
"--test-criterion", "JacocoCoverageSelector",
"--iteration", "1",
"--amplifiers", "FastLiteralAmplifier",
"--test", "example.ParametrizedTestSuiteExample",
"--input-ampl-distributor", "TextualDistanceInputAmplDistributor",
- "--no-minimize",
"--test-cases", "test2"
});
- final CtClass> amplifiedTestClass = InputConfiguration.get().getFactory().Class().get("example.ParametrizedTestSuiteExample");
- assertNotNull(amplifiedTestClass);
+ assertTrue(new File("target/dspot/output/example/ParametrizedTestSuiteExample.java").exists());
}
@Test
public void testOnProjectWithResources() throws Exception {
Main.main(new String[]{
"--verbose",
- "--path-to-properties", "src/test/resources/project-with-resources/project-with-resources.properties",
+ "--absolute-path-to-project-root", new File("src/test/resources/project-with-resources/").getAbsolutePath() + "/",
"--test-criterion", "JacocoCoverageSelector",
"--iteration", "1"
});
@@ -225,10 +213,10 @@ public void testExample() throws Exception {
*/
Main.main(new String[]{"--verbose", "--example"});
- final File reportFile = new File("target/trash/report.txt");
- final File amplifiedTestClass = new File("target/trash/example/TestSuiteExample.java");
+ final File reportFile = new File("target/dspot/output/report.txt");
+ final File amplifiedTestClass = new File("target/dspot/output/example/TestSuiteExample.java");
assertTrue(reportFile.exists());
- assertTrue(new File("target/trash/example.TestSuiteExample_report.json").exists());
+ assertTrue(new File("target/dspot/output/example.TestSuiteExample_report.json").exists());
assertTrue(amplifiedTestClass.exists());
try (BufferedReader reader = new BufferedReader(new FileReader(reportFile))) {
String content = reader.lines().collect(Collectors.joining(AmplificationHelper.LINE_SEPARATOR)) + AmplificationHelper.LINE_SEPARATOR;
@@ -286,9 +274,9 @@ public void testOverrideExistingResults() throws Exception {
// run 1: lot of amplifiers
Main.main(new String[]{
- "--path-to-properties", "src/test/resources/test-projects/test-projects.properties",
+ "--absolute-path-to-project-root", new File("src/test/resources/test-projects/").getAbsolutePath() + "/",
"--test-criterion", "JacocoCoverageSelector",
- "--amplifiers", "MethodAdd" + AmplificationHelper.PATH_SEPARATOR + "FastLiteralAmplifier" + AmplificationHelper.PATH_SEPARATOR + "MethodAdderOnExistingObjectsAmplifier" + AmplificationHelper.PATH_SEPARATOR + "ReturnValueAmplifier",
+ "--amplifiers", "MethodDuplicationAmplifier,FastLiteralAmplifier,MethodAdderOnExistingObjectsAmplifier,ReturnValueAmplifier",
"--iteration", "1",
"--random-seed", "72",
"--test", "example.TestSuiteExample",
@@ -306,9 +294,9 @@ public void testOverrideExistingResults() throws Exception {
// run 2: some amplifiers
Main.main(new String[]{
- "--path-to-properties", "src/test/resources/test-projects/test-projects.properties",
+ "--absolute-path-to-project-root", new File("src/test/resources/test-projects/").getAbsolutePath() + "/",
"--test-criterion", "JacocoCoverageSelector",
- "--amplifiers", "MethodAdd" + AmplificationHelper.PATH_SEPARATOR + "FastLiteralAmplifier",
+ "--amplifiers", "MethodDuplicationAmplifier,FastLiteralAmplifier",
"--iteration", "1",
"--random-seed", "72",
"--test", "example.TestSuiteExample",
@@ -330,9 +318,9 @@ public void testOverrideExistingResults() throws Exception {
// run 3: some amplifiers
// run 2 + 3 = run 1
Main.main(new String[]{
- "--path-to-properties", "src/test/resources/test-projects/test-projects.properties",
+ "--absolute-path-to-project-root", new File("src/test/resources/test-projects/").getAbsolutePath() + "/",
"--test-criterion", "JacocoCoverageSelector",
- "--amplifiers", "MethodAdderOnExistingObjectsAmplifier" + AmplificationHelper.PATH_SEPARATOR + "ReturnValueAmplifier",
+ "--amplifiers", "MethodAdderOnExistingObjectsAmplifier,ReturnValueAmplifier",
"--iteration", "1",
"--random-seed", "72",
"--test", "example.TestSuiteExample",
@@ -350,9 +338,9 @@ public void testOverrideExistingResults() throws Exception {
//run 4: equals to run 1 minus run 2 = run 3
Main.main(new String[]{
- "--path-to-properties", "src/test/resources/test-projects/test-projects.properties",
+ "--absolute-path-to-project-root", new File("src/test/resources/test-projects/").getAbsolutePath() + "/",
"--test-criterion", "JacocoCoverageSelector",
- "--amplifiers", "MethodAdderOnExistingObjectsAmplifier" + AmplificationHelper.PATH_SEPARATOR + "ReturnValueAmplifier",
+ "--amplifiers", "MethodDuplicationAmplifier,ReturnValueAmplifier",
"--iteration", "1",
"--random-seed", "72",
"--test", "example.TestSuiteExample",
diff --git a/dspot/src/test/java/eu/stamp_project/Utils.java b/dspot/src/test/java/eu/stamp_project/Utils.java
deleted file mode 100644
index 9a2392613..000000000
--- a/dspot/src/test/java/eu/stamp_project/Utils.java
+++ /dev/null
@@ -1,148 +0,0 @@
-package eu.stamp_project;
-
-import eu.stamp_project.automaticbuilder.AutomaticBuilder;
-import eu.stamp_project.test_framework.TestFramework;
-import eu.stamp_project.utils.options.InputAmplDistributorEnum;
-import eu.stamp_project.utils.program.InputConfiguration;
-import eu.stamp_project.utils.compilation.DSpotCompiler;
-import org.apache.commons.io.FileUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import spoon.reflect.code.CtLiteral;
-import spoon.reflect.declaration.CtClass;
-import spoon.reflect.declaration.CtMethod;
-import spoon.reflect.declaration.CtType;
-import spoon.reflect.factory.Factory;
-import spoon.reflect.visitor.chain.CtQueryable;
-import spoon.reflect.visitor.filter.TypeFilter;
-
-import java.io.File;
-import java.util.List;
-import java.util.Set;
-
-
-/**
- * User: Simon
- * Date: 25/11/16
- * Time: 11:16
- */
-public class Utils {
-
- public static final Logger LOGGER = LoggerFactory.getLogger(Utils.class);
-
- private static AutomaticBuilder builder;
-
- private static InputConfiguration inputConfiguration;
-
- private static DSpotCompiler compiler;
-
- private static String currentInputConfigurationLoaded = null;
-
- public static DSpotCompiler getCompiler() {
- return compiler;
- }
-
- public static InputConfiguration getInputConfiguration() {
- return inputConfiguration;
- }
-
- public static AutomaticBuilder getBuilder() {
- return builder;
- }
-
- public static void reset() {
- currentInputConfigurationLoaded = null;
- }
-
- public static void init(String pathToConfFile) {
- try {
- FileUtils.forceDelete(new File(inputConfiguration.getOutputDirectory()));
- } catch (Exception ignored) {
-
- }
- try {
- FileUtils.forceDelete(new File("target/dspot/tmp_test_sources/"));
- } catch (Exception ignored) {
-
- }
- if (pathToConfFile.equals(currentInputConfigurationLoaded)) {
- return;
- }
- try {
- inputConfiguration = InputConfiguration.initialize(pathToConfFile);
- Utils.getInputConfiguration().setMinimize(false);
- Utils.getInputConfiguration().setVerbose(true);
- builder = inputConfiguration.getBuilder();
- compiler = DSpotCompiler.createDSpotCompiler(inputConfiguration, inputConfiguration.getDependencies());
- inputConfiguration.setFactory(compiler.getLauncher().getFactory());
- inputConfiguration.setBudgetizer(InputAmplDistributorEnum.RandomInputAmplDistributor);
- currentInputConfigurationLoaded = pathToConfFile;
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- public static CtClass> findClass(String fullQualifiedName) {
- return getInputConfiguration().getFactory().Class().get(fullQualifiedName);
- }
-
- public static CtType> findType(String fullQualifiedName) {
- return getInputConfiguration().getFactory().Type().get(fullQualifiedName);
- }
-
-
- public static CtMethod> findMethod(CtClass> ctClass, String methodName) {
- Set> mths = ctClass.getMethods();
- return mths.stream()
- .filter(mth -> mth.getSimpleName().endsWith(methodName))
- .findFirst()
- .orElse(null);
- }
-
- public static CtMethod findMethod(String className, String methodName) {
- return findClass(className).getMethods().stream()
- .filter(mth -> mth.getSimpleName().endsWith(methodName))
- .findFirst()
- .orElse(null);
- }
-
- public static List> getAllTestMethodsFrom(String className) {
- return getAllTestMethodsFrom(getFactory().Type().get(className));
- }
-
- public static List> getAllTestMethodsFrom(CtType> testClass) {
- return testClass.filterChildren(new TypeFilter>(CtMethod.class) {
- @Override
- public boolean matches(CtMethod> element) {
- return TestFramework.get().isTest(element);
- }
- }).list();
- }
-
- @SuppressWarnings("unchecked")
- public static void replaceGivenLiteralByNewValue(CtQueryable parent, T newValue) {
- ((CtLiteral)parent.filterChildren(new FILTER_LITERAL_OF_GIVEN_TYPE(newValue.getClass()))
- .first())
- .replace(getFactory().createLiteral(newValue));
- }
-
- public static Factory getFactory() {
- return getInputConfiguration().getFactory();
- }
-
- public static final class FILTER_LITERAL_OF_GIVEN_TYPE extends TypeFilter {
-
- private Class> clazz;
-
- public FILTER_LITERAL_OF_GIVEN_TYPE(Class> clazz) {
- super(CtLiteral.class);
- this.clazz = clazz;
- }
-
- @Override
- public boolean matches(CtLiteral element) {
- return clazz.isAssignableFrom(element.getValue().getClass()) ||
- element.getValue().getClass().isAssignableFrom(clazz);
- }
- }
-}
diff --git a/dspot/src/test/java/eu/stamp_project/UtilsModifier.java b/dspot/src/test/java/eu/stamp_project/UtilsModifier.java
new file mode 100644
index 000000000..fcce2f01f
--- /dev/null
+++ b/dspot/src/test/java/eu/stamp_project/UtilsModifier.java
@@ -0,0 +1,38 @@
+package eu.stamp_project;
+
+import spoon.reflect.code.CtLiteral;
+import spoon.reflect.factory.Factory;
+import spoon.reflect.visitor.chain.CtQueryable;
+import spoon.reflect.visitor.filter.TypeFilter;
+
+
+/**
+ * User: Simon
+ * Date: 25/11/16
+ * Time: 11:16
+ */
+public class UtilsModifier {
+
+ @SuppressWarnings("unchecked")
+ public static void replaceGivenLiteralByNewValue(Factory factory, CtQueryable parent, T newValue) {
+ ((CtLiteral)parent.filterChildren(new FILTER_LITERAL_OF_GIVEN_TYPE(newValue.getClass()))
+ .first())
+ .replace(factory.createLiteral(newValue));
+ }
+
+ public static final class FILTER_LITERAL_OF_GIVEN_TYPE extends TypeFilter {
+
+ private Class> clazz;
+
+ public FILTER_LITERAL_OF_GIVEN_TYPE(Class> clazz) {
+ super(CtLiteral.class);
+ this.clazz = clazz;
+ }
+
+ @Override
+ public boolean matches(CtLiteral element) {
+ return clazz.isAssignableFrom(element.getValue().getClass()) ||
+ element.getValue().getClass().isAssignableFrom(clazz);
+ }
+ }
+}
diff --git a/dspot/src/test/java/eu/stamp_project/automaticbuilder/AutomaticBuilderFactoryTest.java b/dspot/src/test/java/eu/stamp_project/automaticbuilder/AutomaticBuilderFactoryTest.java
deleted file mode 100644
index 0e73ab14a..000000000
--- a/dspot/src/test/java/eu/stamp_project/automaticbuilder/AutomaticBuilderFactoryTest.java
+++ /dev/null
@@ -1,88 +0,0 @@
-package eu.stamp_project.automaticbuilder;
-
-import eu.stamp_project.automaticbuilder.gradle.GradleAutomaticBuilder;
-import eu.stamp_project.automaticbuilder.maven.MavenAutomaticBuilder;
-import eu.stamp_project.utils.program.InputConfiguration;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-/**
- * Created by Daniele Gagliardi
- * daniele.gagliardi@eng.it
- * on 14/07/17.
- */
-public class AutomaticBuilderFactoryTest {
-
- private static final String PATH_SEPARATOR = System.getProperty("path.separator");
-
- @Before
- public void setUp() throws Exception {
-
- }
-
- @After
- public void tearDown() throws Exception {
- }
-
- @Test
- public void getAutomaticBuilder_whenMaven() throws Exception {
-
- InputConfiguration inputConfiguration = InputConfiguration.initialize("src/test/resources/test-projects/test-projects.properties");
- inputConfiguration.setBuilderName("MAVEN");
-
- assertTrue(inputConfiguration.getBuilderName().toUpperCase().contains("MAVEN"));
-
- AutomaticBuilder builder = AutomaticBuilderFactory.getAutomaticBuilder(inputConfiguration.getBuilderName());
-
- assertNotNull(builder);
- assertTrue(builder.getClass().equals(MavenAutomaticBuilder.class));
- }
-
- @Test
- public void getAutomaticBuilder_whenGradle() throws Exception {
-
- InputConfiguration inputConfiguration = InputConfiguration.initialize("src/test/resources/test-projects/test-projects.properties");
- inputConfiguration.setBuilderName("GRADLE");
-
- assertTrue(inputConfiguration.getBuilderName().toUpperCase().contains("GRADLE"));
-
- AutomaticBuilder builder = AutomaticBuilderFactory.getAutomaticBuilder(inputConfiguration.getBuilderName());
-
- assertNotNull(builder);
- assertTrue(builder.getClass().equals(GradleAutomaticBuilder.class));
- }
-
- @Test
- public void getAutomaticBuilder_whenUnknown() throws Exception {
-
- InputConfiguration inputConfiguration = InputConfiguration.initialize("src/test/resources/test-projects/test-projects.properties");
- inputConfiguration.setBuilderName("UNKNOWNBuilder");
-
- assertFalse(inputConfiguration.getBuilderName() == null);
- assertFalse(inputConfiguration.getBuilderName().toUpperCase().contains("MAVEN"));
- assertFalse(inputConfiguration.getBuilderName().toUpperCase().contains("GRADLE"));
-
- AutomaticBuilder builder = AutomaticBuilderFactory.getAutomaticBuilder(inputConfiguration.getBuilderName());
-
- assertNotNull(builder);
- assertTrue(builder.getClass().equals(MavenAutomaticBuilder.class));
- }
-
- @Test
- public void getAutomaticBuilder_whenConfDoesntContainBuilder() throws Exception {
-
- InputConfiguration inputConfiguration = InputConfiguration.initialize("src/test/resources/test-projects/test-projects.properties");
-
- assertTrue(inputConfiguration.getBuilderName().isEmpty());
-
- AutomaticBuilder builder = AutomaticBuilderFactory.getAutomaticBuilder(inputConfiguration.getBuilderName());
-
- assertNotNull(builder);
- assertTrue(builder.getClass().equals(MavenAutomaticBuilder.class));
- }
-}
\ No newline at end of file
diff --git a/dspot/src/test/java/eu/stamp_project/automaticbuilder/gradle/GradleAutomaticBuilderTest.java b/dspot/src/test/java/eu/stamp_project/automaticbuilder/gradle/GradleAutomaticBuilderTest.java
index 1832fe53f..90a452a36 100644
--- a/dspot/src/test/java/eu/stamp_project/automaticbuilder/gradle/GradleAutomaticBuilderTest.java
+++ b/dspot/src/test/java/eu/stamp_project/automaticbuilder/gradle/GradleAutomaticBuilderTest.java
@@ -1,17 +1,18 @@
package eu.stamp_project.automaticbuilder.gradle;
-import eu.stamp_project.Utils;
+import eu.stamp_project.Main;
import eu.stamp_project.automaticbuilder.AutomaticBuilder;
-import eu.stamp_project.automaticbuilder.AutomaticBuilderFactory;
+import eu.stamp_project.utils.options.AutomaticBuilderEnum;
import eu.stamp_project.utils.pit.AbstractPitResult;
import eu.stamp_project.utils.pit.PitXMLResultParser;
import eu.stamp_project.utils.program.InputConfiguration;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
-import org.junit.BeforeClass;
import org.junit.Test;
-import spoon.reflect.declaration.CtClass;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import spoon.Launcher;
import java.io.BufferedReader;
import java.io.File;
@@ -31,49 +32,55 @@
*/
public class GradleAutomaticBuilderTest {
+ private static final Logger LOGGER = LoggerFactory.getLogger(GradleAutomaticBuilderTest.class);
+
private AutomaticBuilder sut = null;
- PitXMLResultParser parser;
- @BeforeClass
- public static void setUpClass() throws Exception {
- Utils.reset();
- }
+ private PitXMLResultParser parser;
+
+ private final String pathToProjectRoot = "src/test/resources/test-projects/";
- private final String pathToConfFile = "src/test/resources/test-projects/test-projects.properties";
+ private Launcher launcher;
@Before
public void setUp() throws Exception {
+ Main.verbose = true;
cleanTestEnv();
- Utils.init(pathToConfFile);
- Utils.LOGGER.debug("Test Set-up - Reading input parameters...");
- InputConfiguration inputConfiguration = Utils.getInputConfiguration();
- inputConfiguration.setBuilderName("GradleBuilder");
- Utils.LOGGER.debug("Test Set-up - instantiating Automatic Builder (SUT)...");
- sut = AutomaticBuilderFactory.getAutomaticBuilder(inputConfiguration.getBuilderName());
+ LOGGER.debug("Test Set-up - Reading input parameters...");
+ LOGGER.debug("Test Set-up - instantiating Automatic Builder (SUT)...");
+ final InputConfiguration configuration = new InputConfiguration();
+ configuration.setAbsolutePathToProjectRoot(this.pathToProjectRoot);
+ configuration.setGregorMode(true);
+ configuration.setFilter("example.*");
+ launcher = new Launcher();
+ launcher.addInputResource(pathToProjectRoot + "src/");
+ launcher.getEnvironment().setNoClasspath(true);
+ launcher.buildModel();
+ sut = AutomaticBuilderEnum.Gradle.getAutomaticBuilder(configuration);
sut.compile();
- Utils.LOGGER.debug("Test Set-up complete.");
+ LOGGER.debug("Test Set-up complete.");
parser = new PitXMLResultParser();
}
@After
public void tearDown() throws Exception {
- Utils.LOGGER.debug("Test Tear-down...");
+ LOGGER.debug("Test Tear-down...");
cleanTestEnv();
- Utils.LOGGER.debug("Test Tear-down complete.");
+ LOGGER.debug("Test Tear-down complete.");
}
@Test
public void compile_whenCleanCompileTestTasksAreAppliedToDSpotTestExampleProject() throws Exception {
- Utils.LOGGER.info("Starting Gradle Automatic Builder compile() test...");
+ LOGGER.info("Starting Gradle Automatic Builder compile() test...");
sut.compile();
File buildDir = new File("src/test/resources/test-projects/build");
assertTrue("After compilation, build dir should exist", buildDir.exists());
- Utils.LOGGER.info("Gradle Automatic Builder compile() test complete.");
+ LOGGER.info("Gradle Automatic Builder compile() test complete.");
}
@Test
public void buildClasspath_whenAppliedToDSpotTestExampleProject() throws Exception {
- Utils.LOGGER.info("Starting Gradle Automatic Builder buildClasspath() test...");
+ LOGGER.info("Starting Gradle Automatic Builder buildClasspath() test...");
String[] expectedCompilationLibraries = {"log4j-api-2.8.2.jar", "log4j-core-2.8.2.jar"};
String[] expectedTestCompilationLibraries = {"hamcrest-core-1.3.jar", "junit-4.12.jar"};
String classPath = sut.buildClasspath();
@@ -85,63 +92,59 @@ public void buildClasspath_whenAppliedToDSpotTestExampleProject() throws Excepti
try (final BufferedReader reader = new BufferedReader(new FileReader(new File("src/test/resources/test-projects/" + GradleInjector.GRADLE_BUILD_FILE)))) {
assertFalse( reader.lines().collect(Collectors.joining("\n")).contains(GradleInjector.WRITE_CLASSPATH_TASK));
}
- Utils.LOGGER.info("Gradle Automatic Builder buildClasspath() test complete.");
+ LOGGER.info("Gradle Automatic Builder buildClasspath() test complete.");
}
@Test
public void runPit_whenNoTestClassIsSpecified() throws Exception {
- Utils.LOGGER.info("Starting Gradle Automatic Builder runPit() test when no test class is specified...");
- InputConfiguration.get().setDescartesMode(false);
+ LOGGER.info("Starting Gradle Automatic Builder runPit() test when no test class is specified...");
+ //InputConfiguration.get().setDescartesMode(false);
sut.runPit();
List extends AbstractPitResult> pitResults = parser.parseAndDelete("src/test/resources/test-projects/" + sut.getOutputDirectoryPit());
assertTrue("PIT results shouldn't be null", pitResults != null);
assertTrue("PIT results shouldn't be empty", !pitResults.isEmpty());
- Utils.LOGGER.info("Gradle Automatic Builder runPit() test complete when no test class is specified.");
+ LOGGER.info("Gradle Automatic Builder runPit() test complete when no test class is specified.");
}
@Test
public void runPit_whenTestClassIsSpecified() throws Exception {
- Utils.LOGGER.info("Starting Gradle Automatic Builder runPit() test when a test class is specified...");
-
- InputConfiguration.get().setDescartesMode(false);
-
- CtClass