From fa1b5e5425a1b4bc98ade9189b4347e9a3a1485e Mon Sep 17 00:00:00 2001 From: "oleg.shaburov" Date: Sun, 27 Sep 2020 06:29:19 +0300 Subject: [PATCH 01/24] Init spring boot starter --- .../core/tests/utils/BuggyUtilsTests.java | 1 - buggy-spring-boot-starter-example/pom.xml | 48 ++++++++++++ .../spring/boot/starter/example/Command1.java | 13 ++++ .../spring/boot/starter/example/Command2.java | 16 ++++ .../spring/boot/starter/example/Command3.java | 16 ++++ .../spring/boot/starter/example/Command4.java | 16 ++++ .../spring/boot/starter/example/SBBuggy.java | 14 ++++ buggy-spring-boot-starter/pom.xml | 66 ++++++++++++++++ .../buggy/spring/boot/starter/Buggy.java | 19 +++++ .../boot/starter/BuggyAutoConfiguration.java | 36 +++++++++ .../spring/boot/starter/BuggyConfig.java | 13 ++++ .../spring/boot/starter/IBuggyConfig.java | 8 ++ .../boot/starter/JCommanderConfiguration.java | 76 +++++++++++++++++++ .../buggy/spring/boot/starter/SBBuggy.java | 72 ++++++++++++++++++ .../main/resources/META-INF/spring.factories | 1 + .../src/main/resources/application.properties | 1 + pom.xml | 9 ++- 17 files changed, 421 insertions(+), 4 deletions(-) create mode 100644 buggy-spring-boot-starter-example/pom.xml create mode 100644 buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/Command1.java create mode 100644 buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/Command2.java create mode 100644 buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/Command3.java create mode 100644 buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/Command4.java create mode 100644 buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/SBBuggy.java create mode 100644 buggy-spring-boot-starter/pom.xml create mode 100644 buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/Buggy.java create mode 100644 buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/BuggyAutoConfiguration.java create mode 100644 buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/BuggyConfig.java create mode 100644 buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/IBuggyConfig.java create mode 100644 buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/JCommanderConfiguration.java create mode 100644 buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/SBBuggy.java create mode 100644 buggy-spring-boot-starter/src/main/resources/META-INF/spring.factories create mode 100644 buggy-spring-boot-starter/src/main/resources/application.properties 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..a703f32 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 @@ -4,7 +4,6 @@ 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; diff --git a/buggy-spring-boot-starter-example/pom.xml b/buggy-spring-boot-starter-example/pom.xml new file mode 100644 index 0000000..703830b --- /dev/null +++ b/buggy-spring-boot-starter-example/pom.xml @@ -0,0 +1,48 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 2.3.4.RELEASE + + + org.touchbit.buggy + buggy-spring-boot-starter-example + Buggy SB starter + Buggy spring boot starter + 0.3.7 + jar + + + org.touchbit:buggy-spring-boot-starter-example + + + + + org.touchbit.buggy + buggy-spring-boot-starter + 0.3.7 + compile + + + org.springframework.boot + spring-boot-starter + 2.3.4.RELEASE + + + org.springframework.boot + spring-boot-starter-logging + + + org.apache.logging.log4j + log4j-to-slf4j + + + + + + \ No newline at end of file diff --git a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/Command1.java b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/Command1.java new file mode 100644 index 0000000..541f86a --- /dev/null +++ b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/Command1.java @@ -0,0 +1,13 @@ +package org.touchbit.buggy.spring.boot.starter.example; + +import com.beust.jcommander.Parameter; +import org.touchbit.buggy.spring.boot.starter.IBuggyConfig; + +public class Command1 implements IBuggyConfig { + + @Parameter(names = {"-fgh"}, description = "Running all tests, including those that fall.") + private Boolean force =null; + + @Parameter(names = {"-a"}, description = "FFFFFFFFFFFFFFFFFFFFF.") + private Boolean a = null; +} diff --git a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/Command2.java b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/Command2.java new file mode 100644 index 0000000..45213b6 --- /dev/null +++ b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/Command2.java @@ -0,0 +1,16 @@ +package org.touchbit.buggy.spring.boot.starter.example; + +import com.beust.jcommander.Parameter; +import com.beust.jcommander.Parameters; +import org.touchbit.buggy.spring.boot.starter.IBuggyConfig; + + +public class Command2 implements IBuggyConfig { + + @Parameter(names = {"-?", "--help"}, hidden = true, help = true, description = "Print usage.") + private Boolean help = null; + + @Parameter(names = {"-ad"}, description = "FFFFFFFFFFFFFFFFFFFFF.") + private Boolean a = null; + +} diff --git a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/Command3.java b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/Command3.java new file mode 100644 index 0000000..4d371d6 --- /dev/null +++ b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/Command3.java @@ -0,0 +1,16 @@ +package org.touchbit.buggy.spring.boot.starter.example; + +import com.beust.jcommander.Parameter; +import com.beust.jcommander.Parameters; +import org.touchbit.buggy.spring.boot.starter.IBuggyConfig; + +@Parameters(commandNames = {"c1"}, commandDescription = "secondary config") +public class Command3 implements IBuggyConfig { + + @Parameter(names = {"----?"}, hidden = true, help = true, description = "Print usage.") + private Boolean help = null; + + @Parameter(names = {"-a"}, description = "FFFFFFFFFFFFFFFFFFFFF.") + private Boolean a = null; + +} diff --git a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/Command4.java b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/Command4.java new file mode 100644 index 0000000..0815b89 --- /dev/null +++ b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/Command4.java @@ -0,0 +1,16 @@ +package org.touchbit.buggy.spring.boot.starter.example; + +import com.beust.jcommander.Parameter; +import com.beust.jcommander.Parameters; +import org.touchbit.buggy.spring.boot.starter.IBuggyConfig; + +@Parameters(commandNames = "c2") +public class Command4 implements IBuggyConfig { + + @Parameter(names = {"---?"}, hidden = true, help = true, description = "Print usage.") + private Boolean help = null; + + @Parameter(names = {"-a"}, description = "FFFFFFFFFFFFFFFFFFFFF.") + private Boolean a = null; + +} diff --git a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/SBBuggy.java b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/SBBuggy.java new file mode 100644 index 0000000..b4e8960 --- /dev/null +++ b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/SBBuggy.java @@ -0,0 +1,14 @@ +package org.touchbit.buggy.spring.boot.starter.example; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.touchbit.buggy.spring.boot.starter.Buggy; + +public class SBBuggy extends Buggy { + + public static void main(String[] args) { + args = new String[]{"--force"}; + SpringApplication.run(SBBuggy.class, args); + } + +} diff --git a/buggy-spring-boot-starter/pom.xml b/buggy-spring-boot-starter/pom.xml new file mode 100644 index 0000000..1f41552 --- /dev/null +++ b/buggy-spring-boot-starter/pom.xml @@ -0,0 +1,66 @@ + + + 4.0.0 + + + org.touchbit.buggy + buggy + 0.3.7 + + + 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 + + + com.beust + jcommander + 1.78 + + + org.springframework.boot + spring-boot-starter-validation + 2.3.4.RELEASE + + + org.springframework.boot + spring-boot-configuration-processor + 2.3.4.RELEASE + true + + + org.springframework.boot + spring-boot-starter-test + 2.3.4.RELEASE + test + + + + org.touchbit.buggy + buggy-core + test-jar + + + org.atteo.classindex + classindex + 3.7 + compile + + + + \ No newline at end of file diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/Buggy.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/Buggy.java new file mode 100644 index 0000000..63cefe3 --- /dev/null +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/Buggy.java @@ -0,0 +1,19 @@ +package org.touchbit.buggy.spring.boot.starter; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.testng.TestNG; + +@SpringBootApplication +public abstract class Buggy implements CommandLineRunner { + + @Autowired + private TestNG testNG; + + @Override + public void run(final String... args) throws Exception { + System.out.println(" >>>> RUN"); + } + +} diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/BuggyAutoConfiguration.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/BuggyAutoConfiguration.java new file mode 100644 index 0000000..ad3505a --- /dev/null +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/BuggyAutoConfiguration.java @@ -0,0 +1,36 @@ +package org.touchbit.buggy.spring.boot.starter; + +import com.beust.jcommander.JCommander; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.AutoConfigureBefore; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnNotWebApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.DependsOn; +import org.springframework.core.annotation.Order; +import org.testng.TestNG; +import org.touchbit.buggy.core.utils.StringUtils; + +import java.util.Map; + +import static org.touchbit.buggy.core.utils.BuggyUtils.CONSOLE_DELIMITER; + +@Configuration +@DependsOn({"initBuggyConfiguration"}) +@ConditionalOnNotWebApplication +@AutoConfigureBefore(JCommanderConfiguration.class) +public class BuggyAutoConfiguration { + + public BuggyAutoConfiguration() { + StringUtils.println(CONSOLE_DELIMITER); + StringUtils.println("Loading TestNG configuration"); + } + + @Bean + public TestNG testNG() { + StringUtils.println(CONSOLE_DELIMITER); + return new TestNG(); + } + +} diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/BuggyConfig.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/BuggyConfig.java new file mode 100644 index 0000000..2bd96b0 --- /dev/null +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/BuggyConfig.java @@ -0,0 +1,13 @@ +package org.touchbit.buggy.spring.boot.starter; + +import com.beust.jcommander.Parameter; +import org.atteo.classindex.IndexSubclasses; +import org.springframework.context.annotation.Configuration; +import org.springframework.stereotype.Component; + +public class BuggyConfig implements IBuggyConfig { + + @Parameter(names = {"-f", "--force"}, description = "Running all tests, including those that fall.") + public static Boolean force = false; + +} diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/IBuggyConfig.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/IBuggyConfig.java new file mode 100644 index 0000000..64d8470 --- /dev/null +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/IBuggyConfig.java @@ -0,0 +1,8 @@ +package org.touchbit.buggy.spring.boot.starter; + +import org.springframework.context.annotation.Configuration; + +@Configuration +public interface IBuggyConfig { + +} diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/JCommanderConfiguration.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/JCommanderConfiguration.java new file mode 100644 index 0000000..13ec955 --- /dev/null +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/JCommanderConfiguration.java @@ -0,0 +1,76 @@ +package org.touchbit.buggy.spring.boot.starter; + +import com.beust.jcommander.JCommander; +import com.beust.jcommander.ParameterException; +import com.beust.jcommander.Parameters; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnNotWebApplication; +import org.springframework.context.annotation.*; +import org.springframework.core.annotation.Order; +import org.touchbit.buggy.core.utils.StringUtils; + +import java.util.*; + +import static org.touchbit.buggy.core.utils.BuggyUtils.CONSOLE_DELIMITER; + +//@Order(1) +@Configuration +@ConditionalOnNotWebApplication +@ComponentScan(includeFilters = @ComponentScan.Filter( + type = FilterType.ASSIGNABLE_TYPE, + classes = {IBuggyConfig.class})) +public class JCommanderConfiguration { + + private final List list; + private final String[] args; + + public JCommanderConfiguration(List list, ApplicationArguments args) { + this.list = list; + this.args = args.getSourceArgs(); + StringUtils.println(CONSOLE_DELIMITER); + StringUtils.println("Loading IBuggyConfig implementations"); + } + + @Bean("initBuggyConfiguration") + public Map, IBuggyConfig> initBuggyConfiguration() { + StringUtils.println(CONSOLE_DELIMITER); + Map, IBuggyConfig> result = new HashMap<>(); + for (IBuggyConfig config : list) { + result.put(config.getClass(), config); + StringUtils.println(StringUtils + .dotFiller(config.getClass().getSimpleName(), 47, "OK")); + } + JCommander jc = new JCommander(); + addConfiguration(jc, result.values()); + try { + jc.parse(args); + } catch (ParameterException e) { + exitRunWithUsage(e); + } + return result; + } + + private void addConfiguration(JCommander jc, Collection configs) { + for (IBuggyConfig c : configs) { + if (c.getClass().isAnnotationPresent(Parameters.class) && + c.getClass().getAnnotation(Parameters.class).commandNames().length > 0) { + jc.addCommand(c); + } else { + jc.addObject(c); + } + } + } + + public void exitRunWithUsage(ParameterException e) { + StringUtils.println(CONSOLE_DELIMITER); + e.usage(); + StringUtils.println(CONSOLE_DELIMITER); + StringUtils.println(e.getMessage()); + StringUtils.println(CONSOLE_DELIMITER); + StringUtils.println(StringUtils.dotFiller("Exit code", 47, 1)); + StringUtils.println(CONSOLE_DELIMITER); + System.exit(1); + } + +} diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/SBBuggy.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/SBBuggy.java new file mode 100644 index 0000000..3ccfc23 --- /dev/null +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/SBBuggy.java @@ -0,0 +1,72 @@ +package org.touchbit.buggy.spring.boot.starter; + +import com.beust.jcommander.JCommander; +import com.beust.jcommander.ParameterException; +import com.beust.jcommander.Parameters; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.testng.TestNG; +import org.touchbit.buggy.core.config.SecondaryConfig; +import org.touchbit.buggy.core.utils.BuggyUtils; + +import java.util.ArrayList; +import java.util.List; + + +public class SBBuggy { + + private static int javaVersion = getVersion(); + + public static void main(String[] args) { +// args = new String[]{"-?"}; + JCommander jc = new JCommander(); +// jc.addObject(); + List> instantiatedSubclasses = BuggyUtils + .findInstantiatedSubclasses(IBuggyConfig.class); + List configs = new ArrayList<>(); + for (Class instantiatedSubclass : instantiatedSubclasses) { + try { + configs.add(instantiatedSubclass.newInstance()); + JCommander tempJc = new JCommander(); + for (IBuggyConfig config : configs) { + if (config.getClass().isAnnotationPresent(Parameters.class)) { + tempJc.addCommand(config); + } else { + tempJc.addObject(config); + } + } + try { + tempJc.parse(args); + if (javaVersion > 8) { + System.out.println(instantiatedSubclass.getSimpleName() + "......OK"); + } else { + System.out.println(instantiatedSubclass.getClass().getSimpleName() + "......OK"); + } + } catch (ParameterException e) { + if (javaVersion > 8) { + System.out.println(instantiatedSubclass.getSimpleName() + "....FAIL"); + } else { + System.out.println(instantiatedSubclass.getClass().getSimpleName() + "....FAIL"); + } + e.usage(); + throw (ParameterException) e.fillInStackTrace(); + } + } catch (InstantiationException | IllegalAccessException e) { + e.printStackTrace(); + } + } + jc.setProgramName("name"); + jc.parse(args); + jc.usage(); + } + + private static int getVersion() { + String version = System.getProperty("java.version"); + System.out.println(" >>>> " + version); + if(version.startsWith("1.")) { + version = version.substring(2, 3); + } else { + int dot = version.indexOf("."); + if(dot != -1) { version = version.substring(0, dot); } + } return Integer.parseInt(version); + } +} diff --git a/buggy-spring-boot-starter/src/main/resources/META-INF/spring.factories b/buggy-spring-boot-starter/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000..28ae80d --- /dev/null +++ b/buggy-spring-boot-starter/src/main/resources/META-INF/spring.factories @@ -0,0 +1 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=org.touchbit.buggy.spring.boot.starter.BuggyAutoConfiguration \ No newline at end of file diff --git a/buggy-spring-boot-starter/src/main/resources/application.properties b/buggy-spring-boot-starter/src/main/resources/application.properties new file mode 100644 index 0000000..471ce01 --- /dev/null +++ b/buggy-spring-boot-starter/src/main/resources/application.properties @@ -0,0 +1 @@ +#logging.level.root=OFF diff --git a/pom.xml b/pom.xml index 55bb016..d69076a 100644 --- a/pom.xml +++ b/pom.xml @@ -13,6 +13,8 @@ buggy-core + buggy-spring-boot-starter + buggy-spring-boot-starter-example buggy-feign buggy-min-example buggy-okhttp @@ -72,7 +74,7 @@ ${jdk.version} UTF-8 UTF-8 - 2.9.1 + 2.13.3 5.5.0 10.2.3 @@ -187,12 +189,12 @@ org.testng testng - 7.0.0-beta7 + 7.3.0 com.beust jcommander - 1.74 + 1.78 org.atteo.classindex @@ -219,6 +221,7 @@ org.apache.logging.log4j log4j-slf4j-impl ${log4j.version} + test org.apache.logging.log4j From 6116e779e651eeb4b58ef707f20564df8a666e4d Mon Sep 17 00:00:00 2001 From: "oleg.shaburov" Date: Mon, 28 Sep 2020 17:06:16 +0300 Subject: [PATCH 02/24] Add LoggerConfiguration --- .../buggy/core/utils/StringUtils.java | 52 ++++++ .../buggy/core/utils/log/BuggyLog.java | 6 +- buggy-spring-boot-starter-example/pom.xml | 23 +-- .../spring/boot/starter/example/Command1.java | 2 +- .../spring/boot/starter/example/SBBuggy.java | 2 +- buggy-spring-boot-starter/pom.xml | 24 +++ .../boot/starter/BaseConfiguration.java | 20 +++ .../buggy/spring/boot/starter/Buggy.java | 8 + .../boot/starter/BuggyAutoConfiguration.java | 21 +-- .../spring/boot/starter/BuggyConfig.java | 16 ++ .../spring/boot/starter/IBuggyConfig.java | 5 +- .../boot/starter/JCommanderConfiguration.java | 152 ++++++++++++++---- .../boot/starter/LoggerConfiguration.java | 149 +++++++++++++++++ .../buggy/spring/boot/starter/SBBuggy.java | 72 --------- .../src/main/resources/application.properties | 2 +- .../src/main/resources/logging.properties | 3 + 16 files changed, 417 insertions(+), 140 deletions(-) create mode 100644 buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/BaseConfiguration.java create mode 100644 buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/LoggerConfiguration.java delete mode 100644 buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/SBBuggy.java create mode 100644 buggy-spring-boot-starter/src/main/resources/logging.properties 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 index f589339..1d9c06f 100644 --- 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 @@ -28,6 +28,11 @@ */ public class StringUtils { + public static final int STRING_LEN = 47; + public static final String BLOCK = "="; + public static final String STEP = "\u2014"; + public static final String DOT = "."; + public static String underscoreFiller(Object prefix, int i) { return underscoreFiller(prefix, i, null); } @@ -40,14 +45,34 @@ public static String dotFiller(Object prefix, int i) { return dotFiller(prefix, i, null); } + public static String dotFiller(Object prefix) { + return dotFiller(prefix, STRING_LEN, null); + } + public static String dotFiller(Object prefix, int i, Object suffix) { return filler(prefix, ".", i, suffix); } + public static String dotFiller(Object prefix, Object suffix) { + return filler(prefix, ".", STRING_LEN, suffix); + } + public static String filler(Object prefix, String symbol, int i) { return filler(prefix, symbol, i, null); } + public static String filler(String symbol) { + return filler(null, symbol, STRING_LEN, null); + } + + public static String filler(Object prefix, String symbol) { + return filler(prefix, symbol, STRING_LEN, null); + } + + public static String filler(Object prefix, String symbol, Object postfix) { + return filler(prefix, symbol, STRING_LEN, postfix); + } + public static String filler(Object prefix, String symbol, int length, Object postfix) { if (isNull(symbol) || symbol.isEmpty()) { symbol = "."; @@ -102,6 +127,33 @@ public static String decode(String value) { } } + public static void sPrint() { + println(filler(STEP)); + } + + public static void bPrint() { + println(filler(BLOCK)); + } + + public static void fPrint(String symbol) { + println(filler(symbol)); + } + + public static void fPrint(Object prefix, String symbol, Object postfix) { + println(filler(prefix, symbol, postfix)); + } + + public static void cPrint(String msg) { + if (msg != null && !msg.isEmpty()) { + int diff = STRING_LEN - msg.length(); + if (diff > 0) { + int indent = diff / 2; + String result = filler("", " ", indent, "") + msg; + println(result); + } + } + } + public static void println(String msg) { println(msg, null); } 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 index 8fb5e80..e861afe 100644 --- 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 @@ -108,9 +108,9 @@ public static synchronized void loadDefaultConfig() { 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)); + StringUtils.sPrint(); + StringUtils.fPrint("Logger", " ", "Level"); + StringUtils.sPrint(); if (configuration != null) { configuration.getLoggers() .forEach((k, v) -> { diff --git a/buggy-spring-boot-starter-example/pom.xml b/buggy-spring-boot-starter-example/pom.xml index 703830b..0979021 100644 --- a/buggy-spring-boot-starter-example/pom.xml +++ b/buggy-spring-boot-starter-example/pom.xml @@ -5,12 +5,11 @@ 4.0.0 - org.springframework.boot - spring-boot-starter-parent - 2.3.4.RELEASE + org.touchbit.buggy + buggy + 0.3.7 - org.touchbit.buggy buggy-spring-boot-starter-example Buggy SB starter Buggy spring boot starter @@ -19,6 +18,7 @@ org.touchbit:buggy-spring-boot-starter-example + 2.13.3 @@ -28,21 +28,6 @@ 0.3.7 compile - - org.springframework.boot - spring-boot-starter - 2.3.4.RELEASE - - - org.springframework.boot - spring-boot-starter-logging - - - org.apache.logging.log4j - log4j-to-slf4j - - - \ No newline at end of file diff --git a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/Command1.java b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/Command1.java index 541f86a..b7e9d03 100644 --- a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/Command1.java +++ b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/Command1.java @@ -5,7 +5,7 @@ public class Command1 implements IBuggyConfig { - @Parameter(names = {"-fgh"}, description = "Running all tests, including those that fall.") + @Parameter(names = {"--f"}, description = "Running all tests, including those that fall.") private Boolean force =null; @Parameter(names = {"-a"}, description = "FFFFFFFFFFFFFFFFFFFFF.") diff --git a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/SBBuggy.java b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/SBBuggy.java index b4e8960..3333f7c 100644 --- a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/SBBuggy.java +++ b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/SBBuggy.java @@ -7,7 +7,7 @@ public class SBBuggy extends Buggy { public static void main(String[] args) { - args = new String[]{"--force"}; + args = new String[]{"--force", "-v"}; SpringApplication.run(SBBuggy.class, args); } diff --git a/buggy-spring-boot-starter/pom.xml b/buggy-spring-boot-starter/pom.xml index 1f41552..fc77f06 100644 --- a/buggy-spring-boot-starter/pom.xml +++ b/buggy-spring-boot-starter/pom.xml @@ -37,6 +37,30 @@ spring-boot-starter-validation 2.3.4.RELEASE + + org.springframework.boot + spring-boot-starter + 2.3.4.RELEASE + + + ch.qos.logback + logback-classic + + + org.springframework.boot + spring-boot-starter-logging + + + org.apache.logging.log4j + log4j-to-slf4j + + + + + + + + org.springframework.boot spring-boot-configuration-processor diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/BaseConfiguration.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/BaseConfiguration.java new file mode 100644 index 0000000..efabf06 --- /dev/null +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/BaseConfiguration.java @@ -0,0 +1,20 @@ +package org.touchbit.buggy.spring.boot.starter; + +import org.touchbit.buggy.core.utils.StringUtils; + +public abstract class BaseConfiguration { + + public static void exitRun(Exception e) { + exitRun(e.getMessage()); + } + + public static void exitRun(String message) { + StringUtils.bPrint(); + StringUtils.println(message); + StringUtils.bPrint(); + StringUtils.println(StringUtils.dotFiller("Exit code", "1")); + StringUtils.bPrint(); + System.exit(1); + } + +} diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/Buggy.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/Buggy.java index 63cefe3..bf53b53 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/Buggy.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/Buggy.java @@ -2,9 +2,17 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.context.logging.LoggingApplicationListener; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; +import org.springframework.context.ApplicationListener; import org.testng.TestNG; +import java.lang.reflect.Field; +import java.util.List; + @SpringBootApplication public abstract class Buggy implements CommandLineRunner { diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/BuggyAutoConfiguration.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/BuggyAutoConfiguration.java index ad3505a..8c9c5fb 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/BuggyAutoConfiguration.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/BuggyAutoConfiguration.java @@ -1,28 +1,31 @@ package org.touchbit.buggy.spring.boot.starter; -import com.beust.jcommander.JCommander; +import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.AutoConfigureBefore; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnNotWebApplication; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.DependsOn; -import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; import org.testng.TestNG; import org.touchbit.buggy.core.utils.StringUtils; - -import java.util.Map; +import org.touchbit.buggy.core.utils.log.BuggyLog; import static org.touchbit.buggy.core.utils.BuggyUtils.CONSOLE_DELIMITER; -@Configuration -@DependsOn({"initBuggyConfiguration"}) +@Configuration() +@DependsOn({"initAndGetBuggyConfigurations", "isBuggyLoggerInitialized"}) @ConditionalOnNotWebApplication -@AutoConfigureBefore(JCommanderConfiguration.class) public class BuggyAutoConfiguration { - public BuggyAutoConfiguration() { + private Logger consoleLogger; + + public BuggyAutoConfiguration(boolean isBuggyLoggerInitialized) { + if (isBuggyLoggerInitialized) { + consoleLogger = LoggerConfiguration.console(); + consoleLogger.info(" <<<<<<>>>>>>>>>"); + } StringUtils.println(CONSOLE_DELIMITER); StringUtils.println("Loading TestNG configuration"); } diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/BuggyConfig.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/BuggyConfig.java index 2bd96b0..379c3da 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/BuggyConfig.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/BuggyConfig.java @@ -3,11 +3,27 @@ import com.beust.jcommander.Parameter; import org.atteo.classindex.IndexSubclasses; import org.springframework.context.annotation.Configuration; +import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; +import static org.touchbit.buggy.core.config.BParameters.ALL; + +@Order(1) public class BuggyConfig implements IBuggyConfig { @Parameter(names = {"-f", "--force"}, description = "Running all tests, including those that fall.") public static Boolean force = false; + @Parameter(names = {"-v", "--verbose"}, hidden = true, description = "Print all configuration parameters.") + public static Boolean verbose = false; + + private static String absoluteLogPath; + + public static void setAbsoluteLogPath(String path) { + absoluteLogPath = path; + } + + public static String getAbsoluteLogPath() { + return absoluteLogPath; + } } diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/IBuggyConfig.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/IBuggyConfig.java index 64d8470..cbf59f7 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/IBuggyConfig.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/IBuggyConfig.java @@ -1,8 +1,7 @@ package org.touchbit.buggy.spring.boot.starter; -import org.springframework.context.annotation.Configuration; - -@Configuration public interface IBuggyConfig { + + } diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/JCommanderConfiguration.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/JCommanderConfiguration.java index 13ec955..c103488 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/JCommanderConfiguration.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/JCommanderConfiguration.java @@ -1,54 +1,83 @@ package org.touchbit.buggy.spring.boot.starter; import com.beust.jcommander.JCommander; +import com.beust.jcommander.Parameter; import com.beust.jcommander.ParameterException; import com.beust.jcommander.Parameters; +import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.lang3.ClassUtils; import org.springframework.boot.ApplicationArguments; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnNotWebApplication; import org.springframework.context.annotation.*; -import org.springframework.core.annotation.Order; import org.touchbit.buggy.core.utils.StringUtils; +import java.lang.reflect.Field; +import java.lang.reflect.Method; import java.util.*; -import static org.touchbit.buggy.core.utils.BuggyUtils.CONSOLE_DELIMITER; +import static org.touchbit.buggy.core.utils.StringUtils.DOT; -//@Order(1) @Configuration @ConditionalOnNotWebApplication @ComponentScan(includeFilters = @ComponentScan.Filter( type = FilterType.ASSIGNABLE_TYPE, classes = {IBuggyConfig.class})) -public class JCommanderConfiguration { +public class JCommanderConfiguration extends BaseConfiguration { private final List list; private final String[] args; + private Map, IBuggyConfig> buggyConfigurations; public JCommanderConfiguration(List list, ApplicationArguments args) { this.list = list; this.args = args.getSourceArgs(); - StringUtils.println(CONSOLE_DELIMITER); - StringUtils.println("Loading IBuggyConfig implementations"); } - @Bean("initBuggyConfiguration") - public Map, IBuggyConfig> initBuggyConfiguration() { - StringUtils.println(CONSOLE_DELIMITER); - Map, IBuggyConfig> result = new HashMap<>(); - for (IBuggyConfig config : list) { - result.put(config.getClass(), config); - StringUtils.println(StringUtils - .dotFiller(config.getClass().getSimpleName(), 47, "OK")); + @Bean("initAndGetBuggyConfigurations") + public synchronized Map, IBuggyConfig> initAndGetBuggyConfigurations() { + if (buggyConfigurations == null) { + StringUtils.bPrint(); + StringUtils.println("JCommander configuration construction"); + StringUtils.sPrint(); + buggyConfigurations = new HashMap<>(); + for (IBuggyConfig config : list) { + buggyConfigurations.put(config.getClass(), config); + StringUtils.println(StringUtils + .dotFiller(config.getClass().getSimpleName(), "OK")); + } + JCommander jc = new JCommander(); + addConfiguration(jc, buggyConfigurations.values()); + try { + jc.parse(args); + StringUtils.sPrint(); + StringUtils.fPrint("Parsing arguments", DOT, "OK"); + printConfigurationParams(buggyConfigurations); + } catch (ParameterException e) { + BuggyConfig.verbose = true; + StringUtils.sPrint(); + StringUtils.fPrint("Parsing arguments", DOT, "FAIL"); + printConfigurationParams(buggyConfigurations); + exitRun(e); + } } - JCommander jc = new JCommander(); - addConfiguration(jc, result.values()); - try { - jc.parse(args); - } catch (ParameterException e) { - exitRunWithUsage(e); + return buggyConfigurations; + } + + @Bean("isBuggyConfigured") + public boolean isBuggyConfigured() { + return buggyConfigurations.containsKey(BuggyConfig.class); + } + + public void printConfigurationParams(Map, IBuggyConfig> configs) { + for (IBuggyConfig autowiredConfig : list) { + IBuggyConfig config = configs.get(autowiredConfig.getClass()); + String params = configurationToString(config); + if (!params.isEmpty()) { + StringUtils.sPrint(); + StringUtils.cPrint(config.getClass().getSimpleName()); + StringUtils.println(params); + } } - return result; } private void addConfiguration(JCommander jc, Collection configs) { @@ -62,15 +91,76 @@ private void addConfiguration(JCommander jc, Collection configs) { } } - public void exitRunWithUsage(ParameterException e) { - StringUtils.println(CONSOLE_DELIMITER); - e.usage(); - StringUtils.println(CONSOLE_DELIMITER); - StringUtils.println(e.getMessage()); - StringUtils.println(CONSOLE_DELIMITER); - StringUtils.println(StringUtils.dotFiller("Exit code", 47, 1)); - StringUtils.println(CONSOLE_DELIMITER); - System.exit(1); + static String configurationToString(IBuggyConfig 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(IBuggyConfig 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() || BuggyConfig.verbose)) { + String[] names = parameter.names(); + try { + if (parameter.password()) { + map.put(Arrays.toString(names), "********"); + } else { + field.setAccessible(true); + map.put(Arrays.toString(names), field.get(config)); + } + } catch (Exception e) { + if (BuggyConfig.verbose) { + StringUtils.println(e.getMessage()); + } + } finally { + field.setAccessible(false); + } + } + } } + static void addMethodsValuesToMap(IBuggyConfig 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() || BuggyConfig.verbose)) { + 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 e) { + if (BuggyConfig.verbose) { + StringUtils.println(e.getMessage()); + } + } + } + } } diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/LoggerConfiguration.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/LoggerConfiguration.java new file mode 100644 index 0000000..9a43adf --- /dev/null +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/LoggerConfiguration.java @@ -0,0 +1,149 @@ +package org.touchbit.buggy.spring.boot.starter; + +import org.apache.logging.log4j.core.config.LoggerConfig; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.AutoConfigureBefore; +import org.springframework.boot.autoconfigure.condition.ConditionalOnNotWebApplication; +import org.springframework.context.annotation.*; +import org.touchbit.buggy.core.utils.IOHelper; +import org.touchbit.buggy.core.utils.StringUtils; +import org.touchbit.buggy.core.utils.log.XMLLogConfigurator; + +import javax.annotation.PostConstruct; +import java.io.File; + +@Configuration() +@ConditionalOnNotWebApplication +@DependsOn({"initAndGetBuggyConfigurations", "isBuggyConfigured"}) +public class LoggerConfiguration extends BaseConfiguration { + + 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"; + + @Autowired + private static boolean isBuggyConfigured; + + private static Logger console; + private static Logger framework; + private static Logger test; + private static String logPath; + private static boolean isBuggyLoggerInitialized; + + public LoggerConfiguration() { + loadDefaultConfig(); + isBuggyLoggerInitialized = true; + } + + @Bean("isBuggyLoggerInitialized") + public boolean isBuggyLoggerInitialized() { + return isBuggyLoggerInitialized; + } + + public static String getLogsDirPath() { + return logPath; + } + + public static void setLogsDirPath(String path) { + if (path == null) { + exitRun("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; + org.apache.logging.log4j.core.config.Configuration configuration = 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) { todo +// } + configuration.getLoggerContext().reconfigure(); + setTestLog(LoggerFactory.getLogger("Routing")); + setConsoleLog(LoggerFactory.getLogger("Console")); + setFrameworkLog(LoggerFactory.getLogger("Framework")); + StringUtils.sPrint(); + StringUtils.fPrint("Logger", " ", "Level"); + StringUtils.sPrint(); + 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.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) { + LoggerConfiguration.console = console; + } + + public static void setFrameworkLog(Logger framework) { + LoggerConfiguration.framework = framework; + } + + public static void setTestLog(Logger test) { + LoggerConfiguration.test = test; + } + + private static void checkBuggyConfiguration() { + if (isBuggyConfigured) { + exitRun("The logger cannot be initialized before the Buggy configuration."); + } + if (logPath == null) { + setLogsDirPath("./"); + } + } + +} diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/SBBuggy.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/SBBuggy.java deleted file mode 100644 index 3ccfc23..0000000 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/SBBuggy.java +++ /dev/null @@ -1,72 +0,0 @@ -package org.touchbit.buggy.spring.boot.starter; - -import com.beust.jcommander.JCommander; -import com.beust.jcommander.ParameterException; -import com.beust.jcommander.Parameters; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.testng.TestNG; -import org.touchbit.buggy.core.config.SecondaryConfig; -import org.touchbit.buggy.core.utils.BuggyUtils; - -import java.util.ArrayList; -import java.util.List; - - -public class SBBuggy { - - private static int javaVersion = getVersion(); - - public static void main(String[] args) { -// args = new String[]{"-?"}; - JCommander jc = new JCommander(); -// jc.addObject(); - List> instantiatedSubclasses = BuggyUtils - .findInstantiatedSubclasses(IBuggyConfig.class); - List configs = new ArrayList<>(); - for (Class instantiatedSubclass : instantiatedSubclasses) { - try { - configs.add(instantiatedSubclass.newInstance()); - JCommander tempJc = new JCommander(); - for (IBuggyConfig config : configs) { - if (config.getClass().isAnnotationPresent(Parameters.class)) { - tempJc.addCommand(config); - } else { - tempJc.addObject(config); - } - } - try { - tempJc.parse(args); - if (javaVersion > 8) { - System.out.println(instantiatedSubclass.getSimpleName() + "......OK"); - } else { - System.out.println(instantiatedSubclass.getClass().getSimpleName() + "......OK"); - } - } catch (ParameterException e) { - if (javaVersion > 8) { - System.out.println(instantiatedSubclass.getSimpleName() + "....FAIL"); - } else { - System.out.println(instantiatedSubclass.getClass().getSimpleName() + "....FAIL"); - } - e.usage(); - throw (ParameterException) e.fillInStackTrace(); - } - } catch (InstantiationException | IllegalAccessException e) { - e.printStackTrace(); - } - } - jc.setProgramName("name"); - jc.parse(args); - jc.usage(); - } - - private static int getVersion() { - String version = System.getProperty("java.version"); - System.out.println(" >>>> " + version); - if(version.startsWith("1.")) { - version = version.substring(2, 3); - } else { - int dot = version.indexOf("."); - if(dot != -1) { version = version.substring(0, dot); } - } return Integer.parseInt(version); - } -} diff --git a/buggy-spring-boot-starter/src/main/resources/application.properties b/buggy-spring-boot-starter/src/main/resources/application.properties index 471ce01..2629c16 100644 --- a/buggy-spring-boot-starter/src/main/resources/application.properties +++ b/buggy-spring-boot-starter/src/main/resources/application.properties @@ -1 +1 @@ -#logging.level.root=OFF +logging.level.root=OFF \ No newline at end of file diff --git a/buggy-spring-boot-starter/src/main/resources/logging.properties b/buggy-spring-boot-starter/src/main/resources/logging.properties new file mode 100644 index 0000000..f8d3259 --- /dev/null +++ b/buggy-spring-boot-starter/src/main/resources/logging.properties @@ -0,0 +1,3 @@ +handlers=java.util.logging.FileHandler +java.util.logging.FileHandler.pattern=baeldung.log +java.util.logging.FileHandler.formatter=java.util.logging.SimpleFormatter From b6303da68bc998b01c0838c5ad3ef231cd9466e7 Mon Sep 17 00:00:00 2001 From: "oleg.shaburov" Date: Thu, 1 Oct 2020 20:59:48 +0300 Subject: [PATCH 03/24] Improve configuration --- buggy-core/pom.xml | 5 + .../spring/boot/starter/example/Command1.java | 13 -- .../spring/boot/starter/example/Command2.java | 16 -- .../spring/boot/starter/example/Command4.java | 16 -- .../spring/boot/starter/example/SBBuggy.java | 8 +- .../boot/starter/example/conf/Command1.java | 13 ++ .../boot/starter/example/conf/Command2.java | 16 ++ .../starter/example/{ => conf}/Command3.java | 10 +- .../boot/starter/example/conf/Command4.java | 25 +++ buggy-spring-boot-starter/pom.xml | 67 +++---- .../boot/starter/BaseConfiguration.java | 20 --- .../buggy/spring/boot/starter/Buggy.java | 10 +- .../boot/starter/BuggyAutoConfiguration.java | 39 ---- .../spring/boot/starter/BuggyConfig.java | 29 --- .../spring/boot/starter/IBuggyConfig.java | 7 - .../boot/starter/JCommanderConfiguration.java | 166 ----------------- .../boot/starter/LoggerConfiguration.java | 149 ---------------- .../spring/boot/starter/conf/BuggyConfig.java | 47 +++++ .../boot/starter/conf/JCConfiguration.java | 103 +++++++++++ .../boot/starter/conf/SBConfiguration.java | 34 ++++ .../conf/SBJCommanderConfiguration.java | 157 ++++++++++++++++ .../starter/conf/SBLogbackConfiguration.java | 144 +++++++++++++++ .../starter/conf/SBTestNGConfiguration.java | 46 +++++ .../buggy/spring/boot/starter/log/ANSI.java | 30 ++++ .../boot/starter/log/ConfigurationLogger.java | 167 ++++++++++++++++++ .../starter/log/ConsoleLoggerColorLayout.java | 53 ++++++ .../starter/log/FrameworkLoggerLayout.java | 46 +++++ .../spring/boot/starter/utils/JUtils.java | 80 +++++++++ .../main/resources/META-INF/spring.factories | 1 - .../src/main/resources/application.properties | 1 - .../src/main/resources/application.yml | 12 ++ .../src/main/resources/buggy-logback.xml | 51 ++++++ .../src/main/resources/logging.properties | 3 - 33 files changed, 1075 insertions(+), 509 deletions(-) delete mode 100644 buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/Command1.java delete mode 100644 buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/Command2.java delete mode 100644 buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/Command4.java create mode 100644 buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/conf/Command1.java create mode 100644 buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/conf/Command2.java rename buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/{ => conf}/Command3.java (55%) create mode 100644 buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/conf/Command4.java delete mode 100644 buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/BaseConfiguration.java delete mode 100644 buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/BuggyAutoConfiguration.java delete mode 100644 buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/BuggyConfig.java delete mode 100644 buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/IBuggyConfig.java delete mode 100644 buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/JCommanderConfiguration.java delete mode 100644 buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/LoggerConfiguration.java create mode 100644 buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/BuggyConfig.java create mode 100644 buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/JCConfiguration.java create mode 100644 buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBConfiguration.java create mode 100644 buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBJCommanderConfiguration.java create mode 100644 buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBLogbackConfiguration.java create mode 100644 buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBTestNGConfiguration.java create mode 100644 buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/log/ANSI.java create mode 100644 buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/log/ConfigurationLogger.java create mode 100644 buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/log/ConsoleLoggerColorLayout.java create mode 100644 buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/log/FrameworkLoggerLayout.java create mode 100644 buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/utils/JUtils.java delete mode 100644 buggy-spring-boot-starter/src/main/resources/application.properties create mode 100644 buggy-spring-boot-starter/src/main/resources/application.yml create mode 100644 buggy-spring-boot-starter/src/main/resources/buggy-logback.xml delete mode 100644 buggy-spring-boot-starter/src/main/resources/logging.properties diff --git a/buggy-core/pom.xml b/buggy-core/pom.xml index 6d94494..7e8d2b4 100644 --- a/buggy-core/pom.xml +++ b/buggy-core/pom.xml @@ -37,6 +37,11 @@ org.apache.commons commons-lang3 + + org.aspectj + aspectjweaver + 1.9.6 + org.apache.logging.log4j diff --git a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/Command1.java b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/Command1.java deleted file mode 100644 index b7e9d03..0000000 --- a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/Command1.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.touchbit.buggy.spring.boot.starter.example; - -import com.beust.jcommander.Parameter; -import org.touchbit.buggy.spring.boot.starter.IBuggyConfig; - -public class Command1 implements IBuggyConfig { - - @Parameter(names = {"--f"}, description = "Running all tests, including those that fall.") - private Boolean force =null; - - @Parameter(names = {"-a"}, description = "FFFFFFFFFFFFFFFFFFFFF.") - private Boolean a = null; -} diff --git a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/Command2.java b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/Command2.java deleted file mode 100644 index 45213b6..0000000 --- a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/Command2.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.touchbit.buggy.spring.boot.starter.example; - -import com.beust.jcommander.Parameter; -import com.beust.jcommander.Parameters; -import org.touchbit.buggy.spring.boot.starter.IBuggyConfig; - - -public class Command2 implements IBuggyConfig { - - @Parameter(names = {"-?", "--help"}, hidden = true, help = true, description = "Print usage.") - private Boolean help = null; - - @Parameter(names = {"-ad"}, description = "FFFFFFFFFFFFFFFFFFFFF.") - private Boolean a = null; - -} diff --git a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/Command4.java b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/Command4.java deleted file mode 100644 index 0815b89..0000000 --- a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/Command4.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.touchbit.buggy.spring.boot.starter.example; - -import com.beust.jcommander.Parameter; -import com.beust.jcommander.Parameters; -import org.touchbit.buggy.spring.boot.starter.IBuggyConfig; - -@Parameters(commandNames = "c2") -public class Command4 implements IBuggyConfig { - - @Parameter(names = {"---?"}, hidden = true, help = true, description = "Print usage.") - private Boolean help = null; - - @Parameter(names = {"-a"}, description = "FFFFFFFFFFFFFFFFFFFFF.") - private Boolean a = null; - -} diff --git a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/SBBuggy.java b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/SBBuggy.java index 3333f7c..c9386dc 100644 --- a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/SBBuggy.java +++ b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/SBBuggy.java @@ -1,13 +1,17 @@ package org.touchbit.buggy.spring.boot.starter.example; import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; import org.touchbit.buggy.spring.boot.starter.Buggy; +import org.touchbit.buggy.spring.boot.starter.conf.BuggyConfig; public class SBBuggy extends Buggy { + static { + BuggyConfig.setForce(true); + } + public static void main(String[] args) { - args = new String[]{"--force", "-v"}; +// args = new String[]{"--force", "-v"}; SpringApplication.run(SBBuggy.class, args); } diff --git a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/conf/Command1.java b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/conf/Command1.java new file mode 100644 index 0000000..55f96d9 --- /dev/null +++ b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/conf/Command1.java @@ -0,0 +1,13 @@ +package org.touchbit.buggy.spring.boot.starter.example.conf; + +import com.beust.jcommander.Parameter; +import org.touchbit.buggy.spring.boot.starter.conf.JCConfiguration; + +public class Command1 implements JCConfiguration { + + @Parameter(names = {"--f"}, description = "Running all tests, including those that fall.") + private static Boolean force =null; + + @Parameter(names = {"-a"}, description = "FFFFFFFFFFFFFFFFFFFFF.") + private static Boolean a = null; +} diff --git a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/conf/Command2.java b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/conf/Command2.java new file mode 100644 index 0000000..4da7e9c --- /dev/null +++ b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/conf/Command2.java @@ -0,0 +1,16 @@ +package org.touchbit.buggy.spring.boot.starter.example.conf; + +import com.beust.jcommander.Parameter; +import com.beust.jcommander.Parameters; +import org.touchbit.buggy.spring.boot.starter.conf.JCConfiguration; + +@Parameters() +public class Command2 implements JCConfiguration { + + @Parameter(names = {"-?", "--help"}, hidden = true, help = true, description = "Print usage.") + private static Boolean help = null; + + @Parameter(names = {"-----f"}, description = "FFFFFFFFFFFFFFFFFFFFF.") + private static Boolean a = null; + +} diff --git a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/Command3.java b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/conf/Command3.java similarity index 55% rename from buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/Command3.java rename to buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/conf/Command3.java index 4d371d6..191e3a1 100644 --- a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/Command3.java +++ b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/conf/Command3.java @@ -1,16 +1,16 @@ -package org.touchbit.buggy.spring.boot.starter.example; +package org.touchbit.buggy.spring.boot.starter.example.conf; import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; -import org.touchbit.buggy.spring.boot.starter.IBuggyConfig; +import org.touchbit.buggy.spring.boot.starter.conf.JCConfiguration; @Parameters(commandNames = {"c1"}, commandDescription = "secondary config") -public class Command3 implements IBuggyConfig { +public class Command3 implements JCConfiguration { @Parameter(names = {"----?"}, hidden = true, help = true, description = "Print usage.") - private Boolean help = null; + private static Boolean help = null; @Parameter(names = {"-a"}, description = "FFFFFFFFFFFFFFFFFFFFF.") - private Boolean a = null; + private static Boolean a = null; } diff --git a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/conf/Command4.java b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/conf/Command4.java new file mode 100644 index 0000000..7695550 --- /dev/null +++ b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/conf/Command4.java @@ -0,0 +1,25 @@ +package org.touchbit.buggy.spring.boot.starter.example.conf; + +import com.beust.jcommander.Parameter; +import com.beust.jcommander.Parameters; +import org.touchbit.buggy.spring.boot.starter.conf.JCConfiguration; + +@Parameters(commandNames = "c2") +public class Command4 implements JCConfiguration { + + @Parameter(names = {"---?"}, hidden = true, help = true, description = "Print usage.") + private static Boolean help = null; + + private static Boolean a = null; + +// @Parameter(names = {"-a"}, description = "FFFFFFFFFFFFFFFFFFFFF.") + public static Boolean getA() { + return a; + } + + @Parameter(names = {"-a"}, description = "FFFFFFFFFFFFFFFFFFFFF.") + public static void setA(Boolean a) { + Command4.a = a; + } + +} diff --git a/buggy-spring-boot-starter/pom.xml b/buggy-spring-boot-starter/pom.xml index fc77f06..6627411 100644 --- a/buggy-spring-boot-starter/pom.xml +++ b/buggy-spring-boot-starter/pom.xml @@ -1,6 +1,6 @@ - 4.0.0 @@ -26,6 +26,33 @@ org.touchbit.buggy buggy-core 0.3.7 + + + 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 + + + + + ch.qos.logback + logback-classic + 1.2.3 com.beust @@ -41,26 +68,12 @@ org.springframework.boot spring-boot-starter 2.3.4.RELEASE - - - ch.qos.logback - logback-classic - - - org.springframework.boot - spring-boot-starter-logging - - - org.apache.logging.log4j - log4j-to-slf4j - - - - - - - + + org.springframework.boot + spring-boot-starter-logging + 2.3.4.RELEASE + org.springframework.boot spring-boot-configuration-processor @@ -73,18 +86,6 @@ 2.3.4.RELEASE test - - - org.touchbit.buggy - buggy-core - test-jar - - - org.atteo.classindex - classindex - 3.7 - compile - \ No newline at end of file diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/BaseConfiguration.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/BaseConfiguration.java deleted file mode 100644 index efabf06..0000000 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/BaseConfiguration.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.touchbit.buggy.spring.boot.starter; - -import org.touchbit.buggy.core.utils.StringUtils; - -public abstract class BaseConfiguration { - - public static void exitRun(Exception e) { - exitRun(e.getMessage()); - } - - public static void exitRun(String message) { - StringUtils.bPrint(); - StringUtils.println(message); - StringUtils.bPrint(); - StringUtils.println(StringUtils.dotFiller("Exit code", "1")); - StringUtils.bPrint(); - System.exit(1); - } - -} diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/Buggy.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/Buggy.java index bf53b53..f1b0298 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/Buggy.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/Buggy.java @@ -2,17 +2,9 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; -import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.context.logging.LoggingApplicationListener; -import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; -import org.springframework.context.ApplicationListener; import org.testng.TestNG; -import java.lang.reflect.Field; -import java.util.List; - @SpringBootApplication public abstract class Buggy implements CommandLineRunner { @@ -21,7 +13,7 @@ public abstract class Buggy implements CommandLineRunner { @Override public void run(final String... args) throws Exception { - System.out.println(" >>>> RUN"); + System.out.println(" >>>> RUN: " + testNG); } } diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/BuggyAutoConfiguration.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/BuggyAutoConfiguration.java deleted file mode 100644 index 8c9c5fb..0000000 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/BuggyAutoConfiguration.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.touchbit.buggy.spring.boot.starter; - -import org.slf4j.Logger; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.AutoConfigureBefore; -import org.springframework.boot.autoconfigure.condition.ConditionalOnNotWebApplication; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.DependsOn; -import org.springframework.stereotype.Component; -import org.testng.TestNG; -import org.touchbit.buggy.core.utils.StringUtils; -import org.touchbit.buggy.core.utils.log.BuggyLog; - -import static org.touchbit.buggy.core.utils.BuggyUtils.CONSOLE_DELIMITER; - -@Configuration() -@DependsOn({"initAndGetBuggyConfigurations", "isBuggyLoggerInitialized"}) -@ConditionalOnNotWebApplication -public class BuggyAutoConfiguration { - - private Logger consoleLogger; - - public BuggyAutoConfiguration(boolean isBuggyLoggerInitialized) { - if (isBuggyLoggerInitialized) { - consoleLogger = LoggerConfiguration.console(); - consoleLogger.info(" <<<<<<>>>>>>>>>"); - } - StringUtils.println(CONSOLE_DELIMITER); - StringUtils.println("Loading TestNG configuration"); - } - - @Bean - public TestNG testNG() { - StringUtils.println(CONSOLE_DELIMITER); - return new TestNG(); - } - -} diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/BuggyConfig.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/BuggyConfig.java deleted file mode 100644 index 379c3da..0000000 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/BuggyConfig.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.touchbit.buggy.spring.boot.starter; - -import com.beust.jcommander.Parameter; -import org.atteo.classindex.IndexSubclasses; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.annotation.Order; -import org.springframework.stereotype.Component; - -import static org.touchbit.buggy.core.config.BParameters.ALL; - -@Order(1) -public class BuggyConfig implements IBuggyConfig { - - @Parameter(names = {"-f", "--force"}, description = "Running all tests, including those that fall.") - public static Boolean force = false; - - @Parameter(names = {"-v", "--verbose"}, hidden = true, description = "Print all configuration parameters.") - public static Boolean verbose = false; - - private static String absoluteLogPath; - - public static void setAbsoluteLogPath(String path) { - absoluteLogPath = path; - } - - public static String getAbsoluteLogPath() { - return absoluteLogPath; - } -} diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/IBuggyConfig.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/IBuggyConfig.java deleted file mode 100644 index cbf59f7..0000000 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/IBuggyConfig.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.touchbit.buggy.spring.boot.starter; - -public interface IBuggyConfig { - - - -} diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/JCommanderConfiguration.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/JCommanderConfiguration.java deleted file mode 100644 index c103488..0000000 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/JCommanderConfiguration.java +++ /dev/null @@ -1,166 +0,0 @@ -package org.touchbit.buggy.spring.boot.starter; - -import com.beust.jcommander.JCommander; -import com.beust.jcommander.Parameter; -import com.beust.jcommander.ParameterException; -import com.beust.jcommander.Parameters; -import org.apache.commons.lang3.ArrayUtils; -import org.apache.commons.lang3.ClassUtils; -import org.springframework.boot.ApplicationArguments; -import org.springframework.boot.autoconfigure.condition.ConditionalOnNotWebApplication; -import org.springframework.context.annotation.*; -import org.touchbit.buggy.core.utils.StringUtils; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.*; - -import static org.touchbit.buggy.core.utils.StringUtils.DOT; - -@Configuration -@ConditionalOnNotWebApplication -@ComponentScan(includeFilters = @ComponentScan.Filter( - type = FilterType.ASSIGNABLE_TYPE, - classes = {IBuggyConfig.class})) -public class JCommanderConfiguration extends BaseConfiguration { - - private final List list; - private final String[] args; - private Map, IBuggyConfig> buggyConfigurations; - - public JCommanderConfiguration(List list, ApplicationArguments args) { - this.list = list; - this.args = args.getSourceArgs(); - } - - @Bean("initAndGetBuggyConfigurations") - public synchronized Map, IBuggyConfig> initAndGetBuggyConfigurations() { - if (buggyConfigurations == null) { - StringUtils.bPrint(); - StringUtils.println("JCommander configuration construction"); - StringUtils.sPrint(); - buggyConfigurations = new HashMap<>(); - for (IBuggyConfig config : list) { - buggyConfigurations.put(config.getClass(), config); - StringUtils.println(StringUtils - .dotFiller(config.getClass().getSimpleName(), "OK")); - } - JCommander jc = new JCommander(); - addConfiguration(jc, buggyConfigurations.values()); - try { - jc.parse(args); - StringUtils.sPrint(); - StringUtils.fPrint("Parsing arguments", DOT, "OK"); - printConfigurationParams(buggyConfigurations); - } catch (ParameterException e) { - BuggyConfig.verbose = true; - StringUtils.sPrint(); - StringUtils.fPrint("Parsing arguments", DOT, "FAIL"); - printConfigurationParams(buggyConfigurations); - exitRun(e); - } - } - return buggyConfigurations; - } - - @Bean("isBuggyConfigured") - public boolean isBuggyConfigured() { - return buggyConfigurations.containsKey(BuggyConfig.class); - } - - public void printConfigurationParams(Map, IBuggyConfig> configs) { - for (IBuggyConfig autowiredConfig : list) { - IBuggyConfig config = configs.get(autowiredConfig.getClass()); - String params = configurationToString(config); - if (!params.isEmpty()) { - StringUtils.sPrint(); - StringUtils.cPrint(config.getClass().getSimpleName()); - StringUtils.println(params); - } - } - } - - private void addConfiguration(JCommander jc, Collection configs) { - for (IBuggyConfig c : configs) { - if (c.getClass().isAnnotationPresent(Parameters.class) && - c.getClass().getAnnotation(Parameters.class).commandNames().length > 0) { - jc.addCommand(c); - } else { - jc.addObject(c); - } - } - } - - static String configurationToString(IBuggyConfig 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(IBuggyConfig 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() || BuggyConfig.verbose)) { - String[] names = parameter.names(); - try { - if (parameter.password()) { - map.put(Arrays.toString(names), "********"); - } else { - field.setAccessible(true); - map.put(Arrays.toString(names), field.get(config)); - } - } catch (Exception e) { - if (BuggyConfig.verbose) { - StringUtils.println(e.getMessage()); - } - } finally { - field.setAccessible(false); - } - } - } - } - - static void addMethodsValuesToMap(IBuggyConfig 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() || BuggyConfig.verbose)) { - 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 e) { - if (BuggyConfig.verbose) { - StringUtils.println(e.getMessage()); - } - } - } - } -} diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/LoggerConfiguration.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/LoggerConfiguration.java deleted file mode 100644 index 9a43adf..0000000 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/LoggerConfiguration.java +++ /dev/null @@ -1,149 +0,0 @@ -package org.touchbit.buggy.spring.boot.starter; - -import org.apache.logging.log4j.core.config.LoggerConfig; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.MDC; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.AutoConfigureBefore; -import org.springframework.boot.autoconfigure.condition.ConditionalOnNotWebApplication; -import org.springframework.context.annotation.*; -import org.touchbit.buggy.core.utils.IOHelper; -import org.touchbit.buggy.core.utils.StringUtils; -import org.touchbit.buggy.core.utils.log.XMLLogConfigurator; - -import javax.annotation.PostConstruct; -import java.io.File; - -@Configuration() -@ConditionalOnNotWebApplication -@DependsOn({"initAndGetBuggyConfigurations", "isBuggyConfigured"}) -public class LoggerConfiguration extends BaseConfiguration { - - 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"; - - @Autowired - private static boolean isBuggyConfigured; - - private static Logger console; - private static Logger framework; - private static Logger test; - private static String logPath; - private static boolean isBuggyLoggerInitialized; - - public LoggerConfiguration() { - loadDefaultConfig(); - isBuggyLoggerInitialized = true; - } - - @Bean("isBuggyLoggerInitialized") - public boolean isBuggyLoggerInitialized() { - return isBuggyLoggerInitialized; - } - - public static String getLogsDirPath() { - return logPath; - } - - public static void setLogsDirPath(String path) { - if (path == null) { - exitRun("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; - org.apache.logging.log4j.core.config.Configuration configuration = 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) { todo -// } - configuration.getLoggerContext().reconfigure(); - setTestLog(LoggerFactory.getLogger("Routing")); - setConsoleLog(LoggerFactory.getLogger("Console")); - setFrameworkLog(LoggerFactory.getLogger("Framework")); - StringUtils.sPrint(); - StringUtils.fPrint("Logger", " ", "Level"); - StringUtils.sPrint(); - 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.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) { - LoggerConfiguration.console = console; - } - - public static void setFrameworkLog(Logger framework) { - LoggerConfiguration.framework = framework; - } - - public static void setTestLog(Logger test) { - LoggerConfiguration.test = test; - } - - private static void checkBuggyConfiguration() { - if (isBuggyConfigured) { - exitRun("The logger cannot be initialized before the Buggy configuration."); - } - if (logPath == null) { - setLogsDirPath("./"); - } - } - -} diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/BuggyConfig.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/BuggyConfig.java new file mode 100644 index 0000000..a45cd66 --- /dev/null +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/BuggyConfig.java @@ -0,0 +1,47 @@ +package org.touchbit.buggy.spring.boot.starter.conf; + +import com.beust.jcommander.Parameter; +import org.springframework.core.annotation.Order; + +/** + * Configuration class for customizing Buggy. + *

+ * Created by Oleg Shaburov on 01.10.2020 + * shaburov.o.a@gmail.com + */ +@Order(1) +public class BuggyConfig implements JCConfiguration { + + @Parameter(names = {"-f", "--force"}, description = "Running all tests, including those that fall.") + private static Boolean force = false; + + @Parameter(names = {"-v", "--verbose"}, hidden = true, description = "Print all configuration parameters.") + private static Boolean verbose = false; + + private static String absoluteLogPath; + + public static Boolean getForce() { + return force; + } + + public static void setForce(boolean force) { + BuggyConfig.force = force; + } + + public static Boolean getVerbose() { + return verbose; + } + + public static void setVerbose(Boolean verbose) { + BuggyConfig.verbose = verbose; + } + + public static String getAbsoluteLogPath() { + return absoluteLogPath; + } + + public static void setAbsoluteLogPath(String absoluteLogPath) { + BuggyConfig.absoluteLogPath = absoluteLogPath; + } + +} diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/JCConfiguration.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/JCConfiguration.java new file mode 100644 index 0000000..ad7cc9e --- /dev/null +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/JCConfiguration.java @@ -0,0 +1,103 @@ +package org.touchbit.buggy.spring.boot.starter.conf; + +import com.beust.jcommander.Parameter; +import org.touchbit.buggy.spring.boot.starter.log.ConfigurationLogger; +import org.touchbit.buggy.spring.boot.starter.utils.JUtils; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.*; + +/** + * An interface for finding all inherited {@link com.beust.jcommander.JCommander} configuration classes. + * Search is performed using spring-boot annotation @ComponentScan. + *

+ * All fields and setter-methods marked with {@link Parameter} annotation must be static. + *

+ * Your config classes should be in the "buggy" package since ComponentScan + * is limited to filter (basePackages = "**.buggy") to speed up the search for all inheritors. + * For example: org.example.foo.bar.buggy.MyConfiguration.class (implements IBuggyConfig). + *

+ * Created by Oleg Shaburov on 01.10.2020 + * shaburov.o.a@gmail.com + */ +public interface JCConfiguration { + + /** + * 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); + Map sorted = new LinkedHashMap<>(); + map.entrySet().stream() + .sorted(Map.Entry.comparingByKey()) + .forEachOrdered(k -> sorted.put(k.getKey(), k.getValue())); + return sorted; + } + + /** + * 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(); + try { + if (parameter.password()) { + map.put(Arrays.toString(names), "*****"); + } else { + field.setAccessible(true); + map.put(Arrays.toString(names), field.get(this)); + } + } catch (Exception e) { + ConfigurationLogger.errPrint(e.getMessage()); + } 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(2); + 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) { + ConfigurationLogger.errPrint(e.getMessage()); // TODO + } finally { + method.getValue().setAccessible(false); + } + } + } + +} diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBConfiguration.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBConfiguration.java new file mode 100644 index 0000000..31d8a52 --- /dev/null +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBConfiguration.java @@ -0,0 +1,34 @@ +package org.touchbit.buggy.spring.boot.starter.conf; + +import org.touchbit.buggy.spring.boot.starter.log.ConfigurationLogger; + +/** + * Interface for Buggy spring boot configurations + *

+ * Created by Oleg Shaburov on 01.10.2020 + * shaburov.o.a@gmail.com + */ +public interface SBConfiguration { + + default void exitRunWithErr(Exception e) { + exitRunWithErr(e.getMessage()); + } + + default void exitRunWithErr(String message) { + exitRun(1, message); + } + + default void exitRun(int status, String message) { + ConfigurationLogger.bPrint(); + if (status == 0) { + ConfigurationLogger.print(message); + } else { + ConfigurationLogger.errPrint(message); + } + ConfigurationLogger.bPrint(); + ConfigurationLogger.fdPrint("Exit code", status); + ConfigurationLogger.bPrint(); + System.exit(status); + } + +} diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBJCommanderConfiguration.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBJCommanderConfiguration.java new file mode 100644 index 0000000..c876ab7 --- /dev/null +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBJCommanderConfiguration.java @@ -0,0 +1,157 @@ +package org.touchbit.buggy.spring.boot.starter.conf; + +import com.beust.jcommander.JCommander; +import com.beust.jcommander.Parameter; +import com.beust.jcommander.ParameterException; +import com.beust.jcommander.Parameters; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.autoconfigure.condition.ConditionalOnNotWebApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.touchbit.buggy.spring.boot.starter.log.ConfigurationLogger; +import org.touchbit.buggy.spring.boot.starter.utils.JUtils; + +import javax.annotation.PostConstruct; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.*; + +import static org.springframework.context.annotation.FilterType.ASSIGNABLE_TYPE; + +/** + * {@link JCommander} spring boot configuration class. + * {@link ComponentScan} searches for all implementations of the {@link JCConfiguration} 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 +@ComponentScan( + basePackages = "**.buggy", + useDefaultFilters = false, + includeFilters = @ComponentScan.Filter(type = ASSIGNABLE_TYPE, classes = JCConfiguration.class)) +public class SBJCommanderConfiguration implements SBConfiguration { + + private final List list; + private final String[] args; + private Map, JCConfiguration> buggyConfigurations; + + public SBJCommanderConfiguration(List list, ApplicationArguments args) { + this.list = list; + this.args = args.getSourceArgs(); + init(); + } + + @Bean("initAndGetBuggyConfigurations") + public Map, JCConfiguration> getBuggyConfigurations() { + return buggyConfigurations; + } + + @Bean("isBuggyConfigured") + public boolean isBuggyConfigured() { + return buggyConfigurations.containsKey(BuggyConfig.class); + } + + @PostConstruct + public void postConstruct() { + printConfigurationsParams(buggyConfigurations); + } + + public void init() { + if (buggyConfigurations == null) { + ConfigurationLogger.bPrint(); + ConfigurationLogger.cbPrint("JCommander configuration construction"); + ConfigurationLogger.sPrint(); + buggyConfigurations = new HashMap<>(); + JCommander jc = new JCommander(); + for (JCConfiguration config : list) { + buggyConfigurations.put(config.getClass(), config); + checkConfiguration(config); + if (config.getClass().isAnnotationPresent(Parameters.class) && + config.getClass().getAnnotation(Parameters.class).commandNames().length > 0) { + jc.addCommand(config); + } else { + jc.addObject(config); + } + ConfigurationLogger.fdPrint(config.getClass().getSimpleName(), "OK"); + } + try { + jc.parse(args); + ConfigurationLogger.sPrint(); + ConfigurationLogger.fdPrint("Parsing arguments", "OK"); + } catch (Exception e) { + ConfigurationLogger.sPrint(); + ConfigurationLogger.fdPrint("Parsing arguments", "FAIL"); + printConfigurationsParams(buggyConfigurations); + if (!(e instanceof ParameterException)) { + e.printStackTrace(); + } + exitRunWithErr(e); + } + } + } + + public void checkConfiguration(JCConfiguration config) { + for (Field field : JUtils.getFields(config)) { + Parameter parameter = field.getAnnotation(Parameter.class); + if (parameter != null && !Modifier.isStatic(field.getModifiers())) { + String[] names = parameter.names(); + ConfigurationLogger.fdPrint(config.getClass().getSimpleName(), "FAIL"); + printConfigurationParams(config); + exitRunWithErr("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) { + ConfigurationLogger.fdPrint(config.getClass().getSimpleName(), "FAIL"); + printConfigurationParams(config); + exitRunWithErr(error); + } + } + } + } + + public void printConfigurationsParams(Map, JCConfiguration> configs) { + for (JCConfiguration autowiredConfig : list) { + JCConfiguration config = configs.get(autowiredConfig.getClass()); + printConfigurationParams(config); + } + } + + public void printConfigurationParams(JCConfiguration config) { + Map params = config.configurationToMap(); + if (params != null && !params.isEmpty()) { + ConfigurationLogger.sPrint(); + ConfigurationLogger.cPrint(config.getClass().getSimpleName()); + for (Map.Entry entry : params.entrySet()) { + ConfigurationLogger.fdPrint(entry.getKey(), entry.getValue()); + } + } + } + +} diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBLogbackConfiguration.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBLogbackConfiguration.java new file mode 100644 index 0000000..c67c1ca --- /dev/null +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBLogbackConfiguration.java @@ -0,0 +1,144 @@ +package org.touchbit.buggy.spring.boot.starter.conf; + +import ch.qos.logback.classic.LoggerContext; +import ch.qos.logback.classic.joran.JoranConfigurator; +import ch.qos.logback.core.joran.spi.JoranException; +import ch.qos.logback.core.util.Loader; +import ch.qos.logback.core.util.StatusPrinter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.autoconfigure.condition.ConditionalOnNotWebApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.DependsOn; +import org.springframework.core.env.Environment; +import org.touchbit.buggy.spring.boot.starter.log.ConfigurationLogger; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.net.URL; + +/** + * Logback loggers configuration + *

+ * Created by Oleg Shaburov on 30.09.2020 + * shaburov.o.a@gmail.com + */ +@Configuration() +@ConditionalOnNotWebApplication +@DependsOn({"initAndGetBuggyConfigurations", "isBuggyConfigured"}) +public class SBLogbackConfiguration implements SBConfiguration { + + public static final String LOG_FILE_NAME = "log.file.name"; + public static final String LOG_DIRECTORY = "log.directory"; + protected static final String LOGBACK_XML = "logback.xml"; + protected static final String BUGGY_LOGBACK_XML = "buggy-logback.xml"; + protected static final String DEFAULT_LOGGING_CONFIG_VALUE = "classpath:" + BUGGY_LOGBACK_XML; + private static Logger console; + private static Logger framework; + private static Logger test; + private final boolean isBuggyLoggerInitialized; + private final String loggingConfigFile; + + public SBLogbackConfiguration(Environment env) { + loggingConfigFile = env.getProperty("logging.config"); + ConfigurationLogger.bPrint(); + ConfigurationLogger.cbPrint("Loading logback configuration"); + ConfigurationLogger.sPrint(); + URL logbackXml = getResource(LOGBACK_XML, this.getClass()); + URL buggyLogbackXml = getResource("buggy-logback.xml", this.getClass()); + LoggerContext context = null; + if (logbackXml != null) { + ConfigurationLogger.fPrint(LOGBACK_XML, ".", "OK"); + context = reloadLogger(logbackXml); + } else { + ConfigurationLogger.fPrint(LOGBACK_XML, ".", "FAIL"); + } + + if (logbackXml == null && buggyLogbackXml != null) { + ConfigurationLogger.fPrint(BUGGY_LOGBACK_XML, ".", "OK"); + context = reloadLogger(buggyLogbackXml); + } else { + ConfigurationLogger.fPrint(BUGGY_LOGBACK_XML, ".", "FAIL"); + exitRunWithErr("Logback configuration not found"); + } + if (context != null) { + setTestLog(LoggerFactory.getLogger("Routing")); + setConsoleLog(LoggerFactory.getLogger("Console")); + setFrameworkLog(LoggerFactory.getLogger("Framework")); + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + PrintStream printStream = new PrintStream(stream); + StatusPrinter.setPrintStream(printStream); + StatusPrinter.printInCaseOfErrorsOrWarnings(context); + framework.info(stream.toString()); + for (ch.qos.logback.classic.Logger logger : context.getLoggerList()) { + if (logger.getLevel() != null) { + String name = logger.getName(); + try { + Class c = this.getClass().getClassLoader().loadClass(name); + name = c.getSimpleName() + ".class"; + } catch (ClassNotFoundException ignore) { + } + console.info(ConfigurationLogger.filler(name, ".", logger.getLevel())); + } + } + } + isBuggyLoggerInitialized = true; + } + + @Bean("isBuggyLoggerInitialized") + public boolean isBuggyLoggerInitialized() { + return isBuggyLoggerInitialized; + } + + public static Logger console() { + return console; + } + + public static Logger test() { + return test; + } + + public static Logger framework() { + return framework; + } + + public LoggerContext reloadLogger(URL config) { + ConfigurationLogger.sPrint(); + LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); + // Already loaded. Return current context. + if (DEFAULT_LOGGING_CONFIG_VALUE.equals(loggingConfigFile)) { + return loggerContext; + } + try { + JoranConfigurator configurator = new JoranConfigurator(); + configurator.setContext(loggerContext); + loggerContext.reset(); + configurator.doConfigure(config); + } catch (JoranException ignore) { + } + return loggerContext; + } + + public URL getResource(String filename, Class c) { + try { + ClassLoader myClassLoader = Loader.getClassLoaderOfObject(c); + return Loader.getResource(filename, myClassLoader); + } catch (Exception ignore) { + return null; + } + } + + public void setConsoleLog(Logger console) { + SBLogbackConfiguration.console = console; + } + + public void setFrameworkLog(Logger framework) { + SBLogbackConfiguration.framework = framework; + } + + public void setTestLog(Logger test) { + SBLogbackConfiguration.test = test; + } + +} diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBTestNGConfiguration.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBTestNGConfiguration.java new file mode 100644 index 0000000..e5da23a --- /dev/null +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBTestNGConfiguration.java @@ -0,0 +1,46 @@ +package org.touchbit.buggy.spring.boot.starter.conf; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.condition.ConditionalOnNotWebApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.DependsOn; +import org.testng.TestNG; +import org.touchbit.buggy.spring.boot.starter.log.ConfigurationLogger; + +import java.util.Map; + + +/** + * TestNG configuration + * Filter test classes for suites by: + * 1. {@link org.touchbit.buggy.core.process.Component}* + * 2. {@link org.touchbit.buggy.core.process.Service}* + * 3. {@link org.touchbit.buggy.core.process.Interface}* + *

+ * Created by Oleg Shaburov on 01.10.2020 + * shaburov.o.a@gmail.com + */ +@Configuration() +@ConditionalOnNotWebApplication +@DependsOn({"initAndGetBuggyConfigurations", "isBuggyLoggerInitialized"}) +public class SBTestNGConfiguration implements SBConfiguration { + + @Autowired + Map, JCConfiguration> getBuggyConfigurations; + + public SBTestNGConfiguration(boolean isBuggyLoggerInitialized) { + if (!isBuggyLoggerInitialized) { + exitRunWithErr("Logger must be initialized"); + } + ConfigurationLogger.bPrint(); + ConfigurationLogger.cbPrint("Loading TestNG configuration"); + } + + @Bean + public TestNG testNG() { + ConfigurationLogger.sPrint(); + return new TestNG(); + } + +} diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/log/ANSI.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/log/ANSI.java new file mode 100644 index 0000000..91983a9 --- /dev/null +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/log/ANSI.java @@ -0,0 +1,30 @@ +package org.touchbit.buggy.spring.boot.starter.log; + +public enum ANSI { + + RESET("\u001B[0m"), + BOLD("\u001B[1m"), + RED("\u001B[31m"), + GREEN("\u001B[32m"), + BLUE("\u001B[34m"), + PURPLE("\u001B[35m"), + ; + + String symbol; + + ANSI(String symbol) { + this.symbol = symbol; + } + + public static String unwrap(String msg) { + for (ANSI value : ANSI.values()) { + msg = msg.replace(value.symbol, ""); + } + return msg; + } + + public String wrap(String msg) { + return this.symbol + msg + RESET.symbol; + } + +} diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/log/ConfigurationLogger.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/log/ConfigurationLogger.java new file mode 100644 index 0000000..b743d23 --- /dev/null +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/log/ConfigurationLogger.java @@ -0,0 +1,167 @@ +package org.touchbit.buggy.spring.boot.starter.log; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.StringJoiner; + +import static java.util.Objects.isNull; +import static org.touchbit.buggy.spring.boot.starter.log.ANSI.BOLD; +import static org.touchbit.buggy.spring.boot.starter.log.ANSI.RED; + +/** + * Utility class for logging configuration events in TestNG format + *

+ * Created by Oleg Shaburov on 01.10.2020 + * shaburov.o.a@gmail.com + */ +public class ConfigurationLogger { + + public static final int STRING_LEN = 47; + public static final String BLOCK = "="; + public static final String STEP = "\u2014"; + public static final String DOT = "."; + + private static final Logger CONSOLE = LoggerFactory.getLogger(ConfigurationLogger.class); + + private ConfigurationLogger() { + throw new IllegalStateException("Utility class. Prohibit instantiation."); + } + + 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) { + return dotFiller(prefix, STRING_LEN, null); + } + + public static String dotFiller(Object prefix, int i, Object suffix) { + return filler(prefix, DOT, i, suffix); + } + + public static String dotFiller(Object prefix, Object suffix) { + return filler(prefix, ".", STRING_LEN, suffix); + } + + public static String filler(Object prefix, String symbol, int i) { + return filler(prefix, symbol, i, null); + } + + public static String filler(String symbol) { + return filler(null, symbol, STRING_LEN, null); + } + + public static String filler(Object prefix, String symbol) { + return filler(prefix, symbol, STRING_LEN, null); + } + + public static String filler(Object prefix, String symbol, Object postfix) { + return filler(prefix, symbol, 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 sPrint() { + print(filler(STEP)); + } + + public static void bPrint() { + print(filler(BLOCK)); + } + + public static void fdPrint(Object prefix, Object postfix) { + print(filler(prefix, DOT, postfix)); + } + + public static void fPrint(Object prefix, String symbol, Object postfix) { + print(filler(prefix, symbol, postfix)); + } + + public static void cbPrint(String msg) { + print(BOLD.wrap(center(msg))); + } + + public static void cPrint(String msg) { + print(center(msg)); + } + + private static String center(String msg) { + if (msg != null && !msg.isEmpty()) { + int diff = STRING_LEN - msg.length(); + if (diff > 0) { + int indent = diff / 2; + return filler("", " ", indent, "") + msg; + } + } + return msg; + } + + public static void print(String msg) { + CONSOLE.info(msg); + } + + public static void errPrint(String msg, Exception t) { + String breakMsg = lineBreak(msg); + CONSOLE.error(RED.wrap(breakMsg), t); + } + + public static void errPrint(String msg) { + String breakMsg = lineBreak(msg); + CONSOLE.error(RED.wrap(breakMsg)); + } + + public static String lineBreak(String msg) { + StringJoiner sj = new StringJoiner("\n"); + StringBuilder line = new StringBuilder(); + for (String s : msg.split(" ")) { + String tmp = line + " " + s; + if (tmp.length() < 47) { + line.append(s).append(" "); + } + if (tmp.length() == 47) { + sj.add(tmp); + line = new StringBuilder(); + } + if (tmp.length() > 47) { + if (line.length() == 0) { + sj.add(s); + } else { + sj.add(line.toString()); + line = new StringBuilder(s + " "); + } + } + } + sj.add(line); + return sj.toString(); + } + +} diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/log/ConsoleLoggerColorLayout.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/log/ConsoleLoggerColorLayout.java new file mode 100644 index 0000000..7129b84 --- /dev/null +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/log/ConsoleLoggerColorLayout.java @@ -0,0 +1,53 @@ +package org.touchbit.buggy.spring.boot.starter.log; + +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.spring.boot.starter.log.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(ILoggingEvent event) { + StringBuilder stringBuilder = new StringBuilder(128); + 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-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/log/FrameworkLoggerLayout.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/log/FrameworkLoggerLayout.java new file mode 100644 index 0000000..f2b08bc --- /dev/null +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/log/FrameworkLoggerLayout.java @@ -0,0 +1,46 @@ +package org.touchbit.buggy.spring.boot.starter.log; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.CoreConstants; +import ch.qos.logback.core.LayoutBase; +import ch.qos.logback.core.util.CachingDateFormatter; + +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() { + long timestamp = new Date().getTime(); + String time = TIME_FORMATTER.format(timestamp); + 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(ILoggingEvent event) { + long timestamp = event.getTimeStamp(); + String message = event.getFormattedMessage(); + String finalMessage = ANSI.unwrap(message); + String time = TIME_FORMATTER.format(timestamp); + Level level = event.getLevel(); + return time + " " + level + " - " + finalMessage + CoreConstants.LINE_SEPARATOR; + } + +} diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/utils/JUtils.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/utils/JUtils.java new file mode 100644 index 0000000..c466ec1 --- /dev/null +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/utils/JUtils.java @@ -0,0 +1,80 @@ +package org.touchbit.buggy.spring.boot.starter.utils; + +import org.springframework.util.ClassUtils; + +import java.lang.management.ManagementFactory; +import java.lang.management.RuntimeMXBean; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Set; + +/** + * 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 boolean isJetBrainsIdeRun() { + RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean(); + List arguments = runtimeMxBean.getInputArguments(); + return arguments.stream() + .anyMatch(v -> v.startsWith("-javaagent") && + (v.contains("JetBrains") || v.contains("IDEA") || v.contains("idea"))); + } + + public static String getRunPath() { + String runDir = System.getProperty("user.dir"); + if (isJetBrainsIdeRun()) { + String javaClassPath = System.getProperty("java.class.path"); + if (javaClassPath != null && !javaClassPath.isEmpty()) { + String firstClassPath = javaClassPath.split(":")[0]; + if (firstClassPath.contains("/target/") && firstClassPath.contains(runDir)) { + return firstClassPath.substring(0, firstClassPath.indexOf("/target/")) + "/target"; + } + } + } + return runDir; + } + + public static List getFields(Object o) { + if (o != null) { + return getFields(o.getClass()); + } + return new ArrayList<>(); + } + + public static List getFields(Class c) { + Set> interfaces = ClassUtils.getAllInterfacesAsSet(c); + 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) { + Set> interfaces = ClassUtils.getAllInterfacesAsSet(c); + 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; + } + +} diff --git a/buggy-spring-boot-starter/src/main/resources/META-INF/spring.factories b/buggy-spring-boot-starter/src/main/resources/META-INF/spring.factories index 28ae80d..e69de29 100644 --- a/buggy-spring-boot-starter/src/main/resources/META-INF/spring.factories +++ b/buggy-spring-boot-starter/src/main/resources/META-INF/spring.factories @@ -1 +0,0 @@ -org.springframework.boot.autoconfigure.EnableAutoConfiguration=org.touchbit.buggy.spring.boot.starter.BuggyAutoConfiguration \ No newline at end of file diff --git a/buggy-spring-boot-starter/src/main/resources/application.properties b/buggy-spring-boot-starter/src/main/resources/application.properties deleted file mode 100644 index 2629c16..0000000 --- a/buggy-spring-boot-starter/src/main/resources/application.properties +++ /dev/null @@ -1 +0,0 @@ -logging.level.root=OFF \ No newline at end of file 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..a5555ec --- /dev/null +++ b/buggy-spring-boot-starter/src/main/resources/application.yml @@ -0,0 +1,12 @@ +logging: + config: 'classpath:buggy-logback.xml' +spring: + main: + allow-bean-definition-overriding: true +buggy: + all: true + force: true + print-suite: true + print-cause: true + print-log: true + type: SYSTEM \ No newline at end of file diff --git a/buggy-spring-boot-starter/src/main/resources/buggy-logback.xml b/buggy-spring-boot-starter/src/main/resources/buggy-logback.xml new file mode 100644 index 0000000..e74bf4a --- /dev/null +++ b/buggy-spring-boot-starter/src/main/resources/buggy-logback.xml @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + + + + ${log.path}/Framework.log + + + + + + + ${log.path}/TestSupervisor.log + + ${base.log.pattern} + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/buggy-spring-boot-starter/src/main/resources/logging.properties b/buggy-spring-boot-starter/src/main/resources/logging.properties deleted file mode 100644 index f8d3259..0000000 --- a/buggy-spring-boot-starter/src/main/resources/logging.properties +++ /dev/null @@ -1,3 +0,0 @@ -handlers=java.util.logging.FileHandler -java.util.logging.FileHandler.pattern=baeldung.log -java.util.logging.FileHandler.formatter=java.util.logging.SimpleFormatter From 0cbd00c7e253d9e092243c44f77ffa631928f7e3 Mon Sep 17 00:00:00 2001 From: "oleg.shaburov" Date: Fri, 2 Oct 2020 01:57:49 +0300 Subject: [PATCH 04/24] Add BuggyConfig --- .../buggy/core/config/BParameters.java | 2 +- .../{SBBuggy.java => ExampleBuggyImpl.java} | 8 +- .../boot/starter/example/conf/Command1.java | 13 -- .../boot/starter/example/conf/Command2.java | 16 -- .../boot/starter/example/conf/Command3.java | 16 -- .../boot/starter/example/conf/Command4.java | 25 --- .../example/conf/ExampleConfiguration.java | 30 +++ .../boot/starter/{Buggy.java => SBBuggy.java} | 9 +- .../spring/boot/starter/conf/BuggyConfig.java | 172 ++++++++++++++++-- .../boot/starter/conf/SBConfiguration.java | 22 ++- .../conf/SBJCommanderConfiguration.java | 40 ++-- .../starter/conf/SBLogbackConfiguration.java | 8 +- .../starter/conf/SBTestNGConfiguration.java | 6 +- .../boot/starter/log/ConfigurationLogger.java | 16 +- 14 files changed, 251 insertions(+), 132 deletions(-) rename buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/{SBBuggy.java => ExampleBuggyImpl.java} (58%) delete mode 100644 buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/conf/Command1.java delete mode 100644 buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/conf/Command2.java delete mode 100644 buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/conf/Command3.java delete mode 100644 buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/conf/Command4.java create mode 100644 buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/conf/ExampleConfiguration.java rename buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/{Buggy.java => SBBuggy.java} (51%) 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 index 7ae0ae4..c36d8ca 100644 --- 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 @@ -26,7 +26,7 @@ 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 HELP = "-?, --help"; public static final String S = "-s"; public static final String SERVICES = "--services"; public static final String I = "-i"; diff --git a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/SBBuggy.java b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleBuggyImpl.java similarity index 58% rename from buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/SBBuggy.java rename to buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleBuggyImpl.java index c9386dc..ebda9b5 100644 --- a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/SBBuggy.java +++ b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleBuggyImpl.java @@ -1,18 +1,18 @@ package org.touchbit.buggy.spring.boot.starter.example; import org.springframework.boot.SpringApplication; -import org.touchbit.buggy.spring.boot.starter.Buggy; +import org.touchbit.buggy.spring.boot.starter.SBBuggy; import org.touchbit.buggy.spring.boot.starter.conf.BuggyConfig; -public class SBBuggy extends Buggy { +public class ExampleBuggyImpl extends SBBuggy { static { BuggyConfig.setForce(true); + BuggyConfig.setHelp(true); } public static void main(String[] args) { -// args = new String[]{"--force", "-v"}; - SpringApplication.run(SBBuggy.class, args); + SpringApplication.run(ExampleBuggyImpl.class, args); } } diff --git a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/conf/Command1.java b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/conf/Command1.java deleted file mode 100644 index 55f96d9..0000000 --- a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/conf/Command1.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.touchbit.buggy.spring.boot.starter.example.conf; - -import com.beust.jcommander.Parameter; -import org.touchbit.buggy.spring.boot.starter.conf.JCConfiguration; - -public class Command1 implements JCConfiguration { - - @Parameter(names = {"--f"}, description = "Running all tests, including those that fall.") - private static Boolean force =null; - - @Parameter(names = {"-a"}, description = "FFFFFFFFFFFFFFFFFFFFF.") - private static Boolean a = null; -} diff --git a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/conf/Command2.java b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/conf/Command2.java deleted file mode 100644 index 4da7e9c..0000000 --- a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/conf/Command2.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.touchbit.buggy.spring.boot.starter.example.conf; - -import com.beust.jcommander.Parameter; -import com.beust.jcommander.Parameters; -import org.touchbit.buggy.spring.boot.starter.conf.JCConfiguration; - -@Parameters() -public class Command2 implements JCConfiguration { - - @Parameter(names = {"-?", "--help"}, hidden = true, help = true, description = "Print usage.") - private static Boolean help = null; - - @Parameter(names = {"-----f"}, description = "FFFFFFFFFFFFFFFFFFFFF.") - private static Boolean a = null; - -} diff --git a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/conf/Command3.java b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/conf/Command3.java deleted file mode 100644 index 191e3a1..0000000 --- a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/conf/Command3.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.touchbit.buggy.spring.boot.starter.example.conf; - -import com.beust.jcommander.Parameter; -import com.beust.jcommander.Parameters; -import org.touchbit.buggy.spring.boot.starter.conf.JCConfiguration; - -@Parameters(commandNames = {"c1"}, commandDescription = "secondary config") -public class Command3 implements JCConfiguration { - - @Parameter(names = {"----?"}, hidden = true, help = true, description = "Print usage.") - private static Boolean help = null; - - @Parameter(names = {"-a"}, description = "FFFFFFFFFFFFFFFFFFFFF.") - private static Boolean a = null; - -} diff --git a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/conf/Command4.java b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/conf/Command4.java deleted file mode 100644 index 7695550..0000000 --- a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/conf/Command4.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.touchbit.buggy.spring.boot.starter.example.conf; - -import com.beust.jcommander.Parameter; -import com.beust.jcommander.Parameters; -import org.touchbit.buggy.spring.boot.starter.conf.JCConfiguration; - -@Parameters(commandNames = "c2") -public class Command4 implements JCConfiguration { - - @Parameter(names = {"---?"}, hidden = true, help = true, description = "Print usage.") - private static Boolean help = null; - - private static Boolean a = null; - -// @Parameter(names = {"-a"}, description = "FFFFFFFFFFFFFFFFFFFFF.") - public static Boolean getA() { - return a; - } - - @Parameter(names = {"-a"}, description = "FFFFFFFFFFFFFFFFFFFFF.") - public static void setA(Boolean a) { - Command4.a = a; - } - -} 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..ded77e1 --- /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.spring.boot.starter.conf.JCConfiguration; + +public class ExampleConfiguration implements JCConfiguration { + + @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/src/main/java/org/touchbit/buggy/spring/boot/starter/Buggy.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/SBBuggy.java similarity index 51% rename from buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/Buggy.java rename to buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/SBBuggy.java index f1b0298..042fd1b 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/Buggy.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/SBBuggy.java @@ -1,19 +1,20 @@ package org.touchbit.buggy.spring.boot.starter; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.testng.TestNG; @SpringBootApplication -public abstract class Buggy implements CommandLineRunner { +public abstract class SBBuggy implements ApplicationRunner { @Autowired private TestNG testNG; @Override - public void run(final String... args) throws Exception { - System.out.println(" >>>> RUN: " + testNG); + public void run(ApplicationArguments args) { + System.out.println("Hello World from Application Runner"); } } diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/BuggyConfig.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/BuggyConfig.java index a45cd66..40ea5ec 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/BuggyConfig.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/BuggyConfig.java @@ -2,6 +2,18 @@ import com.beust.jcommander.Parameter; import org.springframework.core.annotation.Order; +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 java.util.List; + +import static org.touchbit.buggy.core.config.BParameters.*; /** * Configuration class for customizing Buggy. @@ -12,36 +24,170 @@ @Order(1) public class BuggyConfig implements JCConfiguration { - @Parameter(names = {"-f", "--force"}, description = "Running all tests, including those that fall.") + @Parameter(names = HELP, help = true, description = "Print usage.") + private static Boolean help = false; + + @Parameter(names = {F, FORCE}, description = "Running all tests, including those that fall.") private static Boolean force = false; - @Parameter(names = {"-v", "--verbose"}, hidden = true, description = "Print all configuration parameters.") - private static Boolean verbose = false; + @Parameter(names = {PRINT_SUITE}, description = "Display information on the Suite in the console log.") + private static Boolean printSuite = false; + + @Parameter(names = {PRINT_CAUSE}, description = "Print the cause of a fail or skip test in the console log.") + private static Boolean printCause = false; + + @Parameter(names = {PRINT_LOG}, description = "Print the test log file path in the console log") + private static Boolean printLog = false; + + private static Boolean printLogOnlyFail = false; + + @Parameter(names = {SELF_CHECK}, description = "Check buggy configuration without test run.") + private static Boolean check = false; + + @Parameter(names = {V, VERSION}, description = "Print program version", validateValueWith = ValueValidator.class) + private static Boolean version = false; - private static String absoluteLogPath; + @Parameter(names = {THREADS}, description = "The number of threads to run the test methods.") + private static Integer threads = 50; + + @Parameter(names = {STATUS}, description = "Completion with the specified status.") + private static Integer status; + + @Parameter(names = {LOG}, description = "Absolute path to the directory for test logs.") + private static String logPath = "logs"; + + @Parameter(names = {ARTIFACTS_URL}, description = "The storage address for the builds (artifacts).") + private static String artifactsUrl; + + @Parameter(names = {T, TYPE}, description = "Type of tests to run.", validateWith = ParameterValidator.class) + private static Type type = Type.INTEGRATION; + + @Parameter(names = {S, SERVICES}, description = "List of tested services in the format: NAME,NAME,NAME.", + validateWith = ParameterValidator.class, listConverter = ServiceConverter.class) + private static List services = BuggyUtils.findServices(); + + @Parameter(names = {I, INTERFACE}, description = "List of tested interfaces in the format: NAME,NAME,NAME.", + validateWith = ParameterValidator.class, listConverter = InterfaceConverter.class) + private static List interfaces = BuggyUtils.findInterfaces(); + + public static Boolean getHelp() { + return help; + } + + public static void setHelp(Boolean help) { + BuggyConfig.help = help; + } public static Boolean getForce() { return force; } - public static void setForce(boolean force) { + public static void setForce(Boolean force) { BuggyConfig.force = force; } - public static Boolean getVerbose() { - return verbose; + public static Boolean getPrintSuite() { + return printSuite; + } + + public static void setPrintSuite(Boolean printSuite) { + BuggyConfig.printSuite = printSuite; + } + + public static Boolean getPrintCause() { + return printCause; + } + + public static void setPrintCause(Boolean printCause) { + BuggyConfig.printCause = printCause; + } + + public static Boolean getPrintLog() { + return printLog; + } + + public static void setPrintLog(Boolean printLog) { + BuggyConfig.printLog = printLog; + } + + public static Boolean getPrintLogOnlyFail() { + return printLogOnlyFail; + } + + public static void setPrintLogOnlyFail(Boolean printLogOnlyFail) { + BuggyConfig.printLogOnlyFail = printLogOnlyFail; + } + + public static Boolean getCheck() { + return check; + } + + public static void setCheck(Boolean check) { + BuggyConfig.check = check; + } + + public static Boolean getVersion() { + return version; + } + + public static void setVersion(Boolean version) { + BuggyConfig.version = version; + } + + public static Integer getThreads() { + return threads; + } + + public static void setThreads(Integer threads) { + BuggyConfig.threads = threads; + } + + public static Integer getStatus() { + return status; + } + + public static void setStatus(Integer status) { + BuggyConfig.status = status; + } + + public static String getLogPath() { + return logPath; + } + + public static void setLogPath(String logPath) { + BuggyConfig.logPath = logPath; + } + + public static String getArtifactsUrl() { + return artifactsUrl; + } + + public static void setArtifactsUrl(String artifactsUrl) { + BuggyConfig.artifactsUrl = artifactsUrl; + } + + public static Type getType() { + return type; + } + + public static void setType(Type type) { + BuggyConfig.type = type; + } + + public static List getServices() { + return services; } - public static void setVerbose(Boolean verbose) { - BuggyConfig.verbose = verbose; + public static void setServices(List services) { + BuggyConfig.services = services; } - public static String getAbsoluteLogPath() { - return absoluteLogPath; + public static List getInterfaces() { + return interfaces; } - public static void setAbsoluteLogPath(String absoluteLogPath) { - BuggyConfig.absoluteLogPath = absoluteLogPath; + public static void setInterfaces(List interfaces) { + BuggyConfig.interfaces = interfaces; } } diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBConfiguration.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBConfiguration.java index 31d8a52..9cb83e9 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBConfiguration.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBConfiguration.java @@ -18,16 +18,22 @@ default void exitRunWithErr(String message) { exitRun(1, message); } + default void exitRun(int status) { + exitRun(status, null); + } + default void exitRun(int status, String message) { - ConfigurationLogger.bPrint(); - if (status == 0) { - ConfigurationLogger.print(message); - } else { - ConfigurationLogger.errPrint(message); + if (message != null) { + ConfigurationLogger.blockDelimeter(); + if (status == 0) { + ConfigurationLogger.print(message); + } else { + ConfigurationLogger.errPrint(message); + } } - ConfigurationLogger.bPrint(); - ConfigurationLogger.fdPrint("Exit code", status); - ConfigurationLogger.bPrint(); + ConfigurationLogger.blockDelimeter(); + ConfigurationLogger.dotPlaceholder("Exit code", status); + ConfigurationLogger.blockDelimeter(); System.exit(status); } diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBJCommanderConfiguration.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBJCommanderConfiguration.java index c876ab7..d2ff161 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBJCommanderConfiguration.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBJCommanderConfiguration.java @@ -36,6 +36,7 @@ includeFilters = @ComponentScan.Filter(type = ASSIGNABLE_TYPE, classes = JCConfiguration.class)) public class SBJCommanderConfiguration implements SBConfiguration { + private static final JCommander JC = new JCommander(); private final List list; private final String[] args; private Map, JCConfiguration> buggyConfigurations; @@ -58,34 +59,39 @@ public boolean isBuggyConfigured() { @PostConstruct public void postConstruct() { + if (BuggyConfig.getHelp()) { + ConfigurationLogger.stepDelimeter(); + JC.usage(); + exitRun(0); + } printConfigurationsParams(buggyConfigurations); } public void init() { if (buggyConfigurations == null) { - ConfigurationLogger.bPrint(); - ConfigurationLogger.cbPrint("JCommander configuration construction"); - ConfigurationLogger.sPrint(); + ConfigurationLogger.blockDelimeter(); + ConfigurationLogger.centerBold("JCommander configuration construction"); + ConfigurationLogger.stepDelimeter(); buggyConfigurations = new HashMap<>(); - JCommander jc = new JCommander(); + for (JCConfiguration config : list) { buggyConfigurations.put(config.getClass(), config); checkConfiguration(config); if (config.getClass().isAnnotationPresent(Parameters.class) && config.getClass().getAnnotation(Parameters.class).commandNames().length > 0) { - jc.addCommand(config); + JC.addCommand(config); } else { - jc.addObject(config); + JC.addObject(config); } - ConfigurationLogger.fdPrint(config.getClass().getSimpleName(), "OK"); + ConfigurationLogger.dotPlaceholder(config.getClass().getSimpleName(), "OK"); } try { - jc.parse(args); - ConfigurationLogger.sPrint(); - ConfigurationLogger.fdPrint("Parsing arguments", "OK"); + JC.parse(args); + ConfigurationLogger.stepDelimeter(); + ConfigurationLogger.dotPlaceholder("Parsing arguments", "OK"); } catch (Exception e) { - ConfigurationLogger.sPrint(); - ConfigurationLogger.fdPrint("Parsing arguments", "FAIL"); + ConfigurationLogger.stepDelimeter(); + ConfigurationLogger.dotPlaceholder("Parsing arguments", "FAIL"); printConfigurationsParams(buggyConfigurations); if (!(e instanceof ParameterException)) { e.printStackTrace(); @@ -100,7 +106,7 @@ public void checkConfiguration(JCConfiguration config) { Parameter parameter = field.getAnnotation(Parameter.class); if (parameter != null && !Modifier.isStatic(field.getModifiers())) { String[] names = parameter.names(); - ConfigurationLogger.fdPrint(config.getClass().getSimpleName(), "FAIL"); + ConfigurationLogger.dotPlaceholder(config.getClass().getSimpleName(), "FAIL"); printConfigurationParams(config); exitRunWithErr("Field " + config.getClass().getSimpleName() + "#" + field.getName() + " marked with @Parameter " + Arrays.toString(names) + " must be static."); @@ -128,7 +134,7 @@ public void checkConfiguration(JCConfiguration config) { "(method name must start with 'is' or 'set')."; } if (error != null) { - ConfigurationLogger.fdPrint(config.getClass().getSimpleName(), "FAIL"); + ConfigurationLogger.dotPlaceholder(config.getClass().getSimpleName(), "FAIL"); printConfigurationParams(config); exitRunWithErr(error); } @@ -146,10 +152,10 @@ public void printConfigurationsParams(Map, JCCo public void printConfigurationParams(JCConfiguration config) { Map params = config.configurationToMap(); if (params != null && !params.isEmpty()) { - ConfigurationLogger.sPrint(); - ConfigurationLogger.cPrint(config.getClass().getSimpleName()); + ConfigurationLogger.stepDelimeter(); + ConfigurationLogger.center(config.getClass().getSimpleName()); for (Map.Entry entry : params.entrySet()) { - ConfigurationLogger.fdPrint(entry.getKey(), entry.getValue()); + ConfigurationLogger.dotPlaceholder(entry.getKey(), entry.getValue()); } } } diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBLogbackConfiguration.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBLogbackConfiguration.java index c67c1ca..3e9f004 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBLogbackConfiguration.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBLogbackConfiguration.java @@ -42,9 +42,9 @@ public class SBLogbackConfiguration implements SBConfiguration { public SBLogbackConfiguration(Environment env) { loggingConfigFile = env.getProperty("logging.config"); - ConfigurationLogger.bPrint(); - ConfigurationLogger.cbPrint("Loading logback configuration"); - ConfigurationLogger.sPrint(); + ConfigurationLogger.blockDelimeter(); + ConfigurationLogger.centerBold("Loading logback configuration"); + ConfigurationLogger.stepDelimeter(); URL logbackXml = getResource(LOGBACK_XML, this.getClass()); URL buggyLogbackXml = getResource("buggy-logback.xml", this.getClass()); LoggerContext context = null; @@ -104,7 +104,7 @@ public static Logger framework() { } public LoggerContext reloadLogger(URL config) { - ConfigurationLogger.sPrint(); + ConfigurationLogger.stepDelimeter(); LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); // Already loaded. Return current context. if (DEFAULT_LOGGING_CONFIG_VALUE.equals(loggingConfigFile)) { diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBTestNGConfiguration.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBTestNGConfiguration.java index e5da23a..e5354b3 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBTestNGConfiguration.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBTestNGConfiguration.java @@ -33,13 +33,13 @@ public SBTestNGConfiguration(boolean isBuggyLoggerInitialized) { if (!isBuggyLoggerInitialized) { exitRunWithErr("Logger must be initialized"); } - ConfigurationLogger.bPrint(); - ConfigurationLogger.cbPrint("Loading TestNG configuration"); + ConfigurationLogger.blockDelimeter(); + ConfigurationLogger.centerBold("Loading TestNG configuration"); } @Bean public TestNG testNG() { - ConfigurationLogger.sPrint(); + ConfigurationLogger.stepDelimeter(); return new TestNG(); } diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/log/ConfigurationLogger.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/log/ConfigurationLogger.java index b743d23..cff0ebf 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/log/ConfigurationLogger.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/log/ConfigurationLogger.java @@ -90,15 +90,15 @@ public static String filler(Object prefix, String symbol, int length, Object pos return sb.toString(); } - public static void sPrint() { + public static void stepDelimeter() { print(filler(STEP)); } - public static void bPrint() { + public static void blockDelimeter() { print(filler(BLOCK)); } - public static void fdPrint(Object prefix, Object postfix) { + public static void dotPlaceholder(Object prefix, Object postfix) { print(filler(prefix, DOT, postfix)); } @@ -106,15 +106,15 @@ public static void fPrint(Object prefix, String symbol, Object postfix) { print(filler(prefix, symbol, postfix)); } - public static void cbPrint(String msg) { - print(BOLD.wrap(center(msg))); + public static void centerBold(String msg) { + print(BOLD.wrap(centerMsg(msg))); } - public static void cPrint(String msg) { - print(center(msg)); + public static void center(String msg) { + print(centerMsg(msg)); } - private static String center(String msg) { + private static String centerMsg(String msg) { if (msg != null && !msg.isEmpty()) { int diff = STRING_LEN - msg.length(); if (diff > 0) { From 56e9b249fbf382b6c3f1281be78e741ea185d5c1 Mon Sep 17 00:00:00 2001 From: "oleg.shaburov" Date: Fri, 2 Oct 2020 18:55:10 +0300 Subject: [PATCH 05/24] Improve test types, goals, BuggyConfig --- .../buggy/core/config/BParameters.java | 11 +- .../buggy/core/config/PrimaryConfig.java | 8 +- .../config/jcommander/ComponentConverter.java | 2 +- .../core/config/jcommander/GoalConverter.java | 4 +- .../config/jcommander/InterfaceConverter.java | 2 +- .../config/jcommander/ServiceConverter.java | 2 +- .../config/jcommander/ValueValidator.java | 6 +- .../buggy/core/{process => goal}/Goal.java | 2 +- .../component/AllComponents.java} | 16 +- .../component}/Component.java | 7 +- .../buggy/core/goal/interfaze/API.java | 15 ++ .../core/goal/interfaze/AllInterfaces.java | 15 ++ .../interfaze}/Interface.java | 3 +- .../buggy/core/goal/service/AllServices.java | 14 ++ .../{process => goal/service}/Service.java | 3 +- .../buggy/core/model/BParallelMode.java | 24 +++ .../touchbit/buggy/core/model/Details.java | 6 +- .../org/touchbit/buggy/core/model/Suite.java | 14 +- .../org/touchbit/buggy/core/model/Type.java | 49 +++--- .../touchbit/buggy/core/testng/TestSuite.java | 6 +- .../listeners/BuggyExecutionListener.java | 4 +- .../touchbit/buggy/core/utils/BuggyUtils.java | 6 +- .../buggy/core/config/TestClassWithSuite.java | 2 +- .../buggy/core/config/TestComponent.java | 9 +- .../buggy/core/config/TestInterface.java | 2 +- .../buggy/core/config/TestService.java | 2 +- .../buggy/core/tests/BaseUnitTest.java | 14 +- .../buggy/core/tests/common/BuggyTests.java | 4 +- .../buggy/core/tests/common/GoalTests.java | 6 +- .../tests/config/JCommanderConfigTests.java | 4 +- .../core/tests/config/JCommanderTests.java | 13 +- .../buggy/core/tests/model/ModelTests.java | 36 ----- .../core/tests/testng/TestSuiteTests.java | 20 +-- .../BuggyExecutionListenerTests.java | 8 +- .../core/tests/utils/BuggyUtilsTests.java | 21 +-- .../touchbit/buggy/example/min/goals/API.java | 2 +- .../buggy/example/min/goals/GitLab.java | 2 +- .../buggy/example/min/tests/GitLabTests.java | 2 +- .../starter/example/ExampleBuggyImpl.java | 1 - .../spring/boot/starter/conf/BuggyConfig.java | 150 +++++++++++++++--- .../boot/starter/conf/JCConfiguration.java | 15 +- .../conf/SBJCommanderConfiguration.java | 22 ++- .../starter/conf/SBTestNGConfiguration.java | 9 +- 43 files changed, 350 insertions(+), 213 deletions(-) rename buggy-core/src/main/java/org/touchbit/buggy/core/{process => goal}/Goal.java (94%) rename buggy-core/src/main/java/org/touchbit/buggy/core/{process/DefaultComponent.java => goal/component/AllComponents.java} (72%) rename buggy-core/src/main/java/org/touchbit/buggy/core/{process => goal/component}/Component.java (90%) create mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/goal/interfaze/API.java create mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/goal/interfaze/AllInterfaces.java rename buggy-core/src/main/java/org/touchbit/buggy/core/{process => goal/interfaze}/Interface.java (92%) create mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/goal/service/AllServices.java rename buggy-core/src/main/java/org/touchbit/buggy/core/{process => goal/service}/Service.java (92%) create mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/model/BParallelMode.java 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 index c36d8ca..9639bab 100644 --- 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 @@ -27,18 +27,21 @@ public class BParameters { public static final String VERSION = "--version"; public static final String QUESTION_MARK = "-?"; public static final String HELP = "-?, --help"; + public static final String C = "-c"; + public static final String COMPONENTS = "--component"; public static final String S = "-s"; - public static final String SERVICES = "--services"; + public static final String SERVICES = "--service"; 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 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"; + public static final String FORCE = "--force-run"; public static final String ARTIFACTS_URL = "--artifacts-url"; - public static final String STATUS = "--status"; + public static final String EXIT_STATUS = "--exit-status"; public static final String ALL = "--all"; public static final String PRINT_SUITE = "--print-suite"; public static final String PRINT_CAUSE = "--print-cause"; 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 index fdfe883..b610902 100644 --- 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 @@ -26,8 +26,8 @@ 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.goal.interfaze.Interface; +import org.touchbit.buggy.core.goal.service.Service; import org.touchbit.buggy.core.utils.BuggyUtils; import org.touchbit.buggy.core.utils.StringUtils; @@ -109,7 +109,7 @@ default Integer getThreads() { return DEFAULT_VALUES.threads; } - @Parameter(names = {LOG}, hidden = true, description = "Absolute path to the directory for test logs.") + @Parameter(names = {LOGS_PATH}, hidden = true, description = "Absolute path to the directory for test logs.") default void setLogPath(String logDir) { DEFAULT_VALUES.logPath = logDir; } @@ -147,7 +147,7 @@ default Type getType() { return DEFAULT_VALUES.type; } - @Parameter(names = {STATUS}, hidden = true, description = "Completion with the specified status.") + @Parameter(names = {EXIT_STATUS}, hidden = true, description = "Completion with the specified status.") default void setStatus(Integer status) { DEFAULT_VALUES.status = status; } diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/config/jcommander/ComponentConverter.java b/buggy-core/src/main/java/org/touchbit/buggy/core/config/jcommander/ComponentConverter.java index eba3ac7..423e99c 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/config/jcommander/ComponentConverter.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/config/jcommander/ComponentConverter.java @@ -16,7 +16,7 @@ package org.touchbit.buggy.core.config.jcommander; 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-core/src/main/java/org/touchbit/buggy/core/config/jcommander/GoalConverter.java index 5d927cd..ee775dd 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/config/jcommander/GoalConverter.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/config/jcommander/GoalConverter.java @@ -19,7 +19,7 @@ import com.beust.jcommander.IStringConverter; import org.atteo.classindex.ClassIndex; import org.touchbit.buggy.core.exceptions.BuggyConfigurationException; -import org.touchbit.buggy.core.process.Goal; +import org.touchbit.buggy.core.goal.Goal; /** * Created by Oleg Shaburov on 08.09.2018 @@ -49,4 +49,4 @@ public T convert(String s) { 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-core/src/main/java/org/touchbit/buggy/core/config/jcommander/InterfaceConverter.java index 646a992..827739e 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/config/jcommander/InterfaceConverter.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/config/jcommander/InterfaceConverter.java @@ -17,7 +17,7 @@ package org.touchbit.buggy.core.config.jcommander; 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/ServiceConverter.java b/buggy-core/src/main/java/org/touchbit/buggy/core/config/jcommander/ServiceConverter.java index 8e29939..265285f 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/config/jcommander/ServiceConverter.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/config/jcommander/ServiceConverter.java @@ -17,7 +17,7 @@ package org.touchbit.buggy.core.config.jcommander; 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-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 index 3b89a1e..6e7274c 100644 --- 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 @@ -32,15 +32,15 @@ * Created by Oleg Shaburov on 19.09.2018 * shaburov.o.a@gmail.com */ -public class ValueValidator implements IValueValidator { +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)) { + if ((name.equals(QUESTION_MARK) || name.equals(HELP)) && Boolean.parseBoolean(stringValue)) { Buggy.getExitHandler().exitRunWithUsage(0); } - if ((name.equals(V) || name.equals(VERSION)) && Boolean.valueOf(String.valueOf(stringValue))) { + if ((name.equals(V) || name.equals(VERSION)) && Boolean.parseBoolean(String.valueOf(stringValue))) { printManifestInfo(); Buggy.getExitHandler().exitRun(0); } 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 94% 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..ba80432 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 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/AllComponents.java similarity index 72% 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/AllComponents.java index 3847225..88e0bd0 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/AllComponents.java @@ -14,30 +14,22 @@ * 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 AllComponents extends Component { @Override public String getName() { - return "DEFAULT"; + return "ALL"; } @Override public String getDescription() { - return "Default component"; + return "All components"; } } 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 90% 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..f2d7cfe 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,10 @@ * 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 @@ -29,8 +28,6 @@ @IndexSubclasses public abstract class Component implements Goal { - public abstract List getServices(); - public abstract String getDescription(); 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..cb012ae --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/interfaze/AllInterfaces.java @@ -0,0 +1,15 @@ +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"; + } + +} 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 92% 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..2638779 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,9 +14,10 @@ * 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.) 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..5cd4f34 --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/service/AllServices.java @@ -0,0 +1,14 @@ +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"; + } +} 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 92% 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..a7edb6f 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,10 @@ * 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 diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/model/BParallelMode.java b/buggy-core/src/main/java/org/touchbit/buggy/core/model/BParallelMode.java new file mode 100644 index 0000000..68b07a3 --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/model/BParallelMode.java @@ -0,0 +1,24 @@ +package org.touchbit.buggy.core.model; + +import org.testng.xml.XmlSuite; + +public enum BParallelMode { + + TESTS(XmlSuite.ParallelMode.TESTS), + METHODS(XmlSuite.ParallelMode.METHODS), + CLASSES(XmlSuite.ParallelMode.CLASSES), + INSTANCES(XmlSuite.ParallelMode.INSTANCES), + NONE(XmlSuite.ParallelMode.NONE), + ; + + private XmlSuite.ParallelMode testNGMode; + + BParallelMode(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/model/Details.java b/buggy-core/src/main/java/org/touchbit/buggy/core/model/Details.java index 009cf3a..873cdf7 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/Details.java @@ -43,13 +43,13 @@ */ Status status() default SUCCESS; - /** Issues ID in the task-tracker system. Format: "MAPI-269" */ + /** Issues ID in the task-tracker system. Format: "STORY-269" */ String[] issue() default {""}; - /** Defects ID in the task-tracker system. Format: "MAPI-269" */ + /** Defects ID in the task-tracker system. Format: "BUG-269" */ String[] bug() default {""}; /** Type of auto test */ - Type type() default Type.MODULE; + Type[] type() default {Type.REGRESSION}; } 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..fe293bb 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 @@ -17,10 +17,10 @@ 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.AllComponents; +import org.touchbit.buggy.core.goal.interfaze.Interface; +import org.touchbit.buggy.core.goal.service.Service; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; @@ -37,7 +37,7 @@ public @interface Suite { /** The component to be tested */ - Class component() default DefaultComponent.class; + Class component() default AllComponents.class; /** The test service included in the component */ Class service(); @@ -45,7 +45,7 @@ /** The interface on which the test is performed */ Class interfaze(); - /** 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..da30f6c 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,38 @@ 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. + 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/testng/TestSuite.java b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/TestSuite.java index f708a03..048762d 100644 --- 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 @@ -25,9 +25,9 @@ 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.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.BuggyUtils; import java.util.*; 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 index d4ff86a..55d109a 100644 --- 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 @@ -327,7 +327,7 @@ public void disableTestsByType(final ISuite suite) { methods.forEach(method -> { Details details = getDetails(method); Type configType = Buggy.getPrimaryConfig().getType(); - if (details != null && !configType.isIncludeOrEquals(details.type())) { + if (details != null) { // && !configType.isIncludeOrEquals(details.type()) method.setInvocationCount(0); resultLog(method, Status.SKIP, buildDetailsMessage(details, details.type(), "test type")); } @@ -394,7 +394,7 @@ public void resultLog(ITestNGMethod method, Status status, String details) { 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()); + sj.add(suite.purpose().trim()); resultMsg.add(sj.toString().trim()); } testLog.info("{} - {} {}", methodName, statusName, method.getDescription()); 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 index 1338c2d..c93a28e 100644 --- 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 @@ -21,9 +21,9 @@ 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.goal.component.Component; +import org.touchbit.buggy.core.goal.interfaze.Interface; +import org.touchbit.buggy.core.goal.service.Service; import org.touchbit.buggy.core.testng.TestSuite; import java.io.IOException; 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..ee97853 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 @@ -25,7 +25,7 @@ * 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") 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..022f9e6 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,7 +1,7 @@ package org.touchbit.buggy.core.config; -import org.touchbit.buggy.core.process.Component; -import org.touchbit.buggy.core.process.Service; +import org.touchbit.buggy.core.goal.component.Component; +import org.touchbit.buggy.core.goal.service.Service; import java.util.ArrayList; import java.util.List; @@ -12,11 +12,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/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/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/tests/BaseUnitTest.java b/buggy-core/src/test/java/org/touchbit/buggy/core/tests/BaseUnitTest.java index 08b5ee3..c6063c6 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 @@ -18,9 +18,9 @@ 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.goal.component.Component; +import org.touchbit.buggy.core.goal.interfaze.Interface; +import org.touchbit.buggy.core.goal.service.Service; import org.touchbit.buggy.core.testng.listeners.BuggyExecutionListener; import org.touchbit.buggy.core.utils.log.BuggyLog; @@ -368,10 +368,10 @@ protected static Details getDetails(Status status, String... issue) { } protected static Details getDetails(Status status, Type type, String... issue) { - return getDetails(new long[0], status, type, issue); + return getDetails(new long[0], status, new Type[]{type}, issue); } - protected static Details getDetails(long[] ids, Status status, Type type, String... issue) { + protected static Details getDetails(long[] ids, Status status, Type[] type, String... issue) { return new Details() { @Override public long[] id() { return ids; } @@ -386,7 +386,7 @@ public String[] bug() { } @Override - public Type type() { return type; } + public Type[] type() { return type; } @Override public Class annotationType() { return Details.class; } }; @@ -416,7 +416,7 @@ public Class interfaze() { } @Override - public String task() { + public String purpose() { return UUID.randomUUID().toString(); } }; 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 index 77a1165..e982a70 100644 --- 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 @@ -640,7 +640,7 @@ public int runTestNG(TestNG testNG) { private abstract class AbstractBuggyListener implements BuggyListener {} - @Suite(component = TestComponent.class, service = TestService.class, interfaze = TestInterface.class, task = "PrivateTestSuite") + @Suite(component = TestComponent.class, service = TestService.class, interfaze = TestInterface.class, purpose = "PrivateTestSuite") private static class PrivateTestSuite extends TestSuite { } private static class PrivateBuggyTestsBuggyLog extends BuggyLog { } @@ -656,7 +656,7 @@ 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") + @Suite(component = TestComponent.class, service = TestService.class, interfaze = TestInterface.class, purpose = "task") public static class BuggyTestsClass { @org.testng.annotations.Test(description = "test_20181016172050 description") @Details 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..21b1f0a 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,7 +21,7 @@ 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.*; @@ -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..c41f6a6 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 @@ -26,8 +26,8 @@ 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 java.io.File; import java.lang.reflect.Constructor; 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..dad1b53 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 @@ -10,14 +10,13 @@ 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.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.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; @@ -324,15 +323,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..875a575 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 @@ -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/TestSuiteTests.java b/buggy-core/src/test/java/org/touchbit/buggy/core/tests/testng/TestSuiteTests.java index 875a1c2..b7cafd4 100644 --- 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 @@ -20,7 +20,7 @@ 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.goal.component.AllComponents; import org.touchbit.buggy.core.tests.BaseUnitTest; import org.touchbit.buggy.core.exceptions.BuggyConfigurationException; import org.touchbit.buggy.core.config.TestClassWithoutSuite; @@ -28,9 +28,9 @@ 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.goal.component.Component; +import org.touchbit.buggy.core.goal.interfaze.Interface; +import org.touchbit.buggy.core.goal.service.Service; import org.touchbit.buggy.core.testng.TestSuite; import java.lang.annotation.Annotation; @@ -56,7 +56,7 @@ void unitTest_20180920150141() { assertThat(suite.getComponent(), is(notNullValue())); assertThat(suite.getService(), is(notNullValue())); assertThat(suite.getSuite(), is(notNullValue())); - assertThat(suite.getSuite().task(), is("")); + assertThat(suite.getSuite().purpose(), is("")); } @Test @@ -67,7 +67,7 @@ void unitTest_20180920153817() { assertThat(suite.getComponent(), is(notNullValue())); assertThat(suite.getService(), is(notNullValue())); assertThat(suite.getSuite(), is(notNullValue())); - assertThat(suite.getSuite().task(), is("")); + assertThat(suite.getSuite().purpose(), is("")); } @Test @@ -94,7 +94,7 @@ void unitTest_20180920154032() { assertThat(testSuite.getComponent(), is(notNullValue())); assertThat(testSuite.getService(), is(notNullValue())); assertThat(testSuite.getSuite(), is(notNullValue())); - assertThat(testSuite.getSuite().task(), is("task")); + assertThat(testSuite.getSuite().purpose(), is("task")); assertThat(testSuite.getName(), is("name")); } @@ -252,13 +252,13 @@ void unitTest_20181029004902() { @Override public Class annotationType() { return Suite.class; } @Override - public Class component() { return DefaultComponent.class; } + public Class component() { return AllComponents.class; } @Override public Class service() { return TestService.class; } @Override public Class interfaze() { return TestInterface.class; } @Override - public String task() { return "task"; } + public String purpose() { return "task"; } }; private static final Suite SUITE = new Suite() { @@ -271,7 +271,7 @@ void unitTest_20181029004902() { @Override public Class interfaze() { return TestInterface.class; } @Override - public String task() { return "task"; } + public String purpose() { return "task"; } }; @SuppressWarnings("WeakerAccess") 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 index 9d58079..6030017 100644 --- 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 @@ -26,9 +26,9 @@ 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.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.Buggy; import org.touchbit.buggy.core.exceptions.ExpectedImplementationException; @@ -1600,7 +1600,7 @@ public Class interfaze() { } @Override - public String task() { + public String purpose() { return "TestTask"; } }; 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 a703f32..c2f96f3 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 @@ -9,9 +9,9 @@ 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.goal.component.Component; +import org.touchbit.buggy.core.goal.interfaze.Interface; +import org.touchbit.buggy.core.goal.service.Service; import org.touchbit.buggy.core.testng.TestSuite; import org.touchbit.buggy.core.utils.BuggyUtils; import org.touchbit.buggy.core.utils.IOHelper; @@ -349,10 +349,10 @@ public static class Child extends Parent {} public static @interface BuggyUtilsTestsInterface {} - @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") private static class PrivateTestClass {} - @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 abstract static class AbstractTestClass {} private static final Suite SUITE_1 = new Suite() { @@ -378,7 +378,7 @@ public Class interfaze() { } @Override - public String task() { + public String purpose() { return "TestTask"; } }; @@ -406,7 +406,7 @@ public Class interfaze() { } @Override - public String task() { + public String purpose() { return "TestTask"; } }; @@ -434,7 +434,7 @@ public Class interfaze() { } @Override - public String task() { + public String purpose() { return "TestTask"; } }; @@ -457,11 +457,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-min-example/src/main/java/org/touchbit/buggy/example/min/goals/API.java b/buggy-min-example/src/main/java/org/touchbit/buggy/example/min/goals/API.java index f6a4f6c..1308137 100644 --- a/buggy-min-example/src/main/java/org/touchbit/buggy/example/min/goals/API.java +++ b/buggy-min-example/src/main/java/org/touchbit/buggy/example/min/goals/API.java @@ -16,7 +16,7 @@ package org.touchbit.buggy.example.min.goals; -import org.touchbit.buggy.core.process.Interface; +import org.touchbit.buggy.core.goal.interfaze.Interface; /** * Created by Oleg Shaburov on 18.09.2018 diff --git a/buggy-min-example/src/main/java/org/touchbit/buggy/example/min/goals/GitLab.java b/buggy-min-example/src/main/java/org/touchbit/buggy/example/min/goals/GitLab.java index ce3c9f6..b1d69d9 100644 --- a/buggy-min-example/src/main/java/org/touchbit/buggy/example/min/goals/GitLab.java +++ b/buggy-min-example/src/main/java/org/touchbit/buggy/example/min/goals/GitLab.java @@ -16,7 +16,7 @@ package org.touchbit.buggy.example.min.goals; -import org.touchbit.buggy.core.process.Service; +import org.touchbit.buggy.core.goal.service.Service; /** * Created by Oleg Shaburov on 18.09.2018 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 index 2eee1ce..b1f029c 100644 --- 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 @@ -29,7 +29,7 @@ * Created by Oleg Shaburov on 18.09.2018 * shaburov.o.a@gmail.com */ -@Suite(service = GitLab.class, interfaze = API.class, task = "common") +@Suite(service = GitLab.class, interfaze = API.class, purpose = "common") @SuppressWarnings("squid:S00100") public class GitLabTests extends BaseTest { diff --git a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleBuggyImpl.java b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleBuggyImpl.java index ebda9b5..862df78 100644 --- a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleBuggyImpl.java +++ b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleBuggyImpl.java @@ -8,7 +8,6 @@ public class ExampleBuggyImpl extends SBBuggy { static { BuggyConfig.setForce(true); - BuggyConfig.setHelp(true); } public static void main(String[] args) { diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/BuggyConfig.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/BuggyConfig.java index 40ea5ec..2dd5aec 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/BuggyConfig.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/BuggyConfig.java @@ -6,14 +6,19 @@ 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.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.service.AllServices; +import org.touchbit.buggy.core.model.BParallelMode; 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.goal.interfaze.Interface; +import org.touchbit.buggy.core.goal.service.Service; -import java.util.List; +import java.util.*; import static org.touchbit.buggy.core.config.BParameters.*; +import static org.touchbit.buggy.core.model.BParallelMode.METHODS; /** * Configuration class for customizing Buggy. @@ -50,25 +55,32 @@ public class BuggyConfig implements JCConfiguration { @Parameter(names = {THREADS}, description = "The number of threads to run the test methods.") private static Integer threads = 50; - @Parameter(names = {STATUS}, description = "Completion with the specified status.") + @Parameter(names = {EXIT_STATUS}, description = "Completion with the specified status.") private static Integer status; - @Parameter(names = {LOG}, description = "Absolute path to the directory for test logs.") - private static String logPath = "logs"; + @Parameter(names = {LOGS_PATH}, description = "Absolute path to the directory for test logs.") + private static String logsPath = "logs"; @Parameter(names = {ARTIFACTS_URL}, description = "The storage address for the builds (artifacts).") private static String artifactsUrl; - @Parameter(names = {T, TYPE}, description = "Type of tests to run.", validateWith = ParameterValidator.class) - private static Type type = Type.INTEGRATION; + @Parameter(names = {PARALLEL_MODE}, description = "TestNG parallel mode.") + private static BParallelMode parallelMode = METHODS; + + @Parameter(names = {C, COMPONENTS}, description = "List of tested components in the format: NAME,NAME,NAME.", + validateWith = ParameterValidator.class, listConverter = ServiceConverter.class) + private static List components = new ArrayList() {{ add(new AllComponents()); }}; @Parameter(names = {S, SERVICES}, description = "List of tested services in the format: NAME,NAME,NAME.", validateWith = ParameterValidator.class, listConverter = ServiceConverter.class) - private static List services = BuggyUtils.findServices(); + private static List services = new ArrayList() {{ add(new AllServices()); }}; @Parameter(names = {I, INTERFACE}, description = "List of tested interfaces in the format: NAME,NAME,NAME.", validateWith = ParameterValidator.class, listConverter = InterfaceConverter.class) - private static List interfaces = BuggyUtils.findInterfaces(); + private static List interfaces = new ArrayList() {{ add(new AllInterfaces()); }}; + + @Parameter(names = {T, TYPE}, description = "Type of tests to run.", validateWith = ParameterValidator.class) + private static List types = new ArrayList() {{ add(Type.ALL); }}; public static Boolean getHelp() { return help; @@ -150,12 +162,12 @@ public static void setStatus(Integer status) { BuggyConfig.status = status; } - public static String getLogPath() { - return logPath; + public static String getLogsPath() { + return logsPath; } - public static void setLogPath(String logPath) { - BuggyConfig.logPath = logPath; + public static void setLogsPath(String logsPath) { + BuggyConfig.logsPath = logsPath; } public static String getArtifactsUrl() { @@ -166,12 +178,26 @@ public static void setArtifactsUrl(String artifactsUrl) { BuggyConfig.artifactsUrl = artifactsUrl; } - public static Type getType() { - return type; + public static List getTypes() { + return types; + } + + public static void setTypes(List types) { + if (types != null) { + BuggyConfig.types = types; + } + } + + public static void addTypes(List types) { + if (types != null && !types.isEmpty()) { + BuggyConfig.types.addAll(types); + } } - public static void setType(Type type) { - BuggyConfig.type = type; + public static void addTypes(Type... types) { + if (types != null) { + addTypes(Arrays.asList(types)); + } } public static List getServices() { @@ -179,7 +205,21 @@ public static List getServices() { } public static void setServices(List services) { - BuggyConfig.services = services; + if (services != null) { + BuggyConfig.services = services; + } + } + + public static void addServices(List services) { + if (services != null) { + BuggyConfig.services.addAll(services); + } + } + + public static void addServices(Service... services) { + if (services != null) { + addServices(Arrays.asList(services)); + } } public static List getInterfaces() { @@ -187,7 +227,75 @@ public static List getInterfaces() { } public static void setInterfaces(List interfaces) { - BuggyConfig.interfaces = interfaces; + if (interfaces != null) { + BuggyConfig.interfaces = interfaces; + } + } + + public static void addInterfaces(List interfaces) { + if (interfaces != null) { + BuggyConfig.interfaces.addAll(interfaces); + } + } + + public static void addInterfaces(Interface... interfaces) { + if (interfaces != null) { + addInterfaces(Arrays.asList(interfaces)); + } + } + + public static List getComponents() { + return components; + } + + public static void setComponents(List components) { + if (components != null) { + BuggyConfig.components = components; + } + } + + public static void addComponents(List components) { + if (components != null) { + BuggyConfig.components.addAll(components); + } + } + + public static void addComponents(Component... components) { + if (components != null) { + addComponents(Arrays.asList(components)); + } + } + + public static BParallelMode getParallelMode() { + return parallelMode; + } + + public static void setParallelMode(BParallelMode parallelMode) { + BuggyConfig.parallelMode = parallelMode; + } + + @Override + public Map sort(Map map) { + String[] sort = new String[] + {THREADS, PARALLEL_MODE, F, PRINT_LOG, PRINT_CAUSE, PRINT_SUITE, + 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/conf/JCConfiguration.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/JCConfiguration.java index ad7cc9e..76763fd 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/JCConfiguration.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/JCConfiguration.java @@ -33,11 +33,7 @@ default Map configurationToMap() { Map map = new HashMap<>(); addFieldValuesToMap(map); addMethodsValuesToMap(map); - Map sorted = new LinkedHashMap<>(); - map.entrySet().stream() - .sorted(Map.Entry.comparingByKey()) - .forEachOrdered(k -> sorted.put(k.getKey(), k.getValue())); - return sorted; + return sort(map); } /** @@ -100,4 +96,13 @@ default void addMethodsValuesToMap(Map map) { } } + /** + * Default no sort + * @param map - unsorted map + * @return - sorted map + */ + default Map sort(Map map) { + return map; + } + } diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBJCommanderConfiguration.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBJCommanderConfiguration.java index d2ff161..45babb1 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBJCommanderConfiguration.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBJCommanderConfiguration.java @@ -9,6 +9,11 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; +import org.touchbit.buggy.core.goal.Goal; +import org.touchbit.buggy.core.goal.component.AllComponents; +import org.touchbit.buggy.core.goal.interfaze.AllInterfaces; +import org.touchbit.buggy.core.goal.service.AllServices; +import org.touchbit.buggy.core.model.Type; import org.touchbit.buggy.spring.boot.starter.log.ConfigurationLogger; import org.touchbit.buggy.spring.boot.starter.utils.JUtils; @@ -33,16 +38,21 @@ @ComponentScan( basePackages = "**.buggy", useDefaultFilters = false, - includeFilters = @ComponentScan.Filter(type = ASSIGNABLE_TYPE, classes = JCConfiguration.class)) + includeFilters = { + @ComponentScan.Filter(type = ASSIGNABLE_TYPE, classes = JCConfiguration.class), + @ComponentScan.Filter(type = ASSIGNABLE_TYPE, classes = Goal.class), + }) public class SBJCommanderConfiguration implements SBConfiguration { private static final JCommander JC = new JCommander(); - private final List list; + private final List jcConfigurations; + private final List goals; private final String[] args; private Map, JCConfiguration> buggyConfigurations; - public SBJCommanderConfiguration(List list, ApplicationArguments args) { - this.list = list; + public SBJCommanderConfiguration(List list, List goals, ApplicationArguments args) { + this.goals = goals; + this.jcConfigurations = list; this.args = args.getSourceArgs(); init(); } @@ -74,7 +84,7 @@ public void init() { ConfigurationLogger.stepDelimeter(); buggyConfigurations = new HashMap<>(); - for (JCConfiguration config : list) { + for (JCConfiguration config : jcConfigurations) { buggyConfigurations.put(config.getClass(), config); checkConfiguration(config); if (config.getClass().isAnnotationPresent(Parameters.class) && @@ -143,7 +153,7 @@ public void checkConfiguration(JCConfiguration config) { } public void printConfigurationsParams(Map, JCConfiguration> configs) { - for (JCConfiguration autowiredConfig : list) { + for (JCConfiguration autowiredConfig : jcConfigurations) { JCConfiguration config = configs.get(autowiredConfig.getClass()); printConfigurationParams(config); } diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBTestNGConfiguration.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBTestNGConfiguration.java index e5354b3..9ac86b0 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBTestNGConfiguration.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBTestNGConfiguration.java @@ -6,6 +6,9 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.DependsOn; import org.testng.TestNG; +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.spring.boot.starter.log.ConfigurationLogger; import java.util.Map; @@ -14,9 +17,9 @@ /** * TestNG configuration * Filter test classes for suites by: - * 1. {@link org.touchbit.buggy.core.process.Component}* - * 2. {@link org.touchbit.buggy.core.process.Service}* - * 3. {@link org.touchbit.buggy.core.process.Interface}* + * 1. {@link Component}* + * 2. {@link Service}* + * 3. {@link Interface}* *

* Created by Oleg Shaburov on 01.10.2020 * shaburov.o.a@gmail.com From 094fd4d7cc4b3cbdb1bf0ad5fe638bec3d7a08ae Mon Sep 17 00:00:00 2001 From: "oleg.shaburov" Date: Fri, 2 Oct 2020 20:51:04 +0300 Subject: [PATCH 06/24] Added default component & service + API, WEB interfaces --- .../core/goal/component/DefaultComponent.java | 35 +++++++++++++++++++ .../buggy/core/goal/interfaze/Interface.java | 2 +- .../buggy/core/goal/interfaze/WEB.java | 15 ++++++++ .../core/goal/service/DefaultService.java | 15 ++++++++ 4 files changed, 66 insertions(+), 1 deletion(-) create mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/goal/component/DefaultComponent.java create mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/goal/interfaze/WEB.java create mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/goal/service/DefaultService.java diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/goal/component/DefaultComponent.java b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/component/DefaultComponent.java new file mode 100644 index 0000000..85e8cbc --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/component/DefaultComponent.java @@ -0,0 +1,35 @@ +/* + * 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.goal.component; + +/** + * Created by Oleg Shaburov on 08.09.2018 + * shaburov.o.a@gmail.com + */ +public final class DefaultComponent extends Component { + + @Override + public String getName() { + return "DEFAULT"; + } + + @Override + public String getDescription() { + return "Default component for test suites"; + } + +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/goal/interfaze/Interface.java b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/interfaze/Interface.java index 2638779..1d529e9 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/goal/interfaze/Interface.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/interfaze/Interface.java @@ -20,7 +20,7 @@ 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 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/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"; + } + +} From bae75aba02a6c88e10263b543e70f5b002835116 Mon Sep 17 00:00:00 2001 From: "oleg.shaburov" Date: Sun, 4 Oct 2020 00:33:37 +0300 Subject: [PATCH 07/24] Added SBTestNGConfiguration --- .../core/goal/interfaze/DefaultInterface.java | 33 ++++++ .../org/touchbit/buggy/core/model/Suite.java | 9 +- .../org/touchbit/buggy/core/test/ITest.java | 9 ++ .../IntellijIdeaTestNgPluginListener.java | 2 +- ...BuggyImpl.java => ExampleBuggyRunner.java} | 6 +- .../boot/starter/example/ExampleTests.java | 7 ++ .../example/conf/ExampleConfiguration.java | 1 + buggy-spring-boot-starter/pom.xml | 21 +++- .../{SBBuggy.java => BuggyRunnerBase.java} | 7 +- .../starter/conf/ApplicationProperties.java | 67 +++++++++++ .../boot/starter/conf/SBConfiguration.java | 33 ++++-- .../conf/SBJCommanderConfiguration.java | 5 +- .../starter/conf/SBLogbackConfiguration.java | 36 +++++- .../starter/conf/SBTestNGConfiguration.java | 107 +++++++++++++++--- .../boot/starter/log/ConfigurationLogger.java | 33 +----- .../starter/log/ConsoleLoggerColorLayout.java | 9 ++ .../starter/log/FrameworkLoggerLayout.java | 9 +- .../src/main/resources/application.yml | 15 ++- .../src/main/resources/buggy-logback.xml | 2 +- 19 files changed, 330 insertions(+), 81 deletions(-) create mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/goal/interfaze/DefaultInterface.java create mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/test/ITest.java rename buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/{ExampleBuggyImpl.java => ExampleBuggyRunner.java} (60%) create mode 100644 buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleTests.java rename buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/{SBBuggy.java => BuggyRunnerBase.java} (66%) create mode 100644 buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/ApplicationProperties.java diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/goal/interfaze/DefaultInterface.java b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/interfaze/DefaultInterface.java new file mode 100644 index 0000000..1abf82c --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/interfaze/DefaultInterface.java @@ -0,0 +1,33 @@ +/* + * 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.goal.interfaze; + +/** + * Created by Oleg Shaburov on 03.10.2020 + * shaburov.o.a@gmail.com + */ +public class DefaultInterface extends Interface { + + public String getName() { + return "DEFAULT"; + } + + public String getDescription() { + return "Default test interface"; + } + +} 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 fe293bb..725ce48 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 @@ -19,7 +19,10 @@ import org.atteo.classindex.IndexAnnotated; import org.touchbit.buggy.core.goal.component.Component; import org.touchbit.buggy.core.goal.component.AllComponents; +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; @@ -37,13 +40,13 @@ public @interface Suite { /** The component to be tested */ - Class component() default AllComponents.class; + Class component() default DefaultComponent.class; /** The test service included in the component */ - Class service(); + Class service() default DefaultService.class; /** The interface on which the test is performed */ - Class interfaze(); + Class interfaze() default DefaultInterface.class; /** 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/test/ITest.java b/buggy-core/src/main/java/org/touchbit/buggy/core/test/ITest.java new file mode 100644 index 0000000..13062a1 --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/test/ITest.java @@ -0,0 +1,9 @@ +package org.touchbit.buggy.core.test; + +import org.testng.annotations.Listeners; +import org.touchbit.buggy.core.testng.listeners.IntellijIdeaTestNgPluginListener; + +@Listeners(IntellijIdeaTestNgPluginListener.class) +public interface ITest { + +} 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 index bb68b5d..8e5eb8c 100644 --- 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 @@ -60,7 +60,7 @@ public IntellijIdeaTestNgPluginListener() { } }); String[] args = list.toArray(new String[0]); - Buggy.prepare(args); +// Buggy.prepare(args); } @SuppressWarnings("unchecked") diff --git a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleBuggyImpl.java b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleBuggyRunner.java similarity index 60% rename from buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleBuggyImpl.java rename to buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleBuggyRunner.java index 862df78..a061b3f 100644 --- a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleBuggyImpl.java +++ b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleBuggyRunner.java @@ -1,17 +1,17 @@ package org.touchbit.buggy.spring.boot.starter.example; import org.springframework.boot.SpringApplication; -import org.touchbit.buggy.spring.boot.starter.SBBuggy; +import org.touchbit.buggy.spring.boot.starter.BuggyRunnerBase; import org.touchbit.buggy.spring.boot.starter.conf.BuggyConfig; -public class ExampleBuggyImpl extends SBBuggy { +public class ExampleBuggyRunner extends BuggyRunnerBase { static { BuggyConfig.setForce(true); } public static void main(String[] args) { - SpringApplication.run(ExampleBuggyImpl.class, args); + SpringApplication.run(ExampleBuggyRunner.class, args); } } diff --git a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleTests.java b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleTests.java new file mode 100644 index 0000000..a3e8d13 --- /dev/null +++ b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleTests.java @@ -0,0 +1,7 @@ +package org.touchbit.buggy.spring.boot.starter.example; + +import org.touchbit.buggy.core.model.Suite; + +@Suite() +public class ExampleTests { +} 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 index ded77e1..d29e0b7 100644 --- 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 @@ -6,6 +6,7 @@ public class ExampleConfiguration implements JCConfiguration { @Parameter(names = {"--example-host"}, description = "Example host.") +// @Parameter(names = {"-f"}, description = "Example host.") private static String exampleHost = "https://exmaole.com"; @Parameter(names = {"--example-pass"}, password = true, description = "Example password.") diff --git a/buggy-spring-boot-starter/pom.xml b/buggy-spring-boot-starter/pom.xml index 6627411..8faf177 100644 --- a/buggy-spring-boot-starter/pom.xml +++ b/buggy-spring-boot-starter/pom.xml @@ -5,9 +5,10 @@ 4.0.0 - org.touchbit.buggy - buggy - 0.3.7 + org.springframework.boot + spring-boot-starter-parent + 2.3.4.RELEASE + org.touchbit.buggy @@ -88,4 +89,18 @@ + + + + + + + + + + src/main/resources + true + + + \ No newline at end of file diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/SBBuggy.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/BuggyRunnerBase.java similarity index 66% rename from buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/SBBuggy.java rename to buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/BuggyRunnerBase.java index 042fd1b..f4009aa 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/SBBuggy.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/BuggyRunnerBase.java @@ -1,16 +1,11 @@ package org.touchbit.buggy.spring.boot.starter; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.testng.TestNG; @SpringBootApplication -public abstract class SBBuggy implements ApplicationRunner { - - @Autowired - private TestNG testNG; +public abstract class BuggyRunnerBase implements ApplicationRunner { @Override public void run(ApplicationArguments args) { 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..7e4fbab --- /dev/null +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/ApplicationProperties.java @@ -0,0 +1,67 @@ +package org.touchbit.buggy.spring.boot.starter.conf; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; +import org.springframework.core.io.ClassPathResource; + +@Configuration +public class ApplicationProperties { + + @Value("${buggy.configuration.testng.scanner.suite.basePackage:**.buggy1}") + private String testNGScannerSuiteBasePackage; + + @Value("${buggy.configuration.testng.scanner.suite.useDefaultFilters:false}") + private boolean testNGScannerSuiteUseDefaultFilters; + + @Value("${buggy.configuration.testng.scanner.listener.basePackage:**.buggy1}") + private String testNGScannerListenerBasePackage; + + @Value("${buggy.configuration.testng.scanner.listener.useDefaultFilters:false}") + private boolean testNGScannerListenerUseDefaultFilters; + + public String getTestNGScannerSuiteBasePackage() { + return testNGScannerSuiteBasePackage; + } + + public void setTestNGScannerSuiteBasePackage(String testNGScannerSuiteBasePackage) { + this.testNGScannerSuiteBasePackage = testNGScannerSuiteBasePackage; + } + + public boolean isTestNGScannerSuiteUseDefaultFilters() { + return testNGScannerSuiteUseDefaultFilters; + } + + public void setTestNGScannerSuiteUseDefaultFilters(boolean testNGScannerSuiteUseDefaultFilters) { + this.testNGScannerSuiteUseDefaultFilters = testNGScannerSuiteUseDefaultFilters; + } + + public String getTestNGScannerListenerBasePackage() { + return testNGScannerListenerBasePackage; + } + + public void setTestNGScannerListenerBasePackage(String testNGScannerListenerBasePackage) { + this.testNGScannerListenerBasePackage = testNGScannerListenerBasePackage; + } + + public boolean isTestNGScannerListenerUseDefaultFilters() { + return testNGScannerListenerUseDefaultFilters; + } + + public void setTestNGScannerListenerUseDefaultFilters(boolean testNGScannerListenerUseDefaultFilters) { + this.testNGScannerListenerUseDefaultFilters = testNGScannerListenerUseDefaultFilters; + } + + @Bean + public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() { + PropertySourcesPlaceholderConfigurer c = new PropertySourcesPlaceholderConfigurer(); + c.setLocation(new ClassPathResource("application.yml")); + c.setIgnoreUnresolvablePlaceholders(true); + c.setIgnoreResourceNotFound(true); + c.setTrimValues(true); + c.setNullValue(""); + return c; + } + +} diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBConfiguration.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBConfiguration.java index 9cb83e9..3ac3309 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBConfiguration.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBConfiguration.java @@ -1,7 +1,16 @@ package org.touchbit.buggy.spring.boot.starter.conf; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.LoggerContext; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.Appender; +import ch.qos.logback.core.FileAppender; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; import org.touchbit.buggy.spring.boot.starter.log.ConfigurationLogger; +import java.util.Iterator; + /** * Interface for Buggy spring boot configurations *

@@ -10,25 +19,35 @@ */ public interface SBConfiguration { - default void exitRunWithErr(Exception e) { - exitRunWithErr(e.getMessage()); + default void exitRunWithErr(String message) { + exitRunWithErr(message, null); } - default void exitRunWithErr(String message) { - exitRun(1, message); + default void exitRunWithErr(String message, Exception e) { + exitRun(1, message, e); } default void exitRun(int status) { - exitRun(status, null); + exitRun(status, null, null); } - default void exitRun(int status, String message) { + default void exitRun(int status, String message, Exception e) { if (message != null) { ConfigurationLogger.blockDelimeter(); + String frameworkLogPath = ""; if (status == 0) { ConfigurationLogger.print(message); } else { - ConfigurationLogger.errPrint(message); + if (SBLogbackConfiguration.framework() == null) { + MDC.put("print.console.stacktrace", "true"); + } else { + String frameworkLogFilePath = SBLogbackConfiguration.getFrameworkLogFilePath(); + if (frameworkLogFilePath != null && !frameworkLogFilePath.isEmpty()) { + frameworkLogPath = "\nFor more information see " + frameworkLogFilePath; + } + } + String eMsg = "\n" + e.getClass().getSimpleName() + ": " + e.getMessage(); + ConfigurationLogger.errPrint(message + eMsg + frameworkLogPath, e); } } ConfigurationLogger.blockDelimeter(); diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBJCommanderConfiguration.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBJCommanderConfiguration.java index 45babb1..f04fa53 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBJCommanderConfiguration.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBJCommanderConfiguration.java @@ -103,10 +103,7 @@ public void init() { ConfigurationLogger.stepDelimeter(); ConfigurationLogger.dotPlaceholder("Parsing arguments", "FAIL"); printConfigurationsParams(buggyConfigurations); - if (!(e instanceof ParameterException)) { - e.printStackTrace(); - } - exitRunWithErr(e); + exitRunWithErr(e.getMessage(), e); } } } diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBLogbackConfiguration.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBLogbackConfiguration.java index 3e9f004..1556709 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBLogbackConfiguration.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBLogbackConfiguration.java @@ -2,11 +2,15 @@ import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.joran.JoranConfigurator; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.Appender; +import ch.qos.logback.core.FileAppender; import ch.qos.logback.core.joran.spi.JoranException; import ch.qos.logback.core.util.Loader; import ch.qos.logback.core.util.StatusPrinter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnNotWebApplication; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -17,6 +21,7 @@ import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.net.URL; +import java.util.Iterator; /** * Logback loggers configuration @@ -39,6 +44,7 @@ public class SBLogbackConfiguration implements SBConfiguration { private static Logger test; private final boolean isBuggyLoggerInitialized; private final String loggingConfigFile; + private final LoggerContext context; public SBLogbackConfiguration(Environment env) { loggingConfigFile = env.getProperty("logging.config"); @@ -47,21 +53,21 @@ public SBLogbackConfiguration(Environment env) { ConfigurationLogger.stepDelimeter(); URL logbackXml = getResource(LOGBACK_XML, this.getClass()); URL buggyLogbackXml = getResource("buggy-logback.xml", this.getClass()); - LoggerContext context = null; + LoggerContext tmpContext = null; if (logbackXml != null) { ConfigurationLogger.fPrint(LOGBACK_XML, ".", "OK"); - context = reloadLogger(logbackXml); + tmpContext = reloadLogger(logbackXml); } else { ConfigurationLogger.fPrint(LOGBACK_XML, ".", "FAIL"); } - if (logbackXml == null && buggyLogbackXml != null) { ConfigurationLogger.fPrint(BUGGY_LOGBACK_XML, ".", "OK"); - context = reloadLogger(buggyLogbackXml); + tmpContext = reloadLogger(buggyLogbackXml); } else { ConfigurationLogger.fPrint(BUGGY_LOGBACK_XML, ".", "FAIL"); exitRunWithErr("Logback configuration not found"); } + context = tmpContext; if (context != null) { setTestLog(LoggerFactory.getLogger("Routing")); setConsoleLog(LoggerFactory.getLogger("Console")); @@ -82,15 +88,22 @@ public SBLogbackConfiguration(Environment env) { console.info(ConfigurationLogger.filler(name, ".", logger.getLevel())); } } + } else { + exitRunWithErr("Unable to load Logback configuration."); } isBuggyLoggerInitialized = true; } - @Bean("isBuggyLoggerInitialized") + @Bean() +// @ConditionalOnMissingBean public boolean isBuggyLoggerInitialized() { return isBuggyLoggerInitialized; } + public LoggerContext getContext() { + return context; + } + public static Logger console() { return console; } @@ -141,4 +154,17 @@ public void setTestLog(Logger test) { SBLogbackConfiguration.test = test; } + public static String getFrameworkLogFilePath() { + LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); + for (ch.qos.logback.classic.Logger logger : context.getLoggerList()) { + for (Iterator> index = logger.iteratorForAppenders(); index.hasNext();) { + Appender appender = index.next(); + if (appender instanceof FileAppender && appender.getName().equalsIgnoreCase("Framework")) { + FileAppender fileAppender = (FileAppender) appender; + return fileAppender.getFile(); + } + } + } + return null; + } } diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBTestNGConfiguration.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBTestNGConfiguration.java index 9ac86b0..49acc43 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBTestNGConfiguration.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBTestNGConfiguration.java @@ -1,18 +1,25 @@ package org.touchbit.buggy.spring.boot.starter.conf; -import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.boot.autoconfigure.condition.ConditionalOnNotWebApplication; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.DependsOn; -import org.testng.TestNG; +import org.springframework.cglib.beans.BeanGenerator; +import org.springframework.context.annotation.*; +import org.springframework.core.type.filter.AnnotationTypeFilter; +import org.springframework.core.type.filter.AssignableTypeFilter; 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.testng.listeners.BuggyListener; import org.touchbit.buggy.spring.boot.starter.log.ConfigurationLogger; -import java.util.Map; +import java.lang.annotation.Annotation; +import java.lang.reflect.Constructor; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import static java.lang.reflect.Modifier.*; /** * TestNG configuration @@ -26,24 +33,98 @@ */ @Configuration() @ConditionalOnNotWebApplication -@DependsOn({"initAndGetBuggyConfigurations", "isBuggyLoggerInitialized"}) +@DependsOn({"initAndGetBuggyConfigurations"}) public class SBTestNGConfiguration implements SBConfiguration { - @Autowired - Map, JCConfiguration> getBuggyConfigurations; + private final ApplicationProperties properties; - public SBTestNGConfiguration(boolean isBuggyLoggerInitialized) { + private final List listenerList; + private final List enabledBuggyListeners = new ArrayList<>(); + private final List> testClasses; + + public SBTestNGConfiguration(final boolean isBuggyLoggerInitialized, final ApplicationProperties properties) { + this.properties = properties; if (!isBuggyLoggerInitialized) { exitRunWithErr("Logger must be initialized"); } ConfigurationLogger.blockDelimeter(); ConfigurationLogger.centerBold("Loading TestNG configuration"); + this.testClasses = getTestClassesWithSuiteAnnotation(); + this.listenerList = getTestNGListeners(); + for (BuggyListener buggyListener : this.listenerList) { + if (buggyListener.isEnable()) { + enabledBuggyListeners.add(buggyListener); + ConfigurationLogger.dotPlaceholder(buggyListener.getClass().getSimpleName(), "Enable"); + } else { + ConfigurationLogger.dotPlaceholder(buggyListener.getClass().getSimpleName(), "Disable"); + } + } + } + + @Bean("getTestClasses") + public List> getTestClasses() { + return testClasses; + } + + @Bean("getBuggyListeners") + public List getBuggyListeners() { + return listenerList; + } + + @Bean("getEnabledBuggyListeners") + public List getEnabledBuggyListeners() { + return enabledBuggyListeners; } - @Bean - public TestNG testNG() { + public List> getTestClassesWithSuiteAnnotation() { + List> resultList = new ArrayList<>(); + boolean useDefaultFilters = properties.isTestNGScannerSuiteUseDefaultFilters(); + String basePackage = properties.getTestNGScannerSuiteBasePackage(); + Set definitions = scanBeanDefinitions(useDefaultFilters, basePackage, Suite.class); + for (BeanDefinition bd : definitions) { + try { + Class testClass = Thread.currentThread().getContextClassLoader().loadClass(bd.getBeanClassName()); + int mods = testClass.getModifiers(); + if (isPublic(mods) && !isAbstract(mods) && !isInterface(mods)) { + resultList.add(testClass); + } + } catch (ClassNotFoundException e) { + exitRunWithErr("Failed to load @Suite-annotated class.", e); + } + } + return resultList; + } + + public List getTestNGListeners() { + List result = new ArrayList<>(); + boolean useDefaultFilters = properties.isTestNGScannerListenerUseDefaultFilters(); + String basePackage = properties.getTestNGScannerListenerBasePackage(); ConfigurationLogger.stepDelimeter(); - return new TestNG(); + ConfigurationLogger.center("TestNG listeners"); + Set definitions = scanBeanDefinitions(useDefaultFilters, basePackage, BuggyListener.class); + for (BeanDefinition bd : definitions) { + try { + Class c = BeanGenerator.class.getClassLoader().loadClass(bd.getBeanClassName()); + Constructor con = c.getConstructor(); + BuggyListener instance = (BuggyListener) con.newInstance(); + result.add(instance); + } catch (Exception e) { + exitRunWithErr("Failed to load inheritor of class BuggyListener.", e); + } + } + return result; + } + + public 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)); + } + return scanner.findCandidateComponents(basePackage); } } diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/log/ConfigurationLogger.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/log/ConfigurationLogger.java index cff0ebf..7e29378 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/log/ConfigurationLogger.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/log/ConfigurationLogger.java @@ -129,39 +129,16 @@ public static void print(String msg) { CONSOLE.info(msg); } - public static void errPrint(String msg, Exception t) { - String breakMsg = lineBreak(msg); - CONSOLE.error(RED.wrap(breakMsg), t); + public static void errPrint(String msg, Throwable t) { + CONSOLE.error(RED.wrap(msg), t); } public static void errPrint(String msg) { - String breakMsg = lineBreak(msg); - CONSOLE.error(RED.wrap(breakMsg)); + CONSOLE.error(RED.wrap(msg)); } - public static String lineBreak(String msg) { - StringJoiner sj = new StringJoiner("\n"); - StringBuilder line = new StringBuilder(); - for (String s : msg.split(" ")) { - String tmp = line + " " + s; - if (tmp.length() < 47) { - line.append(s).append(" "); - } - if (tmp.length() == 47) { - sj.add(tmp); - line = new StringBuilder(); - } - if (tmp.length() > 47) { - if (line.length() == 0) { - sj.add(s); - } else { - sj.add(line.toString()); - line = new StringBuilder(s + " "); - } - } - } - sj.add(line); - return sj.toString(); + public static Logger getLogger() { + return CONSOLE; } } diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/log/ConsoleLoggerColorLayout.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/log/ConsoleLoggerColorLayout.java index 7129b84..cb277cf 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/log/ConsoleLoggerColorLayout.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/log/ConsoleLoggerColorLayout.java @@ -1,8 +1,11 @@ package org.touchbit.buggy.spring.boot.starter.log; 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 org.slf4j.MDC; import static ch.qos.logback.classic.Level.*; import static org.touchbit.buggy.spring.boot.starter.log.ANSI.*; @@ -47,6 +50,12 @@ public String doLayout(ILoggingEvent event) { default: return ""; } + IThrowableProxy throwableProxy = event.getThrowableProxy(); + boolean withST = Boolean.parseBoolean(MDC.get("print.console.stacktrace")); + if (throwableProxy != null && withST) { + stringBuilder.append(CoreConstants.LINE_SEPARATOR); + stringBuilder.append(ThrowableProxyUtil.asString(throwableProxy)); + } stringBuilder.append(CoreConstants.LINE_SEPARATOR); return stringBuilder.toString(); } diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/log/FrameworkLoggerLayout.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/log/FrameworkLoggerLayout.java index f2b08bc..f94d13c 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/log/FrameworkLoggerLayout.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/log/FrameworkLoggerLayout.java @@ -2,6 +2,8 @@ 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; @@ -40,7 +42,12 @@ public String doLayout(ILoggingEvent event) { String finalMessage = ANSI.unwrap(message); String time = TIME_FORMATTER.format(timestamp); Level level = event.getLevel(); - return time + " " + level + " - " + finalMessage + CoreConstants.LINE_SEPARATOR; + 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-spring-boot-starter/src/main/resources/application.yml b/buggy-spring-boot-starter/src/main/resources/application.yml index a5555ec..e52d680 100644 --- a/buggy-spring-boot-starter/src/main/resources/application.yml +++ b/buggy-spring-boot-starter/src/main/resources/application.yml @@ -4,9 +4,12 @@ spring: main: allow-bean-definition-overriding: true buggy: - all: true - force: true - print-suite: true - print-cause: true - print-log: true - type: SYSTEM \ No newline at end of file + configuration: + testng: + scanner: + suite: + basePackage: "**.buggy" + useDefaultFilters: false + listener: + basePackage: "**.buggy" + useDefaultFilters: false \ No newline at end of file diff --git a/buggy-spring-boot-starter/src/main/resources/buggy-logback.xml b/buggy-spring-boot-starter/src/main/resources/buggy-logback.xml index e74bf4a..3e06cd5 100644 --- a/buggy-spring-boot-starter/src/main/resources/buggy-logback.xml +++ b/buggy-spring-boot-starter/src/main/resources/buggy-logback.xml @@ -34,7 +34,7 @@ - + From 779d8c3add5762a7d9fbd68f87f45bd980a12acf Mon Sep 17 00:00:00 2001 From: "oleg.shaburov" Date: Sun, 4 Oct 2020 21:22:49 +0300 Subject: [PATCH 08/24] Logback loggers moved to the core module --- buggy-core/pom.xml | 4 + .../buggy/core/config/BParameters.java | 2 +- .../buggy/core/config}/BuggyConfig.java | 32 +--- .../buggy/core/config}/JCConfiguration.java | 9 +- .../config/jcommander/ValueValidator.java | 29 +-- .../touchbit/buggy/core/utils/BuggyUtils.java | 25 --- .../org/touchbit/buggy/core/utils/JUtils.java | 154 ++++++++++++++++ .../touchbit/buggy/core/utils}/log/ANSI.java | 11 +- .../buggy/core/utils/log/BuggyLoggers.java | 65 +++++++ .../core/utils/log/ConfigurationLogger.java | 110 ++++++++++++ .../utils}/log/ConsoleLoggerColorLayout.java | 14 +- .../utils}/log/FrameworkLoggerLayout.java | 32 ++-- .../core/utils/log/ShiftingLoggerLayout.java | 60 +++++++ .../core/tests/utils/BuggyUtilsTests.java | 13 -- .../starter/example/ExampleBuggyRunner.java | 7 +- .../example/conf/ExampleConfiguration.java | 2 +- buggy-spring-boot-starter/pom.xml | 52 ------ .../spring/boot/starter/BuggyRunner.java | 61 +++++++ .../spring/boot/starter/BuggyRunnerBase.java | 15 -- .../starter/conf/ApplicationProperties.java | 30 +++- .../boot/starter/conf/IConfiguration.java | 76 ++++++++ ...tion.java => JCommanderConfiguration.java} | 145 ++++++++------- .../starter/conf/LogbackConfiguration.java | 53 ++++++ .../boot/starter/conf/SBConfiguration.java | 59 ------ .../starter/conf/SBLogbackConfiguration.java | 170 ------------------ .../starter/conf/SBTestNGConfiguration.java | 130 -------------- .../starter/conf/TestNGConfiguration.java | 86 +++++++++ .../boot/starter/log/ConfigurationLogger.java | 144 --------------- .../spring/boot/starter/utils/JUtils.java | 80 --------- .../main/resources/META-INF/spring.factories | 0 .../src/main/resources/application.yml | 26 ++- .../src/main/resources/buggy-logback.xml | 41 +++-- pom.xml | 5 + 33 files changed, 872 insertions(+), 870 deletions(-) rename {buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf => buggy-core/src/main/java/org/touchbit/buggy/core/config}/BuggyConfig.java (90%) rename {buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf => buggy-core/src/main/java/org/touchbit/buggy/core/config}/JCConfiguration.java (92%) create mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/utils/JUtils.java rename {buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter => buggy-core/src/main/java/org/touchbit/buggy/core/utils}/log/ANSI.java (59%) create mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/utils/log/BuggyLoggers.java create mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/utils/log/ConfigurationLogger.java rename {buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter => buggy-core/src/main/java/org/touchbit/buggy/core/utils}/log/ConsoleLoggerColorLayout.java (79%) rename {buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter => buggy-core/src/main/java/org/touchbit/buggy/core/utils}/log/FrameworkLoggerLayout.java (61%) create mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/utils/log/ShiftingLoggerLayout.java create mode 100644 buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/BuggyRunner.java delete mode 100644 buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/BuggyRunnerBase.java create mode 100644 buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/IConfiguration.java rename buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/{SBJCommanderConfiguration.java => JCommanderConfiguration.java} (55%) create mode 100644 buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/LogbackConfiguration.java delete mode 100644 buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBConfiguration.java delete mode 100644 buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBLogbackConfiguration.java delete mode 100644 buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBTestNGConfiguration.java create mode 100644 buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/TestNGConfiguration.java delete mode 100644 buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/log/ConfigurationLogger.java delete mode 100644 buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/utils/JUtils.java delete mode 100644 buggy-spring-boot-starter/src/main/resources/META-INF/spring.factories diff --git a/buggy-core/pom.xml b/buggy-core/pom.xml index 7e8d2b4..3cf127c 100644 --- a/buggy-core/pom.xml +++ b/buggy-core/pom.xml @@ -43,6 +43,10 @@ 1.9.6 + + ch.qos.logback + logback-classic + org.apache.logging.log4j log4j-slf4j-impl 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 index 9639bab..a963011 100644 --- 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 @@ -26,7 +26,7 @@ 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 HELP = "--help"; public static final String C = "-c"; public static final String COMPONENTS = "--component"; public static final String S = "-s"; diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/BuggyConfig.java b/buggy-core/src/main/java/org/touchbit/buggy/core/config/BuggyConfig.java similarity index 90% rename from buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/BuggyConfig.java rename to buggy-core/src/main/java/org/touchbit/buggy/core/config/BuggyConfig.java index 2dd5aec..8040efb 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/BuggyConfig.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/config/BuggyConfig.java @@ -1,11 +1,9 @@ -package org.touchbit.buggy.spring.boot.starter.conf; +package org.touchbit.buggy.core.config; import com.beust.jcommander.Parameter; -import org.springframework.core.annotation.Order; 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.goal.component.AllComponents; import org.touchbit.buggy.core.goal.component.Component; import org.touchbit.buggy.core.goal.interfaze.AllInterfaces; @@ -26,10 +24,10 @@ * Created by Oleg Shaburov on 01.10.2020 * shaburov.o.a@gmail.com */ -@Order(1) +@SuppressWarnings("unused") public class BuggyConfig implements JCConfiguration { - @Parameter(names = HELP, help = true, description = "Print usage.") + @Parameter(names = {QUESTION_MARK, HELP}, help = true, description = "Print usage.") private static Boolean help = false; @Parameter(names = {F, FORCE}, description = "Running all tests, including those that fall.") @@ -46,10 +44,7 @@ public class BuggyConfig implements JCConfiguration { private static Boolean printLogOnlyFail = false; - @Parameter(names = {SELF_CHECK}, description = "Check buggy configuration without test run.") - private static Boolean check = false; - - @Parameter(names = {V, VERSION}, description = "Print program version", validateValueWith = ValueValidator.class) + @Parameter(names = {V, VERSION}, description = "Print program version") private static Boolean version = false; @Parameter(names = {THREADS}, description = "The number of threads to run the test methods.") @@ -58,9 +53,6 @@ public class BuggyConfig implements JCConfiguration { @Parameter(names = {EXIT_STATUS}, description = "Completion with the specified status.") private static Integer status; - @Parameter(names = {LOGS_PATH}, description = "Absolute path to the directory for test logs.") - private static String logsPath = "logs"; - @Parameter(names = {ARTIFACTS_URL}, description = "The storage address for the builds (artifacts).") private static String artifactsUrl; @@ -130,14 +122,6 @@ public static void setPrintLogOnlyFail(Boolean printLogOnlyFail) { BuggyConfig.printLogOnlyFail = printLogOnlyFail; } - public static Boolean getCheck() { - return check; - } - - public static void setCheck(Boolean check) { - BuggyConfig.check = check; - } - public static Boolean getVersion() { return version; } @@ -162,14 +146,6 @@ public static void setStatus(Integer status) { BuggyConfig.status = status; } - public static String getLogsPath() { - return logsPath; - } - - public static void setLogsPath(String logsPath) { - BuggyConfig.logsPath = logsPath; - } - public static String getArtifactsUrl() { return artifactsUrl; } diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/JCConfiguration.java b/buggy-core/src/main/java/org/touchbit/buggy/core/config/JCConfiguration.java similarity index 92% rename from buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/JCConfiguration.java rename to buggy-core/src/main/java/org/touchbit/buggy/core/config/JCConfiguration.java index 76763fd..317d1c6 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/JCConfiguration.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/config/JCConfiguration.java @@ -1,8 +1,7 @@ -package org.touchbit.buggy.spring.boot.starter.conf; +package org.touchbit.buggy.core.config; import com.beust.jcommander.Parameter; -import org.touchbit.buggy.spring.boot.starter.log.ConfigurationLogger; -import org.touchbit.buggy.spring.boot.starter.utils.JUtils; +import org.touchbit.buggy.core.utils.JUtils; import java.lang.reflect.Field; import java.lang.reflect.Method; @@ -53,7 +52,7 @@ default void addFieldValuesToMap(Map map) { map.put(Arrays.toString(names), field.get(this)); } } catch (Exception e) { - ConfigurationLogger.errPrint(e.getMessage()); +// ConfigurationLogger.errPrint(e.getMessage()); TODO } finally { field.setAccessible(false); } @@ -89,7 +88,7 @@ default void addMethodsValuesToMap(Map map) { method.getValue().setAccessible(true); map.put(method.getKey().toString(), method.getValue().invoke(this)); } catch (Exception e) { - ConfigurationLogger.errPrint(e.getMessage()); // TODO +// ConfigurationLogger.errPrint(e.getMessage()); TODO } finally { method.getValue().setAccessible(false); } 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 index 6e7274c..e71194e 100644 --- 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 @@ -36,34 +36,7 @@ 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.parseBoolean(stringValue)) { - Buggy.getExitHandler().exitRunWithUsage(0); - } - if ((name.equals(V) || name.equals(VERSION)) && Boolean.parseBoolean(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); - } - } + // TODO remove } } 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 index c93a28e..1d6bbcf 100644 --- 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 @@ -151,31 +151,6 @@ public static boolean equalsSuites(Suite s1, Suite s2) { 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/JUtils.java b/buggy-core/src/main/java/org/touchbit/buggy/core/utils/JUtils.java new file mode 100644 index 0000000..ac8307c --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/utils/JUtils.java @@ -0,0 +1,154 @@ +package org.touchbit.buggy.core.utils; + +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.jar.Attributes; +import java.util.jar.Manifest; +import java.util.stream.Collectors; + +import static org.touchbit.buggy.core.utils.BuggyUtils.CONSOLE_DELIMITER; +import static org.touchbit.buggy.core.utils.StringUtils.underscoreFiller; + +/** + * 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 boolean isJetBrainsIdeRun() { + RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean(); + List arguments = runtimeMxBean.getInputArguments(); + return arguments.stream() + .anyMatch(v -> v.startsWith("-javaagent") && + (v.contains("JetBrains") || v.contains("IDEA") || v.contains("idea"))); + } + + public static String getRunPath() { + String runDir = System.getProperty("user.dir"); + if (isJetBrainsIdeRun()) { + String javaClassPath = System.getProperty("java.class.path"); + if (javaClassPath != null && !javaClassPath.isEmpty()) { + String firstClassPath = javaClassPath.split(":")[0]; + if (firstClassPath.contains("/target/") && firstClassPath.contains(runDir)) { + return firstClassPath.substring(0, firstClassPath.indexOf("/target/")) + "/target"; + } + } + } + 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; + } + } + +} diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/log/ANSI.java b/buggy-core/src/main/java/org/touchbit/buggy/core/utils/log/ANSI.java similarity index 59% rename from buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/log/ANSI.java rename to buggy-core/src/main/java/org/touchbit/buggy/core/utils/log/ANSI.java index 91983a9..ec93c34 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/log/ANSI.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/utils/log/ANSI.java @@ -1,4 +1,4 @@ -package org.touchbit.buggy.spring.boot.starter.log; +package org.touchbit.buggy.core.utils.log; public enum ANSI { @@ -16,14 +16,15 @@ public enum ANSI { this.symbol = symbol; } - public static String unwrap(String msg) { + public static String unwrap(final String msg) { + String resultMsg = msg; for (ANSI value : ANSI.values()) { - msg = msg.replace(value.symbol, ""); + resultMsg = msg.replace(value.symbol, ""); } - return msg; + return resultMsg; } - public String wrap(String msg) { + public String wrap(final String msg) { return this.symbol + msg + RESET.symbol; } diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/utils/log/BuggyLoggers.java b/buggy-core/src/main/java/org/touchbit/buggy/core/utils/log/BuggyLoggers.java new file mode 100644 index 0000000..8ed0c4c --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/utils/log/BuggyLoggers.java @@ -0,0 +1,65 @@ +package org.touchbit.buggy.core.utils.log; + +import ch.qos.logback.classic.LoggerContext; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.Appender; +import ch.qos.logback.core.FileAppender; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; + +import java.io.File; +import java.util.Iterator; + +public class BuggyLoggers { + + public static final String CONSOLE_LOGGER_NAME = "Console"; + public static final String FRAMEWORK_LOGGER_NAME = "Framework"; + public static final String SIFTING_LOGGER_NAME = "Sifting"; + public static final String CONFIG_PROPERTY = "logging.config"; + public static final String SIFTING_LOG_FILE_PATH = "sifting.log.file.path"; + + public static final Logger C_LOG = LoggerFactory.getLogger(CONSOLE_LOGGER_NAME); + public static final Logger CONSOLE = C_LOG; + public static final Logger F_LOG = LoggerFactory.getLogger(FRAMEWORK_LOGGER_NAME); + public static final Logger FRAMEWORK = F_LOG; + public static final Logger S_LOG = LoggerFactory.getLogger(SIFTING_LOGGER_NAME); + public static final Logger SIFTING = S_LOG; + public static final String LOGGING_CONFIG_FILE = System.getProperty(CONFIG_PROPERTY, "buggy-logback.xml"); + public static final LoggerContext LOGGER_CONTEXT = (LoggerContext) LoggerFactory.getILoggerFactory(); + + public static String getFrameworkLogFilePath() { + return getLogFilePath(FRAMEWORK_LOGGER_NAME); + } + + public static String getLogFilePath(String loggerName) { + LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); + for (ch.qos.logback.classic.Logger logger : context.getLoggerList()) { + for (Iterator> index = logger.iteratorForAppenders(); index.hasNext();) { + Appender appender = index.next(); + if (appender instanceof FileAppender && appender.getName().equalsIgnoreCase(loggerName)) { + FileAppender fileAppender = (FileAppender) appender; + return fileAppender.getFile(); + } + } + } + return null; + } + + public static void setSiftingLogFilePath(String dir, String filename) { + setSiftingLogFilePath(new File(dir, filename)); + } + + public static void setSiftingLogFilePath(String filePath) { + setSiftingLogFilePath(new File(filePath)); + } + + public static void setSiftingLogFilePath(File file) { + MDC.put(SIFTING_LOG_FILE_PATH, file.getPath()); + } + + protected BuggyLoggers() { + throw new IllegalStateException("Utility class. Prohibit instantiation."); + } + +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/utils/log/ConfigurationLogger.java b/buggy-core/src/main/java/org/touchbit/buggy/core/utils/log/ConfigurationLogger.java new file mode 100644 index 0000000..5f543ef --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/utils/log/ConfigurationLogger.java @@ -0,0 +1,110 @@ +package org.touchbit.buggy.core.utils.log; + +import static java.util.Objects.isNull; +import static org.touchbit.buggy.core.utils.log.ANSI.BOLD; +import static org.touchbit.buggy.core.utils.log.ANSI.RED; + +/** + * Utility class for logging configuration events in TestNG format + *

+ * Created by Oleg Shaburov on 01.10.2020 + * shaburov.o.a@gmail.com + */ +public class ConfigurationLogger { + + 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 ConfigurationLogger() { + 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) { + info(filler(prefix, DOT, postfix)); + } + + 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) { + BuggyLoggers.CONSOLE.info(msg); + } + + public static void error(String msg, Throwable t) { + BuggyLoggers.CONSOLE.error(RED.wrap(msg), t); + } + + public static void error(String msg) { + BuggyLoggers.CONSOLE.error(RED.wrap(msg)); + } + +} diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/log/ConsoleLoggerColorLayout.java b/buggy-core/src/main/java/org/touchbit/buggy/core/utils/log/ConsoleLoggerColorLayout.java similarity index 79% rename from buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/log/ConsoleLoggerColorLayout.java rename to buggy-core/src/main/java/org/touchbit/buggy/core/utils/log/ConsoleLoggerColorLayout.java index cb277cf..cd28f5d 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/log/ConsoleLoggerColorLayout.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/utils/log/ConsoleLoggerColorLayout.java @@ -1,4 +1,4 @@ -package org.touchbit.buggy.spring.boot.starter.log; +package org.touchbit.buggy.core.utils.log; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.classic.spi.IThrowableProxy; @@ -8,7 +8,7 @@ import org.slf4j.MDC; import static ch.qos.logback.classic.Level.*; -import static org.touchbit.buggy.spring.boot.starter.log.ANSI.*; +import static org.touchbit.buggy.core.utils.log.ANSI.*; /** * Console logger layout for dividing logging levels by color. @@ -28,9 +28,9 @@ public class ConsoleLoggerColorLayout extends LayoutBase { * Log format: message\n */ @Override - public String doLayout(ILoggingEvent event) { - StringBuilder stringBuilder = new StringBuilder(128); - String msg = event.getFormattedMessage(); + 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)); @@ -50,8 +50,8 @@ public String doLayout(ILoggingEvent event) { default: return ""; } - IThrowableProxy throwableProxy = event.getThrowableProxy(); - boolean withST = Boolean.parseBoolean(MDC.get("print.console.stacktrace")); + final IThrowableProxy throwableProxy = event.getThrowableProxy(); + final boolean withST = Boolean.parseBoolean(MDC.get("print.console.stacktrace")); if (throwableProxy != null && withST) { stringBuilder.append(CoreConstants.LINE_SEPARATOR); stringBuilder.append(ThrowableProxyUtil.asString(throwableProxy)); diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/log/FrameworkLoggerLayout.java b/buggy-core/src/main/java/org/touchbit/buggy/core/utils/log/FrameworkLoggerLayout.java similarity index 61% rename from buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/log/FrameworkLoggerLayout.java rename to buggy-core/src/main/java/org/touchbit/buggy/core/utils/log/FrameworkLoggerLayout.java index f94d13c..9137481 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/log/FrameworkLoggerLayout.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/utils/log/FrameworkLoggerLayout.java @@ -1,4 +1,4 @@ -package org.touchbit.buggy.spring.boot.starter.log; +package org.touchbit.buggy.core.utils.log; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.spi.ILoggingEvent; @@ -7,6 +7,7 @@ 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.log.ANSI; import java.util.Date; @@ -26,9 +27,18 @@ public class FrameworkLoggerLayout extends LayoutBase { */ @Override public String getPresentationHeader() { - long timestamp = new Date().getTime(); - String time = TIME_FORMATTER.format(timestamp); - String date = DATE_FORMATTER.format(timestamp); + 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; } @@ -36,13 +46,13 @@ public String getPresentationHeader() { * Log format: 17:28:15.142 INFO - message\n */ @Override - public String doLayout(ILoggingEvent event) { - long timestamp = event.getTimeStamp(); - String message = event.getFormattedMessage(); - String finalMessage = ANSI.unwrap(message); - String time = TIME_FORMATTER.format(timestamp); - Level level = event.getLevel(); - IThrowableProxy throwableProxy = event.getThrowableProxy(); + 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); diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/utils/log/ShiftingLoggerLayout.java b/buggy-core/src/main/java/org/touchbit/buggy/core/utils/log/ShiftingLoggerLayout.java new file mode 100644 index 0000000..14f2e55 --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/utils/log/ShiftingLoggerLayout.java @@ -0,0 +1,60 @@ +package org.touchbit.buggy.core.utils.log; + +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 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 ILoggingEvent 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/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 c2f96f3..0625c1b 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 @@ -114,11 +114,6 @@ 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") @@ -161,14 +156,6 @@ public int read() throws IOException { 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() { 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 index a061b3f..e858e3d 100644 --- 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 @@ -1,13 +1,14 @@ package org.touchbit.buggy.spring.boot.starter.example; import org.springframework.boot.SpringApplication; -import org.touchbit.buggy.spring.boot.starter.BuggyRunnerBase; -import org.touchbit.buggy.spring.boot.starter.conf.BuggyConfig; +import org.touchbit.buggy.spring.boot.starter.BuggyRunner; +import org.touchbit.buggy.core.config.BuggyConfig; -public class ExampleBuggyRunner extends BuggyRunnerBase { +public class ExampleBuggyRunner extends BuggyRunner { static { BuggyConfig.setForce(true); + BuggyConfig.setVersion(true); } public static void main(String[] 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 index d29e0b7..bc32390 100644 --- 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 @@ -1,7 +1,7 @@ package org.touchbit.buggy.spring.boot.starter.example.conf; import com.beust.jcommander.Parameter; -import org.touchbit.buggy.spring.boot.starter.conf.JCConfiguration; +import org.touchbit.buggy.core.config.JCConfiguration; public class ExampleConfiguration implements JCConfiguration { diff --git a/buggy-spring-boot-starter/pom.xml b/buggy-spring-boot-starter/pom.xml index 8faf177..cf8b155 100644 --- a/buggy-spring-boot-starter/pom.xml +++ b/buggy-spring-boot-starter/pom.xml @@ -27,80 +27,28 @@ org.touchbit.buggy buggy-core 0.3.7 - - - 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 - - - - - ch.qos.logback - logback-classic - 1.2.3 - - - com.beust - jcommander - 1.78 org.springframework.boot spring-boot-starter-validation - 2.3.4.RELEASE org.springframework.boot spring-boot-starter - 2.3.4.RELEASE org.springframework.boot spring-boot-starter-logging - 2.3.4.RELEASE org.springframework.boot spring-boot-configuration-processor - 2.3.4.RELEASE true org.springframework.boot spring-boot-starter-test - 2.3.4.RELEASE test - - - - - - - - - - - src/main/resources - true - - - \ 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..1e8cade --- /dev/null +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/BuggyRunner.java @@ -0,0 +1,61 @@ +package org.touchbit.buggy.spring.boot.starter; + +import org.slf4j.MDC; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.touchbit.buggy.core.utils.log.ConfigurationLogger; +import org.touchbit.buggy.core.utils.log.BuggyLoggers; + +@SpringBootApplication +public class BuggyRunner implements ApplicationRunner { + + @Override + public void run(ApplicationArguments args) { + ConfigurationLogger.blockDelimiter(); + System.out.println("Hello World from Buggy Runner"); + exit(0); + } + + 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) { + ConfigurationLogger.blockDelimiter(); + String frameworkLogPath = ""; + if (status == 0) { + ConfigurationLogger.info(message); + } else { + if (BuggyLoggers.F_LOG == null) { + MDC.put("print.console.stacktrace", "true"); + } else { + String frameworkLogFilePath = BuggyLoggers.getFrameworkLogFilePath(); + if (frameworkLogFilePath != null && !frameworkLogFilePath.isEmpty()) { + frameworkLogPath = "\nFor more information see " + frameworkLogFilePath; + } + } + String eMsg = "\n" + e.getClass().getSimpleName() + ": " + e.getMessage(); + ConfigurationLogger.error(message + eMsg + frameworkLogPath, e); + } + } + ConfigurationLogger.blockDelimiter(); + ConfigurationLogger.dotPlaceholder("Exit code", status); + ConfigurationLogger.blockDelimiter(); + System.exit(status); + } + +} diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/BuggyRunnerBase.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/BuggyRunnerBase.java deleted file mode 100644 index f4009aa..0000000 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/BuggyRunnerBase.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.touchbit.buggy.spring.boot.starter; - -import org.springframework.boot.ApplicationArguments; -import org.springframework.boot.ApplicationRunner; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public abstract class BuggyRunnerBase implements ApplicationRunner { - - @Override - public void run(ApplicationArguments args) { - System.out.println("Hello World from Application Runner"); - } - -} 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 index 7e4fbab..2fd0947 100644 --- 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 @@ -9,18 +9,40 @@ @Configuration public class ApplicationProperties { - @Value("${buggy.configuration.testng.scanner.suite.basePackage:**.buggy1}") + @Value("${buggy.spring.configuration.testng.scanner.suite.basePackage:**.buggy}") private String testNGScannerSuiteBasePackage; - @Value("${buggy.configuration.testng.scanner.suite.useDefaultFilters:false}") + @Value("${buggy.spring.configuration.testng.scanner.suite.useDefaultFilters:false}") private boolean testNGScannerSuiteUseDefaultFilters; - @Value("${buggy.configuration.testng.scanner.listener.basePackage:**.buggy1}") + @Value("${buggy.spring.configuration.testng.scanner.listener.basePackage:**.buggy}") private String testNGScannerListenerBasePackage; - @Value("${buggy.configuration.testng.scanner.listener.useDefaultFilters:false}") + @Value("${buggy.spring.configuration.testng.scanner.listener.useDefaultFilters:false}") private boolean testNGScannerListenerUseDefaultFilters; + @Value("${buggy.spring.configuration.jcommander.scanner.commands.basePackage:**.buggy}") + private String jCommanderScannerCommandsBasePackage; + + @Value("${buggy.spring.configuration.jcommander.scanner.commands.useDefaultFilters:false}") + private boolean jCommanderScannerCommandsUseDefaultFilters; + + public String getJCommanderScannerCommandsBasePackage() { + return jCommanderScannerCommandsBasePackage; + } + + public void setJCommanderScannerCommandsBasePackage(String jCommanderScannerCommandsBasePackage) { + this.jCommanderScannerCommandsBasePackage = jCommanderScannerCommandsBasePackage; + } + + public boolean isJCommanderScannerCommandsUseDefaultFilters() { + return jCommanderScannerCommandsUseDefaultFilters; + } + + public void setJCommanderScannerCommandsUseDefaultFilters(boolean jCommanderScannerCommandsUseDefaultFilters) { + this.jCommanderScannerCommandsUseDefaultFilters = jCommanderScannerCommandsUseDefaultFilters; + } + public String getTestNGScannerSuiteBasePackage() { return testNGScannerSuiteBasePackage; } 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..93903d3 --- /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 testClass = BeanGenerator.class.getClassLoader().loadClass(bd.getBeanClassName()); + int mods = testClass.getModifiers(); + if (isPublic(mods) && !isAbstract(mods) && !isInterface(mods)) { + result.add(testClass); + } + } 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/SBJCommanderConfiguration.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/JCommanderConfiguration.java similarity index 55% rename from buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBJCommanderConfiguration.java rename to buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/JCommanderConfiguration.java index f04fa53..31fa55c 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBJCommanderConfiguration.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/JCommanderConfiguration.java @@ -2,20 +2,18 @@ import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; -import com.beust.jcommander.ParameterException; import com.beust.jcommander.Parameters; +import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.autoconfigure.condition.ConditionalOnNotWebApplication; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; -import org.touchbit.buggy.core.goal.Goal; -import org.touchbit.buggy.core.goal.component.AllComponents; -import org.touchbit.buggy.core.goal.interfaze.AllInterfaces; -import org.touchbit.buggy.core.goal.service.AllServices; -import org.touchbit.buggy.core.model.Type; -import org.touchbit.buggy.spring.boot.starter.log.ConfigurationLogger; -import org.touchbit.buggy.spring.boot.starter.utils.JUtils; +import org.touchbit.buggy.core.config.BuggyConfig; +import org.touchbit.buggy.core.config.JCConfiguration; +import org.touchbit.buggy.spring.boot.starter.BuggyRunner; +import org.touchbit.buggy.core.utils.log.ConfigurationLogger; +import org.touchbit.buggy.core.utils.JUtils; import javax.annotation.PostConstruct; import java.lang.reflect.Field; @@ -23,8 +21,6 @@ import java.lang.reflect.Modifier; import java.util.*; -import static org.springframework.context.annotation.FilterType.ASSIGNABLE_TYPE; - /** * {@link JCommander} spring boot configuration class. * {@link ComponentScan} searches for all implementations of the {@link JCConfiguration} class. @@ -35,77 +31,104 @@ */ @Configuration @ConditionalOnNotWebApplication -@ComponentScan( - basePackages = "**.buggy", - useDefaultFilters = false, - includeFilters = { - @ComponentScan.Filter(type = ASSIGNABLE_TYPE, classes = JCConfiguration.class), - @ComponentScan.Filter(type = ASSIGNABLE_TYPE, classes = Goal.class), - }) -public class SBJCommanderConfiguration implements SBConfiguration { - - private static final JCommander JC = new JCommander(); - private final List jcConfigurations; - private final List goals; +public class JCommanderConfiguration implements IConfiguration { + + private final JCommander jCommander; + private final Set jcConfigurations = new LinkedHashSet<>(); + private final ApplicationProperties properties; private final String[] args; - private Map, JCConfiguration> buggyConfigurations; + private final Map, JCConfiguration> buggyConfigurations = new HashMap<>(); - public SBJCommanderConfiguration(List list, List goals, ApplicationArguments args) { - this.goals = goals; - this.jcConfigurations = list; + public JCommanderConfiguration(final ApplicationProperties properties, final ApplicationArguments args) { + this.properties = properties; this.args = args.getSourceArgs(); - init(); + beforeConfiguration(); + this.jcConfigurations.addAll(scanBuggyConfig()); + scanJCConfigurations().stream() + .filter(i -> !(i instanceof BuggyConfig)) + .forEach(this.jcConfigurations::add); + this.jCommander = buildJCommander(); + parseArguments(); } - @Bean("initAndGetBuggyConfigurations") - public Map, JCConfiguration> getBuggyConfigurations() { - return buggyConfigurations; - } - - @Bean("isBuggyConfigured") - public boolean isBuggyConfigured() { - return buggyConfigurations.containsKey(BuggyConfig.class); + public void beforeConfiguration() { + ConfigurationLogger.blockDelimiter(); + ConfigurationLogger.centerBold("JCommander configuration construction"); + ConfigurationLogger.stepDelimiter(); } @PostConstruct public void postConstruct() { if (BuggyConfig.getHelp()) { - ConfigurationLogger.stepDelimeter(); - JC.usage(); - exitRun(0); + ConfigurationLogger.stepDelimiter(); + jCommander.usage(); + BuggyRunner.exit(0); + } + if (BuggyConfig.getVersion()) { + ConfigurationLogger.stepDelimiter(); + ConfigurationLogger.centerBold("Version info"); + JUtils.getBuggyManifest().forEach(ConfigurationLogger::dotPlaceholder); + BuggyRunner.exit(0); } printConfigurationsParams(buggyConfigurations); } - public void init() { - if (buggyConfigurations == null) { - ConfigurationLogger.blockDelimeter(); - ConfigurationLogger.centerBold("JCommander configuration construction"); - ConfigurationLogger.stepDelimeter(); - buggyConfigurations = new HashMap<>(); + private Set scanBuggyConfig() { + final boolean useDefaultFilters = false; + final String basePackage = "org.touchbit.buggy.core.config"; + final Set defs = scanBeanDefinitions(useDefaultFilters, basePackage, BuggyConfig.class); + return getBeanDefinitionInstances(defs, BuggyConfig.class); + } - for (JCConfiguration config : jcConfigurations) { - buggyConfigurations.put(config.getClass(), config); - checkConfiguration(config); + public Set scanJCConfigurations() { + final boolean useDefaultFilters = properties.isJCommanderScannerCommandsUseDefaultFilters(); + final String basePackage = properties.getJCommanderScannerCommandsBasePackage(); + final Set defs = scanBeanDefinitions(useDefaultFilters, basePackage, JCConfiguration.class); + return getBeanDefinitionInstances(defs, JCConfiguration.class); + } + + private JCommander buildJCommander() { + JCommander jCommander = new JCommander(); + for (JCConfiguration config : jcConfigurations) { + buggyConfigurations.put(config.getClass(), config); + checkConfiguration(config); + try { if (config.getClass().isAnnotationPresent(Parameters.class) && config.getClass().getAnnotation(Parameters.class).commandNames().length > 0) { - JC.addCommand(config); + jCommander.addCommand(config); } else { - JC.addObject(config); + jCommander.addObject(config); } ConfigurationLogger.dotPlaceholder(config.getClass().getSimpleName(), "OK"); - } - try { - JC.parse(args); - ConfigurationLogger.stepDelimeter(); - ConfigurationLogger.dotPlaceholder("Parsing arguments", "OK"); } catch (Exception e) { - ConfigurationLogger.stepDelimeter(); - ConfigurationLogger.dotPlaceholder("Parsing arguments", "FAIL"); - printConfigurationsParams(buggyConfigurations); - exitRunWithErr(e.getMessage(), e); + ConfigurationLogger.dotPlaceholder(config.getClass().getSimpleName(), "FAIL"); + BuggyRunner.exit(1, "Unexpected error while loading Jcommander configs", e); } } + return jCommander; + } + + public void parseArguments() { + try { + jCommander.parse(args); + ConfigurationLogger.stepDelimiter(); + ConfigurationLogger.dotPlaceholder("Parsing arguments", "OK"); + } catch (Exception e) { + ConfigurationLogger.stepDelimiter(); + ConfigurationLogger.dotPlaceholder("Parsing arguments", "FAIL"); + printConfigurationsParams(buggyConfigurations); + BuggyRunner.exit(e.getMessage(), e); + } + } + + @Bean("isBuggyConfigured") + public boolean isBuggyConfigured() { + return buggyConfigurations.containsKey(BuggyConfig.class); + } + + @Bean() + public Map, JCConfiguration> getBuggyConfigurations() { + return buggyConfigurations; } public void checkConfiguration(JCConfiguration config) { @@ -115,7 +138,7 @@ public void checkConfiguration(JCConfiguration config) { String[] names = parameter.names(); ConfigurationLogger.dotPlaceholder(config.getClass().getSimpleName(), "FAIL"); printConfigurationParams(config); - exitRunWithErr("Field " + config.getClass().getSimpleName() + "#" + field.getName() + + BuggyRunner.exit(1, "Field " + config.getClass().getSimpleName() + "#" + field.getName() + " marked with @Parameter " + Arrays.toString(names) + " must be static."); } } @@ -143,7 +166,7 @@ public void checkConfiguration(JCConfiguration config) { if (error != null) { ConfigurationLogger.dotPlaceholder(config.getClass().getSimpleName(), "FAIL"); printConfigurationParams(config); - exitRunWithErr(error); + BuggyRunner.exit(1, error); } } } @@ -159,7 +182,7 @@ public void printConfigurationsParams(Map, JCCo public void printConfigurationParams(JCConfiguration config) { Map params = config.configurationToMap(); if (params != null && !params.isEmpty()) { - ConfigurationLogger.stepDelimeter(); + ConfigurationLogger.stepDelimiter(); ConfigurationLogger.center(config.getClass().getSimpleName()); for (Map.Entry entry : params.entrySet()) { ConfigurationLogger.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..8c98918 --- /dev/null +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/LogbackConfiguration.java @@ -0,0 +1,53 @@ +package org.touchbit.buggy.spring.boot.starter.conf; + +import ch.qos.logback.core.util.StatusPrinter; +import org.springframework.boot.autoconfigure.condition.ConditionalOnNotWebApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.touchbit.buggy.core.utils.log.BuggyLoggers; +import org.touchbit.buggy.core.utils.log.ConfigurationLogger; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; + +/** + * 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 isBuggyLoggerInitialized; + + public LogbackConfiguration() { + ConfigurationLogger.blockDelimiter(); + ConfigurationLogger.centerBold("Logback configuration (" + BuggyLoggers.LOGGING_CONFIG_FILE + ")"); + ConfigurationLogger.stepDelimiter(); + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + PrintStream printStream = new PrintStream(stream); + StatusPrinter.setPrintStream(printStream); + StatusPrinter.printInCaseOfErrorsOrWarnings(BuggyLoggers.LOGGER_CONTEXT); + BuggyLoggers.F_LOG.info(stream.toString()); + for (ch.qos.logback.classic.Logger logger : BuggyLoggers.LOGGER_CONTEXT.getLoggerList()) { + if (logger.getLevel() != null) { + String name = logger.getName(); + try { + Class c = this.getClass().getClassLoader().loadClass(name); + name = c.getSimpleName() + ".class"; + } catch (ClassNotFoundException ignore) { + } + ConfigurationLogger.dotPlaceholder(name, logger.getLevel()); + } + } + isBuggyLoggerInitialized = true; + } + + @Bean() + public boolean isBuggyLoggerInitialized() { + return isBuggyLoggerInitialized; + } + +} diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBConfiguration.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBConfiguration.java deleted file mode 100644 index 3ac3309..0000000 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBConfiguration.java +++ /dev/null @@ -1,59 +0,0 @@ -package org.touchbit.buggy.spring.boot.starter.conf; - -import ch.qos.logback.classic.Logger; -import ch.qos.logback.classic.LoggerContext; -import ch.qos.logback.classic.spi.ILoggingEvent; -import ch.qos.logback.core.Appender; -import ch.qos.logback.core.FileAppender; -import org.slf4j.LoggerFactory; -import org.slf4j.MDC; -import org.touchbit.buggy.spring.boot.starter.log.ConfigurationLogger; - -import java.util.Iterator; - -/** - * Interface for Buggy spring boot configurations - *

- * Created by Oleg Shaburov on 01.10.2020 - * shaburov.o.a@gmail.com - */ -public interface SBConfiguration { - - default void exitRunWithErr(String message) { - exitRunWithErr(message, null); - } - - default void exitRunWithErr(String message, Exception e) { - exitRun(1, message, e); - } - - default void exitRun(int status) { - exitRun(status, null, null); - } - - default void exitRun(int status, String message, Exception e) { - if (message != null) { - ConfigurationLogger.blockDelimeter(); - String frameworkLogPath = ""; - if (status == 0) { - ConfigurationLogger.print(message); - } else { - if (SBLogbackConfiguration.framework() == null) { - MDC.put("print.console.stacktrace", "true"); - } else { - String frameworkLogFilePath = SBLogbackConfiguration.getFrameworkLogFilePath(); - if (frameworkLogFilePath != null && !frameworkLogFilePath.isEmpty()) { - frameworkLogPath = "\nFor more information see " + frameworkLogFilePath; - } - } - String eMsg = "\n" + e.getClass().getSimpleName() + ": " + e.getMessage(); - ConfigurationLogger.errPrint(message + eMsg + frameworkLogPath, e); - } - } - ConfigurationLogger.blockDelimeter(); - ConfigurationLogger.dotPlaceholder("Exit code", status); - ConfigurationLogger.blockDelimeter(); - System.exit(status); - } - -} diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBLogbackConfiguration.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBLogbackConfiguration.java deleted file mode 100644 index 1556709..0000000 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBLogbackConfiguration.java +++ /dev/null @@ -1,170 +0,0 @@ -package org.touchbit.buggy.spring.boot.starter.conf; - -import ch.qos.logback.classic.LoggerContext; -import ch.qos.logback.classic.joran.JoranConfigurator; -import ch.qos.logback.classic.spi.ILoggingEvent; -import ch.qos.logback.core.Appender; -import ch.qos.logback.core.FileAppender; -import ch.qos.logback.core.joran.spi.JoranException; -import ch.qos.logback.core.util.Loader; -import ch.qos.logback.core.util.StatusPrinter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnNotWebApplication; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.DependsOn; -import org.springframework.core.env.Environment; -import org.touchbit.buggy.spring.boot.starter.log.ConfigurationLogger; - -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; -import java.net.URL; -import java.util.Iterator; - -/** - * Logback loggers configuration - *

- * Created by Oleg Shaburov on 30.09.2020 - * shaburov.o.a@gmail.com - */ -@Configuration() -@ConditionalOnNotWebApplication -@DependsOn({"initAndGetBuggyConfigurations", "isBuggyConfigured"}) -public class SBLogbackConfiguration implements SBConfiguration { - - public static final String LOG_FILE_NAME = "log.file.name"; - public static final String LOG_DIRECTORY = "log.directory"; - protected static final String LOGBACK_XML = "logback.xml"; - protected static final String BUGGY_LOGBACK_XML = "buggy-logback.xml"; - protected static final String DEFAULT_LOGGING_CONFIG_VALUE = "classpath:" + BUGGY_LOGBACK_XML; - private static Logger console; - private static Logger framework; - private static Logger test; - private final boolean isBuggyLoggerInitialized; - private final String loggingConfigFile; - private final LoggerContext context; - - public SBLogbackConfiguration(Environment env) { - loggingConfigFile = env.getProperty("logging.config"); - ConfigurationLogger.blockDelimeter(); - ConfigurationLogger.centerBold("Loading logback configuration"); - ConfigurationLogger.stepDelimeter(); - URL logbackXml = getResource(LOGBACK_XML, this.getClass()); - URL buggyLogbackXml = getResource("buggy-logback.xml", this.getClass()); - LoggerContext tmpContext = null; - if (logbackXml != null) { - ConfigurationLogger.fPrint(LOGBACK_XML, ".", "OK"); - tmpContext = reloadLogger(logbackXml); - } else { - ConfigurationLogger.fPrint(LOGBACK_XML, ".", "FAIL"); - } - if (logbackXml == null && buggyLogbackXml != null) { - ConfigurationLogger.fPrint(BUGGY_LOGBACK_XML, ".", "OK"); - tmpContext = reloadLogger(buggyLogbackXml); - } else { - ConfigurationLogger.fPrint(BUGGY_LOGBACK_XML, ".", "FAIL"); - exitRunWithErr("Logback configuration not found"); - } - context = tmpContext; - if (context != null) { - setTestLog(LoggerFactory.getLogger("Routing")); - setConsoleLog(LoggerFactory.getLogger("Console")); - setFrameworkLog(LoggerFactory.getLogger("Framework")); - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - PrintStream printStream = new PrintStream(stream); - StatusPrinter.setPrintStream(printStream); - StatusPrinter.printInCaseOfErrorsOrWarnings(context); - framework.info(stream.toString()); - for (ch.qos.logback.classic.Logger logger : context.getLoggerList()) { - if (logger.getLevel() != null) { - String name = logger.getName(); - try { - Class c = this.getClass().getClassLoader().loadClass(name); - name = c.getSimpleName() + ".class"; - } catch (ClassNotFoundException ignore) { - } - console.info(ConfigurationLogger.filler(name, ".", logger.getLevel())); - } - } - } else { - exitRunWithErr("Unable to load Logback configuration."); - } - isBuggyLoggerInitialized = true; - } - - @Bean() -// @ConditionalOnMissingBean - public boolean isBuggyLoggerInitialized() { - return isBuggyLoggerInitialized; - } - - public LoggerContext getContext() { - return context; - } - - public static Logger console() { - return console; - } - - public static Logger test() { - return test; - } - - public static Logger framework() { - return framework; - } - - public LoggerContext reloadLogger(URL config) { - ConfigurationLogger.stepDelimeter(); - LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); - // Already loaded. Return current context. - if (DEFAULT_LOGGING_CONFIG_VALUE.equals(loggingConfigFile)) { - return loggerContext; - } - try { - JoranConfigurator configurator = new JoranConfigurator(); - configurator.setContext(loggerContext); - loggerContext.reset(); - configurator.doConfigure(config); - } catch (JoranException ignore) { - } - return loggerContext; - } - - public URL getResource(String filename, Class c) { - try { - ClassLoader myClassLoader = Loader.getClassLoaderOfObject(c); - return Loader.getResource(filename, myClassLoader); - } catch (Exception ignore) { - return null; - } - } - - public void setConsoleLog(Logger console) { - SBLogbackConfiguration.console = console; - } - - public void setFrameworkLog(Logger framework) { - SBLogbackConfiguration.framework = framework; - } - - public void setTestLog(Logger test) { - SBLogbackConfiguration.test = test; - } - - public static String getFrameworkLogFilePath() { - LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); - for (ch.qos.logback.classic.Logger logger : context.getLoggerList()) { - for (Iterator> index = logger.iteratorForAppenders(); index.hasNext();) { - Appender appender = index.next(); - if (appender instanceof FileAppender && appender.getName().equalsIgnoreCase("Framework")) { - FileAppender fileAppender = (FileAppender) appender; - return fileAppender.getFile(); - } - } - } - return null; - } -} diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBTestNGConfiguration.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBTestNGConfiguration.java deleted file mode 100644 index 49acc43..0000000 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/SBTestNGConfiguration.java +++ /dev/null @@ -1,130 +0,0 @@ -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.cglib.beans.BeanGenerator; -import org.springframework.context.annotation.*; -import org.springframework.core.type.filter.AnnotationTypeFilter; -import org.springframework.core.type.filter.AssignableTypeFilter; -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.testng.listeners.BuggyListener; -import org.touchbit.buggy.spring.boot.starter.log.ConfigurationLogger; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Constructor; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - -import static java.lang.reflect.Modifier.*; - -/** - * TestNG configuration - * Filter 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 -@DependsOn({"initAndGetBuggyConfigurations"}) -public class SBTestNGConfiguration implements SBConfiguration { - - private final ApplicationProperties properties; - - private final List listenerList; - private final List enabledBuggyListeners = new ArrayList<>(); - private final List> testClasses; - - public SBTestNGConfiguration(final boolean isBuggyLoggerInitialized, final ApplicationProperties properties) { - this.properties = properties; - if (!isBuggyLoggerInitialized) { - exitRunWithErr("Logger must be initialized"); - } - ConfigurationLogger.blockDelimeter(); - ConfigurationLogger.centerBold("Loading TestNG configuration"); - this.testClasses = getTestClassesWithSuiteAnnotation(); - this.listenerList = getTestNGListeners(); - for (BuggyListener buggyListener : this.listenerList) { - if (buggyListener.isEnable()) { - enabledBuggyListeners.add(buggyListener); - ConfigurationLogger.dotPlaceholder(buggyListener.getClass().getSimpleName(), "Enable"); - } else { - ConfigurationLogger.dotPlaceholder(buggyListener.getClass().getSimpleName(), "Disable"); - } - } - } - - @Bean("getTestClasses") - public List> getTestClasses() { - return testClasses; - } - - @Bean("getBuggyListeners") - public List getBuggyListeners() { - return listenerList; - } - - @Bean("getEnabledBuggyListeners") - public List getEnabledBuggyListeners() { - return enabledBuggyListeners; - } - - public List> getTestClassesWithSuiteAnnotation() { - List> resultList = new ArrayList<>(); - boolean useDefaultFilters = properties.isTestNGScannerSuiteUseDefaultFilters(); - String basePackage = properties.getTestNGScannerSuiteBasePackage(); - Set definitions = scanBeanDefinitions(useDefaultFilters, basePackage, Suite.class); - for (BeanDefinition bd : definitions) { - try { - Class testClass = Thread.currentThread().getContextClassLoader().loadClass(bd.getBeanClassName()); - int mods = testClass.getModifiers(); - if (isPublic(mods) && !isAbstract(mods) && !isInterface(mods)) { - resultList.add(testClass); - } - } catch (ClassNotFoundException e) { - exitRunWithErr("Failed to load @Suite-annotated class.", e); - } - } - return resultList; - } - - public List getTestNGListeners() { - List result = new ArrayList<>(); - boolean useDefaultFilters = properties.isTestNGScannerListenerUseDefaultFilters(); - String basePackage = properties.getTestNGScannerListenerBasePackage(); - ConfigurationLogger.stepDelimeter(); - ConfigurationLogger.center("TestNG listeners"); - Set definitions = scanBeanDefinitions(useDefaultFilters, basePackage, BuggyListener.class); - for (BeanDefinition bd : definitions) { - try { - Class c = BeanGenerator.class.getClassLoader().loadClass(bd.getBeanClassName()); - Constructor con = c.getConstructor(); - BuggyListener instance = (BuggyListener) con.newInstance(); - result.add(instance); - } catch (Exception e) { - exitRunWithErr("Failed to load inheritor of class BuggyListener.", e); - } - } - return result; - } - - public 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)); - } - return scanner.findCandidateComponents(basePackage); - } - -} diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/TestNGConfiguration.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/TestNGConfiguration.java new file mode 100644 index 0000000..00cbfea --- /dev/null +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/TestNGConfiguration.java @@ -0,0 +1,86 @@ +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.context.annotation.*; +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.testng.listeners.BuggyListener; +import org.touchbit.buggy.spring.boot.starter.BuggyRunner; +import org.touchbit.buggy.core.utils.log.ConfigurationLogger; + +import java.util.LinkedHashSet; +import java.util.Set; + +/** + * TestNG configuration + * Filter 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 +public class TestNGConfiguration implements IConfiguration { + + private final ApplicationProperties properties; + private final Set buggyListeners; + private final Set enabledBuggyListeners = new LinkedHashSet<>(); + private final Set> testClasses; + + public TestNGConfiguration(final boolean isBuggyLoggerInitialized, final ApplicationProperties properties) { + this.properties = properties; + if (!isBuggyLoggerInitialized) { + BuggyRunner.exit(1, "Logger must be initialized"); + } + ConfigurationLogger.blockDelimiter(); + ConfigurationLogger.centerBold("Loading TestNG configuration"); + ConfigurationLogger.stepDelimiter(); + ConfigurationLogger.center("TestNG listeners"); + this.buggyListeners = getTestNGListeners(); + for (BuggyListener buggyListener : this.buggyListeners) { + if (buggyListener.isEnable()) { + enabledBuggyListeners.add(buggyListener); + ConfigurationLogger.dotPlaceholder(buggyListener.getClass().getSimpleName(), "Enable"); + } else { + ConfigurationLogger.dotPlaceholder(buggyListener.getClass().getSimpleName(), "Disable"); + } + } + this.testClasses = getTestClassesWithSuiteAnnotation(); + } + + @Bean("getTestClasses") + public Set> getTestClasses() { + return testClasses; + } + + @Bean("getBuggyListeners") + public Set getBuggyListeners() { + return buggyListeners; + } + + @Bean("getEnabledBuggyListeners") + public Set getEnabledBuggyListeners() { + return enabledBuggyListeners; + } + + public Set> getTestClassesWithSuiteAnnotation() { + final boolean useDefaultFilters = properties.isTestNGScannerSuiteUseDefaultFilters(); + final String basePackage = properties.getTestNGScannerSuiteBasePackage(); + final Set definitions = scanBeanDefinitions(useDefaultFilters, basePackage, Suite.class); + return getBeanDefinitionAnnotatedClasses(definitions, Suite.class); + } + + public Set getTestNGListeners() { + final boolean useDefaultFilters = properties.isTestNGScannerListenerUseDefaultFilters(); + final String basePackage = properties.getTestNGScannerListenerBasePackage(); + final Set defs = scanBeanDefinitions(useDefaultFilters, basePackage, BuggyListener.class); + return getBeanDefinitionInstances(defs, BuggyListener.class); + } + +} diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/log/ConfigurationLogger.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/log/ConfigurationLogger.java deleted file mode 100644 index 7e29378..0000000 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/log/ConfigurationLogger.java +++ /dev/null @@ -1,144 +0,0 @@ -package org.touchbit.buggy.spring.boot.starter.log; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.StringJoiner; - -import static java.util.Objects.isNull; -import static org.touchbit.buggy.spring.boot.starter.log.ANSI.BOLD; -import static org.touchbit.buggy.spring.boot.starter.log.ANSI.RED; - -/** - * Utility class for logging configuration events in TestNG format - *

- * Created by Oleg Shaburov on 01.10.2020 - * shaburov.o.a@gmail.com - */ -public class ConfigurationLogger { - - public static final int STRING_LEN = 47; - public static final String BLOCK = "="; - public static final String STEP = "\u2014"; - public static final String DOT = "."; - - private static final Logger CONSOLE = LoggerFactory.getLogger(ConfigurationLogger.class); - - private ConfigurationLogger() { - throw new IllegalStateException("Utility class. Prohibit instantiation."); - } - - 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) { - return dotFiller(prefix, STRING_LEN, null); - } - - public static String dotFiller(Object prefix, int i, Object suffix) { - return filler(prefix, DOT, i, suffix); - } - - public static String dotFiller(Object prefix, Object suffix) { - return filler(prefix, ".", STRING_LEN, suffix); - } - - public static String filler(Object prefix, String symbol, int i) { - return filler(prefix, symbol, i, null); - } - - public static String filler(String symbol) { - return filler(null, symbol, STRING_LEN, null); - } - - public static String filler(Object prefix, String symbol) { - return filler(prefix, symbol, STRING_LEN, null); - } - - public static String filler(Object prefix, String symbol, Object postfix) { - return filler(prefix, symbol, 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 stepDelimeter() { - print(filler(STEP)); - } - - public static void blockDelimeter() { - print(filler(BLOCK)); - } - - public static void dotPlaceholder(Object prefix, Object postfix) { - print(filler(prefix, DOT, postfix)); - } - - public static void fPrint(Object prefix, String symbol, Object postfix) { - print(filler(prefix, symbol, postfix)); - } - - public static void centerBold(String msg) { - print(BOLD.wrap(centerMsg(msg))); - } - - public static void center(String msg) { - print(centerMsg(msg)); - } - - private static String centerMsg(String msg) { - if (msg != null && !msg.isEmpty()) { - int diff = STRING_LEN - msg.length(); - if (diff > 0) { - int indent = diff / 2; - return filler("", " ", indent, "") + msg; - } - } - return msg; - } - - public static void print(String msg) { - CONSOLE.info(msg); - } - - public static void errPrint(String msg, Throwable t) { - CONSOLE.error(RED.wrap(msg), t); - } - - public static void errPrint(String msg) { - CONSOLE.error(RED.wrap(msg)); - } - - public static Logger getLogger() { - return CONSOLE; - } - -} diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/utils/JUtils.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/utils/JUtils.java deleted file mode 100644 index c466ec1..0000000 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/utils/JUtils.java +++ /dev/null @@ -1,80 +0,0 @@ -package org.touchbit.buggy.spring.boot.starter.utils; - -import org.springframework.util.ClassUtils; - -import java.lang.management.ManagementFactory; -import java.lang.management.RuntimeMXBean; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Set; - -/** - * 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 boolean isJetBrainsIdeRun() { - RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean(); - List arguments = runtimeMxBean.getInputArguments(); - return arguments.stream() - .anyMatch(v -> v.startsWith("-javaagent") && - (v.contains("JetBrains") || v.contains("IDEA") || v.contains("idea"))); - } - - public static String getRunPath() { - String runDir = System.getProperty("user.dir"); - if (isJetBrainsIdeRun()) { - String javaClassPath = System.getProperty("java.class.path"); - if (javaClassPath != null && !javaClassPath.isEmpty()) { - String firstClassPath = javaClassPath.split(":")[0]; - if (firstClassPath.contains("/target/") && firstClassPath.contains(runDir)) { - return firstClassPath.substring(0, firstClassPath.indexOf("/target/")) + "/target"; - } - } - } - return runDir; - } - - public static List getFields(Object o) { - if (o != null) { - return getFields(o.getClass()); - } - return new ArrayList<>(); - } - - public static List getFields(Class c) { - Set> interfaces = ClassUtils.getAllInterfacesAsSet(c); - 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) { - Set> interfaces = ClassUtils.getAllInterfacesAsSet(c); - 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; - } - -} diff --git a/buggy-spring-boot-starter/src/main/resources/META-INF/spring.factories b/buggy-spring-boot-starter/src/main/resources/META-INF/spring.factories deleted file mode 100644 index e69de29..0000000 diff --git a/buggy-spring-boot-starter/src/main/resources/application.yml b/buggy-spring-boot-starter/src/main/resources/application.yml index e52d680..697cd1c 100644 --- a/buggy-spring-boot-starter/src/main/resources/application.yml +++ b/buggy-spring-boot-starter/src/main/resources/application.yml @@ -1,15 +1,23 @@ logging: config: 'classpath:buggy-logback.xml' + file: + path: ./logs spring: main: allow-bean-definition-overriding: true buggy: - configuration: - testng: - scanner: - suite: - basePackage: "**.buggy" - useDefaultFilters: false - listener: - basePackage: "**.buggy" - useDefaultFilters: false \ No newline at end of file + spring: + configuration: + jcommander: + scanner: + commands: + basePackage: "**.buggy" + useDefaultFilters: false + testng: + scanner: + suite: + basePackage: "**.buggy" + useDefaultFilters: false + listener: + basePackage: "**.buggy" + useDefaultFilters: false \ No newline at end of file diff --git a/buggy-spring-boot-starter/src/main/resources/buggy-logback.xml b/buggy-spring-boot-starter/src/main/resources/buggy-logback.xml index 3e06cd5..c8201fe 100644 --- a/buggy-spring-boot-starter/src/main/resources/buggy-logback.xml +++ b/buggy-spring-boot-starter/src/main/resources/buggy-logback.xml @@ -1,27 +1,35 @@ - - - + - + - - ${log.path}/Framework.log + ${logging.file.path}/Framework.log - + - + + + sifting.log.file.path + default-sifting.log + + + + ${logging.file.path}/${sifting.log.file.path} + + + + - ${log.path}/TestSupervisor.log + ${logging.file.path}/TestSupervisor.log ${base.log.pattern} @@ -34,18 +42,13 @@ - - - + + - + - - - - - + - \ No newline at end of file + diff --git a/pom.xml b/pom.xml index d69076a..71d22d1 100644 --- a/pom.xml +++ b/pom.xml @@ -217,6 +217,11 @@ ${feign.version} + + ch.qos.logback + logback-classic + 1.2.3 + org.apache.logging.log4j log4j-slf4j-impl From 44787499b1f83e8dbb3f158676412e206a77e899 Mon Sep 17 00:00:00 2001 From: "oleg.shaburov" Date: Sun, 4 Oct 2020 22:31:23 +0300 Subject: [PATCH 09/24] TestNGConfiguration: collect goals --- .../org/touchbit/buggy/core/goal/Goal.java | 10 ++- .../core/goal/component/AllComponents.java | 5 ++ .../buggy/core/goal/component/Component.java | 2 - .../core/goal/component/DefaultComponent.java | 2 +- .../core/goal/interfaze/AllInterfaces.java | 5 ++ .../buggy/core/goal/service/AllServices.java | 6 ++ .../org/touchbit/buggy/core/utils/JUtils.java | 19 +++++ .../starter/example/ExampleBuggyRunner.java | 1 - .../starter/conf/TestNGConfiguration.java | 75 +++++++++++++++++++ 9 files changed, 120 insertions(+), 5 deletions(-) diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/goal/Goal.java b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/Goal.java index ba80432..32c13d4 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/goal/Goal.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/Goal.java @@ -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-core/src/main/java/org/touchbit/buggy/core/goal/component/AllComponents.java b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/component/AllComponents.java index 88e0bd0..3ea19ac 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/goal/component/AllComponents.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/component/AllComponents.java @@ -32,4 +32,9 @@ public String getDescription() { return "All components"; } + @Override + public boolean isActive() { + return false; + } + } diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/goal/component/Component.java b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/component/Component.java index f2d7cfe..f091cac 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/goal/component/Component.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/component/Component.java @@ -28,8 +28,6 @@ @IndexSubclasses public abstract class Component implements Goal { - public abstract String getDescription(); - public String getName() { return this.getClass().getSimpleName().toUpperCase(); } diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/goal/component/DefaultComponent.java b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/component/DefaultComponent.java index 85e8cbc..f4bd8a5 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/goal/component/DefaultComponent.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/component/DefaultComponent.java @@ -29,7 +29,7 @@ public String getName() { @Override public String getDescription() { - return "Default component for test suites"; + return "Default component"; } } 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 index cb012ae..1eaccbc 100644 --- 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 @@ -12,4 +12,9 @@ public String getDescription() { return "All interfaces"; } + @Override + public boolean isActive() { + return false; + } + } 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 index 5cd4f34..cf8da19 100644 --- 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 @@ -11,4 +11,10 @@ public String getName() { public String getDescription() { return "All services"; } + + @Override + public boolean isActive() { + return false; + } + } 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 index ac8307c..cfe2d0b 100644 --- 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 @@ -151,4 +151,23 @@ public static Manifest readManifest(InputStream inputStream) { } } + 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-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 index e858e3d..a78cbfa 100644 --- 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 @@ -8,7 +8,6 @@ public class ExampleBuggyRunner extends BuggyRunner { static { BuggyConfig.setForce(true); - BuggyConfig.setVersion(true); } public static void main(String[] args) { diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/TestNGConfiguration.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/TestNGConfiguration.java index 00cbfea..fe8d131 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/TestNGConfiguration.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/TestNGConfiguration.java @@ -3,16 +3,24 @@ import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.boot.autoconfigure.condition.ConditionalOnNotWebApplication; import org.springframework.context.annotation.*; +import org.touchbit.buggy.core.config.BuggyConfig; +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.model.Suite; import org.touchbit.buggy.core.testng.listeners.BuggyListener; +import org.touchbit.buggy.core.utils.JUtils; import org.touchbit.buggy.spring.boot.starter.BuggyRunner; import org.touchbit.buggy.core.utils.log.ConfigurationLogger; import java.util.LinkedHashSet; +import java.util.List; import java.util.Set; +import java.util.stream.Collectors; /** * TestNG configuration @@ -32,6 +40,10 @@ public class TestNGConfiguration implements IConfiguration { private final Set buggyListeners; private final Set enabledBuggyListeners = new LinkedHashSet<>(); private final Set> testClasses; + private final Set goals; + private final Set enabledComponents; + private final Set enabledServices; + private final Set enabledInterfaces; public TestNGConfiguration(final boolean isBuggyLoggerInitialized, final ApplicationProperties properties) { this.properties = properties; @@ -52,6 +64,62 @@ public TestNGConfiguration(final boolean isBuggyLoggerInitialized, final Applica } } this.testClasses = getTestClassesWithSuiteAnnotation(); + this.goals = getGoals(); + ConfigurationLogger.stepDelimiter(); + ConfigurationLogger.center("Enabled suites goals"); + ConfigurationLogger.stepDelimiter(); + ConfigurationLogger.center("Components"); + this.enabledComponents = filter(this.goals, BuggyConfig.getComponents(), Component.class, AllComponents.class); + this.enabledComponents.forEach(g -> ConfigurationLogger.dotPlaceholder(JUtils.getSimpleNameC(g), g.getName())); + ConfigurationLogger.stepDelimiter(); + ConfigurationLogger.center("Services"); + this.enabledServices = filter(this.goals, BuggyConfig.getComponents(), Service.class, AllServices.class); + this.enabledServices.forEach(g -> ConfigurationLogger.dotPlaceholder(JUtils.getSimpleNameC(g), g.getName())); + ConfigurationLogger.stepDelimiter(); + ConfigurationLogger.center("Interfaces"); + this.enabledInterfaces = filter(this.goals, BuggyConfig.getComponents(), Interface.class, AllInterfaces.class); + this.enabledInterfaces.forEach(g -> ConfigurationLogger.dotPlaceholder(JUtils.getSimpleNameC(g), g.getName())); + } + + @SuppressWarnings("unchecked") + public Set filter(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()); + } + } + + @Bean("getEnabledComponents") + public Set getEnabledComponents() { + return enabledComponents; + } + + @Bean("getEnabledServices") + public Set getEnabledServices() { + return enabledServices; + } + + @Bean("getEnabledInterfaces") + public Set getEnabledInterfaces() { + return enabledInterfaces; + } + + @Bean("getAllGoals") + public Set getAllGoals() { + return goals; } @Bean("getTestClasses") @@ -69,6 +137,13 @@ public Set getEnabledBuggyListeners() { return enabledBuggyListeners; } + public Set getGoals() { + final boolean useDefaultFilters = properties.isTestNGScannerListenerUseDefaultFilters(); + final String basePackage = properties.getTestNGScannerListenerBasePackage(); + final Set defs = scanBeanDefinitions(useDefaultFilters, basePackage, Goal.class); + return getBeanDefinitionInstances(defs, Goal.class); + } + public Set> getTestClassesWithSuiteAnnotation() { final boolean useDefaultFilters = properties.isTestNGScannerSuiteUseDefaultFilters(); final String basePackage = properties.getTestNGScannerSuiteBasePackage(); From 73ddb55057b80b0ccd8bf14d510716d5284d3c82 Mon Sep 17 00:00:00 2001 From: "oleg.shaburov" Date: Sun, 4 Oct 2020 23:31:07 +0300 Subject: [PATCH 10/24] TestNGConfiguration add filters by Buggy conf --- .../buggy/core/config/BuggyConfig.java | 63 ++++-- .../org/touchbit/buggy/core/model/Suite.java | 1 + .../starter/example/ExampleBuggyRunner.java | 2 + .../boot/starter/example/ExampleTests2.java | 8 + .../spring/boot/starter/BuggyRunner.java | 46 ++++- .../starter/conf/ApplicationProperties.java | 97 +++------ .../starter/conf/JCommanderConfiguration.java | 20 +- .../starter/conf/LogbackConfiguration.java | 15 +- .../starter/conf/TestNGConfiguration.java | 186 +++++++++++++----- .../src/main/resources/application.yml | 26 +-- 10 files changed, 301 insertions(+), 163 deletions(-) create mode 100644 buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleTests2.java diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/config/BuggyConfig.java b/buggy-core/src/main/java/org/touchbit/buggy/core/config/BuggyConfig.java index 8040efb..6cf5587 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/config/BuggyConfig.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/config/BuggyConfig.java @@ -164,15 +164,9 @@ public static void setTypes(List types) { } } - public static void addTypes(List types) { - if (types != null && !types.isEmpty()) { - BuggyConfig.types.addAll(types); - } - } - - public static void addTypes(Type... types) { + public static void setTypes(Type... types) { if (types != null) { - addTypes(Arrays.asList(types)); + setTypes(Arrays.asList(types)); } } @@ -186,15 +180,24 @@ public static void setServices(List services) { } } - public static void addServices(List services) { + @SafeVarargs + public static void setServices(S... services) { if (services != null) { - BuggyConfig.services.addAll(services); + setServices(Arrays.asList(services)); } } - public static void addServices(Service... services) { - if (services != null) { - addServices(Arrays.asList(services)); + @SafeVarargs + public static void setServices(Class... services) { + if (interfaces != null) { + BuggyConfig.services = new ArrayList<>(); + for (Class service : services) { + try { + BuggyConfig.services.add(service.getDeclaredConstructor().newInstance()); + } catch (Exception e) { + e.printStackTrace(); + } + } } } @@ -208,15 +211,24 @@ public static void setInterfaces(List interfaces) { } } - public static void addInterfaces(List interfaces) { + @SafeVarargs + public static void setInterfaces(I... interfaces) { if (interfaces != null) { - BuggyConfig.interfaces.addAll(interfaces); + setInterfaces(Arrays.asList(interfaces)); } } - public static void addInterfaces(Interface... interfaces) { + @SafeVarargs + public static void setInterfaces(Class... interfaces) { if (interfaces != null) { - addInterfaces(Arrays.asList(interfaces)); + BuggyConfig.interfaces = new ArrayList<>(); + for (Class anInterface : interfaces) { + try { + BuggyConfig.interfaces.add(anInterface.getDeclaredConstructor().newInstance()); + } catch (Exception e) { + e.printStackTrace(); + } + } } } @@ -230,15 +242,24 @@ public static void setComponents(List components) { } } - public static void addComponents(List components) { + @SafeVarargs + public static void setComponents(C... components) { if (components != null) { - BuggyConfig.components.addAll(components); + setComponents(Arrays.asList(components)); } } - public static void addComponents(Component... components) { + @SafeVarargs + public static void setComponents(Class... components) { if (components != null) { - addComponents(Arrays.asList(components)); + BuggyConfig.components = new ArrayList<>(); + for (Class component : components) { + try { + BuggyConfig.components.add(component.getDeclaredConstructor().newInstance()); + } catch (Exception e) { + e.printStackTrace(); + } + } } } 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 725ce48..ea1895b 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 @@ -17,6 +17,7 @@ package org.touchbit.buggy.core.model; import org.atteo.classindex.IndexAnnotated; +import org.touchbit.buggy.core.goal.Goal; import org.touchbit.buggy.core.goal.component.Component; import org.touchbit.buggy.core.goal.component.AllComponents; import org.touchbit.buggy.core.goal.component.DefaultComponent; 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 index a78cbfa..3ddbb66 100644 --- 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 @@ -1,6 +1,7 @@ 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.core.config.BuggyConfig; @@ -8,6 +9,7 @@ public class ExampleBuggyRunner extends BuggyRunner { static { BuggyConfig.setForce(true); + BuggyConfig.setInterfaces(API.class); } public static void main(String[] args) { diff --git a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleTests2.java b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleTests2.java new file mode 100644 index 0000000..86694e1 --- /dev/null +++ b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleTests2.java @@ -0,0 +1,8 @@ +package org.touchbit.buggy.spring.boot.starter.example; + +import org.touchbit.buggy.core.goal.interfaze.API; +import org.touchbit.buggy.core.model.Suite; + +@Suite(interfaze = API.class) +public class ExampleTests2 { +} 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 index 1e8cade..a99dc53 100644 --- 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 @@ -1,22 +1,66 @@ package org.touchbit.buggy.spring.boot.starter; import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.autoconfigure.SpringBootApplication; +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.testng.listeners.BuggyListener; import org.touchbit.buggy.core.utils.log.ConfigurationLogger; import org.touchbit.buggy.core.utils.log.BuggyLoggers; +import java.util.LinkedHashSet; +import java.util.Set; + @SpringBootApplication public class BuggyRunner implements ApplicationRunner { + private Set enabledBuggyListeners; + private Set> testClasses; + private Set enabledComponents; + private Set enabledServices; + private Set enabledInterfaces; + @Override public void run(ApplicationArguments args) { ConfigurationLogger.blockDelimiter(); - System.out.println("Hello World from Buggy Runner"); + ConfigurationLogger.info(" >>>>> " + enabledBuggyListeners); + ConfigurationLogger.info(" >>>>> " + testClasses); + ConfigurationLogger.info(" >>>>> " + enabledComponents); + ConfigurationLogger.info(" >>>>> " + enabledServices); + ConfigurationLogger.info(" >>>>> " + enabledInterfaces); exit(0); } + @Autowired + public void setEnabledBuggyListeners(Set enabledBuggyListeners) { + this.enabledBuggyListeners = enabledBuggyListeners; + } + + @Autowired + public void setTestClasses(Set> testClasses) { + this.testClasses = testClasses; + } + + @Autowired + public void setEnabledComponents(Set enabledComponents) { + this.enabledComponents = enabledComponents; + } + + @Autowired + public void setEnabledServices(Set enabledServices) { + this.enabledServices = enabledServices; + } + + @Autowired + public void setEnabledInterfaces(Set enabledInterfaces) { + this.enabledInterfaces = enabledInterfaces; + } + public static void exit(String message, Exception e) { if (e != null) { exit(1, message, e); 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 index 2fd0947..3a22986 100644 --- 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 @@ -1,89 +1,56 @@ package org.touchbit.buggy.spring.boot.starter.conf; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; -import org.springframework.core.io.ClassPathResource; +import org.springframework.boot.context.properties.ConfigurationProperties; -@Configuration -public class ApplicationProperties { - - @Value("${buggy.spring.configuration.testng.scanner.suite.basePackage:**.buggy}") - private String testNGScannerSuiteBasePackage; - - @Value("${buggy.spring.configuration.testng.scanner.suite.useDefaultFilters:false}") - private boolean testNGScannerSuiteUseDefaultFilters; - - @Value("${buggy.spring.configuration.testng.scanner.listener.basePackage:**.buggy}") - private String testNGScannerListenerBasePackage; +import java.util.ArrayList; +import java.util.List; - @Value("${buggy.spring.configuration.testng.scanner.listener.useDefaultFilters:false}") - private boolean testNGScannerListenerUseDefaultFilters; - - @Value("${buggy.spring.configuration.jcommander.scanner.commands.basePackage:**.buggy}") - private String jCommanderScannerCommandsBasePackage; - - @Value("${buggy.spring.configuration.jcommander.scanner.commands.useDefaultFilters:false}") - private boolean jCommanderScannerCommandsUseDefaultFilters; - - public String getJCommanderScannerCommandsBasePackage() { - return jCommanderScannerCommandsBasePackage; - } - - public void setJCommanderScannerCommandsBasePackage(String jCommanderScannerCommandsBasePackage) { - this.jCommanderScannerCommandsBasePackage = jCommanderScannerCommandsBasePackage; - } - - public boolean isJCommanderScannerCommandsUseDefaultFilters() { - return jCommanderScannerCommandsUseDefaultFilters; - } - - public void setJCommanderScannerCommandsUseDefaultFilters(boolean jCommanderScannerCommandsUseDefaultFilters) { - this.jCommanderScannerCommandsUseDefaultFilters = jCommanderScannerCommandsUseDefaultFilters; - } +@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 String getTestNGScannerSuiteBasePackage() { - return testNGScannerSuiteBasePackage; + 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 void setTestNGScannerSuiteBasePackage(String testNGScannerSuiteBasePackage) { - this.testNGScannerSuiteBasePackage = testNGScannerSuiteBasePackage; + public List getCommandsScannerBasePackages() { + return commandsScannerBasePackages; } - public boolean isTestNGScannerSuiteUseDefaultFilters() { - return testNGScannerSuiteUseDefaultFilters; + public void setCommandsScannerBasePackages(List commandsScannerBasePackages) { + this.commandsScannerBasePackages = commandsScannerBasePackages; } - public void setTestNGScannerSuiteUseDefaultFilters(boolean testNGScannerSuiteUseDefaultFilters) { - this.testNGScannerSuiteUseDefaultFilters = testNGScannerSuiteUseDefaultFilters; + public List getGoalsScannerBasePackages() { + return goalsScannerBasePackages; } - public String getTestNGScannerListenerBasePackage() { - return testNGScannerListenerBasePackage; + public void setGoalsScannerBasePackages(List goalsScannerBasePackages) { + this.goalsScannerBasePackages = goalsScannerBasePackages; } - public void setTestNGScannerListenerBasePackage(String testNGScannerListenerBasePackage) { - this.testNGScannerListenerBasePackage = testNGScannerListenerBasePackage; + public List getSuitesScannerBasePackages() { + return suitesScannerBasePackages; } - public boolean isTestNGScannerListenerUseDefaultFilters() { - return testNGScannerListenerUseDefaultFilters; + public void setSuitesScannerBasePackages(List suitesScannerBasePackages) { + this.suitesScannerBasePackages = suitesScannerBasePackages; } - public void setTestNGScannerListenerUseDefaultFilters(boolean testNGScannerListenerUseDefaultFilters) { - this.testNGScannerListenerUseDefaultFilters = testNGScannerListenerUseDefaultFilters; + public List getListenersScannerBasePackages() { + return listenersScannerBasePackages; } - @Bean - public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() { - PropertySourcesPlaceholderConfigurer c = new PropertySourcesPlaceholderConfigurer(); - c.setLocation(new ClassPathResource("application.yml")); - c.setIgnoreUnresolvablePlaceholders(true); - c.setIgnoreResourceNotFound(true); - c.setTrimValues(true); - c.setNullValue(""); - return c; + 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/JCommanderConfiguration.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/JCommanderConfiguration.java index 31fa55c..6be4e85 100644 --- 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 @@ -6,6 +6,7 @@ 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; @@ -20,6 +21,7 @@ import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.*; +import java.util.stream.Collectors; /** * {@link JCommander} spring boot configuration class. @@ -31,6 +33,7 @@ */ @Configuration @ConditionalOnNotWebApplication +@EnableConfigurationProperties(ApplicationProperties.class) public class JCommanderConfiguration implements IConfiguration { private final JCommander jCommander; @@ -38,6 +41,7 @@ public class JCommanderConfiguration implements IConfiguration { private final ApplicationProperties properties; private final String[] args; private final Map, JCConfiguration> buggyConfigurations = new HashMap<>(); + private final boolean isJCommanderConfigured; public JCommanderConfiguration(final ApplicationProperties properties, final ApplicationArguments args) { this.properties = properties; @@ -49,6 +53,7 @@ public JCommanderConfiguration(final ApplicationProperties properties, final App .forEach(this.jcConfigurations::add); this.jCommander = buildJCommander(); parseArguments(); + isJCommanderConfigured = true; } public void beforeConfiguration() { @@ -57,6 +62,11 @@ public void beforeConfiguration() { ConfigurationLogger.stepDelimiter(); } + @Bean + public boolean isJCommanderConfigured() { + return isJCommanderConfigured; + } + @PostConstruct public void postConstruct() { if (BuggyConfig.getHelp()) { @@ -81,9 +91,13 @@ private Set scanBuggyConfig() { } public Set scanJCConfigurations() { - final boolean useDefaultFilters = properties.isJCommanderScannerCommandsUseDefaultFilters(); - final String basePackage = properties.getJCommanderScannerCommandsBasePackage(); - final Set defs = scanBeanDefinitions(useDefaultFilters, basePackage, JCConfiguration.class); + 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, JCConfiguration.class)); + } return getBeanDefinitionInstances(defs, JCConfiguration.class); } 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 index 8c98918..2e1773f 100644 --- 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 @@ -2,10 +2,12 @@ import ch.qos.logback.core.util.StatusPrinter; 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.utils.log.BuggyLoggers; import org.touchbit.buggy.core.utils.log.ConfigurationLogger; +import org.touchbit.buggy.spring.boot.starter.BuggyRunner; import java.io.ByteArrayOutputStream; import java.io.PrintStream; @@ -20,9 +22,12 @@ @ConditionalOnNotWebApplication public class LogbackConfiguration implements IConfiguration { - private final boolean isBuggyLoggerInitialized; + private final boolean isLogbackConfigurationInitialized; - public LogbackConfiguration() { + public LogbackConfiguration(boolean isJCommanderConfigured) { + if (!isJCommanderConfigured) { + BuggyRunner.exit(1, "JCommander must be initialized"); + } ConfigurationLogger.blockDelimiter(); ConfigurationLogger.centerBold("Logback configuration (" + BuggyLoggers.LOGGING_CONFIG_FILE + ")"); ConfigurationLogger.stepDelimiter(); @@ -42,12 +47,12 @@ public LogbackConfiguration() { ConfigurationLogger.dotPlaceholder(name, logger.getLevel()); } } - isBuggyLoggerInitialized = true; + isLogbackConfigurationInitialized = true; } @Bean() - public boolean isBuggyLoggerInitialized() { - return isBuggyLoggerInitialized; + public boolean isLogbackConfigurationInitialized() { + return isLogbackConfigurationInitialized; } } diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/TestNGConfiguration.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/TestNGConfiguration.java index fe8d131..97b309b 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/TestNGConfiguration.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/TestNGConfiguration.java @@ -2,6 +2,7 @@ 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.*; import org.touchbit.buggy.core.config.BuggyConfig; import org.touchbit.buggy.core.goal.Goal; @@ -17,6 +18,7 @@ import org.touchbit.buggy.spring.boot.starter.BuggyRunner; import org.touchbit.buggy.core.utils.log.ConfigurationLogger; +import javax.annotation.PostConstruct; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; @@ -24,68 +26,142 @@ /** * TestNG configuration - * Filter test classes for suites by: - * 1. {@link Component}* - * 2. {@link Service}* - * 3. {@link Interface}* + * 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 TestNGConfiguration implements IConfiguration { private final ApplicationProperties properties; private final Set buggyListeners; - private final Set enabledBuggyListeners = new LinkedHashSet<>(); + private final Set enabledBuggyListeners; private final Set> testClasses; private final Set goals; - private final Set enabledComponents; - private final Set enabledServices; - private final Set enabledInterfaces; - - public TestNGConfiguration(final boolean isBuggyLoggerInitialized, final ApplicationProperties properties) { - this.properties = properties; - if (!isBuggyLoggerInitialized) { - BuggyRunner.exit(1, "Logger must be initialized"); + private final Set availableComponents; + private final Set availableServices; + private final Set availableInterfaces; + + public TestNGConfiguration(final boolean isLogbackConfigurationInitialized, final ApplicationProperties props) { + beforeConfiguration(isLogbackConfigurationInitialized); + this.properties = props; + this.buggyListeners = getTestNGListeners(); + this.enabledBuggyListeners = this.buggyListeners.stream() + .filter(BuggyListener::isEnable) + .collect(Collectors.toSet()); + Set> testClassesWithSuiteAnnotation = getTestClassesWithSuiteAnnotation(); + this.testClasses = filterTestClassesByBuggyConfig(testClassesWithSuiteAnnotation); + this.goals = getGoals(); + Set components = + filterByGoalType(this.goals, BuggyConfig.getComponents(), Component.class, AllComponents.class); + this.availableComponents = filterComponentsByTestClasses(components, testClasses); + Set services = + filterByGoalType(this.goals, BuggyConfig.getComponents(), Service.class, AllServices.class); + this.availableServices = filterServiceByTestClasses(services, testClasses); + Set interfaces = + filterByGoalType(this.goals, BuggyConfig.getComponents(), Interface.class, AllInterfaces.class); + this.availableInterfaces = filterInterfaceByTestClasses(interfaces, testClasses); + } + + public void beforeConfiguration(final boolean isLogbackConfigurationInitialized) { + if (!isLogbackConfigurationInitialized) { + BuggyRunner.exit(1, "LogbackConfiguration must be initialized"); } ConfigurationLogger.blockDelimiter(); - ConfigurationLogger.centerBold("Loading TestNG configuration"); + ConfigurationLogger.centerBold("Preparing TestNG configuration"); ConfigurationLogger.stepDelimiter(); + } + + @PostConstruct + public void printTestNgConfigurationInfo() { ConfigurationLogger.center("TestNG listeners"); - this.buggyListeners = getTestNGListeners(); for (BuggyListener buggyListener : this.buggyListeners) { if (buggyListener.isEnable()) { - enabledBuggyListeners.add(buggyListener); ConfigurationLogger.dotPlaceholder(buggyListener.getClass().getSimpleName(), "Enable"); } else { ConfigurationLogger.dotPlaceholder(buggyListener.getClass().getSimpleName(), "Disable"); } } - this.testClasses = getTestClassesWithSuiteAnnotation(); - this.goals = getGoals(); ConfigurationLogger.stepDelimiter(); - ConfigurationLogger.center("Enabled suites goals"); + ConfigurationLogger.center("Available suites goals"); ConfigurationLogger.stepDelimiter(); ConfigurationLogger.center("Components"); - this.enabledComponents = filter(this.goals, BuggyConfig.getComponents(), Component.class, AllComponents.class); - this.enabledComponents.forEach(g -> ConfigurationLogger.dotPlaceholder(JUtils.getSimpleNameC(g), g.getName())); + this.availableComponents.forEach(g -> ConfigurationLogger.dotPlaceholder(JUtils.getSimpleNameC(g), g.getName())); ConfigurationLogger.stepDelimiter(); ConfigurationLogger.center("Services"); - this.enabledServices = filter(this.goals, BuggyConfig.getComponents(), Service.class, AllServices.class); - this.enabledServices.forEach(g -> ConfigurationLogger.dotPlaceholder(JUtils.getSimpleNameC(g), g.getName())); + this.availableServices.forEach(g -> ConfigurationLogger.dotPlaceholder(JUtils.getSimpleNameC(g), g.getName())); ConfigurationLogger.stepDelimiter(); ConfigurationLogger.center("Interfaces"); - this.enabledInterfaces = filter(this.goals, BuggyConfig.getComponents(), Interface.class, AllInterfaces.class); - this.enabledInterfaces.forEach(g -> ConfigurationLogger.dotPlaceholder(JUtils.getSimpleNameC(g), g.getName())); + this.availableInterfaces.forEach(g -> ConfigurationLogger.dotPlaceholder(JUtils.getSimpleNameC(g), g.getName())); + } + + public Set> filterTestClassesByBuggyConfig(Set> testClassesWithSuiteAnnotation) { + List> components = BuggyConfig.getComponents().stream() + .map(Component::getClass) + .collect(Collectors.toList()); + List> services = BuggyConfig.getServices().stream() + .map(Service::getClass) + .collect(Collectors.toList()); + List> interfaces = BuggyConfig.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 filter(final Set allGoals, - final List expectedGoals, - final Class goalFilter, - final Class allFilter) { + 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())) @@ -103,18 +179,18 @@ public Set filter(final Set allGoals, } @Bean("getEnabledComponents") - public Set getEnabledComponents() { - return enabledComponents; + public Set getAvailableComponents() { + return availableComponents; } @Bean("getEnabledServices") - public Set getEnabledServices() { - return enabledServices; + public Set getAvailableServices() { + return availableServices; } @Bean("getEnabledInterfaces") - public Set getEnabledInterfaces() { - return enabledInterfaces; + public Set getAvailableInterfaces() { + return availableInterfaces; } @Bean("getAllGoals") @@ -127,34 +203,44 @@ public Set> getTestClasses() { return testClasses; } - @Bean("getBuggyListeners") - public Set getBuggyListeners() { - return buggyListeners; - } - @Bean("getEnabledBuggyListeners") public Set getEnabledBuggyListeners() { return enabledBuggyListeners; } public Set getGoals() { - final boolean useDefaultFilters = properties.isTestNGScannerListenerUseDefaultFilters(); - final String basePackage = properties.getTestNGScannerListenerBasePackage(); - final Set defs = scanBeanDefinitions(useDefaultFilters, basePackage, Goal.class); + 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> getTestClassesWithSuiteAnnotation() { - final boolean useDefaultFilters = properties.isTestNGScannerSuiteUseDefaultFilters(); - final String basePackage = properties.getTestNGScannerSuiteBasePackage(); - final Set definitions = scanBeanDefinitions(useDefaultFilters, basePackage, Suite.class); - return getBeanDefinitionAnnotatedClasses(definitions, Suite.class); + 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 getTestNGListeners() { - final boolean useDefaultFilters = properties.isTestNGScannerListenerUseDefaultFilters(); - final String basePackage = properties.getTestNGScannerListenerBasePackage(); - final Set defs = scanBeanDefinitions(useDefaultFilters, basePackage, BuggyListener.class); + 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); } diff --git a/buggy-spring-boot-starter/src/main/resources/application.yml b/buggy-spring-boot-starter/src/main/resources/application.yml index 697cd1c..70cbd5e 100644 --- a/buggy-spring-boot-starter/src/main/resources/application.yml +++ b/buggy-spring-boot-starter/src/main/resources/application.yml @@ -2,22 +2,12 @@ logging: config: 'classpath:buggy-logback.xml' file: path: ./logs -spring: - main: - allow-bean-definition-overriding: true buggy: - spring: - configuration: - jcommander: - scanner: - commands: - basePackage: "**.buggy" - useDefaultFilters: false - testng: - scanner: - suite: - basePackage: "**.buggy" - useDefaultFilters: false - listener: - basePackage: "**.buggy" - useDefaultFilters: false \ No newline at end of file + commandsScannerBasePackages: + - "**.buggy" + goalsScannerBasePackages: + - "**.buggy" + suitesScannerBasePackages: + - "**.buggy" + listenersScannerBasePackages: + - "**.buggy" \ No newline at end of file From caf6ef0962a737e3a7283e734404459d915d1d21 Mon Sep 17 00:00:00 2001 From: "oleg.shaburov" Date: Mon, 5 Oct 2020 06:04:09 +0300 Subject: [PATCH 11/24] Add Qualifiers --- .../spring/boot/starter/BuggyRunner.java | 184 ++++++++++++++---- .../starter/conf/ApplicationProperties.java | 2 +- ...iguration.java => BuggyConfiguration.java} | 166 +++++++++------- .../starter/conf/JCommanderConfiguration.java | 4 +- .../starter/conf/LogbackConfiguration.java | 1 - .../spring/boot/starter/conf/Qualifiers.java | 17 ++ .../src/main/resources/application.yml | 8 +- 7 files changed, 265 insertions(+), 117 deletions(-) rename buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/{TestNGConfiguration.java => BuggyConfiguration.java} (69%) create mode 100644 buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/Qualifiers.java 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 index a99dc53..b81d02e 100644 --- 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 @@ -2,63 +2,53 @@ import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.testng.TestNG; +import org.touchbit.buggy.core.config.BuggyConfig; 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.testng.listeners.BuggyListener; -import org.touchbit.buggy.core.utils.log.ConfigurationLogger; import org.touchbit.buggy.core.utils.log.BuggyLoggers; +import org.touchbit.buggy.core.utils.log.ConfigurationLogger; -import java.util.LinkedHashSet; import java.util.Set; +import static org.touchbit.buggy.spring.boot.starter.conf.Qualifiers.*; + @SpringBootApplication public class BuggyRunner implements ApplicationRunner { + private Set allBuggyListeners; private Set enabledBuggyListeners; - private Set> testClasses; - private Set enabledComponents; - private Set enabledServices; - private Set enabledInterfaces; + 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(); @Override public void run(ApplicationArguments args) { - ConfigurationLogger.blockDelimiter(); - ConfigurationLogger.info(" >>>>> " + enabledBuggyListeners); - ConfigurationLogger.info(" >>>>> " + testClasses); - ConfigurationLogger.info(" >>>>> " + enabledComponents); - ConfigurationLogger.info(" >>>>> " + enabledServices); - ConfigurationLogger.info(" >>>>> " + enabledInterfaces); - exit(0); - } - - @Autowired - public void setEnabledBuggyListeners(Set enabledBuggyListeners) { - this.enabledBuggyListeners = enabledBuggyListeners; - } - - @Autowired - public void setTestClasses(Set> testClasses) { - this.testClasses = testClasses; - } - - @Autowired - public void setEnabledComponents(Set enabledComponents) { - this.enabledComponents = enabledComponents; - } - - @Autowired - public void setEnabledServices(Set enabledServices) { - this.enabledServices = enabledServices; - } - - @Autowired - public void setEnabledInterfaces(Set enabledInterfaces) { - this.enabledInterfaces = enabledInterfaces; + TestNG testNG = getTestNG(); + try { + testNG.run(); + if (BuggyConfig.getStatus() != null) { + exit(BuggyConfig.getStatus()); + } + exit(testNG.getStatus()); + } catch (Exception e) { + e.printStackTrace(); + exit(1, "TestNG safely died."); + } } public static void exit(String message, Exception e) { @@ -102,4 +92,122 @@ public static void exit(int status, String message, Exception e) { System.exit(status); } + 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 index 3a22986..ca1b05a 100644 --- 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 @@ -7,7 +7,7 @@ @ConfigurationProperties("buggy") public class ApplicationProperties { - + private static final String BASE_BUGGY_SCAN_PACKAGE = "**.buggy"; private List commandsScannerBasePackages = new ArrayList<>(); private List goalsScannerBasePackages = new ArrayList<>(); diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/TestNGConfiguration.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/BuggyConfiguration.java similarity index 69% rename from buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/TestNGConfiguration.java rename to buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/BuggyConfiguration.java index 97b309b..d2fd0e8 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/TestNGConfiguration.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/BuggyConfiguration.java @@ -3,7 +3,8 @@ 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.*; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; import org.touchbit.buggy.core.config.BuggyConfig; import org.touchbit.buggy.core.goal.Goal; import org.touchbit.buggy.core.goal.component.AllComponents; @@ -15,8 +16,8 @@ import org.touchbit.buggy.core.model.Suite; import org.touchbit.buggy.core.testng.listeners.BuggyListener; import org.touchbit.buggy.core.utils.JUtils; -import org.touchbit.buggy.spring.boot.starter.BuggyRunner; import org.touchbit.buggy.core.utils.log.ConfigurationLogger; +import org.touchbit.buggy.spring.boot.starter.BuggyRunner; import javax.annotation.PostConstruct; import java.util.LinkedHashSet; @@ -24,6 +25,8 @@ 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: @@ -37,36 +40,35 @@ @Configuration() @ConditionalOnNotWebApplication @EnableConfigurationProperties(ApplicationProperties.class) -public class TestNGConfiguration implements IConfiguration { +public class BuggyConfiguration implements IConfiguration { private final ApplicationProperties properties; - private final Set buggyListeners; + private final Set allBuggyListeners; private final Set enabledBuggyListeners; - private final Set> testClasses; - private final Set goals; + 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 TestNGConfiguration(final boolean isLogbackConfigurationInitialized, final ApplicationProperties props) { + public BuggyConfiguration(final boolean isLogbackConfigurationInitialized, final ApplicationProperties props) { beforeConfiguration(isLogbackConfigurationInitialized); - this.properties = props; - this.buggyListeners = getTestNGListeners(); - this.enabledBuggyListeners = this.buggyListeners.stream() - .filter(BuggyListener::isEnable) - .collect(Collectors.toSet()); - Set> testClassesWithSuiteAnnotation = getTestClassesWithSuiteAnnotation(); - this.testClasses = filterTestClassesByBuggyConfig(testClassesWithSuiteAnnotation); - this.goals = getGoals(); - Set components = - filterByGoalType(this.goals, BuggyConfig.getComponents(), Component.class, AllComponents.class); - this.availableComponents = filterComponentsByTestClasses(components, testClasses); - Set services = - filterByGoalType(this.goals, BuggyConfig.getComponents(), Service.class, AllServices.class); - this.availableServices = filterServiceByTestClasses(services, testClasses); - Set interfaces = - filterByGoalType(this.goals, BuggyConfig.getComponents(), Interface.class, AllInterfaces.class); - this.availableInterfaces = filterInterfaceByTestClasses(interfaces, testClasses); + properties = props; + allBuggyListeners = scanTestNGListeners(); + enabledBuggyListeners = allBuggyListeners.stream().filter(BuggyListener::isEnable).collect(Collectors.toSet()); + allTestClasses = scanTestClassesWithSuiteAnnotation(); + filteredTestClasses = filterTestClassesByBuggyConfig(allTestClasses); + allGoals = scanGoals(); + allComponents = filterByGoalType(allGoals, BuggyConfig.getComponents(), Component.class, AllComponents.class); + availableComponents = filterComponentsByTestClasses(allComponents, filteredTestClasses); + allServices = filterByGoalType(allGoals, BuggyConfig.getComponents(), Service.class, AllServices.class); + availableServices = filterServiceByTestClasses(allServices, filteredTestClasses); + allInterfaces = filterByGoalType(allGoals, BuggyConfig.getComponents(), Interface.class, AllInterfaces.class); + availableInterfaces = filterInterfaceByTestClasses(allInterfaces, filteredTestClasses); } public void beforeConfiguration(final boolean isLogbackConfigurationInitialized) { @@ -79,9 +81,9 @@ public void beforeConfiguration(final boolean isLogbackConfigurationInitialized) } @PostConstruct - public void printTestNgConfigurationInfo() { + public void printConfigurationInfo() { ConfigurationLogger.center("TestNG listeners"); - for (BuggyListener buggyListener : this.buggyListeners) { + for (BuggyListener buggyListener : allBuggyListeners) { if (buggyListener.isEnable()) { ConfigurationLogger.dotPlaceholder(buggyListener.getClass().getSimpleName(), "Enable"); } else { @@ -92,13 +94,13 @@ public void printTestNgConfigurationInfo() { ConfigurationLogger.center("Available suites goals"); ConfigurationLogger.stepDelimiter(); ConfigurationLogger.center("Components"); - this.availableComponents.forEach(g -> ConfigurationLogger.dotPlaceholder(JUtils.getSimpleNameC(g), g.getName())); + availableComponents.forEach(g -> ConfigurationLogger.dotPlaceholder(JUtils.getSimpleNameC(g), g.getName())); ConfigurationLogger.stepDelimiter(); ConfigurationLogger.center("Services"); - this.availableServices.forEach(g -> ConfigurationLogger.dotPlaceholder(JUtils.getSimpleNameC(g), g.getName())); + availableServices.forEach(g -> ConfigurationLogger.dotPlaceholder(JUtils.getSimpleNameC(g), g.getName())); ConfigurationLogger.stepDelimiter(); ConfigurationLogger.center("Interfaces"); - this.availableInterfaces.forEach(g -> ConfigurationLogger.dotPlaceholder(JUtils.getSimpleNameC(g), g.getName())); + availableInterfaces.forEach(g -> ConfigurationLogger.dotPlaceholder(JUtils.getSimpleNameC(g), g.getName())); } public Set> filterTestClassesByBuggyConfig(Set> testClassesWithSuiteAnnotation) { @@ -112,15 +114,12 @@ public Set> filterTestClassesByBuggyConfig(Set> testClassesWit .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())) + .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()); } @@ -178,37 +177,7 @@ public Set filterByGoalType(final Set allGoals, } } - @Bean("getEnabledComponents") - public Set getAvailableComponents() { - return availableComponents; - } - - @Bean("getEnabledServices") - public Set getAvailableServices() { - return availableServices; - } - - @Bean("getEnabledInterfaces") - public Set getAvailableInterfaces() { - return availableInterfaces; - } - - @Bean("getAllGoals") - public Set getAllGoals() { - return goals; - } - - @Bean("getTestClasses") - public Set> getTestClasses() { - return testClasses; - } - - @Bean("getEnabledBuggyListeners") - public Set getEnabledBuggyListeners() { - return enabledBuggyListeners; - } - - public Set getGoals() { + public Set scanGoals() { final Set defs = new LinkedHashSet<>(); final List basePackages = properties .getGoalsScannerBasePackages().stream() @@ -220,7 +189,7 @@ public Set getGoals() { return getBeanDefinitionInstances(defs, Goal.class); } - public Set> getTestClassesWithSuiteAnnotation() { + public Set> scanTestClassesWithSuiteAnnotation() { final Set defs = new LinkedHashSet<>(); final List basePackages = properties .getSuitesScannerBasePackages().stream() @@ -232,7 +201,7 @@ public Set> getTestClassesWithSuiteAnnotation() { return getBeanDefinitionAnnotatedClasses(defs, Suite.class); } - public Set getTestNGListeners() { + public Set scanTestNGListeners() { final Set defs = new LinkedHashSet<>(); final List basePackages = properties .getListenersScannerBasePackages().stream() @@ -244,4 +213,59 @@ public Set getTestNGListeners() { 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/JCommanderConfiguration.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/JCommanderConfiguration.java index 6be4e85..539c581 100644 --- 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 @@ -12,9 +12,9 @@ import org.springframework.context.annotation.Configuration; import org.touchbit.buggy.core.config.BuggyConfig; import org.touchbit.buggy.core.config.JCConfiguration; -import org.touchbit.buggy.spring.boot.starter.BuggyRunner; -import org.touchbit.buggy.core.utils.log.ConfigurationLogger; import org.touchbit.buggy.core.utils.JUtils; +import org.touchbit.buggy.core.utils.log.ConfigurationLogger; +import org.touchbit.buggy.spring.boot.starter.BuggyRunner; import javax.annotation.PostConstruct; import java.lang.reflect.Field; 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 index 2e1773f..4a8c815 100644 --- 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 @@ -2,7 +2,6 @@ import ch.qos.logback.core.util.StatusPrinter; 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.utils.log.BuggyLoggers; 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/resources/application.yml b/buggy-spring-boot-starter/src/main/resources/application.yml index 70cbd5e..d895262 100644 --- a/buggy-spring-boot-starter/src/main/resources/application.yml +++ b/buggy-spring-boot-starter/src/main/resources/application.yml @@ -4,10 +4,10 @@ logging: path: ./logs buggy: commandsScannerBasePackages: - - "**.buggy" + - "**.buggy" goalsScannerBasePackages: - - "**.buggy" + - "**.buggy" suitesScannerBasePackages: - - "**.buggy" + - "**.buggy" listenersScannerBasePackages: - - "**.buggy" \ No newline at end of file + - "**.buggy" \ No newline at end of file From 9a5282ae0e7033282d9d2823787435938226eea7 Mon Sep 17 00:00:00 2001 From: "oleg.shaburov" Date: Tue, 6 Oct 2020 04:47:55 +0300 Subject: [PATCH 12/24] Global refactoring --- buggy-core/pom.xml | 59 +- .../buggy/core/{test => }/BaseBuggyTest.java | 27 +- .../java/org/touchbit/buggy/core/Buggy.java | 474 ---- .../touchbit/buggy/core/BuggyProcessor.java | 45 - .../org/touchbit/buggy/core/ExitHandler.java | 43 - .../buggy/core/config/BuggyConfig.java | 162 +- .../buggy/core/config/BuggyConfigYML.java | 82 + .../buggy/core/config/PrimaryConfig.java | 348 --- .../buggy/core/config/SecondaryConfig.java | 24 - .../core/config/jcommander/GoalConverter.java | 52 - .../config/jcommander/ValueValidator.java | 42 - .../buggy/core/goal/component/Component.java | 2 - .../buggy/core/goal/interfaze/Interface.java | 2 - .../buggy/core/goal/service/Service.java | 2 - .../core/{utils => }/log/BuggyLoggers.java | 32 +- .../{utils => }/log/ConfigurationLogger.java | 6 +- .../layout}/ConsoleLoggerColorLayout.java | 4 +- .../layout}/FrameworkLoggerLayout.java | 6 +- .../layout}/ShiftingLoggerLayout.java | 7 +- .../touchbit/buggy/core/model/Details.java | 20 +- .../touchbit/buggy/core/model/IStatus.java | 7 + .../{BParallelMode.java => ParallelMode.java} | 6 +- .../buggy/core/model/ResultStatus.java | 22 +- .../org/touchbit/buggy/core/model/Status.java | 7 +- .../org/touchbit/buggy/core/model/Suite.java | 20 +- .../org/touchbit/buggy/core/test/ITest.java | 9 - .../touchbit/buggy/core/test/TRProperty.java | 23 - .../buggy/core/test/TestRailTest.java | 19 - .../BaseBuggyExecutionListener.java | 32 +- .../{listeners => }/BaseTelegramNotifier.java | 28 +- .../BuggyExecutionListener.java | 166 +- .../testng/{listeners => }/BuggyListener.java | 4 +- .../IntellijIdeaTestNgPluginListener.java | 43 + .../touchbit/buggy/core/testng/TestSuite.java | 204 -- .../{listeners => }/TestSupervisor.java | 50 +- .../IntellijIdeaTestNgPluginListener.java | 92 - .../CURLLoggingInterceptor.java | 2 +- .../buggy/core/utils/{log => }/ANSI.java | 4 +- .../touchbit/buggy/core/utils/BuggyUtils.java | 158 -- .../utils/ExitHandlerExpectedException.java | 9 - .../touchbit/buggy/core/utils/IOHelper.java | 14 +- .../org/touchbit/buggy/core/utils/JUtils.java | 76 +- .../buggy/core/utils/StringUtils.java | 41 +- .../buggy/core/utils/log/BuggyLog.java | 169 -- .../core/utils/log/XMLLogConfigurator.java | 75 - .../src/main/resources/buggy-config.yml | 18 + .../src/main/resources/buggy-log4j2.xml | 58 - .../src/main/resources/buggy-logback.xml | 8 +- .../src/main/resources/buggy.properties | 21 - .../core/config/DisabledUnitTestListener.java | 2 +- .../core/config/EnabledUnitTestListener.java | 2 +- .../buggy/core/config/TestClassWithSuite.java | 2 +- .../core/config/TestClassWithoutSuite.java | 2 +- .../buggy/core/config/TestComponent.java | 4 - .../buggy/core/config/TestExitHandler.java | 72 - .../core/config/UnitTestPrimaryConfig.java | 12 - .../core/config/UnitTestSecondaryConfig.java | 11 - .../buggy/core/helpful/SystemOutLogger.java | 41 +- .../buggy/core/helpful/UnitTestLogger.java | 103 +- .../buggy/core/tests/BaseUnitTest.java | 360 ++- .../core/tests/common/BaseBuggyTestTests.java | 93 +- .../buggy/core/tests/common/BuggyTests.java | 666 ------ .../core/tests/common/ExceptionsTests.java | 2 +- .../core/tests/common/ExitHandlerTests.java | 95 - .../buggy/core/tests/common/GoalTests.java | 2 +- .../tests/config/JCommanderConfigTests.java | 672 +++--- .../core/tests/config/JCommanderTests.java | 495 ++--- .../buggy/core/tests/model/ModelTests.java | 2 +- .../BaseBuggyExecutionListenerTests.java | 97 + .../BaseTelegramNotifierTests.java | 59 +- .../BuggyExecutionListenerTests.java | 1978 ++++++++--------- ...IntellijIdeaTestNgPluginListenerTests.java | 30 +- .../core/tests/testng/TestSuiteTests.java | 292 --- .../{listeners => }/TestSupervisorTests.java | 6 +- .../BaseBuggyExecutionListenerTests.java | 102 - .../CURLLoggingInterceptorTests.java | 14 +- .../buggy/core/tests/utils/BuggyLogTests.java | 144 -- .../core/tests/utils/BuggyUtilsTests.java | 395 +--- .../buggy/core/tests/utils/IOHelperTests.java | 126 +- .../core/tests/utils/StringUtilsTests.java | 4 +- .../src/test/resources/buggy.properties | 1 - buggy-core/src/test/resources/log4j2.xml | 4 +- buggy-feign/pom.xml | 4 +- .../feign/FeignCURLLoggingInterceptor.java | 4 +- .../FeignCURLLoggingInterceptorTests.java | 7 +- .../buggy/feign/FeignCallLoggerTests.java | 4 +- buggy-min-example/pom.xml | 49 - .../buggy/example/min/config/Config.java | 37 - .../min/config/MinExampleSecondaryConfig.java | 81 - .../touchbit/buggy/example/min/goals/API.java | 32 - .../example/min/listeners/StatusMap.java | 32 - .../min/listeners/TestRailListener.java | 15 - .../buggy/example/min/tests/BaseTest.java | 16 - .../buggy/example/min/tests/GitLabTests.java | 124 -- buggy-okhttp/pom.xml | 4 +- .../okhttp/OkHttpCURLLoggingInterceptor.java | 4 +- .../okhttp/OkHttpCallLoggingInterceptor.java | 2 +- .../okhttp/CURLLoggingInterceptorTests.java | 4 +- .../OkHttpCallLoggingInterceptorTests.java | 8 +- buggy-spring-boot-starter-example/pom.xml | 4 +- .../starter/example/ExampleBuggyRunner.java | 11 +- .../boot/starter/example/ExampleTests.java | 18 +- .../boot/starter/example/ExampleTests2.java | 10 + .../boot/starter/example/ExampleTests3.java | 18 + .../example/conf/ExampleConfiguration.java | 4 +- .../spring/boot/starter/BuggyRunner.java | 103 +- .../boot/starter/conf/BuggyConfiguration.java | 4 +- .../starter/conf/JCommanderConfiguration.java | 45 +- .../starter/conf/LogbackConfiguration.java | 6 +- .../boot/starter/jcommander}/BParameters.java | 6 +- .../starter/jcommander/BuggyJCommand.java | 181 ++ .../boot/starter/jcommander/JCommand.java | 8 +- .../jcommander/converters}/ArraySplitter.java | 2 +- .../converters}/ComponentConverter.java | 2 +- .../jcommander/converters/GoalConverter.java | 81 + .../converters}/InterfaceConverter.java | 2 +- .../converters}/ParameterValidator.java | 4 +- .../converters}/ServiceConverter.java | 2 +- .../src/main/resources/application.yml | 2 +- buggy-testrail/pom.xml | 4 +- .../buggy/testrail/BTRParameters.java | 8 +- .../buggy/testrail/BaseTestRailConfig.java | 49 +- .../buggy/testrail/RunsResultsStorage.java | 4 +- .../listeners/BaseTestRailListener.java | 32 +- .../listeners/DefaultTestRailListener.java | 51 +- pom.xml | 9 +- 126 files changed, 3057 insertions(+), 6754 deletions(-) rename buggy-core/src/main/java/org/touchbit/buggy/core/{test => }/BaseBuggyTest.java (62%) delete mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/Buggy.java delete mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/BuggyProcessor.java delete mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/ExitHandler.java create mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/config/BuggyConfigYML.java delete mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/config/PrimaryConfig.java delete mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/config/SecondaryConfig.java delete mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/config/jcommander/GoalConverter.java delete mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/config/jcommander/ValueValidator.java rename buggy-core/src/main/java/org/touchbit/buggy/core/{utils => }/log/BuggyLoggers.java (74%) rename buggy-core/src/main/java/org/touchbit/buggy/core/{utils => }/log/ConfigurationLogger.java (94%) rename buggy-core/src/main/java/org/touchbit/buggy/core/{utils/log => log/layout}/ConsoleLoggerColorLayout.java (95%) rename buggy-core/src/main/java/org/touchbit/buggy/core/{utils/log => log/layout}/FrameworkLoggerLayout.java (91%) rename buggy-core/src/main/java/org/touchbit/buggy/core/{utils/log => log/layout}/ShiftingLoggerLayout.java (89%) create mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/model/IStatus.java rename buggy-core/src/main/java/org/touchbit/buggy/core/model/{BParallelMode.java => ParallelMode.java} (76%) rename buggy-min-example/src/main/java/org/touchbit/buggy/example/min/goals/GitLab.java => buggy-core/src/main/java/org/touchbit/buggy/core/model/ResultStatus.java (68%) delete mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/test/ITest.java delete mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/test/TRProperty.java delete mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/test/TestRailTest.java rename buggy-core/src/main/java/org/touchbit/buggy/core/testng/{listeners => }/BaseBuggyExecutionListener.java (84%) rename buggy-core/src/main/java/org/touchbit/buggy/core/testng/{listeners => }/BaseTelegramNotifier.java (86%) rename buggy-core/src/main/java/org/touchbit/buggy/core/testng/{listeners => }/BuggyExecutionListener.java (83%) rename buggy-core/src/main/java/org/touchbit/buggy/core/testng/{listeners => }/BuggyListener.java (63%) create mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/testng/IntellijIdeaTestNgPluginListener.java delete mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/testng/TestSuite.java rename buggy-core/src/main/java/org/touchbit/buggy/core/testng/{listeners => }/TestSupervisor.java (91%) delete mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/testng/listeners/IntellijIdeaTestNgPluginListener.java rename buggy-core/src/main/java/org/touchbit/buggy/core/transport/{interceptor => }/CURLLoggingInterceptor.java (95%) rename buggy-core/src/main/java/org/touchbit/buggy/core/utils/{log => }/ANSI.java (84%) delete mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/utils/BuggyUtils.java delete mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/utils/ExitHandlerExpectedException.java delete mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/utils/log/BuggyLog.java delete mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/utils/log/XMLLogConfigurator.java create mode 100644 buggy-core/src/main/resources/buggy-config.yml delete mode 100644 buggy-core/src/main/resources/buggy-log4j2.xml rename {buggy-spring-boot-starter => buggy-core}/src/main/resources/buggy-logback.xml (84%) delete mode 100644 buggy-core/src/main/resources/buggy.properties delete mode 100644 buggy-core/src/test/java/org/touchbit/buggy/core/config/TestExitHandler.java delete mode 100644 buggy-core/src/test/java/org/touchbit/buggy/core/config/UnitTestPrimaryConfig.java delete mode 100644 buggy-core/src/test/java/org/touchbit/buggy/core/config/UnitTestSecondaryConfig.java delete mode 100644 buggy-core/src/test/java/org/touchbit/buggy/core/tests/common/BuggyTests.java delete mode 100644 buggy-core/src/test/java/org/touchbit/buggy/core/tests/common/ExitHandlerTests.java create mode 100644 buggy-core/src/test/java/org/touchbit/buggy/core/tests/testng/BaseBuggyExecutionListenerTests.java rename buggy-core/src/test/java/org/touchbit/buggy/core/tests/testng/{listeners => }/BaseTelegramNotifierTests.java (87%) rename buggy-core/src/test/java/org/touchbit/buggy/core/tests/testng/{listeners => }/BuggyExecutionListenerTests.java (55%) rename buggy-core/src/test/java/org/touchbit/buggy/core/tests/testng/{listeners => }/IntellijIdeaTestNgPluginListenerTests.java (53%) delete mode 100644 buggy-core/src/test/java/org/touchbit/buggy/core/tests/testng/TestSuiteTests.java rename buggy-core/src/test/java/org/touchbit/buggy/core/tests/testng/{listeners => }/TestSupervisorTests.java (98%) delete mode 100644 buggy-core/src/test/java/org/touchbit/buggy/core/tests/testng/listeners/BaseBuggyExecutionListenerTests.java delete mode 100644 buggy-core/src/test/java/org/touchbit/buggy/core/tests/utils/BuggyLogTests.java delete mode 100644 buggy-min-example/pom.xml delete mode 100644 buggy-min-example/src/main/java/org/touchbit/buggy/example/min/config/Config.java delete mode 100644 buggy-min-example/src/main/java/org/touchbit/buggy/example/min/config/MinExampleSecondaryConfig.java delete mode 100644 buggy-min-example/src/main/java/org/touchbit/buggy/example/min/goals/API.java delete mode 100644 buggy-min-example/src/main/java/org/touchbit/buggy/example/min/listeners/StatusMap.java delete mode 100644 buggy-min-example/src/main/java/org/touchbit/buggy/example/min/listeners/TestRailListener.java delete mode 100644 buggy-min-example/src/main/java/org/touchbit/buggy/example/min/tests/BaseTest.java delete mode 100644 buggy-min-example/src/main/java/org/touchbit/buggy/example/min/tests/GitLabTests.java create mode 100644 buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleTests3.java rename {buggy-core/src/main/java/org/touchbit/buggy/core/config => buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander}/BParameters.java (91%) create mode 100644 buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/BuggyJCommand.java rename buggy-core/src/main/java/org/touchbit/buggy/core/config/JCConfiguration.java => buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/JCommand.java (97%) rename {buggy-core/src/main/java/org/touchbit/buggy/core/config/jcommander => buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters}/ArraySplitter.java (94%) rename {buggy-core/src/main/java/org/touchbit/buggy/core/config/jcommander => buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters}/ComponentConverter.java (93%) create mode 100644 buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/GoalConverter.java rename {buggy-core/src/main/java/org/touchbit/buggy/core/config/jcommander => buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters}/InterfaceConverter.java (93%) rename {buggy-core/src/main/java/org/touchbit/buggy/core/config/jcommander => buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters}/ParameterValidator.java (90%) rename {buggy-core/src/main/java/org/touchbit/buggy/core/config/jcommander => buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters}/ServiceConverter.java (93%) diff --git a/buggy-core/pom.xml b/buggy-core/pom.xml index 3cf127c..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,48 +39,15 @@ com.beust jcommander - - org.atteo.classindex - classindex - org.apache.commons commons-lang3 - - org.aspectj - aspectjweaver - 1.9.6 - ch.qos.logback logback-classic - - 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 - org.jetbrains @@ -80,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 62% 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..3d190b0 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.log.BuggyLoggers; +import org.touchbit.buggy.core.testng.BuggyExecutionListener; +import org.touchbit.buggy.core.testng.IntellijIdeaTestNgPluginListener; /** * Base class for tests. @@ -29,21 +29,17 @@ * 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 Logger log; protected BaseBuggyTest() { - this(null); + this(BuggyLoggers.SIFTING); } protected BaseBuggyTest(final Logger logger) { - if (!IntellijIdeaTestNgPluginListener.isIntellijIdeaTestRun() && !Buggy.isTestRun()) { - Buggy.getExitHandler().exitRun(1, "Missing IntellijIdeaPluginListener in the Intellij IDEA" + - " TestNG plugin configuration."); - } setLog(logger); - setRunId(); } /** @@ -59,9 +55,4 @@ protected static void setLog(final Logger 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/BuggyConfig.java b/buggy-core/src/main/java/org/touchbit/buggy/core/config/BuggyConfig.java index 6cf5587..4e0c15d 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/config/BuggyConfig.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/config/BuggyConfig.java @@ -1,22 +1,22 @@ package org.touchbit.buggy.core.config; -import com.beust.jcommander.Parameter; -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.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.service.AllServices; -import org.touchbit.buggy.core.model.BParallelMode; -import org.touchbit.buggy.core.model.Type; 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 java.util.ArrayList; +import java.util.Arrays; +import java.util.List; -import static org.touchbit.buggy.core.config.BParameters.*; -import static org.touchbit.buggy.core.model.BParallelMode.METHODS; +import static org.touchbit.buggy.core.model.ParallelMode.METHODS; +import static org.touchbit.buggy.core.model.Type.ALL; /** * Configuration class for customizing Buggy. @@ -25,54 +25,31 @@ * shaburov.o.a@gmail.com */ @SuppressWarnings("unused") -public class BuggyConfig implements JCConfiguration { +public final class BuggyConfig { - @Parameter(names = {QUESTION_MARK, HELP}, help = true, description = "Print usage.") private static Boolean help = false; - - @Parameter(names = {F, FORCE}, description = "Running all tests, including those that fall.") private static Boolean force = false; - - @Parameter(names = {PRINT_SUITE}, description = "Display information on the Suite in the console log.") private static Boolean printSuite = false; - - @Parameter(names = {PRINT_CAUSE}, description = "Print the cause of a fail or skip test in the console log.") private static Boolean printCause = false; - - @Parameter(names = {PRINT_LOG}, description = "Print the test log file path in the console log") private static Boolean printLog = false; - private static Boolean printLogOnlyFail = false; - - @Parameter(names = {V, VERSION}, description = "Print program version") private static Boolean version = false; - - @Parameter(names = {THREADS}, description = "The number of threads to run the test methods.") private static Integer threads = 50; - - @Parameter(names = {EXIT_STATUS}, description = "Completion with the specified status.") - private static Integer status; - - @Parameter(names = {ARTIFACTS_URL}, description = "The storage address for the builds (artifacts).") private static String artifactsUrl; + private static ParallelMode parallelMode = METHODS; + private static List components = JUtils.getListWith(AllComponents::new); + private static List services = JUtils.getListWith(AllServices::new); + private static List interfaces = JUtils.getListWith(AllInterfaces::new); + private static List types = JUtils.getListWith(ALL); + private static String programName = "Buggy"; - @Parameter(names = {PARALLEL_MODE}, description = "TestNG parallel mode.") - private static BParallelMode parallelMode = METHODS; - - @Parameter(names = {C, COMPONENTS}, description = "List of tested components in the format: NAME,NAME,NAME.", - validateWith = ParameterValidator.class, listConverter = ServiceConverter.class) - private static List components = new ArrayList() {{ add(new AllComponents()); }}; - - @Parameter(names = {S, SERVICES}, description = "List of tested services in the format: NAME,NAME,NAME.", - validateWith = ParameterValidator.class, listConverter = ServiceConverter.class) - private static List services = new ArrayList() {{ add(new AllServices()); }}; - - @Parameter(names = {I, INTERFACE}, description = "List of tested interfaces in the format: NAME,NAME,NAME.", - validateWith = ParameterValidator.class, listConverter = InterfaceConverter.class) - private static List interfaces = new ArrayList() {{ add(new AllInterfaces()); }}; + public static void setPrintLogFileOnlyFail(Boolean printLogIfFail) { + BuggyConfig.printLogOnlyFail = printLogIfFail; + } - @Parameter(names = {T, TYPE}, description = "Type of tests to run.", validateWith = ParameterValidator.class) - private static List types = new ArrayList() {{ add(Type.ALL); }}; + public static Boolean isPrintLogFileOnlyFail() { + return BuggyConfig.printLogOnlyFail; + } public static Boolean getHelp() { return help; @@ -82,7 +59,7 @@ public static void setHelp(Boolean help) { BuggyConfig.help = help; } - public static Boolean getForce() { + public static Boolean isForce() { return force; } @@ -90,7 +67,7 @@ public static void setForce(Boolean force) { BuggyConfig.force = force; } - public static Boolean getPrintSuite() { + public static Boolean isPrintSuite() { return printSuite; } @@ -98,7 +75,7 @@ public static void setPrintSuite(Boolean printSuite) { BuggyConfig.printSuite = printSuite; } - public static Boolean getPrintCause() { + public static Boolean isPrintCause() { return printCause; } @@ -106,7 +83,7 @@ public static void setPrintCause(Boolean printCause) { BuggyConfig.printCause = printCause; } - public static Boolean getPrintLog() { + public static Boolean isPrintLog() { return printLog; } @@ -114,15 +91,11 @@ public static void setPrintLog(Boolean printLog) { BuggyConfig.printLog = printLog; } - public static Boolean getPrintLogOnlyFail() { - return printLogOnlyFail; - } - public static void setPrintLogOnlyFail(Boolean printLogOnlyFail) { BuggyConfig.printLogOnlyFail = printLogOnlyFail; } - public static Boolean getVersion() { + public static Boolean isVersion() { return version; } @@ -138,14 +111,6 @@ public static void setThreads(Integer threads) { BuggyConfig.threads = threads; } - public static Integer getStatus() { - return status; - } - - public static void setStatus(Integer status) { - BuggyConfig.status = status; - } - public static String getArtifactsUrl() { return artifactsUrl; } @@ -189,15 +154,10 @@ public static void setServices(S... services) { @SafeVarargs public static void setServices(Class... services) { - if (interfaces != null) { - BuggyConfig.services = new ArrayList<>(); - for (Class service : services) { - try { - BuggyConfig.services.add(service.getDeclaredConstructor().newInstance()); - } catch (Exception e) { - e.printStackTrace(); - } - } + BuggyConfig.services = new ArrayList<>(); + for (Class service : services) { + Service instance = JUtils.newInstance(service, BuggyConfigurationException::new); + BuggyConfig.services.add(instance); } } @@ -220,15 +180,10 @@ public static void setInterfaces(I... interfaces) { @SafeVarargs public static void setInterfaces(Class... interfaces) { - if (interfaces != null) { - BuggyConfig.interfaces = new ArrayList<>(); - for (Class anInterface : interfaces) { - try { - BuggyConfig.interfaces.add(anInterface.getDeclaredConstructor().newInstance()); - } catch (Exception e) { - e.printStackTrace(); - } - } + BuggyConfig.interfaces = new ArrayList<>(); + for (Class anInterface : interfaces) { + Interface instance = JUtils.newInstance(anInterface, BuggyConfigurationException::new); + BuggyConfig.interfaces.add(instance); } } @@ -251,48 +206,27 @@ public static void setComponents(C... components) { @SafeVarargs public static void setComponents(Class... components) { - if (components != null) { - BuggyConfig.components = new ArrayList<>(); - for (Class component : components) { - try { - BuggyConfig.components.add(component.getDeclaredConstructor().newInstance()); - } catch (Exception e) { - e.printStackTrace(); - } - } + BuggyConfig.components = new ArrayList<>(); + for (Class component : components) { + Component instance = JUtils.newInstance(component, BuggyConfigurationException::new); + BuggyConfig.components.add(instance); } } - public static BParallelMode getParallelMode() { + public static ParallelMode getParallelMode() { return parallelMode; } - public static void setParallelMode(BParallelMode parallelMode) { + public static void setParallelMode(ParallelMode parallelMode) { BuggyConfig.parallelMode = parallelMode; } - @Override - public Map sort(Map map) { - String[] sort = new String[] - {THREADS, PARALLEL_MODE, F, PRINT_LOG, PRINT_CAUSE, PRINT_SUITE, - 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; + public static String getProgramName() { + return BuggyConfig.programName; + } + + public static void setProgramName(String programName) { + BuggyConfig.programName = programName; } } diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/config/BuggyConfigYML.java b/buggy-core/src/main/java/org/touchbit/buggy/core/config/BuggyConfigYML.java new file mode 100644 index 0000000..828aa57 --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/config/BuggyConfigYML.java @@ -0,0 +1,82 @@ +package org.touchbit.buggy.core.config; + +import org.touchbit.buggy.core.exceptions.BuggyConfigurationException; +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.core.utils.JUtils; + +import java.util.List; +import java.util.stream.Collectors; + +public final class BuggyConfigYML { + + public void setHelp(Boolean help) { + BuggyConfig.setHelp(help); + } + + public void setForce(Boolean force) { + BuggyConfig.setForce(force); + } + + public void setPrintSuite(Boolean printSuite) { + BuggyConfig.setPrintSuite(printSuite); + } + + public void setPrintCause(Boolean printCause) { + BuggyConfig.setPrintCause(printCause); + } + + public void setPrintLog(Boolean printLog) { + BuggyConfig.setPrintLog(printLog); + } + + public void setPrintLogOnlyFail(Boolean printLogOnlyFail) { + BuggyConfig.setPrintLogOnlyFail(printLogOnlyFail); + } + + public void setVersion(Boolean version) { + BuggyConfig.setVersion(version); + } + + public void setThreads(Integer threads) { + BuggyConfig.setThreads(threads); + } + + public void setArtifactsUrl(String artifactsUrl) { + BuggyConfig.setArtifactsUrl(artifactsUrl); + } + + public void setParallelMode(ParallelMode parallelMode) { + BuggyConfig.setParallelMode(parallelMode); + } + + public void setComponents(List components) { + BuggyConfig.setComponents(components.stream() + .map(c -> (Component) JUtils.newInstance(c, BuggyConfigurationException::new)) + .collect(Collectors.toList())); + } + + public void setServices(List services) { + BuggyConfig.setServices(services.stream() + .map(s -> (Service) JUtils.newInstance(s, BuggyConfigurationException::new)) + .collect(Collectors.toList())); + } + + public void setInterfaces(List interfaces) { + BuggyConfig.setInterfaces(interfaces.stream() + .map(i -> (Interface) JUtils.newInstance(i, BuggyConfigurationException::new)) + .collect(Collectors.toList())); + } + + public void setTypes(List types) { + BuggyConfig.setTypes(types); + } + + public void setProgramName(String programName) { + BuggyConfig.setProgramName(programName); + } + +} 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 b610902..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.goal.interfaze.Interface; -import org.touchbit.buggy.core.goal.service.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 = {LOGS_PATH}, 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 = {EXIT_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/SecondaryConfig.java b/buggy-core/src/main/java/org/touchbit/buggy/core/config/SecondaryConfig.java deleted file mode 100644 index c9d7e39..0000000 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/config/SecondaryConfig.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * 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 org.atteo.classindex.IndexSubclasses; - -/** - * Secondary Config for jCommander command block - *

- * Created by Oleg Shaburov on 17.05.2018 - * shaburov.o.a@gmail.com - */ -@IndexSubclasses -public interface SecondaryConfig { } diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/config/jcommander/GoalConverter.java b/buggy-core/src/main/java/org/touchbit/buggy/core/config/jcommander/GoalConverter.java deleted file mode 100644 index ee775dd..0000000 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/config/jcommander/GoalConverter.java +++ /dev/null @@ -1,52 +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.IStringConverter; -import org.atteo.classindex.ClassIndex; -import org.touchbit.buggy.core.exceptions.BuggyConfigurationException; -import org.touchbit.buggy.core.goal.Goal; - -/** - * Created by Oleg Shaburov on 08.09.2018 - * shaburov.o.a@gmail.com - */ -public final class GoalConverter implements IStringConverter { - - private final Class tClass; - - public GoalConverter(final Class t) { - tClass = 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()); - } - } - throw new BuggyConfigurationException("No " + tClass.getSimpleName() + " found with name " + s); - } - -} 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 e71194e..0000000 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/config/jcommander/ValueValidator.java +++ /dev/null @@ -1,42 +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) { - // TODO remove - } - -} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/goal/component/Component.java b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/component/Component.java index f091cac..67f0573 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/goal/component/Component.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/component/Component.java @@ -16,7 +16,6 @@ package org.touchbit.buggy.core.goal.component; -import org.atteo.classindex.IndexSubclasses; import org.touchbit.buggy.core.goal.Goal; /** @@ -25,7 +24,6 @@ * Created by Oleg Shaburov on 15.05.2018 * shaburov.o.a@gmail.com */ -@IndexSubclasses public abstract class Component implements Goal { public String getName() { diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/goal/interfaze/Interface.java b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/interfaze/Interface.java index 1d529e9..79e698f 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/goal/interfaze/Interface.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/interfaze/Interface.java @@ -16,7 +16,6 @@ package org.touchbit.buggy.core.goal.interfaze; -import org.atteo.classindex.IndexSubclasses; import org.touchbit.buggy.core.goal.Goal; /** @@ -25,7 +24,6 @@ * 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/service/Service.java b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/service/Service.java index a7edb6f..a1db158 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/goal/service/Service.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/service/Service.java @@ -16,7 +16,6 @@ package org.touchbit.buggy.core.goal.service; -import org.atteo.classindex.IndexSubclasses; import org.touchbit.buggy.core.goal.Goal; /** @@ -25,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/utils/log/BuggyLoggers.java b/buggy-core/src/main/java/org/touchbit/buggy/core/log/BuggyLoggers.java similarity index 74% rename from buggy-core/src/main/java/org/touchbit/buggy/core/utils/log/BuggyLoggers.java rename to buggy-core/src/main/java/org/touchbit/buggy/core/log/BuggyLoggers.java index 8ed0c4c..623d1b7 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/utils/log/BuggyLoggers.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/log/BuggyLoggers.java @@ -1,4 +1,4 @@ -package org.touchbit.buggy.core.utils.log; +package org.touchbit.buggy.core.log; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.spi.ILoggingEvent; @@ -7,27 +7,39 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; +import org.touchbit.buggy.core.utils.JUtils; import java.io.File; import java.util.Iterator; public class BuggyLoggers { + static { + if (JUtils.isJetBrainsIdeRun()) { + System.setProperty("LOG_PATH", "target/logs"); + } else { + System.setProperty("LOG_PATH", "logs"); + } + System.setProperty("logging.config", "buggy-logback.xml"); + System.setProperty("logback.configurationFile", "buggy-logback.xml"); + } + public static final String CONSOLE_LOGGER_NAME = "Console"; public static final String FRAMEWORK_LOGGER_NAME = "Framework"; public static final String SIFTING_LOGGER_NAME = "Sifting"; public static final String CONFIG_PROPERTY = "logging.config"; public static final String SIFTING_LOG_FILE_PATH = "sifting.log.file.path"; - public static final Logger C_LOG = LoggerFactory.getLogger(CONSOLE_LOGGER_NAME); - public static final Logger CONSOLE = C_LOG; - public static final Logger F_LOG = LoggerFactory.getLogger(FRAMEWORK_LOGGER_NAME); - public static final Logger FRAMEWORK = F_LOG; - public static final Logger S_LOG = LoggerFactory.getLogger(SIFTING_LOGGER_NAME); - public static final Logger SIFTING = S_LOG; + public static final Logger CONSOLE = LoggerFactory.getLogger(CONSOLE_LOGGER_NAME); + public static final Logger FRAMEWORK = LoggerFactory.getLogger(FRAMEWORK_LOGGER_NAME); + public static final Logger SIFTING = LoggerFactory.getLogger(SIFTING_LOGGER_NAME); public static final String LOGGING_CONFIG_FILE = System.getProperty(CONFIG_PROPERTY, "buggy-logback.xml"); public static final LoggerContext LOGGER_CONTEXT = (LoggerContext) LoggerFactory.getILoggerFactory(); + protected BuggyLoggers() { + throw new IllegalStateException("Utility class. Prohibit instantiation."); + } + public static String getFrameworkLogFilePath() { return getLogFilePath(FRAMEWORK_LOGGER_NAME); } @@ -35,7 +47,7 @@ public static String getFrameworkLogFilePath() { public static String getLogFilePath(String loggerName) { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); for (ch.qos.logback.classic.Logger logger : context.getLoggerList()) { - for (Iterator> index = logger.iteratorForAppenders(); index.hasNext();) { + for (Iterator> index = logger.iteratorForAppenders(); index.hasNext(); ) { Appender appender = index.next(); if (appender instanceof FileAppender && appender.getName().equalsIgnoreCase(loggerName)) { FileAppender fileAppender = (FileAppender) appender; @@ -58,8 +70,4 @@ public static void setSiftingLogFilePath(File file) { MDC.put(SIFTING_LOG_FILE_PATH, file.getPath()); } - protected BuggyLoggers() { - throw new IllegalStateException("Utility class. Prohibit instantiation."); - } - } diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/utils/log/ConfigurationLogger.java b/buggy-core/src/main/java/org/touchbit/buggy/core/log/ConfigurationLogger.java similarity index 94% rename from buggy-core/src/main/java/org/touchbit/buggy/core/utils/log/ConfigurationLogger.java rename to buggy-core/src/main/java/org/touchbit/buggy/core/log/ConfigurationLogger.java index 5f543ef..697bea2 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/utils/log/ConfigurationLogger.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/log/ConfigurationLogger.java @@ -1,8 +1,8 @@ -package org.touchbit.buggy.core.utils.log; +package org.touchbit.buggy.core.log; import static java.util.Objects.isNull; -import static org.touchbit.buggy.core.utils.log.ANSI.BOLD; -import static org.touchbit.buggy.core.utils.log.ANSI.RED; +import static org.touchbit.buggy.core.utils.ANSI.BOLD; +import static org.touchbit.buggy.core.utils.ANSI.RED; /** * Utility class for logging configuration events in TestNG format diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/utils/log/ConsoleLoggerColorLayout.java b/buggy-core/src/main/java/org/touchbit/buggy/core/log/layout/ConsoleLoggerColorLayout.java similarity index 95% rename from buggy-core/src/main/java/org/touchbit/buggy/core/utils/log/ConsoleLoggerColorLayout.java rename to buggy-core/src/main/java/org/touchbit/buggy/core/log/layout/ConsoleLoggerColorLayout.java index cd28f5d..1763be8 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/utils/log/ConsoleLoggerColorLayout.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/log/layout/ConsoleLoggerColorLayout.java @@ -1,4 +1,4 @@ -package org.touchbit.buggy.core.utils.log; +package org.touchbit.buggy.core.log.layout; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.classic.spi.IThrowableProxy; @@ -8,7 +8,7 @@ import org.slf4j.MDC; import static ch.qos.logback.classic.Level.*; -import static org.touchbit.buggy.core.utils.log.ANSI.*; +import static org.touchbit.buggy.core.utils.ANSI.*; /** * Console logger layout for dividing logging levels by color. diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/utils/log/FrameworkLoggerLayout.java b/buggy-core/src/main/java/org/touchbit/buggy/core/log/layout/FrameworkLoggerLayout.java similarity index 91% rename from buggy-core/src/main/java/org/touchbit/buggy/core/utils/log/FrameworkLoggerLayout.java rename to buggy-core/src/main/java/org/touchbit/buggy/core/log/layout/FrameworkLoggerLayout.java index 9137481..83e3568 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/utils/log/FrameworkLoggerLayout.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/log/layout/FrameworkLoggerLayout.java @@ -1,4 +1,4 @@ -package org.touchbit.buggy.core.utils.log; +package org.touchbit.buggy.core.log.layout; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.spi.ILoggingEvent; @@ -7,7 +7,7 @@ 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.log.ANSI; +import org.touchbit.buggy.core.utils.ANSI; import java.util.Date; @@ -57,7 +57,7 @@ public String doLayout(final ILoggingEvent event) { if (throwableProxy != null) { tMsg = CoreConstants.LINE_SEPARATOR + ThrowableProxyUtil.asString(throwableProxy); } - return time + " " + level + " - " + finalMessage + tMsg + CoreConstants.LINE_SEPARATOR; + return time + " " + level + " - " + finalMessage + tMsg + CoreConstants.LINE_SEPARATOR; } } diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/utils/log/ShiftingLoggerLayout.java b/buggy-core/src/main/java/org/touchbit/buggy/core/log/layout/ShiftingLoggerLayout.java similarity index 89% rename from buggy-core/src/main/java/org/touchbit/buggy/core/utils/log/ShiftingLoggerLayout.java rename to buggy-core/src/main/java/org/touchbit/buggy/core/log/layout/ShiftingLoggerLayout.java index 14f2e55..d0c5fa7 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/utils/log/ShiftingLoggerLayout.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/log/layout/ShiftingLoggerLayout.java @@ -1,6 +1,5 @@ -package org.touchbit.buggy.core.utils.log; +package org.touchbit.buggy.core.log.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; @@ -44,8 +43,8 @@ public String getPresentation() { /** * 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) + * java.lang.IllegalArgumentException: 'value' must not be null + * at org.springframework.util.Assert.notNull(Assert.java:201) */ @Override public String doLayout(final ILoggingEvent event) { 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/Details.java index 873cdf7..2d22342 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/Details.java @@ -21,8 +21,6 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import static org.touchbit.buggy.core.model.Status.SUCCESS; - /** * Interface of binding test methods. * Custom statuses for tests are provided. @@ -34,22 +32,30 @@ @Target({ElementType.METHOD}) public @interface Details { - /** Test-case identifiers */ + /** + * Test-case identifiers + */ long[] id() default -1; /** * Test status (see: {@link Status}) * Used values: EXP_IMPL, EXP_FIX, BLOCKED, CORRUPTED */ - Status status() default SUCCESS; + Status status(); - /** Issues ID in the task-tracker system. Format: "STORY-269" */ + /** + * Issues ID in the task-tracker system. Format: "STORY-269" + */ String[] issue() default {""}; - /** Defects ID in the task-tracker system. Format: "BUG-269" */ + /** + * Defects ID in the task-tracker system. Format: "BUG-269" + */ String[] bug() default {""}; - /** Type of auto test */ + /** + * Type of auto test + */ Type[] type() 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/BParallelMode.java b/buggy-core/src/main/java/org/touchbit/buggy/core/model/ParallelMode.java similarity index 76% rename from buggy-core/src/main/java/org/touchbit/buggy/core/model/BParallelMode.java rename to buggy-core/src/main/java/org/touchbit/buggy/core/model/ParallelMode.java index 68b07a3..f07053e 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/model/BParallelMode.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/model/ParallelMode.java @@ -2,7 +2,7 @@ import org.testng.xml.XmlSuite; -public enum BParallelMode { +public enum ParallelMode { TESTS(XmlSuite.ParallelMode.TESTS), METHODS(XmlSuite.ParallelMode.METHODS), @@ -11,9 +11,9 @@ public enum BParallelMode { NONE(XmlSuite.ParallelMode.NONE), ; - private XmlSuite.ParallelMode testNGMode; + private final XmlSuite.ParallelMode testNGMode; - BParallelMode(XmlSuite.ParallelMode testNGMode) { + ParallelMode(XmlSuite.ParallelMode testNGMode) { this.testNGMode = testNGMode; } 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/model/ResultStatus.java similarity index 68% 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/model/ResultStatus.java index b1d69d9..f5e28e2 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/model/ResultStatus.java @@ -14,19 +14,27 @@ * limitations under the License. */ -package org.touchbit.buggy.example.min.goals; - -import org.touchbit.buggy.core.goal.service.Service; +package org.touchbit.buggy.core.model; /** - * Created by Oleg Shaburov on 18.09.2018 + * Test completion statuses + *

+ * Created by Oleg Shaburov on 16.05.2018 * shaburov.o.a@gmail.com */ -public class GitLab extends Service { +public enum ResultStatus implements IStatus { + + FIXED, + IMPLEMENTED, + UNTESTED, + SUCCESS, + SKIP, + FAILED, + ; @Override - public String getDescription() { - return "GitLab service"; + 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..6de4fc3 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,7 +22,7 @@ * 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, @@ -39,4 +39,9 @@ public enum Status { FAILED, ; + @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 ea1895b..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,10 +16,7 @@ package org.touchbit.buggy.core.model; -import org.atteo.classindex.IndexAnnotated; -import org.touchbit.buggy.core.goal.Goal; import org.touchbit.buggy.core.goal.component.Component; -import org.touchbit.buggy.core.goal.component.AllComponents; import org.touchbit.buggy.core.goal.component.DefaultComponent; import org.touchbit.buggy.core.goal.interfaze.DefaultInterface; import org.touchbit.buggy.core.goal.interfaze.Interface; @@ -37,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 */ + /** + * The test service included in the component + */ Class service() default DefaultService.class; - /** The interface on which the test is performed */ + /** + * The interface on which the test is performed + */ Class interfaze() default DefaultInterface.class; - /** The purpose of the tests included in the test class. (example: 'update_user' or 'upload_pdf') */ + /** + * 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/test/ITest.java b/buggy-core/src/main/java/org/touchbit/buggy/core/test/ITest.java deleted file mode 100644 index 13062a1..0000000 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/test/ITest.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.touchbit.buggy.core.test; - -import org.testng.annotations.Listeners; -import org.touchbit.buggy.core.testng.listeners.IntellijIdeaTestNgPluginListener; - -@Listeners(IntellijIdeaTestNgPluginListener.class) -public interface ITest { - -} 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/listeners/BaseBuggyExecutionListener.java b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/BaseBuggyExecutionListener.java similarity index 84% rename from buggy-core/src/main/java/org/touchbit/buggy/core/testng/listeners/BaseBuggyExecutionListener.java rename to buggy-core/src/main/java/org/touchbit/buggy/core/testng/BaseBuggyExecutionListener.java index 2b013dd..f5464b0 100644 --- 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/BaseBuggyExecutionListener.java @@ -14,21 +14,21 @@ * limitations under the License. */ -package org.touchbit.buggy.core.testng.listeners; +package org.touchbit.buggy.core.testng; 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.config.BuggyConfig; +import org.touchbit.buggy.core.log.BuggyLoggers; 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.Arrays; +import java.util.Date; +import java.util.StringJoiner; import java.util.concurrent.atomic.AtomicInteger; /** @@ -58,13 +58,13 @@ public abstract class BaseBuggyExecutionListener implements BuggyListener, IExec public void onExecutionStart() { startTime = new Date().getTime(); if (testLog == null) { - testLog = BuggyLog.test(); + testLog = BuggyLoggers.SIFTING; } if (frameworkLog == null) { - frameworkLog = BuggyLog.framework(); + frameworkLog = BuggyLoggers.FRAMEWORK; } if (consoleLog == null) { - consoleLog = BuggyLog.console(); + consoleLog = BuggyLoggers.CONSOLE; } } @@ -94,16 +94,14 @@ protected Suite getSuite(ITestNGMethod method) { } 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(); + if (!"null".equalsIgnoreCase(String.valueOf(BuggyConfig.getArtifactsUrl()))) { + return BuggyConfig.getArtifactsUrl().endsWith("/") ? + BuggyConfig.getArtifactsUrl() : + BuggyConfig.getArtifactsUrl() + "/"; } else { - return "file://" + new File(c.getTestLogDir(), getInvokedMethodLogFileName(method)); + return "file://" + new File(new File(BuggyLoggers.getFrameworkLogFilePath()).getAbsolutePath() + + "/" + getInvokedMethodLogFileName(method)); } } 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/BaseTelegramNotifier.java similarity index 86% rename from buggy-core/src/main/java/org/touchbit/buggy/core/testng/listeners/BaseTelegramNotifier.java rename to buggy-core/src/main/java/org/touchbit/buggy/core/testng/BaseTelegramNotifier.java index bd2906b..4ace8c4 100644 --- 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/BaseTelegramNotifier.java @@ -14,15 +14,13 @@ * limitations under the License. */ -package org.touchbit.buggy.core.testng.listeners; +package org.touchbit.buggy.core.testng; 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.config.BuggyConfig; +import org.touchbit.buggy.core.log.BuggyLoggers; 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; @@ -34,8 +32,6 @@ @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") @@ -44,7 +40,8 @@ public BaseTelegramNotifier(final Notifier notifier) { } @Override - public void onExecutionStart() { } + public void onExecutionStart() { + } @Override public void onExecutionFinish() { @@ -54,7 +51,7 @@ public void onExecutionFinish() { } private void telegramResultNotification() { - String name = Buggy.getProgramName(); + String name = BuggyConfig.getProgramName(); StringJoiner sj; if (name == null || name.isEmpty()) { sj = new StringJoiner("\n", "Run Results:\n", "\n"); @@ -102,26 +99,25 @@ private void telegramResultNotification() { 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() + ")"); + sj.add("[Logs](" + BuggyConfig.getArtifactsUrl() + ")"); try { notifier.report(sj.toString()); } catch (Exception e) { - Buggy.incrementBuggyErrors(); - log.error("Failed to send message to Telegram.", e); + BuggyLoggers.CONSOLE.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 ) { + 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 = Buggy.getPrimaryConfig().getArtifactsUrl() + "/fixed/" + subLink; - if (value > 0 ) { + 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/listeners/BuggyExecutionListener.java b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/BuggyExecutionListener.java similarity index 83% rename from buggy-core/src/main/java/org/touchbit/buggy/core/testng/listeners/BuggyExecutionListener.java rename to buggy-core/src/main/java/org/touchbit/buggy/core/testng/BuggyExecutionListener.java index 55d109a..2c2fc09 100644 --- 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/BuggyExecutionListener.java @@ -14,22 +14,22 @@ * limitations under the License. */ -package org.touchbit.buggy.core.testng.listeners; +package org.touchbit.buggy.core.testng; 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.config.BuggyConfig; import org.touchbit.buggy.core.exceptions.CorruptedTestException; +import org.touchbit.buggy.core.log.BuggyLoggers; +import org.touchbit.buggy.core.log.ConfigurationLogger; 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.JUtils; import org.touchbit.buggy.core.utils.StringUtils; -import org.touchbit.buggy.core.utils.log.BuggyLog; import java.io.File; import java.io.IOException; @@ -37,12 +37,10 @@ import java.lang.reflect.Method; import java.util.*; +import static org.testng.ITestResult.SKIP; +import static org.testng.ITestResult.SUCCESS; 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.*; +import static org.touchbit.buggy.core.model.Status.*; /** * Listener for processing executable tests. @@ -64,6 +62,31 @@ public BuggyExecutionListener(Logger testLogger, Logger frameworkLogger, Logger consoleLog = consoleLogger; } + /** + * 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); + } + @Override public boolean isEnable() { return true; @@ -116,7 +139,7 @@ public void onTestFinish(ITestResult result) { getSteps().forEach(step -> sb.append(step).append("\n")); testLog.info("Steps:\n{}", sb); } else { - Buggy.incrementBuggyWarns(); +// Buggy.incrementBuggyWarns(); frameworkLog.warn("There are no playback steps in the test method {}", method.getName()); } testLog.info("Date: {}", new Date()); @@ -125,7 +148,7 @@ public void onTestFinish(ITestResult result) { @Override public void onAfterClass(ITestClass iTestClass) { if (getSuite(iTestClass) == null) { - Buggy.incrementBuggyErrors(); +// Buggy.incrementBuggyErrors(); frameworkLog.error("There is no @Suite annotation for the test class: {}", iTestClass.getName()); } } @@ -133,7 +156,7 @@ public void onAfterClass(ITestClass iTestClass) { @Override public void onStart(ISuite suite) { disableTestsByType(suite); - if (!Buggy.getPrimaryConfig().isForceRun()) { + if (!BuggyConfig.isForce()) { disableTestsByStatus(suite); } } @@ -145,7 +168,7 @@ public void onFinish(ISuite suite) { try { copyTestMethodLogFile(m); } catch (Exception e) { - Buggy.incrementBuggyErrors(); +// Buggy.incrementBuggyErrors(); frameworkLog.error(e.getMessage(), e); } }); @@ -155,7 +178,7 @@ public void onFinish(ISuite suite) { public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { STEPS.set(new ArrayList<>()); String methodName = getMethodName(method); - BuggyLog.setTestLogFileName(getInvokedMethodLogFileName(method)); + BuggyLoggers.setSiftingLogFilePath(getInvokedMethodLogFileName(method)); if (method.isTestMethod()) { testLog.info("Test method is running:\n{} - {}", methodName, getDescription(method)); } else { @@ -164,9 +187,9 @@ public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { if (testLog.isDebugEnabled()) { StringJoiner sj = new StringJoiner("\n", "\n", "\n"); for (Annotation annotation : getRealMethod(method).getAnnotations()) { - sj.add(annotation.toString()); + sj.add(annotation.annotationType().getTypeName()); } - testLog.trace("Declared method annotations:{}", sj); + testLog.debug("Declared method annotations:{}", sj); } } @@ -191,7 +214,7 @@ public void afterInvocation(IInvokedMethod method, ITestResult testResult) { if (details != null) { processTestMethodResult(method, testResult, details); } else { - Buggy.incrementBuggyWarns(); +// Buggy.incrementBuggyWarns(); frameworkLog.warn("The test method {} does not contain the @Details annotation", methodName); } } else { @@ -200,31 +223,6 @@ public void afterInvocation(IInvokedMethod method, ITestResult 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()) { @@ -270,7 +268,7 @@ public void processTestMethodResult(IInvokedMethod m, ITestResult testResult, De break; default: frameworkLog.error("Received unprocessed status: {}", testResult.getStatus()); - Buggy.incrementBuggyErrors(); +// Buggy.incrementBuggyErrors(); } } @@ -291,7 +289,7 @@ public void processConfigurationMethodResult(IInvokedMethod method, ITestResult methodName, testResult.getThrowable().getMessage()); break; default: - Buggy.incrementBuggyErrors(); +// Buggy.incrementBuggyErrors(); frameworkLog.error("Received unresolved status of configuration method [{}]. Status: {}", methodName, testResult.getStatus()); } @@ -315,7 +313,7 @@ public void disableTestsByStatus(ISuite suite) { } } } else { - Buggy.incrementBuggyWarns(); +// Buggy.incrementBuggyWarns(); frameworkLog.warn("The test method {} does not contain the @Details annotation", method.getMethodName()); } @@ -326,23 +324,26 @@ 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")); + List configType = BuggyConfig.getTypes(); + if (details != null) { + List methodTypes = new ArrayList<>(Arrays.asList(details.type())); + boolean matched = methodTypes.stream().anyMatch(configType::contains); + if (!configType.contains(Type.ALL) && !matched) { + method.setInvocationCount(0); + resultLog(method, Status.SKIP, buildDetailsMessage(details, details.type(), "test types")); + } } }); } 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 sourceFile = new File(getInvokedMethodLogFileName(method)); File targetFile = null; if (details == null) { if (iTestResultStatus == FAILURE || iTestResultStatus == SUCCESS_PERCENTAGE_FAILURE) { - targetFile = new File(c.getNewErrorLogDir(), getInvokedMethodLogFileName(method)); + targetFile = new File("new", getInvokedMethodLogFileName(method)); copyFile(sourceFile, targetFile); } return; @@ -351,29 +352,29 @@ public void copyTestMethodLogFile(IInvokedMethod method) throws IOException { switch (iTestResultStatus) { case ITestResult.SUCCESS: if (status.equals(EXP_FIX) || status.equals(BLOCKED)) { - targetFile = new File(c.getFixedLogDir(), getInvokedMethodLogFileName(method)); + targetFile = new File("fixed", getInvokedMethodLogFileName(method)); } if (status.equals(EXP_IMPL)) { - targetFile = new File(c.getImplementedLogDir(), getInvokedMethodLogFileName(method)); + targetFile = new File("implemented", getInvokedMethodLogFileName(method)); } break; case ITestResult.FAILURE: case ITestResult.SUCCESS_PERCENTAGE_FAILURE: switch (status) { case EXP_FIX: - targetFile = new File(c.getExpFixErrorLogDir(), getInvokedMethodLogFileName(method)); + targetFile = new File("exp_fix", getInvokedMethodLogFileName(method)); break; case EXP_IMPL: - targetFile = new File(c.getExpImplErrorLogDir(), getInvokedMethodLogFileName(method)); + targetFile = new File("exp_impl", getInvokedMethodLogFileName(method)); break; case BLOCKED: - targetFile = new File(c.getBlockedErrorLogDir(), getInvokedMethodLogFileName(method)); + targetFile = new File("blocked", getInvokedMethodLogFileName(method)); break; case CORRUPTED: - targetFile = new File(c.getCorruptedErrorLogDir(), getInvokedMethodLogFileName(method)); + targetFile = new File("corrupted", getInvokedMethodLogFileName(method)); break; default: - targetFile = new File(c.getNewErrorLogDir(), getInvokedMethodLogFileName(method)); + targetFile = new File("new", getInvokedMethodLogFileName(method)); } default: // ignore unhandled statuses @@ -384,28 +385,27 @@ public void copyTestMethodLogFile(IInvokedMethod method) throws IOException { } 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()) { + if (BuggyConfig.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(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 ((config.isPrintCause() || method.getInvocationCount() < 1) && !detailsString.isEmpty()) { + if ((BuggyConfig.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└"); + 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) + @@ -472,16 +472,16 @@ protected void increment(Status status) { } 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); - } + ConfigurationLogger.blockDelimiter(); +// 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) { +// ConfigurationLogger.blockDelimiter(); +// } int fixedCount = fixed.get() + implemented.get(); int errorCount = expFixError.get() + expImplError.get() + newError.get() + corruptedError.get() + blockedError.get(); @@ -491,7 +491,7 @@ protected void printTestStatistic() { if (errorCount > 0) { checkWarnAndPrint("Failed tests", errorCount); checkErrorAndPrint("New Errors", newError.get()); - println(CONSOLE_DELIMITER); + ConfigurationLogger.blockDelimiter(); checkWarnAndPrint("Waiting to fix a defect", expFixError.get()); checkWarnAndPrint("Waiting for implementation", expImplError.get()); checkWarnAndPrint("Blocked tests", blockedError.get()); @@ -501,14 +501,14 @@ protected void printTestStatistic() { consoleLog.info(result); } if (fixedCount > 0) { - println(CONSOLE_DELIMITER); + ConfigurationLogger.blockDelimiter(); checkDebugAndPrint("Fixed cases", fixed.get()); checkDebugAndPrint("Implemented cases", implemented.get()); } - println(CONSOLE_DELIMITER); + ConfigurationLogger.blockDelimiter(); consoleLog.info(StringUtils.dotFiller("Execution time", 47, org.apache.commons.lang3.time.DurationFormatUtils .formatDuration(finishTime - startTime, "HH:mm:ss,SSS"))); - println(CONSOLE_DELIMITER); + ConfigurationLogger.blockDelimiter(); } protected void checkDebugAndPrint(String msg, int count) { 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/BuggyListener.java similarity index 63% rename from buggy-core/src/main/java/org/touchbit/buggy/core/testng/listeners/BuggyListener.java rename to buggy-core/src/main/java/org/touchbit/buggy/core/testng/BuggyListener.java index 035be73..f7b85f5 100644 --- 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/BuggyListener.java @@ -1,13 +1,11 @@ -package org.touchbit.buggy.core.testng.listeners; +package org.touchbit.buggy.core.testng; -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/IntellijIdeaTestNgPluginListener.java b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/IntellijIdeaTestNgPluginListener.java new file mode 100644 index 0000000..be0c6fc --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/IntellijIdeaTestNgPluginListener.java @@ -0,0 +1,43 @@ +/* + * 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.ITestNGListener; +import org.touchbit.buggy.core.log.BuggyLoggers; +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 BuggyExecutionListener implements ITestNGListener { + + public IntellijIdeaTestNgPluginListener() { + if (JUtils.isJetBrainsIdeRun()) { + BuggyLoggers.SIFTING.info("IntellijIdeaTestNgPluginListener enabled"); + JUtils.initBuggyConfigurationYml(); + } + } + + @Override + public final boolean isEnable() { + return JUtils.isJetBrainsIdeRun(); + } + +} 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 048762d..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.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.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/IntellijIdeaTestNgPluginListener.java b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/listeners/IntellijIdeaTestNgPluginListener.java deleted file mode 100644 index 8e5eb8c..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/log/ANSI.java b/buggy-core/src/main/java/org/touchbit/buggy/core/utils/ANSI.java similarity index 84% rename from buggy-core/src/main/java/org/touchbit/buggy/core/utils/log/ANSI.java rename to buggy-core/src/main/java/org/touchbit/buggy/core/utils/ANSI.java index ec93c34..8435b16 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/utils/log/ANSI.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/utils/ANSI.java @@ -1,4 +1,4 @@ -package org.touchbit.buggy.core.utils.log; +package org.touchbit.buggy.core.utils; public enum ANSI { @@ -19,7 +19,7 @@ public enum ANSI { public static String unwrap(final String msg) { String resultMsg = msg; for (ANSI value : ANSI.values()) { - resultMsg = msg.replace(value.symbol, ""); + resultMsg = resultMsg.replace(value.symbol, ""); } return resultMsg; } 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 1d6bbcf..0000000 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/utils/BuggyUtils.java +++ /dev/null @@ -1,158 +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.goal.component.Component; -import org.touchbit.buggy.core.goal.interfaze.Interface; -import org.touchbit.buggy.core.goal.service.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()); - } - - 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..f659fc5 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); @@ -130,8 +136,4 @@ public static Properties readPropertiesFileFromResource(final String file) { } } - 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 index cfe2d0b..2c5cd98 100644 --- 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 @@ -1,35 +1,88 @@ package org.touchbit.buggy.core.utils; +import org.touchbit.buggy.core.config.BuggyConfigYML; +import org.touchbit.buggy.core.exceptions.BuggyConfigurationException; +import org.touchbit.buggy.core.goal.Goal; +import org.touchbit.buggy.core.model.Suite; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; +import org.yaml.snakeyaml.representer.Representer; + 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; -import static org.touchbit.buggy.core.utils.BuggyUtils.CONSOLE_DELIMITER; -import static org.touchbit.buggy.core.utils.StringUtils.underscoreFiller; - /** * Created by Oleg Shaburov on 01.10.2020 * shaburov.o.a@gmail.com */ public class JUtils { + public static final String BUGGY_CONFIG_YML = "buggy-config.yml"; + private JUtils() { throw new IllegalStateException("Utility class. Prohibit instantiation."); } + public static void initBuggyConfigurationYml() { + Representer representer = new Representer(); + representer.getPropertyUtils().setSkipMissingProperties(true); + Yaml yaml = new Yaml(new Constructor(BuggyConfigYML.class), representer); + InputStream inputStream = JUtils.getCurrentThreadClassLoader().getResourceAsStream(BUGGY_CONFIG_YML); + yaml.load(inputStream); + } + + 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()); + } + + public static < U extends Exception> Object newInstance(String cName, BiFunction s) throws U { + try { + Class aClass = getCurrentThreadClassLoader().loadClass(cName); + return newInstance(aClass, s); + } catch (ClassNotFoundException 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 isJetBrainsIdeRun() { - RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean(); - List arguments = runtimeMxBean.getInputArguments(); - return arguments.stream() - .anyMatch(v -> v.startsWith("-javaagent") && - (v.contains("JetBrains") || v.contains("IDEA") || v.contains("idea"))); + for (StackTraceElement stackTraceElement : Thread.currentThread().getStackTrace()) { + if (stackTraceElement.toString().contains("com.intellij.rt.testng")) { + return true; + } + } + return false; } public static String getRunPath() { @@ -99,8 +152,7 @@ public static Set> getAllInterfacesForClassAsSet(Class clazz, ClassL private static boolean isLoadable(Class clazz, ClassLoader classLoader) { try { return (clazz == classLoader.loadClass(clazz.getName())); - } - catch (ClassNotFoundException ignore) { + } catch (ClassNotFoundException ignore) { return false; } } 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 index 1d9c06f..c4c42f2 100644 --- 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 @@ -29,9 +29,11 @@ public class StringUtils { public static final int STRING_LEN = 47; - public static final String BLOCK = "="; public static final String STEP = "\u2014"; - public static final String DOT = "."; + + private StringUtils() { + throw new IllegalStateException("Utility class. Prohibit instantiation."); + } public static String underscoreFiller(Object prefix, int i) { return underscoreFiller(prefix, i, null); @@ -45,18 +47,10 @@ public static String dotFiller(Object prefix, int i) { return dotFiller(prefix, i, null); } - public static String dotFiller(Object prefix) { - return dotFiller(prefix, STRING_LEN, null); - } - public static String dotFiller(Object prefix, int i, Object suffix) { return filler(prefix, ".", i, suffix); } - public static String dotFiller(Object prefix, Object suffix) { - return filler(prefix, ".", STRING_LEN, suffix); - } - public static String filler(Object prefix, String symbol, int i) { return filler(prefix, symbol, i, null); } @@ -131,29 +125,6 @@ public static void sPrint() { println(filler(STEP)); } - public static void bPrint() { - println(filler(BLOCK)); - } - - public static void fPrint(String symbol) { - println(filler(symbol)); - } - - public static void fPrint(Object prefix, String symbol, Object postfix) { - println(filler(prefix, symbol, postfix)); - } - - public static void cPrint(String msg) { - if (msg != null && !msg.isEmpty()) { - int diff = STRING_LEN - msg.length(); - if (diff > 0) { - int indent = diff / 2; - String result = filler("", " ", indent, "") + msg; - println(result); - } - } - } - public static void println(String msg) { println(msg, null); } @@ -166,8 +137,4 @@ public static void println(String msg, Throwable t) { 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 e861afe..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.sPrint(); - StringUtils.fPrint("Logger", " ", "Level"); - StringUtils.sPrint(); - 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..8de0904 --- /dev/null +++ b/buggy-core/src/main/resources/buggy-config.yml @@ -0,0 +1,18 @@ +programName: Buggy +help: false +force: true +printSuite: true +printCause: true +printLog: true +printLogOnlyFail: false +threads: 50 +artifactsUrl: null +parallelMode: 'METHODS' +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 \ 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-spring-boot-starter/src/main/resources/buggy-logback.xml b/buggy-core/src/main/resources/buggy-logback.xml similarity index 84% rename from buggy-spring-boot-starter/src/main/resources/buggy-logback.xml rename to buggy-core/src/main/resources/buggy-logback.xml index c8201fe..e8a5b63 100644 --- a/buggy-spring-boot-starter/src/main/resources/buggy-logback.xml +++ b/buggy-core/src/main/resources/buggy-logback.xml @@ -7,13 +7,13 @@ - + ${logging.file.path}/Framework.log - + @@ -24,7 +24,7 @@ ${logging.file.path}/${sifting.log.file.path} - + @@ -48,7 +48,7 @@ - + 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 ee97853..39c966b 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,9 +17,9 @@ package org.touchbit.buggy.core.config; import org.testng.annotations.Test; +import org.touchbit.buggy.core.BaseBuggyTest; import org.touchbit.buggy.core.model.Details; import org.touchbit.buggy.core.model.Suite; -import org.touchbit.buggy.core.test.BaseBuggyTest; /** * Created by Oleg Shaburov on 20.09.2018 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..a88cf1e 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.BaseBuggyTest; import org.touchbit.buggy.core.model.Details; -import org.touchbit.buggy.core.test.BaseBuggyTest; /** * Created by Oleg Shaburov on 20.09.2018 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 022f9e6..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.goal.component.Component; -import org.touchbit.buggy.core.goal.service.Service; - -import java.util.ArrayList; -import java.util.List; /** * Created by Oleg Shaburov on 16.09.2018 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/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 c6063c6..4547dc4 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,6 @@ 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 +8,35 @@ 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.Status; import org.touchbit.buggy.core.model.Suite; import org.touchbit.buggy.core.model.Type; -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.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.io.IOException; 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 +45,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 +61,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,6 +132,133 @@ protected static ITestResult getMockITestResult(Integer status) { return iTestResult; } + @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); + } + + protected static Details getDetails(Status status, Type type, String... issue) { + return getDetails(new long[0], status, new Type[]{type}, issue); + } + + protected static Details getDetails(long[] ids, Status status, Type[] type, String... issue) { + return new Details() { + @Override + public long[] id() { + return ids; + } + + @Override + public Status status() { + return status; + } + + @Override + public String[] issue() { + return issue; + } + + @Override + public String[] bug() { + return new String[]{}; + } + + @Override + public Type[] type() { + return type; + } + + @Override + public Class annotationType() { + return Details.class; + } + }; + } + + protected static Suite getSuite() { + return 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 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); } @@ -354,72 +344,4 @@ public void increment(Status 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); - } - - protected static Details getDetails(Status status, Type type, String... issue) { - return getDetails(new long[0], status, new Type[]{type}, issue); - } - - protected static Details getDetails(long[] ids, Status status, Type[] type, String... issue) { - return new Details() { - @Override - public long[] id() { return ids; } - @Override - public Status status() { return status; } - @Override - public String[] issue() { return issue; } - - @Override - public String[] bug() { - return new String[] {}; - } - - @Override - public Type[] type() { return type; } - @Override - public Class annotationType() { return Details.class; } - }; - } - - protected static Suite getSuite() { - return 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 purpose() { - return UUID.randomUUID().toString(); - } - }; - } - } 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..c4d6565 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,52 +28,53 @@ @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() { + } BuggyTest(final Logger logger) { super(logger); 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 e982a70..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, purpose = "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, purpose = "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 21b1f0a..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 @@ -24,7 +24,7 @@ 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 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 c41f6a6..f876332 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,20 @@ 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.BuggyConfig; 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.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 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 +38,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 = BuggyConfig.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")); + BuggyConfig.setThreads(10); + assertThat(BuggyConfig.getThreads(), is(10)); } finally { - Buggy.getPrimaryConfig().setLogPath(log); + BuggyConfig.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() { - List services = Buggy.getPrimaryConfig().getServices(); + List services = BuggyConfig.getServices(); try { - List newServices = new ArrayList() {{ add(new TestService()); }}; - Buggy.getPrimaryConfig().setServices(newServices); - assertThat(Buggy.getPrimaryConfig().getServices(), is(newServices)); + List newServices = new ArrayList() {{ + add(new TestService()); + }}; + BuggyConfig.setServices(newServices); + assertThat(BuggyConfig.getServices(), is(newServices)); } finally { - Buggy.getPrimaryConfig().setServices(services); + BuggyConfig.setServices(services); } } @Test @DisplayName("Check PrimaryConfig.setInterfaces(List interfaces)") void unitTest_20180919195248() { - List interfaces = Buggy.getPrimaryConfig().getInterfaces(); + List interfaces = BuggyConfig.getInterfaces(); try { - List newInterfaces = new ArrayList() {{ add(new TestInterface()); }}; - Buggy.getPrimaryConfig().setInterfaces(newInterfaces); - assertThat(Buggy.getPrimaryConfig().getInterfaces(), is(newInterfaces)); + List newInterfaces = new ArrayList() {{ + add(new TestInterface()); + }}; + BuggyConfig.setInterfaces(newInterfaces); + assertThat(BuggyConfig.getInterfaces(), is(newInterfaces)); } finally { - Buggy.getPrimaryConfig().setInterfaces(interfaces); + BuggyConfig.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); - } - } +// @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 = BuggyConfig.getArtifactsUrl(); try { assertThat(String.valueOf(buildLogUrl), is("null")); - Buggy.getPrimaryConfig().setArtifactsUrl("BuildUrl"); - assertThat(Buggy.getPrimaryConfig().getArtifactsUrl(), is("BuildUrl")); + BuggyConfig.setArtifactsUrl("BuildUrl"); + assertThat(BuggyConfig.getArtifactsUrl(), is("BuildUrl")); } finally { - Buggy.getPrimaryConfig().setArtifactsUrl(buildLogUrl); + BuggyConfig.setArtifactsUrl(buildLogUrl); } } @Test @DisplayName("Check PrimaryConfig.setPrintSuite(Boolean printSuite)") void unitTest_20180919201621() { - boolean printSuite = Buggy.getPrimaryConfig().isPrintSuite(); + boolean printSuite = BuggyConfig.isPrintSuite(); try { assertThat(printSuite, is(false)); - Buggy.getPrimaryConfig().setPrintSuite(true); - assertThat(Buggy.getPrimaryConfig().isPrintSuite(), is(true)); + BuggyConfig.setPrintSuite(true); + assertThat(BuggyConfig.isPrintSuite(), is(true)); } finally { - Buggy.getPrimaryConfig().setPrintSuite(printSuite); + BuggyConfig.setPrintSuite(printSuite); } } @Test @DisplayName("Check PrimaryConfig.setPrintCause(Boolean printCause)") void unitTest_20180919201754() { - boolean printCause = Buggy.getPrimaryConfig().isPrintCause(); + boolean printCause = BuggyConfig.isPrintCause(); try { assertThat(printCause, is(false)); - Buggy.getPrimaryConfig().setPrintCause(true); - assertThat(Buggy.getPrimaryConfig().isPrintCause(), is(true)); + BuggyConfig.setPrintCause(true); + assertThat(BuggyConfig.isPrintCause(), is(true)); } finally { - Buggy.getPrimaryConfig().setPrintCause(printCause); + BuggyConfig.setPrintCause(printCause); } } @Test @DisplayName("Check PrimaryConfig.setPrintLogFile(Boolean printLog)") void unitTest_20180919201844() { - boolean printLogFile = Buggy.getPrimaryConfig().isPrintLogFile(); + boolean printLogFile = BuggyConfig.isPrintLog(); try { assertThat(printLogFile, is(false)); - Buggy.getPrimaryConfig().setPrintLogFile(true); - assertThat(Buggy.getPrimaryConfig().isPrintLogFile(), is(true)); + BuggyConfig.setPrintLog(true); + assertThat(BuggyConfig.isPrintLog(), is(true)); } finally { - Buggy.getPrimaryConfig().setPrintLogFile(printLogFile); + BuggyConfig.setPrintLog(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)); - } finally { - Buggy.getPrimaryConfig().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 = 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"; - } - - } - + assertThat(BuggyConfig.isVersion(), is(false)); + BuggyConfig.setVersion(true); + assertThat(BuggyConfig.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 dad1b53..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,31 +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.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.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.IOHelper; - -import java.io.File; -import java.io.IOException; -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.*; +import org.touchbit.buggy.core.tests.BaseUnitTest; /** * Created by Oleg Shaburov on 16.09.2018 @@ -34,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 { 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 875a575..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; 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..5fe5bc9 --- /dev/null +++ b/buggy-core/src/test/java/org/touchbit/buggy/core/tests/testng/BaseBuggyExecutionListenerTests.java @@ -0,0 +1,97 @@ +package org.touchbit.buggy.core.tests.testng; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.testng.ITestNGMethod; +import org.touchbit.buggy.core.config.BuggyConfig; +import org.touchbit.buggy.core.testng.BaseBuggyExecutionListener; +import org.touchbit.buggy.core.tests.BaseUnitTest; + +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 = 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) { + 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/BaseTelegramNotifierTests.java similarity index 87% rename from buggy-core/src/test/java/org/touchbit/buggy/core/tests/testng/listeners/BaseTelegramNotifierTests.java rename to buggy-core/src/test/java/org/touchbit/buggy/core/tests/testng/BaseTelegramNotifierTests.java index 4ab6ba7..8d6bafc 100644 --- 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/BaseTelegramNotifierTests.java @@ -14,18 +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.touchbit.buggy.core.tests.BaseUnitTest; -import org.touchbit.buggy.core.Buggy; -import org.touchbit.buggy.core.exceptions.CorruptedTestException; +import org.touchbit.buggy.core.config.BuggyConfig; import org.touchbit.buggy.core.model.Notifier; -import org.touchbit.buggy.core.testng.listeners.BaseTelegramNotifier; +import org.touchbit.buggy.core.testng.BaseTelegramNotifier; +import org.touchbit.buggy.core.tests.BaseUnitTest; -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; @@ -78,7 +75,7 @@ public boolean isEnable() { "`--------------------------------`\n" + "Test execution time: *00:00:00*\n" + "[Logs](null)\n")); - Buggy.setProgramName(""); + BuggyConfig.setProgramName(""); sb = new StringBuilder(); notifier = sb::append; telegram = new BaseTelegramNotifier(notifier) { @@ -123,7 +120,7 @@ public boolean isEnable() { @DisplayName("Check report with program name") void unitTest_20180920231126() { StringBuilder sb = new StringBuilder(); - Buggy.setProgramName("unitTest_20180920231126"); + BuggyConfig.setProgramName("unitTest_20180920231126"); Notifier notifier = sb::append; BaseTelegramNotifier telegram = new BaseTelegramNotifier(notifier) { @Override @@ -168,9 +165,9 @@ public boolean isEnable() { @DisplayName("Check report with ArtifactsUrl") void unitTest_20180920231553() { StringBuilder sb = new StringBuilder(); - Buggy.setProgramName(null); + BuggyConfig.setProgramName(null); Notifier notifier = sb::append; - Buggy.getPrimaryConfig().setArtifactsUrl("http://build.url"); + BuggyConfig.setArtifactsUrl("http://build.url"); try { BaseTelegramNotifier telegram = new BaseTelegramNotifier(notifier) { @Override @@ -208,26 +205,26 @@ public boolean isEnable() { "Test execution time: *00:00:00*\n" + "[Logs](http://build.url)\n")); } finally { - Buggy.getPrimaryConfig().setArtifactsUrl(null); + 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 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") @@ -236,7 +233,9 @@ void unitTest_20180920230951() { Notifier notifier = sb::append; BaseTelegramNotifier telegram = new BaseTelegramNotifier(notifier) { @Override - public boolean isEnable() { return false; } + public boolean isEnable() { + return false; + } }; telegram.onExecutionStart(); telegram.onExecutionFinish(); 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/BuggyExecutionListenerTests.java similarity index 55% rename from buggy-core/src/test/java/org/touchbit/buggy/core/tests/testng/listeners/BuggyExecutionListenerTests.java rename to buggy-core/src/test/java/org/touchbit/buggy/core/tests/testng/BuggyExecutionListenerTests.java index 6030017..e1517bc 100644 --- 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/BuggyExecutionListenerTests.java @@ -14,7 +14,7 @@ * 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.Nested; @@ -24,33 +24,25 @@ 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.exceptions.ExpectedImplementationException; 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.Status; +import org.touchbit.buggy.core.model.Suite; +import org.touchbit.buggy.core.testng.BuggyExecutionListener; 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.*; +import static org.touchbit.buggy.core.model.Type.SMOKE; /** * Created by Oleg Shaburov on 21.09.2018 @@ -163,7 +155,9 @@ void unitTest_20180921183125() { void unitTest_20180921183228() { BuggyExecutionListener listener = new BuggyExecutionListener(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); ITestResult iTestResult = getMockITestResult(1); - BuggyExecutionListener.setSteps(new ArrayList() {{ add("steppp"); }}); + BuggyExecutionListener.setSteps(new ArrayList() {{ + add("steppp"); + }}); listener.onTestFinish(iTestResult); } @@ -184,58 +178,58 @@ void unitTest_20180921184448() { 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 onStart() if forceRun disabled") +// void unitTest_20180922083207() { +// Type configType = BuggyConfig.getTypes(); +// boolean isForceRun = BuggyConfig.isForce(); +// try { +// BuggyConfig.setTypes(MODULE); +// BuggyConfig.setForce(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 { +// BuggyConfig.setType(configType); +// BuggyConfig.setForceRun(isForceRun); +// } +// } +// +// @Test +// @DisplayName("Check onStart() if forceRun enabled") +// void unitTest_20180922085022() { +// Type configType = BuggyConfig.getType(); +// boolean isForceRun = BuggyConfig.isForceRun(); +// try { +// BuggyConfig.setType(MODULE); +// BuggyConfig.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 { +// BuggyConfig.setType(configType); +// BuggyConfig.setForceRun(isForceRun); +// } +// } @Test @DisplayName("Check onFinish()") @@ -249,6 +243,94 @@ void unitTest_20180922085205() { listener.onFinish(suite); } + @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" + )); + } + @Nested() @DisplayName("beforeInvocation() tests") class BeforeInvocationTests extends BaseUnitTest { @@ -465,7 +547,7 @@ void unitTest_20180922023815() { 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() { @@ -840,102 +922,102 @@ void unitTest_20180922040055() { 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())); - } +// +// @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)); - } +// +// @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)); +// } } @@ -943,242 +1025,242 @@ void unitTest_20180922061516() { @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)); - } +// @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)); +// } } @@ -1186,71 +1268,71 @@ void unitTest_20180922070623() { @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); - } - } +// @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 = BuggyConfig.getType(); +// try { +// BuggyConfig.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 { +// BuggyConfig.setType(configType); +// } +// } +// +// @Test +// @DisplayName("Check disabling the test, if config !Type.isIncludeOrEquals(testType)") +// void unitTest_20180922081522() { +// Type configType = BuggyConfig.getType(); +// try { +// BuggyConfig.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 { +// BuggyConfig.setType(configType); +// } +// } } @@ -1295,33 +1377,33 @@ void unitTest_20181018183643() throws Exception { 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.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") @@ -1336,188 +1418,188 @@ void unitTest_20181018205529() throws Exception { 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 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") @@ -1604,106 +1686,106 @@ public String purpose() { 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 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() { +// BuggyConfig.setPrintSuite(true); +// BuggyConfig.setPrintCause(false); +// BuggyConfig.setPrintLog(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() { +// BuggyConfig.setPrintSuite(false); +// BuggyConfig.setPrintCause(true); +// BuggyConfig.setPrintLog(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() { +// BuggyConfig.setPrintCause(false); +// BuggyConfig.setPrintSuite(false); +// BuggyConfig.setPrintLog(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() { +// BuggyConfig.setPrintCause(true); +// BuggyConfig.setPrintSuite(true); +// BuggyConfig.setPrintLog(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") @@ -1964,229 +2046,141 @@ private void assertTestStatusCount(UnitTestBuggyExecutionListener listener, } } - - @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)); - } +// +// @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/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 b7cafd4..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.goal.component.AllComponents; -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.goal.component.Component; -import org.touchbit.buggy.core.goal.interfaze.Interface; -import org.touchbit.buggy.core.goal.service.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().purpose(), 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().purpose(), 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().purpose(), 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 AllComponents.class; } - @Override - public Class service() { return TestService.class; } - @Override - public Class interfaze() { return TestInterface.class; } - @Override - public String purpose() { 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 purpose() { 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/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 0625c1b..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,346 +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.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.model.Suite; +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.testng.TestSuite; -import org.touchbit.buggy.core.utils.BuggyUtils; +import org.touchbit.buggy.core.model.Suite; +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("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 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, 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 {} +@DisplayName("JUtils Tests") +class JUtilsTests extends BaseUnitTest { private static final Suite SUITE_1 = new Suite() { @@ -369,7 +56,6 @@ public String purpose() { return "TestTask"; } }; - private static final Suite SUITE_2 = new Suite() { @Override @@ -397,7 +83,6 @@ public String purpose() { return "TestTask"; } }; - private static final Suite PRIVATE_SUITE = new Suite() { @Override @@ -426,6 +111,70 @@ public String purpose() { } }; + @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 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..7b02272 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,15 +18,15 @@ @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(\"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\")") @@ -46,15 +44,15 @@ void unitTest_20180915215744() { is("The following file can not be found in the project resources: " + 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(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 +103,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 index a83d5f1..64c6f89 100644 --- 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 @@ -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.AssertionException; +import org.touchbit.buggy.core.tests.BaseUnitTest; import org.touchbit.buggy.core.utils.StringUtils; import static org.hamcrest.MatcherAssert.assertThat; @@ -143,7 +143,7 @@ void unitTest_20180914223459() { } @Test - @DisplayName("Check BuggyUtils constructor") + @DisplayName("Check JUtils 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 index 3311325..e4121c6 100644 --- a/buggy-core/src/test/resources/log4j2.xml +++ b/buggy-core/src/test/resources/log4j2.xml @@ -39,7 +39,7 @@ - + @@ -51,7 +51,7 @@ - + diff --git a/buggy-feign/pom.xml b/buggy-feign/pom.xml index b5af225..26872b0 100644 --- a/buggy-feign/pom.xml +++ b/buggy-feign/pom.xml @@ -1,6 +1,6 @@ - 4.0.0 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/goals/API.java b/buggy-min-example/src/main/java/org/touchbit/buggy/example/min/goals/API.java deleted file mode 100644 index 1308137..0000000 --- a/buggy-min-example/src/main/java/org/touchbit/buggy/example/min/goals/API.java +++ /dev/null @@ -1,32 +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.goals; - -import org.touchbit.buggy.core.goal.interfaze.Interface; - -/** - * Created by Oleg Shaburov on 18.09.2018 - * shaburov.o.a@gmail.com - */ -public class API extends Interface { - - @Override - public String getDescription() { - return "REST API"; - } - -} 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 b1f029c..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, purpose = "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..355dfc5 100644 --- a/buggy-okhttp/pom.xml +++ b/buggy-okhttp/pom.xml @@ -1,6 +1,6 @@ - 4.0.0 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 index 0979021..c7c3445 100644 --- a/buggy-spring-boot-starter-example/pom.xml +++ b/buggy-spring-boot-starter-example/pom.xml @@ -1,6 +1,6 @@ - 4.0.0 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 index 3ddbb66..ee36716 100644 --- 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 @@ -1,15 +1,20 @@ package org.touchbit.buggy.spring.boot.starter.example; import org.springframework.boot.SpringApplication; +import org.touchbit.buggy.core.goal.component.DefaultComponent; import org.touchbit.buggy.core.goal.interfaze.API; import org.touchbit.buggy.spring.boot.starter.BuggyRunner; -import org.touchbit.buggy.core.config.BuggyConfig; +import org.touchbit.buggy.spring.boot.starter.jcommander.BuggyJCommand; public class ExampleBuggyRunner extends BuggyRunner { static { - BuggyConfig.setForce(true); - BuggyConfig.setInterfaces(API.class); + BuggyJCommand.setForce(true); + BuggyJCommand.setInterfaces(API.class); + BuggyJCommand.setPrintLog(true); + BuggyJCommand.setPrintSuite(true); + BuggyJCommand.setPrintCause(true); + BuggyJCommand.setComponents(DefaultComponent.class); } public static void main(String[] args) { diff --git a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleTests.java b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleTests.java index a3e8d13..920832b 100644 --- a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleTests.java +++ b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleTests.java @@ -1,7 +1,23 @@ package org.touchbit.buggy.spring.boot.starter.example; +import org.testng.annotations.Test; +import org.touchbit.buggy.core.BaseBuggyTest; +import org.touchbit.buggy.core.config.BuggyConfig; +import org.touchbit.buggy.core.model.Details; import org.touchbit.buggy.core.model.Suite; @Suite() -public class ExampleTests { +public class ExampleTests extends BaseBuggyTest { + + @Test + @Details + public void test_1() { + System.out.println("test_1" + BuggyConfig.isForce()); + System.out.println("test_1" + BuggyConfig.isPrintLog()); + System.out.println("test_1" + BuggyConfig.getComponents()); + System.out.println("test_1" + BuggyConfig.getServices()); + System.out.println("test_1" + BuggyConfig.getInterfaces()); + System.out.println("test_1" + BuggyConfig.getTypes()); + } + } diff --git a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleTests2.java b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleTests2.java index 86694e1..add8823 100644 --- a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleTests2.java +++ b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleTests2.java @@ -1,8 +1,18 @@ package org.touchbit.buggy.spring.boot.starter.example; +import org.testng.annotations.Test; import org.touchbit.buggy.core.goal.interfaze.API; +import org.touchbit.buggy.core.model.Details; +import org.touchbit.buggy.core.model.Status; import org.touchbit.buggy.core.model.Suite; @Suite(interfaze = API.class) public class ExampleTests2 { + + @Test + @Details(status = Status.EXP_FIX) + public void test_2() { + + } + } diff --git a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleTests3.java b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleTests3.java new file mode 100644 index 0000000..5457539 --- /dev/null +++ b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleTests3.java @@ -0,0 +1,18 @@ +package org.touchbit.buggy.spring.boot.starter.example; + +import org.testng.annotations.Test; +import org.touchbit.buggy.core.exceptions.CorruptedTestException; +import org.touchbit.buggy.core.goal.interfaze.API; +import org.touchbit.buggy.core.model.Details; +import org.touchbit.buggy.core.model.Suite; + +@Suite(interfaze = API.class) +public class ExampleTests3 { + + @Test + @Details + public void test_3() { + throw new CorruptedTestException(" >>> ? "); + } + +} 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 index bc32390..2bed25f 100644 --- 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 @@ -1,9 +1,9 @@ package org.touchbit.buggy.spring.boot.starter.example.conf; import com.beust.jcommander.Parameter; -import org.touchbit.buggy.core.config.JCConfiguration; +import org.touchbit.buggy.spring.boot.starter.jcommander.JCommand; -public class ExampleConfiguration implements JCConfiguration { +public class ExampleConfiguration implements JCommand { @Parameter(names = {"--example-host"}, description = "Example host.") // @Parameter(names = {"-f"}, description = "Example host.") 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 index b81d02e..b923bb7 100644 --- 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 @@ -3,25 +3,30 @@ import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.boot.ApplicationArguments; -import org.springframework.boot.ApplicationRunner; +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.BuggyConfig; 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.testng.listeners.BuggyListener; -import org.touchbit.buggy.core.utils.log.BuggyLoggers; -import org.touchbit.buggy.core.utils.log.ConfigurationLogger; +import org.touchbit.buggy.core.log.BuggyLoggers; +import org.touchbit.buggy.core.log.ConfigurationLogger; +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.BuggyJCommand; -import java.util.Set; +import java.util.*; import static org.touchbit.buggy.spring.boot.starter.conf.Qualifiers.*; @SpringBootApplication -public class BuggyRunner implements ApplicationRunner { +public class BuggyRunner implements CommandLineRunner { private Set allBuggyListeners; private Set enabledBuggyListeners; @@ -36,21 +41,6 @@ public class BuggyRunner implements ApplicationRunner { private Set availableInterfaces; private TestNG testNG = new TestNG(); - @Override - public void run(ApplicationArguments args) { - TestNG testNG = getTestNG(); - try { - testNG.run(); - if (BuggyConfig.getStatus() != null) { - exit(BuggyConfig.getStatus()); - } - exit(testNG.getStatus()); - } catch (Exception e) { - e.printStackTrace(); - exit(1, "TestNG safely died."); - } - } - public static void exit(String message, Exception e) { if (e != null) { exit(1, message, e); @@ -74,7 +64,7 @@ public static void exit(int status, String message, Exception e) { if (status == 0) { ConfigurationLogger.info(message); } else { - if (BuggyLoggers.F_LOG == null) { + if (BuggyLoggers.FRAMEWORK == null) { MDC.put("print.console.stacktrace", "true"); } else { String frameworkLogFilePath = BuggyLoggers.getFrameworkLogFilePath(); @@ -92,6 +82,72 @@ public static void exit(int status, String message, Exception e) { System.exit(status); } + @Override + public void run(String... args) { + Map>> testClassesBySuitesMap = getTestClassesBySuitesMap(filteredTestClasses); + List xmlSuites = getXmlSuites(testClassesBySuitesMap); + TestNG testNG = getTestNG(); + try { + testNG.setParallel(BuggyConfig.getParallelMode().getTestNGMode()); + testNG.setSuiteThreadPoolSize(xmlSuites.isEmpty() ? 1 : xmlSuites.size()); + testNG.setUseDefaultListeners(false); + for (BuggyListener enabledBuggyListener : enabledBuggyListeners) { + testNG.addListener(enabledBuggyListener); + } + testNG.setXmlSuites(xmlSuites); + testNG.run(); + if (BuggyJCommand.getExitStatus() != null) { + exit(BuggyJCommand.getExitStatus()); + } + exit(testNG.getStatus()); + } catch (Exception e) { + exit(1, "TestNG safely died.", e); + } + } + + 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(BuggyConfig.getParallelMode().getTestNGMode()); + xmlSuite.setThreadCount(BuggyConfig.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; } @@ -209,5 +265,4 @@ public Set getAvailableInterfaces() { 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/BuggyConfiguration.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/BuggyConfiguration.java index d2fd0e8..f6c6f79 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/BuggyConfiguration.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/BuggyConfiguration.java @@ -13,10 +13,10 @@ 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.log.ConfigurationLogger; import org.touchbit.buggy.core.model.Suite; -import org.touchbit.buggy.core.testng.listeners.BuggyListener; +import org.touchbit.buggy.core.testng.BuggyListener; import org.touchbit.buggy.core.utils.JUtils; -import org.touchbit.buggy.core.utils.log.ConfigurationLogger; import org.touchbit.buggy.spring.boot.starter.BuggyRunner; import javax.annotation.PostConstruct; 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 index 539c581..16ab009 100644 --- 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 @@ -11,10 +11,11 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.touchbit.buggy.core.config.BuggyConfig; -import org.touchbit.buggy.core.config.JCConfiguration; +import org.touchbit.buggy.core.log.ConfigurationLogger; import org.touchbit.buggy.core.utils.JUtils; -import org.touchbit.buggy.core.utils.log.ConfigurationLogger; import org.touchbit.buggy.spring.boot.starter.BuggyRunner; +import org.touchbit.buggy.spring.boot.starter.jcommander.BuggyJCommand; +import org.touchbit.buggy.spring.boot.starter.jcommander.JCommand; import javax.annotation.PostConstruct; import java.lang.reflect.Field; @@ -25,7 +26,7 @@ /** * {@link JCommander} spring boot configuration class. - * {@link ComponentScan} searches for all implementations of the {@link JCConfiguration} 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 @@ -37,20 +38,20 @@ public class JCommanderConfiguration implements IConfiguration { private final JCommander jCommander; - private final Set jcConfigurations = new LinkedHashSet<>(); + private final Set JCommands = new LinkedHashSet<>(); private final ApplicationProperties properties; private final String[] args; - private final Map, JCConfiguration> buggyConfigurations = new HashMap<>(); + private final Map, JCommand> buggyConfigurations = new HashMap<>(); private final boolean isJCommanderConfigured; public JCommanderConfiguration(final ApplicationProperties properties, final ApplicationArguments args) { this.properties = properties; this.args = args.getSourceArgs(); beforeConfiguration(); - this.jcConfigurations.addAll(scanBuggyConfig()); + this.JCommands.addAll(scanBuggyConfig()); scanJCConfigurations().stream() - .filter(i -> !(i instanceof BuggyConfig)) - .forEach(this.jcConfigurations::add); + .filter(i -> !(i instanceof BuggyJCommand)) + .forEach(this.JCommands::add); this.jCommander = buildJCommander(); parseArguments(); isJCommanderConfigured = true; @@ -74,7 +75,7 @@ public void postConstruct() { jCommander.usage(); BuggyRunner.exit(0); } - if (BuggyConfig.getVersion()) { + if (BuggyConfig.isVersion()) { ConfigurationLogger.stepDelimiter(); ConfigurationLogger.centerBold("Version info"); JUtils.getBuggyManifest().forEach(ConfigurationLogger::dotPlaceholder); @@ -83,27 +84,27 @@ public void postConstruct() { printConfigurationsParams(buggyConfigurations); } - private Set scanBuggyConfig() { + private Set scanBuggyConfig() { final boolean useDefaultFilters = false; final String basePackage = "org.touchbit.buggy.core.config"; - final Set defs = scanBeanDefinitions(useDefaultFilters, basePackage, BuggyConfig.class); - return getBeanDefinitionInstances(defs, BuggyConfig.class); + final Set defs = scanBeanDefinitions(useDefaultFilters, basePackage, BuggyJCommand.class); + return getBeanDefinitionInstances(defs, BuggyJCommand.class); } - public Set scanJCConfigurations() { + 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, JCConfiguration.class)); + defs.addAll(scanBeanDefinitions(false, basePackage, JCommand.class)); } - return getBeanDefinitionInstances(defs, JCConfiguration.class); + return getBeanDefinitionInstances(defs, JCommand.class); } private JCommander buildJCommander() { JCommander jCommander = new JCommander(); - for (JCConfiguration config : jcConfigurations) { + for (JCommand config : JCommands) { buggyConfigurations.put(config.getClass(), config); checkConfiguration(config); try { @@ -141,11 +142,11 @@ public boolean isBuggyConfigured() { } @Bean() - public Map, JCConfiguration> getBuggyConfigurations() { + public Map, JCommand> getBuggyConfigurations() { return buggyConfigurations; } - public void checkConfiguration(JCConfiguration config) { + public void checkConfiguration(JCommand config) { for (Field field : JUtils.getFields(config)) { Parameter parameter = field.getAnnotation(Parameter.class); if (parameter != null && !Modifier.isStatic(field.getModifiers())) { @@ -186,14 +187,14 @@ public void checkConfiguration(JCConfiguration config) { } } - public void printConfigurationsParams(Map, JCConfiguration> configs) { - for (JCConfiguration autowiredConfig : jcConfigurations) { - JCConfiguration config = configs.get(autowiredConfig.getClass()); + public void printConfigurationsParams(Map, JCommand> configs) { + for (JCommand autowiredConfig : JCommands) { + JCommand config = configs.get(autowiredConfig.getClass()); printConfigurationParams(config); } } - public void printConfigurationParams(JCConfiguration config) { + public void printConfigurationParams(JCommand config) { Map params = config.configurationToMap(); if (params != null && !params.isEmpty()) { ConfigurationLogger.stepDelimiter(); 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 index 4a8c815..fe26197 100644 --- 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 @@ -4,8 +4,8 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnNotWebApplication; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.touchbit.buggy.core.utils.log.BuggyLoggers; -import org.touchbit.buggy.core.utils.log.ConfigurationLogger; +import org.touchbit.buggy.core.log.BuggyLoggers; +import org.touchbit.buggy.core.log.ConfigurationLogger; import org.touchbit.buggy.spring.boot.starter.BuggyRunner; import java.io.ByteArrayOutputStream; @@ -34,7 +34,7 @@ public LogbackConfiguration(boolean isJCommanderConfigured) { PrintStream printStream = new PrintStream(stream); StatusPrinter.setPrintStream(printStream); StatusPrinter.printInCaseOfErrorsOrWarnings(BuggyLoggers.LOGGER_CONTEXT); - BuggyLoggers.F_LOG.info(stream.toString()); + BuggyLoggers.FRAMEWORK.info(stream.toString()); for (ch.qos.logback.classic.Logger logger : BuggyLoggers.LOGGER_CONTEXT.getLoggerList()) { if (logger.getLevel() != null) { String name = logger.getName(); diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/config/BParameters.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/BParameters.java similarity index 91% rename from buggy-core/src/main/java/org/touchbit/buggy/core/config/BParameters.java rename to buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/BParameters.java index a963011..ba6b08a 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/config/BParameters.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/BParameters.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.touchbit.buggy.core.config; +package org.touchbit.buggy.spring.boot.starter.jcommander; /** * Created by Oleg Shaburov on 18.09.2018 @@ -46,8 +46,8 @@ public class BParameters { 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"; - + public static final String PRINT_LOG_IF_FAIL = "--print-log-if-fail"; + public static final String PROGRAM_NAME = "--program-name"; private BParameters() { throw new IllegalStateException("Utility class. Prohibit instantiation."); diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/BuggyJCommand.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/BuggyJCommand.java new file mode 100644 index 0000000..511538f --- /dev/null +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/BuggyJCommand.java @@ -0,0 +1,181 @@ +package org.touchbit.buggy.spring.boot.starter.jcommander; + +import com.beust.jcommander.Parameter; +import org.touchbit.buggy.core.config.BuggyConfig; +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.InterfaceConverter; +import org.touchbit.buggy.spring.boot.starter.jcommander.converters.ParameterValidator; +import org.touchbit.buggy.spring.boot.starter.jcommander.converters.ServiceConverter; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import static org.touchbit.buggy.spring.boot.starter.jcommander.BParameters.*; + +/** + * Configuration class for customizing Buggy. + *

+ * Created by Oleg Shaburov on 01.10.2020 + * shaburov.o.a@gmail.com + */ +@SuppressWarnings("unused") +public final class BuggyJCommand implements JCommand { + + private static Boolean version; + private static Integer exitStatus; + + public static Boolean getVersion() { + return version; + } + + public static Integer getExitStatus() { + return exitStatus; + } + + @Parameter(names = {V, VERSION}, description = "Print program version") + public static void setVersion(Boolean version) { + BuggyJCommand.version = version; + } + + @Parameter(names = {EXIT_STATUS}, description = "Completion with the specified status.") + public static void setExitStatus(Integer exitStatus) { + BuggyJCommand.exitStatus = exitStatus; + } + + @Parameter(names = {QUESTION_MARK, HELP}, help = true, description = "Print usage.") + public static void setHelp(Boolean help) { + BuggyConfig.setHelp(help); + } + + @Parameter(names = {F, FORCE}, description = "Running all tests, including those that fall.") + public static void setForce(Boolean force) { + BuggyConfig.setForce(force); + } + + @Parameter(names = {PRINT_SUITE}, description = "Display information on the Suite in the console log.") + public static void setPrintSuite(Boolean printSuite) { + BuggyConfig.setPrintSuite(printSuite); + } + + @Parameter(names = {PRINT_CAUSE}, description = "Print the cause of a fail or skip test in the console log.") + public static void setPrintCause(Boolean printCause) { + BuggyConfig.setPrintCause(printCause); + } + + @Parameter(names = {PRINT_LOG}, description = "Print the test log file path in the console log") + public static void setPrintLog(Boolean printLog) { + BuggyConfig.setPrintLog(printLog); + } + + @Parameter(names = {PRINT_LOG_IF_FAIL}, description = "Print the failed test log file path in the console log") + public static void setPrintLogOnlyFail(Boolean printLogOnlyFail) { + BuggyConfig.setPrintLogOnlyFail(printLogOnlyFail); + } + + @Parameter(names = {THREADS}, description = "The number of threads to run the test methods.") + public static void setThreads(Integer threads) { + BuggyConfig.setThreads(threads); + } + + @Parameter(names = {ARTIFACTS_URL}, description = "The storage address for the builds (artifacts).") + public static void setArtifactsUrl(String artifactsUrl) { + BuggyConfig.setArtifactsUrl(artifactsUrl); + } + + @Parameter(names = {T, TYPE}, description = "Type of tests to run.", validateWith = ParameterValidator.class) + public static void setTypes(List types) { + BuggyConfig.setTypes(types); + } + + public static void setTypes(Type... types) { + BuggyConfig.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) { + BuggyConfig.setServices(services); + } + + @SafeVarargs + public static void setServices(S... services) { + BuggyConfig.setServices(services); + } + + @SafeVarargs + public static void setServices(Class... services) { + BuggyConfig.setServices(services); + } + + @Parameter(names = {I, INTERFACE}, description = "List of tested interfaces in the format: NAME,NAME,NAME.", + validateWith = ParameterValidator.class, listConverter = InterfaceConverter.class) + public static void setInterfaces(List interfaces) { + BuggyConfig.setInterfaces(interfaces); + } + + @SafeVarargs + public static void setInterfaces(I... interfaces) { + BuggyConfig.setInterfaces(interfaces); + } + + @SafeVarargs + public static void setInterfaces(Class... interfaces) { + BuggyConfig.setInterfaces(interfaces); + } + + @Parameter(names = {C, COMPONENTS}, description = "List of tested components in the format: NAME,NAME,NAME.", + validateWith = ParameterValidator.class, listConverter = ServiceConverter.class) + public static void setComponents(List components) { + BuggyConfig.setComponents(components); + } + + @SafeVarargs + public static void setComponents(C... components) { + BuggyConfig.setComponents(components); + } + + @SafeVarargs + public static void setComponents(Class... components) { + BuggyConfig.setComponents(components); + } + + @Parameter(names = {PARALLEL_MODE}, description = "TestNG parallel mode.") + public static void setParallelMode(ParallelMode parallelMode) { + BuggyConfig.setParallelMode(parallelMode); + } + + @Parameter(names = {PROGRAM_NAME}, description = "Current program name") + public static void setProgramName(String programName) { + BuggyConfig.setProgramName(programName); + } + + @Override + public Map sort(Map map) { + String[] sort = new String[] + {THREADS, PARALLEL_MODE, F, PRINT_LOG, PRINT_CAUSE, PRINT_SUITE, + 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-core/src/main/java/org/touchbit/buggy/core/config/JCConfiguration.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/JCommand.java similarity index 97% rename from buggy-core/src/main/java/org/touchbit/buggy/core/config/JCConfiguration.java rename to buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/JCommand.java index 317d1c6..67d116d 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/config/JCConfiguration.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/JCommand.java @@ -1,4 +1,4 @@ -package org.touchbit.buggy.core.config; +package org.touchbit.buggy.spring.boot.starter.jcommander; import com.beust.jcommander.Parameter; import org.touchbit.buggy.core.utils.JUtils; @@ -20,12 +20,13 @@ * Created by Oleg Shaburov on 01.10.2020 * shaburov.o.a@gmail.com */ -public interface JCConfiguration { +public interface JCommand { /** * 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() { @@ -37,6 +38,7 @@ default Map configurationToMap() { /** * Method adds to Map {@link Parameter#names()} and values of annotated fields + * * @param map - configuration parameters and values map */ default void addFieldValuesToMap(Map map) { @@ -62,6 +64,7 @@ default void addFieldValuesToMap(Map map) { /** * Method adds to Map {@link Parameter#names()} and values of annotated methods + * * @param map - configuration parameters and values map */ default void addMethodsValuesToMap(Map map) { @@ -97,6 +100,7 @@ default void addMethodsValuesToMap(Map map) { /** * Default no sort + * * @param map - unsorted map * @return - sorted map */ 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 93% 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 423e99c..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,7 +13,7 @@ * 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.goal.component.Component; diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/GoalConverter.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/GoalConverter.java new file mode 100644 index 0000000..de0005c --- /dev/null +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/GoalConverter.java @@ -0,0 +1,81 @@ +/* + * 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 org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.cglib.beans.BeanGenerator; +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.goal.Goal; + +import java.lang.reflect.Constructor; +import java.util.LinkedHashSet; +import java.util.Set; + +/** + * Created by Oleg Shaburov on 08.09.2018 + * shaburov.o.a@gmail.com + */ +public final class GoalConverter implements IStringConverter { + + private final Class tClass; + + public GoalConverter(final Class t) { + tClass = t; + } + + @Override + public T convert(String s) { + Set beanDefinitionInstances = scanBeanDefinitions(false, "**.buggy", tClass); + Set goalClasses = getBeanDefinitionInstances(beanDefinitionInstances, tClass); + for (T goal : goalClasses) { + if (goal.getClass().getSimpleName().equalsIgnoreCase(s)) { + return goal; + } + } + throw new BuggyConfigurationException("No " + tClass.getSimpleName() + " found with name " + s); + } + + private 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) { + throw new BuggyConfigurationException("Can not create a new instance of " + tClass.getSimpleName()); + } + } + return result; + } + + private Set scanBeanDefinitions(boolean useDefaultFilters, String basePackage, Class c) { + ClassPathScanningCandidateComponentProvider scanner = + new ClassPathScanningCandidateComponentProvider(useDefaultFilters); + scanner.addIncludeFilter(new AssignableTypeFilter(c)); + try { + return scanner.findCandidateComponents(basePackage); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + +} 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 93% 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 827739e..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,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.DefaultListConverter; import org.touchbit.buggy.core.goal.interfaze.Interface; 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 90% 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..7483912 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.BParameters.*; /** * Created by Oleg Shaburov on 08.09.2018 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 93% 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 265285f..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,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.DefaultListConverter; import org.touchbit.buggy.core.goal.service.Service; diff --git a/buggy-spring-boot-starter/src/main/resources/application.yml b/buggy-spring-boot-starter/src/main/resources/application.yml index d895262..76d67f5 100644 --- a/buggy-spring-boot-starter/src/main/resources/application.yml +++ b/buggy-spring-boot-starter/src/main/resources/application.yml @@ -1,7 +1,7 @@ logging: config: 'classpath:buggy-logback.xml' file: - path: ./logs + path: logs buggy: commandsScannerBasePackages: - "**.buggy" 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..1240aa1 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.testng.IExecutionListener; +import org.testng.IInvokedMethodListener; +import org.testng.ITestResult; +import org.touchbit.buggy.core.config.BuggyConfig; import org.touchbit.buggy.core.model.Details; -import org.touchbit.buggy.core.testng.listeners.BaseBuggyExecutionListener; -import org.testng.*; +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); } } @@ -92,9 +89,10 @@ public void onExecutionFinish() { protected void addResult(ITestResult result, Details details, 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); @@ -115,8 +113,8 @@ 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); } } @@ -130,7 +128,7 @@ protected String addAttachments(ITestResult testResult) { } protected String attachLogfile(String prefix) { - String logfile = config.getArtifactsUrl() + "/tests/" + prefix + ".log"; + String logfile = BuggyConfig.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"; + BuggyConfig.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..d4b7042 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 @@ -13,7 +13,6 @@ 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,27 +25,6 @@ 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); @@ -62,7 +40,7 @@ public void afterInvocation(IInvokedMethod method, ITestResult result) { } protected void processErrorTest(Details details, ITestResult result, String throwableMsg) { - switch(details.status()) { + switch (details.status()) { case SKIP: case FAILED: case EXP_FIX: @@ -93,7 +71,7 @@ protected String processResultThrowable(Details details, ITestResult result) { } protected void processSuccessTest(Details details, ITestResult result, String throwableMsg) { - switch(details.status()) { + switch (details.status()) { case EXP_FIX: case BLOCKED: addResult(result, details, FIXED, @@ -116,4 +94,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 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); + } + } + } + } diff --git a/pom.xml b/pom.xml index 71d22d1..a8b414d 100644 --- a/pom.xml +++ b/pom.xml @@ -1,6 +1,6 @@ - 4.0.0 @@ -9,14 +9,15 @@ 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 From 41cb1a9cd3ef3e2830fb0a2fef437b5ff318a7e4 Mon Sep 17 00:00:00 2001 From: "oleg.shaburov" Date: Wed, 7 Oct 2020 04:30:13 +0300 Subject: [PATCH 13/24] Logging refactoring --- .../touchbit/buggy/core/BaseBuggyTest.java | 4 +- .../buggy/core/config/BuggyConfig.java | 6 +- .../buggy/core/log/BaseLogbackWrapper.java | 213 ++++++++++++++++++ .../touchbit/buggy/core/log/BuggyLoggers.java | 73 ------ .../buggy/core/log/ConfigurationLogger.java | 8 +- .../buggy/core/log/ConsoleLogger.java | 9 + .../buggy/core/log/FrameworkLogger.java | 32 +++ .../buggy/core/log/SiftingTestLogger.java | 33 +++ .../DecomposeTestLogsFileAppender.java | 90 ++++++++ .../log/layout/ConsoleLoggerColorLayout.java | 6 - .../touchbit/buggy/core/model/Details.java | 6 +- .../buggy/core/model/ResultStatus.java | 8 +- .../org/touchbit/buggy/core/model/Status.java | 1 + .../testng/BaseBuggyExecutionListener.java | 23 +- .../core/testng/BaseTelegramNotifier.java | 3 +- .../core/testng/BuggyExecutionListener.java | 12 +- .../IntellijIdeaTestNgPluginListener.java | 7 +- .../org/touchbit/buggy/core/utils/JUtils.java | 26 ++- .../src/main/resources/buggy-logback.xml | 8 +- .../BaseBuggyExecutionListenerTests.java | 68 +++--- buggy-core/src/test/resources/log4j2.xml | 58 ----- buggy-feign/pom.xml | 10 - buggy-okhttp/pom.xml | 10 - buggy-spring-boot-starter-example/pom.xml | 1 - .../starter/example/ExampleBuggyRunner.java | 1 - .../boot/starter/example/ExampleTests.java | 12 +- .../example/conf/ExampleConfiguration.java | 1 - .../boot/starter/example/goal/Actions.java | 12 + .../boot/starter/example/goal/GitHub.java | 7 + .../spring/boot/starter/BuggyRunner.java | 29 ++- .../starter/conf/JCommanderConfiguration.java | 4 +- .../starter/conf/LogbackConfiguration.java | 25 +- .../starter/jcommander/BuggyJCommand.java | 58 +++++ .../boot/starter/jcommander/JCommand.java | 2 +- pom.xml | 27 --- 35 files changed, 602 insertions(+), 291 deletions(-) create mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/log/BaseLogbackWrapper.java delete mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/log/BuggyLoggers.java create mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/log/ConsoleLogger.java create mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/log/FrameworkLogger.java create mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/log/SiftingTestLogger.java create mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/log/appender/DecomposeTestLogsFileAppender.java delete mode 100644 buggy-core/src/test/resources/log4j2.xml create mode 100644 buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/goal/Actions.java create mode 100644 buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/goal/GitHub.java diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/BaseBuggyTest.java b/buggy-core/src/main/java/org/touchbit/buggy/core/BaseBuggyTest.java index 3d190b0..d715712 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/BaseBuggyTest.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/BaseBuggyTest.java @@ -19,7 +19,7 @@ import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.testng.annotations.Listeners; -import org.touchbit.buggy.core.log.BuggyLoggers; +import org.touchbit.buggy.core.log.SiftingTestLogger; import org.touchbit.buggy.core.testng.BuggyExecutionListener; import org.touchbit.buggy.core.testng.IntellijIdeaTestNgPluginListener; @@ -35,7 +35,7 @@ public abstract class BaseBuggyTest { protected static Logger log; protected BaseBuggyTest() { - this(BuggyLoggers.SIFTING); + this(new SiftingTestLogger()); } protected BaseBuggyTest(final Logger logger) { diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/config/BuggyConfig.java b/buggy-core/src/main/java/org/touchbit/buggy/core/config/BuggyConfig.java index 4e0c15d..996f027 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/config/BuggyConfig.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/config/BuggyConfig.java @@ -48,11 +48,11 @@ public static void setPrintLogFileOnlyFail(Boolean printLogIfFail) { } public static Boolean isPrintLogFileOnlyFail() { - return BuggyConfig.printLogOnlyFail; + return printLogOnlyFail; } - public static Boolean getHelp() { - return help; + public static Boolean isHelp() { + return BuggyConfig.help; } public static void setHelp(Boolean help) { diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/log/BaseLogbackWrapper.java b/buggy-core/src/main/java/org/touchbit/buggy/core/log/BaseLogbackWrapper.java new file mode 100644 index 0000000..2165e2c --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/log/BaseLogbackWrapper.java @@ -0,0 +1,213 @@ +package org.touchbit.buggy.core.log; + +import ch.qos.logback.classic.LoggerContext; +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.utils.JUtils; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.util.List; + +public class BaseLogbackWrapper extends MarkerIgnoringBase { + + public static final String LOG_PATH = "LOG_PATH"; + 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 static final String LOGGING_CONFIG = "logging.config"; + private static final String LOGBACK_CONFIG = "logback.configurationFile"; + + static { + if (System.getProperty("logback.configurationFile") == null) { + System.setProperty("logback.configurationFile", "buggy-logback.xml"); + } + 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"); + } + } + + 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_CONFIG, "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(); + } + + 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/log/BuggyLoggers.java b/buggy-core/src/main/java/org/touchbit/buggy/core/log/BuggyLoggers.java deleted file mode 100644 index 623d1b7..0000000 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/log/BuggyLoggers.java +++ /dev/null @@ -1,73 +0,0 @@ -package org.touchbit.buggy.core.log; - -import ch.qos.logback.classic.LoggerContext; -import ch.qos.logback.classic.spi.ILoggingEvent; -import ch.qos.logback.core.Appender; -import ch.qos.logback.core.FileAppender; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.MDC; -import org.touchbit.buggy.core.utils.JUtils; - -import java.io.File; -import java.util.Iterator; - -public class BuggyLoggers { - - static { - if (JUtils.isJetBrainsIdeRun()) { - System.setProperty("LOG_PATH", "target/logs"); - } else { - System.setProperty("LOG_PATH", "logs"); - } - System.setProperty("logging.config", "buggy-logback.xml"); - System.setProperty("logback.configurationFile", "buggy-logback.xml"); - } - - public static final String CONSOLE_LOGGER_NAME = "Console"; - public static final String FRAMEWORK_LOGGER_NAME = "Framework"; - public static final String SIFTING_LOGGER_NAME = "Sifting"; - public static final String CONFIG_PROPERTY = "logging.config"; - public static final String SIFTING_LOG_FILE_PATH = "sifting.log.file.path"; - - public static final Logger CONSOLE = LoggerFactory.getLogger(CONSOLE_LOGGER_NAME); - public static final Logger FRAMEWORK = LoggerFactory.getLogger(FRAMEWORK_LOGGER_NAME); - public static final Logger SIFTING = LoggerFactory.getLogger(SIFTING_LOGGER_NAME); - public static final String LOGGING_CONFIG_FILE = System.getProperty(CONFIG_PROPERTY, "buggy-logback.xml"); - public static final LoggerContext LOGGER_CONTEXT = (LoggerContext) LoggerFactory.getILoggerFactory(); - - protected BuggyLoggers() { - throw new IllegalStateException("Utility class. Prohibit instantiation."); - } - - public static String getFrameworkLogFilePath() { - return getLogFilePath(FRAMEWORK_LOGGER_NAME); - } - - public static String getLogFilePath(String loggerName) { - LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); - for (ch.qos.logback.classic.Logger logger : context.getLoggerList()) { - for (Iterator> index = logger.iteratorForAppenders(); index.hasNext(); ) { - Appender appender = index.next(); - if (appender instanceof FileAppender && appender.getName().equalsIgnoreCase(loggerName)) { - FileAppender fileAppender = (FileAppender) appender; - return fileAppender.getFile(); - } - } - } - return null; - } - - public static void setSiftingLogFilePath(String dir, String filename) { - setSiftingLogFilePath(new File(dir, filename)); - } - - public static void setSiftingLogFilePath(String filePath) { - setSiftingLogFilePath(new File(filePath)); - } - - public static void setSiftingLogFilePath(File file) { - MDC.put(SIFTING_LOG_FILE_PATH, file.getPath()); - } - -} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/log/ConfigurationLogger.java b/buggy-core/src/main/java/org/touchbit/buggy/core/log/ConfigurationLogger.java index 697bea2..1d75868 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/log/ConfigurationLogger.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/log/ConfigurationLogger.java @@ -18,6 +18,8 @@ public class ConfigurationLogger { public static final String DOT = "."; public static final String UNDERSCORE = "_"; + private static final ConsoleLogger CONSOLE = new ConsoleLogger(); + private ConfigurationLogger() { throw new IllegalStateException("Utility class. Prohibit instantiation."); } @@ -96,15 +98,15 @@ private static String centerMsg(String msg) { } public static void info(String msg) { - BuggyLoggers.CONSOLE.info(msg); + CONSOLE.info(msg); } public static void error(String msg, Throwable t) { - BuggyLoggers.CONSOLE.error(RED.wrap(msg), t); + CONSOLE.error(msg, t); } public static void error(String msg) { - BuggyLoggers.CONSOLE.error(RED.wrap(msg)); + CONSOLE.error(msg); } } diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/log/ConsoleLogger.java b/buggy-core/src/main/java/org/touchbit/buggy/core/log/ConsoleLogger.java new file mode 100644 index 0000000..e5d2fba --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/log/ConsoleLogger.java @@ -0,0 +1,9 @@ +package org.touchbit.buggy.core.log; + +public class ConsoleLogger extends BaseLogbackWrapper { + + public ConsoleLogger() { + super(CONSOLE_LOGGER_NAME); + } + +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/log/FrameworkLogger.java b/buggy-core/src/main/java/org/touchbit/buggy/core/log/FrameworkLogger.java new file mode 100644 index 0000000..69d8dd6 --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/log/FrameworkLogger.java @@ -0,0 +1,32 @@ +package org.touchbit.buggy.core.log; + +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.FileAppender; + +import java.io.File; +import java.util.List; +import java.util.stream.Collectors; +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()) { + List> collect = Stream.generate(logger.iteratorForAppenders()::next) + .limit(1000) + .filter(appender -> appender instanceof FileAppender) + .filter(fileAppender -> fileAppender.getName().equals(FRAMEWORK_LOGGER_NAME)) + .map(f -> (FileAppender) f) + .collect(Collectors.toList()); + if (!collect.isEmpty()) { + return new File(collect.get(1).getFile()); + } + } + return null; + } + +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/log/SiftingTestLogger.java b/buggy-core/src/main/java/org/touchbit/buggy/core/log/SiftingTestLogger.java new file mode 100644 index 0000000..ba090bf --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/log/SiftingTestLogger.java @@ -0,0 +1,33 @@ +package org.touchbit.buggy.core.log; + +import org.slf4j.MDC; +import org.touchbit.buggy.core.log.appender.DecomposeTestLogsFileAppender; +import org.touchbit.buggy.core.model.IStatus; + +import java.io.File; + +public class SiftingTestLogger extends BaseLogbackWrapper { + + public static final String SIFTING_LOG_FILE_PATH = "sifting.test.log.file.path"; + public static final String SIFTING_LOG_DIR = "tests"; + + public SiftingTestLogger() { + super(SIFTING_LOGGER_NAME); + } + + public static void setTestLogFileName(String logFileName) { + setTestLogFile(new File(SIFTING_LOG_DIR, logFileName)); + } + + public static void setTestLogFile(File file) { + MDC.put(SIFTING_LOG_FILE_PATH, file.getPath()); + } + + public static File getSiftingLogFile(String fileName) { + return DecomposeTestLogsFileAppender.getFile(fileName); + } + + public static void setTestStatus(String fileName, IStatus status) { + DecomposeTestLogsFileAppender.setTestStatus(fileName, status); + } +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/log/appender/DecomposeTestLogsFileAppender.java b/buggy-core/src/main/java/org/touchbit/buggy/core/log/appender/DecomposeTestLogsFileAppender.java new file mode 100644 index 0000000..4374b2a --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/log/appender/DecomposeTestLogsFileAppender.java @@ -0,0 +1,90 @@ +package org.touchbit.buggy.core.log.appender; + +import ch.qos.logback.core.FileAppender; + +import java.io.File; +import java.util.*; + +import org.touchbit.buggy.core.model.IStatus; +import org.touchbit.buggy.core.model.ResultStatus; +import org.touchbit.buggy.core.utils.IOHelper; + +import static org.touchbit.buggy.core.log.BaseLogbackWrapper.LOG_PATH; +import static org.touchbit.buggy.core.model.Status.*; + +public class DecomposeTestLogsFileAppender extends FileAppender { + + public static final Map TEST_LOGS_WITH_STATUS = new HashMap(); + public static final String LOG_DIR = System.getProperty(LOG_PATH, "logs"); + public static final File NEW_DIR = new File(LOG_DIR, "1_new"); + public static final File CORRUPTED_DIR = new File(LOG_DIR, "2_corrupted"); + public static final File BLOCKED_DIR = new File(LOG_DIR, "3_blocked"); + public static final File FIXED_DIR = new File(LOG_DIR, "4_fixed"); + public static final File IMPLEMENTED_DIR = new File(LOG_DIR, "5_implemented"); + public static final File EXP_FIX_DIR = new File(LOG_DIR, "6_exp_fix"); + public static final File EXP_IMPL_DIR = new File(LOG_DIR, "7_exp_impl"); + + @Override + public void setFile(String file) { + super.setFile(file); + TEST_LOGS_WITH_STATUS.put(new File(file), NONE); + } + + public static File getFile(String fileName) { + return TEST_LOGS_WITH_STATUS.entrySet().stream() + .filter(e -> e.getKey().getName().equals(fileName)) + .findFirst() + .map(Map.Entry::getKey) + .orElse(null); + } + + public static void setTestStatus(String fileName, IStatus status) { + TEST_LOGS_WITH_STATUS.entrySet().stream() + .filter(e -> e.getKey().getName().contains(fileName)) + .findFirst() + .ifPresent(first -> TEST_LOGS_WITH_STATUS.put(first.getKey(), status)); + } + + public static void decomposeTestLogs() { + for (Map.Entry log : TEST_LOGS_WITH_STATUS.entrySet()) { + String fileName = log.getKey().getName(); + File destFile = null; + switch (ResultStatus.valueOf(log.getValue().getStatus())) { + 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: + case UNTESTED: + default: + // do nothing + } + if (destFile != null) { + try { + IOHelper.copyFile(log.getKey(), destFile); + } catch (Exception e) { + // ignore todo + } + } + } + } + +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/log/layout/ConsoleLoggerColorLayout.java b/buggy-core/src/main/java/org/touchbit/buggy/core/log/layout/ConsoleLoggerColorLayout.java index 1763be8..55b4d27 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/log/layout/ConsoleLoggerColorLayout.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/log/layout/ConsoleLoggerColorLayout.java @@ -50,12 +50,6 @@ public String doLayout(final ILoggingEvent event) { default: return ""; } - final IThrowableProxy throwableProxy = event.getThrowableProxy(); - final boolean withST = Boolean.parseBoolean(MDC.get("print.console.stacktrace")); - if (throwableProxy != null && withST) { - stringBuilder.append(CoreConstants.LINE_SEPARATOR); - stringBuilder.append(ThrowableProxyUtil.asString(throwableProxy)); - } stringBuilder.append(CoreConstants.LINE_SEPARATOR); return stringBuilder.toString(); } 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/Details.java index 2d22342..2e2916f 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/Details.java @@ -21,6 +21,8 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import static org.touchbit.buggy.core.model.Status.NONE; + /** * Interface of binding test methods. * Custom statuses for tests are provided. @@ -41,7 +43,7 @@ * Test status (see: {@link Status}) * Used values: EXP_IMPL, EXP_FIX, BLOCKED, CORRUPTED */ - Status status(); + Status status() default NONE; /** * Issues ID in the task-tracker system. Format: "STORY-269" @@ -49,7 +51,7 @@ String[] issue() default {""}; /** - * Defects ID in the task-tracker system. Format: "BUG-269" + * Defects ID in the task-tracker system. Format: "BUG-354" */ String[] bug() default {""}; diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/model/ResultStatus.java b/buggy-core/src/main/java/org/touchbit/buggy/core/model/ResultStatus.java index f5e28e2..df37510 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/model/ResultStatus.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/model/ResultStatus.java @@ -24,12 +24,16 @@ */ public enum ResultStatus implements IStatus { + SUCCESS, + FAILED, + CORRUPTED, + BLOCKED, FIXED, IMPLEMENTED, + EXP_FIX, + EXP_IMPL, UNTESTED, - SUCCESS, SKIP, - FAILED, ; @Override 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 6de4fc3..b83cbc7 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 @@ -29,6 +29,7 @@ public enum Status implements IStatus { EXP_FIX, BLOCKED, CORRUPTED, + NONE, // Result statuses FIXED, 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 index f5464b0..a14d011 100644 --- 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 @@ -20,8 +20,11 @@ import org.slf4j.Logger; import org.testng.*; import org.touchbit.buggy.core.config.BuggyConfig; -import org.touchbit.buggy.core.log.BuggyLoggers; +import org.touchbit.buggy.core.log.ConsoleLogger; +import org.touchbit.buggy.core.log.FrameworkLogger; +import org.touchbit.buggy.core.log.SiftingTestLogger; import org.touchbit.buggy.core.model.Details; +import org.touchbit.buggy.core.model.IStatus; import org.touchbit.buggy.core.model.Suite; import java.io.File; @@ -58,13 +61,13 @@ public abstract class BaseBuggyExecutionListener implements BuggyListener, IExec public void onExecutionStart() { startTime = new Date().getTime(); if (testLog == null) { - testLog = BuggyLoggers.SIFTING; + testLog = new SiftingTestLogger(); } if (frameworkLog == null) { - frameworkLog = BuggyLoggers.FRAMEWORK; + frameworkLog = new FrameworkLogger(); } if (consoleLog == null) { - consoleLog = BuggyLoggers.CONSOLE; + consoleLog = new ConsoleLogger(); } } @@ -93,15 +96,21 @@ protected Suite getSuite(ITestNGMethod method) { return (Suite) method.getRealClass().getAnnotation(Suite.class); } - protected String getLogFilePath(ITestNGMethod method) { + protected String getLogFilePath(ITestNGMethod method, IStatus status) { // Do not change the check. Feature parsing values by jCommander library. if (!"null".equalsIgnoreCase(String.valueOf(BuggyConfig.getArtifactsUrl()))) { return BuggyConfig.getArtifactsUrl().endsWith("/") ? BuggyConfig.getArtifactsUrl() : BuggyConfig.getArtifactsUrl() + "/"; } else { - return "file://" + new File(new File(BuggyLoggers.getFrameworkLogFilePath()).getAbsolutePath() + - "/" + getInvokedMethodLogFileName(method)); + String fileName = getInvokedMethodLogFileName(method); + SiftingTestLogger.setTestStatus(fileName, status); + File file = SiftingTestLogger.getSiftingLogFile(fileName); + if (file != null) { + return "file://" + file.getAbsolutePath(); + } else { + return "Log file not found: " + fileName; + } } } 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 index 4ace8c4..2bbac30 100644 --- 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 @@ -19,7 +19,6 @@ import org.apache.commons.lang3.time.DurationFormatUtils; import org.testng.IExecutionListener; import org.touchbit.buggy.core.config.BuggyConfig; -import org.touchbit.buggy.core.log.BuggyLoggers; import org.touchbit.buggy.core.model.Notifier; import org.touchbit.buggy.core.utils.StringUtils; @@ -103,7 +102,7 @@ private void telegramResultNotification() { try { notifier.report(sj.toString()); } catch (Exception e) { - BuggyLoggers.CONSOLE.error("Failed to send message to Telegram.", e); +// BuggyLoggers.CONSOLE.error("Failed to send message to Telegram.", e); TODO } } 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 index 2c2fc09..4f0a46b 100644 --- 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 @@ -21,8 +21,8 @@ import org.testng.*; import org.touchbit.buggy.core.config.BuggyConfig; import org.touchbit.buggy.core.exceptions.CorruptedTestException; -import org.touchbit.buggy.core.log.BuggyLoggers; import org.touchbit.buggy.core.log.ConfigurationLogger; +import org.touchbit.buggy.core.log.SiftingTestLogger; import org.touchbit.buggy.core.model.Details; import org.touchbit.buggy.core.model.Status; import org.touchbit.buggy.core.model.Suite; @@ -57,9 +57,9 @@ public BuggyExecutionListener() { } public BuggyExecutionListener(Logger testLogger, Logger frameworkLogger, Logger consoleLogger) { - testLog = testLogger; - frameworkLog = frameworkLogger; - consoleLog = consoleLogger; +// testLog = testLogger; +// frameworkLog = frameworkLogger; +// consoleLog = consoleLogger; } /** @@ -178,7 +178,7 @@ public void onFinish(ISuite suite) { public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { STEPS.set(new ArrayList<>()); String methodName = getMethodName(method); - BuggyLoggers.setSiftingLogFilePath(getInvokedMethodLogFileName(method)); + SiftingTestLogger.setTestLogFileName(getInvokedMethodLogFileName(method)); if (method.isTestMethod()) { testLog.info("Test method is running:\n{} - {}", methodName, getDescription(method)); } else { @@ -402,7 +402,7 @@ public void resultLog(ITestNGMethod method, Status status, String details) { if ((BuggyConfig.isPrintCause() || method.getInvocationCount() < 1) && !detailsString.isEmpty()) { resultMsg.add(detailsString); } - String logPathString = getLogFilePath(method).trim(); + String logPathString = getLogFilePath(method, status).trim(); if (BuggyConfig.isPrintLog() && method.getInvocationCount() > 0 && !logPathString.isEmpty() && (!BuggyConfig.isPrintLogFileOnlyFail() || status != Status.SUCCESS)) { resultMsg.add("\n └"); 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 index be0c6fc..2576fc3 100644 --- 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 @@ -17,7 +17,6 @@ package org.touchbit.buggy.core.testng; import org.testng.ITestNGListener; -import org.touchbit.buggy.core.log.BuggyLoggers; import org.touchbit.buggy.core.utils.JUtils; /** @@ -29,15 +28,15 @@ public final class IntellijIdeaTestNgPluginListener extends BuggyExecutionListener implements ITestNGListener { public IntellijIdeaTestNgPluginListener() { - if (JUtils.isJetBrainsIdeRun()) { - BuggyLoggers.SIFTING.info("IntellijIdeaTestNgPluginListener enabled"); + if (JUtils.isJetBrainsIdeTestNGPluginRun()) { + consoleLog.info("IntellijIdeaTestNgPluginListener enabled"); JUtils.initBuggyConfigurationYml(); } } @Override public final boolean isEnable() { - return JUtils.isJetBrainsIdeRun(); + return JUtils.isJetBrainsIdeTestNGPluginRun(); } } 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 index 2c5cd98..3800df0 100644 --- 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 @@ -10,6 +10,8 @@ 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.*; @@ -76,7 +78,7 @@ public static R newInstance(Class t, BiFunction arguments = runtimeMxBean.getInputArguments(); + 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 (isJetBrainsIdeRun()) { + 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)) { - return firstClassPath.substring(0, firstClassPath.indexOf("/target/")) + "/target"; + 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; } } } diff --git a/buggy-core/src/main/resources/buggy-logback.xml b/buggy-core/src/main/resources/buggy-logback.xml index e8a5b63..d6ec1d3 100644 --- a/buggy-core/src/main/resources/buggy-logback.xml +++ b/buggy-core/src/main/resources/buggy-logback.xml @@ -1,7 +1,7 @@ - + @@ -18,12 +18,12 @@ - sifting.log.file.path + sifting.test.log.file.path default-sifting.log - - ${logging.file.path}/${sifting.log.file.path} + + ${logging.file.path}/${sifting.test.log.file.path} 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 index 5fe5bc9..9f0299d 100644 --- 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 @@ -15,36 +15,36 @@ * 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 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") @@ -87,10 +87,10 @@ public boolean isEnable() { return false; } - @Override - public String getLogFilePath(ITestNGMethod method) { - return super.getLogFilePath(method); - } +// @Override +// public String getLogFilePath(ITestNGMethod method, S) { +// return super.getLogFilePath(method, null); +// } } diff --git a/buggy-core/src/test/resources/log4j2.xml b/buggy-core/src/test/resources/log4j2.xml deleted file mode 100644 index e4121c6..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 26872b0..e50cbbf 100644 --- a/buggy-feign/pom.xml +++ b/buggy-feign/pom.xml @@ -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-okhttp/pom.xml b/buggy-okhttp/pom.xml index 355dfc5..40b6c4c 100644 --- a/buggy-okhttp/pom.xml +++ b/buggy-okhttp/pom.xml @@ -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-spring-boot-starter-example/pom.xml b/buggy-spring-boot-starter-example/pom.xml index c7c3445..25e4a97 100644 --- a/buggy-spring-boot-starter-example/pom.xml +++ b/buggy-spring-boot-starter-example/pom.xml @@ -18,7 +18,6 @@ org.touchbit:buggy-spring-boot-starter-example - 2.13.3 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 index ee36716..1d37eaa 100644 --- 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 @@ -14,7 +14,6 @@ public class ExampleBuggyRunner extends BuggyRunner { BuggyJCommand.setPrintLog(true); BuggyJCommand.setPrintSuite(true); BuggyJCommand.setPrintCause(true); - BuggyJCommand.setComponents(DefaultComponent.class); } public static void main(String[] args) { diff --git a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleTests.java b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleTests.java index 920832b..cbcf498 100644 --- a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleTests.java +++ b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleTests.java @@ -3,21 +3,19 @@ import org.testng.annotations.Test; import org.touchbit.buggy.core.BaseBuggyTest; import org.touchbit.buggy.core.config.BuggyConfig; +import org.touchbit.buggy.core.goal.interfaze.API; import org.touchbit.buggy.core.model.Details; 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() +@Suite(component = GitHub.class, service = Actions.class, interfaze = API.class) public class ExampleTests extends BaseBuggyTest { @Test @Details public void test_1() { - System.out.println("test_1" + BuggyConfig.isForce()); - System.out.println("test_1" + BuggyConfig.isPrintLog()); - System.out.println("test_1" + BuggyConfig.getComponents()); - System.out.println("test_1" + BuggyConfig.getServices()); - System.out.println("test_1" + BuggyConfig.getInterfaces()); - System.out.println("test_1" + BuggyConfig.getTypes()); + step("test_1"); } } 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 index 2bed25f..7b56b64 100644 --- 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 @@ -6,7 +6,6 @@ public class ExampleConfiguration implements JCommand { @Parameter(names = {"--example-host"}, description = "Example host.") -// @Parameter(names = {"-f"}, description = "Example host.") private static String exampleHost = "https://exmaole.com"; @Parameter(names = {"--example-pass"}, password = true, description = "Example password.") 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/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 index b923bb7..1d41356 100644 --- 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 @@ -1,6 +1,5 @@ package org.touchbit.buggy.spring.boot.starter; -import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.CommandLineRunner; @@ -14,20 +13,32 @@ 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.log.BuggyLoggers; import org.touchbit.buggy.core.log.ConfigurationLogger; +import org.touchbit.buggy.core.log.FrameworkLogger; +import org.touchbit.buggy.core.log.appender.DecomposeTestLogsFileAppender; 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.BuggyJCommand; +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; @@ -64,13 +75,9 @@ public static void exit(int status, String message, Exception e) { if (status == 0) { ConfigurationLogger.info(message); } else { - if (BuggyLoggers.FRAMEWORK == null) { - MDC.put("print.console.stacktrace", "true"); - } else { - String frameworkLogFilePath = BuggyLoggers.getFrameworkLogFilePath(); - if (frameworkLogFilePath != null && !frameworkLogFilePath.isEmpty()) { - frameworkLogPath = "\nFor more information see " + frameworkLogFilePath; - } + File file = FrameworkLogger.getLogFile(); + if (file != null) { + frameworkLogPath = "\nFor more information see " + file.getName(); } String eMsg = "\n" + e.getClass().getSimpleName() + ": " + e.getMessage(); ConfigurationLogger.error(message + eMsg + frameworkLogPath, e); @@ -84,6 +91,7 @@ public static void exit(int status, String message, Exception e) { @Override public void run(String... args) { + // TODO exit_1 if test methods names not unique Map>> testClassesBySuitesMap = getTestClassesBySuitesMap(filteredTestClasses); List xmlSuites = getXmlSuites(testClassesBySuitesMap); TestNG testNG = getTestNG(); @@ -96,12 +104,15 @@ public void run(String... args) { } testNG.setXmlSuites(xmlSuites); testNG.run(); + DecomposeTestLogsFileAppender.decomposeTestLogs(); if (BuggyJCommand.getExitStatus() != null) { exit(BuggyJCommand.getExitStatus()); } exit(testNG.getStatus()); } catch (Exception e) { exit(1, "TestNG safely died.", e); + } finally { + DecomposeTestLogsFileAppender.decomposeTestLogs(); } } 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 index 16ab009..a365359 100644 --- 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 @@ -70,7 +70,7 @@ public boolean isJCommanderConfigured() { @PostConstruct public void postConstruct() { - if (BuggyConfig.getHelp()) { + if (BuggyConfig.isHelp()) { ConfigurationLogger.stepDelimiter(); jCommander.usage(); BuggyRunner.exit(0); @@ -86,7 +86,7 @@ public void postConstruct() { private Set scanBuggyConfig() { final boolean useDefaultFilters = false; - final String basePackage = "org.touchbit.buggy.core.config"; + final String basePackage = "org.touchbit.buggy.spring.boot.starter.jcommander"; final Set defs = scanBeanDefinitions(useDefaultFilters, basePackage, BuggyJCommand.class); return getBeanDefinitionInstances(defs, BuggyJCommand.class); } 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 index fe26197..0005153 100644 --- 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 @@ -1,15 +1,15 @@ package org.touchbit.buggy.spring.boot.starter.conf; -import ch.qos.logback.core.util.StatusPrinter; import org.springframework.boot.autoconfigure.condition.ConditionalOnNotWebApplication; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.touchbit.buggy.core.log.BuggyLoggers; +import org.springframework.core.env.ConfigurableEnvironment; +import org.touchbit.buggy.core.log.BaseLogbackWrapper; import org.touchbit.buggy.core.log.ConfigurationLogger; +import org.touchbit.buggy.core.log.FrameworkLogger; import org.touchbit.buggy.spring.boot.starter.BuggyRunner; -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; +import static org.springframework.boot.context.logging.LoggingApplicationListener.CONFIG_PROPERTY; /** * Logback loggers configuration @@ -23,19 +23,20 @@ public class LogbackConfiguration implements IConfiguration { private final boolean isLogbackConfigurationInitialized; - public LogbackConfiguration(boolean isJCommanderConfigured) { + 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"); } ConfigurationLogger.blockDelimiter(); - ConfigurationLogger.centerBold("Logback configuration (" + BuggyLoggers.LOGGING_CONFIG_FILE + ")"); + ConfigurationLogger.centerBold("Logback configuration (" + BaseLogbackWrapper.getConfFileName() + ")"); ConfigurationLogger.stepDelimiter(); - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - PrintStream printStream = new PrintStream(stream); - StatusPrinter.setPrintStream(printStream); - StatusPrinter.printInCaseOfErrorsOrWarnings(BuggyLoggers.LOGGER_CONTEXT); - BuggyLoggers.FRAMEWORK.info(stream.toString()); - for (ch.qos.logback.classic.Logger logger : BuggyLoggers.LOGGER_CONTEXT.getLoggerList()) { + new FrameworkLogger().info(BaseLogbackWrapper.getInCaseOfErrorsOrWarnings()); + for (ch.qos.logback.classic.Logger logger : BaseLogbackWrapper.getLoggerList()) { if (logger.getLevel() != null) { String name = logger.getName(); try { diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/BuggyJCommand.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/BuggyJCommand.java index 511538f..70d827e 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/BuggyJCommand.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/BuggyJCommand.java @@ -154,6 +154,64 @@ public static void setProgramName(String programName) { BuggyConfig.setProgramName(programName); } + public static Boolean isHelp() { + return BuggyConfig.isHelp(); + } + public static Boolean isPrintLogFileOnlyFail() { + return BuggyConfig.isPrintLog(); + } + public static Boolean isForce() { + return BuggyConfig.isForce(); + } + + public static Boolean isPrintSuite() { + return BuggyConfig.isPrintSuite(); + } + + public static Boolean isPrintCause() { + return BuggyConfig.isPrintCause(); + } + + public static Boolean isPrintLog() { + return BuggyConfig.isPrintLog(); + } + + public static Boolean isVersion() { + return BuggyConfig.isVersion(); + } + + public static Integer getThreads() { + return BuggyConfig.getThreads(); + } + + public static String getArtifactsUrl() { + return BuggyConfig.getArtifactsUrl(); + } + + public static List getTypes() { + return BuggyConfig.getTypes(); + } + + public static List getServices() { + return BuggyConfig.getServices(); + } + + public static List getInterfaces() { + return BuggyConfig.getInterfaces(); + } + + public static List getComponents() { + return BuggyConfig.getComponents(); + } + + public static ParallelMode getParallelMode() { + return BuggyConfig.getParallelMode(); + } + + public static String getProgramName() { + return BuggyConfig.getProgramName(); + } + @Override public Map sort(Map map) { String[] sort = new String[] diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/JCommand.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/JCommand.java index 67d116d..f4c5e68 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/JCommand.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/JCommand.java @@ -78,7 +78,7 @@ default void addMethodsValuesToMap(Map map) { map.put(Arrays.toString(names), "*****"); } else { String mName = method.getName(); - String is = "is" + mName.substring(2); + String is = "is" + mName.substring(3); String get = "get" + mName.substring(3); methods.stream() .filter(m -> (m.getName().equalsIgnoreCase(is) || m.getName().equalsIgnoreCase(get))) diff --git a/pom.xml b/pom.xml index a8b414d..873a255 100644 --- a/pom.xml +++ b/pom.xml @@ -75,7 +75,6 @@ ${jdk.version} UTF-8 UTF-8 - 2.13.3 5.5.0 10.2.3 @@ -223,32 +222,6 @@ logback-classic 1.2.3 - - org.apache.logging.log4j - log4j-slf4j-impl - ${log4j.version} - test - - - 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} - org.slf4j slf4j-api From 0ac8cdd0edd66c26928bc69f2aaab8bf64ce7fe5 Mon Sep 17 00:00:00 2001 From: "oleg.shaburov" Date: Wed, 7 Oct 2020 04:48:57 +0300 Subject: [PATCH 14/24] FileAppenders: append=false --- .../touchbit/buggy/core/log/layout/FrameworkLoggerLayout.java | 4 ++-- .../touchbit/buggy/core/log/layout/ShiftingLoggerLayout.java | 4 ++-- buggy-core/src/main/resources/buggy-logback.xml | 3 +++ 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/log/layout/FrameworkLoggerLayout.java b/buggy-core/src/main/java/org/touchbit/buggy/core/log/layout/FrameworkLoggerLayout.java index 83e3568..a0a582c 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/log/layout/FrameworkLoggerLayout.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/log/layout/FrameworkLoggerLayout.java @@ -20,10 +20,10 @@ 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"); + 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 + * Print welcome message in the format: 17:28:14.985 INFO - Launch date: 30.09.2020 */ @Override public String getPresentationHeader() { diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/log/layout/ShiftingLoggerLayout.java b/buggy-core/src/main/java/org/touchbit/buggy/core/log/layout/ShiftingLoggerLayout.java index d0c5fa7..d51dcdb 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/log/layout/ShiftingLoggerLayout.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/log/layout/ShiftingLoggerLayout.java @@ -18,10 +18,10 @@ 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"); + 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 + * Print welcome message in the format: 17:28:14.985 INFO - Launch date: 30.09.2020 */ @Override public String getPresentationHeader() { diff --git a/buggy-core/src/main/resources/buggy-logback.xml b/buggy-core/src/main/resources/buggy-logback.xml index d6ec1d3..ce2fe73 100644 --- a/buggy-core/src/main/resources/buggy-logback.xml +++ b/buggy-core/src/main/resources/buggy-logback.xml @@ -12,6 +12,7 @@ ${logging.file.path}/Framework.log + false @@ -24,12 +25,14 @@ ${logging.file.path}/${sifting.test.log.file.path} + false ${logging.file.path}/TestSupervisor.log + false ${base.log.pattern} From 4008425f436d3b56ee97c3561f0be979cfad541f Mon Sep 17 00:00:00 2001 From: "oleg.shaburov" Date: Wed, 7 Oct 2020 07:54:07 +0300 Subject: [PATCH 15/24] Added TestStatisticListener --- ...nfigurationLogger.java => ConfLogger.java} | 17 ++- .../DecomposeTestLogsFileAppender.java | 3 +- .../touchbit/buggy/core/model/Details.java | 4 +- .../buggy/core/model/ResultStatus.java | 1 - .../org/touchbit/buggy/core/model/Status.java | 7 + .../core/testng/BuggyExecutionListener.java | 15 +- .../core/testng/TestStatisticListener.java | 138 ++++++++++++++++++ .../buggy/core/utils/TestNGHelper.java | 31 ++++ .../spring/boot/starter/BuggyRunner.java | 14 +- .../boot/starter/conf/BuggyConfiguration.java | 36 ++--- .../starter/conf/JCommanderConfiguration.java | 38 ++--- .../starter/conf/LogbackConfiguration.java | 10 +- 12 files changed, 251 insertions(+), 63 deletions(-) rename buggy-core/src/main/java/org/touchbit/buggy/core/log/{ConfigurationLogger.java => ConfLogger.java} (87%) create mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/testng/TestStatisticListener.java create mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/utils/TestNGHelper.java diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/log/ConfigurationLogger.java b/buggy-core/src/main/java/org/touchbit/buggy/core/log/ConfLogger.java similarity index 87% rename from buggy-core/src/main/java/org/touchbit/buggy/core/log/ConfigurationLogger.java rename to buggy-core/src/main/java/org/touchbit/buggy/core/log/ConfLogger.java index 1d75868..7fc2207 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/log/ConfigurationLogger.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/log/ConfLogger.java @@ -1,5 +1,10 @@ package org.touchbit.buggy.core.log; +import org.touchbit.buggy.core.utils.ANSI; + +import java.util.function.BooleanSupplier; +import java.util.function.Function; + import static java.util.Objects.isNull; import static org.touchbit.buggy.core.utils.ANSI.BOLD; import static org.touchbit.buggy.core.utils.ANSI.RED; @@ -10,7 +15,7 @@ * Created by Oleg Shaburov on 01.10.2020 * shaburov.o.a@gmail.com */ -public class ConfigurationLogger { +public class ConfLogger { public static final int CONF_STRING_LEN = 47; public static final String CONF_BLOCK = "="; @@ -20,7 +25,7 @@ public class ConfigurationLogger { private static final ConsoleLogger CONSOLE = new ConsoleLogger(); - private ConfigurationLogger() { + private ConfLogger() { throw new IllegalStateException("Utility class. Prohibit instantiation."); } @@ -32,6 +37,14 @@ public static void blockDelimiter() { info(filler(CONF_BLOCK)); } + public static void dotPlaceholder(Object prefix, Object postfix, ANSI ansi, boolean isWrapCondition) { + String msg = filler(prefix, DOT, postfix); + if (isWrapCondition) { + msg = ansi.wrap(msg); + } + info(msg); + } + public static void dotPlaceholder(Object prefix, Object postfix) { info(filler(prefix, DOT, postfix)); } diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/log/appender/DecomposeTestLogsFileAppender.java b/buggy-core/src/main/java/org/touchbit/buggy/core/log/appender/DecomposeTestLogsFileAppender.java index 4374b2a..d964fee 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/log/appender/DecomposeTestLogsFileAppender.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/log/appender/DecomposeTestLogsFileAppender.java @@ -27,7 +27,7 @@ public class DecomposeTestLogsFileAppender extends FileAppender { @Override public void setFile(String file) { super.setFile(file); - TEST_LOGS_WITH_STATUS.put(new File(file), NONE); + TEST_LOGS_WITH_STATUS.put(new File(file), UNTESTED); } public static File getFile(String fileName) { @@ -73,7 +73,6 @@ public static void decomposeTestLogs() { break; case SUCCESS: case SKIP: - case UNTESTED: default: // do nothing } 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/Details.java index 2e2916f..96e51c9 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/Details.java @@ -21,7 +21,7 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import static org.touchbit.buggy.core.model.Status.NONE; +import static org.touchbit.buggy.core.model.Status.UNTESTED; /** * Interface of binding test methods. @@ -43,7 +43,7 @@ * Test status (see: {@link Status}) * Used values: EXP_IMPL, EXP_FIX, BLOCKED, CORRUPTED */ - Status status() default NONE; + Status status() default UNTESTED; /** * Issues ID in the task-tracker system. Format: "STORY-269" diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/model/ResultStatus.java b/buggy-core/src/main/java/org/touchbit/buggy/core/model/ResultStatus.java index df37510..0eb4c58 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/model/ResultStatus.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/model/ResultStatus.java @@ -32,7 +32,6 @@ public enum ResultStatus implements IStatus { IMPLEMENTED, EXP_FIX, EXP_IMPL, - UNTESTED, SKIP, ; 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 b83cbc7..6cd839b 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 @@ -24,6 +24,13 @@ */ public enum Status implements IStatus { +// EXP_IMPL, +// EXP_FIX, +// BLOCKED, +// CORRUPTED, +// UNTESTED, +// ; +// // Test method statuses EXP_IMPL, EXP_FIX, 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 index 4f0a46b..2804083 100644 --- 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 @@ -21,7 +21,7 @@ import org.testng.*; import org.touchbit.buggy.core.config.BuggyConfig; import org.touchbit.buggy.core.exceptions.CorruptedTestException; -import org.touchbit.buggy.core.log.ConfigurationLogger; +import org.touchbit.buggy.core.log.ConfLogger; import org.touchbit.buggy.core.log.SiftingTestLogger; import org.touchbit.buggy.core.model.Details; import org.touchbit.buggy.core.model.Status; @@ -101,7 +101,8 @@ public void onExecutionStart() { @Override public void onExecutionFinish() { super.onExecutionFinish(); - printTestStatistic(); + System.out.println(" >>>>>>>>>>>>>>> " + this.getClass()); +// printTestStatistic(); } @Override @@ -472,7 +473,7 @@ protected void increment(Status status) { } protected void printTestStatistic() { - ConfigurationLogger.blockDelimiter(); + ConfLogger.blockDelimiter(); // if (Buggy.getBuggyErrors() > 0) { // consoleLog.error(StringUtils.dotFiller("Framework errors", 47, Buggy.getBuggyErrors())); // } @@ -491,7 +492,7 @@ protected void printTestStatistic() { if (errorCount > 0) { checkWarnAndPrint("Failed tests", errorCount); checkErrorAndPrint("New Errors", newError.get()); - ConfigurationLogger.blockDelimiter(); + ConfLogger.blockDelimiter(); checkWarnAndPrint("Waiting to fix a defect", expFixError.get()); checkWarnAndPrint("Waiting for implementation", expImplError.get()); checkWarnAndPrint("Blocked tests", blockedError.get()); @@ -501,14 +502,14 @@ protected void printTestStatistic() { consoleLog.info(result); } if (fixedCount > 0) { - ConfigurationLogger.blockDelimiter(); + ConfLogger.blockDelimiter(); checkDebugAndPrint("Fixed cases", fixed.get()); checkDebugAndPrint("Implemented cases", implemented.get()); } - ConfigurationLogger.blockDelimiter(); + ConfLogger.blockDelimiter(); consoleLog.info(StringUtils.dotFiller("Execution time", 47, org.apache.commons.lang3.time.DurationFormatUtils .formatDuration(finishTime - startTime, "HH:mm:ss,SSS"))); - ConfigurationLogger.blockDelimiter(); + ConfLogger.blockDelimiter(); } protected void checkDebugAndPrint(String msg, int count) { diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/testng/TestStatisticListener.java b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/TestStatisticListener.java new file mode 100644 index 0000000..bd85e9e --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/TestStatisticListener.java @@ -0,0 +1,138 @@ +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.log.ConfLogger; +import org.touchbit.buggy.core.model.Details; +import org.touchbit.buggy.core.model.Status; +import org.touchbit.buggy.core.utils.TestNGHelper; + +import java.util.Date; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.testng.ITestResult.*; +import static org.touchbit.buggy.core.utils.ANSI.*; + +public class TestStatisticListener 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 waitingToFixDefect = new AtomicInteger(0); + protected static AtomicInteger waitingForImplementation = 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()) { + Details details = TestNGHelper.getDetails(method); + if (details == 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 (details != null) { + Status status = details.status(); + if (testNgTestStatus == SUCCESS) { + switch (status) { + case BLOCKED: + case CORRUPTED: + case EXP_FIX: + fixedCases.incrementAndGet(); + break; + case EXP_IMPL: + implemented.incrementAndGet(); + break; + case UNTESTED: + 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: + waitingToFixDefect.incrementAndGet(); + break; + case EXP_IMPL: + waitingForImplementation.incrementAndGet(); + break; + case UNTESTED: + 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, unsuccess.get() != 0); + ConfLogger.dotPlaceholder("Successful tests", successfulTests); + ConfLogger.dotPlaceholder("Skipped tests", skippedTests); + ConfLogger.dotPlaceholder("Without @Details", notDetailedTests); + ConfLogger.center("Details"); + ConfLogger.dotPlaceholder("New Errors", newErrors, RED, newErrors.get() != 0); + ConfLogger.dotPlaceholder("Corrupted tests", corruptedTests, RED, corruptedTests.get() != 0); + ConfLogger.dotPlaceholder("Blocked tests", blockedTests); + ConfLogger.dotPlaceholder("Waiting to fix a defect", waitingToFixDefect); + ConfLogger.dotPlaceholder("Waiting for implementation", waitingForImplementation); + ConfLogger.dotPlaceholder("Fixed (did not work before)", fixedCases, GREEN, fixedCases.get() != 0); + ConfLogger.dotPlaceholder("Implemented cases", implemented, GREEN, implemented.get() != 0); + ConfLogger.stepDelimiter(); + String time = DurationFormatUtils.formatDuration(finishTime - startTime, "HH:mm:ss,SSS"); + ConfLogger.dotPlaceholder("Execution time", time); + } + + @Override + public boolean isEnable() { + return true; + } + +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/utils/TestNGHelper.java b/buggy-core/src/main/java/org/touchbit/buggy/core/utils/TestNGHelper.java new file mode 100644 index 0000000..6f7a09f --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/utils/TestNGHelper.java @@ -0,0 +1,31 @@ +package org.touchbit.buggy.core.utils; + +import org.jetbrains.annotations.Nullable; +import org.testng.IInvokedMethod; +import org.testng.ITestNGMethod; +import org.touchbit.buggy.core.model.Details; + +import java.lang.reflect.Method; + +public class TestNGHelper { + + @Nullable + public static Details getDetails(IInvokedMethod method) { + return getDetails(method.getTestMethod()); + } + + @Nullable + public static Details getDetails(ITestNGMethod method) { + return getDetails(method.getConstructorOrMethod().getMethod()); + } + + @Nullable + public static Details getDetails(Method method) { + return method.getAnnotation(Details.class); + } + + private TestNGHelper() { + throw new IllegalStateException("Utility class. Prohibit instantiation."); + } + +} 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 index 1d41356..78b8062 100644 --- 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 @@ -13,7 +13,7 @@ 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.log.ConfigurationLogger; +import org.touchbit.buggy.core.log.ConfLogger; import org.touchbit.buggy.core.log.FrameworkLogger; import org.touchbit.buggy.core.log.appender.DecomposeTestLogsFileAppender; import org.touchbit.buggy.core.model.Suite; @@ -70,22 +70,22 @@ public static void exit(int status, String message) { public static void exit(int status, String message, Exception e) { if (message != null) { - ConfigurationLogger.blockDelimiter(); + ConfLogger.blockDelimiter(); String frameworkLogPath = ""; if (status == 0) { - ConfigurationLogger.info(message); + ConfLogger.info(message); } else { File file = FrameworkLogger.getLogFile(); if (file != null) { frameworkLogPath = "\nFor more information see " + file.getName(); } String eMsg = "\n" + e.getClass().getSimpleName() + ": " + e.getMessage(); - ConfigurationLogger.error(message + eMsg + frameworkLogPath, e); + ConfLogger.error(message + eMsg + frameworkLogPath, e); } } - ConfigurationLogger.blockDelimiter(); - ConfigurationLogger.dotPlaceholder("Exit code", status); - ConfigurationLogger.blockDelimiter(); + ConfLogger.blockDelimiter(); + ConfLogger.dotPlaceholder("Exit code", status); + ConfLogger.blockDelimiter(); System.exit(status); } diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/BuggyConfiguration.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/BuggyConfiguration.java index f6c6f79..423967b 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/BuggyConfiguration.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/BuggyConfiguration.java @@ -13,7 +13,7 @@ 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.log.ConfigurationLogger; +import org.touchbit.buggy.core.log.ConfLogger; import org.touchbit.buggy.core.model.Suite; import org.touchbit.buggy.core.testng.BuggyListener; import org.touchbit.buggy.core.utils.JUtils; @@ -75,32 +75,32 @@ public void beforeConfiguration(final boolean isLogbackConfigurationInitialized) if (!isLogbackConfigurationInitialized) { BuggyRunner.exit(1, "LogbackConfiguration must be initialized"); } - ConfigurationLogger.blockDelimiter(); - ConfigurationLogger.centerBold("Preparing TestNG configuration"); - ConfigurationLogger.stepDelimiter(); + ConfLogger.blockDelimiter(); + ConfLogger.centerBold("Preparing TestNG configuration"); + ConfLogger.stepDelimiter(); } @PostConstruct public void printConfigurationInfo() { - ConfigurationLogger.center("TestNG listeners"); + ConfLogger.center("TestNG listeners"); for (BuggyListener buggyListener : allBuggyListeners) { if (buggyListener.isEnable()) { - ConfigurationLogger.dotPlaceholder(buggyListener.getClass().getSimpleName(), "Enable"); + ConfLogger.dotPlaceholder(buggyListener.getClass().getSimpleName(), "Enable"); } else { - ConfigurationLogger.dotPlaceholder(buggyListener.getClass().getSimpleName(), "Disable"); + ConfLogger.dotPlaceholder(buggyListener.getClass().getSimpleName(), "Disable"); } } - ConfigurationLogger.stepDelimiter(); - ConfigurationLogger.center("Available suites goals"); - ConfigurationLogger.stepDelimiter(); - ConfigurationLogger.center("Components"); - availableComponents.forEach(g -> ConfigurationLogger.dotPlaceholder(JUtils.getSimpleNameC(g), g.getName())); - ConfigurationLogger.stepDelimiter(); - ConfigurationLogger.center("Services"); - availableServices.forEach(g -> ConfigurationLogger.dotPlaceholder(JUtils.getSimpleNameC(g), g.getName())); - ConfigurationLogger.stepDelimiter(); - ConfigurationLogger.center("Interfaces"); - availableInterfaces.forEach(g -> ConfigurationLogger.dotPlaceholder(JUtils.getSimpleNameC(g), g.getName())); + ConfLogger.stepDelimiter(); + ConfLogger.center("Available suites goals"); + ConfLogger.stepDelimiter(); + ConfLogger.center("Components"); + availableComponents.forEach(g -> ConfLogger.dotPlaceholder(JUtils.getSimpleNameC(g), g.getName())); + ConfLogger.stepDelimiter(); + ConfLogger.center("Services"); + availableServices.forEach(g -> ConfLogger.dotPlaceholder(JUtils.getSimpleNameC(g), g.getName())); + ConfLogger.stepDelimiter(); + ConfLogger.center("Interfaces"); + availableInterfaces.forEach(g -> ConfLogger.dotPlaceholder(JUtils.getSimpleNameC(g), g.getName())); } public Set> filterTestClassesByBuggyConfig(Set> testClassesWithSuiteAnnotation) { 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 index a365359..5813b5b 100644 --- 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 @@ -11,7 +11,7 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.touchbit.buggy.core.config.BuggyConfig; -import org.touchbit.buggy.core.log.ConfigurationLogger; +import org.touchbit.buggy.core.log.ConfLogger; import org.touchbit.buggy.core.utils.JUtils; import org.touchbit.buggy.spring.boot.starter.BuggyRunner; import org.touchbit.buggy.spring.boot.starter.jcommander.BuggyJCommand; @@ -58,9 +58,9 @@ public JCommanderConfiguration(final ApplicationProperties properties, final App } public void beforeConfiguration() { - ConfigurationLogger.blockDelimiter(); - ConfigurationLogger.centerBold("JCommander configuration construction"); - ConfigurationLogger.stepDelimiter(); + ConfLogger.blockDelimiter(); + ConfLogger.centerBold("JCommander configuration construction"); + ConfLogger.stepDelimiter(); } @Bean @@ -71,14 +71,14 @@ public boolean isJCommanderConfigured() { @PostConstruct public void postConstruct() { if (BuggyConfig.isHelp()) { - ConfigurationLogger.stepDelimiter(); + ConfLogger.stepDelimiter(); jCommander.usage(); BuggyRunner.exit(0); } if (BuggyConfig.isVersion()) { - ConfigurationLogger.stepDelimiter(); - ConfigurationLogger.centerBold("Version info"); - JUtils.getBuggyManifest().forEach(ConfigurationLogger::dotPlaceholder); + ConfLogger.stepDelimiter(); + ConfLogger.centerBold("Version info"); + JUtils.getBuggyManifest().forEach(ConfLogger::dotPlaceholder); BuggyRunner.exit(0); } printConfigurationsParams(buggyConfigurations); @@ -114,9 +114,9 @@ private JCommander buildJCommander() { } else { jCommander.addObject(config); } - ConfigurationLogger.dotPlaceholder(config.getClass().getSimpleName(), "OK"); + ConfLogger.dotPlaceholder(config.getClass().getSimpleName(), "OK"); } catch (Exception e) { - ConfigurationLogger.dotPlaceholder(config.getClass().getSimpleName(), "FAIL"); + ConfLogger.dotPlaceholder(config.getClass().getSimpleName(), "FAIL"); BuggyRunner.exit(1, "Unexpected error while loading Jcommander configs", e); } } @@ -126,11 +126,11 @@ private JCommander buildJCommander() { public void parseArguments() { try { jCommander.parse(args); - ConfigurationLogger.stepDelimiter(); - ConfigurationLogger.dotPlaceholder("Parsing arguments", "OK"); + ConfLogger.stepDelimiter(); + ConfLogger.dotPlaceholder("Parsing arguments", "OK"); } catch (Exception e) { - ConfigurationLogger.stepDelimiter(); - ConfigurationLogger.dotPlaceholder("Parsing arguments", "FAIL"); + ConfLogger.stepDelimiter(); + ConfLogger.dotPlaceholder("Parsing arguments", "FAIL"); printConfigurationsParams(buggyConfigurations); BuggyRunner.exit(e.getMessage(), e); } @@ -151,7 +151,7 @@ public void checkConfiguration(JCommand config) { Parameter parameter = field.getAnnotation(Parameter.class); if (parameter != null && !Modifier.isStatic(field.getModifiers())) { String[] names = parameter.names(); - ConfigurationLogger.dotPlaceholder(config.getClass().getSimpleName(), "FAIL"); + 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."); @@ -179,7 +179,7 @@ public void checkConfiguration(JCommand config) { "(method name must start with 'is' or 'set')."; } if (error != null) { - ConfigurationLogger.dotPlaceholder(config.getClass().getSimpleName(), "FAIL"); + ConfLogger.dotPlaceholder(config.getClass().getSimpleName(), "FAIL"); printConfigurationParams(config); BuggyRunner.exit(1, error); } @@ -197,10 +197,10 @@ public void printConfigurationsParams(Map, JCommand> c public void printConfigurationParams(JCommand config) { Map params = config.configurationToMap(); if (params != null && !params.isEmpty()) { - ConfigurationLogger.stepDelimiter(); - ConfigurationLogger.center(config.getClass().getSimpleName()); + ConfLogger.stepDelimiter(); + ConfLogger.center(config.getClass().getSimpleName()); for (Map.Entry entry : params.entrySet()) { - ConfigurationLogger.dotPlaceholder(entry.getKey(), entry.getValue()); + 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 index 0005153..6942c98 100644 --- 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 @@ -5,7 +5,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.env.ConfigurableEnvironment; import org.touchbit.buggy.core.log.BaseLogbackWrapper; -import org.touchbit.buggy.core.log.ConfigurationLogger; +import org.touchbit.buggy.core.log.ConfLogger; import org.touchbit.buggy.core.log.FrameworkLogger; import org.touchbit.buggy.spring.boot.starter.BuggyRunner; @@ -32,9 +32,9 @@ public LogbackConfiguration(boolean isJCommanderConfigured, ConfigurableEnvironm if (!isJCommanderConfigured) { BuggyRunner.exit(1, "JCommander must be initialized"); } - ConfigurationLogger.blockDelimiter(); - ConfigurationLogger.centerBold("Logback configuration (" + BaseLogbackWrapper.getConfFileName() + ")"); - ConfigurationLogger.stepDelimiter(); + 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) { @@ -44,7 +44,7 @@ public LogbackConfiguration(boolean isJCommanderConfigured, ConfigurableEnvironm name = c.getSimpleName() + ".class"; } catch (ClassNotFoundException ignore) { } - ConfigurationLogger.dotPlaceholder(name, logger.getLevel()); + ConfLogger.dotPlaceholder(name, logger.getLevel()); } } isLogbackConfigurationInitialized = true; From 0eda68f9736ed6b208ce04391e825755b8b5761c Mon Sep 17 00:00:00 2001 From: "oleg.shaburov" Date: Wed, 7 Oct 2020 08:17:50 +0300 Subject: [PATCH 16/24] Rename package log -> logback --- .../touchbit/buggy/core/BaseBuggyTest.java | 2 +- .../{log => logback}/BaseLogbackWrapper.java | 2 +- .../core/{log => logback}/ConfLogger.java | 6 +----- .../core/{log => logback}/ConsoleLogger.java | 2 +- .../{log => logback}/FrameworkLogger.java | 2 +- .../{log => logback}/SiftingTestLogger.java | 4 ++-- .../DecomposeTestLogsFileAppender.java | 21 ++++++++++--------- .../layout/ConsoleLoggerColorLayout.java | 5 +---- .../layout/FrameworkLoggerLayout.java | 2 +- .../layout/ShiftingLoggerLayout.java | 2 +- .../testng/BaseBuggyExecutionListener.java | 6 +++--- .../core/testng/BuggyExecutionListener.java | 4 ++-- .../core/testng/TestStatisticListener.java | 2 +- .../src/main/resources/buggy-logback.xml | 8 +++---- .../spring/boot/starter/BuggyRunner.java | 6 +++--- .../boot/starter/conf/BuggyConfiguration.java | 2 +- .../starter/conf/JCommanderConfiguration.java | 2 +- .../starter/conf/LogbackConfiguration.java | 6 +++--- 18 files changed, 39 insertions(+), 45 deletions(-) rename buggy-core/src/main/java/org/touchbit/buggy/core/{log => logback}/BaseLogbackWrapper.java (99%) rename buggy-core/src/main/java/org/touchbit/buggy/core/{log => logback}/ConfLogger.java (95%) rename buggy-core/src/main/java/org/touchbit/buggy/core/{log => logback}/ConsoleLogger.java (76%) rename buggy-core/src/main/java/org/touchbit/buggy/core/{log => logback}/FrameworkLogger.java (96%) rename buggy-core/src/main/java/org/touchbit/buggy/core/{log => logback}/SiftingTestLogger.java (88%) rename buggy-core/src/main/java/org/touchbit/buggy/core/{log => logback}/appender/DecomposeTestLogsFileAppender.java (81%) rename buggy-core/src/main/java/org/touchbit/buggy/core/{log => logback}/layout/ConsoleLoggerColorLayout.java (90%) rename buggy-core/src/main/java/org/touchbit/buggy/core/{log => logback}/layout/FrameworkLoggerLayout.java (97%) rename buggy-core/src/main/java/org/touchbit/buggy/core/{log => logback}/layout/ShiftingLoggerLayout.java (97%) diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/BaseBuggyTest.java b/buggy-core/src/main/java/org/touchbit/buggy/core/BaseBuggyTest.java index d715712..5fd3573 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/BaseBuggyTest.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/BaseBuggyTest.java @@ -19,7 +19,7 @@ import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.testng.annotations.Listeners; -import org.touchbit.buggy.core.log.SiftingTestLogger; +import org.touchbit.buggy.core.logback.SiftingTestLogger; import org.touchbit.buggy.core.testng.BuggyExecutionListener; import org.touchbit.buggy.core.testng.IntellijIdeaTestNgPluginListener; diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/log/BaseLogbackWrapper.java b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/BaseLogbackWrapper.java similarity index 99% rename from buggy-core/src/main/java/org/touchbit/buggy/core/log/BaseLogbackWrapper.java rename to buggy-core/src/main/java/org/touchbit/buggy/core/logback/BaseLogbackWrapper.java index 2165e2c..f92bbfc 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/log/BaseLogbackWrapper.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/BaseLogbackWrapper.java @@ -1,4 +1,4 @@ -package org.touchbit.buggy.core.log; +package org.touchbit.buggy.core.logback; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.core.util.StatusPrinter; diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/log/ConfLogger.java b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/ConfLogger.java similarity index 95% rename from buggy-core/src/main/java/org/touchbit/buggy/core/log/ConfLogger.java rename to buggy-core/src/main/java/org/touchbit/buggy/core/logback/ConfLogger.java index 7fc2207..34327f6 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/log/ConfLogger.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/ConfLogger.java @@ -1,13 +1,9 @@ -package org.touchbit.buggy.core.log; +package org.touchbit.buggy.core.logback; import org.touchbit.buggy.core.utils.ANSI; -import java.util.function.BooleanSupplier; -import java.util.function.Function; - import static java.util.Objects.isNull; import static org.touchbit.buggy.core.utils.ANSI.BOLD; -import static org.touchbit.buggy.core.utils.ANSI.RED; /** * Utility class for logging configuration events in TestNG format diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/log/ConsoleLogger.java b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/ConsoleLogger.java similarity index 76% rename from buggy-core/src/main/java/org/touchbit/buggy/core/log/ConsoleLogger.java rename to buggy-core/src/main/java/org/touchbit/buggy/core/logback/ConsoleLogger.java index e5d2fba..c1a3328 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/log/ConsoleLogger.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/ConsoleLogger.java @@ -1,4 +1,4 @@ -package org.touchbit.buggy.core.log; +package org.touchbit.buggy.core.logback; public class ConsoleLogger extends BaseLogbackWrapper { diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/log/FrameworkLogger.java b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/FrameworkLogger.java similarity index 96% rename from buggy-core/src/main/java/org/touchbit/buggy/core/log/FrameworkLogger.java rename to buggy-core/src/main/java/org/touchbit/buggy/core/logback/FrameworkLogger.java index 69d8dd6..a1cced3 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/log/FrameworkLogger.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/FrameworkLogger.java @@ -1,4 +1,4 @@ -package org.touchbit.buggy.core.log; +package org.touchbit.buggy.core.logback; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.FileAppender; diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/log/SiftingTestLogger.java b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/SiftingTestLogger.java similarity index 88% rename from buggy-core/src/main/java/org/touchbit/buggy/core/log/SiftingTestLogger.java rename to buggy-core/src/main/java/org/touchbit/buggy/core/logback/SiftingTestLogger.java index ba090bf..bd7bce1 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/log/SiftingTestLogger.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/SiftingTestLogger.java @@ -1,7 +1,7 @@ -package org.touchbit.buggy.core.log; +package org.touchbit.buggy.core.logback; import org.slf4j.MDC; -import org.touchbit.buggy.core.log.appender.DecomposeTestLogsFileAppender; +import org.touchbit.buggy.core.logback.appender.DecomposeTestLogsFileAppender; import org.touchbit.buggy.core.model.IStatus; import java.io.File; diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/log/appender/DecomposeTestLogsFileAppender.java b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/appender/DecomposeTestLogsFileAppender.java similarity index 81% rename from buggy-core/src/main/java/org/touchbit/buggy/core/log/appender/DecomposeTestLogsFileAppender.java rename to buggy-core/src/main/java/org/touchbit/buggy/core/logback/appender/DecomposeTestLogsFileAppender.java index d964fee..99a3db9 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/log/appender/DecomposeTestLogsFileAppender.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/appender/DecomposeTestLogsFileAppender.java @@ -1,4 +1,4 @@ -package org.touchbit.buggy.core.log.appender; +package org.touchbit.buggy.core.logback.appender; import ch.qos.logback.core.FileAppender; @@ -9,20 +9,21 @@ import org.touchbit.buggy.core.model.ResultStatus; import org.touchbit.buggy.core.utils.IOHelper; -import static org.touchbit.buggy.core.log.BaseLogbackWrapper.LOG_PATH; +import static org.touchbit.buggy.core.logback.BaseLogbackWrapper.LOG_PATH; import static org.touchbit.buggy.core.model.Status.*; public class DecomposeTestLogsFileAppender extends FileAppender { - public static final Map TEST_LOGS_WITH_STATUS = new HashMap(); + public static final Map TEST_LOGS_WITH_STATUS = new HashMap<>(); public static final String LOG_DIR = System.getProperty(LOG_PATH, "logs"); - public static final File NEW_DIR = new File(LOG_DIR, "1_new"); - public static final File CORRUPTED_DIR = new File(LOG_DIR, "2_corrupted"); - public static final File BLOCKED_DIR = new File(LOG_DIR, "3_blocked"); - public static final File FIXED_DIR = new File(LOG_DIR, "4_fixed"); - public static final File IMPLEMENTED_DIR = new File(LOG_DIR, "5_implemented"); - public static final File EXP_FIX_DIR = new File(LOG_DIR, "6_exp_fix"); - public static final File EXP_IMPL_DIR = new File(LOG_DIR, "7_exp_impl"); + 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"); @Override public void setFile(String file) { diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/log/layout/ConsoleLoggerColorLayout.java b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/layout/ConsoleLoggerColorLayout.java similarity index 90% rename from buggy-core/src/main/java/org/touchbit/buggy/core/log/layout/ConsoleLoggerColorLayout.java rename to buggy-core/src/main/java/org/touchbit/buggy/core/logback/layout/ConsoleLoggerColorLayout.java index 55b4d27..a2c505d 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/log/layout/ConsoleLoggerColorLayout.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/layout/ConsoleLoggerColorLayout.java @@ -1,11 +1,8 @@ -package org.touchbit.buggy.core.log.layout; +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 org.slf4j.MDC; import static ch.qos.logback.classic.Level.*; import static org.touchbit.buggy.core.utils.ANSI.*; diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/log/layout/FrameworkLoggerLayout.java b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/layout/FrameworkLoggerLayout.java similarity index 97% rename from buggy-core/src/main/java/org/touchbit/buggy/core/log/layout/FrameworkLoggerLayout.java rename to buggy-core/src/main/java/org/touchbit/buggy/core/logback/layout/FrameworkLoggerLayout.java index a0a582c..b2df097 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/log/layout/FrameworkLoggerLayout.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/layout/FrameworkLoggerLayout.java @@ -1,4 +1,4 @@ -package org.touchbit.buggy.core.log.layout; +package org.touchbit.buggy.core.logback.layout; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.spi.ILoggingEvent; diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/log/layout/ShiftingLoggerLayout.java b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/layout/ShiftingLoggerLayout.java similarity index 97% rename from buggy-core/src/main/java/org/touchbit/buggy/core/log/layout/ShiftingLoggerLayout.java rename to buggy-core/src/main/java/org/touchbit/buggy/core/logback/layout/ShiftingLoggerLayout.java index d51dcdb..df8bc37 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/log/layout/ShiftingLoggerLayout.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/layout/ShiftingLoggerLayout.java @@ -1,4 +1,4 @@ -package org.touchbit.buggy.core.log.layout; +package org.touchbit.buggy.core.logback.layout; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.classic.spi.IThrowableProxy; 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 index a14d011..0fef4f7 100644 --- 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 @@ -20,9 +20,9 @@ import org.slf4j.Logger; import org.testng.*; import org.touchbit.buggy.core.config.BuggyConfig; -import org.touchbit.buggy.core.log.ConsoleLogger; -import org.touchbit.buggy.core.log.FrameworkLogger; -import org.touchbit.buggy.core.log.SiftingTestLogger; +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.Details; import org.touchbit.buggy.core.model.IStatus; import org.touchbit.buggy.core.model.Suite; 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 index 2804083..9df5ab4 100644 --- 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 @@ -21,8 +21,8 @@ import org.testng.*; import org.touchbit.buggy.core.config.BuggyConfig; import org.touchbit.buggy.core.exceptions.CorruptedTestException; -import org.touchbit.buggy.core.log.ConfLogger; -import org.touchbit.buggy.core.log.SiftingTestLogger; +import org.touchbit.buggy.core.logback.ConfLogger; +import org.touchbit.buggy.core.logback.SiftingTestLogger; import org.touchbit.buggy.core.model.Details; import org.touchbit.buggy.core.model.Status; import org.touchbit.buggy.core.model.Suite; diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/testng/TestStatisticListener.java b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/TestStatisticListener.java index bd85e9e..7397eed 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/testng/TestStatisticListener.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/TestStatisticListener.java @@ -5,7 +5,7 @@ import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestResult; -import org.touchbit.buggy.core.log.ConfLogger; +import org.touchbit.buggy.core.logback.ConfLogger; import org.touchbit.buggy.core.model.Details; import org.touchbit.buggy.core.model.Status; import org.touchbit.buggy.core.utils.TestNGHelper; diff --git a/buggy-core/src/main/resources/buggy-logback.xml b/buggy-core/src/main/resources/buggy-logback.xml index ce2fe73..6dd7464 100644 --- a/buggy-core/src/main/resources/buggy-logback.xml +++ b/buggy-core/src/main/resources/buggy-logback.xml @@ -7,14 +7,14 @@ - + ${logging.file.path}/Framework.log false - + @@ -23,10 +23,10 @@ default-sifting.log - + ${logging.file.path}/${sifting.test.log.file.path} false - + 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 index 78b8062..80adcc9 100644 --- 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 @@ -13,9 +13,9 @@ 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.log.ConfLogger; -import org.touchbit.buggy.core.log.FrameworkLogger; -import org.touchbit.buggy.core.log.appender.DecomposeTestLogsFileAppender; +import org.touchbit.buggy.core.logback.ConfLogger; +import org.touchbit.buggy.core.logback.FrameworkLogger; +import org.touchbit.buggy.core.logback.appender.DecomposeTestLogsFileAppender; import org.touchbit.buggy.core.model.Suite; import org.touchbit.buggy.core.testng.BuggyListener; import org.touchbit.buggy.core.utils.JUtils; diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/BuggyConfiguration.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/BuggyConfiguration.java index 423967b..f63e15c 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/BuggyConfiguration.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/BuggyConfiguration.java @@ -13,7 +13,7 @@ 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.log.ConfLogger; +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; 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 index 5813b5b..b24aa7d 100644 --- 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 @@ -11,7 +11,7 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.touchbit.buggy.core.config.BuggyConfig; -import org.touchbit.buggy.core.log.ConfLogger; +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.BuggyJCommand; 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 index 6942c98..0017159 100644 --- 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 @@ -4,9 +4,9 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.ConfigurableEnvironment; -import org.touchbit.buggy.core.log.BaseLogbackWrapper; -import org.touchbit.buggy.core.log.ConfLogger; -import org.touchbit.buggy.core.log.FrameworkLogger; +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; From 1377071df1d9bf7946db26491f30758b5874d0da Mon Sep 17 00:00:00 2001 From: "oleg.shaburov" Date: Thu, 8 Oct 2020 02:08:53 +0300 Subject: [PATCH 17/24] LoggingListener v1 --- .../buggy/core/config/BuggyConfig.java | 8 + .../buggy/core/config/BuggyConfigYML.java | 7 + .../exceptions/BaseBuggyTestException.java | 4 +- .../buggy/core/logback/ConfLogger.java | 10 +- .../buggy/core/logback/FrameworkLogger.java | 10 +- .../DecomposeTestLogsFileAppender.java | 64 +- .../touchbit/buggy/core/model/Details.java | 12 +- .../org/touchbit/buggy/core/model/Status.java | 1 - .../org/touchbit/buggy/core/model/Type.java | 3 + .../testng/BaseBuggyExecutionListener.java | 139 +- .../core/testng/BaseTelegramNotifier.java | 160 +- .../core/testng/BuggyExecutionListener.java | 736 ++---- .../buggy/core/testng/BuggyListener.java | 327 ++- .../IntellijIdeaTestNgPluginListener.java | 20 +- .../buggy/core/testng/LoggingListener.java | 290 +++ .../core/testng/TestStatisticListener.java | 6 +- .../buggy/core/testng/TestSupervisor.java | 3 + .../org/touchbit/buggy/core/utils/ANSI.java | 4 + .../buggy/core/utils/TestNGHelper.java | 27 +- .../buggy/core/tests/BaseUnitTest.java | 61 +- .../testng/BaseTelegramNotifierTests.java | 352 +-- .../testng/BuggyExecutionListenerTests.java | 2186 ----------------- .../starter/example/ExampleBuggyRunner.java | 1 + .../boot/starter/example/ExampleTests2.java | 14 +- .../boot/starter/example/ExampleTests3.java | 10 +- .../src/main/resources/buggy-config.yml | 19 + .../spring/boot/starter/BuggyRunner.java | 6 +- .../starter/jcommander/BuggyJCommand.java | 11 + .../src/main/resources/application.yml | 2 +- .../listeners/BaseTestRailListener.java | 8 +- .../listeners/DefaultTestRailListener.java | 2 +- 31 files changed, 1334 insertions(+), 3169 deletions(-) create mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/testng/LoggingListener.java delete mode 100644 buggy-core/src/test/java/org/touchbit/buggy/core/tests/testng/BuggyExecutionListenerTests.java create mode 100644 buggy-spring-boot-starter-example/src/main/resources/buggy-config.yml diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/config/BuggyConfig.java b/buggy-core/src/main/java/org/touchbit/buggy/core/config/BuggyConfig.java index 996f027..fab1601 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/config/BuggyConfig.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/config/BuggyConfig.java @@ -42,6 +42,7 @@ public final class BuggyConfig { private static List interfaces = JUtils.getListWith(AllInterfaces::new); private static List types = JUtils.getListWith(ALL); private static String programName = "Buggy"; + private static String taskTrackerIssueUrl = ""; public static void setPrintLogFileOnlyFail(Boolean printLogIfFail) { BuggyConfig.printLogOnlyFail = printLogIfFail; @@ -229,4 +230,11 @@ public static void setProgramName(String programName) { BuggyConfig.programName = programName; } + public static String getTaskTrackerIssueUrl() { + return taskTrackerIssueUrl; + } + + public static void setTaskTrackerIssueUrl(String taskTrackerIssueUrl) { + BuggyConfig.taskTrackerIssueUrl = taskTrackerIssueUrl; + } } diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/config/BuggyConfigYML.java b/buggy-core/src/main/java/org/touchbit/buggy/core/config/BuggyConfigYML.java index 828aa57..c0826b6 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/config/BuggyConfigYML.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/config/BuggyConfigYML.java @@ -79,4 +79,11 @@ public void setProgramName(String programName) { BuggyConfig.setProgramName(programName); } + public String getTaskTrackerIssueUrl() { + return BuggyConfig.getTaskTrackerIssueUrl(); + } + + public void setTaskTrackerIssueUrl(String taskTrackerIssueUrl) { + BuggyConfig.setTaskTrackerIssueUrl(taskTrackerIssueUrl); + } } 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..020718a 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 @@ -32,11 +32,11 @@ protected static String getMsg(String brief, Details details) { sb.append(brief); if (details != null) { String[] tmp; - tmp = details.issue(); + tmp = details.issues(); if (tmp.length > 0) { sb.append(". Related issues: ").append(Arrays.toString(tmp)); } - tmp = details.bug(); + tmp = details.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/logback/ConfLogger.java b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/ConfLogger.java index 34327f6..276294f 100644 --- 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 @@ -1,5 +1,6 @@ package org.touchbit.buggy.core.logback; +import org.touchbit.buggy.core.model.Status; import org.touchbit.buggy.core.utils.ANSI; import static java.util.Objects.isNull; @@ -34,7 +35,7 @@ public static void blockDelimiter() { } public static void dotPlaceholder(Object prefix, Object postfix, ANSI ansi, boolean isWrapCondition) { - String msg = filler(prefix, DOT, postfix); + String msg = getDotPlaceholder(prefix, postfix); if (isWrapCondition) { msg = ansi.wrap(msg); } @@ -42,7 +43,11 @@ public static void dotPlaceholder(Object prefix, Object postfix, ANSI ansi, bool } public static void dotPlaceholder(Object prefix, Object postfix) { - info(filler(prefix, DOT, postfix)); + info(getDotPlaceholder(prefix, postfix)); + } + + public static String getDotPlaceholder(Object prefix, Object postfix) { + return filler(prefix, DOT, postfix); } public static void underscorePlaceholder(Object prefix, Object postfix) { @@ -118,4 +123,5 @@ public static void error(String msg) { CONSOLE.error(msg); } + } 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 index a1cced3..01bf143 100644 --- 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 @@ -16,14 +16,14 @@ public FrameworkLogger() { public static File getLogFile() { for (ch.qos.logback.classic.Logger logger : getLoggerList()) { - List> collect = Stream.generate(logger.iteratorForAppenders()::next) + FileAppender appender = Stream.generate(logger.iteratorForAppenders()::next) .limit(1000) - .filter(appender -> appender instanceof FileAppender) + .filter(a -> a instanceof FileAppender) .filter(fileAppender -> fileAppender.getName().equals(FRAMEWORK_LOGGER_NAME)) .map(f -> (FileAppender) f) - .collect(Collectors.toList()); - if (!collect.isEmpty()) { - return new File(collect.get(1).getFile()); + .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/appender/DecomposeTestLogsFileAppender.java b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/appender/DecomposeTestLogsFileAppender.java index 99a3db9..35311d8 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/logback/appender/DecomposeTestLogsFileAppender.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/appender/DecomposeTestLogsFileAppender.java @@ -7,6 +7,7 @@ import org.touchbit.buggy.core.model.IStatus; import org.touchbit.buggy.core.model.ResultStatus; +import org.touchbit.buggy.core.model.Status; import org.touchbit.buggy.core.utils.IOHelper; import static org.touchbit.buggy.core.logback.BaseLogbackWrapper.LOG_PATH; @@ -28,7 +29,7 @@ public class DecomposeTestLogsFileAppender extends FileAppender { @Override public void setFile(String file) { super.setFile(file); - TEST_LOGS_WITH_STATUS.put(new File(file), UNTESTED); + TEST_LOGS_WITH_STATUS.put(new File(file), NONE); } public static File getFile(String fileName) { @@ -50,32 +51,41 @@ public static void decomposeTestLogs() { for (Map.Entry log : TEST_LOGS_WITH_STATUS.entrySet()) { String fileName = log.getKey().getName(); File destFile = null; - switch (ResultStatus.valueOf(log.getValue().getStatus())) { - 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 + IStatus testLogStatus = log.getValue(); + ResultStatus resultStatus = null; + for (ResultStatus value : ResultStatus.values()) { + if (value.getStatus().equals(testLogStatus.getStatus())) { + resultStatus = value; + } + } + 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 { 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/Details.java index 96e51c9..0093174 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/Details.java @@ -21,7 +21,7 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import static org.touchbit.buggy.core.model.Status.UNTESTED; +import static org.touchbit.buggy.core.model.Status.NONE; /** * Interface of binding test methods. @@ -37,27 +37,27 @@ /** * Test-case identifiers */ - long[] id() default -1; + String[] caseIDs() default {""}; /** * Test status (see: {@link Status}) * Used values: EXP_IMPL, EXP_FIX, BLOCKED, CORRUPTED */ - Status status() default UNTESTED; + Status status() default NONE; /** * Issues ID in the task-tracker system. Format: "STORY-269" */ - String[] issue() default {""}; + String[] issues() default {}; /** * Defects ID in the task-tracker system. Format: "BUG-354" */ - String[] bug() default {""}; + String[] bugs() default {}; /** * Type of auto test */ - Type[] type() default {Type.REGRESSION}; + Type[] types() default {Type.REGRESSION}; } 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 6cd839b..bfd322e 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 @@ -41,7 +41,6 @@ public enum Status implements IStatus { // Result statuses FIXED, IMPLEMENTED, - UNTESTED, SUCCESS, SKIP, FAILED, 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 da30f6c..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 @@ -48,6 +48,9 @@ public enum Type { SYSTEM, ACCEPTANCE, // Helper type for filtering. + SLOW, + NORMAL, + FAST, ALL, ; 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 index 0fef4f7..ef77428 100644 --- 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 @@ -16,23 +16,15 @@ package org.touchbit.buggy.core.testng; -import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.testng.*; -import org.touchbit.buggy.core.config.BuggyConfig; 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.Details; -import org.touchbit.buggy.core.model.IStatus; -import org.touchbit.buggy.core.model.Suite; -import java.io.File; -import java.lang.reflect.Method; import java.util.Arrays; -import java.util.Date; import java.util.StringJoiner; -import java.util.concurrent.atomic.AtomicInteger; /** * Created by Oleg Shaburov on 16.05.2018 @@ -41,25 +33,12 @@ @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 = new SiftingTestLogger(); } @@ -71,84 +50,8 @@ public void onExecutionStart() { } } - @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, IStatus status) { - // Do not change the check. Feature parsing values by jCommander library. - if (!"null".equalsIgnoreCase(String.valueOf(BuggyConfig.getArtifactsUrl()))) { - return BuggyConfig.getArtifactsUrl().endsWith("/") ? - BuggyConfig.getArtifactsUrl() : - BuggyConfig.getArtifactsUrl() + "/"; - } else { - String fileName = getInvokedMethodLogFileName(method); - SiftingTestLogger.setTestStatus(fileName, status); - File file = SiftingTestLogger.getSiftingLogFile(fileName); - if (file != null) { - return "file://" + file.getAbsolutePath(); - } else { - return "Log file not found: " + fileName; - } - } - } - - 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()) { + for (String s : details.issues()) { if (!s.isEmpty()) { return true; } @@ -157,11 +60,11 @@ protected boolean isIssuesPresent(Details details) { } protected String getIssues(Details details) { - String[] issues = details.issue(); + String[] issues = details.issues(); if (issues.length == 0) { return ""; } - return Arrays.toString(details.issue()); + return Arrays.toString(details.issues()); } protected String buildDetailsMessage(Details details, Object... appends) { @@ -177,40 +80,4 @@ protected String buildDetailsMessage(Details details, Object... appends) { 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/BaseTelegramNotifier.java b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/BaseTelegramNotifier.java index 2bbac30..6d4ae43 100644 --- 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 @@ -41,85 +41,85 @@ public BaseTelegramNotifier(final 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); - } +// +// @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 index 9df5ab4..2e8cbce 100644 --- 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 @@ -21,7 +21,6 @@ import org.testng.*; import org.touchbit.buggy.core.config.BuggyConfig; import org.touchbit.buggy.core.exceptions.CorruptedTestException; -import org.touchbit.buggy.core.logback.ConfLogger; import org.touchbit.buggy.core.logback.SiftingTestLogger; import org.touchbit.buggy.core.model.Details; import org.touchbit.buggy.core.model.Status; @@ -40,7 +39,6 @@ import static org.testng.ITestResult.SKIP; import static org.testng.ITestResult.SUCCESS; import static org.testng.ITestResult.*; -import static org.touchbit.buggy.core.model.Status.*; /** * Listener for processing executable tests. @@ -101,476 +99,278 @@ public void onExecutionStart() { @Override public void onExecutionFinish() { super.onExecutionFinish(); - System.out.println(" >>>>>>>>>>>>>>> " + this.getClass()); // 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 (!BuggyConfig.isForce()) { - 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); - SiftingTestLogger.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.annotationType().getTypeName()); - } - testLog.debug("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); - } - - } - - 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); - List configType = BuggyConfig.getTypes(); - if (details != null) { - List methodTypes = new ArrayList<>(Arrays.asList(details.type())); - boolean matched = methodTypes.stream().anyMatch(configType::contains); - if (!configType.contains(Type.ALL) && !matched) { - method.setInvocationCount(0); - resultLog(method, Status.SKIP, buildDetailsMessage(details, details.type(), "test types")); - } - } - }); - } - - public void copyTestMethodLogFile(IInvokedMethod method) throws IOException { - Details details = getDetails(method); - int iTestResultStatus = method.getTestResult().getStatus(); - File sourceFile = new File(getInvokedMethodLogFileName(method)); - File targetFile = null; - if (details == null) { - if (iTestResultStatus == FAILURE || iTestResultStatus == SUCCESS_PERCENTAGE_FAILURE) { - targetFile = new File("new", 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("fixed", getInvokedMethodLogFileName(method)); - } - if (status.equals(EXP_IMPL)) { - targetFile = new File("implemented", getInvokedMethodLogFileName(method)); - } - break; - case ITestResult.FAILURE: - case ITestResult.SUCCESS_PERCENTAGE_FAILURE: - switch (status) { - case EXP_FIX: - targetFile = new File("exp_fix", getInvokedMethodLogFileName(method)); - break; - case EXP_IMPL: - targetFile = new File("exp_impl", getInvokedMethodLogFileName(method)); - break; - case BLOCKED: - targetFile = new File("blocked", getInvokedMethodLogFileName(method)); - break; - case CORRUPTED: - targetFile = new File("corrupted", getInvokedMethodLogFileName(method)); - break; - default: - targetFile = new File("new", getInvokedMethodLogFileName(method)); - } - default: - // ignore unhandled statuses - } - if (targetFile != null) { - copyFile(sourceFile, targetFile); - } - } - - 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() : "")); - 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() { - ConfLogger.blockDelimiter(); -// if (Buggy.getBuggyErrors() > 0) { -// consoleLog.error(StringUtils.dotFiller("Framework errors", 47, Buggy.getBuggyErrors())); +// +// @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 (Buggy.getBuggyWarns() > 0) { -// consoleLog.warn(StringUtils.dotFiller("Framework warns", 47, Buggy.getBuggyWarns())); +// if (result.getStatus() == ITestResult.SKIP) { +// testLog.warn("The test {} is skipped.", method.getName()); +// return; // } -// if (Buggy.getBuggyErrors() > 0 || Buggy.getBuggyWarns() > 0) { -// ConfigurationLogger.blockDelimiter(); +// 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()); // } - 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()); - ConfLogger.blockDelimiter(); - 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) { - ConfLogger.blockDelimiter(); - checkDebugAndPrint("Fixed cases", fixed.get()); - checkDebugAndPrint("Implemented cases", implemented.get()); - } - ConfLogger.blockDelimiter(); - consoleLog.info(StringUtils.dotFiller("Execution time", 47, org.apache.commons.lang3.time.DurationFormatUtils - .formatDuration(finishTime - startTime, "HH:mm:ss,SSS"))); - ConfLogger.blockDelimiter(); - } - - 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 - } +// 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 (!BuggyConfig.isForce()) { +// disableTestsByStatus(suite); +// } +// } +// +// @Override +// public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { +// STEPS.set(new ArrayList<>()); +// String methodName = getMethodName(method); +// SiftingTestLogger.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.annotationType().getTypeName()); +// } +// testLog.debug("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()) { +// 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); +// } +// +// } +// +// 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); +// List configType = BuggyConfig.getTypes(); +// if (details != null) { +// List methodTypes = new ArrayList<>(Arrays.asList(details.types())); +// boolean matched = methodTypes.stream().anyMatch(configType::contains); +// if (!configType.contains(Type.ALL) && !matched) { +// method.setInvocationCount(0); +// resultLog(method, Status.SKIP, buildDetailsMessage(details, details.types(), "test types")); +// } +// } +// }); +// } +// +// 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 index f7b85f5..8fcef49 100644 --- 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 @@ -1,6 +1,16 @@ package org.touchbit.buggy.core.testng; -import org.testng.ITestNGListener; +import org.jetbrains.annotations.Nullable; +import org.testng.*; +import org.touchbit.buggy.core.model.Details; +import org.touchbit.buggy.core.model.ResultStatus; +import org.touchbit.buggy.core.model.Status; +import org.touchbit.buggy.core.model.Suite; + +import java.lang.reflect.Method; +import java.util.function.Function; + +import static org.touchbit.buggy.core.model.Status.*; /** * Created by Oleg Shaburov on 28.05.2018 @@ -10,4 +20,319 @@ public interface BuggyListener extends ITestNGListener { boolean isEnable(); + default boolean isRun(IInvokedMethod method) { + throwNPE(method); + return isRun(method.getTestMethod()); + } + + default boolean isRun(ITestNGMethod method) { + throwNPE(method); + return method.getInvocationCount() > 0; + } + + default boolean isSkip(IInvokedMethod method) { + throwNPE(method); + if (isRun(method)) { + return false; + } + return isSkip(method.getTestResult()); + } + + default boolean isSkip(ITestResult result) { + throwNPE(result); + return isITestResultSkip(result); + } + + default boolean isSuccess(IInvokedMethod method) { + throwNPE(method); + if (!hasDetails(method)) { + return isITestResultSuccess(method); + } + Status status = getDetailsValue(Details::status, method); + return status.equals(NONE) && isITestResultSuccess(method); + } + + default boolean isNewError(IInvokedMethod method) { + throwNPE(method); + if (!hasDetails(method)) { + return isITestResultFailure(method); + } + Status status = getDetailsValue(Details::status, method); + return status.equals(NONE) && isITestResultFailure(method); + } + + default boolean isFixed(IInvokedMethod method) { + throwNPE(method); + if (!hasDetails(method)) { + return false; + } + Status status = getDetailsValue(Details::status, method); + return (status.equals(EXP_FIX) || status.equals(BLOCKED) || status.equals(CORRUPTED)) && + isITestResultSuccess(method); + } + + default boolean isImplemented(IInvokedMethod method) { + throwNPE(method); + if (!hasDetails(method)) { + return false; + } + Status status = getDetailsValue(Details::status, method); + return status.equals(EXP_IMPL) && isITestResultSuccess(method); + } + + default boolean isExpectedImplementation(IInvokedMethod method) { + throwNPE(method); + if (!hasDetails(method)) { + return false; + } + Status status = getDetailsValue(Details::status, method); + return status.equals(EXP_IMPL) && isITestResultFailure(method); + } + + default boolean isExpectedFix(IInvokedMethod method) { + throwNPE(method); + if (!hasDetails(method)) { + return false; + } + Status status = getDetailsValue(Details::status, method); + return status.equals(EXP_FIX) && isITestResultFailure(method); + } + + default boolean isCorrupted(IInvokedMethod method) { + throwNPE(method); + if (!hasDetails(method)) { + return false; + } + Status status = getDetailsValue(Details::status, method); + return status.equals(CORRUPTED) && isITestResultFailure(method); + } + + default boolean isBlocked(IInvokedMethod method) { + throwNPE(method); + if (!hasDetails(method)) { + return false; + } + Status status = getDetailsValue(Details::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) { + throwNPE(method); + return isITestResultSuccess(method.getTestResult()); + } + + default boolean isITestResultSuccess(ITestResult testResult) { + throwNPE(testResult); + int status = testResult.getStatus(); + return status == ITestResult.SUCCESS; + } + + default boolean isITestResultFailure(IInvokedMethod method) { + throwNPE(method); + return isITestResultFailure(method.getTestResult()); + } + + + default boolean isITestResultFailure(ITestResult result) { + throwNPE(result); + int iTestResult = getITestResultStatus(result); + return iTestResult == ITestResult.FAILURE || iTestResult == ITestResult.SUCCESS_PERCENTAGE_FAILURE; + } + + default boolean isITestResultSkip(IInvokedMethod method) { + throwNPE(method); + return isITestResultSkip(method.getTestResult()); + } + + default boolean isITestResultSkip(ITestResult result) { + throwNPE(result); + int iTestResult = getITestResultStatus(result); + return iTestResult == ITestResult.SKIP; + } + + default T getDetailsValue(Function function, IInvokedMethod method) { + throwNPE(method); + Details details = getDetails(method); + return getDetailsValue(function, details); + } + + default T getDetailsValue(Function function, Details details) { + throwNPE(details); + return function.apply(details); + } + + default int getITestResultStatus(ITestResult iTestResult) { + throwNPE(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(); + return description != null && !description.isEmpty(); + } + + default String getDescription(IInvokedMethod method) { + if (hasDescription(method)) { + return getDescription(method.getTestMethod()); + } + return ""; + } + + default String getDescription(ITestNGMethod method) { + if (hasDescription(method)) { + return method.getDescription(); + } + return ""; + } + + default boolean hasDetails(IInvokedMethod method) { + if (method != null) { + return hasDetails(method.getTestMethod()); + } + return false; + } + + default boolean hasDetails(ITestNGMethod method) { + if (method != null) { + return hasDetails(method.getConstructorOrMethod().getMethod()); + } + return false; + } + + default boolean hasDetails(Method method) { + if (method != null) { + return method.isAnnotationPresent(Details.class); + } + return false; + } + + @Nullable + default Details getDetails(IInvokedMethod method) { + if (hasDetails(method)) { + return getDetails(method.getTestMethod()); + } + return null; + } + + @Nullable + default Details getDetails(ITestNGMethod method) { + if (hasDetails(method)) { + return getDetails(method.getConstructorOrMethod().getMethod()); + } + return null; + } + + @Nullable + default Details getDetails(Method method) { + if (hasDetails(method)) { + return method.getAnnotation(Details.class); + } + return null; + } + + default boolean hasSuite(IInvokedMethod method) { + if (method != null) { + return hasSuite(method.getTestMethod()); + } + return false; + } + + default boolean hasSuite(ITestClass iTestClass) { + if (iTestClass != null) { + return hasSuite(iTestClass.getRealClass()); + } + return false; + } + + default boolean hasSuite(ITestNGMethod method) { + if (method != null) { + return hasSuite(method.getRealClass()); + } + return false; + } + + default boolean hasSuite(Class realClass) { + return realClass.isAnnotationPresent(Suite.class); + } + + @Nullable + default Suite getSuite(IInvokedMethod method) { + if (hasSuite(method)) { + return getSuite(method.getTestMethod()); + } + return null; + } + + @Nullable + default Suite getSuite(ITestClass iTestClass) { + if (hasSuite(iTestClass)) { + return getSuite(iTestClass.getRealClass()); + } + return null; + } + + @Nullable + default Suite getSuite(ITestNGMethod method) { + if (hasSuite(method)) { + return getSuite(method.getRealClass()); + } + return null; + } + + @Nullable + default Suite getSuite(Class realClass) { + if (hasSuite(realClass)) { + return realClass.getAnnotation(Suite.class); + } + return null; + } + + default void throwNPE(Object o) { + if (o == null) { + throw new NullPointerException(); + } + } + + } 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 index 2576fc3..183d7ce 100644 --- 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 @@ -16,7 +16,10 @@ package org.touchbit.buggy.core.testng; +import org.testng.IInvokedMethod; import org.testng.ITestNGListener; +import org.testng.ITestResult; +import org.touchbit.buggy.core.logback.SiftingTestLogger; import org.touchbit.buggy.core.utils.JUtils; /** @@ -25,15 +28,28 @@ * Created by Oleg Shaburov on 15.05.2018 * shaburov.o.a@gmail.com */ -public final class IntellijIdeaTestNgPluginListener extends BuggyExecutionListener implements ITestNGListener { +public final class IntellijIdeaTestNgPluginListener extends LoggingListener { public IntellijIdeaTestNgPluginListener() { if (JUtils.isJetBrainsIdeTestNGPluginRun()) { - consoleLog.info("IntellijIdeaTestNgPluginListener enabled"); JUtils.initBuggyConfigurationYml(); } } + @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/LoggingListener.java b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/LoggingListener.java new file mode 100644 index 0000000..397b2e3 --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/LoggingListener.java @@ -0,0 +1,290 @@ +/* + * 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.BuggyConfig; +import org.touchbit.buggy.core.exceptions.CorruptedTestException; +import org.touchbit.buggy.core.logback.ConfLogger; +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.*; +import org.touchbit.buggy.core.utils.JUtils; +import org.touchbit.buggy.core.utils.StringUtils; +import org.touchbit.buggy.core.utils.TestNGHelper; + +import java.io.File; +import java.lang.reflect.Method; +import java.util.*; + +import static org.testng.ITestResult.*; +import static org.touchbit.buggy.core.utils.ANSI.*; + +/** + * Listener for processing executable tests. + *

+ * Created by Shaburov Oleg on 31.07.2017. + */ +public class LoggingListener implements BuggyListener, IInvokedMethodListener { + + private static final FrameworkLogger FRAMEWORK = new FrameworkLogger(); + private static final ConsoleLogger CONSOLE = new ConsoleLogger(); + private static final SiftingTestLogger TEST = new SiftingTestLogger(); + + @Override + public boolean isEnable() { + return true; + } + + @Override + public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { + SiftingTestLogger.setTestLogFileName(getLogFileName(method)); + } + + @Override + public void afterInvocation(IInvokedMethod method, ITestResult testResult) { + TEST.info("Date: {}", new Date()); + Boolean printLog = BuggyConfig.isPrintLog(); + Boolean printSuite = BuggyConfig.isPrintSuite(); + Boolean printCause = BuggyConfig.isPrintCause(); + String methodName = TestNGHelper.getMethodName(method); + Throwable throwable = testResult.getThrowable(); + if (hasDetails(method) && hasSuite(method) && method.isTestMethod()) { + Details details = getDetails(method); + Suite suite = getSuite(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 = details.status(); + Type[] types = details.types(); + String[] ids = details.caseIDs(); + String[] issues = details.issues(); + String[] bugs = details.bugs(); + String indent = " "; + + String dotPlaceholder = ConfLogger.getDotPlaceholder(methodName, status); + StringBuilder message = new StringBuilder(); + message.append(dotPlaceholder); + if (printSuite) { + message.append(" [") + .append(component).append(" ") + .append(service).append(" ") + .append(interfaze); + if (!purpose.isEmpty()) { + message.append(" ").append(purpose); + } + message.append("]"); + } + if (hasDescription(method)) { +// message.append("\n").append(" § ").append(description); + message.append("\n Case: ").append(getDescription(method)); + indent += indent; + } + if (printLog) { + message.append("\n Log: ").append(getLogFilePath(method.getTestMethod(), status)); + indent += indent; + } + if (printCause && bugs.length > 0) { + if (BuggyConfig.getTaskTrackerIssueUrl() != null && !BuggyConfig.getTaskTrackerIssueUrl().isEmpty()) { + for (String bug : bugs) { +// message.append("\n └").append(BOLD.wrap(RED.wrap(" ❗ "))) + message.append("\n Bug: ").append(BuggyConfig.getTaskTrackerIssueUrl()).append(bug); + } + } else { + message.append(" ").append(Arrays.toString(bugs)); + } + } + if (true) { + if (BuggyConfig.getTaskTrackerIssueUrl() != null && !BuggyConfig.getTaskTrackerIssueUrl().isEmpty()) { + for (String bug : bugs) { +// message.append("\n └").append(BOLD.wrap(GREEN.wrap(" ✓ "))) + message.append("\n Issue: ").append(BuggyConfig.getTaskTrackerIssueUrl()).append(bug); + } + } else { + message.append(" ").append(Arrays.toString(bugs)); + } + } + + if (printCause && 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()); +// processTestMethodResult(method, testResult, details); + } else { +// processConfigurationMethodResult(method, testResult); + } + } +// +// public void resultLog(ITestNGMethod method, Status status, String details) { +// String methodName = method.getMethodName(); +// Suite suite = TestNGHelper.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()); +// } +// TEST.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() : "")); +// } +// +// 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: +// FRAMEWORK.error("Received unprocessed status: {}", testResult.getStatus()); +//// Buggy.incrementBuggyErrors(); +// } +// } +// +// public void processConfigurationMethodResult(IInvokedMethod method, ITestResult testResult) { +// String methodName = TestNGHelper.getMethodName(method); +// String description = getDescription(method); +// switch (testResult.getStatus()) { +// case SUCCESS: +// TEST.info("Invoke configuration method [{}] completed successfully", methodName); +// break; +// case SKIP: +// TEST.warn("Invoke configuration method [{}] skipped. " + +// "List of dependent tests that were missed: {}", methodName, description); +// break; +// case SUCCESS_PERCENTAGE_FAILURE: +// case FAILURE: +// TEST.error("Invoke configuration method [{}] completed with error \n{}", +// methodName, testResult.getThrowable().getMessage()); +// break; +// default: +//// Buggy.incrementBuggyErrors(); +// FRAMEWORK.error("Received unresolved status of configuration method [{}]. Status: {}", +// methodName, testResult.getStatus()); +// } +// } +// +// +// 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 String getLogFilePath(ITestNGMethod method, IStatus status) { + // Do not change the check. Feature parsing values by jCommander library. + if (!"null".equalsIgnoreCase(String.valueOf(BuggyConfig.getArtifactsUrl()))) { + return BuggyConfig.getArtifactsUrl().endsWith("/") ? + BuggyConfig.getArtifactsUrl() : + BuggyConfig.getArtifactsUrl() + "/"; + } else { + String fileName = getLogFileName(method); + SiftingTestLogger.setTestStatus(fileName, status); + File file = SiftingTestLogger.getSiftingLogFile(fileName); + if (file != null) { + return "file://" + file.getAbsolutePath(); + } else { + return "Log file not found: " + fileName; + } + } + } + + protected String getLogFileName(IInvokedMethod method) { + return getLogFileName(method.getTestMethod()); + } + + protected String getLogFileName(ITestNGMethod iTestNGMethod) { + Method method = iTestNGMethod.getConstructorOrMethod().getMethod(); + return method.getName() + ".log"; + } + +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/testng/TestStatisticListener.java b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/TestStatisticListener.java index 7397eed..73b478d 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/testng/TestStatisticListener.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/TestStatisticListener.java @@ -50,7 +50,7 @@ public void onExecutionFinish() { @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) { if (method.isTestMethod()) { - Details details = TestNGHelper.getDetails(method); + Details details = getDetails(method); if (details == null) { notDetailedTests.incrementAndGet(); // TODO remove after --check realisation } @@ -79,7 +79,7 @@ public void afterInvocation(IInvokedMethod method, ITestResult testResult) { case EXP_IMPL: implemented.incrementAndGet(); break; - case UNTESTED: + case NONE: break; default: // do nothing @@ -99,7 +99,7 @@ public void afterInvocation(IInvokedMethod method, ITestResult testResult) { case EXP_IMPL: waitingForImplementation.incrementAndGet(); break; - case UNTESTED: + case NONE: default: newErrors.incrementAndGet(); } diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/testng/TestSupervisor.java b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/TestSupervisor.java index ec55b61..2ae0d0d 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/testng/TestSupervisor.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/TestSupervisor.java @@ -13,6 +13,9 @@ import java.util.List; import java.util.StringJoiner; +import static org.touchbit.buggy.core.utils.TestNGHelper.getClassSimpleName; +import static org.touchbit.buggy.core.utils.TestNGHelper.getMethodName; + /** * Created by Oleg Shaburov on 16.09.2018 * shaburov.o.a@gmail.com 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 index 8435b16..ba86b75 100644 --- 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 @@ -8,6 +8,7 @@ public enum ANSI { GREEN("\u001B[32m"), BLUE("\u001B[34m"), PURPLE("\u001B[35m"), + NONE(""), ; String symbol; @@ -25,6 +26,9 @@ public static String unwrap(final String msg) { } 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/TestNGHelper.java b/buggy-core/src/main/java/org/touchbit/buggy/core/utils/TestNGHelper.java index 6f7a09f..91f8bb8 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/utils/TestNGHelper.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/utils/TestNGHelper.java @@ -2,26 +2,33 @@ import org.jetbrains.annotations.Nullable; import org.testng.IInvokedMethod; +import org.testng.ITestClass; import org.testng.ITestNGMethod; -import org.touchbit.buggy.core.model.Details; +import org.testng.ITestResult; import java.lang.reflect.Method; public class TestNGHelper { - @Nullable - public static Details getDetails(IInvokedMethod method) { - return getDetails(method.getTestMethod()); + public static Method getRealMethod(ITestResult result) { + return getRealMethod(result.getMethod()); } - @Nullable - public static Details getDetails(ITestNGMethod method) { - return getDetails(method.getConstructorOrMethod().getMethod()); + public static Method getRealMethod(IInvokedMethod method) { + return getRealMethod(method.getTestMethod()); } - @Nullable - public static Details getDetails(Method method) { - return method.getAnnotation(Details.class); + public static Method getRealMethod(ITestNGMethod method) { + return method.getConstructorOrMethod().getMethod(); + } + + + public static String getClassSimpleName(IInvokedMethod method) { + return method.getTestMethod().getRealClass().getSimpleName(); + } + + public static String getMethodName(IInvokedMethod method) { + return method.getTestMethod().getMethodName(); } private TestNGHelper() { 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 4547dc4..3ee285a 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 @@ -146,13 +146,13 @@ protected static Details getDetails(Status status, String... issue) { } protected static Details getDetails(Status status, Type type, String... issue) { - return getDetails(new long[0], status, new Type[]{type}, issue); + return getDetails(new String[] {"0"}, status, new Type[]{type}, issue); } - protected static Details getDetails(long[] ids, Status status, Type[] type, String... issue) { + protected static Details getDetails(String[] ids, Status status, Type[] type, String... issue) { return new Details() { @Override - public long[] id() { + public String[] caseIDs() { return ids; } @@ -162,17 +162,17 @@ public Status status() { } @Override - public String[] issue() { + public String[] issues() { return issue; } @Override - public String[] bug() { + public String[] bugs() { return new String[]{}; } @Override - public Type[] type() { + public Type[] types() { return type; } @@ -268,12 +268,12 @@ protected BuggyExecutionListener getBuggyExecutionListener(boolean withOverrideC 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); - } - } +// @Override +// public void copyFile(File sourceFile, File destFile) throws IOException { +// if (!withOverrideCopyFile) { +// super.copyFile(sourceFile, destFile); +// } +// } }; @@ -303,43 +303,6 @@ public UnitTestBuggyExecutionListener(Logger testLogger, Logger frameworkLogger, 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); } } 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 index 8d6bafc..554d843 100644 --- 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 @@ -32,182 +32,182 @@ */ @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 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") diff --git a/buggy-core/src/test/java/org/touchbit/buggy/core/tests/testng/BuggyExecutionListenerTests.java b/buggy-core/src/test/java/org/touchbit/buggy/core/tests/testng/BuggyExecutionListenerTests.java deleted file mode 100644 index e1517bc..0000000 --- a/buggy-core/src/test/java/org/touchbit/buggy/core/tests/testng/BuggyExecutionListenerTests.java +++ /dev/null @@ -1,2186 +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.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.exceptions.ExpectedImplementationException; -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.Status; -import org.touchbit.buggy.core.model.Suite; -import org.touchbit.buggy.core.testng.BuggyExecutionListener; -import org.touchbit.buggy.core.tests.BaseUnitTest; - -import java.lang.annotation.Annotation; -import java.util.ArrayList; -import java.util.List; - -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.model.Status.*; -import static org.touchbit.buggy.core.model.Type.SMOKE; - -/** - * 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 = BuggyConfig.getTypes(); -// boolean isForceRun = BuggyConfig.isForce(); -// try { -// BuggyConfig.setTypes(MODULE); -// BuggyConfig.setForce(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 { -// BuggyConfig.setType(configType); -// BuggyConfig.setForceRun(isForceRun); -// } -// } -// -// @Test -// @DisplayName("Check onStart() if forceRun enabled") -// void unitTest_20180922085022() { -// Type configType = BuggyConfig.getType(); -// boolean isForceRun = BuggyConfig.isForceRun(); -// try { -// BuggyConfig.setType(MODULE); -// BuggyConfig.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 { -// BuggyConfig.setType(configType); -// BuggyConfig.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); - } - - @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" - )); - } - - @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 = BuggyConfig.getType(); -// try { -// BuggyConfig.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 { -// BuggyConfig.setType(configType); -// } -// } -// -// @Test -// @DisplayName("Check disabling the test, if config !Type.isIncludeOrEquals(testType)") -// void unitTest_20180922081522() { -// Type configType = BuggyConfig.getType(); -// try { -// BuggyConfig.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 { -// BuggyConfig.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 purpose() { - 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() { -// BuggyConfig.setPrintSuite(true); -// BuggyConfig.setPrintCause(false); -// BuggyConfig.setPrintLog(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() { -// BuggyConfig.setPrintSuite(false); -// BuggyConfig.setPrintCause(true); -// BuggyConfig.setPrintLog(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() { -// BuggyConfig.setPrintCause(false); -// BuggyConfig.setPrintSuite(false); -// BuggyConfig.setPrintLog(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() { -// BuggyConfig.setPrintCause(true); -// BuggyConfig.setPrintSuite(true); -// BuggyConfig.setPrintLog(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("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-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 index 1d37eaa..10545ba 100644 --- 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 @@ -14,6 +14,7 @@ public class ExampleBuggyRunner extends BuggyRunner { BuggyJCommand.setPrintLog(true); BuggyJCommand.setPrintSuite(true); BuggyJCommand.setPrintCause(true); + BuggyJCommand.setTaskTrackerIssueUrl("https://example.jira.com/issues/"); } public static void main(String[] args) { diff --git a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleTests2.java b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleTests2.java index add8823..d938b83 100644 --- a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleTests2.java +++ b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleTests2.java @@ -1,18 +1,24 @@ package org.touchbit.buggy.spring.boot.starter.example; 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.Details; import org.touchbit.buggy.core.model.Status; import org.touchbit.buggy.core.model.Suite; @Suite(interfaze = API.class) -public class ExampleTests2 { +public class ExampleTests2 extends BaseBuggyTest { - @Test - @Details(status = Status.EXP_FIX) + @Test(description = "Ожидается успешное создание пользователя, если firstName=<пустая строка>") + @Details(status = Status.EXP_FIX, bugs = "JIRA-123") public void test_2() { - + 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]'>"); } } diff --git a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleTests3.java b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleTests3.java index 5457539..b40ce21 100644 --- a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleTests3.java +++ b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleTests3.java @@ -6,13 +6,17 @@ import org.touchbit.buggy.core.model.Details; 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 - @Details - public void test_3() { - throw new CorruptedTestException(" >>> ? "); + @Details(status = CORRUPTED) + public void test_3() throws Exception { + throw new ProtocolException("Received HTTP_PROXY_AUTH (407) code while not using proxy"); } } 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..6c8438c --- /dev/null +++ b/buggy-spring-boot-starter-example/src/main/resources/buggy-config.yml @@ -0,0 +1,19 @@ +programName: Buggy +help: false +force: true +printSuite: true +printCause: true +printLog: true +printLogOnlyFail: false +threads: 50 +artifactsUrl: null +parallelMode: 'METHODS' +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 +taskTrackerIssueUrl: 'https://example.jira.com/issues/' \ 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 index 80adcc9..9e00d0d 100644 --- 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 @@ -79,8 +79,10 @@ public static void exit(int status, String message, Exception e) { if (file != null) { frameworkLogPath = "\nFor more information see " + file.getName(); } - String eMsg = "\n" + e.getClass().getSimpleName() + ": " + e.getMessage(); - ConfLogger.error(message + eMsg + frameworkLogPath, e); + if (e != null) { + message += "\n" + e.getClass().getSimpleName() + ": " + e.getMessage(); + } + ConfLogger.error(message + frameworkLogPath, e); } } ConfLogger.blockDelimiter(); diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/BuggyJCommand.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/BuggyJCommand.java index 70d827e..5d6cb37 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/BuggyJCommand.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/BuggyJCommand.java @@ -154,12 +154,19 @@ public static void setProgramName(String programName) { BuggyConfig.setProgramName(programName); } + @Parameter(names = {"--task-tracker-issue-url"}, description = "TODO") + public static void setTaskTrackerIssueUrl(String taskTrackerIssueUrl) { + BuggyConfig.setTaskTrackerIssueUrl(taskTrackerIssueUrl); + } + public static Boolean isHelp() { return BuggyConfig.isHelp(); } + public static Boolean isPrintLogFileOnlyFail() { return BuggyConfig.isPrintLog(); } + public static Boolean isForce() { return BuggyConfig.isForce(); } @@ -212,6 +219,10 @@ public static String getProgramName() { return BuggyConfig.getProgramName(); } + public static String getTaskTrackerIssueUrl() { + return BuggyConfig.getTaskTrackerIssueUrl(); + } + @Override public Map sort(Map map) { String[] sort = new String[] diff --git a/buggy-spring-boot-starter/src/main/resources/application.yml b/buggy-spring-boot-starter/src/main/resources/application.yml index 76d67f5..cd09784 100644 --- a/buggy-spring-boot-starter/src/main/resources/application.yml +++ b/buggy-spring-boot-starter/src/main/resources/application.yml @@ -1,7 +1,7 @@ logging: config: 'classpath:buggy-logback.xml' file: - path: logs + path: /tmp/logs buggy: commandsScannerBasePackages: - "**.buggy" 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 1240aa1..04c6589 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 @@ -96,14 +96,14 @@ protected void addResult(ITestResult result, Details details, S status, String c } try { Long runID = Long.parseLong(strRunID); - for (Long caseId : details.id()) { + for (String caseId : details.caseIDs()) { if (statusMapper.getId(status) > 0) { StringJoiner defects = new StringJoiner(", "); - for (String bug : details.bug()) { + for (String bug : details.bugs()) { defects.add(bug); } TRResult trResult = new TRResult() - .withCaseId(caseId) + .withCaseId(Long.valueOf(caseId)) .withStatusId(statusMapper.getId(status)) .withComment(msg) .withDefects(defects.toString()); @@ -122,7 +122,7 @@ protected String addAttachments(ITestResult testResult) { Method method = testResult.getMethod().getConstructorOrMethod().getMethod(); Details trCase = method.getAnnotation(Details.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); } 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 d4b7042..2c55cd3 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 @@ -106,7 +106,7 @@ public long getId(Status status) { case BLOCKED: case SKIP: return Statuses.BLOCKED.getId(); - case UNTESTED: + case NONE: return Statuses.UNTESTED.getId(); case FAILED: case CORRUPTED: From 40b866a7ed755410040ab63160861a2b2912f9cd Mon Sep 17 00:00:00 2001 From: Shaburov Oleg Date: Sat, 10 Oct 2020 04:31:10 +0300 Subject: [PATCH 18/24] snakeyaml: write values to static fields --- .../buggy/core/config/BuggyConfigYML.java | 89 -------- ...Config.java => BuggyConfigurationYML.java} | 61 ++--- .../buggy/core/config/ConfigurationYML.java | 34 +++ .../core/goal/component/AllComponents.java | 8 + .../buggy/core/logback/ConfLogger.java | 1 - .../buggy/core/logback/FrameworkLogger.java | 2 - .../DecomposeTestLogsFileAppender.java | 11 +- .../snakeyaml/BuggyYamlPropertyUtils.java | 39 ++++ .../testng/BaseBuggyExecutionListener.java | 2 +- .../core/testng/BaseTelegramNotifier.java | 5 - .../core/testng/BuggyExecutionListener.java | 21 +- .../IntellijIdeaTestNgPluginListener.java | 8 +- ...Listener.java => LoggingListenerBase.java} | 44 ++-- .../core/testng/TestStatisticListener.java | 1 - .../org/touchbit/buggy/core/utils/JUtils.java | 27 +-- .../buggy/core/utils/TestNGHelper.java | 2 - .../src/main/resources/buggy-config.yml | 9 +- .../buggy/core/tests/BaseUnitTest.java | 2 - .../tests/config/JCommanderConfigTests.java | 64 +++--- .../BaseBuggyExecutionListenerTests.java | 7 - .../testng/BaseTelegramNotifierTests.java | 1 - .../starter/example/ExampleBuggyRunner.java | 19 +- .../example/{ => tests}/ExampleTests.java | 3 +- .../example/{ => tests}/ExampleTests2.java | 2 +- .../example/{ => tests}/ExampleTests3.java | 3 +- .../src/main/resources/buggy-config.yml | 14 +- .../src/main/resources/testng-1.0.dtd | 213 ++++++++++++++++++ buggy-spring-boot-starter/pom.xml | 7 + .../spring/boot/starter/BuggyRunner.java | 14 +- ...ion.java => BuggyRunnerConfiguration.java} | 18 +- .../starter/conf/JCommanderConfiguration.java | 18 +- ...yJCommand.java => BuggyConfiguration.java} | 88 ++++---- .../boot/starter/jcommander/JCommand.java | 33 ++- .../jcommander/converters/GoalConverter.java | 17 +- buggy-testng-listeners/pom.xml | 28 +++ .../testng/listeners/LoggingListener.java | 12 + .../listeners/BaseTestRailListener.java | 6 +- pom.xml | 15 +- 38 files changed, 570 insertions(+), 378 deletions(-) delete mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/config/BuggyConfigYML.java rename buggy-core/src/main/java/org/touchbit/buggy/core/config/{BuggyConfig.java => BuggyConfigurationYML.java} (77%) create mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/config/ConfigurationYML.java create mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/snakeyaml/BuggyYamlPropertyUtils.java rename buggy-core/src/main/java/org/touchbit/buggy/core/testng/{LoggingListener.java => LoggingListenerBase.java} (90%) rename buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/{ => tests}/ExampleTests.java (84%) rename buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/{ => tests}/ExampleTests2.java (94%) rename buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/{ => tests}/ExampleTests3.java (81%) create mode 100644 buggy-spring-boot-starter-example/src/main/resources/testng-1.0.dtd rename buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/{BuggyConfiguration.java => BuggyRunnerConfiguration.java} (93%) rename buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/{BuggyJCommand.java => BuggyConfiguration.java} (72%) create mode 100644 buggy-testng-listeners/pom.xml create mode 100644 buggy-testng-listeners/src/main/java/org/touchbit/buggy/testng/listeners/LoggingListener.java diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/config/BuggyConfigYML.java b/buggy-core/src/main/java/org/touchbit/buggy/core/config/BuggyConfigYML.java deleted file mode 100644 index c0826b6..0000000 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/config/BuggyConfigYML.java +++ /dev/null @@ -1,89 +0,0 @@ -package org.touchbit.buggy.core.config; - -import org.touchbit.buggy.core.exceptions.BuggyConfigurationException; -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.core.utils.JUtils; - -import java.util.List; -import java.util.stream.Collectors; - -public final class BuggyConfigYML { - - public void setHelp(Boolean help) { - BuggyConfig.setHelp(help); - } - - public void setForce(Boolean force) { - BuggyConfig.setForce(force); - } - - public void setPrintSuite(Boolean printSuite) { - BuggyConfig.setPrintSuite(printSuite); - } - - public void setPrintCause(Boolean printCause) { - BuggyConfig.setPrintCause(printCause); - } - - public void setPrintLog(Boolean printLog) { - BuggyConfig.setPrintLog(printLog); - } - - public void setPrintLogOnlyFail(Boolean printLogOnlyFail) { - BuggyConfig.setPrintLogOnlyFail(printLogOnlyFail); - } - - public void setVersion(Boolean version) { - BuggyConfig.setVersion(version); - } - - public void setThreads(Integer threads) { - BuggyConfig.setThreads(threads); - } - - public void setArtifactsUrl(String artifactsUrl) { - BuggyConfig.setArtifactsUrl(artifactsUrl); - } - - public void setParallelMode(ParallelMode parallelMode) { - BuggyConfig.setParallelMode(parallelMode); - } - - public void setComponents(List components) { - BuggyConfig.setComponents(components.stream() - .map(c -> (Component) JUtils.newInstance(c, BuggyConfigurationException::new)) - .collect(Collectors.toList())); - } - - public void setServices(List services) { - BuggyConfig.setServices(services.stream() - .map(s -> (Service) JUtils.newInstance(s, BuggyConfigurationException::new)) - .collect(Collectors.toList())); - } - - public void setInterfaces(List interfaces) { - BuggyConfig.setInterfaces(interfaces.stream() - .map(i -> (Interface) JUtils.newInstance(i, BuggyConfigurationException::new)) - .collect(Collectors.toList())); - } - - public void setTypes(List types) { - BuggyConfig.setTypes(types); - } - - public void setProgramName(String programName) { - BuggyConfig.setProgramName(programName); - } - - public String getTaskTrackerIssueUrl() { - return BuggyConfig.getTaskTrackerIssueUrl(); - } - - public void setTaskTrackerIssueUrl(String taskTrackerIssueUrl) { - BuggyConfig.setTaskTrackerIssueUrl(taskTrackerIssueUrl); - } -} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/config/BuggyConfig.java b/buggy-core/src/main/java/org/touchbit/buggy/core/config/BuggyConfigurationYML.java similarity index 77% rename from buggy-core/src/main/java/org/touchbit/buggy/core/config/BuggyConfig.java rename to buggy-core/src/main/java/org/touchbit/buggy/core/config/BuggyConfigurationYML.java index fab1601..dc7cb0b 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/config/BuggyConfig.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/config/BuggyConfigurationYML.java @@ -25,7 +25,7 @@ * shaburov.o.a@gmail.com */ @SuppressWarnings("unused") -public final class BuggyConfig { +public final class BuggyConfigurationYML implements ConfigurationYML { private static Boolean help = false; private static Boolean force = false; @@ -42,10 +42,10 @@ public final class BuggyConfig { private static List interfaces = JUtils.getListWith(AllInterfaces::new); private static List types = JUtils.getListWith(ALL); private static String programName = "Buggy"; - private static String taskTrackerIssueUrl = ""; + private static String issuesUrl = ""; public static void setPrintLogFileOnlyFail(Boolean printLogIfFail) { - BuggyConfig.printLogOnlyFail = printLogIfFail; + BuggyConfigurationYML.printLogOnlyFail = printLogIfFail; } public static Boolean isPrintLogFileOnlyFail() { @@ -53,11 +53,11 @@ public static Boolean isPrintLogFileOnlyFail() { } public static Boolean isHelp() { - return BuggyConfig.help; + return BuggyConfigurationYML.help; } public static void setHelp(Boolean help) { - BuggyConfig.help = help; + BuggyConfigurationYML.help = help; } public static Boolean isForce() { @@ -65,7 +65,7 @@ public static Boolean isForce() { } public static void setForce(Boolean force) { - BuggyConfig.force = force; + BuggyConfigurationYML.force = force; } public static Boolean isPrintSuite() { @@ -73,7 +73,7 @@ public static Boolean isPrintSuite() { } public static void setPrintSuite(Boolean printSuite) { - BuggyConfig.printSuite = printSuite; + BuggyConfigurationYML.printSuite = printSuite; } public static Boolean isPrintCause() { @@ -81,7 +81,7 @@ public static Boolean isPrintCause() { } public static void setPrintCause(Boolean printCause) { - BuggyConfig.printCause = printCause; + BuggyConfigurationYML.printCause = printCause; } public static Boolean isPrintLog() { @@ -89,11 +89,11 @@ public static Boolean isPrintLog() { } public static void setPrintLog(Boolean printLog) { - BuggyConfig.printLog = printLog; + BuggyConfigurationYML.printLog = printLog; } public static void setPrintLogOnlyFail(Boolean printLogOnlyFail) { - BuggyConfig.printLogOnlyFail = printLogOnlyFail; + BuggyConfigurationYML.printLogOnlyFail = printLogOnlyFail; } public static Boolean isVersion() { @@ -101,7 +101,7 @@ public static Boolean isVersion() { } public static void setVersion(Boolean version) { - BuggyConfig.version = version; + BuggyConfigurationYML.version = version; } public static Integer getThreads() { @@ -109,7 +109,7 @@ public static Integer getThreads() { } public static void setThreads(Integer threads) { - BuggyConfig.threads = threads; + BuggyConfigurationYML.threads = threads; } public static String getArtifactsUrl() { @@ -117,7 +117,7 @@ public static String getArtifactsUrl() { } public static void setArtifactsUrl(String artifactsUrl) { - BuggyConfig.artifactsUrl = artifactsUrl; + BuggyConfigurationYML.artifactsUrl = artifactsUrl; } public static List getTypes() { @@ -126,7 +126,7 @@ public static List getTypes() { public static void setTypes(List types) { if (types != null) { - BuggyConfig.types = types; + BuggyConfigurationYML.types = types; } } @@ -142,7 +142,7 @@ public static List getServices() { public static void setServices(List services) { if (services != null) { - BuggyConfig.services = services; + BuggyConfigurationYML.services = services; } } @@ -155,10 +155,10 @@ public static void setServices(S... services) { @SafeVarargs public static void setServices(Class... services) { - BuggyConfig.services = new ArrayList<>(); + BuggyConfigurationYML.services = new ArrayList<>(); for (Class service : services) { Service instance = JUtils.newInstance(service, BuggyConfigurationException::new); - BuggyConfig.services.add(instance); + BuggyConfigurationYML.services.add(instance); } } @@ -168,7 +168,7 @@ public static List getInterfaces() { public static void setInterfaces(List interfaces) { if (interfaces != null) { - BuggyConfig.interfaces = interfaces; + BuggyConfigurationYML.interfaces = interfaces; } } @@ -181,10 +181,10 @@ public static void setInterfaces(I... interfaces) { @SafeVarargs public static void setInterfaces(Class... interfaces) { - BuggyConfig.interfaces = new ArrayList<>(); + BuggyConfigurationYML.interfaces = new ArrayList<>(); for (Class anInterface : interfaces) { Interface instance = JUtils.newInstance(anInterface, BuggyConfigurationException::new); - BuggyConfig.interfaces.add(instance); + BuggyConfigurationYML.interfaces.add(instance); } } @@ -194,7 +194,7 @@ public static List getComponents() { public static void setComponents(List components) { if (components != null) { - BuggyConfig.components = components; + BuggyConfigurationYML.components = components; } } @@ -207,10 +207,10 @@ public static void setComponents(C... components) { @SafeVarargs public static void setComponents(Class... components) { - BuggyConfig.components = new ArrayList<>(); + BuggyConfigurationYML.components = new ArrayList<>(); for (Class component : components) { Component instance = JUtils.newInstance(component, BuggyConfigurationException::new); - BuggyConfig.components.add(instance); + BuggyConfigurationYML.components.add(instance); } } @@ -219,22 +219,23 @@ public static ParallelMode getParallelMode() { } public static void setParallelMode(ParallelMode parallelMode) { - BuggyConfig.parallelMode = parallelMode; + BuggyConfigurationYML.parallelMode = parallelMode; } public static String getProgramName() { - return BuggyConfig.programName; + return BuggyConfigurationYML.programName; } public static void setProgramName(String programName) { - BuggyConfig.programName = programName; + BuggyConfigurationYML.programName = programName; } - public static String getTaskTrackerIssueUrl() { - return taskTrackerIssueUrl; + public static String getIssuesUrl() { + return issuesUrl; } - public static void setTaskTrackerIssueUrl(String taskTrackerIssueUrl) { - BuggyConfig.taskTrackerIssueUrl = taskTrackerIssueUrl; + public static void setIssuesUrl(String issuesUrl) { + BuggyConfigurationYML.issuesUrl = issuesUrl; } + } 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..8c12f1f --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/config/ConfigurationYML.java @@ -0,0 +1,34 @@ +package org.touchbit.buggy.core.config; + +import org.touchbit.buggy.core.snakeyaml.BuggyYamlPropertyUtils; +import org.touchbit.buggy.core.utils.JUtils; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; +import org.yaml.snakeyaml.representer.Representer; + +import java.io.InputStream; + +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) { + Representer representer = new Representer(); + BuggyYamlPropertyUtils propertyUtils = new BuggyYamlPropertyUtils(); + propertyUtils.setSkipMissingProperties(true); + propertyUtils.setBeanAccess(FIELD); + representer.setPropertyUtils(propertyUtils); + Constructor constructor = new Constructor(configClass); + Yaml yaml = new Yaml(constructor, representer); + InputStream inputStream = JUtils.getCurrentThreadClassLoader().getResourceAsStream(BUGGY_CONFIG_YML); + yaml.load(inputStream); + } + +} diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/goal/component/AllComponents.java b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/component/AllComponents.java index 3ea19ac..e9631ff 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/goal/component/AllComponents.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/component/AllComponents.java @@ -22,6 +22,14 @@ */ public final class AllComponents extends Component { + public AllComponents() { + + } + + public AllComponents(Object o) { + + } + @Override public String getName() { return "ALL"; 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 index 276294f..e38729b 100644 --- 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 @@ -1,6 +1,5 @@ package org.touchbit.buggy.core.logback; -import org.touchbit.buggy.core.model.Status; import org.touchbit.buggy.core.utils.ANSI; import static java.util.Objects.isNull; 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 index 01bf143..2915724 100644 --- 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 @@ -4,8 +4,6 @@ import ch.qos.logback.core.FileAppender; import java.io.File; -import java.util.List; -import java.util.stream.Collectors; import java.util.stream.Stream; public class FrameworkLogger extends BaseLogbackWrapper { diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/logback/appender/DecomposeTestLogsFileAppender.java b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/appender/DecomposeTestLogsFileAppender.java index 35311d8..a341e5b 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/logback/appender/DecomposeTestLogsFileAppender.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/appender/DecomposeTestLogsFileAppender.java @@ -1,17 +1,16 @@ package org.touchbit.buggy.core.logback.appender; import ch.qos.logback.core.FileAppender; - -import java.io.File; -import java.util.*; - import org.touchbit.buggy.core.model.IStatus; import org.touchbit.buggy.core.model.ResultStatus; -import org.touchbit.buggy.core.model.Status; import org.touchbit.buggy.core.utils.IOHelper; +import java.io.File; +import java.util.HashMap; +import java.util.Map; + import static org.touchbit.buggy.core.logback.BaseLogbackWrapper.LOG_PATH; -import static org.touchbit.buggy.core.model.Status.*; +import static org.touchbit.buggy.core.model.Status.NONE; public class DecomposeTestLogsFileAppender extends FileAppender { 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/testng/BaseBuggyExecutionListener.java b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/BaseBuggyExecutionListener.java index ef77428..3e62041 100644 --- 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 @@ -17,7 +17,7 @@ package org.touchbit.buggy.core.testng; import org.slf4j.Logger; -import org.testng.*; +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; 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 index 6d4ae43..675ce15 100644 --- 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 @@ -16,13 +16,8 @@ package org.touchbit.buggy.core.testng; -import org.apache.commons.lang3.time.DurationFormatUtils; import org.testng.IExecutionListener; -import org.touchbit.buggy.core.config.BuggyConfig; import org.touchbit.buggy.core.model.Notifier; -import org.touchbit.buggy.core.utils.StringUtils; - -import java.util.StringJoiner; /** * Created by Oleg Shaburov on 06.09.2018 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 index 2e8cbce..b2d2a31 100644 --- 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 @@ -19,26 +19,9 @@ import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.testng.*; -import org.touchbit.buggy.core.config.BuggyConfig; -import org.touchbit.buggy.core.exceptions.CorruptedTestException; -import org.touchbit.buggy.core.logback.SiftingTestLogger; -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.IOHelper; -import org.touchbit.buggy.core.utils.JUtils; -import org.touchbit.buggy.core.utils.StringUtils; -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.SKIP; -import static org.testng.ITestResult.SUCCESS; -import static org.testng.ITestResult.*; +import java.util.ArrayList; +import java.util.List; /** * Listener for processing executable tests. 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 index 183d7ce..190d687 100644 --- 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 @@ -17,9 +17,9 @@ package org.touchbit.buggy.core.testng; import org.testng.IInvokedMethod; -import org.testng.ITestNGListener; import org.testng.ITestResult; -import org.touchbit.buggy.core.logback.SiftingTestLogger; +import org.touchbit.buggy.core.config.BuggyConfigurationYML; +import org.touchbit.buggy.core.config.ConfigurationYML; import org.touchbit.buggy.core.utils.JUtils; /** @@ -28,11 +28,11 @@ * Created by Oleg Shaburov on 15.05.2018 * shaburov.o.a@gmail.com */ -public final class IntellijIdeaTestNgPluginListener extends LoggingListener { +public final class IntellijIdeaTestNgPluginListener extends LoggingListenerBase { public IntellijIdeaTestNgPluginListener() { if (JUtils.isJetBrainsIdeTestNGPluginRun()) { - JUtils.initBuggyConfigurationYml(); + ConfigurationYML.initConfigurationYml(BuggyConfigurationYML.class); } } diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/testng/LoggingListener.java b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/LoggingListenerBase.java similarity index 90% rename from buggy-core/src/main/java/org/touchbit/buggy/core/testng/LoggingListener.java rename to buggy-core/src/main/java/org/touchbit/buggy/core/testng/LoggingListenerBase.java index 397b2e3..2134abd 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/testng/LoggingListener.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/LoggingListenerBase.java @@ -16,41 +16,37 @@ package org.touchbit.buggy.core.testng; -import org.testng.*; -import org.touchbit.buggy.core.config.BuggyConfig; -import org.touchbit.buggy.core.exceptions.CorruptedTestException; +import org.testng.IInvokedMethod; +import org.testng.IInvokedMethodListener; +import org.testng.ITestNGMethod; +import org.testng.ITestResult; +import org.touchbit.buggy.core.config.BuggyConfigurationYML; import org.touchbit.buggy.core.logback.ConfLogger; 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.*; import org.touchbit.buggy.core.utils.JUtils; -import org.touchbit.buggy.core.utils.StringUtils; import org.touchbit.buggy.core.utils.TestNGHelper; import java.io.File; import java.lang.reflect.Method; -import java.util.*; +import java.util.Arrays; +import java.util.Date; -import static org.testng.ITestResult.*; -import static org.touchbit.buggy.core.utils.ANSI.*; +import static org.touchbit.buggy.core.utils.ANSI.RED; /** * Listener for processing executable tests. *

* Created by Shaburov Oleg on 31.07.2017. */ -public class LoggingListener implements BuggyListener, IInvokedMethodListener { +public abstract class LoggingListenerBase implements BuggyListener, IInvokedMethodListener { private static final FrameworkLogger FRAMEWORK = new FrameworkLogger(); private static final ConsoleLogger CONSOLE = new ConsoleLogger(); private static final SiftingTestLogger TEST = new SiftingTestLogger(); - @Override - public boolean isEnable() { - return true; - } - @Override public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { SiftingTestLogger.setTestLogFileName(getLogFileName(method)); @@ -59,9 +55,9 @@ public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) { TEST.info("Date: {}", new Date()); - Boolean printLog = BuggyConfig.isPrintLog(); - Boolean printSuite = BuggyConfig.isPrintSuite(); - Boolean printCause = BuggyConfig.isPrintCause(); + Boolean printLog = BuggyConfigurationYML.isPrintLog(); + Boolean printSuite = BuggyConfigurationYML.isPrintSuite(); + Boolean printCause = BuggyConfigurationYML.isPrintCause(); String methodName = TestNGHelper.getMethodName(method); Throwable throwable = testResult.getThrowable(); if (hasDetails(method) && hasSuite(method) && method.isTestMethod()) { @@ -103,20 +99,20 @@ public void afterInvocation(IInvokedMethod method, ITestResult testResult) { indent += indent; } if (printCause && bugs.length > 0) { - if (BuggyConfig.getTaskTrackerIssueUrl() != null && !BuggyConfig.getTaskTrackerIssueUrl().isEmpty()) { + if (BuggyConfigurationYML.getIssuesUrl() != null && !BuggyConfigurationYML.getIssuesUrl().isEmpty()) { for (String bug : bugs) { // message.append("\n └").append(BOLD.wrap(RED.wrap(" ❗ "))) - message.append("\n Bug: ").append(BuggyConfig.getTaskTrackerIssueUrl()).append(bug); + message.append("\n Bug: ").append(BuggyConfigurationYML.getIssuesUrl()).append(bug); } } else { message.append(" ").append(Arrays.toString(bugs)); } } if (true) { - if (BuggyConfig.getTaskTrackerIssueUrl() != null && !BuggyConfig.getTaskTrackerIssueUrl().isEmpty()) { + if (BuggyConfigurationYML.getIssuesUrl() != null && !BuggyConfigurationYML.getIssuesUrl().isEmpty()) { for (String bug : bugs) { // message.append("\n └").append(BOLD.wrap(GREEN.wrap(" ✓ "))) - message.append("\n Issue: ").append(BuggyConfig.getTaskTrackerIssueUrl()).append(bug); + message.append("\n Issue: ").append(BuggyConfigurationYML.getIssuesUrl()).append(bug); } } else { message.append(" ").append(Arrays.toString(bugs)); @@ -262,10 +258,10 @@ public void afterInvocation(IInvokedMethod method, ITestResult testResult) { protected String getLogFilePath(ITestNGMethod method, IStatus status) { // Do not change the check. Feature parsing values by jCommander library. - if (!"null".equalsIgnoreCase(String.valueOf(BuggyConfig.getArtifactsUrl()))) { - return BuggyConfig.getArtifactsUrl().endsWith("/") ? - BuggyConfig.getArtifactsUrl() : - BuggyConfig.getArtifactsUrl() + "/"; + if (!"null".equalsIgnoreCase(String.valueOf(BuggyConfigurationYML.getArtifactsUrl()))) { + return BuggyConfigurationYML.getArtifactsUrl().endsWith("/") ? + BuggyConfigurationYML.getArtifactsUrl() : + BuggyConfigurationYML.getArtifactsUrl() + "/"; } else { String fileName = getLogFileName(method); SiftingTestLogger.setTestStatus(fileName, status); diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/testng/TestStatisticListener.java b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/TestStatisticListener.java index 73b478d..7735120 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/testng/TestStatisticListener.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/TestStatisticListener.java @@ -8,7 +8,6 @@ import org.touchbit.buggy.core.logback.ConfLogger; import org.touchbit.buggy.core.model.Details; import org.touchbit.buggy.core.model.Status; -import org.touchbit.buggy.core.utils.TestNGHelper; import java.util.Date; import java.util.concurrent.atomic.AtomicInteger; 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 index 3800df0..915ec47 100644 --- 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 @@ -1,12 +1,8 @@ package org.touchbit.buggy.core.utils; -import org.touchbit.buggy.core.config.BuggyConfigYML; import org.touchbit.buggy.core.exceptions.BuggyConfigurationException; import org.touchbit.buggy.core.goal.Goal; import org.touchbit.buggy.core.model.Suite; -import org.yaml.snakeyaml.Yaml; -import org.yaml.snakeyaml.constructor.Constructor; -import org.yaml.snakeyaml.representer.Representer; import java.io.IOException; import java.io.InputStream; @@ -28,20 +24,10 @@ */ public class JUtils { - public static final String BUGGY_CONFIG_YML = "buggy-config.yml"; - private JUtils() { throw new IllegalStateException("Utility class. Prohibit instantiation."); } - public static void initBuggyConfigurationYml() { - Representer representer = new Representer(); - representer.getPropertyUtils().setSkipMissingProperties(true); - Yaml yaml = new Yaml(new Constructor(BuggyConfigYML.class), representer); - InputStream inputStream = JUtils.getCurrentThreadClassLoader().getResourceAsStream(BUGGY_CONFIG_YML); - yaml.load(inputStream); - } - public static T getGoal(Function> function, Suite s) { Class tClass = function.apply(s); return JUtils.newInstance(tClass, BuggyConfigurationException::new); @@ -57,11 +43,14 @@ public static List getListWith(T... tClasses) { return Arrays.stream(tClasses).collect(Collectors.toList()); } - public static < U extends Exception> Object newInstance(String cName, BiFunction s) throws U { + @SuppressWarnings("unchecked") + public static A newInstance(String cName, + Class exp, + BiFunction s) throws U { try { - Class aClass = getCurrentThreadClassLoader().loadClass(cName); + Class aClass = (Class) getCurrentThreadClassLoader().loadClass(cName); return newInstance(aClass, s); - } catch (ClassNotFoundException e) { + } catch (Exception e) { throw s.apply("Unable to load class " + cName, e); } } @@ -90,6 +79,10 @@ public static boolean isJetBrainsIdeTestNGPluginRun() { 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"))); diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/utils/TestNGHelper.java b/buggy-core/src/main/java/org/touchbit/buggy/core/utils/TestNGHelper.java index 91f8bb8..5c2688a 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/utils/TestNGHelper.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/utils/TestNGHelper.java @@ -1,8 +1,6 @@ package org.touchbit.buggy.core.utils; -import org.jetbrains.annotations.Nullable; import org.testng.IInvokedMethod; -import org.testng.ITestClass; import org.testng.ITestNGMethod; import org.testng.ITestResult; diff --git a/buggy-core/src/main/resources/buggy-config.yml b/buggy-core/src/main/resources/buggy-config.yml index 8de0904..16a511d 100644 --- a/buggy-core/src/main/resources/buggy-config.yml +++ b/buggy-core/src/main/resources/buggy-config.yml @@ -9,10 +9,11 @@ threads: 50 artifactsUrl: null parallelMode: 'METHODS' components: - - 'org.touchbit.buggy.core.goal.component.AllComponents' + - !!org.touchbit.buggy.core.goal.component.AllComponents {} services: - - 'org.touchbit.buggy.core.goal.service.AllServices' + - !!org.touchbit.buggy.core.goal.service.AllServices {} interfaces: - - 'org.touchbit.buggy.core.goal.interfaze.AllInterfaces' + - !!org.touchbit.buggy.core.goal.interfaze.AllInterfaces {} types: - - ALL \ No newline at end of file + - ALL +issuesUrl: 'https://example.jira.com/issues/' \ No newline at end of file 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 3ee285a..6ddf129 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,6 +1,5 @@ package org.touchbit.buggy.core.tests; -import org.jetbrains.annotations.Nullable; import org.junit.jupiter.api.function.Executable; import org.slf4j.Logger; import org.testng.IInvokedMethod; @@ -23,7 +22,6 @@ import org.touchbit.buggy.core.testng.BuggyExecutionListener; import java.io.File; -import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Method; 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 f876332..2611b4b 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 @@ -18,7 +18,7 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import org.touchbit.buggy.core.config.BuggyConfig; +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.goal.interfaze.Interface; @@ -82,13 +82,13 @@ class JCommanderConfigTests extends BaseUnitTest { @Test @DisplayName("Check PrimaryConfig.setThreads(10)") void unitTest_20180919194007() { - Integer threads = BuggyConfig.getThreads(); + Integer threads = BuggyConfigurationYML.getThreads(); try { assertThat(threads, is(50)); - BuggyConfig.setThreads(10); - assertThat(BuggyConfig.getThreads(), is(10)); + BuggyConfigurationYML.setThreads(10); + assertThat(BuggyConfigurationYML.getThreads(), is(10)); } finally { - BuggyConfig.setThreads(threads); + BuggyConfigurationYML.setThreads(threads); } } // @@ -108,30 +108,30 @@ void unitTest_20180919194007() { @Test @DisplayName("Check PrimaryConfig.setServices(List services)") void unitTest_20180919194549() { - List services = BuggyConfig.getServices(); + List services = BuggyConfigurationYML.getServices(); try { List newServices = new ArrayList() {{ add(new TestService()); }}; - BuggyConfig.setServices(newServices); - assertThat(BuggyConfig.getServices(), is(newServices)); + BuggyConfigurationYML.setServices(newServices); + assertThat(BuggyConfigurationYML.getServices(), is(newServices)); } finally { - BuggyConfig.setServices(services); + BuggyConfigurationYML.setServices(services); } } @Test @DisplayName("Check PrimaryConfig.setInterfaces(List interfaces)") void unitTest_20180919195248() { - List interfaces = BuggyConfig.getInterfaces(); + List interfaces = BuggyConfigurationYML.getInterfaces(); try { List newInterfaces = new ArrayList() {{ add(new TestInterface()); }}; - BuggyConfig.setInterfaces(newInterfaces); - assertThat(BuggyConfig.getInterfaces(), is(newInterfaces)); + BuggyConfigurationYML.setInterfaces(newInterfaces); + assertThat(BuggyConfigurationYML.getInterfaces(), is(newInterfaces)); } finally { - BuggyConfig.setInterfaces(interfaces); + BuggyConfigurationYML.setInterfaces(interfaces); } } @@ -164,61 +164,61 @@ void unitTest_20180919195248() { @Test @DisplayName("Check PrimaryConfig.setArtifactsUrl(String buildsUrl)") void unitTest_20180919201516() { - String buildLogUrl = BuggyConfig.getArtifactsUrl(); + String buildLogUrl = BuggyConfigurationYML.getArtifactsUrl(); try { assertThat(String.valueOf(buildLogUrl), is("null")); - BuggyConfig.setArtifactsUrl("BuildUrl"); - assertThat(BuggyConfig.getArtifactsUrl(), is("BuildUrl")); + BuggyConfigurationYML.setArtifactsUrl("BuildUrl"); + assertThat(BuggyConfigurationYML.getArtifactsUrl(), is("BuildUrl")); } finally { - BuggyConfig.setArtifactsUrl(buildLogUrl); + BuggyConfigurationYML.setArtifactsUrl(buildLogUrl); } } @Test @DisplayName("Check PrimaryConfig.setPrintSuite(Boolean printSuite)") void unitTest_20180919201621() { - boolean printSuite = BuggyConfig.isPrintSuite(); + boolean printSuite = BuggyConfigurationYML.isPrintSuite(); try { assertThat(printSuite, is(false)); - BuggyConfig.setPrintSuite(true); - assertThat(BuggyConfig.isPrintSuite(), is(true)); + BuggyConfigurationYML.setPrintSuite(true); + assertThat(BuggyConfigurationYML.isPrintSuite(), is(true)); } finally { - BuggyConfig.setPrintSuite(printSuite); + BuggyConfigurationYML.setPrintSuite(printSuite); } } @Test @DisplayName("Check PrimaryConfig.setPrintCause(Boolean printCause)") void unitTest_20180919201754() { - boolean printCause = BuggyConfig.isPrintCause(); + boolean printCause = BuggyConfigurationYML.isPrintCause(); try { assertThat(printCause, is(false)); - BuggyConfig.setPrintCause(true); - assertThat(BuggyConfig.isPrintCause(), is(true)); + BuggyConfigurationYML.setPrintCause(true); + assertThat(BuggyConfigurationYML.isPrintCause(), is(true)); } finally { - BuggyConfig.setPrintCause(printCause); + BuggyConfigurationYML.setPrintCause(printCause); } } @Test @DisplayName("Check PrimaryConfig.setPrintLogFile(Boolean printLog)") void unitTest_20180919201844() { - boolean printLogFile = BuggyConfig.isPrintLog(); + boolean printLogFile = BuggyConfigurationYML.isPrintLog(); try { assertThat(printLogFile, is(false)); - BuggyConfig.setPrintLog(true); - assertThat(BuggyConfig.isPrintLog(), is(true)); + BuggyConfigurationYML.setPrintLog(true); + assertThat(BuggyConfigurationYML.isPrintLog(), is(true)); } finally { - BuggyConfig.setPrintLog(printLogFile); + BuggyConfigurationYML.setPrintLog(printLogFile); } } @Test @DisplayName("Check PrimaryConfig.setVersion(Boolean version)") void unitTest_20180919201933() { - assertThat(BuggyConfig.isVersion(), is(false)); - BuggyConfig.setVersion(true); - assertThat(BuggyConfig.isVersion(), is(false)); + assertThat(BuggyConfigurationYML.isVersion(), is(false)); + BuggyConfigurationYML.setVersion(true); + assertThat(BuggyConfigurationYML.isVersion(), is(false)); } // // @Test 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 index 9f0299d..d239f00 100644 --- 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 @@ -1,15 +1,8 @@ package org.touchbit.buggy.core.tests.testng; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.testng.ITestNGMethod; -import org.touchbit.buggy.core.config.BuggyConfig; import org.touchbit.buggy.core.testng.BaseBuggyExecutionListener; import org.touchbit.buggy.core.tests.BaseUnitTest; -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 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 index 554d843..4db8ce0 100644 --- 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 @@ -18,7 +18,6 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import org.touchbit.buggy.core.config.BuggyConfig; import org.touchbit.buggy.core.model.Notifier; import org.touchbit.buggy.core.testng.BaseTelegramNotifier; import org.touchbit.buggy.core.tests.BaseUnitTest; 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 index 10545ba..7059e63 100644 --- 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 @@ -1,23 +1,20 @@ package org.touchbit.buggy.spring.boot.starter.example; import org.springframework.boot.SpringApplication; -import org.touchbit.buggy.core.goal.component.DefaultComponent; import org.touchbit.buggy.core.goal.interfaze.API; import org.touchbit.buggy.spring.boot.starter.BuggyRunner; -import org.touchbit.buggy.spring.boot.starter.jcommander.BuggyJCommand; +import org.touchbit.buggy.spring.boot.starter.jcommander.BuggyConfiguration; public class ExampleBuggyRunner extends BuggyRunner { - static { - BuggyJCommand.setForce(true); - BuggyJCommand.setInterfaces(API.class); - BuggyJCommand.setPrintLog(true); - BuggyJCommand.setPrintSuite(true); - BuggyJCommand.setPrintCause(true); - BuggyJCommand.setTaskTrackerIssueUrl("https://example.jira.com/issues/"); - } - public static void main(String[] args) { + BuggyConfiguration.setForce(true); + BuggyConfiguration.setPrintLog(true); + BuggyConfiguration.setPrintSuite(true); + BuggyConfiguration.setPrintCause(true); + BuggyConfiguration.setInterfaces(API.class); + BuggyConfiguration.setTaskTrackerIssueUrl("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/ExampleTests.java b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/tests/ExampleTests.java similarity index 84% rename from buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleTests.java rename to buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/tests/ExampleTests.java index cbcf498..8a29aea 100644 --- a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleTests.java +++ b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/tests/ExampleTests.java @@ -1,8 +1,7 @@ -package org.touchbit.buggy.spring.boot.starter.example; +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.config.BuggyConfig; import org.touchbit.buggy.core.goal.interfaze.API; import org.touchbit.buggy.core.model.Details; import org.touchbit.buggy.core.model.Suite; diff --git a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleTests2.java b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/tests/ExampleTests2.java similarity index 94% rename from buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleTests2.java rename to buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/tests/ExampleTests2.java index d938b83..0c61a07 100644 --- a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleTests2.java +++ b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/tests/ExampleTests2.java @@ -1,4 +1,4 @@ -package org.touchbit.buggy.spring.boot.starter.example; +package org.touchbit.buggy.spring.boot.starter.example.tests; import org.testng.annotations.Test; import org.touchbit.buggy.core.BaseBuggyTest; diff --git a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleTests3.java b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/tests/ExampleTests3.java similarity index 81% rename from buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleTests3.java rename to buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/tests/ExampleTests3.java index b40ce21..40d43fa 100644 --- a/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/ExampleTests3.java +++ b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/tests/ExampleTests3.java @@ -1,7 +1,6 @@ -package org.touchbit.buggy.spring.boot.starter.example; +package org.touchbit.buggy.spring.boot.starter.example.tests; import org.testng.annotations.Test; -import org.touchbit.buggy.core.exceptions.CorruptedTestException; import org.touchbit.buggy.core.goal.interfaze.API; import org.touchbit.buggy.core.model.Details; import org.touchbit.buggy.core.model.Suite; 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 index 6c8438c..ef2df54 100644 --- a/buggy-spring-boot-starter-example/src/main/resources/buggy-config.yml +++ b/buggy-spring-boot-starter-example/src/main/resources/buggy-config.yml @@ -1,19 +1,21 @@ -programName: Buggy +programName: 'Buggy example' help: false force: true printSuite: true printCause: true printLog: true -printLogOnlyFail: false +printLogOnlyFail: true threads: 50 artifactsUrl: null parallelMode: 'METHODS' components: - - 'org.touchbit.buggy.core.goal.component.AllComponents' + - !!org.touchbit.buggy.core.goal.component.AllComponents {} services: - - 'org.touchbit.buggy.core.goal.service.AllServices' + - !!org.touchbit.buggy.core.goal.service.AllServices {} interfaces: - - 'org.touchbit.buggy.core.goal.interfaze.AllInterfaces' + - !!org.touchbit.buggy.core.goal.interfaze.AllInterfaces {} types: - ALL -taskTrackerIssueUrl: 'https://example.jira.com/issues/' \ No newline at end of file +issuesUrl: 'https://example.jira.com/issues/' +exampleHost: foo +examplePass: bar \ No newline at end of file diff --git a/buggy-spring-boot-starter-example/src/main/resources/testng-1.0.dtd b/buggy-spring-boot-starter-example/src/main/resources/testng-1.0.dtd new file mode 100644 index 0000000..2527392 --- /dev/null +++ b/buggy-spring-boot-starter-example/src/main/resources/testng-1.0.dtd @@ -0,0 +1,213 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/buggy-spring-boot-starter/pom.xml b/buggy-spring-boot-starter/pom.xml index cf8b155..b7f9eed 100644 --- a/buggy-spring-boot-starter/pom.xml +++ b/buggy-spring-boot-starter/pom.xml @@ -27,6 +27,13 @@ org.touchbit.buggy buggy-core 0.3.7 + compile + + + org.touchbit.buggy + buggy-testng-listeners + 0.3.7 + compile org.springframework.boot 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 index 9e00d0d..5ca6ad3 100644 --- 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 @@ -8,7 +8,7 @@ import org.testng.xml.XmlClass; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; -import org.touchbit.buggy.core.config.BuggyConfig; +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; @@ -19,7 +19,7 @@ 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.BuggyJCommand; +import org.touchbit.buggy.spring.boot.starter.jcommander.BuggyConfiguration; import java.io.File; import java.util.*; @@ -98,7 +98,7 @@ public void run(String... args) { List xmlSuites = getXmlSuites(testClassesBySuitesMap); TestNG testNG = getTestNG(); try { - testNG.setParallel(BuggyConfig.getParallelMode().getTestNGMode()); + testNG.setParallel(BuggyConfigurationYML.getParallelMode().getTestNGMode()); testNG.setSuiteThreadPoolSize(xmlSuites.isEmpty() ? 1 : xmlSuites.size()); testNG.setUseDefaultListeners(false); for (BuggyListener enabledBuggyListener : enabledBuggyListeners) { @@ -107,8 +107,8 @@ public void run(String... args) { testNG.setXmlSuites(xmlSuites); testNG.run(); DecomposeTestLogsFileAppender.decomposeTestLogs(); - if (BuggyJCommand.getExitStatus() != null) { - exit(BuggyJCommand.getExitStatus()); + if (BuggyConfiguration.getExitStatus() != null) { + exit(BuggyConfiguration.getExitStatus()); } exit(testNG.getStatus()); } catch (Exception e) { @@ -139,8 +139,8 @@ public List getXmlSuites(Map>> buggySuitesTests) { List suites = new ArrayList<>(); for (Map.Entry>> entry : buggySuitesTests.entrySet()) { XmlSuite xmlSuite = new XmlSuite(); - xmlSuite.setParallel(BuggyConfig.getParallelMode().getTestNGMode()); - xmlSuite.setThreadCount(BuggyConfig.getThreads()); + xmlSuite.setParallel(BuggyConfigurationYML.getParallelMode().getTestNGMode()); + xmlSuite.setThreadCount(BuggyConfigurationYML.getThreads()); Suite buggySuite = entry.getKey(); try { Component cGoal = JUtils.getGoal(Suite::component, buggySuite); diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/BuggyConfiguration.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/BuggyRunnerConfiguration.java similarity index 93% rename from buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/BuggyConfiguration.java rename to buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/BuggyRunnerConfiguration.java index f63e15c..d184488 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/BuggyConfiguration.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/conf/BuggyRunnerConfiguration.java @@ -5,7 +5,7 @@ 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.BuggyConfig; +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; @@ -40,7 +40,7 @@ @Configuration() @ConditionalOnNotWebApplication @EnableConfigurationProperties(ApplicationProperties.class) -public class BuggyConfiguration implements IConfiguration { +public class BuggyRunnerConfiguration implements IConfiguration { private final ApplicationProperties properties; private final Set allBuggyListeners; @@ -55,7 +55,7 @@ public class BuggyConfiguration implements IConfiguration { private final Set allInterfaces; private final Set availableInterfaces; - public BuggyConfiguration(final boolean isLogbackConfigurationInitialized, final ApplicationProperties props) { + public BuggyRunnerConfiguration(final boolean isLogbackConfigurationInitialized, final ApplicationProperties props) { beforeConfiguration(isLogbackConfigurationInitialized); properties = props; allBuggyListeners = scanTestNGListeners(); @@ -63,11 +63,11 @@ public BuggyConfiguration(final boolean isLogbackConfigurationInitialized, final allTestClasses = scanTestClassesWithSuiteAnnotation(); filteredTestClasses = filterTestClassesByBuggyConfig(allTestClasses); allGoals = scanGoals(); - allComponents = filterByGoalType(allGoals, BuggyConfig.getComponents(), Component.class, AllComponents.class); + allComponents = filterByGoalType(allGoals, BuggyConfigurationYML.getComponents(), Component.class, AllComponents.class); availableComponents = filterComponentsByTestClasses(allComponents, filteredTestClasses); - allServices = filterByGoalType(allGoals, BuggyConfig.getComponents(), Service.class, AllServices.class); + allServices = filterByGoalType(allGoals, BuggyConfigurationYML.getComponents(), Service.class, AllServices.class); availableServices = filterServiceByTestClasses(allServices, filteredTestClasses); - allInterfaces = filterByGoalType(allGoals, BuggyConfig.getComponents(), Interface.class, AllInterfaces.class); + allInterfaces = filterByGoalType(allGoals, BuggyConfigurationYML.getComponents(), Interface.class, AllInterfaces.class); availableInterfaces = filterInterfaceByTestClasses(allInterfaces, filteredTestClasses); } @@ -104,13 +104,13 @@ public void printConfigurationInfo() { } public Set> filterTestClassesByBuggyConfig(Set> testClassesWithSuiteAnnotation) { - List> components = BuggyConfig.getComponents().stream() + List> components = BuggyConfigurationYML.getComponents().stream() .map(Component::getClass) .collect(Collectors.toList()); - List> services = BuggyConfig.getServices().stream() + List> services = BuggyConfigurationYML.getServices().stream() .map(Service::getClass) .collect(Collectors.toList()); - List> interfaces = BuggyConfig.getInterfaces().stream() + List> interfaces = BuggyConfigurationYML.getInterfaces().stream() .map(Interface::getClass) .collect(Collectors.toList()); return testClassesWithSuiteAnnotation.stream() 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 index b24aa7d..1847f97 100644 --- 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 @@ -10,11 +10,11 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; -import org.touchbit.buggy.core.config.BuggyConfig; +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.BuggyJCommand; +import org.touchbit.buggy.spring.boot.starter.jcommander.BuggyConfiguration; import org.touchbit.buggy.spring.boot.starter.jcommander.JCommand; import javax.annotation.PostConstruct; @@ -50,7 +50,7 @@ public JCommanderConfiguration(final ApplicationProperties properties, final App beforeConfiguration(); this.JCommands.addAll(scanBuggyConfig()); scanJCConfigurations().stream() - .filter(i -> !(i instanceof BuggyJCommand)) + .filter(i -> !(i instanceof BuggyConfiguration)) .forEach(this.JCommands::add); this.jCommander = buildJCommander(); parseArguments(); @@ -70,12 +70,12 @@ public boolean isJCommanderConfigured() { @PostConstruct public void postConstruct() { - if (BuggyConfig.isHelp()) { + if (BuggyConfigurationYML.isHelp()) { ConfLogger.stepDelimiter(); jCommander.usage(); BuggyRunner.exit(0); } - if (BuggyConfig.isVersion()) { + if (BuggyConfigurationYML.isVersion()) { ConfLogger.stepDelimiter(); ConfLogger.centerBold("Version info"); JUtils.getBuggyManifest().forEach(ConfLogger::dotPlaceholder); @@ -84,11 +84,11 @@ public void postConstruct() { printConfigurationsParams(buggyConfigurations); } - private Set scanBuggyConfig() { + private Set scanBuggyConfig() { final boolean useDefaultFilters = false; final String basePackage = "org.touchbit.buggy.spring.boot.starter.jcommander"; - final Set defs = scanBeanDefinitions(useDefaultFilters, basePackage, BuggyJCommand.class); - return getBeanDefinitionInstances(defs, BuggyJCommand.class); + final Set defs = scanBeanDefinitions(useDefaultFilters, basePackage, BuggyConfiguration.class); + return getBeanDefinitionInstances(defs, BuggyConfiguration.class); } public Set scanJCConfigurations() { @@ -138,7 +138,7 @@ public void parseArguments() { @Bean("isBuggyConfigured") public boolean isBuggyConfigured() { - return buggyConfigurations.containsKey(BuggyConfig.class); + return buggyConfigurations.containsKey(BuggyConfigurationYML.class); } @Bean() diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/BuggyJCommand.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/BuggyConfiguration.java similarity index 72% rename from buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/BuggyJCommand.java rename to buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/BuggyConfiguration.java index 5d6cb37..1616a92 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/BuggyJCommand.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/BuggyConfiguration.java @@ -1,7 +1,7 @@ package org.touchbit.buggy.spring.boot.starter.jcommander; import com.beust.jcommander.Parameter; -import org.touchbit.buggy.core.config.BuggyConfig; +import org.touchbit.buggy.core.config.BuggyConfigurationYML; import org.touchbit.buggy.core.goal.component.Component; import org.touchbit.buggy.core.goal.interfaze.Interface; import org.touchbit.buggy.core.goal.service.Service; @@ -24,7 +24,7 @@ * shaburov.o.a@gmail.com */ @SuppressWarnings("unused") -public final class BuggyJCommand implements JCommand { +public final class BuggyConfiguration implements JCommand { private static Boolean version; private static Integer exitStatus; @@ -39,188 +39,190 @@ public static Integer getExitStatus() { @Parameter(names = {V, VERSION}, description = "Print program version") public static void setVersion(Boolean version) { - BuggyJCommand.version = version; + BuggyConfiguration.version = version; } @Parameter(names = {EXIT_STATUS}, description = "Completion with the specified status.") public static void setExitStatus(Integer exitStatus) { - BuggyJCommand.exitStatus = exitStatus; + BuggyConfiguration.exitStatus = exitStatus; } + // ---------------------- Map default BuggyConfigurationYML values ---------------------- // + @Parameter(names = {QUESTION_MARK, HELP}, help = true, description = "Print usage.") public static void setHelp(Boolean help) { - BuggyConfig.setHelp(help); + BuggyConfigurationYML.setHelp(help); } @Parameter(names = {F, FORCE}, description = "Running all tests, including those that fall.") public static void setForce(Boolean force) { - BuggyConfig.setForce(force); + BuggyConfigurationYML.setForce(force); } @Parameter(names = {PRINT_SUITE}, description = "Display information on the Suite in the console log.") public static void setPrintSuite(Boolean printSuite) { - BuggyConfig.setPrintSuite(printSuite); + BuggyConfigurationYML.setPrintSuite(printSuite); } @Parameter(names = {PRINT_CAUSE}, description = "Print the cause of a fail or skip test in the console log.") public static void setPrintCause(Boolean printCause) { - BuggyConfig.setPrintCause(printCause); + BuggyConfigurationYML.setPrintCause(printCause); } @Parameter(names = {PRINT_LOG}, description = "Print the test log file path in the console log") public static void setPrintLog(Boolean printLog) { - BuggyConfig.setPrintLog(printLog); + BuggyConfigurationYML.setPrintLog(printLog); } @Parameter(names = {PRINT_LOG_IF_FAIL}, description = "Print the failed test log file path in the console log") public static void setPrintLogOnlyFail(Boolean printLogOnlyFail) { - BuggyConfig.setPrintLogOnlyFail(printLogOnlyFail); + BuggyConfigurationYML.setPrintLogOnlyFail(printLogOnlyFail); } @Parameter(names = {THREADS}, description = "The number of threads to run the test methods.") public static void setThreads(Integer threads) { - BuggyConfig.setThreads(threads); + BuggyConfigurationYML.setThreads(threads); } @Parameter(names = {ARTIFACTS_URL}, description = "The storage address for the builds (artifacts).") public static void setArtifactsUrl(String artifactsUrl) { - BuggyConfig.setArtifactsUrl(artifactsUrl); + BuggyConfigurationYML.setArtifactsUrl(artifactsUrl); } @Parameter(names = {T, TYPE}, description = "Type of tests to run.", validateWith = ParameterValidator.class) public static void setTypes(List types) { - BuggyConfig.setTypes(types); + BuggyConfigurationYML.setTypes(types); } public static void setTypes(Type... types) { - BuggyConfig.setTypes(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) { - BuggyConfig.setServices(services); + BuggyConfigurationYML.setServices(services); } @SafeVarargs public static void setServices(S... services) { - BuggyConfig.setServices(services); + BuggyConfigurationYML.setServices(services); } @SafeVarargs public static void setServices(Class... services) { - BuggyConfig.setServices(services); + BuggyConfigurationYML.setServices(services); } @Parameter(names = {I, INTERFACE}, description = "List of tested interfaces in the format: NAME,NAME,NAME.", validateWith = ParameterValidator.class, listConverter = InterfaceConverter.class) public static void setInterfaces(List interfaces) { - BuggyConfig.setInterfaces(interfaces); + BuggyConfigurationYML.setInterfaces(interfaces); } @SafeVarargs public static void setInterfaces(I... interfaces) { - BuggyConfig.setInterfaces(interfaces); + BuggyConfigurationYML.setInterfaces(interfaces); } @SafeVarargs public static void setInterfaces(Class... interfaces) { - BuggyConfig.setInterfaces(interfaces); + BuggyConfigurationYML.setInterfaces(interfaces); } @Parameter(names = {C, COMPONENTS}, description = "List of tested components in the format: NAME,NAME,NAME.", validateWith = ParameterValidator.class, listConverter = ServiceConverter.class) public static void setComponents(List components) { - BuggyConfig.setComponents(components); + BuggyConfigurationYML.setComponents(components); } @SafeVarargs public static void setComponents(C... components) { - BuggyConfig.setComponents(components); + BuggyConfigurationYML.setComponents(components); } @SafeVarargs public static void setComponents(Class... components) { - BuggyConfig.setComponents(components); + BuggyConfigurationYML.setComponents(components); } @Parameter(names = {PARALLEL_MODE}, description = "TestNG parallel mode.") public static void setParallelMode(ParallelMode parallelMode) { - BuggyConfig.setParallelMode(parallelMode); + BuggyConfigurationYML.setParallelMode(parallelMode); } @Parameter(names = {PROGRAM_NAME}, description = "Current program name") public static void setProgramName(String programName) { - BuggyConfig.setProgramName(programName); + BuggyConfigurationYML.setProgramName(programName); } - @Parameter(names = {"--task-tracker-issue-url"}, description = "TODO") + @Parameter(names = {"--issues-url"}, description = "Task tracker issues URL.") public static void setTaskTrackerIssueUrl(String taskTrackerIssueUrl) { - BuggyConfig.setTaskTrackerIssueUrl(taskTrackerIssueUrl); + BuggyConfigurationYML.setIssuesUrl(taskTrackerIssueUrl); } public static Boolean isHelp() { - return BuggyConfig.isHelp(); + return BuggyConfigurationYML.isHelp(); } public static Boolean isPrintLogFileOnlyFail() { - return BuggyConfig.isPrintLog(); + return BuggyConfigurationYML.isPrintLog(); } public static Boolean isForce() { - return BuggyConfig.isForce(); + return BuggyConfigurationYML.isForce(); } public static Boolean isPrintSuite() { - return BuggyConfig.isPrintSuite(); + return BuggyConfigurationYML.isPrintSuite(); } public static Boolean isPrintCause() { - return BuggyConfig.isPrintCause(); + return BuggyConfigurationYML.isPrintCause(); } public static Boolean isPrintLog() { - return BuggyConfig.isPrintLog(); + return BuggyConfigurationYML.isPrintLog(); } public static Boolean isVersion() { - return BuggyConfig.isVersion(); + return BuggyConfigurationYML.isVersion(); } public static Integer getThreads() { - return BuggyConfig.getThreads(); + return BuggyConfigurationYML.getThreads(); } public static String getArtifactsUrl() { - return BuggyConfig.getArtifactsUrl(); + return BuggyConfigurationYML.getArtifactsUrl(); } public static List getTypes() { - return BuggyConfig.getTypes(); + return BuggyConfigurationYML.getTypes(); } public static List getServices() { - return BuggyConfig.getServices(); + return BuggyConfigurationYML.getServices(); } public static List getInterfaces() { - return BuggyConfig.getInterfaces(); + return BuggyConfigurationYML.getInterfaces(); } public static List getComponents() { - return BuggyConfig.getComponents(); + return BuggyConfigurationYML.getComponents(); } public static ParallelMode getParallelMode() { - return BuggyConfig.getParallelMode(); + return BuggyConfigurationYML.getParallelMode(); } public static String getProgramName() { - return BuggyConfig.getProgramName(); + return BuggyConfigurationYML.getProgramName(); } public static String getTaskTrackerIssueUrl() { - return BuggyConfig.getTaskTrackerIssueUrl(); + return BuggyConfigurationYML.getIssuesUrl(); } @Override diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/JCommand.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/JCommand.java index f4c5e68..450d727 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/JCommand.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/JCommand.java @@ -1,26 +1,15 @@ package org.touchbit.buggy.spring.boot.starter.jcommander; import com.beust.jcommander.Parameter; +import org.touchbit.buggy.core.config.ConfigurationYML; +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.*; -/** - * An interface for finding all inherited {@link com.beust.jcommander.JCommander} configuration classes. - * Search is performed using spring-boot annotation @ComponentScan. - *

- * All fields and setter-methods marked with {@link Parameter} annotation must be static. - *

- * Your config classes should be in the "buggy" package since ComponentScan - * is limited to filter (basePackages = "**.buggy") to speed up the search for all inheritors. - * For example: org.example.foo.bar.buggy.MyConfiguration.class (implements IBuggyConfig). - *

- * Created by Oleg Shaburov on 01.10.2020 - * shaburov.o.a@gmail.com - */ -public interface JCommand { +public interface JCommand extends ConfigurationYML { /** * Convert configuration parameters and values to map where: @@ -46,15 +35,18 @@ default void addFieldValuesToMap(Map map) { 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(Arrays.toString(names), "*****"); + map.put(parameters, "*****"); } else { field.setAccessible(true); - map.put(Arrays.toString(names), field.get(this)); + map.put(parameters, field.get(this)); } } catch (Exception e) { -// ConfigurationLogger.errPrint(e.getMessage()); TODO + map.put(parameters, ""); + new FrameworkLogger().error("Error getting value from field " + + field.getDeclaringClass().getSimpleName() + "#" + field.getName(), e); } finally { field.setAccessible(false); } @@ -91,7 +83,12 @@ default void addMethodsValuesToMap(Map map) { method.getValue().setAccessible(true); map.put(method.getKey().toString(), method.getValue().invoke(this)); } catch (Exception e) { -// ConfigurationLogger.errPrint(e.getMessage()); TODO + 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); } diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/GoalConverter.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/GoalConverter.java index de0005c..cf74463 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/GoalConverter.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/GoalConverter.java @@ -18,13 +18,12 @@ import com.beust.jcommander.IStringConverter; 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.AssignableTypeFilter; import org.touchbit.buggy.core.exceptions.BuggyConfigurationException; import org.touchbit.buggy.core.goal.Goal; +import org.touchbit.buggy.core.utils.JUtils; -import java.lang.reflect.Constructor; import java.util.LinkedHashSet; import java.util.Set; @@ -52,17 +51,11 @@ public T convert(String s) { throw new BuggyConfigurationException("No " + tClass.getSimpleName() + " found with name " + s); } - private Set getBeanDefinitionInstances(Set definitions, Class tClass) { - Set result = new LinkedHashSet<>(); + private 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) { - throw new BuggyConfigurationException("Can not create a new instance of " + tClass.getSimpleName()); - } + A instance = JUtils.newInstance(bd.getBeanClassName(), tClass, BuggyConfigurationException::new); + result.add(instance); } return result; } 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/LoggingListener.java b/buggy-testng-listeners/src/main/java/org/touchbit/buggy/testng/listeners/LoggingListener.java new file mode 100644 index 0000000..e5cdf68 --- /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 true; + } + +} 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 04c6589..0a3f994 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 @@ -3,7 +3,7 @@ import org.testng.IExecutionListener; import org.testng.IInvokedMethodListener; import org.testng.ITestResult; -import org.touchbit.buggy.core.config.BuggyConfig; +import org.touchbit.buggy.core.config.BuggyConfigurationYML; import org.touchbit.buggy.core.model.Details; import org.touchbit.buggy.core.testng.BaseBuggyExecutionListener; import org.touchbit.buggy.testrail.BaseTestRailConfig; @@ -128,7 +128,7 @@ protected String addAttachments(ITestResult testResult) { } protected String attachLogfile(String prefix) { - String logfile = BuggyConfig.getArtifactsUrl() + "/tests/" + prefix + ".log"; + String logfile = BuggyConfigurationYML.getArtifactsUrl() + "/tests/" + prefix + ".log"; return attachFile(logfile); } @@ -148,7 +148,7 @@ protected String attachScreenshots(String prefix) { protected String attachFile(String filename) { File sourceFile = new File(filename); return "[" + sourceFile.getName() + "](" + - BuggyConfig.getArtifactsUrl() + "/tests/" + sourceFile.getName() + ")\n"; + BuggyConfigurationYML.getArtifactsUrl() + "/tests/" + sourceFile.getName() + ")\n"; } protected List getTestRailCasesByRunId(Long rId) { diff --git a/pom.xml b/pom.xml index 873a255..d97b9a8 100644 --- a/pom.xml +++ b/pom.xml @@ -20,6 +20,7 @@ buggy-feign buggy-okhttp buggy-testrail + buggy-testng-listeners @@ -177,6 +178,12 @@ 0.3.7 compile + + org.touchbit.buggy + buggy-testng-listeners + 0.3.7 + compile + org.touchbit.buggy @@ -341,20 +348,12 @@ ${project.version} - executable true - - - org.atteo.classindex - classindex-transformer - 3.7 - - org.apache.maven.plugins From b6da984018b308124339ab01d3d642d386515a6a Mon Sep 17 00:00:00 2001 From: Shaburov Oleg Date: Sun, 11 Oct 2020 00:34:41 +0300 Subject: [PATCH 19/24] Sifting logs --- .../core/logback/BaseLogbackWrapper.java | 18 +-- .../buggy/core/logback/SiftingTestLogger.java | 32 ++--- .../appender/BaseBuggyFileAppender.java | 43 +++++++ .../appender/ConsoleColorAppender.java | 16 +++ .../DecomposeTestLogsFileAppender.java | 99 ---------------- .../appender/FrameworkFileAppender.java | 19 +++ .../logback/appender/SiftingAppender.java | 20 ++++ .../logback/appender/SiftingFileAppender.java | 111 ++++++++++++++++++ .../buggy/core/logback/appender/TestLog.java | 36 ++++++ .../appender/TestSupervisorFileAppender.java | 19 +++ .../layout/ConsoleLoggerColorLayout.java | 2 +- .../logback/layout/FrameworkLoggerLayout.java | 2 +- .../logback/layout/ShiftingLoggerLayout.java | 4 +- .../layout/TestSupervisorLoggerLayout.java | 59 ++++++++++ .../core/testng/LoggingListenerBase.java | 17 ++- .../src/main/resources/buggy-logback.xml | 41 +------ .../starter/example/ExampleBuggyRunner.java | 2 +- .../starter/example/tests/ExampleTests.java | 4 +- .../starter/example/tests/ExampleTests2.java | 6 + .../starter/example/tests/ExampleTests3.java | 7 ++ .../spring/boot/starter/BuggyRunner.java | 8 +- .../boot/starter/jcommander/BParameters.java | 11 +- .../jcommander/BuggyConfiguration.java | 6 +- .../boot/starter/jcommander/OutputRule.java | 9 ++ 24 files changed, 399 insertions(+), 192 deletions(-) create mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/logback/appender/BaseBuggyFileAppender.java create mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/logback/appender/ConsoleColorAppender.java delete mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/logback/appender/DecomposeTestLogsFileAppender.java create mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/logback/appender/FrameworkFileAppender.java create mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/logback/appender/SiftingAppender.java create mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/logback/appender/SiftingFileAppender.java create mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/logback/appender/TestLog.java create mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/logback/appender/TestSupervisorFileAppender.java create mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/logback/layout/TestSupervisorLoggerLayout.java create mode 100644 buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/OutputRule.java 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 index f92bbfc..9144805 100644 --- 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 @@ -13,25 +13,9 @@ public class BaseLogbackWrapper extends MarkerIgnoringBase { - public static final String LOG_PATH = "LOG_PATH"; 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 static final String LOGGING_CONFIG = "logging.config"; - private static final String LOGBACK_CONFIG = "logback.configurationFile"; - - static { - if (System.getProperty("logback.configurationFile") == null) { - System.setProperty("logback.configurationFile", "buggy-logback.xml"); - } - 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"); - } - } private final Logger logger; @@ -41,7 +25,7 @@ public BaseLogbackWrapper(final String name) { } public static String getConfFileName() { - return System.getProperty(LOGGING_CONFIG, System.getProperty(LOGBACK_CONFIG, "undefined")) + return System.getProperty("logging.config", System.getProperty("logback.configurationFile", "undefined")) .replace("classpath:", ""); } 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 index bd7bce1..06c64bc 100644 --- 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 @@ -1,33 +1,37 @@ package org.touchbit.buggy.core.logback; -import org.slf4j.MDC; -import org.touchbit.buggy.core.logback.appender.DecomposeTestLogsFileAppender; -import org.touchbit.buggy.core.model.IStatus; +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; public class SiftingTestLogger extends BaseLogbackWrapper { - public static final String SIFTING_LOG_FILE_PATH = "sifting.test.log.file.path"; - public static final String SIFTING_LOG_DIR = "tests"; - public SiftingTestLogger() { super(SIFTING_LOGGER_NAME); } - public static void setTestLogFileName(String logFileName) { - setTestLogFile(new File(SIFTING_LOG_DIR, logFileName)); + public static void setTestLogFileName(IInvokedMethod method) { + if (method != null) { + setTestLogFileName(method.getTestMethod()); + } } - public static void setTestLogFile(File file) { - MDC.put(SIFTING_LOG_FILE_PATH, file.getPath()); + public static void setTestLogFileName(ITestNGMethod iTestNGMethod) { + if (iTestNGMethod != null) { + String name = iTestNGMethod.getConstructorOrMethod().getMethod().getName(); + SiftingFileAppender.setTestLogFileName(name); + } } - public static File getSiftingLogFile(String fileName) { - return DecomposeTestLogsFileAppender.getFile(fileName); + public static File getSiftingLogFile() { + return SiftingFileAppender.getTestLogFile(); } - public static void setTestStatus(String fileName, IStatus status) { - DecomposeTestLogsFileAppender.setTestStatus(fileName, status); + public static void setTestResultStatus(ResultStatus status) { + SiftingFileAppender.setTestResultStatus(status); } + } 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..229388a --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/appender/BaseBuggyFileAppender.java @@ -0,0 +1,43 @@ +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 (System.getProperty("logback.configurationFile") == null) { + System.setProperty("logback.configurationFile", "buggy-logback.xml"); + } + 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/DecomposeTestLogsFileAppender.java b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/appender/DecomposeTestLogsFileAppender.java deleted file mode 100644 index a341e5b..0000000 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/logback/appender/DecomposeTestLogsFileAppender.java +++ /dev/null @@ -1,99 +0,0 @@ -package org.touchbit.buggy.core.logback.appender; - -import ch.qos.logback.core.FileAppender; -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.HashMap; -import java.util.Map; - -import static org.touchbit.buggy.core.logback.BaseLogbackWrapper.LOG_PATH; -import static org.touchbit.buggy.core.model.Status.NONE; - -public class DecomposeTestLogsFileAppender extends FileAppender { - - public static final Map TEST_LOGS_WITH_STATUS = new HashMap<>(); - public static final String LOG_DIR = System.getProperty(LOG_PATH, "logs"); - 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"); - - @Override - public void setFile(String file) { - super.setFile(file); - TEST_LOGS_WITH_STATUS.put(new File(file), NONE); - } - - public static File getFile(String fileName) { - return TEST_LOGS_WITH_STATUS.entrySet().stream() - .filter(e -> e.getKey().getName().equals(fileName)) - .findFirst() - .map(Map.Entry::getKey) - .orElse(null); - } - - public static void setTestStatus(String fileName, IStatus status) { - TEST_LOGS_WITH_STATUS.entrySet().stream() - .filter(e -> e.getKey().getName().contains(fileName)) - .findFirst() - .ifPresent(first -> TEST_LOGS_WITH_STATUS.put(first.getKey(), status)); - } - - public static void decomposeTestLogs() { - for (Map.Entry log : TEST_LOGS_WITH_STATUS.entrySet()) { - String fileName = log.getKey().getName(); - File destFile = null; - IStatus testLogStatus = log.getValue(); - ResultStatus resultStatus = null; - for (ResultStatus value : ResultStatus.values()) { - if (value.getStatus().equals(testLogStatus.getStatus())) { - resultStatus = value; - } - } - 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(log.getKey(), destFile); - } catch (Exception e) { - // ignore todo - } - } - } - } - -} 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..ef63257 --- /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 = true; + } + +} 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..87654ce --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/appender/SiftingFileAppender.java @@ -0,0 +1,111 @@ +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.Map; +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 = true; + } + + 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..d84caf4 --- /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 = true; + } + +} 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 index a2c505d..dab5e2c 100644 --- 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 @@ -19,7 +19,7 @@ * Created by Oleg Shaburov on 30.09.2020 * shaburov.o.a@gmail.com */ -public class ConsoleLoggerColorLayout extends LayoutBase { +public class ConsoleLoggerColorLayout extends LayoutBase { /** * Log format: message\n 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 index b2df097..8190afe 100644 --- 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 @@ -17,7 +17,7 @@ * Created by Oleg Shaburov on 30.09.2020 * shaburov.o.a@gmail.com */ -public class FrameworkLoggerLayout extends LayoutBase { +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"); 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 index df8bc37..898c49b 100644 --- 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 @@ -15,7 +15,7 @@ * Created by Oleg Shaburov on 30.09.2020 * shaburov.o.a@gmail.com */ -public class ShiftingLoggerLayout extends LayoutBase { +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"); @@ -47,7 +47,7 @@ public String getPresentation() { * at org.springframework.util.Assert.notNull(Assert.java:201) */ @Override - public String doLayout(final ILoggingEvent event) { + public String doLayout(final E event) { final long timestamp = event.getTimeStamp(); final String message = event.getFormattedMessage(); final IThrowableProxy tProxy = event.getThrowableProxy(); 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/testng/LoggingListenerBase.java b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/LoggingListenerBase.java index 2134abd..809fa14 100644 --- 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 @@ -49,12 +49,14 @@ public abstract class LoggingListenerBase implements BuggyListener, IInvokedMeth @Override public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { - SiftingTestLogger.setTestLogFileName(getLogFileName(method)); + SiftingTestLogger.setTestLogFileName(method); } @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) { TEST.info("Date: {}", new Date()); + ResultStatus resultStatus = getResultStatus(method); + SiftingTestLogger.setTestResultStatus(resultStatus); Boolean printLog = BuggyConfigurationYML.isPrintLog(); Boolean printSuite = BuggyConfigurationYML.isPrintSuite(); Boolean printCause = BuggyConfigurationYML.isPrintCause(); @@ -76,7 +78,7 @@ public void afterInvocation(IInvokedMethod method, ITestResult testResult) { String[] bugs = details.bugs(); String indent = " "; - String dotPlaceholder = ConfLogger.getDotPlaceholder(methodName, status); + String dotPlaceholder = ConfLogger.getDotPlaceholder(methodName, resultStatus); StringBuilder message = new StringBuilder(); message.append(dotPlaceholder); if (printSuite) { @@ -95,7 +97,7 @@ public void afterInvocation(IInvokedMethod method, ITestResult testResult) { indent += indent; } if (printLog) { - message.append("\n Log: ").append(getLogFilePath(method.getTestMethod(), status)); + message.append("\n Log: ").append(getLogFilePath()); indent += indent; } if (printCause && bugs.length > 0) { @@ -255,21 +257,18 @@ public void afterInvocation(IInvokedMethod method, ITestResult testResult) { // } // } - - protected String getLogFilePath(ITestNGMethod method, IStatus status) { + 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 { - String fileName = getLogFileName(method); - SiftingTestLogger.setTestStatus(fileName, status); - File file = SiftingTestLogger.getSiftingLogFile(fileName); + File file = SiftingTestLogger.getSiftingLogFile(); if (file != null) { return "file://" + file.getAbsolutePath(); } else { - return "Log file not found: " + fileName; + return "Log file not found"; } } } diff --git a/buggy-core/src/main/resources/buggy-logback.xml b/buggy-core/src/main/resources/buggy-logback.xml index 6dd7464..085af35 100644 --- a/buggy-core/src/main/resources/buggy-logback.xml +++ b/buggy-core/src/main/resources/buggy-logback.xml @@ -1,41 +1,12 @@ + - - - - - - - - - - - ${logging.file.path}/Framework.log - false - - - - - - - sifting.test.log.file.path - default-sifting.log - - - - ${logging.file.path}/${sifting.test.log.file.path} - false - - - - - - ${logging.file.path}/TestSupervisor.log - false - - ${base.log.pattern} - + + + + + 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 index 7059e63..768b5b6 100644 --- 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 @@ -13,8 +13,8 @@ public static void main(String[] args) { BuggyConfiguration.setPrintSuite(true); BuggyConfiguration.setPrintCause(true); BuggyConfiguration.setInterfaces(API.class); + BuggyConfiguration.setPrintLogOnlyFail(true); BuggyConfiguration.setTaskTrackerIssueUrl("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/tests/ExampleTests.java b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/tests/ExampleTests.java index 8a29aea..08f21a2 100644 --- 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 @@ -11,9 +11,9 @@ @Suite(component = GitHub.class, service = Actions.class, interfaze = API.class) public class ExampleTests extends BaseBuggyTest { - @Test + @Test(invocationCount = 10) @Details - public void test_1() { + 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 index 0c61a07..26ac873 100644 --- 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 @@ -21,4 +21,10 @@ public void test_2() { " 4) [Professor] expected:<'[well kempt]'> but was:<'[bloodied and dishevelled]'>"); } + @Test(description = "") + @Details(status = Status.EXP_IMPL, bugs = "JIRA-321") + public void test_1() { + + } + } 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 index 40d43fa..425df34 100644 --- 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 @@ -3,6 +3,7 @@ import org.testng.annotations.Test; import org.touchbit.buggy.core.goal.interfaze.API; import org.touchbit.buggy.core.model.Details; +import org.touchbit.buggy.core.model.Status; import org.touchbit.buggy.core.model.Suite; import java.net.ProtocolException; @@ -18,4 +19,10 @@ public void test_3() throws Exception { throw new ProtocolException("Received HTTP_PROXY_AUTH (407) code while not using proxy"); } + @Test(description = "") + @Details(status = Status.BLOCKED, bugs = "JIRA-321") + public void test_1() { + + } + } 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 index 5ca6ad3..1e5ee12 100644 --- 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 @@ -15,7 +15,7 @@ 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.DecomposeTestLogsFileAppender; +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; @@ -93,7 +93,7 @@ public static void exit(int status, String message, Exception e) { @Override public void run(String... args) { - // TODO exit_1 if test methods names not unique + ConfLogger.blockDelimiter(); Map>> testClassesBySuitesMap = getTestClassesBySuitesMap(filteredTestClasses); List xmlSuites = getXmlSuites(testClassesBySuitesMap); TestNG testNG = getTestNG(); @@ -106,7 +106,7 @@ public void run(String... args) { } testNG.setXmlSuites(xmlSuites); testNG.run(); - DecomposeTestLogsFileAppender.decomposeTestLogs(); + SiftingFileAppender.decomposeTestLogs(); if (BuggyConfiguration.getExitStatus() != null) { exit(BuggyConfiguration.getExitStatus()); } @@ -114,7 +114,7 @@ public void run(String... args) { } catch (Exception e) { exit(1, "TestNG safely died.", e); } finally { - DecomposeTestLogsFileAppender.decomposeTestLogs(); + SiftingFileAppender.decomposeTestLogs(); } } diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/BParameters.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/BParameters.java index ba6b08a..7dd7ef6 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/BParameters.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/BParameters.java @@ -41,11 +41,14 @@ public class BParameters { 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 EXIT_STATUS = "--exit-status"; - public static final String ALL = "--all"; - public static final String PRINT_SUITE = "--print-suite"; + public static final String EXIT_STATUS = "--exit-status"; + 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 OUTPUT_RULE = "--output-rule"; public static final String PRINT_CAUSE = "--print-cause"; - public static final String PRINT_LOG = "--print-log"; public static final String PRINT_LOG_IF_FAIL = "--print-log-if-fail"; public static final String PROGRAM_NAME = "--program-name"; 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 index 1616a92..b82f507 100644 --- 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 @@ -59,7 +59,7 @@ public static void setForce(Boolean force) { BuggyConfigurationYML.setForce(force); } - @Parameter(names = {PRINT_SUITE}, description = "Display information on the Suite in the console log.") + @Parameter(names = {TEST_SUITE_INFO}, description = "Display information on the Suite in the console log.") public static void setPrintSuite(Boolean printSuite) { BuggyConfigurationYML.setPrintSuite(printSuite); } @@ -69,7 +69,7 @@ public static void setPrintCause(Boolean printCause) { BuggyConfigurationYML.setPrintCause(printCause); } - @Parameter(names = {PRINT_LOG}, description = "Print the test log file path in the console log") + @Parameter(names = {TEST_LOG_FILE_PATH}, description = "Print the test log file path in the console log") public static void setPrintLog(Boolean printLog) { BuggyConfigurationYML.setPrintLog(printLog); } @@ -228,7 +228,7 @@ public static String getTaskTrackerIssueUrl() { @Override public Map sort(Map map) { String[] sort = new String[] - {THREADS, PARALLEL_MODE, F, PRINT_LOG, PRINT_CAUSE, PRINT_SUITE, + {THREADS, PARALLEL_MODE, F, TEST_LOG_FILE_PATH, PRINT_CAUSE, TEST_SUITE_INFO, C, S, I, T, LOGS_PATH, ARTIFACTS_URL, EXIT_STATUS}; Map sorted = new LinkedHashMap<>(); for (String s : sort) { diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/OutputRule.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/OutputRule.java new file mode 100644 index 0000000..3fa597f --- /dev/null +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/OutputRule.java @@ -0,0 +1,9 @@ +package org.touchbit.buggy.spring.boot.starter.jcommander; + +public enum OutputRule { + + OFF, + UNSUCCESSFUL, + ALWAYS + +} From fc55719fe1397666793df6e2a8eab076498eb18a Mon Sep 17 00:00:00 2001 From: Shaburov Oleg Date: Sun, 11 Oct 2020 01:00:06 +0300 Subject: [PATCH 20/24] Rename @Details -> @Buggy --- .../exceptions/BaseBuggyTestException.java | 10 ++--- .../core/exceptions/BlockedTestException.java | 6 +-- .../exceptions/CorruptedTestException.java | 6 +-- .../ExpectedImplementationException.java | 6 +-- .../appender/FrameworkFileAppender.java | 2 +- .../logback/appender/SiftingFileAppender.java | 2 +- .../appender/TestSupervisorFileAppender.java | 2 +- .../core/model/{Details.java => Buggy.java} | 14 ++++++- .../testng/BaseBuggyExecutionListener.java | 16 +++---- .../buggy/core/testng/BuggyListener.java | 40 +++++++++--------- .../core/testng/LoggingListenerBase.java | 12 +++--- .../core/testng/TestStatisticListener.java | 10 ++--- .../buggy/core/config/TestClassWithSuite.java | 4 +- .../core/config/TestClassWithoutSuite.java | 4 +- .../core/config/TestNGTestClassWithSuite.java | 4 +- .../buggy/core/tests/BaseUnitTest.java | 41 ++++++++++++------ .../starter/example/tests/ExampleTests.java | 4 +- .../starter/example/tests/ExampleTests2.java | 8 ++-- .../starter/example/tests/ExampleTests3.java | 8 ++-- .../listeners/BaseTestRailListener.java | 10 ++--- .../listeners/DefaultTestRailListener.java | 42 +++++++++---------- 21 files changed, 139 insertions(+), 112 deletions(-) rename buggy-core/src/main/java/org/touchbit/buggy/core/model/{Details.java => Buggy.java} (85%) 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 020718a..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.issues(); + tmp = buggy.issues(); if (tmp.length > 0) { sb.append(". Related issues: ").append(Arrays.toString(tmp)); } - tmp = details.bugs(); + 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/logback/appender/FrameworkFileAppender.java b/buggy-core/src/main/java/org/touchbit/buggy/core/logback/appender/FrameworkFileAppender.java index ef63257..d9f3a8f 100644 --- 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 @@ -13,7 +13,7 @@ public FrameworkFileAppender() { super.setContext((LoggerContext) LoggerFactory.getILoggerFactory()); super.setLayout(new FrameworkLoggerLayout<>()); super.setFile(new File(LOG_DIR, "Framework" + LOG_EXT).getPath()); - super.append = true; + super.append = false; } } 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 index 87654ce..ba77f4a 100644 --- 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 @@ -24,7 +24,7 @@ public class SiftingFileAppender extends BaseBuggyFileA public SiftingFileAppender() { super.setContext((LoggerContext) LoggerFactory.getILoggerFactory()); super.setLayout(new ShiftingLoggerLayout<>()); - super.append = true; + super.append = false; } public static synchronized void setTestLogFileName(String logFileName) { 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 index d84caf4..3ebf988 100644 --- 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 @@ -13,7 +13,7 @@ public TestSupervisorFileAppender() { super.setContext((LoggerContext) LoggerFactory.getILoggerFactory()); super.setLayout(new TestSupervisorLoggerLayout<>()); super.setFile(new File(LOG_DIR, "TestSupervisor.log").getPath()); - super.append = true; + super.append = false; } } 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 85% 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 0093174..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,6 +16,8 @@ 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; @@ -32,13 +34,23 @@ */ @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 {""}; + @AliasFor("caseIDs") + String[] IDs() default {""}; + /** * Test status (see: {@link Status}) * Used values: EXP_IMPL, EXP_FIX, BLOCKED, CORRUPTED 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 index 3e62041..9f54b1a 100644 --- 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 @@ -21,7 +21,7 @@ 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.Details; +import org.touchbit.buggy.core.model.Buggy; import java.util.Arrays; import java.util.StringJoiner; @@ -50,8 +50,8 @@ public void onExecutionStart() { } } - protected boolean isIssuesPresent(Details details) { - for (String s : details.issues()) { + protected boolean isIssuesPresent(Buggy buggy) { + for (String s : buggy.issues()) { if (!s.isEmpty()) { return true; } @@ -59,20 +59,20 @@ protected boolean isIssuesPresent(Details details) { return false; } - protected String getIssues(Details details) { - String[] issues = details.issues(); + protected String getIssues(Buggy buggy) { + String[] issues = buggy.issues(); if (issues.length == 0) { return ""; } - return Arrays.toString(details.issues()); + return Arrays.toString(buggy.issues()); } - protected String buildDetailsMessage(Details details, Object... appends) { + protected String buildDetailsMessage(Buggy buggy, Object... appends) { StringJoiner stringJoiner = new StringJoiner(" "); for (Object o : appends) { stringJoiner.add(String.valueOf(o)); } - String ref = isIssuesPresent(details) ? "" + getIssues(details).trim() : ""; + String ref = isIssuesPresent(buggy) ? "" + getIssues(buggy).trim() : ""; String appendsResult = stringJoiner.toString().trim(); if (ref.length() != 0) { return ref + (appendsResult.length() > 0 ? " " + appendsResult.trim() : ""); 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 index 8fcef49..f6b0e98 100644 --- 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 @@ -2,7 +2,7 @@ import org.jetbrains.annotations.Nullable; import org.testng.*; -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.core.model.Suite; @@ -48,7 +48,7 @@ default boolean isSuccess(IInvokedMethod method) { if (!hasDetails(method)) { return isITestResultSuccess(method); } - Status status = getDetailsValue(Details::status, method); + Status status = getDetailsValue(Buggy::status, method); return status.equals(NONE) && isITestResultSuccess(method); } @@ -57,7 +57,7 @@ default boolean isNewError(IInvokedMethod method) { if (!hasDetails(method)) { return isITestResultFailure(method); } - Status status = getDetailsValue(Details::status, method); + Status status = getDetailsValue(Buggy::status, method); return status.equals(NONE) && isITestResultFailure(method); } @@ -66,7 +66,7 @@ default boolean isFixed(IInvokedMethod method) { if (!hasDetails(method)) { return false; } - Status status = getDetailsValue(Details::status, method); + Status status = getDetailsValue(Buggy::status, method); return (status.equals(EXP_FIX) || status.equals(BLOCKED) || status.equals(CORRUPTED)) && isITestResultSuccess(method); } @@ -76,7 +76,7 @@ default boolean isImplemented(IInvokedMethod method) { if (!hasDetails(method)) { return false; } - Status status = getDetailsValue(Details::status, method); + Status status = getDetailsValue(Buggy::status, method); return status.equals(EXP_IMPL) && isITestResultSuccess(method); } @@ -85,7 +85,7 @@ default boolean isExpectedImplementation(IInvokedMethod method) { if (!hasDetails(method)) { return false; } - Status status = getDetailsValue(Details::status, method); + Status status = getDetailsValue(Buggy::status, method); return status.equals(EXP_IMPL) && isITestResultFailure(method); } @@ -94,7 +94,7 @@ default boolean isExpectedFix(IInvokedMethod method) { if (!hasDetails(method)) { return false; } - Status status = getDetailsValue(Details::status, method); + Status status = getDetailsValue(Buggy::status, method); return status.equals(EXP_FIX) && isITestResultFailure(method); } @@ -103,7 +103,7 @@ default boolean isCorrupted(IInvokedMethod method) { if (!hasDetails(method)) { return false; } - Status status = getDetailsValue(Details::status, method); + Status status = getDetailsValue(Buggy::status, method); return status.equals(CORRUPTED) && isITestResultFailure(method); } @@ -112,7 +112,7 @@ default boolean isBlocked(IInvokedMethod method) { if (!hasDetails(method)) { return false; } - Status status = getDetailsValue(Details::status, method); + Status status = getDetailsValue(Buggy::status, method); return status.equals(BLOCKED) && isITestResultFailure(method); } @@ -181,15 +181,15 @@ default boolean isITestResultSkip(ITestResult result) { return iTestResult == ITestResult.SKIP; } - default T getDetailsValue(Function function, IInvokedMethod method) { + default T getDetailsValue(Function function, IInvokedMethod method) { throwNPE(method); - Details details = getDetails(method); - return getDetailsValue(function, details); + Buggy buggy = getDetails(method); + return getDetailsValue(function, buggy); } - default T getDetailsValue(Function function, Details details) { - throwNPE(details); - return function.apply(details); + default T getDetailsValue(Function function, Buggy buggy) { + throwNPE(buggy); + return function.apply(buggy); } default int getITestResultStatus(ITestResult iTestResult) { @@ -242,13 +242,13 @@ default boolean hasDetails(ITestNGMethod method) { default boolean hasDetails(Method method) { if (method != null) { - return method.isAnnotationPresent(Details.class); + return method.isAnnotationPresent(Buggy.class); } return false; } @Nullable - default Details getDetails(IInvokedMethod method) { + default Buggy getDetails(IInvokedMethod method) { if (hasDetails(method)) { return getDetails(method.getTestMethod()); } @@ -256,7 +256,7 @@ default Details getDetails(IInvokedMethod method) { } @Nullable - default Details getDetails(ITestNGMethod method) { + default Buggy getDetails(ITestNGMethod method) { if (hasDetails(method)) { return getDetails(method.getConstructorOrMethod().getMethod()); } @@ -264,9 +264,9 @@ default Details getDetails(ITestNGMethod method) { } @Nullable - default Details getDetails(Method method) { + default Buggy getDetails(Method method) { if (hasDetails(method)) { - return method.getAnnotation(Details.class); + return method.getAnnotation(Buggy.class); } return null; } 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 index 809fa14..8f7e2e9 100644 --- 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 @@ -63,7 +63,7 @@ public void afterInvocation(IInvokedMethod method, ITestResult testResult) { String methodName = TestNGHelper.getMethodName(method); Throwable throwable = testResult.getThrowable(); if (hasDetails(method) && hasSuite(method) && method.isTestMethod()) { - Details details = getDetails(method); + Buggy buggy = getDetails(method); Suite suite = getSuite(method); String component = JUtils.getGoal(Suite::component, suite).getName().trim(); String service = JUtils.getGoal(Suite::service, suite).getName().trim(); @@ -71,11 +71,11 @@ public void afterInvocation(IInvokedMethod method, ITestResult testResult) { //noinspection ConstantConditions String purpose = suite.purpose().trim(); //noinspection ConstantConditions - Status status = details.status(); - Type[] types = details.types(); - String[] ids = details.caseIDs(); - String[] issues = details.issues(); - String[] bugs = details.bugs(); + 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); diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/testng/TestStatisticListener.java b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/TestStatisticListener.java index 7735120..06789e5 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/testng/TestStatisticListener.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/TestStatisticListener.java @@ -6,7 +6,7 @@ import org.testng.IInvokedMethodListener; import org.testng.ITestResult; import org.touchbit.buggy.core.logback.ConfLogger; -import org.touchbit.buggy.core.model.Details; +import org.touchbit.buggy.core.model.Buggy; import org.touchbit.buggy.core.model.Status; import java.util.Date; @@ -49,8 +49,8 @@ public void onExecutionFinish() { @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) { if (method.isTestMethod()) { - Details details = getDetails(method); - if (details == null) { + Buggy buggy = getDetails(method); + if (buggy == null) { notDetailedTests.incrementAndGet(); // TODO remove after --check realisation } totalCountOfTests.incrementAndGet(); @@ -66,8 +66,8 @@ public void afterInvocation(IInvokedMethod method, ITestResult testResult) { if (testNgTestStatus == FAILURE || testNgTestStatus == SUCCESS_PERCENTAGE_FAILURE) { unsuccess.incrementAndGet(); } - if (details != null) { - Status status = details.status(); + if (buggy != null) { + Status status = buggy.status(); if (testNgTestStatus == SUCCESS) { switch (status) { case BLOCKED: 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 39c966b..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 @@ -18,7 +18,7 @@ import org.testng.annotations.Test; import org.touchbit.buggy.core.BaseBuggyTest; -import org.touchbit.buggy.core.model.Details; +import org.touchbit.buggy.core.model.Buggy; import org.touchbit.buggy.core.model.Suite; /** @@ -29,7 +29,7 @@ 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 a88cf1e..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 @@ -18,7 +18,7 @@ import org.testng.annotations.Test; import org.touchbit.buggy.core.BaseBuggyTest; -import org.touchbit.buggy.core.model.Details; +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/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/tests/BaseUnitTest.java b/buggy-core/src/test/java/org/touchbit/buggy/core/tests/BaseUnitTest.java index 6ddf129..3b82cbe 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 @@ -15,7 +15,7 @@ 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; @@ -131,29 +131,44 @@ protected static ITestResult getMockITestResult(Integer status) { } @SuppressWarnings("unused") - protected static Details getDetails() { + protected static Buggy getDetails() { return getDetails(SUCCESS, MODULE); } - protected static Details getDetails(Type type) { + protected static Buggy getDetails(Type type) { return getDetails(SUCCESS, type); } - protected static Details getDetails(Status status, String... issue) { + protected static Buggy getDetails(Status status, String... issue) { return getDetails(status, SYSTEM, issue); } - protected static Details getDetails(Status status, Type type, String... issue) { + protected static Buggy getDetails(Status status, Type type, String... issue) { return getDetails(new String[] {"0"}, status, new Type[]{type}, issue); } - protected static Details getDetails(String[] ids, Status status, Type[] type, String... issue) { - return new Details() { + protected static Buggy getDetails(String[] ids, Status status, Type[] type, String... issue) { + return new Buggy() { + @Override + public String value() { + return null; + } + + @Override + public String testCase() { + return null; + } + @Override public String[] caseIDs() { return ids; } + @Override + public String[] IDs() { + return ids; + } + @Override public Status status() { return status; @@ -176,7 +191,7 @@ public Type[] types() { @Override public Class annotationType() { - return Details.class; + return Buggy.class; } }; } @@ -282,7 +297,7 @@ protected class UnitTestBuggyExecutionListener extends BuggyExecutionListener { public ITestNGMethod method; public Status status; public String msg; - public Details details; + public Buggy buggy; public File sourceFile; public File targetFile; @@ -290,17 +305,17 @@ public UnitTestBuggyExecutionListener() { this(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER); } - public UnitTestBuggyExecutionListener(Details details) { - this(TEST_LOGGER, TEST_LOGGER, TEST_LOGGER, details); + 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, Details details) { + public UnitTestBuggyExecutionListener(Logger testLogger, Logger frameworkLogger, Logger consoleLogger, Buggy buggy) { super(testLogger, frameworkLogger, consoleLogger); - this.details = details; + this.buggy = buggy; } } 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 index 08f21a2..2cc9815 100644 --- 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 @@ -3,7 +3,7 @@ import org.testng.annotations.Test; import org.touchbit.buggy.core.BaseBuggyTest; import org.touchbit.buggy.core.goal.interfaze.API; -import org.touchbit.buggy.core.model.Details; +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; @@ -12,7 +12,7 @@ public class ExampleTests extends BaseBuggyTest { @Test(invocationCount = 10) - @Details + @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 index 26ac873..b850c55 100644 --- 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 @@ -4,7 +4,7 @@ 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.Details; +import org.touchbit.buggy.core.model.Buggy; import org.touchbit.buggy.core.model.Status; import org.touchbit.buggy.core.model.Suite; @@ -12,7 +12,7 @@ public class ExampleTests2 extends BaseBuggyTest { @Test(description = "Ожидается успешное создание пользователя, если firstName=<пустая строка>") - @Details(status = Status.EXP_FIX, bugs = "JIRA-123") + @Buggy(status = Status.EXP_FIX, bugs = "JIRA-123") public void test_2() { throw new AssertionException("The following 4 assertions failed:\n" + " 1) [Living Guests] expected:<[7]> but was:<[6]>\n" + @@ -21,8 +21,8 @@ public void test_2() { " 4) [Professor] expected:<'[well kempt]'> but was:<'[bloodied and dishevelled]'>"); } - @Test(description = "") - @Details(status = Status.EXP_IMPL, bugs = "JIRA-321") + @Test() + @Buggy("Ожидается успешное создание пользователя, если middleName=<пустая строка>") public void test_1() { } 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 index 425df34..556ee47 100644 --- 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 @@ -2,7 +2,7 @@ import org.testng.annotations.Test; import org.touchbit.buggy.core.goal.interfaze.API; -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; @@ -14,13 +14,13 @@ public class ExampleTests3 { @Test - @Details(status = CORRUPTED) + @Buggy(status = CORRUPTED) public void test_3() throws Exception { throw new ProtocolException("Received HTTP_PROXY_AUTH (407) code while not using proxy"); } - @Test(description = "") - @Details(status = Status.BLOCKED, bugs = "JIRA-321") + @Test + @Buggy(status = Status.BLOCKED, bugs = "JIRA-321") public void test_1() { } 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 0a3f994..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 @@ -4,7 +4,7 @@ import org.testng.IInvokedMethodListener; import org.testng.ITestResult; import org.touchbit.buggy.core.config.BuggyConfigurationYML; -import org.touchbit.buggy.core.model.Details; +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; @@ -87,7 +87,7 @@ 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 = "0"; // TODO // String strRunID = String.valueOf(result.getAttribute(RUN_ID.toString())); @@ -96,10 +96,10 @@ protected void addResult(ITestResult result, Details details, S status, String c } try { Long runID = Long.parseLong(strRunID); - for (String caseId : details.caseIDs()) { + for (String caseId : buggy.caseIDs()) { if (statusMapper.getId(status) > 0) { StringJoiner defects = new StringJoiner(", "); - for (String bug : details.bugs()) { + for (String bug : buggy.bugs()) { defects.add(bug); } TRResult trResult = new TRResult() @@ -120,7 +120,7 @@ protected void addResult(ITestResult result, Details details, S status, String c 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.caseIDs()) + "_" : ""; String prefix = caseIds + method.getName(); 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 2c55cd3..5e93cfd 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,7 +6,7 @@ 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.Status; import org.touchbit.buggy.testrail.BaseTestRailConfig; import org.touchbit.buggy.testrail.StatusMapper; @@ -27,65 +27,65 @@ public DefaultTestRailListener(StatusMapper statusMapper) { @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 = getDetails(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()) { + 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()) { + protected void processSuccessTest(Buggy buggy, ITestResult result, String throwableMsg) { + switch (buggy.status()) { case EXP_FIX: case BLOCKED: - addResult(result, details, FIXED, + 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, details, IMPLEMENTED, + addResult(result, buggy, 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()); + addResult(result, buggy, CORRUPTED, new CorruptedTestException(buggy).getMessage()); break; default: - addResult(result, details, SUCCESS, "The test passed successfully." + throwableMsg); + addResult(result, buggy, SUCCESS, "The test passed successfully." + throwableMsg); } } From de9dc6898201c51b8f6b8f0898e2442849b79b18 Mon Sep 17 00:00:00 2001 From: Shaburov Oleg Date: Sun, 11 Oct 2020 07:04:45 +0300 Subject: [PATCH 21/24] LoggingListener v2 --- .../core/config/BuggyConfigurationYML.java | 134 ++++++---- .../touchbit/buggy/core/config}/JCommand.java | 3 +- .../buggy/core/config}/OutputRule.java | 2 +- .../buggy/core/logback/ConfLogger.java | 13 +- .../org/touchbit/buggy/core/model/Status.java | 15 -- .../testng/BaseBuggyExecutionListener.java | 30 --- .../core/testng/BuggyExecutionListener.java | 137 +++++----- .../buggy/core/testng/BuggyListener.java | 197 +++++++++----- .../core/testng/ExecutionListenerBase.java | 47 ++++ .../core/testng/LoggingListenerBase.java | 253 +++++++----------- ...er.java => TestStatisticListenerBase.java} | 33 ++- .../buggy/core/testng/TestSupervisor.java | 3 - .../org/touchbit/buggy/core/utils/ANSI.java | 6 + .../buggy/core/utils/TestNGHelper.java | 36 --- .../src/main/resources/buggy-config.yml | 17 +- .../buggy/core/tests/BaseUnitTest.java | 10 - .../tests/config/JCommanderConfigTests.java | 94 +++---- .../starter/example/ExampleBuggyRunner.java | 9 +- .../example/conf/ExampleConfiguration.java | 2 +- .../starter/example/tests/ExampleTests.java | 3 +- .../starter/example/tests/ExampleTests2.java | 19 +- .../starter/example/tests/ExampleTests3.java | 4 +- .../boot/starter/example/tests/WebTests.java | 21 ++ .../src/main/resources/buggy-config.yml | 17 +- .../spring/boot/starter/BuggyRunner.java | 6 +- .../starter/conf/JCommanderConfiguration.java | 6 +- .../boot/starter/jcommander/BParameters.java | 59 ---- .../jcommander/BuggyConfiguration.java | 108 +++++--- .../boot/starter/jcommander/CommandNames.java | 57 ++++ .../jcommander/converters/GoalConverter.java | 8 +- .../converters/ParameterValidator.java | 2 +- .../testng/listeners/ExecutionListener.java | 12 + .../listeners/ListenerConfiguration.java | 40 +++ .../testng/listeners/LoggingListener.java | 2 +- .../listeners/TestStatisticListener.java | 12 + .../listeners/DefaultTestRailListener.java | 2 +- 36 files changed, 769 insertions(+), 650 deletions(-) rename {buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander => buggy-core/src/main/java/org/touchbit/buggy/core/config}/JCommand.java (97%) rename {buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander => buggy-core/src/main/java/org/touchbit/buggy/core/config}/OutputRule.java (53%) create mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/testng/ExecutionListenerBase.java rename buggy-core/src/main/java/org/touchbit/buggy/core/testng/{TestStatisticListener.java => TestStatisticListenerBase.java} (84%) delete mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/utils/TestNGHelper.java create mode 100644 buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/tests/WebTests.java delete mode 100644 buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/BParameters.java create mode 100644 buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/CommandNames.java create mode 100644 buggy-testng-listeners/src/main/java/org/touchbit/buggy/testng/listeners/ExecutionListener.java create mode 100644 buggy-testng-listeners/src/main/java/org/touchbit/buggy/testng/listeners/ListenerConfiguration.java create mode 100644 buggy-testng-listeners/src/main/java/org/touchbit/buggy/testng/listeners/TestStatisticListener.java 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 index dc7cb0b..373e8e3 100644 --- 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 @@ -27,30 +27,24 @@ @SuppressWarnings("unused") public final class BuggyConfigurationYML implements ConfigurationYML { + private static String programName = "Buggy"; private static Boolean help = false; - private static Boolean force = false; - private static Boolean printSuite = false; - private static Boolean printCause = false; - private static Boolean printLog = false; - private static Boolean printLogOnlyFail = false; - private static Boolean version = false; + private static Boolean forceRun = false; private static Integer threads = 50; - private static String artifactsUrl; private static ParallelMode parallelMode = METHODS; + private static String artifactsUrl; private static List components = JUtils.getListWith(AllComponents::new); private static List services = JUtils.getListWith(AllServices::new); private static List interfaces = JUtils.getListWith(AllInterfaces::new); private static List types = JUtils.getListWith(ALL); - private static String programName = "Buggy"; private static String issuesUrl = ""; - - public static void setPrintLogFileOnlyFail(Boolean printLogIfFail) { - BuggyConfigurationYML.printLogOnlyFail = printLogIfFail; - } - - public static Boolean isPrintLogFileOnlyFail() { - return printLogOnlyFail; - } + 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; @@ -60,48 +54,12 @@ public static void setHelp(Boolean help) { BuggyConfigurationYML.help = help; } - public static Boolean isForce() { - return force; + public static Boolean isForceRun() { + return forceRun; } - public static void setForce(Boolean force) { - BuggyConfigurationYML.force = force; - } - - public static Boolean isPrintSuite() { - return printSuite; - } - - public static void setPrintSuite(Boolean printSuite) { - BuggyConfigurationYML.printSuite = printSuite; - } - - public static Boolean isPrintCause() { - return printCause; - } - - public static void setPrintCause(Boolean printCause) { - BuggyConfigurationYML.printCause = printCause; - } - - public static Boolean isPrintLog() { - return printLog; - } - - public static void setPrintLog(Boolean printLog) { - BuggyConfigurationYML.printLog = printLog; - } - - public static void setPrintLogOnlyFail(Boolean printLogOnlyFail) { - BuggyConfigurationYML.printLogOnlyFail = printLogOnlyFail; - } - - public static Boolean isVersion() { - return version; - } - - public static void setVersion(Boolean version) { - BuggyConfigurationYML.version = version; + public static void setForceRun(Boolean forceRun) { + BuggyConfigurationYML.forceRun = forceRun; } public static Integer getThreads() { @@ -238,4 +196,68 @@ 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-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/JCommand.java b/buggy-core/src/main/java/org/touchbit/buggy/core/config/JCommand.java similarity index 97% rename from buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/JCommand.java rename to buggy-core/src/main/java/org/touchbit/buggy/core/config/JCommand.java index 450d727..d9998a5 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/JCommand.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/config/JCommand.java @@ -1,7 +1,6 @@ -package org.touchbit.buggy.spring.boot.starter.jcommander; +package org.touchbit.buggy.core.config; import com.beust.jcommander.Parameter; -import org.touchbit.buggy.core.config.ConfigurationYML; import org.touchbit.buggy.core.logback.FrameworkLogger; import org.touchbit.buggy.core.utils.JUtils; diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/OutputRule.java b/buggy-core/src/main/java/org/touchbit/buggy/core/config/OutputRule.java similarity index 53% rename from buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/OutputRule.java rename to buggy-core/src/main/java/org/touchbit/buggy/core/config/OutputRule.java index 3fa597f..67b7289 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/OutputRule.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/config/OutputRule.java @@ -1,4 +1,4 @@ -package org.touchbit.buggy.spring.boot.starter.jcommander; +package org.touchbit.buggy.core.config; public enum OutputRule { 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 index e38729b..cf1f6fd 100644 --- 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 @@ -36,8 +36,14 @@ public static void blockDelimiter() { public static void dotPlaceholder(Object prefix, Object postfix, ANSI ansi, boolean isWrapCondition) { String msg = getDotPlaceholder(prefix, postfix); if (isWrapCondition) { - msg = ansi.wrap(msg); + 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); } @@ -49,6 +55,11 @@ 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)); } 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 bfd322e..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 @@ -24,26 +24,11 @@ */ public enum Status implements IStatus { -// EXP_IMPL, -// EXP_FIX, -// BLOCKED, -// CORRUPTED, -// UNTESTED, -// ; -// - // Test method statuses EXP_IMPL, EXP_FIX, BLOCKED, CORRUPTED, NONE, - - // Result statuses - FIXED, - IMPLEMENTED, - SUCCESS, - SKIP, - FAILED, ; @Override 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 index 9f54b1a..9a28370 100644 --- 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 @@ -50,34 +50,4 @@ public void onExecutionStart() { } } - protected boolean isIssuesPresent(Buggy buggy) { - for (String s : buggy.issues()) { - if (!s.isEmpty()) { - return true; - } - } - return false; - } - - protected String getIssues(Buggy buggy) { - String[] issues = buggy.issues(); - if (issues.length == 0) { - return ""; - } - return Arrays.toString(buggy.issues()); - } - - protected String buildDetailsMessage(Buggy buggy, Object... appends) { - StringJoiner stringJoiner = new StringJoiner(" "); - for (Object o : appends) { - stringJoiner.add(String.valueOf(o)); - } - String ref = isIssuesPresent(buggy) ? "" + getIssues(buggy).trim() : ""; - String appendsResult = stringJoiner.toString().trim(); - if (ref.length() != 0) { - return ref + (appendsResult.length() > 0 ? " " + appendsResult.trim() : ""); - } - return stringJoiner.length() != 0 ? stringJoiner.toString().trim() : ""; - } - } 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 index b2d2a31..bfa85ca 100644 --- 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 @@ -19,9 +19,15 @@ 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.util.ArrayList; +import java.util.Arrays; import java.util.List; +import java.util.StringJoiner; /** * Listener for processing executable tests. @@ -29,7 +35,7 @@ * Created by Shaburov Oleg on 31.07.2017. */ @SuppressWarnings({"unused", "UnusedReturnValue", "squid:S2629"}) -public class BuggyExecutionListener extends BaseBuggyExecutionListener +public abstract class BuggyExecutionListener extends BaseBuggyExecutionListener implements IExecutionListener, IInvokedMethodListener, ISuiteListener, ITestListener, IClassListener { private static final ThreadLocal> STEPS = new ThreadLocal<>(); @@ -134,32 +140,31 @@ public void onExecutionFinish() { // } // } // -// @Override -// public void onStart(ISuite suite) { -// disableTestsByType(suite); -// if (!BuggyConfig.isForce()) { -// disableTestsByStatus(suite); -// } -// } + @Override + public void onStart(ISuite suite) { + disableTestsByType(suite); + if (!BuggyConfigurationYML.isForceRun()) { + disableTestsByStatus(suite); + } + } // -// @Override -// public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { -// STEPS.set(new ArrayList<>()); -// String methodName = getMethodName(method); -// SiftingTestLogger.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.annotationType().getTypeName()); -// } -// testLog.debug("Declared method annotations:{}", sj); -// } -// } + @Override + public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { + STEPS.set(new ArrayList<>()); + String methodName = getMethodName(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.annotationType().getTypeName()); + } + testLog.debug("Declared method annotations:{}", sj); + } + } // // @Override // public void afterInvocation(IInvokedMethod method, ITestResult testResult) { @@ -260,46 +265,46 @@ public void onExecutionFinish() { // } // } // -// 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); -// List configType = BuggyConfig.getTypes(); -// if (details != null) { -// List methodTypes = new ArrayList<>(Arrays.asList(details.types())); -// boolean matched = methodTypes.stream().anyMatch(configType::contains); -// if (!configType.contains(Type.ALL) && !matched) { -// method.setInvocationCount(0); -// resultLog(method, Status.SKIP, buildDetailsMessage(details, details.types(), "test types")); -// } -// } -// }); -// } + 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); + List configType = BuggyConfigurationYML.getTypes(); + 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(); 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 index f6b0e98..bb21647 100644 --- 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 @@ -2,12 +2,13 @@ import org.jetbrains.annotations.Nullable; import org.testng.*; -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.core.model.Suite; +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.List; import java.util.function.Function; import static org.touchbit.buggy.core.model.Status.*; @@ -21,31 +22,70 @@ public interface BuggyListener extends ITestNGListener { boolean isEnable(); default boolean isRun(IInvokedMethod method) { - throwNPE(method); + assertNotNull(method); return isRun(method.getTestMethod()); } default boolean isRun(ITestNGMethod method) { - throwNPE(method); + assertNotNull(method); return method.getInvocationCount() > 0; } default boolean isSkip(IInvokedMethod method) { - throwNPE(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) { - throwNPE(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; + } + List types = BuggyConfigurationYML.getTypes(); + if (types.contains(Type.ALL)) { + return false; + } + boolean contains = false; + for (Type type : buggyAnnotation.types()) { + if (types.contains(type)) { + contains = true; + break; + } + } + return !contains; + } + default boolean isSuccess(IInvokedMethod method) { - throwNPE(method); - if (!hasDetails(method)) { + assertNotNull(method); + if (!hasBuggyAnnotation(method)) { return isITestResultSuccess(method); } Status status = getDetailsValue(Buggy::status, method); @@ -53,8 +93,8 @@ default boolean isSuccess(IInvokedMethod method) { } default boolean isNewError(IInvokedMethod method) { - throwNPE(method); - if (!hasDetails(method)) { + assertNotNull(method); + if (!hasBuggyAnnotation(method)) { return isITestResultFailure(method); } Status status = getDetailsValue(Buggy::status, method); @@ -62,8 +102,8 @@ default boolean isNewError(IInvokedMethod method) { } default boolean isFixed(IInvokedMethod method) { - throwNPE(method); - if (!hasDetails(method)) { + assertNotNull(method); + if (!hasBuggyAnnotation(method)) { return false; } Status status = getDetailsValue(Buggy::status, method); @@ -72,8 +112,8 @@ default boolean isFixed(IInvokedMethod method) { } default boolean isImplemented(IInvokedMethod method) { - throwNPE(method); - if (!hasDetails(method)) { + assertNotNull(method); + if (!hasBuggyAnnotation(method)) { return false; } Status status = getDetailsValue(Buggy::status, method); @@ -81,8 +121,8 @@ default boolean isImplemented(IInvokedMethod method) { } default boolean isExpectedImplementation(IInvokedMethod method) { - throwNPE(method); - if (!hasDetails(method)) { + assertNotNull(method); + if (!hasBuggyAnnotation(method)) { return false; } Status status = getDetailsValue(Buggy::status, method); @@ -90,8 +130,8 @@ default boolean isExpectedImplementation(IInvokedMethod method) { } default boolean isExpectedFix(IInvokedMethod method) { - throwNPE(method); - if (!hasDetails(method)) { + assertNotNull(method); + if (!hasBuggyAnnotation(method)) { return false; } Status status = getDetailsValue(Buggy::status, method); @@ -99,8 +139,8 @@ default boolean isExpectedFix(IInvokedMethod method) { } default boolean isCorrupted(IInvokedMethod method) { - throwNPE(method); - if (!hasDetails(method)) { + assertNotNull(method); + if (!hasBuggyAnnotation(method)) { return false; } Status status = getDetailsValue(Buggy::status, method); @@ -108,8 +148,8 @@ default boolean isCorrupted(IInvokedMethod method) { } default boolean isBlocked(IInvokedMethod method) { - throwNPE(method); - if (!hasDetails(method)) { + assertNotNull(method); + if (!hasBuggyAnnotation(method)) { return false; } Status status = getDetailsValue(Buggy::status, method); @@ -148,52 +188,52 @@ default ResultStatus getResultStatus(IInvokedMethod method) { } default boolean isITestResultSuccess(IInvokedMethod method) { - throwNPE(method); + assertNotNull(method); return isITestResultSuccess(method.getTestResult()); } default boolean isITestResultSuccess(ITestResult testResult) { - throwNPE(testResult); + assertNotNull(testResult); int status = testResult.getStatus(); return status == ITestResult.SUCCESS; } default boolean isITestResultFailure(IInvokedMethod method) { - throwNPE(method); + assertNotNull(method); return isITestResultFailure(method.getTestResult()); } default boolean isITestResultFailure(ITestResult result) { - throwNPE(result); + assertNotNull(result); int iTestResult = getITestResultStatus(result); return iTestResult == ITestResult.FAILURE || iTestResult == ITestResult.SUCCESS_PERCENTAGE_FAILURE; } default boolean isITestResultSkip(IInvokedMethod method) { - throwNPE(method); + assertNotNull(method); return isITestResultSkip(method.getTestResult()); } default boolean isITestResultSkip(ITestResult result) { - throwNPE(result); + assertNotNull(result); int iTestResult = getITestResultStatus(result); return iTestResult == ITestResult.SKIP; } default T getDetailsValue(Function function, IInvokedMethod method) { - throwNPE(method); - Buggy buggy = getDetails(method); + assertNotNull(method); + Buggy buggy = getBuggyAnnotation(method); return getDetailsValue(function, buggy); } default T getDetailsValue(Function function, Buggy buggy) { - throwNPE(buggy); + assertNotNull(buggy); return function.apply(buggy); } default int getITestResultStatus(ITestResult iTestResult) { - throwNPE(iTestResult); + assertNotNull(iTestResult); return iTestResult.getStatus(); } @@ -226,21 +266,21 @@ default String getDescription(ITestNGMethod method) { return ""; } - default boolean hasDetails(IInvokedMethod method) { + default boolean hasBuggyAnnotation(IInvokedMethod method) { if (method != null) { - return hasDetails(method.getTestMethod()); + return hasBuggyAnnotation(method.getTestMethod()); } return false; } - default boolean hasDetails(ITestNGMethod method) { + default boolean hasBuggyAnnotation(ITestNGMethod method) { if (method != null) { - return hasDetails(method.getConstructorOrMethod().getMethod()); + return hasBuggyAnnotation(method.getConstructorOrMethod().getMethod()); } return false; } - default boolean hasDetails(Method method) { + default boolean hasBuggyAnnotation(Method method) { if (method != null) { return method.isAnnotationPresent(Buggy.class); } @@ -248,91 +288,116 @@ default boolean hasDetails(Method method) { } @Nullable - default Buggy getDetails(IInvokedMethod method) { - if (hasDetails(method)) { - return getDetails(method.getTestMethod()); + default Buggy getBuggyAnnotation(IInvokedMethod method) { + if (hasBuggyAnnotation(method)) { + return getBuggyAnnotation(method.getTestMethod()); } return null; } @Nullable - default Buggy getDetails(ITestNGMethod method) { - if (hasDetails(method)) { - return getDetails(method.getConstructorOrMethod().getMethod()); + default Buggy getBuggyAnnotation(ITestNGMethod method) { + if (hasBuggyAnnotation(method)) { + return getBuggyAnnotation(method.getConstructorOrMethod().getMethod()); } return null; } @Nullable - default Buggy getDetails(Method method) { - if (hasDetails(method)) { + default Buggy getBuggyAnnotation(Method method) { + if (hasBuggyAnnotation(method)) { return method.getAnnotation(Buggy.class); } return null; } - default boolean hasSuite(IInvokedMethod method) { + default boolean hasSuiteAnnotation(IInvokedMethod method) { if (method != null) { - return hasSuite(method.getTestMethod()); + return hasSuiteAnnotation(method.getTestMethod()); } return false; } - default boolean hasSuite(ITestClass iTestClass) { + default boolean hasSuiteAnnotation(ITestClass iTestClass) { if (iTestClass != null) { - return hasSuite(iTestClass.getRealClass()); + return hasSuiteAnnotation(iTestClass.getRealClass()); } return false; } - default boolean hasSuite(ITestNGMethod method) { + default boolean hasSuiteAnnotation(ITestNGMethod method) { if (method != null) { - return hasSuite(method.getRealClass()); + return hasSuiteAnnotation(method.getRealClass()); } return false; } - default boolean hasSuite(Class realClass) { + default boolean hasSuiteAnnotation(Class realClass) { return realClass.isAnnotationPresent(Suite.class); } @Nullable - default Suite getSuite(IInvokedMethod method) { - if (hasSuite(method)) { - return getSuite(method.getTestMethod()); + default Suite getSuiteAnnotation(IInvokedMethod method) { + if (hasSuiteAnnotation(method)) { + return getSuiteAnnotation(method.getTestMethod()); } return null; } @Nullable - default Suite getSuite(ITestClass iTestClass) { - if (hasSuite(iTestClass)) { - return getSuite(iTestClass.getRealClass()); + default Suite getSuiteAnnotation(ITestClass iTestClass) { + if (hasSuiteAnnotation(iTestClass)) { + return getSuiteAnnotation(iTestClass.getRealClass()); } return null; } @Nullable - default Suite getSuite(ITestNGMethod method) { - if (hasSuite(method)) { - return getSuite(method.getRealClass()); + default Suite getSuiteAnnotation(ITestNGMethod method) { + if (hasSuiteAnnotation(method)) { + return getSuiteAnnotation(method.getRealClass()); } return null; } @Nullable - default Suite getSuite(Class realClass) { - if (hasSuite(realClass)) { + default Suite getSuiteAnnotation(Class realClass) { + if (hasSuiteAnnotation(realClass)) { return realClass.getAnnotation(Suite.class); } return null; } - default void throwNPE(Object o) { + 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..96c2264 --- /dev/null +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/ExecutionListenerBase.java @@ -0,0 +1,47 @@ +/* + * 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) { + 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/LoggingListenerBase.java b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/LoggingListenerBase.java index 8f7e2e9..814cbd1 100644 --- 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 @@ -16,37 +16,73 @@ package org.touchbit.buggy.core.testng; -import org.testng.IInvokedMethod; -import org.testng.IInvokedMethodListener; -import org.testng.ITestNGMethod; -import org.testng.ITestResult; +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.ConsoleLogger; -import org.touchbit.buggy.core.logback.FrameworkLogger; 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 org.touchbit.buggy.core.utils.TestNGHelper; import java.io.File; import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.Date; +import java.util.*; -import static org.touchbit.buggy.core.utils.ANSI.RED; +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 { +public abstract class LoggingListenerBase implements BuggyListener, IInvokedMethodListener, ISuiteListener { - private static final FrameworkLogger FRAMEWORK = new FrameworkLogger(); - private static final ConsoleLogger CONSOLE = new ConsoleLogger(); private static final SiftingTestLogger TEST = new SiftingTestLogger(); + private 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); + } + + private 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); + } + } + + public 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); + } + } + + public 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); @@ -54,17 +90,14 @@ public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) { - TEST.info("Date: {}", new Date()); ResultStatus resultStatus = getResultStatus(method); SiftingTestLogger.setTestResultStatus(resultStatus); - Boolean printLog = BuggyConfigurationYML.isPrintLog(); - Boolean printSuite = BuggyConfigurationYML.isPrintSuite(); - Boolean printCause = BuggyConfigurationYML.isPrintCause(); - String methodName = TestNGHelper.getMethodName(method); + String methodName = getMethodName(method); + TEST.info("Date: {}", new Date()); Throwable throwable = testResult.getThrowable(); - if (hasDetails(method) && hasSuite(method) && method.isTestMethod()) { - Buggy buggy = getDetails(method); - Suite suite = getSuite(method); + 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(); @@ -77,11 +110,18 @@ public void afterInvocation(IInvokedMethod method, ITestResult testResult) { String[] issues = buggy.issues(); String[] bugs = buggy.bugs(); String indent = " "; - - String dotPlaceholder = ConfLogger.getDotPlaceholder(methodName, resultStatus); + 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 (printSuite) { + if (BuggyConfigurationYML.getTestSuiteInfo()) { message.append(" [") .append(component).append(" ") .append(service).append(" ") @@ -91,16 +131,16 @@ public void afterInvocation(IInvokedMethod method, ITestResult testResult) { } message.append("]"); } - if (hasDescription(method)) { + if (BuggyConfigurationYML.getTestCaseTitle() && hasDescription(method)) { // message.append("\n").append(" § ").append(description); message.append("\n Case: ").append(getDescription(method)); indent += indent; } - if (printLog) { + if (BuggyConfigurationYML.getTestLogFilePath()) { message.append("\n Log: ").append(getLogFilePath()); indent += indent; } - if (printCause && bugs.length > 0) { + 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(" ❗ "))) @@ -110,7 +150,7 @@ public void afterInvocation(IInvokedMethod method, ITestResult testResult) { message.append(" ").append(Arrays.toString(bugs)); } } - if (true) { + if (BuggyConfigurationYML.getTestIssuesInfo()) { if (BuggyConfigurationYML.getIssuesUrl() != null && !BuggyConfigurationYML.getIssuesUrl().isEmpty()) { for (String bug : bugs) { // message.append("\n └").append(BOLD.wrap(GREEN.wrap(" ✓ "))) @@ -121,7 +161,7 @@ public void afterInvocation(IInvokedMethod method, ITestResult testResult) { } } - if (printCause && throwable != null) { + if (BuggyConfigurationYML.getTestErrorInfo() && throwable != null) { // message.append("\n └ ").append(BOLD.wrap(RED.wrap("↯ "))) message.append("\n ") .append(RED.wrap(throwable.getClass().getSimpleName())) @@ -129,133 +169,29 @@ public void afterInvocation(IInvokedMethod method, ITestResult testResult) { .append(throwable.getMessage()); } ConfLogger.info(message.append("\n").toString()); -// processTestMethodResult(method, testResult, details); - } else { -// processConfigurationMethodResult(method, testResult); } } -// -// public void resultLog(ITestNGMethod method, Status status, String details) { -// String methodName = method.getMethodName(); -// Suite suite = TestNGHelper.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()); -// } -// TEST.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() : "")); -// } -// -// 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: -// FRAMEWORK.error("Received unprocessed status: {}", testResult.getStatus()); -//// Buggy.incrementBuggyErrors(); -// } -// } -// -// public void processConfigurationMethodResult(IInvokedMethod method, ITestResult testResult) { -// String methodName = TestNGHelper.getMethodName(method); -// String description = getDescription(method); -// switch (testResult.getStatus()) { -// case SUCCESS: -// TEST.info("Invoke configuration method [{}] completed successfully", methodName); -// break; -// case SKIP: -// TEST.warn("Invoke configuration method [{}] skipped. " + -// "List of dependent tests that were missed: {}", methodName, description); -// break; -// case SUCCESS_PERCENTAGE_FAILURE: -// case FAILURE: -// TEST.error("Invoke configuration method [{}] completed with error \n{}", -// methodName, testResult.getThrowable().getMessage()); -// break; -// default: -//// Buggy.incrementBuggyErrors(); -// FRAMEWORK.error("Received unresolved status of configuration method [{}]. Status: {}", -// methodName, testResult.getStatus()); -// } -// } -// -// -// 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 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. @@ -273,13 +209,4 @@ protected String getLogFilePath() { } } - protected String getLogFileName(IInvokedMethod method) { - return getLogFileName(method.getTestMethod()); - } - - protected String getLogFileName(ITestNGMethod iTestNGMethod) { - Method method = iTestNGMethod.getConstructorOrMethod().getMethod(); - return method.getName() + ".log"; - } - } diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/testng/TestStatisticListener.java b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/TestStatisticListenerBase.java similarity index 84% rename from buggy-core/src/main/java/org/touchbit/buggy/core/testng/TestStatisticListener.java rename to buggy-core/src/main/java/org/touchbit/buggy/core/testng/TestStatisticListenerBase.java index 06789e5..afc5254 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/testng/TestStatisticListener.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/TestStatisticListenerBase.java @@ -15,7 +15,7 @@ import static org.testng.ITestResult.*; import static org.touchbit.buggy.core.utils.ANSI.*; -public class TestStatisticListener implements BuggyListener, IExecutionListener, IInvokedMethodListener { +public abstract class TestStatisticListenerBase implements BuggyListener, IExecutionListener, IInvokedMethodListener { protected static AtomicInteger totalCountOfTests = new AtomicInteger(0); protected static AtomicInteger totalCountOfTestsRun = new AtomicInteger(0); @@ -25,8 +25,8 @@ public class TestStatisticListener implements BuggyListener, IExecutionListener, protected static AtomicInteger notDetailedTests = new AtomicInteger(0); protected static AtomicInteger newErrors = new AtomicInteger(0); - protected static AtomicInteger waitingToFixDefect = new AtomicInteger(0); - protected static AtomicInteger waitingForImplementation = 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); @@ -49,7 +49,7 @@ public void onExecutionFinish() { @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) { if (method.isTestMethod()) { - Buggy buggy = getDetails(method); + Buggy buggy = getBuggyAnnotation(method); if (buggy == null) { notDetailedTests.incrementAndGet(); // TODO remove after --check realisation } @@ -93,10 +93,10 @@ public void afterInvocation(IInvokedMethod method, ITestResult testResult) { blockedTests.incrementAndGet(); break; case EXP_FIX: - waitingToFixDefect.incrementAndGet(); + expFix.incrementAndGet(); break; case EXP_IMPL: - waitingForImplementation.incrementAndGet(); + expImpl.incrementAndGet(); break; case NONE: default: @@ -112,26 +112,25 @@ public void printTestStatistic() { ConfLogger.centerBold("Summary"); ConfLogger.dotPlaceholder("Total count of tests", totalCountOfTests); ConfLogger.dotPlaceholder("Total count of tests run", totalCountOfTestsRun); - ConfLogger.dotPlaceholder("Unsuccessful tests", unsuccess, PURPLE, unsuccess.get() != 0); + 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, newErrors.get() != 0); - ConfLogger.dotPlaceholder("Corrupted tests", corruptedTests, RED, corruptedTests.get() != 0); - ConfLogger.dotPlaceholder("Blocked tests", blockedTests); - ConfLogger.dotPlaceholder("Waiting to fix a defect", waitingToFixDefect); - ConfLogger.dotPlaceholder("Waiting for implementation", waitingForImplementation); - ConfLogger.dotPlaceholder("Fixed (did not work before)", fixedCases, GREEN, fixedCases.get() != 0); - ConfLogger.dotPlaceholder("Implemented cases", implemented, GREEN, implemented.get() != 0); + 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); } - @Override - public boolean isEnable() { - return true; + protected boolean isNotZero(AtomicInteger integer) { + return integer.get() != 0; } } diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/testng/TestSupervisor.java b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/TestSupervisor.java index 2ae0d0d..ec55b61 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/testng/TestSupervisor.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/testng/TestSupervisor.java @@ -13,9 +13,6 @@ import java.util.List; import java.util.StringJoiner; -import static org.touchbit.buggy.core.utils.TestNGHelper.getClassSimpleName; -import static org.touchbit.buggy.core.utils.TestNGHelper.getMethodName; - /** * Created by Oleg Shaburov on 16.09.2018 * shaburov.o.a@gmail.com 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 index ba86b75..5307f1b 100644 --- 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 @@ -5,9 +5,15 @@ 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(""), ; diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/utils/TestNGHelper.java b/buggy-core/src/main/java/org/touchbit/buggy/core/utils/TestNGHelper.java deleted file mode 100644 index 5c2688a..0000000 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/utils/TestNGHelper.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.touchbit.buggy.core.utils; - -import org.testng.IInvokedMethod; -import org.testng.ITestNGMethod; -import org.testng.ITestResult; - -import java.lang.reflect.Method; - -public class TestNGHelper { - - public static Method getRealMethod(ITestResult result) { - return getRealMethod(result.getMethod()); - } - - public static Method getRealMethod(IInvokedMethod method) { - return getRealMethod(method.getTestMethod()); - } - - public static Method getRealMethod(ITestNGMethod method) { - return method.getConstructorOrMethod().getMethod(); - } - - - public static String getClassSimpleName(IInvokedMethod method) { - return method.getTestMethod().getRealClass().getSimpleName(); - } - - public static String getMethodName(IInvokedMethod method) { - return method.getTestMethod().getMethodName(); - } - - private TestNGHelper() { - 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 index 16a511d..132142e 100644 --- a/buggy-core/src/main/resources/buggy-config.yml +++ b/buggy-core/src/main/resources/buggy-config.yml @@ -1,13 +1,9 @@ programName: Buggy help: false -force: true -printSuite: true -printCause: true -printLog: true -printLogOnlyFail: false +forceRun: true threads: 50 -artifactsUrl: null parallelMode: 'METHODS' +artifactsUrl: null components: - !!org.touchbit.buggy.core.goal.component.AllComponents {} services: @@ -16,4 +12,11 @@ interfaces: - !!org.touchbit.buggy.core.goal.interfaze.AllInterfaces {} types: - ALL -issuesUrl: 'https://example.jira.com/issues/' \ No newline at end of file +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/test/java/org/touchbit/buggy/core/tests/BaseUnitTest.java b/buggy-core/src/test/java/org/touchbit/buggy/core/tests/BaseUnitTest.java index 3b82cbe..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 @@ -32,7 +32,6 @@ 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; @@ -130,15 +129,6 @@ protected static ITestResult getMockITestResult(Integer status) { return iTestResult; } - @SuppressWarnings("unused") - protected static Buggy getDetails() { - return getDetails(SUCCESS, MODULE); - } - - protected static Buggy getDetails(Type type) { - return getDetails(SUCCESS, type); - } - protected static Buggy getDetails(Status status, String... issue) { return getDetails(status, SYSTEM, issue); } 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 2611b4b..5693700 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 @@ -173,53 +173,53 @@ void unitTest_20180919201516() { BuggyConfigurationYML.setArtifactsUrl(buildLogUrl); } } - - @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("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()") 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 index 768b5b6..75e464c 100644 --- 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 @@ -5,16 +5,15 @@ 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.setPrintLog(true); - BuggyConfiguration.setPrintSuite(true); - BuggyConfiguration.setPrintCause(true); BuggyConfiguration.setInterfaces(API.class); - BuggyConfiguration.setPrintLogOnlyFail(true); - BuggyConfiguration.setTaskTrackerIssueUrl("https://jira.com/issues/"); + 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 index 7b56b64..e3dd03a 100644 --- 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 @@ -1,7 +1,7 @@ package org.touchbit.buggy.spring.boot.starter.example.conf; import com.beust.jcommander.Parameter; -import org.touchbit.buggy.spring.boot.starter.jcommander.JCommand; +import org.touchbit.buggy.core.config.JCommand; public class ExampleConfiguration implements JCommand { 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 index 2cc9815..ade3f49 100644 --- 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 @@ -3,12 +3,13 @@ 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(component = GitHub.class, service = Actions.class, interfaze = API.class) +@Suite(component = GitHub.class, service = Actions.class, interfaze = WEB.class) public class ExampleTests extends BaseBuggyTest { @Test(invocationCount = 10) 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 index b850c55..1980b9f 100644 --- 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 @@ -7,13 +7,16 @@ 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 static org.touchbit.buggy.core.model.Type.SYSTEM; @Suite(interfaze = API.class) public class ExampleTests2 extends BaseBuggyTest { @Test(description = "Ожидается успешное создание пользователя, если firstName=<пустая строка>") @Buggy(status = Status.EXP_FIX, bugs = "JIRA-123") - public void test_2() { + public void test_2_1() { 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" + @@ -23,7 +26,19 @@ public void test_2() { @Test() @Buggy("Ожидается успешное создание пользователя, если middleName=<пустая строка>") - public void test_1() { + 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 index 556ee47..1eb5ffb 100644 --- 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 @@ -15,13 +15,13 @@ public class ExampleTests3 { @Test @Buggy(status = CORRUPTED) - public void test_3() throws Exception { + 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_1() { + 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..345d5ef --- /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(component = GitHub.class, 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 index ef2df54..777d575 100644 --- a/buggy-spring-boot-starter-example/src/main/resources/buggy-config.yml +++ b/buggy-spring-boot-starter-example/src/main/resources/buggy-config.yml @@ -1,13 +1,9 @@ programName: 'Buggy example' help: false -force: true -printSuite: true -printCause: true -printLog: true -printLogOnlyFail: true +forceRun: true threads: 50 -artifactsUrl: null parallelMode: 'METHODS' +artifactsUrl: null components: - !!org.touchbit.buggy.core.goal.component.AllComponents {} services: @@ -17,5 +13,10 @@ interfaces: types: - ALL issuesUrl: 'https://example.jira.com/issues/' -exampleHost: foo -examplePass: bar \ No newline at end of file +testCaseTitle: true +testSuiteInfo: false +testLogFilePath: true +testIssuesInfo: false +testBugsInfo: true +testErrorInfo: true +outputRule: UNSUCCESSFUL 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 index 1e5ee12..fd51032 100644 --- 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 @@ -94,10 +94,10 @@ public static void exit(int status, String message, Exception e) { @Override public void run(String... args) { ConfLogger.blockDelimiter(); - Map>> testClassesBySuitesMap = getTestClassesBySuitesMap(filteredTestClasses); - List xmlSuites = getXmlSuites(testClassesBySuitesMap); - TestNG testNG = getTestNG(); try { + Map>> testClassesBySuitesMap = getTestClassesBySuitesMap(filteredTestClasses); + List xmlSuites = getXmlSuites(testClassesBySuitesMap); + TestNG testNG = getTestNG(); testNG.setParallel(BuggyConfigurationYML.getParallelMode().getTestNGMode()); testNG.setSuiteThreadPoolSize(xmlSuites.isEmpty() ? 1 : xmlSuites.size()); testNG.setUseDefaultListeners(false); 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 index 1847f97..dcc194e 100644 --- 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 @@ -15,7 +15,7 @@ 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.spring.boot.starter.jcommander.JCommand; +import org.touchbit.buggy.core.config.JCommand; import javax.annotation.PostConstruct; import java.lang.reflect.Field; @@ -70,12 +70,12 @@ public boolean isJCommanderConfigured() { @PostConstruct public void postConstruct() { - if (BuggyConfigurationYML.isHelp()) { + if (BuggyConfiguration.isHelp()) { ConfLogger.stepDelimiter(); jCommander.usage(); BuggyRunner.exit(0); } - if (BuggyConfigurationYML.isVersion()) { + if (BuggyConfiguration.isVersion()) { ConfLogger.stepDelimiter(); ConfLogger.centerBold("Version info"); JUtils.getBuggyManifest().forEach(ConfLogger::dotPlaceholder); diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/BParameters.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/BParameters.java deleted file mode 100644 index 7dd7ef6..0000000 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/BParameters.java +++ /dev/null @@ -1,59 +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.spring.boot.starter.jcommander; - -/** - * 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 C = "-c"; - public static final String COMPONENTS = "--component"; - public static final String S = "-s"; - public static final String SERVICES = "--service"; - 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 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 EXIT_STATUS = "--exit-status"; - 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 OUTPUT_RULE = "--output-rule"; - public static final String PRINT_CAUSE = "--print-cause"; - public static final String PRINT_LOG_IF_FAIL = "--print-log-if-fail"; - public static final String PROGRAM_NAME = "--program-name"; - - private BParameters() { - throw new IllegalStateException("Utility class. Prohibit instantiation."); - } - -} 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 index b82f507..c406dd3 100644 --- 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 @@ -2,6 +2,8 @@ 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; @@ -15,7 +17,7 @@ import java.util.List; import java.util.Map; -import static org.touchbit.buggy.spring.boot.starter.jcommander.BParameters.*; +import static org.touchbit.buggy.spring.boot.starter.jcommander.CommandNames.*; /** * Configuration class for customizing Buggy. @@ -26,8 +28,8 @@ @SuppressWarnings("unused") public final class BuggyConfiguration implements JCommand { - private static Boolean version; - private static Integer exitStatus; + private static Boolean version = false; + private static Integer exitStatus = null; public static Boolean getVersion() { return version; @@ -37,7 +39,7 @@ public static Integer getExitStatus() { return exitStatus; } - @Parameter(names = {V, VERSION}, description = "Print program version") + @Parameter(names = {VERSION}, description = "Print program version") public static void setVersion(Boolean version) { BuggyConfiguration.version = version; } @@ -56,27 +58,7 @@ public static void setHelp(Boolean help) { @Parameter(names = {F, FORCE}, description = "Running all tests, including those that fall.") public static void setForce(Boolean force) { - BuggyConfigurationYML.setForce(force); - } - - @Parameter(names = {TEST_SUITE_INFO}, description = "Display information on the Suite in the console log.") - public static void setPrintSuite(Boolean printSuite) { - BuggyConfigurationYML.setPrintSuite(printSuite); - } - - @Parameter(names = {PRINT_CAUSE}, description = "Print the cause of a fail or skip test in the console log.") - public static void setPrintCause(Boolean printCause) { - BuggyConfigurationYML.setPrintCause(printCause); - } - - @Parameter(names = {TEST_LOG_FILE_PATH}, description = "Print the test log file path in the console log") - public static void setPrintLog(Boolean printLog) { - BuggyConfigurationYML.setPrintLog(printLog); - } - - @Parameter(names = {PRINT_LOG_IF_FAIL}, description = "Print the failed test log file path in the console log") - public static void setPrintLogOnlyFail(Boolean printLogOnlyFail) { - BuggyConfigurationYML.setPrintLogOnlyFail(printLogOnlyFail); + BuggyConfigurationYML.setForceRun(force); } @Parameter(names = {THREADS}, description = "The number of threads to run the test methods.") @@ -157,7 +139,7 @@ public static void setProgramName(String programName) { } @Parameter(names = {"--issues-url"}, description = "Task tracker issues URL.") - public static void setTaskTrackerIssueUrl(String taskTrackerIssueUrl) { + public static void setIssuesUrl(String taskTrackerIssueUrl) { BuggyConfigurationYML.setIssuesUrl(taskTrackerIssueUrl); } @@ -165,28 +147,75 @@ public static Boolean isHelp() { return BuggyConfigurationYML.isHelp(); } - public static Boolean isPrintLogFileOnlyFail() { - return BuggyConfigurationYML.isPrintLog(); + @Parameter(names = {TEST_CASE_TITLE}, description = "Print the title of the test case to the console log.") + public static void setTestCaseTitle(Boolean testCaseTitle) { + BuggyConfigurationYML.setTestCaseTitle(testCaseTitle); } - public static Boolean isForce() { - return BuggyConfigurationYML.isForce(); + @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); } - public static Boolean isPrintSuite() { - return BuggyConfigurationYML.isPrintSuite(); + @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); } - public static Boolean isPrintCause() { - return BuggyConfigurationYML.isPrintCause(); + @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 isPrintLog() { - return BuggyConfigurationYML.isPrintLog(); + 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 BuggyConfigurationYML.isVersion(); + return version; + } + + public static Boolean isForce() { + return BuggyConfigurationYML.isForceRun(); } public static Integer getThreads() { @@ -228,8 +257,9 @@ public static String getTaskTrackerIssueUrl() { @Override public Map sort(Map map) { String[] sort = new String[] - {THREADS, PARALLEL_MODE, F, TEST_LOG_FILE_PATH, PRINT_CAUSE, TEST_SUITE_INFO, - C, S, I, T, LOGS_PATH, ARTIFACTS_URL, EXIT_STATUS}; + {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()) { 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..1f43314 --- /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 = "--component"; + public static final String S = "-s"; + public static final String SERVICES = "--service"; + 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 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/converters/GoalConverter.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/GoalConverter.java index cf74463..d8bf2e4 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/GoalConverter.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/GoalConverter.java @@ -41,7 +41,7 @@ public GoalConverter(final Class t) { @Override public T convert(String s) { - Set beanDefinitionInstances = scanBeanDefinitions(false, "**.buggy", tClass); + Set beanDefinitionInstances = scanBeanDefinitions(tClass); Set goalClasses = getBeanDefinitionInstances(beanDefinitionInstances, tClass); for (T goal : goalClasses) { if (goal.getClass().getSimpleName().equalsIgnoreCase(s)) { @@ -60,12 +60,12 @@ private Set getBeanDefinitionInstances(Set definitions, return result; } - private Set scanBeanDefinitions(boolean useDefaultFilters, String basePackage, Class c) { + private Set scanBeanDefinitions(Class c) { ClassPathScanningCandidateComponentProvider scanner = - new ClassPathScanningCandidateComponentProvider(useDefaultFilters); + new ClassPathScanningCandidateComponentProvider(false); scanner.addIncludeFilter(new AssignableTypeFilter(c)); try { - return scanner.findCandidateComponents(basePackage); + return scanner.findCandidateComponents("**.buggy"); } catch (Exception e) { throw new RuntimeException(e); } diff --git a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/ParameterValidator.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/ParameterValidator.java index 7483912..24b4512 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/ParameterValidator.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/ParameterValidator.java @@ -19,7 +19,7 @@ import com.beust.jcommander.IParameterValidator; import com.beust.jcommander.ParameterException; -import static org.touchbit.buggy.spring.boot.starter.jcommander.BParameters.*; +import static org.touchbit.buggy.spring.boot.starter.jcommander.CommandNames.*; /** * Created by Oleg Shaburov on 08.09.2018 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 index e5cdf68..a14337b 100644 --- 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 @@ -6,7 +6,7 @@ public class LoggingListener extends LoggingListenerBase { @Override public boolean isEnable() { - return true; + 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/src/main/java/org/touchbit/buggy/testrail/listeners/DefaultTestRailListener.java b/buggy-testrail/src/main/java/org/touchbit/buggy/testrail/listeners/DefaultTestRailListener.java index 5e93cfd..077bfa1 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 @@ -27,7 +27,7 @@ public DefaultTestRailListener(StatusMapper statusMapper) { @Override public void afterInvocation(IInvokedMethod method, ITestResult result) { - Buggy buggy = getDetails(method); + Buggy buggy = getBuggyAnnotation(method); String throwableMsg = processResultThrowable(buggy, result); if (method.isTestMethod() && buggy != null && result.getMethod().getInvocationCount() > 0) { int rStatus = result.getStatus(); From 3e26261356868a0222b2ed0c1eec510eb115ff1a Mon Sep 17 00:00:00 2001 From: Shaburov Oleg Date: Sun, 11 Oct 2020 07:07:08 +0300 Subject: [PATCH 22/24] AllComponents: remove constructors --- .../touchbit/buggy/core/goal/component/AllComponents.java | 8 -------- 1 file changed, 8 deletions(-) diff --git a/buggy-core/src/main/java/org/touchbit/buggy/core/goal/component/AllComponents.java b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/component/AllComponents.java index e9631ff..3ea19ac 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/goal/component/AllComponents.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/goal/component/AllComponents.java @@ -22,14 +22,6 @@ */ public final class AllComponents extends Component { - public AllComponents() { - - } - - public AllComponents(Object o) { - - } - @Override public String getName() { return "ALL"; From 7be3894e98bc86430e0cb039403ccd11b3628c3f Mon Sep 17 00:00:00 2001 From: Shaburov Oleg Date: Thu, 15 Oct 2020 09:13:17 +0300 Subject: [PATCH 23/24] Add logging test steps --- .gitignore | 3 +- .../touchbit/buggy/core/BaseBuggyTest.java | 12 +- .../core/logback/BaseLogbackWrapper.java | 26 +++ .../buggy/core/logback/SiftingTestLogger.java | 36 +++ .../appender/BaseBuggyFileAppender.java | 3 - .../logback/appender/SiftingFileAppender.java | 1 - .../core/testng/BuggyExecutionListener.java | 72 ------ .../buggy/core/testng/BuggyListener.java | 18 +- .../core/testng/LoggingListenerBase.java | 16 +- .../touchbit/buggy/core/utils/IOHelper.java | 19 -- .../buggy/core/utils/StringUtils.java | 140 ------------ .../core/tests/common/BaseBuggyTestTests.java | 22 +- .../buggy/core/tests/utils/IOHelperTests.java | 16 -- .../core/tests/utils/StringUtilsTests.java | 151 ------------- buggy-spring-boot-starter-example/pom.xml | 24 +- .../starter/example/tests/ExampleTests2.java | 21 ++ .../src/main/resources/testng-1.0.dtd | 213 ------------------ .../listeners/DefaultTestRailListener.java | 67 +++--- 18 files changed, 184 insertions(+), 676 deletions(-) delete mode 100644 buggy-core/src/main/java/org/touchbit/buggy/core/utils/StringUtils.java delete mode 100644 buggy-core/src/test/java/org/touchbit/buggy/core/tests/utils/StringUtilsTests.java delete mode 100644 buggy-spring-boot-starter-example/src/main/resources/testng-1.0.dtd 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/src/main/java/org/touchbit/buggy/core/BaseBuggyTest.java b/buggy-core/src/main/java/org/touchbit/buggy/core/BaseBuggyTest.java index 5fd3573..2f02f0e 100644 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/BaseBuggyTest.java +++ b/buggy-core/src/main/java/org/touchbit/buggy/core/BaseBuggyTest.java @@ -32,13 +32,11 @@ @Listeners(IntellijIdeaTestNgPluginListener.class) public abstract class BaseBuggyTest { - protected static Logger log; + protected static SiftingTestLogger log = new SiftingTestLogger(); - protected BaseBuggyTest() { - this(new SiftingTestLogger()); - } + protected BaseBuggyTest() { } - protected BaseBuggyTest(final Logger logger) { + protected BaseBuggyTest(final L logger) { setLog(logger); } @@ -46,10 +44,10 @@ protected BaseBuggyTest(final Logger logger) { * 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; } 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 index 9144805..fd0ffc1 100644 --- 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 @@ -1,18 +1,29 @@ 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"; @@ -37,6 +48,21 @@ public static String getInCaseOfErrorsOrWarnings() { 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(); } 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 index 06c64bc..1c465e4 100644 --- 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 @@ -1,14 +1,19 @@ 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); } @@ -26,6 +31,7 @@ public static void setTestLogFileName(ITestNGMethod iTestNGMethod) { } } + @Nullable public static File getSiftingLogFile() { return SiftingFileAppender.getTestLogFile(); } @@ -34,4 +40,34 @@ 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 index 229388a..6478f84 100644 --- 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 @@ -10,9 +10,6 @@ public abstract class BaseBuggyFileAppender extends FileAppender { public static final String LOG_PATH = "LOG_PATH"; static { - if (System.getProperty("logback.configurationFile") == null) { - System.setProperty("logback.configurationFile", "buggy-logback.xml"); - } if (JUtils.isJetBrainsIdeTestNGPluginRun()) { System.setProperty(LOG_PATH, "target/logs"); } else if (JUtils.isJetBrainsIdeConsoleRun()) { 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 index ba77f4a..dd41d47 100644 --- 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 @@ -12,7 +12,6 @@ import java.io.File; import java.util.ArrayList; import java.util.List; -import java.util.Map; import java.util.stream.Collectors; import static org.touchbit.buggy.core.logback.appender.SiftingAppender.SIFTING_LOG_FILE_PATH; 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 index bfa85ca..b7c33fc 100644 --- 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 @@ -38,8 +38,6 @@ public abstract class BuggyExecutionListener extends BaseBuggyExecutionListener implements IExecutionListener, IInvokedMethodListener, ISuiteListener, ITestListener, IClassListener { - private static final ThreadLocal> STEPS = new ThreadLocal<>(); - public BuggyExecutionListener() { } @@ -49,31 +47,6 @@ public BuggyExecutionListener(Logger testLogger, Logger frameworkLogger, Logger // consoleLog = consoleLogger; } - /** - * 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); - } - @Override public boolean isEnable() { return true; @@ -147,51 +120,6 @@ public void onStart(ISuite suite) { disableTestsByStatus(suite); } } -// - @Override - public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { - STEPS.set(new ArrayList<>()); - String methodName = getMethodName(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.annotationType().getTypeName()); - } - testLog.debug("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()) { -// 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); -// } -// -// } // // public void processTestMethodResult(IInvokedMethod m, ITestResult testResult, Details details) { // ITestNGMethod method = m.getTestMethod(); 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 index bb21647..1e94670 100644 --- 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 @@ -249,7 +249,16 @@ default boolean hasDescription(ITestNGMethod method) { return false; } String description = method.getDescription(); - return description != null && !description.isEmpty(); + 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) { @@ -261,7 +270,12 @@ default String getDescription(IInvokedMethod method) { default String getDescription(ITestNGMethod method) { if (hasDescription(method)) { - return method.getDescription(); + String description = method.getDescription(); + if (description != null && !description.isEmpty()) { + return description; + } + //noinspection ConstantConditions + return getBuggyAnnotation(method).testCase(); } return ""; } 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 index 814cbd1..76a8f0a 100644 --- 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 @@ -40,9 +40,9 @@ */ public abstract class LoggingListenerBase implements BuggyListener, IInvokedMethodListener, ISuiteListener { - private static final SiftingTestLogger TEST = new SiftingTestLogger(); + protected static final SiftingTestLogger TEST = new SiftingTestLogger(); - private static final Set DISABLED_METHODS = new HashSet<>(); + protected static final Set DISABLED_METHODS = new HashSet<>(); @Override public void onStart(ISuite suite) { @@ -51,7 +51,7 @@ public void onStart(ISuite suite) { suite.getAllMethods().forEach(this::skippedByTestAnnotation); } - private void skippedTestsByType(ITestNGMethod method) { + protected void skippedTestsByType(ITestNGMethod method) { if (isSkipByType(method) && !DISABLED_METHODS.contains(method)) { DISABLED_METHODS.add(method); String placeholder = ConfLogger.getDotPlaceholder(method.getMethodName(), SKIP); @@ -62,7 +62,7 @@ private void skippedTestsByType(ITestNGMethod method) { } } - public void skippedByTestStatus(ITestNGMethod method) { + protected void skippedByTestStatus(ITestNGMethod method) { if (isSkipByTestStatus(method) && !DISABLED_METHODS.contains(method)) { DISABLED_METHODS.add(method); String placeholder = ConfLogger.getDotPlaceholder(method.getMethodName(), SKIP); @@ -73,7 +73,7 @@ public void skippedByTestStatus(ITestNGMethod method) { } } - public void skippedByTestAnnotation(ITestNGMethod method) { + protected void skippedByTestAnnotation(ITestNGMethod method) { assertNotNull(method); if (!method.getEnabled()) { String placeholder = ConfLogger.getDotPlaceholder(method.getMethodName(), SKIP); @@ -90,11 +90,14 @@ public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) { + TEST.steps(); ResultStatus resultStatus = getResultStatus(method); SiftingTestLogger.setTestResultStatus(resultStatus); String methodName = getMethodName(method); - TEST.info("Date: {}", new Date()); 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); @@ -170,6 +173,7 @@ public void afterInvocation(IInvokedMethod method, ITestResult testResult) { } ConfLogger.info(message.append("\n").toString()); } + TEST.info("Date: {}", new Date()); } protected ANSI getANSI(ResultStatus status) { 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 f659fc5..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 @@ -117,23 +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); - } - } - } 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 c4c42f2..0000000 --- a/buggy-core/src/main/java/org/touchbit/buggy/core/utils/StringUtils.java +++ /dev/null @@ -1,140 +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 final int STRING_LEN = 47; - public static final String STEP = "\u2014"; - - private StringUtils() { - throw new IllegalStateException("Utility class. Prohibit instantiation."); - } - - 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(String symbol) { - return filler(null, symbol, STRING_LEN, null); - } - - public static String filler(Object prefix, String symbol) { - return filler(prefix, symbol, STRING_LEN, null); - } - - public static String filler(Object prefix, String symbol, Object postfix) { - return filler(prefix, symbol, 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(); - } - - /** - * 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 sPrint() { - println(filler(STEP)); - } - - 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(); - } - } -} 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 c4d6565..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 @@ -72,17 +72,17 @@ class BaseBuggyTestTests extends BaseUnitTest { // } 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/utils/IOHelperTests.java b/buggy-core/src/test/java/org/touchbit/buggy/core/tests/utils/IOHelperTests.java index 7b02272..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 @@ -28,22 +28,6 @@ class IOHelperTests extends BaseUnitTest { // 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 getFileFromResource(exists)") // void unitTest_20180915220703() { 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 64c6f89..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.exceptions.AssertionException; -import org.touchbit.buggy.core.tests.BaseUnitTest; -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 JUtils constructor") - void unitTest_20180915213419() throws NoSuchMethodException { - checkUtilityClassConstructor(StringUtils.class); - } - -} diff --git a/buggy-spring-boot-starter-example/pom.xml b/buggy-spring-boot-starter-example/pom.xml index 25e4a97..51b2afb 100644 --- a/buggy-spring-boot-starter-example/pom.xml +++ b/buggy-spring-boot-starter-example/pom.xml @@ -17,7 +17,8 @@ jar - org.touchbit:buggy-spring-boot-starter-example + org.touchbit.buggy.spring.boot.starter.example.ExampleBuggyRunner + Buggy @@ -29,4 +30,25 @@ + + + + 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/tests/ExampleTests2.java b/buggy-spring-boot-starter-example/src/main/java/org/touchbit/buggy/spring/boot/starter/example/tests/ExampleTests2.java index 1980b9f..eb5622f 100644 --- 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 @@ -9,14 +9,35 @@ import org.touchbit.buggy.core.model.Suite; import org.touchbit.buggy.core.model.Type; +import java.util.Map; +import java.util.UUID; + import static org.touchbit.buggy.core.model.Type.SYSTEM; @Suite(interfaze = API.class) public class ExampleTests2 extends BaseBuggyTest { + @Test + @Buggy() + public void test1603008938585() throws Exception { + Map env = System.getenv(); + for (String envName : env.keySet()) { + System.out.format("%s=%s%n", + envName, + env.get(envName)); + } + System.out.println(" >>>>>> " + System.getProperty("BUGGY_EXAMPLE")); + System.out.println(" >>>>>> " + System.getProperty("JAVA_BUGGY_EXAMPLE")); + System.out.println(" >>>>>> " + System.getenv("BUGGY_EXAMPLE")); + System.out.println(" >>>>>> " + System.getenv("JAVA_BUGGY_EXAMPLE")); + } + @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" + diff --git a/buggy-spring-boot-starter-example/src/main/resources/testng-1.0.dtd b/buggy-spring-boot-starter-example/src/main/resources/testng-1.0.dtd deleted file mode 100644 index 2527392..0000000 --- a/buggy-spring-boot-starter-example/src/main/resources/testng-1.0.dtd +++ /dev/null @@ -1,213 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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 077bfa1..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 @@ -7,6 +7,7 @@ import org.touchbit.buggy.core.exceptions.CorruptedTestException; import org.touchbit.buggy.core.exceptions.ExpectedImplementationException; 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; @@ -41,8 +42,8 @@ public void afterInvocation(IInvokedMethod method, ITestResult result) { protected void processErrorTest(Buggy buggy, ITestResult result, String throwableMsg) { switch (buggy.status()) { - case SKIP: - case FAILED: +// case SKIP: +// case FAILED: case EXP_FIX: case BLOCKED: case EXP_IMPL: @@ -50,7 +51,7 @@ protected void processErrorTest(Buggy buggy, ITestResult result, String throwabl addResult(result, buggy, buggy.status(), throwableMsg); break; default: - addResult(result, buggy, FAILED, throwableMsg); +// addResult(result, buggy, FAILED, throwableMsg); } } @@ -71,22 +72,22 @@ protected String processResultThrowable(Buggy buggy, ITestResult result) { } 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); - } +// 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 @@ -99,20 +100,20 @@ 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(); +// 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); } From 236c481ae9da1754a4192cf1d55709a956287da3 Mon Sep 17 00:00:00 2001 From: Shaburov Oleg Date: Sun, 18 Oct 2020 16:53:57 +0300 Subject: [PATCH 24/24] support for environment variables --- .../core/config/BuggyConfigurationYML.java | 23 +-- .../buggy/core/config/ConfigurationYML.java | 13 +- .../buggy/core/model/ParallelMode.java | 2 +- .../core/testng/BuggyExecutionListener.java | 9 +- .../buggy/core/testng/BuggyListener.java | 13 +- .../core/testng/ExecutionListenerBase.java | 1 + .../tests/config/JCommanderConfigTests.java | 61 ++++---- .../starter/example/tests/ExampleTests.java | 4 +- .../starter/example/tests/ExampleTests2.java | 18 +-- .../boot/starter/example/tests/WebTests.java | 2 +- .../spring/boot/starter/BuggyRunner.java | 26 +++- .../conf/BuggyRunnerConfiguration.java | 44 +++--- .../boot/starter/conf/IConfiguration.java | 6 +- .../starter/conf/JCommanderConfiguration.java | 68 ++++++--- .../jcommander/BuggyConfiguration.java | 20 +-- .../boot/starter/jcommander/CommandNames.java | 8 +- .../config/EnvironmentUsageFormatter.java | 137 ++++++++++++++++++ .../jcommander/converters/GoalConverter.java | 31 +--- .../converters/ParameterValidator.java | 4 +- .../jcommander/converters/TypeConverter.java | 49 +++++++ .../converters/TypeListConverter.java | 38 +++++ .../spring/boot/starter/util/BeanScanner.java | 48 ++++++ pom.xml | 6 + 23 files changed, 459 insertions(+), 172 deletions(-) create mode 100644 buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/config/EnvironmentUsageFormatter.java create mode 100644 buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/TypeConverter.java create mode 100644 buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/TypeListConverter.java create mode 100644 buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/util/BeanScanner.java 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 index 373e8e3..4b579b8 100644 --- 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 @@ -11,12 +11,9 @@ import org.touchbit.buggy.core.model.Type; import org.touchbit.buggy.core.utils.JUtils; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; +import java.util.*; import static org.touchbit.buggy.core.model.ParallelMode.METHODS; -import static org.touchbit.buggy.core.model.Type.ALL; /** * Configuration class for customizing Buggy. @@ -33,10 +30,10 @@ public final class BuggyConfigurationYML implements ConfigurationYML { private static Integer threads = 50; private static ParallelMode parallelMode = METHODS; private static String artifactsUrl; - private static List components = JUtils.getListWith(AllComponents::new); - private static List services = JUtils.getListWith(AllServices::new); - private static List interfaces = JUtils.getListWith(AllInterfaces::new); - private static List types = JUtils.getListWith(ALL); + 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; @@ -78,19 +75,13 @@ public static void setArtifactsUrl(String artifactsUrl) { BuggyConfigurationYML.artifactsUrl = artifactsUrl; } - public static List getTypes() { + public static Type[] getTypes() { return types; } - public static void setTypes(List types) { - if (types != null) { - BuggyConfigurationYML.types = types; - } - } - public static void setTypes(Type... types) { if (types != null) { - setTypes(Arrays.asList(types)); + BuggyConfigurationYML.types = types; } } 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 index 8c12f1f..3ab1153 100644 --- 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 @@ -1,12 +1,16 @@ 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; @@ -20,15 +24,18 @@ 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); - Yaml yaml = new Yaml(constructor, representer); - InputStream inputStream = JUtils.getCurrentThreadClassLoader().getResourceAsStream(BUGGY_CONFIG_YML); - yaml.load(inputStream); + return new Yaml(constructor, representer); } } 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 index f07053e..8093f23 100644 --- 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 @@ -8,7 +8,7 @@ public enum ParallelMode { METHODS(XmlSuite.ParallelMode.METHODS), CLASSES(XmlSuite.ParallelMode.CLASSES), INSTANCES(XmlSuite.ParallelMode.INSTANCES), - NONE(XmlSuite.ParallelMode.NONE), + OFF(XmlSuite.ParallelMode.NONE), ; private final XmlSuite.ParallelMode testNGMode; 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 index b7c33fc..4b6b7fb 100644 --- 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 @@ -24,10 +24,8 @@ import org.touchbit.buggy.core.model.Type; import java.lang.annotation.Annotation; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.StringJoiner; +import java.lang.reflect.Array; +import java.util.*; /** * Listener for processing executable tests. @@ -222,7 +220,8 @@ public void disableTestsByType(final ISuite suite) { final List methods = suite.getAllMethods(); methods.forEach(method -> { Buggy details = getBuggyAnnotation(method); - List configType = BuggyConfigurationYML.getTypes(); + 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); 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 index 1e94670..5073ce4 100644 --- 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 @@ -8,7 +8,10 @@ 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.*; @@ -69,13 +72,17 @@ default boolean isSkipByType(ITestNGMethod method) { if (buggyAnnotation == null) { return false; } - List types = BuggyConfigurationYML.getTypes(); - if (types.contains(Type.ALL)) { + 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 (types.contains(type)) { + if (configTypes.contains(type)) { contains = true; break; } 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 index 96c2264..75c0315 100644 --- 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 @@ -33,6 +33,7 @@ public void onStart(ISuite suite) { } private void disableTestsByType(ITestNGMethod method) { + System.out.println(" >>>>>>>>>> " + isSkipByType(method)); if (isSkipByType(method)) { method.setInvocationCount(0); } 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 5693700..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 @@ -27,6 +27,7 @@ import java.util.ArrayList; import java.util.List; +import java.util.Set; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; @@ -104,36 +105,36 @@ void unitTest_20180919194007() { // BuggyConfig.setLogPath(log); // } // } - - @Test - @DisplayName("Check PrimaryConfig.setServices(List services)") - void unitTest_20180919194549() { - List services = BuggyConfigurationYML.getServices(); - try { - List newServices = new ArrayList() {{ - 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.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)") 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 index ade3f49..28732a0 100644 --- 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 @@ -9,10 +9,10 @@ import org.touchbit.buggy.spring.boot.starter.example.goal.Actions; import org.touchbit.buggy.spring.boot.starter.example.goal.GitHub; -@Suite(component = GitHub.class, service = Actions.class, interfaze = WEB.class) +@Suite(service = Actions.class, interfaze = WEB.class) public class ExampleTests extends BaseBuggyTest { - @Test(invocationCount = 10) + @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 index eb5622f..c1080e7 100644 --- 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 @@ -7,29 +7,19 @@ 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.spring.boot.starter.example.goal.GitHub; -import java.util.Map; import java.util.UUID; import static org.touchbit.buggy.core.model.Type.SYSTEM; -@Suite(interfaze = API.class) +@Suite(component = GitHub.class, interfaze = API.class) public class ExampleTests2 extends BaseBuggyTest { @Test @Buggy() - public void test1603008938585() throws Exception { - Map env = System.getenv(); - for (String envName : env.keySet()) { - System.out.format("%s=%s%n", - envName, - env.get(envName)); - } - System.out.println(" >>>>>> " + System.getProperty("BUGGY_EXAMPLE")); - System.out.println(" >>>>>> " + System.getProperty("JAVA_BUGGY_EXAMPLE")); - System.out.println(" >>>>>> " + System.getenv("BUGGY_EXAMPLE")); - System.out.println(" >>>>>> " + System.getenv("JAVA_BUGGY_EXAMPLE")); + public void test1603008938585() { + } @Test(description = "Ожидается успешное создание пользователя, если firstName=<пустая строка>") 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 index 345d5ef..e5eb268 100644 --- 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 @@ -8,7 +8,7 @@ import org.touchbit.buggy.spring.boot.starter.example.goal.Actions; import org.touchbit.buggy.spring.boot.starter.example.goal.GitHub; -@Suite(component = GitHub.class, service = Actions.class, interfaze = WEB.class) +@Suite(service = Actions.class, interfaze = WEB.class) public class WebTests extends BaseBuggyTest { @Test 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 index fd51032..05af7d0 100644 --- 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 @@ -69,18 +69,25 @@ public static void exit(int status, String message) { } public static void exit(int status, String message, Exception e) { - if (message != null) { + if (message != null || e != null) { ConfLogger.blockDelimiter(); String frameworkLogPath = ""; if (status == 0) { - ConfLogger.info(message); + if (message != null) { + ConfLogger.info(message); + } } else { File file = FrameworkLogger.getLogFile(); if (file != null) { frameworkLogPath = "\nFor more information see " + file.getName(); } if (e != null) { - message += "\n" + e.getClass().getSimpleName() + ": " + e.getMessage(); + 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); } @@ -93,10 +100,20 @@ public static void exit(int status, String message, Exception e) { @Override public void run(String... args) { - ConfLogger.blockDelimiter(); 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()); @@ -105,6 +122,7 @@ public void run(String... args) { testNG.addListener(enabledBuggyListener); } testNG.setXmlSuites(xmlSuites); + ConfLogger.blockDelimiter(); testNG.run(); SiftingFileAppender.decomposeTestLogs(); if (BuggyConfiguration.getExitStatus() != null) { 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 index d184488..1e19b78 100644 --- 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 @@ -56,19 +56,24 @@ public class BuggyRunnerConfiguration implements IConfiguration { private final Set availableInterfaces; public BuggyRunnerConfiguration(final boolean isLogbackConfigurationInitialized, final ApplicationProperties props) { - 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); + 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) { @@ -82,7 +87,7 @@ public void beforeConfiguration(final boolean isLogbackConfigurationInitialized) @PostConstruct public void printConfigurationInfo() { - ConfLogger.center("TestNG listeners"); + ConfLogger.center("Buggy listeners"); for (BuggyListener buggyListener : allBuggyListeners) { if (buggyListener.isEnable()) { ConfLogger.dotPlaceholder(buggyListener.getClass().getSimpleName(), "Enable"); @@ -90,17 +95,6 @@ public void printConfigurationInfo() { ConfLogger.dotPlaceholder(buggyListener.getClass().getSimpleName(), "Disable"); } } - ConfLogger.stepDelimiter(); - ConfLogger.center("Available suites goals"); - ConfLogger.stepDelimiter(); - ConfLogger.center("Components"); - availableComponents.forEach(g -> ConfLogger.dotPlaceholder(JUtils.getSimpleNameC(g), g.getName())); - ConfLogger.stepDelimiter(); - ConfLogger.center("Services"); - availableServices.forEach(g -> ConfLogger.dotPlaceholder(JUtils.getSimpleNameC(g), g.getName())); - ConfLogger.stepDelimiter(); - ConfLogger.center("Interfaces"); - availableInterfaces.forEach(g -> ConfLogger.dotPlaceholder(JUtils.getSimpleNameC(g), g.getName())); } public Set> filterTestClassesByBuggyConfig(Set> testClassesWithSuiteAnnotation) { 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 index 93903d3..fd07198 100644 --- 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 @@ -61,10 +61,10 @@ default Set> getBeanDefinitionAnnotatedClasses(Set defi Set> result = new LinkedHashSet<>(); for (BeanDefinition bd : definitions) { try { - Class testClass = BeanGenerator.class.getClassLoader().loadClass(bd.getBeanClassName()); - int mods = testClass.getModifiers(); + Class annotatedClass = BeanGenerator.class.getClassLoader().loadClass(bd.getBeanClassName()); + int mods = annotatedClass.getModifiers(); if (isPublic(mods) && !isAbstract(mods) && !isInterface(mods)) { - result.add(testClass); + result.add(annotatedClass); } } catch (ClassNotFoundException e) { BuggyRunner.exit("Could not load class for annotation type: " + tClass.getSimpleName(), e); 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 index dcc194e..d9ca466 100644 --- 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 @@ -1,8 +1,7 @@ package org.touchbit.buggy.spring.boot.starter.conf; -import com.beust.jcommander.JCommander; -import com.beust.jcommander.Parameter; -import com.beust.jcommander.Parameters; +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; @@ -16,6 +15,7 @@ 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; @@ -24,6 +24,9 @@ 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. @@ -38,23 +41,28 @@ public class JCommanderConfiguration implements IConfiguration { private final JCommander jCommander; - private final Set JCommands = new LinkedHashSet<>(); + private final Set jCommands = new LinkedHashSet<>(); private final ApplicationProperties properties; - private final String[] args; private final Map, JCommand> buggyConfigurations = new HashMap<>(); private final boolean isJCommanderConfigured; - public JCommanderConfiguration(final ApplicationProperties properties, final ApplicationArguments args) { - this.properties = properties; - this.args = args.getSourceArgs(); - beforeConfiguration(); - this.JCommands.addAll(scanBuggyConfig()); - scanJCConfigurations().stream() - .filter(i -> !(i instanceof BuggyConfiguration)) - .forEach(this.JCommands::add); - this.jCommander = buildJCommander(); - parseArguments(); - isJCommanderConfigured = true; + 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() { @@ -102,10 +110,11 @@ public Set scanJCConfigurations() { return getBeanDefinitionInstances(defs, JCommand.class); } - private JCommander buildJCommander() { + private JCommander buildJCommander(Set jCommands, Map, JCommand> configMap) { JCommander jCommander = new JCommander(); - for (JCommand config : JCommands) { - buggyConfigurations.put(config.getClass(), config); + jCommander.setUsageFormatter(new EnvironmentUsageFormatter(jCommander)); + for (JCommand config : jCommands) { + configMap.put(config.getClass(), config); checkConfiguration(config); try { if (config.getClass().isAnnotationPresent(Parameters.class) && @@ -123,7 +132,24 @@ private JCommander buildJCommander() { return jCommander; } - public void parseArguments() { + 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(); @@ -188,7 +214,7 @@ public void checkConfiguration(JCommand config) { } public void printConfigurationsParams(Map, JCommand> configs) { - for (JCommand autowiredConfig : JCommands) { + for (JCommand autowiredConfig : jCommands) { JCommand config = configs.get(autowiredConfig.getClass()); printConfigurationParams(config); } 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 index c406dd3..8988d02 100644 --- 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 @@ -9,13 +9,12 @@ 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.InterfaceConverter; -import org.touchbit.buggy.spring.boot.starter.jcommander.converters.ParameterValidator; -import org.touchbit.buggy.spring.boot.starter.jcommander.converters.ServiceConverter; +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.*; @@ -71,11 +70,8 @@ public static void setArtifactsUrl(String artifactsUrl) { BuggyConfigurationYML.setArtifactsUrl(artifactsUrl); } - @Parameter(names = {T, TYPE}, description = "Type of tests to run.", validateWith = ParameterValidator.class) - public static void setTypes(List types) { - BuggyConfigurationYML.setTypes(types); - } - + @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); } @@ -96,7 +92,7 @@ public static void setServices(Class... services) { BuggyConfigurationYML.setServices(services); } - @Parameter(names = {I, INTERFACE}, description = "List of tested interfaces in the format: NAME,NAME,NAME.", + @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); @@ -113,7 +109,7 @@ public static void setInterfaces(Class... interfaces) { } @Parameter(names = {C, COMPONENTS}, description = "List of tested components in the format: NAME,NAME,NAME.", - validateWith = ParameterValidator.class, listConverter = ServiceConverter.class) + validateWith = ParameterValidator.class, listConverter = ComponentConverter.class) public static void setComponents(List components) { BuggyConfigurationYML.setComponents(components); } @@ -147,7 +143,7 @@ public static Boolean isHelp() { return BuggyConfigurationYML.isHelp(); } - @Parameter(names = {TEST_CASE_TITLE}, description = "Print the title of the test case to the console log.") + @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); } @@ -226,7 +222,7 @@ public static String getArtifactsUrl() { return BuggyConfigurationYML.getArtifactsUrl(); } - public static List getTypes() { + public static Type[] getTypes() { return BuggyConfigurationYML.getTypes(); } 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 index 1f43314..fc04bc2 100644 --- 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 @@ -29,13 +29,13 @@ public class CommandNames { public static final String QUESTION_MARK = "-?"; public static final String HELP = "--help"; public static final String C = "-c"; - public static final String COMPONENTS = "--component"; + public static final String COMPONENTS = "--components"; public static final String S = "-s"; - public static final String SERVICES = "--service"; + public static final String SERVICES = "--services"; public static final String I = "-i"; - public static final String INTERFACE = "--interface"; + public static final String INTERFACES = "--interfaces"; public static final String T = "-t"; - public static final String TYPE = "--type"; + 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"; 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-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/GoalConverter.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/GoalConverter.java index d8bf2e4..30afab7 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/GoalConverter.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/GoalConverter.java @@ -18,13 +18,10 @@ import com.beust.jcommander.IStringConverter; 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.goal.Goal; -import org.touchbit.buggy.core.utils.JUtils; +import org.touchbit.buggy.spring.boot.starter.util.BeanScanner; -import java.util.LinkedHashSet; import java.util.Set; /** @@ -41,34 +38,14 @@ public GoalConverter(final Class t) { @Override public T convert(String s) { - Set beanDefinitionInstances = scanBeanDefinitions(tClass); - Set goalClasses = getBeanDefinitionInstances(beanDefinitionInstances, tClass); + Set beanDefinitionInstances = BeanScanner.scanBeanDefinitions(tClass); + Set goalClasses = BeanScanner.getBeanDefinitionInstances(beanDefinitionInstances, tClass); for (T goal : goalClasses) { - if (goal.getClass().getSimpleName().equalsIgnoreCase(s)) { + if (goal.getName().equalsIgnoreCase(s)) { return goal; } } throw new BuggyConfigurationException("No " + tClass.getSimpleName() + " found with name " + s); } - private 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; - } - - private 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/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/ParameterValidator.java b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/ParameterValidator.java index 24b4512..1527386 100644 --- a/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/ParameterValidator.java +++ b/buggy-spring-boot-starter/src/main/java/org/touchbit/buggy/spring/boot/starter/jcommander/converters/ParameterValidator.java @@ -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-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/pom.xml b/pom.xml index d97b9a8..986c0e2 100644 --- a/pom.xml +++ b/pom.xml @@ -160,6 +160,12 @@ 0.3.7 compile + + org.touchbit.buggy + buggy-spring-boot-starter + 0.3.7 + compile + org.touchbit.buggy buggy-feign