diff --git a/.gitignore b/.gitignore index c6abdd4..398b255 100644 --- a/.gitignore +++ b/.gitignore @@ -2,4 +2,5 @@ *.iml site/ **/target -pom.xml.versionsBackup \ No newline at end of file +pom.xml.versionsBackup +dependency-reduced-pom.xml \ No newline at end of file diff --git a/buggy-core/pom.xml b/buggy-core/pom.xml index 6d94494..4ca604e 100644 --- a/buggy-core/pom.xml +++ b/buggy-core/pom.xml @@ -1,6 +1,6 @@ - 4.0.0 @@ -21,6 +21,16 @@ + + org.springframework + spring-core + 5.2.9.RELEASE + + + org.yaml + snakeyaml + 1.27 + org.testng testng @@ -29,38 +39,14 @@ com.beust jcommander - - org.atteo.classindex - classindex - org.apache.commons commons-lang3 - org.apache.logging.log4j - log4j-slf4j-impl - - - org.apache.logging.log4j - log4j-1.2-api - - - org.apache.logging.log4j - log4j-jul - - - org.apache.logging.log4j - log4j-core - - - org.apache.logging.log4j - log4j-api - - - org.slf4j - slf4j-api + ch.qos.logback + logback-classic @@ -71,6 +57,18 @@ com.google.guava guava + + org.springframework + spring-beans + 5.2.9.RELEASE + compile + + + org.springframework + spring-context + 5.2.9.RELEASE + compile + diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/test/BaseBuggyTest.java b/buggy-core/src/main/java/org/touchbit/buggy/core/BaseBuggyTest.java similarity index 52% rename from buggy-core/src/main/java/org/touchbit/buggy/core/test/BaseBuggyTest.java rename to buggy-core/src/main/java/org/touchbit/buggy/core/BaseBuggyTest.java index 0e5cab9..2f02f0e 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/test/BaseBuggyTest.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/BaseBuggyTest.java @@ -14,14 +14,14 @@ * limitations under the License. */ -package org.touchbit.buggy.core.test; +package org.touchbit.buggy.core; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; -import org.touchbit.buggy.core.Buggy; -import org.touchbit.buggy.core.testng.listeners.BuggyExecutionListener; -import org.touchbit.buggy.core.testng.listeners.IntellijIdeaTestNgPluginListener; -import org.touchbit.buggy.core.utils.log.BuggyLog; +import org.testng.annotations.Listeners; +import org.touchbit.buggy.core.logback.SiftingTestLogger; +import org.touchbit.buggy.core.testng.BuggyExecutionListener; +import org.touchbit.buggy.core.testng.IntellijIdeaTestNgPluginListener; /** * Base class for tests. @@ -29,39 +29,28 @@ * Created by Oleg Shaburov on 17.05.2018 * shaburov.o.a@gmail.com */ -public abstract class BaseBuggyTest implements TestRailTest { +@Listeners(IntellijIdeaTestNgPluginListener.class) +public abstract class BaseBuggyTest { - protected static Logger log = BuggyLog.test(); + protected static SiftingTestLogger log = new SiftingTestLogger(); - protected BaseBuggyTest() { - this(null); - } + protected BaseBuggyTest() { } - protected BaseBuggyTest(final Logger logger) { - if (!IntellijIdeaTestNgPluginListener.isIntellijIdeaTestRun() && !Buggy.isTestRun()) { - Buggy.getExitHandler().exitRun(1, "Missing IntellijIdeaPluginListener in the Intellij IDEA" + - " TestNG plugin configuration."); - } + protected BaseBuggyTest(final L logger) { setLog(logger); - setRunId(); } /** * Method for the separation of steps in the test log. */ protected static void step(@NotNull final String msg, @NotNull final Object... args) { - BuggyExecutionListener.step(log, msg, args); + log.step(msg, args); } - protected static void setLog(final Logger logger) { + protected static void setLog(final L logger) { if (logger != null) { log = logger; } } - @Override - public long getRunId() { - return 0; - } - } diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/Buggy.java b/buggy-core/src/main/java/org/touchbit/buggy/core/Buggy.java deleted file mode 100644 index a23bbdc..0000000 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/Buggy.java +++ /dev/null @@ -1,474 +0,0 @@ -/* - * Copyright © 2018 Shaburov Oleg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.touchbit.buggy.core; - -import com.beust.jcommander.JCommander; -import org.apache.logging.log4j.Level; -import org.apache.logging.log4j.status.StatusLogger; -import org.testng.TestNG; -import org.testng.xml.XmlSuite; -import org.touchbit.buggy.core.config.PrimaryConfig; -import org.touchbit.buggy.core.config.SecondaryConfig; -import org.touchbit.buggy.core.model.Suite; -import org.touchbit.buggy.core.testng.TestSuite; -import org.touchbit.buggy.core.testng.listeners.BuggyListener; -import org.touchbit.buggy.core.testng.listeners.IntellijIdeaTestNgPluginListener; -import org.touchbit.buggy.core.utils.BuggyUtils; -import org.touchbit.buggy.core.utils.StringUtils; -import org.touchbit.buggy.core.utils.log.BuggyLog; - -import java.io.File; -import java.util.*; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.stream.Collectors; - -import static org.testng.xml.XmlSuite.FailurePolicy.CONTINUE; -import static org.touchbit.buggy.core.utils.BuggyUtils.CONSOLE_DELIMITER; - -/** - * Created by Oleg Shaburov on 08.09.2018 - * shaburov.o.a@gmail.com - */ -public abstract class Buggy { - - static { - StatusLogger.getLogger().setLevel(Level.OFF); - } - - private static final String UNABLE_CREATE_CLASS = "Unable to create a new instance of "; - private static AtomicInteger buggyErrors = new AtomicInteger(); - private static AtomicInteger buggyWarns = new AtomicInteger(); - private static JCommander jCommander; - private static Class buggyLogClass; - private static String programName = "Buggy"; - private static PrimaryConfig primaryConfig; - private static Class primaryConfigClass; - private static List> secondaryConfigClasses = new ArrayList<>(); - private static List secondaryConfigs = new ArrayList<>(); - private static BuggyProcessor processor = new DefaultBuggyProcessor(); - private static boolean primaryConfigInitialized = false; - private static boolean testRun = false; - private static TestNG testNG = new TestNG(); - - public static void main(String[] args) { - delegate(new TestNG(), args); - } - - @SuppressWarnings("WeakerAccess") - public static void delegate(TestNG delegate, String... args) { - reset(); - testNG = delegate; - prepare(args); - checkPrimaryConfig(); - run(); - } - - public static void run() { - testRun = true; - int status = processor.runTestNG(testNG); - if (status == 60) { - processor.getExitHandler().exitRun(60, "TestNG safely died."); - } else { - processor.getExitHandler().exitRun(status); - } - testRun = false; - } - - public static void checkPrimaryConfig() { - if (primaryConfig.isCheck()) { - processor.getExitHandler().exitRun(0, "Buggy configuration is correct."); - } - } - - public static boolean isTestRun() { - return testRun; - } - - public static void reset() { - programName = "Buggy"; - testNG = new TestNG(); - jCommander = null; - primaryConfigInitialized = false; - testRun = false; - buggyErrors.set(0); - buggyWarns.set(0); - } - - public static void prepare(String... args) { - StringUtils.println(CONSOLE_DELIMITER); - primaryConfig = processor.getPrimaryConfig(primaryConfigClass); - primaryConfigClass = primaryConfig.getClass(); - secondaryConfigs = processor.getSecondaryConfigList(secondaryConfigClasses); - jCommander = processor.prepareJCommander(primaryConfig, secondaryConfigs, programName); - try { - jCommander.parse(args); - } catch (Exception e) { - getExitHandler().exitRunWithUsage(1, e.getClass().getSimpleName() + ": " + e.getMessage()); - } - primaryConfigInitialized = processor.preparePrimaryConfig(primaryConfig); - processor.prepareBuggyLog(buggyLogClass); - StringUtils.println(CONSOLE_DELIMITER); - processor.printConfig(primaryConfig); - StringUtils.println(CONSOLE_DELIMITER); - processor.prepareTestNG(testNG); - StringUtils.println(CONSOLE_DELIMITER); - } - - public static class DefaultBuggyProcessor implements BuggyProcessor { - - @Override - public PrimaryConfig getPrimaryConfig(Class primaryConfigClass) { - PrimaryConfig primaryConfig = null; - if (primaryConfigClass == null) { - primaryConfigClass = getPrimaryConfigClass(BuggyUtils.findInstantiatedSubclasses(PrimaryConfig.class)); - Buggy.setPrimaryConfigClass(primaryConfigClass); - } - try { - primaryConfig = primaryConfigClass.newInstance(); - } catch (Exception e) { - this.getExitHandler().exitRun(1, UNABLE_CREATE_CLASS + primaryConfigClass, e); - } - return primaryConfig; - } - - public Class getPrimaryConfigClass(List> classes) { - if (classes == null || !classes.iterator().hasNext()) { - getExitHandler().exitRun(1, "Primary config implementation not found."); - } else { - if (classes.size() > 1) { - StringJoiner sj = new StringJoiner("\n"); - classes.forEach(c -> sj.add(c.toString())); - getExitHandler().exitRun(1, "Found more than 1 inherited class from PrimaryConfig.class:\n" + sj); - } - return classes.get(0); - } - return null; - } - - @Override - public List getSecondaryConfigList(List> classList) { - List secondaryConfigs = new ArrayList<>(); - if (classList == null || classList.isEmpty()) { - classList = BuggyUtils.findInstantiatedSubclasses(SecondaryConfig.class); - } - classList.forEach(c -> { - try { - secondaryConfigs.add(c.newInstance()); - } catch (Exception e) { - processor.getExitHandler().exitRun(1, UNABLE_CREATE_CLASS + c, e); - } - }); - return secondaryConfigs; - } - - @Override - public JCommander prepareJCommander(PrimaryConfig primary, - List secondary, - String name) { - if (primary == null || secondary == null) { - this.getExitHandler().exitRun(1, - "An invalid 'null' value was received for one of the parameters:" + - "\nPrimaryConfig = " + primary + - "\nSecondaryConfigs list = " + secondary); - } else { - JCommander jCommander = new JCommander(primary); - jCommander.setProgramName(name); - secondary.forEach(jCommander::addCommand); - return jCommander; - } - return null; - } - - @Override - public boolean preparePrimaryConfig(PrimaryConfig primaryConfig) { - primaryConfig.setRunDir(this.getRunDirectory(primaryConfig.getClass())); - File absoluteLogDir; - if (primaryConfig.getLogPath().startsWith("/")) { - absoluteLogDir = new File(primaryConfig.getLogPath()); - } else { - absoluteLogDir = new File(primaryConfig.getRunDir(), primaryConfig.getLogPath()); - } - //noinspection ResultOfMethodCallIgnored - absoluteLogDir.mkdirs(); - if (!absoluteLogDir.exists() || !absoluteLogDir.canWrite()) { - Buggy.getExitHandler().exitRun(1, "No write permission for the specified log directory: '" + - absoluteLogDir.getAbsolutePath() + "'"); - return false; - } - primaryConfig.setAbsoluteLogPath(absoluteLogDir.getAbsolutePath()); - return true; - } - - @Override - public void prepareBuggyLog(Class buggyLogClass) { - if (buggyLogClass == null) { - buggyLogClass = getBuggyLogSubClass(BuggyUtils.findInstantiatedSubclasses(BuggyLog.class)); - } - try { - buggyLogClass.newInstance(); - } catch (Exception e) { - this.getExitHandler().exitRun(1, UNABLE_CREATE_CLASS + buggyLogClass.getTypeName(), e); - } - } - - public Class getBuggyLogSubClass(List> list) { - if (list == null) { - return BuggyLog.class; - } - if (list.size() > 1) { - StringJoiner sj = new StringJoiner("\n"); - list.forEach(c -> sj.add(c.toString())); - this.getExitHandler().exitRun(1, "Found more than 1 inherited class from BaseLog.class:\n" + sj); - } - return list.size() == 1 ? list.get(0) : BuggyLog.class; - } - - @Override - public List getTestSuites() { - List subTestSuites = getSubTestSuites(BuggyUtils.findInstantiatedSubclasses(TestSuite.class)); - List> annotatedTestClasses = findAnnotatedSuiteTestClasses(); - return mergeTestSuites(annotatedTestClasses, subTestSuites); - } - - public List getSubTestSuites(List> subclasses) { - List testSuites = new ArrayList<>(); - if (subclasses != null) { - for (Class testSuiteClass : subclasses) { - try { - if (!testSuiteClass.isAnnotationPresent(Suite.class)) { - processor.getExitHandler().exitRun(1, "The " + testSuiteClass + " " + - "does not contain the annotation @Suite"); - } - testSuites.add(testSuiteClass.newInstance()); - } catch (Exception e) { - processor.getExitHandler().exitRun(1, UNABLE_CREATE_CLASS + testSuiteClass, e); - } - } - } - return testSuites; - } - - public List> findAnnotatedSuiteTestClasses() { - return BuggyUtils.findAnnotatedInstantiatedClasses(Suite.class).stream() - .filter(s -> !BuggyUtils.isAssignableFrom(s, TestSuite.class)) - .collect(Collectors.toList()); - } - - public List mergeTestSuites(final List> annotated, - final List subTestSuites) { - List testClassSuites = new ArrayList<>(); - for (Class testClass : annotated) { - Suite testClassSuite = testClass.getAnnotation(Suite.class); - if (BuggyUtils.isListBaseSuiteContainsClass(subTestSuites, testClass) || - BuggyUtils.isListBaseSuiteContainsClass(testClassSuites, testClass)) { - continue; - } - TestSuite testSuite = null; - for (TestSuite s : testClassSuites) { - if (BuggyUtils.equalsSuites(s.getSuite(), testClassSuite)) { - testSuite = s; - } - } - if (testSuite == null) { - TestSuite s = new TestSuite(testClassSuite); - s.addTestPackage("default", testClass); - testClassSuites.add(s); - } else { - testSuite.addTestPackage("default", testClass); - } - } - subTestSuites.addAll(testClassSuites); - return subTestSuites; - } - - @Override - public List getXmlSuitesForConfiguration(PrimaryConfig config, List testSuites) { - List xmlSuites = new ArrayList<>(); - testSuites.forEach(suite -> config.getServices().forEach(service -> { - if (suite.getService().getName().equals(service.getName())) { - config.getInterfaces().forEach(i -> { - if (suite.getInterface().getName().equals(i.getName())) { - xmlSuites.add(suite); - } - }); - } - })); - if (xmlSuites.isEmpty()) { - getExitHandler().exitRun(1, "There are no test suites for the current configuration."); - } - return xmlSuites; - } - - @Override - public void prepareTestNG(TestNG testNG) { - List testSuites = getTestSuites(); - List xmlSuites = getXmlSuitesForConfiguration(primaryConfig, testSuites); - testNG.setXmlSuites(xmlSuites); - testNG.setSuiteThreadPoolSize(xmlSuites.size()); - testNG.setUseDefaultListeners(true); - testNG.setConfigFailurePolicy(CONTINUE); - testNG.setOutputDirectory(getReportsOutputDirectory()); - List listeners = getBuggyListeners(BuggyUtils - .findInstantiatedSubclasses(BuggyListener.class)); - listeners.forEach(testNG::addListener); - } - - public List getBuggyListeners(List> subclasses) { - List listeners = new ArrayList<>(); - if (IntellijIdeaTestNgPluginListener.isIntellijIdeaTestRun()) { - StringUtils.println(StringUtils - .dotFiller(IntellijIdeaTestNgPluginListener.class.getSimpleName(), 47, "ENABLED")); - } else { - StringUtils.println(StringUtils - .dotFiller(IntellijIdeaTestNgPluginListener.class.getSimpleName(), 47, "DISABLED")); - subclasses.remove(IntellijIdeaTestNgPluginListener.class); - subclasses.forEach(l -> { - try { - BuggyListener listener = l.newInstance(); - if (listener.isEnable()) { - listeners.add(listener); - StringUtils.println(StringUtils.dotFiller(l.getSimpleName(), 47, "ENABLED")); - } else { - StringUtils.println(StringUtils.dotFiller(l.getSimpleName(), 47, "DISABLED")); - } - } catch (Exception e) { - this.getExitHandler().exitRun(1, UNABLE_CREATE_CLASS + l, e); - } - }); - } - return listeners; - } - - @Override - @SuppressWarnings("squid:S1148") - public int runTestNG(TestNG testNG) { - try { - testNG.run(); - if (primaryConfig.getStatus() != null) { - return primaryConfig.getStatus(); - } - return testNG.getStatus(); - } catch (Throwable t) { - t.printStackTrace(); - return 60; - } - } - - @Override - public String getRunDirectory(Class clazz) { - return new File(clazz.getProtectionDomain().getCodeSource().getLocation().getPath()) - .getParentFile().getAbsolutePath(); - } - - @Override - public String getReportsOutputDirectory() { - return new File(this.getRunDirectory(primaryConfig.getClass()), "reports").getAbsolutePath() ; - } - - @Override - public ExitHandler getExitHandler() { - return new DefaultBuggySystemExitHandler(); - } - - @Override - public void printConfig(PrimaryConfig primaryConfig) { - StringUtils.println(PrimaryConfig.configurationToString(primaryConfig)); - } - - public static class DefaultBuggySystemExitHandler implements ExitHandler { - - @Override - public void exitRunWithUsage(int status, String msg) { - if(jCommander != null) { - jCommander.usage(); - StringUtils.println(CONSOLE_DELIMITER); - exitRun(status, msg); - } else { - StringUtils.println(CONSOLE_DELIMITER); - exitRun(1, "JCommander not initialized."); - } - } - - @Override - public void exit(int status) { - java.lang.System.exit(status); - } - - } - - } - - public static void setBuggyProcessor(BuggyProcessor processor) { - Buggy.processor = processor; - } - - public static ExitHandler getExitHandler() { - return processor.getExitHandler(); - } - - public static boolean isPrimaryConfigInitialized() { - return primaryConfigInitialized; - } - - public static PrimaryConfig getPrimaryConfig() { - return primaryConfig; - } - - public static void setPrimaryConfigClass(Class c) { - primaryConfigClass = c; - } - - public static void setSecondaryConfigClasses(List> secondary) { - secondaryConfigClasses = secondary; - } - - public static void setProgramName(String name) { - programName = name; - } - - public static String getProgramName() { - return programName; - } - - public static void incrementBuggyWarns() { - buggyWarns.incrementAndGet(); - } - - public static void incrementBuggyErrors() { - buggyErrors.incrementAndGet(); - } - - public static int getBuggyWarns() { - return buggyWarns.get(); - } - - public static int getBuggyErrors() { - return buggyErrors.get(); - } - - public static void setBuggyLogClass(Class logClass) { - buggyLogClass = logClass; - } - - public static JCommander getJCommander() { - return jCommander; - } - - public static List getSecondaryConfigs() { - return secondaryConfigs; - } -} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/BuggyProcessor.java b/buggy-core/src/main/java/org/touchbit/buggy/core/BuggyProcessor.java deleted file mode 100644 index edfaeea..0000000 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/BuggyProcessor.java +++ /dev/null @@ -1,45 +0,0 @@ -package org.touchbit.buggy.core; - -import com.beust.jcommander.JCommander; -import org.testng.TestNG; -import org.testng.xml.XmlSuite; -import org.touchbit.buggy.core.config.PrimaryConfig; -import org.touchbit.buggy.core.config.SecondaryConfig; -import org.touchbit.buggy.core.testng.TestSuite; -import org.touchbit.buggy.core.utils.log.BuggyLog; - -import java.util.List; - -/** - * Created by Oleg Shaburov on 20.10.2018 - * shaburov.o.a@gmail.com - */ -public interface BuggyProcessor { - - PrimaryConfig getPrimaryConfig(Class primaryConfigClass); - - List getSecondaryConfigList(List> secondaryConfigClasses); - - JCommander prepareJCommander(PrimaryConfig primary, List secondary, String name); - - boolean preparePrimaryConfig(PrimaryConfig primaryConfig); - - void prepareBuggyLog(Class buggyLogClass); - - List getTestSuites(); - - List getXmlSuitesForConfiguration(PrimaryConfig config, List testSuites); - - void prepareTestNG(TestNG testNG); - - int runTestNG(TestNG testNG); - - String getRunDirectory(Class clazz); - - String getReportsOutputDirectory(); - - ExitHandler getExitHandler(); - - void printConfig(PrimaryConfig primaryConfig); - -} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/ExitHandler.java b/buggy-core/src/main/java/org/touchbit/buggy/core/ExitHandler.java deleted file mode 100644 index b24aa17..0000000 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/ExitHandler.java +++ /dev/null @@ -1,43 +0,0 @@ -package org.touchbit.buggy.core; - -import org.touchbit.buggy.core.utils.StringUtils; - -import static org.touchbit.buggy.core.utils.BuggyUtils.CONSOLE_DELIMITER; - -/** - * Created by Oleg Shaburov on 16.10.2018 - * shaburov.o.a@gmail.com - */ -public interface ExitHandler { - - default void exitRunWithUsage(int status) { - exitRunWithUsage(status, null); - } - - void exitRunWithUsage(int status, String msg); - - default void exitRun(int status) { - exitRun(status, null, null); - } - - default void exitRun(int status, String msg) { - exitRun(status, msg, null); - } - - default void exitRun(int status, String msg, Throwable t) { - if (msg !=null) { - if (t != null) { - StringUtils.println(msg, t); - } else { - StringUtils.println(msg); - } - StringUtils.println(CONSOLE_DELIMITER); - } - StringUtils.println(StringUtils.dotFiller("Exit code", 47, status)); - StringUtils.println(CONSOLE_DELIMITER); - exit(status); - } - - void exit(int status); - -} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/config/BParameters.java b/buggy-core/src/main/java/org/touchbit/buggy/core/config/BParameters.java deleted file mode 100644 index 7ae0ae4..0000000 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/config/BParameters.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright © 2018 Shaburov Oleg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.touchbit.buggy.core.config; - -/** - * Created by Oleg Shaburov on 18.09.2018 - * shaburov.o.a@gmail.com - */ -@SuppressWarnings("WeakerAccess") -public class BParameters { - - public static final String V = "-v"; - public static final String VERSION = "--version"; - public static final String QUESTION_MARK = "-?"; - public static final String HELP = "--help"; - public static final String S = "-s"; - public static final String SERVICES = "--services"; - public static final String I = "-i"; - public static final String INTERFACE = "--interface"; - public static final String T = "-t"; - public static final String TYPE = "--type"; - public static final String LOG = "--log"; - public static final String THREADS = "--threads"; - public static final String F = "-f"; - public static final String FORCE = "--force"; - public static final String ARTIFACTS_URL = "--artifacts-url"; - public static final String STATUS = "--status"; - public static final String ALL = "--all"; - public static final String PRINT_SUITE = "--print-suite"; - public static final String PRINT_CAUSE = "--print-cause"; - public static final String PRINT_LOG = "--print-log"; - public static final String SELF_CHECK = "--check"; - - - private BParameters() { - throw new IllegalStateException("Utility class. Prohibit instantiation."); - } - -} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/config/BuggyConfigurationYML.java b/buggy-core/src/main/java/org/touchbit/buggy/core/config/BuggyConfigurationYML.java new file mode 100644 index 0000000..4b579b8 --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/config/BuggyConfigurationYML.java @@ -0,0 +1,254 @@ +package org.touchbit.buggy.core.config; + +import org.touchbit.buggy.core.exceptions.BuggyConfigurationException; +import org.touchbit.buggy.core.goal.component.AllComponents; +import org.touchbit.buggy.core.goal.component.Component; +import org.touchbit.buggy.core.goal.interfaze.AllInterfaces; +import org.touchbit.buggy.core.goal.interfaze.Interface; +import org.touchbit.buggy.core.goal.service.AllServices; +import org.touchbit.buggy.core.goal.service.Service; +import org.touchbit.buggy.core.model.ParallelMode; +import org.touchbit.buggy.core.model.Type; +import org.touchbit.buggy.core.utils.JUtils; + +import java.util.*; + +import static org.touchbit.buggy.core.model.ParallelMode.METHODS; + +/** + * Configuration class for customizing Buggy. + *

+ * Created by Oleg Shaburov on 01.10.2020 + * shaburov.o.a@gmail.com + */ +@SuppressWarnings("unused") +public final class BuggyConfigurationYML implements ConfigurationYML { + + private static String programName = "Buggy"; + private static Boolean help = false; + private static Boolean forceRun = false; + private static Integer threads = 50; + private static ParallelMode parallelMode = METHODS; + private static String artifactsUrl; + private static List components = new ArrayList() {{ add(new AllComponents()); }}; + private static List services = new ArrayList() {{ add(new AllServices()); }}; + private static List interfaces = new ArrayList() {{ add(new AllInterfaces()); }}; + private static Type[] types = new Type[] { Type.REGRESSION }; + private static String issuesUrl = ""; + private static Boolean testCaseTitle = true; + private static Boolean testSuiteInfo = false; + private static Boolean testLogFilePath = true; + private static Boolean testIssuesInfo = false; + private static Boolean testBugsInfo = true; + private static Boolean testErrorInfo = true; + private static OutputRule outputRule = OutputRule.UNSUCCESSFUL; + + public static Boolean isHelp() { + return BuggyConfigurationYML.help; + } + + public static void setHelp(Boolean help) { + BuggyConfigurationYML.help = help; + } + + public static Boolean isForceRun() { + return forceRun; + } + + public static void setForceRun(Boolean forceRun) { + BuggyConfigurationYML.forceRun = forceRun; + } + + public static Integer getThreads() { + return threads; + } + + public static void setThreads(Integer threads) { + BuggyConfigurationYML.threads = threads; + } + + public static String getArtifactsUrl() { + return artifactsUrl; + } + + public static void setArtifactsUrl(String artifactsUrl) { + BuggyConfigurationYML.artifactsUrl = artifactsUrl; + } + + public static Type[] getTypes() { + return types; + } + + public static void setTypes(Type... types) { + if (types != null) { + BuggyConfigurationYML.types = types; + } + } + + public static List getServices() { + return services; + } + + public static void setServices(List services) { + if (services != null) { + BuggyConfigurationYML.services = services; + } + } + + @SafeVarargs + public static void setServices(S... services) { + if (services != null) { + setServices(Arrays.asList(services)); + } + } + + @SafeVarargs + public static void setServices(Class... services) { + BuggyConfigurationYML.services = new ArrayList<>(); + for (Class service : services) { + Service instance = JUtils.newInstance(service, BuggyConfigurationException::new); + BuggyConfigurationYML.services.add(instance); + } + } + + public static List getInterfaces() { + return interfaces; + } + + public static void setInterfaces(List interfaces) { + if (interfaces != null) { + BuggyConfigurationYML.interfaces = interfaces; + } + } + + @SafeVarargs + public static void setInterfaces(I... interfaces) { + if (interfaces != null) { + setInterfaces(Arrays.asList(interfaces)); + } + } + + @SafeVarargs + public static void setInterfaces(Class... interfaces) { + BuggyConfigurationYML.interfaces = new ArrayList<>(); + for (Class anInterface : interfaces) { + Interface instance = JUtils.newInstance(anInterface, BuggyConfigurationException::new); + BuggyConfigurationYML.interfaces.add(instance); + } + } + + public static List getComponents() { + return components; + } + + public static void setComponents(List components) { + if (components != null) { + BuggyConfigurationYML.components = components; + } + } + + @SafeVarargs + public static void setComponents(C... components) { + if (components != null) { + setComponents(Arrays.asList(components)); + } + } + + @SafeVarargs + public static void setComponents(Class... components) { + BuggyConfigurationYML.components = new ArrayList<>(); + for (Class component : components) { + Component instance = JUtils.newInstance(component, BuggyConfigurationException::new); + BuggyConfigurationYML.components.add(instance); + } + } + + public static ParallelMode getParallelMode() { + return parallelMode; + } + + public static void setParallelMode(ParallelMode parallelMode) { + BuggyConfigurationYML.parallelMode = parallelMode; + } + + public static String getProgramName() { + return BuggyConfigurationYML.programName; + } + + public static void setProgramName(String programName) { + BuggyConfigurationYML.programName = programName; + } + + public static String getIssuesUrl() { + return issuesUrl; + } + + public static void setIssuesUrl(String issuesUrl) { + BuggyConfigurationYML.issuesUrl = issuesUrl; + } + + public static Boolean getHelp() { + return help; + } + + public static Boolean getForceRun() { + return forceRun; + } + + public static Boolean getTestCaseTitle() { + return testCaseTitle; + } + + public static void setTestCaseTitle(Boolean testCaseTitle) { + BuggyConfigurationYML.testCaseTitle = testCaseTitle; + } + + public static Boolean getTestSuiteInfo() { + return testSuiteInfo; + } + + public static void setTestSuiteInfo(Boolean testSuiteInfo) { + BuggyConfigurationYML.testSuiteInfo = testSuiteInfo; + } + + public static Boolean getTestLogFilePath() { + return testLogFilePath; + } + + public static void setTestLogFilePath(Boolean testLogFilePath) { + BuggyConfigurationYML.testLogFilePath = testLogFilePath; + } + + public static Boolean getTestIssuesInfo() { + return testIssuesInfo; + } + + public static void setTestIssuesInfo(Boolean testIssuesInfo) { + BuggyConfigurationYML.testIssuesInfo = testIssuesInfo; + } + + public static Boolean getTestBugsInfo() { + return testBugsInfo; + } + + public static void setTestBugsInfo(Boolean testBugsInfo) { + BuggyConfigurationYML.testBugsInfo = testBugsInfo; + } + + public static Boolean getTestErrorInfo() { + return testErrorInfo; + } + + public static void setTestErrorInfo(Boolean testErrorInfo) { + BuggyConfigurationYML.testErrorInfo = testErrorInfo; + } + + public static OutputRule getOutputRule() { + return outputRule; + } + + public static void setOutputRule(OutputRule outputRule) { + BuggyConfigurationYML.outputRule = outputRule; + } + +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/config/ConfigurationYML.java b/buggy-core/src/main/java/org/touchbit/buggy/core/config/ConfigurationYML.java new file mode 100644 index 0000000..3ab1153 --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/config/ConfigurationYML.java @@ -0,0 +1,41 @@ +package org.touchbit.buggy.core.config; + +import com.google.common.base.CaseFormat; +import org.touchbit.buggy.core.snakeyaml.BuggyYamlPropertyUtils; +import org.touchbit.buggy.core.utils.JUtils; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; +import org.yaml.snakeyaml.representer.Representer; + +import java.io.InputStream; +import java.util.Map; +import java.util.stream.Collectors; + +import static org.yaml.snakeyaml.introspector.BeanAccess.FIELD; + +/** + * Created by Oleg Shaburov on 01.10.2020 + * shaburov.o.a@gmail.com + */ +@SuppressWarnings("unused") +public interface ConfigurationYML { + + String BUGGY_CONFIG_YML = "buggy-config.yml"; + + static void initConfigurationYml(Class configClass) { + InputStream inputStream = JUtils.getCurrentThreadClassLoader().getResourceAsStream(BUGGY_CONFIG_YML); + getYamlLoader(configClass).load(inputStream); + } + + static Yaml getYamlLoader(Class configClass) { + Representer representer = new Representer(); + BuggyYamlPropertyUtils propertyUtils = new BuggyYamlPropertyUtils(); + propertyUtils.setSkipMissingProperties(true); + propertyUtils.setBeanAccess(FIELD); + representer.setPropertyUtils(propertyUtils); + Constructor constructor = new Constructor(configClass); + return new Yaml(constructor, representer); + } + +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/config/JCommand.java b/buggy-core/src/main/java/org/touchbit/buggy/core/config/JCommand.java new file mode 100644 index 0000000..d9998a5 --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/config/JCommand.java @@ -0,0 +1,107 @@ +package org.touchbit.buggy.core.config; + +import com.beust.jcommander.Parameter; +import org.touchbit.buggy.core.logback.FrameworkLogger; +import org.touchbit.buggy.core.utils.JUtils; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.*; + +public interface JCommand extends ConfigurationYML { + + /** + * Convert configuration parameters and values to map where: + * key - {@link Parameter#names()} + * value - field or method value + * + * @return map with configuration parameters names and values + */ + default Map configurationToMap() { + Map map = new HashMap<>(); + addFieldValuesToMap(map); + addMethodsValuesToMap(map); + return sort(map); + } + + /** + * Method adds to Map {@link Parameter#names()} and values of annotated fields + * + * @param map - configuration parameters and values map + */ + default void addFieldValuesToMap(Map map) { + for (Field field : JUtils.getFields(this)) { + Parameter parameter = field.getAnnotation(Parameter.class); + if (parameter != null && !parameter.hidden()) { + String[] names = parameter.names(); + String parameters = Arrays.toString(names); + try { + if (parameter.password()) { + map.put(parameters, "*****"); + } else { + field.setAccessible(true); + map.put(parameters, field.get(this)); + } + } catch (Exception e) { + map.put(parameters, ""); + new FrameworkLogger().error("Error getting value from field " + + field.getDeclaringClass().getSimpleName() + "#" + field.getName(), e); + } finally { + field.setAccessible(false); + } + } + } + } + + /** + * Method adds to Map {@link Parameter#names()} and values of annotated methods + * + * @param map - configuration parameters and values map + */ + default void addMethodsValuesToMap(Map map) { + List methods = JUtils.getMethods(this); + Map, Method> getters = new HashMap<>(); + for (Method method : methods) { + Parameter parameter = method.getAnnotation(Parameter.class); + if (parameter != null && !parameter.hidden()) { + String[] names = parameter.names(); + if (parameter.password()) { + map.put(Arrays.toString(names), "*****"); + } else { + String mName = method.getName(); + String is = "is" + mName.substring(3); + String get = "get" + mName.substring(3); + methods.stream() + .filter(m -> (m.getName().equalsIgnoreCase(is) || m.getName().equalsIgnoreCase(get))) + .forEach(g -> getters.put(new ArrayList<>(Arrays.asList(names)), g)); + } + } + } + for (Map.Entry, Method> method : getters.entrySet()) { + try { + method.getValue().setAccessible(true); + map.put(method.getKey().toString(), method.getValue().invoke(this)); + } catch (Exception e) { + map.put(method.getKey().toString(), ""); + Method m = method.getValue(); + StringJoiner sj = new StringJoiner(", ", "(", ")"); + Arrays.stream(m.getParameterTypes()).forEach(p -> sj.add(p.getSimpleName())); + new FrameworkLogger().error("Error getting value from method " + + m.getDeclaringClass().getSimpleName() + "#" + m.getName() + sj.toString(), e); + } finally { + method.getValue().setAccessible(false); + } + } + } + + /** + * Default no sort + * + * @param map - unsorted map + * @return - sorted map + */ + default Map sort(Map map) { + return map; + } + +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/config/OutputRule.java b/buggy-core/src/main/java/org/touchbit/buggy/core/config/OutputRule.java new file mode 100644 index 0000000..67b7289 --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/config/OutputRule.java @@ -0,0 +1,9 @@ +package org.touchbit.buggy.core.config; + +public enum OutputRule { + + OFF, + UNSUCCESSFUL, + ALWAYS + +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/config/PrimaryConfig.java b/buggy-core/src/main/java/org/touchbit/buggy/core/config/PrimaryConfig.java deleted file mode 100644 index fdfe883..0000000 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/config/PrimaryConfig.java +++ /dev/null @@ -1,348 +0,0 @@ -/* - * Copyright © 2018 Shaburov Oleg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.touchbit.buggy.core.config; - -import com.beust.jcommander.IDefaultProvider; -import com.beust.jcommander.Parameter; -import org.apache.commons.lang3.ArrayUtils; -import org.apache.commons.lang3.ClassUtils; -import org.atteo.classindex.IndexSubclasses; -import org.touchbit.buggy.core.config.jcommander.InterfaceConverter; -import org.touchbit.buggy.core.config.jcommander.ParameterValidator; -import org.touchbit.buggy.core.config.jcommander.ServiceConverter; -import org.touchbit.buggy.core.config.jcommander.ValueValidator; -import org.touchbit.buggy.core.model.Type; -import org.touchbit.buggy.core.process.Interface; -import org.touchbit.buggy.core.process.Service; -import org.touchbit.buggy.core.utils.BuggyUtils; -import org.touchbit.buggy.core.utils.StringUtils; - -import java.io.File; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.*; - -import static org.touchbit.buggy.core.config.BParameters.*; - -/** - * Primary Config for jCommander - *

- * Created by Oleg Shaburov on 30.05.2018 - * shaburov.o.a@gmail.com - */ -@SuppressWarnings({"unused", "squid:S1214"}) -@IndexSubclasses -public interface PrimaryConfig { - - DefaultValues DEFAULT_VALUES = new DefaultValues(); - - class DefaultValues { - private Boolean force = false; - private Boolean printAll = false; - private Boolean printSuite = false; - private Boolean printCause = false; - private Boolean printLog = false; - private Boolean printLogOnlyFail = false; - private Boolean check = false; - private Integer threads = 50; - private Integer status; - private String logPath = "logs"; - private String absoluteLogPath; - private String runDir; - private String artifactsUrl; - private Type type = Type.INTEGRATION; - private List services = BuggyUtils.findServices(); - private List interfaces = BuggyUtils.findInterfaces(); - - /** Utility class. Prohibit instantiation. */ - private DefaultValues() { } - } - - @Parameter(names = {QUESTION_MARK, HELP}, hidden = true, help = true, validateValueWith = ValueValidator.class, - description = "Print usage.") - default void setHelp(Boolean help) { - // Do nothing - } - - default Boolean isHelp() { - return false; - } - - @Parameter(names = {ALL}, hidden = true, description = "Print all configuration parameters.") - default void setPrintAllParameters(Boolean printAllParameters) { - DEFAULT_VALUES.printAll = printAllParameters; - } - - default Boolean isPrintAllParameters() { - return DEFAULT_VALUES.printAll; - } - - @Parameter(names = {F, FORCE}, description = "Running all tests, including those that fall.") - default void setForceRun(Boolean force) { - DEFAULT_VALUES.force = force; - } - - default Boolean isForceRun() { - return DEFAULT_VALUES.force; - } - - @Parameter(names = {THREADS}, description = "The number of threads to run the test methods.") - default void setThreads(Integer threads) { - DEFAULT_VALUES.threads = threads; - } - - default Integer getThreads() { - return DEFAULT_VALUES.threads; - } - - @Parameter(names = {LOG}, hidden = true, description = "Absolute path to the directory for test logs.") - default void setLogPath(String logDir) { - DEFAULT_VALUES.logPath = logDir; - } - - default String getLogPath() { - return DEFAULT_VALUES.logPath; - } - - @Parameter(names = {S, SERVICES}, description = "List of tested services in the format: NAME,NAME,NAME.", - validateWith = ParameterValidator.class, listConverter = ServiceConverter.class) - default void setServices(List services) { - DEFAULT_VALUES.services = services; - } - - default List getServices() { - return DEFAULT_VALUES.services; - } - - @Parameter(names = {I, INTERFACE}, description = "List of tested interfaces in the format: NAME,NAME,NAME.", - validateWith = ParameterValidator.class, listConverter = InterfaceConverter.class) - default void setInterfaces(List interfaces) { - DEFAULT_VALUES.interfaces = interfaces; - } - - default List getInterfaces() { - return DEFAULT_VALUES.interfaces; - } - - @Parameter(names = {T, TYPE}, description = "Type of tests to run.", validateWith = ParameterValidator.class) - default void setType(Type type) { - DEFAULT_VALUES.type = type; - } - - default Type getType() { - return DEFAULT_VALUES.type; - } - - @Parameter(names = {STATUS}, hidden = true, description = "Completion with the specified status.") - default void setStatus(Integer status) { - DEFAULT_VALUES.status = status; - } - - default Integer getStatus() { - return DEFAULT_VALUES.status; - } - - @Parameter(names = {ARTIFACTS_URL}, hidden = true, description = "The storage address for the builds (artifacts).") - default void setArtifactsUrl(String artifactsUrl) { - DEFAULT_VALUES.artifactsUrl = artifactsUrl; - } - - default String getArtifactsUrl() { - return DEFAULT_VALUES.artifactsUrl; - } - - @Parameter(names = {PRINT_SUITE}, hidden = true, description = "Display information on the Suite in the console log.") - default void setPrintSuite(Boolean printSuite) { - DEFAULT_VALUES.printSuite = printSuite; - } - - default Boolean isPrintSuite() { - return DEFAULT_VALUES.printSuite; - } - - @Parameter(names = {PRINT_CAUSE}, hidden = true, description = "Print the cause of a fail or skip test in the console log.") - default void setPrintCause(Boolean printCause) { - DEFAULT_VALUES.printCause = printCause; - } - - default Boolean isPrintCause() { - return DEFAULT_VALUES.printCause; - } - - @Parameter(names = {PRINT_LOG}, hidden = true, description = "Print the test log file path in the console log") - default void setPrintLogFile(Boolean printLog) { - DEFAULT_VALUES.printLog = printLog; - } - - default Boolean isPrintLogFile() { - return DEFAULT_VALUES.printLog; - } - - default void setPrintLogFileOnlyFail(Boolean printLogIfFail) { - DEFAULT_VALUES.printLogOnlyFail = printLogIfFail; - } - - default Boolean isPrintLogFileOnlyFail() { - return DEFAULT_VALUES.printLogOnlyFail; - } - - @Parameter(names = {V, VERSION}, hidden = true, description = "Print program version", validateValueWith = ValueValidator.class) - default void setVersion(Boolean version) { - // Do nothing - } - - default boolean isVersion() { - return false; - } - - @Parameter(names = {SELF_CHECK}, hidden = true, description = "Check buggy configuration without test run.") - default void setCheck(Boolean check) { - DEFAULT_VALUES.check = check; - } - - default Boolean isCheck() { - return DEFAULT_VALUES.check; - } - - default void setRunDir(String path) { - DEFAULT_VALUES.runDir = path; - } - - default String getRunDir() { - return DEFAULT_VALUES.runDir; - } - - default void setAbsoluteLogPath(String path) { - DEFAULT_VALUES.absoluteLogPath = path; - } - - default String getAbsoluteLogPath() { - return DEFAULT_VALUES.absoluteLogPath; - } - - default File getErrorLogDir() { - return new File(getAbsoluteLogPath(), "errors"); - } - - default File getTestLogDir() { - return new File(getAbsoluteLogPath(), "tests"); - } - - default File getFixedLogDir() { - return new File(getAbsoluteLogPath(), "fixed"); - } - - default File getImplementedLogDir() { - return new File(getAbsoluteLogPath(), "implemented"); - } - - default File getNewErrorLogDir() { - return new File(getErrorLogDir(), "new"); - } - - default File getExpFixErrorLogDir() { - return new File(getErrorLogDir(), "exp_fix"); - } - - default File getExpImplErrorLogDir() { - return new File(getErrorLogDir(), "exp_impl"); - } - - default File getCorruptedErrorLogDir() { - return new File(getErrorLogDir(), "corrupted"); - } - - default File getBlockedErrorLogDir() { - return new File(getErrorLogDir(), "blocked"); - } - - @SuppressWarnings("WeakerAccess") - class DefaultValueProvider implements IDefaultProvider { - - @Override - public String getDefaultValueFor(String optionName) { - return null; - } - - } - - static String configurationToString(T config) { - Map map = new HashMap<>(); - addFieldValuesToMap(config, map); - addMethodsValuesToMap(config, map); - Map sorted = new LinkedHashMap<>(); - map.entrySet().stream() - .sorted(Map.Entry.comparingByKey()) - .forEachOrdered(k -> sorted.put(k.getKey(), k.getValue())); - StringJoiner sj = new StringJoiner("\n"); - sorted.forEach((k, v) -> sj.add(StringUtils.dotFiller(k, 47, v))); - return sj.toString(); - } - - static void addFieldValuesToMap(T config, Map map) { - Class cClass = config.getClass(); - Field[] fields = ArrayUtils.addAll(cClass.getDeclaredFields(), cClass.getSuperclass().getDeclaredFields()); - for (Field field : fields) { - Parameter parameter = field.getAnnotation(Parameter.class); - if (parameter != null && (!parameter.hidden() || config.isPrintAllParameters())) { - String[] names = parameter.names(); - try { - if (parameter.password()) { - map.put(Arrays.toString(names), "********"); - } else { - map.put(Arrays.toString(names), field.get(config.getClass())); - } - } catch (Exception ignore) { - // do nothing - } - } - } - } - - static void addMethodsValuesToMap(T config, Map map) { - Class cClass = config.getClass(); - List> interfaces = ClassUtils.getAllInterfaces(cClass); - Set setMethods = new HashSet<>(); - Collections.addAll(setMethods, cClass.getDeclaredMethods()); - Collections.addAll(setMethods, cClass.getMethods()); - interfaces.forEach(i -> Collections.addAll(setMethods, i.getMethods())); - interfaces.forEach(i -> Collections.addAll(setMethods, i.getDeclaredMethods())); - Map, Method> getMethodsMap = new HashMap<>(); - for (Method method : setMethods) { - Parameter parameter = method.getAnnotation(Parameter.class); - if (parameter != null && (!parameter.hidden() || config.isPrintAllParameters())) { - String[] names = parameter.names(); - if (parameter.password()) { - map.put(Arrays.toString(names), "********"); - } else { - setMethods.stream().filter(m -> - (m.getName().equalsIgnoreCase("is" + method.getName().substring(3)) || - m.getName().equalsIgnoreCase("get" + method.getName().substring(3)))) - .forEach(k -> getMethodsMap.put(new ArrayList<>(Arrays.asList(names)), k)); - } - } - } - for (Map.Entry, Method> getMethod : getMethodsMap.entrySet()) { - try { - map.put(getMethod.getKey().toString(), getMethod.getValue().invoke(config)); - } catch (Exception ignore) { - // do nothing - } - } - } - -} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/config/jcommander/ValueValidator.java b/buggy-core/src/main/java/org/touchbit/buggy/core/config/jcommander/ValueValidator.java deleted file mode 100644 index 3b89a1e..0000000 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/config/jcommander/ValueValidator.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright © 2018 Shaburov Oleg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.touchbit.buggy.core.config.jcommander; - -import com.beust.jcommander.IValueValidator; -import org.touchbit.buggy.core.Buggy; -import org.touchbit.buggy.core.utils.BuggyUtils; -import org.touchbit.buggy.core.utils.StringUtils; - -import java.util.StringJoiner; -import java.util.jar.Attributes; - -import static org.touchbit.buggy.core.config.BParameters.*; -import static org.touchbit.buggy.core.utils.BuggyUtils.CONSOLE_DELIMITER; -import static org.touchbit.buggy.core.utils.StringUtils.underscoreFiller; - -/** - * Created by Oleg Shaburov on 19.09.2018 - * shaburov.o.a@gmail.com - */ -public class ValueValidator implements IValueValidator { - - @Override - public void validate(String name, Object value) { - String stringValue = String.valueOf(value); - if ((name.equals(QUESTION_MARK) || name.equals(HELP)) && Boolean.valueOf(stringValue)) { - Buggy.getExitHandler().exitRunWithUsage(0); - } - if ((name.equals(V) || name.equals(VERSION)) && Boolean.valueOf(String.valueOf(stringValue))) { - printManifestInfo(); - Buggy.getExitHandler().exitRun(0); - } - } - - private static void printManifestInfo() { - Attributes attributes = BuggyUtils.getManifestAttributes(); - printAttributes(attributes); - } - - private static void printAttributes(Attributes attributes) { - StringJoiner stringJoiner = new StringJoiner("\n"); - if (attributes != null) { - attributes.entrySet().stream() - .filter(e -> String.valueOf(e.getKey()).startsWith("Implementation") && e.getValue() != null) - .forEach(e -> stringJoiner.add( - underscoreFiller(String.valueOf(e.getKey()).replace("Implementation-", ""), - 47, e.getValue()))); - if (stringJoiner.length() > 0) { - StringUtils.println(stringJoiner.toString()); - StringUtils.println(CONSOLE_DELIMITER); - } - } - } - -} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/exceptions/BaseBuggyTestException.java b/buggy-core/src/main/java/org/touchbit/buggy/core/exceptions/BaseBuggyTestException.java index b9e0a2c..d8c5a19 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/exceptions/BaseBuggyTestException.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/exceptions/BaseBuggyTestException.java @@ -1,6 +1,6 @@ package org.touchbit.buggy.core.exceptions; -import org.touchbit.buggy.core.model.Details; +import org.touchbit.buggy.core.model.Buggy; import java.util.Arrays; @@ -27,16 +27,16 @@ public BaseBuggyTestException(Throwable e) { super(e); } - protected static String getMsg(String brief, Details details) { + protected static String getMsg(String brief, Buggy buggy) { StringBuilder sb = new StringBuilder(); sb.append(brief); - if (details != null) { + if (buggy != null) { String[] tmp; - tmp = details.issue(); + tmp = buggy.issues(); if (tmp.length > 0) { sb.append(". Related issues: ").append(Arrays.toString(tmp)); } - tmp = details.bug(); + tmp = buggy.bugs(); if (tmp.length > 0) { sb.append(". Related bugs: ").append(Arrays.toString(tmp)); } diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/exceptions/BlockedTestException.java b/buggy-core/src/main/java/org/touchbit/buggy/core/exceptions/BlockedTestException.java index 57b5724..b43be5a 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/exceptions/BlockedTestException.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/exceptions/BlockedTestException.java @@ -12,7 +12,7 @@ package org.touchbit.buggy.core.exceptions; -import org.touchbit.buggy.core.model.Details; +import org.touchbit.buggy.core.model.Buggy; /** * Created by Oleg Shaburov on 18.05.2018 @@ -22,8 +22,8 @@ public class BlockedTestException extends BaseBuggyTestException { private static final String MSG = "Autotest blocked. Test case verification is not possible."; - public BlockedTestException(Details details) { - super(getMsg(MSG, details)); + public BlockedTestException(Buggy buggy) { + super(getMsg(MSG, buggy)); } public BlockedTestException() { diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/exceptions/CorruptedTestException.java b/buggy-core/src/main/java/org/touchbit/buggy/core/exceptions/CorruptedTestException.java index f5eec55..d04641e 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/exceptions/CorruptedTestException.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/exceptions/CorruptedTestException.java @@ -16,7 +16,7 @@ package org.touchbit.buggy.core.exceptions; -import org.touchbit.buggy.core.model.Details; +import org.touchbit.buggy.core.model.Buggy; /** * Created by Oleg Shaburov on 18.05.2018 @@ -26,8 +26,8 @@ public class CorruptedTestException extends BaseBuggyTestException { private static final String MSG = "The autotest is corrupted and must be repaired."; - public CorruptedTestException(Details details) { - super(getMsg(MSG, details)); + public CorruptedTestException(Buggy buggy) { + super(getMsg(MSG, buggy)); } public CorruptedTestException() { diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/exceptions/ExpectedImplementationException.java b/buggy-core/src/main/java/org/touchbit/buggy/core/exceptions/ExpectedImplementationException.java index adaa28c..92f96eb 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/exceptions/ExpectedImplementationException.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/exceptions/ExpectedImplementationException.java @@ -12,7 +12,7 @@ package org.touchbit.buggy.core.exceptions; -import org.touchbit.buggy.core.model.Details; +import org.touchbit.buggy.core.model.Buggy; /** * Created by Oleg Shaburov on 18.05.2018 @@ -22,8 +22,8 @@ public class ExpectedImplementationException extends BaseBuggyTestException { private static final String MSG = "The autotest is waiting for the implementation of the related test-case"; - public ExpectedImplementationException(Details details) { - super(getMsg(MSG, details)); + public ExpectedImplementationException(Buggy buggy) { + super(getMsg(MSG, buggy)); } public ExpectedImplementationException() { diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/process/Goal.java b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/Goal.java similarity index 77% rename from buggy-core/src/main/java/org/touchbit/buggy/core/process/Goal.java rename to buggy-core/src/main/java/org/touchbit/buggy/core/goal/Goal.java index 97dedff..32c13d4 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/process/Goal.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/Goal.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.touchbit.buggy.core.process; +package org.touchbit.buggy.core.goal; /** * Created by Oleg Shaburov on 08.09.2018 @@ -22,6 +22,14 @@ */ public interface Goal { - public String getName(); + String getName(); + + default boolean isActive() { + return true; + } + + default String getDescription() { + return ""; + } } diff --git a/buggy-min-example/src/main/java/org/touchbit/buggy/example/min/goals/API.java b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/component/AllComponents.java similarity index 68% rename from buggy-min-example/src/main/java/org/touchbit/buggy/example/min/goals/API.java rename to buggy-core/src/main/java/org/touchbit/buggy/core/goal/component/AllComponents.java index f6a4f6c..3ea19ac 100644 --- a/buggy-min-example/src/main/java/org/touchbit/buggy/example/min/goals/API.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/component/AllComponents.java @@ -14,19 +14,27 @@ * limitations under the License. */ -package org.touchbit.buggy.example.min.goals; - -import org.touchbit.buggy.core.process.Interface; +package org.touchbit.buggy.core.goal.component; /** - * Created by Oleg Shaburov on 18.09.2018 + * Created by Oleg Shaburov on 08.09.2018 * shaburov.o.a@gmail.com */ -public class API extends Interface { +public final class AllComponents extends Component { + + @Override + public String getName() { + return "ALL"; + } @Override public String getDescription() { - return "REST API"; + return "All components"; + } + + @Override + public boolean isActive() { + return false; } } diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/process/Component.java b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/component/Component.java similarity index 80% rename from buggy-core/src/main/java/org/touchbit/buggy/core/process/Component.java rename to buggy-core/src/main/java/org/touchbit/buggy/core/goal/component/Component.java index 698cb51..67f0573 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/process/Component.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/component/Component.java @@ -14,11 +14,9 @@ * limitations under the License. */ -package org.touchbit.buggy.core.process; +package org.touchbit.buggy.core.goal.component; -import org.atteo.classindex.IndexSubclasses; - -import java.util.List; +import org.touchbit.buggy.core.goal.Goal; /** * The tested component of the system @@ -26,13 +24,8 @@ * Created by Oleg Shaburov on 15.05.2018 * shaburov.o.a@gmail.com */ -@IndexSubclasses public abstract class Component implements Goal { - public abstract List getServices(); - - public abstract String getDescription(); - public String getName() { return this.getClass().getSimpleName().toUpperCase(); } diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/process/DefaultComponent.java b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/component/DefaultComponent.java similarity index 78% rename from buggy-core/src/main/java/org/touchbit/buggy/core/process/DefaultComponent.java rename to buggy-core/src/main/java/org/touchbit/buggy/core/goal/component/DefaultComponent.java index 3847225..f4bd8a5 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/process/DefaultComponent.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/component/DefaultComponent.java @@ -14,21 +14,13 @@ * limitations under the License. */ -package org.touchbit.buggy.core.process; - -import java.util.ArrayList; -import java.util.List; +package org.touchbit.buggy.core.goal.component; /** * Created by Oleg Shaburov on 08.09.2018 * shaburov.o.a@gmail.com */ -public class DefaultComponent extends Component { - - @Override - public List getServices() { - return new ArrayList<>(); - } +public final class DefaultComponent extends Component { @Override public String getName() { diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/goal/interfaze/API.java b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/interfaze/API.java new file mode 100644 index 0000000..f02844d --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/interfaze/API.java @@ -0,0 +1,15 @@ +package org.touchbit.buggy.core.goal.interfaze; + +public class API extends Interface { + + @Override + public String getName() { + return "API"; + } + + @Override + public String getDescription() { + return "Application programming interface"; + } + +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/goal/interfaze/AllInterfaces.java b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/interfaze/AllInterfaces.java new file mode 100644 index 0000000..1eaccbc --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/interfaze/AllInterfaces.java @@ -0,0 +1,20 @@ +package org.touchbit.buggy.core.goal.interfaze; + +public final class AllInterfaces extends Interface { + + @Override + public String getName() { + return "ALL"; + } + + @Override + public String getDescription() { + return "All interfaces"; + } + + @Override + public boolean isActive() { + return false; + } + +} diff --git a/buggy-min-example/src/main/java/org/touchbit/buggy/example/min/goals/GitLab.java b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/interfaze/DefaultInterface.java similarity index 73% rename from buggy-min-example/src/main/java/org/touchbit/buggy/example/min/goals/GitLab.java rename to buggy-core/src/main/java/org/touchbit/buggy/core/goal/interfaze/DefaultInterface.java index ce3c9f6..1abf82c 100644 --- a/buggy-min-example/src/main/java/org/touchbit/buggy/example/min/goals/GitLab.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/interfaze/DefaultInterface.java @@ -14,19 +14,20 @@ * limitations under the License. */ -package org.touchbit.buggy.example.min.goals; - -import org.touchbit.buggy.core.process.Service; +package org.touchbit.buggy.core.goal.interfaze; /** - * Created by Oleg Shaburov on 18.09.2018 + * Created by Oleg Shaburov on 03.10.2020 * shaburov.o.a@gmail.com */ -public class GitLab extends Service { +public class DefaultInterface extends Interface { + + public String getName() { + return "DEFAULT"; + } - @Override public String getDescription() { - return "GitLab service"; + return "Default test interface"; } } diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/process/Interface.java b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/interfaze/Interface.java similarity index 82% rename from buggy-core/src/main/java/org/touchbit/buggy/core/process/Interface.java rename to buggy-core/src/main/java/org/touchbit/buggy/core/goal/interfaze/Interface.java index f15d124..79e698f 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/process/Interface.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/interfaze/Interface.java @@ -14,17 +14,16 @@ * limitations under the License. */ -package org.touchbit.buggy.core.process; +package org.touchbit.buggy.core.goal.interfaze; -import org.atteo.classindex.IndexSubclasses; +import org.touchbit.buggy.core.goal.Goal; /** - * The tested interface. (example: API, DAV, SMTP, IMAP, WEB, IOS, ANDROID, TIZEN, DESKTOP etc.) + * The tested interface. (example: API, WEB, IOS, ANDROID, TIZEN, DESKTOP etc.) *

* Created by Oleg Shaburov on 15.05.2018 * shaburov.o.a@gmail.com */ -@IndexSubclasses public abstract class Interface implements Goal { public String getName() { diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/goal/interfaze/WEB.java b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/interfaze/WEB.java new file mode 100644 index 0000000..8a2a023 --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/interfaze/WEB.java @@ -0,0 +1,15 @@ +package org.touchbit.buggy.core.goal.interfaze; + +public class WEB extends Interface { + + @Override + public String getName() { + return "WEB"; + } + + @Override + public String getDescription() { + return "WEB interface"; + } + +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/goal/service/AllServices.java b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/service/AllServices.java new file mode 100644 index 0000000..cf8da19 --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/service/AllServices.java @@ -0,0 +1,20 @@ +package org.touchbit.buggy.core.goal.service; + +public final class AllServices extends Service { + + @Override + public String getName() { + return "ALL"; + } + + @Override + public String getDescription() { + return "All services"; + } + + @Override + public boolean isActive() { + return false; + } + +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/goal/service/DefaultService.java b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/service/DefaultService.java new file mode 100644 index 0000000..717cb39 --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/service/DefaultService.java @@ -0,0 +1,15 @@ +package org.touchbit.buggy.core.goal.service; + +public final class DefaultService extends Service { + + @Override + public String getName() { + return "DEFAULT"; + } + + @Override + public String getDescription() { + return "Default service for test suites"; + } + +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/process/Service.java b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/service/Service.java similarity index 90% rename from buggy-core/src/main/java/org/touchbit/buggy/core/process/Service.java rename to buggy-core/src/main/java/org/touchbit/buggy/core/goal/service/Service.java index 56dd9e4..a1db158 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/process/Service.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/service/Service.java @@ -14,9 +14,9 @@ * limitations under the License. */ -package org.touchbit.buggy.core.process; +package org.touchbit.buggy.core.goal.service; -import org.atteo.classindex.IndexSubclasses; +import org.touchbit.buggy.core.goal.Goal; /** * The tested service included in (belongs to) the system component @@ -24,7 +24,6 @@ * Created by Oleg Shaburov on 15.05.2018 * shaburov.o.a@gmail.com */ -@IndexSubclasses public abstract class Service implements Goal { public String getName() { diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/logback/BaseLogbackWrapper.java b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/BaseLogbackWrapper.java new file mode 100644 index 0000000..fd0ffc1 --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/BaseLogbackWrapper.java @@ -0,0 +1,223 @@ +package org.touchbit.buggy.core.logback; + +import ch.qos.logback.classic.LoggerContext; +import ch.qos.logback.classic.util.ContextInitializer; +import ch.qos.logback.core.joran.spi.JoranException; +import ch.qos.logback.core.util.StatusPrinter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.helpers.MarkerIgnoringBase; +import org.touchbit.buggy.core.exceptions.BuggyConfigurationException; +import org.touchbit.buggy.core.utils.JUtils; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.net.URL; +import java.util.List; + +public class BaseLogbackWrapper extends MarkerIgnoringBase { + + static { + if (System.getProperty("logback.configurationFile") == null) { + System.setProperty("logback.configurationFile", "buggy-logback.xml"); + } + startLoggerContext(); + } + + protected static final String CONSOLE_LOGGER_NAME = "Console"; + protected static final String FRAMEWORK_LOGGER_NAME = "Framework"; + protected static final String SIFTING_LOGGER_NAME = "Sifting"; + + private final Logger logger; + + public BaseLogbackWrapper(final String name) { + this.name = name; + this.logger = LoggerFactory.getLogger(name); + } + + public static String getConfFileName() { + return System.getProperty("logging.config", System.getProperty("logback.configurationFile", "undefined")) + .replace("classpath:", ""); + } + + public static String getInCaseOfErrorsOrWarnings() { + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + PrintStream printStream = new PrintStream(stream); + StatusPrinter.setPrintStream(printStream); + StatusPrinter.printInCaseOfErrorsOrWarnings(getLoggerContext()); + return stream.toString(); + } + + protected static void startLoggerContext() { + LoggerContext loggerContext = getLoggerContext(); + ContextInitializer ci = new ContextInitializer(loggerContext); + URL url = ci.findURLOfDefaultConfigurationFile(true); + if (loggerContext.isStarted()) { + return; + } + try { + loggerContext.reset(); + ci.configureByResource(url); + } catch (JoranException e) { + throw new BuggyConfigurationException("Unable to initialize configuration: " + url); + } + } + + public static List getLoggerList() { + return getLoggerContext().getLoggerList(); + } + + public static LoggerContext getLoggerContext() { + return (LoggerContext) LoggerFactory.getILoggerFactory(); + } + + @Override + public boolean isTraceEnabled() { + return logger.isTraceEnabled(); + } + + @Override + public void trace(String msg) { + logger.trace(msg); + } + + @Override + public void trace(String format, Object arg) { + logger.trace(format, arg); + } + + @Override + public void trace(String format, Object arg1, Object arg2) { + logger.trace(format, arg1, arg2); + } + + @Override + public void trace(String format, Object... arguments) { + logger.trace(format, arguments); + } + + @Override + public void trace(String msg, Throwable t) { + logger.trace(msg, t); + } + + @Override + public boolean isDebugEnabled() { + return logger.isDebugEnabled(); + } + + @Override + public void debug(String msg) { + logger.debug(msg); + } + + @Override + public void debug(String format, Object arg) { + logger.debug(format, arg); + } + + @Override + public void debug(String format, Object arg1, Object arg2) { + logger.debug(format, arg1, arg2); + } + + @Override + public void debug(String format, Object... arguments) { + logger.debug(format, arguments); + } + + @Override + public void debug(String msg, Throwable t) { + logger.debug(msg, t); + } + + @Override + public boolean isInfoEnabled() { + return logger.isInfoEnabled(); + } + + @Override + public void info(String msg) { + logger.info(msg); + } + + @Override + public void info(String format, Object arg) { + logger.info(format, arg); + } + + @Override + public void info(String format, Object arg1, Object arg2) { + logger.info(format, arg1, arg2); + } + + @Override + public void info(String format, Object... arguments) { + logger.info(format, arguments); + } + + @Override + public void info(String msg, Throwable t) { + logger.info(msg, t); + } + + @Override + public boolean isWarnEnabled() { + return logger.isWarnEnabled(); + } + + @Override + public void warn(String msg) { + logger.warn(msg); + } + + @Override + public void warn(String format, Object arg) { + logger.warn(format, arg); + } + + @Override + public void warn(String format, Object... arguments) { + logger.warn(format, arguments); + } + + @Override + public void warn(String format, Object arg1, Object arg2) { + logger.warn(format, arg1, arg2); + } + + @Override + public void warn(String msg, Throwable t) { + logger.warn(msg, t); + } + + @Override + public boolean isErrorEnabled() { + return logger.isErrorEnabled(); + } + + @Override + public void error(String msg) { + logger.error(msg); + } + + @Override + public void error(String format, Object arg) { + logger.error(format, arg); + } + + @Override + public void error(String format, Object arg1, Object arg2) { + logger.error(format, arg1, arg2); + } + + @Override + public void error(String format, Object... arguments) { + logger.error(format, arguments); + } + + @Override + public void error(String msg, Throwable t) { + logger.error(msg, t); + } +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/logback/ConfLogger.java b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/ConfLogger.java new file mode 100644 index 0000000..cf1f6fd --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/ConfLogger.java @@ -0,0 +1,137 @@ +package org.touchbit.buggy.core.logback; + +import org.touchbit.buggy.core.utils.ANSI; + +import static java.util.Objects.isNull; +import static org.touchbit.buggy.core.utils.ANSI.BOLD; + +/** + * Utility class for logging configuration events in TestNG format + *

+ * Created by Oleg Shaburov on 01.10.2020 + * shaburov.o.a@gmail.com + */ +public class ConfLogger { + + public static final int CONF_STRING_LEN = 47; + public static final String CONF_BLOCK = "="; + public static final String CONF_STEP = "\u2014"; + public static final String DOT = "."; + public static final String UNDERSCORE = "_"; + + private static final ConsoleLogger CONSOLE = new ConsoleLogger(); + + private ConfLogger() { + throw new IllegalStateException("Utility class. Prohibit instantiation."); + } + + public static void stepDelimiter() { + info(filler(CONF_STEP)); + } + + public static void blockDelimiter() { + info(filler(CONF_BLOCK)); + } + + public static void dotPlaceholder(Object prefix, Object postfix, ANSI ansi, boolean isWrapCondition) { + String msg = getDotPlaceholder(prefix, postfix); + if (isWrapCondition) { + dotPlaceholder(prefix, postfix, ansi); + } else { + info(msg); + } + } + + public static void dotPlaceholder(Object prefix, Object postfix, ANSI ansi) { + String msg = getDotPlaceholder(prefix, postfix, ansi); + info(msg); + } + + public static void dotPlaceholder(Object prefix, Object postfix) { + info(getDotPlaceholder(prefix, postfix)); + } + + public static String getDotPlaceholder(Object prefix, Object postfix) { + return filler(prefix, DOT, postfix); + } + + public static String getDotPlaceholder(Object prefix, Object postfix, ANSI ansi) { + String filler = filler(prefix, DOT, postfix); + return ansi.wrap(filler); + } + + public static void underscorePlaceholder(Object prefix, Object postfix) { + info(filler(prefix, UNDERSCORE, postfix)); + } + + public static String filler(String symbol) { + return filler(null, symbol, CONF_STRING_LEN, null); + } + + public static String filler(Object prefix, String symbol) { + return filler(prefix, symbol, CONF_STRING_LEN, null); + } + + public static String filler(Object prefix, String symbol, Object postfix) { + return filler(prefix, symbol, CONF_STRING_LEN, postfix); + } + + public static String filler(Object prefix, String symbol, int length, Object postfix) { + if (isNull(symbol) || symbol.isEmpty()) { + symbol = "."; + } + if (isNull(prefix)) { + prefix = ""; + } + if (isNull(postfix)) { + postfix = ""; + } + StringBuilder sb = new StringBuilder(); + int msgLen = (prefix.toString() + postfix.toString()).length(); + sb.append(prefix); + if (msgLen >= length) { + sb.append(symbol).append(symbol).append(symbol); + } + if (msgLen < length) { + for (int j = 0; j < (length - msgLen); j++) { + sb.append(symbol); + + } + } + sb.append(postfix); + return sb.toString(); + } + + public static void centerBold(String msg) { + info(BOLD.wrap(centerMsg(msg))); + } + + public static void center(String msg) { + info(centerMsg(msg)); + } + + private static String centerMsg(String msg) { + if (msg != null && !msg.isEmpty()) { + int diff = CONF_STRING_LEN - msg.length(); + if (diff > 0) { + int indent = diff / 2; + return filler("", " ", indent, "") + msg; + } + } + return msg; + } + + public static void info(String msg) { + CONSOLE.info(msg); + } + + public static void error(String msg, Throwable t) { + CONSOLE.error(msg, t); + } + + public static void error(String msg) { + CONSOLE.error(msg); + } + + +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/logback/ConsoleLogger.java b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/ConsoleLogger.java new file mode 100644 index 0000000..c1a3328 --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/ConsoleLogger.java @@ -0,0 +1,9 @@ +package org.touchbit.buggy.core.logback; + +public class ConsoleLogger extends BaseLogbackWrapper { + + public ConsoleLogger() { + super(CONSOLE_LOGGER_NAME); + } + +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/logback/FrameworkLogger.java b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/FrameworkLogger.java new file mode 100644 index 0000000..2915724 --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/FrameworkLogger.java @@ -0,0 +1,30 @@ +package org.touchbit.buggy.core.logback; + +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.FileAppender; + +import java.io.File; +import java.util.stream.Stream; + +public class FrameworkLogger extends BaseLogbackWrapper { + + public FrameworkLogger() { + super(FRAMEWORK_LOGGER_NAME); + } + + public static File getLogFile() { + for (ch.qos.logback.classic.Logger logger : getLoggerList()) { + FileAppender appender = Stream.generate(logger.iteratorForAppenders()::next) + .limit(1000) + .filter(a -> a instanceof FileAppender) + .filter(fileAppender -> fileAppender.getName().equals(FRAMEWORK_LOGGER_NAME)) + .map(f -> (FileAppender) f) + .findFirst().orElse(null); + if (appender != null) { + return new File(appender.getFile()); + } + } + return null; + } + +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/logback/SiftingTestLogger.java b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/SiftingTestLogger.java new file mode 100644 index 0000000..1c465e4 --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/SiftingTestLogger.java @@ -0,0 +1,73 @@ +package org.touchbit.buggy.core.logback; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.testng.IInvokedMethod; +import org.testng.ITestNGMethod; +import org.touchbit.buggy.core.logback.appender.SiftingFileAppender; +import org.touchbit.buggy.core.model.ResultStatus; + +import java.io.File; +import java.util.*; + +public class SiftingTestLogger extends BaseLogbackWrapper { + + private static final Map> STEPS = Collections.synchronizedMap(new HashMap<>()); + + public SiftingTestLogger() { + super(SIFTING_LOGGER_NAME); + } + + public static void setTestLogFileName(IInvokedMethod method) { + if (method != null) { + setTestLogFileName(method.getTestMethod()); + } + } + + public static void setTestLogFileName(ITestNGMethod iTestNGMethod) { + if (iTestNGMethod != null) { + String name = iTestNGMethod.getConstructorOrMethod().getMethod().getName(); + SiftingFileAppender.setTestLogFileName(name); + } + } + + @Nullable + public static File getSiftingLogFile() { + return SiftingFileAppender.getTestLogFile(); + } + + public static void setTestResultStatus(ResultStatus status) { + SiftingFileAppender.setTestResultStatus(status); + } + + public void step(@NotNull final String msg, @NotNull final Object... args) { + int stepNum = getSteps().size() + 1; + String msgBody = msg; + for (Object s : args) { + msgBody = msgBody.replaceFirst("\\{}", String.valueOf(s)); + } + String stepInfo = "STEP " + stepNum + ": " + msgBody; + this.info(" ---> {}", stepInfo); + getSteps().add(stepInfo); + } + + protected List getSteps() { + File file = getSiftingLogFile(); + if (file != null) { + String path = file.getPath(); + return STEPS.computeIfAbsent(path, k -> new ArrayList<>()); + } + return new ArrayList<>(); + } + + public void steps() { + List steps = getSteps(); + if (steps != null && steps.size() > 0) { + StringJoiner sj = new StringJoiner("\n", "Playback steps:\n", ""); + steps.forEach(sj::add); + this.info(sj.toString()); + } else { + this.info("No playback steps."); + } + } +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/logback/appender/BaseBuggyFileAppender.java b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/appender/BaseBuggyFileAppender.java new file mode 100644 index 0000000..6478f84 --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/appender/BaseBuggyFileAppender.java @@ -0,0 +1,40 @@ +package org.touchbit.buggy.core.logback.appender; + +import ch.qos.logback.core.FileAppender; +import org.touchbit.buggy.core.utils.JUtils; + +import java.io.File; + +public abstract class BaseBuggyFileAppender extends FileAppender { + + public static final String LOG_PATH = "LOG_PATH"; + + static { + if (JUtils.isJetBrainsIdeTestNGPluginRun()) { + System.setProperty(LOG_PATH, "target/logs"); + } else if (JUtils.isJetBrainsIdeConsoleRun()) { + System.setProperty(LOG_PATH, JUtils.getJetBrainsIdeConsoleRunTargetPath() + "/logs"); + } else { + System.setProperty(LOG_PATH, "logs"); + } + } + + public static final File LOG_DIR = new File(getLogPath()); + + public static final File TEST_DIR = new File(LOG_DIR, "tests"); + public static final File FIXED_DIR = new File(LOG_DIR, "fixed"); + public static final File IMPLEMENTED_DIR = new File(LOG_DIR, "implemented"); + + public static final File ERRORS = new File(LOG_DIR, "errors"); + public static final File NEW_DIR = new File(ERRORS, "new"); + public static final File CORRUPTED_DIR = new File(ERRORS, "corrupted"); + public static final File BLOCKED_DIR = new File(ERRORS, "blocked"); + public static final File EXP_FIX_DIR = new File(ERRORS, "exp_fix"); + public static final File EXP_IMPL_DIR = new File(ERRORS, "exp_impl"); + public static final String LOG_EXT = ".log"; + + public static String getLogPath() { + return System.getProperty(LOG_PATH, "logs"); + } + +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/logback/appender/ConsoleColorAppender.java b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/appender/ConsoleColorAppender.java new file mode 100644 index 0000000..0276095 --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/appender/ConsoleColorAppender.java @@ -0,0 +1,16 @@ +package org.touchbit.buggy.core.logback.appender; + +import ch.qos.logback.classic.LoggerContext; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.ConsoleAppender; +import org.slf4j.LoggerFactory; +import org.touchbit.buggy.core.logback.layout.ConsoleLoggerColorLayout; + +public class ConsoleColorAppender extends ConsoleAppender { + + public ConsoleColorAppender() { + super.setContext((LoggerContext) LoggerFactory.getILoggerFactory()); + super.setLayout(new ConsoleLoggerColorLayout<>()); + } + +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/logback/appender/FrameworkFileAppender.java b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/appender/FrameworkFileAppender.java new file mode 100644 index 0000000..d9f3a8f --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/appender/FrameworkFileAppender.java @@ -0,0 +1,19 @@ +package org.touchbit.buggy.core.logback.appender; + +import ch.qos.logback.classic.LoggerContext; +import ch.qos.logback.classic.spi.ILoggingEvent; +import org.slf4j.LoggerFactory; +import org.touchbit.buggy.core.logback.layout.FrameworkLoggerLayout; + +import java.io.File; + +public class FrameworkFileAppender extends BaseBuggyFileAppender { + + public FrameworkFileAppender() { + super.setContext((LoggerContext) LoggerFactory.getILoggerFactory()); + super.setLayout(new FrameworkLoggerLayout<>()); + super.setFile(new File(LOG_DIR, "Framework" + LOG_EXT).getPath()); + super.append = false; + } + +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/logback/appender/SiftingAppender.java b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/appender/SiftingAppender.java new file mode 100644 index 0000000..4f315ba --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/appender/SiftingAppender.java @@ -0,0 +1,20 @@ +package org.touchbit.buggy.core.logback.appender; + +import ch.qos.logback.classic.LoggerContext; +import ch.qos.logback.classic.sift.MDCBasedDiscriminator; +import org.slf4j.LoggerFactory; + +public class SiftingAppender extends ch.qos.logback.classic.sift.SiftingAppender { + + public static final String SIFTING_LOG_FILE_PATH = "sifting.test.log.file.path"; + + public SiftingAppender() { + super.setContext((LoggerContext) LoggerFactory.getILoggerFactory()); + MDCBasedDiscriminator discriminator = new MDCBasedDiscriminator(); + discriminator.setKey(SIFTING_LOG_FILE_PATH); + discriminator.setDefaultValue("base-sifting"); + discriminator.start(); + super.setDiscriminator(discriminator); + } + +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/logback/appender/SiftingFileAppender.java b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/appender/SiftingFileAppender.java new file mode 100644 index 0000000..dd41d47 --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/appender/SiftingFileAppender.java @@ -0,0 +1,110 @@ +package org.touchbit.buggy.core.logback.appender; + +import ch.qos.logback.classic.LoggerContext; +import ch.qos.logback.classic.spi.ILoggingEvent; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.touchbit.buggy.core.logback.layout.ShiftingLoggerLayout; +import org.touchbit.buggy.core.model.IStatus; +import org.touchbit.buggy.core.model.ResultStatus; +import org.touchbit.buggy.core.utils.IOHelper; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +import static org.touchbit.buggy.core.logback.appender.SiftingAppender.SIFTING_LOG_FILE_PATH; + +public class SiftingFileAppender extends BaseBuggyFileAppender { + + private static final List TEST_LOGS = new ArrayList<>(); + + public SiftingFileAppender() { + super.setContext((LoggerContext) LoggerFactory.getILoggerFactory()); + super.setLayout(new ShiftingLoggerLayout<>()); + super.append = false; + } + + public static synchronized void setTestLogFileName(String logFileName) { + List testLogs = TEST_LOGS.stream() + .filter(l -> l.getFileName().contains(logFileName)) + .collect(Collectors.toList()); + String fileName = logFileName + "_" + testLogs.size(); + File logFile = new File(TEST_DIR, fileName + LOG_EXT); + TestLog testLog = new TestLog(); + testLog.setFileName(fileName); + testLog.setFile(logFile); + TEST_LOGS.add(testLog); + MDC.put(SIFTING_LOG_FILE_PATH, fileName); + } + + @Override + public String getFile() { + File testLogFile = getTestLogFile(); + if (testLogFile != null) { + return testLogFile.getPath(); + } + return null; + } + + public static File getTestLogFile() { + String logFile = MDC.get(SIFTING_LOG_FILE_PATH); + return TEST_LOGS.stream() + .filter(f -> f.getFileName().equals(logFile)) + .map(TestLog::getFile) + .findFirst().orElse(null); + } + + public static void setTestResultStatus(ResultStatus status) { + String logFile = MDC.get(SIFTING_LOG_FILE_PATH); + TEST_LOGS.stream() + .filter(f -> f.getFileName().equals(logFile)) + .forEach(f -> f.setResultStatus(status)); + } + + public static void decomposeTestLogs() { + for (TestLog testLog : TEST_LOGS) { + ResultStatus resultStatus = testLog.getResultStatus(); + String fileName = testLog.getFileName(); + File destFile = null; + if (resultStatus != null) { + switch (resultStatus) { + case FAILED: + destFile = new File(NEW_DIR, fileName); + break; + case CORRUPTED: + destFile = new File(CORRUPTED_DIR, fileName); + break; + case BLOCKED: + destFile = new File(BLOCKED_DIR, fileName); + break; + case FIXED: + destFile = new File(FIXED_DIR, fileName); + break; + case IMPLEMENTED: + destFile = new File(IMPLEMENTED_DIR, fileName); + break; + case EXP_FIX: + destFile = new File(EXP_FIX_DIR, fileName); + break; + case EXP_IMPL: + destFile = new File(EXP_IMPL_DIR, fileName); + break; + case SUCCESS: + case SKIP: + default: + // do nothing + } + } + if (destFile != null) { + try { + IOHelper.copyFile(testLog.getFile(), destFile); + } catch (Exception e) { + // ignore todo + } + } + } + } + +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/logback/appender/TestLog.java b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/appender/TestLog.java new file mode 100644 index 0000000..ba42a07 --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/appender/TestLog.java @@ -0,0 +1,36 @@ +package org.touchbit.buggy.core.logback.appender; + +import org.touchbit.buggy.core.model.ResultStatus; + +import java.io.File; + +public class TestLog { + + private File file; + private String fileName; + private ResultStatus resultStatus; + + public File getFile() { + return file; + } + + public void setFile(File file) { + this.file = file; + } + + public String getFileName() { + return fileName; + } + + public void setFileName(String fileName) { + this.fileName = fileName; + } + + public ResultStatus getResultStatus() { + return resultStatus; + } + + public void setResultStatus(ResultStatus resultStatus) { + this.resultStatus = resultStatus; + } +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/logback/appender/TestSupervisorFileAppender.java b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/appender/TestSupervisorFileAppender.java new file mode 100644 index 0000000..3ebf988 --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/appender/TestSupervisorFileAppender.java @@ -0,0 +1,19 @@ +package org.touchbit.buggy.core.logback.appender; + +import ch.qos.logback.classic.LoggerContext; +import ch.qos.logback.classic.spi.ILoggingEvent; +import org.slf4j.LoggerFactory; +import org.touchbit.buggy.core.logback.layout.TestSupervisorLoggerLayout; + +import java.io.File; + +public class TestSupervisorFileAppender extends BaseBuggyFileAppender { + + public TestSupervisorFileAppender() { + super.setContext((LoggerContext) LoggerFactory.getILoggerFactory()); + super.setLayout(new TestSupervisorLoggerLayout<>()); + super.setFile(new File(LOG_DIR, "TestSupervisor.log").getPath()); + super.append = false; + } + +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/logback/layout/ConsoleLoggerColorLayout.java b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/layout/ConsoleLoggerColorLayout.java new file mode 100644 index 0000000..dab5e2c --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/layout/ConsoleLoggerColorLayout.java @@ -0,0 +1,53 @@ +package org.touchbit.buggy.core.logback.layout; + +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.CoreConstants; +import ch.qos.logback.core.LayoutBase; + +import static ch.qos.logback.classic.Level.*; +import static org.touchbit.buggy.core.utils.ANSI.*; + +/** + * Console logger layout for dividing logging levels by color. + * Used to color-code the status of completed tests and framework events. + * ERROR - red + * WARN - purple + * INFO - none + * DEBUG - green + * TRACE - blue + *

+ * Created by Oleg Shaburov on 30.09.2020 + * shaburov.o.a@gmail.com + */ +public class ConsoleLoggerColorLayout extends LayoutBase { + + /** + * Log format: message\n + */ + @Override + public String doLayout(final ILoggingEvent event) { + final StringBuilder stringBuilder = new StringBuilder(128); + final String msg = event.getFormattedMessage(); + switch (event.getLevel().levelInt) { + case ERROR_INT: + stringBuilder.append(RED.wrap(msg)); + break; + case WARN_INT: + stringBuilder.append(PURPLE.wrap(msg)); + break; + case INFO_INT: + stringBuilder.append(msg); + break; + case DEBUG_INT: + stringBuilder.append(GREEN.wrap(msg)); + break; + case TRACE_INT: + stringBuilder.append(BLUE.wrap(msg)); + break; + default: + return ""; + } + stringBuilder.append(CoreConstants.LINE_SEPARATOR); + return stringBuilder.toString(); + } +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/logback/layout/FrameworkLoggerLayout.java b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/layout/FrameworkLoggerLayout.java new file mode 100644 index 0000000..8190afe --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/layout/FrameworkLoggerLayout.java @@ -0,0 +1,63 @@ +package org.touchbit.buggy.core.logback.layout; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.classic.spi.IThrowableProxy; +import ch.qos.logback.classic.spi.ThrowableProxyUtil; +import ch.qos.logback.core.CoreConstants; +import ch.qos.logback.core.LayoutBase; +import ch.qos.logback.core.util.CachingDateFormatter; +import org.touchbit.buggy.core.utils.ANSI; + +import java.util.Date; + +/** + * File logger layout for framework events (without ANSI colors) + *

+ * Created by Oleg Shaburov on 30.09.2020 + * shaburov.o.a@gmail.com + */ +public class FrameworkLoggerLayout extends LayoutBase { + + private static final CachingDateFormatter TIME_FORMATTER = new CachingDateFormatter("HH:mm:ss.SSS"); + private static final CachingDateFormatter DATE_FORMATTER = new CachingDateFormatter("dd.MM.YYYY"); + + /** + * Print welcome message in the format: 17:28:14.985 INFO - Launch date: 30.09.2020 + */ + @Override + public String getPresentationHeader() { + return getPresentation(); + } + + @Override + public String getPresentationFooter() { + return getPresentation(); + } + + public String getPresentation() { + final long timestamp = new Date().getTime(); + final String time = TIME_FORMATTER.format(timestamp); + final String date = DATE_FORMATTER.format(timestamp); + return time + " INFO - Launch date: " + date; + } + + /** + * Log format: 17:28:15.142 INFO - message\n + */ + @Override + public String doLayout(final ILoggingEvent event) { + final long timestamp = event.getTimeStamp(); + final String message = event.getFormattedMessage(); + final String finalMessage = ANSI.unwrap(message); + final String time = TIME_FORMATTER.format(timestamp); + final Level level = event.getLevel(); + final IThrowableProxy throwableProxy = event.getThrowableProxy(); + String tMsg = ""; + if (throwableProxy != null) { + tMsg = CoreConstants.LINE_SEPARATOR + ThrowableProxyUtil.asString(throwableProxy); + } + return time + " " + level + " - " + finalMessage + tMsg + CoreConstants.LINE_SEPARATOR; + } + +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/logback/layout/ShiftingLoggerLayout.java b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/layout/ShiftingLoggerLayout.java new file mode 100644 index 0000000..898c49b --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/layout/ShiftingLoggerLayout.java @@ -0,0 +1,59 @@ +package org.touchbit.buggy.core.logback.layout; + +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.classic.spi.IThrowableProxy; +import ch.qos.logback.classic.spi.ThrowableProxyUtil; +import ch.qos.logback.core.CoreConstants; +import ch.qos.logback.core.LayoutBase; +import ch.qos.logback.core.util.CachingDateFormatter; + +import java.util.Date; + +/** + * Shofting logger layout for framework events + *

+ * Created by Oleg Shaburov on 30.09.2020 + * shaburov.o.a@gmail.com + */ +public class ShiftingLoggerLayout extends LayoutBase { + + private static final CachingDateFormatter TIME_FORMATTER = new CachingDateFormatter("HH:mm:ss.SSS"); + private static final CachingDateFormatter DATE_FORMATTER = new CachingDateFormatter("dd.MM.YYYY"); + + /** + * Print welcome message in the format: 17:28:14.985 INFO - Launch date: 30.09.2020 + */ + @Override + public String getPresentationHeader() { + return getPresentation(); + } + + @Override + public String getPresentationFooter() { + return getPresentation(); + } + + public String getPresentation() { + final long timestamp = new Date().getTime(); + final String time = TIME_FORMATTER.format(timestamp); + final String date = DATE_FORMATTER.format(timestamp); + return time + " INFO - Launch date: " + date; + } + + /** + * Log format: %d{HH:mm:ss:SSS} %-5level - %msg%n%rEx + * Example: 19:37:00.595 ERROR - Could not find beans of class JCConfiguration in package [null] + * java.lang.IllegalArgumentException: 'value' must not be null + * at org.springframework.util.Assert.notNull(Assert.java:201) + */ + @Override + public String doLayout(final E event) { + final long timestamp = event.getTimeStamp(); + final String message = event.getFormattedMessage(); + final IThrowableProxy tProxy = event.getThrowableProxy(); + return TIME_FORMATTER.format(timestamp) + " " + event.getLevel() + " - " + message + + (tProxy != null ? CoreConstants.LINE_SEPARATOR + ThrowableProxyUtil.asString(tProxy) : "") + + CoreConstants.LINE_SEPARATOR; + } + +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/logback/layout/TestSupervisorLoggerLayout.java b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/layout/TestSupervisorLoggerLayout.java new file mode 100644 index 0000000..c451c28 --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/layout/TestSupervisorLoggerLayout.java @@ -0,0 +1,59 @@ +package org.touchbit.buggy.core.logback.layout; + +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.classic.spi.IThrowableProxy; +import ch.qos.logback.classic.spi.ThrowableProxyUtil; +import ch.qos.logback.core.CoreConstants; +import ch.qos.logback.core.LayoutBase; +import ch.qos.logback.core.util.CachingDateFormatter; + +import java.util.Date; + +/** + * Shofting logger layout for framework events + *

+ * Created by Oleg Shaburov on 30.09.2020 + * shaburov.o.a@gmail.com + */ +public class TestSupervisorLoggerLayout extends LayoutBase { + + private static final CachingDateFormatter TIME_FORMATTER = new CachingDateFormatter("HH:mm:ss.SSS"); + private static final CachingDateFormatter DATE_FORMATTER = new CachingDateFormatter("dd.MM.YYYY"); + + /** + * Print welcome message in the format: 17:28:14.985 INFO - Launch date: 30.09.2020 + */ + @Override + public String getPresentationHeader() { + return getPresentation(); + } + + @Override + public String getPresentationFooter() { + return getPresentation(); + } + + public String getPresentation() { + final long timestamp = new Date().getTime(); + final String time = TIME_FORMATTER.format(timestamp); + final String date = DATE_FORMATTER.format(timestamp); + return time + " INFO - Launch date: " + date; + } + + /** + * Log format: %d{HH:mm:ss:SSS} %-5level - %msg%n%rEx + * Example: 19:37:00.595 ERROR - Could not find beans of class JCConfiguration in package [null] + * java.lang.IllegalArgumentException: 'value' must not be null + * at org.springframework.util.Assert.notNull(Assert.java:201) + */ + @Override + public String doLayout(final E event) { + final long timestamp = event.getTimeStamp(); + final String message = event.getFormattedMessage(); + final IThrowableProxy tProxy = event.getThrowableProxy(); + return TIME_FORMATTER.format(timestamp) + " - " + message + + (tProxy != null ? CoreConstants.LINE_SEPARATOR + ThrowableProxyUtil.asString(tProxy) : "") + + CoreConstants.LINE_SEPARATOR; + } + +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/model/Details.java b/buggy-core/src/main/java/org/touchbit/buggy/core/model/Buggy.java similarity index 60% rename from buggy-core/src/main/java/org/touchbit/buggy/core/model/Details.java rename to buggy-core/src/main/java/org/touchbit/buggy/core/model/Buggy.java index 009cf3a..04a26e2 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/model/Details.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/model/Buggy.java @@ -16,12 +16,14 @@ package org.touchbit.buggy.core.model; +import org.springframework.core.annotation.AliasFor; + import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import static org.touchbit.buggy.core.model.Status.SUCCESS; +import static org.touchbit.buggy.core.model.Status.NONE; /** * Interface of binding test methods. @@ -32,24 +34,42 @@ */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD}) -public @interface Details { +public @interface Buggy { + + @AliasFor("testCase") + String value() default ""; + + @AliasFor("value") + String testCase() default ""; + + /** + * Test-case identifiers + */ + @AliasFor("IDs") + String[] caseIDs() default {""}; - /** Test-case identifiers */ - long[] id() default -1; + @AliasFor("caseIDs") + String[] IDs() default {""}; /** * Test status (see: {@link Status}) * Used values: EXP_IMPL, EXP_FIX, BLOCKED, CORRUPTED */ - Status status() default SUCCESS; + Status status() default NONE; - /** Issues ID in the task-tracker system. Format: "MAPI-269" */ - String[] issue() default {""}; + /** + * Issues ID in the task-tracker system. Format: "STORY-269" + */ + String[] issues() default {}; - /** Defects ID in the task-tracker system. Format: "MAPI-269" */ - String[] bug() default {""}; + /** + * Defects ID in the task-tracker system. Format: "BUG-354" + */ + String[] bugs() default {}; - /** Type of auto test */ - Type type() default Type.MODULE; + /** + * Type of auto test + */ + Type[] types() default {Type.REGRESSION}; } diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/model/IStatus.java b/buggy-core/src/main/java/org/touchbit/buggy/core/model/IStatus.java new file mode 100644 index 0000000..0fec4d6 --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/model/IStatus.java @@ -0,0 +1,7 @@ +package org.touchbit.buggy.core.model; + +public interface IStatus { + + String getStatus(); + +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/model/ParallelMode.java b/buggy-core/src/main/java/org/touchbit/buggy/core/model/ParallelMode.java new file mode 100644 index 0000000..8093f23 --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/model/ParallelMode.java @@ -0,0 +1,24 @@ +package org.touchbit.buggy.core.model; + +import org.testng.xml.XmlSuite; + +public enum ParallelMode { + + TESTS(XmlSuite.ParallelMode.TESTS), + METHODS(XmlSuite.ParallelMode.METHODS), + CLASSES(XmlSuite.ParallelMode.CLASSES), + INSTANCES(XmlSuite.ParallelMode.INSTANCES), + OFF(XmlSuite.ParallelMode.NONE), + ; + + private final XmlSuite.ParallelMode testNGMode; + + ParallelMode(XmlSuite.ParallelMode testNGMode) { + this.testNGMode = testNGMode; + } + + public XmlSuite.ParallelMode getTestNGMode() { + return this.testNGMode; + } + +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/config/SecondaryConfig.java b/buggy-core/src/main/java/org/touchbit/buggy/core/model/ResultStatus.java similarity index 59% rename from buggy-core/src/main/java/org/touchbit/buggy/core/config/SecondaryConfig.java rename to buggy-core/src/main/java/org/touchbit/buggy/core/model/ResultStatus.java index c9d7e39..0eb4c58 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/config/SecondaryConfig.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/model/ResultStatus.java @@ -1,8 +1,12 @@ /* + * Copyright © 2018 Shaburov Oleg + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at + * * http://www.apache.org/licenses/LICENSE-2.0 + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -10,15 +14,30 @@ * limitations under the License. */ -package org.touchbit.buggy.core.config; - -import org.atteo.classindex.IndexSubclasses; +package org.touchbit.buggy.core.model; /** - * Secondary Config for jCommander command block + * Test completion statuses *

- * Created by Oleg Shaburov on 17.05.2018 + * Created by Oleg Shaburov on 16.05.2018 * shaburov.o.a@gmail.com */ -@IndexSubclasses -public interface SecondaryConfig { } +public enum ResultStatus implements IStatus { + + SUCCESS, + FAILED, + CORRUPTED, + BLOCKED, + FIXED, + IMPLEMENTED, + EXP_FIX, + EXP_IMPL, + SKIP, + ; + + @Override + public String getStatus() { + return this.name(); + } + +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/model/Status.java b/buggy-core/src/main/java/org/touchbit/buggy/core/model/Status.java index 9ebce0b..56c35c8 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/model/Status.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/model/Status.java @@ -22,21 +22,18 @@ * Created by Oleg Shaburov on 16.05.2018 * shaburov.o.a@gmail.com */ -public enum Status { +public enum Status implements IStatus { - // Test method statuses EXP_IMPL, EXP_FIX, BLOCKED, CORRUPTED, - - // Result statuses - FIXED, - IMPLEMENTED, - UNTESTED, - SUCCESS, - SKIP, - FAILED, + NONE, ; + @Override + public String getStatus() { + return this.name(); + } + } diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/model/Suite.java b/buggy-core/src/main/java/org/touchbit/buggy/core/model/Suite.java index f5542c5..3e250cd 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/model/Suite.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/model/Suite.java @@ -16,11 +16,12 @@ package org.touchbit.buggy.core.model; -import org.atteo.classindex.IndexAnnotated; -import org.touchbit.buggy.core.process.Component; -import org.touchbit.buggy.core.process.DefaultComponent; -import org.touchbit.buggy.core.process.Interface; -import org.touchbit.buggy.core.process.Service; +import org.touchbit.buggy.core.goal.component.Component; +import org.touchbit.buggy.core.goal.component.DefaultComponent; +import org.touchbit.buggy.core.goal.interfaze.DefaultInterface; +import org.touchbit.buggy.core.goal.interfaze.Interface; +import org.touchbit.buggy.core.goal.service.DefaultService; +import org.touchbit.buggy.core.goal.service.Service; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; @@ -33,19 +34,26 @@ */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) -@IndexAnnotated public @interface Suite { - /** The component to be tested */ + /** + * The component to be tested + */ Class component() default DefaultComponent.class; - /** The test service included in the component */ - Class service(); + /** + * The test service included in the component + */ + Class service() default DefaultService.class; - /** The interface on which the test is performed */ - Class interfaze(); + /** + * The interface on which the test is performed + */ + Class interfaze() default DefaultInterface.class; - /** The task for the tests included in the test class. (example: add_user) */ - String task() default ""; + /** + * The purpose of the tests included in the test class. (example: 'update_user' or 'upload_pdf') + */ + String purpose() default ""; } diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/model/Type.java b/buggy-core/src/main/java/org/touchbit/buggy/core/model/Type.java index 56a03da..2c84d18 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/model/Type.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/model/Type.java @@ -17,35 +17,41 @@ package org.touchbit.buggy.core.model; /** - * Types of autoTests. + * All kinds and levels of testing. + * This enumeration is used to label tests and further filter which tests are run. *

* Created by Oleg Shaburov on 16.05.2018 * shaburov.o.a@gmail.com */ public enum Type { - SMOKE (new Type[]{}), - MODULE (new Type[]{SMOKE}), - INTEGRATION (new Type[]{SMOKE, MODULE}), - SYSTEM (new Type[]{SMOKE, MODULE, INTEGRATION}), + FUNCTIONAL, + SECURITY, + INTEROPERABILITY, + LOAD, + PERFORMANCE, + STRESS, + VOLUME, + STABILITY, + SMOKE, + BUILD, + SANITY, + REGRESSION, + USABILITY, + FAILOVER_AND_RECOVERY, + CONFIGURATION, + INSTALLATION, + UNIT, + MODULE, + INTEGRATION, + COMPATIBILITY, + SYSTEM, + ACCEPTANCE, + // Helper type for filtering. + SLOW, + NORMAL, + FAST, + ALL, ; - private Type[] innerTypes; - - Type(Type[] priority) { - this.innerTypes = priority; - } - - public boolean isIncludeOrEquals(Type type) { - if (this.equals(type)) { - return true; - } - for (Type innerType : innerTypes) { - if (innerType.equals(type)) { - return true; - } - } - return false; - } - } diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/snakeyaml/BuggyYamlPropertyUtils.java b/buggy-core/src/main/java/org/touchbit/buggy/core/snakeyaml/BuggyYamlPropertyUtils.java new file mode 100644 index 0000000..313e74c --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/snakeyaml/BuggyYamlPropertyUtils.java @@ -0,0 +1,39 @@ +package org.touchbit.buggy.core.snakeyaml; + +import org.touchbit.buggy.core.exceptions.BuggyConfigurationException; +import org.yaml.snakeyaml.introspector.BeanAccess; +import org.yaml.snakeyaml.introspector.FieldProperty; +import org.yaml.snakeyaml.introspector.Property; +import org.yaml.snakeyaml.introspector.PropertyUtils; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * Allow + *

+ * Created by Oleg Shaburov on 10.10.2020 + * shaburov.o.a@gmail.com + */ +public class BuggyYamlPropertyUtils extends PropertyUtils { + + protected Map getPropertiesMap(Class type, BeanAccess bAccess) { + Map properties = new LinkedHashMap(); + if (bAccess == BeanAccess.FIELD) { + for (Class c = type; c != null; c = c.getSuperclass()) { + for (Field field : c.getDeclaredFields()) { + int modifiers = field.getModifiers(); + if (!Modifier.isTransient(modifiers) && !properties.containsKey(field.getName())) { + properties.put(field.getName(), new FieldProperty(field)); + } + } + } + } else { + throw new BuggyConfigurationException("Supported only BeanAccess.FIELD"); + } + return properties; + } + +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/test/TRProperty.java b/buggy-core/src/main/java/org/touchbit/buggy/core/test/TRProperty.java deleted file mode 100644 index f90915e..0000000 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/test/TRProperty.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.touchbit.buggy.core.test; - -/** - * Created by Oleg Shaburov on 13.01.2019 - * shaburov.o.a@gmail.com - */ -public enum TRProperty { - - RUN_ID ("testrail.run.id") - ; - - private String property; - - TRProperty(String property) { - this.property = property; - } - - @Override - public String toString() { - return property; - } - -} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/test/TestRailTest.java b/buggy-core/src/main/java/org/touchbit/buggy/core/test/TestRailTest.java deleted file mode 100644 index f788e6f..0000000 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/test/TestRailTest.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.touchbit.buggy.core.test; - -import static org.touchbit.buggy.core.test.TRProperty.RUN_ID; - -/** - * Created by Oleg Shaburov on 12.01.2019 - * shaburov.o.a@gmail.com - */ -public interface TestRailTest { - - long getRunId(); - - default void setRunId() { - if (getRunId() > 0) { - System.setProperty(RUN_ID.toString(), String.valueOf(getRunId())); - } - } - -} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/testng/BaseBuggyExecutionListener.java b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/BaseBuggyExecutionListener.java new file mode 100644 index 0000000..9a28370 --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/BaseBuggyExecutionListener.java @@ -0,0 +1,53 @@ +/* + * Copyright © 2018 Shaburov Oleg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.touchbit.buggy.core.testng; + +import org.slf4j.Logger; +import org.testng.IExecutionListener; +import org.touchbit.buggy.core.logback.ConsoleLogger; +import org.touchbit.buggy.core.logback.FrameworkLogger; +import org.touchbit.buggy.core.logback.SiftingTestLogger; +import org.touchbit.buggy.core.model.Buggy; + +import java.util.Arrays; +import java.util.StringJoiner; + +/** + * Created by Oleg Shaburov on 16.05.2018 + * shaburov.o.a@gmail.com + */ +@SuppressWarnings("WeakerAccess") +public abstract class BaseBuggyExecutionListener implements BuggyListener, IExecutionListener { + + protected Logger testLog; + protected Logger frameworkLog; + protected Logger consoleLog; + + @Override + public void onExecutionStart() { + if (testLog == null) { + testLog = new SiftingTestLogger(); + } + if (frameworkLog == null) { + frameworkLog = new FrameworkLogger(); + } + if (consoleLog == null) { + consoleLog = new ConsoleLogger(); + } + } + +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/testng/BaseTelegramNotifier.java b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/BaseTelegramNotifier.java new file mode 100644 index 0000000..675ce15 --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/BaseTelegramNotifier.java @@ -0,0 +1,120 @@ +/* + * Copyright © 2018 Shaburov Oleg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.touchbit.buggy.core.testng; + +import org.testng.IExecutionListener; +import org.touchbit.buggy.core.model.Notifier; + +/** + * Created by Oleg Shaburov on 06.09.2018 + * shaburov.o.a@gmail.com + */ +@SuppressWarnings({"unused", "squid:S2629"}) +public abstract class BaseTelegramNotifier extends BaseBuggyExecutionListener implements IExecutionListener { + + private final Notifier notifier; + + @SuppressWarnings("WeakerAccess") + public BaseTelegramNotifier(final Notifier notifier) { + this.notifier = notifier; + } + + @Override + public void onExecutionStart() { + } +// +// @Override +// public void onExecutionFinish() { +// if (isEnable()) { +// telegramResultNotification(); +// } +// } +// +// private void telegramResultNotification() { +// String name = BuggyConfig.getProgramName(); +// StringJoiner sj; +// if (name == null || name.isEmpty()) { +// sj = new StringJoiner("\n", "Run Results:\n", "\n"); +// } else { +// sj = new StringJoiner("\n", "*" + name + "*\nRun Results:\n", "\n"); +// } +// int len = 33; +// int errorCount = expFixError.get() + expImplError.get() + newError.get() + +// corruptedError.get() + blockedError.get(); +// int testCountLen = testCount.toString().length(); +// int fullLen = len + testCountLen; +// sj.add(StringUtils.filler("`", "-", fullLen, "`")); +// int runningLen = len + testCountLen - testCount.toString().length(); +// sj.add(StringUtils.dotFiller("`Running tests", runningLen, "`") + testCount.get()); +// sj.add(StringUtils.filler("`", "-", fullLen, "`")); +// int successfulLen = len + testCountLen - (String.valueOf(testCount.get() - errorCount)).length(); +// sj.add(StringUtils.dotFiller("`Successful tests", successfulLen, "`") + +// (testCount.get() - errorCount)); +// sj.add(StringUtils.dotFiller("`Skipped tests", successfulLen, "`") + (skippedTests.get())); +// int failedLen = len + testCountLen - (String.valueOf(errorCount)).length(); +// sj.add(StringUtils.dotFiller("`Failed tests", failedLen, "`") + errorCount); +// sj.add(StringUtils.filler("`", "-", fullLen, "`")); +// int newErrorsLen = len + testCountLen - newError.toString().length(); +// sj.add(StringUtils.dotFiller("`New Errors", newErrorsLen, "`") + +// wrapErrorsMDLink(newError.get(), "new/")); +// int waitFixLen = len + testCountLen - expFixError.toString().length(); +// sj.add(StringUtils.dotFiller("`Waiting to fix a defect", waitFixLen, "`") + +// wrapErrorsMDLink(expFixError.get(), "exp_fix/")); +// int waitImplLen = len + testCountLen - expImplError.toString().length(); +// sj.add(StringUtils.dotFiller("`Waiting for the implementation", waitImplLen, "`") + +// wrapErrorsMDLink(expImplError.get(), "exp_impl/")); +// int blockedLen = len + testCountLen - blockedError.toString().length(); +// sj.add(StringUtils.dotFiller("`Blocked tests", blockedLen, "`") + +// wrapErrorsMDLink(blockedError.get(), "blocked/")); +// int corruptedLen = len + testCountLen - corruptedError.toString().length(); +// sj.add(StringUtils.dotFiller("`Corrupted tests", corruptedLen, "`") + +// wrapErrorsMDLink(corruptedError.get(), "corrupted/")); +// sj.add(StringUtils.filler("`", "-", fullLen, "`")); +// int fixedLen = len + testCountLen - fixed.toString().length(); +// sj.add(StringUtils.dotFiller("`Fixed defects", fixedLen, "`") + +// wrapFixedMDLink(fixed.get(), "exp_fix/")); +// int implementedLen = len + testCountLen - implemented.toString().length(); +// sj.add(StringUtils.dotFiller("`Implemented cases", implementedLen, "`") + +// wrapFixedMDLink(implemented.get(), "exp_impl/")); +// sj.add(StringUtils.filler("`", "-", fullLen, "`")); +// String date = DurationFormatUtils.formatDuration(finishTime - startTime, "HH:mm:ss"); +// sj.add("Test execution time: *" + date + "*"); +// sj.add("[Logs](" + BuggyConfig.getArtifactsUrl() + ")"); +// try { +// notifier.report(sj.toString()); +// } catch (Exception e) { +//// BuggyLoggers.CONSOLE.error("Failed to send message to Telegram.", e); TODO +// } +// } +// +// private String wrapErrorsMDLink(Integer value, String subLink) { +// String artifactLogPath = BuggyConfig.getArtifactsUrl() + "/errors/" + subLink; +// if (value > 0) { +// return "[" + value + "](" + artifactLogPath + ")"; +// } +// return String.valueOf(value); +// } +// +// private String wrapFixedMDLink(Integer value, String subLink) { +// String artifactLogPath = BuggyConfig.getArtifactsUrl() + "/fixed/" + subLink; +// if (value > 0) { +// return "[" + value + "](" + artifactLogPath + ")"; +// } +// return String.valueOf(value); +// } + +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/testng/BuggyExecutionListener.java b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/BuggyExecutionListener.java new file mode 100644 index 0000000..4b6b7fb --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/BuggyExecutionListener.java @@ -0,0 +1,291 @@ +/* + * Copyright © 2018 Shaburov Oleg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.touchbit.buggy.core.testng; + +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; +import org.testng.*; +import org.touchbit.buggy.core.config.BuggyConfigurationYML; +import org.touchbit.buggy.core.model.Buggy; +import org.touchbit.buggy.core.model.Type; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Array; +import java.util.*; + +/** + * Listener for processing executable tests. + *

+ * Created by Shaburov Oleg on 31.07.2017. + */ +@SuppressWarnings({"unused", "UnusedReturnValue", "squid:S2629"}) +public abstract class BuggyExecutionListener extends BaseBuggyExecutionListener + implements IExecutionListener, IInvokedMethodListener, ISuiteListener, ITestListener, IClassListener { + + public BuggyExecutionListener() { + } + + public BuggyExecutionListener(Logger testLogger, Logger frameworkLogger, Logger consoleLogger) { +// testLog = testLogger; +// frameworkLog = frameworkLogger; +// consoleLog = consoleLogger; + } + + @Override + public boolean isEnable() { + return true; + } + + @Override + public void onExecutionStart() { + super.onExecutionStart(); + consoleLog.info(""); + } + + @Override + public void onExecutionFinish() { + super.onExecutionFinish(); +// printTestStatistic(); + } +// +// @Override +// public void onTestSuccess(ITestResult result) { +// onTestFinish(result); +// } +// +// @Override +// public void onTestFailure(ITestResult result) { +// onTestFinish(result); +// } +// +// @Override +// public void onTestSkipped(ITestResult result) { +// onTestFinish(result); +// } +// +// @Override +// public void onTestFailedButWithinSuccessPercentage(ITestResult result) { +// onTestFinish(result); +// } +// +// public void onTestFinish(ITestResult result) { +// Method method = getRealMethod(result); +// Throwable t = result.getThrowable(); +// if ((t != null && t.getClass().getName().contains("ExpectedImplementationException"))) { +// return; +// } +// if (result.getStatus() == ITestResult.SKIP) { +// testLog.warn("The test {} is skipped.", method.getName()); +// return; +// } +// if (!getSteps().isEmpty()) { +// StringBuilder sb = new StringBuilder(); +// getSteps().forEach(step -> sb.append(step).append("\n")); +// testLog.info("Steps:\n{}", sb); +// } else { +//// Buggy.incrementBuggyWarns(); +// frameworkLog.warn("There are no playback steps in the test method {}", method.getName()); +// } +// testLog.info("Date: {}", new Date()); +// } +// +// @Override +// public void onAfterClass(ITestClass iTestClass) { +// if (getSuite(iTestClass) == null) { +//// Buggy.incrementBuggyErrors(); +// frameworkLog.error("There is no @Suite annotation for the test class: {}", iTestClass.getName()); +// } +// } +// + @Override + public void onStart(ISuite suite) { + disableTestsByType(suite); + if (!BuggyConfigurationYML.isForceRun()) { + disableTestsByStatus(suite); + } + } +// +// public void processTestMethodResult(IInvokedMethod m, ITestResult testResult, Details details) { +// ITestNGMethod method = m.getTestMethod(); +// switch (testResult.getStatus()) { +// case SUCCESS: +// switch (details.status()) { +// case BLOCKED: +// case EXP_FIX: +// resultLog(method, Status.FIXED, buildDetailsMessage(details)); +// break; +// case EXP_IMPL: +// resultLog(method, Status.IMPLEMENTED, buildDetailsMessage(details)); +// break; +// case CORRUPTED: +// resultLog(method, Status.CORRUPTED, buildDetailsMessage(details)); +// testResult.setThrowable(new CorruptedTestException()); +// break; +// default: +// resultLog(method, Status.SUCCESS, buildDetailsMessage(details)); +// } +// break; +// case SUCCESS_PERCENTAGE_FAILURE: +// case FAILURE: +// switch (details.status()) { +// case CORRUPTED: +// resultLog(method, Status.CORRUPTED, buildDetailsMessage(details)); +// testResult.setThrowable(new CorruptedTestException()); +// break; +// case EXP_FIX: +// resultLog(method, Status.EXP_FIX, buildDetailsMessage(details)); +// break; +// case EXP_IMPL: +// resultLog(method, Status.EXP_IMPL, buildDetailsMessage(details)); +// break; +// case BLOCKED: +// resultLog(method, Status.BLOCKED, buildDetailsMessage(details)); +// break; +// default: +// resultLog(method, Status.FAILED, buildDetailsMessage(details)); +// } +// break; +// case SKIP: +// resultLog(method, Status.SKIP, buildDetailsMessage(details)); +// break; +// default: +// frameworkLog.error("Received unprocessed status: {}", testResult.getStatus()); +//// Buggy.incrementBuggyErrors(); +// } +// } +// +// public void processConfigurationMethodResult(IInvokedMethod method, ITestResult testResult) { +// String methodName = getMethodName(method); +// String description = getDescription(method); +// switch (testResult.getStatus()) { +// case SUCCESS: +// testLog.info("Invoke configuration method [{}] completed successfully", methodName); +// break; +// case SKIP: +// testLog.warn("Invoke configuration method [{}] skipped. " + +// "List of dependent tests that were missed: {}", methodName, description); +// break; +// case SUCCESS_PERCENTAGE_FAILURE: +// case FAILURE: +// testLog.error("Invoke configuration method [{}] completed with error \n{}", +// methodName, testResult.getThrowable().getMessage()); +// break; +// default: +//// Buggy.incrementBuggyErrors(); +// frameworkLog.error("Received unresolved status of configuration method [{}]. Status: {}", +// methodName, testResult.getStatus()); +// } +// } +// + public void disableTestsByStatus(ISuite suite) { + suite.getAllMethods().forEach(method -> { + Buggy details = getBuggyAnnotation(method); + if (details != null) { + if (method.getInvocationCount() > 0) { + switch (details.status()) { + case EXP_FIX: + case EXP_IMPL: + case BLOCKED: + case CORRUPTED: + System.out.println(" >>>> disableTestsByStatus : " + method.getMethodName() + ": " + details.status()); + method.setInvocationCount(0); + break; + default: + // do nothing + } + } + } else { +// Buggy.incrementBuggyWarns(); + frameworkLog.warn("The test method {} does not contain the @Details annotation", + method.getMethodName()); + } + }); + } + + public void disableTestsByType(final ISuite suite) { + final List methods = suite.getAllMethods(); + methods.forEach(method -> { + Buggy details = getBuggyAnnotation(method); + Type[] types = BuggyConfigurationYML.getTypes(); + Set configType = new HashSet<>(Arrays.asList(types)); + if (details != null) { + List methodTypes = new ArrayList<>(Arrays.asList(details.types())); + boolean matched = methodTypes.stream().anyMatch(configType::contains); + if (!configType.contains(Type.ALL) && !matched) { + System.out.println(" >>>> disableTestsByStatus : " + method.getMethodName() + ": " + methodTypes); + method.setInvocationCount(0); + } + } + }); + } +// +// public void resultLog(ITestNGMethod method, Status status, String details) { +// String methodName = method.getMethodName(); +// Suite suite = getSuite(method); +// String statusName = status.name(); +// StringJoiner resultMsg = new StringJoiner(" "); +// if (BuggyConfig.isPrintSuite()) { +// StringJoiner sj = new StringJoiner(" ", " [", "]"); +// sj.add(JUtils.getGoal(Suite::component, suite).getName().trim()); +// sj.add(JUtils.getGoal(Suite::service, suite).getName().trim()); +// sj.add(JUtils.getGoal(Suite::interfaze, suite).getName().trim()); +// sj.add(suite.purpose().trim()); +// resultMsg.add(sj.toString().trim()); +// } +// testLog.info("{} - {} {}", methodName, statusName, method.getDescription()); +// String detailsString = details.trim(); +// if ((BuggyConfig.isPrintCause() || method.getInvocationCount() < 1) && !detailsString.isEmpty()) { +// resultMsg.add(detailsString); +// } +// String logPathString = getLogFilePath(method, status).trim(); +// if (BuggyConfig.isPrintLog() && method.getInvocationCount() > 0 && !logPathString.isEmpty() && +// (!BuggyConfig.isPrintLogFileOnlyFail() || status != Status.SUCCESS)) { +// resultMsg.add("\n └"); +// resultMsg.add(logPathString); +// } +// printASCIIStatus(status, StringUtils.dotFiller(methodName, 47, statusName) + +// (resultMsg.length() > 0 ? " " + resultMsg.toString().trim() : "")); +// } +// +// protected void printASCIIStatus(Status status, String msg) { +// switch (status) { +// case FAILED: +// case CORRUPTED: +// consoleLog.error(msg); +// break; +// case EXP_IMPL: +// case EXP_FIX: +// case BLOCKED: +// case SKIP: +// consoleLog.warn(msg); +// break; +// case IMPLEMENTED: +// case FIXED: +// consoleLog.debug(msg); +// break; +// default: +// consoleLog.info(msg); +// } +// } +// +// +// +// protected void copyFile(File sourceFile, File destFile) throws IOException { +// IOHelper.copyFile(sourceFile, destFile); +// } + +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/testng/BuggyListener.java b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/BuggyListener.java new file mode 100644 index 0000000..5073ce4 --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/BuggyListener.java @@ -0,0 +1,424 @@ +package org.touchbit.buggy.core.testng; + +import org.jetbrains.annotations.Nullable; +import org.testng.*; +import org.touchbit.buggy.core.config.BuggyConfigurationYML; +import org.touchbit.buggy.core.logback.SiftingTestLogger; +import org.touchbit.buggy.core.model.*; + +import java.io.File; +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.function.Function; + +import static org.touchbit.buggy.core.model.Status.*; + +/** + * Created by Oleg Shaburov on 28.05.2018 + * shaburov.o.a@gmail.com + */ +public interface BuggyListener extends ITestNGListener { + + boolean isEnable(); + + default boolean isRun(IInvokedMethod method) { + assertNotNull(method); + return isRun(method.getTestMethod()); + } + + default boolean isRun(ITestNGMethod method) { + assertNotNull(method); + return method.getInvocationCount() > 0; + } + + default boolean isSkip(IInvokedMethod method) { + assertNotNull(method); + if (isRun(method)) { + return false; + } + return isSkip(method.getTestResult()); + } + + default boolean isSkip(ITestNGMethod method) { + assertNotNull(method); + return !isRun(method); + } + + default boolean isSkip(ITestResult result) { + assertNotNull(result); + return isITestResultSkip(result); + } + + default boolean isSkipByTestStatus(ITestNGMethod method) { + assertNotNull(method); + Buggy buggy = getBuggyAnnotation(method); + if (buggy != null && !buggy.status().equals(Status.NONE) && !BuggyConfigurationYML.isForceRun()) { + return true; + } + return false; + } + + default boolean isSkipByType(IInvokedMethod method) { + assertNotNull(method); + return isSkipByType(method.getTestMethod()); + } + + default boolean isSkipByType(ITestNGMethod method) { + assertNotNull(method); + Buggy buggyAnnotation = getBuggyAnnotation(method); + if (buggyAnnotation == null) { + return false; + } + Type[] types = BuggyConfigurationYML.getTypes(); + Set configTypes = new HashSet<>(Arrays.asList(types)); + if (configTypes.contains(Type.ALL)) { + return false; + } + for (Type type : types) { + System.out.println(" >>>>>>>>> " + type + " >> " + type.getClass()); + } + boolean contains = false; + for (Type type : buggyAnnotation.types()) { + if (configTypes.contains(type)) { + contains = true; + break; + } + } + return !contains; + } + + default boolean isSuccess(IInvokedMethod method) { + assertNotNull(method); + if (!hasBuggyAnnotation(method)) { + return isITestResultSuccess(method); + } + Status status = getDetailsValue(Buggy::status, method); + return status.equals(NONE) && isITestResultSuccess(method); + } + + default boolean isNewError(IInvokedMethod method) { + assertNotNull(method); + if (!hasBuggyAnnotation(method)) { + return isITestResultFailure(method); + } + Status status = getDetailsValue(Buggy::status, method); + return status.equals(NONE) && isITestResultFailure(method); + } + + default boolean isFixed(IInvokedMethod method) { + assertNotNull(method); + if (!hasBuggyAnnotation(method)) { + return false; + } + Status status = getDetailsValue(Buggy::status, method); + return (status.equals(EXP_FIX) || status.equals(BLOCKED) || status.equals(CORRUPTED)) && + isITestResultSuccess(method); + } + + default boolean isImplemented(IInvokedMethod method) { + assertNotNull(method); + if (!hasBuggyAnnotation(method)) { + return false; + } + Status status = getDetailsValue(Buggy::status, method); + return status.equals(EXP_IMPL) && isITestResultSuccess(method); + } + + default boolean isExpectedImplementation(IInvokedMethod method) { + assertNotNull(method); + if (!hasBuggyAnnotation(method)) { + return false; + } + Status status = getDetailsValue(Buggy::status, method); + return status.equals(EXP_IMPL) && isITestResultFailure(method); + } + + default boolean isExpectedFix(IInvokedMethod method) { + assertNotNull(method); + if (!hasBuggyAnnotation(method)) { + return false; + } + Status status = getDetailsValue(Buggy::status, method); + return status.equals(EXP_FIX) && isITestResultFailure(method); + } + + default boolean isCorrupted(IInvokedMethod method) { + assertNotNull(method); + if (!hasBuggyAnnotation(method)) { + return false; + } + Status status = getDetailsValue(Buggy::status, method); + return status.equals(CORRUPTED) && isITestResultFailure(method); + } + + default boolean isBlocked(IInvokedMethod method) { + assertNotNull(method); + if (!hasBuggyAnnotation(method)) { + return false; + } + Status status = getDetailsValue(Buggy::status, method); + return status.equals(BLOCKED) && isITestResultFailure(method); + } + + default ResultStatus getResultStatus(IInvokedMethod method) { + if (isSkip(method)) { + return ResultStatus.SKIP; + } + if (isSuccess(method)) { + return ResultStatus.SUCCESS; + } + if (isNewError(method)) { + return ResultStatus.FAILED; + } + if (isImplemented(method)) { + return ResultStatus.IMPLEMENTED; + } + if (isFixed(method)) { + return ResultStatus.FIXED; + } + if (isExpectedImplementation(method)) { + return ResultStatus.EXP_IMPL; + } + if (isExpectedFix(method)) { + return ResultStatus.EXP_FIX; + } + if (isCorrupted(method)) { + return ResultStatus.CORRUPTED; + } + if (isBlocked(method)) { + return ResultStatus.BLOCKED; + } + return ResultStatus.FAILED; + } + + default boolean isITestResultSuccess(IInvokedMethod method) { + assertNotNull(method); + return isITestResultSuccess(method.getTestResult()); + } + + default boolean isITestResultSuccess(ITestResult testResult) { + assertNotNull(testResult); + int status = testResult.getStatus(); + return status == ITestResult.SUCCESS; + } + + default boolean isITestResultFailure(IInvokedMethod method) { + assertNotNull(method); + return isITestResultFailure(method.getTestResult()); + } + + + default boolean isITestResultFailure(ITestResult result) { + assertNotNull(result); + int iTestResult = getITestResultStatus(result); + return iTestResult == ITestResult.FAILURE || iTestResult == ITestResult.SUCCESS_PERCENTAGE_FAILURE; + } + + default boolean isITestResultSkip(IInvokedMethod method) { + assertNotNull(method); + return isITestResultSkip(method.getTestResult()); + } + + default boolean isITestResultSkip(ITestResult result) { + assertNotNull(result); + int iTestResult = getITestResultStatus(result); + return iTestResult == ITestResult.SKIP; + } + + default T getDetailsValue(Function function, IInvokedMethod method) { + assertNotNull(method); + Buggy buggy = getBuggyAnnotation(method); + return getDetailsValue(function, buggy); + } + + default T getDetailsValue(Function function, Buggy buggy) { + assertNotNull(buggy); + return function.apply(buggy); + } + + default int getITestResultStatus(ITestResult iTestResult) { + assertNotNull(iTestResult); + return iTestResult.getStatus(); + } + + default boolean hasDescription(IInvokedMethod method) { + if (method == null) { + return false; + } + return hasDescription(method.getTestMethod()); + } + + default boolean hasDescription(ITestNGMethod method) { + if (method == null) { + return false; + } + String description = method.getDescription(); + if (description != null && !description.isEmpty()) { + return true; + } + if (hasBuggyAnnotation(method)) { + Buggy buggyAnnotation = getBuggyAnnotation(method); + //noinspection ConstantConditions + String testCase = buggyAnnotation.testCase(); + return !testCase.isEmpty(); + } + return false; + } + + default String getDescription(IInvokedMethod method) { + if (hasDescription(method)) { + return getDescription(method.getTestMethod()); + } + return ""; + } + + default String getDescription(ITestNGMethod method) { + if (hasDescription(method)) { + String description = method.getDescription(); + if (description != null && !description.isEmpty()) { + return description; + } + //noinspection ConstantConditions + return getBuggyAnnotation(method).testCase(); + } + return ""; + } + + default boolean hasBuggyAnnotation(IInvokedMethod method) { + if (method != null) { + return hasBuggyAnnotation(method.getTestMethod()); + } + return false; + } + + default boolean hasBuggyAnnotation(ITestNGMethod method) { + if (method != null) { + return hasBuggyAnnotation(method.getConstructorOrMethod().getMethod()); + } + return false; + } + + default boolean hasBuggyAnnotation(Method method) { + if (method != null) { + return method.isAnnotationPresent(Buggy.class); + } + return false; + } + + @Nullable + default Buggy getBuggyAnnotation(IInvokedMethod method) { + if (hasBuggyAnnotation(method)) { + return getBuggyAnnotation(method.getTestMethod()); + } + return null; + } + + @Nullable + default Buggy getBuggyAnnotation(ITestNGMethod method) { + if (hasBuggyAnnotation(method)) { + return getBuggyAnnotation(method.getConstructorOrMethod().getMethod()); + } + return null; + } + + @Nullable + default Buggy getBuggyAnnotation(Method method) { + if (hasBuggyAnnotation(method)) { + return method.getAnnotation(Buggy.class); + } + return null; + } + + default boolean hasSuiteAnnotation(IInvokedMethod method) { + if (method != null) { + return hasSuiteAnnotation(method.getTestMethod()); + } + return false; + } + + default boolean hasSuiteAnnotation(ITestClass iTestClass) { + if (iTestClass != null) { + return hasSuiteAnnotation(iTestClass.getRealClass()); + } + return false; + } + + default boolean hasSuiteAnnotation(ITestNGMethod method) { + if (method != null) { + return hasSuiteAnnotation(method.getRealClass()); + } + return false; + } + + default boolean hasSuiteAnnotation(Class realClass) { + return realClass.isAnnotationPresent(Suite.class); + } + + @Nullable + default Suite getSuiteAnnotation(IInvokedMethod method) { + if (hasSuiteAnnotation(method)) { + return getSuiteAnnotation(method.getTestMethod()); + } + return null; + } + + @Nullable + default Suite getSuiteAnnotation(ITestClass iTestClass) { + if (hasSuiteAnnotation(iTestClass)) { + return getSuiteAnnotation(iTestClass.getRealClass()); + } + return null; + } + + @Nullable + default Suite getSuiteAnnotation(ITestNGMethod method) { + if (hasSuiteAnnotation(method)) { + return getSuiteAnnotation(method.getRealClass()); + } + return null; + } + + @Nullable + default Suite getSuiteAnnotation(Class realClass) { + if (hasSuiteAnnotation(realClass)) { + return realClass.getAnnotation(Suite.class); + } + return null; + } + + default void assertNotNull(Object o) { + if (o == null) { + throw new NullPointerException(); + } + } + + default String getMethodName(IInvokedMethod method) { + assertNotNull(method); + return method.getTestMethod().getMethodName(); + } + + default Method getRealMethod(ITestResult result) { + assertNotNull(result); + return getRealMethod(result.getMethod()); + } + + default Method getRealMethod(IInvokedMethod method) { + assertNotNull(method); + return getRealMethod(method.getTestMethod()); + } + + default Method getRealMethod(ITestNGMethod method) { + assertNotNull(method); + return method.getConstructorOrMethod().getMethod(); + } + + + default String getClassSimpleName(IInvokedMethod method) { + assertNotNull(method); + return method.getTestMethod().getRealClass().getSimpleName(); + } + +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/testng/ExecutionListenerBase.java b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/ExecutionListenerBase.java new file mode 100644 index 0000000..75c0315 --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/ExecutionListenerBase.java @@ -0,0 +1,48 @@ +/* + * Copyright © 2018 Shaburov Oleg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.touchbit.buggy.core.testng; + +import org.testng.*; + +/** + * Listener for processing executable tests. + *

+ * Created by Shaburov Oleg on 31.07.2017. + */ +@SuppressWarnings({"unused", "UnusedReturnValue", "squid:S2629"}) +public abstract class ExecutionListenerBase implements BuggyListener, ISuiteListener { + + @Override + public void onStart(ISuite suite) { + suite.getAllMethods().forEach(this::disableTestsByType); + suite.getAllMethods().forEach(this::disableByTestStatus); + } + + private void disableTestsByType(ITestNGMethod method) { + System.out.println(" >>>>>>>>>> " + isSkipByType(method)); + if (isSkipByType(method)) { + method.setInvocationCount(0); + } + } + + public void disableByTestStatus(ITestNGMethod method) { + if (isSkipByTestStatus(method)) { + method.setInvocationCount(0); + } + } + +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/testng/IntellijIdeaTestNgPluginListener.java b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/IntellijIdeaTestNgPluginListener.java new file mode 100644 index 0000000..190d687 --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/IntellijIdeaTestNgPluginListener.java @@ -0,0 +1,58 @@ +/* + * Copyright © 2018 Shaburov Oleg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.touchbit.buggy.core.testng; + +import org.testng.IInvokedMethod; +import org.testng.ITestResult; +import org.touchbit.buggy.core.config.BuggyConfigurationYML; +import org.touchbit.buggy.core.config.ConfigurationYML; +import org.touchbit.buggy.core.utils.JUtils; + +/** + * Intellij IDEA TestNG Plugin Listener + *

+ * Created by Oleg Shaburov on 15.05.2018 + * shaburov.o.a@gmail.com + */ +public final class IntellijIdeaTestNgPluginListener extends LoggingListenerBase { + + public IntellijIdeaTestNgPluginListener() { + if (JUtils.isJetBrainsIdeTestNGPluginRun()) { + ConfigurationYML.initConfigurationYml(BuggyConfigurationYML.class); + } + } + + @Override + public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { + if (JUtils.isJetBrainsIdeTestNGPluginRun()) { + super.beforeInvocation(method, testResult); + } + } + + @Override + public void afterInvocation(IInvokedMethod method, ITestResult testResult) { + if (JUtils.isJetBrainsIdeTestNGPluginRun()) { + super.afterInvocation(method, testResult); + } + } + + @Override + public final boolean isEnable() { + return JUtils.isJetBrainsIdeTestNGPluginRun(); + } + +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/testng/LoggingListenerBase.java b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/LoggingListenerBase.java new file mode 100644 index 0000000..76a8f0a --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/LoggingListenerBase.java @@ -0,0 +1,216 @@ +/* + * Copyright © 2018 Shaburov Oleg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.touchbit.buggy.core.testng; + +import org.testng.*; +import org.touchbit.buggy.core.config.BuggyConfigurationYML; +import org.touchbit.buggy.core.config.OutputRule; +import org.touchbit.buggy.core.logback.ConfLogger; +import org.touchbit.buggy.core.logback.SiftingTestLogger; +import org.touchbit.buggy.core.model.*; +import org.touchbit.buggy.core.utils.ANSI; +import org.touchbit.buggy.core.utils.JUtils; + +import java.io.File; +import java.lang.reflect.Method; +import java.util.*; + +import static org.touchbit.buggy.core.model.ResultStatus.SKIP; +import static org.touchbit.buggy.core.model.ResultStatus.SUCCESS; +import static org.touchbit.buggy.core.utils.ANSI.*; + +/** + * Listener for processing executable tests. + *

+ * Created by Shaburov Oleg on 31.07.2017. + */ +public abstract class LoggingListenerBase implements BuggyListener, IInvokedMethodListener, ISuiteListener { + + protected static final SiftingTestLogger TEST = new SiftingTestLogger(); + + protected static final Set DISABLED_METHODS = new HashSet<>(); + + @Override + public void onStart(ISuite suite) { + suite.getAllMethods().forEach(this::skippedTestsByType); + suite.getAllMethods().forEach(this::skippedByTestStatus); + suite.getAllMethods().forEach(this::skippedByTestAnnotation); + } + + protected void skippedTestsByType(ITestNGMethod method) { + if (isSkipByType(method) && !DISABLED_METHODS.contains(method)) { + DISABLED_METHODS.add(method); + String placeholder = ConfLogger.getDotPlaceholder(method.getMethodName(), SKIP); + String msg = YELLOW.wrap(placeholder); + Buggy buggy = getBuggyAnnotation(method); + msg += " by test types: " + Arrays.toString(Objects.requireNonNull(buggy).types()); + ConfLogger.info(msg); + } + } + + protected void skippedByTestStatus(ITestNGMethod method) { + if (isSkipByTestStatus(method) && !DISABLED_METHODS.contains(method)) { + DISABLED_METHODS.add(method); + String placeholder = ConfLogger.getDotPlaceholder(method.getMethodName(), SKIP); + String msg = YELLOW.wrap(placeholder); + Buggy buggy = getBuggyAnnotation(method); + msg += " by status: " + Objects.requireNonNull(buggy).status(); + ConfLogger.info(msg); + } + } + + protected void skippedByTestAnnotation(ITestNGMethod method) { + assertNotNull(method); + if (!method.getEnabled()) { + String placeholder = ConfLogger.getDotPlaceholder(method.getMethodName(), SKIP); + String msg = YELLOW.wrap(placeholder); + msg += " by @Test annotation."; + ConfLogger.info(msg); + } + } + + @Override + public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { + SiftingTestLogger.setTestLogFileName(method); + } + + @Override + public void afterInvocation(IInvokedMethod method, ITestResult testResult) { + TEST.steps(); + ResultStatus resultStatus = getResultStatus(method); + SiftingTestLogger.setTestResultStatus(resultStatus); + String methodName = getMethodName(method); + Throwable throwable = testResult.getThrowable(); + if (throwable != null) { + TEST.error("{}: {}", throwable.getClass().getSimpleName(), throwable.getMessage()); + } + if (hasBuggyAnnotation(method) && hasSuiteAnnotation(method) && method.isTestMethod()) { + Buggy buggy = getBuggyAnnotation(method); + Suite suite = getSuiteAnnotation(method); + String component = JUtils.getGoal(Suite::component, suite).getName().trim(); + String service = JUtils.getGoal(Suite::service, suite).getName().trim(); + String interfaze = JUtils.getGoal(Suite::interfaze, suite).getName().trim(); + //noinspection ConstantConditions + String purpose = suite.purpose().trim(); + //noinspection ConstantConditions + Status status = buggy.status(); + Type[] types = buggy.types(); + String[] ids = buggy.caseIDs(); + String[] issues = buggy.issues(); + String[] bugs = buggy.bugs(); + String indent = " "; + String dotPlaceholder = ConfLogger.getDotPlaceholder(methodName, resultStatus, getANSI(resultStatus)); + if (BuggyConfigurationYML.getOutputRule().equals(OutputRule.OFF)) { + ConfLogger.info(dotPlaceholder); + return; + } + if (BuggyConfigurationYML.getOutputRule().equals(OutputRule.UNSUCCESSFUL) && resultStatus == SUCCESS) { + ConfLogger.info(dotPlaceholder); + return; + } + StringBuilder message = new StringBuilder(); + message.append(dotPlaceholder); + if (BuggyConfigurationYML.getTestSuiteInfo()) { + message.append(" [") + .append(component).append(" ") + .append(service).append(" ") + .append(interfaze); + if (!purpose.isEmpty()) { + message.append(" ").append(purpose); + } + message.append("]"); + } + if (BuggyConfigurationYML.getTestCaseTitle() && hasDescription(method)) { +// message.append("\n").append(" § ").append(description); + message.append("\n Case: ").append(getDescription(method)); + indent += indent; + } + if (BuggyConfigurationYML.getTestLogFilePath()) { + message.append("\n Log: ").append(getLogFilePath()); + indent += indent; + } + if (BuggyConfigurationYML.getTestBugsInfo() && bugs.length > 0) { + if (BuggyConfigurationYML.getIssuesUrl() != null && !BuggyConfigurationYML.getIssuesUrl().isEmpty()) { + for (String bug : bugs) { +// message.append("\n └").append(BOLD.wrap(RED.wrap(" ❗ "))) + message.append("\n Bug: ").append(BuggyConfigurationYML.getIssuesUrl()).append(bug); + } + } else { + message.append(" ").append(Arrays.toString(bugs)); + } + } + if (BuggyConfigurationYML.getTestIssuesInfo()) { + if (BuggyConfigurationYML.getIssuesUrl() != null && !BuggyConfigurationYML.getIssuesUrl().isEmpty()) { + for (String bug : bugs) { +// message.append("\n └").append(BOLD.wrap(GREEN.wrap(" ✓ "))) + message.append("\n Issue: ").append(BuggyConfigurationYML.getIssuesUrl()).append(bug); + } + } else { + message.append(" ").append(Arrays.toString(bugs)); + } + } + + if (BuggyConfigurationYML.getTestErrorInfo() && throwable != null) { +// message.append("\n └ ").append(BOLD.wrap(RED.wrap("↯ "))) + message.append("\n ") + .append(RED.wrap(throwable.getClass().getSimpleName())) + .append(": ") + .append(throwable.getMessage()); + } + ConfLogger.info(message.append("\n").toString()); + } + TEST.info("Date: {}", new Date()); + } + + protected ANSI getANSI(ResultStatus status) { + assertNotNull(status); + switch (status) { + case SUCCESS: + return NONE; + case FIXED: + case IMPLEMENTED: + return GREEN; + case FAILED: + case CORRUPTED: + return RED; + case SKIP: + return YELLOW; + case BLOCKED: + case EXP_FIX: + case EXP_IMPL: + default: + return PURPLE; + } + } + + protected String getLogFilePath() { + // Do not change the check. Feature parsing values by jCommander library. + if (!"null".equalsIgnoreCase(String.valueOf(BuggyConfigurationYML.getArtifactsUrl()))) { + return BuggyConfigurationYML.getArtifactsUrl().endsWith("/") ? + BuggyConfigurationYML.getArtifactsUrl() : + BuggyConfigurationYML.getArtifactsUrl() + "/"; + } else { + File file = SiftingTestLogger.getSiftingLogFile(); + if (file != null) { + return "file://" + file.getAbsolutePath(); + } else { + return "Log file not found"; + } + } + } + +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/testng/TestStatisticListenerBase.java b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/TestStatisticListenerBase.java new file mode 100644 index 0000000..afc5254 --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/TestStatisticListenerBase.java @@ -0,0 +1,136 @@ +package org.touchbit.buggy.core.testng; + +import org.apache.commons.lang3.time.DurationFormatUtils; +import org.testng.IExecutionListener; +import org.testng.IInvokedMethod; +import org.testng.IInvokedMethodListener; +import org.testng.ITestResult; +import org.touchbit.buggy.core.logback.ConfLogger; +import org.touchbit.buggy.core.model.Buggy; +import org.touchbit.buggy.core.model.Status; + +import java.util.Date; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.testng.ITestResult.*; +import static org.touchbit.buggy.core.utils.ANSI.*; + +public abstract class TestStatisticListenerBase implements BuggyListener, IExecutionListener, IInvokedMethodListener { + + protected static AtomicInteger totalCountOfTests = new AtomicInteger(0); + protected static AtomicInteger totalCountOfTestsRun = new AtomicInteger(0); + protected static AtomicInteger successfulTests = new AtomicInteger(0); + protected static AtomicInteger skippedTests = new AtomicInteger(0); + protected static AtomicInteger unsuccess = new AtomicInteger(0); + protected static AtomicInteger notDetailedTests = new AtomicInteger(0); + + protected static AtomicInteger newErrors = new AtomicInteger(0); + protected static AtomicInteger expFix = new AtomicInteger(0); + protected static AtomicInteger expImpl = new AtomicInteger(0); + protected static AtomicInteger blockedTests = new AtomicInteger(0); + protected static AtomicInteger corruptedTests = new AtomicInteger(0); + protected static AtomicInteger fixedCases = new AtomicInteger(0); + protected static AtomicInteger implemented = new AtomicInteger(0); + + protected long startTime; + protected long finishTime; + + @Override + public void onExecutionStart() { + startTime = new Date().getTime(); + } + + @Override + public void onExecutionFinish() { + finishTime = new Date().getTime(); + printTestStatistic(); + } + + @Override + public void afterInvocation(IInvokedMethod method, ITestResult testResult) { + if (method.isTestMethod()) { + Buggy buggy = getBuggyAnnotation(method); + if (buggy == null) { + notDetailedTests.incrementAndGet(); // TODO remove after --check realisation + } + totalCountOfTests.incrementAndGet(); + int testNgTestStatus = testResult.getStatus(); + if (testNgTestStatus == SKIP) { + skippedTests.incrementAndGet(); + } else { + totalCountOfTestsRun.incrementAndGet(); + } + if (testNgTestStatus == SUCCESS) { + successfulTests.incrementAndGet(); + } + if (testNgTestStatus == FAILURE || testNgTestStatus == SUCCESS_PERCENTAGE_FAILURE) { + unsuccess.incrementAndGet(); + } + if (buggy != null) { + Status status = buggy.status(); + if (testNgTestStatus == SUCCESS) { + switch (status) { + case BLOCKED: + case CORRUPTED: + case EXP_FIX: + fixedCases.incrementAndGet(); + break; + case EXP_IMPL: + implemented.incrementAndGet(); + break; + case NONE: + break; + default: + // do nothing + } + } + if (testNgTestStatus == FAILURE || testNgTestStatus == SUCCESS_PERCENTAGE_FAILURE) { + switch (status) { + case CORRUPTED: + corruptedTests.incrementAndGet(); + break; + case BLOCKED: + blockedTests.incrementAndGet(); + break; + case EXP_FIX: + expFix.incrementAndGet(); + break; + case EXP_IMPL: + expImpl.incrementAndGet(); + break; + case NONE: + default: + newErrors.incrementAndGet(); + } + } + } + } + } + + public void printTestStatistic() { + ConfLogger.blockDelimiter(); + ConfLogger.centerBold("Summary"); + ConfLogger.dotPlaceholder("Total count of tests", totalCountOfTests); + ConfLogger.dotPlaceholder("Total count of tests run", totalCountOfTestsRun); + ConfLogger.dotPlaceholder("Unsuccessful tests", unsuccess, PURPLE, isNotZero(unsuccess)); + ConfLogger.dotPlaceholder("Successful tests", successfulTests); + ConfLogger.dotPlaceholder("Skipped tests", skippedTests); + ConfLogger.dotPlaceholder("Without @Details", notDetailedTests); + ConfLogger.center("Details"); + ConfLogger.dotPlaceholder("New Errors", newErrors, RED, isNotZero(newErrors)); + ConfLogger.dotPlaceholder("Corrupted tests", corruptedTests, RED, isNotZero(corruptedTests)); + ConfLogger.dotPlaceholder("Blocked tests", blockedTests, PURPLE, isNotZero(blockedTests)); + ConfLogger.dotPlaceholder("Waiting to fix a defect", expFix, PURPLE, isNotZero(expFix)); + ConfLogger.dotPlaceholder("Waiting for implementation", expImpl, PURPLE, isNotZero(expImpl)); + ConfLogger.dotPlaceholder("Fixed (did not work before)", fixedCases, GREEN, isNotZero(fixedCases)); + ConfLogger.dotPlaceholder("Implemented cases", implemented, GREEN, isNotZero(implemented)); + ConfLogger.stepDelimiter(); + String time = DurationFormatUtils.formatDuration(finishTime - startTime, "HH:mm:ss,SSS"); + ConfLogger.dotPlaceholder("Execution time", time); + } + + protected boolean isNotZero(AtomicInteger integer) { + return integer.get() != 0; + } + +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/testng/TestSuite.java b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/TestSuite.java deleted file mode 100644 index f708a03..0000000 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/testng/TestSuite.java +++ /dev/null @@ -1,204 +0,0 @@ -/* - * Copyright © 2018 Shaburov Oleg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.touchbit.buggy.core.testng; - -import org.atteo.classindex.IndexSubclasses; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.xml.XmlClass; -import org.testng.xml.XmlSuite; -import org.testng.xml.XmlTest; -import org.touchbit.buggy.core.Buggy; -import org.touchbit.buggy.core.exceptions.BuggyConfigurationException; -import org.touchbit.buggy.core.model.Suite; -import org.touchbit.buggy.core.process.Component; -import org.touchbit.buggy.core.process.Interface; -import org.touchbit.buggy.core.process.Service; -import org.touchbit.buggy.core.utils.BuggyUtils; - -import java.util.*; -import java.util.stream.Collectors; - -import static org.testng.TestNG.DEFAULT_COMMAND_LINE_TEST_NAME; -import static org.testng.xml.XmlSuite.ParallelMode.METHODS; - -/** - * Base class of test suite. - *

- * Created by Oleg Shaburov on 15.05.2018 - * shaburov.o.a@gmail.com - */ -@SuppressWarnings("WeakerAccess") -@IndexSubclasses -public class TestSuite extends XmlSuite { - - protected Logger log = LoggerFactory.getLogger(TestSuite.class); - - private Suite suite; - private Component component; - private Service service; - private Interface anInterface; - - public TestSuite() { - this(Buggy.getPrimaryConfig().getThreads(), METHODS); - } - - public TestSuite(Suite suite) { - this(null, Buggy.getPrimaryConfig().getThreads(), METHODS, suite); - } - - public TestSuite(int threadCount) { - this(threadCount, METHODS); - } - - public TestSuite(int threadCount, ParallelMode parallel) { - this(null, threadCount, parallel); - } - - public TestSuite(String name, int threadCount, ParallelMode parallel) { - this(name, threadCount, parallel, null); - } - - public TestSuite(String name, int threadCount, ParallelMode parallel, Suite s) { - suite = s; - if (s == null) { - suite = this.getClass().getAnnotation(Suite.class); - } - if (suite == null) { - throw new BuggyConfigurationException("There is no @Suite annotation for " + this.getClass()); - } - component = BuggyUtils.getComponent(suite); - service = BuggyUtils.getService(suite); - anInterface = BuggyUtils.getInterface(suite); - if (name == null) { - this.setName(component.getName() + " " + service.getName() + " " + anInterface.getName() + " suite"); - } else { - this.setName(name); - } - this.setParallel(parallel); - this.setThreadCount(threadCount); - } - - /** - * The method of adding to the test classes {@link XmlClass} in the test package {@link XmlTest} - * @param packageName - name / description of the test package - * @param classes - array of added classes. - */ - public void addTestPackage(String packageName, final Class... classes) { - if (packageName == null || packageName.isEmpty()) { - packageName = DEFAULT_COMMAND_LINE_TEST_NAME; - } - if (classes.length == 0) { - Buggy.incrementBuggyWarns(); - log.warn("There are no classes for the test package: {}", packageName); - return; - } - List> classList = new ArrayList<>(Arrays.asList(classes)); - removeDuplicatesClasses(classList); - List xmlClasses = new ArrayList<>(); - for (Class aClass : classList) { - xmlClasses.add(new XmlClass(aClass)); - } - removeDuplicatesXmlClasses(xmlClasses, this.getTests()); - XmlTest testPackage = null; - for (XmlTest t : this.getTests()) { - if (t.getName().equals(packageName)) { - testPackage = t; - break; - } - } - if (!xmlClasses.isEmpty()) { - if (testPackage == null) { - testPackage = new XmlTest(this); - } - testPackage.setName(packageName); - testPackage.getXmlClasses().addAll(xmlClasses); - log.debug("Suite {}. Add test package (XmlTest): {}", this.getName(), packageName); - if (log.isDebugEnabled()) { - StringJoiner stringJoiner = new StringJoiner("\n ", "[\n ", "\n]"); - testPackage.getXmlClasses().forEach(c -> stringJoiner.add(c.getName())); - log.debug("{} classes:\n{}", packageName, stringJoiner); - } - } else { - log.debug("The {} test package (XmlTest) does not contain unique test classes " + - "and has not been added to the {} test suite.", packageName, this.getName()); - } - } - - private void removeDuplicatesClasses(final List> classList) { - Set> hs = new HashSet<>(classList); - if (hs.size() != classList.size()) { - List> duplicates = new ArrayList<>(classList); - hs.forEach(duplicates::remove); - duplicates.forEach(c -> { - classList.remove(c); - Buggy.incrementBuggyWarns(); - log.info("TRVariables duplicate has been removed from the class list: {}", c.getTypeName()); - }); - } - } - - private void removeDuplicatesXmlClasses(final List classesList, List xmlTests) { - for (XmlTest test : xmlTests) { - List duplicates = test.getXmlClasses().stream() - .filter(tc -> classesList.stream() - .anyMatch(tc::equals)) - .collect(Collectors.toList()); - if (!duplicates.isEmpty()) { - duplicates.forEach(c -> { - Buggy.incrementBuggyWarns(); - log.info("The test package {} already contains a class: {}", test.getName(), c); - }); - } - duplicates.forEach(classesList::remove); - } - } - - @Override - public boolean equals(Object obj) { - if (super.equals(obj)) { - TestSuite testSuite = (TestSuite) obj; - return testSuite.suite.equals(suite); - } - return false; - } - - @Override - public int hashCode() { - return 31 * super.hashCode() + suite.hashCode(); - } - - public Suite getSuite() { - return suite; - } - - public Component getComponent() { - return component; - } - - public Service getService() { - return service; - } - - public Interface getInterface() { - return anInterface; - } - - public void setLog(Logger logger) { - log = logger; - } -} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/testng/listeners/TestSupervisor.java b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/TestSupervisor.java similarity index 91% rename from buggy-core/src/main/java/org/touchbit/buggy/core/testng/listeners/TestSupervisor.java rename to buggy-core/src/main/java/org/touchbit/buggy/core/testng/TestSupervisor.java index 3a531c3..ec55b61 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/testng/listeners/TestSupervisor.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/TestSupervisor.java @@ -1,4 +1,4 @@ -package org.touchbit.buggy.core.testng.listeners; +package org.touchbit.buggy.core.testng; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -21,9 +21,9 @@ public class TestSupervisor extends BaseBuggyExecutionListener implements IExecu private static final Logger LOG = LoggerFactory.getLogger(TestSupervisor.class); - private List executableTests = Collections.synchronizedList(new ArrayList<>()); + private final List executableTests = Collections.synchronizedList(new ArrayList<>()); - private long tact; + private final long tact; private boolean runMetronome = false; private Thread thread; @@ -31,9 +31,9 @@ public TestSupervisor() { this(9999); } - public TestSupervisor(long tact) { - if (tact < 1) { - throw new BuggyConfigurationException("TestSupervisor metronome tact can not be less than 1 ms. " + + public TestSupervisor(final long tact) { + if (tact < 1000) { + throw new BuggyConfigurationException("TestSupervisor metronome tact can not be less than 1 sec. " + "Received: " + tact); } this.tact = tact; @@ -68,25 +68,6 @@ private String getSupervisorTestName(IInvokedMethod method) { return getMethodName(method) + " (" + getClassSimpleName(method) + ")"; } - private class Metronome implements Runnable { - - @Override - public synchronized void run() { - LOG.info("Metronome is started."); - while (runMetronome) { - try { - StringJoiner sj = new StringJoiner("\n ", "[", "]"); - getExecutableTests().forEach(sj::add); - LOG.info("Executable tests:\n{}", sj); - this.wait(tact); - } catch (Exception ignore) { - runMetronome = false; - Thread.currentThread().interrupt(); - } - } - } - } - private void addTest(String name) { if (!executableTests.contains(name)) { executableTests.add(name); @@ -123,4 +104,23 @@ public boolean isEnable() { return true; } + private class Metronome implements Runnable { + + @Override + public synchronized void run() { + LOG.info("Metronome is started."); + while (runMetronome) { + try { + StringJoiner sj = new StringJoiner("\n ", "[", "]"); + getExecutableTests().forEach(sj::add); + LOG.info("Executable tests:\n{}", sj); + this.wait(tact); + } catch (Exception ignore) { + runMetronome = false; + Thread.currentThread().interrupt(); + } + } + } + } + } diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/testng/listeners/BaseBuggyExecutionListener.java b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/listeners/BaseBuggyExecutionListener.java deleted file mode 100644 index 2b013dd..0000000 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/testng/listeners/BaseBuggyExecutionListener.java +++ /dev/null @@ -1,209 +0,0 @@ -/* - * Copyright © 2018 Shaburov Oleg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.touchbit.buggy.core.testng.listeners; - -import org.jetbrains.annotations.Nullable; -import org.slf4j.Logger; -import org.testng.*; -import org.touchbit.buggy.core.Buggy; -import org.touchbit.buggy.core.config.PrimaryConfig; -import org.touchbit.buggy.core.model.Details; -import org.touchbit.buggy.core.model.Suite; -import org.touchbit.buggy.core.utils.StringUtils; -import org.touchbit.buggy.core.utils.log.BuggyLog; - -import java.io.File; -import java.lang.reflect.Method; -import java.util.*; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * Created by Oleg Shaburov on 16.05.2018 - * shaburov.o.a@gmail.com - */ -@SuppressWarnings("WeakerAccess") -public abstract class BaseBuggyExecutionListener implements BuggyListener, IExecutionListener { - - protected static AtomicInteger testCount = new AtomicInteger(0); - protected static AtomicInteger skippedTests = new AtomicInteger(0); - protected static AtomicInteger corruptedError = new AtomicInteger(0); - protected static AtomicInteger expFixError = new AtomicInteger(0); - protected static AtomicInteger expImplError = new AtomicInteger(0); - protected static AtomicInteger blockedError = new AtomicInteger(0); - protected static AtomicInteger newError = new AtomicInteger(0); - protected static AtomicInteger fixed = new AtomicInteger(0); - protected static AtomicInteger implemented = new AtomicInteger(0); - - protected long startTime; - protected long finishTime; - protected Logger testLog; - protected Logger frameworkLog; - protected Logger consoleLog; - - @Override - public void onExecutionStart() { - startTime = new Date().getTime(); - if (testLog == null) { - testLog = BuggyLog.test(); - } - if (frameworkLog == null) { - frameworkLog = BuggyLog.framework(); - } - if (consoleLog == null) { - consoleLog = BuggyLog.console(); - } - } - - @Override - public void onExecutionFinish() { - finishTime = new Date().getTime(); - } - - protected @Nullable Details getDetails(IInvokedMethod method) { - return getDetails(method.getTestMethod()); - } - - protected @Nullable Details getDetails(ITestNGMethod method) { - return getDetails(method.getConstructorOrMethod().getMethod()); - } - - protected @Nullable Details getDetails(Method method) { - return method.getAnnotation(Details.class); - } - - protected Suite getSuite(ITestClass iTestClass) { - return iTestClass.getRealClass().getAnnotation(Suite.class); - } - - protected Suite getSuite(ITestNGMethod method) { - return (Suite) method.getRealClass().getAnnotation(Suite.class); - } - - protected String getLogFilePath(ITestNGMethod method) { - PrimaryConfig c = Buggy.getPrimaryConfig(); - String urlEncoded = StringUtils.encode(getInvokedMethodLogFileName(method)); - // Do not change the check. Feature parsing values by jCommander library. - if (!"null".equalsIgnoreCase(String.valueOf(c.getArtifactsUrl()))) { - String parentDir = c.getTestLogDir().getParentFile().getName(); - String logDir = new File(parentDir, c.getTestLogDir().getName()).getPath(); - String url = c.getArtifactsUrl().endsWith("/") ? c.getArtifactsUrl() : c.getArtifactsUrl() + "/"; - return url + new File(logDir, urlEncoded).getPath(); - } else { - return "file://" + new File(c.getTestLogDir(), getInvokedMethodLogFileName(method)); - } - } - - protected String getInvokedMethodLogFileName(IInvokedMethod method) { - return getInvokedMethodLogFileName(method.getTestMethod()); - } - - protected String getInvokedMethodLogFileName(ITestNGMethod iTestNGMethod) { - Method method = iTestNGMethod.getConstructorOrMethod().getMethod(); - return method.getName() + ".log"; - } - - protected Method getRealMethod(ITestResult result) { - return getRealMethod(result.getMethod()); - } - - protected Method getRealMethod(IInvokedMethod method) { - return getRealMethod(method.getTestMethod()); - } - - protected Method getRealMethod(ITestNGMethod method) { - return method.getConstructorOrMethod().getMethod(); - } - - protected String getDescription(IInvokedMethod method) { - return method.getTestMethod().getDescription(); - } - - protected String getClassSimpleName(IInvokedMethod method) { - return method.getTestMethod().getRealClass().getSimpleName(); - } - - protected String getMethodName(IInvokedMethod method) { - return method.getTestMethod().getMethodName(); - } - - protected boolean isIssuesPresent(Details details) { - for (String s : details.issue()) { - if (!s.isEmpty()) { - return true; - } - } - return false; - } - - protected String getIssues(Details details) { - String[] issues = details.issue(); - if (issues.length == 0) { - return ""; - } - return Arrays.toString(details.issue()); - } - - protected String buildDetailsMessage(Details details, Object... appends) { - StringJoiner stringJoiner = new StringJoiner(" "); - for (Object o : appends) { - stringJoiner.add(String.valueOf(o)); - } - String ref = isIssuesPresent(details) ? "" + getIssues(details).trim() : ""; - String appendsResult = stringJoiner.toString().trim(); - if (ref.length() != 0) { - return ref + (appendsResult.length() > 0 ? " " + appendsResult.trim() : ""); - } - return stringJoiner.length() != 0 ? stringJoiner.toString().trim() : ""; - } - - public int getTestCount() { - return testCount.get(); - } - - public int getSkippedTests() { - return skippedTests.get(); - } - - public int getCorruptedError() { - return corruptedError.get(); - } - - public int getExpFixError() { - return expFixError.get(); - } - - public int getExpImplError() { - return expImplError.get(); - } - - public int getBlockedError() { - return blockedError.get(); - } - - public int getNewError() { - return newError.get(); - } - - public int getFixed() { - return fixed.get(); - } - - public int getImplemented() { - return implemented.get(); - } - -} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/testng/listeners/BaseTelegramNotifier.java b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/listeners/BaseTelegramNotifier.java deleted file mode 100644 index bd2906b..0000000 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/testng/listeners/BaseTelegramNotifier.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright © 2018 Shaburov Oleg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.touchbit.buggy.core.testng.listeners; - -import org.apache.commons.lang3.time.DurationFormatUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.IExecutionListener; -import org.touchbit.buggy.core.Buggy; -import org.touchbit.buggy.core.model.Notifier; -import org.touchbit.buggy.core.testng.TestSuite; -import org.touchbit.buggy.core.utils.StringUtils; - -import java.util.StringJoiner; - -/** - * Created by Oleg Shaburov on 06.09.2018 - * shaburov.o.a@gmail.com - */ -@SuppressWarnings({"unused", "squid:S2629"}) -public abstract class BaseTelegramNotifier extends BaseBuggyExecutionListener implements IExecutionListener { - - protected Logger log = LoggerFactory.getLogger(TestSuite.class); - - private final Notifier notifier; - - @SuppressWarnings("WeakerAccess") - public BaseTelegramNotifier(final Notifier notifier) { - this.notifier = notifier; - } - - @Override - public void onExecutionStart() { } - - @Override - public void onExecutionFinish() { - if (isEnable()) { - telegramResultNotification(); - } - } - - private void telegramResultNotification() { - String name = Buggy.getProgramName(); - StringJoiner sj; - if (name == null || name.isEmpty()) { - sj = new StringJoiner("\n", "Run Results:\n", "\n"); - } else { - sj = new StringJoiner("\n", "*" + name + "*\nRun Results:\n", "\n"); - } - int len = 33; - int errorCount = expFixError.get() + expImplError.get() + newError.get() + - corruptedError.get() + blockedError.get(); - int testCountLen = testCount.toString().length(); - int fullLen = len + testCountLen; - sj.add(StringUtils.filler("`", "-", fullLen, "`")); - int runningLen = len + testCountLen - testCount.toString().length(); - sj.add(StringUtils.dotFiller("`Running tests", runningLen, "`") + testCount.get()); - sj.add(StringUtils.filler("`", "-", fullLen, "`")); - int successfulLen = len + testCountLen - (String.valueOf(testCount.get() - errorCount)).length(); - sj.add(StringUtils.dotFiller("`Successful tests", successfulLen, "`") + - (testCount.get() - errorCount)); - sj.add(StringUtils.dotFiller("`Skipped tests", successfulLen, "`") + (skippedTests.get())); - int failedLen = len + testCountLen - (String.valueOf(errorCount)).length(); - sj.add(StringUtils.dotFiller("`Failed tests", failedLen, "`") + errorCount); - sj.add(StringUtils.filler("`", "-", fullLen, "`")); - int newErrorsLen = len + testCountLen - newError.toString().length(); - sj.add(StringUtils.dotFiller("`New Errors", newErrorsLen, "`") + - wrapErrorsMDLink(newError.get(), "new/")); - int waitFixLen = len + testCountLen - expFixError.toString().length(); - sj.add(StringUtils.dotFiller("`Waiting to fix a defect", waitFixLen, "`") + - wrapErrorsMDLink(expFixError.get(), "exp_fix/")); - int waitImplLen = len + testCountLen - expImplError.toString().length(); - sj.add(StringUtils.dotFiller("`Waiting for the implementation", waitImplLen, "`") + - wrapErrorsMDLink(expImplError.get(), "exp_impl/")); - int blockedLen = len + testCountLen - blockedError.toString().length(); - sj.add(StringUtils.dotFiller("`Blocked tests", blockedLen, "`") + - wrapErrorsMDLink(blockedError.get(), "blocked/")); - int corruptedLen = len + testCountLen - corruptedError.toString().length(); - sj.add(StringUtils.dotFiller("`Corrupted tests", corruptedLen, "`") + - wrapErrorsMDLink(corruptedError.get(), "corrupted/")); - sj.add(StringUtils.filler("`", "-", fullLen, "`")); - int fixedLen = len + testCountLen - fixed.toString().length(); - sj.add(StringUtils.dotFiller("`Fixed defects", fixedLen, "`") + - wrapFixedMDLink(fixed.get(), "exp_fix/")); - int implementedLen = len + testCountLen - implemented.toString().length(); - sj.add(StringUtils.dotFiller("`Implemented cases", implementedLen, "`") + - wrapFixedMDLink(implemented.get(), "exp_impl/")); - sj.add(StringUtils.filler("`", "-", fullLen, "`")); - String date = DurationFormatUtils.formatDuration(finishTime - startTime, "HH:mm:ss"); - sj.add("Test execution time: *" + date + "*"); - sj.add("[Logs](" + Buggy.getPrimaryConfig().getArtifactsUrl() + ")"); - try { - notifier.report(sj.toString()); - } catch (Exception e) { - Buggy.incrementBuggyErrors(); - log.error("Failed to send message to Telegram.", e); - } - } - - private String wrapErrorsMDLink(Integer value, String subLink) { - String artifactLogPath = Buggy.getPrimaryConfig().getArtifactsUrl() + "/errors/" + subLink; - if (value > 0 ) { - return "[" + value + "](" + artifactLogPath + ")"; - } - return String.valueOf(value); - } - - private String wrapFixedMDLink(Integer value, String subLink) { - String artifactLogPath = Buggy.getPrimaryConfig().getArtifactsUrl() + "/fixed/" + subLink; - if (value > 0 ) { - return "[" + value + "](" + artifactLogPath + ")"; - } - return String.valueOf(value); - } - -} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/testng/listeners/BuggyExecutionListener.java b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/listeners/BuggyExecutionListener.java deleted file mode 100644 index d4ff86a..0000000 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/testng/listeners/BuggyExecutionListener.java +++ /dev/null @@ -1,575 +0,0 @@ -/* - * Copyright © 2018 Shaburov Oleg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.touchbit.buggy.core.testng.listeners; - -import org.jetbrains.annotations.NotNull; -import org.slf4j.Logger; -import org.testng.*; -import org.touchbit.buggy.core.Buggy; -import org.touchbit.buggy.core.config.PrimaryConfig; -import org.touchbit.buggy.core.exceptions.CorruptedTestException; -import org.touchbit.buggy.core.model.Details; -import org.touchbit.buggy.core.model.Status; -import org.touchbit.buggy.core.model.Suite; -import org.touchbit.buggy.core.model.Type; -import org.touchbit.buggy.core.utils.BuggyUtils; -import org.touchbit.buggy.core.utils.IOHelper; -import org.touchbit.buggy.core.utils.StringUtils; -import org.touchbit.buggy.core.utils.log.BuggyLog; - -import java.io.File; -import java.io.IOException; -import java.lang.annotation.Annotation; -import java.lang.reflect.Method; -import java.util.*; - -import static org.testng.ITestResult.*; -import static org.touchbit.buggy.core.model.Status.BLOCKED; -import static org.touchbit.buggy.core.model.Status.EXP_FIX; -import static org.touchbit.buggy.core.model.Status.EXP_IMPL; -import static org.touchbit.buggy.core.utils.BuggyUtils.CONSOLE_DELIMITER; -import static org.touchbit.buggy.core.utils.StringUtils.*; - -/** - * Listener for processing executable tests. - *

- * Created by Shaburov Oleg on 31.07.2017. - */ -@SuppressWarnings({"unused", "UnusedReturnValue", "squid:S2629"}) -public class BuggyExecutionListener extends BaseBuggyExecutionListener - implements IExecutionListener, IInvokedMethodListener, ISuiteListener, ITestListener, IClassListener { - - private static final ThreadLocal> STEPS = new ThreadLocal<>(); - - public BuggyExecutionListener() { - } - - public BuggyExecutionListener(Logger testLogger, Logger frameworkLogger, Logger consoleLogger) { - testLog = testLogger; - frameworkLog = frameworkLogger; - consoleLog = consoleLogger; - } - - @Override - public boolean isEnable() { - return true; - } - - @Override - public void onExecutionStart() { - super.onExecutionStart(); - consoleLog.info(""); - } - - @Override - public void onExecutionFinish() { - super.onExecutionFinish(); - printTestStatistic(); - } - - @Override - public void onTestSuccess(ITestResult result) { - onTestFinish(result); - } - - @Override - public void onTestFailure(ITestResult result) { - onTestFinish(result); - } - - @Override - public void onTestSkipped(ITestResult result) { - onTestFinish(result); - } - - @Override - public void onTestFailedButWithinSuccessPercentage(ITestResult result) { - onTestFinish(result); - } - - public void onTestFinish(ITestResult result) { - Method method = getRealMethod(result); - Throwable t = result.getThrowable(); - if ((t != null && t.getClass().getName().contains("ExpectedImplementationException"))) { - return; - } - if (result.getStatus() == ITestResult.SKIP) { - testLog.warn("The test {} is skipped.", method.getName()); - return; - } - if (!getSteps().isEmpty()) { - StringBuilder sb = new StringBuilder(); - getSteps().forEach(step -> sb.append(step).append("\n")); - testLog.info("Steps:\n{}", sb); - } else { - Buggy.incrementBuggyWarns(); - frameworkLog.warn("There are no playback steps in the test method {}", method.getName()); - } - testLog.info("Date: {}", new Date()); - } - - @Override - public void onAfterClass(ITestClass iTestClass) { - if (getSuite(iTestClass) == null) { - Buggy.incrementBuggyErrors(); - frameworkLog.error("There is no @Suite annotation for the test class: {}", iTestClass.getName()); - } - } - - @Override - public void onStart(ISuite suite) { - disableTestsByType(suite); - if (!Buggy.getPrimaryConfig().isForceRun()) { - disableTestsByStatus(suite); - } - } - - @Override - public void onFinish(ISuite suite) { - suite.getAllInvokedMethods() - .forEach(m -> { - try { - copyTestMethodLogFile(m); - } catch (Exception e) { - Buggy.incrementBuggyErrors(); - frameworkLog.error(e.getMessage(), e); - } - }); - } - - @Override - public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { - STEPS.set(new ArrayList<>()); - String methodName = getMethodName(method); - BuggyLog.setTestLogFileName(getInvokedMethodLogFileName(method)); - if (method.isTestMethod()) { - testLog.info("Test method is running:\n{} - {}", methodName, getDescription(method)); - } else { - testLog.info("Configuration method is running:\n{} - {}.", methodName, getDescription(method)); - } - if (testLog.isDebugEnabled()) { - StringJoiner sj = new StringJoiner("\n", "\n", "\n"); - for (Annotation annotation : getRealMethod(method).getAnnotations()) { - sj.add(annotation.toString()); - } - testLog.trace("Declared method annotations:{}", sj); - } - } - - @Override - public void afterInvocation(IInvokedMethod method, ITestResult testResult) { - Throwable throwable = testResult.getThrowable(); - String methodName = getMethodName(method); - if (throwable != null) { - List stepList = getSteps(); - if (!stepList.isEmpty()) { - int lastIndex = stepList.size() - 1; - stepList.set(lastIndex, stepList.get(lastIndex) + " - ERROR"); - setSteps(stepList); - } - testLog.error("Execution of {} resulted in an error.", methodName, throwable); - } - if (method.isTestMethod()) { - if (testResult.getStatus() != SKIP) { - testCount.incrementAndGet(); - } - Details details = getDetails(method); - if (details != null) { - processTestMethodResult(method, testResult, details); - } else { - Buggy.incrementBuggyWarns(); - frameworkLog.warn("The test method {} does not contain the @Details annotation", methodName); - } - } else { - processConfigurationMethodResult(method, testResult); - } - - } - - /** - * Method for the separation of steps in the test log. - */ - public static void step(@NotNull final Logger logger, @NotNull final String msg, @NotNull final Object... args) { - int stepNum = getSteps().size() + 1; - String msgBody = msg; - for (Object s : args) { - msgBody = msgBody.replaceFirst("\\{}", String.valueOf(s)); - } - String stepInfo = "Step " + stepNum + ". " + msgBody; - logger.info(" ------------> {}", stepInfo); - getSteps().add(stepInfo); - } - - public static List getSteps() { - if (STEPS.get() == null) { - STEPS.set(new ArrayList<>()); - } - return STEPS.get(); - } - - public static void setSteps(List stepList) { - STEPS.set(stepList); - } - - public void processTestMethodResult(IInvokedMethod m, ITestResult testResult, Details details) { - ITestNGMethod method = m.getTestMethod(); - switch (testResult.getStatus()) { - case SUCCESS: - switch (details.status()) { - case BLOCKED: - case EXP_FIX: - resultLog(method, Status.FIXED, buildDetailsMessage(details)); - break; - case EXP_IMPL: - resultLog(method, Status.IMPLEMENTED, buildDetailsMessage(details)); - break; - case CORRUPTED: - resultLog(method, Status.CORRUPTED, buildDetailsMessage(details)); - testResult.setThrowable(new CorruptedTestException()); - break; - default: - resultLog(method, Status.SUCCESS, buildDetailsMessage(details)); - } - break; - case SUCCESS_PERCENTAGE_FAILURE: - case FAILURE: - switch (details.status()) { - case CORRUPTED: - resultLog(method, Status.CORRUPTED, buildDetailsMessage(details)); - testResult.setThrowable(new CorruptedTestException()); - break; - case EXP_FIX: - resultLog(method, Status.EXP_FIX, buildDetailsMessage(details)); - break; - case EXP_IMPL: - resultLog(method, Status.EXP_IMPL, buildDetailsMessage(details)); - break; - case BLOCKED: - resultLog(method, Status.BLOCKED, buildDetailsMessage(details)); - break; - default: - resultLog(method, Status.FAILED, buildDetailsMessage(details)); - } - break; - case SKIP: - resultLog(method, Status.SKIP, buildDetailsMessage(details)); - break; - default: - frameworkLog.error("Received unprocessed status: {}", testResult.getStatus()); - Buggy.incrementBuggyErrors(); - } - } - - public void processConfigurationMethodResult(IInvokedMethod method, ITestResult testResult) { - String methodName = getMethodName(method); - String description = getDescription(method); - switch (testResult.getStatus()) { - case SUCCESS: - testLog.info("Invoke configuration method [{}] completed successfully", methodName); - break; - case SKIP: - testLog.warn("Invoke configuration method [{}] skipped. " + - "List of dependent tests that were missed: {}", methodName, description); - break; - case SUCCESS_PERCENTAGE_FAILURE: - case FAILURE: - testLog.error("Invoke configuration method [{}] completed with error \n{}", - methodName, testResult.getThrowable().getMessage()); - break; - default: - Buggy.incrementBuggyErrors(); - frameworkLog.error("Received unresolved status of configuration method [{}]. Status: {}", - methodName, testResult.getStatus()); - } - } - - public void disableTestsByStatus(ISuite suite) { - suite.getAllMethods().forEach(method -> { - Details details = getDetails(method); - if (details != null) { - if (method.getInvocationCount() > 0) { - switch (details.status()) { - case EXP_FIX: - case EXP_IMPL: - case BLOCKED: - case CORRUPTED: - method.setInvocationCount(0); - resultLog(method, details.status(), buildDetailsMessage(details, "forced test run disabled")); - break; - default: - // do nothing - } - } - } else { - Buggy.incrementBuggyWarns(); - frameworkLog.warn("The test method {} does not contain the @Details annotation", - method.getMethodName()); - } - }); - } - - public void disableTestsByType(final ISuite suite) { - final List methods = suite.getAllMethods(); - methods.forEach(method -> { - Details details = getDetails(method); - Type configType = Buggy.getPrimaryConfig().getType(); - if (details != null && !configType.isIncludeOrEquals(details.type())) { - method.setInvocationCount(0); - resultLog(method, Status.SKIP, buildDetailsMessage(details, details.type(), "test type")); - } - }); - } - - public void copyTestMethodLogFile(IInvokedMethod method) throws IOException { - PrimaryConfig c = Buggy.getPrimaryConfig(); - Details details = getDetails(method); - int iTestResultStatus = method.getTestResult().getStatus(); - File sourceFile = new File(c.getTestLogDir(), getInvokedMethodLogFileName(method)); - File targetFile = null; - if (details == null) { - if (iTestResultStatus == FAILURE || iTestResultStatus == SUCCESS_PERCENTAGE_FAILURE) { - targetFile = new File(c.getNewErrorLogDir(), getInvokedMethodLogFileName(method)); - copyFile(sourceFile, targetFile); - } - return; - } - Status status = details.status(); - switch (iTestResultStatus) { - case ITestResult.SUCCESS: - if (status.equals(EXP_FIX) || status.equals(BLOCKED)) { - targetFile = new File(c.getFixedLogDir(), getInvokedMethodLogFileName(method)); - } - if (status.equals(EXP_IMPL)) { - targetFile = new File(c.getImplementedLogDir(), getInvokedMethodLogFileName(method)); - } - break; - case ITestResult.FAILURE: - case ITestResult.SUCCESS_PERCENTAGE_FAILURE: - switch (status) { - case EXP_FIX: - targetFile = new File(c.getExpFixErrorLogDir(), getInvokedMethodLogFileName(method)); - break; - case EXP_IMPL: - targetFile = new File(c.getExpImplErrorLogDir(), getInvokedMethodLogFileName(method)); - break; - case BLOCKED: - targetFile = new File(c.getBlockedErrorLogDir(), getInvokedMethodLogFileName(method)); - break; - case CORRUPTED: - targetFile = new File(c.getCorruptedErrorLogDir(), getInvokedMethodLogFileName(method)); - break; - default: - targetFile = new File(c.getNewErrorLogDir(), getInvokedMethodLogFileName(method)); - } - default: - // ignore unhandled statuses - } - if (targetFile != null) { - copyFile(sourceFile, targetFile); - } - } - - public void resultLog(ITestNGMethod method, Status status, String details) { - PrimaryConfig config = Buggy.getPrimaryConfig(); - String methodName = method.getMethodName(); - Suite suite = getSuite(method); - String statusName = status.name(); - StringJoiner resultMsg = new StringJoiner(" "); - if (config.isPrintSuite()) { - StringJoiner sj = new StringJoiner(" ", " [", "]"); - sj.add(BuggyUtils.getComponent(suite).getName().trim()); - sj.add(BuggyUtils.getService(suite).getName().trim()); - sj.add(BuggyUtils.getInterface(suite).getName().trim()); - sj.add(suite.task().trim()); - resultMsg.add(sj.toString().trim()); - } - testLog.info("{} - {} {}", methodName, statusName, method.getDescription()); - String detailsString = details.trim(); - if ((config.isPrintCause() || method.getInvocationCount() < 1) && !detailsString.isEmpty()) { - resultMsg.add(detailsString); - } - String logPathString = getLogFilePath(method).trim(); - if (config.isPrintLogFile() && method.getInvocationCount() > 0 && !logPathString.isEmpty() && - (!config.isPrintLogFileOnlyFail() || (config.isPrintLogFileOnlyFail() && status != Status.SUCCESS))) { - resultMsg.add("\n└"); - resultMsg.add(logPathString); - } - printASCIIStatus(status, StringUtils.dotFiller(methodName, 47, statusName) + - (resultMsg.length() > 0 ? " " + resultMsg.toString().trim() : "")); - if (method.isTest()) { - if (method.getInvocationCount() > 0) { - increment(status); - } else { - increment(Status.SKIP); - } - } - } - - protected void printASCIIStatus(Status status, String msg) { - switch (status) { - case FAILED: - case CORRUPTED: - consoleLog.error(msg); - break; - case EXP_IMPL: - case EXP_FIX: - case BLOCKED: - case SKIP: - consoleLog.warn(msg); - break; - case IMPLEMENTED: - case FIXED: - consoleLog.debug(msg); - break; - default: - consoleLog.info(msg); - } - } - - protected void increment(Status status) { - switch (status) { - case FAILED: - newError.incrementAndGet(); - break; - case CORRUPTED: - corruptedError.incrementAndGet(); - break; - case EXP_IMPL: - expImplError.incrementAndGet(); - break; - case EXP_FIX: - expFixError.incrementAndGet(); - break; - case BLOCKED: - blockedError.incrementAndGet(); - break; - case IMPLEMENTED: - implemented.incrementAndGet(); - break; - case FIXED: - fixed.incrementAndGet(); - break; - case SKIP: - skippedTests.incrementAndGet(); - break; - default: - // do nothing - } - } - - protected void printTestStatistic() { - println(CONSOLE_DELIMITER); - if (Buggy.getBuggyErrors() > 0) { - consoleLog.error(StringUtils.dotFiller("Framework errors", 47, Buggy.getBuggyErrors())); - } - if (Buggy.getBuggyWarns() > 0) { - consoleLog.warn(StringUtils.dotFiller("Framework warns", 47, Buggy.getBuggyWarns())); - } - if (Buggy.getBuggyErrors() > 0 || Buggy.getBuggyWarns() > 0) { - println(CONSOLE_DELIMITER); - } - int fixedCount = fixed.get() + implemented.get(); - int errorCount = expFixError.get() + expImplError.get() + newError.get() + - corruptedError.get() + blockedError.get(); - consoleLog.info(StringUtils.dotFiller("Total tests run", 47, testCount.get())); - consoleLog.info(StringUtils.dotFiller("Successful tests", 47, testCount.get() - errorCount)); - checkWarnAndPrint("Skipped tests", skippedTests.get()); - if (errorCount > 0) { - checkWarnAndPrint("Failed tests", errorCount); - checkErrorAndPrint("New Errors", newError.get()); - println(CONSOLE_DELIMITER); - checkWarnAndPrint("Waiting to fix a defect", expFixError.get()); - checkWarnAndPrint("Waiting for implementation", expImplError.get()); - checkWarnAndPrint("Blocked tests", blockedError.get()); - checkErrorAndPrint("Corrupted tests", corruptedError.get()); - } else { - String result = StringUtils.dotFiller("Errors", 47, errorCount); - consoleLog.info(result); - } - if (fixedCount > 0) { - println(CONSOLE_DELIMITER); - checkDebugAndPrint("Fixed cases", fixed.get()); - checkDebugAndPrint("Implemented cases", implemented.get()); - } - println(CONSOLE_DELIMITER); - consoleLog.info(StringUtils.dotFiller("Execution time", 47, org.apache.commons.lang3.time.DurationFormatUtils - .formatDuration(finishTime - startTime, "HH:mm:ss,SSS"))); - println(CONSOLE_DELIMITER); - } - - protected void checkDebugAndPrint(String msg, int count) { - String result = StringUtils.dotFiller(msg, 47, count); - if (count > 0) { - consoleLog.debug(result); - } else { - consoleLog.info(result); - } - } - - protected void checkErrorAndPrint(String msg, int count) { - String result = StringUtils.dotFiller(msg, 47, count); - if (count > 0) { - consoleLog.error(result); - } else { - consoleLog.info(result); - } - } - - protected void checkWarnAndPrint(String msg, int count) { - String result = StringUtils.dotFiller(msg, 47, count); - if (count > 0) { - consoleLog.warn(result); - } else { - consoleLog.info(result); - } - } - - @SuppressWarnings("SameParameterValue") - protected void checkTraceAndPrint(String msg, int count) { - String result = StringUtils.dotFiller(msg, 47, count); - if (count > 0) { - consoleLog.trace(result); - } else { - consoleLog.info(result); - } - } - - protected void copyFile(File sourceFile, File destFile) throws IOException { - IOHelper.copyFile(sourceFile, destFile); - } - - @Override - public void onStart(ITestContext context) { - // do nothing - } - - @Override - public void onFinish(ITestContext context) { - // do nothing - } - - @Override - public void onBeforeClass(ITestClass testClass) { - // do nothing - } - - @Override - public void onTestStart(ITestResult result) { - // do nothing - } - -} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/testng/listeners/BuggyListener.java b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/listeners/BuggyListener.java deleted file mode 100644 index 035be73..0000000 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/testng/listeners/BuggyListener.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.touchbit.buggy.core.testng.listeners; - -import org.atteo.classindex.IndexSubclasses; -import org.testng.ITestNGListener; - -/** - * Created by Oleg Shaburov on 28.05.2018 - * shaburov.o.a@gmail.com - */ -@IndexSubclasses -public interface BuggyListener extends ITestNGListener { - - boolean isEnable(); - -} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/testng/listeners/IntellijIdeaTestNgPluginListener.java b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/listeners/IntellijIdeaTestNgPluginListener.java deleted file mode 100644 index bb68b5d..0000000 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/testng/listeners/IntellijIdeaTestNgPluginListener.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright © 2018 Shaburov Oleg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.touchbit.buggy.core.testng.listeners; - -import org.testng.ITestNGListener; -import org.touchbit.buggy.core.Buggy; -import org.touchbit.buggy.core.config.PrimaryConfig; -import org.touchbit.buggy.core.utils.ExitHandlerExpectedException; - -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -import static org.touchbit.buggy.core.utils.IOHelper.readPropertiesFileFromResource; - -/** - * Intellij IDEA TestNG Plugin Listener - *

- * Created by Oleg Shaburov on 15.05.2018 - * shaburov.o.a@gmail.com - */ -@SuppressWarnings("WeakerAccess") -public final class IntellijIdeaTestNgPluginListener extends BuggyExecutionListener implements ITestNGListener { - - public static final String INTELLIJ_IDEA_TEST_RUN = "intellij.idea.test.run"; - - @SuppressWarnings("StatementWithEmptyBody") - public IntellijIdeaTestNgPluginListener() { - System.setProperty(INTELLIJ_IDEA_TEST_RUN, Boolean.TRUE.toString()); - Properties properties = readPropertiesFileFromResource("buggy.properties"); - List list = new ArrayList<>(); - properties.forEach((k, v) -> { - String key = String.valueOf(k); - String val = String.valueOf(v); - // option key - if (key.startsWith("-")) { - list.add(key); - // option value - if (!val.isEmpty()) { - list.add(val); - } - } else { - if (key.startsWith("buggy.primary.config.class")) { - Buggy.setPrimaryConfigClass(getPrimaryConfig(val)); - } - } - }); - String[] args = list.toArray(new String[0]); - Buggy.prepare(args); - } - - @SuppressWarnings("unchecked") - public Class getPrimaryConfig(String val) { - try { - return (Class) this.getClass().getClassLoader().loadClass(val); - } catch (Exception e) { - Buggy.getExitHandler().exitRun(1, "Unable to create a new instance of PrimaryConfig class", e); - } - throw new ExitHandlerExpectedException(); - } - - @Override - public void onExecutionStart() { - super.onExecutionStart(); - // fix incorrect Intellij Idea Test Run Console output - consoleLog.info(""); - } - - @Override - public final boolean isEnable() { - return false; - } - - public static Boolean isIntellijIdeaTestRun() { - return Boolean.valueOf(System.getProperty(INTELLIJ_IDEA_TEST_RUN, Boolean.FALSE.toString())); - } - -} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/transport/interceptor/CURLLoggingInterceptor.java b/buggy-core/src/main/java/org/touchbit/buggy/core/transport/CURLLoggingInterceptor.java similarity index 95% rename from buggy-core/src/main/java/org/touchbit/buggy/core/transport/interceptor/CURLLoggingInterceptor.java rename to buggy-core/src/main/java/org/touchbit/buggy/core/transport/CURLLoggingInterceptor.java index 7d7559a..7753a3c 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/transport/interceptor/CURLLoggingInterceptor.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/transport/CURLLoggingInterceptor.java @@ -1,4 +1,4 @@ -package org.touchbit.buggy.core.transport.interceptor; +package org.touchbit.buggy.core.transport; import java.util.Map; import java.util.StringJoiner; diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/utils/ANSI.java b/buggy-core/src/main/java/org/touchbit/buggy/core/utils/ANSI.java new file mode 100644 index 0000000..5307f1b --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/utils/ANSI.java @@ -0,0 +1,41 @@ +package org.touchbit.buggy.core.utils; + +public enum ANSI { + + RESET("\u001B[0m"), + BOLD("\u001B[1m"), + RED("\u001B[31m"), + BR_RED("\u001B[31;1m"), + GREEN("\u001B[32m"), + BR_GREEN("\u001B[32;1m"), + YELLOW("\u001b[33m"), + BR_YELLOW("\u001b[33;1m"), + BLUE("\u001B[34m"), + BR_BLUE("\u001B[34;1m"), + PURPLE("\u001B[35m"), + BR_PURPLE("\u001B[35;1m"), + NONE(""), + ; + + String symbol; + + ANSI(String symbol) { + this.symbol = symbol; + } + + public static String unwrap(final String msg) { + String resultMsg = msg; + for (ANSI value : ANSI.values()) { + resultMsg = resultMsg.replace(value.symbol, ""); + } + return resultMsg; + } + + public String wrap(final String msg) { + if (this.equals(NONE)) { + return msg; + } + return this.symbol + msg + RESET.symbol; + } + +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/utils/BuggyUtils.java b/buggy-core/src/main/java/org/touchbit/buggy/core/utils/BuggyUtils.java deleted file mode 100644 index 1338c2d..0000000 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/utils/BuggyUtils.java +++ /dev/null @@ -1,183 +0,0 @@ -/* - * Copyright © 2018 Shaburov Oleg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.touchbit.buggy.core.utils; - -import org.atteo.classindex.ClassIndex; -import org.testng.xml.XmlClass; -import org.testng.xml.XmlTest; -import org.touchbit.buggy.core.exceptions.BuggyConfigurationException; -import org.touchbit.buggy.core.model.Suite; -import org.touchbit.buggy.core.process.Component; -import org.touchbit.buggy.core.process.Interface; -import org.touchbit.buggy.core.process.Service; -import org.touchbit.buggy.core.testng.TestSuite; - -import java.io.IOException; -import java.io.InputStream; -import java.lang.annotation.Annotation; -import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; -import java.util.jar.Attributes; -import java.util.jar.Manifest; -import java.util.stream.Collectors; -import java.util.stream.StreamSupport; - -/** - * Created by Oleg Shaburov on 08.09.2018 - * shaburov.o.a@gmail.com - */ -@SuppressWarnings("WeakerAccess") -public class BuggyUtils { - - public static final String CONSOLE_DELIMITER = "==============================================="; - - public static boolean isListBaseSuiteContainsClass(final List suites, final Class aClass) { - if (suites == null || suites.isEmpty() || aClass == null) { - return false; - } - for (TestSuite suite : suites) { - for (XmlTest test : suite.getTests()) { - for (XmlClass xmlClass : test.getXmlClasses()) { - if (xmlClass.getName().equals(aClass.getName())) { - return true; - } - } - } - } - return false; - } - - public static List> findAnnotatedInstantiatedClasses(Class annotation) { - return StreamSupport.stream(ClassIndex.getAnnotated(annotation).spliterator(), false) - .filter(c -> Modifier.isPublic(c.getModifiers()) && !Modifier.isAbstract(c.getModifiers())) - .collect(Collectors.toList()); - } - - public static List> findInstantiatedSubclasses(Class superClass) { - return StreamSupport.stream(ClassIndex.getSubclasses(superClass).spliterator(), false) - .filter(c -> Modifier.isPublic(c.getModifiers()) && !Modifier.isAbstract(c.getModifiers())) - .collect(Collectors.toList()); - } - - public static boolean isAssignableFrom(Class checkedClass, Class assignableClass) { - if (checkedClass == null || assignableClass == null || checkedClass.isInstance(Object.class)) { - return false; - } - if (checkedClass == assignableClass) { - return true; - } else { - return isAssignableFrom(checkedClass.getSuperclass(), assignableClass); - } - } - - public static List findComponents() { - return getSubclassesNewObjectList(Component.class); - } - - public static List findServices() { - return getSubclassesNewObjectList(Service.class); - } - - public static List findInterfaces() { - return getSubclassesNewObjectList(Interface.class); - } - - public static List getSubclassesNewObjectList(Class tClass) { - List result = new ArrayList<>(); - List> classList = findInstantiatedSubclasses(tClass); - for (Class aClass : classList) { - try { - result.add(aClass.newInstance()); - } catch (Exception e) { - throw new BuggyConfigurationException("Can not create a new instance of the " + tClass.getSimpleName() + - " class " + aClass.getTypeName(), e); - } - } - return result; - } - - public static Component getComponent(Suite suite) { - try { - return suite.component().newInstance(); - } catch (Exception e) { - throw new BuggyConfigurationException("Can not create a new instance of the Component class " + - suite.component()); - } - } - - public static Service getService(Suite suite) { - try { - return suite.service().newInstance(); - } catch (Exception e) { - throw new BuggyConfigurationException("Can not create a new instance of the Service class " + - suite.service()); - } - } - - public static Interface getInterface(Suite suite) { - try { - return suite.interfaze().newInstance(); - } catch (Exception e) { - throw new BuggyConfigurationException("Can not create a new instance of the Interface class " + - suite.interfaze()); - } - } - - public static boolean equalsSuites(Suite s1, Suite s2) { - if (s1 == null || s2 == null) { - return false; - } - if (Objects.equals(s1, s2)) { - return true; - } - return s1.component().equals(s2.component()) && - s1.service().equals(s2.service()) && - s1.interfaze().equals(s2.interfaze()); - } - - public static Attributes getManifestAttributes() { - Manifest mf = getManifest(); - return mf.getMainAttributes(); - } - - public static Manifest getManifest() { - InputStream inputStream = IOHelper.getResourceAsStream("./META-INF/MANIFEST.MF"); - if (inputStream == null) { - inputStream = IOHelper.getResourceAsStream("META-INF/MANIFEST.MF"); - } - return readManifest(inputStream); - } - - private static Manifest readManifest(InputStream inputStream) { - Manifest manifest = new Manifest(); - try { - if (inputStream != null) { - manifest.read(inputStream); - } - return manifest; - } catch (IOException ignore) { - return manifest; - } - } - - private BuggyUtils() { - throw new IllegalStateException("Utility class. Prohibit instantiation."); - } - -} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/utils/ExitHandlerExpectedException.java b/buggy-core/src/main/java/org/touchbit/buggy/core/utils/ExitHandlerExpectedException.java deleted file mode 100644 index 1d0160c..0000000 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/utils/ExitHandlerExpectedException.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.touchbit.buggy.core.utils; - -public class ExitHandlerExpectedException extends RuntimeException { - - public ExitHandlerExpectedException() { - super("ExitHandler.exitRun() call expected."); - } - -} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/utils/IOHelper.java b/buggy-core/src/main/java/org/touchbit/buggy/core/utils/IOHelper.java index bff9c6e..c81ab04 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/utils/IOHelper.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/utils/IOHelper.java @@ -21,9 +21,11 @@ import com.google.common.io.Files; import org.touchbit.buggy.core.exceptions.BuggyException; -import java.io.*; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; import java.nio.charset.StandardCharsets; -import java.util.*; +import java.util.Properties; /** * Utility class work with OC. @@ -34,6 +36,10 @@ @SuppressWarnings({"ResultOfMethodCallIgnored", "UnstableApiUsage", "WeakerAccess"}) public class IOHelper { + private IOHelper() { + throw new IllegalStateException("Utility class. Prohibit instantiation."); + } + public static void copyFile(String sourceFile, String destFile) throws IOException { File from = new File(sourceFile); File to = new File(destFile); @@ -111,27 +117,4 @@ public static File getFileFromResource(final String file) { } } - /** - * Returns the file {@link File} from the resources. - * - * @param file - relative path to file - * @return {@link File} - */ - public static Properties readPropertiesFileFromResource(final String file) { - try (InputStream inputStream = getResourceAsStream(file)) { - if ((inputStream == null)) { - throw new BuggyException("The following file can not be found in the project resources: " + file); - } - final Properties properties = new Properties(); - properties.load(inputStream); - return properties; - } catch (IOException e) { - throw new BuggyException("Error reading file [" + file + "] from project resources", e); - } - } - - private IOHelper() { - throw new IllegalStateException("Utility class. Prohibit instantiation."); - } - } diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/utils/JUtils.java b/buggy-core/src/main/java/org/touchbit/buggy/core/utils/JUtils.java new file mode 100644 index 0000000..915ec47 --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/utils/JUtils.java @@ -0,0 +1,236 @@ +package org.touchbit.buggy.core.utils; + +import org.touchbit.buggy.core.exceptions.BuggyConfigurationException; +import org.touchbit.buggy.core.goal.Goal; +import org.touchbit.buggy.core.model.Suite; + +import java.io.IOException; +import java.io.InputStream; +import java.lang.management.ManagementFactory; +import java.lang.management.RuntimeMXBean; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.*; +import java.util.function.BiFunction; +import java.util.function.Function; +import java.util.function.Supplier; +import java.util.jar.Attributes; +import java.util.jar.Manifest; +import java.util.stream.Collectors; + +/** + * Created by Oleg Shaburov on 01.10.2020 + * shaburov.o.a@gmail.com + */ +public class JUtils { + + private JUtils() { + throw new IllegalStateException("Utility class. Prohibit instantiation."); + } + + public static T getGoal(Function> function, Suite s) { + Class tClass = function.apply(s); + return JUtils.newInstance(tClass, BuggyConfigurationException::new); + } + + @SafeVarargs + public static List getListWith(Supplier... suppliers) { + return Arrays.stream(suppliers).map(Supplier::get).collect(Collectors.toList()); + } + + @SafeVarargs + public static List getListWith(T... tClasses) { + return Arrays.stream(tClasses).collect(Collectors.toList()); + } + + @SuppressWarnings("unchecked") + public static A newInstance(String cName, + Class exp, + BiFunction s) throws U { + try { + Class aClass = (Class) getCurrentThreadClassLoader().loadClass(cName); + return newInstance(aClass, s); + } catch (Exception e) { + throw s.apply("Unable to load class " + cName, e); + } + } + + public static ClassLoader getCurrentThreadClassLoader() { + return Thread.currentThread().getContextClassLoader(); + } + + public static R newInstance(Class t, BiFunction s) throws U { + try { + return t.getDeclaredConstructor().newInstance(); + } catch (Exception e) { + throw s.apply("Unable to create an instance of " + t.getSimpleName() + ".class", e); + } + } + + public static boolean isJetBrainsIdeTestNGPluginRun() { + for (StackTraceElement stackTraceElement : Thread.currentThread().getStackTrace()) { + if (stackTraceElement.toString().contains("com.intellij.rt.testng")) { + return true; + } + } + return false; + } + + public static boolean isJetBrainsIdeConsoleRun() { + RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean(); + List arguments = runtimeMxBean.getInputArguments(); + String xpcServiceName = System.getenv("XPC_SERVICE_NAME"); + if (xpcServiceName != null && xpcServiceName.contains("com.jetbrains.intellij")) { + return true; + } + return arguments.stream() + .anyMatch(v -> v.startsWith("-javaagent") && + (v.contains("JetBrains") || v.contains("IDEA") || v.contains("idea"))); + } + + public static String getJetBrainsIdeConsoleRunTargetPath() { + String runDir = System.getProperty("user.dir"); + if (isJetBrainsIdeConsoleRun()) { + String javaClassPath = System.getProperty("java.class.path"); + if (javaClassPath != null && !javaClassPath.isEmpty()) { + String firstClassPath = javaClassPath.split(":")[0]; + if (firstClassPath.contains("/target/") && firstClassPath.contains(runDir)) { + String moduleTarget = firstClassPath.replace(runDir, "") + .replace("classes", ""); + if (moduleTarget.startsWith("/")) { + moduleTarget = moduleTarget.replaceFirst("/", ""); + } + while (moduleTarget.endsWith("/")) { + moduleTarget = moduleTarget.substring(0, moduleTarget.length() - 1); + } + return moduleTarget; + } + } + } + return runDir; + } + + public static List getFields(Object o) { + if (o != null) { + return getFields(o.getClass()); + } + return new ArrayList<>(); + } + + public static List getFields(Class c) { + ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); + Set> interfaces = getAllInterfacesForClassAsSet(c, contextClassLoader); + List fields = new ArrayList<>(); + fields.addAll(Arrays.asList(c.getDeclaredFields())); + fields.addAll(Arrays.asList(c.getFields())); + interfaces.forEach(i -> fields.addAll(Arrays.asList(i.getDeclaredFields()))); + interfaces.forEach(i -> fields.addAll(Arrays.asList(i.getFields()))); + return fields; + } + + public static List getMethods(Object o) { + if (o != null) { + return getMethods(o.getClass()); + } + return new ArrayList<>(); + } + + public static List getMethods(Class c) { + ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); + Set> interfaces = getAllInterfacesForClassAsSet(c, contextClassLoader); + List methods = new ArrayList<>(); + methods.addAll(Arrays.asList(c.getDeclaredMethods())); + methods.addAll(Arrays.asList(c.getMethods())); + interfaces.forEach(i -> methods.addAll(Arrays.asList(i.getDeclaredMethods()))); + interfaces.forEach(i -> methods.addAll(Arrays.asList(i.getMethods()))); + return methods; + } + + public static Set> getAllInterfacesForClassAsSet(Class clazz, ClassLoader classLoader) { + if (clazz.isInterface() && isLoadable(clazz, classLoader)) { + return Collections.singleton(clazz); + } + Set> interfaces = new LinkedHashSet<>(); + Class current = clazz; + while (current != null) { + Class[] ifcs = current.getInterfaces(); + interfaces.addAll(Arrays.asList(ifcs)); + current = current.getSuperclass(); + } + return interfaces; + } + + private static boolean isLoadable(Class clazz, ClassLoader classLoader) { + try { + return (clazz == classLoader.loadClass(clazz.getName())); + } catch (ClassNotFoundException ignore) { + return false; + } + } + + public static Map getBuggyManifest() { + return getManifestAttributesInfo("Buggy-"); + } + + public static Map getManifestAttributesInfo(String prefix) { + return getManifestAttributesInfo().entrySet().stream() + .filter(e -> String.valueOf(e.getKey()).startsWith(prefix) && e.getValue() != null) + .collect(Collectors.toMap(e -> e.getKey().replace(prefix, ""), Map.Entry::getValue)); + } + + public static Map getManifestAttributesInfo() { + Attributes attributes = getManifestAttributes(); + if (attributes != null) { + return attributes.entrySet().stream() + .collect(Collectors.toMap( + e -> String.valueOf(e.getKey()), + e -> String.valueOf(e.getValue()))); + } + return new HashMap<>(); + } + + public static Attributes getManifestAttributes() { + Manifest mf = getManifest(); + return mf.getMainAttributes(); + } + + public static Manifest getManifest() { + InputStream inputStream = IOHelper.getResourceAsStream("./META-INF/MANIFEST.MF"); + if (inputStream == null) { + inputStream = IOHelper.getResourceAsStream("META-INF/MANIFEST.MF"); + } + return readManifest(inputStream); + } + + public static Manifest readManifest(InputStream inputStream) { + Manifest manifest = new Manifest(); + try { + if (inputStream != null) { + manifest.read(inputStream); + } + return manifest; + } catch (IOException ignore) { + return manifest; + } + } + + public static String getSimpleNameC(Object o) { + return getSimpleNameC(o.getClass()); + } + + public static String getSimpleNameC(Class c) { + return getSimpleName(c) + ".class"; + } + + public static String getSimpleName(Object o) { + return getSimpleName(o.getClass()); + } + + public static String getSimpleName(Class c) { + if (c != null) { + return c.getSimpleName(); + } + return ""; + } + +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/utils/StringUtils.java b/buggy-core/src/main/java/org/touchbit/buggy/core/utils/StringUtils.java deleted file mode 100644 index f589339..0000000 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/utils/StringUtils.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright © 2018 Shaburov Oleg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.touchbit.buggy.core.utils; - -import java.net.URLDecoder; -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; - -import static java.util.Objects.isNull; - -/** - * Created by Oleg Shaburov on 08.09.2018 - * shaburov.o.a@gmail.com - */ -public class StringUtils { - - public static String underscoreFiller(Object prefix, int i) { - return underscoreFiller(prefix, i, null); - } - - public static String underscoreFiller(Object prefix, int i, Object suffix) { - return filler(prefix, "_", i, suffix); - } - - public static String dotFiller(Object prefix, int i) { - return dotFiller(prefix, i, null); - } - - public static String dotFiller(Object prefix, int i, Object suffix) { - return filler(prefix, ".", i, suffix); - } - - public static String filler(Object prefix, String symbol, int i) { - return filler(prefix, symbol, i, null); - } - - public static String filler(Object prefix, String symbol, int length, Object postfix) { - if (isNull(symbol) || symbol.isEmpty()) { - symbol = "."; - } - if (isNull(prefix)) { - prefix = ""; - } - if (isNull(postfix)) { - postfix = ""; - } - StringBuilder sb = new StringBuilder(); - int msgLen = (prefix.toString() + postfix.toString()).length(); - sb.append(prefix); - if (msgLen >= length) { - sb.append(symbol).append(symbol).append(symbol); - } - if (msgLen < length) { - for (int j = 0; j < (length - msgLen); j++) { - sb.append(symbol); - - } - } - sb.append(postfix); - return sb.toString(); - } - - /** - * Converts a string to an encoded URL format (using the UTF-8 encoding scheme). - * - * @param value string to be converted - * @return encoded URL string - */ - public static String encode(String value) { - try { - return URLEncoder.encode(value, StandardCharsets.UTF_8.name()); - } catch (Exception ignore) { - return value; - } - } - - /** - * Converts a string encoded in the URL format into its original representation (using UTF-8 encoding scheme). - * - * @param value coded string - * @return original string representation - */ - public static String decode(String value) { - try { - return URLDecoder.decode(value, StandardCharsets.UTF_8.name()); - } catch (Exception ignore) { - return value; - } - } - - public static void println(String msg) { - println(msg, null); - } - - public static void println(String msg, Throwable t) { - if (msg != null) { - System.out.println(msg); - } - if (t != null) { - t.printStackTrace(); - } - } - - private StringUtils() { - throw new IllegalStateException("Utility class. Prohibit instantiation."); - } -} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/utils/log/BuggyLog.java b/buggy-core/src/main/java/org/touchbit/buggy/core/utils/log/BuggyLog.java deleted file mode 100644 index 8fb5e80..0000000 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/utils/log/BuggyLog.java +++ /dev/null @@ -1,169 +0,0 @@ -/* - * Copyright © 2018 Shaburov Oleg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.touchbit.buggy.core.utils.log; - -import org.apache.logging.log4j.core.config.Configuration; -import org.apache.logging.log4j.core.config.LoggerConfig; -import org.atteo.classindex.IndexSubclasses; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.MDC; -import org.touchbit.buggy.core.Buggy; -import org.touchbit.buggy.core.exceptions.BuggyConfigurationException; -import org.touchbit.buggy.core.utils.IOHelper; -import org.touchbit.buggy.core.utils.StringUtils; - -import java.io.File; - -/** - * Basic implementation of the test logger. - *

- * Created by Oleg Shaburov on 17.05.2018 - * shaburov.o.a@gmail.com - */ -@SuppressWarnings({"WeakerAccess", "unused", "squid:S1118"}) -@IndexSubclasses -public class BuggyLog { - - private static final String CONFIG = "log4j2.xml"; - private static final String DEFAULT_CONFIG = "buggy-log4j2.xml"; - - public static final String LOG_FILE_NAME = "log.file.name"; - public static final String LOG_DIRECTORY = "log.directory"; - - protected static Logger console; - protected static Logger framework; - protected static Logger test; - private static String logPath; - private static Configuration configuration; - - static { - System.setProperty("java.util.logging.manager", "org.apache.logging.log4j.jul.LogManager"); - } - - public BuggyLog() { - loadDefaultConfig(); - } - - public BuggyLog(Logger consoleLogger, Logger frameworkLogger, Logger testLogger) { - checkBuggyConfiguration(); - setConsoleLog(consoleLogger); - setFrameworkLog(frameworkLogger); - setTestLog(testLogger); - } - - public static String getLogsDirPath() { - return logPath; - } - - public static void setLogsDirPath(String path) { - if (path == null) { - throw new BuggyConfigurationException("The path to the log directory can not be empty"); - } - logPath = path; - System.setProperty(LOG_DIRECTORY, logPath); - } - - public static void setTestLogFileName(String logName) { - MDC.put(LOG_FILE_NAME, logName); - } - - public static synchronized void loadDefaultConfig() { - checkBuggyConfiguration(); - Exception exception = null; - try { - configuration = XMLLogConfigurator.reloadXMLConfiguration(CONFIG); - } catch (Exception e) { - exception = e; - } - StringUtils.println(StringUtils - .dotFiller("Load " + CONFIG + " configuration", 47, exception != null ? "FAIL" : "OK")); - if (exception != null) { - exception = null; - try { - configuration = XMLLogConfigurator.reloadXMLConfiguration(DEFAULT_CONFIG); - } catch (Exception e) { - exception = e; - } - StringUtils.println(StringUtils - .dotFiller("Load " + DEFAULT_CONFIG + " configuration", 47, - exception != null ? "FAIL" : "OK")); - } - if (exception == null) { - setTestLog(LoggerFactory.getLogger("Routing")); - setConsoleLog(LoggerFactory.getLogger("Console")); - setFrameworkLog(LoggerFactory.getLogger("Framework")); - } - StringUtils.println(StringUtils.filler(null, "\u2014", 47, null)); - StringUtils.println(StringUtils.filler("Logger", " ", 47, "Level")); - StringUtils.println(StringUtils.filler(null, "\u2014", 47, null)); - if (configuration != null) { - configuration.getLoggers() - .forEach((k, v) -> { - String name = v.getName(); - // Short Class name - if (name.contains(".") && name.lastIndexOf('.') < name.length() - 1) { - name = name.substring(name.lastIndexOf('.') + 1); - } - StringUtils - .println(StringUtils.dotFiller(name, 47, v.getLevel())); - }); - framework.info("Log4j2 appenders: {}", configuration.getLoggerContext().getConfiguration().getAppenders()); - framework.info("Log4j2 loggers: {}", configuration.getLoggerContext().getLoggers()); - framework.info("Log4j2 configuration location: {}", configuration.getLoggerContext().getConfigLocation()); - String conf = IOHelper.readFile(new File(configuration.getLoggerContext().getConfigLocation())); - framework.trace("Log4j2 configuration:\n{}", conf); - } else { - LoggerConfig root = XMLLogConfigurator.getRootLoggerConfig(); - StringUtils.println(StringUtils.dotFiller(root, 47, root.getLevel())); - } - } - - public static Logger console() { - return console; - } - - public static Logger test() { - return test; - } - - public static Logger framework() { - return framework; - } - - public static void setConsoleLog(Logger console) { - BuggyLog.console = console; - } - - public static void setFrameworkLog(Logger framework) { - BuggyLog.framework = framework; - } - - public static void setTestLog(Logger test) { - BuggyLog.test = test; - } - - private static void checkBuggyConfiguration() { - if (!Buggy.isPrimaryConfigInitialized()) { - Buggy.getExitHandler().exitRun(1, "The logger cannot be initialized before the Buggy configuration."); - } - if (logPath == null) { - setLogsDirPath(Buggy.getPrimaryConfig().getAbsoluteLogPath()); - } - } - -} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/utils/log/XMLLogConfigurator.java b/buggy-core/src/main/java/org/touchbit/buggy/core/utils/log/XMLLogConfigurator.java deleted file mode 100644 index 31e212b..0000000 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/utils/log/XMLLogConfigurator.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright © 2018 Shaburov Oleg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.touchbit.buggy.core.utils.log; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.core.LoggerContext; -import org.apache.logging.log4j.core.config.Configuration; -import org.apache.logging.log4j.core.config.ConfigurationSource; -import org.apache.logging.log4j.core.config.LoggerConfig; -import org.apache.logging.log4j.core.config.xml.XmlConfiguration; -import org.touchbit.buggy.core.exceptions.BuggyConfigurationException; - -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; - -import static org.touchbit.buggy.core.utils.IOHelper.getFileFromResource; - -/** - * The class is designed to programmatically add loggers to the existing log4j2 configuration - *

- * Created by Oleg Shaburov on 17.05.2018 - * shaburov.o.a@gmail.com - */ -@SuppressWarnings({"WeakerAccess"}) -public class XMLLogConfigurator { - - private static final LoggerContext CONTEXT = (LoggerContext) LogManager.getContext(false); - - public static Configuration reloadXMLConfiguration(String log4j2ConfigFile) { - try { - File file = getFileFromResource(log4j2ConfigFile); - CONTEXT.setConfigLocation(file.toURI()); - try (InputStream targetStream = new FileInputStream(file)) { - Config configuration = new Config(CONTEXT, new ConfigurationSource(targetStream)); - return configuration.getLoggerContext().getConfiguration(); - } - } catch (Exception e) { - throw new BuggyConfigurationException("Reload log4j2 configuration is failed. Configuration path: " + - log4j2ConfigFile, e); - } - } - - public static LoggerConfig getRootLoggerConfig() { - return CONTEXT.getRootLogger().get(); - } - - private static class Config extends XmlConfiguration { - - private Config(final LoggerContext loggerContext, final ConfigurationSource configSource) { - super(loggerContext, configSource); - doConfigure(); - } - - } - - private XMLLogConfigurator() { - throw new IllegalStateException("Utility class. Prohibit instantiation."); - } - -} diff --git a/buggy-core/src/main/resources/buggy-config.yml b/buggy-core/src/main/resources/buggy-config.yml new file mode 100644 index 0000000..132142e --- /dev/null +++ b/buggy-core/src/main/resources/buggy-config.yml @@ -0,0 +1,22 @@ +programName: Buggy +help: false +forceRun: true +threads: 50 +parallelMode: 'METHODS' +artifactsUrl: null +components: + - !!org.touchbit.buggy.core.goal.component.AllComponents {} +services: + - !!org.touchbit.buggy.core.goal.service.AllServices {} +interfaces: + - !!org.touchbit.buggy.core.goal.interfaze.AllInterfaces {} +types: + - ALL +issuesUrl: '' +testCaseTitle: true +testSuiteInfo: false +testLogFilePath: true +testIssuesInfo: false +testBugsInfo: true +testErrorInfo: true +outputRule: UNSUCCESSFUL \ No newline at end of file diff --git a/buggy-core/src/main/resources/buggy-log4j2.xml b/buggy-core/src/main/resources/buggy-log4j2.xml deleted file mode 100644 index a9dd873..0000000 --- a/buggy-core/src/main/resources/buggy-log4j2.xml +++ /dev/null @@ -1,58 +0,0 @@ - - - - - ${sys:log.directory} - - %d{HH:mm:ss.SSS} - %m%n - %d{HH:mm:ss.SSS} %-5level - %m%n - - {FATAL=red blink, ERROR=red, WARN=Magenta, INFO=NAN, DEBUG=green, TRACE=blue} - red bright - {FATAL=${rb}, ERROR=${rb}, WARN=${rb}, INFO=${rb}, DEBUG=${rb}, TRACE=${rb}} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/buggy-core/src/main/resources/buggy-logback.xml b/buggy-core/src/main/resources/buggy-logback.xml new file mode 100644 index 0000000..085af35 --- /dev/null +++ b/buggy-core/src/main/resources/buggy-logback.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/buggy-core/src/main/resources/buggy.properties b/buggy-core/src/main/resources/buggy.properties deleted file mode 100644 index 6a2101c..0000000 --- a/buggy-core/src/main/resources/buggy.properties +++ /dev/null @@ -1,21 +0,0 @@ -# -# Copyright © 2018 Shaburov Oleg -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -# suppress inspection "WrongPropertyKeyValueDelimiter" for whole file ---all ---force ---print-suite ---print-cause ---print-log ---type=SYSTEM \ No newline at end of file diff --git a/buggy-core/src/test/java/org/touchbit/buggy/core/config/DisabledUnitTestListener.java b/buggy-core/src/test/java/org/touchbit/buggy/core/config/DisabledUnitTestListener.java index 6b6c9e2..20a81c7 100644 --- a/buggy-core/src/test/java/org/touchbit/buggy/core/config/DisabledUnitTestListener.java +++ b/buggy-core/src/test/java/org/touchbit/buggy/core/config/DisabledUnitTestListener.java @@ -1,6 +1,6 @@ package org.touchbit.buggy.core.config; -import org.touchbit.buggy.core.testng.listeners.BuggyListener; +import org.touchbit.buggy.core.testng.BuggyListener; /** * Created by Oleg Shaburov on 22.10.2018 diff --git a/buggy-core/src/test/java/org/touchbit/buggy/core/config/EnabledUnitTestListener.java b/buggy-core/src/test/java/org/touchbit/buggy/core/config/EnabledUnitTestListener.java index f4b0772..3a06c9f 100644 --- a/buggy-core/src/test/java/org/touchbit/buggy/core/config/EnabledUnitTestListener.java +++ b/buggy-core/src/test/java/org/touchbit/buggy/core/config/EnabledUnitTestListener.java @@ -1,6 +1,6 @@ package org.touchbit.buggy.core.config; -import org.touchbit.buggy.core.testng.listeners.BuggyListener; +import org.touchbit.buggy.core.testng.BuggyListener; /** * Created by Oleg Shaburov on 22.10.2018 diff --git a/buggy-core/src/test/java/org/touchbit/buggy/core/config/TestClassWithSuite.java b/buggy-core/src/test/java/org/touchbit/buggy/core/config/TestClassWithSuite.java index fba2e40..2f288e2 100644 --- a/buggy-core/src/test/java/org/touchbit/buggy/core/config/TestClassWithSuite.java +++ b/buggy-core/src/test/java/org/touchbit/buggy/core/config/TestClassWithSuite.java @@ -17,19 +17,19 @@ package org.touchbit.buggy.core.config; import org.testng.annotations.Test; -import org.touchbit.buggy.core.model.Details; +import org.touchbit.buggy.core.BaseBuggyTest; +import org.touchbit.buggy.core.model.Buggy; import org.touchbit.buggy.core.model.Suite; -import org.touchbit.buggy.core.test.BaseBuggyTest; /** * Created by Oleg Shaburov on 20.09.2018 * shaburov.o.a@gmail.com */ -@Suite(component = TestComponent.class, service = TestService.class, interfaze = TestInterface.class, task = "unit_test") +@Suite(component = TestComponent.class, service = TestService.class, interfaze = TestInterface.class, purpose = "unit_test") public class TestClassWithSuite extends BaseBuggyTest { @Test(description = "test_20181021171954") - @Details + @Buggy public void test_20181021171954() { step("Example step test_20181021171954"); } diff --git a/buggy-core/src/test/java/org/touchbit/buggy/core/config/TestClassWithoutSuite.java b/buggy-core/src/test/java/org/touchbit/buggy/core/config/TestClassWithoutSuite.java index e09a660..e355ac1 100644 --- a/buggy-core/src/test/java/org/touchbit/buggy/core/config/TestClassWithoutSuite.java +++ b/buggy-core/src/test/java/org/touchbit/buggy/core/config/TestClassWithoutSuite.java @@ -17,8 +17,8 @@ package org.touchbit.buggy.core.config; import org.testng.annotations.Test; -import org.touchbit.buggy.core.model.Details; -import org.touchbit.buggy.core.test.BaseBuggyTest; +import org.touchbit.buggy.core.BaseBuggyTest; +import org.touchbit.buggy.core.model.Buggy; /** * Created by Oleg Shaburov on 20.09.2018 @@ -27,7 +27,7 @@ public class TestClassWithoutSuite extends BaseBuggyTest { @Test(description = "test_20180920150514") - @Details + @Buggy public void test_20180920150514() { step("Example step test_20180920150514"); } diff --git a/buggy-core/src/test/java/org/touchbit/buggy/core/config/TestComponent.java b/buggy-core/src/test/java/org/touchbit/buggy/core/config/TestComponent.java index d6b2285..56bc4ac 100644 --- a/buggy-core/src/test/java/org/touchbit/buggy/core/config/TestComponent.java +++ b/buggy-core/src/test/java/org/touchbit/buggy/core/config/TestComponent.java @@ -1,10 +1,6 @@ package org.touchbit.buggy.core.config; -import org.touchbit.buggy.core.process.Component; -import org.touchbit.buggy.core.process.Service; - -import java.util.ArrayList; -import java.util.List; +import org.touchbit.buggy.core.goal.component.Component; /** * Created by Oleg Shaburov on 16.09.2018 @@ -12,11 +8,6 @@ */ public class TestComponent extends Component { - @Override - public List getServices() { - return new ArrayList() {{add(new TestService());}}; - } - @Override public String getDescription() { return "TestComponent"; diff --git a/buggy-core/src/test/java/org/touchbit/buggy/core/config/TestExitHandler.java b/buggy-core/src/test/java/org/touchbit/buggy/core/config/TestExitHandler.java deleted file mode 100644 index 79f30aa..0000000 --- a/buggy-core/src/test/java/org/touchbit/buggy/core/config/TestExitHandler.java +++ /dev/null @@ -1,72 +0,0 @@ -package org.touchbit.buggy.core.config; - -import org.touchbit.buggy.core.Buggy; - -/** - * Created by Oleg Shaburov on 16.10.2018 - * shaburov.o.a@gmail.com - */ -public class TestExitHandler extends Buggy.DefaultBuggyProcessor.DefaultBuggySystemExitHandler { - - private Throwable throwable = null; - private Integer status = null; - private String msg = null; - - private Boolean isWorked = false; - - public void realExitRunWithUsage(int status, String msg) { - super.exitRunWithUsage(status, msg); - } - - @Override - public void exitRun(int status) { - exitRun(status, null, null); - } - - @Override - public void exitRun(int status, String msg) { - exitRun(status, msg, null); - } - - @Override - public synchronized void exitRun(int status, String msg, Throwable t) { - if (isWorked) { - return; - } - this.throwable = t; - this.status = status; - this.msg = msg; - isWorked = true; - } - - @Override - public void exit(int status) { - exitRun(status, null, null); - } - - public void clean() { - throwable = null; - status = null; - msg = null; - isWorked = false; - } - - public Throwable getThrowable() { - Throwable throwable = this.throwable; - this.throwable = null; - return throwable; - } - - public Integer getStatus() { - Integer status = this.status; - this.status = null; - return status; - } - - public String getMsg() { - String msg = this.msg; - this.msg = null; - return msg; - } - -} \ No newline at end of file diff --git a/buggy-core/src/test/java/org/touchbit/buggy/core/config/TestInterface.java b/buggy-core/src/test/java/org/touchbit/buggy/core/config/TestInterface.java index 9cbfc3e..ee1c77c 100644 --- a/buggy-core/src/test/java/org/touchbit/buggy/core/config/TestInterface.java +++ b/buggy-core/src/test/java/org/touchbit/buggy/core/config/TestInterface.java @@ -1,6 +1,6 @@ package org.touchbit.buggy.core.config; -import org.touchbit.buggy.core.process.Interface; +import org.touchbit.buggy.core.goal.interfaze.Interface; /** * Created by Oleg Shaburov on 16.09.2018 diff --git a/buggy-core/src/test/java/org/touchbit/buggy/core/config/TestNGTestClassWithSuite.java b/buggy-core/src/test/java/org/touchbit/buggy/core/config/TestNGTestClassWithSuite.java index 48a742c..336fb82 100644 --- a/buggy-core/src/test/java/org/touchbit/buggy/core/config/TestNGTestClassWithSuite.java +++ b/buggy-core/src/test/java/org/touchbit/buggy/core/config/TestNGTestClassWithSuite.java @@ -1,7 +1,7 @@ package org.touchbit.buggy.core.config; import org.testng.annotations.Test; -import org.touchbit.buggy.core.model.Details; +import org.touchbit.buggy.core.model.Buggy; import org.touchbit.buggy.core.model.Suite; /** @@ -12,7 +12,7 @@ public class TestNGTestClassWithSuite { @Test - @Details + @Buggy public void iTestResultMethodWithDetails() { } diff --git a/buggy-core/src/test/java/org/touchbit/buggy/core/config/TestService.java b/buggy-core/src/test/java/org/touchbit/buggy/core/config/TestService.java index 2dd204e..b3447e9 100644 --- a/buggy-core/src/test/java/org/touchbit/buggy/core/config/TestService.java +++ b/buggy-core/src/test/java/org/touchbit/buggy/core/config/TestService.java @@ -1,6 +1,6 @@ package org.touchbit.buggy.core.config; -import org.touchbit.buggy.core.process.Service; +import org.touchbit.buggy.core.goal.service.Service; /** * Created by Oleg Shaburov on 16.09.2018 diff --git a/buggy-core/src/test/java/org/touchbit/buggy/core/config/UnitTestPrimaryConfig.java b/buggy-core/src/test/java/org/touchbit/buggy/core/config/UnitTestPrimaryConfig.java deleted file mode 100644 index eeb6238..0000000 --- a/buggy-core/src/test/java/org/touchbit/buggy/core/config/UnitTestPrimaryConfig.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.touchbit.buggy.core.config; - -/** - * Created by Oleg Shaburov on 15.09.2018 - * shaburov.o.a@gmail.com - */ -public class UnitTestPrimaryConfig implements PrimaryConfig { - - private static class UnitTestPrimaryConfigs extends UnitTestPrimaryConfig { - } - -} diff --git a/buggy-core/src/test/java/org/touchbit/buggy/core/config/UnitTestSecondaryConfig.java b/buggy-core/src/test/java/org/touchbit/buggy/core/config/UnitTestSecondaryConfig.java deleted file mode 100644 index b71410e..0000000 --- a/buggy-core/src/test/java/org/touchbit/buggy/core/config/UnitTestSecondaryConfig.java +++ /dev/null @@ -1,11 +0,0 @@ -package org.touchbit.buggy.core.config; - -import com.beust.jcommander.Parameters; - -/** - * Created by Oleg Shaburov on 15.09.2018 - * shaburov.o.a@gmail.com - */ -@Parameters(commandNames = "junit") -public class UnitTestSecondaryConfig implements SecondaryConfig { -} diff --git a/buggy-core/src/test/java/org/touchbit/buggy/core/helpful/SystemOutLogger.java b/buggy-core/src/test/java/org/touchbit/buggy/core/helpful/SystemOutLogger.java index 57be849..099518a 100644 --- a/buggy-core/src/test/java/org/touchbit/buggy/core/helpful/SystemOutLogger.java +++ b/buggy-core/src/test/java/org/touchbit/buggy/core/helpful/SystemOutLogger.java @@ -8,13 +8,33 @@ */ public class SystemOutLogger extends UnitTestLogger { - public SystemOutLogger(File logFile){ + public SystemOutLogger(File logFile) { OutputStream outputStream = getPrintStream(logFile); LoggerPrintStream loggerPrintStream = new LoggerPrintStream(this, outputStream); System.setOut(loggerPrintStream); System.setErr(loggerPrintStream); } + private static OutputStream getPrintStream(File logFile) { + try { + if (logFile.createNewFile()) { + System.out.println("\nSystem.out log file path: " + logFile.getAbsolutePath() + "\n"); + return new PrintStream(new BufferedOutputStream(new FileOutputStream(logFile)), true); + } else { + return new FakeOutputStream(); + } + } catch (Exception e) { + e.printStackTrace(); + return new FakeOutputStream(); + } + } + + public static class FakeOutputStream extends OutputStream { + @Override + public void write(int b) { + } + } + private class LoggerPrintStream extends PrintStream { private SystemOutLogger logger; @@ -37,23 +57,4 @@ public void println(String line) { } - private static OutputStream getPrintStream(File logFile) { - try { - if (logFile.createNewFile()) { - System.out.println("\nSystem.out log file path: " + logFile.getAbsolutePath() + "\n"); - return new PrintStream(new BufferedOutputStream(new FileOutputStream(logFile)), true); - } else { - return new FakeOutputStream(); - } - } catch (Exception e) { - e.printStackTrace(); - return new FakeOutputStream(); - } - } - - public static class FakeOutputStream extends OutputStream { - @Override - public void write(int b) { } - } - } diff --git a/buggy-core/src/test/java/org/touchbit/buggy/core/helpful/UnitTestLogger.java b/buggy-core/src/test/java/org/touchbit/buggy/core/helpful/UnitTestLogger.java index b187b15..ff99f12 100644 --- a/buggy-core/src/test/java/org/touchbit/buggy/core/helpful/UnitTestLogger.java +++ b/buggy-core/src/test/java/org/touchbit/buggy/core/helpful/UnitTestLogger.java @@ -1,18 +1,11 @@ package org.touchbit.buggy.core.helpful; -import org.apache.logging.log4j.Level; -import org.apache.logging.log4j.Marker; -import org.apache.logging.log4j.message.Message; -import org.apache.logging.log4j.spi.AbstractLogger; -import org.apache.logging.slf4j.Log4jLogger; import org.slf4j.helpers.SubstituteLogger; import java.util.ArrayList; import java.util.Collections; import java.util.List; -import static org.apache.logging.log4j.Level.ALL; - /** * Created by Oleg Shaburov on 16.10.2018 * shaburov.o.a@gmail.com @@ -30,7 +23,7 @@ public class UnitTestLogger extends SubstituteLogger { public UnitTestLogger() { super("UnitTestLogger", null, false); - setDelegate(new Log4jLogger(new UnitTestLog4jLogger(), "UnitTestLog4jLogger")); +// setDelegate(new Log4jLogger(new UnitTestLog4jLogger(), "UnitTestLog4jLogger")); } public List takeLoggedMessages() { @@ -55,100 +48,6 @@ public void reset() { this.isInfo = true; } - private class UnitTestLog4jLogger extends AbstractLogger { - - @Override - public void logMessage(String fqcn, Level level, Marker marker, Message message, Throwable t) { - loggedMessages.add(message.getFormattedMessage()); - loggedMessagesWithLevel.add(level + " " + message.getFormattedMessage()); - } - - @Override - public boolean isEnabled(Level level, Marker marker, Message message, Throwable t) { - return true; - } - - @Override - public boolean isEnabled(Level level, Marker marker, CharSequence message, Throwable t) { - return true; - } - - @Override - public boolean isEnabled(Level level, Marker marker, Object message, Throwable t) { - return true; - } - - @Override - public boolean isEnabled(Level level, Marker marker, String message, Throwable t) { - return true; - } - - @Override - public boolean isEnabled(Level level, Marker marker, String message) { - return true; - } - - @Override - public boolean isEnabled(Level level, Marker marker, String message, Object... params) { - return true; - } - - @Override - public boolean isEnabled(Level level, Marker marker, String message, Object p0) { - return true; - } - - @Override - public boolean isEnabled(Level level, Marker marker, String message, Object p0, Object p1) { - return true; - } - - @Override - public boolean isEnabled(Level level, Marker marker, String message, Object p0, Object p1, Object p2) { - return true; - } - - @Override - public boolean isEnabled(Level level, Marker marker, String message, Object p0, Object p1, Object p2, Object p3) { - return true; - } - - @Override - public boolean isEnabled(Level level, Marker marker, String message, Object p0, Object p1, Object p2, Object p3, Object p4) { - return true; - } - - @Override - public boolean isEnabled(Level level, Marker marker, String message, Object p0, Object p1, Object p2, Object p3, Object p4, Object p5) { - return true; - } - - @Override - public boolean isEnabled(Level level, Marker marker, String message, Object p0, Object p1, Object p2, Object p3, Object p4, Object p5, Object p6) { - return true; - } - - @Override - public boolean isEnabled(Level level, Marker marker, String message, Object p0, Object p1, Object p2, Object p3, Object p4, Object p5, Object p6, Object p7) { - return true; - } - - @Override - public boolean isEnabled(Level level, Marker marker, String message, Object p0, Object p1, Object p2, Object p3, Object p4, Object p5, Object p6, Object p7, Object p8) { - return true; - } - - @Override - public boolean isEnabled(Level level, Marker marker, String message, Object p0, Object p1, Object p2, Object p3, Object p4, Object p5, Object p6, Object p7, Object p8, Object p9) { - return true; - } - - @Override - public Level getLevel() { - return ALL; - } - } - @Override public boolean isDebugEnabled() { return this.isDebug; diff --git a/buggy-core/src/test/java/org/touchbit/buggy/core/tests/BaseUnitTest.java b/buggy-core/src/test/java/org/touchbit/buggy/core/tests/BaseUnitTest.java index 08b5ee3..d32405e 100644 --- a/buggy-core/src/test/java/org/touchbit/buggy/core/tests/BaseUnitTest.java +++ b/buggy-core/src/test/java/org/touchbit/buggy/core/tests/BaseUnitTest.java @@ -1,7 +1,5 @@ package org.touchbit.buggy.core.tests; -import org.jetbrains.annotations.Nullable; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.function.Executable; import org.slf4j.Logger; import org.testng.IInvokedMethod; @@ -9,36 +7,33 @@ import org.testng.ITestNGMethod; import org.testng.ITestResult; import org.testng.internal.ConstructorOrMethod; -import org.touchbit.buggy.core.Buggy; -import org.touchbit.buggy.core.ExitHandler; -import org.touchbit.buggy.core.config.*; -import org.touchbit.buggy.core.helpful.SystemOutLogger; +import org.touchbit.buggy.core.config.TestComponent; +import org.touchbit.buggy.core.config.TestInterface; +import org.touchbit.buggy.core.config.TestNGTestClassWithSuite; +import org.touchbit.buggy.core.config.TestService; +import org.touchbit.buggy.core.goal.component.Component; +import org.touchbit.buggy.core.goal.interfaze.Interface; +import org.touchbit.buggy.core.goal.service.Service; import org.touchbit.buggy.core.helpful.UnitTestLogger; -import org.touchbit.buggy.core.model.Details; +import org.touchbit.buggy.core.model.Buggy; import org.touchbit.buggy.core.model.Status; import org.touchbit.buggy.core.model.Suite; import org.touchbit.buggy.core.model.Type; -import org.touchbit.buggy.core.process.Component; -import org.touchbit.buggy.core.process.Interface; -import org.touchbit.buggy.core.process.Service; -import org.touchbit.buggy.core.testng.listeners.BuggyExecutionListener; -import org.touchbit.buggy.core.utils.log.BuggyLog; +import org.touchbit.buggy.core.testng.BuggyExecutionListener; -import java.io.*; +import java.io.File; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Method; -import java.util.ArrayList; import java.util.UUID; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -import static org.touchbit.buggy.core.model.Status.SUCCESS; import static org.touchbit.buggy.core.model.Type.MODULE; import static org.touchbit.buggy.core.model.Type.SYSTEM; -import static org.touchbit.buggy.core.utils.log.BuggyLog.LOG_DIRECTORY; /** * Created by Oleg Shaburov on 15.09.2018 @@ -47,115 +42,12 @@ @SuppressWarnings({"WeakerAccess", "ResultOfMethodCallIgnored"}) public abstract class BaseUnitTest { + // protected static final Logger LOG = NOP_LOGGER; + protected static final UnitTestLogger TEST_LOGGER = new UnitTestLogger(); private static String runDir = new File(BaseUnitTest.class .getProtectionDomain().getCodeSource().getLocation().getPath()) .getParentFile().getAbsolutePath(); -// protected static final Logger LOG = NOP_LOGGER; - protected static final String WASTE; - protected static final String CLASSES; - protected static final String TEST_CLASSES; - protected static final UnitTestLogger SYSTEM_OUT_LOGGER; - protected static final UnitTestLogger TEST_LOGGER = new UnitTestLogger(); - protected static final TestExitHandler EXIT_HANDLER = new TestExitHandler(); - - static { - WASTE = runDir + "/waste-unit-tests"; - CLASSES = runDir + "/classes"; - TEST_CLASSES = runDir + "/test-classes"; - System.setProperty(LOG_DIRECTORY, WASTE + "/"); - File wasteDir = new File(WASTE); - File logFile = new File(WASTE, "console.txt"); - delete(wasteDir); - wasteDir.mkdirs(); - SYSTEM_OUT_LOGGER = new SystemOutLogger(logFile); - Buggy.setBuggyLogClass(TestBuggyLog.class); - Buggy.setBuggyProcessor(new UnitTestBuggyProcessor()); - Buggy.setPrimaryConfigClass(UnitTestPrimaryConfig.class); - Buggy.prepare(); - } - - @BeforeEach - public void clean() { - Buggy.reset(); - Buggy.setBuggyProcessor(new UnitTestBuggyProcessor()); - Buggy.setPrimaryConfigClass(UnitTestPrimaryConfig.class); - Buggy.setSecondaryConfigClasses(new ArrayList<>()); - Buggy.setBuggyLogClass(TestBuggyLog.class); - EXIT_HANDLER.clean(); - TEST_LOGGER.reset(); - SYSTEM_OUT_LOGGER.reset(); - Buggy.getPrimaryConfig().setCheck(false); - Buggy.getPrimaryConfig().setAbsoluteLogPath(WASTE); - Buggy.getPrimaryConfig().setPrintAllParameters(false); - Buggy.getPrimaryConfig().setPrintCause(false); - Buggy.getPrimaryConfig().setPrintSuite(false); - Buggy.getPrimaryConfig().setPrintLogFile(false); - Buggy.getPrimaryConfig().setArtifactsUrl(null); - BuggyExecutionListener.setSteps(new ArrayList<>()); - new BuggyExecutionListener() {}; - } - - public static class TestBuggyLog extends BuggyLog { - - public TestBuggyLog() { - super(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - } - - } - - public static class UnitTestBuggyProcessor extends Buggy.DefaultBuggyProcessor { - @Override - public TestExitHandler getExitHandler() { - return EXIT_HANDLER; - } - - @Override - public String getReportsOutputDirectory() { - return WASTE + "/reports"; - } - - public String getRealReportsOutputDirectory() { - return super.getReportsOutputDirectory(); - } - - public ExitHandler getRealExitHandler() { - return super.getExitHandler(); - } - } - - protected void assertExitCode(Integer code) { - assertExitCode(code, null, null); - } - - @SuppressWarnings("SameParameterValue") - protected void assertExitCode(Integer code, String msg) { - assertExitCode(code, msg, null); - } - - @SuppressWarnings("SameParameterValue") - protected void assertExitCode(Integer code, String msg, Class throwableClass) { - try { - if (code == null) { - assertThat(EXIT_HANDLER.getStatus(), is(nullValue())); - } else { - assertThat(EXIT_HANDLER.getStatus(), is(code)); - } - if (msg == null) { - assertThat(EXIT_HANDLER.getMsg(), is(nullValue())); - } else { - assertThat(EXIT_HANDLER.getMsg(), is(msg)); - } - if (throwableClass == null) { - assertThat(EXIT_HANDLER.getThrowable(), is(nullValue())); - } else { - assertThat(EXIT_HANDLER.getThrowable(), is(instanceOf(throwableClass))); - } - } finally { - EXIT_HANDLER.clean(); - } - } - @SuppressWarnings({"ConstantConditions", "ResultOfMethodCallIgnored"}) private static void delete(File file) { if (file.exists() && file.isDirectory()) { @@ -166,38 +58,6 @@ private static void delete(File file) { file.delete(); } - protected void checkUtilityClassConstructor(Class clazz) throws NoSuchMethodException { - Constructor constructor = clazz.getDeclaredConstructor(); - constructor.setAccessible(true); - Throwable exception = execute(constructor::newInstance); - assertThat(exception.getCause(), instanceOf(IllegalStateException.class)); - assertThat(exception.getCause().getMessage(), is("Utility class. Prohibit instantiation.")); - } - - @SuppressWarnings({"unchecked", "WeakerAccess"}) - protected Throwable execute(Executable executable) { - Throwable throwable = null; - try { - executable.execute(); - } catch (Throwable e) { - throwable = e; - } - assertThat("Exception is present", throwable != null, is(true)); - return throwable; - } - - @SuppressWarnings({"unchecked", "SameParameterValue"}) - protected T execute(Executable executable, Class exceptionClass) { - Throwable throwable = null; - try { - executable.execute(); - } catch (Throwable e) { - throwable = e; - } - assertThat(throwable, instanceOf(exceptionClass)); - return (T) throwable; - } - protected static IInvokedMethod getMockIInvokedMethod() { return getMockIInvokedMethod(true); } @@ -269,126 +129,60 @@ protected static ITestResult getMockITestResult(Integer status) { return iTestResult; } - protected BuggyExecutionListener getBuggyExecutionListener() { - return getBuggyExecutionListener(true); + protected static Buggy getDetails(Status status, String... issue) { + return getDetails(status, SYSTEM, issue); } - @SuppressWarnings("SameParameterValue") - protected BuggyExecutionListener getBuggyExecutionListener(boolean withOverrideCopyFile) { - - return new BuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER) { + protected static Buggy getDetails(Status status, Type type, String... issue) { + return getDetails(new String[] {"0"}, status, new Type[]{type}, issue); + } + protected static Buggy getDetails(String[] ids, Status status, Type[] type, String... issue) { + return new Buggy() { @Override - public void copyFile(File sourceFile, File destFile) throws IOException { - if (!withOverrideCopyFile) { - super.copyFile(sourceFile, destFile); - } + public String value() { + return null; } - }; - - } - - protected class UnitTestBuggyExecutionListener extends BuggyExecutionListener { - - public ITestNGMethod method; - public Status status; - public String msg; - public Details details; - public File sourceFile; - public File targetFile; - - public UnitTestBuggyExecutionListener() { - this(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - } - - public UnitTestBuggyExecutionListener(Details details) { - this(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER, details); - } - - public UnitTestBuggyExecutionListener(Logger testLogger, Logger frameworkLogger, Logger consoleLogger) { - this(testLogger, frameworkLogger, consoleLogger, null); - } - - public UnitTestBuggyExecutionListener(Logger testLogger, Logger frameworkLogger, Logger consoleLogger, Details details) { - super(testLogger, frameworkLogger, consoleLogger); - this.details = details; - testCount.set(0); - skippedTests.set(0); - corruptedError.set(0); - expFixError.set(0); - expImplError.set(0); - blockedError.set(0); - newError.set(0); - fixed.set(0); - implemented.set(0); - } - - @Override - public void resultLog(ITestNGMethod method, Status status, String details) { - this.method = method; - this.status = status; - this.msg = details; - } - - @Override - protected @Nullable Details getDetails(Method method) { - return details; - } - - @Override - public void copyFile(File sourceFile, File destFile) { - this.sourceFile = sourceFile; - this.targetFile = destFile; - } - - @Override - public void printASCIIStatus(Status status, String msg) { - super.printASCIIStatus(status, msg); - } - - @Override - public void increment(Status status) { - super.increment(status); - } - - } - - @SuppressWarnings("unused") - protected static Details getDetails() { - return getDetails(SUCCESS, MODULE); - } - - protected static Details getDetails(Type type) { - return getDetails(SUCCESS, type); - } - - protected static Details getDetails(Status status, String... issue) { - return getDetails(status, SYSTEM, issue); - } + @Override + public String testCase() { + return null; + } - protected static Details getDetails(Status status, Type type, String... issue) { - return getDetails(new long[0], status, type, issue); - } + @Override + public String[] caseIDs() { + return ids; + } - protected static Details getDetails(long[] ids, Status status, Type type, String... issue) { - return new Details() { @Override - public long[] id() { return ids; } + public String[] IDs() { + return ids; + } + @Override - public Status status() { return status; } + public Status status() { + return status; + } + @Override - public String[] issue() { return issue; } + public String[] issues() { + return issue; + } @Override - public String[] bug() { - return new String[] {}; + public String[] bugs() { + return new String[]{}; } @Override - public Type type() { return type; } + public Type[] types() { + return type; + } + @Override - public Class annotationType() { return Details.class; } + public Class annotationType() { + return Buggy.class; + } }; } @@ -416,10 +210,104 @@ public Class interfaze() { } @Override - public String task() { + public String purpose() { return UUID.randomUUID().toString(); } }; } + protected void assertExitCode(Integer code) { + assertExitCode(code, null, null); + } + + @SuppressWarnings("SameParameterValue") + protected void assertExitCode(Integer code, String msg) { + assertExitCode(code, msg, null); + } + + @SuppressWarnings("SameParameterValue") + protected void assertExitCode(Integer code, String msg, Class throwableClass) { + + } + + protected void checkUtilityClassConstructor(Class clazz) throws NoSuchMethodException { + Constructor constructor = clazz.getDeclaredConstructor(); + constructor.setAccessible(true); + Throwable exception = execute(constructor::newInstance); + assertThat(exception.getCause(), instanceOf(IllegalStateException.class)); + assertThat(exception.getCause().getMessage(), is("Utility class. Prohibit instantiation.")); + } + + @SuppressWarnings({"unchecked", "WeakerAccess"}) + protected Throwable execute(Executable executable) { + Throwable throwable = null; + try { + executable.execute(); + } catch (Throwable e) { + throwable = e; + } + assertThat("Exception is present", throwable != null, is(true)); + return throwable; + } + + @SuppressWarnings({"unchecked", "SameParameterValue"}) + protected T execute(Executable executable, Class exceptionClass) { + Throwable throwable = null; + try { + executable.execute(); + } catch (Throwable e) { + throwable = e; + } + assertThat(throwable, instanceOf(exceptionClass)); + return (T) throwable; + } + + protected BuggyExecutionListener getBuggyExecutionListener() { + return getBuggyExecutionListener(true); + } + + @SuppressWarnings("SameParameterValue") + protected BuggyExecutionListener getBuggyExecutionListener(boolean withOverrideCopyFile) { + + return new BuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER) { + +// @Override +// public void copyFile(File sourceFile, File destFile) throws IOException { +// if (!withOverrideCopyFile) { +// super.copyFile(sourceFile, destFile); +// } +// } + + }; + + } + + protected class UnitTestBuggyExecutionListener extends BuggyExecutionListener { + + public ITestNGMethod method; + public Status status; + public String msg; + public Buggy buggy; + public File sourceFile; + public File targetFile; + + public UnitTestBuggyExecutionListener() { + this(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); + } + + public UnitTestBuggyExecutionListener(Buggy buggy) { + this(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER, buggy); + } + + public UnitTestBuggyExecutionListener(Logger testLogger, Logger frameworkLogger, Logger consoleLogger) { + this(testLogger, frameworkLogger, consoleLogger, null); + } + + public UnitTestBuggyExecutionListener(Logger testLogger, Logger frameworkLogger, Logger consoleLogger, Buggy buggy) { + super(testLogger, frameworkLogger, consoleLogger); + this.buggy = buggy; + } + + } + } diff --git a/buggy-core/src/test/java/org/touchbit/buggy/core/tests/common/BaseBuggyTestTests.java b/buggy-core/src/test/java/org/touchbit/buggy/core/tests/common/BaseBuggyTestTests.java index 61f31c0..14547b4 100644 --- a/buggy-core/src/test/java/org/touchbit/buggy/core/tests/common/BaseBuggyTestTests.java +++ b/buggy-core/src/test/java/org/touchbit/buggy/core/tests/common/BaseBuggyTestTests.java @@ -17,13 +17,9 @@ package org.touchbit.buggy.core.tests.common; import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; import org.slf4j.Logger; +import org.touchbit.buggy.core.BaseBuggyTest; import org.touchbit.buggy.core.tests.BaseUnitTest; -import org.touchbit.buggy.core.test.BaseBuggyTest; - -import static org.mockito.Mockito.mock; -import static org.touchbit.buggy.core.testng.listeners.IntellijIdeaTestNgPluginListener.INTELLIJ_IDEA_TEST_RUN; /** * Created by Oleg Shaburov on 19.09.2018 @@ -32,60 +28,61 @@ @DisplayName("BaseBuggyTest class Tests") class BaseBuggyTestTests extends BaseUnitTest { - @Test - @DisplayName("Check BuggyTest.getSteps()") - void unitTest_20180919223844() { - System.setProperty(INTELLIJ_IDEA_TEST_RUN, Boolean.TRUE.toString()); - try { - Logger logger = mock(Logger.class); - BuggyTest buggyTest = new BuggyTest(logger); - buggyTest.test(); - } finally { - System.setProperty(INTELLIJ_IDEA_TEST_RUN, Boolean.FALSE.toString()); - } - } - - @Test - @DisplayName("Check setLog(final Logger logger)") - void unitTest_20180919230422() { - System.setProperty(INTELLIJ_IDEA_TEST_RUN, Boolean.TRUE.toString()); - try { - Logger logger = mock(Logger.class); - BuggyTest buggyTest = new BuggyTest(); - buggyTest.setLogger(logger); - buggyTest.test(); - buggyTest.setLogger(null); - } finally { - System.setProperty(INTELLIJ_IDEA_TEST_RUN, Boolean.FALSE.toString()); - } - } - - @Test - @DisplayName("Check Missing IntellijIdeaPluginListener") - void unitTest_20180920000012() { - System.setProperty(INTELLIJ_IDEA_TEST_RUN, Boolean.FALSE.toString()); - try { - Logger logger = mock(Logger.class); - BuggyTest buggyTest = new BuggyTest(); - buggyTest.setLogger(logger); - buggyTest.test(); - assertExitCode(1, "Missing IntellijIdeaPluginListener in the Intellij IDEA TestNG plugin configuration."); - } finally { - System.setProperty(INTELLIJ_IDEA_TEST_RUN, Boolean.FALSE.toString()); - } - } +// @Test +// @DisplayName("Check BuggyTest.getSteps()") +// void unitTest_20180919223844() { +// System.setProperty(INTELLIJ_IDEA_TEST_RUN, Boolean.TRUE.toString()); +// try { +// Logger logger = mock(Logger.class); +// BuggyTest buggyTest = new BuggyTest(logger); +// buggyTest.test(); +// } finally { +// System.setProperty(INTELLIJ_IDEA_TEST_RUN, Boolean.FALSE.toString()); +// } +// } +// +// @Test +// @DisplayName("Check setLog(final Logger logger)") +// void unitTest_20180919230422() { +// System.setProperty(INTELLIJ_IDEA_TEST_RUN, Boolean.TRUE.toString()); +// try { +// Logger logger = mock(Logger.class); +// BuggyTest buggyTest = new BuggyTest(); +// buggyTest.setLogger(logger); +// buggyTest.test(); +// buggyTest.setLogger(null); +// } finally { +// System.setProperty(INTELLIJ_IDEA_TEST_RUN, Boolean.FALSE.toString()); +// } +// } +// +// @Test +// @DisplayName("Check Missing IntellijIdeaPluginListener") +// void unitTest_20180920000012() { +// System.setProperty(INTELLIJ_IDEA_TEST_RUN, Boolean.FALSE.toString()); +// try { +// Logger logger = mock(Logger.class); +// BuggyTest buggyTest = new BuggyTest(); +// buggyTest.setLogger(logger); +// buggyTest.test(); +// assertExitCode(1, "Missing IntellijIdeaPluginListener in the Intellij IDEA TestNG plugin configuration."); +// } finally { +// System.setProperty(INTELLIJ_IDEA_TEST_RUN, Boolean.FALSE.toString()); +// } +// } private static class BuggyTest extends BaseBuggyTest { - - BuggyTest() {} - - BuggyTest(final Logger logger) { - super(logger); - } - - void setLogger(final Logger logger) { - BaseBuggyTest.setLog(logger); - } +// +// BuggyTest() { +// } +// +// BuggyTest(final Logger logger) { +// super(logger); +// } +// +// void setLogger(final Logger logger) { +// BaseBuggyTest.setLog(logger); +// } protected void test() { step("test"); diff --git a/buggy-core/src/test/java/org/touchbit/buggy/core/tests/common/BuggyTests.java b/buggy-core/src/test/java/org/touchbit/buggy/core/tests/common/BuggyTests.java deleted file mode 100644 index 77a1165..0000000 --- a/buggy-core/src/test/java/org/touchbit/buggy/core/tests/common/BuggyTests.java +++ /dev/null @@ -1,666 +0,0 @@ -package org.touchbit.buggy.core.tests.common; - -import com.beust.jcommander.JCommander; -import com.beust.jcommander.Parameters; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Nested; -import org.junit.jupiter.api.Test; -import org.testng.TestNG; -import org.testng.xml.XmlSuite; -import org.touchbit.buggy.core.testng.TestSuite; -import org.touchbit.buggy.core.testng.listeners.BuggyListener; -import org.touchbit.buggy.core.tests.BaseUnitTest; -import org.touchbit.buggy.core.Buggy; -import org.touchbit.buggy.core.config.*; -import org.touchbit.buggy.core.model.Details; -import org.touchbit.buggy.core.model.Suite; -import org.touchbit.buggy.core.utils.log.BuggyLog; - -import java.util.ArrayList; -import java.util.List; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.testng.xml.XmlSuite.ParallelMode.METHODS; - -/** - * Created by Oleg Shaburov on 16.10.2018 - * shaburov.o.a@gmail.com - */ -@DisplayName("Buggy class test") -class BuggyTests extends BaseUnitTest { - - @Nested - @DisplayName("DefaultBuggyProcessor class tests") - class DefaultBuggyProcessorTests extends BaseUnitTest { - - private final UnitTestBuggyProcessor processor = new UnitTestBuggyProcessor(); - - @Test - @DisplayName("GIVEN UnitTestPrimaryConfig.class WHEN getPrimaryConfig THEN PrimaryConfig") - void unitTest_20181021190453() { - PrimaryConfig result = processor.getPrimaryConfig(UnitTestPrimaryConfig.class); - assertThat(result, is(notNullValue())); - assertThat(result, is(instanceOf(UnitTestPrimaryConfig.class))); - } - - @Test - @DisplayName("GIVEN null WHEN getPrimaryConfig THEN PrimaryConfig") - void unitTest_20181021190947() { - PrimaryConfig result = processor.getPrimaryConfig(null); - assertThat(result, is(notNullValue())); - assertThat(EXIT_HANDLER.getMsg(), is(containsString("Found more than 1 inherited " + - "class from PrimaryConfig.class:"))); - assertThat(EXIT_HANDLER.getStatus(), is(1)); - } - - @Test - @DisplayName("GIVEN PrivatePrimaryConfig WHEN getPrimaryConfig THEN exit 1") - void unitTest_20181021191129() { - PrimaryConfig result = processor.getPrimaryConfig(PrivatePrimaryConfig.class); - assertThat(result, is(nullValue())); - assertThat(EXIT_HANDLER.getMsg(), is("Unable to create a new instance of " + - PrivatePrimaryConfig.class)); - assertThat(EXIT_HANDLER.getStatus(), is(1)); - assertThat(EXIT_HANDLER.getThrowable().getMessage(), - is("Class org.touchbit.buggy.core.Buggy$DefaultBuggyProcessor can not access a member of " + - PrivatePrimaryConfig.class + " with modifiers \"private\"")); - } - - @Test - @DisplayName("GIVEN PrimaryConfigList(1) WHEN getPrimaryConfigClass THEN PrimaryConfig") - void unitTest_20181021192009() { - List> list = new ArrayList>() {{ - add(UnitTestPrimaryConfig.class); - }}; - Class result = processor.getPrimaryConfigClass(list); - assertThat(result, is(notNullValue())); - assertThat(result, is(sameInstance(UnitTestPrimaryConfig.class))); - assertThat(EXIT_HANDLER.getMsg(), is(nullValue())); - assertThat(EXIT_HANDLER.getStatus(), is(nullValue())); - assertThat(EXIT_HANDLER.getThrowable(), is(nullValue())); - } - - @Test - @DisplayName("GIVEN PrimaryConfigList(2) WHEN getPrimaryConfigClass THEN PrimaryConfig") - void unitTest_20181021192919() { - List> list = new ArrayList>() {{ - add(UnitTestPrimaryConfig.class); - add(UnitTestPrimaryConfig.class); - }}; - Class result = processor.getPrimaryConfigClass(list); - assertThat(result, is(notNullValue())); - assertThat(result, is(sameInstance(UnitTestPrimaryConfig.class))); - assertThat(EXIT_HANDLER.getMsg(), - is(containsString("Found more than 1 inherited class from PrimaryConfig.class:"))); - assertThat(EXIT_HANDLER.getStatus(), is(1)); - assertThat(EXIT_HANDLER.getThrowable(), is(nullValue())); - } - - @Test - @DisplayName("GIVEN PrimaryConfigList(0) WHEN getPrimaryConfigClass THEN PrimaryConfig") - void unitTest_20181021193116() { - List> list = new ArrayList<>(); - Class result = processor.getPrimaryConfigClass(list); - assertThat(result, is(nullValue())); - assertThat(EXIT_HANDLER.getMsg(), is("Primary config implementation not found.")); - assertThat(EXIT_HANDLER.getStatus(), is(1)); - assertThat(EXIT_HANDLER.getThrowable(), is(nullValue())); - } - - @Test - @DisplayName("GIVEN null WHEN getPrimaryConfigClass THEN PrimaryConfig") - void unitTest_20181021193322() { - Class result = processor.getPrimaryConfigClass(null); - assertThat(result, is(nullValue())); - assertThat(EXIT_HANDLER.getMsg(), is("Primary config implementation not found.")); - assertThat(EXIT_HANDLER.getStatus(), is(1)); - assertThat(EXIT_HANDLER.getThrowable(), is(nullValue())); - } - - @Test - @DisplayName("GIVEN SecondaryConfigClassList(1) WHEN getSecondaryConfigList THEN SecondaryConfigList(1)") - void unitTest_20181021194144() { - List> list = new ArrayList<>(); - list.add(UnitTestSecondaryConfig.class); - List result = processor.getSecondaryConfigList(list); - assertThat(result.size(), is(1)); - assertThat(result, is(contains(instanceOf(UnitTestSecondaryConfig.class)))); - assertThat(EXIT_HANDLER.getMsg(), is(nullValue())); - assertThat(EXIT_HANDLER.getStatus(), is(nullValue())); - assertThat(EXIT_HANDLER.getThrowable(), is(nullValue())); - } - - @SuppressWarnings("unchecked") - @Test - @DisplayName("GIVEN SecondaryConfigClassList(2) WHEN getSecondaryConfigList THEN SecondaryConfigList(2)") - void unitTest_20181021194443() { - List> list = new ArrayList<>(); - list.add(UnitTestSecondaryConfig.class); - list.add(UnitTestSecondaryConfig.class); - List result = processor.getSecondaryConfigList(list); - assertThat(result.size(), is(2)); - assertThat(result, is(contains( - instanceOf(UnitTestSecondaryConfig.class), - instanceOf(UnitTestSecondaryConfig.class) - ))); - assertThat(EXIT_HANDLER.getMsg(), is(nullValue())); - assertThat(EXIT_HANDLER.getStatus(), is(nullValue())); - assertThat(EXIT_HANDLER.getThrowable(), is(nullValue())); - } - - @Test - @DisplayName("GIVEN PrivateSecondaryConfig WHEN getSecondaryConfigList THEN exit 1") - void unitTest_20181021194948() { - List> list = new ArrayList<>(); - list.add(UnitTestSecondaryConfig.class); - list.add(PrivateSecondaryConfig.class); - processor.getSecondaryConfigList(list); - assertThat(EXIT_HANDLER.getMsg(), is("Unable to create a new instance of " + - PrivateSecondaryConfig.class)); - assertThat(EXIT_HANDLER.getStatus(), is(1)); - assertThat(EXIT_HANDLER.getThrowable().getMessage(), - is("Class org.touchbit.buggy.core.Buggy$DefaultBuggyProcessor can not access a member of " + - PrivateSecondaryConfig.class + " with modifiers \"private\"")); - } - - @Test - @DisplayName("GIVEN SecondaryConfigClassList(0) WHEN getSecondaryConfigList THEN UnitTestSecondaryConfig") - void unitTest_20181021195615() { - List result = processor.getSecondaryConfigList(new ArrayList<>()); - assertThat(result, is(hasItem(instanceOf(UnitTestSecondaryConfig.class)))); - assertThat(EXIT_HANDLER.getMsg(), is(nullValue())); - assertThat(EXIT_HANDLER.getStatus(), is(nullValue())); - assertThat(EXIT_HANDLER.getThrowable(), is(nullValue())); - } - - @Test - @DisplayName("GIVEN null WHEN getSecondaryConfigList THEN UnitTestSecondaryConfig") - void unitTest_20181021195736() { - List result = processor.getSecondaryConfigList(null); - assertThat(result, is(hasItem(instanceOf(UnitTestSecondaryConfig.class)))); - assertThat(EXIT_HANDLER.getMsg(), is(nullValue())); - assertThat(EXIT_HANDLER.getStatus(), is(nullValue())); - assertThat(EXIT_HANDLER.getThrowable(), is(nullValue())); - } - - @Test - @DisplayName("GIVEN empty args WHEN prepareJCommander THEN return JCommander") - void unitTest_20181021200419() { - JCommander result = processor.prepareJCommander(new UnitTestPrimaryConfig(), new ArrayList<>(), ""); - assertThat(result, is(notNullValue())); - assertThat(EXIT_HANDLER.getMsg(), is(nullValue())); - assertThat(EXIT_HANDLER.getStatus(), is(nullValue())); - assertThat(EXIT_HANDLER.getThrowable(), is(nullValue())); - } - - @Test - @DisplayName("GIVEN name==null WHEN prepareJCommander THEN return JCommander") - void unitTest_20181021201229() { - JCommander result = processor.prepareJCommander(new UnitTestPrimaryConfig(), new ArrayList<>(), null); - assertThat(result, is(notNullValue())); - assertThat(EXIT_HANDLER.getMsg(), is(nullValue())); - assertThat(EXIT_HANDLER.getStatus(), is(nullValue())); - assertThat(EXIT_HANDLER.getThrowable(), is(nullValue())); - } - - @Test - @DisplayName("GIVEN SecondaryConfigList = null WHEN prepareJCommander THEN return JCommander") - void unitTest_20181021201615() { - JCommander result = processor.prepareJCommander(new UnitTestPrimaryConfig(), null, "name"); - assertThat(result, is(nullValue())); - String msg = EXIT_HANDLER.getMsg(); - assertThat(msg, is(containsString("An invalid 'null' value was received for one of the parameters:"))); - assertThat(msg, is(containsString("SecondaryConfigs list = null"))); - assertThat(EXIT_HANDLER.getStatus(), is(1)); - assertThat(EXIT_HANDLER.getThrowable(), is(nullValue())); - } - - @Test - @DisplayName("GIVEN PrimaryConfig = null WHEN prepareJCommander THEN return JCommander") - void unitTest_20181021202628() { - JCommander result = processor.prepareJCommander(null, new ArrayList<>(), "name"); - assertThat(result, is(nullValue())); - String msg = EXIT_HANDLER.getMsg(); - assertThat(msg, is(containsString("An invalid 'null' value was received for one of the parameters:"))); - assertThat(msg, is(containsString("PrimaryConfig = null"))); - assertThat(EXIT_HANDLER.getStatus(), is(1)); - assertThat(EXIT_HANDLER.getThrowable(), is(nullValue())); - } - - @Test - @DisplayName("GIVEN relative logPath WHEN preparePrimaryConfig THEN true") - void unitTest_20181021203059() { - PrimaryConfig config = new PrimaryConfig() { - }; - String logPath = config.getLogPath(); - String runDir = config.getRunDir(); - try { - config.setLogPath("waste-unit-tests/LogPath_20181021203059"); - boolean result = processor.preparePrimaryConfig(config); - assertThat(result, is(true)); - assertThat(config.getLogPath(), is("waste-unit-tests/LogPath_20181021203059")); - } finally { - config.setLogPath(logPath); - config.setRunDir(runDir); - } - } - - @Test - @DisplayName("GIVEN full logPath WHEN preparePrimaryConfig THEN true") - void unitTest_20181021204652() { - PrimaryConfig config = new PrimaryConfig() { - }; - String logPath = config.getLogPath(); - String runDir = config.getRunDir(); - try { - config.setLogPath(WASTE + "/unitTest_20181021204652"); - boolean result = processor.preparePrimaryConfig(config); - assertThat(result, is(true)); - assertThat(config.getLogPath(), is(WASTE + "/unitTest_20181021204652")); - } finally { - config.setLogPath(logPath); - config.setRunDir(runDir); - } - } - - @Test - @DisplayName("GIVEN full logPath not exists WHEN preparePrimaryConfig THEN false") - void unitTest_20181021204855() { - PrimaryConfig config = new PrimaryConfig() { - }; - String logPath = config.getLogPath(); - String runDir = config.getRunDir(); - try { - config.setLogPath("/unitTest_20181021204652"); - boolean result = processor.preparePrimaryConfig(config); - assertThat(result, is(false)); - assertThat(EXIT_HANDLER.getMsg(), - is("No write permission for the specified log directory: '/unitTest_20181021204652'")); - assertThat(EXIT_HANDLER.getStatus(), is(1)); - assertThat(EXIT_HANDLER.getThrowable(), is(nullValue())); - } finally { - config.setLogPath(logPath); - config.setRunDir(runDir); - } - } - - @Test - @DisplayName("GIVEN full logPath can not write WHEN preparePrimaryConfig THEN false") - void unitTest_20181021205050() { - PrimaryConfig config = new PrimaryConfig() { - }; - String logPath = config.getLogPath(); - String runDir = config.getRunDir(); - try { - config.setLogPath("/"); - boolean result = processor.preparePrimaryConfig(config); - assertThat(result, is(false)); - assertThat(EXIT_HANDLER.getMsg(), - is("No write permission for the specified log directory: '/'")); - assertThat(EXIT_HANDLER.getStatus(), is(1)); - assertThat(EXIT_HANDLER.getThrowable(), is(nullValue())); - } finally { - config.setLogPath(logPath); - config.setRunDir(runDir); - } - } - - @Test - @DisplayName("GIVEN BuggyTestsBuggyLog WHEN prepareBuggyLog THEN no errors") - void unitTest_20181021210611() { - Buggy.setBuggyLogClass(BuggyTestsBuggyLog.class); - Buggy.prepare(); - assertThat(EXIT_HANDLER.getMsg(), is(nullValue())); - assertThat(EXIT_HANDLER.getStatus(), is(nullValue())); - assertThat(EXIT_HANDLER.getThrowable(), is(nullValue())); - } - - @Test - @DisplayName("GIVEN PrivateBuggyTestsBuggyLog WHEN prepareBuggyLog THEN exit 1") - void unitTest_20181021211210() { - processor.prepareBuggyLog(PrivateBuggyTestsBuggyLog.class); - assertThat(EXIT_HANDLER.getMsg(), is("Unable to create a new instance of " + - PrivateBuggyTestsBuggyLog.class.getTypeName())); - assertThat(EXIT_HANDLER.getStatus(), is(1)); - assertThat(EXIT_HANDLER.getThrowable().getMessage(), - is("Class org.touchbit.buggy.core.Buggy$DefaultBuggyProcessor can not access a member of " + - PrivateBuggyTestsBuggyLog.class + " with modifiers \"private\"")); - } - - @Test - @DisplayName("GIVEN null WHEN prepareBuggyLog THEN exit 1") - void unitTest_20181021211708() { - Buggy.prepare(); - processor.prepareBuggyLog(null); - assertThat(EXIT_HANDLER.getMsg(), is(containsString("Found more than 1 inherited class from BaseLog.class:"))); - assertThat(EXIT_HANDLER.getStatus(), is(1)); - assertThat(EXIT_HANDLER.getThrowable(), is(nullValue())); - } - - @Test - @DisplayName("GIVEN List(0) WHEN getBuggyLogSubClass THEN return BuggyLog") - void unitTest_20181021213302() { - Class result = processor.getBuggyLogSubClass(new ArrayList<>()); - assertThat(result, is(sameInstance(BuggyLog.class))); - assertThat(EXIT_HANDLER.getMsg(), is(nullValue())); - assertThat(EXIT_HANDLER.getStatus(), is(nullValue())); - assertThat(EXIT_HANDLER.getThrowable(), is(nullValue())); - } - - @Test - @DisplayName("GIVEN null WHEN getBuggyLogSubClass THEN return BuggyLog") - void unitTest_20181021213515() { - Class result = processor.getBuggyLogSubClass(null); - assertThat(result, is(sameInstance(BuggyLog.class))); - assertThat(EXIT_HANDLER.getMsg(), is(nullValue())); - assertThat(EXIT_HANDLER.getStatus(), is(nullValue())); - assertThat(EXIT_HANDLER.getThrowable(), is(nullValue())); - } - - @Test - @DisplayName("GIVEN List(BuggyTestsBuggyLog) WHEN getBuggyLogSubClass THEN BuggyTestsBuggyLog") - void unitTest_20181021213551() { - List> logClasses = new ArrayList<>(); - logClasses.add(BuggyTestsBuggyLog.class); - Class result = processor.getBuggyLogSubClass(logClasses); - assertThat(result, is(sameInstance(BuggyTestsBuggyLog.class))); - assertThat(EXIT_HANDLER.getMsg(), is(nullValue())); - assertThat(EXIT_HANDLER.getStatus(), is(nullValue())); - assertThat(EXIT_HANDLER.getThrowable(), is(nullValue())); - } - - @Test - @DisplayName("GIVEN null WHEN getSubTestSuites THEN List(0)") - void unitTest_20181021221012() { - List result = processor.getSubTestSuites(null); - assertThat(result, is(empty())); - assertThat(EXIT_HANDLER.getMsg(), is(nullValue())); - assertThat(EXIT_HANDLER.getStatus(), is(nullValue())); - assertThat(EXIT_HANDLER.getThrowable(), is(nullValue())); - } - - @Test - @DisplayName("GIVEN List(null) WHEN getSubTestSuites THEN exit 1") - void unitTest_20181021221222() { - List> subclasses = new ArrayList<>(); - subclasses.add(null); - List result = processor.getSubTestSuites(subclasses); - assertThat(result, is(empty())); - assertThat(EXIT_HANDLER.getMsg(), is("Unable to create a new instance of null")); - assertThat(EXIT_HANDLER.getStatus(), is(1)); - assertThat(EXIT_HANDLER.getThrowable().getMessage(), is(nullValue())); - } - - @Test - @DisplayName("GIVEN List(PrivateTestSuite) WHEN getSubTestSuites THEN exit 1") - void unitTest_20181021221526() { - List> subclasses = new ArrayList<>(); - subclasses.add(PrivateTestSuite.class); - List result = processor.getSubTestSuites(subclasses); - assertThat(result, is(empty())); - assertThat(EXIT_HANDLER.getMsg(), is("Unable to create a new instance of " + - PrivateTestSuite.class)); - assertThat(EXIT_HANDLER.getStatus(), is(1)); - assertThat(EXIT_HANDLER.getThrowable().getMessage(), - is("Class org.touchbit.buggy.core.Buggy$DefaultBuggyProcessor can not access a member of " + - PrivateTestSuite.class + " with modifiers \"private\"")); - } - - @Test - @DisplayName("GIVEN TestSuite List contains Annotated testClass WHEN mergeTestSuites THEN return TestSuite(1)") - void unitTest_20181022003106() { - TestSuite suite = new TestSuite("name_20181022003106", 50, METHODS, getSuite()); - suite.addTestPackage("unitTest_20181022003106", TestNGTestClassWithSuite.class); - List list = new ArrayList<>(); - list.add(suite); - List> annotated = new ArrayList<>(); - annotated.add(TestNGTestClassWithSuite.class); - List result = processor.mergeTestSuites(annotated, list); - assertThat(result, is(contains(suite))); - } - - @Test - @DisplayName("GIVEN TestSuite List not contains Annotated testClass WHEN mergeTestSuites THEN return default TestSuite(1)") - void unitTest_20181022005810() { - List list = new ArrayList<>(); - List> annotated = new ArrayList<>(); - annotated.add(TestNGTestClassWithSuite.class); - List result = processor.mergeTestSuites(annotated, list); - assertThat(result.size(), is(1)); - assertThat(result.get(0).getName(), is("DEFAULT TESTSERVICE TESTINTERFACE suite")); - assertThat(result.get(0).getTests().size(), is(1)); - assertThat(result.get(0).getTests().get(0).getXmlClasses().size(), is(1)); - assertThat(result.get(0).getTests().get(0).getXmlClasses().get(0).getName(), - is(TestNGTestClassWithSuite.class.getTypeName())); - } - - @Test - @DisplayName("GIVEN duplicates Annotated testClass WHEN mergeTestSuites THEN return default TestSuite(1)") - void unitTest_20181022011006() { - List list = new ArrayList<>(); - List> annotated = new ArrayList<>(); - annotated.add(TestNGTestClassWithSuite.class); - annotated.add(TestNGTestClassWithSuite.class); - annotated.add(TestNGTestClassWithSuite.class); - annotated.add(TestNGTestClassWithSuite.class); - List result = processor.mergeTestSuites(annotated, list); - assertThat(result.size(), is(1)); - assertThat(result.get(0).getName(), is("DEFAULT TESTSERVICE TESTINTERFACE suite")); - assertThat(result.get(0).getTests().size(), is(1)); - assertThat(result.get(0).getTests().get(0).getXmlClasses().size(), is(1)); - assertThat(result.get(0).getTests().get(0).getXmlClasses().get(0).getName(), - is(TestNGTestClassWithSuite.class.getTypeName())); - } - - @Test - @DisplayName("GIVEN no test suites WHEN getXmlSuitesForConfiguration THEN exit 1") - void unitTest_20181022012052() { - List xmlSuites = - processor.getXmlSuitesForConfiguration(Buggy.getPrimaryConfig(), new ArrayList<>()); - assertThat(xmlSuites, is(empty())); - assertThat(EXIT_HANDLER.getMsg(), is("There are no test suites for the current configuration.")); - assertThat(EXIT_HANDLER.getStatus(), is(1)); - assertThat(EXIT_HANDLER.getThrowable(), is(nullValue())); - } - - @Test - @DisplayName("GIVEN AbstractBuggyListener WHEN getBuggyListeners THEN exit 1") - void unitTest_20181022012947() { - List> subclasses = new ArrayList<>(); - subclasses.add(AbstractBuggyListener.class); - List listeners = processor.getBuggyListeners(subclasses); - assertThat(listeners, is(empty())); - assertThat(EXIT_HANDLER.getMsg(), is("Unable to create a new instance of " + AbstractBuggyListener.class)); - assertThat(EXIT_HANDLER.getStatus(), is(1)); - } - - @Test - @DisplayName("GIVEN status 0 WHEN jar run with errors THEN exit 0") - void unitTest_20181022014502() { - try { - Buggy.getPrimaryConfig().setStatus(0); - TestNG testNG = new TestNG(); - testNG.setUseDefaultListeners(false); - int status = processor.runTestNG(testNG); - assertThat(status, is(0)); - } finally { - Buggy.getPrimaryConfig().setStatus(null); - } - } - - @Test - @DisplayName("GIVEN new TestNG WHEN runTestNG THEN status 8") - void unitTest_20181022015017() { - TestNG testNG = new TestNG(); - testNG.setUseDefaultListeners(false); - int status = processor.runTestNG(testNG); - assertThat(status, is(8)); - } - - @Test - @DisplayName("GIVEN null WHEN runTestNG THEN status 60") - void unitTest_20181022015030() { - int status = processor.runTestNG(null); - assertThat(status, is(60)); - } - - @Test - @DisplayName("WHEN getReportsOutputDirectory THEN ends with reports") - void unitTest_20181022015230() { - assertThat(processor.getRealReportsOutputDirectory(), is(endsWith("reports"))); - } - - @Test - @DisplayName("WHEN getExitHandler THEN DefaultBuggySystemExitHandler") - void unitTest_20181022015527() { - assertThat(processor.getRealExitHandler(), is(not(nullValue()))); - assertThat(processor.getRealExitHandler().getClass().getSimpleName(), is("DefaultBuggySystemExitHandler")); - } - - @Test - @DisplayName("GIVEN ExitHandler WHEN exitRunWithUsage(10) THEN exit 10") - void unitTest_20181022025250() { - Buggy.prepare(); - processor.getExitHandler().realExitRunWithUsage(10, "unitTest_20181022025250"); - assertThat(EXIT_HANDLER.getStatus(), is(10)); - assertThat(EXIT_HANDLER.getMsg(), is("unitTest_20181022025250")); - } - - @Test - @DisplayName("GIVEN WHEN THEN") - void unitTest_20181022030541() { - new UnitTestBuggyProcessor().getExitHandler().realExitRunWithUsage(10, "unitTest_20181022025250"); - assertThat(EXIT_HANDLER.getStatus(), is(1)); - assertThat(EXIT_HANDLER.getMsg(), is("JCommander not initialized.")); - } - } - - @Test - @DisplayName("GIVEN Buggy.prepare() WHEN prepare() THEN not null") - void unitTest_20181022020129() { - Buggy.prepare(); - assertThat(Buggy.getJCommander(), is(notNullValue())); - } - - @Test - @DisplayName("GIVEN Buggy.prepare() WHEN prepare() THEN not null") - void unitTest_20181022020247() { - Buggy.setPrimaryConfigClass(null); - Buggy.prepare(); - } - - @Test - @DisplayName("GIVEN Buggy.main WHEN --print-log THEN console log contains test log path") - void unitTest_20181022014156() { - Buggy.main(new String[]{"--print-log"}); - assertThat(TEST_LOGGER.takeLoggedMessages(), - is(hasItems("test_20181016172050.....................SUCCESS └ " + - "file://" + Buggy.getPrimaryConfig().getAbsoluteLogPath() + "/tests/test_20181016172050.log"))); - } - - @Test - @DisplayName("GIVEN Buggy.prepare WHEN --invalid-parameter THEN MissingCommandException") - void unitTest_20181021202838() { - Buggy.prepare("--invalid-parameter"); - assertThat(EXIT_HANDLER.getMsg(), is("MissingCommandException: Expected a command, got --invalid-parameter")); - assertThat(EXIT_HANDLER.getStatus(), is(1)); - assertThat(EXIT_HANDLER.getThrowable(), is(nullValue())); - } - - @Test - @DisplayName("GIVEN main WHEN -? THEN print usage") - void unitTest_20181028173318() { - Buggy.main(new String[]{"-?"}); - assertThat(SYSTEM_OUT_LOGGER.takeLoggedMessages().toString(), - containsString("Usage: Buggy [options] [command] [command options]")); - } - - @Test - @DisplayName("GIVEN empty args WHEN jar run THEN console log does not test log path") - void unitTest_20181022014322() { - Buggy.main(new String[]{}); - assertThat(TEST_LOGGER.takeLoggedMessages(), - is(hasItems("test_20181016172050.....................SUCCESS"))); - } - - @Test - @DisplayName("GIVEN isCheck = true WHEN delegate THEN exit 0") - void unitTest_20181022022949() { - Buggy.prepare(); - TestNG testNG = new TestNG(); - testNG.setUseDefaultListeners(false); - Buggy.getPrimaryConfig().setCheck(true); - Buggy.delegate(testNG); - assertThat(EXIT_HANDLER.getMsg(), is("Buggy configuration is correct.")); - assertThat(EXIT_HANDLER.getStatus(), is(0)); - } - - @Test - @DisplayName("GIVEN isCheck = false WHEN delegate THEN exit 0") - void unitTest_20181022023246() { - Buggy.prepare(); - TestNG testNG = new TestNG(); - testNG.setUseDefaultListeners(false); - Buggy.getPrimaryConfig().setCheck(false); - Buggy.delegate(testNG); - assertThat(EXIT_HANDLER.getMsg(), is(nullValue())); - assertThat(EXIT_HANDLER.getStatus(), is(0)); - } - - @Test - @DisplayName("GIVEN broken TestNG WHEN delegate THEN exit 60") - void unitTest_20181022024731() { - Buggy.setBuggyProcessor(new TestNGDieProcessor()); - Buggy.prepare(); - TestNG testNG = new TestNG(); - testNG.setUseDefaultListeners(false); - Buggy.delegate(testNG); - assertThat(EXIT_HANDLER.getMsg(), is("TestNG safely died.")); - assertThat(EXIT_HANDLER.getStatus(), is(60)); - } - - @Test - @DisplayName("WHEN getSecondaryConfigs THEN UnitTestSecondaryConfig") - void unitTest_20181029032307() { - Buggy.prepare(); - assertThat(Buggy.getSecondaryConfigs(), contains( - instanceOf(UnitTestSecondaryConfig.class) - )); - } - - public static class TestNGDieProcessor extends UnitTestBuggyProcessor { - - @Override - public int runTestNG(TestNG testNG) { - return 60; - } - - } - - private abstract class AbstractBuggyListener implements BuggyListener {} - - @Suite(component = TestComponent.class, service = TestService.class, interfaze = TestInterface.class, task = "PrivateTestSuite") - private static class PrivateTestSuite extends TestSuite { } - - private static class PrivateBuggyTestsBuggyLog extends BuggyLog { } - - public static class BuggyTestsBuggyLog extends BuggyLog { - public BuggyTestsBuggyLog() { - super(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - } - } - - private static class PrivatePrimaryConfig implements PrimaryConfig { } - - @Parameters(commandNames = "junit") - private static class PrivateSecondaryConfig implements SecondaryConfig { } - - @Suite(component = TestComponent.class, service = TestService.class, interfaze = TestInterface.class, task = "task") - public static class BuggyTestsClass { - @org.testng.annotations.Test(description = "test_20181016172050 description") - @Details - public void test_20181016172050() {} - } - -} diff --git a/buggy-core/src/test/java/org/touchbit/buggy/core/tests/common/ExceptionsTests.java b/buggy-core/src/test/java/org/touchbit/buggy/core/tests/common/ExceptionsTests.java index 359bc76..2ab9593 100644 --- a/buggy-core/src/test/java/org/touchbit/buggy/core/tests/common/ExceptionsTests.java +++ b/buggy-core/src/test/java/org/touchbit/buggy/core/tests/common/ExceptionsTests.java @@ -18,8 +18,8 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import org.touchbit.buggy.core.tests.BaseUnitTest; import org.touchbit.buggy.core.exceptions.*; +import org.touchbit.buggy.core.tests.BaseUnitTest; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; diff --git a/buggy-core/src/test/java/org/touchbit/buggy/core/tests/common/ExitHandlerTests.java b/buggy-core/src/test/java/org/touchbit/buggy/core/tests/common/ExitHandlerTests.java deleted file mode 100644 index fa5880e..0000000 --- a/buggy-core/src/test/java/org/touchbit/buggy/core/tests/common/ExitHandlerTests.java +++ /dev/null @@ -1,95 +0,0 @@ -package org.touchbit.buggy.core.tests.common; - -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.touchbit.buggy.core.ExitHandler; -import org.touchbit.buggy.core.exceptions.AssertionException; -import org.touchbit.buggy.core.tests.BaseUnitTest; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; - -/** - * Created by Oleg Shaburov on 16.10.2018 - * shaburov.o.a@gmail.com - */ -@DisplayName("ExitHandler interface tests") -class ExitHandlerTests extends BaseUnitTest { - - @Test - @DisplayName("Check exitRun(int status)") - void unitTest_20181016214800() { - TestExitHandler handler = new TestExitHandler(); - handler.exitRun(0); - assertThat(SYSTEM_OUT_LOGGER.takeLoggedMessages(), contains( - "Exit code.....................................0", - "===============================================" - )); - } - - @Test - @DisplayName("Check exitRun(int status, String msg)") - void unitTest_20181016215145() { - TestExitHandler handler = new TestExitHandler(); - handler.exitRun(0, "msg"); - assertThat(SYSTEM_OUT_LOGGER.takeLoggedMessages(), contains( - "msg", - "===============================================", - "Exit code.....................................0", - "===============================================" - )); - } - - @Test - @DisplayName("Check exitRun(int status, String msg, Throwable t)") - void unitTest_20181016215216() { - TestExitHandler handler = new TestExitHandler(); - handler.exitRun(1, "unitTest_20181016215258", new AssertionException("BigBadaBum")); - assertThat(SYSTEM_OUT_LOGGER.takeLoggedMessages(), contains( - "unitTest_20181016215258", - "org.touchbit.buggy.core.exceptions.AssertionException: BigBadaBum", - "===============================================", - "Exit code.....................................1", - "===============================================" - )); - } - - @Test - @DisplayName("Check exitRunWithUsage(int status)") - void unitTest_20181016215242() { - TestExitHandler handler = new TestExitHandler(); - handler.exitRunWithUsage(0); - assertThat(SYSTEM_OUT_LOGGER.takeLoggedMessages(), contains( - "Exit code.....................................0", - "===============================================" - )); - } - - @Test - @DisplayName("Check exitRunWithUsage(int status, String msg)") - void unitTest_20181016215258() { - TestExitHandler handler = new TestExitHandler(); - handler.exitRunWithUsage(0, "msg"); - assertThat(SYSTEM_OUT_LOGGER.takeLoggedMessages(), contains( - "msg", - "===============================================", - "Exit code.....................................0", - "===============================================" - )); - } - - private static class TestExitHandler implements ExitHandler { - - @Override - public void exitRunWithUsage(int status, String msg) { - exitRun(status, msg); - } - - @Override - public void exit(int status) { - // do nothing - } - - } - -} diff --git a/buggy-core/src/test/java/org/touchbit/buggy/core/tests/common/GoalTests.java b/buggy-core/src/test/java/org/touchbit/buggy/core/tests/common/GoalTests.java index f67600e..038a90d 100644 --- a/buggy-core/src/test/java/org/touchbit/buggy/core/tests/common/GoalTests.java +++ b/buggy-core/src/test/java/org/touchbit/buggy/core/tests/common/GoalTests.java @@ -21,10 +21,10 @@ import org.touchbit.buggy.core.config.TestComponent; import org.touchbit.buggy.core.config.TestInterface; import org.touchbit.buggy.core.config.TestService; -import org.touchbit.buggy.core.process.DefaultComponent; +import org.touchbit.buggy.core.goal.component.AllComponents; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.is; /** * Created by Oleg Shaburov on 19.09.2018 @@ -36,11 +36,10 @@ class GoalTests { @Test @DisplayName("Check DefaultComponent") void unitTest_20180919222639() { - DefaultComponent component = new DefaultComponent(); + AllComponents component = new AllComponents(); assertThat(component.getName(), is("DEFAULT")); assertThat(component.toString(), is("DEFAULT")); assertThat(component.getDescription(), is("Default component")); - assertThat(component.getServices(), is(empty())); } @Test @@ -50,7 +49,6 @@ void unitTest_20180919223019() { assertThat(component.getName(), is("TESTCOMPONENT")); assertThat(component.toString(), is("TESTCOMPONENT")); assertThat(component.getDescription(), is("TestComponent")); - assertThat(component.getServices(), contains(instanceOf(TestService.class))); } @Test diff --git a/buggy-core/src/test/java/org/touchbit/buggy/core/tests/config/JCommanderConfigTests.java b/buggy-core/src/test/java/org/touchbit/buggy/core/tests/config/JCommanderConfigTests.java index bd7f3e3..a3b2bf0 100644 --- a/buggy-core/src/test/java/org/touchbit/buggy/core/tests/config/JCommanderConfigTests.java +++ b/buggy-core/src/test/java/org/touchbit/buggy/core/tests/config/JCommanderConfigTests.java @@ -16,30 +16,21 @@ package org.touchbit.buggy.core.tests.config; -import com.beust.jcommander.Parameter; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import org.touchbit.buggy.core.Buggy; -import org.touchbit.buggy.core.tests.BaseUnitTest; -import org.touchbit.buggy.core.config.BParameters; -import org.touchbit.buggy.core.config.PrimaryConfig; +import org.touchbit.buggy.core.config.BuggyConfigurationYML; import org.touchbit.buggy.core.config.TestInterface; import org.touchbit.buggy.core.config.TestService; -import org.touchbit.buggy.core.model.Type; -import org.touchbit.buggy.core.process.Interface; -import org.touchbit.buggy.core.process.Service; +import org.touchbit.buggy.core.goal.interfaze.Interface; +import org.touchbit.buggy.core.goal.service.Service; +import org.touchbit.buggy.core.tests.BaseUnitTest; -import java.io.File; -import java.lang.reflect.Constructor; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; -import java.util.Map; +import java.util.Set; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.touchbit.buggy.core.model.Type.INTEGRATION; -import static org.touchbit.buggy.core.model.Type.SYSTEM; +import static org.hamcrest.Matchers.is; /** * Created by Oleg Shaburov on 19.09.2018 @@ -48,440 +39,358 @@ @SuppressWarnings("ALL") @DisplayName("JCommander configuration tests") class JCommanderConfigTests extends BaseUnitTest { - - @Test - @DisplayName("Check parameters constructor") - void unitTest_20180919162214() throws NoSuchMethodException { - checkUtilityClassConstructor(BParameters.class); - } - - @Test - @DisplayName("Check PrimaryConfig.isHelp()") - void unitTest_20180919193201() { - assertThat(Buggy.getPrimaryConfig().isHelp(), is(false)); - Buggy.getPrimaryConfig().setHelp(true); - assertThat(Buggy.getPrimaryConfig().isHelp(), is(false)); - } - - @Test - @DisplayName("Check PrimaryConfig.setPrintAllParameters(true)") - void unitTest_20180919193619() { - boolean isPrintAllParameters = Buggy.getPrimaryConfig().isPrintAllParameters(); - try { - assertThat(isPrintAllParameters, is(false)); - Buggy.getPrimaryConfig().setPrintAllParameters(true); - assertThat(Buggy.getPrimaryConfig().isPrintAllParameters(), is(true)); - } finally { - Buggy.getPrimaryConfig().setPrintAllParameters(isPrintAllParameters); - } - } - - @Test - @DisplayName("Check PrimaryConfig.setForceRun(true)") - void unitTest_20180919193913() { - boolean isForceRun = Buggy.getPrimaryConfig().isForceRun(); - try { - assertThat(isForceRun, is(false)); - Buggy.getPrimaryConfig().setForceRun(true); - assertThat(Buggy.getPrimaryConfig().isForceRun(), is(true)); - } finally { - Buggy.getPrimaryConfig().setForceRun(isForceRun); - } - } +// +// @Test +// @DisplayName("Check parameters constructor") +// void unitTest_20180919162214() throws NoSuchMethodException { +// checkUtilityClassConstructor(BParameters.class); +// } +// +// @Test +// @DisplayName("Check PrimaryConfig.isHelp()") +// void unitTest_20180919193201() { +// assertThat(BuggyConfig.isHelp(), is(false)); +// BuggyConfig.setHelp(true); +// assertThat(BuggyConfig.isHelp(), is(false)); +// } +// +// @Test +// @DisplayName("Check PrimaryConfig.setPrintAllParameters(true)") +// void unitTest_20180919193619() { +// boolean isPrintAllParameters = BuggyConfig.isPrintAllParameters(); +// try { +// assertThat(isPrintAllParameters, is(false)); +// BuggyConfig.setPrintAllParameters(true); +// assertThat(BuggyConfig.isPrintAllParameters(), is(true)); +// } finally { +// BuggyConfig.setPrintAllParameters(isPrintAllParameters); +// } +// } +// +// @Test +// @DisplayName("Check PrimaryConfig.setForceRun(true)") +// void unitTest_20180919193913() { +// boolean isForceRun = BuggyConfig.isForceRun(); +// try { +// assertThat(isForceRun, is(false)); +// BuggyConfig.setForceRun(true); +// assertThat(BuggyConfig.isForceRun(), is(true)); +// } finally { +// BuggyConfig.setForceRun(isForceRun); +// } +// } @Test @DisplayName("Check PrimaryConfig.setThreads(10)") void unitTest_20180919194007() { - Integer threads = Buggy.getPrimaryConfig().getThreads(); + Integer threads = BuggyConfigurationYML.getThreads(); try { assertThat(threads, is(50)); - Buggy.getPrimaryConfig().setThreads(10); - assertThat(Buggy.getPrimaryConfig().getThreads(), is(10)); - } finally { - Buggy.getPrimaryConfig().setThreads(threads); - } - } - - @Test - @DisplayName("Check PrimaryConfig.setLogPath(\"testLogs\")") - void unitTest_20180919194154() { - String log = Buggy.getPrimaryConfig().getLogPath(); - try { - assertThat(log, is("logs")); - Buggy.getPrimaryConfig().setLogPath("testLogs"); - assertThat(Buggy.getPrimaryConfig().getLogPath(), is("testLogs")); - } finally { - Buggy.getPrimaryConfig().setLogPath(log); - } - } - - @Test - @DisplayName("Check PrimaryConfig.setServices(List services)") - void unitTest_20180919194549() { - List services = Buggy.getPrimaryConfig().getServices(); - try { - List newServices = new ArrayList() {{ add(new TestService()); }}; - Buggy.getPrimaryConfig().setServices(newServices); - assertThat(Buggy.getPrimaryConfig().getServices(), is(newServices)); + BuggyConfigurationYML.setThreads(10); + assertThat(BuggyConfigurationYML.getThreads(), is(10)); } finally { - Buggy.getPrimaryConfig().setServices(services); - } - } - - @Test - @DisplayName("Check PrimaryConfig.setInterfaces(List interfaces)") - void unitTest_20180919195248() { - List interfaces = Buggy.getPrimaryConfig().getInterfaces(); - try { - List newInterfaces = new ArrayList() {{ add(new TestInterface()); }}; - Buggy.getPrimaryConfig().setInterfaces(newInterfaces); - assertThat(Buggy.getPrimaryConfig().getInterfaces(), is(newInterfaces)); - } finally { - Buggy.getPrimaryConfig().setInterfaces(interfaces); - } - } - - @Test - @DisplayName("Check PrimaryConfig.setType(Type type)") - void unitTest_20180919195515() { - Type type = Buggy.getPrimaryConfig().getType(); - try { - assertThat(type, is(INTEGRATION)); - Buggy.getPrimaryConfig().setType(SYSTEM); - assertThat(Buggy.getPrimaryConfig().getType(), is(SYSTEM)); - } finally { - Buggy.getPrimaryConfig().setType(type); - } - } - - @Test - @DisplayName("Check PrimaryConfig.setStatus(Integer status)") - void unitTest_20180919195706() { - Integer status = Buggy.getPrimaryConfig().getStatus(); - try { - assertThat(status, is(nullValue())); - Buggy.getPrimaryConfig().setStatus(10); - assertThat(Buggy.getPrimaryConfig().getStatus(), is(10)); - } finally { - Buggy.getPrimaryConfig().setStatus(status); + BuggyConfigurationYML.setThreads(threads); } } +// +// @Test +// @DisplayName("Check PrimaryConfig.setLogPath(\"testLogs\")") +// void unitTest_20180919194154() { +// String log = BuggyConfig.getLogPath(); +// try { +// assertThat(log, is("logs")); +// BuggyConfig.setLogPath("testLogs"); +// assertThat(BuggyConfig.getLogPath(), is("testLogs")); +// } finally { +// BuggyConfig.setLogPath(log); +// } +// } +// +// @Test +// @DisplayName("Check PrimaryConfig.setServices(List services)") +// void unitTest_20180919194549() { +// Set services = BuggyConfigurationYML.getServices(); +// try { +// Set newServices = new ha() {{ +// add(new TestService()); +// }}; +// BuggyConfigurationYML.setServices(newServices); +// assertThat(BuggyConfigurationYML.getServices(), is(newServices)); +// } finally { +// BuggyConfigurationYML.setServices(services); +// } +// } +// +// @Test +// @DisplayName("Check PrimaryConfig.setInterfaces(List interfaces)") +// void unitTest_20180919195248() { +// List interfaces = BuggyConfigurationYML.getInterfaces(); +// try { +// List newInterfaces = new ArrayList() {{ +// add(new TestInterface()); +// }}; +// BuggyConfigurationYML.setInterfaces(newInterfaces); +// assertThat(BuggyConfigurationYML.getInterfaces(), is(newInterfaces)); +// } finally { +// BuggyConfigurationYML.setInterfaces(interfaces); +// } +// } + +// @Test +// @DisplayName("Check PrimaryConfig.setType(Type type)") +// void unitTest_20180919195515() { +// Type type = BuggyConfig.getType(); +// try { +// assertThat(type, is(INTEGRATION)); +// BuggyConfig.setType(SYSTEM); +// assertThat(BuggyConfig.getType(), is(SYSTEM)); +// } finally { +// BuggyConfig.setType(type); +// } +// } +// +// @Test +// @DisplayName("Check PrimaryConfig.setStatus(Integer status)") +// void unitTest_20180919195706() { +// Integer status = BuggyConfig.getStatus(); +// try { +// assertThat(status, is(nullValue())); +// BuggyConfig.setStatus(10); +// assertThat(BuggyConfig.getStatus(), is(10)); +// } finally { +// BuggyConfig.setStatus(status); +// } +// } @Test @DisplayName("Check PrimaryConfig.setArtifactsUrl(String buildsUrl)") void unitTest_20180919201516() { - String buildLogUrl = Buggy.getPrimaryConfig().getArtifactsUrl(); + String buildLogUrl = BuggyConfigurationYML.getArtifactsUrl(); try { assertThat(String.valueOf(buildLogUrl), is("null")); - Buggy.getPrimaryConfig().setArtifactsUrl("BuildUrl"); - assertThat(Buggy.getPrimaryConfig().getArtifactsUrl(), is("BuildUrl")); - } finally { - Buggy.getPrimaryConfig().setArtifactsUrl(buildLogUrl); - } - } - - @Test - @DisplayName("Check PrimaryConfig.setPrintSuite(Boolean printSuite)") - void unitTest_20180919201621() { - boolean printSuite = Buggy.getPrimaryConfig().isPrintSuite(); - try { - assertThat(printSuite, is(false)); - Buggy.getPrimaryConfig().setPrintSuite(true); - assertThat(Buggy.getPrimaryConfig().isPrintSuite(), is(true)); - } finally { - Buggy.getPrimaryConfig().setPrintSuite(printSuite); - } - } - - @Test - @DisplayName("Check PrimaryConfig.setPrintCause(Boolean printCause)") - void unitTest_20180919201754() { - boolean printCause = Buggy.getPrimaryConfig().isPrintCause(); - try { - assertThat(printCause, is(false)); - Buggy.getPrimaryConfig().setPrintCause(true); - assertThat(Buggy.getPrimaryConfig().isPrintCause(), is(true)); - } finally { - Buggy.getPrimaryConfig().setPrintCause(printCause); - } - } - - @Test - @DisplayName("Check PrimaryConfig.setPrintLogFile(Boolean printLog)") - void unitTest_20180919201844() { - boolean printLogFile = Buggy.getPrimaryConfig().isPrintLogFile(); - try { - assertThat(printLogFile, is(false)); - Buggy.getPrimaryConfig().setPrintLogFile(true); - assertThat(Buggy.getPrimaryConfig().isPrintLogFile(), is(true)); - } finally { - Buggy.getPrimaryConfig().setPrintLogFile(printLogFile); - } - } - - @Test - @DisplayName("Check PrimaryConfig.setVersion(Boolean version)") - void unitTest_20180919201933() { - assertThat(Buggy.getPrimaryConfig().isVersion(), is(false)); - Buggy.getPrimaryConfig().setVersion(true); - assertThat(Buggy.getPrimaryConfig().isVersion(), is(false)); - } - - @Test - @DisplayName("GIVEN PrimaryConfig WHEN setCheck() THEN isCheck()") - void unitTest_20181020063716() { - boolean check = Buggy.getPrimaryConfig().isCheck(); - try { - assertThat(check, is(false)); - Buggy.getPrimaryConfig().setCheck(true); - assertThat(Buggy.getPrimaryConfig().isCheck(), is(true)); - } finally { - Buggy.getPrimaryConfig().setCheck(check); - } - } - - @Test - @DisplayName("Check PrimaryConfig.setAbsoluteLogPath(String path)") - void unitTest_20180919202117() { - String absolutePath = Buggy.getPrimaryConfig().getAbsoluteLogPath(); - try { - assertThat(absolutePath, is(WASTE)); - Buggy.getPrimaryConfig().setAbsoluteLogPath(WASTE + "/AbsolutePath"); - assertThat(Buggy.getPrimaryConfig().getAbsoluteLogPath(), is(WASTE + "/AbsolutePath")); - } finally { - Buggy.getPrimaryConfig().setAbsoluteLogPath(absolutePath); - } - } - - @Test - @DisplayName("Check PrimaryConfig.getErrorLogDir()") - void unitTest_20180919202645() { - assertThat(Buggy.getPrimaryConfig().getErrorLogDir(), is(new File(WASTE, "errors"))); - } - - @Test - @DisplayName("Check PrimaryConfig.getTestLogDir()") - void unitTest_20180919202812() { - assertThat(Buggy.getPrimaryConfig().getTestLogDir(), is(new File(WASTE, "tests"))); - } - - @Test - @DisplayName("Check PrimaryConfig.getFixedLogDir()") - void unitTest_20180919202835() { - assertThat(Buggy.getPrimaryConfig().getFixedLogDir(), is(new File(WASTE, "fixed"))); - } - - @Test - @DisplayName("Check PrimaryConfig.getImplementedLogDir()") - void unitTest_20180919202856() { - assertThat(Buggy.getPrimaryConfig().getImplementedLogDir(), is(new File(WASTE, "implemented"))); - } - - @Test - @DisplayName("Check PrimaryConfig.getNewErrorLogDir()") - void unitTest_20180919202909() { - assertThat(Buggy.getPrimaryConfig().getNewErrorLogDir(), is(new File(WASTE, "errors/new"))); - } - - @Test - @DisplayName("Check PrimaryConfig.getExpFixErrorLogDir()") - void unitTest_20180919202937() { - assertThat(Buggy.getPrimaryConfig().getExpFixErrorLogDir(), is(new File(WASTE, "errors/exp_fix"))); - } - - @Test - @DisplayName("Check PrimaryConfig.getExpImplErrorLogDir()") - void unitTest_20180919202959() { - assertThat(Buggy.getPrimaryConfig().getExpImplErrorLogDir(), is(new File(WASTE, "errors/exp_impl"))); - } - - @Test - @DisplayName("Check PrimaryConfig.getCorruptedErrorLogDir()") - void unitTest_20180919203022() { - assertThat(Buggy.getPrimaryConfig().getCorruptedErrorLogDir(), is(new File(WASTE, "errors/corrupted"))); - } - - @Test - @DisplayName("Check PrimaryConfig.getBlockedErrorLogDir()") - void unitTest_20180919203048() { - assertThat(Buggy.getPrimaryConfig().getBlockedErrorLogDir(), is(new File(WASTE, "errors/blocked"))); - } - - @Test - @DisplayName("Check PrimaryConfig.") - void unitTest_20180919204139() { - String p = PrimaryConfig.configurationToString(Buggy.getPrimaryConfig()); - assertThat(p.contains("[--all]"), is(false)); - } - - @Test - @DisplayName("Check PrimaryConfig.configurationToString(config) with PrintAllParameters(false)") - void unitTest_20180919204525() { - boolean printAllParameters = Buggy.getPrimaryConfig().isPrintAllParameters(); - try { - Buggy.getPrimaryConfig().setPrintAllParameters(true); - String p = PrimaryConfig.configurationToString(Buggy.getPrimaryConfig()); - assertThat(p.contains("[--all]"), is(true)); + BuggyConfigurationYML.setArtifactsUrl("BuildUrl"); + assertThat(BuggyConfigurationYML.getArtifactsUrl(), is("BuildUrl")); } finally { - Buggy.getPrimaryConfig().setPrintAllParameters(printAllParameters); + BuggyConfigurationYML.setArtifactsUrl(buildLogUrl); } } - - @Test - @DisplayName("Check PrimaryConfig.configurationToString(config) with PrintAllParameters(true)") - void unitTest_20180919205544() { - JCommanderPrimaryConfig config = new JCommanderPrimaryConfig(); - config.setPrintAllParameters(true); - String p = PrimaryConfig.configurationToString(config); - assertThat(p.contains("[--phm]...................getPublicHiddenMethod"), is(true)); - assertThat(p.contains("[--php]....................publcHiddenParameter"), is(true)); - assertThat(p.contains("[--pm]..........................setPublicMethod"), is(true)); - assertThat(p.contains("[--pp]...........................publcParameter"), is(true)); - assertThat(p.contains("[--ppm]................................********"), is(true)); - assertThat(p.contains("[--ppp]................................********"), is(true)); - } - - @Test - @DisplayName("Check PrimaryConfig.configurationToString(config) with private parameter") - void unitTest_20180919211539() { - JCommanderPrimaryConfigFailGetField config = new JCommanderPrimaryConfigFailGetField(); - config.setPrintAllParameters(true); - PrimaryConfig.configurationToString(config); - } - - @Test - @DisplayName("Check PrimaryConfig.") - void unitTest_20180919212056() { - JCommanderPrimaryConfigFailGetMethod config = new JCommanderPrimaryConfigFailGetMethod(); - config.setPrintAllParameters(true); - PrimaryConfig.configurationToString(config); - } - - @Test - @DisplayName("GIVEN private constructor WHEN new DefaultValues() THEN IllegalStateException") - void unitTest_20181028233416() throws Exception { - Constructor constructor = PrimaryConfig.DefaultValues.class.getDeclaredConstructor(); - constructor.setAccessible(true); - constructor.newInstance(); - } - - @Test - @DisplayName("GIVEN DefaultValueProvider WHEN any value THEN return null") - void unitTest_20181028233806() { - PrimaryConfig.DefaultValueProvider provider = new PrimaryConfig.DefaultValueProvider(); - assertThat(provider.getDefaultValueFor(""), is(nullValue())); - assertThat(provider.getDefaultValueFor("-?"), is(nullValue())); - assertThat(provider.getDefaultValueFor(null), is(nullValue())); - assertThat(provider.getDefaultValueFor("unitTest_20181028233806"), is(nullValue())); - } - - @Test - @DisplayName("GIVEN WHEN THEN") - void unitTest_20181029002410() { - boolean isPrintAllParameters = Buggy.getPrimaryConfig().isPrintAllParameters(); - try { - Map map = new HashMap<>(); - JCommanderPrimaryConfigGetField config = new JCommanderPrimaryConfigGetField() {}; - config.setPrintAllParameters(false); - PrimaryConfig.addFieldValuesToMap(config, map); - assertThat(map.get("[-ffff]"), is("publicParameter")); - assertThat(map.get("[-hhhh]"), is(not("publicHiddenParameter"))); - assertThat(map.size(), is(1)); - config.setPrintAllParameters(true); - map.clear(); - PrimaryConfig.addFieldValuesToMap(config, map); - assertThat(map.get("[-ffff]"), is("publicParameter")); - assertThat(map.get("[-hhhh]"), is("publicHiddenParameter")); - assertThat(map.size(), is(2)); - } finally { - Buggy.getPrimaryConfig().setPrintAllParameters(isPrintAllParameters); - } - } - - public static class JCommanderPrimaryConfigGetField implements PrimaryConfig { - private static final String F = "-ffff"; - private static final String H = "-hhhh"; - - @Parameter(names = {F}) - public static String publicParameter = "publicParameter"; - - @Parameter(names = {H}, hidden = true) - public static String publicHiddenParameter = "publicHiddenParameter"; - - public static String parameter = "parameter"; - } - - - public static class JCommanderPrimaryConfigFailGetField implements PrimaryConfig { - - private static final String FF = "--ff"; - @Parameter(names = {FF}) - private static String privateParameter = "privateParameter"; - - } - - public static class JCommanderPrimaryConfigFailGetMethod implements PrimaryConfig { - - private static final String FF = "--ff"; - - @Parameter(names = {FF}) - private void setPrivateHiddenMethod(String s) { - - } - - private String getPrivateHiddenMethod() { - return "getPrivateHiddenMethod"; - } - - } - - @SuppressWarnings("unused") - public static class JCommanderPrimaryConfig implements PrimaryConfig { - - private static final String PP = "--pp"; - private static final String PHP = "--php"; - private static final String PPP = "--ppp"; - private static final String PM = "--pm"; - private static final String PHM = "--phm"; - private static final String PPM = "--ppm"; - - @Parameter(names = {PP}) - public static String publicParameter = "publcParameter"; - - @Parameter(names = {PHP}, hidden = true) - public static String publicHiddenParameter = "publcHiddenParameter"; - - @Parameter(names = {PPP}, password = true) - public static String publicPasswordParameter = "publcPasswordParameter"; - - @Parameter(names = {PM}) - public static void setPublicMethod(String s) { - - } - - public String getPublicMethod() { - return "setPublicMethod"; - } - - @Parameter(names = {PHM}, hidden = true) - public void setPublicHiddenMethod(String s) { - - } - - public String getPublicHiddenMethod() { - return "getPublicHiddenMethod"; - } - - @Parameter(names = {PPM}, password = true) - public void setPublicPasswordMethod(String s) { - - } - - public String getPublicPasswordMethod() { - return "getPublicPasswordMethod"; - } - - } - +// +// @Test +// @DisplayName("Check PrimaryConfig.setPrintSuite(Boolean printSuite)") +// void unitTest_20180919201621() { +// boolean printSuite = BuggyConfigurationYML.isPrintSuite(); +// try { +// assertThat(printSuite, is(false)); +// BuggyConfigurationYML.setPrintSuite(true); +// assertThat(BuggyConfigurationYML.isPrintSuite(), is(true)); +// } finally { +// BuggyConfigurationYML.setPrintSuite(printSuite); +// } +// } +// +// @Test +// @DisplayName("Check PrimaryConfig.setPrintCause(Boolean printCause)") +// void unitTest_20180919201754() { +// boolean printCause = BuggyConfigurationYML.isPrintCause(); +// try { +// assertThat(printCause, is(false)); +// BuggyConfigurationYML.setPrintCause(true); +// assertThat(BuggyConfigurationYML.isPrintCause(), is(true)); +// } finally { +// BuggyConfigurationYML.setPrintCause(printCause); +// } +// } +// +// @Test +// @DisplayName("Check PrimaryConfig.setPrintLogFile(Boolean printLog)") +// void unitTest_20180919201844() { +// boolean printLogFile = BuggyConfigurationYML.isPrintLog(); +// try { +// assertThat(printLogFile, is(false)); +// BuggyConfigurationYML.setPrintLog(true); +// assertThat(BuggyConfigurationYML.isPrintLog(), is(true)); +// } finally { +// BuggyConfigurationYML.setPrintLog(printLogFile); +// } +// } +// +// @Test +// @DisplayName("Check PrimaryConfig.setVersion(Boolean version)") +// void unitTest_20180919201933() { +// assertThat(BuggyConfigurationYML.isVersion(), is(false)); +// BuggyConfigurationYML.setVersion(true); +// assertThat(BuggyConfigurationYML.isVersion(), is(false)); +// } +// +// @Test +// @DisplayName("GIVEN PrimaryConfig WHEN setCheck() THEN isCheck()") +// void unitTest_20181020063716() { +// boolean check = BuggyConfig.isCheck(); +// try { +// assertThat(check, is(false)); +// BuggyConfig.setCheck(true); +// assertThat(BuggyConfig.isCheck(), is(true)); +// } finally { +// BuggyConfig.setCheck(check); +// } +// } +// +// @Test +// @DisplayName("Check PrimaryConfig.setAbsoluteLogPath(String path)") +// void unitTest_20180919202117() { +// String absolutePath = BuggyConfig.getAbsoluteLogPath(); +// try { +// assertThat(absolutePath, is(WASTE)); +// BuggyConfig.setAbsoluteLogPath(WASTE + "/AbsolutePath"); +// assertThat(BuggyConfig.getAbsoluteLogPath(), is(WASTE + "/AbsolutePath")); +// } finally { +// BuggyConfig.setAbsoluteLogPath(absolutePath); +// } +// } +// +// @Test +// @DisplayName("Check PrimaryConfig.getErrorLogDir()") +// void unitTest_20180919202645() { +// assertThat(BuggyConfig.getErrorLogDir(), is(new File(WASTE, "errors"))); +// } +// +// @Test +// @DisplayName("Check PrimaryConfig.getTestLogDir()") +// void unitTest_20180919202812() { +// assertThat(BuggyConfig.getTestLogDir(), is(new File(WASTE, "tests"))); +// } +// +// @Test +// @DisplayName("Check PrimaryConfig.getFixedLogDir()") +// void unitTest_20180919202835() { +// assertThat(BuggyConfig.getFixedLogDir(), is(new File(WASTE, "fixed"))); +// } +// +// @Test +// @DisplayName("Check PrimaryConfig.getImplementedLogDir()") +// void unitTest_20180919202856() { +// assertThat(BuggyConfig.getImplementedLogDir(), is(new File(WASTE, "implemented"))); +// } +// +// @Test +// @DisplayName("Check PrimaryConfig.getNewErrorLogDir()") +// void unitTest_20180919202909() { +// assertThat(BuggyConfig.getNewErrorLogDir(), is(new File(WASTE, "errors/new"))); +// } +// +// @Test +// @DisplayName("Check PrimaryConfig.getExpFixErrorLogDir()") +// void unitTest_20180919202937() { +// assertThat(BuggyConfig.getExpFixErrorLogDir(), is(new File(WASTE, "errors/exp_fix"))); +// } +// +// @Test +// @DisplayName("Check PrimaryConfig.getExpImplErrorLogDir()") +// void unitTest_20180919202959() { +// assertThat(BuggyConfig.getExpImplErrorLogDir(), is(new File(WASTE, "errors/exp_impl"))); +// } +// +// @Test +// @DisplayName("Check PrimaryConfig.getCorruptedErrorLogDir()") +// void unitTest_20180919203022() { +// assertThat(BuggyConfig.getCorruptedErrorLogDir(), is(new File(WASTE, "errors/corrupted"))); +// } +// +// @Test +// @DisplayName("Check PrimaryConfig.getBlockedErrorLogDir()") +// void unitTest_20180919203048() { +// assertThat(BuggyConfig.getBlockedErrorLogDir(), is(new File(WASTE, "errors/blocked"))); +// } +// +// @Test +// @DisplayName("Check PrimaryConfig.") +// void unitTest_20180919204139() { +// String p = PrimaryConfig.configurationToString(BuggyConfig); +// assertThat(p.contains("[--all]"), is(false)); +// } +// +// @Test +// @DisplayName("Check PrimaryConfig.configurationToString(config) with PrintAllParameters(false)") +// void unitTest_20180919204525() { +// boolean printAllParameters = BuggyConfig.isPrintAllParameters(); +// try { +// BuggyConfig.setPrintAllParameters(true); +// String p = PrimaryConfig.configurationToString(BuggyConfig); +// assertThat(p.contains("[--all]"), is(true)); +// } finally { +// BuggyConfig.setPrintAllParameters(printAllParameters); +// } +// } +// +// @Test +// @DisplayName("Check PrimaryConfig.configurationToString(config) with PrintAllParameters(true)") +// void unitTest_20180919205544() { +// JCommanderPrimaryConfig config = new JCommanderPrimaryConfig(); +// config.setPrintAllParameters(true); +// String p = PrimaryConfig.configurationToString(config); +// assertThat(p.contains("[--phm]...................getPublicHiddenMethod"), is(true)); +// assertThat(p.contains("[--php]....................publcHiddenParameter"), is(true)); +// assertThat(p.contains("[--pm]..........................setPublicMethod"), is(true)); +// assertThat(p.contains("[--pp]...........................publcParameter"), is(true)); +// assertThat(p.contains("[--ppm]................................********"), is(true)); +// assertThat(p.contains("[--ppp]................................********"), is(true)); +// } +// +// @Test +// @DisplayName("Check PrimaryConfig.configurationToString(config) with private parameter") +// void unitTest_20180919211539() { +// JCommanderPrimaryConfigFailGetField config = new JCommanderPrimaryConfigFailGetField(); +// config.setPrintAllParameters(true); +// PrimaryConfig.configurationToString(config); +// } +// +// @Test +// @DisplayName("Check PrimaryConfig.") +// void unitTest_20180919212056() { +// JCommanderPrimaryConfigFailGetMethod config = new JCommanderPrimaryConfigFailGetMethod(); +// config.setPrintAllParameters(true); +// PrimaryConfig.configurationToString(config); +// } +// +// @Test +// @DisplayName("GIVEN private constructor WHEN new DefaultValues() THEN IllegalStateException") +// void unitTest_20181028233416() throws Exception { +// Constructor constructor = PrimaryConfig.DefaultValues.class.getDeclaredConstructor(); +// constructor.setAccessible(true); +// constructor.newInstance(); +// } +// +// @Test +// @DisplayName("GIVEN DefaultValueProvider WHEN any value THEN return null") +// void unitTest_20181028233806() { +// PrimaryConfig.DefaultValueProvider provider = new PrimaryConfig.DefaultValueProvider(); +// assertThat(provider.getDefaultValueFor(""), is(nullValue())); +// assertThat(provider.getDefaultValueFor("-?"), is(nullValue())); +// assertThat(provider.getDefaultValueFor(null), is(nullValue())); +// assertThat(provider.getDefaultValueFor("unitTest_20181028233806"), is(nullValue())); +// } +// +// @Test +// @DisplayName("GIVEN WHEN THEN") +// void unitTest_20181029002410() { +// boolean isPrintAllParameters = BuggyConfig.isPrintAllParameters(); +// try { +// Map map = new HashMap<>(); +// JCommanderPrimaryConfigGetField config = new JCommanderPrimaryConfigGetField() {}; +// config.setPrintAllParameters(false); +// PrimaryConfig.addFieldValuesToMap(config, map); +// assertThat(map.get("[-ffff]"), is("publicParameter")); +// assertThat(map.get("[-hhhh]"), is(not("publicHiddenParameter"))); +// assertThat(map.size(), is(1)); +// config.setPrintAllParameters(true); +// map.clear(); +// PrimaryConfig.addFieldValuesToMap(config, map); +// assertThat(map.get("[-ffff]"), is("publicParameter")); +// assertThat(map.get("[-hhhh]"), is("publicHiddenParameter")); +// assertThat(map.size(), is(2)); +// } finally { +// BuggyConfig.setPrintAllParameters(isPrintAllParameters); +// } +// } } diff --git a/buggy-core/src/test/java/org/touchbit/buggy/core/tests/config/JCommanderTests.java b/buggy-core/src/test/java/org/touchbit/buggy/core/tests/config/JCommanderTests.java index b2d8ef2..d68d261 100644 --- a/buggy-core/src/test/java/org/touchbit/buggy/core/tests/config/JCommanderTests.java +++ b/buggy-core/src/test/java/org/touchbit/buggy/core/tests/config/JCommanderTests.java @@ -1,32 +1,10 @@ package org.touchbit.buggy.core.tests.config; -import com.beust.jcommander.ParameterException; import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.touchbit.buggy.core.Buggy; +import org.touchbit.buggy.core.goal.component.Component; +import org.touchbit.buggy.core.goal.interfaze.Interface; +import org.touchbit.buggy.core.goal.service.Service; import org.touchbit.buggy.core.tests.BaseUnitTest; -import org.touchbit.buggy.core.config.jcommander.*; -import org.touchbit.buggy.core.exceptions.BuggyConfigurationException; -import org.touchbit.buggy.core.config.TestComponent; -import org.touchbit.buggy.core.config.TestInterface; -import org.touchbit.buggy.core.config.TestService; -import org.touchbit.buggy.core.process.Component; -import org.touchbit.buggy.core.process.Interface; -import org.touchbit.buggy.core.process.Service; -import org.touchbit.buggy.core.utils.IOHelper; - -import java.io.File; -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.jar.Attributes; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.touchbit.buggy.core.config.BParameters.*; /** * Created by Oleg Shaburov on 16.09.2018 @@ -35,276 +13,208 @@ @DisplayName("JCommander util classes tests") class JCommanderTests extends BaseUnitTest { - @Test - @DisplayName("Check ArraySplitter.split(\"\")") - void unitTest_20180916231916() throws ClassNotFoundException { - Class configClass = this.getClass() - .getClassLoader().loadClass("org.touchbit.buggy.core.config.UnitTestPrimaryConfig$UnitTestPrimaryConfigs"); - System.out.println(configClass); - System.out.println(Arrays.toString(configClass.getInterfaces())); - System.out.println(Arrays.toString(configClass.getGenericInterfaces())); - System.out.println(Arrays.toString(configClass.getAnnotatedInterfaces())); - } - - @Test - @DisplayName("Check ArraySplitter.split(\"[]\")") - void unitTest_20180916232212() { - ArraySplitter splitter = new ArraySplitter(); - List result = splitter.split("[]"); - assertThat(result, is(new ArrayList())); - } - - @Test - @DisplayName("Check ArraySplitter.split(\" [ v1 , v2 ] \")") - void unitTest_20180916232243() { - ArraySplitter splitter = new ArraySplitter(); - List result = splitter.split(" [ v1 , v2 ,, ] "); - assertThat(result, is(new ArrayList() {{ add("V1"); add("V2"); }})); - } - - @Test - @DisplayName("Check GoalConverter.convert(\"TestComponent\")") - void unitTest_20180916233351() { - GoalConverter converter = new GoalConverter<>(Component.class); - Component component = converter.convert("TestComponent"); - assertThat(component, is(notNullValue())); - } - - @Test - @DisplayName("Check GoalConverter.convert(\"FakeComponent\")") - void unitTest_20180916233835() { - GoalConverter converter = new GoalConverter<>(Component.class); - BuggyConfigurationException e = execute(() -> - converter.convert("FakeComponent"), BuggyConfigurationException.class); - assertThat(e.getMessage(), is("No Component found with name FakeComponent")); - } - - @Test - @DisplayName("Check GoalConverter.convert(\"TestService\")") - void unitTest_20180916234404() { - GoalConverter converter = new GoalConverter<>(Service.class); - Service service = converter.convert("TestService"); - assertThat(service, is(notNullValue())); - } - - @Test - @DisplayName("Check GoalConverter.convert(\"TestService\")") - void unitTest_20180916234519() { - GoalConverter converter = new GoalConverter<>(Service.class); - BuggyConfigurationException e = execute(() -> - converter.convert("FakeService"), BuggyConfigurationException.class); - assertThat(e.getMessage(), is("No Service found with name FakeService")); - } - - @Test - @DisplayName("Check GoalConverter.convert(\"TestService\")") - void unitTest_20180916234623() { - GoalConverter converter = new GoalConverter<>(Interface.class); - Interface testInterface = converter.convert("TestInterface"); - assertThat(testInterface, is(notNullValue())); - } - - @Test - @DisplayName("Check GoalConverter.convert(\"FakeInterface\")") - void unitTest_20180916234700() { - GoalConverter converter = new GoalConverter<>(Interface.class); - BuggyConfigurationException e = execute(() -> - converter.convert("FakeInterface"), BuggyConfigurationException.class); - assertThat(e.getMessage(), is("No Interface found with name FakeInterface")); - } - - @Test - @DisplayName("Check GoalConverter.convert(\"PrivateTestInterfaceJC\")") - void unitTest_20180916234947() { - GoalConverter converter = new GoalConverter<>(Interface.class); - BuggyConfigurationException e = execute(() -> - converter.convert("PrivateTestInterfaceJC"), BuggyConfigurationException.class); - assertThat(e.getMessage(), - is("Can not create a new instance of " + PrivateTestInterfaceJC.class + - " inheriting from class Interface")); - } - - @Test - @DisplayName("Check GoalConverter.convert(\"PrivateTestServiceJC\")") - void unitTest_20180916235242() { - GoalConverter converter = new GoalConverter<>(Service.class); - BuggyConfigurationException e = execute(() -> - converter.convert("PrivateTestServiceJC"), BuggyConfigurationException.class); - assertThat(e.getMessage(), - is("Can not create a new instance of " + PrivateTestServiceJC.class + - " inheriting from class Service")); - } - - @Test - @DisplayName("Check Check GoalConverter.convert(\"PrivateTestComponentJC\")") - void unitTest_20180916235302() { - GoalConverter converter = new GoalConverter<>(Component.class); - BuggyConfigurationException e = execute(() -> - converter.convert("PrivateTestComponentJC"), BuggyConfigurationException.class); - assertThat(e.getMessage(), - is("Can not create a new instance of " + PrivateTestComponentJC.class + - " inheriting from class Component")); - } - - @Test - @DisplayName("Check ComponentConverter.convert(\"TestComponent\")") - void unitTest_20180917001139() { - ComponentConverter converter = new ComponentConverter(); - List components = converter.convert("TestComponent"); - assertThat(components.size(), is(1)); - assertThat(components.get(0), instanceOf(TestComponent.class)); - } - - @Test - @DisplayName("Check InterfaceConverter.convert(\"TestInterface\")") - void unitTest_20180917001424() { - InterfaceConverter converter = new InterfaceConverter(); - List list = converter.convert("TestInterface"); - assertThat(list.size(), is(1)); - assertThat(list.get(0), instanceOf(TestInterface.class)); - } - - @Test - @DisplayName("Check ServiceConverter.convert(\"TestService\")") - void unitTest_20180917001526() { - ServiceConverter converter = new ServiceConverter(); - List list = converter.convert("TestService"); - assertThat(list.size(), is(1)); - assertThat(list.get(0), instanceOf(TestService.class)); - } - - @Test - @DisplayName("Check ValueValidator.validate(QUESTION_MARK & HELP)") - void unitTest_20180917001718() { - Buggy.prepare(); - ValueValidator validator = new ValueValidator(); - validator.validate(QUESTION_MARK, "true"); - assertExitCode(0); - validator.validate(HELP, "true"); - assertExitCode(0); - validator.validate(QUESTION_MARK, "false"); - assertExitCode(null); - validator.validate(HELP, "false"); - assertExitCode(null); - } - - @Test - @DisplayName("Check ValueValidator.validate(VERSION & V)") - void unitTest_20180917003731() throws IOException { - File testManifest = new File(TEST_CLASSES + "/META-INF", "MANIFEST.MF"); - File srcManifest = new File(CLASSES + "/META-INF", "MANIFEST.MF"); - IOHelper.copyFile(testManifest, srcManifest); - ValueValidator validator = new ValueValidator(); - validator.validate(VERSION, "true"); - assertExitCode(0); - validator.validate(V, "true"); - assertExitCode(0); - validator.validate(VERSION, "false"); - assertExitCode(null); - validator.validate(V, "false"); - assertExitCode(null); - } - - @Test - @DisplayName("Check ParameterValidator.validate(SERVICES & Suite) with value") - void unitTest_20180917003944() { - ParameterValidator validator = new ParameterValidator(); - validator.validate(SERVICES, "false"); - validator.validate(S, "false"); - } - - @Test - @DisplayName("Check ParameterValidator.validate(SERVICES & Suite) without value") - void unitTest_20180917004113() { - ParameterValidator validator = new ParameterValidator(); - ParameterException e = execute(() -> validator.validate(SERVICES, null), ParameterException.class); - assertThat(e.getMessage(), is("Parameter " + SERVICES + " can not be empty")); - e = execute(() -> validator.validate(S, ""), ParameterException.class); - assertThat(e.getMessage(), is("Parameter " + S + " can not be empty")); - } - - @Test - @DisplayName("Check ParameterValidator.validate(INTERFACE & I) with value") - void unitTest_20180917005308() { - ParameterValidator validator = new ParameterValidator(); - validator.validate(INTERFACE, "false"); - validator.validate(I, "false"); - } - - @Test - @DisplayName("Check ParameterValidator.validate(INTERFACE & I) without value") - void unitTest_20180917005351() { - ParameterValidator validator = new ParameterValidator(); - ParameterException e = execute(() -> validator.validate(INTERFACE, null), ParameterException.class); - assertThat(e.getMessage(), is("Parameter " + INTERFACE + " can not be empty")); - e = execute(() -> validator.validate(I, ""), ParameterException.class); - assertThat(e.getMessage(), is("Parameter " + I + " can not be empty")); - } - - @Test - @DisplayName("Check ParameterValidator.validate(TYPE & T) with value") - void unitTest_20180917005429() { - ParameterValidator validator = new ParameterValidator(); - validator.validate(TYPE, "false"); - validator.validate(T, "false"); - } - - @Test - @DisplayName("Check Check ParameterValidator.validate(TYPE & T) without value") - void unitTest_20180917005500() { - ParameterValidator validator = new ParameterValidator(); - ParameterException e = execute(() -> validator.validate(TYPE, null), ParameterException.class); - assertThat(e.getMessage(), is("Parameter " + TYPE + " can not be empty")); - e = execute(() -> validator.validate(T, ""), ParameterException.class); - assertThat(e.getMessage(), is("Parameter " + T + " can not be empty")); - } - - @Test - @DisplayName("Check Check ParameterValidator.validate(FAKE) without value") - void unitTest_20180917005537() { - ParameterValidator validator = new ParameterValidator(); - validator.validate("--fake", ""); - validator.validate("--fake", null); - } - - @Test - @DisplayName("GIVEN null WHEN printAttributes() THEN empty version information") - void unitTest_20181028234354() throws Exception { - Class clazz = ValueValidator.class; - Method method = clazz.getDeclaredMethod("printAttributes", Attributes.class); - method.setAccessible(true); - Attributes attributes = null; - method.invoke(clazz, attributes); - assertThat(SYSTEM_OUT_LOGGER.takeLoggedMessages(), is(empty())); - } - - @Test - @DisplayName("GIVEN empty Attributes WHEN printAttributes() THEN empty version information") - void unitTest_20181028235141() throws Exception { - Class clazz = ValueValidator.class; - Method method = clazz.getDeclaredMethod("printAttributes", Attributes.class); - method.setAccessible(true); - Attributes attributes = new Attributes(); - method.invoke(clazz, attributes); - assertThat(SYSTEM_OUT_LOGGER.takeLoggedMessages(), is(empty())); - } - - @Test - @DisplayName("GIVEN Attributes WHEN printAttributes() THEN empty version information") - void unitTest_20181028235254() throws Exception { - Class clazz = ValueValidator.class; - Method method = clazz.getDeclaredMethod("printAttributes", Attributes.class); - method.setAccessible(true); - Attributes attributes = new Attributes(); - attributes.put(new Attributes.Name("Implementation-unit-test"), "unitTest_20181028235254"); - attributes.put(new Attributes.Name("Implementation-unit-test-null"), null); - attributes.put(new Attributes.Name("Another-attribute"), "attribute"); - method.invoke(clazz, attributes); - assertThat(SYSTEM_OUT_LOGGER.takeLoggedMessages(), contains( - "unit-test_______________unitTest_20181028235254", - "===============================================" - )); - } +// @Test +// @DisplayName("Check ArraySplitter.split(\"\")") +// void unitTest_20180916231916() throws ClassNotFoundException { +// Class configClass = this.getClass() +// .getClassLoader().loadClass("org.touchbit.buggy.core.config.UnitTestPrimaryConfig$UnitTestPrimaryConfigs"); +// System.out.println(configClass); +// System.out.println(Arrays.toString(configClass.getInterfaces())); +// System.out.println(Arrays.toString(configClass.getGenericInterfaces())); +// System.out.println(Arrays.toString(configClass.getAnnotatedInterfaces())); +// } +// +// @Test +// @DisplayName("Check ArraySplitter.split(\"[]\")") +// void unitTest_20180916232212() { +// ArraySplitter splitter = new ArraySplitter(); +// List result = splitter.split("[]"); +// assertThat(result, is(new ArrayList<>())); +// } +// +// @Test +// @DisplayName("Check ArraySplitter.split(\" [ v1 , v2 ] \")") +// void unitTest_20180916232243() { +// ArraySplitter splitter = new ArraySplitter(); +// List result = splitter.split(" [ v1 , v2 ,, ] "); +// assertThat(result, is(new ArrayList() {{ +// add("V1"); +// add("V2"); +// }})); +// } +// +// @Test +// @DisplayName("Check GoalConverter.convert(\"TestComponent\")") +// void unitTest_20180916233351() { +// GoalConverter converter = new GoalConverter<>(Component.class); +// Component component = converter.convert("TestComponent"); +// assertThat(component, is(notNullValue())); +// } +// +// @Test +// @DisplayName("Check GoalConverter.convert(\"FakeComponent\")") +// void unitTest_20180916233835() { +// GoalConverter converter = new GoalConverter<>(Component.class); +// BuggyConfigurationException e = execute(() -> +// converter.convert("FakeComponent"), BuggyConfigurationException.class); +// assertThat(e.getMessage(), is("No Component found with name FakeComponent")); +// } +// +// @Test +// @DisplayName("Check GoalConverter.convert(\"TestService\")") +// void unitTest_20180916234404() { +// GoalConverter converter = new GoalConverter<>(Service.class); +// Service service = converter.convert("TestService"); +// assertThat(service, is(notNullValue())); +// } +// +// @Test +// @DisplayName("Check GoalConverter.convert(\"TestService\")") +// void unitTest_20180916234519() { +// GoalConverter converter = new GoalConverter<>(Service.class); +// BuggyConfigurationException e = execute(() -> +// converter.convert("FakeService"), BuggyConfigurationException.class); +// assertThat(e.getMessage(), is("No Service found with name FakeService")); +// } +// +// @Test +// @DisplayName("Check GoalConverter.convert(\"TestService\")") +// void unitTest_20180916234623() { +// GoalConverter converter = new GoalConverter<>(Interface.class); +// Interface testInterface = converter.convert("TestInterface"); +// assertThat(testInterface, is(notNullValue())); +// } +// +// @Test +// @DisplayName("Check GoalConverter.convert(\"FakeInterface\")") +// void unitTest_20180916234700() { +// GoalConverter converter = new GoalConverter<>(Interface.class); +// BuggyConfigurationException e = execute(() -> +// converter.convert("FakeInterface"), BuggyConfigurationException.class); +// assertThat(e.getMessage(), is("No Interface found with name FakeInterface")); +// } +// +// @Test +// @DisplayName("Check GoalConverter.convert(\"PrivateTestInterfaceJC\")") +// void unitTest_20180916234947() { +// GoalConverter converter = new GoalConverter<>(Interface.class); +// BuggyConfigurationException e = execute(() -> +// converter.convert("PrivateTestInterfaceJC"), BuggyConfigurationException.class); +// assertThat(e.getMessage(), +// is("Can not create a new instance of " + PrivateTestInterfaceJC.class + +// " inheriting from class Interface")); +// } +// +// @Test +// @DisplayName("Check GoalConverter.convert(\"PrivateTestServiceJC\")") +// void unitTest_20180916235242() { +// GoalConverter converter = new GoalConverter<>(Service.class); +// BuggyConfigurationException e = execute(() -> +// converter.convert("PrivateTestServiceJC"), BuggyConfigurationException.class); +// assertThat(e.getMessage(), +// is("Can not create a new instance of " + PrivateTestServiceJC.class + +// " inheriting from class Service")); +// } +// +// @Test +// @DisplayName("Check Check GoalConverter.convert(\"PrivateTestComponentJC\")") +// void unitTest_20180916235302() { +// GoalConverter converter = new GoalConverter<>(Component.class); +// BuggyConfigurationException e = execute(() -> +// converter.convert("PrivateTestComponentJC"), BuggyConfigurationException.class); +// assertThat(e.getMessage(), +// is("Can not create a new instance of " + PrivateTestComponentJC.class + +// " inheriting from class Component")); +// } +// +// @Test +// @DisplayName("Check ComponentConverter.convert(\"TestComponent\")") +// void unitTest_20180917001139() { +// ComponentConverter converter = new ComponentConverter(); +// List components = converter.convert("TestComponent"); +// assertThat(components.size(), is(1)); +// assertThat(components.get(0), instanceOf(TestComponent.class)); +// } +// +// @Test +// @DisplayName("Check InterfaceConverter.convert(\"TestInterface\")") +// void unitTest_20180917001424() { +// InterfaceConverter converter = new InterfaceConverter(); +// List list = converter.convert("TestInterface"); +// assertThat(list.size(), is(1)); +// assertThat(list.get(0), instanceOf(TestInterface.class)); +// } +// +// @Test +// @DisplayName("Check ServiceConverter.convert(\"TestService\")") +// void unitTest_20180917001526() { +// ServiceConverter converter = new ServiceConverter(); +// List list = converter.convert("TestService"); +// assertThat(list.size(), is(1)); +// assertThat(list.get(0), instanceOf(TestService.class)); +// } +// +// @Test +// @DisplayName("Check ParameterValidator.validate(SERVICES & Suite) with value") +// void unitTest_20180917003944() { +// ParameterValidator validator = new ParameterValidator(); +// validator.validate(SERVICES, "false"); +// validator.validate(S, "false"); +// } +// +// @Test +// @DisplayName("Check ParameterValidator.validate(SERVICES & Suite) without value") +// void unitTest_20180917004113() { +// ParameterValidator validator = new ParameterValidator(); +// ParameterException e = execute(() -> validator.validate(SERVICES, null), ParameterException.class); +// assertThat(e.getMessage(), is("Parameter " + SERVICES + " can not be empty")); +// e = execute(() -> validator.validate(S, ""), ParameterException.class); +// assertThat(e.getMessage(), is("Parameter " + S + " can not be empty")); +// } +// +// @Test +// @DisplayName("Check ParameterValidator.validate(INTERFACE & I) with value") +// void unitTest_20180917005308() { +// ParameterValidator validator = new ParameterValidator(); +// validator.validate(INTERFACE, "false"); +// validator.validate(I, "false"); +// } +// +// @Test +// @DisplayName("Check ParameterValidator.validate(INTERFACE & I) without value") +// void unitTest_20180917005351() { +// ParameterValidator validator = new ParameterValidator(); +// ParameterException e = execute(() -> validator.validate(INTERFACE, null), ParameterException.class); +// assertThat(e.getMessage(), is("Parameter " + INTERFACE + " can not be empty")); +// e = execute(() -> validator.validate(I, ""), ParameterException.class); +// assertThat(e.getMessage(), is("Parameter " + I + " can not be empty")); +// } +// +// @Test +// @DisplayName("Check ParameterValidator.validate(TYPE & T) with value") +// void unitTest_20180917005429() { +// ParameterValidator validator = new ParameterValidator(); +// validator.validate(TYPE, "false"); +// validator.validate(T, "false"); +// } +// +// @Test +// @DisplayName("Check Check ParameterValidator.validate(TYPE & T) without value") +// void unitTest_20180917005500() { +// ParameterValidator validator = new ParameterValidator(); +// ParameterException e = execute(() -> validator.validate(TYPE, null), ParameterException.class); +// assertThat(e.getMessage(), is("Parameter " + TYPE + " can not be empty")); +// e = execute(() -> validator.validate(T, ""), ParameterException.class); +// assertThat(e.getMessage(), is("Parameter " + T + " can not be empty")); +// } +// +// @Test +// @DisplayName("Check Check ParameterValidator.validate(FAKE) without value") +// void unitTest_20180917005537() { +// ParameterValidator validator = new ParameterValidator(); +// validator.validate("--fake", ""); +// validator.validate("--fake", null); +// } private static class PrivateTestInterfaceJC extends Interface { @@ -324,15 +234,11 @@ public String getDescription() { private static class PrivateTestComponentJC extends Component { - @Override - public List getServices() { - return new ArrayList() {{add(new TestService());}}; - } - @Override public String getDescription() { return "PrivateTestComponentJC"; } + } } diff --git a/buggy-core/src/test/java/org/touchbit/buggy/core/tests/model/ModelTests.java b/buggy-core/src/test/java/org/touchbit/buggy/core/tests/model/ModelTests.java index 333e7fc..1fbe50b 100644 --- a/buggy-core/src/test/java/org/touchbit/buggy/core/tests/model/ModelTests.java +++ b/buggy-core/src/test/java/org/touchbit/buggy/core/tests/model/ModelTests.java @@ -4,9 +4,9 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; -import org.touchbit.buggy.core.tests.BaseUnitTest; import org.touchbit.buggy.core.model.Status; import org.touchbit.buggy.core.model.Type; +import org.touchbit.buggy.core.tests.BaseUnitTest; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; @@ -55,42 +55,6 @@ void unitTest_20180916221800() { assertThat(Type.values().length, is(4)); } - @Test - @DisplayName("Check SMOKE.isIncludeOrEquals()") - void unitTest_20180922075454() { - assertThat(Type.SMOKE.isIncludeOrEquals(Type.SMOKE), is(true)); - assertThat(Type.SMOKE.isIncludeOrEquals(Type.MODULE), is(false)); - assertThat(Type.SMOKE.isIncludeOrEquals(Type.INTEGRATION), is(false)); - assertThat(Type.SMOKE.isIncludeOrEquals(Type.SYSTEM), is(false)); - } - - @Test - @DisplayName("Check MODULE.isIncludeOrEquals()") - void unitTest_20180922075825() { - assertThat(Type.MODULE.isIncludeOrEquals(Type.SMOKE), is(true)); - assertThat(Type.MODULE.isIncludeOrEquals(Type.MODULE), is(true)); - assertThat(Type.MODULE.isIncludeOrEquals(Type.INTEGRATION), is(false)); - assertThat(Type.MODULE.isIncludeOrEquals(Type.SYSTEM), is(false)); - } - - @Test - @DisplayName("Check INTEGRATION.isIncludeOrEquals()") - void unitTest_20180922075850() { - assertThat(Type.INTEGRATION.isIncludeOrEquals(Type.SMOKE), is(true)); - assertThat(Type.INTEGRATION.isIncludeOrEquals(Type.MODULE), is(true)); - assertThat(Type.INTEGRATION.isIncludeOrEquals(Type.INTEGRATION), is(true)); - assertThat(Type.INTEGRATION.isIncludeOrEquals(Type.SYSTEM), is(false)); - } - - @Test - @DisplayName("Check SYSTEM.isIncludeOrEquals()") - void unitTest_20180922075855() { - assertThat(Type.SYSTEM.isIncludeOrEquals(Type.SMOKE), is(true)); - assertThat(Type.SYSTEM.isIncludeOrEquals(Type.MODULE), is(true)); - assertThat(Type.SYSTEM.isIncludeOrEquals(Type.INTEGRATION), is(true)); - assertThat(Type.SYSTEM.isIncludeOrEquals(Type.SYSTEM), is(true)); - } - } } diff --git a/buggy-core/src/test/java/org/touchbit/buggy/core/tests/testng/BaseBuggyExecutionListenerTests.java b/buggy-core/src/test/java/org/touchbit/buggy/core/tests/testng/BaseBuggyExecutionListenerTests.java new file mode 100644 index 0000000..d239f00 --- /dev/null +++ b/buggy-core/src/test/java/org/touchbit/buggy/core/tests/testng/BaseBuggyExecutionListenerTests.java @@ -0,0 +1,90 @@ +package org.touchbit.buggy.core.tests.testng; + +import org.touchbit.buggy.core.testng.BaseBuggyExecutionListener; +import org.touchbit.buggy.core.tests.BaseUnitTest; + +/** + * Created by Oleg Shaburov on 14.10.2018 + * shaburov.o.a@gmail.com + */ +class BaseBuggyExecutionListenerTests extends BaseUnitTest { +// +// @Test +// @DisplayName("Check get url log file where !getArtifactsUrl().endsWith(\"/\")") +// void unitTest_20181014215332() { +// String temp = BuggyConfig.getArtifactsUrl(); +// try { +// UnitTestBaseBuggyExecutionListener listener = new UnitTestBaseBuggyExecutionListener(); +// BuggyConfig.setArtifactsUrl("https://touchbit.org/artifacts"); +// ITestNGMethod method = getMockITestNGMethod(); +// String result = listener.getLogFilePath(method); +// assertThat(result, is("https://touchbit.org/artifacts/waste-unit-tests/tests/iTestResultMethodWithDetails.log")); +// } finally { +// BuggyConfig.setArtifactsUrl(temp); +// } +// } +// +// @Test +// @DisplayName("Check get url log file where getArtifactsUrl().endsWith(\"/\")") +// void unitTest_20181014222846() { +// String temp = BuggyConfig.getArtifactsUrl(); +// try { +// UnitTestBaseBuggyExecutionListener listener = new UnitTestBaseBuggyExecutionListener(); +// BuggyConfig.setArtifactsUrl("https://touchbit.org/artifacts/"); +// ITestNGMethod method = getMockITestNGMethod(); +// String result = listener.getLogFilePath(method); +// assertThat(result, is("https://touchbit.org/artifacts/waste-unit-tests/tests/iTestResultMethodWithDetails.log")); +// } finally { +// BuggyConfig.setArtifactsUrl(temp); +// } +// } +// +// @Test +// @DisplayName("Check get local log file if ArtifactsUrl == null") +// void unitTest_20181014223022() { +// String temp = BuggyConfig.getArtifactsUrl(); +// try { +// BuggyConfig.setArtifactsUrl(null); +// UnitTestBaseBuggyExecutionListener listener = new UnitTestBaseBuggyExecutionListener(); +// BuggyConfig.setArtifactsUrl(null); +// ITestNGMethod method = getMockITestNGMethod(); +// String result = listener.getLogFilePath(method); +// assertThat(result, is("file://" + BuggyConfig.getAbsoluteLogPath() + +// "/tests/iTestResultMethodWithDetails.log")); +// } finally { +// BuggyConfig.setArtifactsUrl(temp); +// } +// } +// +// @Test +// @DisplayName("Check get local log file if ArtifactsUrl == \"null\"") +// void unitTest_20181016135040() { +// String temp = BuggyConfig.getArtifactsUrl(); +// try { +// BuggyConfig.setArtifactsUrl("null"); +// UnitTestBaseBuggyExecutionListener listener = new UnitTestBaseBuggyExecutionListener(); +// BuggyConfig.setArtifactsUrl(null); +// ITestNGMethod method = getMockITestNGMethod(); +// String result = listener.getLogFilePath(method); +// assertThat(result, is("file://" + BuggyConfig.getAbsoluteLogPath() + +// "/tests/iTestResultMethodWithDetails.log")); +// } finally { +// BuggyConfig.setArtifactsUrl(temp); +// } +// } + + private static class UnitTestBaseBuggyExecutionListener extends BaseBuggyExecutionListener { + + @Override + public boolean isEnable() { + return false; + } + +// @Override +// public String getLogFilePath(ITestNGMethod method, S) { +// return super.getLogFilePath(method, null); +// } + + } + +} diff --git a/buggy-core/src/test/java/org/touchbit/buggy/core/tests/testng/BaseTelegramNotifierTests.java b/buggy-core/src/test/java/org/touchbit/buggy/core/tests/testng/BaseTelegramNotifierTests.java new file mode 100644 index 0000000..4db8ce0 --- /dev/null +++ b/buggy-core/src/test/java/org/touchbit/buggy/core/tests/testng/BaseTelegramNotifierTests.java @@ -0,0 +1,244 @@ +/* + * Copyright © 2018 Shaburov Oleg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.touchbit.buggy.core.tests.testng; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.touchbit.buggy.core.model.Notifier; +import org.touchbit.buggy.core.testng.BaseTelegramNotifier; +import org.touchbit.buggy.core.tests.BaseUnitTest; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + +/** + * Created by Oleg Shaburov on 20.09.2018 + * shaburov.o.a@gmail.com + */ +@DisplayName("BaseTelegramNotifier class tests") +class BaseTelegramNotifierTests extends BaseUnitTest { +// +// @Test +// @DisplayName("Check onExecutionFinish report") +// void unitTest_20180920225957() { +// StringBuilder sb = new StringBuilder(); +// Notifier notifier = sb::append; +// BaseTelegramNotifier telegram = new BaseTelegramNotifier(notifier) { +// @Override +// public boolean isEnable() { +// testCount.set(0); +// skippedTests.set(0); +// corruptedError.set(0); +// expFixError.set(0); +// expImplError.set(0); +// blockedError.set(0); +// newError.set(0); +// fixed.set(0); +// implemented.set(0); +// return true; +// } +// }; +// telegram.onExecutionFinish(); +// assertThat(sb.toString(), is("" + +// "*Buggy*\n" + +// "Run Results:\n" + +// "`--------------------------------`\n" + +// "`Running tests..................`0\n" + +// "`--------------------------------`\n" + +// "`Successful tests...............`0\n" + +// "`Skipped tests..................`0\n" + +// "`Failed tests...................`0\n" + +// "`--------------------------------`\n" + +// "`New Errors.....................`0\n" + +// "`Waiting to fix a defect........`0\n" + +// "`Waiting for the implementation.`0\n" + +// "`Blocked tests..................`0\n" + +// "`Corrupted tests................`0\n" + +// "`--------------------------------`\n" + +// "`Fixed defects..................`0\n" + +// "`Implemented cases..............`0\n" + +// "`--------------------------------`\n" + +// "Test execution time: *00:00:00*\n" + +// "[Logs](null)\n")); +// BuggyConfig.setProgramName(""); +// sb = new StringBuilder(); +// notifier = sb::append; +// telegram = new BaseTelegramNotifier(notifier) { +// @Override +// public boolean isEnable() { +// testCount.set(0); +// skippedTests.set(0); +// corruptedError.set(0); +// expFixError.set(0); +// expImplError.set(0); +// blockedError.set(0); +// newError.set(0); +// fixed.set(0); +// implemented.set(0); +// return true; +// } +// }; +// telegram.onExecutionFinish(); +// assertThat(sb.toString(), is("" + +// "Run Results:\n" + +// "`--------------------------------`\n" + +// "`Running tests..................`0\n" + +// "`--------------------------------`\n" + +// "`Successful tests...............`0\n" + +// "`Skipped tests..................`0\n" + +// "`Failed tests...................`0\n" + +// "`--------------------------------`\n" + +// "`New Errors.....................`0\n" + +// "`Waiting to fix a defect........`0\n" + +// "`Waiting for the implementation.`0\n" + +// "`Blocked tests..................`0\n" + +// "`Corrupted tests................`0\n" + +// "`--------------------------------`\n" + +// "`Fixed defects..................`0\n" + +// "`Implemented cases..............`0\n" + +// "`--------------------------------`\n" + +// "Test execution time: *00:00:00*\n" + +// "[Logs](null)\n")); +// } +// +// @Test +// @DisplayName("Check report with program name") +// void unitTest_20180920231126() { +// StringBuilder sb = new StringBuilder(); +// BuggyConfig.setProgramName("unitTest_20180920231126"); +// Notifier notifier = sb::append; +// BaseTelegramNotifier telegram = new BaseTelegramNotifier(notifier) { +// @Override +// public boolean isEnable() { +// testCount.set(0); +// skippedTests.set(0); +// corruptedError.set(0); +// expFixError.set(0); +// expImplError.set(0); +// blockedError.set(0); +// newError.set(0); +// fixed.set(0); +// implemented.set(0); +// return true; +// } +// }; +// telegram.onExecutionFinish(); +// assertThat(sb.toString(), is("" + +// "*unitTest_20180920231126*\n" + +// "Run Results:\n" + +// "`--------------------------------`\n" + +// "`Running tests..................`0\n" + +// "`--------------------------------`\n" + +// "`Successful tests...............`0\n" + +// "`Skipped tests..................`0\n" + +// "`Failed tests...................`0\n" + +// "`--------------------------------`\n" + +// "`New Errors.....................`0\n" + +// "`Waiting to fix a defect........`0\n" + +// "`Waiting for the implementation.`0\n" + +// "`Blocked tests..................`0\n" + +// "`Corrupted tests................`0\n" + +// "`--------------------------------`\n" + +// "`Fixed defects..................`0\n" + +// "`Implemented cases..............`0\n" + +// "`--------------------------------`\n" + +// "Test execution time: *00:00:00*\n" + +// "[Logs](null)\n")); +// } +// +// @Test +// @DisplayName("Check report with ArtifactsUrl") +// void unitTest_20180920231553() { +// StringBuilder sb = new StringBuilder(); +// BuggyConfig.setProgramName(null); +// Notifier notifier = sb::append; +// BuggyConfig.setArtifactsUrl("http://build.url"); +// try { +// BaseTelegramNotifier telegram = new BaseTelegramNotifier(notifier) { +// @Override +// public boolean isEnable() { +// testCount.set(6); +// skippedTests.set(1); +// corruptedError.incrementAndGet(); +// expFixError.incrementAndGet(); +// expImplError.incrementAndGet(); +// blockedError.incrementAndGet(); +// newError.incrementAndGet(); +// fixed.incrementAndGet(); +// implemented.incrementAndGet(); +// return true; +// } +// }; +// telegram.onExecutionFinish(); +// assertThat(sb.toString(), is("Run Results:\n" + +// "`--------------------------------`\n" + +// "`Running tests..................`6\n" + +// "`--------------------------------`\n" + +// "`Successful tests...............`1\n" + +// "`Skipped tests..................`1\n" + +// "`Failed tests...................`5\n" + +// "`--------------------------------`\n" + +// "`New Errors.....................`[1](http://build.url/errors/new/)\n" + +// "`Waiting to fix a defect........`[1](http://build.url/errors/exp_fix/)\n" + +// "`Waiting for the implementation.`[1](http://build.url/errors/exp_impl/)\n" + +// "`Blocked tests..................`[1](http://build.url/errors/blocked/)\n" + +// "`Corrupted tests................`[1](http://build.url/errors/corrupted/)\n" + +// "`--------------------------------`\n" + +// "`Fixed defects..................`[1](http://build.url/fixed/exp_fix/)\n" + +// "`Implemented cases..............`[1](http://build.url/fixed/exp_impl/)\n" + +// "`--------------------------------`\n" + +// "Test execution time: *00:00:00*\n" + +// "[Logs](http://build.url)\n")); +// } finally { +// BuggyConfig.setArtifactsUrl(null); +// } +// } +// +// @Test +// @DisplayName("Check failed notification") +// void unitTest_20180920232942() { +// int errors = Buggy.getBuggyErrors(); +// Notifier notifier = msg -> { +// throw new CorruptedTestException("unitTest_20180920232942"); +// }; +// BaseTelegramNotifier telegram = new BaseTelegramNotifier(notifier) { +// @Override +// public boolean isEnable() { return true; } +// }; +// telegram.onExecutionStart(); +// await().atMost(50, MILLISECONDS); +// telegram.onExecutionFinish(); +// assertThat(Buggy.getBuggyErrors(), is((errors + 1))); +// } + + @Test + @DisplayName("Check disable notification") + void unitTest_20180920230951() { + StringBuilder sb = new StringBuilder(); + Notifier notifier = sb::append; + BaseTelegramNotifier telegram = new BaseTelegramNotifier(notifier) { + @Override + public boolean isEnable() { + return false; + } + }; + telegram.onExecutionStart(); + telegram.onExecutionFinish(); + assertThat(sb.toString(), is("")); + } + +} diff --git a/buggy-core/src/test/java/org/touchbit/buggy/core/tests/testng/listeners/IntellijIdeaTestNgPluginListenerTests.java b/buggy-core/src/test/java/org/touchbit/buggy/core/tests/testng/IntellijIdeaTestNgPluginListenerTests.java similarity index 53% rename from buggy-core/src/test/java/org/touchbit/buggy/core/tests/testng/listeners/IntellijIdeaTestNgPluginListenerTests.java rename to buggy-core/src/test/java/org/touchbit/buggy/core/tests/testng/IntellijIdeaTestNgPluginListenerTests.java index 87d1150..ba289b8 100644 --- a/buggy-core/src/test/java/org/touchbit/buggy/core/tests/testng/listeners/IntellijIdeaTestNgPluginListenerTests.java +++ b/buggy-core/src/test/java/org/touchbit/buggy/core/tests/testng/IntellijIdeaTestNgPluginListenerTests.java @@ -14,16 +14,10 @@ * limitations under the License. */ -package org.touchbit.buggy.core.tests.testng.listeners; +package org.touchbit.buggy.core.tests.testng; import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; import org.touchbit.buggy.core.tests.BaseUnitTest; -import org.touchbit.buggy.core.testng.listeners.IntellijIdeaTestNgPluginListener; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; -import static org.touchbit.buggy.core.testng.listeners.IntellijIdeaTestNgPluginListener.INTELLIJ_IDEA_TEST_RUN; /** * Created by Oleg Shaburov on 20.09.2018 @@ -32,16 +26,16 @@ @DisplayName("IntellijIdeaTestNgPluginListener class tests") class IntellijIdeaTestNgPluginListenerTests extends BaseUnitTest { - @Test - @DisplayName("Check onExecutionStart()") - void unitTest_20180920223244() { - try { - IntellijIdeaTestNgPluginListener listener = new IntellijIdeaTestNgPluginListener(); - listener.onExecutionStart(); - assertThat(listener.isEnable(), is(false)); - } finally { - System.setProperty(INTELLIJ_IDEA_TEST_RUN, Boolean.FALSE.toString()); - } - } +// @Test +// @DisplayName("Check onExecutionStart()") +// void unitTest_20180920223244() { +// try { +// IntellijIdeaTestNgPluginListener listener = new IntellijIdeaTestNgPluginListener(); +// listener.onExecutionStart(); +// assertThat(listener.isEnable(), is(false)); +// } finally { +// System.setProperty(INTELLIJ_IDEA_TEST_RUN, Boolean.FALSE.toString()); +// } +// } } diff --git a/buggy-core/src/test/java/org/touchbit/buggy/core/tests/testng/TestSuiteTests.java b/buggy-core/src/test/java/org/touchbit/buggy/core/tests/testng/TestSuiteTests.java deleted file mode 100644 index 875a1c2..0000000 --- a/buggy-core/src/test/java/org/touchbit/buggy/core/tests/testng/TestSuiteTests.java +++ /dev/null @@ -1,292 +0,0 @@ -/* - * Copyright © 2018 Shaburov Oleg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.touchbit.buggy.core.tests.testng; - -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.testng.xml.XmlClass; -import org.testng.xml.XmlTest; -import org.touchbit.buggy.core.process.DefaultComponent; -import org.touchbit.buggy.core.tests.BaseUnitTest; -import org.touchbit.buggy.core.exceptions.BuggyConfigurationException; -import org.touchbit.buggy.core.config.TestClassWithoutSuite; -import org.touchbit.buggy.core.config.TestComponent; -import org.touchbit.buggy.core.config.TestInterface; -import org.touchbit.buggy.core.config.TestService; -import org.touchbit.buggy.core.model.Suite; -import org.touchbit.buggy.core.process.Component; -import org.touchbit.buggy.core.process.Interface; -import org.touchbit.buggy.core.process.Service; -import org.touchbit.buggy.core.testng.TestSuite; - -import java.lang.annotation.Annotation; -import java.util.Set; -import java.util.stream.Collectors; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.testng.xml.XmlSuite.ParallelMode.TESTS; - -/** - * Created by Oleg Shaburov on 20.09.2018 - * shaburov.o.a@gmail.com - */ -@DisplayName("TestSuite class tests") -class TestSuiteTests extends BaseUnitTest { - - @Test - @DisplayName("Check TestSuite() constructor with @Suite") - void unitTest_20180920150141() { - UnitTestTestSuite suite = new UnitTestTestSuite(); - assertThat(suite.getInterface(), is(notNullValue())); - assertThat(suite.getComponent(), is(notNullValue())); - assertThat(suite.getService(), is(notNullValue())); - assertThat(suite.getSuite(), is(notNullValue())); - assertThat(suite.getSuite().task(), is("")); - } - - @Test - @DisplayName("Check TestSuite(int threadCount) constructor with @Suite") - void unitTest_20180920153817() { - UnitTestTestSuite suite = new UnitTestTestSuite(10); - assertThat(suite.getInterface(), is(notNullValue())); - assertThat(suite.getComponent(), is(notNullValue())); - assertThat(suite.getService(), is(notNullValue())); - assertThat(suite.getSuite(), is(notNullValue())); - assertThat(suite.getSuite().task(), is("")); - } - - @Test - @DisplayName("Check TestSuite() constructor without @Suite") - void unitTest_20180920151455() { - BuggyConfigurationException e = execute(TestSuite::new, BuggyConfigurationException.class); - assertThat(e.getMessage(), - is("There is no @Suite annotation for class org.touchbit.buggy.core.testng.TestSuite")); - } - - @Test - @DisplayName("Check TestSuite(int threadCount) constructor without @Suite") - void unitTest_20180920153513() { - BuggyConfigurationException e = execute(() -> new TestSuite(10), BuggyConfigurationException.class); - assertThat(e.getMessage(), - is("There is no @Suite annotation for class org.touchbit.buggy.core.testng.TestSuite")); - } - - @Test - @DisplayName("Check TestSuite(String name, int threadCount, ParallelMode parallel, Suite s)") - void unitTest_20180920154032() { - TestSuite testSuite = new TestSuite("name", 120, TESTS, SUITE); - assertThat(testSuite.getInterface(), is(notNullValue())); - assertThat(testSuite.getComponent(), is(notNullValue())); - assertThat(testSuite.getService(), is(notNullValue())); - assertThat(testSuite.getSuite(), is(notNullValue())); - assertThat(testSuite.getSuite().task(), is("task")); - assertThat(testSuite.getName(), is("name")); - } - - @Test - @DisplayName("Check the same XmlTest & XmlClasses") - void unitTest_20180920154709() { - TestSuite testSuite = new TestSuite("name", 120, TESTS, SUITE); - testSuite.addTestPackage("TestPackage", TestClassWithoutSuite.class); - testSuite.addTestPackage("TestPackage", TestClassWithoutSuite.class); - assertThat(testSuite.getTests().size(), is(1)); - assertThat(testSuite.getTests().get(0).getName(), is("TestPackage")); - assertThat(testSuite.getTests().get(0).getXmlClasses().size(), is(1)); - assertThat(testSuite.getTests().get(0).getXmlClasses().get(0).getName(), - is(TestClassWithoutSuite.class.getTypeName())); - } - - @Test - @DisplayName("Check different XmlClasses") - void unitTest_20180920173105() { - TestSuite testSuite = new TestSuite("name", 120, TESTS, SUITE); - testSuite.addTestPackage("TestPackage", TestClassWithoutSuite.class); - testSuite.addTestPackage("TestPackage", TestSuiteTests.class); - assertThat(testSuite.getName(), is("name")); - assertThat(testSuite.getTests().size(), is(1)); - assertThat(testSuite.getTests().get(0).getName(), is("TestPackage")); - assertThat(testSuite.getTests().get(0).getXmlClasses().size(), is(2)); - Set unavailableItems = testSuite.getTests().get(0).getXmlClasses().stream() - .map(XmlClass::getName) - .collect(Collectors.toSet()); - assertThat(unavailableItems, - containsInAnyOrder(TestSuiteTests.class.getTypeName(), TestClassWithoutSuite.class.getTypeName())); - } - - @Test - @DisplayName("Check duplicates classes") - void unitTest_20180920200611() { - TestSuite testSuite = new TestSuite("name", 120, TESTS, SUITE); - testSuite.addTestPackage("TestPackage", TestClassWithoutSuite.class, TestClassWithoutSuite.class); - assertThat(testSuite.getName(), is("name")); - assertThat(testSuite.getTests().size(), is(1)); - assertThat(testSuite.getTests().get(0).getName(), is("TestPackage")); - assertThat(testSuite.getTests().get(0).getXmlClasses().size(), is(1)); - Set unavailableItems = testSuite.getTests().get(0).getXmlClasses().stream() - .map(XmlClass::getName) - .collect(Collectors.toSet()); - assertThat(unavailableItems, - containsInAnyOrder(TestClassWithoutSuite.class.getTypeName())); - } - - @Test - @DisplayName("Check duplicates XmlTest") - void unitTest_20180920200806() { - TestSuite testSuite = new TestSuite("name", 120, TESTS, SUITE); - testSuite.setLog(TEST_LOGGER); - testSuite.addTestPackage("TestPackage1", TestClassWithoutSuite.class, TestClassWithoutSuite.class); - testSuite.addTestPackage("TestPackage2", TestSuiteTests.class, TestSuiteTests.class); - testSuite.addTestPackage("TestPackage1", TestClassWithoutSuite.class, TestClassWithoutSuite.class); - assertThat(testSuite.getName(), is("name")); - assertThat(testSuite.getTests().size(), is(2)); - Set xmlTestSet = testSuite.getTests().stream() - .map(XmlTest::getName) - .collect(Collectors.toSet()); - assertThat(xmlTestSet, containsInAnyOrder("TestPackage1", "TestPackage2")); - assertThat(testSuite.getTests().get(0).getXmlClasses().size(), is(1)); - for (XmlTest test : testSuite.getTests()) { - Set classSet = test.getXmlClasses().stream() - .map(XmlClass::getName) - .collect(Collectors.toSet()); - if (test.getName().equalsIgnoreCase("TestPackage1")) { - assertThat(classSet, containsInAnyOrder(TestClassWithoutSuite.class.getTypeName())); - } else { - assertThat(classSet, containsInAnyOrder(TestSuiteTests.class.getTypeName())); - } - } - assertThat(TEST_LOGGER.takeLoggedMessages().toString(), containsString(" classes:\n")); - } - - @Test - @DisplayName("Check empty XmlTest") - void unitTest_20180920204620() { - TestSuite testSuite = new TestSuite("name", 120, TESTS, SUITE); - testSuite.addTestPackage("TestPackage1"); - assertThat(testSuite.getTests().size(), is(0)); - } - - @Test - @DisplayName("Check empty XmlTest name") - void unitTest_20180920204732() { - TestSuite testSuite = new TestSuite("name", 120, TESTS, SUITE); - testSuite.addTestPackage(""); - assertThat(testSuite.getTests().size(), is(0)); - testSuite.addTestPackage(null); - assertThat(testSuite.getTests().size(), is(0)); - } - - @Test - @DisplayName("Check equals by Suite annotation") - void unitTest_20181022031937() { - TestSuite testSuite1 = new TestSuite("name", 120, TESTS, SUITE); - TestSuite testSuite2 = new TestSuite("name", 120, TESTS, SUITE); - assertThat(testSuite1.equals(testSuite2), is(true)); - } - - @Test - @DisplayName("Check not equals by Suite annotation") - void unitTest_20181022032227() { - TestSuite testSuite1 = new TestSuite("name", 120, TESTS, SUITE); - TestSuite testSuite2 = new TestSuite("name", 120, TESTS, SUITE2); - assertThat(testSuite1.equals(testSuite2), is(false)); - } - - @Test - @DisplayName("Check not equals by Object") - void unitTest_20181022032554() { - TestSuite testSuite = new TestSuite("name", 120, TESTS, SUITE); - testSuite.setLog(TEST_LOGGER); - assertThat(testSuite.equals(new Object()), is(false)); - } - - @Test - @DisplayName("Check hashCode for 2 same suites") - void unitTest_20181022033229() { - TestSuite testSuite1 = new TestSuite("name", 120, TESTS, SUITE); - TestSuite testSuite2 = new TestSuite("name", 120, TESTS, SUITE); - assertThat(testSuite1.hashCode(), is(testSuite2.hashCode())); - } - - @Test - @DisplayName("Check hashCode for 2 different suites") - void unitTest_20181022033314() { - TestSuite testSuite1 = new TestSuite("name", 120, TESTS, SUITE); - TestSuite testSuite2 = new TestSuite("name", 120, TESTS, SUITE2); - assertThat(testSuite1.hashCode(), not(testSuite2.hashCode())); - } - - @Test - @DisplayName("GIVEN WHEN THEN") - void unitTest_20181029004902() { - TestSuite testSuite = new TestSuite("TestSuiteName", 120, TESTS, SUITE); - testSuite.setLog(TEST_LOGGER); - TEST_LOGGER.whenDebugEnabled(false); - testSuite.addTestPackage("TestPackage_1", Object.class); - assertThat(TEST_LOGGER.takeLoggedMessages(), - contains("Suite TestSuiteName. Add test package (XmlTest): TestPackage_1") - ); - TEST_LOGGER.whenDebugEnabled(true); - testSuite.addTestPackage("TestPackage_2", Object.class); - assertThat(TEST_LOGGER.takeLoggedMessages(), contains( - "The test package TestPackage_1 already contains a class: [XmlClass class=java.lang.Object]", - "The TestPackage_2 test package (XmlTest) does not contain unique test classes and has not been added to the TestSuiteName test suite.") - ); - } - - private static final Suite SUITE2 = new Suite() { - @Override - public Class annotationType() { return Suite.class; } - @Override - public Class component() { return DefaultComponent.class; } - @Override - public Class service() { return TestService.class; } - @Override - public Class interfaze() { return TestInterface.class; } - @Override - public String task() { return "task"; } - }; - - private static final Suite SUITE = new Suite() { - @Override - public Class annotationType() { return Suite.class; } - @Override - public Class component() { return TestComponent.class; } - @Override - public Class service() { return TestService.class; } - @Override - public Class interfaze() { return TestInterface.class; } - @Override - public String task() { return "task"; } - }; - - @SuppressWarnings("WeakerAccess") - @Suite(component = TestComponent.class, service = TestService.class, interfaze = TestInterface.class) - public static class UnitTestTestSuite extends TestSuite { - - public UnitTestTestSuite(int threadCount) { - super(threadCount); - addTestPackage("Example", TestClassWithoutSuite.class); - } - - public UnitTestTestSuite() { - addTestPackage("Example", TestClassWithoutSuite.class); - } - - } - -} diff --git a/buggy-core/src/test/java/org/touchbit/buggy/core/tests/testng/listeners/TestSupervisorTests.java b/buggy-core/src/test/java/org/touchbit/buggy/core/tests/testng/TestSupervisorTests.java similarity index 98% rename from buggy-core/src/test/java/org/touchbit/buggy/core/tests/testng/listeners/TestSupervisorTests.java rename to buggy-core/src/test/java/org/touchbit/buggy/core/tests/testng/TestSupervisorTests.java index 0b4fe2b..ff991af 100644 --- a/buggy-core/src/test/java/org/touchbit/buggy/core/tests/testng/listeners/TestSupervisorTests.java +++ b/buggy-core/src/test/java/org/touchbit/buggy/core/tests/testng/TestSupervisorTests.java @@ -14,15 +14,15 @@ * limitations under the License. */ -package org.touchbit.buggy.core.tests.testng.listeners; +package org.touchbit.buggy.core.tests.testng; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.testng.IInvokedMethod; import org.testng.ITestNGMethod; -import org.touchbit.buggy.core.tests.BaseUnitTest; import org.touchbit.buggy.core.exceptions.BuggyConfigurationException; -import org.touchbit.buggy.core.testng.listeners.TestSupervisor; +import org.touchbit.buggy.core.testng.TestSupervisor; +import org.touchbit.buggy.core.tests.BaseUnitTest; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.awaitility.Awaitility.await; diff --git a/buggy-core/src/test/java/org/touchbit/buggy/core/tests/testng/listeners/BaseBuggyExecutionListenerTests.java b/buggy-core/src/test/java/org/touchbit/buggy/core/tests/testng/listeners/BaseBuggyExecutionListenerTests.java deleted file mode 100644 index 22dbb81..0000000 --- a/buggy-core/src/test/java/org/touchbit/buggy/core/tests/testng/listeners/BaseBuggyExecutionListenerTests.java +++ /dev/null @@ -1,102 +0,0 @@ -package org.touchbit.buggy.core.tests.testng.listeners; - -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.testng.ITestNGMethod; -import org.touchbit.buggy.core.Buggy; -import org.touchbit.buggy.core.model.Details; -import org.touchbit.buggy.core.model.Status; -import org.touchbit.buggy.core.model.Type; -import org.touchbit.buggy.core.tests.BaseUnitTest; -import org.touchbit.buggy.core.testng.listeners.BaseBuggyExecutionListener; - -import java.lang.reflect.Method; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; - -/** - * Created by Oleg Shaburov on 14.10.2018 - * shaburov.o.a@gmail.com - */ -class BaseBuggyExecutionListenerTests extends BaseUnitTest { - - @Test - @DisplayName("Check get url log file where !getArtifactsUrl().endsWith(\"/\")") - void unitTest_20181014215332() { - String temp = Buggy.getPrimaryConfig().getArtifactsUrl(); - try { - UnitTestBaseBuggyExecutionListener listener = new UnitTestBaseBuggyExecutionListener(); - Buggy.getPrimaryConfig().setArtifactsUrl("https://touchbit.org/artifacts"); - ITestNGMethod method = getMockITestNGMethod(); - String result = listener.getLogFilePath(method); - assertThat(result, is("https://touchbit.org/artifacts/waste-unit-tests/tests/iTestResultMethodWithDetails.log")); - } finally { - Buggy.getPrimaryConfig().setArtifactsUrl(temp); - } - } - - @Test - @DisplayName("Check get url log file where getArtifactsUrl().endsWith(\"/\")") - void unitTest_20181014222846() { - String temp = Buggy.getPrimaryConfig().getArtifactsUrl(); - try { - UnitTestBaseBuggyExecutionListener listener = new UnitTestBaseBuggyExecutionListener(); - Buggy.getPrimaryConfig().setArtifactsUrl("https://touchbit.org/artifacts/"); - ITestNGMethod method = getMockITestNGMethod(); - String result = listener.getLogFilePath(method); - assertThat(result, is("https://touchbit.org/artifacts/waste-unit-tests/tests/iTestResultMethodWithDetails.log")); - } finally { - Buggy.getPrimaryConfig().setArtifactsUrl(temp); - } - } - - @Test - @DisplayName("Check get local log file if ArtifactsUrl == null") - void unitTest_20181014223022() { - String temp = Buggy.getPrimaryConfig().getArtifactsUrl(); - try { - Buggy.getPrimaryConfig().setArtifactsUrl(null); - UnitTestBaseBuggyExecutionListener listener = new UnitTestBaseBuggyExecutionListener(); - Buggy.getPrimaryConfig().setArtifactsUrl(null); - ITestNGMethod method = getMockITestNGMethod(); - String result = listener.getLogFilePath(method); - assertThat(result, is("file://" + Buggy.getPrimaryConfig().getAbsoluteLogPath() + - "/tests/iTestResultMethodWithDetails.log")); - } finally { - Buggy.getPrimaryConfig().setArtifactsUrl(temp); - } - } - - @Test - @DisplayName("Check get local log file if ArtifactsUrl == \"null\"") - void unitTest_20181016135040() { - String temp = Buggy.getPrimaryConfig().getArtifactsUrl(); - try { - Buggy.getPrimaryConfig().setArtifactsUrl("null"); - UnitTestBaseBuggyExecutionListener listener = new UnitTestBaseBuggyExecutionListener(); - Buggy.getPrimaryConfig().setArtifactsUrl(null); - ITestNGMethod method = getMockITestNGMethod(); - String result = listener.getLogFilePath(method); - assertThat(result, is("file://" + Buggy.getPrimaryConfig().getAbsoluteLogPath() + - "/tests/iTestResultMethodWithDetails.log")); - } finally { - Buggy.getPrimaryConfig().setArtifactsUrl(temp); - } - } - - private static class UnitTestBaseBuggyExecutionListener extends BaseBuggyExecutionListener { - - @Override - public boolean isEnable() { - return false; - } - - @Override - public String getLogFilePath(ITestNGMethod method) { - return super.getLogFilePath(method); - } - - } - -} diff --git a/buggy-core/src/test/java/org/touchbit/buggy/core/tests/testng/listeners/BaseTelegramNotifierTests.java b/buggy-core/src/test/java/org/touchbit/buggy/core/tests/testng/listeners/BaseTelegramNotifierTests.java deleted file mode 100644 index 4ab6ba7..0000000 --- a/buggy-core/src/test/java/org/touchbit/buggy/core/tests/testng/listeners/BaseTelegramNotifierTests.java +++ /dev/null @@ -1,246 +0,0 @@ -/* - * Copyright © 2018 Shaburov Oleg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.touchbit.buggy.core.tests.testng.listeners; - -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.touchbit.buggy.core.tests.BaseUnitTest; -import org.touchbit.buggy.core.Buggy; -import org.touchbit.buggy.core.exceptions.CorruptedTestException; -import org.touchbit.buggy.core.model.Notifier; -import org.touchbit.buggy.core.testng.listeners.BaseTelegramNotifier; - -import static java.util.concurrent.TimeUnit.MILLISECONDS; -import static org.awaitility.Awaitility.await; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; - -/** - * Created by Oleg Shaburov on 20.09.2018 - * shaburov.o.a@gmail.com - */ -@DisplayName("BaseTelegramNotifier class tests") -class BaseTelegramNotifierTests extends BaseUnitTest { - - @Test - @DisplayName("Check onExecutionFinish report") - void unitTest_20180920225957() { - StringBuilder sb = new StringBuilder(); - Notifier notifier = sb::append; - BaseTelegramNotifier telegram = new BaseTelegramNotifier(notifier) { - @Override - public boolean isEnable() { - testCount.set(0); - skippedTests.set(0); - corruptedError.set(0); - expFixError.set(0); - expImplError.set(0); - blockedError.set(0); - newError.set(0); - fixed.set(0); - implemented.set(0); - return true; - } - }; - telegram.onExecutionFinish(); - assertThat(sb.toString(), is("" + - "*Buggy*\n" + - "Run Results:\n" + - "`--------------------------------`\n" + - "`Running tests..................`0\n" + - "`--------------------------------`\n" + - "`Successful tests...............`0\n" + - "`Skipped tests..................`0\n" + - "`Failed tests...................`0\n" + - "`--------------------------------`\n" + - "`New Errors.....................`0\n" + - "`Waiting to fix a defect........`0\n" + - "`Waiting for the implementation.`0\n" + - "`Blocked tests..................`0\n" + - "`Corrupted tests................`0\n" + - "`--------------------------------`\n" + - "`Fixed defects..................`0\n" + - "`Implemented cases..............`0\n" + - "`--------------------------------`\n" + - "Test execution time: *00:00:00*\n" + - "[Logs](null)\n")); - Buggy.setProgramName(""); - sb = new StringBuilder(); - notifier = sb::append; - telegram = new BaseTelegramNotifier(notifier) { - @Override - public boolean isEnable() { - testCount.set(0); - skippedTests.set(0); - corruptedError.set(0); - expFixError.set(0); - expImplError.set(0); - blockedError.set(0); - newError.set(0); - fixed.set(0); - implemented.set(0); - return true; - } - }; - telegram.onExecutionFinish(); - assertThat(sb.toString(), is("" + - "Run Results:\n" + - "`--------------------------------`\n" + - "`Running tests..................`0\n" + - "`--------------------------------`\n" + - "`Successful tests...............`0\n" + - "`Skipped tests..................`0\n" + - "`Failed tests...................`0\n" + - "`--------------------------------`\n" + - "`New Errors.....................`0\n" + - "`Waiting to fix a defect........`0\n" + - "`Waiting for the implementation.`0\n" + - "`Blocked tests..................`0\n" + - "`Corrupted tests................`0\n" + - "`--------------------------------`\n" + - "`Fixed defects..................`0\n" + - "`Implemented cases..............`0\n" + - "`--------------------------------`\n" + - "Test execution time: *00:00:00*\n" + - "[Logs](null)\n")); - } - - @Test - @DisplayName("Check report with program name") - void unitTest_20180920231126() { - StringBuilder sb = new StringBuilder(); - Buggy.setProgramName("unitTest_20180920231126"); - Notifier notifier = sb::append; - BaseTelegramNotifier telegram = new BaseTelegramNotifier(notifier) { - @Override - public boolean isEnable() { - testCount.set(0); - skippedTests.set(0); - corruptedError.set(0); - expFixError.set(0); - expImplError.set(0); - blockedError.set(0); - newError.set(0); - fixed.set(0); - implemented.set(0); - return true; - } - }; - telegram.onExecutionFinish(); - assertThat(sb.toString(), is("" + - "*unitTest_20180920231126*\n" + - "Run Results:\n" + - "`--------------------------------`\n" + - "`Running tests..................`0\n" + - "`--------------------------------`\n" + - "`Successful tests...............`0\n" + - "`Skipped tests..................`0\n" + - "`Failed tests...................`0\n" + - "`--------------------------------`\n" + - "`New Errors.....................`0\n" + - "`Waiting to fix a defect........`0\n" + - "`Waiting for the implementation.`0\n" + - "`Blocked tests..................`0\n" + - "`Corrupted tests................`0\n" + - "`--------------------------------`\n" + - "`Fixed defects..................`0\n" + - "`Implemented cases..............`0\n" + - "`--------------------------------`\n" + - "Test execution time: *00:00:00*\n" + - "[Logs](null)\n")); - } - - @Test - @DisplayName("Check report with ArtifactsUrl") - void unitTest_20180920231553() { - StringBuilder sb = new StringBuilder(); - Buggy.setProgramName(null); - Notifier notifier = sb::append; - Buggy.getPrimaryConfig().setArtifactsUrl("http://build.url"); - try { - BaseTelegramNotifier telegram = new BaseTelegramNotifier(notifier) { - @Override - public boolean isEnable() { - testCount.set(6); - skippedTests.set(1); - corruptedError.incrementAndGet(); - expFixError.incrementAndGet(); - expImplError.incrementAndGet(); - blockedError.incrementAndGet(); - newError.incrementAndGet(); - fixed.incrementAndGet(); - implemented.incrementAndGet(); - return true; - } - }; - telegram.onExecutionFinish(); - assertThat(sb.toString(), is("Run Results:\n" + - "`--------------------------------`\n" + - "`Running tests..................`6\n" + - "`--------------------------------`\n" + - "`Successful tests...............`1\n" + - "`Skipped tests..................`1\n" + - "`Failed tests...................`5\n" + - "`--------------------------------`\n" + - "`New Errors.....................`[1](http://build.url/errors/new/)\n" + - "`Waiting to fix a defect........`[1](http://build.url/errors/exp_fix/)\n" + - "`Waiting for the implementation.`[1](http://build.url/errors/exp_impl/)\n" + - "`Blocked tests..................`[1](http://build.url/errors/blocked/)\n" + - "`Corrupted tests................`[1](http://build.url/errors/corrupted/)\n" + - "`--------------------------------`\n" + - "`Fixed defects..................`[1](http://build.url/fixed/exp_fix/)\n" + - "`Implemented cases..............`[1](http://build.url/fixed/exp_impl/)\n" + - "`--------------------------------`\n" + - "Test execution time: *00:00:00*\n" + - "[Logs](http://build.url)\n")); - } finally { - Buggy.getPrimaryConfig().setArtifactsUrl(null); - } - } - - @Test - @DisplayName("Check failed notification") - void unitTest_20180920232942() { - int errors = Buggy.getBuggyErrors(); - Notifier notifier = msg -> { - throw new CorruptedTestException("unitTest_20180920232942"); - }; - BaseTelegramNotifier telegram = new BaseTelegramNotifier(notifier) { - @Override - public boolean isEnable() { return true; } - }; - telegram.onExecutionStart(); - await().atMost(50, MILLISECONDS); - telegram.onExecutionFinish(); - assertThat(Buggy.getBuggyErrors(), is((errors + 1))); - } - - @Test - @DisplayName("Check disable notification") - void unitTest_20180920230951() { - StringBuilder sb = new StringBuilder(); - Notifier notifier = sb::append; - BaseTelegramNotifier telegram = new BaseTelegramNotifier(notifier) { - @Override - public boolean isEnable() { return false; } - }; - telegram.onExecutionStart(); - telegram.onExecutionFinish(); - assertThat(sb.toString(), is("")); - } - -} diff --git a/buggy-core/src/test/java/org/touchbit/buggy/core/tests/testng/listeners/BuggyExecutionListenerTests.java b/buggy-core/src/test/java/org/touchbit/buggy/core/tests/testng/listeners/BuggyExecutionListenerTests.java deleted file mode 100644 index 9d58079..0000000 --- a/buggy-core/src/test/java/org/touchbit/buggy/core/tests/testng/listeners/BuggyExecutionListenerTests.java +++ /dev/null @@ -1,2192 +0,0 @@ -/* - * Copyright © 2018 Shaburov Oleg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.touchbit.buggy.core.tests.testng.listeners; - -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Nested; -import org.junit.jupiter.api.Test; -import org.testng.*; -import org.touchbit.buggy.core.config.TestComponent; -import org.touchbit.buggy.core.config.TestInterface; -import org.touchbit.buggy.core.config.TestNGTestClassWithSuite; -import org.touchbit.buggy.core.config.TestService; -import org.touchbit.buggy.core.model.Status; -import org.touchbit.buggy.core.model.Suite; -import org.touchbit.buggy.core.process.Component; -import org.touchbit.buggy.core.process.Interface; -import org.touchbit.buggy.core.process.Service; -import org.touchbit.buggy.core.tests.BaseUnitTest; -import org.touchbit.buggy.core.Buggy; -import org.touchbit.buggy.core.exceptions.ExpectedImplementationException; -import org.touchbit.buggy.core.model.Type; -import org.touchbit.buggy.core.testng.listeners.BuggyExecutionListener; - -import java.io.File; -import java.io.IOException; -import java.lang.annotation.Annotation; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.atomic.AtomicInteger; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import static org.touchbit.buggy.core.config.BParameters.PRINT_CAUSE; -import static org.touchbit.buggy.core.config.BParameters.PRINT_LOG; -import static org.touchbit.buggy.core.config.BParameters.PRINT_SUITE; -import static org.touchbit.buggy.core.model.Status.*; -import static org.touchbit.buggy.core.model.Type.*; - -/** - * Created by Oleg Shaburov on 21.09.2018 - * shaburov.o.a@gmail.com - */ -@DisplayName("BuggyExecutionListener class tests") -class BuggyExecutionListenerTests extends BaseUnitTest { - - @Test - @DisplayName("Check BuggyExecutionListener()") - void unitTest_20180921144349() { - BuggyExecutionListener listener = new BuggyExecutionListener(); - listener.onExecutionStart(); - listener.onExecutionFinish(); - assertThat(listener.isEnable(), is(true)); - } - - @Test - @DisplayName("Check BuggyExecutionListener(null, null, null)") - void unitTest_20180921144529() { - BuggyExecutionListener listener = new BuggyExecutionListener(null, null, null); - listener.onExecutionStart(); - listener.onExecutionFinish(); - assertThat(listener.isEnable(), is(true)); - } - - @Test - @DisplayName("Check BuggyExecutionListener(Logger testLogger, Logger frameworkLogger, Logger consoleLogger)") - void unitTest_20180921144624() { - BuggyExecutionListener listener = new BuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - listener.onExecutionStart(); - listener.onExecutionFinish(); - assertThat(listener.isEnable(), is(true)); - } - - @Test - @DisplayName("Check 'do nothing' methods") - void unitTest_20180921145653() { - BuggyExecutionListener listener = new BuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - ITestContext iTestContext = mock(ITestContext.class); - ITestClass iTestClass = mock(ITestClass.class); - ITestResult iTestResult = mock(ITestResult.class); - listener.onStart(iTestContext); - listener.onFinish(iTestContext); - listener.onBeforeClass(iTestClass); - listener.onTestStart(iTestResult); - } - - @Test - @DisplayName("Check onTestSuccess(ITestResult result)") - void unitTest_20180921150511() { - BuggyExecutionListener listener = new BuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - ITestResult iTestResult = getMockITestResult(1); - listener.onTestSuccess(iTestResult); - } - - @Test - @DisplayName("Check onTestFailure(ITestResult result)") - void unitTest_20180921150916() { - BuggyExecutionListener listener = new BuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - ITestResult iTestResult = getMockITestResult(2); - listener.onTestFailure(iTestResult); - } - - @Test - @DisplayName("Check onTestSkipped(ITestResult result)") - void unitTest_20180921151028() { - BuggyExecutionListener listener = new BuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - ITestResult iTestResult = getMockITestResult(3); - listener.onTestSkipped(iTestResult); - } - - @Test - @DisplayName("Check onTestFailedButWithinSuccessPercentage(ITestResult result)") - void unitTest_20180921151130() { - BuggyExecutionListener listener = new BuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - ITestResult iTestResult = getMockITestResult(4); - listener.onTestFailedButWithinSuccessPercentage(iTestResult); - } - - @Test - @DisplayName("Check onTestFinish with ExpectedImplementationException") - void unitTest_20180921182848() { - BuggyExecutionListener listener = new BuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - ITestResult iTestResult = getMockITestResult(4); - when(iTestResult.getThrowable()).thenReturn(new ExpectedImplementationException("")); - listener.onTestFinish(iTestResult); - } - - @Test - @DisplayName("Check onTestFinish with Exception") - void unitTest_20180921183436() { - BuggyExecutionListener listener = new BuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - ITestResult iTestResult = getMockITestResult(4); - when(iTestResult.getThrowable()).thenReturn(new Exception("")); - listener.onTestFinish(iTestResult); - } - - @Test - @DisplayName("Check onTestFinish with null steps") - void unitTest_20180921183125() { - BuggyExecutionListener listener = new BuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - ITestResult iTestResult = getMockITestResult(1); - BuggyExecutionListener.setSteps(null); - listener.onTestFinish(iTestResult); - } - - @Test - @DisplayName("Check onTestFinish with empty steps") - void unitTest_20180921183228() { - BuggyExecutionListener listener = new BuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - ITestResult iTestResult = getMockITestResult(1); - BuggyExecutionListener.setSteps(new ArrayList() {{ add("steppp"); }}); - listener.onTestFinish(iTestResult); - } - - @Test - @DisplayName("Check onAfterClass(ITestClass iTestClass) with Suite") - void unitTest_20180921183611() { - BuggyExecutionListener listener = new BuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - ITestClass iTestClass = getMockITestClass(TestNGTestClassWithSuite.class); - BuggyExecutionListener.setSteps(new ArrayList<>()); - listener.onAfterClass(iTestClass); - } - - @Test - @DisplayName("Check onAfterClass(ITestClass iTestClass) without Suite") - void unitTest_20180921184448() { - BuggyExecutionListener listener = new BuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - ITestClass iTestClass = getMockITestClass(Object.class); - BuggyExecutionListener.setSteps(new ArrayList<>()); - listener.onAfterClass(iTestClass); - } - - @Test - @DisplayName("Check onStart() if forceRun disabled") - void unitTest_20180922083207() { - Type configType = Buggy.getPrimaryConfig().getType(); - boolean isForceRun = Buggy.getPrimaryConfig().isForceRun(); - try { - Buggy.getPrimaryConfig().setType(MODULE); - Buggy.getPrimaryConfig().setForceRun(false); - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(getDetails(EXP_FIX, SMOKE)); - ITestNGMethod method = getMockITestNGMethod(TestNGTestClassWithSuite.class, "iTestResultMethodWithoutDetails"); - List allMethods = new ArrayList<>(); - allMethods.add(method); - ISuite suite = mock(ISuite.class); - when(suite.getAllMethods()).thenReturn(allMethods); - int expWarn = Buggy.getBuggyWarns(); - listener.onStart(suite); - assertThat(listener.method, not(nullValue())); - assertThat(listener.status, is(EXP_FIX)); - assertThat(listener.msg, is("forced test run disabled")); - assertThat(Buggy.getBuggyWarns(), is(expWarn)); - } finally { - Buggy.getPrimaryConfig().setType(configType); - Buggy.getPrimaryConfig().setForceRun(isForceRun); - } - } - - @Test - @DisplayName("Check onStart() if forceRun enabled") - void unitTest_20180922085022() { - Type configType = Buggy.getPrimaryConfig().getType(); - boolean isForceRun = Buggy.getPrimaryConfig().isForceRun(); - try { - Buggy.getPrimaryConfig().setType(MODULE); - Buggy.getPrimaryConfig().setForceRun(true); - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(getDetails(EXP_FIX, SMOKE)); - ITestNGMethod method = getMockITestNGMethod(TestNGTestClassWithSuite.class, "iTestResultMethodWithoutDetails"); - List allMethods = new ArrayList<>(); - allMethods.add(method); - ISuite suite = mock(ISuite.class); - when(suite.getAllMethods()).thenReturn(allMethods); - int expWarn = Buggy.getBuggyWarns(); - listener.onStart(suite); - assertThat(listener.method, is(nullValue())); - assertThat(listener.status, is(nullValue())); - assertThat(listener.msg, is(nullValue())); - assertThat(Buggy.getBuggyWarns(), is(expWarn)); - } finally { - Buggy.getPrimaryConfig().setType(configType); - Buggy.getPrimaryConfig().setForceRun(isForceRun); - } - } - - @Test - @DisplayName("Check onFinish()") - void unitTest_20180922085205() { - IInvokedMethod method = getMockIInvokedMethod(true); - List allMethods = new ArrayList<>(); - allMethods.add(method); - ISuite suite = mock(ISuite.class); - when(suite.getAllInvokedMethods()).thenReturn(allMethods); - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(getDetails(EXP_FIX, SMOKE)); - listener.onFinish(suite); - } - - @Nested() - @DisplayName("beforeInvocation() tests") - class BeforeInvocationTests extends BaseUnitTest { - - @Test - @DisplayName("Check beforeInvocation() with STARTED status") - void unitTest_20180921191220() { - BuggyExecutionListener listener = getBuggyExecutionListener(); - IInvokedMethod iInvokedMethod = getMockIInvokedMethod(); - ITestResult iTestResult = getMockITestResult(16); - listener.beforeInvocation(iInvokedMethod, iTestResult); - String logResult = TEST_LOGGER.takeLoggedMessages().toString(); - assertThat(logResult, containsString("Test method is running:\niTestResultMethodWithDetails - null")); - assertThat(logResult, containsString("Declared method annotations:\n@")); - } - - @Test - @DisplayName("Check Check beforeInvocation() with CREATED status") - void unitTest_20180921191657() { - BuggyExecutionListener listener = getBuggyExecutionListener(); - IInvokedMethod iInvokedMethod = getMockIInvokedMethod(); - ITestResult iTestResult = getMockITestResult(-1); - listener.beforeInvocation(iInvokedMethod, iTestResult); - String logResult = TEST_LOGGER.takeLoggedMessages().toString(); - assertThat(logResult, containsString("Test method is running:\niTestResultMethodWithDetails - null")); - assertThat(logResult, containsString("Declared method annotations:\n@")); - } - - @Test - @DisplayName("Check beforeInvocation() is test method") - void unitTest_20180921191731() { - BuggyExecutionListener listener = getBuggyExecutionListener(); - IInvokedMethod iInvokedMethod = getMockIInvokedMethod(); - ITestResult iTestResult = getMockITestResult(16); - when(iInvokedMethod.isTestMethod()).thenReturn(true); - listener.beforeInvocation(iInvokedMethod, iTestResult); - String logResult = TEST_LOGGER.takeLoggedMessages().toString(); - assertThat(logResult, containsString("Test method is running:\niTestResultMethodWithDetails - null")); - assertThat(logResult, containsString("Declared method annotations:\n@")); - } - - @Test - @DisplayName("Check beforeInvocation() is no test method") - void unitTest_20180921191829() { - BuggyExecutionListener listener = getBuggyExecutionListener(); - IInvokedMethod iInvokedMethod = getMockIInvokedMethod(); - ITestResult iTestResult = getMockITestResult(16); - when(iInvokedMethod.isTestMethod()).thenReturn(false); - listener.beforeInvocation(iInvokedMethod, iTestResult); - String logResult = TEST_LOGGER.takeLoggedMessages().toString(); - assertThat(logResult, containsString("Configuration method is running:\niTestResultMethodWithDetails - null.")); - assertThat(logResult, containsString("Declared method annotations:\n@")); - } - - @Test - @DisplayName("Check debug info") - void unitTest_20180922090145() { - TEST_LOGGER.whenDebugEnabled(false); - BuggyExecutionListener listener = getBuggyExecutionListener(); - IInvokedMethod iInvokedMethod = getMockIInvokedMethod(); - ITestResult iTestResult = getMockITestResult(16); - when(iInvokedMethod.isTestMethod()).thenReturn(false); - listener.beforeInvocation(iInvokedMethod, iTestResult); - String logResult = TEST_LOGGER.takeLoggedMessages().toString(); - assertThat(logResult, containsString("Configuration method is running:\niTestResultMethodWithDetails - null.")); - assertThat(logResult, is(not(containsString("Declared method annotations:\n@")))); - } - - } - - @Nested() - @DisplayName("afterInvocation() tests") - class AfterInvocationTests extends BaseUnitTest { - - @Test - @DisplayName("Added ERROR to step when test method with exception and step list more than own") - void unitTest_20180921220759() { - BuggyExecutionListener listener = getBuggyExecutionListener(); - IInvokedMethod iInvokedMethod = getMockIInvokedMethod(); - when(iInvokedMethod.isTestMethod()).thenReturn(true); - ITestResult iTestResult = getMockITestResult(1); - when(iTestResult.getThrowable()).thenReturn(new Exception()); - BuggyExecutionListener.step(TEST_LOGGER, "with exception"); - listener.afterInvocation(iInvokedMethod, iTestResult); - assertThat(BuggyExecutionListener.getSteps(), contains("Step 1. with exception - ERROR")); - assertThat(TEST_LOGGER.takeLoggedMessages(), contains( - " ------------> Step 1. with exception", - "Execution of iTestResultMethodWithDetails resulted in an error.", - "iTestResultMethodWithDetails - SUCCESS null", - "iTestResultMethodWithDetails............SUCCESS")); - } - - @Test - @DisplayName("Skip add ERROR to step when test method with exception and step list is empty") - void unitTest_20181019023045() { - BuggyExecutionListener listener = getBuggyExecutionListener(); - IInvokedMethod iInvokedMethod = getMockIInvokedMethod(); - when(iInvokedMethod.isTestMethod()).thenReturn(true); - ITestResult iTestResult = getMockITestResult(1); - when(iTestResult.getThrowable()).thenReturn(new Exception()); - listener.afterInvocation(iInvokedMethod, iTestResult); - assertThat(BuggyExecutionListener.getSteps(), is(empty())); - assertThat(TEST_LOGGER.takeLoggedMessages(), contains( - "Execution of iTestResultMethodWithDetails resulted in an error.", - "iTestResultMethodWithDetails - SUCCESS null", - "iTestResultMethodWithDetails............SUCCESS")); - } - - @Test - @DisplayName("Check afterInvocation test method without exception") - void unitTest_20180921221233() { - BuggyExecutionListener listener = getBuggyExecutionListener(); - IInvokedMethod iInvokedMethod = getMockIInvokedMethod(); - when(iInvokedMethod.isTestMethod()).thenReturn(true); - ITestResult iTestResult = getMockITestResult(1); - listener.afterInvocation(iInvokedMethod, iTestResult); - assertThat(BuggyExecutionListener.getSteps(), is(empty())); - assertThat(TEST_LOGGER.takeLoggedMessages(), contains( - "iTestResultMethodWithDetails - SUCCESS null", - "iTestResultMethodWithDetails............SUCCESS" - )); - } - - @Test - @DisplayName("Check afterInvocation without @Details") - void unitTest_20180921222920() { - BuggyExecutionListener listener = getBuggyExecutionListener(); - IInvokedMethod iInvokedMethod = getMockIInvokedMethod(TestNGTestClassWithSuite.class, - "iTestResultMethodWithoutDetails", true); - when(iInvokedMethod.isTestMethod()).thenReturn(true); - ITestResult iTestResult = getMockITestResult(1); - listener.afterInvocation(iInvokedMethod, iTestResult); - assertThat(BuggyExecutionListener.getSteps(), is(empty())); - assertThat(TEST_LOGGER.takeLoggedMessages(), contains( - "The test method iTestResultMethodWithoutDetails does not contain the @Details annotation" - )); - } - - @Test - @DisplayName("Check afterInvocation configuration method") - void unitTest_20180921224011() { - BuggyExecutionListener listener = getBuggyExecutionListener(); - IInvokedMethod iInvokedMethod = getMockIInvokedMethod(); - when(iInvokedMethod.isTestMethod()).thenReturn(false); - listener.afterInvocation(iInvokedMethod, getMockITestResult(1)); - assertThat(BuggyExecutionListener.getSteps(), is(empty())); - assertThat(TEST_LOGGER.takeLoggedMessages(), contains( - "Invoke configuration method [iTestResultMethodWithDetails] completed successfully" - )); - } - - @Test - @DisplayName("Test count increment when status != SKIP") - void unitTest_20181019022603() { - BuggyExecutionListener listener = getBuggyExecutionListener(); - IInvokedMethod iInvokedMethod = getMockIInvokedMethod(); - when(iInvokedMethod.isTestMethod()).thenReturn(true); - int expTestCount = listener.getTestCount() + 1; - listener.afterInvocation(iInvokedMethod, getMockITestResult(ITestResult.SUCCESS)); - assertThat(listener.getTestCount(), is(expTestCount)); - listener.afterInvocation(iInvokedMethod, getMockITestResult(ITestResult.SKIP)); - assertThat(listener.getTestCount(), is(expTestCount)); - } - - } - - @Nested() - @DisplayName("step() tests") - class StepTests extends BaseUnitTest { - - @Test - @DisplayName("Check step(LOG, \"msg\")") - void unitTest_20180921192521() { - BuggyExecutionListener.step(TEST_LOGGER, "msg"); - assertThat(BuggyExecutionListener.getSteps(), contains("Step 1. msg")); - } - - @Test - @DisplayName("Check step(LOG, \"msg {}\", \"with args\")") - void unitTest_20180921192637() { - BuggyExecutionListener.step(TEST_LOGGER, "msg {}", "with args"); - assertThat(BuggyExecutionListener.getSteps(), contains("Step 1. msg with args")); - } - - @Test - @DisplayName("Check ignoring step() ASC") - void unitTest_20181004002108() { - BuggyExecutionListener.step(TEST_LOGGER, "a"); - BuggyExecutionListener.step(TEST_LOGGER, "b"); - assertThat(BuggyExecutionListener.getSteps().toString(), is("[Step 1. a, Step 2. b]")); - } - - @Test - @DisplayName("Check ignoring step() DESC") - void unitTest_20181004004254() { - BuggyExecutionListener.step(TEST_LOGGER, "b"); - BuggyExecutionListener.step(TEST_LOGGER, "a"); - assertThat(BuggyExecutionListener.getSteps().toString(), is("[Step 1. b, Step 2. a]")); - } - - } - - @Nested() - @DisplayName("processTestMethodResult() tests") - class ProcessTestMethodResultTests extends BaseUnitTest { - - @Test - @DisplayName("Check ITestResult.SUCCESS if Details EXP_FIX Status with issues") - void unitTest_20180922023815() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - IInvokedMethod method = getMockIInvokedMethod(); - listener.processTestMethodResult(method, getMockITestResult(ITestResult.SUCCESS), getDetails(EXP_FIX, "JIRA-123")); - assertThat(listener.method.getMethodName(), is(method.getTestMethod().getMethodName())); - assertThat(listener.status, is(FIXED)); - assertThat(listener.msg, is("[JIRA-123]")); - } - - @Test - @DisplayName("Check ITestResult.SUCCESS if Details EXP_FIX Status without issues") - void unitTest_20180922031547() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - IInvokedMethod method = getMockIInvokedMethod(); - listener.processTestMethodResult(method, getMockITestResult(ITestResult.SUCCESS), getDetails(EXP_FIX)); - assertThat(listener.method.getMethodName(), is(method.getTestMethod().getMethodName())); - assertThat(listener.status, is(FIXED)); - assertThat(listener.msg, is(isEmptyString())); - } - - @Test - @DisplayName("Check ITestResult.SUCCESS if Details BLOCKED Status with issues") - void unitTest_20180922031825() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - IInvokedMethod method = getMockIInvokedMethod(); - listener.processTestMethodResult(method, getMockITestResult(ITestResult.SUCCESS), getDetails(BLOCKED, "JIRA-123")); - assertThat(listener.method.getMethodName(), is(method.getTestMethod().getMethodName())); - assertThat(listener.status, is(FIXED)); - assertThat(listener.msg, is("[JIRA-123]")); - } - - @Test - @DisplayName("Check ITestResult.SUCCESS if Details BLOCKED Status without issues") - void unitTest_20180922031943() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - IInvokedMethod method = getMockIInvokedMethod(); - listener.processTestMethodResult(method, getMockITestResult(ITestResult.SUCCESS), getDetails(BLOCKED)); - assertThat(listener.method.getMethodName(), is(method.getTestMethod().getMethodName())); - assertThat(listener.status, is(FIXED)); - assertThat(listener.msg, is(isEmptyString())); - } - - @Test - @DisplayName("Check ITestResult.SUCCESS if Details EXP_IMPL Status with issues") - void unitTest_20180922033333() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - IInvokedMethod method = getMockIInvokedMethod(); - listener.processTestMethodResult(method, getMockITestResult(ITestResult.SUCCESS), getDetails(EXP_IMPL, "JIRA-123")); - assertThat(listener.method.getMethodName(), is(method.getTestMethod().getMethodName())); - assertThat(listener.status, is(IMPLEMENTED)); - assertThat(listener.msg, is("[JIRA-123]")); - } - - @Test - @DisplayName("Check ITestResult.SUCCESS if Details EXP_IMPL Status without issues") - void unitTest_20180922033338() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - IInvokedMethod method = getMockIInvokedMethod(); - listener.processTestMethodResult(method, getMockITestResult(ITestResult.SUCCESS), getDetails(EXP_IMPL)); - assertThat(listener.method.getMethodName(), is(method.getTestMethod().getMethodName())); - assertThat(listener.status, is(IMPLEMENTED)); - assertThat(listener.msg, is(isEmptyString())); - } - - @Test - @DisplayName("Check ITestResult.SUCCESS if Details CORRUPTED Status with issues") - void unitTest_20180922033427() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - IInvokedMethod method = getMockIInvokedMethod(); - listener.processTestMethodResult(method, getMockITestResult(ITestResult.SUCCESS), getDetails(CORRUPTED, "JIRA-123")); - assertThat(listener.method.getMethodName(), is(method.getTestMethod().getMethodName())); - assertThat(listener.status, is(CORRUPTED)); - assertThat(listener.msg, is("[JIRA-123]")); - } - - @Test - @DisplayName("Check ITestResult.SUCCESS if Details CORRUPTED Status without issues") - void unitTest_20180922033726() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - IInvokedMethod method = getMockIInvokedMethod(); - listener.processTestMethodResult(method, getMockITestResult(ITestResult.SUCCESS), getDetails(CORRUPTED)); - assertThat(listener.method.getMethodName(), is(method.getTestMethod().getMethodName())); - assertThat(listener.status, is(CORRUPTED)); - assertThat(listener.msg, is(isEmptyString())); - } - - @Test - @DisplayName("Check ITestResult.SUCCESS if Details FIXED Status with issues") - void unitTest_20180922033959() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - IInvokedMethod method = getMockIInvokedMethod(); - listener.processTestMethodResult(method, getMockITestResult(ITestResult.SUCCESS), getDetails(FIXED, "JIRA-123")); - assertThat(listener.method.getMethodName(), is(method.getTestMethod().getMethodName())); - assertThat(listener.status, is(SUCCESS)); - assertThat(listener.msg, is("[JIRA-123]")); - } - - @Test - @DisplayName("Check ITestResult.SUCCESS if Details IMPLEMENTED Status with issues") - void unitTest_20180922034106() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - IInvokedMethod method = getMockIInvokedMethod(); - listener.processTestMethodResult(method, getMockITestResult(ITestResult.SUCCESS), getDetails(IMPLEMENTED, "JIRA-123")); - assertThat(listener.method.getMethodName(), is(method.getTestMethod().getMethodName())); - assertThat(listener.status, is(SUCCESS)); - assertThat(listener.msg, is("[JIRA-123]")); - } - - @Test - @DisplayName("Check ITestResult.SUCCESS if Details UNTESTED Status with issues") - void unitTest_20180922034141() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - IInvokedMethod method = getMockIInvokedMethod(); - listener.processTestMethodResult(method, getMockITestResult(ITestResult.SUCCESS), getDetails(UNTESTED, "JIRA-123")); - assertThat(listener.method.getMethodName(), is(method.getTestMethod().getMethodName())); - assertThat(listener.status, is(SUCCESS)); - assertThat(listener.msg, is("[JIRA-123]")); - } - - @Test - @DisplayName("Check ITestResult.SUCCESS if Details SUCCESS Status with issues") - void unitTest_20180922034318() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - IInvokedMethod method = getMockIInvokedMethod(); - listener.processTestMethodResult(method, getMockITestResult(ITestResult.SUCCESS), getDetails(SUCCESS, "JIRA-123")); - assertThat(listener.method.getMethodName(), is(method.getTestMethod().getMethodName())); - assertThat(listener.status, is(SUCCESS)); - assertThat(listener.msg, is("[JIRA-123]")); - } - - @Test - @DisplayName("Check ITestResult.SUCCESS if Details SKIP Status with issues") - void unitTest_20180922034337() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - IInvokedMethod method = getMockIInvokedMethod(); - listener.processTestMethodResult(method, getMockITestResult(ITestResult.SUCCESS), getDetails(SKIP, "JIRA-123")); - assertThat(listener.method.getMethodName(), is(method.getTestMethod().getMethodName())); - assertThat(listener.status, is(SUCCESS)); - assertThat(listener.msg, is("[JIRA-123]")); - } - - @Test - @DisplayName("Check ITestResult.SUCCESS if Details FAILED Status with issues") - void unitTest_20180922034357() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - IInvokedMethod method = getMockIInvokedMethod(); - listener.processTestMethodResult(method, getMockITestResult(ITestResult.SUCCESS), getDetails(FAILED, "JIRA-123")); - assertThat(listener.method.getMethodName(), is(method.getTestMethod().getMethodName())); - assertThat(listener.status, is(SUCCESS)); - assertThat(listener.msg, is("[JIRA-123]")); - } - - @Test - @DisplayName("Check ITestResult.SUCCESS_PERCENTAGE_FAILURE if Details EXP_FIX Status with issues") - void unitTest_20180922034704() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - IInvokedMethod method = getMockIInvokedMethod(); - listener.processTestMethodResult(method, getMockITestResult(ITestResult.SUCCESS_PERCENTAGE_FAILURE), - getDetails(EXP_FIX, "JIRA-123")); - assertThat(listener.method.getMethodName(), is(method.getTestMethod().getMethodName())); - assertThat(listener.status, is(EXP_FIX)); - assertThat(listener.msg, is("[JIRA-123]")); - } - - @Test - @DisplayName("Check ITestResult.FAILURE if Details EXP_FIX Status with issues") - void unitTest_20180922034924() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - IInvokedMethod method = getMockIInvokedMethod(); - listener.processTestMethodResult(method, getMockITestResult(ITestResult.FAILURE), getDetails(EXP_FIX, "JIRA-123")); - assertThat(listener.method.getMethodName(), is(method.getTestMethod().getMethodName())); - assertThat(listener.status, is(EXP_FIX)); - assertThat(listener.msg, is("[JIRA-123]")); - } - - @Test - @DisplayName("Check ITestResult.FAILURE if Details CORRUPTED Status with issues") - void unitTest_20180922035053() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - IInvokedMethod method = getMockIInvokedMethod(); - listener.processTestMethodResult(method, getMockITestResult(ITestResult.FAILURE), getDetails(CORRUPTED, "JIRA-123")); - assertThat(listener.method.getMethodName(), is(method.getTestMethod().getMethodName())); - assertThat(listener.status, is(CORRUPTED)); - assertThat(listener.msg, is("[JIRA-123]")); - } - - @Test - @DisplayName("Check ITestResult.FAILURE if Details EXP_IMPL Status with issues") - void unitTest_20180922035146() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - IInvokedMethod method = getMockIInvokedMethod(); - listener.processTestMethodResult(method, getMockITestResult(ITestResult.FAILURE), getDetails(EXP_IMPL, "JIRA-123")); - assertThat(listener.method.getMethodName(), is(method.getTestMethod().getMethodName())); - assertThat(listener.status, is(EXP_IMPL)); - assertThat(listener.msg, is("[JIRA-123]")); - } - - @Test - @DisplayName("Check ITestResult.FAILURE if Details BLOCKED Status with issues") - void unitTest_20180922035208() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - IInvokedMethod method = getMockIInvokedMethod(); - listener.processTestMethodResult(method, getMockITestResult(ITestResult.FAILURE), getDetails(BLOCKED, "JIRA-123")); - assertThat(listener.method.getMethodName(), is(method.getTestMethod().getMethodName())); - assertThat(listener.status, is(BLOCKED)); - assertThat(listener.msg, is("[JIRA-123]")); - } - - @Test - @DisplayName("Check ITestResult.FAILURE if Details FIXED Status with issues") - void unitTest_20180922035238() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - IInvokedMethod method = getMockIInvokedMethod(); - listener.processTestMethodResult(method, getMockITestResult(ITestResult.FAILURE), getDetails(FIXED, "JIRA-123")); - assertThat(listener.method.getMethodName(), is(method.getTestMethod().getMethodName())); - assertThat(listener.status, is(FAILED)); - assertThat(listener.msg, is("[JIRA-123]")); - } - - @Test - @DisplayName("Check ITestResult.FAILURE if Details IMPLEMENTED Status with issues") - void unitTest_20180922035331() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - IInvokedMethod method = getMockIInvokedMethod(); - listener.processTestMethodResult(method, getMockITestResult(ITestResult.FAILURE), getDetails(IMPLEMENTED, "JIRA-123")); - assertThat(listener.method.getMethodName(), is(method.getTestMethod().getMethodName())); - assertThat(listener.status, is(FAILED)); - assertThat(listener.msg, is("[JIRA-123]")); - } - - @Test - @DisplayName("Check ITestResult.FAILURE if Details UNTESTED Status with issues") - void unitTest_20180922035403() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - IInvokedMethod method = getMockIInvokedMethod(); - listener.processTestMethodResult(method, getMockITestResult(ITestResult.FAILURE), getDetails(UNTESTED, "JIRA-123")); - assertThat(listener.method.getMethodName(), is(method.getTestMethod().getMethodName())); - assertThat(listener.status, is(FAILED)); - assertThat(listener.msg, is("[JIRA-123]")); - } - - @Test - @DisplayName("Check ITestResult.FAILURE if Details SUCCESS Status with issues") - void unitTest_20180922035419() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - IInvokedMethod method = getMockIInvokedMethod(); - listener.processTestMethodResult(method, getMockITestResult(ITestResult.FAILURE), getDetails(SUCCESS, "JIRA-123")); - assertThat(listener.method.getMethodName(), is(method.getTestMethod().getMethodName())); - assertThat(listener.status, is(FAILED)); - assertThat(listener.msg, is("[JIRA-123]")); - } - - @Test - @DisplayName("Check ITestResult.FAILURE if Details SKIP Status with issues") - void unitTest_20180922035435() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - IInvokedMethod method = getMockIInvokedMethod(); - listener.processTestMethodResult(method, getMockITestResult(ITestResult.FAILURE), getDetails(SKIP, "JIRA-123")); - assertThat(listener.method.getMethodName(), is(method.getTestMethod().getMethodName())); - assertThat(listener.status, is(FAILED)); - assertThat(listener.msg, is("[JIRA-123]")); - } - - @Test - @DisplayName("Check ITestResult.FAILURE if Details FAILED Status with issues") - void unitTest_20180922035529() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - IInvokedMethod method = getMockIInvokedMethod(); - listener.processTestMethodResult(method, getMockITestResult(ITestResult.FAILURE), getDetails(FAILED, "JIRA-123")); - assertThat(listener.method.getMethodName(), is(method.getTestMethod().getMethodName())); - assertThat(listener.status, is(FAILED)); - assertThat(listener.msg, is("[JIRA-123]")); - } - - @Test - @DisplayName("Check ITestResult.SKIP if Details EXP_IMPL Status with issues") - void unitTest_20180922035630() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - IInvokedMethod method = getMockIInvokedMethod(); - listener.processTestMethodResult(method, getMockITestResult(ITestResult.SKIP), getDetails(EXP_IMPL, "JIRA-123")); - assertThat(listener.method.getMethodName(), is(method.getTestMethod().getMethodName())); - assertThat(listener.status, is(SKIP)); - assertThat(listener.msg, is("[JIRA-123]")); - } - - @Test - @DisplayName("Check ITestResult.SKIP if Details EXP_FIX Status with issues") - void unitTest_20180922035830() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - IInvokedMethod method = getMockIInvokedMethod(); - listener.processTestMethodResult(method, getMockITestResult(ITestResult.SKIP), getDetails(EXP_FIX, "JIRA-123")); - assertThat(listener.method.getMethodName(), is(method.getTestMethod().getMethodName())); - assertThat(listener.status, is(SKIP)); - assertThat(listener.msg, is("[JIRA-123]")); - } - - @Test - @DisplayName("Check ITestResult.SKIP if Details BLOCKED Status with issues") - void unitTest_20180922035902() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - IInvokedMethod method = getMockIInvokedMethod(); - listener.processTestMethodResult(method, getMockITestResult(ITestResult.SKIP), getDetails(BLOCKED, "JIRA-123")); - assertThat(listener.method.getMethodName(), is(method.getTestMethod().getMethodName())); - assertThat(listener.status, is(SKIP)); - assertThat(listener.msg, is("[JIRA-123]")); - } - - @Test - @DisplayName("Check ITestResult.SKIP if Details CORRUPTED Status with issues") - void unitTest_20180922035917() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - IInvokedMethod method = getMockIInvokedMethod(); - listener.processTestMethodResult(method, getMockITestResult(ITestResult.SKIP), getDetails(CORRUPTED, "JIRA-123")); - assertThat(listener.method.getMethodName(), is(method.getTestMethod().getMethodName())); - assertThat(listener.status, is(SKIP)); - assertThat(listener.msg, is("[JIRA-123]")); - } - - @Test - @DisplayName("Check ITestResult.SKIP if Details FIXED Status with issues") - void unitTest_20180922035933() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - IInvokedMethod method = getMockIInvokedMethod(); - listener.processTestMethodResult(method, getMockITestResult(ITestResult.SKIP), getDetails(FIXED, "JIRA-123")); - assertThat(listener.method.getMethodName(), is(method.getTestMethod().getMethodName())); - assertThat(listener.status, is(SKIP)); - assertThat(listener.msg, is("[JIRA-123]")); - } - - @Test - @DisplayName("Check ITestResult.SKIP if Details IMPLEMENTED Status with issues") - void unitTest_20180922035950() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - IInvokedMethod method = getMockIInvokedMethod(); - listener.processTestMethodResult(method, getMockITestResult(ITestResult.SKIP), getDetails(IMPLEMENTED, "JIRA-123")); - assertThat(listener.method.getMethodName(), is(method.getTestMethod().getMethodName())); - assertThat(listener.status, is(SKIP)); - assertThat(listener.msg, is("[JIRA-123]")); - } - - @Test - @DisplayName("Check ITestResult.SKIP if Details UNTESTED Status with issues") - void unitTest_20180922040014() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - IInvokedMethod method = getMockIInvokedMethod(); - listener.processTestMethodResult(method, getMockITestResult(ITestResult.SKIP), getDetails(UNTESTED, "JIRA-123")); - assertThat(listener.method.getMethodName(), is(method.getTestMethod().getMethodName())); - assertThat(listener.status, is(SKIP)); - assertThat(listener.msg, is("[JIRA-123]")); - } - - @Test - @DisplayName("Check ITestResult.SKIP if Details SUCCESS Status with issues") - void unitTest_20180922040029() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - IInvokedMethod method = getMockIInvokedMethod(); - listener.processTestMethodResult(method, getMockITestResult(ITestResult.SKIP), getDetails(SUCCESS, "JIRA-123")); - assertThat(listener.method.getMethodName(), is(method.getTestMethod().getMethodName())); - assertThat(listener.status, is(SKIP)); - assertThat(listener.msg, is("[JIRA-123]")); - } - - @Test - @DisplayName("Check ITestResult.SKIP if Details SKIP Status with issues") - void unitTest_20180922040042() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - IInvokedMethod method = getMockIInvokedMethod(); - listener.processTestMethodResult(method, getMockITestResult(ITestResult.SKIP), getDetails(SKIP, "JIRA-123")); - assertThat(listener.method.getMethodName(), is(method.getTestMethod().getMethodName())); - assertThat(listener.status, is(SKIP)); - assertThat(listener.msg, is("[JIRA-123]")); - } - - @Test - @DisplayName("Check ITestResult.SKIP if Details FAILED Status with issues") - void unitTest_20180922040055() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - IInvokedMethod method = getMockIInvokedMethod(); - listener.processTestMethodResult(method, getMockITestResult(ITestResult.SKIP), getDetails(FAILED, "JIRA-123")); - assertThat(listener.method.getMethodName(), is(method.getTestMethod().getMethodName())); - assertThat(listener.status, is(SKIP)); - assertThat(listener.msg, is("[JIRA-123]")); - } - - @Test - @DisplayName("Check ITestResult.CREATED is not unprocessed") - void unitTest_20180922040117() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - IInvokedMethod method = getMockIInvokedMethod(); - int expErrors = Buggy.getBuggyErrors() + 1; - listener.processTestMethodResult(method, getMockITestResult(ITestResult.CREATED), getDetails(SUCCESS)); - assertThat(expErrors, is(Buggy.getBuggyErrors())); - assertThat(listener.method, is(nullValue())); - assertThat(listener.status, is(nullValue())); - assertThat(listener.msg, is(nullValue())); - } - - @Test - @DisplayName("Check ITestResult.STARTED is not unprocessed") - void unitTest_20180922040351() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - IInvokedMethod method = getMockIInvokedMethod(); - int expErrors = Buggy.getBuggyErrors() + 1; - listener.processTestMethodResult(method, getMockITestResult(ITestResult.STARTED), getDetails(SUCCESS)); - assertThat(expErrors, is(Buggy.getBuggyErrors())); - assertThat(listener.method, is(nullValue())); - assertThat(listener.status, is(nullValue())); - assertThat(listener.msg, is(nullValue())); - } - - } - - @Nested() - @DisplayName("processConfigurationMethodResult() tests") - class ProcessConfigurationMethodResultTests extends BaseUnitTest { - - @Test - @DisplayName("Check ITestResult.SUCCESS") - void unitTest_20180922043219() { - BuggyExecutionListener listener = new BuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - IInvokedMethod method = getMockIInvokedMethod(false); - int expErrors = Buggy.getBuggyErrors(); - listener.processConfigurationMethodResult(method, getMockITestResult(ITestResult.SUCCESS)); - assertThat(Buggy.getBuggyErrors(), is(expErrors)); - } - - @Test - @DisplayName("Check ITestResult.SKIP") - void unitTest_20180922061334() { - BuggyExecutionListener listener = new BuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - IInvokedMethod method = getMockIInvokedMethod(false); - int expErrors = Buggy.getBuggyErrors(); - listener.processConfigurationMethodResult(method, getMockITestResult(ITestResult.SKIP)); - assertThat(Buggy.getBuggyErrors(), is(expErrors)); - } - - @Test - @DisplayName("Check ITestResult.FAILURE") - void unitTest_20180922061357() { - BuggyExecutionListener listener = new BuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - IInvokedMethod method = getMockIInvokedMethod(false); - int expErrors = Buggy.getBuggyErrors(); - ITestResult result = getMockITestResult(ITestResult.FAILURE); - when(result.getThrowable()).thenReturn(new Exception()); - listener.processConfigurationMethodResult(method, result); - assertThat(Buggy.getBuggyErrors(), is(expErrors)); - } - - @Test - @DisplayName("Check ITestResult.SUCCESS_PERCENTAGE_FAILURE") - void unitTest_20180922061412() { - BuggyExecutionListener listener = new BuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - IInvokedMethod method = getMockIInvokedMethod(false); - int expErrors = Buggy.getBuggyErrors(); - ITestResult result = getMockITestResult(ITestResult.SUCCESS_PERCENTAGE_FAILURE); - when(result.getThrowable()).thenReturn(new Exception()); - listener.processConfigurationMethodResult(method, result); - assertThat(Buggy.getBuggyErrors(), is(expErrors)); - } - - @Test - @DisplayName("Check ITestResult.CREATED") - void unitTest_20180922061437() { - BuggyExecutionListener listener = new BuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - IInvokedMethod method = getMockIInvokedMethod(false); - int expErrors = Buggy.getBuggyErrors() + 1; - listener.processConfigurationMethodResult(method, getMockITestResult(ITestResult.CREATED)); - assertThat(Buggy.getBuggyErrors(), is(expErrors)); - } - - @Test - @DisplayName("Check ITestResult.STARTED") - void unitTest_20180922061516() { - BuggyExecutionListener listener = new BuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); - IInvokedMethod method = getMockIInvokedMethod(false); - int expErrors = Buggy.getBuggyErrors() + 1; - listener.processConfigurationMethodResult(method, getMockITestResult(ITestResult.STARTED)); - assertThat(Buggy.getBuggyErrors(), is(expErrors)); - } - - } - - @Nested() - @DisplayName("disableTestsByStatus() tests") - class DisableTestsByStatusTests extends BaseUnitTest { - - @Test - @DisplayName("Ignore disabling the test, if method is not contains the @Details annotation") - void unitTest_20180922062020() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(); - ITestNGMethod method = getMockITestNGMethod(TestNGTestClassWithSuite.class, "iTestResultMethodWithoutDetails"); - List allMethods = new ArrayList<>(); - allMethods.add(method); - ISuite suite = mock(ISuite.class); - when(suite.getAllMethods()).thenReturn(allMethods); - int expWarn = Buggy.getBuggyWarns() + 1; - listener.disableTestsByStatus(suite); - assertThat(listener.method, is(nullValue())); - assertThat(listener.status, is(nullValue())); - assertThat(listener.msg, is(nullValue())); - assertThat(Buggy.getBuggyWarns(), is(expWarn)); - } - - @Test - @DisplayName("Ignore disabling the test, if method has @Details and invocation count <= 0") - void unitTest_20180922063213() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(getDetails(SUCCESS)); - ITestNGMethod method = getMockITestNGMethod(TestNGTestClassWithSuite.class, "iTestResultMethodWithDetails"); - when(method.getInvocationCount()).thenReturn(0); - List allMethods = new ArrayList<>(); - allMethods.add(method); - ISuite suite = mock(ISuite.class); - when(suite.getAllMethods()).thenReturn(allMethods); - int expWarn = Buggy.getBuggyWarns(); - listener.disableTestsByStatus(suite); - assertThat(listener.method, is(nullValue())); - assertThat(listener.status, is(nullValue())); - assertThat(listener.msg, is(nullValue())); - assertThat(Buggy.getBuggyWarns(), is(expWarn)); - } - - @Test - @DisplayName("Ignore disabling the test, if received configuration method") - void unitTest_20180922063717() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(getDetails(SUCCESS)); - ITestNGMethod method = getMockITestNGMethod(TestNGTestClassWithSuite.class, "iTestResultMethodWithoutDetails"); - when(method.isTest()).thenReturn(false); - List allMethods = new ArrayList<>(); - allMethods.add(method); - ISuite suite = mock(ISuite.class); - when(suite.getAllMethods()).thenReturn(allMethods); - int expWarn = Buggy.getBuggyWarns(); - listener.disableTestsByStatus(suite); - assertThat(listener.method, is(nullValue())); - assertThat(listener.status, is(nullValue())); - assertThat(listener.msg, is(nullValue())); - assertThat(Buggy.getBuggyWarns(), is(expWarn)); - } - - @Test - @DisplayName("Ignore disabling the test, if expected Status.SUCCESS") - void unitTest_20180922063942() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(getDetails(SUCCESS)); - ITestNGMethod method = getMockITestNGMethod(TestNGTestClassWithSuite.class, "iTestResultMethodWithoutDetails"); - when(method.isTest()).thenReturn(true); - List allMethods = new ArrayList<>(); - allMethods.add(method); - ISuite suite = mock(ISuite.class); - when(suite.getAllMethods()).thenReturn(allMethods); - int expWarn = Buggy.getBuggyWarns(); - listener.disableTestsByStatus(suite); - assertThat(listener.method, is(nullValue())); - assertThat(listener.status, is(nullValue())); - assertThat(listener.msg, is(nullValue())); - assertThat(Buggy.getBuggyWarns(), is(expWarn)); - } - - @Test - @DisplayName("Ignore disabling the test, if expected Status.FIXED") - void unitTest_20180922065558() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(getDetails(FIXED)); - ITestNGMethod method = getMockITestNGMethod(TestNGTestClassWithSuite.class, "iTestResultMethodWithoutDetails"); - when(method.isTest()).thenReturn(true); - List allMethods = new ArrayList<>(); - allMethods.add(method); - ISuite suite = mock(ISuite.class); - when(suite.getAllMethods()).thenReturn(allMethods); - int expWarn = Buggy.getBuggyWarns(); - listener.disableTestsByStatus(suite); - assertThat(listener.method, is(nullValue())); - assertThat(listener.status, is(nullValue())); - assertThat(listener.msg, is(nullValue())); - assertThat(Buggy.getBuggyWarns(), is(expWarn)); - } - - @Test - @DisplayName("Ignore disabling the test, if expected Status.IMPLEMENTED") - void unitTest_20180922070145() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(getDetails(IMPLEMENTED)); - ITestNGMethod method = getMockITestNGMethod(TestNGTestClassWithSuite.class, "iTestResultMethodWithoutDetails"); - when(method.isTest()).thenReturn(true); - List allMethods = new ArrayList<>(); - allMethods.add(method); - ISuite suite = mock(ISuite.class); - when(suite.getAllMethods()).thenReturn(allMethods); - int expWarn = Buggy.getBuggyWarns(); - listener.disableTestsByStatus(suite); - assertThat(listener.method, is(nullValue())); - assertThat(listener.status, is(nullValue())); - assertThat(listener.msg, is(nullValue())); - assertThat(Buggy.getBuggyWarns(), is(expWarn)); - } - - @Test - @DisplayName("Ignore disabling the test, if expected Status.UNTESTED") - void unitTest_20180922070204() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(getDetails(UNTESTED)); - ITestNGMethod method = getMockITestNGMethod(TestNGTestClassWithSuite.class, "iTestResultMethodWithoutDetails"); - when(method.isTest()).thenReturn(true); - List allMethods = new ArrayList<>(); - allMethods.add(method); - ISuite suite = mock(ISuite.class); - when(suite.getAllMethods()).thenReturn(allMethods); - int expWarn = Buggy.getBuggyWarns(); - listener.disableTestsByStatus(suite); - assertThat(listener.method, is(nullValue())); - assertThat(listener.status, is(nullValue())); - assertThat(listener.msg, is(nullValue())); - assertThat(Buggy.getBuggyWarns(), is(expWarn)); - } - - @Test - @DisplayName("Ignore disabling the test, if expected Status.SKIP") - void unitTest_20180922070222() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(getDetails(SKIP)); - ITestNGMethod method = getMockITestNGMethod(TestNGTestClassWithSuite.class, "iTestResultMethodWithoutDetails"); - when(method.isTest()).thenReturn(true); - List allMethods = new ArrayList<>(); - allMethods.add(method); - ISuite suite = mock(ISuite.class); - when(suite.getAllMethods()).thenReturn(allMethods); - int expWarn = Buggy.getBuggyWarns(); - listener.disableTestsByStatus(suite); - assertThat(listener.method, is(nullValue())); - assertThat(listener.status, is(nullValue())); - assertThat(listener.msg, is(nullValue())); - assertThat(Buggy.getBuggyWarns(), is(expWarn)); - } - - @Test - @DisplayName("Ignore disabling the test, if expected Status.FAILED") - void unitTest_20180922070246() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(getDetails(FAILED)); - ITestNGMethod method = getMockITestNGMethod(TestNGTestClassWithSuite.class, "iTestResultMethodWithoutDetails"); - when(method.isTest()).thenReturn(true); - List allMethods = new ArrayList<>(); - allMethods.add(method); - ISuite suite = mock(ISuite.class); - when(suite.getAllMethods()).thenReturn(allMethods); - int expWarn = Buggy.getBuggyWarns(); - listener.disableTestsByStatus(suite); - assertThat(listener.method, is(nullValue())); - assertThat(listener.status, is(nullValue())); - assertThat(listener.msg, is(nullValue())); - assertThat(Buggy.getBuggyWarns(), is(expWarn)); - } - - @Test - @DisplayName("Check disabling the test, if expected Status.EXP_FIX") - void unitTest_20180922070306() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(getDetails(EXP_FIX)); - ITestNGMethod method = getMockITestNGMethod(TestNGTestClassWithSuite.class, "iTestResultMethodWithoutDetails"); - when(method.isTest()).thenReturn(true); - List allMethods = new ArrayList<>(); - allMethods.add(method); - ISuite suite = mock(ISuite.class); - when(suite.getAllMethods()).thenReturn(allMethods); - int expWarn = Buggy.getBuggyWarns(); - listener.disableTestsByStatus(suite); - assertThat(listener.method, not(nullValue())); - assertThat(listener.method.getInvocationCount(), not(0)); - assertThat(listener.status, is(EXP_FIX)); - assertThat(listener.msg, is("forced test run disabled")); - assertThat(Buggy.getBuggyWarns(), is(expWarn)); - } - - @Test - @DisplayName("Check disabling the test, if expected Status.EXP_IMPL") - void unitTest_20180922070547() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(getDetails(EXP_IMPL)); - ITestNGMethod method = getMockITestNGMethod(TestNGTestClassWithSuite.class, "iTestResultMethodWithoutDetails"); - when(method.isTest()).thenReturn(true); - List allMethods = new ArrayList<>(); - allMethods.add(method); - ISuite suite = mock(ISuite.class); - when(suite.getAllMethods()).thenReturn(allMethods); - int expWarn = Buggy.getBuggyWarns(); - listener.disableTestsByStatus(suite); - assertThat(listener.method, not(nullValue())); - assertThat(listener.method.getInvocationCount(), not(0)); - assertThat(listener.status, is(EXP_IMPL)); - assertThat(listener.msg, is("forced test run disabled")); - assertThat(Buggy.getBuggyWarns(), is(expWarn)); - } - - @Test - @DisplayName("Check disabling the test, if expected Status.BLOCKED") - void unitTest_20180922070607() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(getDetails(BLOCKED)); - ITestNGMethod method = getMockITestNGMethod(TestNGTestClassWithSuite.class, "iTestResultMethodWithoutDetails"); - when(method.isTest()).thenReturn(true); - List allMethods = new ArrayList<>(); - allMethods.add(method); - ISuite suite = mock(ISuite.class); - when(suite.getAllMethods()).thenReturn(allMethods); - int expWarn = Buggy.getBuggyWarns(); - listener.disableTestsByStatus(suite); - assertThat(listener.method, not(nullValue())); - assertThat(listener.method.getInvocationCount(), not(0)); - assertThat(listener.status, is(BLOCKED)); - assertThat(listener.msg, is("forced test run disabled")); - assertThat(Buggy.getBuggyWarns(), is(expWarn)); - } - - @Test - @DisplayName("Check disabling the test, if expected Status.CORRUPTED") - void unitTest_20180922070623() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(getDetails(CORRUPTED)); - ITestNGMethod method = getMockITestNGMethod(TestNGTestClassWithSuite.class, "iTestResultMethodWithoutDetails"); - when(method.isTest()).thenReturn(true); - List allMethods = new ArrayList<>(); - allMethods.add(method); - ISuite suite = mock(ISuite.class); - when(suite.getAllMethods()).thenReturn(allMethods); - int expWarn = Buggy.getBuggyWarns(); - listener.disableTestsByStatus(suite); - assertThat(listener.method, not(nullValue())); - assertThat(listener.method.getInvocationCount(), not(0)); - assertThat(listener.status, is(CORRUPTED)); - assertThat(listener.msg, is("forced test run disabled")); - assertThat(Buggy.getBuggyWarns(), is(expWarn)); - } - - } - - @Nested() - @DisplayName("disableTestsByType() tests") - class DisableTestsByTypeTests extends BaseUnitTest { - - @Test - @DisplayName("Ignore disabling the test, if @Details is not present") - void unitTest_20180922073418() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(); - ITestNGMethod method = getMockITestNGMethod(TestNGTestClassWithSuite.class, "iTestResultMethodWithoutDetails"); - when(method.isTest()).thenReturn(false); - List allMethods = new ArrayList<>(); - allMethods.add(method); - ISuite suite = mock(ISuite.class); - when(suite.getAllMethods()).thenReturn(allMethods); - int expWarn = Buggy.getBuggyWarns(); - listener.disableTestsByType(suite); - assertThat(listener.method, is(nullValue())); - assertThat(listener.status, is(nullValue())); - assertThat(listener.msg, is(nullValue())); - assertThat(Buggy.getBuggyWarns(), is(expWarn)); - } - - @Test - @DisplayName("Ignore disabling the test, if config Type.isIncludeOrEquals(testType)") - void unitTest_20180922081155() { - Type configType = Buggy.getPrimaryConfig().getType(); - try { - Buggy.getPrimaryConfig().setType(MODULE); - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(getDetails(SMOKE)); - ITestNGMethod method = getMockITestNGMethod(TestNGTestClassWithSuite.class, "iTestResultMethodWithoutDetails"); - when(method.isTest()).thenReturn(false); - List allMethods = new ArrayList<>(); - allMethods.add(method); - ISuite suite = mock(ISuite.class); - when(suite.getAllMethods()).thenReturn(allMethods); - int expWarn = Buggy.getBuggyWarns(); - listener.disableTestsByType(suite); - assertThat(listener.method, is(nullValue())); - assertThat(listener.status, is(nullValue())); - assertThat(listener.msg, is(nullValue())); - assertThat(Buggy.getBuggyWarns(), is(expWarn)); - } finally { - Buggy.getPrimaryConfig().setType(configType); - } - } - - @Test - @DisplayName("Check disabling the test, if config !Type.isIncludeOrEquals(testType)") - void unitTest_20180922081522() { - Type configType = Buggy.getPrimaryConfig().getType(); - try { - Buggy.getPrimaryConfig().setType(MODULE); - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(getDetails(SYSTEM)); - ITestNGMethod method = getMockITestNGMethod(TestNGTestClassWithSuite.class, "iTestResultMethodWithoutDetails"); - when(method.isTest()).thenReturn(false); - List allMethods = new ArrayList<>(); - allMethods.add(method); - ISuite suite = mock(ISuite.class); - when(suite.getAllMethods()).thenReturn(allMethods); - int expWarn = Buggy.getBuggyWarns(); - listener.disableTestsByType(suite); - assertThat(listener.method, not(nullValue())); - assertThat(listener.status, is(SKIP)); - assertThat(listener.msg, is("SYSTEM test type")); - assertThat(Buggy.getBuggyWarns(), is(expWarn)); - } finally { - Buggy.getPrimaryConfig().setType(configType); - } - } - - } - - @Nested() - @DisplayName("Steps tests") - class StepsTests extends BaseUnitTest { - - @Test - @DisplayName("Check getSteps() if setSteps(List)") - void unitTest_20181018171824() { - List steps = new ArrayList<>(); - steps.add("s1"); - BuggyExecutionListener.setSteps(steps); - assertThat(BuggyExecutionListener.getSteps(), contains("s1")); - assertThat(TEST_LOGGER.takeLoggedMessages(), is(empty())); - } - - @Test - @DisplayName("Check getSteps() if setSteps(null)") - void unitTest_20181018172255() { - BuggyExecutionListener.setSteps(null); - assertThat(BuggyExecutionListener.getSteps(), is(empty())); - assertThat(TEST_LOGGER.takeLoggedMessages(), is(empty())); - } - - } - - @Nested() - @DisplayName("copyTestMethodLogFile() tests") - class CopyTestMethodLogFileTests extends BaseUnitTest { - - @Test - @DisplayName("Check copied log files if ITestResult.SUCCESS") - void unitTest_20181018183643() throws Exception { - IInvokedMethod method = getMockIInvokedMethod(); - ITestResult iTestResult = mock(ITestResult.class); - when(iTestResult.getStatus()).thenReturn(ITestResult.SUCCESS); - when(method.getTestResult()).thenReturn(iTestResult); - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(getDetails(SUCCESS)); - listener.copyTestMethodLogFile(method); - assertThat(listener.sourceFile, is(nullValue())); - assertThat(listener.targetFile, is(nullValue())); - assertThat(TEST_LOGGER.takeLoggedMessages(), is(empty())); - } - - @Test - @DisplayName("Check copied log files if ITestResult.FAILURE & details == null") - void unitTest_20181018191517() throws Exception { - IInvokedMethod method = getMockIInvokedMethod(); - ITestResult iTestResult = mock(ITestResult.class); - when(iTestResult.getStatus()).thenReturn(ITestResult.FAILURE); - when(method.getTestResult()).thenReturn(iTestResult); - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(); - listener.copyTestMethodLogFile(method); - assertThat(listener.sourceFile, is(new File(WASTE, "/tests/iTestResultMethodWithDetails.log"))); - assertThat(listener.targetFile, is(new File(WASTE, "/errors/new/iTestResultMethodWithDetails.log"))); - assertThat(TEST_LOGGER.takeLoggedMessages(), is(empty())); - } - - @Test - @DisplayName("Check copied log files if ITestResult.SUCCESS_PERCENTAGE_FAILURE & details == null") - void unitTest_20181018205528() throws Exception { - IInvokedMethod method = getMockIInvokedMethod(); - ITestResult iTestResult = mock(ITestResult.class); - when(iTestResult.getStatus()).thenReturn(ITestResult.SUCCESS_PERCENTAGE_FAILURE); - when(method.getTestResult()).thenReturn(iTestResult); - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(); - listener.copyTestMethodLogFile(method); - assertThat(listener.sourceFile, is(new File(WASTE, "/tests/iTestResultMethodWithDetails.log"))); - assertThat(listener.targetFile, is(new File(WASTE, "/errors/new/iTestResultMethodWithDetails.log"))); - } - - @Test - @DisplayName("Check copied log files if ITestResult.SUCCESS & details == null") - void unitTest_20181018205529() throws Exception { - IInvokedMethod method = getMockIInvokedMethod(); - ITestResult iTestResult = mock(ITestResult.class); - when(iTestResult.getStatus()).thenReturn(ITestResult.SUCCESS); - when(method.getTestResult()).thenReturn(iTestResult); - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(); - listener.copyTestMethodLogFile(method); - assertThat(listener.sourceFile, is(nullValue())); - assertThat(listener.targetFile, is(nullValue())); - } - - @Test - @DisplayName("Check copied log files if ITestResult.SUCCESS & Status.EXP_FIX") - void unitTest_20181018211903() throws Exception { - IInvokedMethod method = getMockIInvokedMethod(); - ITestResult iTestResult = mock(ITestResult.class); - when(iTestResult.getStatus()).thenReturn(ITestResult.SUCCESS); - when(method.getTestResult()).thenReturn(iTestResult); - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(getDetails(EXP_FIX)); - listener.copyTestMethodLogFile(method); - assertThat(listener.sourceFile, is(new File(WASTE, "/tests/iTestResultMethodWithDetails.log"))); - assertThat(listener.targetFile, is(new File(WASTE, "/fixed/iTestResultMethodWithDetails.log"))); - assertThat(TEST_LOGGER.takeLoggedMessages(), is(empty())); - } - - @Test - @DisplayName("Check copied log files if ITestResult.SUCCESS & Status.BLOCKED") - void unitTest_20181018211949() throws Exception { - IInvokedMethod method = getMockIInvokedMethod(); - ITestResult iTestResult = mock(ITestResult.class); - when(iTestResult.getStatus()).thenReturn(ITestResult.SUCCESS); - when(method.getTestResult()).thenReturn(iTestResult); - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(getDetails(BLOCKED)); - listener.copyTestMethodLogFile(method); - assertThat(listener.sourceFile, is(new File(WASTE, "/tests/iTestResultMethodWithDetails.log"))); - assertThat(listener.targetFile, is(new File(WASTE, "/fixed/iTestResultMethodWithDetails.log"))); - } - - @Test - @DisplayName("Check copied log files if ITestResult.SUCCESS & Status.EXP_IMPL") - void unitTest_20181018212222() throws Exception { - IInvokedMethod method = getMockIInvokedMethod(); - ITestResult iTestResult = mock(ITestResult.class); - when(iTestResult.getStatus()).thenReturn(ITestResult.SUCCESS); - when(method.getTestResult()).thenReturn(iTestResult); - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(getDetails(EXP_IMPL)); - listener.copyTestMethodLogFile(method); - assertThat(listener.sourceFile, is(new File(WASTE, "/tests/iTestResultMethodWithDetails.log"))); - assertThat(listener.targetFile, is(new File(WASTE, "/implemented/iTestResultMethodWithDetails.log"))); - } - - @Test - @DisplayName("Check copied log files if ITestResult.FAILURE & Status.EXP_FIX") - void unitTest_20181018214458() throws Exception { - IInvokedMethod method = getMockIInvokedMethod(); - ITestResult iTestResult = mock(ITestResult.class); - when(iTestResult.getStatus()).thenReturn(ITestResult.FAILURE); - when(method.getTestResult()).thenReturn(iTestResult); - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(getDetails(EXP_FIX)); - listener.copyTestMethodLogFile(method); - assertThat(listener.sourceFile, is(new File(WASTE, "/tests/iTestResultMethodWithDetails.log"))); - assertThat(listener.targetFile, is(new File(WASTE, "/errors/exp_fix/iTestResultMethodWithDetails.log"))); - } - - @Test - @DisplayName("Check copied log files if ITestResult.FAILURE & Status.EXP_IMPL") - void unitTest_20181018214554() throws Exception { - IInvokedMethod method = getMockIInvokedMethod(); - ITestResult iTestResult = mock(ITestResult.class); - when(iTestResult.getStatus()).thenReturn(ITestResult.FAILURE); - when(method.getTestResult()).thenReturn(iTestResult); - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(getDetails(EXP_IMPL)); - listener.copyTestMethodLogFile(method); - assertThat(listener.sourceFile, is(new File(WASTE, "/tests/iTestResultMethodWithDetails.log"))); - assertThat(listener.targetFile, is(new File(WASTE, "/errors/exp_impl/iTestResultMethodWithDetails.log"))); - } - - @Test - @DisplayName("Check copied log files if ITestResult.FAILURE & Status.BLOCKED") - void unitTest_20181018214613() throws Exception { - IInvokedMethod method = getMockIInvokedMethod(); - ITestResult iTestResult = mock(ITestResult.class); - when(iTestResult.getStatus()).thenReturn(ITestResult.FAILURE); - when(method.getTestResult()).thenReturn(iTestResult); - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(getDetails(BLOCKED)); - listener.copyTestMethodLogFile(method); - assertThat(listener.sourceFile, is(new File(WASTE, "/tests/iTestResultMethodWithDetails.log"))); - assertThat(listener.targetFile, is(new File(WASTE, "/errors/blocked/iTestResultMethodWithDetails.log"))); - } - - @Test - @DisplayName("Check copied log files if ITestResult.FAILURE & Status.CORRUPTED") - void unitTest_20181018214633() throws Exception { - IInvokedMethod method = getMockIInvokedMethod(); - ITestResult iTestResult = mock(ITestResult.class); - when(iTestResult.getStatus()).thenReturn(ITestResult.FAILURE); - when(method.getTestResult()).thenReturn(iTestResult); - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(getDetails(CORRUPTED)); - listener.copyTestMethodLogFile(method); - assertThat(listener.sourceFile, is(new File(WASTE, "/tests/iTestResultMethodWithDetails.log"))); - assertThat(listener.targetFile, is(new File(WASTE, "/errors/corrupted/iTestResultMethodWithDetails.log"))); - } - - @Test - @DisplayName("Check copied log files if ITestResult.FAILURE & Status.FAILED") - void unitTest_20181018214735() throws Exception { - IInvokedMethod method = getMockIInvokedMethod(); - ITestResult iTestResult = mock(ITestResult.class); - when(iTestResult.getStatus()).thenReturn(ITestResult.FAILURE); - when(method.getTestResult()).thenReturn(iTestResult); - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(getDetails(FAILED)); - listener.copyTestMethodLogFile(method); - assertThat(listener.sourceFile, is(new File(WASTE, "/tests/iTestResultMethodWithDetails.log"))); - assertThat(listener.targetFile, is(new File(WASTE, "/errors/new/iTestResultMethodWithDetails.log"))); - } - - @Test - @DisplayName("Check copied log files if ITestResult.FAILURE & Status.SKIP") - void unitTest_20181018214857() throws Exception { - IInvokedMethod method = getMockIInvokedMethod(); - ITestResult iTestResult = mock(ITestResult.class); - when(iTestResult.getStatus()).thenReturn(ITestResult.FAILURE); - when(method.getTestResult()).thenReturn(iTestResult); - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(getDetails(SKIP)); - listener.copyTestMethodLogFile(method); - assertThat(listener.sourceFile, is(new File(WASTE, "/tests/iTestResultMethodWithDetails.log"))); - assertThat(listener.targetFile, is(new File(WASTE, "/errors/new/iTestResultMethodWithDetails.log"))); - } - - @Test - @DisplayName("Check copied log files if ITestResult.FAILURE & Status.SUCCESS") - void unitTest_20181018214917() throws Exception { - IInvokedMethod method = getMockIInvokedMethod(); - ITestResult iTestResult = mock(ITestResult.class); - when(iTestResult.getStatus()).thenReturn(ITestResult.FAILURE); - when(method.getTestResult()).thenReturn(iTestResult); - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(getDetails(SUCCESS)); - listener.copyTestMethodLogFile(method); - assertThat(listener.sourceFile, is(new File(WASTE, "/tests/iTestResultMethodWithDetails.log"))); - assertThat(listener.targetFile, is(new File(WASTE, "/errors/new/iTestResultMethodWithDetails.log"))); - } - - @Test - @DisplayName("Check copied log files if ITestResult.FAILURE & Status.UNTESTED") - void unitTest_20181018215040() throws Exception { - IInvokedMethod method = getMockIInvokedMethod(); - ITestResult iTestResult = mock(ITestResult.class); - when(iTestResult.getStatus()).thenReturn(ITestResult.FAILURE); - when(method.getTestResult()).thenReturn(iTestResult); - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(getDetails(UNTESTED)); - listener.copyTestMethodLogFile(method); - assertThat(listener.sourceFile, is(new File(WASTE, "/tests/iTestResultMethodWithDetails.log"))); - assertThat(listener.targetFile, is(new File(WASTE, "/errors/new/iTestResultMethodWithDetails.log"))); - } - - @Test - @DisplayName("Check copied log files if ITestResult.FAILURE & Status.IMPLEMENTED") - void unitTest_20181018215101() throws Exception { - IInvokedMethod method = getMockIInvokedMethod(); - ITestResult iTestResult = mock(ITestResult.class); - when(iTestResult.getStatus()).thenReturn(ITestResult.FAILURE); - when(method.getTestResult()).thenReturn(iTestResult); - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(getDetails(IMPLEMENTED)); - listener.copyTestMethodLogFile(method); - assertThat(listener.sourceFile, is(new File(WASTE, "/tests/iTestResultMethodWithDetails.log"))); - assertThat(listener.targetFile, is(new File(WASTE, "/errors/new/iTestResultMethodWithDetails.log"))); - } - - @Test - @DisplayName("Check copied log files if ITestResult.FAILURE & Status.FIXED") - void unitTest_20181018215119() throws Exception { - IInvokedMethod method = getMockIInvokedMethod(); - ITestResult iTestResult = mock(ITestResult.class); - when(iTestResult.getStatus()).thenReturn(ITestResult.FAILURE); - when(method.getTestResult()).thenReturn(iTestResult); - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(getDetails(FIXED)); - listener.copyTestMethodLogFile(method); - assertThat(listener.sourceFile, is(new File(WASTE, "/tests/iTestResultMethodWithDetails.log"))); - assertThat(listener.targetFile, is(new File(WASTE, "/errors/new/iTestResultMethodWithDetails.log"))); - } - - @Test - @DisplayName("Check copied log files if ITestResult.SUCCESS_PERCENTAGE_FAILURE & Status.SUCCESS") - void unitTest_20181018215341() throws Exception { - IInvokedMethod method = getMockIInvokedMethod(); - ITestResult iTestResult = mock(ITestResult.class); - when(iTestResult.getStatus()).thenReturn(ITestResult.SUCCESS_PERCENTAGE_FAILURE); - when(method.getTestResult()).thenReturn(iTestResult); - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(getDetails(SUCCESS)); - listener.copyTestMethodLogFile(method); - assertThat(listener.sourceFile, is(new File(WASTE, "/tests/iTestResultMethodWithDetails.log"))); - assertThat(listener.targetFile, is(new File(WASTE, "/errors/new/iTestResultMethodWithDetails.log"))); - } - - @Test - @DisplayName("Check files if ITestResult.STARTED & Status.SUCCESS") - void unitTest_20181018215411() throws Exception { - IInvokedMethod method = getMockIInvokedMethod(); - ITestResult iTestResult = mock(ITestResult.class); - when(iTestResult.getStatus()).thenReturn(ITestResult.STARTED); - when(method.getTestResult()).thenReturn(iTestResult); - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(getDetails(SUCCESS)); - listener.copyTestMethodLogFile(method); - assertThat(listener.sourceFile, is(nullValue())); - assertThat(listener.targetFile, is(nullValue())); - } - - @Test - @DisplayName("Check files if ITestResult.SKIP & Status.SUCCESS") - void unitTest_20181018215433() throws Exception { - IInvokedMethod method = getMockIInvokedMethod(); - ITestResult iTestResult = mock(ITestResult.class); - when(iTestResult.getStatus()).thenReturn(ITestResult.SKIP); - when(method.getTestResult()).thenReturn(iTestResult); - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(getDetails(SUCCESS)); - listener.copyTestMethodLogFile(method); - assertThat(listener.sourceFile, is(nullValue())); - assertThat(listener.targetFile, is(nullValue())); - } - - @Test - @DisplayName("Check files if ITestResult.SUCCESS & Status.SUCCESS") - void unitTest_20181018215544() throws Exception { - IInvokedMethod method = getMockIInvokedMethod(); - ITestResult iTestResult = mock(ITestResult.class); - when(iTestResult.getStatus()).thenReturn(ITestResult.SUCCESS); - when(method.getTestResult()).thenReturn(iTestResult); - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(getDetails(SUCCESS)); - listener.copyTestMethodLogFile(method); - assertThat(listener.sourceFile, is(nullValue())); - assertThat(listener.targetFile, is(nullValue())); - } - - @Test - @DisplayName("Check files if ITestResult.CREATED & Status.SUCCESS") - void unitTest_20181018215622() throws Exception { - IInvokedMethod method = getMockIInvokedMethod(); - ITestResult iTestResult = mock(ITestResult.class); - when(iTestResult.getStatus()).thenReturn(ITestResult.CREATED); - when(method.getTestResult()).thenReturn(iTestResult); - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(getDetails(SUCCESS)); - listener.copyTestMethodLogFile(method); - assertThat(listener.sourceFile, is(nullValue())); - assertThat(listener.targetFile, is(nullValue())); - } - - } - - @Nested() - @DisplayName("resultLog() tests") - class ResultLogTest extends BaseUnitTest { - - private final Suite suite = new Suite() { - - @Override - public Class annotationType() { - return Suite.class; - } - - @Override - public Class component() { - return TestComponent.class; - } - - @Override - public Class service() { - return TestService.class; - } - - @Override - public Class interfaze() { - return TestInterface.class; - } - - @Override - public String task() { - return "TestTask"; - } - }; - - @Test - @DisplayName("Check logs when " + PRINT_SUITE + "=false " + PRINT_CAUSE + "=false " + PRINT_LOG + "=false") - void unitTest_20181019011816() { - BuggyExecutionListener listener = new BuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER) { - @Override - protected Suite getSuite(ITestNGMethod method) { - return suite; - } - }; - ITestNGMethod iTestNGMethod = getMockITestNGMethod(); - listener.resultLog(iTestNGMethod, Status.SUCCESS, "cause"); - assertThat(TEST_LOGGER.takeLoggedMessages(), contains( - "iTestResultMethodWithDetails - SUCCESS null", - "iTestResultMethodWithDetails............SUCCESS" - )); - } - - @Test - @DisplayName("Check logs when " + PRINT_SUITE + "=true " + PRINT_CAUSE + "=false " + PRINT_LOG + "=false") - void unitTest_20181019012936() { - Buggy.getPrimaryConfig().setPrintSuite(true); - Buggy.getPrimaryConfig().setPrintCause(false); - Buggy.getPrimaryConfig().setPrintLogFile(false); - BuggyExecutionListener listener = new BuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER) { - @Override - protected Suite getSuite(ITestNGMethod method) { - return suite; - } - }; - ITestNGMethod iTestNGMethod = getMockITestNGMethod(); - listener.resultLog(iTestNGMethod, Status.SUCCESS, "cause"); - assertThat(TEST_LOGGER.takeLoggedMessages(), contains( - "iTestResultMethodWithDetails - SUCCESS null", - "iTestResultMethodWithDetails............SUCCESS [TESTCOMPONENT TESTSERVICE TESTINTERFACE TestTask]" - )); - } - - @Test - @DisplayName("Check logs when " + PRINT_SUITE + "=false " + PRINT_CAUSE + "=true " + PRINT_LOG + "=false") - void unitTest_20181019013142() { - Buggy.getPrimaryConfig().setPrintSuite(false); - Buggy.getPrimaryConfig().setPrintCause(true); - Buggy.getPrimaryConfig().setPrintLogFile(false); - BuggyExecutionListener listener = new BuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER) { - @Override - protected Suite getSuite(ITestNGMethod method) { - return suite; - } - }; - ITestNGMethod iTestNGMethod = getMockITestNGMethod(); - listener.resultLog(iTestNGMethod, Status.SUCCESS, "cause"); - assertThat(TEST_LOGGER.takeLoggedMessages(), contains( - "iTestResultMethodWithDetails - SUCCESS null", - "iTestResultMethodWithDetails............SUCCESS cause" - )); - } - - @Test - @DisplayName("Check logs when " + PRINT_SUITE + "=false " + PRINT_CAUSE + "=false " + PRINT_LOG + "=true") - void unitTest_20181019013245() { - Buggy.getPrimaryConfig().setPrintCause(false); - Buggy.getPrimaryConfig().setPrintSuite(false); - Buggy.getPrimaryConfig().setPrintLogFile(true); - BuggyExecutionListener listener = new BuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER) { - @Override - protected Suite getSuite(ITestNGMethod method) { - return suite; - } - }; - ITestNGMethod iTestNGMethod = getMockITestNGMethod(); - listener.resultLog(iTestNGMethod, Status.SUCCESS, "cause"); - assertThat(TEST_LOGGER.takeLoggedMessages(), contains( - "iTestResultMethodWithDetails - SUCCESS null", - "iTestResultMethodWithDetails............SUCCESS └ file://" + WASTE + - "/tests/iTestResultMethodWithDetails.log" - )); - } - - @Test - @DisplayName("Check logs when " + PRINT_SUITE + "=true " + PRINT_CAUSE + "=true " + PRINT_LOG + "=true") - void unitTest_20181019013427() { - Buggy.getPrimaryConfig().setPrintCause(true); - Buggy.getPrimaryConfig().setPrintSuite(true); - Buggy.getPrimaryConfig().setPrintLogFile(true); - BuggyExecutionListener listener = new BuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER) { - @Override - protected Suite getSuite(ITestNGMethod method) { - return suite; - } - }; - ITestNGMethod iTestNGMethod = getMockITestNGMethod(); - listener.resultLog(iTestNGMethod, Status.SUCCESS, "cause"); - assertThat(TEST_LOGGER.takeLoggedMessages(), contains( - "iTestResultMethodWithDetails - SUCCESS null", - "iTestResultMethodWithDetails............SUCCESS [TESTCOMPONENT TESTSERVICE TESTINTERFACE TestTask] " + - "cause \n└ file://" + WASTE + - "/tests/iTestResultMethodWithDetails.log" - )); - } - - @Test - @DisplayName("Check increment call when isTest=true and getInvocationCount() > 0") - void unitTest_20181019014923() { - BuggyExecutionListener listener = new BuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER) { - @Override - protected Suite getSuite(ITestNGMethod method) { - return suite; - } - }; - ITestNGMethod iTestNGMethod = getMockITestNGMethod(); - when(iTestNGMethod.isTest()).thenReturn(true); - when(iTestNGMethod.getInvocationCount()).thenReturn(1); - int expectedErrors = listener.getNewError() + 1; - listener.resultLog(iTestNGMethod, Status.FAILED, "cause"); - assertThat(TEST_LOGGER.takeLoggedMessages(), contains( - "iTestResultMethodWithDetails - FAILED null", - "iTestResultMethodWithDetails.............FAILED" - )); - assertThat(listener.getNewError(), is(expectedErrors)); - } - - @Test - @DisplayName("Check increment call when isTest=true and getInvocationCount() < 1") - void unitTest_20181019015521() { - BuggyExecutionListener listener = new BuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER) { - @Override - protected Suite getSuite(ITestNGMethod method) { - return suite; - } - }; - ITestNGMethod iTestNGMethod = getMockITestNGMethod(); - when(iTestNGMethod.isTest()).thenReturn(true); - when(iTestNGMethod.getInvocationCount()).thenReturn(0); - int expectedErrors = listener.getNewError(); - int expectedSkiped = listener.getSkippedTests() + 1; - listener.resultLog(iTestNGMethod, Status.FAILED, "skip cause"); - assertThat(TEST_LOGGER.takeLoggedMessages(), contains( - "iTestResultMethodWithDetails - FAILED null", - "iTestResultMethodWithDetails.............FAILED skip cause" - )); - assertThat(listener.getNewError(), is(expectedErrors)); - assertThat(listener.getSkippedTests(), is(expectedSkiped)); - } - - @Test - @DisplayName("Check increment call when isTest=false") - void unitTest_20181019015450() { - BuggyExecutionListener listener = new BuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER) { - @Override - protected Suite getSuite(ITestNGMethod method) { - return suite; - } - }; - ITestNGMethod iTestNGMethod = getMockITestNGMethod(); - when(iTestNGMethod.isTest()).thenReturn(false); - int expectedErrors = listener.getNewError(); - listener.resultLog(iTestNGMethod, Status.FAILED, "cause"); - assertThat(TEST_LOGGER.takeLoggedMessages(), contains( - "iTestResultMethodWithDetails - FAILED null", - "iTestResultMethodWithDetails.............FAILED" - )); - assertThat(listener.getNewError(), is(expectedErrors)); - } - - } - - @Nested() - @DisplayName("printASCIIStatus() tests") - class PrintASCIIStatusTest extends BaseUnitTest { - - @Test - @DisplayName("Check ASCII print FAILED Status") - void unitTest_20181019010409() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(); - listener.printASCIIStatus(FAILED, "FAILED msg"); - assertThat(TEST_LOGGER.takeLoggedMessagesWithLevel(), contains("ERROR FAILED msg")); - } - - @Test - @DisplayName("Check ASCII print CORRUPTED Status") - void unitTest_20181019010858() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(); - listener.printASCIIStatus(CORRUPTED, "CORRUPTED msg"); - assertThat(TEST_LOGGER.takeLoggedMessagesWithLevel(), contains("ERROR CORRUPTED msg")); - } - - @Test - @DisplayName("Check ASCII print EXP_IMPL Status") - void unitTest_20181019010928() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(); - listener.printASCIIStatus(EXP_IMPL, "EXP_IMPL msg"); - assertThat(TEST_LOGGER.takeLoggedMessagesWithLevel(), contains("WARN EXP_IMPL msg")); - } - - @Test - @DisplayName("Check ASCII print EXP_FIX Status") - void unitTest_20181019010955() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(); - listener.printASCIIStatus(EXP_FIX, "EXP_FIX msg"); - assertThat(TEST_LOGGER.takeLoggedMessagesWithLevel(), contains("WARN EXP_FIX msg")); - } - - @Test - @DisplayName("Check ASCII print BLOCKED Status") - void unitTest_20181019011009() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(); - listener.printASCIIStatus(BLOCKED, "BLOCKED msg"); - assertThat(TEST_LOGGER.takeLoggedMessagesWithLevel(), contains("WARN BLOCKED msg")); - } - - @Test - @DisplayName("Check ASCII print SKIP Status") - void unitTest_20181019011024() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(); - listener.printASCIIStatus(SKIP, "SKIP msg"); - assertThat(TEST_LOGGER.takeLoggedMessagesWithLevel(), contains("WARN SKIP msg")); - } - - @Test - @DisplayName("Check ASCII print IMPLEMENTED Status") - void unitTest_20181019011041() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(); - listener.printASCIIStatus(IMPLEMENTED, "IMPLEMENTED msg"); - assertThat(TEST_LOGGER.takeLoggedMessagesWithLevel(), contains("DEBUG IMPLEMENTED msg")); - } - - @Test - @DisplayName("Check ASCII print FIXED Status") - void unitTest_20181019011102() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(); - listener.printASCIIStatus(FIXED, "FIXED msg"); - assertThat(TEST_LOGGER.takeLoggedMessagesWithLevel(), contains("DEBUG FIXED msg")); - } - - @Test - @DisplayName("Check ASCII print SUCCESS Status") - void unitTest_20181019011120() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(); - listener.printASCIIStatus(SUCCESS, "SUCCESS msg"); - assertThat(TEST_LOGGER.takeLoggedMessagesWithLevel(), contains("INFO SUCCESS msg")); - } - - @Test - @DisplayName("Check ASCII print UNTESTED Status") - void unitTest_20181019011215() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(); - listener.printASCIIStatus(UNTESTED, "UNTESTED msg"); - assertThat(TEST_LOGGER.takeLoggedMessagesWithLevel(), contains("INFO UNTESTED msg")); - } - - } - - @Nested() - @DisplayName("increment() tests") - class IncrementTests extends BaseUnitTest { - - @Test - @DisplayName("Check increment FAILED status") - void unitTest_20181019004343() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(); - listener.increment(FAILED); - assertTestStatusCount(listener, 0, 0, 0, 0, 0, 0, 1, 0, 0); - } - - @Test - @DisplayName("Check increment CORRUPTED status") - void unitTest_20181019005331() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(); - listener.increment(CORRUPTED); - assertTestStatusCount(listener, 0, 0, 1, 0, 0, 0, 0, 0, 0); - } - - @Test - @DisplayName("Check increment EXP_IMPL status") - void unitTest_20181019005426() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(); - listener.increment(EXP_IMPL); - assertTestStatusCount(listener, 0, 0, 0, 0, 1, 0, 0, 0, 0); - } - - @Test - @DisplayName("Check increment EXP_FIX status") - void unitTest_20181019005447() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(); - listener.increment(EXP_FIX); - assertTestStatusCount(listener, 0, 0, 0, 1, 0, 0, 0, 0, 0); - } - - @Test - @DisplayName("Check increment BLOCKED status") - void unitTest_20181019005511() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(); - listener.increment(BLOCKED); - assertTestStatusCount(listener, 0, 0, 0, 0, 0, 1, 0, 0, 0); - } - - @Test - @DisplayName("Check increment IMPLEMENTED status") - void unitTest_20181019005613() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(); - listener.increment(IMPLEMENTED); - assertTestStatusCount(listener, 0, 0, 0, 0, 0, 0, 0, 0, 1); - } - - @Test - @DisplayName("Check increment FIXED status") - void unitTest_20181019005635() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(); - listener.increment(FIXED); - assertTestStatusCount(listener, 0, 0, 0, 0, 0, 0, 0, 1, 0); - } - - @Test - @DisplayName("Check increment SKIP status") - void unitTest_20181019005659() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(); - listener.increment(SKIP); - assertTestStatusCount(listener, 0, 1, 0, 0, 0, 0, 0, 0, 0); - } - - @Test - @DisplayName("Check increment UNTESTED status") - void unitTest_20181019005918() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(); - listener.increment(UNTESTED); - assertTestStatusCount(listener, 0, 0, 0, 0, 0, 0, 0, 0, 0); - } - - @Test - @DisplayName("Check increment SUCCESS status") - void unitTest_20181019005938() { - UnitTestBuggyExecutionListener listener = new UnitTestBuggyExecutionListener(); - listener.increment(SUCCESS); - assertTestStatusCount(listener, 0, 0, 0, 0, 0, 0, 0, 0, 0); - } - - @SuppressWarnings("SameParameterValue") - private void assertTestStatusCount(UnitTestBuggyExecutionListener listener, - int testCount, - int skippedTests, - int corruptedError, - int expFixError, - int expImplError, - int blockedError, - int newError, - int fixed, - int implemented) { - assertThat(listener.getTestCount(), is(testCount)); - assertThat(listener.getSkippedTests(), is(skippedTests)); - assertThat(listener.getCorruptedError(), is(corruptedError)); - assertThat(listener.getExpFixError(), is(expFixError)); - assertThat(listener.getExpImplError(), is(expImplError)); - assertThat(listener.getBlockedError(), is(blockedError)); - assertThat(listener.getNewError(), is(newError)); - assertThat(listener.getFixed(), is(fixed)); - assertThat(listener.getImplemented(), is(implemented)); - } - - } - - @Test - @DisplayName("Check checkDebugAndPrint when count = 0") - void unitTest_20181019021242() { - new UnitTestBuggyExecutionListener() {{ - checkDebugAndPrint("checkDebugAndPrint", 0); - }}; - assertThat(TEST_LOGGER.takeLoggedMessagesWithLevel(), contains( - "INFO checkDebugAndPrint............................0" - )); - } - - @Test - @DisplayName("Check checkDebugAndPrint when count = 10") - void unitTest_20181019021752() { - new UnitTestBuggyExecutionListener() {{ - checkDebugAndPrint("checkDebugAndPrint", 10); - }}; - assertThat(TEST_LOGGER.takeLoggedMessagesWithLevel(), contains( - "DEBUG checkDebugAndPrint...........................10" - )); - } - - @Test - @DisplayName("Check checkErrorAndPrint when count = 0") - void unitTest_20181019021932() { - new UnitTestBuggyExecutionListener() {{ - checkErrorAndPrint("checkErrorAndPrint", 0); - }}; - assertThat(TEST_LOGGER.takeLoggedMessagesWithLevel(), contains( - "INFO checkErrorAndPrint............................0" - )); - } - - @Test - @DisplayName("Check checkErrorAndPrint when count = 10") - void unitTest_20181019021954() { - new UnitTestBuggyExecutionListener() {{ - checkErrorAndPrint("checkErrorAndPrint", 10); - }}; - assertThat(TEST_LOGGER.takeLoggedMessagesWithLevel(), contains( - "ERROR checkErrorAndPrint...........................10" - )); - } - - @Test - @DisplayName("Check checkWarnAndPrint when count = 0") - void unitTest_20181019022103() { - new UnitTestBuggyExecutionListener() {{ - checkWarnAndPrint("checkWarnAndPrint", 0); - }}; - assertThat(TEST_LOGGER.takeLoggedMessagesWithLevel(), contains( - "INFO checkWarnAndPrint.............................0" - )); - } - - @Test - @DisplayName("Check checkWarnAndPrint when count = 10") - void unitTest_20181019022107() { - new UnitTestBuggyExecutionListener() {{ - checkWarnAndPrint("checkWarnAndPrint", 10); - }}; - assertThat(TEST_LOGGER.takeLoggedMessagesWithLevel(), contains( - "WARN checkWarnAndPrint............................10" - )); - } - - @Test - @DisplayName("Check checkTraceAndPrint when count = 0") - void unitTest_20181019022204() { - new UnitTestBuggyExecutionListener() {{ - checkTraceAndPrint("checkTraceAndPrint", 0); - }}; - assertThat(TEST_LOGGER.takeLoggedMessagesWithLevel(), contains( - "INFO checkTraceAndPrint............................0" - )); - } - - @Test - @DisplayName("Check checkTraceAndPrint when count = 10") - void unitTest_20181019022306() { - new UnitTestBuggyExecutionListener() {{ - checkTraceAndPrint("checkTraceAndPrint", 10); - }}; - assertThat(TEST_LOGGER.takeLoggedMessagesWithLevel(), contains( - "TRACE checkTraceAndPrint...........................10" - )); - } - - @Test - @DisplayName("printTestStatistic when test run complete without errors") - void unitTest_20181019023610() { - new UnitTestBuggyExecutionListener(SYSTEM_OUT_LOGGER, SYSTEM_OUT_LOGGER, SYSTEM_OUT_LOGGER) {{ - testCount = new AtomicInteger(9); - skippedTests = new AtomicInteger(0); - corruptedError = new AtomicInteger(0); - expFixError = new AtomicInteger(0); - expImplError = new AtomicInteger(0); - blockedError = new AtomicInteger(0); - newError = new AtomicInteger(0); - fixed = new AtomicInteger(0); - implemented = new AtomicInteger(0); - printTestStatistic(); - }}; - assertThat(SYSTEM_OUT_LOGGER.takeLoggedMessagesWithLevel(), contains( - "INFO ===============================================", - "INFO Total tests run...............................9", - "INFO Successful tests..............................9", - "INFO Skipped tests.................................0", - "INFO Errors........................................0", - "INFO ===============================================", - "INFO Execution time.....................00:00:00,000", - "INFO ===============================================" - )); - } - - @Test - @DisplayName("printTestStatistic when test run complete with Buggy errors") - void unitTest_20181019024931() { - Buggy.incrementBuggyErrors(); - new UnitTestBuggyExecutionListener(SYSTEM_OUT_LOGGER, SYSTEM_OUT_LOGGER, SYSTEM_OUT_LOGGER) {{ - testCount = new AtomicInteger(9); - skippedTests = new AtomicInteger(0); - corruptedError = new AtomicInteger(0); - expFixError = new AtomicInteger(0); - expImplError = new AtomicInteger(0); - blockedError = new AtomicInteger(0); - newError = new AtomicInteger(0); - fixed = new AtomicInteger(0); - implemented = new AtomicInteger(0); - printTestStatistic(); - }}; - assertThat(SYSTEM_OUT_LOGGER.takeLoggedMessagesWithLevel(), contains( - "INFO ===============================================", - "ERROR Framework errors..............................1", - "INFO ===============================================", - "INFO Total tests run...............................9", - "INFO Successful tests..............................9", - "INFO Skipped tests.................................0", - "INFO Errors........................................0", - "INFO ===============================================", - "INFO Execution time.....................00:00:00,000", - "INFO ===============================================" - )); - } - - @Test - @DisplayName("printTestStatistic when test run complete with Buggy warns") - void unitTest_20181019025058() { - Buggy.incrementBuggyWarns(); - new UnitTestBuggyExecutionListener(SYSTEM_OUT_LOGGER, SYSTEM_OUT_LOGGER, SYSTEM_OUT_LOGGER) {{ - testCount = new AtomicInteger(9); - skippedTests = new AtomicInteger(0); - corruptedError = new AtomicInteger(0); - expFixError = new AtomicInteger(0); - expImplError = new AtomicInteger(0); - blockedError = new AtomicInteger(0); - newError = new AtomicInteger(0); - fixed = new AtomicInteger(0); - implemented = new AtomicInteger(0); - printTestStatistic(); - }}; - assertThat(SYSTEM_OUT_LOGGER.takeLoggedMessagesWithLevel(), contains( - "INFO ===============================================", - "WARN Framework warns...............................1", - "INFO ===============================================", - "INFO Total tests run...............................9", - "INFO Successful tests..............................9", - "INFO Skipped tests.................................0", - "INFO Errors........................................0", - "INFO ===============================================", - "INFO Execution time.....................00:00:00,000", - "INFO ===============================================" - )); - } - - @Test - @DisplayName("printTestStatistic when test run complete with errors") - void unitTest_20181019024528() { - new UnitTestBuggyExecutionListener(SYSTEM_OUT_LOGGER, SYSTEM_OUT_LOGGER, SYSTEM_OUT_LOGGER) {{ - testCount = new AtomicInteger(100500); - skippedTests = new AtomicInteger(1); - corruptedError = new AtomicInteger(1); - expFixError = new AtomicInteger(1); - expImplError = new AtomicInteger(1); - blockedError = new AtomicInteger(1); - newError = new AtomicInteger(1); - fixed = new AtomicInteger(1); - implemented = new AtomicInteger(1); - printTestStatistic(); - }}; - assertThat(SYSTEM_OUT_LOGGER.takeLoggedMessagesWithLevel(), contains( - "INFO ===============================================", - "INFO Total tests run..........................100500", - "INFO Successful tests.........................100495", - "WARN Skipped tests.................................1", - "WARN Failed tests..................................5", - "ERROR New Errors....................................1", - "INFO ===============================================", - "WARN Waiting to fix a defect.......................1", - "WARN Waiting for implementation....................1", - "WARN Blocked tests.................................1", - "ERROR Corrupted tests...............................1", - "INFO ===============================================", - "DEBUG Fixed cases...................................1", - "DEBUG Implemented cases.............................1", - "INFO ===============================================", - "INFO Execution time.....................00:00:00,000", - "INFO ===============================================" - )); - } - - @Test - @DisplayName("Successful copyFile call when file exists") - void unitTest_20181019025312() throws IOException { - File source = new File(WASTE, "unitTest_20181019025312.source"); - //noinspection ResultOfMethodCallIgnored - source.createNewFile(); - File dist = new File(WASTE, "unitTest_20181019025312.dist"); - new BuggyExecutionListener(SYSTEM_OUT_LOGGER, SYSTEM_OUT_LOGGER, SYSTEM_OUT_LOGGER) {{ - copyFile(source, dist); - }}; - assertThat(dist.exists(), is(true)); - } - -} diff --git a/buggy-core/src/test/java/org/touchbit/buggy/core/tests/transport/CURLLoggingInterceptorTests.java b/buggy-core/src/test/java/org/touchbit/buggy/core/tests/transport/CURLLoggingInterceptorTests.java index c48eaac..0f15815 100644 --- a/buggy-core/src/test/java/org/touchbit/buggy/core/tests/transport/CURLLoggingInterceptorTests.java +++ b/buggy-core/src/test/java/org/touchbit/buggy/core/tests/transport/CURLLoggingInterceptorTests.java @@ -3,7 +3,7 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.touchbit.buggy.core.tests.BaseUnitTest; -import org.touchbit.buggy.core.transport.interceptor.CURLLoggingInterceptor; +import org.touchbit.buggy.core.transport.CURLLoggingInterceptor; import java.util.ArrayList; import java.util.Collection; @@ -23,7 +23,8 @@ class CURLLoggingInterceptorTests extends BaseUnitTest { @Test @DisplayName("Check intercept() with body and headers") void unitTest_20181013152105() { - CURLLoggingInterceptor interceptor = new CURLLoggingInterceptor(TEST_LOGGER::info) {{}}; + CURLLoggingInterceptor interceptor = new CURLLoggingInterceptor(TEST_LOGGER::info) {{ + }}; Map> headers = new HashMap>() {{ put("test_header", new ArrayList() {{ add("value"); @@ -38,7 +39,8 @@ void unitTest_20181013152105() { @Test @DisplayName("Check intercept() without body and headers") void unitTest_20181013152204() { - CURLLoggingInterceptor interceptor = new CURLLoggingInterceptor(TEST_LOGGER::info) {{}}; + CURLLoggingInterceptor interceptor = new CURLLoggingInterceptor(TEST_LOGGER::info) {{ + }}; interceptor.intercept("PUT", "http://url.test", null, null); assertThat(TEST_LOGGER.takeLoggedMessages(), contains("Playback curl:\ncurl -i -k -X PUT 'http://url.test'")); @@ -47,7 +49,8 @@ void unitTest_20181013152204() { @Test @DisplayName("Check intercept() header value == null") void unitTest_20181013161843() { - CURLLoggingInterceptor interceptor = new CURLLoggingInterceptor(TEST_LOGGER::info) {{}}; + CURLLoggingInterceptor interceptor = new CURLLoggingInterceptor(TEST_LOGGER::info) {{ + }}; Map> headers = new HashMap>() {{ put("test_header", null); }}; @@ -59,7 +62,8 @@ void unitTest_20181013161843() { @Test @DisplayName("Check intercept() header value is empty list") void unitTest_20181013162005() { - CURLLoggingInterceptor interceptor = new CURLLoggingInterceptor(TEST_LOGGER::info) {{}}; + CURLLoggingInterceptor interceptor = new CURLLoggingInterceptor(TEST_LOGGER::info) {{ + }}; Map> headers = new HashMap>() {{ put("test_header", new ArrayList<>()); }}; diff --git a/buggy-core/src/test/java/org/touchbit/buggy/core/tests/utils/BuggyLogTests.java b/buggy-core/src/test/java/org/touchbit/buggy/core/tests/utils/BuggyLogTests.java deleted file mode 100644 index de30bcd..0000000 --- a/buggy-core/src/test/java/org/touchbit/buggy/core/tests/utils/BuggyLogTests.java +++ /dev/null @@ -1,144 +0,0 @@ -package org.touchbit.buggy.core.tests.utils; - -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.MDC; -import org.touchbit.buggy.core.tests.BaseUnitTest; -import org.touchbit.buggy.core.Buggy; -import org.touchbit.buggy.core.exceptions.BuggyConfigurationException; -import org.touchbit.buggy.core.utils.IOHelper; -import org.touchbit.buggy.core.utils.log.BuggyLog; -import org.touchbit.buggy.core.utils.log.XMLLogConfigurator; - -import java.io.File; -import java.io.IOException; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.touchbit.buggy.core.utils.log.BuggyLog.LOG_DIRECTORY; -import static org.touchbit.buggy.core.utils.log.BuggyLog.LOG_FILE_NAME; - -/** - * Created by Oleg Shaburov on 16.09.2018 - * shaburov.o.a@gmail.com - */ -@SuppressWarnings("ResultOfMethodCallIgnored") -@DisplayName("BuggyLog Tests") -class BuggyLogTests extends BaseUnitTest { - - - - @Test - @DisplayName("Check LogManager") - void unitTest_20180916003840() { - BuggyLog.getLogsDirPath(); - assertThat(System.getProperty("java.util.logging.manager"), - is("org.apache.logging.log4j.jul.LogManager")); - } - - @Test - @DisplayName("Check setLogsDirPath(logPath)") - void unitTest_20180916011731() { - String logPath = WASTE + "/logs"; - BuggyLog.setLogsDirPath(logPath); - assertThat(BuggyLog.getLogsDirPath(), is(logPath)); - assertThat(System.getProperty(LOG_DIRECTORY), is(logPath)); - } - - @Test - @DisplayName("Check setLogsDirPath(null)") - void unitTest_20180916012313() { - BuggyConfigurationException e = execute(() -> BuggyLog.setLogsDirPath(null), BuggyConfigurationException.class); - assertThat(e.getMessage(), is("The path to the log directory can not be empty")); - } - - @Test - @DisplayName("Check setTestLogFileName(String logName)") - void unitTest_20180916015450() { - BuggyLog.setTestLogFileName("unitTest_20180916015450"); - assertThat(MDC.get(LOG_FILE_NAME), is("unitTest_20180916015450")); - } - - @Test - @DisplayName("Check loadDefaultConfig() with root logger") - void unitTest_20180916015619() throws IOException { - BuggyLog.setLogsDirPath(WASTE); - File testResourcesWaste = new File(WASTE, "log4j2.xml"); - File srcResourcesWaste = new File(WASTE, "buggy-log4j2.xml"); - File testResources = new File(TEST_CLASSES, "log4j2.xml"); - File srcResources = new File(CLASSES, "buggy-log4j2.xml"); - try { - IOHelper.moveFile(testResources, testResourcesWaste); - IOHelper.moveFile(srcResources, srcResourcesWaste); - Buggy.prepare(); - BuggyLog.loadDefaultConfig(); - } finally { - IOHelper.moveFile(testResourcesWaste, testResources); - IOHelper.moveFile(srcResourcesWaste, srcResources); - } - } - - @Test - @DisplayName("Check loadDefaultConfig() with log4j2.xml") - void unitTest_20180916212753() { - BuggyLog.setLogsDirPath(WASTE); - BuggyLog.loadDefaultConfig(); - } - - @Test - @DisplayName("Check loadDefaultConfig() with buggy-log4j2.xml") - void unitTest_20180916212008() throws IOException { - BuggyLog.setLogsDirPath(WASTE); - File waste = new File(WASTE, "log4j2.xml"); - File resources = new File(TEST_CLASSES, "log4j2.xml"); - try { - IOHelper.moveFile(resources, waste); - BuggyLog.loadDefaultConfig(); - } finally { - IOHelper.moveFile(waste, resources); - } - } - - @Test - @DisplayName("Check BuggyLog constructor") - void unitTest_20180916025621() { - new BuggyLog(null, null, null); - assertThat(BuggyLog.console(), is(nullValue())); - assertThat(BuggyLog.framework(), is(nullValue())); - assertThat(BuggyLog.test(), is(nullValue())); - Logger logger = LoggerFactory.getLogger("test"); - new BuggyLog(logger, logger, logger); - assertThat(BuggyLog.console(), is(logger)); - assertThat(BuggyLog.framework(), is(logger)); - assertThat(BuggyLog.test(), is(logger)); - } - - @Test - @DisplayName("GIVEN BuggyLog WHEN BuggyLog() THEN no errors") - void unitTest_20181021171040() { - new BuggyLog(); - assertThat(BuggyLog.console(), is(not(nullValue()))); - assertThat(BuggyLog.framework(), is(not(nullValue()))); - assertThat(BuggyLog.test(), is(not(nullValue()))); - assertThat(BuggyLog.console(), is(instanceOf(Logger.class))); - assertThat(BuggyLog.framework(), is(instanceOf(Logger.class))); - assertThat(BuggyLog.test(), is(instanceOf(Logger.class))); - } - - @Test - @DisplayName("Check XMLLogConfigurator constructor") - void unitTest_20180916214825() throws NoSuchMethodException { - checkUtilityClassConstructor(XMLLogConfigurator.class); - } - - @Test - @DisplayName("Check init logger before Buggy") - void unitTest_20181017010157() { - Buggy.reset(); - new BuggyLog(null, null, null); - assertExitCode(1, "The logger cannot be initialized before the Buggy configuration."); - } - -} diff --git a/buggy-core/src/test/java/org/touchbit/buggy/core/tests/utils/BuggyUtilsTests.java b/buggy-core/src/test/java/org/touchbit/buggy/core/tests/utils/BuggyUtilsTests.java index 3a1e96e..8d49ed0 100644 --- a/buggy-core/src/test/java/org/touchbit/buggy/core/tests/utils/BuggyUtilsTests.java +++ b/buggy-core/src/test/java/org/touchbit/buggy/core/tests/utils/BuggyUtilsTests.java @@ -1,360 +1,33 @@ package org.touchbit.buggy.core.tests.utils; -import org.atteo.classindex.IndexSubclasses; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.function.Executable; -import org.testng.xml.Parameters; -import org.touchbit.buggy.core.config.*; -import org.touchbit.buggy.core.tests.BaseUnitTest; -import org.touchbit.buggy.core.Buggy; -import org.touchbit.buggy.core.exceptions.BuggyConfigurationException; +import org.touchbit.buggy.core.config.TestComponent; +import org.touchbit.buggy.core.config.TestInterface; +import org.touchbit.buggy.core.config.TestService; +import org.touchbit.buggy.core.goal.component.Component; +import org.touchbit.buggy.core.goal.interfaze.Interface; +import org.touchbit.buggy.core.goal.service.Service; import org.touchbit.buggy.core.model.Suite; -import org.touchbit.buggy.core.process.Component; -import org.touchbit.buggy.core.process.Interface; -import org.touchbit.buggy.core.process.Service; -import org.touchbit.buggy.core.testng.TestSuite; -import org.touchbit.buggy.core.utils.BuggyUtils; +import org.touchbit.buggy.core.tests.BaseUnitTest; import org.touchbit.buggy.core.utils.IOHelper; +import org.touchbit.buggy.core.utils.JUtils; import java.io.IOException; import java.io.InputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; -import java.util.jar.Attributes; import java.util.jar.Manifest; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; -import static org.junit.jupiter.api.Assertions.assertThrows; /** * Created by Oleg Shaburov on 15.09.2018 * shaburov.o.a@gmail.com */ -@DisplayName("BuggyUtils Tests") -class BuggyUtilsTests extends BaseUnitTest { - - @Test - @DisplayName("Check getComponent(Suite suite)") - void unitTest_20180915175811() { - Component component = BuggyUtils.getComponent(SUITE_1); - assertThat(component, instanceOf(TestComponent.class)); - } - - @Test - @DisplayName("Check getComponent(Suite suite) Configuration Exception") - void unitTest_20180915181738() { - Executable executable = () -> BuggyUtils.getComponent(PRIVATE_SUITE); - assertThrows(BuggyConfigurationException.class, executable, - "Can not create a new instance of the Component class " + - PRIVATE_SUITE.component()); - } - - @Test - @DisplayName("Check getInterface(Suite suite)") - void unitTest_20180915181351() { - Interface anInterface = BuggyUtils.getInterface(SUITE_1); - assertThat(anInterface, instanceOf(TestInterface.class)); - } - - @Test - @DisplayName("Check getInterface(Suite suite) Configuration Exception") - void unitTest_20180915184751() { - Executable executable = () -> BuggyUtils.getInterface(PRIVATE_SUITE); - assertThrows(BuggyConfigurationException.class, executable, - "Can not create a new instance of the Interface class " + - PRIVATE_SUITE.interfaze()); - } - - @Test - @DisplayName("Check getService(Suite suite)") - void unitTest_20180915181442() { - Service service = BuggyUtils.getService(SUITE_1); - assertThat(service, instanceOf(TestService.class)); - } - - @Test - @DisplayName("Check getService(Suite suite) Configuration Exception") - void unitTest_20180915184905() { - Executable executable = () -> BuggyUtils.getService(PRIVATE_SUITE); - assertThrows(BuggyConfigurationException.class, executable, - "Can not create a new instance of the Service class " + - PRIVATE_SUITE.service()); - } - - @Test - @DisplayName("Check equalsSuites(null, SUITE_1)") - void unitTest_20180915185244() { - assertThat(BuggyUtils.equalsSuites(null, SUITE_1), is(false)); - } - - @Test - @DisplayName("Check equalsSuites(SUITE_1, null)") - void unitTest_20180915185356() { - assertThat(BuggyUtils.equalsSuites(SUITE_1, null), is(false)); - } - - @Test - @DisplayName("Check equalsSuites(null, null)") - void unitTest_20180915185504() { - assertThat(BuggyUtils.equalsSuites(null, null), is(false)); - } - - @Test - @DisplayName("Check equalsSuites(SUITE_1, SUITE_1)") - void unitTest_20180915185543() { - assertThat(BuggyUtils.equalsSuites(SUITE_1, SUITE_1), is(true)); - } - - @Test - @DisplayName("Check equalsSuites(SUITE_1, SUITE_2)") - void unitTest_20180915185733() { - assertThat(BuggyUtils.equalsSuites(SUITE_1, SUITE_2), is(true)); - } - - @Test - @DisplayName("Check getManifest()") - void unitTest_20180915185908() { - assertThat(BuggyUtils.getManifest(), is(notNullValue())); - } - - @Test - @DisplayName("GIVEN InputStream == null WHEN readManifest THEN return empty Manifest") - void unitTest_20181029013041() throws Exception { - Class buggyUtilsClass = BuggyUtils.class; - Method readManifest = buggyUtilsClass.getDeclaredMethod("readManifest", InputStream.class); - readManifest.setAccessible(true); - InputStream inputStream = null; - Manifest manifest = (Manifest) readManifest.invoke(buggyUtilsClass, inputStream); - assertThat(manifest.getMainAttributes().entrySet(), is(empty())); - } - - @Test - @DisplayName("GIVEN InputStream WHEN readManifest THEN return Manifest") - void unitTest_20181029013955() throws Exception { - Class buggyUtilsClass = BuggyUtils.class; - Method readManifest = buggyUtilsClass.getDeclaredMethod("readManifest", InputStream.class); - readManifest.setAccessible(true); - InputStream inputStream = IOHelper.getResourceAsStream("./META-INF/MANIFEST.MF"); - if (inputStream == null) { - inputStream = IOHelper.getResourceAsStream("META-INF/MANIFEST.MF"); - } - Manifest manifest = (Manifest) readManifest.invoke(buggyUtilsClass, inputStream); - assertThat(manifest.getMainAttributes().entrySet(), is(not(empty()))); - } - - @Test - @DisplayName("GIVEN InputStream IOException WHEN readManifest THEN return empty Manifest") - void unitTest_20181029014220() throws Exception { - Class buggyUtilsClass = BuggyUtils.class; - Method readManifest = buggyUtilsClass.getDeclaredMethod("readManifest", InputStream.class); - readManifest.setAccessible(true); - InputStream inputStream = new InputStream() { - @Override - public int read() throws IOException { - throw new IOException("unitTest_20181029014220"); - } - }; - Manifest manifest = (Manifest) readManifest.invoke(buggyUtilsClass, inputStream); - assertThat(manifest.getMainAttributes().entrySet(), is(empty())); - } - - @Test - @DisplayName("Check getManifestAttributes()") - void unitTest_20180915192200() { - Attributes attributes = BuggyUtils.getManifestAttributes(); - assertThat(attributes, is(notNullValue())); - assertThat(attributes.isEmpty(), is(false)); - } - - @Test - @DisplayName("Check isListBaseSuiteContainsClass(null, null)") - void unitTest_20180915204319() { - assertThat(BuggyUtils.isListBaseSuiteContainsClass(null, null), is(false)); - } - - @Test - @DisplayName("Check isListBaseSuiteContainsClass(new ArrayList<>(), Object.class)") - void unitTest_20180915204615() { - assertThat(BuggyUtils.isListBaseSuiteContainsClass(new ArrayList<>(), Object.class), is(false)); - } - - @Test - @DisplayName("Check isListBaseSuiteContainsClass(notEmptyTestSuiteList, null)") - void unitTest_20180915204623() { - List notEmptyTestSuiteList = new ArrayList<>(); - Buggy.setPrimaryConfigClass(UnitTestPrimaryConfig.class); - notEmptyTestSuiteList.add(new TestSuite(SUITE_1)); - assertThat(BuggyUtils.isListBaseSuiteContainsClass(notEmptyTestSuiteList, null), is(false)); - } - - @Test - @DisplayName("Check isListBaseSuiteContainsClass(notEmptyTestSuiteList, Object.class)") - void unitTest_20180915204630() { - List notEmptyTestSuiteList = new ArrayList<>(); - Buggy.setPrimaryConfigClass(UnitTestPrimaryConfig.class); - notEmptyTestSuiteList.add(new TestSuite(SUITE_1)); - assertThat(BuggyUtils.isListBaseSuiteContainsClass(notEmptyTestSuiteList, Object.class), is(false)); - } - - @Test - @DisplayName("Check isListBaseSuiteContainsClass(suiteNotContainsTestPackage, BuggyUtilsTests.class)") - void unitTest_20180915211848() { - List suiteNotContainsTestPackage = new ArrayList<>(); - Buggy.setPrimaryConfigClass(UnitTestPrimaryConfig.class); - TestSuite suite = new TestSuite(SUITE_1); - suiteNotContainsTestPackage.add(suite); - assertThat(BuggyUtils - .isListBaseSuiteContainsClass(suiteNotContainsTestPackage, BuggyUtilsTests.class), is(false)); - } - - @Test - @DisplayName("Check isListBaseSuiteContainsClass(suiteNotContainsTestClass, BuggyUtilsTests.class)") - void unitTest_20180915212041() { - List suiteNotContainsTestClass = new ArrayList<>(); - Buggy.setPrimaryConfigClass(UnitTestPrimaryConfig.class); - TestSuite suite = new TestSuite(SUITE_1); - suite.addTestPackage("test"); - suiteNotContainsTestClass.add(suite); - assertThat(BuggyUtils - .isListBaseSuiteContainsClass(suiteNotContainsTestClass, BuggyUtilsTests.class), is(false)); - } - - @Test - @DisplayName("Check isListBaseSuiteContainsClass(suiteContainsTestClass, Object.class)") - void unitTest_20180915212259() { - List suiteContainsTestClass = new ArrayList<>(); - Buggy.setPrimaryConfigClass(UnitTestPrimaryConfig.class); - TestSuite suite = new TestSuite(SUITE_1); - suite.addTestPackage("test", BuggyUtilsTests.class); - suiteContainsTestClass.add(suite); - assertThat(BuggyUtils - .isListBaseSuiteContainsClass(suiteContainsTestClass, Object.class), is(false)); - } - - @Test - @DisplayName("Check isListBaseSuiteContainsClass(notEmptyTestSuiteList, BuggyUtilsTests.class)") - void unitTest_20180915204950() { - List suiteContainsTestClass = new ArrayList<>(); - Buggy.setPrimaryConfigClass(UnitTestPrimaryConfig.class); - TestSuite suite = new TestSuite(SUITE_1); - suite.addTestPackage("test", BuggyUtilsTests.class); - suiteContainsTestClass.add(suite); - assertThat(BuggyUtils - .isListBaseSuiteContainsClass(suiteContainsTestClass, BuggyUtilsTests.class), is(true)); - } - - @Test - @DisplayName("Check BuggyUtils constructor") - void unitTest_20180915192539() throws NoSuchMethodException { - checkUtilityClassConstructor(BuggyUtils.class); - } - - @Test - @DisplayName("GIVEN findAnnotatedInstantiatedClasses(Suite) WHEN public class THEN hasItem") - void unitTest_20181021171954() { - List> suites = BuggyUtils.findAnnotatedInstantiatedClasses(Suite.class); - assertThat(suites, not(empty())); - assertThat(suites, hasItem(sameInstance(TestClassWithSuite.class))); - } - - @Test - @DisplayName("GIVEN findAnnotatedInstantiatedClasses(Suite) WHEN not public class THEN not(hasItem)") - void unitTest_20181021172745() { - List> suites = BuggyUtils.findAnnotatedInstantiatedClasses(Suite.class); - assertThat(suites, not(empty())); - assertThat(suites, not(hasItem(sameInstance(PrivateTestClass.class)))); - } - - @Test - @DisplayName("GIVEN findAnnotatedInstantiatedClasses(Suite) WHEN abstract class THEN not(hasItem)") - void unitTest_20181021173208() { - List> suites = BuggyUtils.findAnnotatedInstantiatedClasses(Suite.class); - assertThat(suites, not(empty())); - assertThat(suites, not(hasItem(sameInstance(AbstractTestClass.class)))); - } - - @Test - @DisplayName("GIVEN findAnnotatedInstantiatedClasses(Suite) WHEN no annotated class THEN is(empty())") - void unitTest_20181021174039() { - List> suites = BuggyUtils.findAnnotatedInstantiatedClasses(BuggyUtilsTestsInterface.class); - assertThat(suites, is(empty())); - } - - @Test - @DisplayName("GIVEN isAssignableFrom WHEN nested inheritance THEN assignable") - void unitTest_20181021174629() { - assertThat(BuggyUtils.isAssignableFrom(Child.class, Parent.class), is(true)); - assertThat(BuggyUtils.isAssignableFrom(Child.class, Child.class), is(true)); - assertThat(BuggyUtils.isAssignableFrom(Parent.class, Child.class), is(false)); - assertThat(BuggyUtils.isAssignableFrom(Child.class, ParentInterface.class), is(false)); - } - - @Test - @DisplayName("GIVEN isAssignableFrom WHEN null THEN false") - void unitTest_20181021175344() { - assertThat(BuggyUtils.isAssignableFrom(null, Parent.class), is(false)); - assertThat(BuggyUtils.isAssignableFrom(Parent.class, null), is(false)); - } - - @Test - @DisplayName("GIVEN isAssignableFrom WHEN Object THEN false") - void unitTest_20181021175526() { - assertThat(BuggyUtils.isAssignableFrom(Object.class, Parent.class), is(false)); - } - - @Test - @DisplayName("WHEN findComponents() THEN hasItem") - void unitTest_20181021175921() { - assertThat(BuggyUtils.findComponents(), hasItem(instanceOf(TestComponent.class))); - } - - @Test - @DisplayName("WHEN findServices() THEN hasItem") - void unitTest_20181021180113() { - assertThat(BuggyUtils.findServices(), hasItem(instanceOf(TestService.class))); - } - - @Test - @DisplayName("WHEN findInterfaces() THEN hasItem") - void unitTest_20181021180159() { - assertThat(BuggyUtils.findInterfaces(), hasItem(instanceOf(TestInterface.class))); - } - - @Test - @DisplayName("GIVEN Class with exception WHEN getSubclassesNewObjectList THEN BuggyConfigurationException") - void unitTest_20181021180411() { - Executable executable = () -> BuggyUtils.getSubclassesNewObjectList(IndexClass.class); - assertThrows(BuggyConfigurationException.class, executable, - "Can not create a new instance of the IndexClass " + IndexedClass.class); - } - - @IndexSubclasses - public static abstract class IndexClass {} - - public static class IndexedClass extends IndexClass { - - public IndexedClass() { - throw new RuntimeException("unitTest_20181021180411 exception"); - } - } - - public interface ParentInterface {} - - public static class Parent implements ParentInterface {} - - public static class Child extends Parent {} - - public static @interface BuggyUtilsTestsInterface {} - - @Suite(component = TestComponent.class, service = TestService.class, interfaze = TestInterface.class, task = "unit_test") - private static class PrivateTestClass {} - - @Suite(component = TestComponent.class, service = TestService.class, interfaze = TestInterface.class, task = "unit_test") - public abstract static class AbstractTestClass {} +@DisplayName("JUtils Tests") +class JUtilsTests extends BaseUnitTest { private static final Suite SUITE_1 = new Suite() { @@ -379,11 +52,10 @@ public Class interfaze() { } @Override - public String task() { + public String purpose() { return "TestTask"; } }; - private static final Suite SUITE_2 = new Suite() { @Override @@ -407,11 +79,10 @@ public Class interfaze() { } @Override - public String task() { + public String purpose() { return "TestTask"; } }; - private static final Suite PRIVATE_SUITE = new Suite() { @Override @@ -435,11 +106,75 @@ public Class interfaze() { } @Override - public String task() { + public String purpose() { return "TestTask"; } }; + @Test + @DisplayName("GIVEN InputStream == null WHEN readManifest THEN return empty Manifest") + void unitTest_20181029013041() throws Exception { + Class JUtilsClass = JUtils.class; + Method readManifest = JUtilsClass.getDeclaredMethod("readManifest", InputStream.class); + readManifest.setAccessible(true); + InputStream inputStream = null; + Manifest manifest = (Manifest) readManifest.invoke(JUtilsClass, inputStream); + assertThat(manifest.getMainAttributes().entrySet(), is(empty())); + } + + @Test + @DisplayName("GIVEN InputStream WHEN readManifest THEN return Manifest") + void unitTest_20181029013955() throws Exception { + Class JUtilsClass = JUtils.class; + Method readManifest = JUtilsClass.getDeclaredMethod("readManifest", InputStream.class); + readManifest.setAccessible(true); + InputStream inputStream = IOHelper.getResourceAsStream("./META-INF/MANIFEST.MF"); + if (inputStream == null) { + inputStream = IOHelper.getResourceAsStream("META-INF/MANIFEST.MF"); + } + Manifest manifest = (Manifest) readManifest.invoke(JUtilsClass, inputStream); + assertThat(manifest.getMainAttributes().entrySet(), is(not(empty()))); + } + + @Test + @DisplayName("GIVEN InputStream IOException WHEN readManifest THEN return empty Manifest") + void unitTest_20181029014220() throws Exception { + Class JUtilsClass = JUtils.class; + Method readManifest = JUtilsClass.getDeclaredMethod("readManifest", InputStream.class); + readManifest.setAccessible(true); + InputStream inputStream = new InputStream() { + @Override + public int read() throws IOException { + throw new IOException("unitTest_20181029014220"); + } + }; + Manifest manifest = (Manifest) readManifest.invoke(JUtilsClass, inputStream); + assertThat(manifest.getMainAttributes().entrySet(), is(empty())); + } + + @Test + @DisplayName("Check JUtils constructor") + void unitTest_20180915192539() throws NoSuchMethodException { + checkUtilityClassConstructor(JUtils.class); + } + + public interface ParentInterface { + } + + public static class Parent implements ParentInterface { + } + + public static class Child extends Parent { + } + + @Suite(component = TestComponent.class, service = TestService.class, interfaze = TestInterface.class, purpose = "unit_test") + private static class PrivateTestClass { + } + + @Suite(component = TestComponent.class, service = TestService.class, interfaze = TestInterface.class, purpose = "unit_test") + public abstract static class AbstractTestClass { + } + private static class PrivateTestInterface extends Interface { @Override @@ -458,11 +193,6 @@ public String getDescription() { private static class PrivateTestComponent extends Component { - @Override - public List getServices() { - return new ArrayList() {{add(new TestService());}}; - } - @Override public String getDescription() { return "PrivateTestComponent"; diff --git a/buggy-core/src/test/java/org/touchbit/buggy/core/tests/utils/IOHelperTests.java b/buggy-core/src/test/java/org/touchbit/buggy/core/tests/utils/IOHelperTests.java index 1c30ec9..c3e567a 100644 --- a/buggy-core/src/test/java/org/touchbit/buggy/core/tests/utils/IOHelperTests.java +++ b/buggy-core/src/test/java/org/touchbit/buggy/core/tests/utils/IOHelperTests.java @@ -2,13 +2,11 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import org.touchbit.buggy.core.tests.BaseUnitTest; import org.touchbit.buggy.core.exceptions.BuggyException; +import org.touchbit.buggy.core.tests.BaseUnitTest; import org.touchbit.buggy.core.utils.IOHelper; import java.io.File; -import java.io.IOException; -import java.util.Properties; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; @@ -20,41 +18,25 @@ @DisplayName("IOHelper Tests") class IOHelperTests extends BaseUnitTest { - @Test - @DisplayName("Check readPropertiesFileFromResource(\"unit_test.properties\")") - void unitTest_20180915215434() { - IOHelper.writeFile(new File(TEST_CLASSES, "unit_test.properties"), - "--single\n--with_value=value"); - Properties properties = IOHelper.readPropertiesFileFromResource("unit_test.properties"); - assertThat(properties.getProperty("--single"), is("")); - assertThat(properties.getProperty("--with_value"), is("value")); - } - - @Test - @DisplayName("Check readPropertiesFileFromResource(\"not_exist.properties\")") - void unitTest_20180915215744() { - Exception exception = null; - String fileName = "not_exist.properties"; - try { - IOHelper.readPropertiesFileFromResource(fileName); - } catch (Exception e) { - exception = e; - } - assertThat("BuggyException", exception, is(notNullValue())); - assertThat(exception.getClass(), sameInstance(BuggyException.class)); - assertThat(exception.getMessage(), - is("The following file can not be found in the project resources: " + fileName)); - } +// @Test +// @DisplayName("Check readPropertiesFileFromResource(\"unit_test.properties\")") +// void unitTest_20180915215434() { +// IOHelper.writeFile(new File(TEST_CLASSES, "unit_test.properties"), +// "--single\n--with_value=value"); +// Properties properties = IOHelper.readPropertiesFileFromResource("unit_test.properties"); +// assertThat(properties.getProperty("--single"), is("")); +// assertThat(properties.getProperty("--with_value"), is("value")); +// } - @Test - @DisplayName("Check getFileFromResource(exists)") - void unitTest_20180915220703() { - String fileName = "unitTest_20180915220703.txt"; - IOHelper.writeFile(new File(TEST_CLASSES, fileName), fileName); - File file = IOHelper.getFileFromResource(fileName); - assertThat(file.exists(), is(true)); - assertThat(IOHelper.readFile(file), is(fileName)); - } +// @Test +// @DisplayName("Check getFileFromResource(exists)") +// void unitTest_20180915220703() { +// String fileName = "unitTest_20180915220703.txt"; +// IOHelper.writeFile(new File(TEST_CLASSES, fileName), fileName); +// File file = IOHelper.getFileFromResource(fileName); +// assertThat(file.exists(), is(true)); +// assertThat(IOHelper.readFile(file), is(fileName)); +// } @Test @DisplayName("Check getFileFromResource(not exists)") @@ -105,49 +87,49 @@ void unitTest_20180915235442() { assertThat(exception.getMessage(), is("Error writing file: " + fileName)); } - - @Test - @DisplayName("Check writeFile & readFile") - void unitTest_20180916000548() { - String fileName = "unitTest_20180916000548.txt"; - File existFile = new File(WASTE, fileName); - IOHelper.writeFile(existFile, "body"); - String body = IOHelper.readFile(existFile); - assertThat(body, is("body")); - } - - @Test - @DisplayName("Check copyFile(existFile, target)") - void unitTest_20180916000532() throws IOException { - String fileName = "unitTest_20180916000532.txt"; - File existFile = new File(WASTE, fileName); - IOHelper.writeFile(existFile, "body"); - File target = new File(WASTE + "/unitTest_20180916000532/", "copy.txt"); - IOHelper.copyFile(existFile, target); - assertThat("target.exists()", target.exists(), is(true)); - } - - @Test - @DisplayName("Check copyFile(existFile.getAbsoluteLogPath(), target.getAbsoluteLogPath()") - void unitTest_20180916001820() throws IOException { - String fileName = "unitTest_20180916001820.txt"; - File existFile = new File(WASTE, fileName); - IOHelper.writeFile(existFile, "body"); - File target = new File(WASTE + "/unitTest_20180916001820/", "copy.txt"); - IOHelper.copyFile(existFile.getAbsolutePath(), target.getAbsolutePath()); - assertThat("target.exists()", target.exists(), is(true)); - } - - @Test - @DisplayName("Check makeParentDirs(file)") - void unitTest_20180916213553() { - File file1 = new File(WASTE); - File file2 = new File(WASTE + "/p1/p2/p3", "file.txt"); - IOHelper.makeParentDirs(file1); - IOHelper.makeParentDirs(file2); - assertThat("makeParentDirs exists", file1.exists(), is(true)); - assertThat("makeParentDirs exists", file2.getParentFile().exists(), is(true)); - } +// +// @Test +// @DisplayName("Check writeFile & readFile") +// void unitTest_20180916000548() { +// String fileName = "unitTest_20180916000548.txt"; +// File existFile = new File(WASTE, fileName); +// IOHelper.writeFile(existFile, "body"); +// String body = IOHelper.readFile(existFile); +// assertThat(body, is("body")); +// } +// +// @Test +// @DisplayName("Check copyFile(existFile, target)") +// void unitTest_20180916000532() throws IOException { +// String fileName = "unitTest_20180916000532.txt"; +// File existFile = new File(WASTE, fileName); +// IOHelper.writeFile(existFile, "body"); +// File target = new File(WASTE + "/unitTest_20180916000532/", "copy.txt"); +// IOHelper.copyFile(existFile, target); +// assertThat("target.exists()", target.exists(), is(true)); +// } +// +// @Test +// @DisplayName("Check copyFile(existFile.getAbsoluteLogPath(), target.getAbsoluteLogPath()") +// void unitTest_20180916001820() throws IOException { +// String fileName = "unitTest_20180916001820.txt"; +// File existFile = new File(WASTE, fileName); +// IOHelper.writeFile(existFile, "body"); +// File target = new File(WASTE + "/unitTest_20180916001820/", "copy.txt"); +// IOHelper.copyFile(existFile.getAbsolutePath(), target.getAbsolutePath()); +// assertThat("target.exists()", target.exists(), is(true)); +// } +// +// @Test +// @DisplayName("Check makeParentDirs(file)") +// void unitTest_20180916213553() { +// File file1 = new File(WASTE); +// File file2 = new File(WASTE + "/p1/p2/p3", "file.txt"); +// IOHelper.makeParentDirs(file1); +// IOHelper.makeParentDirs(file2); +// assertThat("makeParentDirs exists", file1.exists(), is(true)); +// assertThat("makeParentDirs exists", file2.getParentFile().exists(), is(true)); +// } @Test @DisplayName("Check IOHelper constructor") diff --git a/buggy-core/src/test/java/org/touchbit/buggy/core/tests/utils/StringUtilsTests.java b/buggy-core/src/test/java/org/touchbit/buggy/core/tests/utils/StringUtilsTests.java deleted file mode 100644 index a83d5f1..0000000 --- a/buggy-core/src/test/java/org/touchbit/buggy/core/tests/utils/StringUtilsTests.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Copyright © 2018 Shaburov Oleg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.touchbit.buggy.core.tests.utils; - -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.touchbit.buggy.core.tests.BaseUnitTest; -import org.touchbit.buggy.core.exceptions.AssertionException; -import org.touchbit.buggy.core.utils.StringUtils; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; - -/** - * Created by Oleg Shaburov on 14.09.2018 - * shaburov.o.a@gmail.com - */ -@DisplayName("StringUtils Tests") -class StringUtilsTests extends BaseUnitTest { - - @Test - @DisplayName("Check dotFiller(Object prefix, int i)") - void test20180914194403() { - String msg = StringUtils.dotFiller("Test", 10); - assertThat(msg, is("Test......")); - } - - @Test - @DisplayName("Check dotFiller(Object prefix, int i, Object suffix)") - void unitTest_20180914220458() { - String msg = StringUtils.dotFiller("Test", 10, "OK"); - assertThat(msg, is("Test....OK")); - } - - @Test - @DisplayName("Check underscoreFiller(Object prefix, int i)") - void unitTest_20180914221041() { - String msg = StringUtils.underscoreFiller("Test", 10); - assertThat(msg, is("Test______")); - } - - @Test - @DisplayName("Check underscoreFiller(Object prefix, int i, Object suffix)") - void unitTest_20180914221123() { - String msg = StringUtils.underscoreFiller("Test", 10, "OK"); - assertThat(msg, is("Test____OK")); - } - - @Test - @DisplayName("Check filler(Object prefix, String symbol, int i)") - void unitTest_20180914221207() { - String msg = StringUtils.filler("Test", "+", 10); - assertThat(msg, is("Test++++++")); - } - - @Test - @DisplayName("Check filler(Object prefix, String symbol, int length, Object postfix)") - void unitTest_20180914221305() { - String msg = StringUtils.filler("Test", "+", 10, "OK"); - assertThat(msg, is("Test++++OK")); - } - - @Test - @DisplayName("Check filler default values") - void unitTest_20180914221346() { - String msg = StringUtils.filler(null, null, 5, null); - assertThat(msg, is(".....")); - } - - @Test - @DisplayName("WHEN filler with empty symbol THEN default dot") - void unitTest_20181029012204() { - String msg = StringUtils.filler(null, "", 5, null); - assertThat(msg, is(".....")); - } - - @Test - @DisplayName("Check out of message length") - void unitTest_20180914221536() { - String msg = StringUtils.filler("Test", "+", 5, "OK"); - assertThat(msg, is("Test+++OK")); - } - - @Test - @DisplayName("Check URL encode(String value)") - void unitTest_20180914222346() { - String msg = StringUtils.encode("[123]"); - assertThat(msg, is("%5B123%5D")); - } - - @Test - @DisplayName("Check URL decode(String value)") - void unitTest_20180914222738() { - String msg = StringUtils.decode("%5B123%5D"); - assertThat(msg, is("[123]")); - } - - @Test - @DisplayName("Check URL decode ignore exception") - void unitTest_20180914222830() { - String msg = StringUtils.decode(null); - assertThat(msg, is(nullValue())); - } - - @Test - @DisplayName("Check URL encode ignore exception") - void unitTest_20180914223048() { - String msg = StringUtils.encode(null); - assertThat(msg, is(nullValue())); - } - - @Test - @DisplayName("Check println(String msg)") - void unitTest_20180914223136() { - StringUtils.println("unitTest_20180914223136 test message."); - } - - @Test - @DisplayName("Check println(String msg, Throwable t)") - void unitTest_20180914223257() { - StringUtils.println("unitTest_20180914223257 test message", new AssertionException("With Exception")); - } - - @Test - @DisplayName("Check println() null values") - void unitTest_20180914223459() { - StringUtils.println(null, null); - } - - @Test - @DisplayName("Check BuggyUtils constructor") - void unitTest_20180915213419() throws NoSuchMethodException { - checkUtilityClassConstructor(StringUtils.class); - } - -} diff --git a/buggy-core/src/test/resources/buggy.properties b/buggy-core/src/test/resources/buggy.properties index 13eed98..4a382b8 100644 --- a/buggy-core/src/test/resources/buggy.properties +++ b/buggy-core/src/test/resources/buggy.properties @@ -11,7 +11,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - # suppress inspection "WrongPropertyKeyValueDelimiter" for whole file --all --force diff --git a/buggy-core/src/test/resources/log4j2.xml b/buggy-core/src/test/resources/log4j2.xml deleted file mode 100644 index 3311325..0000000 --- a/buggy-core/src/test/resources/log4j2.xml +++ /dev/null @@ -1,58 +0,0 @@ - - - - - ${sys:log.directory} - - %d{HH:mm:ss.SSS} %m%n - %d{HH:mm:ss.SSS} [%17t] - %m%n - - {FATAL=red blink, ERROR=red, WARN=Magenta, INFO=NAN, DEBUG=green, TRACE=blue} - red bright - {FATAL=${rb}, ERROR=${rb}, WARN=${rb}, INFO=${rb}, DEBUG=${rb}, TRACE=${rb}} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/buggy-feign/pom.xml b/buggy-feign/pom.xml index b5af225..e50cbbf 100644 --- a/buggy-feign/pom.xml +++ b/buggy-feign/pom.xml @@ -1,6 +1,6 @@ - 4.0.0 @@ -38,16 +38,6 @@ buggy-core test-jar - - org.apache.logging.log4j - log4j-slf4j-impl - test - - - org.apache.logging.log4j - log4j-1.2-api - test - \ No newline at end of file diff --git a/buggy-feign/src/main/java/org/touchbit/buggy/feign/FeignCURLLoggingInterceptor.java b/buggy-feign/src/main/java/org/touchbit/buggy/feign/FeignCURLLoggingInterceptor.java index 51deb2e..4616ed6 100644 --- a/buggy-feign/src/main/java/org/touchbit/buggy/feign/FeignCURLLoggingInterceptor.java +++ b/buggy-feign/src/main/java/org/touchbit/buggy/feign/FeignCURLLoggingInterceptor.java @@ -20,7 +20,7 @@ import feign.RequestTemplate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.touchbit.buggy.core.transport.interceptor.CURLLoggingInterceptor; +import org.touchbit.buggy.core.transport.CURLLoggingInterceptor; import java.nio.charset.StandardCharsets; import java.util.Collection; @@ -33,7 +33,7 @@ */ public class FeignCURLLoggingInterceptor extends CURLLoggingInterceptor implements RequestInterceptor { - private String host; + private final String host; public FeignCURLLoggingInterceptor(final String host) { this(host, LoggerFactory.getLogger(FeignCURLLoggingInterceptor.class)); diff --git a/buggy-feign/src/test/java/org/touchbit/buggy/feign/FeignCURLLoggingInterceptorTests.java b/buggy-feign/src/test/java/org/touchbit/buggy/feign/FeignCURLLoggingInterceptorTests.java index 3efed64..74da36e 100644 --- a/buggy-feign/src/test/java/org/touchbit/buggy/feign/FeignCURLLoggingInterceptorTests.java +++ b/buggy-feign/src/test/java/org/touchbit/buggy/feign/FeignCURLLoggingInterceptorTests.java @@ -23,13 +23,14 @@ import org.touchbit.buggy.core.tests.BaseUnitTest; import java.nio.charset.Charset; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; import static feign.Request.HttpMethod.POST; -import static java.nio.charset.StandardCharsets.UTF_8; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.is; /** * Created by Oleg Shaburov on 13.10.2018 diff --git a/buggy-feign/src/test/java/org/touchbit/buggy/feign/FeignCallLoggerTests.java b/buggy-feign/src/test/java/org/touchbit/buggy/feign/FeignCallLoggerTests.java index 42d8d6e..4a7512d 100644 --- a/buggy-feign/src/test/java/org/touchbit/buggy/feign/FeignCallLoggerTests.java +++ b/buggy-feign/src/test/java/org/touchbit/buggy/feign/FeignCallLoggerTests.java @@ -5,9 +5,7 @@ import org.touchbit.buggy.core.tests.BaseUnitTest; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.empty; -import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.*; /** * Created by Oleg Shaburov on 13.10.2018 diff --git a/buggy-min-example/pom.xml b/buggy-min-example/pom.xml deleted file mode 100644 index 850b8ca..0000000 --- a/buggy-min-example/pom.xml +++ /dev/null @@ -1,49 +0,0 @@ - - - 4.0.0 - - - org.touchbit.buggy - buggy - 0.3.7 - - - buggy-min-example - Buggy minimal example - 0.3.7 - jar - - - true - org.touchbit:buggy-min-example - - - - - org.touchbit.buggy - buggy-core - - - org.touchbit.buggy - buggy-testrail - - - - - - - org.apache.maven.plugins - maven-shade-plugin - - - org.sonatype.plugins - nexus-staging-maven-plugin - - true - - - - - \ No newline at end of file diff --git a/buggy-min-example/src/main/java/org/touchbit/buggy/example/min/config/Config.java b/buggy-min-example/src/main/java/org/touchbit/buggy/example/min/config/Config.java deleted file mode 100644 index 2575284..0000000 --- a/buggy-min-example/src/main/java/org/touchbit/buggy/example/min/config/Config.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright © 2018 Shaburov Oleg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.touchbit.buggy.example.min.config; - -import org.touchbit.buggy.core.config.PrimaryConfig; -import org.touchbit.buggy.testrail.BaseTestRailConfig; - -/** - * Created by Oleg Shaburov on 18.09.2018 - * shaburov.o.a@gmail.com - */ -public class Config implements PrimaryConfig, BaseTestRailConfig { - - public Config() { - setPrintLogFile(true); - setPrintCause(true); - setPrintSuite(true); - BaseTestRailConfig.setTestRailHost("https://touchbit.org/testrail"); - BaseTestRailConfig.setLogin("automation@touchbit.org"); - BaseTestRailConfig.setPass("automation"); - } - -} diff --git a/buggy-min-example/src/main/java/org/touchbit/buggy/example/min/config/MinExampleSecondaryConfig.java b/buggy-min-example/src/main/java/org/touchbit/buggy/example/min/config/MinExampleSecondaryConfig.java deleted file mode 100644 index 35a1a2e..0000000 --- a/buggy-min-example/src/main/java/org/touchbit/buggy/example/min/config/MinExampleSecondaryConfig.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright © 2018 Shaburov Oleg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.touchbit.buggy.example.min.config; - -import com.beust.jcommander.Parameter; -import com.beust.jcommander.Parameters; -import org.touchbit.buggy.core.config.SecondaryConfig; - -import static org.touchbit.buggy.example.min.config.MinExampleSecondaryConfig.DefaultValues.*; - -/** - * Created by Oleg Shaburov on 02.09.2018 - * shaburov.o.a@gmail.com - */ -@Parameters(commandNames = {"with"}, commandDescription = "secondary config") -public class MinExampleSecondaryConfig implements SecondaryConfig { - - @SuppressWarnings("WeakerAccess") - protected static class DefaultValues { - protected static final String WRITE_TIMEOUT = "--write-timeout"; - protected static final String READ_TIMEOUT = "--read-timeout"; - protected static final String CONNECTION_TIMEOUT = "--connection-timeout"; - - private static int readTimeout = 10; - private static int writeTimeout = 10; - private static int connectionTimeout = 10; - - private DefaultValues() { - throw new IllegalStateException("Utility class. Prohibit instantiation."); - } - } - - @Parameter(names = {READ_TIMEOUT}, description = "Read timeout for response") - public static void setReadTimeout(int readTimeout) { - DefaultValues.readTimeout = readTimeout; - } - - public static int getReadTimeout() { - return DefaultValues.readTimeout; - } - - @Parameter(names = {WRITE_TIMEOUT}, description = "Write timeout for request") - public static void setWriteTimeout(int writeTimeout) { - DefaultValues.writeTimeout = writeTimeout; - } - - public static int getWriteTimeout() { - return DefaultValues.writeTimeout; - } - - @Parameter(names = {CONNECTION_TIMEOUT}, description = "Connection timeout for request") - public static void setConnectionTimeout(int writeTimeout) { - DefaultValues.connectionTimeout = writeTimeout; - } - - public static int getConnectionTimeout() { - return DefaultValues.connectionTimeout; - } - - @Override - public String toString() { - return WRITE_TIMEOUT + " = " + DefaultValues.writeTimeout + "\n" + - READ_TIMEOUT + " = " + DefaultValues.readTimeout + "\n" + - CONNECTION_TIMEOUT + " = " + DefaultValues.connectionTimeout + "\n"; - } - -} diff --git a/buggy-min-example/src/main/java/org/touchbit/buggy/example/min/listeners/StatusMap.java b/buggy-min-example/src/main/java/org/touchbit/buggy/example/min/listeners/StatusMap.java deleted file mode 100644 index 4110f87..0000000 --- a/buggy-min-example/src/main/java/org/touchbit/buggy/example/min/listeners/StatusMap.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.touchbit.buggy.example.min.listeners; - -import org.touchbit.buggy.core.exceptions.BuggyConfigurationException; -import org.touchbit.buggy.core.model.Status; -import org.touchbit.buggy.testrail.StatusMapper; -import org.touchbit.testrail4j.core.type.Statuses; - -/** - * Created by Oleg Shaburov on 12.01.2019 - * shaburov.o.a@gmail.com - */ -public class StatusMap implements StatusMapper { - - @Override - public long getId(Status status) { - switch (status) { - case SUCCESS: return Statuses.PASSED.getId(); - case BLOCKED: return Statuses.BLOCKED.getId(); - case UNTESTED: return Statuses.UNTESTED.getId(); - case FAILED: return Statuses.FAILED.getId(); - case FIXED: return Statuses.CUSTOM_STATUS1.getId(); - case IMPLEMENTED: return Statuses.CUSTOM_STATUS2.getId(); - case CORRUPTED: return Statuses.CUSTOM_STATUS3.getId(); - case EXP_FIX: return Statuses.CUSTOM_STATUS4.getId(); - case SKIP: return Statuses.CUSTOM_STATUS5.getId(); - case EXP_IMPL: return Statuses.CUSTOM_STATUS6.getId(); - default: - throw new BuggyConfigurationException("Unhandled status received: " + status); - } - } - -} diff --git a/buggy-min-example/src/main/java/org/touchbit/buggy/example/min/listeners/TestRailListener.java b/buggy-min-example/src/main/java/org/touchbit/buggy/example/min/listeners/TestRailListener.java deleted file mode 100644 index 8841e14..0000000 --- a/buggy-min-example/src/main/java/org/touchbit/buggy/example/min/listeners/TestRailListener.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.touchbit.buggy.example.min.listeners; - -import org.touchbit.buggy.testrail.listeners.DefaultTestRailListener; - -/** - * Created by Oleg Shaburov on 12.01.2019 - * shaburov.o.a@gmail.com - */ -public class TestRailListener extends DefaultTestRailListener { - - public TestRailListener() { - super(new StatusMap()); - } - -} diff --git a/buggy-min-example/src/main/java/org/touchbit/buggy/example/min/tests/BaseTest.java b/buggy-min-example/src/main/java/org/touchbit/buggy/example/min/tests/BaseTest.java deleted file mode 100644 index 411b740..0000000 --- a/buggy-min-example/src/main/java/org/touchbit/buggy/example/min/tests/BaseTest.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.touchbit.buggy.example.min.tests; - -import org.touchbit.buggy.core.test.BaseBuggyTest; - -/** - * Created by Oleg Shaburov on 12.01.2019 - * shaburov.o.a@gmail.com - */ -public class BaseTest extends BaseBuggyTest { - - @Override - public long getRunId() { - return 1; - } - -} diff --git a/buggy-min-example/src/main/java/org/touchbit/buggy/example/min/tests/GitLabTests.java b/buggy-min-example/src/main/java/org/touchbit/buggy/example/min/tests/GitLabTests.java deleted file mode 100644 index 2eee1ce..0000000 --- a/buggy-min-example/src/main/java/org/touchbit/buggy/example/min/tests/GitLabTests.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright © 2018 Shaburov Oleg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.touchbit.buggy.example.min.tests; - -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.touchbit.buggy.core.exceptions.BuggyException; -import org.touchbit.buggy.core.model.Details; -import org.touchbit.buggy.core.model.Status; -import org.touchbit.buggy.core.model.Suite; -import org.touchbit.buggy.example.min.goals.API; -import org.touchbit.buggy.example.min.goals.GitLab; - -/** - * Created by Oleg Shaburov on 18.09.2018 - * shaburov.o.a@gmail.com - */ -@Suite(service = GitLab.class, interfaze = API.class, task = "common") -@SuppressWarnings("squid:S00100") -public class GitLabTests extends BaseTest { - - private static final String DO_SOMETHING = "do something"; - private static final String EXAMPLE_STEP = "Example step"; - - @BeforeClass(description = "Example description for configuration method") - public void beforeClassConfigurationMethod() { - step("Prepare domain"); - log.info(DO_SOMETHING); - step("Prepare company"); - log.info(DO_SOMETHING); - step("Prepare admin account"); - log.info(DO_SOMETHING); - } - - @Test(description = "Example success test with CORRUPTED status") - @Details(id = 86, bug = "QA-100", status = Status.CORRUPTED) - public void test_20180918045754() { - step(EXAMPLE_STEP); - log.info(DO_SOMETHING); - } - - @Test(description = "Example fail test with CORRUPTED status") - @Details(id = 87, bug = "QA-100", status = Status.CORRUPTED) - public void test_20180918045755() { - step(EXAMPLE_STEP); - log.info(DO_SOMETHING); - throw new BuggyException("Example CORRUPTED exception"); - } - - @Test(description = "Example success test with EXP_FIX status") - @Details(id = 88, bug = "DF-485", status = Status.EXP_FIX) - public void test_20181021232500() { - step(EXAMPLE_STEP); - log.info(DO_SOMETHING); - } - - @Test(description = "Example fail test with EXP_FIX status") - @Details(id = 89, bug = "DF-485", status = Status.EXP_FIX) - public void test_20181021232518() { - step(EXAMPLE_STEP); - log.info(DO_SOMETHING); - throw new BuggyException("Example EXP_FIX exception"); - } - - @Test(description = "Example success test with EXP_IMPL status") - @Details(id = 90, bug = "AD-144", status = Status.EXP_IMPL) - public void test_20181021232522() { - step(EXAMPLE_STEP); - log.info(DO_SOMETHING); - } - - @Test(description = "Example fail test with EXP_IMPL status") - @Details(id = 91, bug = "AD-144", status = Status.EXP_IMPL) - public void test_20181021232527() { - step(EXAMPLE_STEP); - log.info(DO_SOMETHING); - throw new BuggyException("Example EXP_IMPL exception"); - } - - @Test(description = "Example success test with BLOCKED status") - @Details(id = 92, bug = "INFRA-581", status = Status.BLOCKED) - public void test_20181021232530() { - step(EXAMPLE_STEP); - log.info(DO_SOMETHING); - } - - @Test(description = "Example fail test with BLOCKED status") - @Details(id = 93, bug = "INFRA-581", status = Status.BLOCKED) - public void test_20181021232745() { - step(EXAMPLE_STEP); - log.info(DO_SOMETHING); - throw new BuggyException("Example BLOCKED exception"); - } - - @Test(description = "Example success test") - @Details(id = 94) - public void test_20181021232749() { - step(EXAMPLE_STEP); - log.info(DO_SOMETHING); - } - - @Test(description = "Example fail test") - @Details(id = 95) - public void test_20181021232400() { - step(EXAMPLE_STEP); - log.info(DO_SOMETHING); - throw new BuggyException("Example fail test"); - } - -} diff --git a/buggy-okhttp/pom.xml b/buggy-okhttp/pom.xml index 34eb57c..40b6c4c 100644 --- a/buggy-okhttp/pom.xml +++ b/buggy-okhttp/pom.xml @@ -1,6 +1,6 @@ - 4.0.0 @@ -41,16 +41,6 @@ buggy-core test-jar - - org.apache.logging.log4j - log4j-slf4j-impl - test - - - org.apache.logging.log4j - log4j-1.2-api - test - \ No newline at end of file diff --git a/buggy-okhttp/src/main/java/org/touchbit/buggy/okhttp/OkHttpCURLLoggingInterceptor.java b/buggy-okhttp/src/main/java/org/touchbit/buggy/okhttp/OkHttpCURLLoggingInterceptor.java index 4264359..1d9e94e 100644 --- a/buggy-okhttp/src/main/java/org/touchbit/buggy/okhttp/OkHttpCURLLoggingInterceptor.java +++ b/buggy-okhttp/src/main/java/org/touchbit/buggy/okhttp/OkHttpCURLLoggingInterceptor.java @@ -22,7 +22,7 @@ import okio.Buffer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.touchbit.buggy.core.transport.interceptor.CURLLoggingInterceptor; +import org.touchbit.buggy.core.transport.CURLLoggingInterceptor; import java.io.IOException; import java.nio.charset.Charset; @@ -60,7 +60,7 @@ public Response intercept(final Chain chain) throws IOException { } private String bodyToString(final Request request) throws IOException { - try (final Buffer buffer = new Buffer()){ + try (final Buffer buffer = new Buffer()) { if (request.body() == null) { return null; } diff --git a/buggy-okhttp/src/main/java/org/touchbit/buggy/okhttp/OkHttpCallLoggingInterceptor.java b/buggy-okhttp/src/main/java/org/touchbit/buggy/okhttp/OkHttpCallLoggingInterceptor.java index 8b3b8cf..d97bc55 100644 --- a/buggy-okhttp/src/main/java/org/touchbit/buggy/okhttp/OkHttpCallLoggingInterceptor.java +++ b/buggy-okhttp/src/main/java/org/touchbit/buggy/okhttp/OkHttpCallLoggingInterceptor.java @@ -28,7 +28,7 @@ public OkHttpCallLoggingInterceptor(final Logger logger) { public OkHttpCallLoggingInterceptor(final Consumer logMethod) { this.logMethod = logMethod; } - + @NotNull @Override public Response intercept(Chain chain) throws IOException { diff --git a/buggy-okhttp/src/test/java/org/touchbit/buggy/okhttp/CURLLoggingInterceptorTests.java b/buggy-okhttp/src/test/java/org/touchbit/buggy/okhttp/CURLLoggingInterceptorTests.java index 94101f6..a60bb85 100644 --- a/buggy-okhttp/src/test/java/org/touchbit/buggy/okhttp/CURLLoggingInterceptorTests.java +++ b/buggy-okhttp/src/test/java/org/touchbit/buggy/okhttp/CURLLoggingInterceptorTests.java @@ -16,7 +16,9 @@ package org.touchbit.buggy.okhttp; -import okhttp3.*; +import okhttp3.Interceptor; +import okhttp3.Request; +import okhttp3.RequestBody; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.touchbit.buggy.core.tests.BaseUnitTest; diff --git a/buggy-okhttp/src/test/java/org/touchbit/buggy/okhttp/OkHttpCallLoggingInterceptorTests.java b/buggy-okhttp/src/test/java/org/touchbit/buggy/okhttp/OkHttpCallLoggingInterceptorTests.java index f40eb41..7e6dfce 100644 --- a/buggy-okhttp/src/test/java/org/touchbit/buggy/okhttp/OkHttpCallLoggingInterceptorTests.java +++ b/buggy-okhttp/src/test/java/org/touchbit/buggy/okhttp/OkHttpCallLoggingInterceptorTests.java @@ -1,11 +1,13 @@ package org.touchbit.buggy.okhttp; -import okhttp3.*; +import okhttp3.Interceptor; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; import okhttp3.internal.http.RealResponseBody; +import okio.Buffer; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; - -import okio.Buffer; import org.touchbit.buggy.core.tests.BaseUnitTest; import static okhttp3.Protocol.HTTP_1_1; diff --git a/buggy-spring-boot-starter-example/pom.xml b/buggy-spring-boot-starter-example/pom.xml new file mode 100644 index 0000000..51b2afb --- /dev/null +++ b/buggy-spring-boot-starter-example/pom.xml @@ -0,0 +1,54 @@ + + + 4.0.0 + + + org.touchbit.buggy + buggy + 0.3.7 + + + buggy-spring-boot-starter-example + Buggy SB starter + Buggy spring boot starter + 0.3.7 + jar + + + org.touchbit.buggy.spring.boot.starter.example.ExampleBuggyRunner + Buggy + + + + + org.touchbit.buggy + buggy-spring-boot-starter + 0.3.7 + compile + + + + + + + org.springframework.boot + spring-boot-maven-plugin + 2.3.4.RELEASE + + true + ${jar.final.name} + ${jar.main.class} + + + + + repackage + + + + + + + \ No newline at end of file diff --git a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleBuggyRunner.java b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleBuggyRunner.java new file mode 100644 index 0000000..75e464c --- /dev/null +++ b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleBuggyRunner.java @@ -0,0 +1,20 @@ +package org.touchbit.buggy.spring.boot.starter.example; + +import org.springframework.boot.SpringApplication; +import org.touchbit.buggy.core.goal.interfaze.API; +import org.touchbit.buggy.spring.boot.starter.BuggyRunner; +import org.touchbit.buggy.spring.boot.starter.jcommander.BuggyConfiguration; + +import static org.touchbit.buggy.core.model.Type.REGRESSION; + +public class ExampleBuggyRunner extends BuggyRunner { + + public static void main(String[] args) { + BuggyConfiguration.setForce(true); + BuggyConfiguration.setInterfaces(API.class); + BuggyConfiguration.setTypes(REGRESSION); + BuggyConfiguration.setIssuesUrl("https://jira.com/issues/"); + SpringApplication.run(ExampleBuggyRunner.class, args); + } + +} diff --git a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/conf/ExampleConfiguration.java b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/conf/ExampleConfiguration.java new file mode 100644 index 0000000..e3dd03a --- /dev/null +++ b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/conf/ExampleConfiguration.java @@ -0,0 +1,30 @@ +package org.touchbit.buggy.spring.boot.starter.example.conf; + +import com.beust.jcommander.Parameter; +import org.touchbit.buggy.core.config.JCommand; + +public class ExampleConfiguration implements JCommand { + + @Parameter(names = {"--example-host"}, description = "Example host.") + private static String exampleHost = "https://exmaole.com"; + + @Parameter(names = {"--example-pass"}, password = true, description = "Example password.") + private static String examplePass = "pass"; + + public static String getExampleHost() { + return exampleHost; + } + + public static void setExampleHost(String exampleHost) { + ExampleConfiguration.exampleHost = exampleHost; + } + + public static String getExamplePass() { + return examplePass; + } + + public static void setExamplePass(String examplePass) { + ExampleConfiguration.examplePass = examplePass; + } + +} diff --git a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/goal/Actions.java b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/goal/Actions.java new file mode 100644 index 0000000..19353eb --- /dev/null +++ b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/goal/Actions.java @@ -0,0 +1,12 @@ +package org.touchbit.buggy.spring.boot.starter.example.goal; + +import org.touchbit.buggy.core.goal.service.Service; + +public class Actions extends Service { + + @Override + public String getDescription() { + return "Github CI/CD actions service."; + } + +} diff --git a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/goal/GitHub.java b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/goal/GitHub.java new file mode 100644 index 0000000..8115d66 --- /dev/null +++ b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/goal/GitHub.java @@ -0,0 +1,7 @@ +package org.touchbit.buggy.spring.boot.starter.example.goal; + +import org.touchbit.buggy.core.goal.component.Component; + +public class GitHub extends Component { + +} diff --git a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/tests/ExampleTests.java b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/tests/ExampleTests.java new file mode 100644 index 0000000..28732a0 --- /dev/null +++ b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/tests/ExampleTests.java @@ -0,0 +1,21 @@ +package org.touchbit.buggy.spring.boot.starter.example.tests; + +import org.testng.annotations.Test; +import org.touchbit.buggy.core.BaseBuggyTest; +import org.touchbit.buggy.core.goal.interfaze.API; +import org.touchbit.buggy.core.goal.interfaze.WEB; +import org.touchbit.buggy.core.model.Buggy; +import org.touchbit.buggy.core.model.Suite; +import org.touchbit.buggy.spring.boot.starter.example.goal.Actions; +import org.touchbit.buggy.spring.boot.starter.example.goal.GitHub; + +@Suite(service = Actions.class, interfaze = WEB.class) +public class ExampleTests extends BaseBuggyTest { + + @Test + @Buggy + public void invocationCount_10() { + step("test_1"); + } + +} diff --git a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/tests/ExampleTests2.java b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/tests/ExampleTests2.java new file mode 100644 index 0000000..c1080e7 --- /dev/null +++ b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/tests/ExampleTests2.java @@ -0,0 +1,56 @@ +package org.touchbit.buggy.spring.boot.starter.example.tests; + +import org.testng.annotations.Test; +import org.touchbit.buggy.core.BaseBuggyTest; +import org.touchbit.buggy.core.exceptions.AssertionException; +import org.touchbit.buggy.core.goal.interfaze.API; +import org.touchbit.buggy.core.model.Buggy; +import org.touchbit.buggy.core.model.Status; +import org.touchbit.buggy.core.model.Suite; +import org.touchbit.buggy.spring.boot.starter.example.goal.GitHub; + +import java.util.UUID; + +import static org.touchbit.buggy.core.model.Type.SYSTEM; + +@Suite(component = GitHub.class, interfaze = API.class) +public class ExampleTests2 extends BaseBuggyTest { + + @Test + @Buggy() + public void test1603008938585() { + + } + + @Test(description = "Ожидается успешное создание пользователя, если firstName=<пустая строка>") + @Buggy(status = Status.EXP_FIX, bugs = "JIRA-123") + public void test_2_1() { + String id = UUID.randomUUID().toString(); + step("Create user account: id={}", id); + step("Activate user account: id={}", id); + throw new AssertionException("The following 4 assertions failed:\n" + + " 1) [Living Guests] expected:<[7]> but was:<[6]>\n" + + " 2) [Library] expected:<'[clean]'> but was:<'[messy]'>\n" + + " 3) [Candlestick] expected:<'[pristine]'> but was:<'[bent]'>\n" + + " 4) [Professor] expected:<'[well kempt]'> but was:<'[bloodied and dishevelled]'>"); + } + + @Test() + @Buggy("Ожидается успешное создание пользователя, если middleName=<пустая строка>") + public void test_2_2() { + + } + + @Test(enabled = false) + @Buggy("Ожидается успешное создание пользователя, если email=<пустая строка>") + public void test_2_3() { + + } + + @Test() + @Buggy(value = "Ожидается успешное создание пользователя, если email=<пустая строка>", types = SYSTEM) + public void test_2_4() { + + } + +} diff --git a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/tests/ExampleTests3.java b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/tests/ExampleTests3.java new file mode 100644 index 0000000..1eb5ffb --- /dev/null +++ b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/tests/ExampleTests3.java @@ -0,0 +1,28 @@ +package org.touchbit.buggy.spring.boot.starter.example.tests; + +import org.testng.annotations.Test; +import org.touchbit.buggy.core.goal.interfaze.API; +import org.touchbit.buggy.core.model.Buggy; +import org.touchbit.buggy.core.model.Status; +import org.touchbit.buggy.core.model.Suite; + +import java.net.ProtocolException; + +import static org.touchbit.buggy.core.model.Status.CORRUPTED; + +@Suite(interfaze = API.class) +public class ExampleTests3 { + + @Test + @Buggy(status = CORRUPTED) + public void test_3_1() throws Exception { + throw new ProtocolException("Received HTTP_PROXY_AUTH (407) code while not using proxy"); + } + + @Test + @Buggy(status = Status.BLOCKED, bugs = "JIRA-321") + public void test_3_2() { + + } + +} diff --git a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/tests/WebTests.java b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/tests/WebTests.java new file mode 100644 index 0000000..e5eb268 --- /dev/null +++ b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/tests/WebTests.java @@ -0,0 +1,21 @@ +package org.touchbit.buggy.spring.boot.starter.example.tests; + +import org.testng.annotations.Test; +import org.touchbit.buggy.core.BaseBuggyTest; +import org.touchbit.buggy.core.goal.interfaze.WEB; +import org.touchbit.buggy.core.model.Buggy; +import org.touchbit.buggy.core.model.Suite; +import org.touchbit.buggy.spring.boot.starter.example.goal.Actions; +import org.touchbit.buggy.spring.boot.starter.example.goal.GitHub; + +@Suite(service = Actions.class, interfaze = WEB.class) +public class WebTests extends BaseBuggyTest { + + @Test + @Buggy("Ожидается успешная авторизация в админке сужествующего, активного пользователя с правами администратора.") + public void webTest1() { + step("webTest1"); + } + + +} diff --git a/buggy-spring-boot-starter-example/src/main/resources/buggy-config.yml b/buggy-spring-boot-starter-example/src/main/resources/buggy-config.yml new file mode 100644 index 0000000..777d575 --- /dev/null +++ b/buggy-spring-boot-starter-example/src/main/resources/buggy-config.yml @@ -0,0 +1,22 @@ +programName: 'Buggy example' +help: false +forceRun: true +threads: 50 +parallelMode: 'METHODS' +artifactsUrl: null +components: + - !!org.touchbit.buggy.core.goal.component.AllComponents {} +services: + - !!org.touchbit.buggy.core.goal.service.AllServices {} +interfaces: + - !!org.touchbit.buggy.core.goal.interfaze.AllInterfaces {} +types: + - ALL +issuesUrl: 'https://example.jira.com/issues/' +testCaseTitle: true +testSuiteInfo: false +testLogFilePath: true +testIssuesInfo: false +testBugsInfo: true +testErrorInfo: true +outputRule: UNSUCCESSFUL diff --git a/buggy-spring-boot-starter/pom.xml b/buggy-spring-boot-starter/pom.xml new file mode 100644 index 0000000..b7f9eed --- /dev/null +++ b/buggy-spring-boot-starter/pom.xml @@ -0,0 +1,61 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 2.3.4.RELEASE + + + + org.touchbit.buggy + buggy-spring-boot-starter + Buggy SB starter + Buggy spring boot starter + 0.3.7 + jar + + + org.touchbit:buggy-spring-boot-starter + + + + + org.touchbit.buggy + buggy-core + 0.3.7 + compile + + + org.touchbit.buggy + buggy-testng-listeners + 0.3.7 + compile + + + org.springframework.boot + spring-boot-starter-validation + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-starter-logging + + + org.springframework.boot + spring-boot-configuration-processor + true + + + org.springframework.boot + spring-boot-starter-test + test + + + \ No newline at end of file diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/BuggyRunner.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/BuggyRunner.java new file mode 100644 index 0000000..05af7d0 --- /dev/null +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/BuggyRunner.java @@ -0,0 +1,299 @@ +package org.touchbit.buggy.spring.boot.starter; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.testng.TestNG; +import org.testng.xml.XmlClass; +import org.testng.xml.XmlSuite; +import org.testng.xml.XmlTest; +import org.touchbit.buggy.core.config.BuggyConfigurationYML; +import org.touchbit.buggy.core.goal.Goal; +import org.touchbit.buggy.core.goal.component.Component; +import org.touchbit.buggy.core.goal.interfaze.Interface; +import org.touchbit.buggy.core.goal.service.Service; +import org.touchbit.buggy.core.logback.ConfLogger; +import org.touchbit.buggy.core.logback.FrameworkLogger; +import org.touchbit.buggy.core.logback.appender.SiftingFileAppender; +import org.touchbit.buggy.core.model.Suite; +import org.touchbit.buggy.core.testng.BuggyListener; +import org.touchbit.buggy.core.utils.JUtils; +import org.touchbit.buggy.spring.boot.starter.jcommander.BuggyConfiguration; + +import java.io.File; +import java.util.*; + +import static org.springframework.boot.context.logging.LoggingApplicationListener.CONFIG_PROPERTY; +import static org.springframework.boot.logging.LogFile.FILE_PATH_PROPERTY; +import static org.touchbit.buggy.spring.boot.starter.conf.Qualifiers.*; + +@SpringBootApplication +public class BuggyRunner implements CommandLineRunner { + + static { + if (JUtils.isJetBrainsIdeConsoleRun()) { + System.setProperty(FILE_PATH_PROPERTY, JUtils.getJetBrainsIdeConsoleRunTargetPath() + "/logs"); + } + // If application.yml does not contain a variable 'logging.config' + System.setProperty(CONFIG_PROPERTY, "classpath:buggy-logback.xml"); + } + + private Set allBuggyListeners; + private Set enabledBuggyListeners; + private Set> allTestClasses; + private Set> filteredTestClasses; + private Set allGoals; + private Set allComponents; + private Set availableComponents; + private Set allServices; + private Set availableServices; + private Set allInterfaces; + private Set availableInterfaces; + private TestNG testNG = new TestNG(); + + public static void exit(String message, Exception e) { + if (e != null) { + exit(1, message, e); + } else { + exit(0, message); + } + } + + public static void exit(int status) { + exit(status, null, null); + } + + public static void exit(int status, String message) { + exit(status, message, null); + } + + public static void exit(int status, String message, Exception e) { + if (message != null || e != null) { + ConfLogger.blockDelimiter(); + String frameworkLogPath = ""; + if (status == 0) { + if (message != null) { + ConfLogger.info(message); + } + } else { + File file = FrameworkLogger.getLogFile(); + if (file != null) { + frameworkLogPath = "\nFor more information see " + file.getName(); + } + if (e != null) { + String exMsg = e.getMessage(); + if (message != null) { + message += "\n" + e.getClass().getSimpleName() + ": " + (exMsg == null ? "" : exMsg); + } else { + message = e.getClass().getSimpleName() + ": " + (exMsg == null ? "" : exMsg); + } + } + ConfLogger.error(message + frameworkLogPath, e); + } + } + ConfLogger.blockDelimiter(); + ConfLogger.dotPlaceholder("Exit code", status); + ConfLogger.blockDelimiter(); + System.exit(status); + } + + @Override + public void run(String... args) { + try { + if (filteredTestClasses.isEmpty()) { + BuggyRunner.exit(1, "No test classes found for the current configuration"); + } + Map>> testClassesBySuitesMap = getTestClassesBySuitesMap(filteredTestClasses); + List xmlSuites = getXmlSuites(testClassesBySuitesMap); + if (xmlSuites.isEmpty()) { + exit(1, "No test suites found for the current configuration."); + } else { + ConfLogger.center("Suites"); + for (XmlSuite xmlSuite : xmlSuites) { + ConfLogger.info(xmlSuite.getName()); + } + } + TestNG testNG = getTestNG(); + testNG.setParallel(BuggyConfigurationYML.getParallelMode().getTestNGMode()); + testNG.setSuiteThreadPoolSize(xmlSuites.isEmpty() ? 1 : xmlSuites.size()); + testNG.setUseDefaultListeners(false); + for (BuggyListener enabledBuggyListener : enabledBuggyListeners) { + testNG.addListener(enabledBuggyListener); + } + testNG.setXmlSuites(xmlSuites); + ConfLogger.blockDelimiter(); + testNG.run(); + SiftingFileAppender.decomposeTestLogs(); + if (BuggyConfiguration.getExitStatus() != null) { + exit(BuggyConfiguration.getExitStatus()); + } + exit(testNG.getStatus()); + } catch (Exception e) { + exit(1, "TestNG safely died.", e); + } finally { + SiftingFileAppender.decomposeTestLogs(); + } + } + + public Map>> getTestClassesBySuitesMap(Set> testClasses) { + Map>> result = new HashMap<>(); + for (Class testClass : testClasses) { + if (testClass.isAnnotationPresent(Suite.class)) { + Suite suite = testClass.getAnnotation(Suite.class); + if (result.containsKey(suite)) { + result.get(suite).add(testClass); + } else { + Set> set = new LinkedHashSet<>(); + set.add(testClass); + result.put(suite, set); + } + } + } + return result; + } + + public List getXmlSuites(Map>> buggySuitesTests) { + List suites = new ArrayList<>(); + for (Map.Entry>> entry : buggySuitesTests.entrySet()) { + XmlSuite xmlSuite = new XmlSuite(); + xmlSuite.setParallel(BuggyConfigurationYML.getParallelMode().getTestNGMode()); + xmlSuite.setThreadCount(BuggyConfigurationYML.getThreads()); + Suite buggySuite = entry.getKey(); + try { + Component cGoal = JUtils.getGoal(Suite::component, buggySuite); + Service sGoal = JUtils.getGoal(Suite::service, buggySuite); + Interface iGoal = JUtils.getGoal(Suite::interfaze, buggySuite); + xmlSuite.setName(cGoal.getName() + " " + sGoal.getName() + " " + iGoal.getName() + " suite"); + } catch (Exception e) { + exit(1, "Failed to generate TestNG XmlSuite list", e); + } + XmlTest testPackage = new XmlTest(xmlSuite); + testPackage.setName(UUID.randomUUID().toString()); + for (Class testClass : entry.getValue()) { + XmlClass xmlClass = new XmlClass(testClass); + testPackage.getXmlClasses().add(xmlClass); + } + suites.add(xmlSuite); + } + return suites; + } + + public TestNG getTestNG() { + return testNG; + } + + public void setTestNG(TestNG testNG) { + this.testNG = testNG; + } + + public Set getAllBuggyListeners() { + return allBuggyListeners; + } + + @Autowired() + @Qualifier(ALL_BUGGY_LISTENERS) + public void setAllBuggyListeners(Set allBuggyListeners) { + this.allBuggyListeners = allBuggyListeners; + } + + public Set getEnabledBuggyListeners() { + return enabledBuggyListeners; + } + + @Autowired() + @Qualifier(ENABLED_BUGGY_LISTENERS) + public void setEnabledBuggyListeners(Set enabledBuggyListeners) { + this.enabledBuggyListeners = enabledBuggyListeners; + } + + public Set> getAllTestClasses() { + return allTestClasses; + } + + @Autowired() + @Qualifier(ALL_BUGGY_TEST_CLASSES) + public void setAllTestClasses(Set> allTestClasses) { + this.allTestClasses = allTestClasses; + } + + public Set> getFilteredTestClasses() { + return filteredTestClasses; + } + + @Autowired() + @Qualifier(FILTERED_BUGGY_TEST_CLASSES) + public void setFilteredTestClasses(Set> filteredTestClasses) { + this.filteredTestClasses = filteredTestClasses; + } + + public Set getAllGoals() { + return allGoals; + } + + @Autowired() + @Qualifier(ALL_BUGGY_GOALS) + public void setAllGoals(Set allGoals) { + this.allGoals = allGoals; + } + + public Set getAllComponents() { + return allComponents; + } + + @Autowired() + @Qualifier(ALL_BUGGY_COMPONENTS) + public void setAllComponents(Set allComponents) { + this.allComponents = allComponents; + } + + public Set getAvailableComponents() { + return availableComponents; + } + + @Autowired() + @Qualifier(AVAILABLE_BUGGY_COMPONENTS) + public void setAvailableComponents(Set availableComponents) { + this.availableComponents = availableComponents; + } + + public Set getAllServices() { + return allServices; + } + + @Autowired() + @Qualifier(ALL_BUGGY_SERVICES) + public void setAllServices(Set allServices) { + this.allServices = allServices; + } + + public Set getAvailableServices() { + return availableServices; + } + + @Autowired() + @Qualifier(AVAILABLE_BUGGY_SERVICES) + public void setAvailableServices(Set availableServices) { + this.availableServices = availableServices; + } + + public Set getAllInterfaces() { + return allInterfaces; + } + + @Autowired() + @Qualifier(ALL_BUGGY_INTERFACES) + public void setAllInterfaces(Set allInterfaces) { + this.allInterfaces = allInterfaces; + } + + public Set getAvailableInterfaces() { + return availableInterfaces; + } + + @Autowired() + @Qualifier(AVAILABLE_BUGGY_INTERFACES) + public void setAvailableInterfaces(Set availableInterfaces) { + this.availableInterfaces = availableInterfaces; + } +} diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/ApplicationProperties.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/ApplicationProperties.java new file mode 100644 index 0000000..ca1b05a --- /dev/null +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/ApplicationProperties.java @@ -0,0 +1,56 @@ +package org.touchbit.buggy.spring.boot.starter.conf; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +import java.util.ArrayList; +import java.util.List; + +@ConfigurationProperties("buggy") +public class ApplicationProperties { + + private static final String BASE_BUGGY_SCAN_PACKAGE = "**.buggy"; + private List commandsScannerBasePackages = new ArrayList<>(); + private List goalsScannerBasePackages = new ArrayList<>(); + private List suitesScannerBasePackages = new ArrayList<>(); + private List listenersScannerBasePackages = new ArrayList<>(); + + public ApplicationProperties() { + commandsScannerBasePackages.add(BASE_BUGGY_SCAN_PACKAGE); + goalsScannerBasePackages.add(BASE_BUGGY_SCAN_PACKAGE); + suitesScannerBasePackages.add(BASE_BUGGY_SCAN_PACKAGE); + listenersScannerBasePackages.add(BASE_BUGGY_SCAN_PACKAGE); + } + + public List getCommandsScannerBasePackages() { + return commandsScannerBasePackages; + } + + public void setCommandsScannerBasePackages(List commandsScannerBasePackages) { + this.commandsScannerBasePackages = commandsScannerBasePackages; + } + + public List getGoalsScannerBasePackages() { + return goalsScannerBasePackages; + } + + public void setGoalsScannerBasePackages(List goalsScannerBasePackages) { + this.goalsScannerBasePackages = goalsScannerBasePackages; + } + + public List getSuitesScannerBasePackages() { + return suitesScannerBasePackages; + } + + public void setSuitesScannerBasePackages(List suitesScannerBasePackages) { + this.suitesScannerBasePackages = suitesScannerBasePackages; + } + + public List getListenersScannerBasePackages() { + return listenersScannerBasePackages; + } + + public void setListenersScannerBasePackages(List listenersScannerBasePackages) { + this.listenersScannerBasePackages = listenersScannerBasePackages; + } + +} diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/BuggyRunnerConfiguration.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/BuggyRunnerConfiguration.java new file mode 100644 index 0000000..1e19b78 --- /dev/null +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/BuggyRunnerConfiguration.java @@ -0,0 +1,265 @@ +package org.touchbit.buggy.spring.boot.starter.conf; + +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.boot.autoconfigure.condition.ConditionalOnNotWebApplication; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.touchbit.buggy.core.config.BuggyConfigurationYML; +import org.touchbit.buggy.core.goal.Goal; +import org.touchbit.buggy.core.goal.component.AllComponents; +import org.touchbit.buggy.core.goal.component.Component; +import org.touchbit.buggy.core.goal.interfaze.AllInterfaces; +import org.touchbit.buggy.core.goal.interfaze.Interface; +import org.touchbit.buggy.core.goal.service.AllServices; +import org.touchbit.buggy.core.goal.service.Service; +import org.touchbit.buggy.core.logback.ConfLogger; +import org.touchbit.buggy.core.model.Suite; +import org.touchbit.buggy.core.testng.BuggyListener; +import org.touchbit.buggy.core.utils.JUtils; +import org.touchbit.buggy.spring.boot.starter.BuggyRunner; + +import javax.annotation.PostConstruct; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +import static org.touchbit.buggy.spring.boot.starter.conf.Qualifiers.*; + +/** + * TestNG configuration + * Filtering test classes for suites by: + * 1. {@link Component} + * 2. {@link Service} + * 3. {@link Interface} + *

+ * Created by Oleg Shaburov on 01.10.2020 + * shaburov.o.a@gmail.com + */ +@Configuration() +@ConditionalOnNotWebApplication +@EnableConfigurationProperties(ApplicationProperties.class) +public class BuggyRunnerConfiguration implements IConfiguration { + + private final ApplicationProperties properties; + private final Set allBuggyListeners; + private final Set enabledBuggyListeners; + private final Set> allTestClasses; + private final Set> filteredTestClasses; + private final Set allGoals; + private final Set allComponents; + private final Set availableComponents; + private final Set allServices; + private final Set availableServices; + private final Set allInterfaces; + private final Set availableInterfaces; + + public BuggyRunnerConfiguration(final boolean isLogbackConfigurationInitialized, final ApplicationProperties props) { + try { + beforeConfiguration(isLogbackConfigurationInitialized); + properties = props; + allBuggyListeners = scanTestNGListeners(); + enabledBuggyListeners = allBuggyListeners.stream().filter(BuggyListener::isEnable).collect(Collectors.toSet()); + allTestClasses = scanTestClassesWithSuiteAnnotation(); + filteredTestClasses = filterTestClassesByBuggyConfig(allTestClasses); + allGoals = scanGoals(); + allComponents = filterByGoalType(allGoals, BuggyConfigurationYML.getComponents(), Component.class, AllComponents.class); + availableComponents = filterComponentsByTestClasses(allComponents, filteredTestClasses); + allServices = filterByGoalType(allGoals, BuggyConfigurationYML.getComponents(), Service.class, AllServices.class); + availableServices = filterServiceByTestClasses(allServices, filteredTestClasses); + allInterfaces = filterByGoalType(allGoals, BuggyConfigurationYML.getComponents(), Interface.class, AllInterfaces.class); + availableInterfaces = filterInterfaceByTestClasses(allInterfaces, filteredTestClasses); + } catch (Exception e) { + BuggyRunner.exit("Error initializing Buggy config", e); + throw e; + } + } + + public void beforeConfiguration(final boolean isLogbackConfigurationInitialized) { + if (!isLogbackConfigurationInitialized) { + BuggyRunner.exit(1, "LogbackConfiguration must be initialized"); + } + ConfLogger.blockDelimiter(); + ConfLogger.centerBold("Preparing TestNG configuration"); + ConfLogger.stepDelimiter(); + } + + @PostConstruct + public void printConfigurationInfo() { + ConfLogger.center("Buggy listeners"); + for (BuggyListener buggyListener : allBuggyListeners) { + if (buggyListener.isEnable()) { + ConfLogger.dotPlaceholder(buggyListener.getClass().getSimpleName(), "Enable"); + } else { + ConfLogger.dotPlaceholder(buggyListener.getClass().getSimpleName(), "Disable"); + } + } + } + + public Set> filterTestClassesByBuggyConfig(Set> testClassesWithSuiteAnnotation) { + List> components = BuggyConfigurationYML.getComponents().stream() + .map(Component::getClass) + .collect(Collectors.toList()); + List> services = BuggyConfigurationYML.getServices().stream() + .map(Service::getClass) + .collect(Collectors.toList()); + List> interfaces = BuggyConfigurationYML.getInterfaces().stream() + .map(Interface::getClass) + .collect(Collectors.toList()); + return testClassesWithSuiteAnnotation.stream() + .filter(c -> components.contains(AllComponents.class) || + components.contains(c.getAnnotation(Suite.class).component())) + .filter(c -> services.contains(AllServices.class) || + services.contains(c.getAnnotation(Suite.class).service())) + .filter(c -> interfaces.contains(AllInterfaces.class) || + interfaces.contains(c.getAnnotation(Suite.class).interfaze())) + .collect(Collectors.toSet()); + } + + public Set filterComponentsByTestClasses(final Set components, + final Set> testClasses) { + List> testComponents = testClasses.stream() + .filter(c -> c.isAnnotationPresent(Suite.class)) + .map(c -> c.getAnnotation(Suite.class).component()) + .collect(Collectors.toList()); + return components.stream() + .filter(a -> testComponents.contains(a.getClass())) + .collect(Collectors.toSet()); + } + + public Set filterServiceByTestClasses(final Set services, + final Set> testClasses) { + List> tetServices = testClasses.stream() + .filter(c -> c.isAnnotationPresent(Suite.class)) + .map(c -> c.getAnnotation(Suite.class).service()) + .collect(Collectors.toList()); + return services.stream() + .filter(a -> tetServices.contains(a.getClass())) + .collect(Collectors.toSet()); + } + + public Set filterInterfaceByTestClasses(final Set interfaces, + final Set> testClasses) { + List> testInterfaces = testClasses.stream() + .filter(c -> c.isAnnotationPresent(Suite.class)) + .map(c -> c.getAnnotation(Suite.class).interfaze()) + .collect(Collectors.toList()); + return interfaces.stream() + .filter(a -> testInterfaces.contains(a.getClass())) + .collect(Collectors.toSet()); + } + + @SuppressWarnings("unchecked") + public Set filterByGoalType(final Set allGoals, + final List expectedGoals, + final Class goalFilter, + final Class allFilter) { + if (allGoals.stream().anyMatch(c -> c.getClass().equals(allFilter))) { + return (Set) allGoals.stream() + .filter(g -> goalFilter.isAssignableFrom(g.getClass())) + .filter(Goal::isActive) + .collect(Collectors.toSet()); + } else { + return (Set) allGoals.stream() + .filter(g -> goalFilter.isAssignableFrom(g.getClass())) + .filter(Goal::isActive) + .filter(g -> expectedGoals + .stream() + .anyMatch(c -> g.getClass().equals(c.getClass()))) + .collect(Collectors.toSet()); + } + } + + public Set scanGoals() { + final Set defs = new LinkedHashSet<>(); + final List basePackages = properties + .getGoalsScannerBasePackages().stream() + .map(String::valueOf) + .collect(Collectors.toList()); + for (String basePackage : basePackages) { + defs.addAll(scanBeanDefinitions(false, basePackage, Goal.class)); + } + return getBeanDefinitionInstances(defs, Goal.class); + } + + public Set> scanTestClassesWithSuiteAnnotation() { + final Set defs = new LinkedHashSet<>(); + final List basePackages = properties + .getSuitesScannerBasePackages().stream() + .map(String::valueOf) + .collect(Collectors.toList()); + for (String basePackage : basePackages) { + defs.addAll(scanBeanDefinitions(false, basePackage, Suite.class)); + } + return getBeanDefinitionAnnotatedClasses(defs, Suite.class); + } + + public Set scanTestNGListeners() { + final Set defs = new LinkedHashSet<>(); + final List basePackages = properties + .getListenersScannerBasePackages().stream() + .map(String::valueOf) + .collect(Collectors.toList()); + for (String basePackage : basePackages) { + defs.addAll(scanBeanDefinitions(false, basePackage, BuggyListener.class)); + } + return getBeanDefinitionInstances(defs, BuggyListener.class); + } + + @Bean(AVAILABLE_BUGGY_COMPONENTS) + public Set getAvailableComponents() { + return availableComponents; + } + + @Bean(AVAILABLE_BUGGY_SERVICES) + public Set getAvailableServices() { + return availableServices; + } + + @Bean(AVAILABLE_BUGGY_INTERFACES) + public Set getAvailableInterfaces() { + return availableInterfaces; + } + + @Bean(ALL_BUGGY_GOALS) + public Set getAllGoals() { + return allGoals; + } + + @Bean(FILTERED_BUGGY_TEST_CLASSES) + public Set> getFilteredTestClasses() { + return filteredTestClasses; + } + + @Bean(ENABLED_BUGGY_LISTENERS) + public Set getEnabledBuggyListeners() { + return enabledBuggyListeners; + } + + @Bean(ALL_BUGGY_LISTENERS) + public Set getAllBuggyListeners() { + return allBuggyListeners; + } + + @Bean(ALL_BUGGY_TEST_CLASSES) + public Set> getAllTestClasses() { + return allTestClasses; + } + + @Bean(ALL_BUGGY_COMPONENTS) + public Set getAllComponents() { + return allComponents; + } + + @Bean(ALL_BUGGY_SERVICES) + public Set getAllServices() { + return allServices; + } + + @Bean(ALL_BUGGY_INTERFACES) + public Set getAllInterfaces() { + return allInterfaces; + } + +} diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/IConfiguration.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/IConfiguration.java new file mode 100644 index 0000000..fd07198 --- /dev/null +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/IConfiguration.java @@ -0,0 +1,76 @@ +package org.touchbit.buggy.spring.boot.starter.conf; + +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.cglib.beans.BeanGenerator; +import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider; +import org.springframework.core.type.filter.AnnotationTypeFilter; +import org.springframework.core.type.filter.AssignableTypeFilter; +import org.touchbit.buggy.spring.boot.starter.BuggyRunner; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Constructor; +import java.util.LinkedHashSet; +import java.util.Set; + +import static java.lang.reflect.Modifier.*; + +/** + * Interface for Buggy spring boot configurations + *

+ * Created by Oleg Shaburov on 01.10.2020 + * shaburov.o.a@gmail.com + */ +public interface IConfiguration { + + @SuppressWarnings("unchecked") + default Set scanBeanDefinitions(boolean useDefaultFilters, String basePackage, Class c) { + ClassPathScanningCandidateComponentProvider scanner = + new ClassPathScanningCandidateComponentProvider(useDefaultFilters); + if (c.isAnnotation()) { + Class annotation = (Class) c; + scanner.addIncludeFilter(new AnnotationTypeFilter(annotation)); + } else { + scanner.addIncludeFilter(new AssignableTypeFilter(c)); + } + try { + return scanner.findCandidateComponents(basePackage); + } catch (Exception e) { + BuggyRunner.exit("Could not find beans of class " + c.getSimpleName() + + " in package [" + basePackage + "]", e); + throw e; + } + } + + @SuppressWarnings("unchecked") + default Set getBeanDefinitionInstances(Set definitions, Class tClass) { + Set result = new LinkedHashSet<>(); + for (BeanDefinition bd : definitions) { + try { + Class c = BeanGenerator.class.getClassLoader().loadClass(bd.getBeanClassName()); + Constructor con = c.getConstructor(); + T instance = (T) con.newInstance(); + result.add(instance); + } catch (Exception e) { + BuggyRunner.exit("Could not load class for assigned type: " + tClass.getSimpleName(), e); + } + } + return result; + } + + default Set> getBeanDefinitionAnnotatedClasses(Set definitions, Class tClass) { + Set> result = new LinkedHashSet<>(); + for (BeanDefinition bd : definitions) { + try { + Class annotatedClass = BeanGenerator.class.getClassLoader().loadClass(bd.getBeanClassName()); + int mods = annotatedClass.getModifiers(); + if (isPublic(mods) && !isAbstract(mods) && !isInterface(mods)) { + result.add(annotatedClass); + } + } catch (ClassNotFoundException e) { + BuggyRunner.exit("Could not load class for annotation type: " + tClass.getSimpleName(), e); + } + } + return result; + } + +} diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/JCommanderConfiguration.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/JCommanderConfiguration.java new file mode 100644 index 0000000..d9ca466 --- /dev/null +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/JCommanderConfiguration.java @@ -0,0 +1,234 @@ +package org.touchbit.buggy.spring.boot.starter.conf; + +import com.beust.jcommander.*; +import com.google.common.base.CaseFormat; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.autoconfigure.condition.ConditionalOnNotWebApplication; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.touchbit.buggy.core.config.BuggyConfigurationYML; +import org.touchbit.buggy.core.logback.ConfLogger; +import org.touchbit.buggy.core.utils.JUtils; +import org.touchbit.buggy.spring.boot.starter.BuggyRunner; +import org.touchbit.buggy.spring.boot.starter.jcommander.BuggyConfiguration; +import org.touchbit.buggy.core.config.JCommand; +import org.touchbit.buggy.spring.boot.starter.jcommander.config.EnvironmentUsageFormatter; + +import javax.annotation.PostConstruct; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.*; +import java.util.stream.Collectors; + +import static com.google.common.base.CaseFormat.LOWER_HYPHEN; +import static com.google.common.base.CaseFormat.UPPER_UNDERSCORE; + +/** + * {@link JCommander} spring boot configuration class. + * {@link ComponentScan} searches for all implementations of the {@link JCommand} class. + * The search is done for packages that contain a "buggy" package. + *

+ * Created by Oleg Shaburov on 01.10.2020 + * shaburov.o.a@gmail.com + */ +@Configuration +@ConditionalOnNotWebApplication +@EnableConfigurationProperties(ApplicationProperties.class) +public class JCommanderConfiguration implements IConfiguration { + + private final JCommander jCommander; + private final Set jCommands = new LinkedHashSet<>(); + private final ApplicationProperties properties; + private final Map, JCommand> buggyConfigurations = new HashMap<>(); + private final boolean isJCommanderConfigured; + + public JCommanderConfiguration(final ApplicationProperties properties, final ApplicationArguments appArgs) { + try { + beforeConfiguration(); + String[] runArgs = appArgs.getSourceArgs(); + this.properties = properties; + this.jCommands.addAll(scanBuggyConfig()); + scanJCConfigurations().stream() + .filter(i -> !(i instanceof BuggyConfiguration)) + .forEach(this.jCommands::add); + this.jCommander = buildJCommander(this.jCommands, buggyConfigurations); + parseEnvArguments(this.jCommander); + parseRunArguments(this.jCommander, runArgs); + isJCommanderConfigured = true; + } catch (Exception e) { + BuggyRunner.exit("Error initializing JCommander config", e); + throw e; + } + } + + public void beforeConfiguration() { + ConfLogger.blockDelimiter(); + ConfLogger.centerBold("JCommander configuration construction"); + ConfLogger.stepDelimiter(); + } + + @Bean + public boolean isJCommanderConfigured() { + return isJCommanderConfigured; + } + + @PostConstruct + public void postConstruct() { + if (BuggyConfiguration.isHelp()) { + ConfLogger.stepDelimiter(); + jCommander.usage(); + BuggyRunner.exit(0); + } + if (BuggyConfiguration.isVersion()) { + ConfLogger.stepDelimiter(); + ConfLogger.centerBold("Version info"); + JUtils.getBuggyManifest().forEach(ConfLogger::dotPlaceholder); + BuggyRunner.exit(0); + } + printConfigurationsParams(buggyConfigurations); + } + + private Set scanBuggyConfig() { + final boolean useDefaultFilters = false; + final String basePackage = "org.touchbit.buggy.spring.boot.starter.jcommander"; + final Set defs = scanBeanDefinitions(useDefaultFilters, basePackage, BuggyConfiguration.class); + return getBeanDefinitionInstances(defs, BuggyConfiguration.class); + } + + public Set scanJCConfigurations() { + final Set defs = new LinkedHashSet<>(); + final List basePackages = properties.getCommandsScannerBasePackages().stream() + .map(String::valueOf) + .collect(Collectors.toList()); + for (String basePackage : basePackages) { + defs.addAll(scanBeanDefinitions(false, basePackage, JCommand.class)); + } + return getBeanDefinitionInstances(defs, JCommand.class); + } + + private JCommander buildJCommander(Set jCommands, Map, JCommand> configMap) { + JCommander jCommander = new JCommander(); + jCommander.setUsageFormatter(new EnvironmentUsageFormatter(jCommander)); + for (JCommand config : jCommands) { + configMap.put(config.getClass(), config); + checkConfiguration(config); + try { + if (config.getClass().isAnnotationPresent(Parameters.class) && + config.getClass().getAnnotation(Parameters.class).commandNames().length > 0) { + jCommander.addCommand(config); + } else { + jCommander.addObject(config); + } + ConfLogger.dotPlaceholder(config.getClass().getSimpleName(), "OK"); + } catch (Exception e) { + ConfLogger.dotPlaceholder(config.getClass().getSimpleName(), "FAIL"); + BuggyRunner.exit(1, "Unexpected error while loading Jcommander configs", e); + } + } + return jCommander; + } + + public void parseEnvArguments(JCommander jCommander) { + Map buggyEnv = System.getenv().entrySet().stream() + .filter(e -> e.getKey().toUpperCase().startsWith("BUGGY_")) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + for (Map.Entry entry : buggyEnv.entrySet()) { + String[] envVar = new String[]{entry.getKey(), entry.getValue()}; + String key = UPPER_UNDERSCORE.to(LOWER_HYPHEN, entry.getKey().replace("BUGGY_", "__")); + String[] runVar = new String[]{key, entry.getValue()}; + try { + jCommander.parse(runVar); + } catch (Exception e) { + printConfigurationsParams(buggyConfigurations); + BuggyRunner.exit("Error parsing environment variable: " + Arrays.toString(envVar), e); + } + } + } + + public void parseRunArguments(JCommander jCommander, String[] args) { + try { + jCommander.parse(args); + ConfLogger.stepDelimiter(); + ConfLogger.dotPlaceholder("Parsing arguments", "OK"); + } catch (Exception e) { + ConfLogger.stepDelimiter(); + ConfLogger.dotPlaceholder("Parsing arguments", "FAIL"); + printConfigurationsParams(buggyConfigurations); + BuggyRunner.exit(e.getMessage(), e); + } + } + + @Bean("isBuggyConfigured") + public boolean isBuggyConfigured() { + return buggyConfigurations.containsKey(BuggyConfigurationYML.class); + } + + @Bean() + public Map, JCommand> getBuggyConfigurations() { + return buggyConfigurations; + } + + public void checkConfiguration(JCommand config) { + for (Field field : JUtils.getFields(config)) { + Parameter parameter = field.getAnnotation(Parameter.class); + if (parameter != null && !Modifier.isStatic(field.getModifiers())) { + String[] names = parameter.names(); + ConfLogger.dotPlaceholder(config.getClass().getSimpleName(), "FAIL"); + printConfigurationParams(config); + BuggyRunner.exit(1, "Field " + config.getClass().getSimpleName() + "#" + field.getName() + + " marked with @Parameter " + Arrays.toString(names) + " must be static."); + } + } + for (Method method : JUtils.getMethods(config)) { + String error = null; + Parameter parameter = method.getAnnotation(Parameter.class); + if (parameter != null) { + String[] names = parameter.names(); + StringJoiner parameters = new StringJoiner(", "); + for (Class parameterType : method.getParameterTypes()) { + parameters.add(parameterType.getSimpleName()); + } + if (!Modifier.isStatic(method.getModifiers())) { + error = "Method " + config.getClass().getSimpleName() + "#" + method.getName() + + "(" + parameters.toString() + ")" + + " marked with @Parameter " + Arrays.toString(names) + " must be static."; + + } + if (!method.getName().startsWith("is") & !method.getName().startsWith("set")) { + error = "Method " + config.getClass().getSimpleName() + "#" + method.getName() + + "(" + parameters.toString() + ")" + + " marked with @Parameter " + Arrays.toString(names) + " must be а setter " + + "(method name must start with 'is' or 'set')."; + } + if (error != null) { + ConfLogger.dotPlaceholder(config.getClass().getSimpleName(), "FAIL"); + printConfigurationParams(config); + BuggyRunner.exit(1, error); + } + } + } + } + + public void printConfigurationsParams(Map, JCommand> configs) { + for (JCommand autowiredConfig : jCommands) { + JCommand config = configs.get(autowiredConfig.getClass()); + printConfigurationParams(config); + } + } + + public void printConfigurationParams(JCommand config) { + Map params = config.configurationToMap(); + if (params != null && !params.isEmpty()) { + ConfLogger.stepDelimiter(); + ConfLogger.center(config.getClass().getSimpleName()); + for (Map.Entry entry : params.entrySet()) { + ConfLogger.dotPlaceholder(entry.getKey(), entry.getValue()); + } + } + } + +} diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/LogbackConfiguration.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/LogbackConfiguration.java new file mode 100644 index 0000000..0017159 --- /dev/null +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/LogbackConfiguration.java @@ -0,0 +1,58 @@ +package org.touchbit.buggy.spring.boot.starter.conf; + +import org.springframework.boot.autoconfigure.condition.ConditionalOnNotWebApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.ConfigurableEnvironment; +import org.touchbit.buggy.core.logback.BaseLogbackWrapper; +import org.touchbit.buggy.core.logback.ConfLogger; +import org.touchbit.buggy.core.logback.FrameworkLogger; +import org.touchbit.buggy.spring.boot.starter.BuggyRunner; + +import static org.springframework.boot.context.logging.LoggingApplicationListener.CONFIG_PROPERTY; + +/** + * Logback loggers configuration + *

+ * Created by Oleg Shaburov on 30.09.2020 + * shaburov.o.a@gmail.com + */ +@Configuration() +@ConditionalOnNotWebApplication +public class LogbackConfiguration implements IConfiguration { + + private final boolean isLogbackConfigurationInitialized; + + public LogbackConfiguration(boolean isJCommanderConfigured, ConfigurableEnvironment environment) { + String property = environment.getProperty(CONFIG_PROPERTY); + + if (property != null) { + System.setProperty(CONFIG_PROPERTY, property); + } + if (!isJCommanderConfigured) { + BuggyRunner.exit(1, "JCommander must be initialized"); + } + ConfLogger.blockDelimiter(); + ConfLogger.centerBold("Logback configuration (" + BaseLogbackWrapper.getConfFileName() + ")"); + ConfLogger.stepDelimiter(); + new FrameworkLogger().info(BaseLogbackWrapper.getInCaseOfErrorsOrWarnings()); + for (ch.qos.logback.classic.Logger logger : BaseLogbackWrapper.getLoggerList()) { + if (logger.getLevel() != null) { + String name = logger.getName(); + try { + Class c = this.getClass().getClassLoader().loadClass(name); + name = c.getSimpleName() + ".class"; + } catch (ClassNotFoundException ignore) { + } + ConfLogger.dotPlaceholder(name, logger.getLevel()); + } + } + isLogbackConfigurationInitialized = true; + } + + @Bean() + public boolean isLogbackConfigurationInitialized() { + return isLogbackConfigurationInitialized; + } + +} diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/Qualifiers.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/Qualifiers.java new file mode 100644 index 0000000..879f5bf --- /dev/null +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/Qualifiers.java @@ -0,0 +1,17 @@ +package org.touchbit.buggy.spring.boot.starter.conf; + +public class Qualifiers { + + public static final String ALL_BUGGY_GOALS = "bcb5d31a-80a2-4ed1-9c4b-9176304cdb57"; + public static final String ALL_BUGGY_LISTENERS = "2c539293-113a-40ec-bc30-47ea1bc4f895"; + public static final String ENABLED_BUGGY_LISTENERS = "25d0001b-c709-49b4-a773-37b13726ad22"; + public static final String ALL_BUGGY_TEST_CLASSES = "ed42a56a-08ac-46d6-b31c-571d6f18c3d9"; + public static final String FILTERED_BUGGY_TEST_CLASSES = "7a0eaeff-ed78-4c7c-b55d-96b7c328c9f3"; + public static final String ALL_BUGGY_COMPONENTS = "45ecce9f-43a4-48bf-a672-5c19aa134d70"; + public static final String AVAILABLE_BUGGY_COMPONENTS = "70e0c372-5b82-4f77-bdee-821c880a6ffb"; + public static final String ALL_BUGGY_SERVICES = "94c25c52-ad45-4668-8bb9-63f13bd33add"; + public static final String AVAILABLE_BUGGY_SERVICES = "78b85cf8-5022-4853-a003-1bc6e084a577"; + public static final String ALL_BUGGY_INTERFACES = "75e10b3a-c236-458d-9ae6-80030eb42dbe"; + public static final String AVAILABLE_BUGGY_INTERFACES = "079eec1c-7cba-4253-8a55-479d526f993e"; + +} diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/BuggyConfiguration.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/BuggyConfiguration.java new file mode 100644 index 0000000..8988d02 --- /dev/null +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/BuggyConfiguration.java @@ -0,0 +1,278 @@ +package org.touchbit.buggy.spring.boot.starter.jcommander; + +import com.beust.jcommander.Parameter; +import org.touchbit.buggy.core.config.BuggyConfigurationYML; +import org.touchbit.buggy.core.config.JCommand; +import org.touchbit.buggy.core.config.OutputRule; +import org.touchbit.buggy.core.goal.component.Component; +import org.touchbit.buggy.core.goal.interfaze.Interface; +import org.touchbit.buggy.core.goal.service.Service; +import org.touchbit.buggy.core.model.ParallelMode; +import org.touchbit.buggy.core.model.Type; +import org.touchbit.buggy.spring.boot.starter.jcommander.converters.*; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static org.touchbit.buggy.spring.boot.starter.jcommander.CommandNames.*; + +/** + * Configuration class for customizing Buggy. + *

+ * Created by Oleg Shaburov on 01.10.2020 + * shaburov.o.a@gmail.com + */ +@SuppressWarnings("unused") +public final class BuggyConfiguration implements JCommand { + + private static Boolean version = false; + private static Integer exitStatus = null; + + public static Boolean getVersion() { + return version; + } + + public static Integer getExitStatus() { + return exitStatus; + } + + @Parameter(names = {VERSION}, description = "Print program version") + public static void setVersion(Boolean version) { + BuggyConfiguration.version = version; + } + + @Parameter(names = {EXIT_STATUS}, description = "Completion with the specified status.") + public static void setExitStatus(Integer exitStatus) { + BuggyConfiguration.exitStatus = exitStatus; + } + + // ---------------------- Map default BuggyConfigurationYML values ---------------------- // + + @Parameter(names = {QUESTION_MARK, HELP}, help = true, description = "Print usage.") + public static void setHelp(Boolean help) { + BuggyConfigurationYML.setHelp(help); + } + + @Parameter(names = {F, FORCE}, description = "Running all tests, including those that fall.") + public static void setForce(Boolean force) { + BuggyConfigurationYML.setForceRun(force); + } + + @Parameter(names = {THREADS}, description = "The number of threads to run the test methods.") + public static void setThreads(Integer threads) { + BuggyConfigurationYML.setThreads(threads); + } + + @Parameter(names = {ARTIFACTS_URL}, description = "The storage address for the builds (artifacts).") + public static void setArtifactsUrl(String artifactsUrl) { + BuggyConfigurationYML.setArtifactsUrl(artifactsUrl); + } + + @Parameter(names = {T, TYPE}, description = "Type of tests to run.", validateWith = ParameterValidator.class, + listConverter = TypeListConverter.class) + public static void setTypes(Type... types) { + BuggyConfigurationYML.setTypes(types); + } + + @Parameter(names = {S, SERVICES}, description = "List of tested services in the format: NAME,NAME,NAME.", + validateWith = ParameterValidator.class, listConverter = ServiceConverter.class) + public static void setServices(List services) { + BuggyConfigurationYML.setServices(services); + } + + @SafeVarargs + public static void setServices(S... services) { + BuggyConfigurationYML.setServices(services); + } + + @SafeVarargs + public static void setServices(Class... services) { + BuggyConfigurationYML.setServices(services); + } + + @Parameter(names = {I, INTERFACES}, description = "List of tested interfaces in the format: NAME,NAME,NAME.", + validateWith = ParameterValidator.class, listConverter = InterfaceConverter.class) + public static void setInterfaces(List interfaces) { + BuggyConfigurationYML.setInterfaces(interfaces); + } + + @SafeVarargs + public static void setInterfaces(I... interfaces) { + BuggyConfigurationYML.setInterfaces(interfaces); + } + + @SafeVarargs + public static void setInterfaces(Class... interfaces) { + BuggyConfigurationYML.setInterfaces(interfaces); + } + + @Parameter(names = {C, COMPONENTS}, description = "List of tested components in the format: NAME,NAME,NAME.", + validateWith = ParameterValidator.class, listConverter = ComponentConverter.class) + public static void setComponents(List components) { + BuggyConfigurationYML.setComponents(components); + } + + @SafeVarargs + public static void setComponents(C... components) { + BuggyConfigurationYML.setComponents(components); + } + + @SafeVarargs + public static void setComponents(Class... components) { + BuggyConfigurationYML.setComponents(components); + } + + @Parameter(names = {PARALLEL_MODE}, description = "TestNG parallel mode.") + public static void setParallelMode(ParallelMode parallelMode) { + BuggyConfigurationYML.setParallelMode(parallelMode); + } + + @Parameter(names = {PROGRAM_NAME}, description = "Current program name") + public static void setProgramName(String programName) { + BuggyConfigurationYML.setProgramName(programName); + } + + @Parameter(names = {"--issues-url"}, description = "Task tracker issues URL.") + public static void setIssuesUrl(String taskTrackerIssueUrl) { + BuggyConfigurationYML.setIssuesUrl(taskTrackerIssueUrl); + } + + public static Boolean isHelp() { + return BuggyConfigurationYML.isHelp(); + } + + @Parameter(names = {TEST_CASE_TITLE}, arity = 1, description = "Print the title of the test case to the console log.") + public static void setTestCaseTitle(Boolean testCaseTitle) { + BuggyConfigurationYML.setTestCaseTitle(testCaseTitle); + } + + @Parameter(names = {TEST_SUITE_INFO}, description = "Print the suite information in the console log.") + public static void setTestSuiteInfo(Boolean testSuiteInfo) { + BuggyConfigurationYML.setTestSuiteInfo(testSuiteInfo); + } + + @Parameter(names = {TEST_LOG_FILE_PATH}, description = "Print the test log file path in the console log.") + public static void setTestLogFilePath(Boolean testLogFilePath) { + BuggyConfigurationYML.setTestLogFilePath(testLogFilePath); + } + + @Parameter(names = {TEST_ISSUES_INFO}, description = "Print URLs of related issues.") + public static void setTestIssuesInfo(Boolean testIssuesInfo) { + BuggyConfigurationYML.setTestIssuesInfo(testIssuesInfo); + } + + @Parameter(names = {TEST_BUGS_INFO}, description = "Print URLs of related bugs.") + public static void setTestBugsInfo(Boolean testBugsInfo) { + BuggyConfigurationYML.setTestBugsInfo(testBugsInfo); + } + + @Parameter(names = {TEST_ERROR_INFO}, description = "Print the cause of a fail test in the console log.") + public static void setTestErrorInfo(Boolean testErrorInfo) { + BuggyConfigurationYML.setTestErrorInfo(testErrorInfo); + } + + @Parameter(names = {OUTPUT_RULE}, description = "Print the cause of a fail test in the console log.") + public static void setOutputRule(OutputRule outputRule) { + BuggyConfigurationYML.setOutputRule(outputRule); + } + + public static Boolean getTestCaseTitle() { + return BuggyConfigurationYML.getTestCaseTitle(); + } + + public static Boolean getTestSuiteInfo() { + return BuggyConfigurationYML.getTestSuiteInfo(); + } + + public static Boolean getTestLogFilePath() { + return BuggyConfigurationYML.getTestLogFilePath(); + } + + public static Boolean getTestIssuesInfo() { + return BuggyConfigurationYML.getTestIssuesInfo(); + } + + public static Boolean getTestBugsInfo() { + return BuggyConfigurationYML.getTestBugsInfo(); + } + + public static Boolean getTestErrorInfo() { + return BuggyConfigurationYML.getTestErrorInfo(); + } + + public static OutputRule getOutputRule() { + return BuggyConfigurationYML.getOutputRule(); + } + + public static Boolean isVersion() { + return version; + } + + public static Boolean isForce() { + return BuggyConfigurationYML.isForceRun(); + } + + public static Integer getThreads() { + return BuggyConfigurationYML.getThreads(); + } + + public static String getArtifactsUrl() { + return BuggyConfigurationYML.getArtifactsUrl(); + } + + public static Type[] getTypes() { + return BuggyConfigurationYML.getTypes(); + } + + public static List getServices() { + return BuggyConfigurationYML.getServices(); + } + + public static List getInterfaces() { + return BuggyConfigurationYML.getInterfaces(); + } + + public static List getComponents() { + return BuggyConfigurationYML.getComponents(); + } + + public static ParallelMode getParallelMode() { + return BuggyConfigurationYML.getParallelMode(); + } + + public static String getProgramName() { + return BuggyConfigurationYML.getProgramName(); + } + + public static String getTaskTrackerIssueUrl() { + return BuggyConfigurationYML.getIssuesUrl(); + } + + @Override + public Map sort(Map map) { + String[] sort = new String[] + {THREADS, PARALLEL_MODE, F, TEST_CASE_TITLE, TEST_LOG_FILE_PATH, TEST_SUITE_INFO, TEST_LOG_FILE_PATH, + TEST_ISSUES_INFO, TEST_BUGS_INFO, TEST_ERROR_INFO, OUTPUT_RULE, C, S, I, T, + LOGS_PATH, ARTIFACTS_URL, EXIT_STATUS}; + Map sorted = new LinkedHashMap<>(); + for (String s : sort) { + for (Map.Entry entry : map.entrySet()) { + String[] keys = entry.getKey() + .replace(",", "") + .replace("]", "") + .replace("[", "") + .split(" "); + for (String key : keys) { + if (key.equals(s)) { + sorted.put(entry.getKey(), entry.getValue()); + } + } + } + } + sorted.putAll(map); + return sorted; + } + +} diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/CommandNames.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/CommandNames.java new file mode 100644 index 0000000..fc04bc2 --- /dev/null +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/CommandNames.java @@ -0,0 +1,57 @@ +/* + * Copyright © 2018 Shaburov Oleg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.touchbit.buggy.spring.boot.starter.jcommander; + +/** + * Created by Oleg Shaburov on 18.09.2018 + * shaburov.o.a@gmail.com + */ +@SuppressWarnings("WeakerAccess") +public class CommandNames { + + public static final String PROGRAM_NAME = "--program-name"; + public static final String VERSION = "--version"; + public static final String EXIT_STATUS = "--exit-status"; + public static final String QUESTION_MARK = "-?"; + public static final String HELP = "--help"; + public static final String C = "-c"; + public static final String COMPONENTS = "--components"; + public static final String S = "-s"; + public static final String SERVICES = "--services"; + public static final String I = "-i"; + public static final String INTERFACES = "--interfaces"; + public static final String T = "-t"; + public static final String TYPE = "--types"; + public static final String PARALLEL_MODE = "--parallel-mode"; + public static final String LOGS_PATH = "--logs-path"; + public static final String THREADS = "--threads"; + public static final String F = "-f"; + public static final String FORCE = "--force-run"; + public static final String ARTIFACTS_URL = "--artifacts-url"; + public static final String TEST_CASE_TITLE = "--test-case-title"; + public static final String TEST_SUITE_INFO = "--test-suite-info"; + public static final String TEST_LOG_FILE_PATH = "--test-log-file-path"; + public static final String TEST_ISSUES_INFO = "--test-issues-info"; + public static final String TEST_BUGS_INFO = "--test-bugs-info"; + public static final String TEST_ERROR_INFO = "--test-error-info"; + public static final String OUTPUT_RULE = "--output-rule"; + + private CommandNames() { + throw new IllegalStateException("Utility class. Prohibit instantiation."); + } + +} diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/config/EnvironmentUsageFormatter.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/config/EnvironmentUsageFormatter.java new file mode 100644 index 0000000..7abd266 --- /dev/null +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/config/EnvironmentUsageFormatter.java @@ -0,0 +1,137 @@ +package org.touchbit.buggy.spring.boot.starter.jcommander.config; + +import com.beust.jcommander.*; +import org.touchbit.buggy.core.goal.component.Component; +import org.touchbit.buggy.core.goal.interfaze.Interface; +import org.touchbit.buggy.core.goal.service.Service; +import org.touchbit.buggy.core.utils.ANSI; +import org.touchbit.buggy.spring.boot.starter.util.BeanScanner; + +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.*; + +import static org.touchbit.buggy.core.utils.ANSI.BOLD; + +/** + * Created by Oleg Shaburov on 18.10.2020 + * shaburov.o.a@gmail.com + */ +public class EnvironmentUsageFormatter extends DefaultUsageFormatter { + + public EnvironmentUsageFormatter(JCommander commander) { + super(commander); + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + @Override + public void appendAllParametersDetails(StringBuilder out, + int indentCount, + String indent, + List sortedParameters) { + if (sortedParameters.size() > 0) { + out.append(indent).append(" Options:\n"); + } + for (ParameterDescription pd : sortedParameters) { + WrappedParameter parameter = pd.getParameter(); + String description = pd.getDescription(); + boolean hasDescription = !description.isEmpty(); + + String longestName = pd.getLongestName(); + while (longestName.startsWith("-")) { + longestName = longestName.replaceFirst("-", ""); + } + String envKey = "BUGGY_" + longestName.replace("-", "_").toUpperCase(); + // First line, command name + out.append(indent) + .append(" ") + .append(parameter.required() ? "* " : " ") + .append(BOLD.wrap(pd.getNames() + " | " + "${" + envKey + "}")) + .append("\n"); + + if (hasDescription) { + wrapDescription(out, indentCount, s(indentCount) + description); + } + Object def = pd.getDefault(); + + if (pd.isDynamicParameter()) { + String syntax = "Syntax: " + parameter.names()[0] + "key" + parameter.getAssignment() + "value"; + + if (hasDescription) { + out.append(newLineAndIndent(indentCount)); + } else { + out.append(s(indentCount)); + } + out.append(syntax); + } + + if (def != null && !pd.isHelp()) { + String displayedDef = Strings.isStringEmpty(def.toString()) ? "" : def.toString(); + String defaultText = ANSI.BR_PURPLE.wrap("Default: ") + + (parameter.password() ? "********" : displayedDef); + if (hasDescription) { + out.append(newLineAndIndent(indentCount)); + } else { + out.append(s(indentCount)); + } + out.append(defaultText); + } + Parameterized parameterized = pd.getParameterized(); + Class type = parameterized.getType(); + if (type.equals(List.class)) { + Type listType = parameterized.getGenericType(); + if (listType instanceof ParameterizedType) { + ParameterizedType parameterizedType = (ParameterizedType) listType; + Type genericType = parameterizedType.getActualTypeArguments()[0]; + String genericTypeName = genericType.getTypeName(); + StringJoiner sj = new StringJoiner(", "); + if (Component.class.getTypeName().equals(genericTypeName)) { + Set components = BeanScanner.getBeanDefinitionInstances(Component.class); + components.forEach(c -> sj.add(c.getName())); + } + if (Service.class.getTypeName().equals(genericTypeName)) { + Set components = BeanScanner.getBeanDefinitionInstances(Service.class); + components.forEach(c -> sj.add(c.getName())); + } + if (Interface.class.getTypeName().equals(genericTypeName)) { + Set components = BeanScanner.getBeanDefinitionInstances(Interface.class); + components.forEach(c -> sj.add(c.getName())); + } + if (org.touchbit.buggy.core.model.Type.class.getTypeName().equals(genericTypeName)) { + Arrays.stream(org.touchbit.buggy.core.model.Type.values()) + .forEach(c -> sj.add(c.name())); + } + String possibleValues = ANSI.BR_BLUE.wrap("Possible Values:") + " [" + sj.toString() + "]"; + out.append("\n"); + wrapDescription(out, indentCount, s(indentCount) + possibleValues); + } + } + if (type.isEnum()) { + String valueList = EnumSet.allOf((Class) type).toString(); + String possibleValues = ANSI.BR_BLUE.wrap("Possible Values: ") + valueList; + + // Prevent duplicate values list, since it is set as 'Options: [values]' if the description + // of an enum field is empty in ParameterDescription#init(..) + if (!description.contains("Options: " + valueList)) { + if (hasDescription) { + out.append(newLineAndIndent(indentCount)); + } else { + out.append(s(indentCount)); + } + out.append(possibleValues); + } + } + out.append("\n"); + } + } + + /** + * Returns new line followed by indent-many spaces. + * + * @return new line followed by indent-many spaces + */ + private static String newLineAndIndent(int indent) { + return "\n" + s(indent); + } + +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/config/jcommander/ArraySplitter.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/ArraySplitter.java similarity index 94% rename from buggy-core/src/main/java/org/touchbit/buggy/core/config/jcommander/ArraySplitter.java rename to buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/ArraySplitter.java index 3f884a5..7fd7203 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/config/jcommander/ArraySplitter.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/ArraySplitter.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.touchbit.buggy.core.config.jcommander; +package org.touchbit.buggy.spring.boot.starter.jcommander.converters; import com.beust.jcommander.converters.IParameterSplitter; diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/config/jcommander/ComponentConverter.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/ComponentConverter.java similarity index 88% rename from buggy-core/src/main/java/org/touchbit/buggy/core/config/jcommander/ComponentConverter.java rename to buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/ComponentConverter.java index eba3ac7..271734c 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/config/jcommander/ComponentConverter.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/ComponentConverter.java @@ -13,10 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.touchbit.buggy.core.config.jcommander; +package org.touchbit.buggy.spring.boot.starter.jcommander.converters; import com.beust.jcommander.converters.DefaultListConverter; -import org.touchbit.buggy.core.process.Component; +import org.touchbit.buggy.core.goal.component.Component; /** * Created by Oleg Shaburov on 19.05.2018 diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/config/jcommander/GoalConverter.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/GoalConverter.java similarity index 64% rename from buggy-core/src/main/java/org/touchbit/buggy/core/config/jcommander/GoalConverter.java rename to buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/GoalConverter.java index 5d927cd..30afab7 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/config/jcommander/GoalConverter.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/GoalConverter.java @@ -14,12 +14,15 @@ * limitations under the License. */ -package org.touchbit.buggy.core.config.jcommander; +package org.touchbit.buggy.spring.boot.starter.jcommander.converters; import com.beust.jcommander.IStringConverter; -import org.atteo.classindex.ClassIndex; +import org.springframework.beans.factory.config.BeanDefinition; import org.touchbit.buggy.core.exceptions.BuggyConfigurationException; -import org.touchbit.buggy.core.process.Goal; +import org.touchbit.buggy.core.goal.Goal; +import org.touchbit.buggy.spring.boot.starter.util.BeanScanner; + +import java.util.Set; /** * Created by Oleg Shaburov on 08.09.2018 @@ -35,18 +38,14 @@ public GoalConverter(final Class t) { @Override public T convert(String s) { - Iterable> goalClasses = ClassIndex.getSubclasses(tClass); - for (Class goal : goalClasses) { - try { - if (goal.getSimpleName().equalsIgnoreCase(s)) { - return goal.newInstance(); - } - } catch (Exception e) { - throw new BuggyConfigurationException("Can not create a new instance of " + goal + - " inheriting from class " + tClass.getSimpleName()); + Set beanDefinitionInstances = BeanScanner.scanBeanDefinitions(tClass); + Set goalClasses = BeanScanner.getBeanDefinitionInstances(beanDefinitionInstances, tClass); + for (T goal : goalClasses) { + if (goal.getName().equalsIgnoreCase(s)) { + return goal; } } throw new BuggyConfigurationException("No " + tClass.getSimpleName() + " found with name " + s); } -} \ No newline at end of file +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/config/jcommander/InterfaceConverter.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/InterfaceConverter.java similarity index 88% rename from buggy-core/src/main/java/org/touchbit/buggy/core/config/jcommander/InterfaceConverter.java rename to buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/InterfaceConverter.java index 646a992..d227867 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/config/jcommander/InterfaceConverter.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/InterfaceConverter.java @@ -14,10 +14,10 @@ * limitations under the License. */ -package org.touchbit.buggy.core.config.jcommander; +package org.touchbit.buggy.spring.boot.starter.jcommander.converters; import com.beust.jcommander.converters.DefaultListConverter; -import org.touchbit.buggy.core.process.Interface; +import org.touchbit.buggy.core.goal.interfaze.Interface; /** * Created by Oleg Shaburov on 19.05.2018 diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/config/jcommander/ParameterValidator.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/ParameterValidator.java similarity index 86% rename from buggy-core/src/main/java/org/touchbit/buggy/core/config/jcommander/ParameterValidator.java rename to buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/ParameterValidator.java index 3229155..1527386 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/config/jcommander/ParameterValidator.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/ParameterValidator.java @@ -14,12 +14,12 @@ * limitations under the License. */ -package org.touchbit.buggy.core.config.jcommander; +package org.touchbit.buggy.spring.boot.starter.jcommander.converters; import com.beust.jcommander.IParameterValidator; import com.beust.jcommander.ParameterException; -import static org.touchbit.buggy.core.config.BParameters.*; +import static org.touchbit.buggy.spring.boot.starter.jcommander.CommandNames.*; /** * Created by Oleg Shaburov on 08.09.2018 @@ -34,10 +34,12 @@ public void validate(String name, String value) { private void assertNotEmpty(String name, String value) { switch (name) { + case C: + case COMPONENTS: case S: case SERVICES: case I: - case INTERFACE: + case INTERFACES: case T: case TYPE: if (value == null || value.isEmpty()) { diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/config/jcommander/ServiceConverter.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/ServiceConverter.java similarity index 88% rename from buggy-core/src/main/java/org/touchbit/buggy/core/config/jcommander/ServiceConverter.java rename to buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/ServiceConverter.java index 8e29939..ca184cd 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/config/jcommander/ServiceConverter.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/ServiceConverter.java @@ -14,10 +14,10 @@ * limitations under the License. */ -package org.touchbit.buggy.core.config.jcommander; +package org.touchbit.buggy.spring.boot.starter.jcommander.converters; import com.beust.jcommander.converters.DefaultListConverter; -import org.touchbit.buggy.core.process.Service; +import org.touchbit.buggy.core.goal.service.Service; /** * Created by Oleg Shaburov on 08.09.2018 diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/TypeConverter.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/TypeConverter.java new file mode 100644 index 0000000..f7aec61 --- /dev/null +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/TypeConverter.java @@ -0,0 +1,49 @@ +/* + * Copyright © 2018 Shaburov Oleg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.touchbit.buggy.spring.boot.starter.jcommander.converters; + +import com.beust.jcommander.IStringConverter; +import com.beust.jcommander.converters.StringConverter; +import org.springframework.beans.factory.config.BeanDefinition; +import org.touchbit.buggy.core.exceptions.BuggyConfigurationException; +import org.touchbit.buggy.core.model.Type; +import org.touchbit.buggy.spring.boot.starter.util.BeanScanner; + +import java.util.Set; + +/** + * Created by Oleg Shaburov on 08.09.2018 + * shaburov.o.a@gmail.com + */ +public final class TypeConverter implements IStringConverter { + + @Override + public Type convert(String s) { + System.out.println(" >>>>>>>>>>>>>>>>>>> s >>> " + s); + Set beanDefinitionInstances = BeanScanner.scanBeanDefinitions(Type.class); + Set types = BeanScanner.getBeanDefinitionInstances(beanDefinitionInstances, Type.class); + System.out.println(" >>>>> types >>> " + types); + for (Type type : types) { + if (type.name().equalsIgnoreCase(s)) { + System.out.println(" >>>>> type >>> " + type + " >> " + type.getClass()); + return type; + } + } + throw new BuggyConfigurationException("No " + Type.class.getSimpleName() + " found with name " + s); + } + +} \ No newline at end of file diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/TypeListConverter.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/TypeListConverter.java new file mode 100644 index 0000000..a81c61e --- /dev/null +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/TypeListConverter.java @@ -0,0 +1,38 @@ +/* + * Copyright © 2018 Shaburov Oleg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.touchbit.buggy.spring.boot.starter.jcommander.converters; + +import com.beust.jcommander.converters.DefaultListConverter; +import org.springframework.beans.factory.config.BeanDefinition; +import org.touchbit.buggy.core.exceptions.BuggyConfigurationException; +import org.touchbit.buggy.core.model.Type; +import org.touchbit.buggy.spring.boot.starter.util.BeanScanner; + +import java.util.Set; + +/** + * Created by Oleg Shaburov on 08.09.2018 + * shaburov.o.a@gmail.com + */ +public final class TypeListConverter extends DefaultListConverter { + + public TypeListConverter() { + super(new ArraySplitter(), new TypeConverter()); + System.out.println(" >>>>>>>>>>>>>>>>>> " + this); + } + +} diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/util/BeanScanner.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/util/BeanScanner.java new file mode 100644 index 0000000..bc03ae4 --- /dev/null +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/util/BeanScanner.java @@ -0,0 +1,48 @@ +package org.touchbit.buggy.spring.boot.starter.util; + +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider; +import org.springframework.core.type.filter.AssignableTypeFilter; +import org.touchbit.buggy.core.exceptions.BuggyConfigurationException; +import org.touchbit.buggy.core.utils.JUtils; + +import java.util.LinkedHashSet; +import java.util.Set; + +public class BeanScanner { + + private BeanScanner() { + throw new IllegalStateException("Utility class. Prohibit instantiation."); + } + + public static Set getBeanDefinitionInstances(Class tClass) { + Set definitions = scanBeanDefinitions(tClass); + Set result = new LinkedHashSet<>(); + for (BeanDefinition bd : definitions) { + A instance = JUtils.newInstance(bd.getBeanClassName(), tClass, BuggyConfigurationException::new); + result.add(instance); + } + return result; + } + + public static Set getBeanDefinitionInstances(Set definitions, Class tClass) { + Set result = new LinkedHashSet<>(); + for (BeanDefinition bd : definitions) { + A instance = JUtils.newInstance(bd.getBeanClassName(), tClass, BuggyConfigurationException::new); + result.add(instance); + } + return result; + } + + public static Set scanBeanDefinitions(Class c) { + ClassPathScanningCandidateComponentProvider scanner = + new ClassPathScanningCandidateComponentProvider(false); + scanner.addIncludeFilter(new AssignableTypeFilter(c)); + try { + return scanner.findCandidateComponents("**.buggy"); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + +} diff --git a/buggy-spring-boot-starter/src/main/resources/application.yml b/buggy-spring-boot-starter/src/main/resources/application.yml new file mode 100644 index 0000000..cd09784 --- /dev/null +++ b/buggy-spring-boot-starter/src/main/resources/application.yml @@ -0,0 +1,13 @@ +logging: + config: 'classpath:buggy-logback.xml' + file: + path: /tmp/logs +buggy: + commandsScannerBasePackages: + - "**.buggy" + goalsScannerBasePackages: + - "**.buggy" + suitesScannerBasePackages: + - "**.buggy" + listenersScannerBasePackages: + - "**.buggy" \ No newline at end of file diff --git a/buggy-testng-listeners/pom.xml b/buggy-testng-listeners/pom.xml new file mode 100644 index 0000000..819728a --- /dev/null +++ b/buggy-testng-listeners/pom.xml @@ -0,0 +1,28 @@ + + + 4.0.0 + + + org.touchbit.buggy + buggy + 0.3.7 + + + buggy-testng-listeners + TestNG listeners + 0.3.7 + jar + + + org.touchbit:buggy-testng-listeners + + + + + org.touchbit.buggy + buggy-core + + + \ No newline at end of file diff --git a/buggy-testng-listeners/src/main/java/org/touchbit/buggy/testng/listeners/ExecutionListener.java b/buggy-testng-listeners/src/main/java/org/touchbit/buggy/testng/listeners/ExecutionListener.java new file mode 100644 index 0000000..b691ab0 --- /dev/null +++ b/buggy-testng-listeners/src/main/java/org/touchbit/buggy/testng/listeners/ExecutionListener.java @@ -0,0 +1,12 @@ +package org.touchbit.buggy.testng.listeners; + +import org.touchbit.buggy.core.testng.ExecutionListenerBase; + +public class ExecutionListener extends ExecutionListenerBase { + + @Override + public boolean isEnable() { + return !ListenerConfiguration.isDisableExecutionListener(); + } + +} diff --git a/buggy-testng-listeners/src/main/java/org/touchbit/buggy/testng/listeners/ListenerConfiguration.java b/buggy-testng-listeners/src/main/java/org/touchbit/buggy/testng/listeners/ListenerConfiguration.java new file mode 100644 index 0000000..dec774a --- /dev/null +++ b/buggy-testng-listeners/src/main/java/org/touchbit/buggy/testng/listeners/ListenerConfiguration.java @@ -0,0 +1,40 @@ +package org.touchbit.buggy.testng.listeners; + +import com.beust.jcommander.Parameter; +import org.touchbit.buggy.core.config.JCommand; + +public class ListenerConfiguration implements JCommand { + + @Parameter(names = {"--disable-execution-listener"}, hidden = true, description = "Disable ExecutionListener.") + private static Boolean disableExecutionListener = false; + + @Parameter(names = {"--disable-logging-listener"}, hidden = true, description = "Disable LoggingListener.") + private static Boolean disableLoggingListener = false; + + @Parameter(names = {"--disable-statistic-listener"}, hidden = true, description = "Disable TestStatisticListener.") + private static Boolean disableTestStatisticListener = false; + + public static Boolean isDisableExecutionListener() { + return disableExecutionListener; + } + + public static void setDisableExecutionListener(Boolean disableExecutionListener) { + ListenerConfiguration.disableExecutionListener = disableExecutionListener; + } + + public static Boolean isDisableLoggingListener() { + return disableLoggingListener; + } + + public static void setDisableLoggingListener(Boolean disableLoggingListener) { + ListenerConfiguration.disableLoggingListener = disableLoggingListener; + } + + public static Boolean isDisableTestStatisticListener() { + return disableTestStatisticListener; + } + + public static void setDisableTestStatisticListener(Boolean disableTestStatisticListener) { + ListenerConfiguration.disableTestStatisticListener = disableTestStatisticListener; + } +} diff --git a/buggy-testng-listeners/src/main/java/org/touchbit/buggy/testng/listeners/LoggingListener.java b/buggy-testng-listeners/src/main/java/org/touchbit/buggy/testng/listeners/LoggingListener.java new file mode 100644 index 0000000..a14337b --- /dev/null +++ b/buggy-testng-listeners/src/main/java/org/touchbit/buggy/testng/listeners/LoggingListener.java @@ -0,0 +1,12 @@ +package org.touchbit.buggy.testng.listeners; + +import org.touchbit.buggy.core.testng.LoggingListenerBase; + +public class LoggingListener extends LoggingListenerBase { + + @Override + public boolean isEnable() { + return !ListenerConfiguration.isDisableLoggingListener(); + } + +} diff --git a/buggy-testng-listeners/src/main/java/org/touchbit/buggy/testng/listeners/TestStatisticListener.java b/buggy-testng-listeners/src/main/java/org/touchbit/buggy/testng/listeners/TestStatisticListener.java new file mode 100644 index 0000000..d242618 --- /dev/null +++ b/buggy-testng-listeners/src/main/java/org/touchbit/buggy/testng/listeners/TestStatisticListener.java @@ -0,0 +1,12 @@ +package org.touchbit.buggy.testng.listeners; + +import org.touchbit.buggy.core.testng.TestStatisticListenerBase; + +public class TestStatisticListener extends TestStatisticListenerBase { + + @Override + public boolean isEnable() { + return !ListenerConfiguration.isDisableTestStatisticListener(); + } + +} diff --git a/buggy-testrail/pom.xml b/buggy-testrail/pom.xml index c26b491..de4deb3 100644 --- a/buggy-testrail/pom.xml +++ b/buggy-testrail/pom.xml @@ -1,6 +1,6 @@ - 4.0.0 diff --git a/buggy-testrail/src/main/java/org/touchbit/buggy/testrail/BTRParameters.java b/buggy-testrail/src/main/java/org/touchbit/buggy/testrail/BTRParameters.java index f0b906b..7c5c67b 100644 --- a/buggy-testrail/src/main/java/org/touchbit/buggy/testrail/BTRParameters.java +++ b/buggy-testrail/src/main/java/org/touchbit/buggy/testrail/BTRParameters.java @@ -6,10 +6,10 @@ */ public class BTRParameters { - public static final String ENABLE = "--tr"; - public static final String HOST = "--tr-host"; - public static final String LOGIN = "--tr-login"; - public static final String PASS_TOKEN = "--tr-auth"; + public static final String ENABLE = "--tr"; + public static final String HOST = "--tr-host"; + public static final String LOGIN = "--tr-login"; + public static final String PASS_TOKEN = "--tr-auth"; private BTRParameters() { throw new IllegalStateException("Utility class. Prohibit instantiation."); diff --git a/buggy-testrail/src/main/java/org/touchbit/buggy/testrail/BaseTestRailConfig.java b/buggy-testrail/src/main/java/org/touchbit/buggy/testrail/BaseTestRailConfig.java index f450305..d956000 100644 --- a/buggy-testrail/src/main/java/org/touchbit/buggy/testrail/BaseTestRailConfig.java +++ b/buggy-testrail/src/main/java/org/touchbit/buggy/testrail/BaseTestRailConfig.java @@ -11,51 +11,54 @@ @SuppressWarnings({"squid:S1118", "WeakerAccess", "squid:S1214"}) public interface BaseTestRailConfig { - class DefaultValues { - - private static Boolean testRailEnable = false; - private static String testRailHost = "https://testrail.example"; - private static String testRailLogin = ""; - private static String testRailPassToken = ""; - - /** Utility class. Prohibit instantiation. */ - private DefaultValues() { } - } - @Parameter(names = {ENABLE}, description = "Flag of translation results in TestRail") static void setTestRailEnable(Boolean testRailEnable) { DefaultValues.testRailEnable = testRailEnable; } + static Boolean isTestRailEnable() { + return DefaultValues.testRailEnable; + } + + static String getTestRailHost() { + return DefaultValues.testRailHost; + } + @Parameter(names = {HOST}, hidden = true, description = "TestRail server") static void setTestRailHost(String testRailHost) { DefaultValues.testRailHost = testRailHost; } + static String getLogin() { + return DefaultValues.testRailLogin; + } + @Parameter(names = {LOGIN}, hidden = true, password = true, description = "TestRail base64 auth") static void setLogin(String testRailLogin) { DefaultValues.testRailLogin = testRailLogin; } + static String getPass() { + return DefaultValues.testRailPassToken; + } + @Parameter(names = {PASS_TOKEN}, hidden = true, description = "TestRail user password or api token") static void setPass(String testRailPassToken) { DefaultValues.testRailPassToken = testRailPassToken; } - static Boolean isTestRailEnable() { - return DefaultValues.testRailEnable; - } - - static String getTestRailHost() { - return DefaultValues.testRailHost; - } + class DefaultValues { - static String getLogin() { - return DefaultValues.testRailLogin; - } + private static Boolean testRailEnable = false; + private static String testRailHost = "https://testrail.example"; + private static String testRailLogin = ""; + private static String testRailPassToken = ""; - static String getPass() { - return DefaultValues.testRailPassToken; + /** + * Utility class. Prohibit instantiation. + */ + private DefaultValues() { + } } } diff --git a/buggy-testrail/src/main/java/org/touchbit/buggy/testrail/RunsResultsStorage.java b/buggy-testrail/src/main/java/org/touchbit/buggy/testrail/RunsResultsStorage.java index ea022e7..3de5f44 100644 --- a/buggy-testrail/src/main/java/org/touchbit/buggy/testrail/RunsResultsStorage.java +++ b/buggy-testrail/src/main/java/org/touchbit/buggy/testrail/RunsResultsStorage.java @@ -15,8 +15,8 @@ public class RunsResultsStorage { /** - * key - TestRail run id - * value - list of test result objects {@link TRResult} + * key - TestRail run id + * value - list of test result objects {@link TRResult} */ private final Map> runsResults; diff --git a/buggy-testrail/src/main/java/org/touchbit/buggy/testrail/listeners/BaseTestRailListener.java b/buggy-testrail/src/main/java/org/touchbit/buggy/testrail/listeners/BaseTestRailListener.java index 60d505c..8455c7d 100644 --- a/buggy-testrail/src/main/java/org/touchbit/buggy/testrail/listeners/BaseTestRailListener.java +++ b/buggy-testrail/src/main/java/org/touchbit/buggy/testrail/listeners/BaseTestRailListener.java @@ -1,10 +1,11 @@ package org.touchbit.buggy.testrail.listeners; -import org.touchbit.buggy.core.Buggy; -import org.touchbit.buggy.core.config.PrimaryConfig; -import org.touchbit.buggy.core.model.Details; -import org.touchbit.buggy.core.testng.listeners.BaseBuggyExecutionListener; -import org.testng.*; +import org.testng.IExecutionListener; +import org.testng.IInvokedMethodListener; +import org.testng.ITestResult; +import org.touchbit.buggy.core.config.BuggyConfigurationYML; +import org.touchbit.buggy.core.model.Buggy; +import org.touchbit.buggy.core.testng.BaseBuggyExecutionListener; import org.touchbit.buggy.testrail.BaseTestRailConfig; import org.touchbit.buggy.testrail.RunsResultsStorage; import org.touchbit.buggy.testrail.StatusMapper; @@ -19,8 +20,6 @@ import java.util.*; import java.util.stream.Collectors; -import static org.touchbit.buggy.core.test.TRProperty.RUN_ID; - /** * Listener of the test methods to be followed for the subsequent translation of the results into the TestRail. *

@@ -31,14 +30,12 @@ public abstract class BaseTestRailListener extends BaseBuggyExecutionListener implements IExecutionListener, IInvokedMethodListener { - private TestRailClient client; private static RunsResultsStorage runsResults = new RunsResultsStorage(); + private TestRailClient client; private StatusMapper statusMapper; - private final PrimaryConfig config; public BaseTestRailListener(StatusMapper statusMapper) { this.statusMapper = statusMapper; - this.config = Buggy.getPrimaryConfig(); BasicAuth interceptor = new BasicAuth(BaseTestRailConfig.getLogin(), BaseTestRailConfig.getPass()); client = TestRailClientBuilder.build(interceptor, BaseTestRailConfig.getTestRailHost()); } @@ -76,13 +73,13 @@ public void onExecutionFinish() { frameworkLog.info("Test results for run_id={} transferred.", rId); if (!caseIDsCheckList.isEmpty()) { caseIDsCheckList.forEach(cId -> { - Buggy.incrementBuggyErrors(); +// Buggy.incrementBuggyErrors(); frameworkLog.error("In TestRail is absent or in the " + "test the case with id={} is incorrectly specified", cId); }); } } catch (Exception e) { - Buggy.incrementBuggyErrors(); +// Buggy.incrementBuggyErrors(); frameworkLog.error("Error getting data from TestRail.", e); } } @@ -90,22 +87,23 @@ public void onExecutionFinish() { } } - protected void addResult(ITestResult result, Details details, S status, String comment) { + protected void addResult(ITestResult result, Buggy buggy, S status, String comment) { String msg = comment + addAttachments(result); - String strRunID = String.valueOf(result.getAttribute(RUN_ID.toString())); + String strRunID = "0"; // TODO +// String strRunID = String.valueOf(result.getAttribute(RUN_ID.toString())); if ("null".equals(String.valueOf(strRunID))) { - strRunID = String.valueOf(System.getProperty(RUN_ID.toString())); +// strRunID = String.valueOf(System.getProperty(RUN_ID.toString())); } try { Long runID = Long.parseLong(strRunID); - for (Long caseId : details.id()) { + for (String caseId : buggy.caseIDs()) { if (statusMapper.getId(status) > 0) { StringJoiner defects = new StringJoiner(", "); - for (String bug : details.bug()) { + for (String bug : buggy.bugs()) { defects.add(bug); } TRResult trResult = new TRResult() - .withCaseId(caseId) + .withCaseId(Long.valueOf(caseId)) .withStatusId(statusMapper.getId(status)) .withComment(msg) .withDefects(defects.toString()); @@ -115,22 +113,22 @@ protected void addResult(ITestResult result, Details details, S status, String c } } } catch (Exception ignore) { - Buggy.incrementBuggyErrors(); - frameworkLog.error("An incorrect value {} = {} was received", RUN_ID, strRunID); +// BuCo.incrementBuggyErrors(); +// frameworkLog.error("An incorrect value {} = {} was received", RUN_ID, strRunID); } } protected String addAttachments(ITestResult testResult) { Method method = testResult.getMethod().getConstructorOrMethod().getMethod(); - Details trCase = method.getAnnotation(Details.class); + Buggy trCase = method.getAnnotation(Buggy.class); - String caseIds = trCase != null ? Arrays.toString(trCase.id()) + "_" : ""; + String caseIds = trCase != null ? Arrays.toString(trCase.caseIDs()) + "_" : ""; String prefix = caseIds + method.getName(); return "\n" + attachLogfile(prefix) + "\n" + attachScreenshots(prefix); } protected String attachLogfile(String prefix) { - String logfile = config.getArtifactsUrl() + "/tests/" + prefix + ".log"; + String logfile = BuggyConfigurationYML.getArtifactsUrl() + "/tests/" + prefix + ".log"; return attachFile(logfile); } @@ -150,7 +148,7 @@ protected String attachScreenshots(String prefix) { protected String attachFile(String filename) { File sourceFile = new File(filename); return "[" + sourceFile.getName() + "](" + - config.getArtifactsUrl() + "/tests/" + sourceFile.getName() + ")\n"; + BuggyConfigurationYML.getArtifactsUrl() + "/tests/" + sourceFile.getName() + ")\n"; } protected List getTestRailCasesByRunId(Long rId) { diff --git a/buggy-testrail/src/main/java/org/touchbit/buggy/testrail/listeners/DefaultTestRailListener.java b/buggy-testrail/src/main/java/org/touchbit/buggy/testrail/listeners/DefaultTestRailListener.java index 5ca2aa6..6d29568 100644 --- a/buggy-testrail/src/main/java/org/touchbit/buggy/testrail/listeners/DefaultTestRailListener.java +++ b/buggy-testrail/src/main/java/org/touchbit/buggy/testrail/listeners/DefaultTestRailListener.java @@ -6,14 +6,14 @@ import org.touchbit.buggy.core.exceptions.BuggyConfigurationException; import org.touchbit.buggy.core.exceptions.CorruptedTestException; import org.touchbit.buggy.core.exceptions.ExpectedImplementationException; -import org.touchbit.buggy.core.model.Details; +import org.touchbit.buggy.core.model.Buggy; +import org.touchbit.buggy.core.model.ResultStatus; import org.touchbit.buggy.core.model.Status; import org.touchbit.buggy.testrail.BaseTestRailConfig; import org.touchbit.buggy.testrail.StatusMapper; import org.touchbit.testrail4j.core.type.Statuses; import static org.touchbit.buggy.core.model.Status.*; -import static org.touchbit.buggy.core.model.Status.FAILED; @SuppressWarnings({"WeakerAccess", "unused"}) public abstract class DefaultTestRailListener extends BaseTestRailListener { @@ -26,89 +26,68 @@ public DefaultTestRailListener(StatusMapper statusMapper) { super(statusMapper); } - public static class DefaultStatusMapper implements StatusMapper { - - @Override - public long getId(Status status) { - switch (status) { - case SUCCESS: - case FIXED: - case IMPLEMENTED: return Statuses.PASSED.getId(); - case BLOCKED: - case SKIP: return Statuses.BLOCKED.getId(); - case UNTESTED: return Statuses.UNTESTED.getId(); - case FAILED: - case CORRUPTED: - case EXP_IMPL: - case EXP_FIX: return Statuses.FAILED.getId(); - default: - throw new BuggyConfigurationException("Unhandled status received: " + status); - } - } - } - @Override public void afterInvocation(IInvokedMethod method, ITestResult result) { - Details details = getDetails(method); - String throwableMsg = processResultThrowable(details, result); - if (method.isTestMethod() && details != null && result.getMethod().getInvocationCount() > 0) { + Buggy buggy = getBuggyAnnotation(method); + String throwableMsg = processResultThrowable(buggy, result); + if (method.isTestMethod() && buggy != null && result.getMethod().getInvocationCount() > 0) { int rStatus = result.getStatus(); if (rStatus == ITestResult.SUCCESS) { - processSuccessTest(details, result, throwableMsg); + processSuccessTest(buggy, result, throwableMsg); } else { - processErrorTest(details, result, throwableMsg); + processErrorTest(buggy, result, throwableMsg); } } } - protected void processErrorTest(Details details, ITestResult result, String throwableMsg) { - switch(details.status()) { - case SKIP: - case FAILED: + protected void processErrorTest(Buggy buggy, ITestResult result, String throwableMsg) { + switch (buggy.status()) { +// case SKIP: +// case FAILED: case EXP_FIX: case BLOCKED: case EXP_IMPL: case CORRUPTED: - addResult(result, details, details.status(), throwableMsg); + addResult(result, buggy, buggy.status(), throwableMsg); break; default: - addResult(result, details, FAILED, throwableMsg); +// addResult(result, buggy, FAILED, throwableMsg); } } - protected String processResultThrowable(Details details, ITestResult result) { + protected String processResultThrowable(Buggy buggy, ITestResult result) { if (result.getStatus() != ITestResult.SUCCESS) { - if (BLOCKED.equals(details.status())) { + if (BLOCKED.equals(buggy.status())) { result.setThrowable(new BlockedTestException()); } - if (EXP_IMPL.equals(details.status())) { + if (EXP_IMPL.equals(buggy.status())) { result.setThrowable(new ExpectedImplementationException()); } - if (CORRUPTED.equals(details.status())) { - result.setThrowable(new CorruptedTestException(details)); + if (CORRUPTED.equals(buggy.status())) { + result.setThrowable(new CorruptedTestException(buggy)); } } Throwable throwable = result.getThrowable(); return throwable == null ? "" : " " + throwable.getMessage(); } - protected void processSuccessTest(Details details, ITestResult result, String throwableMsg) { - switch(details.status()) { - case EXP_FIX: - case BLOCKED: - addResult(result, details, FIXED, - "The error has been fixed. You need to edit the status for the test." + throwableMsg); - break; - case EXP_IMPL: - addResult(result, details, IMPLEMENTED, - "The test passed successfully. You need to edit the status for the test." + throwableMsg); - break; - case CORRUPTED: - addResult(result, details, CORRUPTED, new CorruptedTestException(details).getMessage()); - break; - default: - addResult(result, details, SUCCESS, "The test passed successfully." + throwableMsg); - } + protected void processSuccessTest(Buggy buggy, ITestResult result, String throwableMsg) { +// switch (buggy.status()) { +// case EXP_FIX: +// case BLOCKED: +// addResult(result, buggy, FIXED, +// "The error has been fixed. You need to edit the status for the test." + throwableMsg); +// break; +// case EXP_IMPL: +// addResult(result, buggy, IMPLEMENTED, +// "The test passed successfully. You need to edit the status for the test." + throwableMsg); +// break; +// case CORRUPTED: +// addResult(result, buggy, CORRUPTED, new CorruptedTestException(buggy).getMessage()); +// break; +// default: +// addResult(result, buggy, SUCCESS, "The test passed successfully." + throwableMsg); +// } } @Override @@ -116,4 +95,29 @@ public boolean isEnable() { return BaseTestRailConfig.isTestRailEnable(); } + public static class DefaultStatusMapper implements StatusMapper { + + @Override + public long getId(Status status) { + switch (status) { +// case SUCCESS: +// case FIXED: +// case IMPLEMENTED: +// return Statuses.PASSED.getId(); +// case BLOCKED: +// case SKIP: +// return Statuses.BLOCKED.getId(); +// case NONE: +// return Statuses.UNTESTED.getId(); +// case FAILED: +// case CORRUPTED: +// case EXP_IMPL: +// case EXP_FIX: +// return Statuses.FAILED.getId(); + default: + throw new BuggyConfigurationException("Unhandled status received: " + status); + } + } + } + } diff --git a/pom.xml b/pom.xml index 55bb016..986c0e2 100644 --- a/pom.xml +++ b/pom.xml @@ -1,6 +1,6 @@ - 4.0.0 @@ -9,14 +9,18 @@ Buggy 0.3.7 pom - Buggy is an add-on to TestNG for quickly creating test projects and easily customizing the launch of automated tests. + Buggy is an add-on to TestNG for quickly creating test projects and easily customizing the launch of + automated tests. + buggy-core + buggy-spring-boot-starter + buggy-spring-boot-starter-example buggy-feign - buggy-min-example buggy-okhttp buggy-testrail + buggy-testng-listeners @@ -72,7 +76,6 @@ ${jdk.version} UTF-8 UTF-8 - 2.9.1 5.5.0 10.2.3 @@ -157,6 +160,12 @@ 0.3.7 compile + + org.touchbit.buggy + buggy-spring-boot-starter + 0.3.7 + compile + org.touchbit.buggy buggy-feign @@ -175,6 +184,12 @@ 0.3.7 compile + + org.touchbit.buggy + buggy-testng-listeners + 0.3.7 + compile + org.touchbit.buggy @@ -187,12 +202,12 @@ org.testng testng - 7.0.0-beta7 + 7.3.0 com.beust jcommander - 1.74 + 1.78 org.atteo.classindex @@ -216,29 +231,9 @@ - org.apache.logging.log4j - log4j-slf4j-impl - ${log4j.version} - - - org.apache.logging.log4j - log4j-1.2-api - ${log4j.version} - - - org.apache.logging.log4j - log4j-jul - ${log4j.version} - - - org.apache.logging.log4j - log4j-core - ${log4j.version} - - - org.apache.logging.log4j - log4j-api - ${log4j.version} + ch.qos.logback + logback-classic + 1.2.3 org.slf4j @@ -359,20 +354,12 @@ ${project.version} - executable true - - - org.atteo.classindex - classindex-transformer - 3.7 - - org.apache.maven.plugins