diff --git a/CICD/Jenkinsfile b/CICD/Jenkinsfile new file mode 100644 index 00000000..0f3af71e --- /dev/null +++ b/CICD/Jenkinsfile @@ -0,0 +1,41 @@ +env.module = "${JOB_NAME}".split('/')[1] +env.workspace = "mrchecker-framework-modules" +pipeline{ + agent {docker {image 'mrchecker/mrchecker:v1.1.3'}} + stages{ + stage('Build'){ + steps{ + echo "Building module ${env.module} and it's dependency" + sh """ + cd ${env.workspace} + mvn clean compile package install -DskipTests=true --projects ${env.module} --also-make + """ + //bulid this module and its dependencies deploy them to local repo + } + } + stage('Test'){ + steps{ + echo "Testing ${env.module}" + sh """ + cd ${env.workspace} + mvn jacoco:prepare-agent verify -Dgroups=UnitTest,IntegrationTest --projects ${env.module} + """ + } + } + } + post{ + always{ + archiveArtifacts artifacts: "${env.workspace}/${env.module}/target/*.jar", fingerprint: true + jacoco() + junit testResults:'**/surefire-reports/*.xml', healthScaleFactor: 0.8 //as I set the junit treshold to 80% + } + success{ + script{ + def downstreamJob = "${JOB_NAME}".split('/') + downstreamJob[0] = 'test' + downstreamJob = downstreamJob.join('/') + build job: downstreamJob, propagate: false, wait: false + } + } + } +} diff --git a/mrchecker-framework-modules/clirunners/0_0_running_tests.bat b/mrchecker-framework-modules/clirunners/0_0_running_tests.bat new file mode 100644 index 00000000..8fee02d4 --- /dev/null +++ b/mrchecker-framework-modules/clirunners/0_0_running_tests.bat @@ -0,0 +1,4 @@ +running tests +cd .. +mvn clean verify -Dgroups=UnitTests,IntegrationTests + diff --git a/mrchecker-framework-modules/clirunners/0_1_install_to_mvn_local.bat b/mrchecker-framework-modules/clirunners/0_1_install_to_mvn_local.bat new file mode 100644 index 00000000..4272df0f --- /dev/null +++ b/mrchecker-framework-modules/clirunners/0_1_install_to_mvn_local.bat @@ -0,0 +1,4 @@ +running tests +cd .. +mvn clean install -Dgroups=UnitTests,IntegrationTests + diff --git a/mrchecker-framework-modules/clirunners/2_generate_report.bat b/mrchecker-framework-modules/clirunners/2_generate_report.bat new file mode 100644 index 00000000..82d457e0 --- /dev/null +++ b/mrchecker-framework-modules/clirunners/2_generate_report.bat @@ -0,0 +1,3 @@ +echo starting allure server to display report +cd .. +mvn site allure:report \ No newline at end of file diff --git a/mrchecker-framework-modules/clirunners/3_show_report.bat b/mrchecker-framework-modules/clirunners/3_show_report.bat new file mode 100644 index 00000000..53ab3de7 --- /dev/null +++ b/mrchecker-framework-modules/clirunners/3_show_report.bat @@ -0,0 +1,3 @@ +echo launching default web browser to show test report +cd .. +mvn site allure:serve \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-core-module/pom.xml b/mrchecker-framework-modules/mrchecker-core-module/pom.xml index 89151702..e453abf1 100644 --- a/mrchecker-framework-modules/mrchecker-core-module/pom.xml +++ b/mrchecker-framework-modules/mrchecker-core-module/pom.xml @@ -4,15 +4,14 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - mrchecker-test-framework com.capgemini.mrchecker - 2.4.2-SNAPSHOT + 3.0.1-SNAPSHOT mrchecker-core-module - 4.12.1.4-SNAPSHOT + 5.6.2.1-SNAPSHOT jar MrChecker - Test core - Module MrChecker Test Framework Core is responsible for: @@ -25,7 +24,7 @@ * Externalize test environment (DEV, QA, PROD) * Adding analytics source code * Update Observers - Based on Junit4.12 + Based on Junit5 https://github.com/devonfw/devonfw-testing @@ -57,87 +56,21 @@ - - UTF8 - - 4.12 - 1.3 - 1.8.5 - 2.9.9 - 1.1 - 1.0.4 - - - 1 - 2.4 - - 2.2 + 2.13.3 1.7.21 - - - 2.6.0 - - 2.9 - - 1.8.10 - - 4.2.0 5.1.0 3.7.0 - - 20160810 - - - - - org.hamcrest - hamcrest-all - ${hamcrest.version} - test - - - - org.apache.commons - commons-csv - ${commons-csv.version} - - - - - - junit - junit - ${junit.version} - - - pl.pragmatists - JUnitParams - ${JUnitParams.version} - - - - org.junit.platform - junit-platform-surefire-provider - ${surefire.provider.version} - - - org.mockito - mockito-core - ${mockito.version} - - - org.apache.logging.log4j @@ -163,39 +96,32 @@ io.qameta.allure - allure-junit4 - + allure-junit5 + + + io.qameta.allure + allure-java-commons + + + io.qameta.allure + allure-junit-platform io.qameta.allure allure-maven - ${allure-maven-report-generator.version} + org.aspectj aspectjweaver - ${aspectj.version} - - - - com.googlecode.junit-toolbox - junit-toolbox - ${junit-toolbox.version} - org.json json - - - com.google.inject - guice - - org.jasypt jasypt @@ -232,16 +158,10 @@ gherkin ${gherkin.cucumber.version} - - - - - - diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/BaseTest.java b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/BaseTest.java index c196c7be..f869d531 100644 --- a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/BaseTest.java +++ b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/BaseTest.java @@ -1,6 +1,7 @@ package com.capgemini.mrchecker.test.core; -import com.capgemini.mrchecker.test.core.BaseTestWatcher.TestClassRule; +import org.junit.jupiter.api.extension.RegisterExtension; + import com.capgemini.mrchecker.test.core.analytics.AnalyticsProvider; import com.capgemini.mrchecker.test.core.analytics.IAnalytics; import com.capgemini.mrchecker.test.core.base.encryption.DataEncryptionModule; @@ -11,132 +12,76 @@ import com.capgemini.mrchecker.test.core.base.properties.PropertiesSettingsModule; import com.capgemini.mrchecker.test.core.base.runtime.RuntimeParametersCore; import com.capgemini.mrchecker.test.core.logger.BFLogger; -import com.capgemini.mrchecker.test.core.testRunners.ParallelTestClassRunner; import com.google.inject.Guice; -import org.junit.*; -import org.junit.rules.TestWatcher; -import org.junit.runner.RunWith; - -import java.net.MalformedURLException; - -@RunWith(ParallelTestClassRunner.class) -public abstract class BaseTest implements IBaseTest { - - private static IEnvironmentService environmentService; - private final static IAnalytics analytics; - - private final static PropertiesCoreTest setPropertiesSettings; +public abstract class BaseTest { + private static PropertiesCoreTest propertiesCoreTest; + + @RegisterExtension + @SuppressWarnings("unused") + public static final ITestExecutionObserver TEST_EXECUTION_OBSERVER = TestExecutionObserver.getInstance(); + + private static IEnvironmentService environmentService; + private static IAnalytics analytics; + static { - setPropertiesSettings = setPropertiesSettings(); - setRuntimeParametersCore(setPropertiesSettings.getDefaultEnvironmentName()); - setEnvironmetInstance(setPropertiesSettings.isEncryptionEnabled()); - analytics = setAnalytics(setPropertiesSettings.isAnalyticsEnabled()); - } - - public BaseTest() { - getAnalytics().sendClassName(); + setProperties(); + setRuntimeParametersCore(propertiesCoreTest.getDefaultEnvironmentName()); + setEnvironmentInstance(propertiesCoreTest.isEncryptionEnabled()); + setAnalytics(propertiesCoreTest.isAnalyticsEnabled()); } - + public static IEnvironmentService getEnvironmentService() { - return BaseTest.environmentService; - } - - public static IAnalytics getAnalytics() { - return BaseTest.analytics; + return environmentService; } - + public static void setEnvironmentService(IEnvironmentService environmentService) { BaseTest.environmentService = environmentService; } - - @BeforeClass - public static final void setUpClass() throws MalformedURLException { - } - - @AfterClass - public static final void tearDownClass() { - BFLogger.logDebug("BaseTest.tearDownClass()"); - BFLogger.logDebug("BaseTestWatcher.observers: " + BaseTestWatcher.observers.get() - .toString()); - BFLogger.logDebug("TestClassRule.classObservers: " + TestClassRule.classObservers.get() - .toString()); - - // Run observers - TestClassRule.classObservers.get() - .forEach(ITestObserver::onTestClassFinish); - BaseTestWatcher.observers.get() - .forEach(ITestObserver::onTestClassFinish); - - // Clear observers for all tests - BaseTestWatcher.observers.get() - .clear(); - TestClassRule.classObservers.get() - .clear(); - BFLogger.logDebug("All observers cleared."); - - } - - @After - public void tearDownTestLast() { - - } - - @Override - abstract public void setUp(); - - @Override - abstract public void tearDown(); - - // Repacks baseTestWatch to allow Cucumber runner - private BaseTestWatcher baseTestWatcher = new BaseTestWatcher(this); - @Rule - public TestWatcher testWatcher = getBaseTestWatcher(); - - @ClassRule - public static TestClassRule classRule = new TestClassRule(); - - private static void setEnvironmetInstance(boolean isEncryptionEnabled) { - // Environment variables either from environmnets.csv or any other input data. - IEnvironmentService environmentInstance = Guice.createInjector(new EnvironmentModule()) - .getInstance(IEnvironmentService.class); - environmentInstance.setEnvironment(RuntimeParametersCore.ENV.getValue()); - if (isEncryptionEnabled) { - IDataEncryptionService encryptionService = Guice.createInjector(new DataEncryptionModule()) - .getInstance(IDataEncryptionService.class); - environmentInstance.setDataEncryptionService(encryptionService); - } - BaseTest.setEnvironmentService(environmentInstance); + + public static IAnalytics getAnalytics() { + return analytics; } - + private static void setRuntimeParametersCore(String defaultEnvironmentName) { RuntimeParametersCore.ENV.setDefaultValue(defaultEnvironmentName); RuntimeParametersCore.ENV.refreshParameterValue(); - // Read System or maven parameters BFLogger.logDebug(RuntimeParametersCore.ENV.toString()); } - - private static PropertiesCoreTest setPropertiesSettings() { + + private static void setProperties() { /* * For now there is no properties settings file for Core module. In future, please have a look on Selenium * Module PropertiesSelenium propertiesSelenium = Guice.createInjector(PropertiesSettingsModule.init()) * .getInstance(PropertiesSelenium.class); */ - + // Get and then set properties information from settings.properties file - PropertiesCoreTest propertiesCoreTest = Guice.createInjector(PropertiesSettingsModule.init()) + propertiesCoreTest = Guice.createInjector(PropertiesSettingsModule.init()) .getInstance(PropertiesCoreTest.class); - return propertiesCoreTest; } - - private static IAnalytics setAnalytics(Boolean isAnalyticsEnabled) { - BFLogger.logAnalytics("Is analytics enabled:" + isAnalyticsEnabled); - return isAnalyticsEnabled ? AnalyticsProvider.DISABLED : AnalyticsProvider.DISABLED; - + + private static void setEnvironmentInstance(boolean isEncryptionEnabled) { + // Environment variables either from environmnets.csv or any other input data. + IEnvironmentService environmentInstance = Guice.createInjector(new EnvironmentModule()) + .getInstance(IEnvironmentService.class); + environmentInstance.setEnvironment(RuntimeParametersCore.ENV.getValue()); + if (isEncryptionEnabled) { + IDataEncryptionService encryptionService = Guice.createInjector(new DataEncryptionModule()) + .getInstance(IDataEncryptionService.class); + environmentInstance.setDataEncryptionService(encryptionService); + } + setEnvironmentService(environmentInstance); } - - public BaseTestWatcher getBaseTestWatcher() { - return baseTestWatcher; + + private static void setAnalytics(Boolean isAnalyticsEnabled) { + BFLogger.logAnalytics("Is analytics enabled: " + isAnalyticsEnabled); + analytics = isAnalyticsEnabled ? AnalyticsProvider.DISABLED : AnalyticsProvider.DISABLED; } - -} + + public void setUp() { + } + + public void tearDown() { + } +} \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/BaseTestWatcher.java b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/BaseTestWatcher.java deleted file mode 100644 index 01a062e6..00000000 --- a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/BaseTestWatcher.java +++ /dev/null @@ -1,233 +0,0 @@ -package com.capgemini.mrchecker.test.core; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; - -import org.junit.AssumptionViolatedException; -import org.junit.rules.ExternalResource; -import org.junit.rules.TestWatcher; -import org.junit.runner.Description; -import org.junit.runners.model.MultipleFailureException; -import org.junit.runners.model.Statement; - -import com.capgemini.mrchecker.test.core.logger.BFLogger; - -import io.qameta.allure.Attachment; - -public class BaseTestWatcher extends TestWatcher { - private BaseTest baseTest; - private long iStart; - - static final ThreadLocal> observers = new ThreadLocal>() { - @Override - protected List initialValue() { - return new ArrayList(); - } - }; - - public static class TestClassRule extends ExternalResource { - - static final ThreadLocal> classObservers = new ThreadLocal>() { - @Override - protected List initialValue() { - return new ArrayList(); - } - }; - - @Override - protected void after() { - classObservers.get() - .clear(); - } - } - - public BaseTestWatcher(BaseTest baseTest) { - this.baseTest = baseTest; - } - - @Override - public Statement apply(final Statement base, final Description description) { - return new Statement() { - @Override - public void evaluate() throws Throwable { - List errors = new ArrayList(); - - try { - starting(description); - base.evaluate(); - succeeded(description); - } catch (org.junit.internal.AssumptionViolatedException e) { - errors.add(e); - skippedQuietly(e, description, errors); - } catch (Throwable e) { - errors.add(e); - failed(e, description); - } finally { - finished(description); - } - - MultipleFailureException.assertEmpty(errors); - } - }; - } - - @Override - protected void starting(Description description) { - String testName = description.getDisplayName(); - this.startingTestWatcher(testName); - } - - public void startingTestWatcher(String testName) { - BFLogger.RestrictedMethods.startSeparateLog(); // start logging for single test - BFLogger.logInfo("\"" + testName + "\"" + ". STARTED."); - this.iStart = System.currentTimeMillis(); // start timing - BaseTest.getAnalytics() - .sendClassName(); - baseTest.setUp(); // Executed as a Before for each test - } - - @Override - protected void finished(Description description) { - String testName = description.getDisplayName(); - this.finishedTestWatcher(testName); - } - - public void finishedTestWatcher(String testName) { - this.iStart = System.currentTimeMillis() - this.iStart; // end timing - printTimeExecutionLog(testName); - baseTest.tearDown(); // Executed as a After for each test - makeLogForTest(); // Finish logging and add created log as an Allure attachment - observers.get() - .forEach(ITestObserver::onTestFinish); - } - - @Override - protected void succeeded(Description description) { - String testName = description.getDisplayName(); - succeededTestWatcher(testName); - } - - public void succeededTestWatcher(String testName) { - BFLogger.logInfo("\"" + testName + "\"" + ". PASSED."); - // Run test observers - TestClassRule.classObservers.get() - .forEach(ITestObserver::onTestSuccess); - observers.get() - .forEach(ITestObserver::onTestSuccess); - } - - @Override - protected void failed(Throwable e, Description description) { - String testName = description.getDisplayName(); - failedTestWatcher(testName); - } - - public void failedTestWatcher(String testName) { - BFLogger.logInfo("\"" + testName + "\"" + ".FAILED."); - // Run test observers - TestClassRule.classObservers.get() - .forEach(ITestObserver::onTestFailure); - observers.get() - .forEach(ITestObserver::onTestFailure); - } - - @Attachment("Log file") - public String makeLogForTest() { - return BFLogger.RestrictedMethods.dumpSeparateLog(); - } - - public static void addObserver(ITestObserver observer) { - BFLogger.logDebug("To add observer: " + observer.toString()); - - boolean anyMatchTestClassObservers = TestClassRule.classObservers.get() - .stream() - .anyMatch(x -> x.getModuleType() - .equals(observer.getModuleType())); - - boolean anyMatchMethodObservers = observers.get() - .stream() - .anyMatch(x -> x.getModuleType() - .equals(observer.getModuleType())); - - BFLogger.logDebug("BaseTestWatcher.observers: " + BaseTestWatcher.observers.get() - .toString()); - BFLogger.logDebug("TestClassRule.classObservers: " + TestClassRule.classObservers.get() - .toString()); - - if (!(anyMatchMethodObservers | anyMatchTestClassObservers)) { - if (isAddedFromBeforeClassMethod()) { - TestClassRule.classObservers.get() - .add(observer); - } else { - observers.get() - .add(observer); - } - BFLogger.logDebug("Added observer: " + observer.toString()); - - } - - } - - public static void removeObserver(ITestObserver observer) { - BFLogger.logDebug("To remove observer: " + observer.toString()); - - if (isAddedFromBeforeClassMethod()) { - TestClassRule.classObservers.get() - .remove(observer); - BFLogger.logDebug("Removed observer: " + observer.toString()); - } else { - if (!TestClassRule.classObservers.get() - .isEmpty()) { - observers.get() - .remove(observer); - BFLogger.logDebug("Removed observer: " + observer.toString()); - } - } - } - - @SuppressWarnings("deprecation") - private void skippedQuietly(org.junit.internal.AssumptionViolatedException e, Description description, List errors) { - try { - if (e instanceof AssumptionViolatedException) { - skipped((AssumptionViolatedException) e, description); - } else { - skipped(e, description); - } - } catch (Throwable e1) { - errors.add(e1); - } - } - - private static boolean isAddedFromBeforeClassMethod() { - for (StackTraceElement elem : Thread.currentThread() - .getStackTrace()) { - try { - Method method = Class.forName(elem.getClassName()) - .getDeclaredMethod(elem.getMethodName()); - if (method.getDeclaredAnnotation(org.junit.BeforeClass.class) != null) { - // Adding from BeforeClass-annotated method - return true; - } - } catch (SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (ClassNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (NoSuchMethodException e) { - continue; - } - } - return false; - } - - private void printTimeExecutionLog(String testName) { - BFLogger.logInfo("Test: \"" + testName + "\". " + getFormatedTestDuration()); - } - - private String getFormatedTestDuration() { - return String.format(" Duration: %1.2f min", (float) this.iStart / (60 * 1000)); - } - -} diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/IBaseTest.java b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/IBaseTest.java deleted file mode 100644 index 382df94a..00000000 --- a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/IBaseTest.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.capgemini.mrchecker.test.core; - -public interface IBaseTest { - - public void tearDown(); - - public void setUp(); -} diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/ITestExecutionObserver.java b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/ITestExecutionObserver.java new file mode 100644 index 00000000..271c086b --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/ITestExecutionObserver.java @@ -0,0 +1,15 @@ +package com.capgemini.mrchecker.test.core; + +import org.junit.jupiter.api.extension.AfterAllCallback; +import org.junit.jupiter.api.extension.AfterTestExecutionCallback; +import org.junit.jupiter.api.extension.BeforeAllCallback; +import org.junit.jupiter.api.extension.BeforeTestExecutionCallback; +import org.junit.jupiter.api.extension.LifecycleMethodExecutionExceptionHandler; +import org.junit.jupiter.api.extension.TestExecutionExceptionHandler; +import org.junit.jupiter.api.extension.TestWatcher; + +public interface ITestExecutionObserver + extends BeforeAllCallback, BeforeTestExecutionCallback, AfterTestExecutionCallback, TestWatcher, AfterAllCallback, LifecycleMethodExecutionExceptionHandler, TestExecutionExceptionHandler, + ITestObservable { + // aggregating interface +} diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/ITestObservable.java b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/ITestObservable.java new file mode 100644 index 00000000..a5fcd8f3 --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/ITestObservable.java @@ -0,0 +1,7 @@ +package com.capgemini.mrchecker.test.core; + +public interface ITestObservable { + void addObserver(ITestObserver testObserver); + + void removeObserver(ITestObserver testObserver); +} diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/ITestObserver.java b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/ITestObserver.java index 88bb0b70..672664f4 100644 --- a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/ITestObserver.java +++ b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/ITestObserver.java @@ -1,15 +1,15 @@ package com.capgemini.mrchecker.test.core; public interface ITestObserver { - public void onTestSuccess(); + void onTestSuccess(); - public void onTestFailure(); + void onTestFailure(); - public void onTestFinish(); + void onTestFinish(); - public void onTestClassFinish(); + void onTestClassFinish(); - public void addObserver(); + void addToTestExecutionObserver(); - public ModuleType getModuleType(); + ModuleType getModuleType(); } diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/ModuleType.java b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/ModuleType.java index 4b4cd700..3a8a20de 100644 --- a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/ModuleType.java +++ b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/ModuleType.java @@ -1,6 +1,7 @@ package com.capgemini.mrchecker.test.core; public enum ModuleType { + CORE, SELENIUM, WEBAPI, DATABASE, diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/Page.java b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/Page.java new file mode 100644 index 00000000..ade965be --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/Page.java @@ -0,0 +1,42 @@ +package com.capgemini.mrchecker.test.core; + +import com.capgemini.mrchecker.test.core.logger.BFLogger; + +public abstract class Page implements ITestObserver { + + protected static final ITestExecutionObserver TEST_EXECUTION_OBSERVER = TestExecutionObserver.getInstance(); + + protected Page() { + } + + @Override + public void onTestSuccess() { + BFLogger.logDebug("Page.onTestSuccess " + getClass() + .getSimpleName()); + } + + @Override + public void onTestFailure() { + BFLogger.logDebug("Page.onTestFailure " + getClass() + .getSimpleName()); + } + + @Override + public void onTestFinish() { + BFLogger.logDebug("Page.onTestFinish " + getClass() + .getSimpleName()); + + TEST_EXECUTION_OBSERVER.removeObserver(this); + } + + @Override + public void onTestClassFinish() { + BFLogger.logDebug("Page.onTestClassFinish " + getClass() + .getSimpleName()); + } + + @Override + public final void addToTestExecutionObserver() { + TEST_EXECUTION_OBSERVER.addObserver(this); + } +} diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/TestExecutionObserver.java b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/TestExecutionObserver.java new file mode 100644 index 00000000..2c90cc37 --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/TestExecutionObserver.java @@ -0,0 +1,250 @@ +package com.capgemini.mrchecker.test.core; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.function.Consumer; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.extension.ExtensionContext; + +import com.capgemini.mrchecker.test.core.logger.BFLogger; +import com.capgemini.mrchecker.test.core.utils.Attachments; + +public class TestExecutionObserver implements ITestExecutionObserver { + + private static TestExecutionObserver instance = new TestExecutionObserver(); + + private final ThreadLocal stopwatch = ThreadLocal.withInitial(() -> 0L); + + private final ThreadLocal> observers = ThreadLocal.withInitial(ArrayList::new); + private final ThreadLocal> classObservers = ThreadLocal.withInitial(ArrayList::new); + + public static final boolean DONT_CONSUME_EXCEPTION_IN_AFTERALL = false; + + private TestExecutionObserver() { + } + + public static TestExecutionObserver getInstance() { + return instance; + } + + @Override + public void beforeAll(ExtensionContext extensionContext) { + String testName = extensionContext.getRequiredTestClass() + .getName(); + BFLogger.logInfo("\"" + testName + "\"" + " - CLASS STARTED."); + } + + @Override + public void beforeTestExecution(ExtensionContext context) { + BFLogger.RestrictedMethods.startSeparateLog(); + logTestInfo(context, "STARTED"); + BaseTest.getAnalytics() + .sendClassName(); + stopwatch.set(System.currentTimeMillis()); + validateTestClassAndCallHook(context, BaseTest::setUp); + } + + @Override + public void afterTestExecution(ExtensionContext context) { + stopwatch.set(System.currentTimeMillis() - stopwatch.get()); // end timing + String testName = logTestInfo(context, "FINISHED"); + printTimeExecutionLog(testName); + validateTestClassAndCallHook(context, BaseTest::tearDown); + } + + private static void makeLogForTest() { + Attachments.attachToAllure(BFLogger.RestrictedMethods.dumpSeparateLog()); + } + + @Override + public void testDisabled(ExtensionContext context, Optional reason) { + logTestInfo(context, "DISABLED"); + reason.ifPresent(s -> BFLogger.logInfo("Reason: " + s)); + } + + @Override + public void testAborted(ExtensionContext context, Throwable cause) { + logTestInfo(context, "ABORTED"); + afterEach(); + } + + @Override + public void testSuccessful(ExtensionContext context) { + logTestInfo(context, "PASSED"); + observers.get() + .forEach(ITestObserver::onTestSuccess); + classObservers.get() + .forEach(ITestObserver::onTestSuccess); + afterEach(); + } + + @Override + public void testFailed(ExtensionContext context, Throwable cause) { + logTestInfo(context, "FAILED"); + observers.get() + .forEach(ITestObserver::onTestFailure); + classObservers.get() + .forEach(ITestObserver::onTestFailure); + afterEach(); + } + + private static String logTestInfo(ExtensionContext context, String testStatus) { + String className = context.getRequiredTestClass() + .getName(); + String testName = context.getDisplayName(); + BFLogger.logInfo("\"" + className + "#" + testName + "\"" + " - " + testStatus + "."); + return testName; + } + + private void afterEach() { + observers.get() + .forEach(ITestObserver::onTestFinish); + makeLogForTest(); + } + + private static void validateTestClassAndCallHook(ExtensionContext context, Consumer hook) { + Object testClass = context.getRequiredTestInstance(); + if (testClass instanceof BaseTest) { + hook.accept((BaseTest) testClass); + } + } + + @Override + public void afterAll(ExtensionContext extensionContext) { + BFLogger.logDebug(getClass().getName() + ".observers: " + observers.get() + .toString()); + + BFLogger.logDebug(getClass().getName() + ".classObservers: " + classObservers.get() + .toString()); + + observers.get() + .forEach(ITestObserver::onTestClassFinish); + classObservers.get() + .forEach(ITestObserver::onTestClassFinish); + + observers.get() + .clear(); + classObservers.get() + .clear(); + + BFLogger.logDebug("All observers cleared."); + } + + private void printTimeExecutionLog(String testName) { + BFLogger.logInfo("\"" + testName + "\"" + getFormattedTestDuration()); + } + + private String getFormattedTestDuration() { + return String.format(" - DURATION: %1.2f min", (float) stopwatch.get() / (60 * 1000)); + } + + @Override + public void handleBeforeAllMethodExecutionException(ExtensionContext context, Throwable throwable) throws Throwable { + logExceptionInfo(context, throwable, "@BeforeAll"); + } + + @Override + public void handleBeforeEachMethodExecutionException(ExtensionContext context, Throwable throwable) throws Throwable { + logExceptionInfo(context, throwable, "@BeforeEach"); + } + + @Override + public void handleTestExecutionException(ExtensionContext context, Throwable throwable) throws Throwable { + logExceptionInfo(context, throwable, "@Test"); + } + + @Override + public void handleAfterEachMethodExecutionException(ExtensionContext context, Throwable throwable) throws Throwable { + logExceptionInfo(context, throwable, "@AfterEach"); + } + + @Override + public void handleAfterAllMethodExecutionException(ExtensionContext context, Throwable throwable) throws Throwable { + try { + logExceptionInfo(context, throwable, "@AfterAll"); + } catch (Throwable e) { + if (DONT_CONSUME_EXCEPTION_IN_AFTERALL) + throw throwable; + } + } + + private void logExceptionInfo(ExtensionContext context, Throwable throwable, String annotationName) throws Throwable { + String className = context.getRequiredTestClass() + .getName(); + String testName = context.getDisplayName(); + BFLogger.logError("\"" + className + "#" + testName + "\"" + " - EXCEPTION in " + annotationName + ": " + throwable.getMessage()); + throw throwable; + } + + @Override + public void addObserver(ITestObserver observer) { + BFLogger.logDebug("To add observer: " + observer.toString()); + + boolean anyMatchTestClassObservers = isObserverAlreadyAdded(classObservers.get(), observer); + boolean anyMatchMethodObservers = isObserverAlreadyAdded(observers.get(), observer); + + BFLogger.logDebug(getClass().getName() + ".observers: " + observers.get() + .toString()); + BFLogger.logDebug(getClass().getName() + ".classObservers: " + classObservers.get() + .toString()); + + if (!(anyMatchMethodObservers | anyMatchTestClassObservers)) { + if (isAddedFromBeforeAllMethod()) { + classObservers.get() + .add(observer); + } else { + observers.get() + .add(observer); + } + BFLogger.logDebug("Added observer: " + observer.toString()); + } + } + + private boolean isObserverAlreadyAdded(List observers, ITestObserver observer) { + return observers.stream() + .anyMatch(x -> x.getModuleType() + .equals(observer.getModuleType())); + } + + private static boolean isAddedFromBeforeAllMethod() { + for (StackTraceElement elem : Thread.currentThread() + .getStackTrace()) { + try { + Method method = Class.forName(elem.getClassName()) + .getDeclaredMethod(elem.getMethodName()); + if (method.getDeclaredAnnotation(BeforeAll.class) != null) { + return true; + } + } catch (SecurityException | ClassNotFoundException e) { + BFLogger.logDebug(e.getMessage()); + } catch (NoSuchMethodException e) { + // do nothing + } + } + + return false; + } + + @Override + public void removeObserver(ITestObserver observer) { + BFLogger.logDebug("To remove observer: " + observer.toString()); + + if (classObservers.get() + .contains(observer)) { + classObservers.get() + .remove(observer); + BFLogger.logDebug("Removed observer: " + observer.toString()); + } else { + // There must be at least one observer when finishing class + if (!classObservers.get() + .isEmpty()) { + observers.get() + .remove(observer); + BFLogger.logDebug("Removed observer: " + observer.toString()); + } + } + } +} \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/analytics/AnalyticsProvider.java b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/analytics/AnalyticsProvider.java index 6f8c6ecf..3f550122 100644 --- a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/analytics/AnalyticsProvider.java +++ b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/analytics/AnalyticsProvider.java @@ -1,32 +1,14 @@ package com.capgemini.mrchecker.test.core.analytics; -/** - * This class stores various system properties - * - * @author LUSTEFAN - */ public enum AnalyticsProvider implements IAnalytics { DISABLED() { - @Override - public void sendClassName(String url, String title, String description) { - // Enable for future enhancements around Analitycs - // BFLogger.logAnalytics("Analytics disabled. Dry run sendClassName()"); - } - - @Override - public void sendMethodEvent(String analitycsCategoryName, String eventName) { - // Enable for future enhancements around Analitycs - // BFLogger.logAnalytics("Analytics disabled. Dry run sendMethodEvent()"); - } - @Override public void setInstance() { } }; - private AnalyticsProvider() { + AnalyticsProvider() { setInstance(); } - } diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/analytics/IAnalytics.java b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/analytics/IAnalytics.java index 1d741850..14001e6a 100644 --- a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/analytics/IAnalytics.java +++ b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/analytics/IAnalytics.java @@ -2,27 +2,27 @@ public interface IAnalytics { - public default void sendClassName(String packageName, String className, String description) { - }; + @SuppressWarnings("unused") + default void sendClassName(String packageName, String className, String description) { + } - public default void sendClassName() { + default void sendClassName() { String packageName = Thread.currentThread() .getStackTrace()[2].getClassName(); String className = Thread.currentThread() .getStackTrace()[2].getMethodName(); sendClassName(packageName, className, ""); - - }; + } - public default void sendMethodEvent(String analitycsCategoryName, String eventName) { - }; + @SuppressWarnings("unused") + default void sendMethodEvent(String analyticsCategoryName, String eventName) { + } - public default void sendMethodEvent(String analitycsCategoryName) { + default void sendMethodEvent(String analyticsCategoryName) { String eventName = Thread.currentThread() .getStackTrace()[2].getMethodName(); - sendMethodEvent(analitycsCategoryName, eventName); + sendMethodEvent(analyticsCategoryName, eventName); } void setInstance(); - } diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/base/encryption/DataEncryptionModule.java b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/base/encryption/DataEncryptionModule.java index eab03006..760bfbdf 100644 --- a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/base/encryption/DataEncryptionModule.java +++ b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/base/encryption/DataEncryptionModule.java @@ -1,15 +1,30 @@ package com.capgemini.mrchecker.test.core.base.encryption; -import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; import java.nio.file.Paths; import com.capgemini.mrchecker.test.core.base.encryption.providers.DataEncryptionService; +import com.capgemini.mrchecker.test.core.exceptions.BFSecureModuleException; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.google.inject.Singleton; public class DataEncryptionModule extends AbstractModule { + private static final String DEFAULT_SECRET_DATA_FILE = "/src/resources/secretData"; + private final String secretFilePath; + + public DataEncryptionModule(String secretFilePath) { + this.secretFilePath = secretFilePath; + } + + public DataEncryptionModule() { + this(DEFAULT_SECRET_DATA_FILE); + } + @Override protected void configure() { @@ -17,10 +32,17 @@ protected void configure() { @Provides @Singleton + @SuppressWarnings("unused") IDataEncryptionService provideSpreadsheetEnvironmentService() { - String path = System.getProperty("user.dir") + Paths.get("/src/resources/secretData"); - DataEncryptionService.init(new File(path)); + String path = System.getProperty("user.dir") + Paths.get(secretFilePath); + try (InputStream secretSource = new FileInputStream(path)) { + DataEncryptionService.init(secretSource); + } catch (FileNotFoundException e) { + throw new BFSecureModuleException("File with secret not found: " + path); + } catch (IOException e) { + throw new BFSecureModuleException("File with secret processing exception: " + path); + } + return DataEncryptionService.getInstance(); } - } diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/base/encryption/IDataEncryptionService.java b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/base/encryption/IDataEncryptionService.java index 782e3ed1..dc303c26 100644 --- a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/base/encryption/IDataEncryptionService.java +++ b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/base/encryption/IDataEncryptionService.java @@ -19,10 +19,10 @@ public interface IDataEncryptionService { * its own decorators (prefix and/or suffix) to be added this way. * * @param text - * Text to be encrypted. + * Text to be encrypted. * @return encrypted and decorated text as string * @throws BFSecureModuleException - * in case of encryption problems. + * in case of encryption problems. */ String encrypt(String text) throws BFSecureModuleException; @@ -33,16 +33,16 @@ public interface IDataEncryptionService { * cipher text. * * @param text - * decorated cipher text. + * decorated cipher text. * @return decrypted text as string. * @throws BFSecureModuleException - * in case of decryption problems. + * in case of decryption problems. */ String decrypt(String text) throws BFSecureModuleException; /** * @param text - * plain text or cipher text. + * plain text or cipher text. * @return true, if the text is encrypted (is cipher text). This means only, that the text * is decorated with a prefix and/or suffix the service defines. false otherwise. */ @@ -58,12 +58,12 @@ public interface IDataEncryptionService { * pass over to this method like e.g. the minimal accepted length of the secret. * * @param secret - * secret to be used for data encryption/decryption. NOTE: "password1" is a bad - * secret. Something like "IM%&@N8932m>|j9123nG&kyYWB" is. + * secret to be used for data encryption/decryption. NOTE: "password1" is a bad + * secret. Something like "IM%&@N8932m>|j9123nG&kyYWB" is. * @throws BFSecureModuleException - * error setting the secret value (usually quality - * rules are not fulfilled. + * error setting the secret value (usually quality + * rules are not fulfilled. */ - public void setSecret(String secret) throws BFSecureModuleException; + void setSecret(String secret) throws BFSecureModuleException; } diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/base/encryption/providers/DataEncryptionService.java b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/base/encryption/providers/DataEncryptionService.java index 02c05025..91ccdb4d 100644 --- a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/base/encryption/providers/DataEncryptionService.java +++ b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/base/encryption/providers/DataEncryptionService.java @@ -1,7 +1,7 @@ package com.capgemini.mrchecker.test.core.base.encryption.providers; -import java.io.File; -import java.io.FileNotFoundException; +import java.io.InputStream; +import java.util.Objects; import java.util.Scanner; import org.jasypt.encryption.pbe.StandardPBEStringEncryptor; @@ -9,7 +9,6 @@ import com.capgemini.mrchecker.test.core.base.encryption.IDataEncryptionService; import com.capgemini.mrchecker.test.core.exceptions.BFSecureModuleException; -import com.google.common.base.Preconditions; /** * Basic data encryption service to encapsulate and isolate the encryption/decryption logic. @@ -19,12 +18,12 @@ */ public class DataEncryptionService implements IDataEncryptionService { + public static final int SECRET_MIN_LENGTH = 8; private static IDataEncryptionService instance; - private StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor(); + private StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor(); - private DataEncryptionService(File path) { - Preconditions.checkNotNull(path); - setSecret(readSecret(path)); + private DataEncryptionService(InputStream secretSource) { + setSecret(readSecret(secretSource)); } /** @@ -33,19 +32,18 @@ private DataEncryptionService(File path) { * the secret in a file that is not checked into your repository, and is passed * among your team members over a different channel. * - * @param path - * path to the file with the secret (only first line is relevant). - * @return Class instance. + * @param secretSource + * A stream input for a secret */ - public static IDataEncryptionService init(File path) { - if (instance == null) { + + public static void init(InputStream secretSource) { + if (Objects.isNull(instance)) { synchronized (DataEncryptionService.class) { - if (instance == null) { - instance = new DataEncryptionService(path); + if (Objects.isNull(instance)) { + instance = new DataEncryptionService(secretSource); } } } - return instance; } public static IDataEncryptionService getInstance() { @@ -56,29 +54,23 @@ public static void delInstance() { DataEncryptionService.instance = null; } - private String readSecret(File secretFile) { - try (Scanner scanner = new Scanner(secretFile)) { - return readLine(scanner, secretFile).trim(); - } catch (FileNotFoundException e) { - throw new BFSecureModuleException("File does not exist: " + secretFile); + private String readSecret(InputStream secretSource) { + try (Scanner scanner = new Scanner(secretSource)) { + return readLine(scanner, secretSource).trim(); } } - private String readLine(Scanner scanner, File secretFile) { + private String readLine(Scanner scanner, InputStream secretSource) { if (scanner.hasNext()) { return scanner.next(); } else { - throw new BFSecureModuleException("File is empty: " + secretFile); + throw new BFSecureModuleException("Secret source is empty: " + secretSource); } } @Override public String encrypt(String text) { - try { - return PropertyValueEncryptionUtils.encrypt(text, encryptor); - } catch (Throwable t) { - throw new BFSecureModuleException(t.getMessage(), t); - } + return PropertyValueEncryptionUtils.encrypt(text, encryptor); } @Override @@ -86,38 +78,39 @@ public String decrypt(String text) { if (!isEncrypted(text)) { throw new BFSecureModuleException("Text is not encrypted: " + text); } - try { - return PropertyValueEncryptionUtils.decrypt(text, encryptor); - } catch (Throwable t) { - throw new BFSecureModuleException(t.getMessage(), t); - } + + return PropertyValueEncryptionUtils.decrypt(text, encryptor); } @Override public void setSecret(String secret) { - if (secret == null) { - throw new BFSecureModuleException("Secret must not be null"); + if (Objects.isNull(secret)) { + throw new BFSecureModuleException("Secret must not be NULL"); } + if (!secret.trim() - .equals(secret)) { + .equals(secret)) { throw new BFSecureModuleException("Secret contains whitespaces which are trimable. " - + "This can cause problems when using command line tools for encryption, due which is not allowed."); + + "This can cause problems when using command line tools for encryption, due which is not allowed."); } - if (secret.length() < 8) { - throw new BFSecureModuleException("Secrets must not be shorter than 8 characters"); + + if (secret.length() < SECRET_MIN_LENGTH) { + throw new BFSecureModuleException("Secrets must not be shorter than " + SECRET_MIN_LENGTH + " characters"); } if (encryptor.isInitialized()) { encryptor = new StandardPBEStringEncryptor(); } + encryptor.setPassword(secret); } @Override public boolean isEncrypted(String text) { - if (text == null) { + if (Objects.isNull(text)) { return false; } + return PropertyValueEncryptionUtils.isEncryptedValue(text); } } diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/base/environment/EnvironmentModule.java b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/base/environment/EnvironmentModule.java index a786d9be..e183d6dd 100644 --- a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/base/environment/EnvironmentModule.java +++ b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/base/environment/EnvironmentModule.java @@ -1,24 +1,46 @@ package com.capgemini.mrchecker.test.core.base.environment; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; + import com.capgemini.mrchecker.test.core.base.environment.providers.SpreadsheetEnvironmentService; import com.capgemini.mrchecker.test.core.base.runtime.RuntimeParametersCore; +import com.capgemini.mrchecker.test.core.exceptions.BFInputDataException; import com.google.inject.AbstractModule; import com.google.inject.Provides; -import java.nio.file.Paths; - public class EnvironmentModule extends AbstractModule { - + + private static final String DEFAULT_ENV_PARAMS_FILE = "/src/resources/enviroments/environments.csv"; + private final String envParamsFilePath; + + public EnvironmentModule(String envParamsFilePath) { + this.envParamsFilePath = envParamsFilePath; + } + + public EnvironmentModule() { + this(DEFAULT_ENV_PARAMS_FILE); + } + @Override protected void configure() { - + } - + @Provides + @SuppressWarnings("unused") IEnvironmentService provideSpreadsheetEnvironmentService() { - String path = System.getProperty("user.dir") + Paths.get("/src/resources/enviroments/environments.csv"); String environment = RuntimeParametersCore.ENV.getValue(); - SpreadsheetEnvironmentService.init(path, environment); + String path = System.getProperty("user.dir") + Paths.get(envParamsFilePath); + String csvData; + try { + csvData = new String(Files.readAllBytes(Paths.get(path))); + } catch (IOException e) { + throw new BFInputDataException("Spreadsheet file could not be processed: " + path); + } + + SpreadsheetEnvironmentService.init(csvData, environment); return SpreadsheetEnvironmentService.getInstance(); } } \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/base/environment/GetEnvironmentParam.java b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/base/environment/GetEnvironmentParam.java deleted file mode 100644 index 21b235c0..00000000 --- a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/base/environment/GetEnvironmentParam.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.capgemini.mrchecker.test.core.base.environment; - -import com.capgemini.mrchecker.test.core.BaseTest; -import com.capgemini.mrchecker.test.core.exceptions.BFInputDataException; - -enum GetEnvironmentParam { - WWW_FONT_URL, - SPS_WI_URL, - TOOLS_QA, - WEB_SERVICE, - HEROKUAPP; - - IEnvironmentService environmentService = BaseTest.getEnvironmentService(); - - public String getValue() { - - if (null == environmentService) { - throw new BFInputDataException("Environment Parameters class wasn't initialized properly"); - } - return environmentService - .getValue(this.name()); - - } - - public static void refreshAll() { - for (GetEnvironmentParam e : values()) { - e.environmentService = BaseTest.getEnvironmentService(); - } - } - -} diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/base/environment/IEnvironmentService.java b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/base/environment/IEnvironmentService.java index 503460da..687636d1 100644 --- a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/base/environment/IEnvironmentService.java +++ b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/base/environment/IEnvironmentService.java @@ -1,5 +1,6 @@ package com.capgemini.mrchecker.test.core.base.environment; + import com.capgemini.mrchecker.test.core.base.encryption.IDataEncryptionService; /** @@ -17,9 +18,7 @@ public interface IEnvironmentService { public void setEnvironment(String environmentName); /** - * Sets environment (e.g. "QC1") - * - * @param environmentName + * Gets environment (e.g. "QC1") */ public String getEnvironment(); @@ -29,14 +28,9 @@ public interface IEnvironmentService { */ public String getValue(String serviceName); - /** - * @return source from Environment variables are taken. This could be file path - */ - public String dataSource(); - /** * @param service - * Optional encryption service to deal with encrypted test data. + * Optional encryption service to deal with encrypted test data. */ public void setDataEncryptionService(IDataEncryptionService service); diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/base/environment/providers/SpreadsheetEnvironmentService.java b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/base/environment/providers/SpreadsheetEnvironmentService.java index 78e137b8..2c04c5e1 100644 --- a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/base/environment/providers/SpreadsheetEnvironmentService.java +++ b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/base/environment/providers/SpreadsheetEnvironmentService.java @@ -1,137 +1,133 @@ package com.capgemini.mrchecker.test.core.base.environment.providers; +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +import org.apache.commons.csv.CSVFormat; +import org.apache.commons.csv.CSVParser; +import org.apache.commons.csv.CSVRecord; + import com.capgemini.mrchecker.test.core.base.encryption.IDataEncryptionService; import com.capgemini.mrchecker.test.core.base.environment.IEnvironmentService; import com.capgemini.mrchecker.test.core.base.runtime.RuntimeParametersCore; import com.capgemini.mrchecker.test.core.exceptions.BFInputDataException; import com.capgemini.mrchecker.test.core.logger.BFLogger; import com.google.inject.Singleton; -import org.apache.commons.csv.CSVFormat; -import org.apache.commons.csv.CSVParser; -import org.apache.commons.csv.CSVRecord; - -import java.io.File; -import java.io.IOException; -import java.nio.charset.Charset; -import java.util.*; /** * This class is responsible for handling addresses of services. Addresses depends on currently set Environment. It is * possible to change environment before run adding -DenvURL parameter. Default Environment is set to DEV1 * - * @author + * @author LUKSTEF + * @author MBABIARZ */ @Singleton public class SpreadsheetEnvironmentService implements IEnvironmentService { - + private static IEnvironmentService instance; - - private List records; - private Map services; - private Optional encryptionService = Optional.empty(); - private String path; - private String environmentName; - - private SpreadsheetEnvironmentService(String path, String environmentName) { - this.path = path; - fetchEnvData(path); + + private List records; + private final Map services = new HashMap<>(); + private Optional encryptionService = Optional.empty(); + private String environmentName; + private int envColumnNumber; + + private SpreadsheetEnvironmentService(String csvData, String environmentName) { + fetchEnvData(csvData); setEnvironment(environmentName); - BFLogger.logDebug("Reading environment from: " + path); - } - - public static IEnvironmentService init() { - String path = SpreadsheetEnvironmentService.class.getResource("") - .getPath() + "/environments/environments.csv"; - String environment = RuntimeParametersCore.ENV.getValue(); - return init(path, environment); } - - public static IEnvironmentService init(String path, String environment) { - if (instance == null) { + + public static void init(String csvData, String environment) { + if (Objects.isNull(instance)) { synchronized (SpreadsheetEnvironmentService.class) { - if (instance == null) { - instance = new SpreadsheetEnvironmentService(path, environment); + if (Objects.isNull(instance)) { + instance = new SpreadsheetEnvironmentService(csvData, environment); } } } - return instance; } - + public static IEnvironmentService getInstance() { return SpreadsheetEnvironmentService.instance; } - + public static void delInstance() { SpreadsheetEnvironmentService.instance = null; RuntimeParametersCore.ENV.refreshParameterValue(); } - + /** * Sets environment (e.g. "QC1") * * @param environmentName + * env to be set */ public void setEnvironment(String environmentName) { this.environmentName = environmentName; - updateServicesMapBasedOn(environmentName); + envColumnNumber = getEnvironmentColumnNumber(this.environmentName); + updateServicesMapBasedOn(); } - + @Override public String getEnvironment() { - return this.environmentName; + return environmentName; } - + /** * @param serviceName + * A name of an option to get * @return value of service for current environment */ public String getValue(String serviceName) { String value = services.get(serviceName); - if (value == null) { + if (Objects.isNull(value)) { throw new BFInputDataException("service " + serviceName + " " + "retrieve address of" + " " + "not found in available services table"); } + return value; } - - private void fetchEnvData(String path) throws BFInputDataException { - File csvData = new File(path); + + private void fetchEnvData(String csvData) throws BFInputDataException { try { - CSVParser parser = CSVParser.parse(csvData, Charset.defaultCharset(), CSVFormat.RFC4180.withIgnoreSurroundingSpaces()); + CSVParser parser = CSVParser.parse(csvData, CSVFormat.RFC4180.withIgnoreSurroundingSpaces()); records = parser.getRecords(); } catch (IOException e) { - throw new BFInputDataException("Unable to parse CSV: " + path); + throw new BFInputDataException("Unable to parse CSV data: " + csvData); } } - - private void updateServicesMapBasedOn(String environmentName) { - services = new HashMap(); - - int environmentNumber = getEnvironmentNumber(environmentName); - + + private void updateServicesMapBasedOn() { + services.clear(); + Iterator it = records.iterator(); it.next(); // first row contains table headers, so skip it while (it.hasNext()) { CSVRecord record = it.next(); String key = record.get(0); - String value = record.get(environmentNumber) + String value = record.get(envColumnNumber) .trim(); value = optionalDecrypt(value); services.put(key, value); } } - + private String optionalDecrypt(String value) { if (encryptionService.isPresent() && encryptionService.get() .isEncrypted(value)) { - return encryptionService.get() + value = encryptionService.get() .decrypt(value); - } else { - return value; } + + return value; } - - private int getEnvironmentNumber(String environmentName) throws BFInputDataException { + + private int getEnvironmentColumnNumber(String environmentName) throws BFInputDataException { CSVRecord header = records.get(0); for (int environmentNumber = 0; environmentNumber < header.size(); environmentNumber++) { String environment = header.get(environmentNumber); @@ -140,18 +136,13 @@ private int getEnvironmentNumber(String environmentName) throws BFInputDataExcep return environmentNumber; } } + throw new BFInputDataException("There is no Environment with name '" + environmentName + "' available"); } - - @Override - public String dataSource() { - return this.path; - } - + @Override - public void setDataEncryptionService(IDataEncryptionService service) { - this.encryptionService = Optional.ofNullable(service); - setEnvironment(getEnvironment()); // enforce value update + public void setDataEncryptionService(IDataEncryptionService dataEncryptionService) { + encryptionService = Optional.ofNullable(dataEncryptionService); + updateServicesMapBasedOn(); } - } diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/base/properties/PropertiesCoreTest.java b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/base/properties/PropertiesCoreTest.java index d2717c5b..31e40aa5 100644 --- a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/base/properties/PropertiesCoreTest.java +++ b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/base/properties/PropertiesCoreTest.java @@ -4,35 +4,39 @@ import com.google.inject.name.Named; public class PropertiesCoreTest { - private String coreDefaultEnvironmentName = "DEV"; - private boolean coreIsAnalyticsEnabled = true; - private boolean coreIsEncryptionEnabled = false; - + + private String coreDefaultEnvironmentName = "DEV"; + private boolean coreIsAnalyticsEnabled = true; + private boolean coreIsEncryptionEnabled = false; + @Inject(optional = true) + @SuppressWarnings("unused") private void setIsAnalyticsEnabled(@Named("core.isAnalyticsEnabled") String status) { - this.coreIsAnalyticsEnabled = status.toLowerCase() - .equals("false") ? false : true; + this.coreIsAnalyticsEnabled = !status.toLowerCase() + .equals("false"); } - + @Inject(optional = true) + @SuppressWarnings("unused") private void setIsEncryptionEnabled(@Named("core.isEncryptionEnabled") String status) { this.coreIsEncryptionEnabled = status.toLowerCase() - .equals("true") ? true : false; + .equals("true"); } - + @Inject(optional = true) - private void setDefaultEnvironmentName(@Named("core.defaultEnvironmentName") String status) { - this.coreDefaultEnvironmentName = status; + @SuppressWarnings("unused") + private void setDefaultEnvironmentName(@Named("core.defaultEnvironmentName") String coreDefaultEnvironmentName) { + this.coreDefaultEnvironmentName = coreDefaultEnvironmentName; } - + public boolean isAnalyticsEnabled() { - return this.coreIsAnalyticsEnabled; + return coreIsAnalyticsEnabled; } - + public boolean isEncryptionEnabled() { return coreIsEncryptionEnabled; } - + public String getDefaultEnvironmentName() { return coreDefaultEnvironmentName; } diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/base/properties/PropertiesSettingsModule.java b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/base/properties/PropertiesSettingsModule.java index 5147cb4c..8825fb6b 100644 --- a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/base/properties/PropertiesSettingsModule.java +++ b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/base/properties/PropertiesSettingsModule.java @@ -1,12 +1,14 @@ package com.capgemini.mrchecker.test.core.base.properties; -import java.io.File; import java.io.FileInputStream; +import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.nio.file.Paths; +import java.util.Objects; import java.util.Properties; +import com.capgemini.mrchecker.test.core.exceptions.BFInputDataException; import com.capgemini.mrchecker.test.core.logger.BFLogger; import com.google.inject.AbstractModule; import com.google.inject.Singleton; @@ -15,75 +17,48 @@ @Singleton public class PropertiesSettingsModule extends AbstractModule { - private static PropertiesSettingsModule instance; - private String path; + private static final String DEFAULT_FILE_SOURCE_FILE_PATH = System.getProperty("user.dir") + Paths.get("/src/resources/settings.properties"); - private PropertiesSettingsModule(String path) { - this.path = path; - BFLogger.logDebug("Properties settings file path=" + this.path); - } + private static PropertiesSettingsModule instance; + private final ThreadLocal propertiesSources = new ThreadLocal<>(); @Override protected void configure() { - - if (!exists(this.path)) { - addError("Could not configure properties file. Path='" + this.path + "' does not exist"); - } - - try { - Properties properties = loadProperties(path); + try (InputStream propertiesSource = propertiesSources.get()) { + Properties properties = new Properties(); + properties.load(propertiesSource); Names.bindProperties(binder(), properties); - } catch (RuntimeException e) { - addError("Could not configure properties file", e); + } catch (IOException e) { + throw new BFInputDataException("Could not read from properties input source: " + propertiesSources.get() + .toString()); } } public static PropertiesSettingsModule init() { - String path = System.getProperty("user.dir") + Paths.get("/src/resources/settings.properties"); - return PropertiesSettingsModule.init(path); + try { + InputStream fileSource = new FileInputStream(DEFAULT_FILE_SOURCE_FILE_PATH); + return PropertiesSettingsModule.init(fileSource); + } catch (FileNotFoundException e) { + throw new BFInputDataException("Default file not found in: " + DEFAULT_FILE_SOURCE_FILE_PATH); + } } - public static PropertiesSettingsModule init(String path) { - if (instance == null) { + public static PropertiesSettingsModule init(InputStream propertiesSource) { + if (Objects.isNull(instance)) { synchronized (PropertiesSettingsModule.class) { - if (instance == null) { - instance = new PropertiesSettingsModule(path); + if (Objects.isNull(instance)) { + instance = new PropertiesSettingsModule(); } } } + + instance.propertiesSources.set(propertiesSource); + BFLogger.logDebug("Properties settings source=" + propertiesSource.toString()); + return instance; } public static void delInstance() { PropertiesSettingsModule.instance = null; } - - private boolean exists(String path) { - File f = new File(path); - if (f.exists()) - return true; - - return false; - } - - private Properties loadProperties(String path) { - Properties properties = new Properties(); - InputStream fileInputStream = null; - - try { - fileInputStream = new FileInputStream(path); - properties.load(fileInputStream); - } catch (IOException e) { - throw new RuntimeException(e); - } finally { - if (fileInputStream != null) { - try { - fileInputStream.close(); - } catch (IOException dontCare) { - } - } - } - return properties; - } - } diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/base/runtime/RuntimeParametersI.java b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/base/runtime/IRuntimeParameters.java similarity index 63% rename from mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/base/runtime/RuntimeParametersI.java rename to mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/base/runtime/IRuntimeParameters.java index cb268bb3..fb9e670c 100644 --- a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/base/runtime/RuntimeParametersI.java +++ b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/base/runtime/IRuntimeParameters.java @@ -3,22 +3,21 @@ /** * @author LUSTEFAN */ -public interface RuntimeParametersI { +public interface IRuntimeParameters { /** * @return value of parameter */ - public String getValue(); - - + String getValue(); + /** * @return parameter key (name) */ - public String getKey(); - + String getKey(); + /** * Read one more time Runtime parameters */ - public void refreshParameterValue(); + void refreshParameterValue(); } diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/base/runtime/RuntimeParametersCore.java b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/base/runtime/RuntimeParametersCore.java index 5527665f..9328f9ff 100644 --- a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/base/runtime/RuntimeParametersCore.java +++ b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/base/runtime/RuntimeParametersCore.java @@ -1,54 +1,56 @@ package com.capgemini.mrchecker.test.core.base.runtime; +import org.apache.commons.lang.StringUtils; + /** * This class stores various system properties * * @author LUSTEFAN */ -public enum RuntimeParametersCore implements RuntimeParametersI { - +public enum RuntimeParametersCore implements IRuntimeParameters { + ENV("env", "DEV"); - - private String paramName; - private String paramValue; - private String defaultValue; - - private RuntimeParametersCore(String paramName, String defaultValue) { + + private final String paramName; + private String paramValue; + private String defaultValue; + + RuntimeParametersCore(String paramName, String defaultValue) { this.paramName = paramName; this.defaultValue = defaultValue; setValue(); } - + @Override public String getValue() { - return this.paramValue; + return paramValue; } - + @Override public String getKey() { - return this.paramName; + return paramName; } - + @Override public String toString() { - return paramName + "=" + this.getValue(); + return getKey() + "=" + getValue(); } - + @Override public void refreshParameterValue() { setValue(); } - + private void setValue() { - String systemParameterValue = System.getProperty(this.paramName); - this.paramValue = isSystemParameterEmpty(systemParameterValue) ? this.defaultValue : systemParameterValue; + String systemParameterValue = System.getProperty(paramName); + paramValue = isSystemParameterEmpty(systemParameterValue) ? defaultValue : systemParameterValue; } - + public void setDefaultValue(String value) { - this.defaultValue = isSystemParameterEmpty(value) ? this.defaultValue : value; + defaultValue = isSystemParameterEmpty(value) ? defaultValue : value; } - + private boolean isSystemParameterEmpty(String systemParameterValue) { - return (null == systemParameterValue || "".equals(systemParameterValue) || "null".equals(systemParameterValue)); + return (StringUtils.isEmpty(systemParameterValue) || "null".equals(systemParameterValue)); } } diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/exceptions/BFInputDataException.java b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/exceptions/BFInputDataException.java index f34e1f18..fc821afc 100644 --- a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/exceptions/BFInputDataException.java +++ b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/exceptions/BFInputDataException.java @@ -4,8 +4,8 @@ public class BFInputDataException extends AssertionError { - private static final long serialVersionUID = 6054714830892676552L; - private static String exceptionMessage; + private static final long serialVersionUID = 6054714830892676552L; + private static String exceptionMessage; /** * This exception should be thrown when test data contains false information, e.g.: invalid USER, USER without @@ -14,6 +14,7 @@ public class BFInputDataException extends AssertionError { * not present.")" is going to create error message: "For user with USER [12341212]: Account is not present." * * @param message + * message */ public BFInputDataException(String message) { super(generateExceptionMessage(message)); diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/exceptions/BFSecureModuleException.java b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/exceptions/BFSecureModuleException.java index 3e3b70ca..d476365b 100644 --- a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/exceptions/BFSecureModuleException.java +++ b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/exceptions/BFSecureModuleException.java @@ -5,7 +5,7 @@ public class BFSecureModuleException extends AssertionError { private static final long serialVersionUID = 6815162645071113994L; - private static String exceptionMessage; + private static String exceptionMessage; public BFSecureModuleException(String message) { super(generateExceptionMessage(message)); diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/exceptions/BFWaitingTimeoutException.java b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/exceptions/BFWaitingTimeoutException.java index 1650f1b3..5839165f 100644 --- a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/exceptions/BFWaitingTimeoutException.java +++ b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/exceptions/BFWaitingTimeoutException.java @@ -4,8 +4,8 @@ public class BFWaitingTimeoutException extends AssertionError { - private static final long serialVersionUID = 6762218637002539008L; - private static String exceptionMessage; + private static final long serialVersionUID = 6762218637002539008L; + private static String exceptionMessage; /** * This error should be thrown when time specified by {@code timeout} parameter has passed while waiting for given @@ -14,7 +14,9 @@ public class BFWaitingTimeoutException extends AssertionError { * create error message: "Timed out waiting [30] seconds for [BorderedProgressBar] to load." * * @param componentName + * componentName * @param timeout + * timeout */ public BFWaitingTimeoutException(String componentName, int timeout) { super(generateExceptionMessage(componentName, timeout)); diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/logger/BFLogger.java b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/logger/BFLogger.java index 0439c7cd..2506fd66 100644 --- a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/logger/BFLogger.java +++ b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/logger/BFLogger.java @@ -11,6 +11,9 @@ protected BFLoggerInstance initialValue() { }; + private BFLogger() { + } + public static BFLoggerInstance getLog() { return loggers.get(); } @@ -63,6 +66,9 @@ public static void logTime(long startTime, String method, String argument) { */ public static class RestrictedMethods { + private RestrictedMethods() { + } + /** * WARING: Do not use this method outside of BaseTestWatcher Begin writing all logs to a separate file in * addition to the main log file diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/logger/BFLoggerInstance.java b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/logger/BFLoggerInstance.java index 0569e0a3..599433d1 100644 --- a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/logger/BFLoggerInstance.java +++ b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/logger/BFLoggerInstance.java @@ -4,7 +4,6 @@ import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; -import java.nio.file.Paths; import java.util.Arrays; import org.apache.log4j.Appender; @@ -20,21 +19,20 @@ public class BFLoggerInstance { - private final String FBEGIN = "Function: "; - private final String FEND = "END"; + private static final String FBEGIN = "Function: "; + private static final String FEND = "END"; static { Logger.getRootLogger() .removeAppender("console"); } - private static final String logPattern = "%d{yyyy-MM-dd 'at' HH:mm:ss z} %M - %m%x%n"; - private static final Level loggerLevel = Level.DEBUG; + private static final String logPattern = "%d{yyyy-MM-dd 'at' HH:mm:ss z} %M - %m%x%n"; + private static final Level loggerLevel = Level.DEBUG; - private File directory; - private File logFile; - private String appenderName; - private Logger logger; + private File logFile; + private String appenderName; + private Logger logger; protected BFLoggerInstance() { } @@ -43,6 +41,7 @@ protected BFLoggerInstance() { * Adds the selected appender to a new instance of AsyncAppender * * @param appender + * appender * @return created AsyncAppender with appender attached */ private AsyncAppender wrapAsync(Appender appender) { @@ -113,18 +112,16 @@ private ConsoleAppender createConsoleAppender() { private File getLogFile() { if (logFile == null) { - logFile = new File(getDirectory().getPath(),getAppenderName() + ".log"); + logFile = new File(getDirectory().getPath(), getAppenderName() + ".log"); logFile.deleteOnExit(); } return logFile; } private File getDirectory() { - if (directory == null) { - directory = new File("./logs"); - if (!directory.exists()) { - directory.mkdir(); - } + File directory = new File("./logs"); + if (!directory.exists()) { + directory.mkdir(); } return directory; } @@ -209,8 +206,7 @@ protected void startSeparateLog() { */ protected String dumpSeparateLog() { try { - String logTxt = Files.toString(getLogFile(), Charsets.UTF_8); - return logTxt; + return Files.toString(getLogFile(), Charsets.UTF_8); } catch (IOException e) { e.printStackTrace(); return ""; diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/logger/EnvironmentLevel.java b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/logger/EnvironmentLevel.java index c5d01ac6..7d7800ec 100644 --- a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/logger/EnvironmentLevel.java +++ b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/logger/EnvironmentLevel.java @@ -20,18 +20,19 @@ protected EnvironmentLevel(int arg0, String arg1, int arg2) { } public static Level toLevel(String logArgument) { + return toLevel(logArgument, Level.DEBUG); + } + + public static Level toLevel(String logArgument, Level defaultLevel) { if (logArgument != null && logArgument.toUpperCase() .equals("ENVIRONMENT")) { return ENVIRONMENT; } - return (Level) toLevel(logArgument); + return Level.toLevel(logArgument, defaultLevel); } public static Level toLevel(int val) { - if (val == ENVIRONMENT_INT) { - return ENVIRONMENT; - } - return (Level) toLevel(val, Level.DEBUG); + return toLevel(val, Level.DEBUG); } public static Level toLevel(int val, Level defaultLevel) { @@ -40,12 +41,4 @@ public static Level toLevel(int val, Level defaultLevel) { } return Level.toLevel(val, defaultLevel); } - - public static Level toLevel(String logArgument, Level defaultLevel) { - if (logArgument != null && logArgument.toUpperCase() - .equals("ENVIRONMENT")) { - return ENVIRONMENT; - } - return Level.toLevel(logArgument, defaultLevel); - } } diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/testRunners/ParallelTestClassRunner.java b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/testRunners/ParallelTestClassRunner.java deleted file mode 100644 index 1146fd8d..00000000 --- a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/testRunners/ParallelTestClassRunner.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.capgemini.mrchecker.test.core.testRunners; - -import java.util.List; - -import org.junit.AfterClass; -import org.junit.internal.AssumptionViolatedException; -import org.junit.internal.runners.model.EachTestNotifier; -import org.junit.runner.notification.RunNotifier; -import org.junit.runner.notification.StoppedByUserException; -import org.junit.runners.BlockJUnit4ClassRunner; -import org.junit.runners.model.FrameworkMethod; -import org.junit.runners.model.InitializationError; -import org.junit.runners.model.Statement; - -import com.capgemini.mrchecker.test.core.testRunners.core.CustomRunAfters; - -/** - * Use this runner to run test classes in parallel, with separate "driver" for each thread. - * - * @author - */ -public class ParallelTestClassRunner extends BlockJUnit4ClassRunner { - - public ParallelTestClassRunner(Class klass) throws InitializationError { - super(klass); - } - - @Override - public void run(final RunNotifier notifier) { - EachTestNotifier testNotifier = new EachTestNotifier(notifier, getDescription()); - try { - Statement statement = classBlock(notifier); - statement.evaluate(); - } catch (AssumptionViolatedException e) { - testNotifier.addFailedAssumption(e); - } catch (StoppedByUserException e) { - throw e; - } catch (Throwable e) { - testNotifier.addFailure(e); - } finally { - } - } - - /** - * Returns a {@link Statement}: run all non-overridden {@code @AfterClass} methods on this class and superclasses - * before executing {@code statement}; all AfterClass methods are always executed: exceptions thrown by previous - * steps are combined, if necessary, with exceptions from AfterClass methods into a - * {@link org.junit.runners.model.MultipleFailureException}. - */ - @Override - protected Statement withAfterClasses(Statement statement) { - List afters = getTestClass().getAnnotatedMethods(AfterClass.class); - return afters.isEmpty() ? statement : new CustomRunAfters(statement, afters, null); - } -} \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/testRunners/core/CustomRunAfters.java b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/testRunners/core/CustomRunAfters.java deleted file mode 100644 index 541df47d..00000000 --- a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/testRunners/core/CustomRunAfters.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.capgemini.mrchecker.test.core.testRunners.core; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.runners.model.FrameworkMethod; -import org.junit.runners.model.MultipleFailureException; -import org.junit.runners.model.Statement; - -import com.capgemini.mrchecker.test.core.logger.BFLogger; - -/** - * This class replace default RunAfters class. The difference is, that using this one, we avoid having additional tests - * in our report. Using default JUnit RunAfters caused false report results in case test fails/breaks during AfterClass - * execution. For example, when we execute 1 test and it fails during AfterClass, in report we will see 1 test passed - * and 1 failed. - * - * @author - */ -public class CustomRunAfters extends Statement { - private final Statement next; - - private final Object target; - - private final List afters; - - public CustomRunAfters(Statement next, List afters, Object target) { - this.next = next; - this.afters = afters; - this.target = target; - } - - @Override - public void evaluate() throws Throwable { - List errors = new ArrayList(); - try { - next.evaluate(); - } catch (Throwable e) { - errors.add(e); - } finally { - for (FrameworkMethod each : afters) { - try { - each.invokeExplosively(target); - } catch (Throwable e) { - BFLogger.logError("There was an exception in @AfterClass " + each.getName() + ": " + e.toString()); - } - } - } - MultipleFailureException.assertEmpty(errors); - } -} \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/utils/Attachments.java b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/utils/Attachments.java new file mode 100644 index 00000000..2f63cf3e --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/utils/Attachments.java @@ -0,0 +1,14 @@ +package com.capgemini.mrchecker.test.core.utils; + +import io.qameta.allure.Attachment; + +public class Attachments { + private Attachments() { + + } + + @Attachment("Log file") + public static String attachToAllure(String content) { + return content; + } +} diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/utils/JsonReader.java b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/utils/JsonReader.java new file mode 100644 index 00000000..1e1af9cb --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/utils/JsonReader.java @@ -0,0 +1,52 @@ +package com.capgemini.mrchecker.test.core.utils; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; + +import org.apache.commons.io.IOUtils; +import org.json.JSONObject; + +import com.capgemini.mrchecker.test.core.exceptions.BFInputDataException; + +public class JsonReader { + + private JsonReader() { + // NOP + } + + /** + * Reads JSON file and return it's + * + * @param jsonFile + * jsonFile + * @return JSONObject + */ + public static JSONObject readJson(File jsonFile) { + try (InputStream inputStream = new FileInputStream(jsonFile)) { + return readJson(inputStream); + } catch (FileNotFoundException e) { + throw new BFInputDataException("Not found JSON file: " + jsonFile.getName()); + } catch (IOException e) { + throw new BFInputDataException("Unable to read JSON file: " + jsonFile.getName()); + } + } + + /** + * Reads JSON file and return it's + * + * @param jsonInputStream + * jsonInputStream + * @return JSONObject + */ + public static JSONObject readJson(InputStream jsonInputStream) { + try { + return new JSONObject(IOUtils.toString(jsonInputStream, StandardCharsets.UTF_8)); + } catch (IOException e) { + throw new BFInputDataException("Unable to read JSON from the stream: " + jsonInputStream.toString()); + } + } +} diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/utils/NumberUtils.java b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/utils/NumberUtils.java index ee133c72..efb901bb 100644 --- a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/utils/NumberUtils.java +++ b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/utils/NumberUtils.java @@ -10,22 +10,21 @@ /** * This class contains utility functions related to numeric operation (getting random numbers, conversion to numbers, * comparison etc.). - * - * @author */ public class NumberUtils { private NumberUtils() { } - public static final String DOLLAR_REGEX = "\\$(?:0|[1-9]\\d{0,2}(?:,?\\d{3})*)(\\.\\d{2})"; - public static final BigDecimal delta = new BigDecimal("0.02"); + public static final String DOLLAR_REGEX = "\\$(?:0|[1-9]\\d{0,2}(?:,?\\d{3})*)(\\.\\d{2})"; + public static final BigDecimal delta = new BigDecimal("0.02"); /** * Checks if input text is a amount and returns value of it (ie. -$23.15 --> -23.15) Warning if given textValue is * null or empty return 0 * - * @param textValue + * @param text + * text * @return BigDecimal object with 2 decimal points precision */ public static BigDecimal getValueFromStringAmount(String text) { @@ -40,6 +39,7 @@ public static BigDecimal getValueFromStringAmount(String text) { * null or empty return 0 * * @param textValue + * textValue * @return BigDecimal object with 2 decimal points precision */ public static BigDecimal convertTextValueToDecimal(String textValue) { @@ -59,7 +59,8 @@ public static BigDecimal convertTextValueToDecimal(String textValue) { * Removes '$' and ',' marks from passed textValue and convert to BigDecimal object Warning if given textValue is * null or empty return 0 * - * @param textValue + * @param textValues + * textValues * @return BigDecimal object with 2 decimal points precision */ public static BigDecimal[] convertTextValueToDecimal(final String[] textValues) { @@ -70,7 +71,8 @@ public static BigDecimal[] convertTextValueToDecimal(final String[] textValues) * Removes '$' and ',' marks from passed textValue and convert to BigDecimal object Warning if given textValue is * null or empty return 0 * - * @param textValue + * @param textValues + * textValues * @return BigDecimal object with 2 decimal points precision */ public static BigDecimal[] convertTextValueToDecimal(final Iterable textValues) { @@ -86,6 +88,7 @@ public static BigDecimal[] convertTextValueToDecimal(final Iterable text * Checks if given text is representing a numerical value (can be negative value, and decimals) * * @param textValue + * textValue * @return true when is numerical; false otherwise */ public static boolean isNumeric(String textValue) { @@ -97,6 +100,7 @@ public static boolean isNumeric(String textValue) { * Checks if given text contain two decimal places * * @param textValue + * textValue * @return boolean value */ public static boolean isTwoDecimalPlaces(String textValue) { @@ -119,10 +123,7 @@ public static boolean isDifferenceMajor(BigDecimal oneValue, BigDecimal secondVa final BigDecimal acceptedDifference = BigDecimal.ONE; BigDecimal absDifference = oneValue.subtract(secondValue) .abs(); - if (absDifference.compareTo(acceptedDifference) <= 0) { - return false; - } - return true; + return absDifference.compareTo(acceptedDifference) > 0; } /** @@ -141,8 +142,8 @@ public static int getRandomInteger(int seed) { * To check is single value as String is correctly formated. That is should contains 2 decimal places * * @param percent + * percent * @return true/false - * @author */ public static boolean isPercentRoundedTo2decimalPlaces(String percent) { String pr = percent.replaceAll("%", "") @@ -161,6 +162,7 @@ public static boolean isPercentRoundedTo2decimalPlaces(String percent) { * @param number * as text * @param precision + * precision * @return String with desired decimal points precision */ public static String convertNumberToXDecimalPoints(String number, int precision) { @@ -179,6 +181,7 @@ public static String convertNumberToXDecimalPoints(String number, int precision) * @param numbersList * as text list * @param precision + * precision * @return list of String with desired decimal points precision */ public static List convertNumberToXDecimalPoints(List numbersList, int precision) { @@ -206,11 +209,9 @@ static public boolean isBigDecimalDifferent(BigDecimal f1, BigDecimal f2, BigDec if (f1.compareTo(f2) == 0) { return false; } - if (f1.subtract(f2) + + return f1.subtract(f2) .abs() - .compareTo(delta) <= 0) { - return false; - } - return true; + .compareTo(delta) > 0; } } diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/utils/PageFactory.java b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/utils/PageFactory.java new file mode 100644 index 00000000..9fe49364 --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/utils/PageFactory.java @@ -0,0 +1,65 @@ +package com.capgemini.mrchecker.test.core.utils; + +import java.lang.reflect.InvocationTargetException; +import java.util.Arrays; +import java.util.stream.Collectors; + +import com.capgemini.mrchecker.test.core.Page; +import com.capgemini.mrchecker.test.core.exceptions.BFInputDataException; + +/** + * This class supports pages creation. It instantiates a page of the given class using a no-arguments constructor + * or a constructor with arguments. After the requested class instance is created it's automatically added to + * test execution observer for notifications. + *

+ * Primitive types in constructors are not allowed. Use object types instead e.g. Integer + */ +public class PageFactory { + private PageFactory() { + } + + public static T getPageInstance(Class pageClass) { + try { + T pageInstance = pageClass.newInstance(); + pageInstance.addToTestExecutionObserver(); + return pageInstance; + } catch (InstantiationException | IllegalAccessException e) { + throw new BFInputDataException("Could not instantiate class: " + pageClass.getName()); + } + } + + public static T getPageInstance(Class pageClass, Object... constructorArgs) { + Class[] argsClassArray = new Class[constructorArgs.length]; + argsClassArray = Arrays.stream(constructorArgs) + .map(Object::getClass) + .collect(Collectors.toList()) + .toArray(argsClassArray); + + try { + T pageInstance = pageClass.getConstructor(argsClassArray) + .newInstance(constructorArgs); + pageInstance.addToTestExecutionObserver(); + return pageInstance; + } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { + throw new BFInputDataException("Could not instantiate class: " + pageClass.getName()); + } + } + + public static T getPageInstance(String pageClassName) { + try { + Class pageClass = (Class) Class.forName(pageClassName); + return getPageInstance(pageClass); + } catch (ClassNotFoundException e) { + throw new BFInputDataException("Could not find a class of the name: " + pageClassName); + } + } + + public static T getPageInstance(String pageClassName, Object... constructorArgs) { + try { + Class pageClass = (Class) Class.forName(pageClassName); + return getPageInstance(pageClass, constructorArgs); + } catch (ClassNotFoundException e) { + throw new BFInputDataException("Could not find a class of the name: " + pageClassName); + } + } +} diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/utils/datadriven/JsonDriven.java b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/utils/datadriven/JsonDriven.java index d10067bc..e7e43027 100644 --- a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/utils/datadriven/JsonDriven.java +++ b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/utils/datadriven/JsonDriven.java @@ -2,6 +2,8 @@ import java.io.FileNotFoundException; import java.io.FileReader; +import java.io.IOException; +import java.io.Reader; import com.capgemini.mrchecker.test.core.logger.BFLogger; @@ -33,19 +35,34 @@ public static T provide(String filename, Class clazz) { .fromJson(fileToJson(filename), clazz); } + public static T provide(Reader reader, Class clazz) { + return new GsonBuilder().create() + .fromJson(readerToJson(reader), clazz); + } + /** * @param fileName + * fileName * @return json from file or empty object when parsing file failed */ private static JsonArray fileToJson(String fileName) { - JsonArray jsonArray = new JsonArray(); - try { - jsonArray = new JsonParser().parse(new FileReader(fileName)) - .getAsJsonArray(); + try (Reader reader = new FileReader(fileName)) { + return readerToJson(reader); } catch (FileNotFoundException e) { BFLogger.logError("Json file not found: " + fileName); + } catch (IOException e) { + BFLogger.logError("Json file could not be read: " + fileName); } - return jsonArray; + return new JsonArray(); } + /** + * @param reader + * reader + * @return json from reader + */ + private static JsonArray readerToJson(Reader reader) { + return new JsonParser().parse(reader) + .getAsJsonArray(); + } } diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/utils/datadriven/json/JsonReader.java b/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/utils/datadriven/json/JsonReader.java deleted file mode 100644 index 310447f7..00000000 --- a/mrchecker-framework-modules/mrchecker-core-module/src/main/java/com/capgemini/mrchecker/test/core/utils/datadriven/json/JsonReader.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.capgemini.mrchecker.test.core.utils.datadriven.json; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.commons.io.IOUtils; -import org.json.JSONException; -import org.json.JSONObject; - -import com.capgemini.mrchecker.test.core.exceptions.BFInputDataException; - -public class JsonReader { - - private JsonReader() { - // NOP - } - - /** - * Reads JSON file and return it's - * - * @param jsonFile - * @return - */ - public static JSONObject readJson(File jsonFile) { - JSONObject jsonObject = null; - try { - InputStream jsonStream = new FileInputStream(jsonFile); - String genreJson = IOUtils.toString(jsonStream); - try { - jsonObject = new JSONObject(genreJson); - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } catch (IOException e) { - throw new BFInputDataException("Unable to read JSON file: " + jsonFile.getName()); - } - return jsonObject; - } - -} diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/analytics/AnalyticsProviderTest.java b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/analytics/AnalyticsProviderTest.java deleted file mode 100644 index 7e63958f..00000000 --- a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/analytics/AnalyticsProviderTest.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.capgemini.mrchecker.test.core.analytics; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.capgemini.mrchecker.test.core.analytics.AnalyticsProvider; - -public class AnalyticsProviderTest { - - @Before - public void setup() { - - } - - @After - public void teardown() { - - } - - @Test - public void testDisabledProvider_sendClassName() { - AnalyticsProvider analyticsProvider = AnalyticsProvider.DISABLED; - analyticsProvider.sendClassName("/com/capgemini/ntc/test/core/analytics", "AnalyticsProviderTest", "testDisabledProvider"); - } - - @Test - public void testDisabledProvider_sendMethodEventShort() { - AnalyticsProvider analyticsProvider = AnalyticsProvider.DISABLED; - analyticsProvider.sendMethodEvent("Selenium-Test-AnalyticsDisabledProvider"); - } - - @Test - public void testDisabledProvider_sendMethodEventLong() { - AnalyticsProvider analyticsProvider = AnalyticsProvider.DISABLED; - analyticsProvider.sendMethodEvent("Selenium-Test-AnalyticsDisabledProvider", "testDisabledProvider - sendMethodEventLong"); - } - -} diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/base/encryption/DataEncryptionTest.java b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/base/encryption/DataEncryptionTest.java deleted file mode 100644 index f7557e53..00000000 --- a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/base/encryption/DataEncryptionTest.java +++ /dev/null @@ -1,206 +0,0 @@ -package com.capgemini.mrchecker.test.core.base.encryption; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.nio.file.Paths; - -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -import com.capgemini.mrchecker.test.core.base.encryption.DataEncryptionModule; -import com.capgemini.mrchecker.test.core.base.encryption.IDataEncryptionService; -import com.capgemini.mrchecker.test.core.base.encryption.providers.DataEncryptionService; -import com.capgemini.mrchecker.test.core.exceptions.BFSecureModuleException; -import com.google.inject.AbstractModule; -import com.google.inject.Guice; -import com.google.inject.Provides; - -public class DataEncryptionTest { - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - - } - - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - private IDataEncryptionService systemUnderTest; - - @Before - public void setUp() throws Exception { - - systemUnderTest = Guice.createInjector(securedataTestModel()) - .getInstance(IDataEncryptionService.class); - - } - - @After - public void tearDown() throws Exception { - } - - @Test(expected = BFSecureModuleException.class) - public void secretdata_file_does_not_exsist() { - DataEncryptionService.delInstance(); - Guice.createInjector(securedataTestModel_secretdata_file_does_not_exsist()) - .getInstance(IDataEncryptionService.class); - } - - private AbstractModule securedataTestModel_secretdata_file_does_not_exsist() { - return new AbstractModule() { - - @Override - protected void configure() { - } - - @Provides - IDataEncryptionService provideSecuredataService() { - String path = System.getProperty("user.dir") + Paths.get("/src/test/resources/secretData_wrong_path"); - DataEncryptionService.init(new File(path)); - return DataEncryptionService.getInstance(); - } - }; - } - - @Test(expected = BFSecureModuleException.class) - public void secretdata_file_with_empty_key() { - DataEncryptionService.delInstance(); - - Guice.createInjector(securedataTestModel_secretdata_file_with_empty_key()) - .getInstance(IDataEncryptionService.class); - } - - private AbstractModule securedataTestModel_secretdata_file_with_empty_key() { - return new AbstractModule() { - - @Override - protected void configure() { - } - - @Provides - IDataEncryptionService provideSecuredataService() { - String path = System.getProperty("user.dir") + Paths.get("/src/test/resources/secretData_emptykey"); - DataEncryptionService.init(new File(path)); - return DataEncryptionService.getInstance(); - } - }; - } - - public void secretdata_file_with_wrong_key() { - DataEncryptionService.delInstance(); - Guice.createInjector(securedataTestModel_secretdata_file_with_wrong_key()) - .getInstance(IDataEncryptionService.class); - // That's ok. At this point we don't have any means to tell it's the wrong key. - } - - private AbstractModule securedataTestModel_secretdata_file_with_wrong_key() { - return new AbstractModule() { - - @Override - protected void configure() { - } - - @Provides - IDataEncryptionService provideSecuredataService() { - String path = System.getProperty("user.dir") + Paths.get("/src/test/resources/secretData_test2"); - DataEncryptionService.init(new File(path)); - return DataEncryptionService.getInstance(); - } - }; - } - - @Test - public void validate_is_text_encrypted() { - assertTrue(systemUnderTest.isEncrypted("ENC(ffqqqsdf)")); - assertFalse(systemUnderTest.isEncrypted("ENC(ffqqqsdf")); - assertFalse(systemUnderTest.isEncrypted("enc(ffqqqsdf)")); - assertFalse(systemUnderTest.isEncrypted("ffqqqsdf")); - } - - @Test(expected = BFSecureModuleException.class) - public void decrypt_with_wrong_key() { - // given - String ciphertext = systemUnderTest.encrypt("test"); - DataEncryptionService.delInstance(); - IDataEncryptionService service = Guice.createInjector(securedataTestModel_secretdata_file_with_wrong_key()) - .getInstance(IDataEncryptionService.class); - - // when - service.decrypt(ciphertext); - } - - @Test - public void decrypt_with_good_key() { - // given - String plaintext = "test"; - String ciphertext = systemUnderTest.encrypt(plaintext); - - // when - String plaintext2 = systemUnderTest.decrypt(ciphertext); - - // then - assertEquals(plaintext, plaintext2); - assertNotEquals(plaintext, ciphertext); - } - - @Test(expected = BFSecureModuleException.class) - public void set_secret_null() { - systemUnderTest.setSecret(null); - } - - @Test(expected = BFSecureModuleException.class) - public void set_secret_short() { - systemUnderTest.setSecret("1234567"); - } - - @Test(expected = BFSecureModuleException.class) - public void set_secret_trimable() { - systemUnderTest.setSecret(" 1234567"); - } - - @Test - public void set_secret_ok() { - systemUnderTest.setSecret("12345678"); - } - - @Test() - public void dataEncryptions_with_default_secretdata_file() { - // given - IDataEncryptionService service = Guice.createInjector(new DataEncryptionModule()) - .getInstance(IDataEncryptionService.class); - String plaintext = "default"; - - // when - String ciphertext = service.encrypt(plaintext); - String plaintext2 = service.decrypt(ciphertext); - - // then - assertEquals(plaintext, plaintext2); - assertNotEquals(ciphertext, plaintext); - } - - private AbstractModule securedataTestModel() { - return new AbstractModule() { - - @Override - protected void configure() { - } - - @Provides - IDataEncryptionService provideSecuredataService() { - String path = System.getProperty("user.dir") + Paths.get("/src/test/resources/secretData_test"); - DataEncryptionService.init(new File(path)); - return DataEncryptionService.getInstance(); - } - }; - } - -} diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/base/environment/EnvironmentMainTest.java b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/base/environment/EnvironmentMainTest.java deleted file mode 100644 index c099374a..00000000 --- a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/base/environment/EnvironmentMainTest.java +++ /dev/null @@ -1,171 +0,0 @@ -package com.capgemini.mrchecker.test.core.base.environment; - -import com.capgemini.mrchecker.test.core.BaseTest; -import com.capgemini.mrchecker.test.core.base.encryption.DataEncryptionModule; -import com.capgemini.mrchecker.test.core.base.encryption.IDataEncryptionService; -import com.capgemini.mrchecker.test.core.base.environment.providers.SpreadsheetEnvironmentService; -import com.capgemini.mrchecker.test.core.exceptions.BFInputDataException; -import com.capgemini.mrchecker.test.core.logger.BFLogger; -import com.google.inject.AbstractModule; -import com.google.inject.Guice; -import com.google.inject.Provides; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; - -import java.nio.file.Paths; - -import static org.junit.Assert.assertEquals; - -@Ignore -public class EnvironmentMainTest { - - IEnvironmentService systemUnderTest; - - @Before - public void setup() { - systemUnderTest = Guice.createInjector(environmentTestModel()) - .getInstance(IEnvironmentService.class); - - BaseTest.getEnvironmentService(); - } - - @After - public void teardown() { - } - - @Test - public void testDependecyInjection() throws Exception { - SpreadsheetEnvironmentService.delInstance(); - IEnvironmentService environmentService = Guice.createInjector(new EnvironmentModule()) - .getInstance(IEnvironmentService.class); - - environmentService.setEnvironment("DEV"); - assertEquals("http://demoqa.com/", environmentService.getValue("WWW_FONT_URL")); - - } - - @Test - public void getServiceAddressShouldReturnCorrectServiceAddressForDefaultEnvironment() { - SpreadsheetEnvironmentService.delInstance(); - systemUnderTest = Guice.createInjector(new EnvironmentModule()) - .getInstance(IEnvironmentService.class); - - String actualAddress = systemUnderTest.getValue("DMA_URL"); - String expectedAddress = "https://dma.company.com"; - assertEquals(expectedAddress, actualAddress); - } - - @Test(expected = BFInputDataException.class) - public void getServiceAddressShouldThrowExceptionWhenServiceNotFound() { - - systemUnderTest.getValue("NOT_EXISTING_SERVICE"); - } - - @Test - public void setEnvironmentShouldSucceedWhenEnvironmentExist() { - - systemUnderTest.setEnvironment("DEV2"); - assertEquals("DEV2", systemUnderTest.getEnvironment()); - } - - @Test - public void getServiceAddressShouldReturnCorrectServiceAddressForSelectedEnvironment() { - - String serviceName = "MY_RESEARCH_URL_VALUE"; - - systemUnderTest.setEnvironment("DEV2"); - String actualAddress = systemUnderTest.getValue(serviceName); - String expectedAddress = "https://myresearchqa2.company.com/"; - assertEquals(expectedAddress, actualAddress); - - systemUnderTest.setEnvironment("DEV1"); - actualAddress = systemUnderTest.getValue(serviceName); - expectedAddress = "https://myresearchqa1.company.com/"; - assertEquals(expectedAddress, actualAddress); - - systemUnderTest.setEnvironment("DEV2"); - actualAddress = systemUnderTest.getValue(serviceName); - expectedAddress = "https://myresearchqa2.company.com/"; - assertEquals(expectedAddress, actualAddress); - } - - @Test(expected = BFInputDataException.class) - public void setEnvironmentShouldThrowExceptionWhenEnvironmentNotFound() { - - systemUnderTest.setEnvironment("DEV99"); - } - - @Test - public void ServicesURLsEnumIsReturningCorrectAddresses() { - BaseTest.getEnvironmentService(); - - systemUnderTest.setEnvironment("DEV1"); - BaseTest.setEnvironmentService(systemUnderTest); - GetEnvironmentParam.refreshAll(); - - String actualAddress = GetEnvironmentParam.WWW_FONT_URL.getValue(); - String expectedAddress = "https://myresearchqa1.company.com/"; - assertEquals(expectedAddress, actualAddress); - - systemUnderTest.setEnvironment("DEV2"); - actualAddress = GetEnvironmentParam.WWW_FONT_URL.getValue(); - expectedAddress = "https://myresearchqa2.company.com/"; - assertEquals(expectedAddress, actualAddress); - } - - @Test - public void envLogTest() { - BFLogger.logEnv("----- test -----"); - } - - @Test - public void testNoDataEncryptionServicePresent() { - // given - String serviceName = "PASSWORD"; - String expected = "ENC(gD6S9sHAhNb6kVsCsZd81A==)"; - systemUnderTest.setEnvironment("DEV"); - systemUnderTest.setDataEncryptionService(null); - - // when - String value = systemUnderTest.getValue(serviceName); - - // then - assertEquals(expected, value); - } - - @Test - public void testDataEncryptionServicePresent() { - // given - String serviceName = "PASSWORD"; - String expected = "test"; - IDataEncryptionService encryptionService = Guice.createInjector(new DataEncryptionModule()) - .getInstance(IDataEncryptionService.class); - systemUnderTest.setDataEncryptionService(encryptionService); - - // when - String value = systemUnderTest.getValue(serviceName); - - // then - assertEquals(expected, value); - } - - private AbstractModule environmentTestModel() { - return new AbstractModule() { - - @Override - protected void configure() { - } - - @Provides - IEnvironmentService provideEnvironmentService() { - String path = System.getProperty("user.dir") + Paths.get("/src/test/resources/enviroments/environments.csv"); - String environment = "QA"; - SpreadsheetEnvironmentService.init(path, environment); - return SpreadsheetEnvironmentService.getInstance(); - } - }; - } - -} diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/base/properties/PropertiesManagerTest.java b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/base/properties/PropertiesManagerTest.java deleted file mode 100644 index f15f078e..00000000 --- a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/base/properties/PropertiesManagerTest.java +++ /dev/null @@ -1,153 +0,0 @@ -package com.capgemini.mrchecker.test.core.base.properties; - -import com.google.inject.Guice; -import com.google.inject.Inject; -import com.google.inject.Injector; -import com.google.inject.name.Named; -import org.junit.*; - -import java.nio.file.Paths; - -import static org.junit.Assert.*; - -public class PropertiesManagerTest { - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - } - - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - private PropertiesCoreTest properties; - - @Before - public void setUp() throws Exception { - String path = System.getProperty("user.dir") + Paths.get("/src/test/resources/settings.properties"); - Injector i = Guice.createInjector(PropertiesSettingsModule.init(path)); - this.properties = i.getInstance(PropertiesCoreTest.class); - } - - @After - public void tearDown() throws Exception { - PropertiesSettingsModule.delInstance(); - } - - @Test - public void testParamterIsAnalyticsEnabled() { - assertEquals("", true, properties.isAnalyticsEnabled()); - } - - @Test - public void testParamterIsEncryptionEnabled() { - assertEquals("", true, properties.isEncryptionEnabled()); - } - - @Test - public void testParamterIsAnalyticsEnabledWithUnkonwText() throws Exception { - PropertiesSettingsModule.delInstance(); - String path = System.getProperty("user.dir") + Paths.get("/src/test/resources/settings3.properties"); - Injector i = Guice.createInjector(PropertiesSettingsModule.init(path)); - properties = i.getInstance(PropertiesCoreTest.class); - - assertTrue("", properties.isAnalyticsEnabled()); - } - - @Test - public void testParamterIsEncryptionEnabledWithUnkonwText() throws Exception { - PropertiesSettingsModule.delInstance(); - String path = System.getProperty("user.dir") + Paths.get("/src/test/resources/settings3.properties"); - Injector i = Guice.createInjector(PropertiesSettingsModule.init(path)); - properties = i.getInstance(PropertiesCoreTest.class); - - assertFalse("", properties.isEncryptionEnabled()); - } - - @Test - public void testParamterIsAnalyticsEnabledWithFalse() throws Exception { - PropertiesSettingsModule.delInstance(); - String path = System.getProperty("user.dir") + Paths.get("/src/test/resources/settings2.properties"); - Injector i = Guice.createInjector(PropertiesSettingsModule.init(path)); - properties = i.getInstance(PropertiesCoreTest.class); - - assertFalse("", properties.isAnalyticsEnabled()); - } - - @Test - public void testParamterIsEncryptionEnabledWithFalse() throws Exception { - PropertiesSettingsModule.delInstance(); - String path = System.getProperty("user.dir") + Paths.get("/src/test/resources/settings2.properties"); - Injector i = Guice.createInjector(PropertiesSettingsModule.init(path)); - properties = i.getInstance(PropertiesCoreTest.class); - - assertFalse("", properties.isEncryptionEnabled()); - } - - @Test - public void testDefaultParamters() { - PropertiesSettingsModule.delInstance(); - - Injector i = Guice.createInjector(PropertiesSettingsModule.init()); - PropertiesCoreTestFake properties = i.getInstance(PropertiesCoreTestFake.class); - - assertEquals("", true, properties.doesNotExist()); - } - - @Test - public void testParamterIsAnalyticsEnabledNoValue() throws Exception { - PropertiesSettingsModule.delInstance(); - String path = System.getProperty("user.dir") + Paths.get("/src/test/resources/settings4.properties"); - Injector i = Guice.createInjector(PropertiesSettingsModule.init(path)); - properties = i.getInstance(PropertiesCoreTest.class); - - assertTrue("", properties.isAnalyticsEnabled()); - } - - @Test - public void testParamterIsEncryptionEnabledNoValue() throws Exception { - PropertiesSettingsModule.delInstance(); - String path = System.getProperty("user.dir") + Paths.get("/src/test/resources/settings4.properties"); - Injector i = Guice.createInjector(PropertiesSettingsModule.init(path)); - properties = i.getInstance(PropertiesCoreTest.class); - - assertFalse("", properties.isEncryptionEnabled()); - } - - @Test - public void testParamterDefaultEnvironmentNameNoValue() throws Exception { - PropertiesSettingsModule.delInstance(); - String path = System.getProperty("user.dir") + Paths.get("/src/test/resources/settings4.properties"); - Injector i = Guice.createInjector(PropertiesSettingsModule.init(path)); - properties = i.getInstance(PropertiesCoreTest.class); - - assertEquals("DEV", properties.getDefaultEnvironmentName()); - } - - @Test - public void testParamterDefaultEnvironmentNameNonDefault() throws Exception { - PropertiesSettingsModule.delInstance(); - String path = System.getProperty("user.dir") + Paths.get("/src/test/resources/settings2.properties"); - Injector i = Guice.createInjector(PropertiesSettingsModule.init(path)); - properties = i.getInstance(PropertiesCoreTest.class); - - assertEquals("NON_DEFAULT", properties.getDefaultEnvironmentName()); - } - - private static class PropertiesCoreTestFake { - - private Boolean coreDoesNotExist = true; - - @Inject(optional = true) - private void setDoesNotExist(@Named("core.doesNotExist") Boolean status) { - this.coreDoesNotExist = status; - - } - - public Boolean doesNotExist() { - return this.coreDoesNotExist; - } - - } - -} diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/base/runtime/RuntimeParametersTest.java b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/base/runtime/RuntimeParametersTest.java deleted file mode 100644 index 6296c924..00000000 --- a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/base/runtime/RuntimeParametersTest.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.capgemini.mrchecker.test.core.base.runtime; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; - -import java.util.ArrayList; - -import org.hamcrest.Matchers; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.capgemini.mrchecker.test.core.base.runtime.RuntimeParametersCore; -import com.google.common.collect.Lists; - -public class RuntimeParametersTest { - - @Before - public void setUp() throws Exception { - System.setProperty("env", "UNKNOWN"); - RuntimeParametersCore.ENV.refreshParameterValue(); - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testGetProperty() { - assertEquals("System parameters for 'env' are not equal", "UNKNOWN", RuntimeParametersCore.ENV.getValue()); - } - - @Test - public void testGetEmptyProperty() { - System.clearProperty("env"); - RuntimeParametersCore.ENV.refreshParameterValue(); - - assertEquals("System parameters for empty property 'env' should be 'DEV'", "DEV", RuntimeParametersCore.ENV.getValue()); - } - - @Test - public void testGetParams() throws Exception { - ArrayList collection = Lists.newArrayList(RuntimeParametersCore.values()); - assertThat(collection, Matchers.hasItem(Matchers.hasToString("env=UNKNOWN"))); - } - -} diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/integration/RunningTestsTest.java b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/integration/RunningTestsTest.java new file mode 100644 index 00000000..2ed22422 --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/integration/RunningTestsTest.java @@ -0,0 +1,411 @@ +package com.capgemini.mrchecker.test.core.integration; + +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.junit.Assert.assertThat; +import static org.junit.jupiter.api.Assertions.fail; +import static org.junit.jupiter.api.Assumptions.assumeFalse; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.List; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.ResourceLock; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvFileSource; +import org.junit.platform.launcher.listeners.TestExecutionSummary; + +import com.capgemini.mrchecker.test.core.BaseTest; +import com.capgemini.mrchecker.test.core.ITestObserver; +import com.capgemini.mrchecker.test.core.ModuleType; +import com.capgemini.mrchecker.test.core.tags.IntegrationTest; +import com.capgemini.mrchecker.test.core.utils.TestLauncher; + +import io.qameta.allure.Feature; +import io.qameta.allure.Muted; + +@IntegrationTest +@ResourceLock(value = "SingleThread") +public class RunningTestsTest { + public static ITestObserver testObserver; + public static ITestObserver testObserverSecond; + + private static boolean isBaseTestSetupCalled; + private static boolean isBaseTestTeardownCalled; + + private static final boolean CALLED = true; + private static final boolean NOT_CALLED = false; + + public static final String CLASS_PREFIX = "com.capgemini.mrchecker.test.core.integration.RunningTestsTest$"; + + @BeforeEach + public void setUp() { + isBaseTestSetupCalled = NOT_CALLED; + isBaseTestTeardownCalled = NOT_CALLED; + } + + public static class BaseTestWithHooks extends BaseTest { + @Override + public void setUp() { + isBaseTestSetupCalled = CALLED; + } + + @Override + public void tearDown() { + isBaseTestTeardownCalled = CALLED; + } + } + + @ParameterizedTest + @CsvFileSource(resources = "/datadriven/integration/running_tests.csv", numLinesToSkip = 1) + public void shouldRunTestBundle(String className, + int expectedOnTestSuccessCount, + int expectedOnTestFailureCount, + int expectedOnTestFinishCount, + int expectedOnTestClassFinishCount, + boolean expectedAreHooksCalled) throws ClassNotFoundException { + testObserver = mock(ITestObserver.class); + when(testObserver.getModuleType()).thenReturn(ModuleType.CORE); + + TestLauncher.launch(CLASS_PREFIX + className); + + verify(testObserver, times(expectedOnTestSuccessCount)).onTestSuccess(); + verify(testObserver, times(expectedOnTestFailureCount)).onTestFailure(); + verify(testObserver, times(expectedOnTestFinishCount)).onTestFinish(); + verify(testObserver, times(expectedOnTestClassFinishCount)).onTestClassFinish(); + + assertThat(isBaseTestSetupCalled, is(equalTo(expectedAreHooksCalled))); + assertThat(isBaseTestTeardownCalled, is(equalTo(expectedAreHooksCalled))); + } + + @Feature("Running tests") + @Muted + public static class PassingTestWithObserverAddedInTestMethod extends BaseTestWithHooks { + @Test + public void simpleTest() { + TEST_EXECUTION_OBSERVER.addObserver(testObserver); + } + } + + @Feature("Running tests") + @Muted + public static class PassingTestWithObserverAddedTwiceInTestMethod extends BaseTestWithHooks { + + @Test + public void simpleTest() { + TEST_EXECUTION_OBSERVER.addObserver(testObserver); + TEST_EXECUTION_OBSERVER.addObserver(testObserver); + } + } + + @Test + public void shouldPassTestWithTwoObserversAddedInTestMethod() { + testObserver = mock(ITestObserver.class); + when(testObserver.getModuleType()).thenReturn(ModuleType.CORE); + testObserverSecond = mock(ITestObserver.class); + when(testObserverSecond.getModuleType()).thenReturn(ModuleType.CORE); + + TestLauncher.launch(PassingTestWithTwoObserversAddedInTestMethod.class); + + verify(testObserver, times(1)).onTestSuccess(); + verify(testObserver, times(0)).onTestFailure(); + verify(testObserver, times(1)).onTestFinish(); + verify(testObserver, times(1)).onTestClassFinish(); + + verify(testObserverSecond, times(0)).onTestSuccess(); + verify(testObserverSecond, times(0)).onTestFailure(); + verify(testObserverSecond, times(0)).onTestFinish(); + verify(testObserverSecond, times(0)).onTestClassFinish(); + + assertThat(isBaseTestSetupCalled, is(equalTo(CALLED))); + assertThat(isBaseTestTeardownCalled, is(equalTo(CALLED))); + } + + @Feature("Running tests") + @Muted + public static class PassingTestWithTwoObserversAddedInTestMethod extends BaseTestWithHooks { + + @Test + public void simpleTest() { + TEST_EXECUTION_OBSERVER.addObserver(testObserver); + TEST_EXECUTION_OBSERVER.addObserver(testObserverSecond); + } + } + + @Feature("Running tests") + @Muted + public static class PassingTestWithObserverAddedInBeforeAll extends BaseTestWithHooks { + + @BeforeAll + public static void setUpClass() { + TEST_EXECUTION_OBSERVER.addObserver(testObserver); + } + + @Test + public void simpleTest() { + } + } + + @Test + public void shouldPassTestsMultithreaded() { + testObserver = mock(ITestObserver.class); + testObserverSecond = mock(ITestObserver.class); + + List> testClasses = new ArrayList<>(); + testClasses.add(shouldPassTestsMultithreadedThread1.class); + testClasses.add(shouldPassTestsMultithreadedThread2.class); + TestLauncher.launch(testClasses); + + verify(testObserver, times(1)).onTestSuccess(); + verify(testObserver, times(0)).onTestFailure(); + verify(testObserver, times(0)).onTestFinish(); + verify(testObserver, times(1)).onTestClassFinish(); + + verify(testObserverSecond, times(1)).onTestSuccess(); + verify(testObserverSecond, times(0)).onTestFailure(); + verify(testObserverSecond, times(0)).onTestFinish(); + verify(testObserverSecond, times(1)).onTestClassFinish(); + + assertThat(isBaseTestSetupCalled, is(equalTo(CALLED))); + assertThat(isBaseTestTeardownCalled, is(equalTo(CALLED))); + } + + @Feature("Running tests") + @Muted + public static class shouldPassTestsMultithreadedThread1 extends BaseTestWithHooks { + + @BeforeAll + public static void setUpClass() { + TEST_EXECUTION_OBSERVER.addObserver(testObserver); + } + + @Test + public void simpleTest() { + } + } + + @Feature("Running tests") + @Muted + public static class shouldPassTestsMultithreadedThread2 extends BaseTestWithHooks { + + @BeforeAll + public static void setUpClass() { + TEST_EXECUTION_OBSERVER.addObserver(testObserverSecond); + } + + @Test + public void simpleTest() { + } + } + + @Feature("Running tests") + @Muted + public static class FailingTestDueToFailingAssertion extends BaseTestWithHooks { + + @BeforeAll + public static void setUpClass() { + TEST_EXECUTION_OBSERVER.addObserver(testObserver); + } + + @Test + public void simpleTest() { + fail(); + } + } + + @Feature("Running tests") + @Muted + public static class FailingTestDueToExceptionInTestMethod extends BaseTestWithHooks { + + @BeforeAll + public static void setUpClass() { + TEST_EXECUTION_OBSERVER.addObserver(testObserver); + } + + @Test + public void simpleTest() { + throw new RuntimeException(); + } + } + + @Feature("Running tests") + @Muted + public static class FailingTestDueToExceptionInBeforeAll extends BaseTestWithHooks { + + @BeforeAll + public static void setUpClass() { + TEST_EXECUTION_OBSERVER.addObserver(testObserver); + throw new RuntimeException(); + } + + @Test + public void simpleTest() { + } + } + + @Feature("Running tests") + @Muted + public static class FailingTestDueToExceptionInBeforeEach extends BaseTestWithHooks { + + @BeforeAll + public static void setUpClass() { + TEST_EXECUTION_OBSERVER.addObserver(testObserver); + } + + @BeforeEach + public void setUp() { + throw new RuntimeException(); + } + + @Test + public void simpleTest() { + } + } + + @Feature("Running tests") + @Muted + public static class FailingTestThatPassedExecutionDueToExceptionInAfterEach extends BaseTestWithHooks { + + @BeforeAll + public static void setUpClass() { + TEST_EXECUTION_OBSERVER.addObserver(testObserver); + } + + @AfterEach + public void teardown() { + throw new RuntimeException(); + } + + @Test + public void simpleTest() { + } + } + + @Feature("Running tests") + @Muted + public static class FailingTestThatFailedExecutionDueToExceptionInAfterEach extends BaseTestWithHooks { + + @BeforeAll + public static void setUpClass() { + TEST_EXECUTION_OBSERVER.addObserver(testObserver); + } + + @AfterEach + public void teardown() { + throw new RuntimeException(); + } + + @Test + public void simpleTest() { + fail(); + } + } + + @Feature("Running tests") + @Muted + public static class FailingTestThatPassedExecutionDueToExceptionInAfterAll extends BaseTestWithHooks { + + @BeforeAll + public static void setUpClass() { + TEST_EXECUTION_OBSERVER.addObserver(testObserver); + } + + @AfterAll + public static void teardown() { + throw new RuntimeException(); + } + + @Test + public void simpleTest() { + } + } + + @Feature("Running tests") + @Muted + public static class FailingTestThatFailedExecutionDueToExceptionInAfterAll extends BaseTestWithHooks { + + @BeforeAll + public static void setUpClass() { + TEST_EXECUTION_OBSERVER.addObserver(testObserver); + } + + @AfterAll + public static void teardown() { + throw new RuntimeException(); + } + + @Test + public void simpleTest() { + fail(); + } + } + + @Feature("Running tests") + @Muted + public static class DisabledTestWithObserverAddedInTestMethod extends BaseTestWithHooks { + + @Disabled + @Test + public void simpleTest() { + TEST_EXECUTION_OBSERVER.addObserver(testObserver); + } + } + + @Feature("Running tests") + @Muted + public static class DisabledTestWithObserverAddedInBeforeAll extends BaseTestWithHooks { + + @BeforeAll + public static void setUpClass() { + TEST_EXECUTION_OBSERVER.addObserver(testObserver); + } + + @Disabled + @Test + public void simpleTest() { + + } + } + + @Feature("Running tests") + @Muted + public static class AbortTestWithObserverAddedInTestMethod extends BaseTestWithHooks { + + @Test + public void simpleTest() { + TEST_EXECUTION_OBSERVER.addObserver(testObserver); + assumeFalse(true, "For test purpose"); + } + } + + @Feature("Running tests") + @Muted + public static class AbortTestWithObserverAddedInBeforeAll extends BaseTestWithHooks { + + @BeforeAll + public static void setUpClass() { + TEST_EXECUTION_OBSERVER.addObserver(testObserver); + } + + @Test + public void simpleTest() { + assumeFalse(true, "For test purpose"); + } + } + + private static void printSummary(TestExecutionSummary summary) { + try (PrintWriter out = new PrintWriter(System.out)) { + summary.printTo(out); + } + } +} diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/integration/logger/LoggingTest.java b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/integration/logger/LoggingTest.java new file mode 100644 index 00000000..a8946218 --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/integration/logger/LoggingTest.java @@ -0,0 +1,218 @@ +package com.capgemini.mrchecker.test.core.integration.logger; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.hamcrest.core.IsNot.not; +import static org.hamcrest.core.IsNull.nullValue; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import org.junit.jupiter.api.Test; + +import com.capgemini.mrchecker.test.core.logger.BFLogger; +import com.capgemini.mrchecker.test.core.logger.BFLoggerInstance; +import com.capgemini.mrchecker.test.core.tags.IntegrationTest; +import com.capgemini.mrchecker.test.core.utils.FileUtils; + +@IntegrationTest +public class LoggingTest { + public static final String FEND = "END"; + + @Test + public void shouldGetLog() { + assertThat(BFLogger.getLog(), is(not(nullValue()))); + } + + @Test + public void shouldGetLogMultithreaded() throws InterruptedException { + ExecutorService executorService = Executors.newFixedThreadPool(2); + Collection> tasks = new ArrayList<>(); + tasks.add(new BFLoggerGetter()); + tasks.add(new BFLoggerGetter()); + + List> loggerInstances = executorService.invokeAll(tasks); + executorService.shutdown(); + executorService.awaitTermination(100, TimeUnit.MILLISECONDS); + + assertThat(loggerInstances.get(0), is(not(equalTo(loggerInstances.get(1))))); + } + + public static class BFLoggerGetter implements Callable { + + @Override + public BFLoggerInstance call() { + return BFLogger.getLog(); + } + } + + @Test + public void shouldLogInfo() throws IOException { + String message = getMessage("Info"); + + BFLogger.logInfo(message); + + String lastLogLine = FileUtils.getLastLineInFile(FileUtils.getLogFilePath()); + assertThat(lastLogLine, containsString(message)); + assertThat(lastLogLine, containsString("logInfo")); + } + + @Test + public void shouldLogDebug() throws IOException { + String message = getMessage("Debug"); + + BFLogger.logDebug(message); + + String lastLogLine = FileUtils.getLastLineInFile(FileUtils.getLogFilePath()); + assertThat(lastLogLine, containsString(message)); + assertThat(lastLogLine, containsString("logDebug")); + } + + @Test + public void shouldLogAnalytics() throws IOException { + String message = getMessage("Analytics"); + + BFLogger.logAnalytics(message); + + String lastLogLine = FileUtils.getLastLineInFile(FileUtils.getLogFilePath()); + assertThat(lastLogLine, containsString(message)); + assertThat(lastLogLine, containsString("logAnalytics")); + } + + @Test + public void shouldLogFunctionBegin() throws IOException { + String message = getMessage("Function begin"); + + BFLogger.logFunctionBegin(message); + + String lastLogLine = FileUtils.getLastLineInFile(FileUtils.getLogFilePath()); + assertThat(lastLogLine, containsString(message)); + assertThat(lastLogLine, containsString("logDebug")); + assertThat(lastLogLine, containsString("Function: ")); + } + + @Test + public void shouldLogFunctionEnd() throws IOException { + BFLogger.logFunctionBegin("Function begin"); + + BFLogger.logFunctionEnd(); + + String lastLogLine = FileUtils.getLastLineInFile(FileUtils.getLogFilePath()); + assertThat(lastLogLine, containsString("END")); + assertThat(lastLogLine, containsString("logDebug")); + } + + @Test + public void shouldLogError() throws IOException { + String message = getMessage("Error"); + + BFLogger.logError(message); + + String lastLogLine = FileUtils.getLastLineInFile(FileUtils.getLogFilePath()); + assertThat(lastLogLine, containsString(message)); + assertThat(lastLogLine, containsString("logError")); + } + + @Test + public void shouldLogErrorWithEnd() throws IOException { + BFLogger.logFunctionBegin("Function begin"); + + BFLogger.logError(FEND); + + String lastLogLine = FileUtils.getLastLineInFile(FileUtils.getLogFilePath()); + assertThat(lastLogLine, containsString(FEND)); + assertThat(lastLogLine, containsString("logError")); + } + + @Test + public void shouldLogEnv() throws IOException { + String message = getMessage("Env"); + + BFLogger.logEnv(message); + + String lastLogLine = FileUtils.getLastLineInFile(FileUtils.getEnvLogFilePath()); + assertThat(lastLogLine, containsString(message)); + assertThat(lastLogLine, containsString("logEnv")); + + lastLogLine = FileUtils.getLastLineInFile(FileUtils.getLogFilePath()); + assertThat(lastLogLine, containsString(message)); + assertThat(lastLogLine, containsString("logEnv")); + } + + @Test + public void shouldLogEnvWithEnd() throws IOException { + BFLogger.logFunctionBegin("Function begin"); + + BFLogger.logEnv(FEND); + + String lastLogLine = FileUtils.getLastLineInFile(FileUtils.getEnvLogFilePath()); + assertThat(lastLogLine, containsString(FEND)); + assertThat(lastLogLine, containsString("logEnv")); + + lastLogLine = FileUtils.getLastLineInFile(FileUtils.getLogFilePath()); + assertThat(lastLogLine, containsString(FEND)); + assertThat(lastLogLine, containsString("logEnv")); + } + + @Test + public void shouldLogTime() throws IOException { + long startTime = System.currentTimeMillis(); + String message = getMessage("Method name"); + + BFLogger.logTime(startTime, message); + + String lastLogLine = FileUtils.getLastLineInFile(FileUtils.getLogFilePath()); + assertThat(lastLogLine, containsString("Waiting for [" + message + "] took")); + assertThat(lastLogLine, containsString("logDebug")); + } + + @Test + public void shouldLogTimeWithArgument() throws IOException { + long startTime = System.currentTimeMillis(); + String message = getMessage("Method name"); + + BFLogger.logTime(startTime, message, "Argument"); + + String lastLogLine = FileUtils.getLastLineInFile(FileUtils.getLogFilePath()); + assertThat(lastLogLine, containsString("Waiting for [" + message + ": Argument] took")); + assertThat(lastLogLine, containsString("logDebug")); + } + + private static String getMessage(String message) { + return System.currentTimeMillis() + "_" + message; + } + + @Test + public void shouldDumpLogFile() throws IOException { + shouldLogDebug(); + + String[] logDump = BFLogger.RestrictedMethods.dumpSeparateLog() + .split(System.lineSeparator()); + + assertThat(logDump[0], is(equalTo(FileUtils.getFirstLineInFile(FileUtils.getLogFilePath())))); + assertThat(logDump[logDump.length - 1], is(equalTo(FileUtils.getLastLineInFile(FileUtils.getLogFilePath())))); + } + + @Test + public void shouldStartNewLogFile() throws IOException { + shouldLogDebug(); + shouldLogDebug(); + + BFLogger.RestrictedMethods.startSeparateLog(); + shouldLogDebug(); + + assertThat(Files.lines(Paths.get(FileUtils.getLogFilePath())) + .count(), is(equalTo(1L))); + } +} \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/tags/IntegrationTest.java b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/tags/IntegrationTest.java new file mode 100644 index 00000000..0c251fca --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/tags/IntegrationTest.java @@ -0,0 +1,14 @@ +package com.capgemini.mrchecker.test.core.tags; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import org.junit.jupiter.api.Tag; + +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +@Tag("IntegrationTest") +public @interface IntegrationTest { +} \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/tags/UnitTest.java b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/tags/UnitTest.java new file mode 100644 index 00000000..76981df9 --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/tags/UnitTest.java @@ -0,0 +1,14 @@ +package com.capgemini.mrchecker.test.core.tags; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import org.junit.jupiter.api.Tag; + +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +@Tag("UnitTest") +public @interface UnitTest { +} \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/testsuites/AllTests.java b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/testsuites/AllTests.java new file mode 100644 index 00000000..6b01f555 --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/testsuites/AllTests.java @@ -0,0 +1,12 @@ +package com.capgemini.mrchecker.test.core.testsuites; + +import org.junit.platform.runner.JUnitPlatform; +import org.junit.platform.suite.api.IncludeTags; +import org.junit.platform.suite.api.SelectPackages; +import org.junit.runner.RunWith; + +@RunWith(JUnitPlatform.class) +@IncludeTags({ "UnitTest", "IntegrationTest" }) +@SelectPackages("com.capgemini.mrchecker.test.core") +public class AllTests { +} diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/testsuites/IntegrationTests.java b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/testsuites/IntegrationTests.java new file mode 100644 index 00000000..6022e1e3 --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/testsuites/IntegrationTests.java @@ -0,0 +1,12 @@ +package com.capgemini.mrchecker.test.core.testsuites; + +import org.junit.platform.runner.JUnitPlatform; +import org.junit.platform.suite.api.IncludeTags; +import org.junit.platform.suite.api.SelectPackages; +import org.junit.runner.RunWith; + +@RunWith(JUnitPlatform.class) +@IncludeTags({ "IntegrationTest" }) +@SelectPackages("com.capgemini.mrchecker.test.core") +public class IntegrationTests { +} diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/testsuites/UnitTests.java b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/testsuites/UnitTests.java new file mode 100644 index 00000000..2d79230f --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/testsuites/UnitTests.java @@ -0,0 +1,12 @@ +package com.capgemini.mrchecker.test.core.testsuites; + +import org.junit.platform.runner.JUnitPlatform; +import org.junit.platform.suite.api.IncludeTags; +import org.junit.platform.suite.api.SelectPackages; +import org.junit.runner.RunWith; + +@RunWith(JUnitPlatform.class) +@IncludeTags({ "UnitTest" }) +@SelectPackages("com.capgemini.mrchecker.test.core") +public class UnitTests { +} diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/BaseTestTest.java b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/BaseTestTest.java new file mode 100644 index 00000000..746ebf8b --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/BaseTestTest.java @@ -0,0 +1,57 @@ +package com.capgemini.mrchecker.test.core.unit; + +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.hamcrest.core.IsNot.not; +import static org.hamcrest.core.IsNull.nullValue; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.ResourceLock; + +import com.capgemini.mrchecker.test.core.BaseTest; +import com.capgemini.mrchecker.test.core.analytics.AnalyticsProvider; +import com.capgemini.mrchecker.test.core.base.environment.IEnvironmentService; +import com.capgemini.mrchecker.test.core.tags.UnitTest; + +@UnitTest +@ResourceLock(value = "SingleThread") +public class BaseTestTest { + + @Test + public void shouldGetAnalyticsReturnDisabled() { + assertThat(BaseTest.getAnalytics(), is(equalTo(AnalyticsProvider.DISABLED))); + } + + @Test + public void shouldGetEnvironmentServiceReturnInstance() { + assertThat(BaseTest.getEnvironmentService(), is(not(nullValue()))); + } + + @Test + public void shouldSetEnvironmentServiceReturnInstance() { + IEnvironmentService envServiceMock = mock(IEnvironmentService.class); + + BaseTest.setEnvironmentService(envServiceMock); + + assertThat(BaseTest.getEnvironmentService(), is(equalTo(envServiceMock))); + } + + @Test + public void shouldCallSetUp() { + new BaseTest() { + }.setUp(); + + assertTrue(true); + } + + @Test + public void shouldCallTearDown() { + new BaseTest() { + }.tearDown(); + + assertTrue(true); + } +} \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/BasicBuildTest.java b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/BasicBuildTest.java deleted file mode 100644 index 6808483c..00000000 --- a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/BasicBuildTest.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.capgemini.mrchecker.test.core.unit; - -import static org.junit.Assert.assertTrue; - -import org.junit.Ignore; -import org.junit.Test; - -import com.capgemini.mrchecker.test.core.BaseTest; - -@Ignore -public class BasicBuildTest extends BaseTest { - - @Test - public void test() { - assertTrue(true); - } - - @Test - public void test2() { - assertTrue(true); - } - - @Test - public void test3() { - assertTrue(true); - } - - @Override - public void setUp() { - // TODO Auto-generated method stub - - } - - @Override - public void tearDown() { - // TODO Auto-generated method stub - - } - -} diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/LoggerTest.java b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/LoggerTest.java deleted file mode 100644 index 4db884fa..00000000 --- a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/LoggerTest.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.capgemini.mrchecker.test.core.unit; - -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; - -import com.capgemini.mrchecker.test.core.BaseTest; -import com.capgemini.mrchecker.test.core.logger.BFLogger; - -@Ignore -public class LoggerTest extends BaseTest { - - @BeforeClass - public static void beforeClass() { - System.out.println("LoggerTest.beforeClass()"); - BFLogger.logDebug("LoggerTest.beforeClass()"); - } - - @Test - public void testPassed() throws InterruptedException { - BFLogger.logDebug("Debug-TestPassed"); - BFLogger.logError("Error-TestPassed"); - BFLogger.logInfo("Info-TestPassed"); - } - - @Test - public void testFailed() throws Exception { - BFLogger.logDebug("Debug-TestFailed"); - BFLogger.logError("Error-TestFailed"); - BFLogger.logInfo("Info-TestFailed"); - } - - @AfterClass - public static void afterClass() { - System.out.println("LoggerTest.afterClass()"); - BFLogger.logDebug("LoggerTest.afterClass()"); - } - - @Override - public void setUp() { - System.out.println("LoggerTest.setUp()"); - BFLogger.logDebug("LoggerTest.setUp()"); - } - - @Override - public void tearDown() { - System.out.println("LoggerTest.tearDown()"); - BFLogger.logDebug("LoggerTest.tearDown()"); - } - -} diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/ModuleTypeTest.java b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/ModuleTypeTest.java new file mode 100644 index 00000000..c96fd015 --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/ModuleTypeTest.java @@ -0,0 +1,21 @@ +package com.capgemini.mrchecker.test.core.unit; + +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsNull.notNullValue; +import static org.junit.Assert.assertThat; + +import org.junit.jupiter.api.Test; + +import com.capgemini.mrchecker.test.core.ModuleType; +import com.capgemini.mrchecker.test.core.tags.UnitTest; + +@UnitTest +public class ModuleTypeTest { + + @Test + public void shouldGetEnum() { + ModuleType sut = ModuleType.DATABASE; + + assertThat(sut, is(notNullValue())); + } +} diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/PageTest.java b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/PageTest.java new file mode 100644 index 00000000..e6b5ae8f --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/PageTest.java @@ -0,0 +1,68 @@ +package com.capgemini.mrchecker.test.core.unit; + +import static org.hamcrest.Matchers.containsString; +import static org.junit.Assert.assertThat; + +import java.io.IOException; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.ResourceLock; + +import com.capgemini.mrchecker.test.core.ModuleType; +import com.capgemini.mrchecker.test.core.Page; +import com.capgemini.mrchecker.test.core.tags.UnitTest; +import com.capgemini.mrchecker.test.core.utils.FileUtils; + +@UnitTest +@ResourceLock(value = "SingleThread") +public class PageTest { + + private static final Page SUT = new TestPage(); + private static final String logFilePath = FileUtils.getLogFilePath(); + + @Test + public void shouldCallOnTestSuccess() throws IOException { + SUT.onTestSuccess(); + + assertThat(FileUtils.getLastLineInFile(logFilePath), containsString("Page.onTestSuccess " + SUT.getClass() + .getSimpleName())); + } + + @Test + public void shouldCallOnTestFailure() throws IOException { + SUT.onTestFailure(); + + assertThat(FileUtils.getLastLineInFile(logFilePath), containsString("Page.onTestFailure " + SUT.getClass() + .getSimpleName())); + } + + @Test + public void shouldCallOnTestFinish() throws IOException { + SUT.onTestFinish(); + + assertThat(FileUtils.getLastLineInFile(logFilePath), containsString("To remove observer: " + SUT.toString())); + } + + @Test + public void shouldCallOnTestClassFinish() throws IOException { + SUT.onTestClassFinish(); + + assertThat(FileUtils.getLastLineInFile(logFilePath), containsString("Page.onTestClassFinish " + SUT.getClass() + .getSimpleName())); + } + + @Test + public void shouldRegister() throws IOException { + SUT.addToTestExecutionObserver(); + + assertThat(FileUtils.getLastLineInFile(logFilePath), containsString("Added observer: " + SUT.toString())); + } + + public static class TestPage extends Page { + @Override + public ModuleType getModuleType() { + return ModuleType.CORE; + } + } + +} diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/TestExecutionClassObserverAfterAllTest.java b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/TestExecutionClassObserverAfterAllTest.java new file mode 100644 index 00000000..fdc6aa1a --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/TestExecutionClassObserverAfterAllTest.java @@ -0,0 +1,41 @@ +package com.capgemini.mrchecker.test.core.unit; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.mockito.Mockito.clearInvocations; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import java.io.IOException; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.capgemini.mrchecker.test.core.utils.FileUtils; + +public class TestExecutionClassObserverAfterAllTest extends TestExecutionObserverBaseTest { + + @BeforeAll + public static void setUpClass() { + SUT.addObserver(observerMock); + } + + @BeforeEach + public void setUp() { + clearInvocations(observerMock); + } + + @Test + public void shouldCallAfterAll() throws IOException { + SUT.afterAll(contextMock); + + verify(observerMock, times(1)).onTestClassFinish(); + assertThat(FileUtils.getAllLinesInFile(FileUtils.getLogFilePath()), containsString("All observers cleared.")); + + SUT.testSuccessful(contextMock); + + verify(observerMock, times(0)).onTestSuccess(); + verify(observerMock, times(0)).onTestFinish(); + } +} diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/TestExecutionClassObserverRemoveTest.java b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/TestExecutionClassObserverRemoveTest.java new file mode 100644 index 00000000..045d18f9 --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/TestExecutionClassObserverRemoveTest.java @@ -0,0 +1,32 @@ +package com.capgemini.mrchecker.test.core.unit; + +import static org.mockito.Mockito.clearInvocations; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class TestExecutionClassObserverRemoveTest extends TestExecutionObserverBaseTest { + + @BeforeAll + public static void setUpClass() { + SUT.addObserver(observerMock); + } + + @BeforeEach + public void setUp() { + clearInvocations(observerMock); + } + + @Test + public void shouldRemoveObserver() { + SUT.removeObserver(observerMock); + + SUT.testSuccessful(contextMock); + + verify(observerMock, times(0)).onTestSuccess(); + verify(observerMock, times(0)).onTestFinish(); + } +} diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/TestExecutionClassObserverTest.java b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/TestExecutionClassObserverTest.java new file mode 100644 index 00000000..33ee792d --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/TestExecutionClassObserverTest.java @@ -0,0 +1,147 @@ +package com.capgemini.mrchecker.test.core.unit; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.hamcrest.core.IsNull.notNullValue; +import static org.hamcrest.core.StringContains.containsString; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.clearInvocations; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import java.io.IOException; +import java.util.Optional; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.capgemini.mrchecker.test.core.TestExecutionObserver; +import com.capgemini.mrchecker.test.core.utils.FileUtils; + +public class TestExecutionClassObserverTest extends TestExecutionObserverBaseTest { + + @BeforeAll + public static void setUpClass() { + SUT.addObserver(observerMock); + } + + @BeforeEach + public void setUp() { + clearInvocations(observerMock); + } + + @AfterAll + public static void tearDown() { + SUT.afterAll(contextMock); + } + + @Test + public void shouldGetInstance() { + assertThat(TestExecutionObserver.getInstance(), is(notNullValue())); + } + + @Test + public void shouldGetInstanceTwice() { + TestExecutionObserver secondRef = TestExecutionObserver.getInstance(); + + assertThat(secondRef, is(equalTo(SUT))); + } + + @Test + public void shouldCallBeforeAll() throws IOException { + SUT.beforeAll(contextMock); + + assertThat(FileUtils.getAllLinesInFile(FileUtils.getLogFilePath()), containsString("- CLASS STARTED.")); + } + + @Test + public void shouldCallBeforeTestExecution() throws IOException { + SUT.beforeTestExecution(contextMock); + + assertThat(FileUtils.getAllLinesInFile(FileUtils.getLogFilePath()), containsString("- STARTED.")); + } + + @Test + public void shouldCallAfterTestExecution() throws IOException { + SUT.afterTestExecution(contextMock); + + assertThat(FileUtils.getAllLinesInFile(FileUtils.getLogFilePath()), containsString("- FINISHED.")); + } + + @Test + public void shouldCallTestDisabled() throws IOException { + SUT.testDisabled(contextMock, Optional.of("Test_reason")); + + assertThat(FileUtils.getAllLinesInFile(FileUtils.getLogFilePath()), containsString("- DISABLED.")); + } + + @Test + public void shouldCallTestAborted() throws IOException { + SUT.testAborted(contextMock, new RuntimeException("Test_Exception")); + + assertThat(FileUtils.getAllLinesInFile(FileUtils.getLogFilePath()), containsString("- ABORTED.")); + verify(observerMock, times(0)).onTestFinish(); + } + + @Test + public void shouldCallTestSuccessful() throws IOException { + SUT.testSuccessful(contextMock); + + assertThat(FileUtils.getAllLinesInFile(FileUtils.getLogFilePath()), containsString("- PASSED.")); + verify(observerMock, times(1)).onTestSuccess(); + verify(observerMock, times(0)).onTestFinish(); + } + + @Test + public void shouldCallTestFailed() throws IOException { + SUT.testFailed(contextMock, new RuntimeException("Test_Exception")); + + assertThat(FileUtils.getAllLinesInFile(FileUtils.getLogFilePath()), containsString("- FAILED.")); + verify(observerMock, times(1)).onTestFailure(); + verify(observerMock, times(0)).onTestFinish(); + } + + @Test + public void shouldCallHandleBeforeAllMethodExecutionException() throws Throwable { + assertThrows(RuntimeException.class, () -> SUT.handleBeforeAllMethodExecutionException(contextMock, new RuntimeException())); + assertThat(FileUtils.getAllLinesInFile(FileUtils.getLogFilePath()), containsString("- EXCEPTION in @BeforeAll:")); + } + + @Test + public void shouldCallHandleBeforeEachMethodExecutionException() throws Throwable { + assertThrows(RuntimeException.class, () -> SUT.handleBeforeEachMethodExecutionException(contextMock, new RuntimeException())); + assertThat(FileUtils.getAllLinesInFile(FileUtils.getLogFilePath()), containsString("- EXCEPTION in @BeforeEach:")); + } + + @Test + public void shouldCallHandleTestExecutionException() throws Throwable { + assertThrows(RuntimeException.class, () -> SUT.handleTestExecutionException(contextMock, new RuntimeException())); + assertThat(FileUtils.getAllLinesInFile(FileUtils.getLogFilePath()), containsString("- EXCEPTION in @Test:")); + } + + @Test + public void shouldCallHandleAfterEachMethodExecutionException() throws Throwable { + assertThrows(RuntimeException.class, () -> SUT.handleAfterEachMethodExecutionException(contextMock, new RuntimeException())); + assertThat(FileUtils.getAllLinesInFile(FileUtils.getLogFilePath()), containsString("- EXCEPTION in @AfterEach:")); + } + + @Test + public void shouldCallHandleAfterAllMethodExecutionException() throws Throwable { + if (TestExecutionObserver.DONT_CONSUME_EXCEPTION_IN_AFTERALL) { + assertThrows(RuntimeException.class, () -> SUT.handleAfterAllMethodExecutionException(contextMock, new RuntimeException())); + } else { + SUT.handleAfterAllMethodExecutionException(contextMock, new RuntimeException()); + } + assertThat(FileUtils.getAllLinesInFile(FileUtils.getLogFilePath()), containsString("- EXCEPTION in @AfterAll:")); + } + + @Test + public void shouldAddObserverTwiceHaveNoEffect() throws IOException { + SUT.addObserver(observerMock); + + shouldCallTestSuccessful(); + } +} diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/TestExecutionObserverBaseTest.java b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/TestExecutionObserverBaseTest.java new file mode 100644 index 00000000..affe304a --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/TestExecutionObserverBaseTest.java @@ -0,0 +1,32 @@ +package com.capgemini.mrchecker.test.core.unit; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.Optional; + +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.parallel.ResourceLock; + +import com.capgemini.mrchecker.test.core.ITestObserver; +import com.capgemini.mrchecker.test.core.ModuleType; +import com.capgemini.mrchecker.test.core.TestExecutionObserver; +import com.capgemini.mrchecker.test.core.tags.UnitTest; + +@UnitTest +@ResourceLock(value = "TestExecutionObserver") +public class TestExecutionObserverBaseTest { + protected static final TestExecutionObserver SUT = TestExecutionObserver.getInstance(); + protected static final ExtensionContext contextMock; + protected static final ITestObserver observerMock; + + static { + contextMock = mock(ExtensionContext.class); + when(contextMock.getTestClass()).thenReturn(Optional.of(TestExecutionObserverBaseTest.class)); + when(contextMock.getRequiredTestClass()).thenCallRealMethod(); + when(contextMock.getDisplayName()).thenReturn("Test_name"); + + observerMock = mock(ITestObserver.class); + when(observerMock.getModuleType()).thenReturn(ModuleType.CORE); + } +} diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/TestExecutionObserverTest.java b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/TestExecutionObserverTest.java new file mode 100644 index 00000000..ee6ae7f9 --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/TestExecutionObserverTest.java @@ -0,0 +1,195 @@ +package com.capgemini.mrchecker.test.core.unit; + +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.hamcrest.core.IsNull.notNullValue; +import static org.hamcrest.core.StringContains.containsString; +import static org.junit.Assert.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.clearInvocations; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.util.Optional; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.parallel.ResourceLock; + +import com.capgemini.mrchecker.test.core.ITestObserver; +import com.capgemini.mrchecker.test.core.ModuleType; +import com.capgemini.mrchecker.test.core.TestExecutionObserver; +import com.capgemini.mrchecker.test.core.tags.UnitTest; +import com.capgemini.mrchecker.test.core.utils.FileUtils; + +@UnitTest +@ResourceLock(value = "TestExecutionObserver") +public class TestExecutionObserverTest { + private static final TestExecutionObserver SUT = TestExecutionObserver.getInstance(); + private static final ExtensionContext contextMock; + private static final ITestObserver observerMock; + + static { + contextMock = mock(ExtensionContext.class); + when(contextMock.getTestClass()).thenReturn(Optional.of(TestExecutionObserverTest.class)); + when(contextMock.getRequiredTestClass()).thenCallRealMethod(); + when(contextMock.getDisplayName()).thenReturn("Test_name"); + + observerMock = mock(ITestObserver.class); + when(observerMock.getModuleType()).thenReturn(ModuleType.CORE); + } + + @BeforeEach + public void setUp() { + SUT.addObserver(observerMock); + clearInvocations(observerMock); + } + + @AfterEach + public void tearDown() { + SUT.afterAll(contextMock); + } + + @Test + public void shouldGetInstance() { + assertThat(TestExecutionObserver.getInstance(), is(notNullValue())); + } + + @Test + public void shouldGetInstanceTwice() { + TestExecutionObserver secondRef = TestExecutionObserver.getInstance(); + + assertThat(secondRef, is(equalTo(SUT))); + } + + @Test + public void shouldCallBeforeAll() throws IOException { + SUT.beforeAll(contextMock); + + assertThat(FileUtils.getAllLinesInFile(FileUtils.getLogFilePath()), containsString("- CLASS STARTED.")); + } + + @Test + public void shouldCallBeforeTestExecution() throws IOException { + SUT.beforeTestExecution(contextMock); + + assertThat(FileUtils.getAllLinesInFile(FileUtils.getLogFilePath()), containsString("- STARTED.")); + } + + @Test + public void shouldCallAfterTestExecution() throws IOException { + SUT.afterTestExecution(contextMock); + + assertThat(FileUtils.getAllLinesInFile(FileUtils.getLogFilePath()), containsString("- FINISHED.")); + } + + @Test + public void shouldCallTestDisabled() throws IOException { + SUT.testDisabled(contextMock, Optional.of("Test_reason")); + + assertThat(FileUtils.getAllLinesInFile(FileUtils.getLogFilePath()), containsString("- DISABLED.")); + } + + @Test + public void shouldCallTestAborted() throws IOException { + SUT.testAborted(contextMock, new RuntimeException("Test_Exception")); + + assertThat(FileUtils.getAllLinesInFile(FileUtils.getLogFilePath()), containsString("- ABORTED.")); + verify(observerMock, times(1)).onTestFinish(); + } + + @Test + public void shouldCallTestSuccessful() throws IOException { + SUT.testSuccessful(contextMock); + + assertThat(FileUtils.getAllLinesInFile(FileUtils.getLogFilePath()), containsString("- PASSED.")); + verify(observerMock, times(1)).onTestSuccess(); + verify(observerMock, times(1)).onTestFinish(); + } + + @Test + public void shouldCallTestFailed() throws IOException { + SUT.testFailed(contextMock, new RuntimeException("Test_Exception")); + + assertThat(FileUtils.getAllLinesInFile(FileUtils.getLogFilePath()), containsString("- FAILED.")); + verify(observerMock, times(1)).onTestFailure(); + verify(observerMock, times(1)).onTestFinish(); + } + + @Test + public void shouldCallAfterAll() throws IOException { + SUT.afterAll(contextMock); + + verify(observerMock, times(1)).onTestClassFinish(); + assertThat(FileUtils.getAllLinesInFile(FileUtils.getLogFilePath()), containsString("All observers cleared.")); + } + + @Test + public void shouldCallHandleBeforeAllMethodExecutionException() throws Throwable { + assertThrows(RuntimeException.class, () -> SUT.handleBeforeAllMethodExecutionException(contextMock, new RuntimeException("Test purpose exception"))); + assertThat(FileUtils.getAllLinesInFile(FileUtils.getLogFilePath()), containsString("- EXCEPTION in @BeforeAll:")); + } + + @Test + public void shouldCallHandleBeforeEachMethodExecutionException() throws Throwable { + assertThrows(RuntimeException.class, () -> SUT.handleBeforeEachMethodExecutionException(contextMock, new RuntimeException("Test purpose exception"))); + assertThat(FileUtils.getAllLinesInFile(FileUtils.getLogFilePath()), containsString("- EXCEPTION in @BeforeEach:")); + } + + @Test + public void shouldCallHandleTestExecutionException() throws Throwable { + assertThrows(RuntimeException.class, () -> SUT.handleTestExecutionException(contextMock, new RuntimeException("Test purpose exception"))); + assertThat(FileUtils.getAllLinesInFile(FileUtils.getLogFilePath()), containsString("- EXCEPTION in @Test:")); + } + + @Test + public void shouldCallHandleAfterEachMethodExecutionException() throws Throwable { + assertThrows(RuntimeException.class, () -> SUT.handleAfterEachMethodExecutionException(contextMock, new RuntimeException("Test purpose exception"))); + assertThat(FileUtils.getAllLinesInFile(FileUtils.getLogFilePath()), containsString("- EXCEPTION in @AfterEach:")); + } + + @Test + public void shouldCallHandleAfterAllMethodExecutionException() throws Throwable { + if (TestExecutionObserver.DONT_CONSUME_EXCEPTION_IN_AFTERALL) { + assertThrows(RuntimeException.class, () -> SUT.handleAfterAllMethodExecutionException(contextMock, new RuntimeException("Test purpose exception"))); + } else { + SUT.handleAfterAllMethodExecutionException(contextMock, new RuntimeException("Test purpose exception")); + } + assertThat(FileUtils.getAllLinesInFile(FileUtils.getLogFilePath()), containsString("- EXCEPTION in @AfterAll:")); + } + + @Test + public void shouldClearAndAddObserver() { + SUT.afterAll(contextMock); + + SUT.testSuccessful(contextMock); + + verify(observerMock, times(0)).onTestSuccess(); + verify(observerMock, times(0)).onTestFinish(); + + SUT.addObserver(observerMock); + + SUT.testSuccessful(contextMock); + verify(observerMock, times(1)).onTestSuccess(); + verify(observerMock, times(1)).onTestFinish(); + } + + @Test + public void shouldAddObserverTwiceHaveNoEffect() throws IOException { + SUT.addObserver(observerMock); + + shouldCallTestSuccessful(); + } + + @Test + public void shouldRemoveObserverTwiceHaveNoEffect() throws IOException { + SUT.removeObserver(observerMock); + + shouldCallTestSuccessful(); + } +} diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/TestWatcherExceptionTest.java b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/TestWatcherExceptionTest.java deleted file mode 100644 index e0888d2d..00000000 --- a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/TestWatcherExceptionTest.java +++ /dev/null @@ -1,223 +0,0 @@ -package com.capgemini.mrchecker.test.core.unit; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.Computer; -import org.junit.runner.JUnitCore; -import org.junit.runner.notification.Failure; -import org.junit.runner.notification.RunListener; - -import com.capgemini.mrchecker.test.core.BaseTest; -import com.capgemini.mrchecker.test.core.exceptions.BFInputDataException; -import com.capgemini.mrchecker.test.core.logger.BFLogger; - -/** - * Class tests if exceptions thrown in each of method invoked in BaseTest lead to proper behavior (e.g. stop running). - * Methods being tested: - *

  • @BeforeClass method
  • - *
  • setUp() method
  • - *
  • sample test method
  • - *
  • tearDown() method
  • - *
  • @AfterClass() method
  • Assertion check if exception thrown in test is initialized or object is null/not null - * what indicate program run stopped/run further - */ - -@Ignore -public class TestWatcherExceptionTest { - private static Computer computer; - private static JUnitCore jUnitCore; - private static Throwable thrownException; - private static Object object; - - @BeforeClass - public static void initJUnit() { - BFLogger.logInfo("Starting base test"); - computer = new Computer(); - jUnitCore = new JUnitCore(); - jUnitCore.addListener(new RunListener() { - @Override - public void testFailure(Failure failure) throws Exception { - thrownException = failure.getException(); - BFLogger.logInfo("An exception has been thrown: " + thrownException.getMessage()); - } - }); - } - - private void resetValues() { - thrownException = null; - object = null; - } - - @Test - public void setupClassExceptionTest() { - resetValues(); - try { - jUnitCore.run(computer, SetUpClassExceptionTest.class); - } catch (BFInputDataException e) { - } - assertNotNull("There was no exception thrown in test", thrownException); - assertNull("Object is not null - program run further after exception, what is wrong behaviour", object); - } - - @Test - public void setupExceptionTest() { - resetValues(); - try { - jUnitCore.run(computer, SetUpExceptionTest.class); - } catch (BFInputDataException e) { - } - assertNotNull("There was no exception thrown in test", thrownException); - assertNull("Object is not null - program run further after exception what is wrong behaviour", object); - } - - @Test - public void testMethodExceptionTest() { - resetValues(); - try { - jUnitCore.run(computer, TestMethodExceptionTest.class); - } catch (BFInputDataException e) { - } - assertNotNull("There was no exception thrown in test", thrownException); - assertNotNull("Object is null - program didn't run further after exception what implicate test watcher logic was rebuild", object); - } - - @Test - public void tearDownExceptionTest() { - resetValues(); - try { - jUnitCore.run(computer, TearDownExceptionTest.class); - } catch (BFInputDataException e) { - } - assertNotNull("There was no exception thrown in test", thrownException); - assertNotNull("Object is null - program didn't run further after exception what implicate test watcher logic was rebuild", object); - } - - @Test - public void tearDownClassExceptionTest() { - resetValues(); - try { - jUnitCore.run(computer, TearDownClassExceptionTest.class); - } catch (BFInputDataException e) { - } - assertNotNull("Object is null - program didn't run further after exception what implicate test watcher logic was rebuild", object); - } - - @Ignore - public static class SetUpClassExceptionTest extends BaseTest { - - @BeforeClass - public static void setUpClazz() { - BFLogger.logInfo(SetUpClassExceptionTest.class.getCanonicalName() + " -> setUpClazz()"); - throw new BFInputDataException("Text exception"); - } - - @Override - public void setUp() { - object = null; - } - - @Test - public void testMethod() { - } - - @Override - public void tearDown() { - } - - } - - @Ignore - public static class SetUpExceptionTest extends BaseTest { - - @Override - public void setUp() { - BFLogger.logInfo(this.getClass() - .getCanonicalName() + " -> setUp()"); - throw new BFInputDataException("Text exception"); - } - - @Test - public void testMethod() { - } - - @Override - public void tearDown() { - object = new Object(); - } - - } - - @Ignore - public static class TestMethodExceptionTest extends BaseTest { - - @Override - public void setUp() { - } - - @Test - public void testMethod() { - BFLogger.logInfo(this.getClass() - .getCanonicalName() + " -> testMethod()"); - throw new BFInputDataException("Text exception"); - } - - @Override - public void tearDown() { - object = new Object(); - } - - } - - @Ignore - public static class TearDownExceptionTest extends BaseTest { - - @Override - public void setUp() { - } - - @Test - public void testMethod() { - } - - @Override - public void tearDown() { - BFLogger.logInfo(this.getClass() - .getCanonicalName() + " -> tearDown()"); - throw new BFInputDataException("Text exception"); - } - - @AfterClass - public static void tearDownClazz() { - object = new Object(); - } - } - - @Ignore - public static class TearDownClassExceptionTest extends BaseTest { - - @Override - public void setUp() { - } - - @Test - public void testMethod() { - } - - @Override - public void tearDown() { - object = new Object(); - } - - @AfterClass - public static void tearDownClazz() { - BFLogger.logInfo(TearDownClassExceptionTest.class.getCanonicalName() + " -> tearDownClazz()"); - throw new BFInputDataException("Text exception"); - } - } - -} diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/analytics/AnalyticsProviderTest.java b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/analytics/AnalyticsProviderTest.java new file mode 100644 index 00000000..15e8a946 --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/analytics/AnalyticsProviderTest.java @@ -0,0 +1,27 @@ +package com.capgemini.mrchecker.test.core.unit.analytics; + +import org.junit.jupiter.api.Test; + +import com.capgemini.mrchecker.test.core.analytics.AnalyticsProvider; +import com.capgemini.mrchecker.test.core.tags.UnitTest; + +@UnitTest +public class AnalyticsProviderTest { + + public static final String DEFAULT_CATEGORY = "DEFAULT_CATEGORY"; + + @Test + public void shouldDisabledAnalyticsSetInstanceDoNothing() { + AnalyticsProvider.DISABLED.setInstance(); + } + + @Test + public void shouldDisabledAnalyticsSendClassNameDoNothing() { + AnalyticsProvider.DISABLED.sendClassName(); + } + + @Test + public void shouldDisabledAnalyticsSendMethodEventDoNothing() { + AnalyticsProvider.DISABLED.sendMethodEvent(DEFAULT_CATEGORY); + } +} diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/base/encryption/DataEncryptionModuleTest.java b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/base/encryption/DataEncryptionModuleTest.java new file mode 100644 index 00000000..b6d937a4 --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/base/encryption/DataEncryptionModuleTest.java @@ -0,0 +1,47 @@ +package com.capgemini.mrchecker.test.core.unit.base.encryption; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.core.IsNull.notNullValue; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.ResourceLock; + +import com.capgemini.mrchecker.test.core.base.encryption.DataEncryptionModule; +import com.capgemini.mrchecker.test.core.base.encryption.IDataEncryptionService; +import com.capgemini.mrchecker.test.core.base.encryption.providers.DataEncryptionService; +import com.capgemini.mrchecker.test.core.exceptions.BFSecureModuleException; +import com.capgemini.mrchecker.test.core.tags.UnitTest; +import com.google.inject.Guice; + +@UnitTest +@ResourceLock(value = "SingleThread") +public class DataEncryptionModuleTest { + public static final String NO_FILE_PATH = "no file path"; + + @BeforeAll + public static void setUpClass() { + DataEncryptionService.delInstance(); + } + + @AfterEach + public void tearDown() { + DataEncryptionService.delInstance(); + } + + @Test + public void shouldCreateDataEncryptionServiceInstance() { + IDataEncryptionService dataEncryptionService = Guice.createInjector(new DataEncryptionModule()) + .getInstance(IDataEncryptionService.class); + assertThat(dataEncryptionService, is(notNullValue())); + } + + @Test + public void shouldCreateThrowBFSecureModuleExceptionWhenWrongFile() { + assertThrows(BFSecureModuleException.class, () -> Guice.createInjector(new DataEncryptionModule(NO_FILE_PATH)) + .getInstance(IDataEncryptionService.class)); + } +} diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/base/encryption/providers/DataEncryptionServiceTest.java b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/base/encryption/providers/DataEncryptionServiceTest.java new file mode 100644 index 00000000..97039e33 --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/base/encryption/providers/DataEncryptionServiceTest.java @@ -0,0 +1,169 @@ +package com.capgemini.mrchecker.test.core.unit.base.encryption.providers; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.hamcrest.core.IsNot.not; +import static org.hamcrest.core.IsNull.notNullValue; +import static org.hamcrest.core.IsNull.nullValue; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.io.ByteArrayInputStream; +import java.io.IOException; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.ResourceLock; + +import com.capgemini.mrchecker.test.core.base.encryption.IDataEncryptionService; +import com.capgemini.mrchecker.test.core.base.encryption.providers.DataEncryptionService; +import com.capgemini.mrchecker.test.core.exceptions.BFSecureModuleException; +import com.capgemini.mrchecker.test.core.tags.UnitTest; +import com.capgemini.mrchecker.test.core.utils.ConcurrencyUtils; + +@UnitTest +@ResourceLock(value = "SingleThread") +public class DataEncryptionServiceTest { + + public static final String SECRET_TOO_SHORT = "1234567"; + public static final String SECRET_TRIMABLE = " 1234567"; + public static final String CORRECT_SECRET_1 = "12345678"; + public static final String CORRECT_SECRET_2 = "87954321"; + public static final String SECRET_EMPTY = ""; + public static final String CIPHERTEXT_1 = "ENC(Kneu8D+oIkD6mMAE/sB97ht95fT1lAhc)"; + public static final String PLAINTEXT_1 = "plain text"; + public static final String CIPHERTEXT_2 = "ENC(QTkxI0hWAyTDXdDJd8a9mP8lGGnngflplukqzFj5nj4=)"; + public static final String PLAINTEXT_2 = "another plain text"; + public static final int THREAD_COUNT = 4; + + @BeforeAll + public static void setUpClass() { + DataEncryptionService.delInstance(); + } + + @AfterEach + public void tearDown() { + DataEncryptionService.delInstance(); + } + + private static DataEncryptionService getSut() { + return (DataEncryptionService) DataEncryptionService.getInstance(); + } + + private static DataEncryptionService initAndGetSut(String secret) throws IOException { + try (ByteArrayInputStream secretSource = new ByteArrayInputStream(secret.getBytes())) { + DataEncryptionService.init(secretSource); + } + return getSut(); + } + + private static DataEncryptionService initAndGetSut() throws IOException { + return initAndGetSut(CORRECT_SECRET_1); + } + + @Test + public void shouldInitiallyBeNull() { + assertThat(getSut(), is(nullValue())); + } + + @Test + public void shouldInitOnce() throws IOException { + assertThat(initAndGetSut(), is(notNullValue())); + } + + @Test + public void shouldInitTwice() throws IOException { + IDataEncryptionService firstRef = initAndGetSut(); + IDataEncryptionService secondRef = initAndGetSut(); + + assertThat(firstRef, is(notNullValue())); + assertThat(firstRef, is(equalTo(secondRef))); + } + + @Test + public void shouldInitMultithreaded() throws InterruptedException { + ConcurrencyUtils.getInstancesConcurrently(() -> { + try { + return initAndGetSut(); + } catch (IOException e) { + System.out.println("IOException"); + } + return null; + }) + .forEach(s -> assertThat(s, is(equalTo(getSut())))); + } + + @Test + public void shouldInitThrowExceptionWhenSecretSourceIsEmpty() { + assertThrows(BFSecureModuleException.class, () -> initAndGetSut(SECRET_EMPTY)); + } + + @Test + public void shouldDelInstance() throws IOException { + assertThat(initAndGetSut(), is(notNullValue())); + + DataEncryptionService.delInstance(); + + assertThat(getSut(), is(nullValue())); + } + + @Test + public void shouldSetSecretThrowExceptionWhenSecretIsNull() { + assertThrows(BFSecureModuleException.class, () -> initAndGetSut().setSecret(null)); + } + + @Test + public void shouldSetSecretThrowExceptionWhenSecretIsShort() { + assertThrows(BFSecureModuleException.class, () -> initAndGetSut().setSecret(SECRET_TOO_SHORT)); + } + + @Test + public void shouldSetSecretThrowExceptionWhenSecretIsTrimable() { + assertThrows(BFSecureModuleException.class, () -> initAndGetSut().setSecret(SECRET_TRIMABLE)); + } + + @Test + public void shouldSetSecret() throws IOException { + initAndGetSut().setSecret(CORRECT_SECRET_1); + } + + @Test + public void shouldIsEncryptedReturnFalseWhenTextIsNull() throws IOException { + assertThat(initAndGetSut().isEncrypted(null), is(equalTo(false))); + } + + @Test + public void shouldIsEncryptedReturnValue() throws IOException { + assertThat(initAndGetSut().isEncrypted(CIPHERTEXT_1), is(equalTo(true))); + } + + @Test + public void shouldEncryptReturnCipherText() throws IOException { + String ciphertextVal = initAndGetSut().encrypt(CIPHERTEXT_1); + + assertThat(ciphertextVal, is(not(equalTo(PLAINTEXT_1)))); + } + + @Test + public void shouldDecryptReturnPlaintext() throws IOException { + String plaintextVal = initAndGetSut().decrypt(CIPHERTEXT_1); + + assertThat(plaintextVal, is(equalTo(PLAINTEXT_1))); + } + + @Test + public void shouldDecryptWithChangedSecret() throws IOException { + shouldDecryptReturnPlaintext(); + getSut().setSecret(CORRECT_SECRET_2); + + String plaintextVal = getSut().decrypt(CIPHERTEXT_2); + + assertThat(plaintextVal, is(equalTo(PLAINTEXT_2))); + } + + @Test + public void shouldDecryptThrowExceptionWhenCipherTextIsNull() { + assertThrows(BFSecureModuleException.class, () -> initAndGetSut().decrypt(null)); + } +} diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/base/environment/EnvironmentModuleTest.java b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/base/environment/EnvironmentModuleTest.java new file mode 100644 index 00000000..75a78c96 --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/base/environment/EnvironmentModuleTest.java @@ -0,0 +1,48 @@ +package com.capgemini.mrchecker.test.core.unit.base.environment; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.core.IsNull.notNullValue; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.ResourceLock; + +import com.capgemini.mrchecker.test.core.base.environment.EnvironmentModule; +import com.capgemini.mrchecker.test.core.base.environment.IEnvironmentService; +import com.capgemini.mrchecker.test.core.base.environment.providers.SpreadsheetEnvironmentService; +import com.capgemini.mrchecker.test.core.exceptions.BFInputDataException; +import com.capgemini.mrchecker.test.core.tags.UnitTest; +import com.google.inject.Guice; + +@UnitTest +@ResourceLock(value = "SingleThread") +public class EnvironmentModuleTest { + + public static final String NO_FILE_PATH = "no file path"; + + @BeforeAll + public static void setUpClass() { + SpreadsheetEnvironmentService.delInstance(); + } + + @AfterEach + public void tearDown() { + SpreadsheetEnvironmentService.delInstance(); + } + + @Test + public void shouldCreateEnvironmentServiceInstance() { + IEnvironmentService environmentService = Guice.createInjector(new EnvironmentModule()) + .getInstance(IEnvironmentService.class); + assertThat(environmentService, is(notNullValue())); + } + + @Test + public void shouldCreateThrowExceptionWhenWrongFile() { + assertThrows(BFInputDataException.class, () -> Guice.createInjector(new EnvironmentModule(NO_FILE_PATH)) + .getInstance(IEnvironmentService.class)); + } +} diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/base/environment/providers/SpreadsheetEnvironmentServiceTest.java b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/base/environment/providers/SpreadsheetEnvironmentServiceTest.java new file mode 100644 index 00000000..d6359b20 --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/base/environment/providers/SpreadsheetEnvironmentServiceTest.java @@ -0,0 +1,191 @@ +package com.capgemini.mrchecker.test.core.unit.base.environment.providers; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.hamcrest.core.IsNull.notNullValue; +import static org.hamcrest.core.IsNull.nullValue; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.Arrays; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.ResourceLock; + +import com.capgemini.mrchecker.test.core.base.encryption.IDataEncryptionService; +import com.capgemini.mrchecker.test.core.base.environment.IEnvironmentService; +import com.capgemini.mrchecker.test.core.base.environment.providers.SpreadsheetEnvironmentService; +import com.capgemini.mrchecker.test.core.base.runtime.RuntimeParametersCore; +import com.capgemini.mrchecker.test.core.exceptions.BFInputDataException; +import com.capgemini.mrchecker.test.core.tags.UnitTest; +import com.capgemini.mrchecker.test.core.utils.ConcurrencyUtils; + +@UnitTest +@ResourceLock(value = "SingleThread") +public class SpreadsheetEnvironmentServiceTest { + + public static final String TEST_ENV = "TEST_ENV"; + public static final String[][] CORRECT_CSV_DATA_ARRAY = { { "service variable", "DEV", TEST_ENV }, + { "Key_1", "DEV_Value1", TEST_ENV + "_Value1" }, + { "Key_2", "DEV_Value2", TEST_ENV + "_Value2" } + }; + + public static final String CORRECT_CSV_DATA; + public static final String NO_SUCH_ENV = "No such env"; + + static { + final StringBuilder sb = new StringBuilder(); + { + Arrays.stream(CORRECT_CSV_DATA_ARRAY) + .forEach(row -> { + Arrays.stream(row) + .forEach(s -> sb.append(s) + .append(',')); + sb.deleteCharAt(sb.length() - 1) + .append('\n'); + }); + CORRECT_CSV_DATA = sb.toString(); + } + } + + public static final String DEFAULT_ENV_WHEN_NO_ENVIRONMENT_SERVICE_SET = "DEV"; + public static final String DECRYPTED_VALUE_FROM_MOCK = "DECRYPTED_VALUE"; + public static final String NO_SUCH_KEY = "NO_SUCH_KEY"; + + @BeforeAll + public static void setUpClass() { + SpreadsheetEnvironmentService.delInstance(); + } + + @AfterEach + public void tearDown() { + SpreadsheetEnvironmentService.delInstance(); + } + + private static SpreadsheetEnvironmentService getSut() { + return (SpreadsheetEnvironmentService) SpreadsheetEnvironmentService.getInstance(); + } + + private static SpreadsheetEnvironmentService initAndGetSut(String csvData, String env) { + SpreadsheetEnvironmentService.init(csvData, env); + return getSut(); + } + + private static SpreadsheetEnvironmentService initAndGetSut() { + return initAndGetSut(CORRECT_CSV_DATA, TEST_ENV); + } + + @Test + public void shouldInitiallyBeNull() { + assertThat(getSut(), is(nullValue())); + } + + @Test + public void shouldInitOnce() { + assertThat(initAndGetSut(), is(notNullValue())); + } + + @Test + public void shouldInitTwice() { + IEnvironmentService firstRef = initAndGetSut(); + IEnvironmentService secondRef = initAndGetSut(); + + assertThat(firstRef, is(notNullValue())); + assertThat(firstRef, is(equalTo(secondRef))); + } + + @Test + public void shouldInitMultithreaded() throws InterruptedException { + ConcurrencyUtils.getInstancesConcurrently(SpreadsheetEnvironmentServiceTest::initAndGetSut) + .forEach(s -> assertThat(s, is(equalTo(getSut())))); + } + + @Test + public void shouldInitThrowExceptionWhenEnvNotFound() { + assertThrows(BFInputDataException.class, () -> initAndGetSut(CORRECT_CSV_DATA, NO_SUCH_ENV)); + } + + @Test + public void shouldDelInstance() { + assertThat(initAndGetSut(), is(notNullValue())); + + SpreadsheetEnvironmentService.delInstance(); + assertThat(getSut(), is(nullValue())); + assertThat(RuntimeParametersCore.ENV.getValue(), is(equalTo(DEFAULT_ENV_WHEN_NO_ENVIRONMENT_SERVICE_SET))); + } + + @Test + public void shouldGetValue() { + initAndGetSut(); + + String testEnv_Value1 = getSut().getValue(CORRECT_CSV_DATA_ARRAY[1][0]); + String testEnv_Value2 = getSut().getValue(CORRECT_CSV_DATA_ARRAY[2][0]); + + assertThat(testEnv_Value1, is(equalTo(CORRECT_CSV_DATA_ARRAY[1][2]))); + assertThat(testEnv_Value2, is(equalTo(CORRECT_CSV_DATA_ARRAY[2][2]))); + } + + @Test + public void shouldGetValueReturnDecryptedValue() { + initAndGetSut(); + IDataEncryptionService dataEncryptionServiceMock = mock(IDataEncryptionService.class); + when(dataEncryptionServiceMock.isEncrypted(anyString())).thenReturn(true); + when(dataEncryptionServiceMock.decrypt(anyString())).thenReturn(DECRYPTED_VALUE_FROM_MOCK); + + getSut().setDataEncryptionService(dataEncryptionServiceMock); + + assertThat(getSut().getValue(CORRECT_CSV_DATA_ARRAY[1][0]), is(equalTo(DECRYPTED_VALUE_FROM_MOCK))); + } + + @Test + public void shouldGetValueReturnOriginalValueWhenDataNotEncrypted() { + initAndGetSut(); + IDataEncryptionService dataEncryptionServiceMock = mock(IDataEncryptionService.class); + when(dataEncryptionServiceMock.isEncrypted(anyString())).thenReturn(false); + + getSut().setDataEncryptionService(dataEncryptionServiceMock); + + assertThat(getSut().getValue(CORRECT_CSV_DATA_ARRAY[1][0]), is(equalTo(CORRECT_CSV_DATA_ARRAY[1][2]))); + } + + @Test + public void shouldGetValueThrowExceptionWhenKeyIsNotFound() { + initAndGetSut(); + + assertThrows(BFInputDataException.class, () -> getSut().getValue(NO_SUCH_KEY)); + } + + @Test + public void shouldGetEnvironmentReturnValue() { + initAndGetSut(); + + assertThat(getSut().getEnvironment(), is(equalTo(TEST_ENV))); + } + + @Test + public void shouldSetDataEncryptionService() { + initAndGetSut(); + IDataEncryptionService dataEncryptionServiceMock = mock(IDataEncryptionService.class); + + getSut().setDataEncryptionService(dataEncryptionServiceMock); + } + + @Test + public void shouldSetEnvironment() { + initAndGetSut(); + + getSut().setEnvironment(DEFAULT_ENV_WHEN_NO_ENVIRONMENT_SERVICE_SET); + } + + @Test + public void shouldSetEnvironmentThrowExceptionWhenNoSuchEnvironment() { + initAndGetSut(); + + assertThrows(BFInputDataException.class, () -> getSut().setEnvironment(NO_SUCH_ENV)); + } +} diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/base/properties/PropertiesCoreTestTest.java b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/base/properties/PropertiesCoreTestTest.java new file mode 100644 index 00000000..6ae99e8b --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/base/properties/PropertiesCoreTestTest.java @@ -0,0 +1,42 @@ +package com.capgemini.mrchecker.test.core.unit.base.properties; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsEqual.equalTo; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.ResourceLock; + +import com.capgemini.mrchecker.test.core.base.properties.PropertiesCoreTest; +import com.capgemini.mrchecker.test.core.tags.UnitTest; + +@UnitTest +@ResourceLock(value = "SingleThread") +public class PropertiesCoreTestTest { + public static final String DEFAULT_ENV = "DEV"; + public static final boolean DEFAULT_ANALYTICS = true; + public static final boolean DEFAULT_ENCRYPTION = false; + + private static PropertiesCoreTest sut; + + @BeforeAll + public static void setUpClass() { + sut = new PropertiesCoreTest(); + } + + @Test + public void shouldInitiallyBeDefaultEnv() { + assertThat(sut.getDefaultEnvironmentName(), is(equalTo(DEFAULT_ENV))); + } + + @Test + public void shouldInitiallyBeAnalyticsEnabled() { + assertThat(sut.isAnalyticsEnabled(), is(equalTo(DEFAULT_ANALYTICS))); + } + + @Test + public void shouldInitiallyBeEncryptionDisabled() { + assertThat(sut.isEncryptionEnabled(), is(equalTo(DEFAULT_ENCRYPTION))); + } +} diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/base/properties/PropertiesSettingsModuleTest.java b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/base/properties/PropertiesSettingsModuleTest.java new file mode 100644 index 00000000..d2d832ff --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/base/properties/PropertiesSettingsModuleTest.java @@ -0,0 +1,154 @@ +package com.capgemini.mrchecker.test.core.unit.base.properties; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.core.IsNot.not; +import static org.hamcrest.core.IsNull.notNullValue; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.ResourceLock; + +import com.capgemini.mrchecker.test.core.base.properties.PropertiesCoreTest; +import com.capgemini.mrchecker.test.core.base.properties.PropertiesSettingsModule; +import com.capgemini.mrchecker.test.core.exceptions.BFInputDataException; +import com.capgemini.mrchecker.test.core.tags.UnitTest; +import com.capgemini.mrchecker.test.core.utils.ConcurrencyUtils; +import com.google.inject.Guice; + +@UnitTest +@ResourceLock(value = "SingleThread") +public class PropertiesSettingsModuleTest { + private static final String DEFAULT_FILE_SOURCE_FILE_PATH = System.getProperty("user.dir") + Paths.get("/src/resources/settings.properties"); + private static final String TEMP_FILE_SOURCE_FILE_PATH = System.getProperty("user.dir") + Paths.get("/src/resources/settings_temp.properties"); + + public static final String[][] TEST_PROPERTIES_ARRAY = { { "core.isAnalyticsEnabled", "false" }, + { "core.isEncryptionEnabled", "false" }, + { "core.defaultEnvironmentName", "TEST_ENV" } + }; + + public static final String[][] TEST_PROPERTIES_SECOND_ARRAY = { { "core.isAnalyticsEnabled", "true" }, + { "core.isEncryptionEnabled", "true" }, + { "core.defaultEnvironmentName", "SECOND_TEST_ENV" } + }; + + public static final String TEST_PROPERTIES = buildProperties(TEST_PROPERTIES_ARRAY); + public static final String TEST_PROPERTIES_SECOND = buildProperties(TEST_PROPERTIES_SECOND_ARRAY); + + private static String buildProperties(String[][] source) { + final StringBuilder sb = new StringBuilder(); + Arrays.stream(source) + .forEach(row -> sb.append(row[0]) + .append("=") + .append(row[1]) + .append('\n')); + return sb.toString(); + } + + @BeforeAll + public static void setUpClass() { + PropertiesSettingsModule.delInstance(); + } + + @AfterEach + public void tearDown() throws IOException { + PropertiesSettingsModule.delInstance(); + if (Files.exists(Paths.get(TEMP_FILE_SOURCE_FILE_PATH))) { + Files.move(Paths.get(TEMP_FILE_SOURCE_FILE_PATH), Paths.get(DEFAULT_FILE_SOURCE_FILE_PATH)); + } + } + + @Test + public void shouldInitWithDefaultInputSource() { + assertThat(PropertiesSettingsModule.init(), is(notNullValue())); + } + + @Test + public void shouldInitWithCustomInputSource() { + verifyProperties(createWithCustomInputSource(TEST_PROPERTIES), TEST_PROPERTIES_ARRAY); + } + + private PropertiesCoreTest createWithCustomInputSource(String testProperties) { + PropertiesSettingsModule propertiesSettingsModule = PropertiesSettingsModule.init(new ByteArrayInputStream(testProperties.getBytes())); + + return Guice.createInjector(propertiesSettingsModule) + .getInstance(PropertiesCoreTest.class); + } + + private void verifyProperties(PropertiesCoreTest properties, String[][] testPropertiesArray) { + assertThat(properties.isAnalyticsEnabled(), is(equalTo(Boolean.parseBoolean(testPropertiesArray[0][1])))); + assertThat(properties.isEncryptionEnabled(), is(equalTo(Boolean.parseBoolean(testPropertiesArray[1][1])))); + assertThat(properties.getDefaultEnvironmentName(), is(equalTo(testPropertiesArray[2][1]))); + } + + @Test + public void shouldInitSecondTimeAfterDelete() { + PropertiesSettingsModule firstInstance = PropertiesSettingsModule.init(); + PropertiesSettingsModule.delInstance(); + PropertiesSettingsModule secondInstance = PropertiesSettingsModule.init(); + + assertThat(firstInstance, is(not(equalTo(secondInstance)))); + } + + @Test + public void shouldInitMultithreadedWithDifferentPropertiesSet() throws InterruptedException, ExecutionException { + ArrayList> testTasks = new ArrayList<>(); + testTasks.add(() -> createWithCustomInputSource(TEST_PROPERTIES)); + testTasks.add(() -> createWithCustomInputSource(TEST_PROPERTIES_SECOND)); + + ExecutorService executorService = Executors.newFixedThreadPool(testTasks.size()); + List> properties = executorService.invokeAll(testTasks); + executorService.shutdown(); + executorService.awaitTermination(1, TimeUnit.SECONDS); + + verifyProperties(properties.get(0) + .get(), TEST_PROPERTIES_ARRAY); + verifyProperties(properties.get(1) + .get(), TEST_PROPERTIES_SECOND_ARRAY); + } + + @Test + public void shouldInitMultithreaded() throws InterruptedException, ExecutionException { + ConcurrencyUtils.getInstancesConcurrently(() -> createWithCustomInputSource(TEST_PROPERTIES)) + .forEach(s -> assertThat(s.getDefaultEnvironmentName(), is(equalTo(TEST_PROPERTIES_ARRAY[2][1])))); + } + + @Test + public void shouldInitThrowExceptionWhenUnparsableInput() throws IOException { + InputStream inputStreamMock = mock(InputStream.class); + when(inputStreamMock.read(any())).thenThrow(new IOException()); + + PropertiesSettingsModule propertiesSettingsModule = PropertiesSettingsModule.init(inputStreamMock); + + assertThrows(BFInputDataException.class, () -> Guice.createInjector(propertiesSettingsModule) + .getInstance(PropertiesCoreTest.class)); + } + + @Test + public void shouldCreateThrowExceptionWhenFileCouldNotBeRead() throws IOException { + Files.move(Paths.get(DEFAULT_FILE_SOURCE_FILE_PATH), Paths.get(TEMP_FILE_SOURCE_FILE_PATH)); + + assertThrows(BFInputDataException.class, PropertiesSettingsModule::init); + } +} diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/base/runtime/RuntimeParametersCoreTest.java b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/base/runtime/RuntimeParametersCoreTest.java new file mode 100644 index 00000000..f8d6e4e5 --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/base/runtime/RuntimeParametersCoreTest.java @@ -0,0 +1,128 @@ +package com.capgemini.mrchecker.test.core.unit.base.runtime; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsEqual.equalTo; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.ResourceLock; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import com.capgemini.mrchecker.test.core.base.runtime.RuntimeParametersCore; +import com.capgemini.mrchecker.test.core.tags.UnitTest; + +@UnitTest +@ResourceLock(value = "SingleThread") +public class RuntimeParametersCoreTest { + + private static final String ENV_KEY = "env"; + private static final String ENV_DEFAULT_VALUE = RuntimeParametersCore.ENV.getValue(); + private static final String ENV_NEW_DEFAULT_VALUE = "NEW_DEFAULT"; + private static final String ENV_NEW_VALUE = "NEW_ENV"; + private static final String STRING_EMPTY = ""; + private static final String STRING_NULL_STRING = "null"; + private static final String TO_STRING_VALUE = "env=DEV"; + + private final static RuntimeParametersCore sut = RuntimeParametersCore.ENV; + + @BeforeEach + public void setUp() { + cleanUpSystemProperties(); + } + + @AfterAll + public static void tearDownClass() { + cleanUpSystemProperties(); + } + + private static void cleanUpSystemProperties() { + System.clearProperty(ENV_KEY); + sut.setDefaultValue(ENV_DEFAULT_VALUE); + sut.refreshParameterValue(); + } + + @Test + public void shouldGetKeyReturnEnvKey() { + assertThat(sut.getKey(), is(equalTo(ENV_KEY))); + } + + @Test + public void shouldEnvGetValueInitiallyBeDefaultValue() { + assertThat(sut.getValue(), is(equalTo(ENV_DEFAULT_VALUE))); + } + + @Test + public void shouldEnvGetValueReturnDefaultValueWhenSystemPropertyIsSetAndValueNOTRefreshed() { + setEnvSystemProperty(ENV_NEW_VALUE); + + assertThat(sut.getValue(), is(equalTo(ENV_DEFAULT_VALUE))); + } + + @Test + public void shouldEnvGetValueReturnNewValueWhenSystemPropertyIsSetAndValueRefreshed() { + setEnvSystemProperty(ENV_NEW_VALUE); + sut.refreshParameterValue(); + + assertThat(sut.getValue(), is(equalTo(ENV_NEW_VALUE))); + } + + @ParameterizedTest + @ValueSource(strings = { STRING_EMPTY, STRING_NULL_STRING }) + public void shouldEnvGetValueReturnDefaultValueWhenSystemPropertyIsSetToInvalidValueAndValueRefreshed(String invalidValue) { + setEnvSystemProperty(invalidValue); + sut.refreshParameterValue(); + + assertThat(sut.getValue(), is(equalTo(ENV_DEFAULT_VALUE))); + } + + @Test + public void shouldEnvGetValueReturnDefaultValueWhenSystemPropertyIsNOTSetAndValueRefreshed() { + sut.refreshParameterValue(); + + assertThat(sut.getValue(), is(equalTo(ENV_DEFAULT_VALUE))); + } + + @Test + public void shouldEnvSetDefaultValueAndValueRefreshed() { + sut.setDefaultValue(ENV_NEW_DEFAULT_VALUE); + sut.refreshParameterValue(); + + assertThat(sut.getValue(), is(equalTo(ENV_NEW_DEFAULT_VALUE))); + } + + @Test + public void shouldEnvNOTSetDefaultValueAndValueNOTRefreshed() { + sut.setDefaultValue(ENV_NEW_DEFAULT_VALUE); + + assertThat(sut.getValue(), is(equalTo(ENV_DEFAULT_VALUE))); + } + + @ParameterizedTest + @ValueSource(strings = { STRING_EMPTY, STRING_NULL_STRING }) + public void shouldEnvNotSetDefaultValueWhenNewDefaultValueIsInvalidAndValueRefreshed(String invalidValue) { + sut.setDefaultValue(invalidValue); + sut.refreshParameterValue(); + + assertThat(sut.getValue(), is(equalTo(ENV_DEFAULT_VALUE))); + } + + @Test + public void shouldEnvNotSetDefaultValueWhenNewDefaultValueNullAndValueRefreshed() { + sut.setDefaultValue(null); + sut.refreshParameterValue(); + + assertThat(sut.getValue(), is(equalTo(ENV_DEFAULT_VALUE))); + } + + @Test + public void shouldEnvToStringReturnValue() { + assertThat(sut.toString(), is(equalTo(TO_STRING_VALUE))); + } + + private static void setEnvSystemProperty(String value) { + System.setProperty(ENV_KEY, value); + } +} diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/exceptions/BFInputDataExceptionTest.java b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/exceptions/BFInputDataExceptionTest.java new file mode 100644 index 00000000..d97068ed --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/exceptions/BFInputDataExceptionTest.java @@ -0,0 +1,26 @@ +package com.capgemini.mrchecker.test.core.unit.exceptions; + +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.hamcrest.core.IsNull.notNullValue; +import static org.junit.Assert.assertThat; + +import org.junit.jupiter.api.Test; + +import com.capgemini.mrchecker.test.core.exceptions.BFInputDataException; +import com.capgemini.mrchecker.test.core.tags.UnitTest; + +@UnitTest +public class BFInputDataExceptionTest { + public static final String TEST_MESSAGE = "TEST_MESSAGE"; + + @Test + public void shouldCreateInstance() { + assertThat(new BFInputDataException(TEST_MESSAGE), is(notNullValue())); + } + + @Test + public void shouldNotFormatMessage() { + assertThat(new BFInputDataException(TEST_MESSAGE).getMessage(), is(equalTo(TEST_MESSAGE))); + } +} diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/exceptions/BFSecureModuleExceptionTest.java b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/exceptions/BFSecureModuleExceptionTest.java new file mode 100644 index 00000000..2ea4e0cb --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/exceptions/BFSecureModuleExceptionTest.java @@ -0,0 +1,48 @@ +package com.capgemini.mrchecker.test.core.unit.exceptions; + +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.hamcrest.core.IsNull.notNullValue; +import static org.junit.Assert.assertThat; + +import org.junit.jupiter.api.Test; + +import com.capgemini.mrchecker.test.core.exceptions.BFSecureModuleException; +import com.capgemini.mrchecker.test.core.tags.UnitTest; + +@UnitTest +public class BFSecureModuleExceptionTest { + + public static final String TEST_MESSAGE = "TEST_MESSAGE"; + public static final String FORMATTED_MESSAGE_WHEN_NULL = ""; + + @Test + public void shouldCreateInstanceWithMessageOnly() { + assertThat(new BFSecureModuleException(TEST_MESSAGE), is(notNullValue())); + } + + @Test + public void shouldNotFormatMessageWithMessageOnly() { + assertThat(new BFSecureModuleException(TEST_MESSAGE).getMessage(), is(equalTo(TEST_MESSAGE))); + } + + @Test + public void shouldFormatMessageWhenNullWithMessageOnly() { + assertThat(new BFSecureModuleException(null).getMessage(), is(equalTo(FORMATTED_MESSAGE_WHEN_NULL))); + } + + @Test + public void shouldCreateInstanceFull() { + assertThat(new BFSecureModuleException(TEST_MESSAGE, new Throwable()), is(notNullValue())); + } + + @Test + public void shouldNotFormatMessageFull() { + assertThat(new BFSecureModuleException(TEST_MESSAGE, new Throwable()).getMessage(), is(equalTo(TEST_MESSAGE))); + } + + @Test + public void shouldFormatMessageWhenNullFull() { + assertThat(new BFSecureModuleException(null, new Throwable()).getMessage(), is(equalTo(FORMATTED_MESSAGE_WHEN_NULL))); + } +} diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/exceptions/BFWaitingTimeoutExceptionTest.java b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/exceptions/BFWaitingTimeoutExceptionTest.java new file mode 100644 index 00000000..9c168217 --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/exceptions/BFWaitingTimeoutExceptionTest.java @@ -0,0 +1,28 @@ +package com.capgemini.mrchecker.test.core.unit.exceptions; + +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.hamcrest.core.IsNull.notNullValue; +import static org.junit.Assert.assertThat; + +import org.junit.jupiter.api.Test; + +import com.capgemini.mrchecker.test.core.exceptions.BFWaitingTimeoutException; +import com.capgemini.mrchecker.test.core.tags.UnitTest; + +@UnitTest +public class BFWaitingTimeoutExceptionTest { + public static final String COMPONENT_NAME = "COMPONENT_NAME"; + public static final int TIMEOUT = 10; + public static final String FORMATTED_MESSAGE = "Timed out waiting [" + TIMEOUT + "] seconds for [" + COMPONENT_NAME + "] to load."; + + @Test + public void shouldCreateInstance() { + assertThat(new BFWaitingTimeoutException(COMPONENT_NAME, TIMEOUT), is(notNullValue())); + } + + @Test + public void shouldFormatMessage() { + assertThat(new BFWaitingTimeoutException(COMPONENT_NAME, TIMEOUT).getMessage(), is(equalTo(FORMATTED_MESSAGE))); + } +} diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/logger/EnvironmentLevelTest.java b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/logger/EnvironmentLevelTest.java new file mode 100644 index 00000000..2fcb32dd --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/logger/EnvironmentLevelTest.java @@ -0,0 +1,66 @@ +package com.capgemini.mrchecker.test.core.unit.logger; + +import static com.capgemini.mrchecker.test.core.logger.EnvironmentLevel.ENVIRONMENT_INT; +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.junit.Assert.assertThat; + +import org.apache.log4j.Level; +import org.junit.jupiter.api.Test; + +import com.capgemini.mrchecker.test.core.logger.EnvironmentLevel; +import com.capgemini.mrchecker.test.core.tags.UnitTest; + +@UnitTest +public class EnvironmentLevelTest { + + public static final String ENVIRONMENT = "environment"; + public static final String UNKNOWN_STRING_LEVEL = "unknown_level"; + public static final int UNKNOWN_VALUE_LEVEL = ENVIRONMENT_INT + 1; + + @Test + public void shouldToLevelStringArgReturnEnvironment() { + assertThat(EnvironmentLevel.toLevel(ENVIRONMENT), is(equalTo(EnvironmentLevel.ENVIRONMENT))); + } + + @Test + public void shouldToLevelStringArgReturnDebugWhenUnknownLevel() { + assertThat(EnvironmentLevel.toLevel(UNKNOWN_STRING_LEVEL), is(equalTo(Level.DEBUG))); + } + + @Test + public void shouldToLevelStringAndDefaultArgsReturnEnvironment() { + assertThat(EnvironmentLevel.toLevel(ENVIRONMENT, Level.INFO), is(equalTo(EnvironmentLevel.ENVIRONMENT))); + } + + @Test + public void shouldToLevelIntAndDefaultArgsReturnGivenDefaultWhenUnknownNull() { + assertThat(EnvironmentLevel.toLevel(null, Level.INFO), is(equalTo(Level.INFO))); + } + + @Test + public void shouldToLevelIntAndDefaultArgsReturnGivenDefaultWhenUnknownLevel() { + assertThat(EnvironmentLevel.toLevel(UNKNOWN_STRING_LEVEL, Level.INFO), is(equalTo(Level.INFO))); + } + + @Test + public void shouldToLevelIntArgReturnEnvironment() { + assertThat(EnvironmentLevel.toLevel(ENVIRONMENT_INT), is(equalTo(EnvironmentLevel.ENVIRONMENT))); + } + + @Test + public void shouldToLevelIntArgReturnDebugWhenUnknownValue() { + assertThat(EnvironmentLevel.toLevel(UNKNOWN_VALUE_LEVEL), is(equalTo(EnvironmentLevel.DEBUG))); + } + + @Test + public void shouldToLevelIntAndDefaultArgsReturnEnvironment() { + assertThat(EnvironmentLevel.toLevel(ENVIRONMENT_INT, Level.INFO), is(equalTo(EnvironmentLevel.ENVIRONMENT))); + } + + @Test + public void shouldToLevelIntAndDefaultArgsReturnGivenDefaultWhenUnknownValue() { + assertThat(EnvironmentLevel.toLevel(UNKNOWN_VALUE_LEVEL, Level.INFO), is(equalTo(Level.INFO))); + } + +} diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/utils/JsonReaderTest.java b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/utils/JsonReaderTest.java new file mode 100644 index 00000000..997ebc5b --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/utils/JsonReaderTest.java @@ -0,0 +1,101 @@ +package com.capgemini.mrchecker.test.core.unit.utils; + +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.junit.Assert.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; + +import org.json.JSONObject; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import com.capgemini.mrchecker.test.core.exceptions.BFInputDataException; +import com.capgemini.mrchecker.test.core.logger.BFLogger; +import com.capgemini.mrchecker.test.core.tags.UnitTest; +import com.capgemini.mrchecker.test.core.utils.JsonReader; + +@UnitTest +public class JsonReaderTest { + private static final String KEY_1 = "KEY_1"; + private static final String KEY_2 = "KEY_2"; + private static final String VALUE_1 = "VALUE_1"; + private static final String VALUE_2 = "VALUE_2"; + private static final String NO_SUCH_FILE = "NO_SUCH_FILE"; + + private static JSONObject jo; + private static final File tempFile = new File(System.getProperty("user.dir") + "/json_test.txt"); + + @BeforeAll + public static void setUpClass() throws IOException { + jo = new JSONObject(); + jo.put(KEY_1, VALUE_1); + jo.put(KEY_2, VALUE_2); + + if (tempFile.exists()) { + if (tempFile.delete()) { + BFLogger.logDebug(tempFile.getName() + " file deleted "); + } + } + + if (tempFile.createNewFile()) { + BFLogger.logDebug(tempFile.getName() + " file created "); + } + } + + @AfterAll + public static void tearDownClass() { + if (tempFile.exists()) { + if (tempFile.delete()) { + BFLogger.logDebug(tempFile.getName() + " file deleted "); + } + } + } + + @Test + public void shouldReadInputStream() throws IOException { + try (InputStream jsonStream = new ByteArrayInputStream(jo.toString() + .getBytes())) { + JSONObject joFromReader = JsonReader.readJson(jsonStream); + verifyResult(joFromReader); + } + } + + @Test + public void shouldReadFile() throws IOException { + try (FileOutputStream out = new FileOutputStream(tempFile)) { + out.write(jo.toString() + .getBytes()); + } + + JSONObject joFromReader = JsonReader.readJson(tempFile); + + verifyResult(joFromReader); + } + + private static void verifyResult(JSONObject joFromReader) { + assertThat(joFromReader.getString(KEY_1), is(equalTo(jo.getString(KEY_1)))); + assertThat(joFromReader.getString(KEY_2), is(equalTo(jo.getString(KEY_2)))); + } + + @Test + public void shouldReadInputStreamThrowException() throws IOException { + InputStream mockStream = mock(InputStream.class); + when(mockStream.available()).thenThrow(new IOException()); + + assertThrows(BFInputDataException.class, () -> JsonReader.readJson(mockStream)); + } + + @Test + public void shouldReadFileThrowBFInputDataExceptionWhenNoFile() { + assertThrows(BFInputDataException.class, () -> JsonReader.readJson(new File(NO_SUCH_FILE))); + } +} diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/utils/PageFactoryTest.java b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/utils/PageFactoryTest.java new file mode 100644 index 00000000..86f81d45 --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/utils/PageFactoryTest.java @@ -0,0 +1,146 @@ +package com.capgemini.mrchecker.test.core.unit.utils; + +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsInstanceOf.instanceOf; +import static org.junit.Assert.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.ResourceLock; + +import com.capgemini.mrchecker.test.core.ModuleType; +import com.capgemini.mrchecker.test.core.Page; +import com.capgemini.mrchecker.test.core.exceptions.BFInputDataException; +import com.capgemini.mrchecker.test.core.tags.UnitTest; +import com.capgemini.mrchecker.test.core.utils.PageFactory; + +@UnitTest +@ResourceLock(value = "SingleThread") +public class PageFactoryTest { + + @Test + public void shouldCreateChildPage() { + Page page = PageFactory.getPageInstance(ChildPage.class); + + assertThat(page, is(instanceOf(ChildPage.class))); + } + + @Test + public void shouldCreateChildPageThrowException() { + assertThrows(BFInputDataException.class, () -> PageFactory.getPageInstance(ChildPageThrowingException.class)); + } + + @Test + public void shouldCreateChildPageThrowExceptionWhenPrivateConstructor() { + assertThrows(BFInputDataException.class, () -> PageFactory.getPageInstance(ChildPageWithPrivateConstructor.class)); + } + + @Test + public void shouldCreateChildPageWithArgs() { + Page page = PageFactory.getPageInstance(ChildPageWithArgs.class, new Object(), 1); + + assertThat(page, is(instanceOf(ChildPageWithArgs.class))); + } + + @Test + public void shouldCreateChildWithArgsPageThrowException() { + assertThrows(BFInputDataException.class, () -> PageFactory.getPageInstance(ChildPageWithArgsThrowingException.class, new Object(), 1)); + } + + @Test + public void shouldCreateChildWithArgsPageThrowExceptionWhenPrivateConstructor() { + assertThrows(BFInputDataException.class, () -> PageFactory.getPageInstance(ChildPageWithArgsWithPrivateConstructor.class, new Object(), 1)); + } + + public static class ChildPage extends Page { + + public ChildPage() { + } + + @Override + public ModuleType getModuleType() { + return ModuleType.CORE; + } + } + + public static class ChildPageThrowingException extends Page { + + public ChildPageThrowingException() throws InstantiationException { + throw new InstantiationException(); + } + + @Override + public ModuleType getModuleType() { + return ModuleType.CORE; + } + } + + public static class ChildPageWithPrivateConstructor extends Page { + + private ChildPageWithPrivateConstructor() { + } + + @Override + public ModuleType getModuleType() { + return ModuleType.CORE; + } + } + + public static class ChildPageWithArgs extends Page { + + public ChildPageWithArgs(Object o, Integer i) { + } + + @Override + public ModuleType getModuleType() { + return ModuleType.CORE; + } + } + + public static class ChildPageWithArgsThrowingException extends Page { + + public ChildPageWithArgsThrowingException(Object o, Integer i) throws InstantiationException { + throw new InstantiationException(); + } + + @Override + public ModuleType getModuleType() { + return ModuleType.CORE; + } + } + + public static class ChildPageWithArgsWithPrivateConstructor extends Page { + + private ChildPageWithArgsWithPrivateConstructor(Object o, Integer i) { + } + + @Override + public ModuleType getModuleType() { + return ModuleType.CORE; + } + } + + @Test + public void shouldCreateChildPageByClassName() { + Page page = PageFactory.getPageInstance("com.capgemini.mrchecker.test.core.unit.utils.PageFactoryTest$ChildPage"); + + assertThat(page, is(instanceOf(ChildPage.class))); + } + + @Test + public void shouldCreateChildPageByClassNameThrowException() { + assertThrows(BFInputDataException.class, () -> PageFactory.getPageInstance("com.capgemini.mrchecker.test.core.unit.utils.PageFactoryTest$NoSuchPage")); + } + + @Test + public void shouldCreateChildPageWithArgsByClassName() { + Page page = PageFactory.getPageInstance("com.capgemini.mrchecker.test.core.unit.utils.PageFactoryTest$ChildPageWithArgs", new Object(), 1); + + assertThat(page, is(instanceOf(ChildPageWithArgs.class))); + } + + @Test + public void shouldCreateChildPageWithArgsByClassNameThrowException() { + assertThrows(BFInputDataException.class, () -> PageFactory.getPageInstance("com.capgemini.mrchecker.test.core.unit.utils.PageFactoryTest$NoSuchPage", new Object(), 1)); + } +} \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/utils/datadriven/JsonDrivenTest.java b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/utils/datadriven/JsonDrivenTest.java new file mode 100644 index 00000000..b3016c33 --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/unit/utils/datadriven/JsonDrivenTest.java @@ -0,0 +1,130 @@ +package com.capgemini.mrchecker.test.core.unit.utils.datadriven; + +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.junit.Assert.assertThat; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.Reader; +import java.io.StringReader; + +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import com.capgemini.mrchecker.test.core.logger.BFLogger; +import com.capgemini.mrchecker.test.core.tags.UnitTest; +import com.capgemini.mrchecker.test.core.utils.datadriven.JsonDriven; + +import gherkin.deps.com.google.gson.GsonBuilder; + +@UnitTest +public class JsonDrivenTest { + + private static final String TEST_STRING = "TEST_STRING"; + private static final int TEST_INTEGER = Integer.MAX_VALUE; + private static final String NO_SUCH_FILE = "NO_SUCH_FILE"; + + private static SimpleObject so; + private static String jsonString; + + private static final File tempFile = new File(System.getProperty("user.dir") + "/json_test.txt"); + + @BeforeAll + public static void setUpClass() throws IOException { + so = new SimpleObject(TEST_STRING, TEST_INTEGER); + jsonString = new GsonBuilder().create() + .toJson(new SimpleObject[] { so }); + if (tempFile.exists()) { + if (tempFile.delete()) { + BFLogger.logDebug(tempFile.getName() + " file deleted "); + } + } + + if (tempFile.createNewFile()) { + BFLogger.logDebug(tempFile.getName() + " file created "); + } + } + + @AfterAll + public static void tearDownClass() { + if (tempFile.exists()) { + if (tempFile.delete()) { + BFLogger.logDebug(tempFile.getName() + " file deleted "); + } + } + } + + @Test + public void shouldProvideSimpleObjectArrayFromReader() throws IOException { + try (Reader in = new StringReader(jsonString)) { + verifyResult(JsonDriven.provide(in, SimpleObject[].class)); + } + } + + @Test + public void shouldProvideSimpleObjectArrayFromFile() throws IOException { + try (FileOutputStream out = new FileOutputStream(tempFile)) { + out.write(jsonString.getBytes()); + } + + verifyResult(JsonDriven.provide(tempFile.getName(), SimpleObject[].class)); + } + + private static void verifyResult(SimpleObject[] soaFromReader) { + assertThat(soaFromReader[0].equals(so), is(equalTo(true))); + } + + @Test + public void shouldProvideEmptyArrayWhenNoFile() { + assertThat(JsonDriven.provide(NO_SUCH_FILE, SimpleObject[].class).length, is(equalTo(0))); + } +} + +@SuppressWarnings("unused") +class SimpleObject { + private String string; + private int integer; + + public SimpleObject(String string, int integer) { + this.string = string; + this.integer = integer; + } + + public String getString() { + return string; + } + + public void setString(String string) { + this.string = string; + } + + public int getInteger() { + return integer; + } + + public void setInteger(int integer) { + this.integer = integer; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (obj == this) { + return true; + } + if (obj.getClass() != getClass()) { + return false; + } + SimpleObject rhs = (SimpleObject) obj; + return new EqualsBuilder() + .append(string, rhs.string) + .append(integer, rhs.integer) + .isEquals(); + } +} diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/utils/ConcurrencyUtils.java b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/utils/ConcurrencyUtils.java new file mode 100644 index 00000000..1420eb9c --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/utils/ConcurrencyUtils.java @@ -0,0 +1,63 @@ +package com.capgemini.mrchecker.test.core.utils; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import java.util.stream.Collectors; + +public class ConcurrencyUtils { + + private static final int THREAD_COUNT = 8; + + private ConcurrencyUtils() { + } + + public static List getInstancesConcurrently(Supplier instanceSupplier) throws InterruptedException { + Collection> tasks = new ArrayList<>(); + InstanceGetter instanceGetter = new InstanceGetter<>(instanceSupplier); + for (int i = 0; i < THREAD_COUNT; i++) { + tasks.add(instanceGetter); + } + + ExecutorService executor = Executors.newFixedThreadPool(THREAD_COUNT); + List> instances = executor.invokeAll(tasks); + executor.shutdown(); + executor.awaitTermination(300, TimeUnit.MILLISECONDS); + + return instances.stream() + .map(future -> { + try { + return future.get(); + } catch (InterruptedException | ExecutionException e) { + e.printStackTrace(); + } + return null; + }) + .collect(Collectors.toList()); + } + + public static class InstanceGetter implements Callable { + + private static final CyclicBarrier barrier = new CyclicBarrier(THREAD_COUNT); + + private final Supplier instanceSupplier; + + public InstanceGetter(Supplier instanceSupplier) { + this.instanceSupplier = instanceSupplier; + } + + @Override + public T call() throws Exception { + barrier.await(); + return instanceSupplier.get(); + } + } +} \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/utils/FileUtils.java b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/utils/FileUtils.java new file mode 100644 index 00000000..7a76547b --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/utils/FileUtils.java @@ -0,0 +1,41 @@ +package com.capgemini.mrchecker.test.core.utils; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.stream.Collectors; + +public final class FileUtils { + + public static final String LOG_DIR = "./logs/"; + + private FileUtils() { + } + + public static String getLogFilePath() { + return LOG_DIR + Thread.currentThread() + .getName() + ".log"; + } + + public static String getEnvLogFilePath() { + return LOG_DIR + Thread.currentThread() + .getName() + "_env.log"; + } + + public static String getFirstLineInFile(String logFilePath) throws IOException { + return Files.lines(Paths.get(logFilePath)) + .findFirst() + .orElse(null); + } + + public static String getLastLineInFile(String logFilePath) throws IOException { + return Files.lines(Paths.get(logFilePath)) + .reduce((first, second) -> second) + .orElse(null); + } + + public static String getAllLinesInFile(String logFilePath) throws IOException { + return Files.lines(Paths.get(logFilePath)) + .collect(Collectors.joining()); + } +} diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/utils/TestLauncher.java b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/utils/TestLauncher.java new file mode 100644 index 00000000..f201a483 --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-core-module/src/test/java/com/capgemini/mrchecker/test/core/utils/TestLauncher.java @@ -0,0 +1,49 @@ +package com.capgemini.mrchecker.test.core.utils; + +import static org.junit.platform.engine.discovery.DiscoverySelectors.selectClass; + +import java.util.List; + +import org.junit.platform.launcher.Launcher; +import org.junit.platform.launcher.LauncherDiscoveryRequest; +import org.junit.platform.launcher.TestPlan; +import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder; +import org.junit.platform.launcher.core.LauncherFactory; +import org.junit.platform.launcher.listeners.SummaryGeneratingListener; +import org.junit.platform.launcher.listeners.TestExecutionSummary; + +import com.capgemini.mrchecker.test.core.BaseTest; + +import edu.emory.mathcs.backport.java.util.Collections; + +public final class TestLauncher { + + private TestLauncher() { + } + + public static TestExecutionSummary launch(Class testClass) { + + return launch(Collections.singletonList(testClass)); + } + + public static TestExecutionSummary launch(String className) throws ClassNotFoundException { + + return launch((Class) Class.forName(className)); + } + + public static TestExecutionSummary launch(List> testClasses) { + SummaryGeneratingListener listener = new SummaryGeneratingListener(); + + LauncherDiscoveryRequestBuilder requestBuilder = LauncherDiscoveryRequestBuilder.request(); + testClasses + .forEach(testClass -> requestBuilder.selectors(selectClass(testClass))); + + LauncherDiscoveryRequest request = requestBuilder.build(); + Launcher launcher = LauncherFactory.create(); + TestPlan testPlan = launcher.discover(request); + launcher.registerTestExecutionListeners(listener); + launcher.execute(request); + + return listener.getSummary(); + } +} diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/resources/allure.properties b/mrchecker-framework-modules/mrchecker-core-module/src/test/resources/allure.properties new file mode 100644 index 00000000..6c1e0bb1 --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-core-module/src/test/resources/allure.properties @@ -0,0 +1 @@ +allure.results.directory=target/allure-results \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/resources/datadriven/integration/running_tests.csv b/mrchecker-framework-modules/mrchecker-core-module/src/test/resources/datadriven/integration/running_tests.csv new file mode 100644 index 00000000..76bad0ed --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-core-module/src/test/resources/datadriven/integration/running_tests.csv @@ -0,0 +1,17 @@ +className,expectedOnTestSuccessCount,expectedOnTestFailureCount,expectedOnTestFinishCount,expectedOnTestClassFinishCount,expectedAreHooksCalled +PassingTestWithObserverAddedInTestMethod,1,0,1,1,true +PassingTestWithObserverAddedTwiceInTestMethod,1,0,1,1,true +PassingTestWithObserverAddedInBeforeAll,1,0,0,1,true +FailingTestDueToFailingAssertion,0,1,0,1,true +FailingTestDueToExceptionInTestMethod,0,1,0,1,true +FailingTestDueToExceptionInBeforeAll,0,0,0,1,false +FailingTestDueToExceptionInBeforeEach,0,1,0,1,false +FailingTestThatPassedExecutionDueToExceptionInAfterEach,0,1,0,1,true +FailingTestThatFailedExecutionDueToExceptionInAfterEach,0,1,0,1,true +FailingTestThatPassedExecutionDueToExceptionInAfterAll,1,0,0,1,true +FailingTestThatFailedExecutionDueToExceptionInAfterAll,0,1,0,1,true +DisabledTestWithObserverAddedInTestMethod,0,0,0,0,false +DisabledTestWithObserverAddedInBeforeAll,0,0,0,1,false +AbortTestWithObserverAddedInTestMethod,0,0,1,1,true +AbortTestWithObserverAddedInBeforeAll,0,0,0,1,true + diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/resources/junit-platform.properties b/mrchecker-framework-modules/mrchecker-core-module/src/test/resources/junit-platform.properties new file mode 100644 index 00000000..0a5f88f7 --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-core-module/src/test/resources/junit-platform.properties @@ -0,0 +1,8 @@ +junit.jupiter.extensions.autodetection.enabled=true +junit.jupiter.execution.parallel.enabled=true +#junit.jupiter.execution.parallel.mode.default=concurrent +junit.jupiter.execution.parallel.mode.default=same_thread +junit.jupiter.execution.parallel.mode.classes.default=concurrent +#junit.jupiter.execution.parallel.mode.classes.default=same_thread +junit.jupiter.execution.parallel.config.strategy=dynamic +junit.jupiter.execution.parallel.config.dynamic.factor=1 diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/resources/secretData_emptykey b/mrchecker-framework-modules/mrchecker-core-module/src/test/resources/secretData_emptykey deleted file mode 100644 index e69de29b..00000000 diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/resources/secretData_test b/mrchecker-framework-modules/mrchecker-core-module/src/test/resources/secretData_test deleted file mode 100644 index ed297b69..00000000 --- a/mrchecker-framework-modules/mrchecker-core-module/src/test/resources/secretData_test +++ /dev/null @@ -1 +0,0 @@ -LhwbTm9V3FUbBO5Tt5PiTUEQrXGgWrDLCMthnzLKNy1zA5FVTFiTdHRQAyPRIGXmsAjPUPlJSoSLeSBM \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/resources/secretData_test2 b/mrchecker-framework-modules/mrchecker-core-module/src/test/resources/secretData_test2 deleted file mode 100644 index 6d145081..00000000 --- a/mrchecker-framework-modules/mrchecker-core-module/src/test/resources/secretData_test2 +++ /dev/null @@ -1 +0,0 @@ -11LhwbTm9V3FUbBO5Tt5PiTUEQrXGgWrDLCMthnzLKNy1zA5FVTFiTdHRQAyPRIGXmsAjPUPlJSoSLeSBM \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/resources/settings2.properties b/mrchecker-framework-modules/mrchecker-core-module/src/test/resources/settings2.properties deleted file mode 100644 index a5db9898..00000000 --- a/mrchecker-framework-modules/mrchecker-core-module/src/test/resources/settings2.properties +++ /dev/null @@ -1,3 +0,0 @@ -core.isAnalyticsEnabled=false -core.isEncryptionEnabled=false -core.defaultEnvironmentName=NON_DEFAULT \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/resources/settings3.properties b/mrchecker-framework-modules/mrchecker-core-module/src/test/resources/settings3.properties deleted file mode 100644 index ea085abc..00000000 --- a/mrchecker-framework-modules/mrchecker-core-module/src/test/resources/settings3.properties +++ /dev/null @@ -1,2 +0,0 @@ -core.isAnalyticsEnabled=UNKNONW_STATUS -core.isEncryptionEnabled=UNKNONW_STATUS \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-core-module/src/test/resources/settings4.properties b/mrchecker-framework-modules/mrchecker-core-module/src/test/resources/settings4.properties deleted file mode 100644 index e69de29b..00000000 diff --git a/mrchecker-framework-modules/mrchecker-database-module/pom.xml b/mrchecker-framework-modules/mrchecker-database-module/pom.xml index 873e1ad2..469085d3 100644 --- a/mrchecker-framework-modules/mrchecker-database-module/pom.xml +++ b/mrchecker-framework-modules/mrchecker-database-module/pom.xml @@ -6,7 +6,7 @@ mrchecker-test-framework com.capgemini.mrchecker - 2.4.2-SNAPSHOT + 3.0.1-SNAPSHOT mrchecker-database-module 0.0.1-SNAPSHOT @@ -21,7 +21,8 @@ Examples build on Hibernate as a JPA provider. IMPORTANT: - For easy of use Lombok library was used. In case of compilation issues please apply newest Lombok plugin for your IDE. + For easy of use Lombok library was used. In case of compilation issues please apply newest Lombok plugin for + your IDE. https://github.com/devonfw/devonfw-testing @@ -60,13 +61,11 @@ - + UTF8 - 4.12.1.4-SNAPSHOT - 2.2 + 5.6.2.1-SNAPSHOT 2.2 - @@ -108,11 +107,22 @@ provided + + + + io.qameta.allure + allure-junit5 + test + + + + io.qameta.allure + allure-junit-platform + - io.qameta.allure - allure-junit4 + allure-java-commons diff --git a/mrchecker-framework-modules/mrchecker-database-module/src/main/java/com/capgemini/mrchecker/database/core/BasePageDatabase.java b/mrchecker-framework-modules/mrchecker-database-module/src/main/java/com/capgemini/mrchecker/database/core/BasePageDatabase.java index 92e5ea28..50b890ad 100644 --- a/mrchecker-framework-modules/mrchecker-database-module/src/main/java/com/capgemini/mrchecker/database/core/BasePageDatabase.java +++ b/mrchecker-framework-modules/mrchecker-database-module/src/main/java/com/capgemini/mrchecker/database/core/BasePageDatabase.java @@ -1,124 +1,105 @@ package com.capgemini.mrchecker.database.core; +import java.util.Objects; + +import javax.persistence.EntityManager; + import com.capgemini.mrchecker.database.core.base.properties.PropertiesFileSettings; import com.capgemini.mrchecker.database.core.base.runtime.RuntimeParameters; import com.capgemini.mrchecker.test.core.BaseTest; -import com.capgemini.mrchecker.test.core.BaseTestWatcher; -import com.capgemini.mrchecker.test.core.ITestObserver; import com.capgemini.mrchecker.test.core.ModuleType; +import com.capgemini.mrchecker.test.core.Page; import com.capgemini.mrchecker.test.core.analytics.IAnalytics; import com.capgemini.mrchecker.test.core.base.environment.IEnvironmentService; import com.capgemini.mrchecker.test.core.base.properties.PropertiesSettingsModule; import com.capgemini.mrchecker.test.core.logger.BFLogger; import com.google.inject.Guice; -import lombok.Getter; -import javax.persistence.EntityManager; - -abstract public class BasePageDatabase implements ITestObserver, IDatabasePrefixHolder { - - private final static PropertiesFileSettings propertiesFileSettings; - private static IEnvironmentService environmentService; - private final static IAnalytics analytics; +import lombok.Getter; +abstract public class BasePageDatabase extends Page implements IDatabasePrefixHolder { + + private final static PropertiesFileSettings PROPERTIES_FILE_SETTINGS; + private static IEnvironmentService environmentService; + private final static IAnalytics ANALYTICS; + @Getter protected EntityManager entityManager = null; - + public final static String analyticsCategoryName = "Database-Module"; - + static { // Get analytics instance created in BaseTest - analytics = BaseTest.getAnalytics(); - + ANALYTICS = BaseTest.getAnalytics(); + // Get and then set properties information from selenium.settings file - propertiesFileSettings = setPropertiesSettings(); - + PROPERTIES_FILE_SETTINGS = setPropertiesSettings(); + // Read System or maven parameters setRuntimeParametersDatabase(); - + // Read Environment variables either from environments.csv or any other input data. setEnvironmentInstance(); } - + public BasePageDatabase() { assignEntityManager(); } - - public static IAnalytics getAnalytics() { - return BasePageDatabase.analytics; + + public static IAnalytics getANALYTICS() { + return ANALYTICS; } - - @Override - public void addObserver() { - BaseTestWatcher.addObserver(this); - } - + @Override public void onTestFailure() { - BFLogger.logDebug("BasePage.onTestFailure " + this.getClass() - .getSimpleName()); + super.onTestFailure(); closeSession(); } - - @Override - public void onTestSuccess() { - // All actions needed while test method is success - BFLogger.logDebug("BasePage.onTestSuccess " + this.getClass() - .getSimpleName()); - } - - @Override - public void onTestFinish() { - // All actions needed while test class is finishing - BFLogger.logDebug("BasePage.onTestFinish " + this.getClass() - .getSimpleName()); - BaseTestWatcher.removeObserver(this); - } - + @Override public void onTestClassFinish() { closeSession(); BFLogger.logDebug("Session for connection: [" + getDatabaseUnitName() + "] closed."); + super.onTestClassFinish(); } - + @Override public ModuleType getModuleType() { return ModuleType.DATABASE; } - + private static PropertiesFileSettings setPropertiesSettings() { // Get and then set properties information from settings.properties file - PropertiesFileSettings propertiesFileSettings = Guice.createInjector(PropertiesSettingsModule.init()) + return Guice.createInjector(PropertiesSettingsModule.init()) .getInstance(PropertiesFileSettings.class); - return propertiesFileSettings; } - + private static void setRuntimeParametersDatabase() { // Read System or maven parameters BFLogger.logDebug(java.util.Arrays.asList(RuntimeParameters.values()) .toString()); - + } - + private void closeSession() { - if (entityManager != null) { + if (!Objects.isNull(entityManager)) { entityManager.close(); } } - + private void assignEntityManager() { - if (entityManager == null) { - this.entityManager = DriverManager.createEntityManager(getDatabaseUnitName()); + if (Objects.isNull(entityManager)) { + entityManager = DriverManager.createEntityManager(getDatabaseUnitName()); } } - + private static void setEnvironmentInstance() { /* * Environment variables either from environmnets.csv or any other input data. For now there is no properties * settings file for Selenium module. In future, please have a look on Core Module IEnvironmentService * environmetInstance = Guice.createInjector(new EnvironmentModule()) .getInstance(IEnvironmentService.class); */ - + } - + } \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-database-module/src/main/java/com/capgemini/mrchecker/database/core/BasePageDatabaseAutoRegistration.java b/mrchecker-framework-modules/mrchecker-database-module/src/main/java/com/capgemini/mrchecker/database/core/BasePageDatabaseAutoRegistration.java new file mode 100644 index 00000000..467f5094 --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-database-module/src/main/java/com/capgemini/mrchecker/database/core/BasePageDatabaseAutoRegistration.java @@ -0,0 +1,13 @@ +package com.capgemini.mrchecker.database.core; + +/** + * The instances of BasePageDatabaseAutoRegistration class are added to the test execution observer automatically in + * constructor. + * Although this operation is unsafe, it's been added to support migration from MrChecker Junit4 to Junit5. + */ +@Deprecated +abstract public class BasePageDatabaseAutoRegistration extends BasePageDatabase { + public BasePageDatabaseAutoRegistration() { + addToTestExecutionObserver(); + } +} \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-database-module/src/main/java/com/capgemini/mrchecker/database/core/DriverManager.java b/mrchecker-framework-modules/mrchecker-database-module/src/main/java/com/capgemini/mrchecker/database/core/DriverManager.java index a4af1f6c..e4f7dc31 100644 --- a/mrchecker-framework-modules/mrchecker-database-module/src/main/java/com/capgemini/mrchecker/database/core/DriverManager.java +++ b/mrchecker-framework-modules/mrchecker-database-module/src/main/java/com/capgemini/mrchecker/database/core/DriverManager.java @@ -3,6 +3,7 @@ import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; +import java.util.Objects; public class DriverManager { @@ -13,7 +14,7 @@ public static EntityManager createEntityManager(String dbPrefix) { } private static EntityManagerFactory getEntityManagerFactory(String dbPrefix) { - return emf != null ? emf : Persistence.createEntityManagerFactory(dbPrefix); + return Objects.isNull(emf) ? Persistence.createEntityManagerFactory(dbPrefix) : emf; } } diff --git a/mrchecker-framework-modules/mrchecker-database-module/src/main/java/com/capgemini/mrchecker/database/core/base/properties/PropertiesFileSettings.java b/mrchecker-framework-modules/mrchecker-database-module/src/main/java/com/capgemini/mrchecker/database/core/base/properties/PropertiesFileSettings.java index de238be2..ae81d655 100644 --- a/mrchecker-framework-modules/mrchecker-database-module/src/main/java/com/capgemini/mrchecker/database/core/base/properties/PropertiesFileSettings.java +++ b/mrchecker-framework-modules/mrchecker-database-module/src/main/java/com/capgemini/mrchecker/database/core/base/properties/PropertiesFileSettings.java @@ -5,7 +5,7 @@ public class PropertiesFileSettings { - private String dbDrivers = "./lib/dbdrivers"; + private final String dbDrivers = "./lib/dbdrivers"; private String jdbcOracle = dbDrivers + "/oracle/ojdbc8.jar"; private String proxy = ""; diff --git a/mrchecker-framework-modules/mrchecker-database-module/src/main/java/com/capgemini/mrchecker/database/core/base/runtime/RuntimeParameters.java b/mrchecker-framework-modules/mrchecker-database-module/src/main/java/com/capgemini/mrchecker/database/core/base/runtime/RuntimeParameters.java index 17e1b9f1..d2caf707 100644 --- a/mrchecker-framework-modules/mrchecker-database-module/src/main/java/com/capgemini/mrchecker/database/core/base/runtime/RuntimeParameters.java +++ b/mrchecker-framework-modules/mrchecker-database-module/src/main/java/com/capgemini/mrchecker/database/core/base/runtime/RuntimeParameters.java @@ -1,56 +1,57 @@ package com.capgemini.mrchecker.database.core.base.runtime; -import com.capgemini.mrchecker.test.core.base.runtime.RuntimeParametersI; - -public enum RuntimeParameters implements RuntimeParametersI { +import com.capgemini.mrchecker.test.core.base.runtime.IRuntimeParameters; +import org.apache.commons.lang3.StringUtils; +public enum RuntimeParameters implements IRuntimeParameters { + DATABASE_TYPE("databaseType", ""), JPA_PROVIDER("provider", "hibernate"), DATABASE_USERNAME("databaseUsername", ""); - - private String paramName; - private String paramValue; - private String defaultValue; - - private RuntimeParameters(String paramName, String defaultValue) { + + private final String paramName; + private String paramValue; + private final String defaultValue; + + RuntimeParameters(String paramName, String defaultValue) { this.paramName = paramName; this.defaultValue = defaultValue; setValue(); } - + @Override public String getValue() { - return this.paramValue; + return paramValue; } - + @Override public String getKey() { - return this.paramName; + return paramName; } - + @Override public String toString() { - return paramName + "=" + this.getValue(); + return getKey() + "=" + getValue(); } - + @Override public void refreshParameterValue() { setValue(); } - + private void setValue() { - - String paramValue = System.getProperty(this.paramName); - paramValue = isSystemParameterEmpty(paramValue) ? this.defaultValue : paramValue.toLowerCase(); - + + String paramValue = System.getProperty(paramName); + paramValue = isSystemParameterEmpty(paramValue) ? defaultValue : paramValue.toLowerCase(); + switch (this.name()) { } - + this.paramValue = paramValue; } - + private boolean isSystemParameterEmpty(String systemParameterValue) { - return (null == systemParameterValue || "".equals(systemParameterValue) || "null".equals(systemParameterValue)); + return (StringUtils.isEmpty(systemParameterValue) || "null".equals(systemParameterValue)); } - + } diff --git a/mrchecker-framework-modules/mrchecker-database-module/src/test/java/com/capgemini/mrchecker/database/tags/IntegrationTest.java b/mrchecker-framework-modules/mrchecker-database-module/src/test/java/com/capgemini/mrchecker/database/tags/IntegrationTest.java new file mode 100644 index 00000000..285939bd --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-database-module/src/test/java/com/capgemini/mrchecker/database/tags/IntegrationTest.java @@ -0,0 +1,14 @@ +package com.capgemini.mrchecker.database.tags; + +import org.junit.jupiter.api.Tag; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +@Tag("IntegrationTest") +public @interface IntegrationTest { +} \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-database-module/src/test/java/com/capgemini/mrchecker/database/tags/UnitTest.java b/mrchecker-framework-modules/mrchecker-database-module/src/test/java/com/capgemini/mrchecker/database/tags/UnitTest.java new file mode 100644 index 00000000..89525d70 --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-database-module/src/test/java/com/capgemini/mrchecker/database/tags/UnitTest.java @@ -0,0 +1,14 @@ +package com.capgemini.mrchecker.database.tags; + +import org.junit.jupiter.api.Tag; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +@Tag("UnitTest") +public @interface UnitTest { +} \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-database-module/src/test/java/com/capgemini/mrchecker/database/testsuites/UnitTestsSuite.java b/mrchecker-framework-modules/mrchecker-database-module/src/test/java/com/capgemini/mrchecker/database/testsuites/UnitTestsSuite.java new file mode 100644 index 00000000..9c83c221 --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-database-module/src/test/java/com/capgemini/mrchecker/database/testsuites/UnitTestsSuite.java @@ -0,0 +1,12 @@ +package com.capgemini.mrchecker.database.testsuites; + +import org.junit.platform.runner.JUnitPlatform; +import org.junit.platform.suite.api.IncludeTags; +import org.junit.platform.suite.api.SelectPackages; +import org.junit.runner.RunWith; + +@RunWith(JUnitPlatform.class) +@IncludeTags({ "UnitTest" }) +@SelectPackages("com.capgemini.mrchecker.database") +public class UnitTestsSuite { +} diff --git a/mrchecker-framework-modules/mrchecker-database-module/src/test/java/com/capgemini/mrchecker/database/BaseDatabaseTest.java b/mrchecker-framework-modules/mrchecker-database-module/src/test/java/com/capgemini/mrchecker/database/unit/BaseDatabaseTest.java similarity index 63% rename from mrchecker-framework-modules/mrchecker-database-module/src/test/java/com/capgemini/mrchecker/database/BaseDatabaseTest.java rename to mrchecker-framework-modules/mrchecker-database-module/src/test/java/com/capgemini/mrchecker/database/unit/BaseDatabaseTest.java index 11e20b18..337d3393 100644 --- a/mrchecker-framework-modules/mrchecker-database-module/src/test/java/com/capgemini/mrchecker/database/BaseDatabaseTest.java +++ b/mrchecker-framework-modules/mrchecker-database-module/src/test/java/com/capgemini/mrchecker/database/unit/BaseDatabaseTest.java @@ -1,13 +1,14 @@ -package com.capgemini.mrchecker.database; +package com.capgemini.mrchecker.database.unit; -import org.junit.Test; +import com.capgemini.mrchecker.database.tags.UnitTest; +import org.junit.jupiter.api.Test; +@UnitTest public class BaseDatabaseTest { @Test public void test() { MyDatabase myDatabase = new MyDatabase(); - myDatabase.myMethod(); } diff --git a/mrchecker-framework-modules/mrchecker-database-module/src/test/java/com/capgemini/mrchecker/database/base/EntityManagerTest.java b/mrchecker-framework-modules/mrchecker-database-module/src/test/java/com/capgemini/mrchecker/database/unit/base/EntityManagerTest.java similarity index 68% rename from mrchecker-framework-modules/mrchecker-database-module/src/test/java/com/capgemini/mrchecker/database/base/EntityManagerTest.java rename to mrchecker-framework-modules/mrchecker-database-module/src/test/java/com/capgemini/mrchecker/database/unit/base/EntityManagerTest.java index 4eb61dd2..cca25dd9 100644 --- a/mrchecker-framework-modules/mrchecker-database-module/src/test/java/com/capgemini/mrchecker/database/base/EntityManagerTest.java +++ b/mrchecker-framework-modules/mrchecker-database-module/src/test/java/com/capgemini/mrchecker/database/unit/base/EntityManagerTest.java @@ -1,17 +1,19 @@ -package com.capgemini.mrchecker.database.base; +package com.capgemini.mrchecker.database.unit.base; -import com.capgemini.mrchecker.database.base.database.MySqlDatabase; -import org.junit.Before; -import org.junit.Test; +import com.capgemini.mrchecker.database.tags.UnitTest; +import com.capgemini.mrchecker.database.unit.base.database.MySqlDatabase; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; +@UnitTest public class EntityManagerTest { private MySqlDatabase mySqlDatabase; - @Before + @BeforeEach public void setUp() throws Exception { mySqlDatabase = new MySqlDatabase(); } diff --git a/mrchecker-framework-modules/mrchecker-database-module/src/test/java/com/capgemini/mrchecker/database/base/database/MySqlDatabase.java b/mrchecker-framework-modules/mrchecker-database-module/src/test/java/com/capgemini/mrchecker/database/unit/base/database/MySqlDatabase.java similarity index 61% rename from mrchecker-framework-modules/mrchecker-database-module/src/test/java/com/capgemini/mrchecker/database/base/database/MySqlDatabase.java rename to mrchecker-framework-modules/mrchecker-database-module/src/test/java/com/capgemini/mrchecker/database/unit/base/database/MySqlDatabase.java index 4209e473..b7bcfa92 100644 --- a/mrchecker-framework-modules/mrchecker-database-module/src/test/java/com/capgemini/mrchecker/database/base/database/MySqlDatabase.java +++ b/mrchecker-framework-modules/mrchecker-database-module/src/test/java/com/capgemini/mrchecker/database/unit/base/database/MySqlDatabase.java @@ -1,7 +1,9 @@ -package com.capgemini.mrchecker.database.base.database; +package com.capgemini.mrchecker.database.unit.base.database; import com.capgemini.mrchecker.database.core.BasePageDatabase; +import com.capgemini.mrchecker.database.tags.UnitTest; +@UnitTest public class MySqlDatabase extends BasePageDatabase { @Override public String getDatabaseUnitName() { diff --git a/mrchecker-framework-modules/mrchecker-database-module/src/test/resources/allure.properties b/mrchecker-framework-modules/mrchecker-database-module/src/test/resources/allure.properties new file mode 100644 index 00000000..6c1e0bb1 --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-database-module/src/test/resources/allure.properties @@ -0,0 +1 @@ +allure.results.directory=target/allure-results \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-database-module/src/test/resources/junit-platform.properties b/mrchecker-framework-modules/mrchecker-database-module/src/test/resources/junit-platform.properties new file mode 100644 index 00000000..0a5f88f7 --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-database-module/src/test/resources/junit-platform.properties @@ -0,0 +1,8 @@ +junit.jupiter.extensions.autodetection.enabled=true +junit.jupiter.execution.parallel.enabled=true +#junit.jupiter.execution.parallel.mode.default=concurrent +junit.jupiter.execution.parallel.mode.default=same_thread +junit.jupiter.execution.parallel.mode.classes.default=concurrent +#junit.jupiter.execution.parallel.mode.classes.default=same_thread +junit.jupiter.execution.parallel.config.strategy=dynamic +junit.jupiter.execution.parallel.config.dynamic.factor=1 diff --git a/mrchecker-framework-modules/mrchecker-mobile-module/pom.xml b/mrchecker-framework-modules/mrchecker-mobile-module/pom.xml index 9ca5a597..63cd9b1b 100644 --- a/mrchecker-framework-modules/mrchecker-mobile-module/pom.xml +++ b/mrchecker-framework-modules/mrchecker-mobile-module/pom.xml @@ -7,10 +7,11 @@ mrchecker-test-framework com.capgemini.mrchecker - 2.4.2-SNAPSHOT + 3.0.1-SNAPSHOT + mrchecker-mobile-module - 7.2.0.2-SNAPSHOT + 7.2.0.3-SNAPSHOT jar MrChecker - Mobile - Module MrChecker Test Framework name supports: @@ -52,7 +53,7 @@ UTF8 - 4.12.1.4-SNAPSHOT + 5.6.2.1-SNAPSHOT 7.2.0 @@ -76,10 +77,22 @@ jasypt - + + + + io.qameta.allure + allure-junit5 + test + + + + io.qameta.allure + allure-junit-platform + + io.qameta.allure - allure-junit4 + allure-java-commons diff --git a/mrchecker-framework-modules/mrchecker-mobile-module/src/main/java/com/capgemini/mrchecker/mobile/core/BasePage.java b/mrchecker-framework-modules/mrchecker-mobile-module/src/main/java/com/capgemini/mrchecker/mobile/core/BasePage.java index 5af9ad99..f0efb677 100644 --- a/mrchecker-framework-modules/mrchecker-mobile-module/src/main/java/com/capgemini/mrchecker/mobile/core/BasePage.java +++ b/mrchecker-framework-modules/mrchecker-mobile-module/src/main/java/com/capgemini/mrchecker/mobile/core/BasePage.java @@ -1,15 +1,18 @@ package com.capgemini.mrchecker.mobile.core; +import java.util.Objects; +import org.openqa.selenium.OutputType; +import org.openqa.selenium.TakesScreenshot; +import org.openqa.selenium.UnhandledAlertException; import com.capgemini.mrchecker.mobile.core.base.driver.DriverManager; import com.capgemini.mrchecker.mobile.core.base.driver.INewMobileDriver; import com.capgemini.mrchecker.mobile.core.base.properties.PropertiesFileSettings; import com.capgemini.mrchecker.mobile.core.base.runtime.RuntimeParameters; import com.capgemini.mrchecker.test.core.BaseTest; -import com.capgemini.mrchecker.test.core.BaseTestWatcher; -import com.capgemini.mrchecker.test.core.ITestObserver; import com.capgemini.mrchecker.test.core.ModuleType; +import com.capgemini.mrchecker.test.core.Page; import com.capgemini.mrchecker.test.core.analytics.IAnalytics; import com.capgemini.mrchecker.test.core.base.environment.IEnvironmentService; import com.capgemini.mrchecker.test.core.base.properties.PropertiesSettingsModule; @@ -17,80 +20,48 @@ import com.google.inject.Guice; import io.qameta.allure.Attachment; -import org.openqa.selenium.OutputType; -import org.openqa.selenium.TakesScreenshot; -import org.openqa.selenium.UnhandledAlertException; -abstract public class BasePage implements ITestObserver { +abstract public class BasePage extends Page { private static DriverManager driver = null; - private final static PropertiesFileSettings propertiesFileSettings; - private static IEnvironmentService environmentService; - private final static IAnalytics analytics; - public final static String analitycsCategoryName = "Mobile"; + private final static PropertiesFileSettings PROPERTIES_FILE_SETTINGS; + private static IEnvironmentService environmentService; + private final static IAnalytics ANALYTICS; + public final static String ANALYTICS_CATEGORY_NAME = "Mobile"; static { // Get analytics instance created in BaseTets - analytics = BaseTest.getAnalytics(); + ANALYTICS = BaseTest.getAnalytics(); // Get and then set properties information from mobile.settings file - propertiesFileSettings = setPropertiesSettings(); + PROPERTIES_FILE_SETTINGS = setPropertiesSettings(); // Read System or maven parameters setRuntimeParametersSelenium(); // Read Environment variables either from environmnets.csv or any other input data. - setEnvironmetInstance(); + setEnvironmentInstance(); } public static IAnalytics getAnalytics() { - return BasePage.analytics; + return ANALYTICS; } public BasePage() { - this(getDriver()); - } - - public BasePage(INewMobileDriver driver) { - // Add given module to Test core Observable list - this.addObserver(); - - } - - @Override - public void addObserver() { - BaseTestWatcher.addObserver(this); + getDriver(); } @Override public void onTestFailure() { - BFLogger.logDebug("BasePage.onTestFailure " + this.getClass() - .getSimpleName()); + super.onTestFailure(); makeScreenshotOnFailure(); makeSourcePageOnFailure(); } - @Override - public void onTestSuccess() { - // All actions needed while test method is success - BFLogger.logDebug("BasePage.onTestSuccess " + this.getClass() - .getSimpleName()); - } - - @Override - public void onTestFinish() { - // All actions needed while test class is finishing - BFLogger.logDebug("BasePage.onTestFinish " + this.getClass() - .getSimpleName()); - BaseTestWatcher.removeObserver(this); - } - @Override public void onTestClassFinish() { - BFLogger.logDebug("BasePage.onTestClassFinish " + this.getClass() - .getSimpleName()); - BFLogger.logDebug("driver:" + getDriver().toString()); + super.onTestClassFinish(); DriverManager.closeDriver(); } @@ -98,7 +69,7 @@ public void onTestClassFinish() { public ModuleType getModuleType() { return ModuleType.MOBILE; } - + @Attachment("Screenshot on failure") public byte[] makeScreenshotOnFailure() { byte[] screenshot = null; @@ -109,7 +80,7 @@ public byte[] makeScreenshotOnFailure() { } return screenshot; } - + @Attachment("Source Page on failure") public String makeSourcePageOnFailure() { return DriverManager.getDriver() @@ -117,19 +88,19 @@ public String makeSourcePageOnFailure() { } public static INewMobileDriver getDriver() { - if (BasePage.driver == null) { + if (Objects.isNull(driver)) { // Create module driver - BasePage.driver = new DriverManager(propertiesFileSettings); + driver = new DriverManager(PROPERTIES_FILE_SETTINGS); } - return BasePage.driver.getDriver(); + + return driver.getDriver(); } - + private static PropertiesFileSettings setPropertiesSettings() { // Get and then set properties information from settings.properties file - PropertiesFileSettings propertiesFileSettings = Guice.createInjector(PropertiesSettingsModule.init()) + return Guice.createInjector(PropertiesSettingsModule.init()) .getInstance(PropertiesFileSettings.class); - return propertiesFileSettings; } private static void setRuntimeParametersSelenium() { @@ -139,7 +110,7 @@ private static void setRuntimeParametersSelenium() { } - private static void setEnvironmetInstance() { + private static void setEnvironmentInstance() { /* * Environment variables either from environmnets.csv or any other input data. For now there is no properties * settings file for Selenium module. In future, please have a look on Core Module IEnvironmentService @@ -147,5 +118,4 @@ private static void setEnvironmetInstance() { */ } - } diff --git a/mrchecker-framework-modules/mrchecker-mobile-module/src/main/java/com/capgemini/mrchecker/mobile/core/BasePageAutoRegistration.java b/mrchecker-framework-modules/mrchecker-mobile-module/src/main/java/com/capgemini/mrchecker/mobile/core/BasePageAutoRegistration.java new file mode 100644 index 00000000..2d7a0df3 --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-mobile-module/src/main/java/com/capgemini/mrchecker/mobile/core/BasePageAutoRegistration.java @@ -0,0 +1,13 @@ +package com.capgemini.mrchecker.mobile.core; + +/** + * The instances of BasePageAutoRegistration class are added to the test execution observer automatically in + * constructor. + * Although this operation is unsafe, it's been added to support migration from MrChecker Junit4 to Junit5. + */ +@Deprecated +abstract public class BasePageAutoRegistration extends BasePage { + public BasePageAutoRegistration() { + addToTestExecutionObserver(); + } +} diff --git a/mrchecker-framework-modules/mrchecker-mobile-module/src/main/java/com/capgemini/mrchecker/mobile/core/base/driver/DriverManager.java b/mrchecker-framework-modules/mrchecker-mobile-module/src/main/java/com/capgemini/mrchecker/mobile/core/base/driver/DriverManager.java index 354ccd79..8473bb76 100644 --- a/mrchecker-framework-modules/mrchecker-mobile-module/src/main/java/com/capgemini/mrchecker/mobile/core/base/driver/DriverManager.java +++ b/mrchecker-framework-modules/mrchecker-mobile-module/src/main/java/com/capgemini/mrchecker/mobile/core/base/driver/DriverManager.java @@ -1,49 +1,53 @@ package com.capgemini.mrchecker.mobile.core.base.driver; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Arrays; +import java.util.Objects; + +import org.openqa.selenium.WebDriverException; +import org.openqa.selenium.remote.DesiredCapabilities; +import com.capgemini.mrchecker.mobile.core.base.exceptions.BFAppiumServerNotConnectedException; import com.capgemini.mrchecker.mobile.core.base.properties.PropertiesFileSettings; import com.capgemini.mrchecker.mobile.core.base.runtime.RuntimeParameters; import com.capgemini.mrchecker.test.core.logger.BFLogger; -import com.capgemini.mrchecker.mobile.core.base.exceptions.BFAppiumServerNotConnectedException; import com.google.inject.Inject; import com.google.inject.name.Named; -import io.appium.java_client.AppiumDriver; -import io.appium.java_client.android.AndroidDriver; -import org.openqa.selenium.WebDriverException; -import org.openqa.selenium.remote.DesiredCapabilities; -import java.net.MalformedURLException; -import java.net.URL; +import io.appium.java_client.android.AndroidDriver; public class DriverManager { - - private static ThreadLocal drivers = new ThreadLocal<>(); - + + private static final ThreadLocal drivers = new ThreadLocal<>(); + // Setup default variables - private static PropertiesFileSettings propertiesFileSettings; - + private static PropertiesFileSettings propertiesFileSettings; + @Inject public DriverManager(@Named("properties") PropertiesFileSettings propertiesFileSettings) { - - if (null == DriverManager.propertiesFileSettings) { + + if (Objects.isNull(DriverManager.propertiesFileSettings)) { DriverManager.propertiesFileSettings = propertiesFileSettings; } - - this.start(); + + start(); } - + public void start() { DriverManager.getDriver(); } - + public void stop() { try { closeDriver(); BFLogger.logDebug("Closing Driver in stop()"); } catch (Exception e) { + // TODO: implement that } } - + + // TODO: refactor that @Override protected void finalize() throws Throwable { super.finalize(); @@ -52,12 +56,12 @@ protected void finalize() throws Throwable { BFLogger.logDebug("Closing Driver in finalize()"); } catch (Exception e) { } - + } - + public static INewMobileDriver getDriver() { INewMobileDriver driver = drivers.get(); - if (driver == null) { + if (Objects.isNull(driver)) { BFLogger.logDebug("Creating new " + RuntimeParameters.PLATFORM_NAME.toString() + " WebDriver."); driver = setupAppiumServer(); drivers.set(driver); @@ -65,11 +69,11 @@ public static INewMobileDriver getDriver() { } return driver; } - + public static AndroidDriver getDriverAndroid() { - //TODO: Validate cast !!!!! + // TODO: Validate cast !!!!! NewAndroidDriver driver = (NewAndroidDriver) drivers.get(); - if (driver == null) { + if (Objects.isNull(driver)) { BFLogger.logDebug("Creating new Android " + RuntimeParameters.PLATFORM_NAME.toString() + " WebDriver."); driver = setupAndroidSession(); drivers.set(driver); @@ -77,11 +81,10 @@ public static AndroidDriver getDriverAndroid() { } return driver; } - - + public static void closeDriver() { INewMobileDriver driver = drivers.get(); - if (driver == null) { + if (Objects.isNull(driver)) { BFLogger.logDebug("closeDriver() was called but there was no driver for this thread."); } else { try { @@ -96,16 +99,15 @@ public static void closeDriver() { } } } - + /** * Method sets desired 'driver' depends on chosen parameters */ private static INewMobileDriver createDriver() { BFLogger.logDebug("Creating new " + RuntimeParameters.PLATFORM_NAME.toString() + " WebDriver."); - INewMobileDriver driver = setupAppiumServer(); - return driver; + return setupAppiumServer(); } - + /** * Method sets Appium session */ @@ -116,7 +118,7 @@ private static INewMobileDriver setupAppiumServer() { throw new BFAppiumServerNotConnectedException(e); } } - + /** * Method sets Android session */ @@ -127,354 +129,356 @@ private static NewAndroidDriver setupAndroidSession() { throw new BFAppiumServerNotConnectedException(e); } } - - + /** * Method sets desired 'driver' depends on chosen parameters */ -// private static INewMobileDriver setupDevice() { -// String device = RuntimeParameters.DEVICE_NAME.getValue(); -// switch (device) { -// case "android": -// return Driver.ANDROID.getDriver(); -// case "ios": -// return Driver.IOS.getDriver(); -// case "windows": -// return Driver.WINDOWS.getDriver(); -// default: -// throw new RuntimeException("Unable to setup [" + device + "] device. Name not recognized. Possible values: android, ios, windows"); -// } -// } - + // private static INewMobileDriver setupDevice() { + // String device = RuntimeParameters.DEVICE_NAME.getValue(); + // switch (device) { + // case "android": + // return Driver.ANDROID.getDriver(); + // case "ios": + // return Driver.IOS.getDriver(); + // case "windows": + // return Driver.WINDOWS.getDriver(); + // default: + // throw new RuntimeException("Unable to setup [" + device + "] device. Name not recognized. Possible values: + // android, ios, windows"); + // } + // } + private enum Driver { - -// ANDROID { -// @Override -// public INewMobileDriver getDriver() { -// String browserPath = DriverManager.propertiesFileSettings.getSeleniumChrome(); -// boolean isDriverAutoUpdateActivated = DriverManager.propertiesFileSettings.getDriverAutoUpdateFlag(); -// synchronized (this) { -// if (isDriverAutoUpdateActivated && !driverDownloadedChrome) { -// if (!DriverManager.propertiesFileSettings.getChromeDriverVersion().equals("")) { -// System.setProperty("wdm.chromeDriverVersion", DriverManager.propertiesFileSettings.getChromeDriverVersion()); -// } -// downloadNewestOrGivenVersionOfWebDriver(ChromeDriver.class); -// OperationsOnFiles.moveWithPruneEmptydirectories(WebDriverManager.getInstance(ChromeDriver.class) -// .getBinaryPath(), browserPath); -// } -// driverDownloadedChrome = true; -// } -// -// System.setProperty("webdriver.chrome.driver", browserPath); -// -// // https://github.com/appium/appium/tree/master/sample-code/java/src -// -//// AndroidCreateSessionTest https://github.com/appium/appium/blob/master/sample-code/java/src/AndroidCreateSessionTest.java -//// File classpathRoot = new File(System.getProperty("user.dir")); -//// File appDir = new File(classpathRoot, "../apps"); -//// File app = new File(appDir.getCanonicalPath(), "ApiDemos-debug.apk"); -//// DesiredCapabilities capabilities = new DesiredCapabilities(); -//// capabilities.setCapability("deviceName", "Android Emulator"); -//// capabilities.setCapability("app", app.getAbsolutePath()); -//// capabilities.setCapability("appPackage", "io.appium.android.apis"); -//// capabilities.setCapability("appActivity", ".ApiDemos"); -//// driver = new AndroidDriver(getServiceUrl(), capabilities); -// -//// AndroidCreateWebSessionTest https://github.com/appium/appium/blob/master/sample-code/java/src/AndroidCreateWebSessionTest.java -//// DesiredCapabilities capabilities = new DesiredCapabilities(); -//// capabilities.setCapability("deviceName", "Android Emulator"); -//// capabilities.setCapability("browserName", "Chrome"); -//// driver = new AndroidDriver(getServiceUrl(), capabilities); -// -// HashMap chromePrefs = new HashMap(); -// chromePrefs.put("download.default_directory", DOWNLOAD_DIR); -// chromePrefs.put("profile.content_settings.pattern_pairs.*.multiple-automatic-downloads", 1); -// ChromeOptions options = new ChromeOptions(); -// options.setExperimentalOption("prefs", chromePrefs); -// options.addArguments("--test-type"); -// -// // Set users browser options -// RuntimeParameters.DEVICE_OPTIONS.getValues() -// .forEach((key, value) -> { -// BFLogger.logInfo("Device option: " + key + " " + value); -// String item = (value.toString() -// .isEmpty()) ? key : key + "=" + value; -// options.addArguments(item); -// }); -// -// // DesiredCapabilities cap = DesiredCapabilities.chrome(); -// // cap.setCapability(ChromeOptions.CAPABILITY, options); -// -// //TODO Add capabilities added by user -// -//// AndroidCreateSessionTest https://github.com/appium/appium/blob/master/sample-code/java/src/AndroidCreateSessionTest.java -// File classpathRoot = new File(System.getProperty("user.dir")); -// File appDir = new File(classpathRoot, "../apps"); -// File app = null; -// try { -// app = new File(appDir.getCanonicalPath(), "ApiDemos-debug.apk"); -// } catch (IOException e) { -// e.printStackTrace(); -// } -// DesiredCapabilities capabilities = new DesiredCapabilities(); -// capabilities.setCapability("deviceName", "Android Emulator"); -// capabilities.setCapability("app", app.getAbsolutePath()); -// capabilities.setCapability("appPackage", "io.appium.android.apis"); -// capabilities.setCapability("appActivity", ".ApiDemos"); -// -// INewMobileDriver driver = new NewAndroidDriver(capabilities); -// return driver; -// } -// -// }, -// IOS { -// @Override -// public INewMobileDriver getDriver() { -// String browserPath = DriverManager.propertiesFileSettings.getSeleniumChrome(); -// boolean isDriverAutoUpdateActivated = DriverManager.propertiesFileSettings.getDriverAutoUpdateFlag(); -// synchronized (this) { -// if (isDriverAutoUpdateActivated && !driverDownloadedChrome) { -// if (!DriverManager.propertiesFileSettings.getChromeDriverVersion().equals("")) { -// System.setProperty("wdm.chromeDriverVersion", DriverManager.propertiesFileSettings.getChromeDriverVersion()); -// } -// downloadNewestOrGivenVersionOfWebDriver(ChromeDriver.class); -// OperationsOnFiles.moveWithPruneEmptydirectories(WebDriverManager.getInstance(ChromeDriver.class) -// .getBinaryPath(), browserPath); -// } -// driverDownloadedChrome = true; -// } -// -// System.setProperty("webdriver.chrome.driver", browserPath); -// -// // https://github.com/appium/appium/tree/master/sample-code/java/src -// -// // IOSCreateSessionTest https://github.com/appium/appium/blob/master/sample-code/java/src/IOSCreateSessionTest.java -// // File classpathRoot = new File(System.getProperty("user.dir")); -// // File appDir = new File(classpathRoot, "../apps"); -// // File app = new File(appDir.getCanonicalPath(), "TestApp.app.zip"); -// // String deviceName = System.getenv("IOS_DEVICE_NAME"); -// // String platformVersion = System.getenv("IOS_PLATFORM_VERSION"); -// // DesiredCapabilities capabilities = new DesiredCapabilities(); -// // capabilities.setCapability("deviceName", deviceName == null ? "iPhone 6s" : deviceName); -// // capabilities.setCapability("platformVersion", platformVersion == null ? "11.1" : platformVersion); -// // capabilities.setCapability("app", app.getAbsolutePath()); -// // capabilities.setCapability("automationName", "XCUITest"); -// // driver = new IOSDriver(getServiceUrl(), capabilities); -// -// // IOSCreateWebSessionTest https://github.com/appium/appium/blob/master/sample-code/java/src/IOSCreateWebSessionTest.java -// // String deviceName = System.getenv("IOS_DEVICE_NAME"); -// // String platformVersion = System.getenv("IOS_PLATFORM_VERSION"); -// // DesiredCapabilities capabilities = new DesiredCapabilities(); -// // capabilities.setCapability("deviceName", deviceName == null ? "iPhone 6s" : deviceName); -// // capabilities.setCapability("platformVersion", platformVersion == null ? "11.1" : platformVersion); -// // capabilities.setCapability("browserName", "Safari"); -// // capabilities.setCapability("automationName", "XCUITest"); -// // driver = new IOSDriver(getServiceUrl(), capabilities); -// -// HashMap chromePrefs = new HashMap(); -// chromePrefs.put("download.default_directory", DOWNLOAD_DIR); -// chromePrefs.put("profile.content_settings.pattern_pairs.*.multiple-automatic-downloads", 1); -// ChromeOptions options = new ChromeOptions(); -// options.setExperimentalOption("prefs", chromePrefs); -// options.addArguments("--test-type"); -// -// // Set users browser options -// RuntimeParameters.BROWSER_OPTIONS.getValues() -// .forEach((key, value) -> { -// BFLogger.logInfo("Browser option: " + key + " " + value); -// String item = (value.toString() -// .isEmpty()) ? key : key + "=" + value; -// options.addArguments(item); -// }); -// -// // DesiredCapabilities cap = DesiredCapabilities.chrome(); -// // cap.setCapability(ChromeOptions.CAPABILITY, options); -// -// INewMobileDriver driver = new NewChromeDriver(options); -// return driver; -// } -// -// }, -// WINDOWS { -// @Override -// public INewMobileDriver getDriver() { -// String browserPath = DriverManager.propertiesFileSettings.getSeleniumChrome(); -// boolean isDriverAutoUpdateActivated = DriverManager.propertiesFileSettings.getDriverAutoUpdateFlag(); -// synchronized (this) { -// if (isDriverAutoUpdateActivated && !driverDownloadedChrome) { -// if (!DriverManager.propertiesFileSettings.getChromeDriverVersion().equals("")) { -// System.setProperty("wdm.chromeDriverVersion", DriverManager.propertiesFileSettings.getChromeDriverVersion()); -// } -// downloadNewestOrGivenVersionOfWebDriver(ChromeDriver.class); -// OperationsOnFiles.moveWithPruneEmptydirectories(WebDriverManager.getInstance(ChromeDriver.class) -// .getBinaryPath(), browserPath); -// } -// driverDownloadedChrome = true; -// } -// -// System.setProperty("webdriver.chrome.driver", browserPath); -// -// // https://github.com/appium/appium/blob/master/sample-code/java/src/WindowsDesktopAppTest.java -// -// // WindowsDesktopAppTest -// // DesiredCapabilities caps = new DesiredCapabilities(); -// // caps.setCapability("platformVersion", "10"); -// // caps.setCapability("platformName", "Windows"); -// // caps.setCapability("deviceName", "WindowsPC"); -// // caps.setCapability("app", "Microsoft.WindowsCalculator_8wekyb3d8bbwe!App"); -// // caps.setCapability("newCommandTimeout", 2000); -// // driver = new WindowsDriver<>(getServiceUrl(), caps); -// -// HashMap chromePrefs = new HashMap(); -// chromePrefs.put("download.default_directory", DOWNLOAD_DIR); -// chromePrefs.put("profile.content_settings.pattern_pairs.*.multiple-automatic-downloads", 1); -// ChromeOptions options = new ChromeOptions(); -// options.setExperimentalOption("prefs", chromePrefs); -// options.addArguments("--test-type"); -// -// // Set users browser options -// RuntimeParameters.BROWSER_OPTIONS.getValues() -// .forEach((key, value) -> { -// BFLogger.logInfo("Browser option: " + key + " " + value); -// String item = (value.toString() -// .isEmpty()) ? key : key + "=" + value; -// options.addArguments(item); -// }); -// -// // DesiredCapabilities cap = DesiredCapabilities.chrome(); -// // cap.setCapability(ChromeOptions.CAPABILITY, options); -// -// INewMobileDriver driver = new NewChromeDriver(options); -// return driver; -// } -// -// }, -// APPIUM_SERVER { -// @Override -// public INewMobileDriver getDriver() { -// -// final String APPIUM_SERVER_URL = RuntimeParameters.DEVICE_URL.getValue() + "/wd/hub"; -// BFLogger.logDebug("Connecting to the Appium Server: " + APPIUM_SERVER_URL); -// -// DesiredCapabilities capabilities = new DesiredCapabilities(); -// capabilities.setCapability(RuntimeParameters.AUTOMATION_NAME.getKey(), RuntimeParameters.AUTOMATION_NAME.getValue()); -// capabilities.setCapability(RuntimeParameters.PLATFORM_NAME.getKey(), RuntimeParameters.PLATFORM_NAME.getValue()); -// capabilities.setCapability(RuntimeParameters.PLATFORM_VERSION.getKey(), RuntimeParameters.PLATFORM_VERSION.getValue()); -// capabilities.setCapability(RuntimeParameters.DEVICE_NAME.getKey(), RuntimeParameters.DEVICE_NAME.getValue()); -// capabilities.setCapability(RuntimeParameters.APP.getKey(), RuntimeParameters.APP.getValue()); -// capabilities.setCapability(RuntimeParameters.BROWSER_NAME.getKey(), RuntimeParameters.BROWSER_NAME.getValue()); -// -// // Set users device options -// RuntimeParameters.DEVICE_OPTIONS.getValues() -// .forEach((key, value) -> { -// BFLogger.logInfo("Device option: " + key + " " + value); -// capabilities.setCapability(key, value); -// }); -// -// NewAppiumDriver newRemoteWebDriver = null; -// try { -// URL url = new URL(APPIUM_SERVER_URL); -// //url = new URL("http://target_ip:used_port/wd/hub"); -// //if it needs to use locally started server -// //then the target_ip is 127.0.0.1 or 0.0.0.0 -// //the default port is 4723 -// BFLogger.logDebug("Capabilities: " + capabilities.toJson()); -// newRemoteWebDriver = new NewAppiumDriver(url, capabilities); -// } catch (MalformedURLException e) { -// BFLogger.logError("Unable connect to Appium Server URL: " + APPIUM_SERVER_URL); -// } -// return newRemoteWebDriver; -// } -// }; -// -// -// -// public INewMobileDriver getDriver() { -// return null; -// } - + + // ANDROID { + // @Override + // public INewMobileDriver getDriver() { + // String browserPath = DriverManager.propertiesFileSettings.getSeleniumChrome(); + // boolean isDriverAutoUpdateActivated = DriverManager.propertiesFileSettings.getDriverAutoUpdateFlag(); + // synchronized (this) { + // if (isDriverAutoUpdateActivated && !driverDownloadedChrome) { + // if (!DriverManager.propertiesFileSettings.getChromeDriverVersion().equals("")) { + // System.setProperty("wdm.chromeDriverVersion", DriverManager.propertiesFileSettings.getChromeDriverVersion()); + // } + // downloadNewestOrGivenVersionOfWebDriver(ChromeDriver.class); + // OperationsOnFiles.moveWithPruneEmptydirectories(WebDriverManager.getInstance(ChromeDriver.class) + // .getBinaryPath(), browserPath); + // } + // driverDownloadedChrome = true; + // } + // + // System.setProperty("webdriver.chrome.driver", browserPath); + // + // // https://github.com/appium/appium/tree/master/sample-code/java/src + // + //// AndroidCreateSessionTest + // https://github.com/appium/appium/blob/master/sample-code/java/src/AndroidCreateSessionTest.java + //// File classpathRoot = new File(System.getProperty("user.dir")); + //// File appDir = new File(classpathRoot, "../apps"); + //// File app = new File(appDir.getCanonicalPath(), "ApiDemos-debug.apk"); + //// DesiredCapabilities capabilities = new DesiredCapabilities(); + //// capabilities.setCapability("deviceName", "Android Emulator"); + //// capabilities.setCapability("app", app.getAbsolutePath()); + //// capabilities.setCapability("appPackage", "io.appium.android.apis"); + //// capabilities.setCapability("appActivity", ".ApiDemos"); + //// driver = new AndroidDriver(getServiceUrl(), capabilities); + // + //// AndroidCreateWebSessionTest + // https://github.com/appium/appium/blob/master/sample-code/java/src/AndroidCreateWebSessionTest.java + //// DesiredCapabilities capabilities = new DesiredCapabilities(); + //// capabilities.setCapability("deviceName", "Android Emulator"); + //// capabilities.setCapability("browserName", "Chrome"); + //// driver = new AndroidDriver(getServiceUrl(), capabilities); + // + // HashMap chromePrefs = new HashMap(); + // chromePrefs.put("download.default_directory", DOWNLOAD_DIR); + // chromePrefs.put("profile.content_settings.pattern_pairs.*.multiple-automatic-downloads", 1); + // ChromeOptions options = new ChromeOptions(); + // options.setExperimentalOption("prefs", chromePrefs); + // options.addArguments("--test-type"); + // + // // Set users browser options + // RuntimeParameters.DEVICE_OPTIONS.getValues() + // .forEach((key, value) -> { + // BFLogger.logInfo("Device option: " + key + " " + value); + // String item = (value.toString() + // .isEmpty()) ? key : key + "=" + value; + // options.addArguments(item); + // }); + // + // // DesiredCapabilities cap = DesiredCapabilities.chrome(); + // // cap.setCapability(ChromeOptions.CAPABILITY, options); + // + // //TODO Add capabilities added by user + // + //// AndroidCreateSessionTest + // https://github.com/appium/appium/blob/master/sample-code/java/src/AndroidCreateSessionTest.java + // File classpathRoot = new File(System.getProperty("user.dir")); + // File appDir = new File(classpathRoot, "../apps"); + // File app = null; + // try { + // app = new File(appDir.getCanonicalPath(), "ApiDemos-debug.apk"); + // } catch (IOException e) { + // e.printStackTrace(); + // } + // DesiredCapabilities capabilities = new DesiredCapabilities(); + // capabilities.setCapability("deviceName", "Android Emulator"); + // capabilities.setCapability("app", app.getAbsolutePath()); + // capabilities.setCapability("appPackage", "io.appium.android.apis"); + // capabilities.setCapability("appActivity", ".ApiDemos"); + // + // INewMobileDriver driver = new NewAndroidDriver(capabilities); + // return driver; + // } + // + // }, + // IOS { + // @Override + // public INewMobileDriver getDriver() { + // String browserPath = DriverManager.propertiesFileSettings.getSeleniumChrome(); + // boolean isDriverAutoUpdateActivated = DriverManager.propertiesFileSettings.getDriverAutoUpdateFlag(); + // synchronized (this) { + // if (isDriverAutoUpdateActivated && !driverDownloadedChrome) { + // if (!DriverManager.propertiesFileSettings.getChromeDriverVersion().equals("")) { + // System.setProperty("wdm.chromeDriverVersion", DriverManager.propertiesFileSettings.getChromeDriverVersion()); + // } + // downloadNewestOrGivenVersionOfWebDriver(ChromeDriver.class); + // OperationsOnFiles.moveWithPruneEmptydirectories(WebDriverManager.getInstance(ChromeDriver.class) + // .getBinaryPath(), browserPath); + // } + // driverDownloadedChrome = true; + // } + // + // System.setProperty("webdriver.chrome.driver", browserPath); + // + // // https://github.com/appium/appium/tree/master/sample-code/java/src + // + // // IOSCreateSessionTest + // https://github.com/appium/appium/blob/master/sample-code/java/src/IOSCreateSessionTest.java + // // File classpathRoot = new File(System.getProperty("user.dir")); + // // File appDir = new File(classpathRoot, "../apps"); + // // File app = new File(appDir.getCanonicalPath(), "TestApp.app.zip"); + // // String deviceName = System.getenv("IOS_DEVICE_NAME"); + // // String platformVersion = System.getenv("IOS_PLATFORM_VERSION"); + // // DesiredCapabilities capabilities = new DesiredCapabilities(); + // // capabilities.setCapability("deviceName", deviceName == null ? "iPhone 6s" : deviceName); + // // capabilities.setCapability("platformVersion", platformVersion == null ? "11.1" : platformVersion); + // // capabilities.setCapability("app", app.getAbsolutePath()); + // // capabilities.setCapability("automationName", "XCUITest"); + // // driver = new IOSDriver(getServiceUrl(), capabilities); + // + // // IOSCreateWebSessionTest + // https://github.com/appium/appium/blob/master/sample-code/java/src/IOSCreateWebSessionTest.java + // // String deviceName = System.getenv("IOS_DEVICE_NAME"); + // // String platformVersion = System.getenv("IOS_PLATFORM_VERSION"); + // // DesiredCapabilities capabilities = new DesiredCapabilities(); + // // capabilities.setCapability("deviceName", deviceName == null ? "iPhone 6s" : deviceName); + // // capabilities.setCapability("platformVersion", platformVersion == null ? "11.1" : platformVersion); + // // capabilities.setCapability("browserName", "Safari"); + // // capabilities.setCapability("automationName", "XCUITest"); + // // driver = new IOSDriver(getServiceUrl(), capabilities); + // + // HashMap chromePrefs = new HashMap(); + // chromePrefs.put("download.default_directory", DOWNLOAD_DIR); + // chromePrefs.put("profile.content_settings.pattern_pairs.*.multiple-automatic-downloads", 1); + // ChromeOptions options = new ChromeOptions(); + // options.setExperimentalOption("prefs", chromePrefs); + // options.addArguments("--test-type"); + // + // // Set users browser options + // RuntimeParameters.BROWSER_OPTIONS.getValues() + // .forEach((key, value) -> { + // BFLogger.logInfo("Browser option: " + key + " " + value); + // String item = (value.toString() + // .isEmpty()) ? key : key + "=" + value; + // options.addArguments(item); + // }); + // + // // DesiredCapabilities cap = DesiredCapabilities.chrome(); + // // cap.setCapability(ChromeOptions.CAPABILITY, options); + // + // INewMobileDriver driver = new NewChromeDriver(options); + // return driver; + // } + // + // }, + // WINDOWS { + // @Override + // public INewMobileDriver getDriver() { + // String browserPath = DriverManager.propertiesFileSettings.getSeleniumChrome(); + // boolean isDriverAutoUpdateActivated = DriverManager.propertiesFileSettings.getDriverAutoUpdateFlag(); + // synchronized (this) { + // if (isDriverAutoUpdateActivated && !driverDownloadedChrome) { + // if (!DriverManager.propertiesFileSettings.getChromeDriverVersion().equals("")) { + // System.setProperty("wdm.chromeDriverVersion", DriverManager.propertiesFileSettings.getChromeDriverVersion()); + // } + // downloadNewestOrGivenVersionOfWebDriver(ChromeDriver.class); + // OperationsOnFiles.moveWithPruneEmptydirectories(WebDriverManager.getInstance(ChromeDriver.class) + // .getBinaryPath(), browserPath); + // } + // driverDownloadedChrome = true; + // } + // + // System.setProperty("webdriver.chrome.driver", browserPath); + // + // // https://github.com/appium/appium/blob/master/sample-code/java/src/WindowsDesktopAppTest.java + // + // // WindowsDesktopAppTest + // // DesiredCapabilities caps = new DesiredCapabilities(); + // // caps.setCapability("platformVersion", "10"); + // // caps.setCapability("platformName", "Windows"); + // // caps.setCapability("deviceName", "WindowsPC"); + // // caps.setCapability("app", "Microsoft.WindowsCalculator_8wekyb3d8bbwe!App"); + // // caps.setCapability("newCommandTimeout", 2000); + // // driver = new WindowsDriver<>(getServiceUrl(), caps); + // + // HashMap chromePrefs = new HashMap(); + // chromePrefs.put("download.default_directory", DOWNLOAD_DIR); + // chromePrefs.put("profile.content_settings.pattern_pairs.*.multiple-automatic-downloads", 1); + // ChromeOptions options = new ChromeOptions(); + // options.setExperimentalOption("prefs", chromePrefs); + // options.addArguments("--test-type"); + // + // // Set users browser options + // RuntimeParameters.BROWSER_OPTIONS.getValues() + // .forEach((key, value) -> { + // BFLogger.logInfo("Browser option: " + key + " " + value); + // String item = (value.toString() + // .isEmpty()) ? key : key + "=" + value; + // options.addArguments(item); + // }); + // + // // DesiredCapabilities cap = DesiredCapabilities.chrome(); + // // cap.setCapability(ChromeOptions.CAPABILITY, options); + // + // INewMobileDriver driver = new NewChromeDriver(options); + // return driver; + // } + // + // }, + // APPIUM_SERVER { + // @Override + // public INewMobileDriver getDriver() { + // + // final String APPIUM_SERVER_URL = RuntimeParameters.DEVICE_URL.getValue() + "/wd/hub"; + // BFLogger.logDebug("Connecting to the Appium Server: " + APPIUM_SERVER_URL); + // + // DesiredCapabilities capabilities = new DesiredCapabilities(); + // capabilities.setCapability(RuntimeParameters.AUTOMATION_NAME.getKey(), + // RuntimeParameters.AUTOMATION_NAME.getValue()); + // capabilities.setCapability(RuntimeParameters.PLATFORM_NAME.getKey(), + // RuntimeParameters.PLATFORM_NAME.getValue()); + // capabilities.setCapability(RuntimeParameters.PLATFORM_VERSION.getKey(), + // RuntimeParameters.PLATFORM_VERSION.getValue()); + // capabilities.setCapability(RuntimeParameters.DEVICE_NAME.getKey(), RuntimeParameters.DEVICE_NAME.getValue()); + // capabilities.setCapability(RuntimeParameters.APP.getKey(), RuntimeParameters.APP.getValue()); + // capabilities.setCapability(RuntimeParameters.BROWSER_NAME.getKey(), + // RuntimeParameters.BROWSER_NAME.getValue()); + // + // // Set users device options + // RuntimeParameters.DEVICE_OPTIONS.getValues() + // .forEach((key, value) -> { + // BFLogger.logInfo("Device option: " + key + " " + value); + // capabilities.setCapability(key, value); + // }); + // + // NewAppiumDriver newRemoteWebDriver = null; + // try { + // URL url = new URL(APPIUM_SERVER_URL); + // //url = new URL("http://target_ip:used_port/wd/hub"); + // //if it needs to use locally started server + // //then the target_ip is 127.0.0.1 or 0.0.0.0 + // //the default port is 4723 + // BFLogger.logDebug("Capabilities: " + capabilities.toJson()); + // newRemoteWebDriver = new NewAppiumDriver(url, capabilities); + // } catch (MalformedURLException e) { + // BFLogger.logError("Unable connect to Appium Server URL: " + APPIUM_SERVER_URL); + // } + // return newRemoteWebDriver; + // } + // }; + // + // + // + // public INewMobileDriver getDriver() { + // return null; + // } + } - - - private interface IDriverManager{ - + + private interface IDriverManager { + String getUrl(); + INewMobileDriver getDriver(); + DesiredCapabilities getCapabilities(); } - - private static class DriverManagerForAppium implements IDriverManager{ - - public String getUrl(){ + + private static class DriverManagerForAppium implements IDriverManager { + + public String getUrl() { return RuntimeParameters.DEVICE_URL.getValue() + "/wd/hub"; } - - - public DesiredCapabilities getCapabilities(){ + + public DesiredCapabilities getCapabilities() { DesiredCapabilities capabilities = new DesiredCapabilities(); - capabilities.setCapability(RuntimeParameters.AUTOMATION_NAME.getKey(), RuntimeParameters.AUTOMATION_NAME.getValue()); - capabilities.setCapability(RuntimeParameters.PLATFORM_NAME.getKey(), RuntimeParameters.PLATFORM_NAME.getValue()); - capabilities.setCapability(RuntimeParameters.PLATFORM_VERSION.getKey(), RuntimeParameters.PLATFORM_VERSION.getValue()); - capabilities.setCapability(RuntimeParameters.DEVICE_NAME.getKey(), RuntimeParameters.DEVICE_NAME.getValue()); - capabilities.setCapability(RuntimeParameters.APP.getKey(), RuntimeParameters.APP.getValue()); - capabilities.setCapability(RuntimeParameters.BROWSER_NAME.getKey(), RuntimeParameters.BROWSER_NAME.getValue()); - + RuntimeParameters[] capsToSet = { RuntimeParameters.AUTOMATION_NAME, RuntimeParameters.PLATFORM_NAME, RuntimeParameters.PLATFORM_VERSION, + RuntimeParameters.DEVICE_NAME, RuntimeParameters.APP, RuntimeParameters.BROWSER_NAME }; + Arrays.stream(capsToSet) + .forEach(e -> capabilities.setCapability(e.getKey(), e.getValue())); + // Set users device options RuntimeParameters.DEVICE_OPTIONS.getValues() .forEach((key, value) -> { BFLogger.logInfo("Device option: " + key + " " + value); capabilities.setCapability(key, value); }); - - + BFLogger.logDebug("Capabilities: " + capabilities.toJson()); return capabilities; } - - - - public INewMobileDriver getDriver(){ - + + public INewMobileDriver getDriver() { + BFLogger.logDebug("Connecting to the Appium Server: " + getUrl()); - + INewMobileDriver newRemoteWebDriver = null; try { URL url = new URL(getUrl()); - //url = new URL("http://target_ip:used_port/wd/hub"); - //if it needs to use locally started server - //then the target_ip is 127.0.0.1 or 0.0.0.0 - //the default port is 4723 - + // url = new URL("http://target_ip:used_port/wd/hub"); + // if it needs to use locally started server + // then the target_ip is 127.0.0.1 or 0.0.0.0 + // the default port is 4723 + newRemoteWebDriver = new NewAppiumDriver(url, getCapabilities()); } catch (MalformedURLException e) { BFLogger.logError("Unable connect to Appium Server URL: " + getUrl()); } return newRemoteWebDriver; }; - - + } - - private static class DriverManagerForAndroid extends DriverManagerForAppium implements IDriverManager{ - - //TODO: Is it possible to connect to Android without Appium Server /wd/hub sub-url ? - public String getUrl(){ + + private static class DriverManagerForAndroid extends DriverManagerForAppium implements IDriverManager { + + // TODO: Is it possible to connect to Android without Appium Server /wd/hub sub-url ? + // currently not used + public String getUrl() { return RuntimeParameters.DEVICE_URL.getValue() + "/wd/hub"; } - - + @Override - public DesiredCapabilities getCapabilities(){ + public DesiredCapabilities getCapabilities() { DesiredCapabilities capabilities = super.getCapabilities(); - String key = ""; - String value = ""; - capabilities.setCapability(key, value); + capabilities.setCapability("", ""); + return capabilities; }; - - - @Override public NewAndroidDriver getDriver(){return null;}; - + + @Override + public NewAndroidDriver getDriver() { + return null; + }; } - -} +} \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-mobile-module/src/main/java/com/capgemini/mrchecker/mobile/core/base/driver/INewMobileDriver.java b/mrchecker-framework-modules/mrchecker-mobile-module/src/main/java/com/capgemini/mrchecker/mobile/core/base/driver/INewMobileDriver.java index a882238a..9749fcce 100644 --- a/mrchecker-framework-modules/mrchecker-mobile-module/src/main/java/com/capgemini/mrchecker/mobile/core/base/driver/INewMobileDriver.java +++ b/mrchecker-framework-modules/mrchecker-mobile-module/src/main/java/com/capgemini/mrchecker/mobile/core/base/driver/INewMobileDriver.java @@ -2,8 +2,6 @@ import io.appium.java_client.MobileDriver; - public interface INewMobileDriver extends MobileDriver { - } diff --git a/mrchecker-framework-modules/mrchecker-mobile-module/src/main/java/com/capgemini/mrchecker/mobile/core/base/driver/NewAndroidDriver.java b/mrchecker-framework-modules/mrchecker-mobile-module/src/main/java/com/capgemini/mrchecker/mobile/core/base/driver/NewAndroidDriver.java index 2d5c06c6..f3477b5d 100644 --- a/mrchecker-framework-modules/mrchecker-mobile-module/src/main/java/com/capgemini/mrchecker/mobile/core/base/driver/NewAndroidDriver.java +++ b/mrchecker-framework-modules/mrchecker-mobile-module/src/main/java/com/capgemini/mrchecker/mobile/core/base/driver/NewAndroidDriver.java @@ -1,24 +1,19 @@ package com.capgemini.mrchecker.mobile.core.base.driver; -import com.capgemini.mrchecker.mobile.core.BasePage; -//import com.capgemini.mrchecker.selenium.core.BasePage; -//import com.capgemini.mrchecker.selenium.core.exceptions.BFElementNotFoundException; -//import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.*; -import com.capgemini.mrchecker.test.core.BaseTest; -import io.appium.java_client.AppiumDriver; -import io.appium.java_client.android.AndroidDriver; -import org.openqa.selenium.remote.DesiredCapabilities; - import java.net.MalformedURLException; import java.net.URL; -public final class NewAndroidDriver extends AndroidDriver implements INewMobileDriver { +import org.openqa.selenium.remote.DesiredCapabilities; + +import io.appium.java_client.android.AndroidDriver; +public final class NewAndroidDriver extends AndroidDriver implements INewMobileDriver { + public NewAndroidDriver(DesiredCapabilities capabilities) { super(getServiceUrl(), capabilities); - + } - + private static URL getServiceUrl() { URL url = null; try { @@ -26,16 +21,10 @@ private static URL getServiceUrl() { } catch (MalformedURLException e) { e.printStackTrace(); } - //if it needs to use locally started server - //then the target_ip is 127.0.0.1 or 0.0.0.0 - //the default port is 4723 - + // if it needs to use locally started server + // then the target_ip is 127.0.0.1 or 0.0.0.0 + // the default port is 4723 + return url; } - - public static void main(String[] args) { - BaseTest.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); - } - } \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-mobile-module/src/main/java/com/capgemini/mrchecker/mobile/core/base/driver/NewAppiumDriver.java b/mrchecker-framework-modules/mrchecker-mobile-module/src/main/java/com/capgemini/mrchecker/mobile/core/base/driver/NewAppiumDriver.java index 10fa543f..61adcfa8 100644 --- a/mrchecker-framework-modules/mrchecker-mobile-module/src/main/java/com/capgemini/mrchecker/mobile/core/base/driver/NewAppiumDriver.java +++ b/mrchecker-framework-modules/mrchecker-mobile-module/src/main/java/com/capgemini/mrchecker/mobile/core/base/driver/NewAppiumDriver.java @@ -1,23 +1,15 @@ package com.capgemini.mrchecker.mobile.core.base.driver; -import com.capgemini.mrchecker.mobile.core.BasePage; -import com.capgemini.mrchecker.test.core.BaseTest; -import io.appium.java_client.AppiumDriver; -import org.openqa.selenium.remote.DesiredCapabilities; - import java.net.URL; +import org.openqa.selenium.remote.DesiredCapabilities; -public final class NewAppiumDriver extends AppiumDriver implements INewMobileDriver { +import io.appium.java_client.AppiumDriver; +public final class NewAppiumDriver extends AppiumDriver implements INewMobileDriver { + public NewAppiumDriver(URL url, DesiredCapabilities capabilities) { - super(url , capabilities); - + super(url, capabilities); } - - public static void main(String[] args) { - BaseTest.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); - } - + } \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-mobile-module/src/main/java/com/capgemini/mrchecker/mobile/core/base/exceptions/BFAppiumServerNotConnectedException.java b/mrchecker-framework-modules/mrchecker-mobile-module/src/main/java/com/capgemini/mrchecker/mobile/core/base/exceptions/BFAppiumServerNotConnectedException.java index a10844da..1484112f 100644 --- a/mrchecker-framework-modules/mrchecker-mobile-module/src/main/java/com/capgemini/mrchecker/mobile/core/base/exceptions/BFAppiumServerNotConnectedException.java +++ b/mrchecker-framework-modules/mrchecker-mobile-module/src/main/java/com/capgemini/mrchecker/mobile/core/base/exceptions/BFAppiumServerNotConnectedException.java @@ -1,25 +1,21 @@ package com.capgemini.mrchecker.mobile.core.base.exceptions; -import com.capgemini.mrchecker.test.core.logger.BFLogger; import org.openqa.selenium.WebDriverException; -public class BFAppiumServerNotConnectedException extends AssertionError { - - private static final long serialVersionUID = -1217616251968376336L; - private static String exceptionMessage; +import com.capgemini.mrchecker.test.core.logger.BFLogger; +public class BFAppiumServerNotConnectedException extends AssertionError { + + private static final long serialVersionUID = -1217616251968376336L; + private static final String EXCEPTION_MESSAGE = "Unable to create connections to Appium Server\n"; + /** * This exception should be thrown when connection to Appium Server is not possible * * @param e */ public BFAppiumServerNotConnectedException(WebDriverException e) { - super(generateExceptionMessage()); - BFLogger.logError(exceptionMessage + e.toString()); - } - - private static String generateExceptionMessage() { - exceptionMessage = "Unable to create connections to Appium Server\n"; - return exceptionMessage; + super(EXCEPTION_MESSAGE); + BFLogger.logError(EXCEPTION_MESSAGE + e.toString()); } } diff --git a/mrchecker-framework-modules/mrchecker-mobile-module/src/main/java/com/capgemini/mrchecker/mobile/core/base/properties/PropertiesFileSettings.java b/mrchecker-framework-modules/mrchecker-mobile-module/src/main/java/com/capgemini/mrchecker/mobile/core/base/properties/PropertiesFileSettings.java index 7ee99479..8264b4df 100644 --- a/mrchecker-framework-modules/mrchecker-mobile-module/src/main/java/com/capgemini/mrchecker/mobile/core/base/properties/PropertiesFileSettings.java +++ b/mrchecker-framework-modules/mrchecker-mobile-module/src/main/java/com/capgemini/mrchecker/mobile/core/base/properties/PropertiesFileSettings.java @@ -5,13 +5,12 @@ public class PropertiesFileSettings { - private String property_1 = "How are you"; // default value - private String property_2 = "What is your today success"; // default value + private String property_1 = "How are you"; // default value + private String property_2 = "What is your today success"; // default value @Inject(optional = true) private void setProperty_1(@Named("name.property_1") String path) { - this.property_1 = path; - + property_1 = path; } public String getProperty_1() { @@ -20,12 +19,10 @@ public String getProperty_1() { @Inject(optional = true) private void setProperty_2(@Named("name.property_2") String path) { - this.property_2 = path; - + property_2 = path; } public String getProperty_2() { - return this.property_2; + return property_2; } - } diff --git a/mrchecker-framework-modules/mrchecker-mobile-module/src/main/java/com/capgemini/mrchecker/mobile/core/base/runtime/RuntimeParameters.java b/mrchecker-framework-modules/mrchecker-mobile-module/src/main/java/com/capgemini/mrchecker/mobile/core/base/runtime/RuntimeParameters.java index 86261ec2..8c64d16d 100644 --- a/mrchecker-framework-modules/mrchecker-mobile-module/src/main/java/com/capgemini/mrchecker/mobile/core/base/runtime/RuntimeParameters.java +++ b/mrchecker-framework-modules/mrchecker-mobile-module/src/main/java/com/capgemini/mrchecker/mobile/core/base/runtime/RuntimeParameters.java @@ -1,32 +1,35 @@ package com.capgemini.mrchecker.mobile.core.base.runtime; -import com.capgemini.mrchecker.test.core.base.runtime.RuntimeParametersI; -import com.capgemini.mrchecker.test.core.logger.BFLogger; -import io.appium.java_client.remote.MobileCapabilityType; -import org.apache.commons.lang.BooleanUtils; -import org.apache.commons.lang.math.NumberUtils; - import java.util.Arrays; import java.util.Map; import java.util.stream.Collectors; +import org.apache.commons.lang.BooleanUtils; +import org.apache.commons.lang.math.NumberUtils; +import org.apache.commons.lang3.StringUtils; + +import com.capgemini.mrchecker.test.core.base.runtime.IRuntimeParameters; +import com.capgemini.mrchecker.test.core.logger.BFLogger; + +import io.appium.java_client.remote.MobileCapabilityType; + /** * This class stores various system properties * * @author LUSTEFAN */ -public enum RuntimeParameters implements RuntimeParametersI { - - //http://appium.io/docs/en/writing-running-appium/caps/#appium-desired-capabilities - // platformName": "iOS", - // "platformVersion": "11.0", - // "deviceName": "iPhone 7", - // "automationName": "XCUITest", - // "app": "/path/to/my.app" - +public enum RuntimeParameters implements IRuntimeParameters { + + // http://appium.io/docs/en/writing-running-appium/caps/#appium-desired-capabilities + // platformName": "iOS", + // "platformVersion": "11.0", + // "deviceName": "iPhone 7", + // "automationName": "XCUITest", + // "app": "/path/to/my.app" + // GENERIC Capabilities // http://appium.io/docs/en/writing-running-appium/caps/#general-capabilities - DEVICE_URL("deviceUrl", "http://127.0.0.1:4723"), + DEVICE_URL("deviceUrl", "http://0.0.0.0:4723"), AUTOMATION_NAME(MobileCapabilityType.AUTOMATION_NAME, "Appium"), PLATFORM_NAME(MobileCapabilityType.PLATFORM_NAME, "Android"), PLATFORM_VERSION(MobileCapabilityType.PLATFORM_VERSION, ""), @@ -36,35 +39,34 @@ public enum RuntimeParameters implements RuntimeParametersI { NEW_COMMAND_TIMEOUT(MobileCapabilityType.NEW_COMMAND_TIMEOUT, "4000"), DEVICE_OPTIONS("deviceOptions", "") { public Map getValues() { - return Arrays.asList(this.paramValue.split(";")) - .stream() + return Arrays.stream(this.paramValue.split(";")) .filter(i -> i != "") // remove empty inputs .map(i -> i.split("=", 2)) // split to key, value. Not more than one time .map(i -> new String[] { i[0], (i.length == 1) ? "" : i[1] }) // if value is empty, set empty text .collect(Collectors.toMap(i -> i[0], i -> (Object) convertToCorrectType(i[1].trim()))); // create } - + }; - - private String paramName; - protected String paramValue; - private String defaultValue; - - private RuntimeParameters(String paramName, String defaultValue) { + + private final String paramName; + protected String paramValue; + private final String defaultValue; + + RuntimeParameters(String paramName, String defaultValue) { this.paramName = paramName; this.defaultValue = defaultValue; setValue(); - + } - + protected static Object convertToCorrectType(String value) { Object convertedValue = value; - + if (null != BooleanUtils.toBooleanObject(value)) { convertedValue = Boolean.valueOf(value); return convertedValue; } - + if (NumberUtils.isNumber(value)) { if (NumberUtils.isDigits(value)) { // so it is integer value @@ -76,90 +78,90 @@ protected static Object convertToCorrectType(String value) { return convertedValue; } } - + return convertedValue; } - + @Override public String getValue() { - return this.paramValue; + return paramValue; } - + @Override public String getKey() { - return this.paramName; + return paramName; } - + public Map getValues() { return null; } - + @Override public String toString() { - return paramName + "=" + this.getValue(); + return getKey() + "=" + getValue(); } - + @Override public void refreshParameterValue() { setValue(); } - + private void setValue() { - + String paramValue = System.getProperty(this.paramName); paramValue = isSystemParameterEmpty(paramValue) ? this.defaultValue : paramValue; - ; - + switch (this.name()) { - //TODO: Set validation for each Runtime Param based on http://appium.io/docs/en/writing-running-appium/caps/#general-capabilities - // MobileCapabilityType.PLATFORM_VERSION, "4.4"); - // MobileCapabilityType.PLATFORM_NAME,"Android"); - // MobileCapabilityType.AUTOMATION_NAME,"UiAutomator2"); - // MobileCapabilityType.DEVICE_NAME, "Samsung Galaxy S4 Emulator"); - // MobileCapabilityType.BROWSER_NAME, "Browser"); - - case "AUTOMATION_NAME": - break; - - case "PLATFORM_VERSION": - break; - case "DEVICE_URL": - break; - case "DEVICE_OPTIONS": - break; - case "PLATFORM_NAME": - if (paramValue.equals("android")) { - paramValue = "Android"; - } else if (paramValue.equals("ios")) { - paramValue = "iOS"; - } - break; - case "DEVICE_NAME": - if (paramValue.equals("android")) { - paramValue = "Android Emulator"; - } - break; - case "BROWSER_NAME": - break; - case "NEW_COMMAND_TIMEOUT": - break; - case "APP": - break; - case "APPLICATION_PACKAGE": - break; - case "APPLICATION_ACTIVITY": - break; - default: - BFLogger.logError("Unknown RuntimeParameter = " + this.name()); - break; + // TODO: Set validation for each Runtime Param based on + // http://appium.io/docs/en/writing-running-appium/caps/#general-capabilities + // MobileCapabilityType.PLATFORM_VERSION, "4.4"); + // MobileCapabilityType.PLATFORM_NAME,"Android"); + // MobileCapabilityType.AUTOMATION_NAME,"UiAutomator2"); + // MobileCapabilityType.DEVICE_NAME, "Samsung Galaxy S4 Emulator"); + // MobileCapabilityType.BROWSER_NAME, "Browser"); + + case "AUTOMATION_NAME": + break; + + case "PLATFORM_VERSION": + break; + case "DEVICE_URL": + break; + case "DEVICE_OPTIONS": + break; + case "PLATFORM_NAME": + if (paramValue.equals("android")) { + paramValue = "Android"; + } else if (paramValue.equals("ios")) { + paramValue = "iOS"; + } + break; + case "DEVICE_NAME": + if (paramValue.equals("android")) { + paramValue = "Android Emulator"; + } + break; + case "BROWSER_NAME": + break; + case "NEW_COMMAND_TIMEOUT": + break; + case "APP": + break; + case "APPLICATION_PACKAGE": + break; + case "APPLICATION_ACTIVITY": + break; + default: + BFLogger.logError("Unknown RuntimeParameter = " + this.name()); + break; } - + this.paramValue = paramValue; - + } - + private boolean isSystemParameterEmpty(String systemParameterValue) { - return (null == systemParameterValue || "".equals(systemParameterValue) || "null".equals(systemParameterValue)); + return (StringUtils.isEmpty(systemParameterValue) || "null".equals(systemParameterValue)); } - + } diff --git a/mrchecker-framework-modules/mrchecker-mobile-module/src/resources/allure.properties b/mrchecker-framework-modules/mrchecker-mobile-module/src/resources/allure.properties new file mode 100644 index 00000000..6c1e0bb1 --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-mobile-module/src/resources/allure.properties @@ -0,0 +1 @@ +allure.results.directory=target/allure-results \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-mobile-module/src/resources/junit-platform.properties b/mrchecker-framework-modules/mrchecker-mobile-module/src/resources/junit-platform.properties new file mode 100644 index 00000000..0a5f88f7 --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-mobile-module/src/resources/junit-platform.properties @@ -0,0 +1,8 @@ +junit.jupiter.extensions.autodetection.enabled=true +junit.jupiter.execution.parallel.enabled=true +#junit.jupiter.execution.parallel.mode.default=concurrent +junit.jupiter.execution.parallel.mode.default=same_thread +junit.jupiter.execution.parallel.mode.classes.default=concurrent +#junit.jupiter.execution.parallel.mode.classes.default=same_thread +junit.jupiter.execution.parallel.config.strategy=dynamic +junit.jupiter.execution.parallel.config.dynamic.factor=1 diff --git a/mrchecker-framework-modules/mrchecker-mobile-module/src/test/java/com/capgemini/mrchecker/mobile/BasePageTest.java b/mrchecker-framework-modules/mrchecker-mobile-module/src/test/java/com/capgemini/mrchecker/mobile/BasePageTest.java deleted file mode 100644 index f1fe5897..00000000 --- a/mrchecker-framework-modules/mrchecker-mobile-module/src/test/java/com/capgemini/mrchecker/mobile/BasePageTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.capgemini.mrchecker.mobile; - -import com.capgemini.mrchecker.mobile.core.BasePage; -import com.capgemini.mrchecker.test.core.logger.BFLogger; -import org.apache.commons.io.FileUtils; -import org.junit.Test; - - -public class BasePageTest { - - @Test - public void test() { - MyPage myPage = new MyPage(); - myPage.myMethod(); - } - - public class MyPage extends BasePage { - - public String myMethod() { - BFLogger.logDebug("TITLE: " + getDriver().getPageSource()); - -// File file = ((TakesScreenshot)getDriver()).getScreenshotAs(OutputType.FILE); -// try { -// FileUtils.copyFile(file, new File("Screenshot.jpg")); -// } catch (IOException e) { -// e.printStackTrace(); -// } - - - return "Welcome"; - } - } - - - -} - - diff --git a/mrchecker-framework-modules/mrchecker-mobile-module/src/test/java/com/capgemini/mrchecker/mobile/tags/IntegrationTest.java b/mrchecker-framework-modules/mrchecker-mobile-module/src/test/java/com/capgemini/mrchecker/mobile/tags/IntegrationTest.java new file mode 100644 index 00000000..566cf959 --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-mobile-module/src/test/java/com/capgemini/mrchecker/mobile/tags/IntegrationTest.java @@ -0,0 +1,14 @@ +package com.capgemini.mrchecker.mobile.tags; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import org.junit.jupiter.api.Tag; + +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +@Tag("IntegrationTest") +public @interface IntegrationTest { +} \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-mobile-module/src/test/java/com/capgemini/mrchecker/mobile/tags/UnitTest.java b/mrchecker-framework-modules/mrchecker-mobile-module/src/test/java/com/capgemini/mrchecker/mobile/tags/UnitTest.java new file mode 100644 index 00000000..cd9b64ac --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-mobile-module/src/test/java/com/capgemini/mrchecker/mobile/tags/UnitTest.java @@ -0,0 +1,14 @@ +package com.capgemini.mrchecker.mobile.tags; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import org.junit.jupiter.api.Tag; + +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +@Tag("UnitTest") +public @interface UnitTest { +} \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-mobile-module/src/test/java/com/capgemini/mrchecker/mobile/testsuites/UnitTestsSuite.java b/mrchecker-framework-modules/mrchecker-mobile-module/src/test/java/com/capgemini/mrchecker/mobile/testsuites/UnitTestsSuite.java new file mode 100644 index 00000000..35ea3492 --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-mobile-module/src/test/java/com/capgemini/mrchecker/mobile/testsuites/UnitTestsSuite.java @@ -0,0 +1,12 @@ +package com.capgemini.mrchecker.mobile.testsuites; + +import org.junit.platform.runner.JUnitPlatform; +import org.junit.platform.suite.api.IncludeTags; +import org.junit.platform.suite.api.SelectPackages; +import org.junit.runner.RunWith; + +@RunWith(JUnitPlatform.class) +@IncludeTags({ "UnitTest" }) +@SelectPackages("com.capgemini.mrchecker.mobile") +public class UnitTestsSuite { +} diff --git a/mrchecker-framework-modules/mrchecker-mobile-module/src/test/java/com/capgemini/mrchecker/mobile/unit/BasePageTest.java b/mrchecker-framework-modules/mrchecker-mobile-module/src/test/java/com/capgemini/mrchecker/mobile/unit/BasePageTest.java new file mode 100644 index 00000000..64c634b2 --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-mobile-module/src/test/java/com/capgemini/mrchecker/mobile/unit/BasePageTest.java @@ -0,0 +1,40 @@ +package com.capgemini.mrchecker.mobile.unit; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.ResourceLock; + +import com.capgemini.mrchecker.mobile.core.BasePage; +import com.capgemini.mrchecker.mobile.tags.UnitTest; +import com.capgemini.mrchecker.test.core.logger.BFLogger; +import com.capgemini.mrchecker.test.core.utils.PageFactory; + +@UnitTest +@ResourceLock("PropertiesFileSettings.class") +@Disabled("Due to no appium running automatically") +public class BasePageTest { + + @Test + public void test() { + MyPage myPage = PageFactory.getPageInstance(MyPage.class); + myPage.myMethod(); + } + + public class MyPage extends BasePage { + + public String myMethod() { + BFLogger.logDebug("TITLE: " + BasePage.getDriver() + .getPageSource()); + + // File file = ((TakesScreenshot)getDriver()).getScreenshotAs(OutputType.FILE); + // try { + // FileUtils.copyFile(file, new File("Screenshot.jpg")); + // } catch (IOException e) { + // e.printStackTrace(); + // } + + return "Welcome"; + } + } + +} diff --git a/mrchecker-framework-modules/mrchecker-mobile-module/src/test/java/com/capgemini/mrchecker/mobile/core/newDrivers/DriverManagerTest.java b/mrchecker-framework-modules/mrchecker-mobile-module/src/test/java/com/capgemini/mrchecker/mobile/unit/core/newDrivers/DriverManagerTest.java similarity index 75% rename from mrchecker-framework-modules/mrchecker-mobile-module/src/test/java/com/capgemini/mrchecker/mobile/core/newDrivers/DriverManagerTest.java rename to mrchecker-framework-modules/mrchecker-mobile-module/src/test/java/com/capgemini/mrchecker/mobile/unit/core/newDrivers/DriverManagerTest.java index b5cb5894..7fc45ab7 100644 --- a/mrchecker-framework-modules/mrchecker-mobile-module/src/test/java/com/capgemini/mrchecker/mobile/core/newDrivers/DriverManagerTest.java +++ b/mrchecker-framework-modules/mrchecker-mobile-module/src/test/java/com/capgemini/mrchecker/mobile/unit/core/newDrivers/DriverManagerTest.java @@ -1,56 +1,55 @@ -package com.capgemini.mrchecker.mobile.core.newDrivers; +package com.capgemini.mrchecker.mobile.unit.core.newDrivers; + +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.nio.file.Paths; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.ResourceLock; import com.capgemini.mrchecker.mobile.core.base.driver.DriverManager; import com.capgemini.mrchecker.mobile.core.base.properties.PropertiesFileSettings; import com.capgemini.mrchecker.mobile.core.base.runtime.RuntimeParameters; +import com.capgemini.mrchecker.mobile.tags.UnitTest; import com.capgemini.mrchecker.test.core.base.properties.PropertiesSettingsModule; import com.google.inject.Guice; -import io.appium.java_client.remote.MobileCapabilityType; -import org.junit.*; -import java.io.File; -import java.nio.file.Paths; - -import static org.junit.Assert.assertTrue; +import io.appium.java_client.remote.MobileCapabilityType; +@UnitTest +@ResourceLock("PropertiesFileSettings.class") +@Disabled("Due to no appium running automatically") public class DriverManagerTest { private DriverManager driverManager; - @BeforeClass - public static void setUpBeforeClass() throws Exception { - } - - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - + @BeforeEach + public void setUp() { + String path = System.getProperty("user.dir") + Paths.get("/src/test/resources/Simple_App_v2.0.1_apkpure.com.apk"); - File app = new File(path); + File app = new File(path); System.setProperty(MobileCapabilityType.APP, app.getAbsolutePath()); System.setProperty(MobileCapabilityType.PLATFORM_NAME, "Android"); System.setProperty(MobileCapabilityType.DEVICE_NAME, "Android Emulator"); System.setProperty(MobileCapabilityType.AUTOMATION_NAME, "UiAutomator1"); - + RuntimeParameters.APP.refreshParameterValue(); RuntimeParameters.PLATFORM_NAME.refreshParameterValue(); RuntimeParameters.DEVICE_NAME.refreshParameterValue(); RuntimeParameters.AUTOMATION_NAME.refreshParameterValue(); - - - + PropertiesFileSettings propertiesFileSettings = Guice.createInjector(PropertiesSettingsModule.init()) .getInstance(PropertiesFileSettings.class); - - + driverManager = new DriverManager(propertiesFileSettings); } - @After + @AfterEach public void tearDown() throws Exception { driverManager.stop(); } diff --git a/mrchecker-framework-modules/mrchecker-mobile-module/src/test/java/com/capgemini/mrchecker/mobile/core/base/properties/PropertiesManagerTest.java b/mrchecker-framework-modules/mrchecker-mobile-module/src/test/java/com/capgemini/mrchecker/mobile/unit/core/properties/PropertiesManagerTest.java similarity index 66% rename from mrchecker-framework-modules/mrchecker-mobile-module/src/test/java/com/capgemini/mrchecker/mobile/core/base/properties/PropertiesManagerTest.java rename to mrchecker-framework-modules/mrchecker-mobile-module/src/test/java/com/capgemini/mrchecker/mobile/unit/core/properties/PropertiesManagerTest.java index fd9f1054..fcb151e0 100644 --- a/mrchecker-framework-modules/mrchecker-mobile-module/src/test/java/com/capgemini/mrchecker/mobile/core/base/properties/PropertiesManagerTest.java +++ b/mrchecker-framework-modules/mrchecker-mobile-module/src/test/java/com/capgemini/mrchecker/mobile/unit/core/properties/PropertiesManagerTest.java @@ -1,57 +1,57 @@ -package com.capgemini.mrchecker.mobile.core.base.properties; - -import com.capgemini.mrchecker.test.core.base.properties.PropertiesSettingsModule; -import com.google.inject.Guice; -import com.google.inject.Injector; -import org.junit.*; - -import java.nio.file.Paths; +package com.capgemini.mrchecker.mobile.unit.core.properties; import static org.junit.Assert.assertEquals; -public class PropertiesManagerTest { +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.nio.file.Paths; - @BeforeClass - public static void setUpBeforeClass() { - } +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.ResourceLock; - @AfterClass - public static void tearDownAfterClass() { - } +import com.capgemini.mrchecker.mobile.core.base.properties.PropertiesFileSettings; +import com.capgemini.mrchecker.mobile.tags.UnitTest; +import com.capgemini.mrchecker.test.core.base.properties.PropertiesSettingsModule; +import com.google.inject.Guice; +import com.google.inject.Injector; +@UnitTest +@ResourceLock("PropertiesFileSettings.class") +public class PropertiesManagerTest { + private PropertiesFileSettings propertiesFileSettings; - - @Before - public void setUp() { + + @BeforeEach + public void setUp() throws FileNotFoundException { String path = System.getProperty("user.dir") + Paths.get("/src/test/resources/settings.properties"); - Injector i = Guice.createInjector(PropertiesSettingsModule.init(path)); + Injector i = Guice.createInjector(PropertiesSettingsModule.init(new FileInputStream(path))); this.propertiesFileSettings = i.getInstance(PropertiesFileSettings.class); } - - @After + + @AfterEach public void tearDown() { PropertiesSettingsModule.delInstance(); } - + @Test public void testParamter_1() { assertEquals("", "This is value for prop 1", propertiesFileSettings.getProperty_1()); } - + @Test public void testParamter_2() { assertEquals("", "This is value for prop 2", propertiesFileSettings.getProperty_2()); } - - // @Ignore + @Test public void testDefaultParamters() { PropertiesSettingsModule.delInstance(); - + Injector i = Guice.createInjector(PropertiesSettingsModule.init()); PropertiesFileSettings propertiesFileSettings = i.getInstance(PropertiesFileSettings.class); - + assertEquals("", "Hello One", propertiesFileSettings.getProperty_1()); } - } diff --git a/mrchecker-framework-modules/mrchecker-mobile-module/src/test/java/com/capgemini/mrchecker/mobile/core/base/runtime/RuntimeParametersTest.java b/mrchecker-framework-modules/mrchecker-mobile-module/src/test/java/com/capgemini/mrchecker/mobile/unit/core/runtime/RuntimeParametersTest.java similarity index 68% rename from mrchecker-framework-modules/mrchecker-mobile-module/src/test/java/com/capgemini/mrchecker/mobile/core/base/runtime/RuntimeParametersTest.java rename to mrchecker-framework-modules/mrchecker-mobile-module/src/test/java/com/capgemini/mrchecker/mobile/unit/core/runtime/RuntimeParametersTest.java index 9bb9d745..959036df 100644 --- a/mrchecker-framework-modules/mrchecker-mobile-module/src/test/java/com/capgemini/mrchecker/mobile/core/base/runtime/RuntimeParametersTest.java +++ b/mrchecker-framework-modules/mrchecker-mobile-module/src/test/java/com/capgemini/mrchecker/mobile/unit/core/runtime/RuntimeParametersTest.java @@ -1,32 +1,30 @@ -package com.capgemini.mrchecker.mobile.core.base.runtime; - -import io.appium.java_client.remote.MobileCapabilityType; -import org.apache.commons.lang.BooleanUtils; -import org.hamcrest.Matchers; -import org.hamcrest.core.IsInstanceOf; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - -import java.util.HashMap; -import java.util.Map; +package com.capgemini.mrchecker.mobile.unit.core.runtime; import static junit.framework.TestCase.assertEquals; import static org.junit.Assert.assertThat; -public class RuntimeParametersTest { - - private Map values = new HashMap(); +import java.util.HashMap; +import java.util.Map; - @Rule - public ExpectedException exceptionGrabber = ExpectedException.none(); +import org.hamcrest.Matchers; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.ResourceLock; - @Before - public void setUp() throws Exception { +import com.capgemini.mrchecker.mobile.core.base.runtime.RuntimeParameters; +import com.capgemini.mrchecker.mobile.tags.UnitTest; - values.put("deviceUrl", "http://192.168.0.1:1234"); +@UnitTest +@ResourceLock("PropertiesFileSettings.class") +public class RuntimeParametersTest { + + private final Map values = new HashMap(); + + @BeforeEach + public void setUp() { + + values.put("deviceUrl", "http://0.0.0.0:4723"); values.put("automationName", "magicAutomationName"); values.put("platformName", "magic_Android"); values.put("platformVersion", "11.0"); @@ -35,9 +33,9 @@ public void setUp() throws Exception { values.put("browserName", "magicChrome"); values.put("newCommandTimeout", "4"); values.put("deviceOptions", "headless;window-size=1200x600;testEquals=FirstEquals=SecondEquals;--testMe;acceptInsecureCerts=true;maxInstances=3"); - + values.forEach(System::setProperty); - + RuntimeParameters.DEVICE_URL.refreshParameterValue(); RuntimeParameters.AUTOMATION_NAME.refreshParameterValue(); RuntimeParameters.PLATFORM_NAME.refreshParameterValue(); @@ -45,18 +43,14 @@ public void setUp() throws Exception { RuntimeParameters.DEVICE_NAME.refreshParameterValue(); RuntimeParameters.APP.refreshParameterValue(); RuntimeParameters.BROWSER_NAME.refreshParameterValue(); - RuntimeParameters.NEW_COMMAND_TIMEOUT.refreshParameterValue();; + RuntimeParameters.NEW_COMMAND_TIMEOUT.refreshParameterValue(); RuntimeParameters.DEVICE_OPTIONS.refreshParameterValue(); } - - @After - public void tearDown() throws Exception { - } - + @Test public void testGetProperty() { - - values.put("deviceUrl", "http://192.168.0.1:1234"); + + values.put("deviceUrl", "http://0.0.0.0:4723"); values.put("automationName", "magicAutomationName"); values.put("platformName", "magic_Android"); values.put("platformVersion", "11.0"); @@ -64,8 +58,8 @@ public void testGetProperty() { values.put("app", "./magic/path"); values.put("browserName", "magicChrome"); values.put("newCommandTimeout", "8000"); - - assertThat("System parameters for empty property 'deviceUrl' should be 'http://192.168.0.1:1234'", RuntimeParameters.DEVICE_URL.getValue(), Matchers.equalTo("http://192.168.0.1:1234")); + + assertThat("System parameters for empty property 'deviceUrl' should be 'http://0.0.0.0:4723'", RuntimeParameters.DEVICE_URL.getValue(), Matchers.equalTo("http://0.0.0.0:4723")); assertThat("System parameters for empty property 'automationName' should be 'magicAutomationName'", RuntimeParameters.AUTOMATION_NAME.getValue(), Matchers.equalTo("magicAutomationName")); assertThat("System parameters for empty property 'platformName' should be 'magic_Android'", RuntimeParameters.PLATFORM_NAME.getValue(), Matchers.equalTo("magic_Android")); assertThat("System parameters for empty property 'platformVersion' should be '11.0'", RuntimeParameters.PLATFORM_VERSION.getValue(), Matchers.equalTo("11.0")); @@ -77,110 +71,111 @@ public void testGetProperty() { "System parameters for empty property 'browserOptions' should be 'headless;window-size=1200x600;testEquals=FirstEquals=SecondEquals;--testMe;acceptInsecureCerts=true;maxInstances=3'", RuntimeParameters.DEVICE_OPTIONS.getValue(), Matchers.equalTo("headless;window-size=1200x600;testEquals=FirstEquals=SecondEquals;--testMe;acceptInsecureCerts=true;maxInstances=3")); - + } - + @Test + @Disabled("Due to wrong implementation") public void testConvertToCorrectTypeBoolean() throws Exception { - - // validate type as Boolean - String value = "true"; - Object convertToCorrectType = RuntimeParameters.convertToCorrectType(value); - assertThat(BooleanUtils.toBooleanObject((boolean) convertToCorrectType), IsInstanceOf.instanceOf(Boolean.class)); - - value = "false"; - convertToCorrectType = RuntimeParameters.convertToCorrectType(value); - assertThat(BooleanUtils.toBooleanObject((boolean) convertToCorrectType), IsInstanceOf.instanceOf(Boolean.class)); - - value = "blue"; - convertToCorrectType = RuntimeParameters.convertToCorrectType(value); - exceptionGrabber.expect(ClassCastException.class); - exceptionGrabber.expectMessage("java.lang.String cannot be cast to java.lang.Boolean"); - assertThat(BooleanUtils.toBooleanObject((boolean) convertToCorrectType), Matchers.not(IsInstanceOf.instanceOf(Boolean.class))); - + // + // // validate type as Boolean + // String value = "true"; + // Object convertToCorrectType = RuntimeParameters.convertToCorrectType(value); + // assertThat(BooleanUtils.toBooleanObject((boolean) convertToCorrectType), + // IsInstanceOf.instanceOf(Boolean.class)); + // + // value = "false"; + // convertToCorrectType = RuntimeParameters.convertToCorrectType(value); + // assertThat(BooleanUtils.toBooleanObject((boolean) convertToCorrectType), + // IsInstanceOf.instanceOf(Boolean.class)); + // + // value = "blue"; + // Object anotherConvertToCorrectType = RuntimeParameters.convertToCorrectType(value); + // assertThrows(ClassCastException.class, () -> BooleanUtils.toBooleanObject((boolean) + // anotherConvertToCorrectType)); } - + @Test + @Disabled("Due to wrong implementation") public void testConvertToCorrectTypeInteger() throws Exception { - - String value = "1"; - Object convertToCorrectType = RuntimeParameters.convertToCorrectType(value); - assertThat((Integer) convertToCorrectType, IsInstanceOf.instanceOf(Integer.class)); - - value = "0.23"; - convertToCorrectType = RuntimeParameters.convertToCorrectType(value); - assertThat((Float) convertToCorrectType, IsInstanceOf.instanceOf(Float.class)); - - value = "blue"; - convertToCorrectType = RuntimeParameters.convertToCorrectType(value); - exceptionGrabber.expect(ClassCastException.class); - exceptionGrabber.expectMessage("java.lang.String cannot be cast to java.lang.Integer"); - assertThat((Integer) convertToCorrectType, IsInstanceOf.instanceOf(Integer.class)); + // + // String value = "1"; + // Object convertToCorrectType = RuntimeParameters.convertToCorrectType(value); + // assertThat((Integer) convertToCorrectType, IsInstanceOf.instanceOf(Integer.class)); + // + // value = "0.23"; + // convertToCorrectType = RuntimeParameters.convertToCorrectType(value); + // assertThat((Float) convertToCorrectType, IsInstanceOf.instanceOf(Float.class)); + // + // value = "blue"; + // Object anotherConvertToCorrectType = RuntimeParameters.convertToCorrectType(value); + // assertThrows(ClassCastException.class, ((Integer) anotherConvertToCorrectType)::toString); } - + @Test + @Disabled("Due to wrong implementation") public void testConvertToCorrectTypeString() throws Exception { - - String value = "hello"; - Object convertToCorrectType = RuntimeParameters.convertToCorrectType(value); - assertThat((String) convertToCorrectType, IsInstanceOf.instanceOf(String.class)); - - value = ""; - convertToCorrectType = RuntimeParameters.convertToCorrectType(value); - assertThat((String) convertToCorrectType, IsInstanceOf.instanceOf(String.class)); - - value = null; - convertToCorrectType = RuntimeParameters.convertToCorrectType(value); - assertThat((String) convertToCorrectType, Matchers.isEmptyOrNullString()); - + // + // String value = "hello"; + // Object convertToCorrectType = RuntimeParameters.convertToCorrectType(value); + // assertThat((String) convertToCorrectType, IsInstanceOf.instanceOf(String.class)); + // + // value = ""; + // convertToCorrectType = RuntimeParameters.convertToCorrectType(value); + // assertThat((String) convertToCorrectType, IsInstanceOf.instanceOf(String.class)); + // + // value = null; + // convertToCorrectType = RuntimeParameters.convertToCorrectType(value); + // assertThat((String) convertToCorrectType, Matchers.isEmptyOrNullString()); + // } - + @Test public void testBrowserOptionsVariable() throws Exception { - - Map expected = new HashMap(); + + Map expected = new HashMap<>(); expected.put("testEquals", "FirstEquals=SecondEquals"); expected.put("headless", ""); expected.put("--testMe", ""); expected.put("window-size", "1200x600"); expected.put("acceptInsecureCerts", true); expected.put("maxInstances", 3); - + assertThat(RuntimeParameters.DEVICE_OPTIONS.getValues() - .size(), + .size(), Matchers.is(6)); - + assertThat(RuntimeParameters.DEVICE_OPTIONS.getValues() - .toString(), + .toString(), Matchers.is(expected.toString())); - + } - + @Test public void testBrowserOptionsSet() throws Exception { - + RuntimeParameters.DEVICE_OPTIONS.getValues() .forEach((key, value) -> { String item = (value.toString() .isEmpty()) ? key : key + "=" + value; System.out.println(item); }); - + } - + @Test public void testPlatformNameIOS() throws Exception { System.setProperty("platformName", "ios"); RuntimeParameters.PLATFORM_NAME.refreshParameterValue(); - + assertEquals("System parameters for empty property 'platformName' should be 'iOS'", "iOS", RuntimeParameters.PLATFORM_NAME.getValue()); - + } - + @Test public void testGetEmptyProperty() { values.forEach((String key, String value) -> System.clearProperty(key)); - + RuntimeParameters.DEVICE_URL.refreshParameterValue(); RuntimeParameters.AUTOMATION_NAME.refreshParameterValue(); RuntimeParameters.PLATFORM_NAME.refreshParameterValue(); @@ -190,8 +185,8 @@ public void testGetEmptyProperty() { RuntimeParameters.BROWSER_NAME.refreshParameterValue(); RuntimeParameters.NEW_COMMAND_TIMEOUT.refreshParameterValue(); RuntimeParameters.DEVICE_OPTIONS.refreshParameterValue(); - - assertThat("System parameters for empty property 'deviceUrl' should be 'http://127.0.0.1:4723'", RuntimeParameters.DEVICE_URL.getValue(), Matchers.equalTo("http://127.0.0.1:4723")); + + assertThat("System parameters for empty property 'deviceUrl' should be 'http://0.0.0.0:4723'", RuntimeParameters.DEVICE_URL.getValue(), Matchers.equalTo("http://0.0.0.0:4723")); assertThat("System parameters for empty property 'automationName' should be 'Appium'", RuntimeParameters.AUTOMATION_NAME.getValue(), Matchers.equalTo("Appium")); assertThat("System parameters for empty property 'platformName' should be 'Android'", RuntimeParameters.PLATFORM_NAME.getValue(), Matchers.equalTo("Android")); assertThat("System parameters for empty property 'platformVersion' should be 'null'", RuntimeParameters.PLATFORM_VERSION.getValue(), Matchers.isEmptyString()); @@ -200,16 +195,13 @@ public void testGetEmptyProperty() { assertThat("System parameters for empty property 'browserName' should be 'null'", RuntimeParameters.BROWSER_NAME.getValue(), Matchers.isEmptyString()); assertThat("System parameters for empty property 'newCommandTimeout' should be '4000'", RuntimeParameters.NEW_COMMAND_TIMEOUT.getValue(), Matchers.equalTo("4000")); assertThat("System parameters for empty property 'deviceOptions' should be 'null'", RuntimeParameters.DEVICE_OPTIONS.getValue(), Matchers.isEmptyString()); - + } - + @Test public void testParamsToString() throws Exception { - RuntimeParameters.valueOf("PLATFORM_NAME") .toString() .equals("platformName=Android"); - } - } diff --git a/mrchecker-framework-modules/mrchecker-security-module/pom.xml b/mrchecker-framework-modules/mrchecker-security-module/pom.xml index 962c3bf6..6a0f6bc1 100644 --- a/mrchecker-framework-modules/mrchecker-security-module/pom.xml +++ b/mrchecker-framework-modules/mrchecker-security-module/pom.xml @@ -1,25 +1,27 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 mrchecker-test-framework com.capgemini.mrchecker - 2.4.2-SNAPSHOT + 3.0.1-SNAPSHOT + mrchecker-security-module - 1.2.1-SNAPSHOT + 1.2.2-SNAPSHOT jar MrChecker - Security - Module MrChecker Test Framework Security supports: - Library reference to make REST/HTTP calls to the tested system - - Other common features needed for security testing + - Other common features needed for security testing + https://github.com/devonfw/devonfw-testing - Capgemini - Nearshore Test Center - Poland + Capgemini - Nearshore Test Center - Poland http://nsc.capgemini.com/nearshoretestcenter @@ -27,7 +29,7 @@ Lukasz Stefaniszyn lukasz.stefaniszyn@capgemini.com - Capgemini - Nearshore Test Center - Poland + Capgemini - Nearshore Test Center - Poland http://nsc.capgemini.com/nearshoretestcenter @@ -54,7 +56,7 @@ UTF8 - 4.12.1.4-SNAPSHOT + 5.6.2.1-SNAPSHOT @@ -73,10 +75,22 @@ rest-assured - + + + + io.qameta.allure + allure-junit5 + test + + + + io.qameta.allure + allure-junit-platform + + io.qameta.allure - allure-junit4 + allure-java-commons diff --git a/mrchecker-framework-modules/mrchecker-security-module/src/main/java/com/capgemini/mrchecker/security/core/BasePage.java b/mrchecker-framework-modules/mrchecker-security-module/src/main/java/com/capgemini/mrchecker/security/core/BasePage.java index fda38a92..444b3fa3 100644 --- a/mrchecker-framework-modules/mrchecker-security-module/src/main/java/com/capgemini/mrchecker/security/core/BasePage.java +++ b/mrchecker-framework-modules/mrchecker-security-module/src/main/java/com/capgemini/mrchecker/security/core/BasePage.java @@ -1,67 +1,29 @@ package com.capgemini.mrchecker.security.core; import com.capgemini.mrchecker.test.core.BaseTest; -import com.capgemini.mrchecker.test.core.BaseTestWatcher; -import com.capgemini.mrchecker.test.core.ITestObserver; import com.capgemini.mrchecker.test.core.ModuleType; +import com.capgemini.mrchecker.test.core.Page; import com.capgemini.mrchecker.test.core.analytics.IAnalytics; import com.capgemini.mrchecker.test.core.base.environment.EnvironmentModule; import com.capgemini.mrchecker.test.core.base.environment.IEnvironmentService; -import com.capgemini.mrchecker.test.core.logger.BFLogger; import com.google.inject.Guice; -abstract public class BasePage implements ITestObserver { +abstract public class BasePage extends Page { private static IEnvironmentService environmentService; - private final static IAnalytics analytics; - public final static String analitycsCategoryName = "Security-Module"; + private final static IAnalytics ANALYTICS; + public final static String ANALYTICS_CATEGORY_NAME = "Security-Module"; static { // Get analytics instance created in BaseTets - analytics = BaseTest.getAnalytics(); + ANALYTICS = BaseTest.getAnalytics(); // Read Environment variables either from environmnets.csv or any other input data. - setEnvironmetInstance(); + setEnvironmentInstance(); } public static IAnalytics getAnalytics() { - return BasePage.analytics; - } - - public BasePage() { - this.addObserver(); - } - - @Override - public void addObserver() { - BaseTestWatcher.addObserver(this); - } - - @Override - public void onTestFailure() { - BFLogger.logDebug("BasePage.onTestFailure " + this.getClass() - .getSimpleName()); - } - - @Override - public void onTestSuccess() { - // All actions needed while test method is success - BFLogger.logDebug("BasePage.onTestSuccess " + this.getClass() - .getSimpleName()); - } - - @Override - public void onTestFinish() { - // All actions needed while test class is finishing - BFLogger.logDebug("BasePage.onTestFinish " + this.getClass() - .getSimpleName()); - BaseTestWatcher.removeObserver(this); - } - - @Override - public void onTestClassFinish() { - BFLogger.logDebug("BasePage.onTestClassFinish " + this.getClass() - .getSimpleName()); + return ANALYTICS; } @Override @@ -69,9 +31,8 @@ public ModuleType getModuleType() { return ModuleType.SECURITY; } - private static void setEnvironmetInstance() { + private static void setEnvironmentInstance() { environmentService = Guice.createInjector(new EnvironmentModule()) .getInstance(IEnvironmentService.class); } - } diff --git a/mrchecker-framework-modules/mrchecker-security-module/src/main/java/com/capgemini/mrchecker/security/core/BasePageAutoRegistration.java b/mrchecker-framework-modules/mrchecker-security-module/src/main/java/com/capgemini/mrchecker/security/core/BasePageAutoRegistration.java new file mode 100644 index 00000000..04a25f5b --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-security-module/src/main/java/com/capgemini/mrchecker/security/core/BasePageAutoRegistration.java @@ -0,0 +1,13 @@ +package com.capgemini.mrchecker.security.core; + +/** + * The instances of BasePageAutoRegistration class are added to the test execution observer automatically in + * constructor. + * Although this operation is unsafe, it's been added to support migration from MrChecker Junit4 to Junit5. + */ +@Deprecated +abstract public class BasePageAutoRegistration extends BasePage { + public BasePageAutoRegistration() { + addToTestExecutionObserver(); + } +} diff --git a/mrchecker-framework-modules/mrchecker-security-module/src/test/java/com/capgemini/mrchecker/security/BasePageTest.java b/mrchecker-framework-modules/mrchecker-security-module/src/test/java/com/capgemini/mrchecker/security/BasePageTest.java deleted file mode 100644 index 15fb0138..00000000 --- a/mrchecker-framework-modules/mrchecker-security-module/src/test/java/com/capgemini/mrchecker/security/BasePageTest.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.capgemini.mrchecker.security; - -import org.junit.Test; - -import com.capgemini.mrchecker.security.core.BasePage; - -public class BasePageTest { - - @Test - public void test() { - MyPage myPage = new MyPage(); - - myPage.myMethod(); - } - - private static class MyPage extends BasePage { - - public String myMethod() { - return "Welcome"; - } - } - -} diff --git a/mrchecker-framework-modules/mrchecker-security-module/src/test/java/com/capgemini/mrchecker/security/tags/IntegrationTest.java b/mrchecker-framework-modules/mrchecker-security-module/src/test/java/com/capgemini/mrchecker/security/tags/IntegrationTest.java new file mode 100644 index 00000000..8d77e5bb --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-security-module/src/test/java/com/capgemini/mrchecker/security/tags/IntegrationTest.java @@ -0,0 +1,14 @@ +package com.capgemini.mrchecker.security.tags; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import org.junit.jupiter.api.Tag; + +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +@Tag("IntegrationTest") +public @interface IntegrationTest { +} \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-security-module/src/test/java/com/capgemini/mrchecker/security/tags/UnitTest.java b/mrchecker-framework-modules/mrchecker-security-module/src/test/java/com/capgemini/mrchecker/security/tags/UnitTest.java new file mode 100644 index 00000000..88c7f4a7 --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-security-module/src/test/java/com/capgemini/mrchecker/security/tags/UnitTest.java @@ -0,0 +1,14 @@ +package com.capgemini.mrchecker.security.tags; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import org.junit.jupiter.api.Tag; + +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +@Tag("UnitTest") +public @interface UnitTest { +} \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-security-module/src/test/java/com/capgemini/mrchecker/security/testsuites/UnitTestsSuite.java b/mrchecker-framework-modules/mrchecker-security-module/src/test/java/com/capgemini/mrchecker/security/testsuites/UnitTestsSuite.java new file mode 100644 index 00000000..b16cd25d --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-security-module/src/test/java/com/capgemini/mrchecker/security/testsuites/UnitTestsSuite.java @@ -0,0 +1,12 @@ +package com.capgemini.mrchecker.security.testsuites; + +import org.junit.platform.runner.JUnitPlatform; +import org.junit.platform.suite.api.IncludeTags; +import org.junit.platform.suite.api.SelectPackages; +import org.junit.runner.RunWith; + +@RunWith(JUnitPlatform.class) +@IncludeTags({ "UnitTest" }) +@SelectPackages("com.capgemini.mrchecker.security") +public class UnitTestsSuite { +} diff --git a/mrchecker-framework-modules/mrchecker-security-module/src/test/java/com/capgemini/mrchecker/security/unit/BasePageTest.java b/mrchecker-framework-modules/mrchecker-security-module/src/test/java/com/capgemini/mrchecker/security/unit/BasePageTest.java new file mode 100644 index 00000000..f5eca5db --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-security-module/src/test/java/com/capgemini/mrchecker/security/unit/BasePageTest.java @@ -0,0 +1,25 @@ +package com.capgemini.mrchecker.security.unit; + +import org.junit.jupiter.api.Test; + +import com.capgemini.mrchecker.security.core.BasePage; +import com.capgemini.mrchecker.security.tags.UnitTest; +import com.capgemini.mrchecker.test.core.utils.PageFactory; + +@UnitTest +public class BasePageTest { + + @Test + public void test() { + MyPage myPage = PageFactory.getPageInstance(MyPage.class); + myPage.myMethod(); + } + + public static class MyPage extends BasePage { + + public String myMethod() { + return "Welcome"; + } + } + +} diff --git a/mrchecker-framework-modules/mrchecker-security-module/src/test/resources/allure.properties b/mrchecker-framework-modules/mrchecker-security-module/src/test/resources/allure.properties new file mode 100644 index 00000000..6c1e0bb1 --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-security-module/src/test/resources/allure.properties @@ -0,0 +1 @@ +allure.results.directory=target/allure-results \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-security-module/src/test/resources/junit-platform.properties b/mrchecker-framework-modules/mrchecker-security-module/src/test/resources/junit-platform.properties new file mode 100644 index 00000000..0a5f88f7 --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-security-module/src/test/resources/junit-platform.properties @@ -0,0 +1,8 @@ +junit.jupiter.extensions.autodetection.enabled=true +junit.jupiter.execution.parallel.enabled=true +#junit.jupiter.execution.parallel.mode.default=concurrent +junit.jupiter.execution.parallel.mode.default=same_thread +junit.jupiter.execution.parallel.mode.classes.default=concurrent +#junit.jupiter.execution.parallel.mode.classes.default=same_thread +junit.jupiter.execution.parallel.config.strategy=dynamic +junit.jupiter.execution.parallel.config.dynamic.factor=1 diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/pom.xml b/mrchecker-framework-modules/mrchecker-selenium-module/pom.xml index 71d55d6e..2d701354 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/pom.xml +++ b/mrchecker-framework-modules/mrchecker-selenium-module/pom.xml @@ -7,10 +7,11 @@ mrchecker-test-framework com.capgemini.mrchecker - 2.4.2-SNAPSHOT + 3.0.1-SNAPSHOT + mrchecker-selenium-module - 3.141.59.2-SNAPSHOT + 3.141.59.3-SNAPSHOT jar MrChecker - Selenium - Module MrChecker Test Framework Selenium supports: @@ -67,18 +68,13 @@ UTF8 - 4.12.1.4-SNAPSHOT + 5.6.2.1-SNAPSHOT 3.141.59 - 1.11.2 - 1.3 - - - 1.0.0-M2 23.0 @@ -104,14 +100,6 @@ ${mrchecker-core-module.version} - - - - io.qameta.allure - allure-junit4 - - - org.seleniumhq.selenium @@ -148,42 +136,24 @@ - + - org.junit.platform - junit-platform-surefire-provider - - - junit - junit - - - - - - com.google.inject - guice - - - - - org.hamcrest - hamcrest-all + + io.qameta.allure + allure-junit5 test - - joda-time - joda-time + io.qameta.allure + allure-junit-platform - org.apache.commons - commons-csv + io.qameta.allure + allure-java-commons - org.jsoup @@ -204,7 +174,6 @@ - diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/BasePage.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/BasePage.java index 9e774738..9add375a 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/BasePage.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/BasePage.java @@ -1,6 +1,7 @@ package com.capgemini.mrchecker.selenium.core; import java.util.List; +import java.util.Objects; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; @@ -18,9 +19,8 @@ import com.capgemini.mrchecker.selenium.core.newDrivers.INewWebDriver; import com.capgemini.mrchecker.selenium.core.utils.WindowUtils; import com.capgemini.mrchecker.test.core.BaseTest; -import com.capgemini.mrchecker.test.core.BaseTestWatcher; -import com.capgemini.mrchecker.test.core.ITestObserver; import com.capgemini.mrchecker.test.core.ModuleType; +import com.capgemini.mrchecker.test.core.Page; import com.capgemini.mrchecker.test.core.analytics.IAnalytics; import com.capgemini.mrchecker.test.core.base.environment.IEnvironmentService; import com.capgemini.mrchecker.test.core.base.properties.PropertiesSettingsModule; @@ -29,100 +29,71 @@ import io.qameta.allure.Attachment; -abstract public class BasePage implements IBasePage, ITestObserver { +abstract public class BasePage extends Page implements IBasePage { // in seconds; this value should be used for very shot delay purpose e.g. to // wait for JavaScript take effort on element - public static final int EXPLICITY_SHORT_WAIT_TIME = 1; + public static final int EXPLICIT_SHORT_WAIT_TIME = 1; - public static final int PROGRESSBARWAITTIMER = 60; + public static final int PROGRESS_BAR_WAIT_TIMER = 60; // in seconds. timer used in findElementDynamic - public static final int EXPLICITYWAITTIMER = 20; + public static final int EXPLICIT_WAIT_TIMER = 20; public static final int MAX_COMPONENT_RELOAD_COUNT = 3; private static DriverManager driver = null; private static WebDriverWait webDriverWait; - - private BasePage parent; + private BasePage parent; private static IEnvironmentService environmentService; - private final static IAnalytics analytics; - public final static String analitycsCategoryName = "Selenium-NewDrivers"; + private final static IAnalytics ANALYTICS; + public final static String ANALYTICS_CATEGORY_NAME = "Selenium-NewDrivers"; + + private final static PropertiesSelenium PROPERTIES_SELENIUM; - private final static PropertiesSelenium propertiesSelenium; static { // Get analytics instance created in BaseTets - analytics = BaseTest.getAnalytics(); + ANALYTICS = BaseTest.getAnalytics(); // Get and then set properties information from selenium.settings file - propertiesSelenium = setPropertiesSettings(); + PROPERTIES_SELENIUM = setPropertiesSettings(); // Read System or maven parameters setRuntimeParametersSelenium(); // Read Environment variables either from environmnets.csv or any other input data. - setEnvironmetInstance(); + setEnvironmentInstance(); } public static IAnalytics getAnalytics() { - return BasePage.analytics; + return ANALYTICS; } public BasePage() { - this(getDriver(), null); + this(null); } public BasePage(BasePage parent) { - this(getDriver(), parent); - } - - public BasePage(INewWebDriver driver, BasePage parent) { - // Add given module to Test core Observable list - this.addObserver(); - - webDriverWait = new WebDriverWait(getDriver(), BasePage.EXPLICITYWAITTIMER); - - this.setParent(parent); + webDriverWait = new WebDriverWait(getDriver(), BasePage.EXPLICIT_WAIT_TIMER); + setParent(parent); // If the page is not yet loaded, then load it - if (!(this.isLoaded())) { // In this scenario check if - this.load(); + // TODO: check that + if (!isLoaded()) { // In this scenario check if + load(); } - - } - - @Override - public void addObserver() { - BaseTestWatcher.addObserver(this); } @Override public void onTestFailure() { - BFLogger.logDebug("BasePage.onTestFailure " + this.getClass() - .getSimpleName()); + super.onTestFailure(); makeScreenshotOnFailure(); makeSourcePageOnFailure(); } - @Override - public void onTestSuccess() { - BFLogger.logDebug("BasePage.onTestSuccess " + this.getClass() - .getSimpleName()); - } - - @Override - public void onTestFinish() { - BFLogger.logDebug("BasePage.onTestFinish " + this.getClass() - .getSimpleName()); - BaseTestWatcher.removeObserver(this); - } - @Override public void onTestClassFinish() { - BFLogger.logDebug("BasePage.onTestClassFinish " + this.getClass() - .getSimpleName()); - BFLogger.logDebug("driver:" + getDriver().toString()); + super.onTestClassFinish(); DriverManager.closeDriver(); } @@ -132,6 +103,7 @@ public ModuleType getModuleType() { } @Attachment("Screenshot on failure") + @SuppressWarnings("UnusedReturnValue") public byte[] makeScreenshotOnFailure() { byte[] screenshot = null; try { @@ -143,6 +115,7 @@ public byte[] makeScreenshotOnFailure() { } @Attachment("Source Page on failure") + @SuppressWarnings("UnusedReturnValue") public String makeSourcePageOnFailure() { return DriverManager.getDriver() .getPageSource(); @@ -158,26 +131,17 @@ public void refreshPage() { } public static INewWebDriver getDriver() { - if (BasePage.driver == null) { - - BasePage.driver = new DriverManager(propertiesSelenium); - + if (Objects.isNull(driver)) { + driver = new DriverManager(PROPERTIES_SELENIUM); } - return BasePage.driver.getDriver(); + return driver.getDriver(); } - public static void navigateBack() { - navigateBack(true); - } - /** * Navigates to previous site (works like pressing browsers 'Back' button) - * - * @param andWait - * - wait for progress bars to load if true */ - public static void navigateBack(boolean andWait) { + public static void navigateBack() { getDriver().navigate() .back(); getDriver().waitForPageLoaded(); @@ -192,7 +156,7 @@ public void setParent(BasePage parent) { } public BasePage getParent() { - return this.parent; + return parent; } public abstract String pageTitle(); @@ -201,7 +165,6 @@ public void loadPage(String url) { BFLogger.logDebug(getClass().getName() + ": Opening page: " + url); getDriver().get(url); getDriver().waitForPageLoaded(); - } public boolean isUrlAndPageTitleAsCurrentPage(String url) { @@ -224,7 +187,9 @@ public boolean isUrlAndPageTitleAsCurrentPage(String url) { * BFElementNotFoundException * * @throws BFElementNotFoundException + * BFElementNotFoundException * @param cssSelector + * cssSelector * @return false if element have an attribute displayed = none, otherwise return true; */ public static boolean isElementDisplayed(By cssSelector) { @@ -242,12 +207,14 @@ public static boolean isElementDisplayed(By cssSelector) { * throw BFElementNotFoundException * * @throws BFElementNotFoundException + * BFElementNotFoundException * @param cssSelector + * cssSelector * @param parent + * parent * @return false if element have an attribute displayed = none, otherwise return true; */ public static boolean isElementDisplayed(By cssSelector, WebElement parent) { - @SuppressWarnings("deprecation") List elements = parent.findElements(cssSelector); if (elements.isEmpty()) { throw new BFElementNotFoundException(cssSelector); @@ -260,7 +227,9 @@ public static boolean isElementDisplayed(By cssSelector, WebElement parent) { * Check if given selector is displayed on the page and it contain a specific text * * @param cssSelector + * cssSelector * @param text + * text * @return true if a given element is displayed with a specific text * @throws BFElementNotFoundException * if element is not found in DOM @@ -286,7 +255,9 @@ public static boolean isElementDisplayed(By cssSelector, String text) { * Check if given selector is displayed on the page * * @param selector + * selector * @param parent + * parent * @return true if a given element is displayed */ public static boolean isElementDisplayedNoException(By selector, WebElement parent) { @@ -301,6 +272,7 @@ public static boolean isElementDisplayedNoException(By selector, WebElement pare * Check if given selector is displayed on the page * * @param selector + * selector * @return true if a given element is displayed */ public static boolean isElementDisplayedNoException(By selector) { @@ -329,8 +301,8 @@ public static boolean isLinkClickable(WebElement element) { } public static WebDriverWait getWebDriverWait() { - if (null == webDriverWait) { - BasePage.webDriverWait = new WebDriverWait(getDriver(), BasePage.EXPLICITYWAITTIMER); + if (Objects.isNull(webDriverWait)) { + BasePage.webDriverWait = new WebDriverWait(getDriver(), BasePage.EXPLICIT_WAIT_TIMER); } return BasePage.webDriverWait; } @@ -353,34 +325,31 @@ private static boolean isTitleElementDisplayed(By selector, String title) { * Open link in new tab * * @param url + * url */ public static void openInNewTab(String url) { - JavascriptExecutor js = (JavascriptExecutor) BasePage.getDriver(); + JavascriptExecutor js = (JavascriptExecutor) getDriver(); js.executeScript("window.open(arguments[0], '_blank');", url); WindowUtils.switchWindow(url, true); } private static PropertiesSelenium setPropertiesSettings() { // Get and then set properties information from selenium.settings file - PropertiesSelenium propertiesSelenium = Guice.createInjector(PropertiesSettingsModule.init()) + return Guice.createInjector(PropertiesSettingsModule.init()) .getInstance(PropertiesSelenium.class); - return propertiesSelenium; } private static void setRuntimeParametersSelenium() { // Read System or maven parameters BFLogger.logDebug(java.util.Arrays.asList(RuntimeParametersSelenium.values()) .toString()); - } - private static void setEnvironmetInstance() { + private static void setEnvironmentInstance() { /* * Environment variables either from environmnets.csv or any other input data. For now there is no properties * settings file for Selenium module. In future, please have a look on Core Module IEnvironmentService * environmetInstance = Guice.createInjector(new EnvironmentModule()) .getInstance(IEnvironmentService.class); */ - } - } diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/BasePageAutoRegistration.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/BasePageAutoRegistration.java new file mode 100644 index 00000000..2fe2b05b --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/BasePageAutoRegistration.java @@ -0,0 +1,19 @@ +package com.capgemini.mrchecker.selenium.core; + +/** + * The instances of BasePageAutoRegistration class are added to the test execution observer automatically in + * constructor. + * Although this operation is unsafe, it's been added to support migration from MrChecker Junit4 to Junit5. + */ +@Deprecated +abstract public class BasePageAutoRegistration extends BasePage { + + public BasePageAutoRegistration() { + addToTestExecutionObserver(); + } + + public BasePageAutoRegistration(BasePageAutoRegistration parent) { + super(parent); + addToTestExecutionObserver(); + } +} diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/base/environment/GetEnvironmentParam.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/base/environment/GetEnvironmentParam.java index 27cb0107..daf399cf 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/base/environment/GetEnvironmentParam.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/base/environment/GetEnvironmentParam.java @@ -1,5 +1,7 @@ package com.capgemini.mrchecker.selenium.core.base.environment; +import java.util.Objects; + import com.capgemini.mrchecker.test.core.BaseTest; import com.capgemini.mrchecker.test.core.exceptions.BFInputDataException; @@ -9,6 +11,7 @@ */ public enum GetEnvironmentParam { + // TODO: do we need that class in module? // Name if enum must be in line with cell name in /src/resources/environments/environment.csv WWW_FONT_URL, TOOLS_QA, @@ -17,20 +20,16 @@ public enum GetEnvironmentParam { public String getValue() { - if (null == BaseTest.getEnvironmentService()) { + if (Objects.isNull(BaseTest.getEnvironmentService())) { throw new BFInputDataException("Environment Parameters class wasn't initialized properly"); } return BaseTest.getEnvironmentService() - .getValue(this.name()); - + .getValue(name()); } @Override public String toString() { - - return this.getValue(); - + return getValue(); } - } diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/base/properties/PropertiesSelenium.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/base/properties/PropertiesSelenium.java index b9182a16..8f604b63 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/base/properties/PropertiesSelenium.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/base/properties/PropertiesSelenium.java @@ -4,153 +4,175 @@ import com.google.inject.name.Named; public class PropertiesSelenium { - - private String webDrivers = "./lib/webdrivers"; // default value - private String seleniumChrome = webDrivers + "/chrome/chromedriver.exe"; // default value - private String seleniumOpera = webDrivers + "/opera/operadriver.exe"; // default value - private String seleniumEdge = webDrivers + "/edge/msedgedriver.exe"; // default value - private String seleniumFirefox = webDrivers + "/firefox/geckodriver.exe"; // default value - private String seleniumIE = webDrivers + "/internetexplorer/IEDriverServer.exe"; // default value - private String proxy = ""; // default value - private boolean driverAutoUpdateFlag = true; // default value - private String chromeDriverVersion = ""; - private String chromeHeadlessDriverVersion = ""; - private String internetExplorerDriverVersion = ""; - private String geckoDriverVersion = ""; - private String edgeDriverVersion = ""; - private boolean edgeDriverFeatureOnDemandFlag = true; - private String operaDriverVersion = ""; - + + private String webDrivers = "./lib/webdrivers"; // default + // value + private String seleniumChrome = webDrivers + "/chrome/chromedriver.exe"; // default + // value + private String seleniumOpera = webDrivers + "/opera/operadriver.exe"; // default + // value + private String seleniumEdge = webDrivers + "/edge/msedgedriver.exe"; // default + // value + private String seleniumFirefox = webDrivers + "/firefox/geckodriver.exe"; // default + // value + private String seleniumIE = webDrivers + "/internetexplorer/IEDriverServer.exe"; // default + // value + private String proxy = ""; // default + // value + private boolean driverAutoUpdateFlag = true; // default + // value + private String chromeDriverVersion = ""; + // private String chromeHeadlessDriverVersion = ""; + private String internetExplorerDriverVersion = ""; + private String geckoDriverVersion = ""; + private String edgeDriverVersion = ""; + private boolean edgeDriverFeatureOnDemandFlag = true; + private String operaDriverVersion = ""; + @Inject(optional = true) + @SuppressWarnings("unused") private void setSeleniumChrome(@Named("selenium.chrome") String path) { - this.seleniumChrome = path; - + seleniumChrome = path; + } - + public String getSeleniumChrome() { - return this.seleniumChrome; + return seleniumChrome; } - + @Inject(optional = true) + @SuppressWarnings("unused") private void setSeleniumOpera(@Named("selenium.opera") String path) { - this.seleniumOpera = path; - + seleniumOpera = path; + } - + public String getSeleniumOpera() { - return this.seleniumOpera; + return seleniumOpera; } - + @Inject(optional = true) + @SuppressWarnings("unused") private void setSeleniumEdge(@Named("selenium.edge") String path) { - this.seleniumEdge = path; - + seleniumEdge = path; + } - + public String getSeleniumEdge() { - return this.seleniumEdge; + return seleniumEdge; } - + @Inject(optional = true) + @SuppressWarnings("unused") private void setSeleniumFirefox(@Named("selenium.firefox") String path) { - this.seleniumFirefox = path; - + seleniumFirefox = path; + } - + public String getSeleniumFirefox() { - return this.seleniumFirefox; + return seleniumFirefox; } - + @Inject(optional = true) + @SuppressWarnings("unused") private void setSeleniumIE(@Named("selenium.ie") String path) { - this.seleniumIE = path; - + seleniumIE = path; + } - + public String getSeleniumIE() { - return this.seleniumIE; + return seleniumIE; } - + @Inject(optional = true) + @SuppressWarnings("unused") private void setWebDrivers(@Named("selenium.webdrivers") String path) { - this.webDrivers = path; - + webDrivers = path; + } - + public String getWebDrivers() { - return this.webDrivers; + return webDrivers; } - + @Inject(optional = true) + @SuppressWarnings("unused") private void setProxy(@Named("selenium.proxy") String path) { - this.proxy = path; - + proxy = path; + } - + public String getProxy() { - return this.proxy; + return proxy; } - + @Inject(optional = true) + @SuppressWarnings("unused") private void setDriverAutoUpdateFlag(@Named("selenium.driverAutoUpdate") boolean flag) { - this.driverAutoUpdateFlag = flag; + driverAutoUpdateFlag = flag; } - + public boolean getDriverAutoUpdateFlag() { - return this.driverAutoUpdateFlag; + return driverAutoUpdateFlag; } - + @Inject(optional = true) + @SuppressWarnings("unused") private void setChromeDriverVersion(@Named("wdm.chromeDriverVersion") String version) { - this.chromeDriverVersion = version; + chromeDriverVersion = version; } - + public String getChromeDriverVersion() { - return this.chromeDriverVersion; + return chromeDriverVersion; } - + @Inject(optional = true) + @SuppressWarnings("unused") private void setInternetExplorerDriverVersion(@Named("wdm.internetExplorerDriverVersion") String version) { - this.geckoDriverVersion = version; + internetExplorerDriverVersion = version; } - + public String getInternetExplorerDriverVersion() { - return this.internetExplorerDriverVersion; + return internetExplorerDriverVersion; } - + @Inject(optional = true) + @SuppressWarnings("unused") private void setGeckoDriverVersion(@Named("wdm.geckoDriverVersion") String version) { - this.geckoDriverVersion = version; + geckoDriverVersion = version; } - + public String getGeckoDriverVersion() { - return this.geckoDriverVersion; + return geckoDriverVersion; } - + @Inject(optional = true) + @SuppressWarnings("unused") private void setEdgeDriverVersion(@Named("wdm.edgeVersion") String version) { - this.edgeDriverVersion = version; + edgeDriverVersion = version; } - + public String getEdgeDriverVersion() { - return this.edgeDriverVersion; + return edgeDriverVersion; } - + @Inject(optional = true) + @SuppressWarnings("unused") private void setEdgeDriverFeatureOnDemandFlag(@Named("wdm.edgeFeatureOnDemand") boolean flag) { - this.edgeDriverFeatureOnDemandFlag = flag; + edgeDriverFeatureOnDemandFlag = flag; } - + public boolean getEdgeDriverFeatureOnDemandFlag() { - return this.edgeDriverFeatureOnDemandFlag; + return edgeDriverFeatureOnDemandFlag; } - + @Inject(optional = true) + @SuppressWarnings("unused") private void setOperaDriverVersion(@Named("wdm.operaDriverVersion") String version) { - this.operaDriverVersion = version; + operaDriverVersion = version; } - + public String getOperaDriverVersion() { - return this.operaDriverVersion; + return operaDriverVersion; } } diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/base/runtime/RuntimeParametersSelenium.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/base/runtime/RuntimeParametersSelenium.java index 8c2213d6..5d92656d 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/base/runtime/RuntimeParametersSelenium.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/base/runtime/RuntimeParametersSelenium.java @@ -2,88 +2,75 @@ import java.util.Arrays; import java.util.Map; +import java.util.Objects; import java.util.stream.Collectors; import org.apache.commons.lang.BooleanUtils; +import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.math.NumberUtils; -import com.capgemini.mrchecker.test.core.base.runtime.RuntimeParametersI; -import com.capgemini.mrchecker.test.core.logger.BFLogger; +import com.capgemini.mrchecker.test.core.base.runtime.IRuntimeParameters; /** * This class stores various system properties - * + * * @author LUSTEFAN + * @author MBABIARZ */ -public enum RuntimeParametersSelenium implements RuntimeParametersI { +public enum RuntimeParametersSelenium implements IRuntimeParameters { - BROWSER("browser", "chrome"), + BROWSER("browser", "chrome") { + protected void setValue() { + super.setValue(); + paramValue = paramValue.toLowerCase(); + if (paramValue.equals(INVALID_IE_NAME)) + paramValue = VALID_IE_NAME; + } + }, BROWSER_VERSION("browserVersion", ""), SELENIUM_GRID("seleniumGrid", ""), OS("os", ""), BROWSER_OPTIONS("browserOptions", "") { public Map getValues() { - return Arrays.asList(this.paramValue.split(";")) - .stream() - .filter(i -> i != "") // remove empty inputs - .map(i -> i.split("=", 2)) // split to key, value. Not more than one time + return Arrays.stream(getValue().split(BROWSER_OPTIONS_DELIMITER_REGEX)) + .filter(i -> !i.isEmpty()) // remove + // empty + // inputs + .map(i -> i.split(BROWSER_OPTIONS_KEY_VALUE_DELIMITER_REGEX, TOKENS_LIMIT)) // split to key, value. + // Not more than one time .map(i -> new String[] { i[0], (i.length == 1) ? "" : i[1] }) // if value is empty, set empty text - .collect(Collectors.toMap(i -> i[0], i -> (Object) convertToCorrectType(i[1].trim()))); // create + .collect(Collectors.toMap(i -> i[0], i -> convertToCorrectType(i[1].trim()))); // create } - }; - private String paramName; - protected String paramValue; - private String defaultValue; + public static final String VALID_IE_NAME = "internet explorer"; + public static final String INVALID_IE_NAME = "ie"; + private static final int TOKENS_LIMIT = 2; + private static final String BROWSER_OPTIONS_KEY_VALUE_DELIMITER_REGEX = "="; + private static final String BROWSER_OPTIONS_DELIMITER_REGEX = ";"; + + private final String paramName; + private final String defaultValue; + protected String paramValue; - private RuntimeParametersSelenium(String paramName, String defaultValue) { + RuntimeParametersSelenium(String paramName, String defaultValue) { this.paramName = paramName; this.defaultValue = defaultValue; setValue(); - - } - - protected static Object convertToCorrectType(String value) { - Object convertedValue = value; - - if (null != BooleanUtils.toBooleanObject(value)) { - convertedValue = Boolean.valueOf(value); - return convertedValue; - } - - if (NumberUtils.isNumber(value)) { - if (NumberUtils.isDigits(value)) { - // so it is integer value - convertedValue = Integer.valueOf(value); - return convertedValue; - } else { - // so it is probably float value - convertedValue = Float.valueOf(value); - return convertedValue; - } - } - - return convertedValue; } @Override public String getValue() { - return this.paramValue; + return paramValue; } public Map getValues() { return null; } - + @Override public String getKey() { - return this.paramName; - } - - @Override - public String toString() { - return paramName + "=" + this.getValue(); + return paramName; } @Override @@ -91,38 +78,33 @@ public void refreshParameterValue() { setValue(); } - private void setValue() { - - String paramValue = System.getProperty(this.paramName); - paramValue = isSystemParameterEmpty(paramValue) ? this.defaultValue : paramValue; - ; - - switch (this.name()) { - case "BROWSER": - paramValue = paramValue.toLowerCase(); - if (paramValue.equals("ie")) { - paramValue = "internet explorer"; - } - break; - case "BROWSER_VERSION": - break; - case "SELENIUM_GRID": - break; - case "OS": - break; - case "BROWSER_OPTIONS": - break; - default: - BFLogger.logError("Unknown RuntimeParameter = " + this.name()); - break; + protected void setValue() { + String paramValueFromSystem = System.getProperty(getKey()); + this.paramValue = isSystemParameterEmpty(paramValueFromSystem) ? defaultValue : paramValueFromSystem; + } + + private static Object convertToCorrectType(String value) { + if (!Objects.isNull(BooleanUtils.toBooleanObject(value))) { + return Boolean.valueOf(value); } - this.paramValue = paramValue; + if (NumberUtils.isNumber(value)) { + if (NumberUtils.isDigits(value)) { + return Integer.parseInt(value); + } else { + return Float.parseFloat(value); + } + } + return value; } - private boolean isSystemParameterEmpty(String systemParameterValue) { - return (null == systemParameterValue || "".equals(systemParameterValue) || "null".equals(systemParameterValue)); + private static boolean isSystemParameterEmpty(String paramValueFromSystem) { + return StringUtils.isEmpty(paramValueFromSystem) || "null".equals(paramValueFromSystem); } -} + @Override + public String toString() { + return getKey() + "=" + getValue(); + } +} \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/enums/ColorsEnum.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/enums/ColorsEnum.java index d242f2e7..1ae5403e 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/enums/ColorsEnum.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/enums/ColorsEnum.java @@ -20,13 +20,13 @@ public enum ColorsEnum { DARK_GREEN_BACKGROUND(33, 93, 49, 1), YELLOW_COLUMN(255, 255, 0, 1); - private String value; - private int r; - private int g; - private int b; - private int alpha; + private final String value; + private final int r; + private final int g; + private final int b; + private final int alpha; - private ColorsEnum(int r, int g, int b, int alpha) { + ColorsEnum(int r, int g, int b, int alpha) { this.r = r; this.g = g; this.b = b; @@ -48,6 +48,7 @@ public String toString() { /** * @param css + * css * @return {@code ColorsEnum} constant for given CSS value */ public static ColorsEnum forCss(String css) { @@ -62,7 +63,6 @@ public static ColorsEnum forCss(String css) { /** * @return Red value in color - * @author */ public int getR() { return r; @@ -70,7 +70,6 @@ public int getR() { /** * @return Green value in color - * @author */ public int getG() { return g; @@ -78,7 +77,6 @@ public int getG() { /** * @return Blue value in color - * @author */ public int getB() { return b; @@ -86,7 +84,6 @@ public int getB() { /** * @return Alpha value in color - * @author */ public int getAlpha() { return alpha; @@ -94,7 +91,6 @@ public int getAlpha() { /** * @return {@link Color} for specified RGB values - * @author */ public Color getColor() { return new Color(r, g, b, alpha); diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/enums/EdgesEnum.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/enums/EdgesEnum.java index 131832a8..ef2ec87f 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/enums/EdgesEnum.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/enums/EdgesEnum.java @@ -2,11 +2,14 @@ public enum EdgesEnum { - TOP("top"), BOTTOM("bottom"), LEFT("left"), RIGHT("right"); + TOP("top"), + BOTTOM("bottom"), + LEFT("left"), + RIGHT("right"); - private String value; + private final String value; - private EdgesEnum(String value) { + EdgesEnum(String value) { this.value = value; } diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/enums/IResolutionList.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/enums/IResolutionList.java index 5a342216..1afd5f34 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/enums/IResolutionList.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/enums/IResolutionList.java @@ -2,9 +2,9 @@ public interface IResolutionList { - public int getWidth(); + int getWidth(); - public int getHeight(); + int getHeight(); - public String toString(); + String toString(); } diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/enums/SubUrl.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/enums/ISubUrl.java similarity index 73% rename from mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/enums/SubUrl.java rename to mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/enums/ISubUrl.java index b14291fa..c65468e4 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/enums/SubUrl.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/enums/ISubUrl.java @@ -1,5 +1,5 @@ package com.capgemini.mrchecker.selenium.core.enums; -public interface SubUrl { +public interface ISubUrl { String subURL(); } diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/enums/PageSubURLsEnum.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/enums/PageSubURLsEnum.java index cf42d6b6..697dca1c 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/enums/PageSubURLsEnum.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/enums/PageSubURLsEnum.java @@ -2,22 +2,22 @@ import com.capgemini.mrchecker.selenium.core.base.environment.GetEnvironmentParam; -public enum PageSubURLsEnum implements SubUrl { +public enum PageSubURLsEnum implements ISubUrl { - WWW_FONT_URL { + WWW_FONT_URL("") { @Override public String subURL() { return GetEnvironmentParam.WWW_FONT_URL.getValue(); } }, - TOOLS_QA { + TOOLS_QA("") { @Override public String subURL() { return GetEnvironmentParam.TOOLS_QA.getValue(); } }, - WEB_SERVICE { + WEB_SERVICE("") { @Override public String subURL() { return GetEnvironmentParam.WEB_SERVICE.getValue(); @@ -37,14 +37,10 @@ public String subURL() { /* * Sub urls are used as real locations in Bank test environment */ - private String subURL; + private final String subURL; - private PageSubURLsEnum(String subURL) { + PageSubURLsEnum(String subURL) { this.subURL = subURL; - }; - - private PageSubURLsEnum() { - } @Override diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/enums/RelatedPositionEnum.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/enums/RelatedPositionEnum.java index 86fec931..d0317290 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/enums/RelatedPositionEnum.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/enums/RelatedPositionEnum.java @@ -1,5 +1,5 @@ package com.capgemini.mrchecker.selenium.core.enums; public enum RelatedPositionEnum { - ABOVE, BELOW, BEFORE, AFTER, INLINE; + ABOVE, BELOW, BEFORE, AFTER, INLINE } diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/enums/ResolutionEnum.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/enums/ResolutionEnum.java index fe3c32b7..25ea50e9 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/enums/ResolutionEnum.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/enums/ResolutionEnum.java @@ -17,14 +17,12 @@ public enum ResolutionEnum implements IResolutionList { iPhoneX(375, 812), SamsungS9(360, 740), Nexus9(1024, 768), - AndroidOne(320, 569), + AndroidOne(320, 569); - ; + private final int width; + private final int height; - private int width; - private int height; - - private ResolutionEnum(int width, int height) { + ResolutionEnum(int width, int height) { this.width = width; this.height = height; } @@ -39,6 +37,5 @@ public int getHeight() { public String toString() { return "Widht:" + getWidth() + " Height:" + getHeight(); - } } diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/exceptions/BFComponentStateException.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/exceptions/BFComponentStateException.java index 8267d933..4491a9cc 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/exceptions/BFComponentStateException.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/exceptions/BFComponentStateException.java @@ -4,8 +4,8 @@ public class BFComponentStateException extends AssertionError { - private static final long serialVersionUID = 2453124693849726543L; - private static String exceptionMessage; + private static final long serialVersionUID = 2453124693849726543L; + private static String exceptionMessage; /** * This exception should be thrown when component state is not as expected, which prevents performing certain @@ -14,8 +14,11 @@ public class BFComponentStateException extends AssertionError { * [Button]. Component is [disabled]." * * @param componentName + * component name * @param action + * action * @param actualState + * actual state */ public BFComponentStateException(String componentName, String action, String actualState) { super(generateExceptionMessage(componentName, action, actualState)); diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/exceptions/BFElementNotFoundException.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/exceptions/BFElementNotFoundException.java index c85131e2..decc4631 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/exceptions/BFElementNotFoundException.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/exceptions/BFElementNotFoundException.java @@ -1,13 +1,14 @@ package com.capgemini.mrchecker.selenium.core.exceptions; -import org.openqa.selenium.*; +import org.openqa.selenium.By; +import org.openqa.selenium.NoSuchElementException; import com.capgemini.mrchecker.test.core.logger.BFLogger; public class BFElementNotFoundException extends NoSuchElementException { - private static final long serialVersionUID = 6697212034783474583L; - private static String messageText; + private static final long serialVersionUID = 6697212034783474583L; + private static String messageText; /** * {@code BFElementNotFoundException} is the class that can be thrown during any type of {@code findElement} and/or @@ -16,7 +17,6 @@ public class BFElementNotFoundException extends NoSuchElementException { * {@code BFElementNotFoundException} and its subclasses are unchecked exceptions. Given exception will be * throw when element is not found directly or by timeout * - * @author * @param by * - {@link org.openqa.selenium.By} */ @@ -31,11 +31,10 @@ public BFElementNotFoundException(By by) { * {@code BFElementNotFoundException} and its subclasses are unchecked exceptions. Given exception will be * throw when element is not found directly or by timeout * - * @author * @param by * - {@link org.openqa.selenium.By} * @param message - * - any addition text in {@link #message} will be added at the beginning of log + * - any addition text in message will be added at the beginning of log */ public BFElementNotFoundException(By by, String message) { this(by, message, false, -1); @@ -48,7 +47,6 @@ public BFElementNotFoundException(By by, String message) { * {@code BFElementNotFoundException} and its subclasses are unchecked exceptions. Given exception will be * throw when element is not found directly or by timeout * - * @author * @param by * - {@link org.openqa.selenium.By} * @param isTimeout @@ -65,12 +63,11 @@ public BFElementNotFoundException(By by, boolean isTimeout) { *

    * {@code BFElementNotFoundException} and its subclasses are unchecked exceptions. Given exception will be * throw when element is not found directly or by timeout - * - * @author + * * @param by * - {@link org.openqa.selenium.By} * @param message - * - any addition text in {@link #message} will be added at the beginning of log + * - any addition text in message will be added at the beginning of log * @param isTimeout * - use this when log must have information that element was not found by timeout */ @@ -85,13 +82,12 @@ public BFElementNotFoundException(By by, String message, boolean isTimeout) { * {@code BFElementNotFoundException} and its subclasses are unchecked exceptions. Given exception will be * throw when element is not found directly or by timeout * - * @author * @param by * - {@link org.openqa.selenium.By} * @param isTimeout * - use this when log must have information that element was not found by timeout * @param timeoutValue - * - used with {@link #isTimeout}. Give timeout in sec will be added in logs + * - used with isTimeout. Give timeout in sec will be added in logs */ public BFElementNotFoundException(By by, boolean isTimeout, int timeoutValue) { this(by, "", isTimeout, timeoutValue); @@ -104,15 +100,14 @@ public BFElementNotFoundException(By by, boolean isTimeout, int timeoutValue) { * {@code BFElementNotFoundException} and its subclasses are unchecked exceptions. Given exception will be * throw when element is not found directly or by timeout * - * @author * @param by * - {@link org.openqa.selenium.By} * @param message - * - any addition text in {@link #message} will be added at the beginning of log + * - any addition text in message will be added at the beginning of log * @param isTimeout * - use this when log must have information that element was not found by timeout * @param timeoutValue - * - used with {@link #isTimeout}. Give timeout in sec will be added in logs + * - used with isTimeout. Give timeout in sec will be added in logs */ public BFElementNotFoundException(By by, String message, boolean isTimeout, int timeoutValue) { super(generateMessage(by, message, isTimeout, timeoutValue)); diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/exceptions/BFRobotInitilizationException.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/exceptions/BFRobotInitilizationException.java index efd63eba..85d9fb87 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/exceptions/BFRobotInitilizationException.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/exceptions/BFRobotInitilizationException.java @@ -1,12 +1,11 @@ package com.capgemini.mrchecker.selenium.core.exceptions; import java.awt.AWTException; +import java.util.Arrays; public class BFRobotInitilizationException extends RuntimeException { public BFRobotInitilizationException(AWTException e) { - System.err.println("Unable to execute Robot action. \n" + e.getStackTrace() - .toString()); - + System.err.println("Unable to execute Robot action. \n" + Arrays.toString(e.getStackTrace())); } } diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/exceptions/BFSeleniumGridNotConnectedException.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/exceptions/BFSeleniumGridNotConnectedException.java index 328e7a45..9efe6a30 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/exceptions/BFSeleniumGridNotConnectedException.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/exceptions/BFSeleniumGridNotConnectedException.java @@ -6,13 +6,14 @@ public class BFSeleniumGridNotConnectedException extends AssertionError { - private static final long serialVersionUID = -1217616251968376336L; - private static String exceptionMessage; + private static final long serialVersionUID = -1217616251968376336L; + private static String exceptionMessage; /** * This exception should be thrown when connection to Selenium Grid is not possible * * @param e + * e */ public BFSeleniumGridNotConnectedException(WebDriverException e) { super(generateExceptionMessage()); diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/exceptions/BFWaittingForBrowserWindowsException.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/exceptions/BFWaittingForBrowserWindowsException.java index b99fdb95..6bd58420 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/exceptions/BFWaittingForBrowserWindowsException.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/exceptions/BFWaittingForBrowserWindowsException.java @@ -4,8 +4,6 @@ /** * Time out exection for multi windows in browser to open - * - * @author */ public class BFWaittingForBrowserWindowsException extends RuntimeException { diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/DriverExtention.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/DriverExtension.java similarity index 73% rename from mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/DriverExtention.java rename to mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/DriverExtension.java index 7e59a5af..986f9866 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/DriverExtention.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/DriverExtension.java @@ -3,8 +3,8 @@ import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; +import java.util.Objects; import java.util.concurrent.TimeUnit; -import java.util.function.Function; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; @@ -25,9 +25,9 @@ import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.DropdownListElement; import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.HorizontalSliderElement; import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.IFrame; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.ImageElement; import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.InputTextElement; import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.LabelElement; -import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.ImageElement; import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.ListElements; import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.MenuElement; import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.NavigationBarElement; @@ -36,12 +36,12 @@ import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.TooltipElement; import com.capgemini.mrchecker.test.core.logger.BFLogger; -public class DriverExtention { +public class DriverExtension { private INewWebDriver driver; - public DriverExtention(INewWebDriver driver) { - this.setDriver(driver); + public DriverExtension(INewWebDriver driver) { + setDriver(driver); } public INewWebDriver getDriver() { @@ -49,21 +49,17 @@ public INewWebDriver getDriver() { } public WebElement findElementQuietly(By by) { - return this.findElementQuietly(null, by); + return findElementQuietly(null, by); } @SuppressWarnings("deprecation") public WebElement findElementQuietly(WebElement elementToSearchIn, By by) { BasePage.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); + .sendMethodEvent(BasePage.ANALYTICS_CATEGORY_NAME); WebElement element = null; try { - if (null == elementToSearchIn) { - element = getDriver().findElement(by); - } else { - element = new NewRemoteWebElement(elementToSearchIn).findElement(by); - } + element = Objects.isNull(elementToSearchIn) ? getDriver().findElement(by) : new NewRemoteWebElement(elementToSearchIn).findElement(by); } catch (NoSuchElementException e) { BFLogger.logError("Element [" + by.toString() + "] was not found in given element"); } @@ -82,27 +78,21 @@ public WebElement findElementDynamic(final By by, int timeOut) throws BFElementN public WebElement findElementDynamic(WebElement elementToSearchIn, By by) throws BFElementNotFoundException { BasePage.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); + .sendMethodEvent(BasePage.ANALYTICS_CATEGORY_NAME); long startTime = System.currentTimeMillis(); - WebElement element; - if (null == elementToSearchIn) { - element = this.findElementDynamic(by); - } else { - element = findElementDynamicBasic(by, startTime); - } - return element; + return Objects.isNull(elementToSearchIn) ? findElementDynamic(by) : findElementDynamicBasic(by, startTime); } private WebElement findElementDynamicBasic(By by, long startTime) throws BFElementNotFoundException { - int timeOut = BasePage.EXPLICITYWAITTIMER; + int timeOut = BasePage.EXPLICIT_WAIT_TIMER; return this.findElementDynamicBasic(by, startTime, timeOut); } private WebElement findElementDynamicBasic(By by, long startTime, int timeOut) throws BFElementNotFoundException { - WebElement element = null; + WebElement element; WebDriverWait wait = webDriverWait(timeOut); try { - element = wait.until((Function) ExpectedConditions.presenceOfElementLocated(by)); + element = wait.until(ExpectedConditions.presenceOfElementLocated(by)); } catch (TimeoutException | NoSuchElementException e) { boolean isTimeout = true; throw new BFElementNotFoundException(by, isTimeout, timeOut); @@ -113,12 +103,12 @@ private WebElement findElementDynamicBasic(By by, long startTime, int timeOut) t public List findElementsDynamic(By by, int timeOut) throws BFElementNotFoundException { BasePage.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); + .sendMethodEvent(BasePage.ANALYTICS_CATEGORY_NAME); long startTime = System.currentTimeMillis(); WebDriverWait wait = webDriverWait(timeOut); - List elements = new ArrayList(); + List elements; try { - elements = wait.until((Function>) ExpectedConditions.presenceOfAllElementsLocatedBy(by)); + elements = wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(by)); } catch (BFElementNotFoundException | TimeoutException e) { throw new BFElementNotFoundException(by, true, timeOut); } @@ -130,28 +120,23 @@ public List findElementsDynamic(By by, int timeOut) throws BFElement } public List findElementsDynamic(By by) throws BFElementNotFoundException { - return findElementsDynamic(by, BasePage.EXPLICITYWAITTIMER); + return findElementsDynamic(by, BasePage.EXPLICIT_WAIT_TIMER); } public WebElement waitForElement(final By by) throws BFElementNotFoundException { BasePage.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); + .sendMethodEvent(BasePage.ANALYTICS_CATEGORY_NAME); long startTime = System.currentTimeMillis(); - WebElement element = null; + WebElement element; - FluentWait wait = new FluentWait(driver); + FluentWait wait = new FluentWait<>(driver); wait.pollingEvery(250, TimeUnit.MILLISECONDS); wait.withTimeout(2, TimeUnit.MINUTES); try { - element = webDriverWait().until(new Function() { - @Override - public WebElement apply(WebDriver driver) { - return driver.findElement(by); - } - }); + element = webDriverWait().until(driver -> driver.findElement(by)); } catch (TimeoutException | NoSuchElementException e) { boolean isTimeout = true; - throw new BFElementNotFoundException(by, isTimeout, BasePage.EXPLICITYWAITTIMER); + throw new BFElementNotFoundException(by, isTimeout, BasePage.EXPLICIT_WAIT_TIMER); } BFLogger.logTime(startTime, "waitForElement()", by.toString()); return element; @@ -159,14 +144,14 @@ public WebElement apply(WebDriver driver) { public WebElement waitUntilElementIsClickable(final By by) { BasePage.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); + .sendMethodEvent(BasePage.ANALYTICS_CATEGORY_NAME); long startTime = System.currentTimeMillis(); - WebElement element = null; + WebElement element; try { - element = webDriverWait().until((Function) ExpectedConditions.elementToBeClickable(by)); + element = webDriverWait().until(ExpectedConditions.elementToBeClickable(by)); } catch (TimeoutException | NoSuchElementException e) { boolean isTimeout = true; - throw new BFElementNotFoundException(by, isTimeout, BasePage.EXPLICITYWAITTIMER); + throw new BFElementNotFoundException(by, isTimeout, BasePage.EXPLICIT_WAIT_TIMER); } BFLogger.logTime(startTime, "waitUntilElementIsClickable()", by.toString()); return element; @@ -174,15 +159,15 @@ public WebElement waitUntilElementIsClickable(final By by) { public WebElement waitForElementVisible(final By by) throws BFElementNotFoundException { BasePage.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); + .sendMethodEvent(BasePage.ANALYTICS_CATEGORY_NAME); long startTime = System.currentTimeMillis(); - WebElement element = null; + WebElement element; try { - element = webDriverWait().until((Function) ExpectedConditions.visibilityOfElementLocated(by)); + element = webDriverWait().until(ExpectedConditions.visibilityOfElementLocated(by)); } catch (TimeoutException | NoSuchElementException e) { boolean isTimeout = true; - throw new BFElementNotFoundException(by, isTimeout, BasePage.EXPLICITYWAITTIMER); + throw new BFElementNotFoundException(by, isTimeout, BasePage.EXPLICIT_WAIT_TIMER); } BFLogger.logTime(startTime, "waitForElementVisible()", by.toString()); return element; @@ -191,16 +176,12 @@ public WebElement waitForElementVisible(final By by) throws BFElementNotFoundExc public void waitForPageLoaded() throws BFElementNotFoundException { long startTime = System.currentTimeMillis(); final String jsVariable = "return document.readyState"; - ExpectedCondition expectation = new ExpectedCondition() { - public Boolean apply(WebDriver driver) { - return ((JavascriptExecutor) driver).executeScript(jsVariable) - .equals("complete"); - } - }; - int progressBarWaitTimer = BasePage.PROGRESSBARWAITTIMER; + ExpectedCondition expectation = driver -> ((JavascriptExecutor) driver).executeScript(jsVariable) + .equals("complete"); + int progressBarWaitTimer = BasePage.PROGRESS_BAR_WAIT_TIMER; WebDriverWait wait = webDriverWait(progressBarWaitTimer); try { - wait.until((Function) expectation); + wait.until(expectation); } catch (TimeoutException | NoSuchElementException e) { boolean isTimeout = true; throw new BFElementNotFoundException(By.cssSelector(jsVariable), isTimeout, progressBarWaitTimer); @@ -213,7 +194,7 @@ private void setDriver(INewWebDriver driver) { } private WebDriverWait webDriverWait() { - return webDriverWait(BasePage.EXPLICITYWAITTIMER); + return webDriverWait(BasePage.EXPLICIT_WAIT_TIMER); } private WebDriverWait webDriverWait(int timeOut) { @@ -221,7 +202,7 @@ private WebDriverWait webDriverWait(int timeOut) { } static List convertWebElementList(List elementList) { - List elementsList = new ArrayList(); + List elementsList = new ArrayList<>(); for (WebElement element : elementList) { elementsList.add(new NewRemoteWebElement(element)); } @@ -230,156 +211,156 @@ static List convertWebElementList(List elementList) { public Button elementButton(By selector) { BasePage.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); + .sendMethodEvent(BasePage.ANALYTICS_CATEGORY_NAME); return new Button(selector); } public RadioButtonElement elementRadioButton(By selector) { BasePage.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); + .sendMethodEvent(BasePage.ANALYTICS_CATEGORY_NAME); return new RadioButtonElement(selector); } public RadioButtonElement elementRadioButton(By selector, By childs) { BasePage.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); + .sendMethodEvent(BasePage.ANALYTICS_CATEGORY_NAME); return new RadioButtonElement(selector, childs); } public RadioButtonElement elementRadioButton(By selector, By childs, List selectedAttributes) { BasePage.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); + .sendMethodEvent(BasePage.ANALYTICS_CATEGORY_NAME); return new RadioButtonElement(selector, childs, selectedAttributes); } public InputTextElement elementInputText(By selector) { BasePage.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); + .sendMethodEvent(BasePage.ANALYTICS_CATEGORY_NAME); return new InputTextElement(selector); } public DropdownListElement elementDropdownList(By selector) { BasePage.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); + .sendMethodEvent(BasePage.ANALYTICS_CATEGORY_NAME); return new DropdownListElement(selector); } public ListElements elementList(By selector) { BasePage.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); + .sendMethodEvent(BasePage.ANALYTICS_CATEGORY_NAME); return new ListElements(selector); } public CheckBox elementCheckbox(By selector) { BasePage.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); + .sendMethodEvent(BasePage.ANALYTICS_CATEGORY_NAME); return new CheckBox(selector); } public CheckBox elementCheckbox(By selector, By childs) { BasePage.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); + .sendMethodEvent(BasePage.ANALYTICS_CATEGORY_NAME); return new CheckBox(selector, childs); } public LabelElement elementLabel(By selector) { BasePage.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); + .sendMethodEvent(BasePage.ANALYTICS_CATEGORY_NAME); return new LabelElement(selector); } public TabElement elementTab(By selector) { BasePage.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); + .sendMethodEvent(BasePage.ANALYTICS_CATEGORY_NAME); return new TabElement(selector); } public TabElement elementTab(By selector, By childs) { BasePage.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); + .sendMethodEvent(BasePage.ANALYTICS_CATEGORY_NAME); return new TabElement(selector, childs); } public TabElement elementTab(By selector, By childs, List selectedAttributes) { BasePage.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); + .sendMethodEvent(BasePage.ANALYTICS_CATEGORY_NAME); return new TabElement(selector, childs, selectedAttributes); } public NavigationBarElement elementNavigationBar(By selector) { BasePage.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); + .sendMethodEvent(BasePage.ANALYTICS_CATEGORY_NAME); return new NavigationBarElement(selector); } public NavigationBarElement elementNavigationBar(By selector, By inputChildsSelector) { BasePage.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); + .sendMethodEvent(BasePage.ANALYTICS_CATEGORY_NAME); return new NavigationBarElement(selector, inputChildsSelector); } public TooltipElement elementTooltip(By selector) { BasePage.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); + .sendMethodEvent(BasePage.ANALYTICS_CATEGORY_NAME); return new TooltipElement(selector); } public MenuElement elementMenu(By selector) { BasePage.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); + .sendMethodEvent(BasePage.ANALYTICS_CATEGORY_NAME); return new MenuElement(selector); } public MenuElement elementMenu(By selector, By childsSelector) { BasePage.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); + .sendMethodEvent(BasePage.ANALYTICS_CATEGORY_NAME); return new MenuElement(selector, childsSelector); } public MenuElement elementMenu(By selector, By childsSelector, By subMenuSelector) { BasePage.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); + .sendMethodEvent(BasePage.ANALYTICS_CATEGORY_NAME); return new MenuElement(selector, childsSelector, subMenuSelector); } public MenuElement elementMenu(By selector, By childsSelector, By subMenuSelector, By childsSubMenuSelector) { BasePage.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); + .sendMethodEvent(BasePage.ANALYTICS_CATEGORY_NAME); return new MenuElement(selector, childsSelector, subMenuSelector, childsSubMenuSelector); } public HorizontalSliderElement elementHorizontalSlider(final By sliderContainerSelector) { BasePage.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); + .sendMethodEvent(BasePage.ANALYTICS_CATEGORY_NAME); return new HorizontalSliderElement(sliderContainerSelector); } public HorizontalSliderElement elementHorizontalSlider(final By sliderContainerSelector, final By sliderSelector, final By valueSelector) { BasePage.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); + .sendMethodEvent(BasePage.ANALYTICS_CATEGORY_NAME); return new HorizontalSliderElement(sliderContainerSelector, sliderSelector, valueSelector); } public HorizontalSliderElement elementHorizontalSlider(final By sliderContainerSelector, - final By sliderSelector, - final By valueSelector, - final BigDecimal minRange, - final BigDecimal maxRange, - final BigDecimal step) { + final By sliderSelector, + final By valueSelector, + final BigDecimal minRange, + final BigDecimal maxRange, + final BigDecimal step) { BasePage.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); + .sendMethodEvent(BasePage.ANALYTICS_CATEGORY_NAME); return new HorizontalSliderElement(sliderContainerSelector, sliderSelector, valueSelector, minRange, maxRange, step); } public IFrame elementIFrame(By selector) { BasePage.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); + .sendMethodEvent(BasePage.ANALYTICS_CATEGORY_NAME); return new IFrame(selector); } - + public ImageElement elementImage(By selector) { BasePage.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); + .sendMethodEvent(BasePage.ANALYTICS_CATEGORY_NAME); return new ImageElement(selector); } @@ -387,7 +368,7 @@ public void mouseRightClick(By selector) { WebElement element = findElementDynamic(selector); Actions action = new Actions(getDriver()).contextClick(element); action.build() - .perform(); + .perform(); } public void mouseLeftClick(By selector) { @@ -401,8 +382,8 @@ public void mouseLeftClick(By selector) { public void mouseLeftClick(WebElement element) { new Actions(getDriver()).click(element) - .build() - .perform(); + .build() + .perform(); } } diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/DriverManager.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/DriverManager.java index addc5198..3b34cf7e 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/DriverManager.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/DriverManager.java @@ -1,16 +1,11 @@ package com.capgemini.mrchecker.selenium.core.newDrivers; -import com.capgemini.mrchecker.selenium.core.base.properties.PropertiesSelenium; -import com.capgemini.mrchecker.selenium.core.base.runtime.RuntimeParametersSelenium; -import com.capgemini.mrchecker.selenium.core.enums.ResolutionEnum; -import com.capgemini.mrchecker.selenium.core.exceptions.BFSeleniumGridNotConnectedException; -import com.capgemini.mrchecker.selenium.core.utils.OperationsOnFiles; -import com.capgemini.mrchecker.selenium.core.utils.ResolutionUtils; -import com.capgemini.mrchecker.test.core.logger.BFLogger; -import com.google.inject.Inject; -import com.google.inject.name.Named; -import io.github.bonigarcia.wdm.WebDriverManager; -import io.github.bonigarcia.wdm.WebDriverManagerException; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.HashMap; +import java.util.Objects; +import java.util.concurrent.TimeUnit; + import org.openqa.selenium.Platform; import org.openqa.selenium.WebDriverException; import org.openqa.selenium.chrome.ChromeDriver; @@ -26,73 +21,85 @@ import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; - -public class DriverManager { +import com.capgemini.mrchecker.selenium.core.base.properties.PropertiesSelenium; +import com.capgemini.mrchecker.selenium.core.base.runtime.RuntimeParametersSelenium; +import com.capgemini.mrchecker.selenium.core.enums.ResolutionEnum; +import com.capgemini.mrchecker.selenium.core.exceptions.BFSeleniumGridNotConnectedException; +import com.capgemini.mrchecker.selenium.core.utils.OperationsOnFiles; +import com.capgemini.mrchecker.selenium.core.utils.ResolutionUtils; +import com.capgemini.mrchecker.test.core.logger.BFLogger; +import com.google.inject.Inject; +import com.google.inject.name.Named; - private static ThreadLocal drivers = new ThreadLocal(); +import io.github.bonigarcia.wdm.WebDriverManager; +import io.github.bonigarcia.wdm.WebDriverManagerException; +public class DriverManager { + + private static final ThreadLocal drivers = new ThreadLocal<>(); + // Setup default variables - private static final ResolutionEnum DEFAULT_RESOLUTION = ResolutionEnum.w1200; - private static final int IMPLICITYWAITTIMER = 2; // in seconds - private static final String DOWNLOAD_DIR = System.getProperty("java.io.tmpdir"); - private static boolean driverDownloadedChrome = false; - private static boolean driverDownloadedGecko = false; - private static boolean driverDownloadedIE = false; - private static boolean driverDownloadedEdge = false; - private static boolean driverDownloadedOpera = false; - private static PropertiesSelenium propertiesSelenium; - + private static final ResolutionEnum DEFAULT_RESOLUTION = ResolutionEnum.w1200; + private static final int IMPLICITYWAITTIMER = 2; // in seconds + private static final String DOWNLOAD_DIR = System.getProperty("java.io.tmpdir"); + private static boolean driverDownloadedChrome = false; + private static boolean driverDownloadedGecko = false; + private static boolean driverDownloadedIE = false; + private static boolean driverDownloadedEdge = false; + private static boolean driverDownloadedOpera = false; + private static PropertiesSelenium propertiesSelenium; + @Inject public DriverManager(@Named("properties") PropertiesSelenium propertiesSelenium) { - - if (null == DriverManager.propertiesSelenium) { + + if (Objects.isNull(DriverManager.propertiesSelenium)) { DriverManager.propertiesSelenium = propertiesSelenium; } - + this.start(); } - + public void start() { DriverManager.getDriver(); } - + public void stop() { try { closeDriver(); BFLogger.logDebug("Closing Driver in stop()"); BFLogger.logInfo(String.format("All clicks took %.2fs", 1.0 * NewRemoteWebElement.dropClickTimer() / 1000)); } catch (Exception e) { + // TODO: handle that } } - + @Override + // TODO: handle that finalize should never been called - it's unreliable. Intoduce Autoclose() protected void finalize() throws Throwable { super.finalize(); try { closeDriver(); BFLogger.logDebug("Closing Driver in finalize()"); } catch (Exception e) { + // TODO: handle that } - + } - + public static INewWebDriver getDriver() { INewWebDriver driver = drivers.get(); - if (driver == null) { + if (Objects.isNull(driver)) { driver = createDriver(); drivers.set(driver); - BFLogger.logDebug("driver:" + driver.toString()); + BFLogger.logDebug("Driver:" + driver); } + return driver; } - + public static void closeDriver() { INewWebDriver driver = drivers.get(); - if (driver == null) { + if (Objects.isNull(driver)) { BFLogger.logDebug("closeDriver() was called but there was no driver for this thread."); } else { try { @@ -102,12 +109,11 @@ public static void closeDriver() { BFLogger.logDebug("Ooops! Something went wrong while closing the driver: "); e.printStackTrace(); } finally { - driver = null; drivers.remove(); } } } - + /** * Method sets desired 'driver' depends on chosen parameters */ @@ -115,25 +121,23 @@ private static INewWebDriver createDriver() { BFLogger.logDebug("Creating new " + RuntimeParametersSelenium.BROWSER.toString() + " WebDriver."); INewWebDriver driver; String seleniumGridParameter = RuntimeParametersSelenium.SELENIUM_GRID.getValue(); - if (isEmpty(seleniumGridParameter)) { - driver = setupBrowser(); - } else { - driver = setupGrid(); - } + + driver = isEmpty(seleniumGridParameter) ? setupBrowser() : setupGrid(); + driver.manage() .timeouts() .implicitlyWait(DriverManager.IMPLICITYWAITTIMER, TimeUnit.SECONDS); - + ResolutionUtils.setResolution(driver, DriverManager.DEFAULT_RESOLUTION); NewRemoteWebElement.setClickTimer(); return driver; } - + private static boolean isEmpty(String seleniumGridParameter) { return seleniumGridParameter == null || seleniumGridParameter.trim() .isEmpty(); } - + /** * Method sets Selenium Grid */ @@ -144,7 +148,7 @@ private static INewWebDriver setupGrid() { throw new BFSeleniumGridNotConnectedException(e); } } - + /** * Method sets desired 'driver' depends on chosen parameters */ @@ -167,9 +171,9 @@ private static INewWebDriver setupBrowser() { throw new RuntimeException("Unable to setup [" + browser + "] browser. Browser not recognized."); } } - + private enum Driver { - + CHROME { @Override public INewWebDriver getDriver() { @@ -177,7 +181,8 @@ public INewWebDriver getDriver() { boolean isDriverAutoUpdateActivated = DriverManager.propertiesSelenium.getDriverAutoUpdateFlag(); synchronized (this) { if (isDriverAutoUpdateActivated && !driverDownloadedChrome) { - if (!DriverManager.propertiesSelenium.getChromeDriverVersion().equals("")) { + if (!DriverManager.propertiesSelenium.getChromeDriverVersion() + .equals("")) { System.setProperty("wdm.chromeDriverVersion", DriverManager.propertiesSelenium.getChromeDriverVersion()); } downloadNewestOrGivenVersionOfWebDriver(ChromeDriver.class); @@ -186,15 +191,15 @@ public INewWebDriver getDriver() { } driverDownloadedChrome = true; } - + System.setProperty("webdriver.chrome.driver", browserPath); - HashMap chromePrefs = new HashMap(); + HashMap chromePrefs = new HashMap<>(); chromePrefs.put("download.default_directory", DOWNLOAD_DIR); chromePrefs.put("profile.content_settings.pattern_pairs.*.multiple-automatic-downloads", 1); ChromeOptions options = new ChromeOptions(); options.setExperimentalOption("prefs", chromePrefs); options.addArguments("--test-type"); - + // Set users browser options RuntimeParametersSelenium.BROWSER_OPTIONS.getValues() .forEach((key, value) -> { @@ -203,30 +208,30 @@ public INewWebDriver getDriver() { .isEmpty()) ? key : key + "=" + value; options.addArguments(item); }); - + // DesiredCapabilities cap = DesiredCapabilities.chrome(); // cap.setCapability(ChromeOptions.CAPABILITY, options); - - INewWebDriver driver = new NewChromeDriver(options); - return driver; + + return new NewChromeDriver(options); } - + }, EDGE { @Override public INewWebDriver getDriver() { - //Microsoft WebDriver for Microsoft Edge from version 18 is a Windows Feature on Demand. - //To install run the following in an elevated command prompt: - //DISM.exe /Online /Add-Capability /CapabilityName:Microsoft.WebDriver~~~~0.0.1.0 - //For builds prior to 18, download the appropriate driver for your installed version of Microsoft Edge - //Info: https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/#downloads + // Microsoft WebDriver for Microsoft Edge from version 18 is a Windows Feature on Demand. + // To install run the following in an elevated command prompt: + // DISM.exe /Online /Add-Capability /CapabilityName:Microsoft.WebDriver~~~~0.0.1.0 + // For builds prior to 18, download the appropriate driver for your installed version of Microsoft Edge + // Info: https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/#downloads boolean featureOnDemand = DriverManager.propertiesSelenium.getEdgeDriverFeatureOnDemandFlag(); - if(!featureOnDemand) { + if (!featureOnDemand) { String browserPath = DriverManager.propertiesSelenium.getSeleniumEdge(); boolean isDriverAutoUpdateActivated = DriverManager.propertiesSelenium.getDriverAutoUpdateFlag(); synchronized (this) { if (isDriverAutoUpdateActivated && !driverDownloadedEdge) { - if (!DriverManager.propertiesSelenium.getEdgeDriverVersion().equals("")) { + if (!DriverManager.propertiesSelenium.getEdgeDriverVersion() + .equals("")) { System.setProperty("wdm.edgeVersion", DriverManager.propertiesSelenium.getEdgeDriverVersion()); } downloadNewestOrGivenVersionOfWebDriver(EdgeDriver.class); @@ -237,19 +242,19 @@ public INewWebDriver getDriver() { } System.setProperty("webdriver.edge.driver", browserPath); } - + EdgeOptions options = new EdgeOptions(); - + // Set users browser options RuntimeParametersSelenium.BROWSER_OPTIONS.getValues() .forEach((key, value) -> { BFLogger.logInfo("Browser option: " + key + " " + value); options.setCapability(key, value); }); - + return new NewEdgeDriver(options); } - + }, OPERA { @Override @@ -258,7 +263,8 @@ public INewWebDriver getDriver() { boolean isDriverAutoUpdateActivated = DriverManager.propertiesSelenium.getDriverAutoUpdateFlag(); synchronized (this) { if (isDriverAutoUpdateActivated && !driverDownloadedOpera) { - if (!DriverManager.propertiesSelenium.getOperaDriverVersion().equals("")) { + if (!DriverManager.propertiesSelenium.getOperaDriverVersion() + .equals("")) { System.setProperty("wdm.operaDriverVersion", DriverManager.propertiesSelenium.getOperaDriverVersion()); } downloadNewestOrGivenVersionOfWebDriver(OperaDriver.class); @@ -267,22 +273,22 @@ public INewWebDriver getDriver() { } driverDownloadedOpera = true; } - + System.setProperty("webdriver.opera.driver", browserPath); - HashMap operaPrefs = new HashMap(); + HashMap operaPrefs = new HashMap<>(); operaPrefs.put("download.default_directory", DOWNLOAD_DIR); operaPrefs.put("profile.content_settings.pattern_pairs.*.multiple-automatic-downloads", 1); OperaOptions options = new OperaOptions(); options.setExperimentalOption("prefs", operaPrefs); options.addArguments("--test-type"); - + // Set users browser options RuntimeParametersSelenium.BROWSER_OPTIONS.getValues() .forEach((key, value) -> { BFLogger.logInfo("Browser option: " + key + " " + value); options.setCapability(key, value); }); - + return new NewOperaDriver(options); } }, @@ -293,7 +299,8 @@ public INewWebDriver getDriver() { boolean isDriverAutoUpdateActivated = DriverManager.propertiesSelenium.getDriverAutoUpdateFlag(); synchronized (this) { if (isDriverAutoUpdateActivated && !driverDownloadedChrome) { - if (!DriverManager.propertiesSelenium.getChromeDriverVersion().equals("")) { + if (!DriverManager.propertiesSelenium.getChromeDriverVersion() + .equals("")) { System.setProperty("wdm.chromeDriverVersion", DriverManager.propertiesSelenium.getChromeDriverVersion()); } downloadNewestOrGivenVersionOfWebDriver(ChromeDriver.class); @@ -303,14 +310,14 @@ public INewWebDriver getDriver() { driverDownloadedChrome = true; } System.setProperty("webdriver.chrome.driver", browserPath); - HashMap chromePrefs = new HashMap(); + HashMap chromePrefs = new HashMap<>(); chromePrefs.put("download.default_directory", DOWNLOAD_DIR); chromePrefs.put("profile.content_settings.pattern_pairs.*.multiple-automatic-downloads", 1); ChromeOptions options = new ChromeOptions(); options.setExperimentalOption("prefs", chromePrefs); options.addArguments("headless"); options.addArguments("window-size=1200x600"); - + // Set users browser options RuntimeParametersSelenium.BROWSER_OPTIONS.getValues() .forEach((key, value) -> { @@ -319,14 +326,13 @@ public INewWebDriver getDriver() { .isEmpty()) ? key : key + "=" + value; options.addArguments(item); }); - + // DesiredCapabilities cap = DesiredCapabilities.chrome(); // cap.setCapability(ChromeOptions.CAPABILITY, options); - - INewWebDriver driver = new NewChromeDriver(options); - return driver; + + return new NewChromeDriver(options); } - + }, FIREFOX { @Override @@ -335,7 +341,8 @@ public INewWebDriver getDriver() { boolean isDriverAutoUpdateActivated = DriverManager.propertiesSelenium.getDriverAutoUpdateFlag(); synchronized (this) { if (isDriverAutoUpdateActivated && !driverDownloadedGecko) { - if (!DriverManager.propertiesSelenium.getGeckoDriverVersion().equals("")) { + if (!DriverManager.propertiesSelenium.getGeckoDriverVersion() + .equals("")) { System.setProperty("wdm.geckoDriverVersion", DriverManager.propertiesSelenium.getGeckoDriverVersion()); } downloadNewestOrGivenVersionOfWebDriver(FirefoxDriver.class); @@ -346,18 +353,18 @@ public INewWebDriver getDriver() { } System.setProperty("webdriver.gecko.driver", browserPath); System.setProperty("webdriver.firefox.logfile", "logs\\firefox_logs.txt"); - + FirefoxProfile profile = new FirefoxProfile(); profile.setPreference("webdriver.firefox.marionette", true); profile.setPreference("browser.download.folderList", 2); profile.setPreference("browser.download.dir", DOWNLOAD_DIR); profile.setPreference("browser.download.useDownloadDir", true); - + profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "text/comma-separated-values, application/vnd.ms-excel, application/msword, application/csv, application/ris, text/csv, image/png, application/pdf, text/html, text/plain, application/zip, application/x-zip, application/x-zip-compressed, application/download, application/octet-stream"); profile.setPreference("browser.download.manager.showWhenStarting", false); profile.setPreference("browser.helperApps.alwaysAsk.force", false); - + FirefoxOptions options = new FirefoxOptions().setProfile(profile); // Set users browser options RuntimeParametersSelenium.BROWSER_OPTIONS.getValues() @@ -365,7 +372,7 @@ public INewWebDriver getDriver() { BFLogger.logInfo("Browser option: " + key + " " + value); options.setCapability(key, value); }); - + return new NewFirefoxDriver(options); } }, @@ -376,7 +383,8 @@ public INewWebDriver getDriver() { boolean isDriverAutoUpdateActivated = DriverManager.propertiesSelenium.getDriverAutoUpdateFlag(); synchronized (this) { if (isDriverAutoUpdateActivated && !driverDownloadedIE) { - if (!DriverManager.propertiesSelenium.getInternetExplorerDriverVersion().equals("")) { + if (!DriverManager.propertiesSelenium.getInternetExplorerDriverVersion() + .equals("")) { System.setProperty("wdm.internetExplorerDriverVersion", DriverManager.propertiesSelenium.getInternetExplorerDriverVersion()); } downloadNewestOrGivenVersionOfWebDriver(InternetExplorerDriver.class); @@ -387,22 +395,26 @@ public INewWebDriver getDriver() { } System.setProperty("webdriver.ie.driver", browserPath); DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer(); - + // Set users browser options RuntimeParametersSelenium.BROWSER_OPTIONS.getValues() .forEach((key, value) -> { BFLogger.logInfo("Browser option: " + key + " " + value); ieCapabilities.setCapability(key, value); }); - + // Due to some issues with IE11 this line must be commented // ieCapabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, // true); return new NewInternetExplorerDriver(ieCapabilities); } - + }, SAFARI { + @Override + protected INewWebDriver getDriver() { + return null; + } }, SELENIUMGRID { @Override @@ -411,7 +423,7 @@ public INewWebDriver getDriver() { BFLogger.logDebug("Connecting to the selenium grid: " + SELENIUM_GRID_URL); DesiredCapabilities capabilities = new DesiredCapabilities(); String operatingSystem = RuntimeParametersSelenium.OS.getValue(); - + // TODO add others os's switch (operatingSystem) { case "windows": @@ -424,17 +436,17 @@ public INewWebDriver getDriver() { capabilities.setPlatform(Platform.MAC); break; } - + capabilities.setVersion(RuntimeParametersSelenium.BROWSER_VERSION.getValue()); capabilities.setBrowserName(RuntimeParametersSelenium.BROWSER.getValue()); - + // Set users browser options RuntimeParametersSelenium.BROWSER_OPTIONS.getValues() .forEach((key, value) -> { BFLogger.logInfo("Browser option: " + key + " " + value); capabilities.setCapability(key, value); }); - + NewRemoteWebDriver newRemoteWebDriver = null; try { newRemoteWebDriver = new NewRemoteWebDriver(new URL(SELENIUM_GRID_URL), capabilities); @@ -445,33 +457,30 @@ public INewWebDriver getDriver() { return newRemoteWebDriver; } }; - + private static void downloadNewestOrGivenVersionOfWebDriver(Class webDriverType) { - + String proxy = DriverManager.propertiesSelenium.getProxy(); String webDriversPath = DriverManager.propertiesSelenium.getWebDrivers(); try { System.setProperty("wdm.targetPath", webDriversPath); System.setProperty("wdm.useBetaVersions", "false"); - + WebDriverManager.getInstance(webDriverType) .proxy(proxy) .setup(); - BFLogger.logDebug("Downloaded version of driver=" + WebDriverManager.getInstance(webDriverType).getDownloadedVersion()); - + BFLogger.logDebug("Downloaded version of driver=" + WebDriverManager.getInstance(webDriverType) + .getDownloadedVersion()); + } catch (WebDriverManagerException e) { BFLogger.logInfo("Unable to download driver automatically. " + "Please try to set up the proxy in properties file. " + "If you want to download them manually, go to the " + "http://www.seleniumhq.org/projects/webdriver/ site."); } - - } - - public INewWebDriver getDriver() { - return null; + } - + + protected abstract INewWebDriver getDriver(); } - } diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/INewWebDriver.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/INewWebDriver.java index 9bbd4248..8983d83f 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/INewWebDriver.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/INewWebDriver.java @@ -15,9 +15,9 @@ import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.DropdownListElement; import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.HorizontalSliderElement; import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.IFrame; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.ImageElement; import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.InputTextElement; import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.LabelElement; -import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.ImageElement; import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.ListElements; import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.MenuElement; import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.NavigationBarElement; @@ -65,7 +65,9 @@ public interface INewWebDriver extends WebDriver { * e.g. PopUp * * @param elementToSearchIn + * elementToSearchIn * @param searchedBySelector + * searchedBySelector * @return found WebElement or null if couldn't find */ WebElement findElementQuietly(WebElement elementToSearchIn, By searchedBySelector); @@ -75,6 +77,7 @@ public interface INewWebDriver extends WebDriver { * e.g. PopUp * * @param searchedBySelector + * searchedBySelector * @return found WebElement or null if couldn't find */ WebElement findElementQuietly(By searchedBySelector); @@ -85,11 +88,11 @@ public interface INewWebDriver extends WebDriver { * * @param by * selector - * @param timeout + * @param timeOut * - maximum time to wait for search WebElement * @return found WebElement object - * @author * @throws BFElementNotFoundException + * BFElementNotFoundException BFElementNotFoundException */ WebElement findElementDynamic(By by, int timeOut) throws BFElementNotFoundException; @@ -100,8 +103,8 @@ public interface INewWebDriver extends WebDriver { * @param by * selector * @return found WebElement object - * @author * @throws BFElementNotFoundException + * BFElementNotFoundException BFElementNotFoundException */ WebElement findElementDynamic(By by) throws BFElementNotFoundException; @@ -111,47 +114,51 @@ public interface INewWebDriver extends WebDriver { * * @param by * selector - * @param timeout + * @param timeOut * - maximum time to wait for search WebElement * @return found WebElement object - * @author * @throws BFElementNotFoundException + * BFElementNotFoundException */ List findElementDynamics(By by, int timeOut); /** - * Try to find by dynamic List of elements - will wait {@link BasePage.EXPLICITYWAITTIMER} seconds for an element to + * Try to find by dynamic List of elements - will wait {@link BasePage#EXPLICIT_WAIT_TIMER} seconds for an element + * to * load on page. If element will not be found then throw an exception (PiAtElementNotLoadedException) * * @param by * selector * @return found WebElement object - * @author * @throws BFElementNotFoundException + * BFElementNotFoundException */ List findElementDynamics(By by); /** - * Waits {@link BasePage.EXPLICITYWAITTIMER} seconds until an element will be enabled to action. If element after + * Waits {@link {@link BasePage#EXPLICIT_WAIT_TIMER}} seconds until an element will be enabled to action. If element + * after * this time will not be enabled then throw an exception (BFElementNotFoundException) * - * @param by + * @param selector * selector * @return WebElement object ready to click - * @author * @throws BFElementNotFoundException + * BFElementNotFoundException */ WebElement waitForElement(final By selector); /** - * Waits {@link BasePage.EXPLICITYWAITTIMER} seconds until an element will be clickable. If element will not be + * Waits {@link {@link BasePage#EXPLICIT_WAIT_TIMER}} seconds until an element will be clickable. If element will + * not be * clickable then throw an exception (BFElementNotFoundException) * - * @param by + * @param selector * selector * @return WebElement object ready to click * @author * @throws BFElementNotFoundException + * BFElementNotFoundException */ WebElement waitUntilElementIsClickable(final By selector); @@ -159,19 +166,19 @@ public interface INewWebDriver extends WebDriver { * Waits for element located by selector to become visible. Throws exception if element is not visible after * specified time period. * - * @param by + * @param selector * selector * @return found WebElement object - * @author * @throws BFElementNotFoundException + * BFElementNotFoundException */ WebElement waitForElementVisible(final By selector); /** * This function force browser (especially usable for IE ) to wait till page is loaded - * - * @param driver + * * @throws BFElementNotFoundException + * BFElementNotFoundException */ void waitForPageLoaded(); @@ -181,15 +188,15 @@ public interface INewWebDriver extends WebDriver { Button elementButton(final By selector); /** - * Operations on Radion Buttons + * Operations on Radio Buttons */ RadioButtonElement elementRadioButton(final By selector); RadioButtonElement elementRadioButton(final By selector, final By inputChildsSelector); RadioButtonElement elementRadioButton(final By selector, - final By inputChildsSelector, - final List listSelectedAttributes); + final By inputChildsSelector, + final List listSelectedAttributes); /** * Operations on Input Text field @@ -215,7 +222,7 @@ RadioButtonElement elementRadioButton(final By selector, * Operations on Label */ LabelElement elementLabel(final By selector); - + /** * Operations on image */ @@ -252,18 +259,15 @@ RadioButtonElement elementRadioButton(final By selector, MenuElement elementMenu(final By selector, final By childsSelector, final By subMenuSelector); MenuElement elementMenu(final By selector, - final By childsSelector, - final By subMenuSelector, - final By childsSubMenuSelector); - - /** - * Operations on Horizontal Slider - */ + final By childsSelector, + final By subMenuSelector, + final By childsSubMenuSelector); /** * Returns horizontal slider object for given container selector. * * @param sliderContainerSelector + * sliderContainerSelector * @return HorizontalSliderElement * @see HorizontalSliderElement */ @@ -273,8 +277,11 @@ MenuElement elementMenu(final By selector, * Returns horizontal slider object for given container selector, slider selector and value selector. * * @param sliderContainerSelector + * sliderContainerSelector * @param sliderSelector + * sliderSelector * @param valueSelector + * valueSelector * @return HorizontalSliderElement * @see HorizontalSliderElement */ @@ -285,20 +292,26 @@ MenuElement elementMenu(final By selector, * Also a range of possible steps and step's size should be defined to perform operations/ * * @param sliderContainerSelector + * sliderContainerSelector * @param sliderSelector + * sliderSelector * @param valueSelector + * valueSelector * @param minRange + * minRange * @param maxRange + * maxRange * @param step + * step * @return HorizontalSliderElement * @see HorizontalSliderElement */ HorizontalSliderElement elementHorizontalSlider(final By sliderContainerSelector, - final By sliderSelector, - final By valueSelector, - final BigDecimal minRange, - final BigDecimal maxRange, - final BigDecimal step); + final By sliderSelector, + final By valueSelector, + final BigDecimal minRange, + final BigDecimal maxRange, + final BigDecimal step); /** * Operations on iFrame @@ -314,13 +327,14 @@ HorizontalSliderElement elementHorizontalSlider(final By sliderContainerSelector * Performs left mouse click on specific element * * @param selector + * selector */ void mouseLeftClick(final By selector); /** * Performs left mouse click on specific element * - * @param web + * @param element * element */ void mouseLeftClick(WebElement element); diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/NewChromeDriver.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/NewChromeDriver.java index 26070125..3356fa87 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/NewChromeDriver.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/NewChromeDriver.java @@ -18,9 +18,9 @@ import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.DropdownListElement; import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.HorizontalSliderElement; import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.IFrame; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.ImageElement; import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.InputTextElement; import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.LabelElement; -import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.ImageElement; import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.ListElements; import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.MenuElement; import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.NavigationBarElement; @@ -31,15 +31,16 @@ public final class NewChromeDriver extends ChromeDriver implements INewWebDriver { - private DriverExtention driverExtention; + private final DriverExtension driverExtension; + // TODO: class instance passed outside before it's been created public NewChromeDriver() { - driverExtention = new DriverExtention(this); + driverExtension = new DriverExtension(this); } public NewChromeDriver(ChromeOptions options) { super(options); - driverExtention = new DriverExtention(this); + driverExtension = new DriverExtension(this); } @Override @@ -54,8 +55,8 @@ protected ExecuteMethod getExecuteMethod() { @Override public List findElements(By by) { BaseTest.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); - return DriverExtention.convertWebElementList(super.findElements(by)); + .sendMethodEvent(BasePage.ANALYTICS_CATEGORY_NAME); + return DriverExtension.convertWebElementList(super.findElements(by)); } /** @@ -65,8 +66,8 @@ public List findElements(By by) { @Override public WebElement findElement(By by) throws BFElementNotFoundException { BaseTest.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); - WebElement elementFromDriver = null; + .sendMethodEvent(BasePage.ANALYTICS_CATEGORY_NAME); + WebElement elementFromDriver; try { elementFromDriver = super.findElement(by); } catch (NoSuchElementException e) { @@ -81,7 +82,7 @@ public WebElement findElement(By by) throws BFElementNotFoundException { * * @param by * selector - * @param timeout + * @param timeOut * - maximum time to wait for search WebElement * @return found WebElement object * @author @@ -89,7 +90,7 @@ public WebElement findElement(By by) throws BFElementNotFoundException { */ @Override public WebElement findElementDynamic(By by, int timeOut) throws BFElementNotFoundException { - return driverExtention.findElementDynamic(by, timeOut); + return driverExtension.findElementDynamic(by, timeOut); } /** @@ -104,7 +105,7 @@ public WebElement findElementDynamic(By by, int timeOut) throws BFElementNotFoun */ @Override public WebElement findElementDynamic(By by) throws BFElementNotFoundException { - return driverExtention.findElementDynamic(by); + return driverExtension.findElementDynamic(by); } /** @@ -120,11 +121,12 @@ public WebElement findElementDynamic(By by) throws BFElementNotFoundException { */ @Override public List findElementDynamics(By by, int timeOut) { - return driverExtention.findElementsDynamic(by, timeOut); + return driverExtension.findElementsDynamic(by, timeOut); } /** - * Try to find by dynamic List of elements - will wait {@link BasePage.EXPLICITYWAITTIMER} seconds for an element to + * Try to find by dynamic List of elements - will wait {@link BasePage#EXPLICIT_WAIT_TIMER} seconds for an element + * to * load on page. If element will not be found will throw an exception (PiAtElementNotLoadedException) * * @param by @@ -134,21 +136,21 @@ public List findElementDynamics(By by, int timeOut) { */ @Override public List findElementDynamics(By by) { - return driverExtention.findElementsDynamic(by); + return driverExtension.findElementsDynamic(by); } @Override public WebElement waitForElement(final By selector) { - return driverExtention.waitForElement(selector); + return driverExtension.waitForElement(selector); } @Override public WebElement waitForElementVisible(final By selector) { - return driverExtention.waitForElementVisible(selector); + return driverExtension.waitForElementVisible(selector); } /** - * Waits {@link BasePage.EXPLICITYWAITTIMER} seconds until an element will be clickable. If element will not be + * Waits {@link BasePage#EXPLICIT_WAIT_TIMER}} seconds until an element will be clickable. If element will not be * clickable then throw an exception (BFElementNotFoundException) * * @param selector @@ -159,7 +161,7 @@ public WebElement waitForElementVisible(final By selector) { */ @Override public WebElement waitUntilElementIsClickable(final By selector) { - return driverExtention.waitUntilElementIsClickable(selector); + return driverExtension.waitUntilElementIsClickable(selector); } /** @@ -172,7 +174,7 @@ public WebElement waitUntilElementIsClickable(final By selector) { */ @Override public WebElement findElementQuietly(WebElement elementToSearchIn, By searchedBySelector) { - return driverExtention.findElementQuietly(elementToSearchIn, searchedBySelector); + return driverExtension.findElementQuietly(elementToSearchIn, searchedBySelector); } /** @@ -184,159 +186,159 @@ public WebElement findElementQuietly(WebElement elementToSearchIn, By searchedBy */ @Override public WebElement findElementQuietly(By searchedBySelector) { - return driverExtention.findElementQuietly(null, searchedBySelector); + return driverExtension.findElementQuietly(null, searchedBySelector); } @Override public void waitForPageLoaded() { - driverExtention.waitForPageLoaded(); + driverExtension.waitForPageLoaded(); } @Override public Button elementButton(By selector) { - return driverExtention.elementButton(selector); + return driverExtension.elementButton(selector); } @Override public RadioButtonElement elementRadioButton(By selector) { - return driverExtention.elementRadioButton(selector); + return driverExtension.elementRadioButton(selector); } @Override public RadioButtonElement elementRadioButton(By selector, By inputChildsSelector) { - return driverExtention.elementRadioButton(selector, inputChildsSelector); + return driverExtension.elementRadioButton(selector, inputChildsSelector); } @Override public RadioButtonElement elementRadioButton(By selector, - By inputChildsSelector, - List listSelectedAttributes) { - return driverExtention.elementRadioButton(selector, inputChildsSelector, listSelectedAttributes); + By inputChildsSelector, + List listSelectedAttributes) { + return driverExtension.elementRadioButton(selector, inputChildsSelector, listSelectedAttributes); } @Override public InputTextElement elementInputText(By selector) { - return driverExtention.elementInputText(selector); + return driverExtension.elementInputText(selector); } @Override public DropdownListElement elementDropdownList(By selector) { - return driverExtention.elementDropdownList(selector); + return driverExtension.elementDropdownList(selector); } @Override public ListElements elementList(By selector) { - return driverExtention.elementList(selector); + return driverExtension.elementList(selector); } @Override public CheckBox elementCheckbox(By selector) { - return driverExtention.elementCheckbox(selector); + return driverExtension.elementCheckbox(selector); } @Override public LabelElement elementLabel(By selector) { - return driverExtention.elementLabel(selector); + return driverExtension.elementLabel(selector); } - + @Override public ImageElement elementImage(By selector) { - return driverExtention.elementImage(selector); + return driverExtension.elementImage(selector); } @Override public IFrame elementIFrame(By selector) { - return driverExtention.elementIFrame(selector); + return driverExtension.elementIFrame(selector); } @Override public TabElement elementTab(By selector) { - return driverExtention.elementTab(selector); + return driverExtension.elementTab(selector); } @Override public TabElement elementTab(By selector, By inputChildsSelector) { - return driverExtention.elementTab(selector, inputChildsSelector); + return driverExtension.elementTab(selector, inputChildsSelector); } @Override public TabElement elementTab(By selector, By inputChildsSelector, List listSelectedAttributes) { - return driverExtention.elementTab(selector, inputChildsSelector, listSelectedAttributes); + return driverExtension.elementTab(selector, inputChildsSelector, listSelectedAttributes); } @Override public NavigationBarElement elementNavigationBar(By selector) { - return driverExtention.elementNavigationBar(selector); + return driverExtension.elementNavigationBar(selector); } @Override public NavigationBarElement elementNavigationBar(By selector, By inputChildsSelector) { - return driverExtention.elementNavigationBar(selector, inputChildsSelector); + return driverExtension.elementNavigationBar(selector, inputChildsSelector); } @Override public TooltipElement elementTooltip(By cssSelector) { - return driverExtention.elementTooltip(cssSelector); + return driverExtension.elementTooltip(cssSelector); } @Override public MenuElement elementMenu(By selector) { - return driverExtention.elementMenu(selector); + return driverExtension.elementMenu(selector); } @Override public MenuElement elementMenu(By selector, By childsSelector) { - return driverExtention.elementMenu(selector, childsSelector); + return driverExtension.elementMenu(selector, childsSelector); } @Override public MenuElement elementMenu(By selector, By childsSelector, By subMenuSelector) { - return driverExtention.elementMenu(selector, childsSelector, subMenuSelector); + return driverExtension.elementMenu(selector, childsSelector, subMenuSelector); } @Override public MenuElement elementMenu(By selector, By childsSelector, By subMenuSelector, By childsSubMenuSelector) { - return driverExtention.elementMenu(selector, childsSelector, subMenuSelector, childsSubMenuSelector); + return driverExtension.elementMenu(selector, childsSelector, subMenuSelector, childsSubMenuSelector); } @Override public HorizontalSliderElement elementHorizontalSlider(final By sliderContainerSelector) { - return driverExtention.elementHorizontalSlider(sliderContainerSelector); + return driverExtension.elementHorizontalSlider(sliderContainerSelector); } @Override public HorizontalSliderElement elementHorizontalSlider(final By sliderContainerSelector, final By sliderSelector, final By valueSelector) { - return driverExtention.elementHorizontalSlider(sliderContainerSelector, sliderSelector, valueSelector); + return driverExtension.elementHorizontalSlider(sliderContainerSelector, sliderSelector, valueSelector); } @Override public HorizontalSliderElement elementHorizontalSlider(final By sliderContainerSelector, - final By sliderSelector, - final By valueSelector, - final BigDecimal minRange, - final BigDecimal maxRange, - final BigDecimal step) { - return driverExtention.elementHorizontalSlider(sliderContainerSelector, sliderSelector, valueSelector, minRange, maxRange, step); + final By sliderSelector, + final By valueSelector, + final BigDecimal minRange, + final BigDecimal maxRange, + final BigDecimal step) { + return driverExtension.elementHorizontalSlider(sliderContainerSelector, sliderSelector, valueSelector, minRange, maxRange, step); } @Override public void mouseRightClick(By selector) { - driverExtention.mouseRightClick(selector); + driverExtension.mouseRightClick(selector); } @Override public void mouseLeftClick(By selector) { - driverExtention.mouseLeftClick(selector); + driverExtension.mouseLeftClick(selector); } @Override public void mouseLeftClick(WebElement element) { - driverExtention.mouseLeftClick(element); + driverExtension.mouseLeftClick(element); } public static void main(String[] args) { BaseTest.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); + .sendMethodEvent(BasePage.ANALYTICS_CATEGORY_NAME); } } \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/NewEdgeDriver.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/NewEdgeDriver.java index 652135be..bff3f48e 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/NewEdgeDriver.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/NewEdgeDriver.java @@ -1,9 +1,8 @@ package com.capgemini.mrchecker.selenium.core.newDrivers; -import com.capgemini.mrchecker.selenium.core.BasePage; -import com.capgemini.mrchecker.selenium.core.exceptions.BFElementNotFoundException; -import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.*; -import com.capgemini.mrchecker.test.core.BaseTest; +import java.math.BigDecimal; +import java.util.List; + import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebElement; @@ -12,27 +11,42 @@ import org.openqa.selenium.remote.ExecuteMethod; import org.openqa.selenium.remote.RemoteExecuteMethod; -import java.math.BigDecimal; -import java.util.List; +import com.capgemini.mrchecker.selenium.core.BasePage; +import com.capgemini.mrchecker.selenium.core.exceptions.BFElementNotFoundException; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.Button; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.CheckBox; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.DropdownListElement; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.HorizontalSliderElement; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.IFrame; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.ImageElement; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.InputTextElement; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.LabelElement; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.ListElements; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.MenuElement; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.NavigationBarElement; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.RadioButtonElement; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.TabElement; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.TooltipElement; +import com.capgemini.mrchecker.test.core.BaseTest; public class NewEdgeDriver extends EdgeDriver implements INewWebDriver { - - private DriverExtention driverExtention; - + + private DriverExtension driverExtension; + public NewEdgeDriver() { - driverExtention = new DriverExtention(this); + driverExtension = new DriverExtension(this); } - + public NewEdgeDriver(EdgeOptions options) { super(options); - driverExtention = new DriverExtention(this); + driverExtension = new DriverExtension(this); } - + @Override protected ExecuteMethod getExecuteMethod() { return new RemoteExecuteMethod(this); } - + /** * @deprecated As of release 1.0.0, replaced by {@link #findElementDynamics(By)()} */ @@ -40,10 +54,10 @@ protected ExecuteMethod getExecuteMethod() { @Override public List findElements(By by) { BaseTest.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); - return DriverExtention.convertWebElementList(super.findElements(by)); + .sendMethodEvent(BasePage.ANALYTICS_CATEGORY_NAME); + return DriverExtension.convertWebElementList(super.findElements(by)); } - + /** * @deprecated As of release 1.0.0, replaced by {@link #findElementDynamic(By)()} */ @@ -51,7 +65,7 @@ public List findElements(By by) { @Override public WebElement findElement(By by) throws BFElementNotFoundException { BaseTest.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); + .sendMethodEvent(BasePage.ANALYTICS_CATEGORY_NAME); WebElement elementFromDriver = null; try { elementFromDriver = super.findElement(by); @@ -60,87 +74,95 @@ public WebElement findElement(By by) throws BFElementNotFoundException { } return new NewRemoteWebElement(elementFromDriver); } - + /** * Try to find by dynamic element - will wait given by user an amount of seconds for an element to load on page. If * element will not be found will throw an exception (PiAtElementNotLoadedException) * - * @param by selector - * @param timeout - maximum time to wait for search WebElement + * @param by + * selector + * @param timeOut + * - maximum time to wait for search WebElement * @return found WebElement object * @throws BFElementNotFoundException * @author */ @Override public WebElement findElementDynamic(By by, int timeOut) throws BFElementNotFoundException { - return driverExtention.findElementDynamic(by, timeOut); + return driverExtension.findElementDynamic(by, timeOut); } - + /** * Try to find by dynamic element - will wait given by user an amount of seconds for an element to load on page. If * element will not be found will throw an exception (PiAtElementNotLoadedException) * - * @param by selector + * @param by + * selector * @return found WebElement object * @throws BFElementNotFoundException * @author */ @Override public WebElement findElementDynamic(By by) throws BFElementNotFoundException { - return driverExtention.findElementDynamic(by); + return driverExtension.findElementDynamic(by); } - + /** * Try to find by dynamic List of elements - will wait given by user an amount of seconds for an element to load on * page. If element will not be found will throw an exception (PiAtElementNotLoadedException) * - * @param by selector - * @param timeOut - maximum time to wait for search WebElement + * @param by + * selector + * @param timeOut + * - maximum time to wait for search WebElement * @return found WebElement object * @author */ @Override public List findElementDynamics(By by, int timeOut) { - return driverExtention.findElementsDynamic(by, timeOut); + return driverExtension.findElementsDynamic(by, timeOut); } - + /** - * Try to find by dynamic List of elements - will wait {@link BasePage.EXPLICITYWAITTIMER} seconds for an element to + * Try to find by dynamic List of elements - will wait {@link BasePage#EXPLICIT_WAIT_TIMER} seconds for an element + * to * load on page. If element will not be found will throw an exception (PiAtElementNotLoadedException) * - * @param by selector + * @param by + * selector * @return found WebElement object * @author */ @Override public List findElementDynamics(By by) { - return driverExtention.findElementsDynamic(by); + return driverExtension.findElementsDynamic(by); } - + @Override public WebElement waitForElement(final By selector) { - return driverExtention.waitForElement(selector); + return driverExtension.waitForElement(selector); } - + @Override public WebElement waitForElementVisible(final By selector) { - return driverExtention.waitForElementVisible(selector); + return driverExtension.waitForElementVisible(selector); } - + /** - * Waits {@link BasePage.EXPLICITYWAITTIMER} seconds until an element will be clickable. If element will not be + * Waits {@link BasePage#EXPLICIT_WAIT_TIMER} seconds until an element will be clickable. If element will not be * clickable then throw an exception (BFElementNotFoundException) * - * @param selector selector + * @param selector + * selector * @return WebElement object ready to click * @throws BFElementNotFoundException * @author */ @Override public WebElement waitUntilElementIsClickable(final By selector) { - return driverExtention.waitUntilElementIsClickable(selector); + return driverExtension.waitUntilElementIsClickable(selector); } - + /** * Try to find element quietly - NoSuchElementException will not be thrown. Use it to check if element exist on page * e.g. PopUp @@ -151,9 +173,9 @@ public WebElement waitUntilElementIsClickable(final By selector) { */ @Override public WebElement findElementQuietly(WebElement elementToSearchIn, By searchedBySelector) { - return driverExtention.findElementQuietly(elementToSearchIn, searchedBySelector); + return driverExtension.findElementQuietly(elementToSearchIn, searchedBySelector); } - + /** * Try to find element quietly - NoSuchElementException will not be thrown. Use it to check if element exist on page * e.g. PopUp @@ -163,132 +185,132 @@ public WebElement findElementQuietly(WebElement elementToSearchIn, By searchedBy */ @Override public WebElement findElementQuietly(By searchedBySelector) { - return driverExtention.findElementQuietly(null, searchedBySelector); + return driverExtension.findElementQuietly(null, searchedBySelector); } - + @Override public void waitForPageLoaded() { - driverExtention.waitForPageLoaded(); - + driverExtension.waitForPageLoaded(); + } - + @Override public Button elementButton(By selector) { - return driverExtention.elementButton(selector); + return driverExtension.elementButton(selector); } - + @Override public RadioButtonElement elementRadioButton(By selector) { - return driverExtention.elementRadioButton(selector); + return driverExtension.elementRadioButton(selector); } - + @Override public RadioButtonElement elementRadioButton(By selector, By inputChildsSelector) { - return driverExtention.elementRadioButton(selector, inputChildsSelector); + return driverExtension.elementRadioButton(selector, inputChildsSelector); } - + @Override public RadioButtonElement elementRadioButton(By selector, By inputChildsSelector, List listSelectedAttributes) { - return driverExtention.elementRadioButton(selector, inputChildsSelector, listSelectedAttributes); + return driverExtension.elementRadioButton(selector, inputChildsSelector, listSelectedAttributes); } - + @Override public InputTextElement elementInputText(By selector) { - return driverExtention.elementInputText(selector); + return driverExtension.elementInputText(selector); } - + @Override public DropdownListElement elementDropdownList(By selector) { - return driverExtention.elementDropdownList(selector); + return driverExtension.elementDropdownList(selector); } - + @Override public ListElements elementList(By selector) { - return driverExtention.elementList(selector); + return driverExtension.elementList(selector); } - + @Override public CheckBox elementCheckbox(By selector) { - return driverExtention.elementCheckbox(selector); + return driverExtension.elementCheckbox(selector); } - + @Override public LabelElement elementLabel(By selector) { - return driverExtention.elementLabel(selector); + return driverExtension.elementLabel(selector); } - + @Override public ImageElement elementImage(By selector) { - return driverExtention.elementImage(selector); + return driverExtension.elementImage(selector); } - + @Override public IFrame elementIFrame(By selector) { - return driverExtention.elementIFrame(selector); + return driverExtension.elementIFrame(selector); } - + @Override public TabElement elementTab(By selector) { - return driverExtention.elementTab(selector); + return driverExtension.elementTab(selector); } - + @Override public TabElement elementTab(By selector, By inputChildsSelector) { - return driverExtention.elementTab(selector, inputChildsSelector); + return driverExtension.elementTab(selector, inputChildsSelector); } - + @Override public TabElement elementTab(By selector, By inputChildsSelector, List listSelectedAttributes) { - return driverExtention.elementTab(selector, inputChildsSelector, listSelectedAttributes); + return driverExtension.elementTab(selector, inputChildsSelector, listSelectedAttributes); } - + @Override public NavigationBarElement elementNavigationBar(By selector) { - return driverExtention.elementNavigationBar(selector); + return driverExtension.elementNavigationBar(selector); } - + @Override public NavigationBarElement elementNavigationBar(By selector, By inputChildsSelector) { - return driverExtention.elementNavigationBar(selector, inputChildsSelector); + return driverExtension.elementNavigationBar(selector, inputChildsSelector); } - + @Override public TooltipElement elementTooltip(By cssSelector) { - return driverExtention.elementTooltip(cssSelector); + return driverExtension.elementTooltip(cssSelector); } - + @Override public MenuElement elementMenu(By selector) { - return driverExtention.elementMenu(selector); + return driverExtension.elementMenu(selector); } - + @Override public MenuElement elementMenu(By selector, By childsSelector) { - return driverExtention.elementMenu(selector, childsSelector); + return driverExtension.elementMenu(selector, childsSelector); } - + @Override public MenuElement elementMenu(By selector, By childsSelector, By subMenuSelector) { - return driverExtention.elementMenu(selector, childsSelector, subMenuSelector); + return driverExtension.elementMenu(selector, childsSelector, subMenuSelector); } - + @Override public MenuElement elementMenu(By selector, By childsSelector, By subMenuSelector, By childsSubMenuSelector) { - return driverExtention.elementMenu(selector, childsSelector, subMenuSelector, childsSubMenuSelector); + return driverExtension.elementMenu(selector, childsSelector, subMenuSelector, childsSubMenuSelector); } - + @Override public HorizontalSliderElement elementHorizontalSlider(final By sliderContainerSelector) { - return driverExtention.elementHorizontalSlider(sliderContainerSelector); + return driverExtension.elementHorizontalSlider(sliderContainerSelector); } - + @Override public HorizontalSliderElement elementHorizontalSlider(final By sliderContainerSelector, final By sliderSelector, final By valueSelector) { - return driverExtention.elementHorizontalSlider(sliderContainerSelector, sliderSelector, valueSelector); + return driverExtension.elementHorizontalSlider(sliderContainerSelector, sliderSelector, valueSelector); } - + @Override public HorizontalSliderElement elementHorizontalSlider(final By sliderContainerSelector, final By sliderSelector, @@ -296,26 +318,26 @@ public HorizontalSliderElement elementHorizontalSlider(final By sliderContainerS final BigDecimal minRange, final BigDecimal maxRange, final BigDecimal step) { - return driverExtention.elementHorizontalSlider(sliderContainerSelector, sliderSelector, valueSelector, minRange, maxRange, step); + return driverExtension.elementHorizontalSlider(sliderContainerSelector, sliderSelector, valueSelector, minRange, maxRange, step); } - + @Override public void mouseRightClick(By selector) { - driverExtention.mouseRightClick(selector); + driverExtension.mouseRightClick(selector); } - + @Override public void mouseLeftClick(By selector) { - driverExtention.mouseLeftClick(selector); + driverExtension.mouseLeftClick(selector); } - + @Override public void mouseLeftClick(WebElement element) { - driverExtention.mouseLeftClick(element); + driverExtension.mouseLeftClick(element); } - + public static void main(String[] args) { BaseTest.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); + .sendMethodEvent(BasePage.ANALYTICS_CATEGORY_NAME); } } \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/NewFirefoxDriver.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/NewFirefoxDriver.java index c35731ed..e3a18a5b 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/NewFirefoxDriver.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/NewFirefoxDriver.java @@ -16,9 +16,9 @@ import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.DropdownListElement; import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.HorizontalSliderElement; import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.IFrame; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.ImageElement; import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.InputTextElement; import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.LabelElement; -import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.ImageElement; import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.ListElements; import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.MenuElement; import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.NavigationBarElement; @@ -28,15 +28,15 @@ public final class NewFirefoxDriver extends FirefoxDriver implements INewWebDriver { - private DriverExtention driverExtention; + private DriverExtension driverExtension; public NewFirefoxDriver() { - driverExtention = new DriverExtention(this); + driverExtension = new DriverExtension(this); } public NewFirefoxDriver(FirefoxOptions options) { super(options); - driverExtention = new DriverExtention(this); + driverExtension = new DriverExtension(this); } /** @@ -46,8 +46,8 @@ public NewFirefoxDriver(FirefoxOptions options) { @Override public List findElements(By by) { BasePage.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); - return DriverExtention.convertWebElementList(super.findElements(by)); + .sendMethodEvent(BasePage.ANALYTICS_CATEGORY_NAME); + return DriverExtension.convertWebElementList(super.findElements(by)); } /** @@ -57,7 +57,7 @@ public List findElements(By by) { @Override public WebElement findElement(By by) throws BFElementNotFoundException { BasePage.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); + .sendMethodEvent(BasePage.ANALYTICS_CATEGORY_NAME); WebElement elementFromDriver = null; try { elementFromDriver = super.findElement(by); @@ -77,7 +77,7 @@ public WebElement findElement(By by) throws BFElementNotFoundException { */ @Override public WebElement findElementQuietly(WebElement elementToSearchIn, By searchedBySelector) { - return driverExtention.findElementQuietly(elementToSearchIn, searchedBySelector); + return driverExtension.findElementQuietly(elementToSearchIn, searchedBySelector); } /** @@ -89,7 +89,7 @@ public WebElement findElementQuietly(WebElement elementToSearchIn, By searchedBy */ @Override public WebElement findElementQuietly(By searchedBySelector) { - return driverExtention.findElementQuietly(null, searchedBySelector); + return driverExtension.findElementQuietly(null, searchedBySelector); } /** @@ -105,7 +105,7 @@ public WebElement findElementQuietly(By searchedBySelector) { * @throws BFElementNotFoundException */ public WebElement findElementDynamic(By by, int timeOut) throws BFElementNotFoundException { - return driverExtention.findElementDynamic(by, timeOut); + return driverExtension.findElementDynamic(by, timeOut); } /** @@ -119,7 +119,7 @@ public WebElement findElementDynamic(By by, int timeOut) throws BFElementNotFoun * @throws BFElementNotFoundException */ public WebElement findElementDynamic(By by) throws BFElementNotFoundException { - return driverExtention.findElementDynamic(by); + return driverExtension.findElementDynamic(by); } /** @@ -134,11 +134,12 @@ public WebElement findElementDynamic(By by) throws BFElementNotFoundException { * @author */ public List findElementDynamics(By by, int timeOut) { - return driverExtention.findElementsDynamic(by, timeOut); + return driverExtension.findElementsDynamic(by, timeOut); } /** - * Try to find by dynamic List of elements - will wait {@link BasePage.EXPLICITYWAITTIMER} seconds for an element to + * Try to find by dynamic List of elements - will wait {@link BasePage#EXPLICIT_WAIT_TIMER} seconds for an element + * to * load on page. If element will not be found will throw an exception (PiAtElementNotLoadedException) * * @param by @@ -147,19 +148,19 @@ public List findElementDynamics(By by, int timeOut) { * @author */ public List findElementDynamics(By by) { - return driverExtention.findElementsDynamic(by); + return driverExtension.findElementsDynamic(by); } public WebElement waitForElement(final By selector) { - return driverExtention.waitForElement(selector); + return driverExtension.waitForElement(selector); } public WebElement waitForElementVisible(final By selector) { - return driverExtention.waitForElementVisible(selector); + return driverExtension.waitForElementVisible(selector); } /** - * Waits {@link BasePage.EXPLICITYWAITTIMER} seconds until an element will be clickable. If element will not be + * Waits {@link BasePage#EXPLICIT_WAIT_TIMER} seconds until an element will be clickable. If element will not be * clickable then throw an exception (BFElementNotFoundException) * * @param selector @@ -169,153 +170,153 @@ public WebElement waitForElementVisible(final By selector) { * @throws BFElementNotFoundException */ public WebElement waitUntilElementIsClickable(final By selector) { - return driverExtention.waitUntilElementIsClickable(selector); + return driverExtension.waitUntilElementIsClickable(selector); } @Override public void waitForPageLoaded() { - driverExtention.waitForPageLoaded(); + driverExtension.waitForPageLoaded(); } @Override public Button elementButton(By selector) { - return driverExtention.elementButton(selector); + return driverExtension.elementButton(selector); } @Override public RadioButtonElement elementRadioButton(By selector) { - return driverExtention.elementRadioButton(selector); + return driverExtension.elementRadioButton(selector); } @Override public RadioButtonElement elementRadioButton(By selector, By inputChildsSelector) { - return driverExtention.elementRadioButton(selector, inputChildsSelector); + return driverExtension.elementRadioButton(selector, inputChildsSelector); } @Override public RadioButtonElement elementRadioButton(By selector, - By inputChildsSelector, - List listSelectedAttributes) { - return driverExtention.elementRadioButton(selector, inputChildsSelector, listSelectedAttributes); + By inputChildsSelector, + List listSelectedAttributes) { + return driverExtension.elementRadioButton(selector, inputChildsSelector, listSelectedAttributes); } @Override public InputTextElement elementInputText(By selector) { - return driverExtention.elementInputText(selector); + return driverExtension.elementInputText(selector); } @Override public DropdownListElement elementDropdownList(By selector) { - return driverExtention.elementDropdownList(selector); + return driverExtension.elementDropdownList(selector); } @Override public ListElements elementList(By selector) { - return driverExtention.elementList(selector); + return driverExtension.elementList(selector); } @Override public CheckBox elementCheckbox(By selector) { - return driverExtention.elementCheckbox(selector); + return driverExtension.elementCheckbox(selector); } @Override public LabelElement elementLabel(By selector) { - return driverExtention.elementLabel(selector); + return driverExtension.elementLabel(selector); } - + @Override public ImageElement elementImage(By selector) { - return driverExtention.elementImage(selector); + return driverExtension.elementImage(selector); } @Override public TabElement elementTab(By selector) { - return driverExtention.elementTab(selector); + return driverExtension.elementTab(selector); } @Override public TabElement elementTab(By selector, By inputChildsSelector) { - return driverExtention.elementTab(selector, inputChildsSelector); + return driverExtension.elementTab(selector, inputChildsSelector); } @Override public TabElement elementTab(By selector, By inputChildsSelector, List listSelectedAttributes) { - return driverExtention.elementTab(selector, inputChildsSelector, listSelectedAttributes); + return driverExtension.elementTab(selector, inputChildsSelector, listSelectedAttributes); } @Override public NavigationBarElement elementNavigationBar(By selector) { - return driverExtention.elementNavigationBar(selector); + return driverExtension.elementNavigationBar(selector); } @Override public NavigationBarElement elementNavigationBar(By selector, By inputChildsSelector) { - return driverExtention.elementNavigationBar(selector, inputChildsSelector); + return driverExtension.elementNavigationBar(selector, inputChildsSelector); } @Override public TooltipElement elementTooltip(By cssSelector) { - return driverExtention.elementTooltip(cssSelector); + return driverExtension.elementTooltip(cssSelector); } @Override public MenuElement elementMenu(By selector) { - return driverExtention.elementMenu(selector); + return driverExtension.elementMenu(selector); } @Override public MenuElement elementMenu(By selector, By childsSelector) { - return driverExtention.elementMenu(selector, childsSelector); + return driverExtension.elementMenu(selector, childsSelector); } @Override public MenuElement elementMenu(By selector, By childsSelector, By subMenuSelector) { - return driverExtention.elementMenu(selector, childsSelector, subMenuSelector); + return driverExtension.elementMenu(selector, childsSelector, subMenuSelector); } @Override public MenuElement elementMenu(By selector, By childsSelector, By subMenuSelector, By childsSubMenuSelector) { - return driverExtention.elementMenu(selector, childsSelector, subMenuSelector, childsSubMenuSelector); + return driverExtension.elementMenu(selector, childsSelector, subMenuSelector, childsSubMenuSelector); } @Override public HorizontalSliderElement elementHorizontalSlider(final By sliderContainerSelector) { - return driverExtention.elementHorizontalSlider(sliderContainerSelector); + return driverExtension.elementHorizontalSlider(sliderContainerSelector); } @Override public HorizontalSliderElement elementHorizontalSlider(final By sliderContainerSelector, final By sliderSelector, final By valueSelector) { - return driverExtention.elementHorizontalSlider(sliderContainerSelector, sliderSelector, valueSelector); + return driverExtension.elementHorizontalSlider(sliderContainerSelector, sliderSelector, valueSelector); } @Override public HorizontalSliderElement elementHorizontalSlider(final By sliderContainerSelector, - final By sliderSelector, - final By valueSelector, - final BigDecimal minRange, - final BigDecimal maxRange, - final BigDecimal step) { - return driverExtention.elementHorizontalSlider(sliderContainerSelector, sliderSelector, valueSelector, minRange, maxRange, step); + final By sliderSelector, + final By valueSelector, + final BigDecimal minRange, + final BigDecimal maxRange, + final BigDecimal step) { + return driverExtension.elementHorizontalSlider(sliderContainerSelector, sliderSelector, valueSelector, minRange, maxRange, step); } @Override public IFrame elementIFrame(By selector) { - return driverExtention.elementIFrame(selector); + return driverExtension.elementIFrame(selector); } @Override public void mouseRightClick(By selector) { - driverExtention.mouseRightClick(selector); + driverExtension.mouseRightClick(selector); } @Override public void mouseLeftClick(By selector) { - driverExtention.mouseLeftClick(selector); + driverExtension.mouseLeftClick(selector); } @Override public void mouseLeftClick(WebElement element) { - driverExtention.mouseLeftClick(element); + driverExtension.mouseLeftClick(element); } } \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/NewInternetExplorerDriver.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/NewInternetExplorerDriver.java index 672a74db..2f48ef44 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/NewInternetExplorerDriver.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/NewInternetExplorerDriver.java @@ -16,9 +16,9 @@ import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.DropdownListElement; import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.HorizontalSliderElement; import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.IFrame; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.ImageElement; import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.InputTextElement; import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.LabelElement; -import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.ImageElement; import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.ListElements; import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.MenuElement; import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.NavigationBarElement; @@ -28,11 +28,11 @@ public final class NewInternetExplorerDriver extends InternetExplorerDriver implements INewWebDriver { - private DriverExtention driverExtention; + private DriverExtension driverExtension; public NewInternetExplorerDriver(Capabilities capabilities) { super(capabilities); - driverExtention = new DriverExtention(this); + driverExtension = new DriverExtension(this); } /** @@ -42,8 +42,8 @@ public NewInternetExplorerDriver(Capabilities capabilities) { @Override public List findElements(By by) { BasePage.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); - return DriverExtention.convertWebElementList(super.findElements(by)); + .sendMethodEvent(BasePage.ANALYTICS_CATEGORY_NAME); + return DriverExtension.convertWebElementList(super.findElements(by)); } /** @@ -53,7 +53,7 @@ public List findElements(By by) { @Override public WebElement findElement(By by) throws BFElementNotFoundException { BasePage.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); + .sendMethodEvent(BasePage.ANALYTICS_CATEGORY_NAME); WebElement elementFromDriver = null; try { elementFromDriver = super.findElement(by); @@ -73,7 +73,7 @@ public WebElement findElement(By by) throws BFElementNotFoundException { */ @Override public WebElement findElementQuietly(WebElement elementToSearchIn, By searchedBySelector) { - return driverExtention.findElementQuietly(elementToSearchIn, searchedBySelector); + return driverExtension.findElementQuietly(elementToSearchIn, searchedBySelector); } /** @@ -85,7 +85,7 @@ public WebElement findElementQuietly(WebElement elementToSearchIn, By searchedBy */ @Override public WebElement findElementQuietly(By searchedBySelector) { - return driverExtention.findElementQuietly(null, searchedBySelector); + return driverExtension.findElementQuietly(null, searchedBySelector); } /** @@ -101,7 +101,7 @@ public WebElement findElementQuietly(By searchedBySelector) { * @throws BFElementNotFoundException */ public WebElement findElementDynamic(By by, int timeOut) throws BFElementNotFoundException { - return driverExtention.findElementDynamic(by, timeOut); + return driverExtension.findElementDynamic(by, timeOut); } /** @@ -115,7 +115,7 @@ public WebElement findElementDynamic(By by, int timeOut) throws BFElementNotFoun * @throws BFElementNotFoundException */ public WebElement findElementDynamic(By by) throws BFElementNotFoundException { - return driverExtention.findElementDynamic(by); + return driverExtension.findElementDynamic(by); } /** @@ -130,11 +130,12 @@ public WebElement findElementDynamic(By by) throws BFElementNotFoundException { * @author */ public List findElementDynamics(By by, int timeOut) { - return driverExtention.findElementsDynamic(by, timeOut); + return driverExtension.findElementsDynamic(by, timeOut); } /** - * Try to find by dynamic List of elements - will wait {@link BasePage.EXPLICITYWAITTIMER} seconds for an element to + * Try to find by dynamic List of elements - will wait {@link BasePage#EXPLICIT_WAIT_TIMER} seconds for an element + * to * load on page. If element will not be found will throw an exception (PiAtElementNotLoadedException) * * @param by @@ -143,15 +144,15 @@ public List findElementDynamics(By by, int timeOut) { * @author */ public List findElementDynamics(By by) { - return driverExtention.findElementsDynamic(by); + return driverExtension.findElementsDynamic(by); } public WebElement waitForElement(final By selector) { - return driverExtention.waitForElement(selector); + return driverExtension.waitForElement(selector); } /** - * Waits {@link BasePage.EXPLICITYWAITTIMER} seconds until an element will be clickable. If element will not be + * Waits {@link BasePage#EXPLICIT_WAIT_TIMER} seconds until an element will be clickable. If element will not be * clickable then throw an exception (BFElementNotFoundException) * * @param selector @@ -161,158 +162,158 @@ public WebElement waitForElement(final By selector) { * @throws BFElementNotFoundException */ public WebElement waitUntilElementIsClickable(final By selector) { - return driverExtention.waitUntilElementIsClickable(selector); + return driverExtension.waitUntilElementIsClickable(selector); } public WebElement waitForElementVisible(final By selector) { - return driverExtention.waitForElementVisible(selector); + return driverExtension.waitForElementVisible(selector); } @Override public void waitForPageLoaded() { - driverExtention.waitForPageLoaded(); + driverExtension.waitForPageLoaded(); } @Override public Button elementButton(By selector) { - return driverExtention.elementButton(selector); + return driverExtension.elementButton(selector); } @Override public RadioButtonElement elementRadioButton(By selector) { - return driverExtention.elementRadioButton(selector); + return driverExtension.elementRadioButton(selector); } @Override public RadioButtonElement elementRadioButton(By selector, By inputChildsSelector) { - return driverExtention.elementRadioButton(selector, inputChildsSelector); + return driverExtension.elementRadioButton(selector, inputChildsSelector); } @Override public RadioButtonElement elementRadioButton(By selector, - By inputChildsSelector, - List listSelectedAttributes) { - return driverExtention.elementRadioButton(selector, inputChildsSelector, listSelectedAttributes); + By inputChildsSelector, + List listSelectedAttributes) { + return driverExtension.elementRadioButton(selector, inputChildsSelector, listSelectedAttributes); } @Override public InputTextElement elementInputText(By selector) { - return driverExtention.elementInputText(selector); + return driverExtension.elementInputText(selector); } @Override public DropdownListElement elementDropdownList(By selector) { - return driverExtention.elementDropdownList(selector); + return driverExtension.elementDropdownList(selector); } @Override public ListElements elementList(By selector) { - return driverExtention.elementList(selector); + return driverExtension.elementList(selector); } @Override public CheckBox elementCheckbox(By selector) { - return driverExtention.elementCheckbox(selector); + return driverExtension.elementCheckbox(selector); } @Override public LabelElement elementLabel(By selector) { - return driverExtention.elementLabel(selector); + return driverExtension.elementLabel(selector); } - + @Override public ImageElement elementImage(By selector) { - return driverExtention.elementImage(selector); + return driverExtension.elementImage(selector); } @Override public TabElement elementTab(By selector) { - return driverExtention.elementTab(selector); + return driverExtension.elementTab(selector); } @Override public TabElement elementTab(By selector, By inputChildsSelector) { - return driverExtention.elementTab(selector, inputChildsSelector); + return driverExtension.elementTab(selector, inputChildsSelector); } @Override public TabElement elementTab(By selector, By inputChildsSelector, List listSelectedAttributes) { - return driverExtention.elementTab(selector, inputChildsSelector, listSelectedAttributes); + return driverExtension.elementTab(selector, inputChildsSelector, listSelectedAttributes); } @Override public NavigationBarElement elementNavigationBar(By selector) { - return driverExtention.elementNavigationBar(selector); + return driverExtension.elementNavigationBar(selector); } @Override public NavigationBarElement elementNavigationBar(By selector, By inputChildsSelector) { - return driverExtention.elementNavigationBar(selector, inputChildsSelector); + return driverExtension.elementNavigationBar(selector, inputChildsSelector); } @Override public TooltipElement elementTooltip(By cssSelector) { - return driverExtention.elementTooltip(cssSelector); + return driverExtension.elementTooltip(cssSelector); } @Override public MenuElement elementMenu(By selector) { - return driverExtention.elementMenu(selector); + return driverExtension.elementMenu(selector); } @Override public MenuElement elementMenu(By selector, By childsSelector) { - return driverExtention.elementMenu(selector, childsSelector); + return driverExtension.elementMenu(selector, childsSelector); } @Override public MenuElement elementMenu(By selector, By childsSelector, By subMenuSelector) { - return driverExtention.elementMenu(selector, childsSelector, subMenuSelector); + return driverExtension.elementMenu(selector, childsSelector, subMenuSelector); } @Override public MenuElement elementMenu(By selector, By childsSelector, By subMenuSelector, By childsSubMenuSelector) { - return driverExtention.elementMenu(selector, childsSelector, subMenuSelector, childsSubMenuSelector); + return driverExtension.elementMenu(selector, childsSelector, subMenuSelector, childsSubMenuSelector); } @Override public HorizontalSliderElement elementHorizontalSlider(final By sliderContainerSelector) { - return driverExtention.elementHorizontalSlider(sliderContainerSelector); + return driverExtension.elementHorizontalSlider(sliderContainerSelector); } @Override public HorizontalSliderElement elementHorizontalSlider(final By sliderContainerSelector, final By sliderSelector, final By valueSelector) { - return driverExtention.elementHorizontalSlider(sliderContainerSelector, sliderSelector, valueSelector); + return driverExtension.elementHorizontalSlider(sliderContainerSelector, sliderSelector, valueSelector); } @Override public HorizontalSliderElement elementHorizontalSlider(final By sliderContainerSelector, - final By sliderSelector, - final By valueSelector, - final BigDecimal minRange, - final BigDecimal maxRange, - final BigDecimal step) { - return driverExtention.elementHorizontalSlider(sliderContainerSelector, sliderSelector, valueSelector, minRange, maxRange, step); + final By sliderSelector, + final By valueSelector, + final BigDecimal minRange, + final BigDecimal maxRange, + final BigDecimal step) { + return driverExtension.elementHorizontalSlider(sliderContainerSelector, sliderSelector, valueSelector, minRange, maxRange, step); } @Override public IFrame elementIFrame(By selector) { - return driverExtention.elementIFrame(selector); + return driverExtension.elementIFrame(selector); } @Override public void mouseRightClick(By selector) { - driverExtention.mouseRightClick(selector); + driverExtension.mouseRightClick(selector); } @Override public void mouseLeftClick(By selector) { - driverExtention.mouseLeftClick(selector); + driverExtension.mouseLeftClick(selector); } @Override public void mouseLeftClick(WebElement element) { - driverExtention.mouseLeftClick(element); + driverExtension.mouseLeftClick(element); } } \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/NewOperaDriver.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/NewOperaDriver.java index 2337f39c..ae88f260 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/NewOperaDriver.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/NewOperaDriver.java @@ -1,9 +1,8 @@ package com.capgemini.mrchecker.selenium.core.newDrivers; -import com.capgemini.mrchecker.selenium.core.BasePage; -import com.capgemini.mrchecker.selenium.core.exceptions.BFElementNotFoundException; -import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.*; -import com.capgemini.mrchecker.test.core.BaseTest; +import java.math.BigDecimal; +import java.util.List; + import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebElement; @@ -12,27 +11,42 @@ import org.openqa.selenium.remote.ExecuteMethod; import org.openqa.selenium.remote.RemoteExecuteMethod; -import java.math.BigDecimal; -import java.util.List; +import com.capgemini.mrchecker.selenium.core.BasePage; +import com.capgemini.mrchecker.selenium.core.exceptions.BFElementNotFoundException; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.Button; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.CheckBox; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.DropdownListElement; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.HorizontalSliderElement; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.IFrame; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.ImageElement; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.InputTextElement; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.LabelElement; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.ListElements; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.MenuElement; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.NavigationBarElement; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.RadioButtonElement; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.TabElement; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.TooltipElement; +import com.capgemini.mrchecker.test.core.BaseTest; public class NewOperaDriver extends OperaDriver implements INewWebDriver { - - private DriverExtention driverExtention; - + + private DriverExtension driverExtension; + public NewOperaDriver() { - driverExtention = new DriverExtention(this); + driverExtension = new DriverExtension(this); } - + public NewOperaDriver(OperaOptions options) { super(options); - driverExtention = new DriverExtention(this); + driverExtension = new DriverExtension(this); } - + @Override protected ExecuteMethod getExecuteMethod() { return new RemoteExecuteMethod(this); } - + /** * @deprecated As of release 1.0.0, replaced by {@link #findElementDynamics(By)()} */ @@ -40,10 +54,10 @@ protected ExecuteMethod getExecuteMethod() { @Override public List findElements(By by) { BaseTest.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); - return DriverExtention.convertWebElementList(super.findElements(by)); + .sendMethodEvent(BasePage.ANALYTICS_CATEGORY_NAME); + return DriverExtension.convertWebElementList(super.findElements(by)); } - + /** * @deprecated As of release 1.0.0, replaced by {@link #findElementDynamic(By)()} */ @@ -51,7 +65,7 @@ public List findElements(By by) { @Override public WebElement findElement(By by) throws BFElementNotFoundException { BaseTest.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); + .sendMethodEvent(BasePage.ANALYTICS_CATEGORY_NAME); WebElement elementFromDriver = null; try { elementFromDriver = super.findElement(by); @@ -60,87 +74,95 @@ public WebElement findElement(By by) throws BFElementNotFoundException { } return new NewRemoteWebElement(elementFromDriver); } - + /** * Try to find by dynamic element - will wait given by user an amount of seconds for an element to load on page. If * element will not be found will throw an exception (PiAtElementNotLoadedException) * - * @param by selector - * @param timeout - maximum time to wait for search WebElement + * @param by + * selector + * @param timeOut + * - maximum time to wait for search WebElement * @return found WebElement object * @throws BFElementNotFoundException * @author */ @Override public WebElement findElementDynamic(By by, int timeOut) throws BFElementNotFoundException { - return driverExtention.findElementDynamic(by, timeOut); + return driverExtension.findElementDynamic(by, timeOut); } - + /** * Try to find by dynamic element - will wait given by user an amount of seconds for an element to load on page. If * element will not be found will throw an exception (PiAtElementNotLoadedException) * - * @param by selector + * @param by + * selector * @return found WebElement object * @throws BFElementNotFoundException * @author */ @Override public WebElement findElementDynamic(By by) throws BFElementNotFoundException { - return driverExtention.findElementDynamic(by); + return driverExtension.findElementDynamic(by); } - + /** * Try to find by dynamic List of elements - will wait given by user an amount of seconds for an element to load on * page. If element will not be found will throw an exception (PiAtElementNotLoadedException) * - * @param by selector - * @param timeOut - maximum time to wait for search WebElement + * @param by + * selector + * @param timeOut + * - maximum time to wait for search WebElement * @return found WebElement object * @author */ @Override public List findElementDynamics(By by, int timeOut) { - return driverExtention.findElementsDynamic(by, timeOut); + return driverExtension.findElementsDynamic(by, timeOut); } - + /** - * Try to find by dynamic List of elements - will wait {@link BasePage.EXPLICITYWAITTIMER} seconds for an element to + * Try to find by dynamic List of elements - will wait {@link BasePage#EXPLICIT_WAIT_TIMER} seconds for an element + * to * load on page. If element will not be found will throw an exception (PiAtElementNotLoadedException) * - * @param by selector + * @param by + * selector * @return found WebElement object * @author */ @Override public List findElementDynamics(By by) { - return driverExtention.findElementsDynamic(by); + return driverExtension.findElementsDynamic(by); } - + @Override public WebElement waitForElement(final By selector) { - return driverExtention.waitForElement(selector); + return driverExtension.waitForElement(selector); } - + @Override public WebElement waitForElementVisible(final By selector) { - return driverExtention.waitForElementVisible(selector); + return driverExtension.waitForElementVisible(selector); } - + /** - * Waits {@link BasePage.EXPLICITYWAITTIMER} seconds until an element will be clickable. If element will not be + * Waits {@link BasePage#EXPLICIT_WAIT_TIMER} seconds until an element will be clickable. If element will not be * clickable then throw an exception (BFElementNotFoundException) * - * @param selector selector + * @param selector + * selector * @return WebElement object ready to click * @throws BFElementNotFoundException * @author */ @Override public WebElement waitUntilElementIsClickable(final By selector) { - return driverExtention.waitUntilElementIsClickable(selector); + return driverExtension.waitUntilElementIsClickable(selector); } - + /** * Try to find element quietly - NoSuchElementException will not be thrown. Use it to check if element exist on page * e.g. PopUp @@ -151,9 +173,9 @@ public WebElement waitUntilElementIsClickable(final By selector) { */ @Override public WebElement findElementQuietly(WebElement elementToSearchIn, By searchedBySelector) { - return driverExtention.findElementQuietly(elementToSearchIn, searchedBySelector); + return driverExtension.findElementQuietly(elementToSearchIn, searchedBySelector); } - + /** * Try to find element quietly - NoSuchElementException will not be thrown. Use it to check if element exist on page * e.g. PopUp @@ -163,132 +185,132 @@ public WebElement findElementQuietly(WebElement elementToSearchIn, By searchedBy */ @Override public WebElement findElementQuietly(By searchedBySelector) { - return driverExtention.findElementQuietly(null, searchedBySelector); + return driverExtension.findElementQuietly(null, searchedBySelector); } - + @Override public void waitForPageLoaded() { - driverExtention.waitForPageLoaded(); - + driverExtension.waitForPageLoaded(); + } - + @Override public Button elementButton(By selector) { - return driverExtention.elementButton(selector); + return driverExtension.elementButton(selector); } - + @Override public RadioButtonElement elementRadioButton(By selector) { - return driverExtention.elementRadioButton(selector); + return driverExtension.elementRadioButton(selector); } - + @Override public RadioButtonElement elementRadioButton(By selector, By inputChildsSelector) { - return driverExtention.elementRadioButton(selector, inputChildsSelector); + return driverExtension.elementRadioButton(selector, inputChildsSelector); } - + @Override public RadioButtonElement elementRadioButton(By selector, By inputChildsSelector, List listSelectedAttributes) { - return driverExtention.elementRadioButton(selector, inputChildsSelector, listSelectedAttributes); + return driverExtension.elementRadioButton(selector, inputChildsSelector, listSelectedAttributes); } - + @Override public InputTextElement elementInputText(By selector) { - return driverExtention.elementInputText(selector); + return driverExtension.elementInputText(selector); } - + @Override public DropdownListElement elementDropdownList(By selector) { - return driverExtention.elementDropdownList(selector); + return driverExtension.elementDropdownList(selector); } - + @Override public ListElements elementList(By selector) { - return driverExtention.elementList(selector); + return driverExtension.elementList(selector); } - + @Override public CheckBox elementCheckbox(By selector) { - return driverExtention.elementCheckbox(selector); + return driverExtension.elementCheckbox(selector); } - + @Override public LabelElement elementLabel(By selector) { - return driverExtention.elementLabel(selector); + return driverExtension.elementLabel(selector); } - + @Override public ImageElement elementImage(By selector) { - return driverExtention.elementImage(selector); + return driverExtension.elementImage(selector); } - + @Override public IFrame elementIFrame(By selector) { - return driverExtention.elementIFrame(selector); + return driverExtension.elementIFrame(selector); } - + @Override public TabElement elementTab(By selector) { - return driverExtention.elementTab(selector); + return driverExtension.elementTab(selector); } - + @Override public TabElement elementTab(By selector, By inputChildsSelector) { - return driverExtention.elementTab(selector, inputChildsSelector); + return driverExtension.elementTab(selector, inputChildsSelector); } - + @Override public TabElement elementTab(By selector, By inputChildsSelector, List listSelectedAttributes) { - return driverExtention.elementTab(selector, inputChildsSelector, listSelectedAttributes); + return driverExtension.elementTab(selector, inputChildsSelector, listSelectedAttributes); } - + @Override public NavigationBarElement elementNavigationBar(By selector) { - return driverExtention.elementNavigationBar(selector); + return driverExtension.elementNavigationBar(selector); } - + @Override public NavigationBarElement elementNavigationBar(By selector, By inputChildsSelector) { - return driverExtention.elementNavigationBar(selector, inputChildsSelector); + return driverExtension.elementNavigationBar(selector, inputChildsSelector); } - + @Override public TooltipElement elementTooltip(By cssSelector) { - return driverExtention.elementTooltip(cssSelector); + return driverExtension.elementTooltip(cssSelector); } - + @Override public MenuElement elementMenu(By selector) { - return driverExtention.elementMenu(selector); + return driverExtension.elementMenu(selector); } - + @Override public MenuElement elementMenu(By selector, By childsSelector) { - return driverExtention.elementMenu(selector, childsSelector); + return driverExtension.elementMenu(selector, childsSelector); } - + @Override public MenuElement elementMenu(By selector, By childsSelector, By subMenuSelector) { - return driverExtention.elementMenu(selector, childsSelector, subMenuSelector); + return driverExtension.elementMenu(selector, childsSelector, subMenuSelector); } - + @Override public MenuElement elementMenu(By selector, By childsSelector, By subMenuSelector, By childsSubMenuSelector) { - return driverExtention.elementMenu(selector, childsSelector, subMenuSelector, childsSubMenuSelector); + return driverExtension.elementMenu(selector, childsSelector, subMenuSelector, childsSubMenuSelector); } - + @Override public HorizontalSliderElement elementHorizontalSlider(final By sliderContainerSelector) { - return driverExtention.elementHorizontalSlider(sliderContainerSelector); + return driverExtension.elementHorizontalSlider(sliderContainerSelector); } - + @Override public HorizontalSliderElement elementHorizontalSlider(final By sliderContainerSelector, final By sliderSelector, final By valueSelector) { - return driverExtention.elementHorizontalSlider(sliderContainerSelector, sliderSelector, valueSelector); + return driverExtension.elementHorizontalSlider(sliderContainerSelector, sliderSelector, valueSelector); } - + @Override public HorizontalSliderElement elementHorizontalSlider(final By sliderContainerSelector, final By sliderSelector, @@ -296,26 +318,26 @@ public HorizontalSliderElement elementHorizontalSlider(final By sliderContainerS final BigDecimal minRange, final BigDecimal maxRange, final BigDecimal step) { - return driverExtention.elementHorizontalSlider(sliderContainerSelector, sliderSelector, valueSelector, minRange, maxRange, step); + return driverExtension.elementHorizontalSlider(sliderContainerSelector, sliderSelector, valueSelector, minRange, maxRange, step); } - + @Override public void mouseRightClick(By selector) { - driverExtention.mouseRightClick(selector); + driverExtension.mouseRightClick(selector); } - + @Override public void mouseLeftClick(By selector) { - driverExtention.mouseLeftClick(selector); + driverExtension.mouseLeftClick(selector); } - + @Override public void mouseLeftClick(WebElement element) { - driverExtention.mouseLeftClick(element); + driverExtension.mouseLeftClick(element); } - + public static void main(String[] args) { BaseTest.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); + .sendMethodEvent(BasePage.ANALYTICS_CATEGORY_NAME); } } \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/NewRemoteWebDriver.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/NewRemoteWebDriver.java index d22eec1e..b8c93768 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/NewRemoteWebDriver.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/NewRemoteWebDriver.java @@ -5,7 +5,6 @@ import java.util.List; import java.util.Map; -import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.*; import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.SessionNotCreatedException; @@ -19,14 +18,28 @@ import com.capgemini.mrchecker.selenium.core.BasePage; import com.capgemini.mrchecker.selenium.core.exceptions.BFElementNotFoundException; import com.capgemini.mrchecker.selenium.core.exceptions.BFInitializationException; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.Button; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.CheckBox; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.DropdownListElement; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.HorizontalSliderElement; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.IFrame; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.ImageElement; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.InputTextElement; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.LabelElement; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.ListElements; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.MenuElement; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.NavigationBarElement; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.RadioButtonElement; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.TabElement; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.TooltipElement; public final class NewRemoteWebDriver extends RemoteWebDriver implements INewWebDriver { - private DriverExtention driverExtention; + private DriverExtension driverExtension; public NewRemoteWebDriver(URL url, DesiredCapabilities capabilities) { super(url, capabilities); - driverExtention = new DriverExtention(this); + driverExtension = new DriverExtension(this); } @Override @@ -57,8 +70,8 @@ protected ExecuteMethod getExecuteMethod() { @Override public List findElements(By by) { BasePage.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); - return DriverExtention.convertWebElementList(super.findElements(by)); + .sendMethodEvent(BasePage.ANALYTICS_CATEGORY_NAME); + return DriverExtension.convertWebElementList(super.findElements(by)); } /** @@ -68,7 +81,7 @@ public List findElements(By by) { @Override public WebElement findElement(By by) throws BFElementNotFoundException { BasePage.getAnalytics() - .sendMethodEvent(BasePage.analitycsCategoryName); + .sendMethodEvent(BasePage.ANALYTICS_CATEGORY_NAME); WebElement elementFromDriver = null; try { elementFromDriver = super.findElement(by); @@ -88,7 +101,7 @@ public WebElement findElement(By by) throws BFElementNotFoundException { */ @Override public WebElement findElementQuietly(WebElement elementToSearchIn, By searchedBySelector) { - return driverExtention.findElementQuietly(elementToSearchIn, searchedBySelector); + return driverExtension.findElementQuietly(elementToSearchIn, searchedBySelector); } /** @@ -100,7 +113,7 @@ public WebElement findElementQuietly(WebElement elementToSearchIn, By searchedBy */ @Override public WebElement findElementQuietly(By searchedBySelector) { - return driverExtention.findElementQuietly(null, searchedBySelector); + return driverExtension.findElementQuietly(null, searchedBySelector); } /** @@ -109,14 +122,14 @@ public WebElement findElementQuietly(By searchedBySelector) { * * @param by * selector - * @param timeout + * @param timeOut * - maximum time to wait for search WebElement * @return found WebElement object * @author * @throws BFElementNotFoundException */ public WebElement findElementDynamic(By by, int timeOut) throws BFElementNotFoundException { - return driverExtention.findElementDynamic(by, timeOut); + return driverExtension.findElementDynamic(by, timeOut); } /** @@ -130,7 +143,7 @@ public WebElement findElementDynamic(By by, int timeOut) throws BFElementNotFoun * @throws BFElementNotFoundException */ public WebElement findElementDynamic(By by) throws BFElementNotFoundException { - return driverExtention.findElementDynamic(by); + return driverExtension.findElementDynamic(by); } /** @@ -139,17 +152,18 @@ public WebElement findElementDynamic(By by) throws BFElementNotFoundException { * * @param by * selector - * @param timeout + * @param timeOut * - maximum time to wait for search WebElement * @return found WebElement object * @author */ public List findElementDynamics(By by, int timeOut) { - return driverExtention.findElementsDynamic(by, timeOut); + return driverExtension.findElementsDynamic(by, timeOut); } /** - * Try to find by dynamic List of elements - will wait {@link BasePage.EXPLICITYWAITTIMER} seconds for an element to + * Try to find by dynamic List of elements - will wait {@link BasePage#EXPLICIT_WAIT_TIMER} seconds for an element + * to * load on page. If element will not be found will throw an exception (PiAtElementNotLoadedException) * * @param by @@ -158,19 +172,19 @@ public List findElementDynamics(By by, int timeOut) { * @author */ public List findElementDynamics(By by) { - return driverExtention.findElementsDynamic(by); + return driverExtension.findElementsDynamic(by); } public WebElement waitForElement(final By selector) { - return driverExtention.waitForElement(selector); + return driverExtension.waitForElement(selector); } public WebElement waitForElementVisible(final By selector) { - return driverExtention.waitForElementVisible(selector); + return driverExtension.waitForElementVisible(selector); } /** - * Waits {@link BasePage.EXPLICITYWAITTIMER} seconds until an element will be clickable. If element will not be + * Waits {@link BasePage#EXPLICIT_WAIT_TIMER seconds until an element will be clickable. If element will not be * clickable then throw an exception (BFElementNotFoundException) * * @param selector @@ -181,152 +195,154 @@ public WebElement waitForElementVisible(final By selector) { */ @Override public WebElement waitUntilElementIsClickable(final By selector) { - return driverExtention.waitUntilElementIsClickable(selector); + return driverExtension.waitUntilElementIsClickable(selector); } @Override public void waitForPageLoaded() { - driverExtention.waitForPageLoaded(); + driverExtension.waitForPageLoaded(); } @Override public Button elementButton(By selector) { - return driverExtention.elementButton(selector); + return driverExtension.elementButton(selector); } @Override public RadioButtonElement elementRadioButton(By selector) { - return driverExtention.elementRadioButton(selector); + return driverExtension.elementRadioButton(selector); } @Override public RadioButtonElement elementRadioButton(By selector, By inputChildsSelector) { - return driverExtention.elementRadioButton(selector, inputChildsSelector); + return driverExtension.elementRadioButton(selector, inputChildsSelector); } @Override public RadioButtonElement elementRadioButton(By selector, - By inputChildsSelector, - List listSelectedAttributes) { - return driverExtention.elementRadioButton(selector, inputChildsSelector, listSelectedAttributes); + By inputChildsSelector, + List listSelectedAttributes) { + return driverExtension.elementRadioButton(selector, inputChildsSelector, listSelectedAttributes); } @Override public InputTextElement elementInputText(By selector) { - return driverExtention.elementInputText(selector); + return driverExtension.elementInputText(selector); } @Override public DropdownListElement elementDropdownList(By selector) { - return driverExtention.elementDropdownList(selector); + return driverExtension.elementDropdownList(selector); } @Override public ListElements elementList(By selector) { - return driverExtention.elementList(selector); + return driverExtension.elementList(selector); } @Override public CheckBox elementCheckbox(By selector) { - return driverExtention.elementCheckbox(selector); + return driverExtension.elementCheckbox(selector); } @Override public LabelElement elementLabel(By selector) { - return driverExtention.elementLabel(selector); + return driverExtension.elementLabel(selector); } - + @Override - public ImageElement elementImage(By selector) { return driverExtention.elementImage(selector); } - + public ImageElement elementImage(By selector) { + return driverExtension.elementImage(selector); + } + @Override public TabElement elementTab(By selector) { - return driverExtention.elementTab(selector); + return driverExtension.elementTab(selector); } @Override public TabElement elementTab(By selector, By inputChildsSelector) { - return driverExtention.elementTab(selector, inputChildsSelector); + return driverExtension.elementTab(selector, inputChildsSelector); } @Override public TabElement elementTab(By selector, By inputChildsSelector, List listSelectedAttributes) { - return driverExtention.elementTab(selector, inputChildsSelector, listSelectedAttributes); + return driverExtension.elementTab(selector, inputChildsSelector, listSelectedAttributes); } @Override public NavigationBarElement elementNavigationBar(By selector) { - return driverExtention.elementNavigationBar(selector); + return driverExtension.elementNavigationBar(selector); } @Override public NavigationBarElement elementNavigationBar(By selector, By inputChildsSelector) { - return driverExtention.elementNavigationBar(selector, inputChildsSelector); + return driverExtension.elementNavigationBar(selector, inputChildsSelector); } @Override public TooltipElement elementTooltip(By cssSelector) { - return driverExtention.elementTooltip(cssSelector); + return driverExtension.elementTooltip(cssSelector); } @Override public MenuElement elementMenu(By selector) { - return driverExtention.elementMenu(selector); + return driverExtension.elementMenu(selector); } @Override public MenuElement elementMenu(By selector, By childsSelector) { - return driverExtention.elementMenu(selector, childsSelector); + return driverExtension.elementMenu(selector, childsSelector); } @Override public MenuElement elementMenu(By selector, By childsSelector, By subMenuSelector) { - return driverExtention.elementMenu(selector, childsSelector, subMenuSelector); + return driverExtension.elementMenu(selector, childsSelector, subMenuSelector); } @Override public MenuElement elementMenu(By selector, By childsSelector, By subMenuSelector, By childsSubMenuSelector) { - return driverExtention.elementMenu(selector, childsSelector, subMenuSelector, childsSubMenuSelector); + return driverExtension.elementMenu(selector, childsSelector, subMenuSelector, childsSubMenuSelector); } @Override public HorizontalSliderElement elementHorizontalSlider(final By sliderContainerSelector) { - return driverExtention.elementHorizontalSlider(sliderContainerSelector); + return driverExtension.elementHorizontalSlider(sliderContainerSelector); } @Override public HorizontalSliderElement elementHorizontalSlider(final By sliderContainerSelector, final By sliderSelector, final By valueSelector) { - return driverExtention.elementHorizontalSlider(sliderContainerSelector, sliderSelector, valueSelector); + return driverExtension.elementHorizontalSlider(sliderContainerSelector, sliderSelector, valueSelector); } @Override public HorizontalSliderElement elementHorizontalSlider(final By sliderContainerSelector, - final By sliderSelector, - final By valueSelector, - final BigDecimal minRange, - final BigDecimal maxRange, - final BigDecimal step) { - return driverExtention.elementHorizontalSlider(sliderContainerSelector, sliderSelector, valueSelector, minRange, maxRange, step); + final By sliderSelector, + final By valueSelector, + final BigDecimal minRange, + final BigDecimal maxRange, + final BigDecimal step) { + return driverExtension.elementHorizontalSlider(sliderContainerSelector, sliderSelector, valueSelector, minRange, maxRange, step); } @Override public IFrame elementIFrame(By selector) { - return driverExtention.elementIFrame(selector); + return driverExtension.elementIFrame(selector); } @Override public void mouseRightClick(By selector) { - driverExtention.mouseRightClick(selector); + driverExtension.mouseRightClick(selector); } @Override public void mouseLeftClick(By selector) { - driverExtention.mouseLeftClick(selector); + driverExtension.mouseLeftClick(selector); } @Override public void mouseLeftClick(WebElement element) { - driverExtention.mouseLeftClick(element); + driverExtension.mouseLeftClick(element); } } \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/BasicElement.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/BasicElement.java index 205053fc..210b39a7 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/BasicElement.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/BasicElement.java @@ -8,14 +8,14 @@ public abstract class BasicElement implements IBasicElement { - private ElementType type; - private By cssSelector; + private final ElementType type; + private By cssSelector; public BasicElement(ElementType type, By cssSelector) { this.type = type; this.setCssSelector(cssSelector); - this.load(); + load(); } @Override @@ -25,14 +25,10 @@ public WebElement load() { @Override public String getElementTypeName() { - return this.type.toString(); + return type.toString(); } public WebElement getElement() throws BFElementNotFoundException { - return getElement(0); - } - - public WebElement getElement(int timeOutInSec) throws BFElementNotFoundException { return BasePage.getDriver() .findElementDynamic(getCssSelector()); } @@ -50,7 +46,7 @@ public String getText() { } public Boolean isDisplayed() { - return BasePage.isElementDisplayed(this.getCssSelector()); + return BasePage.isElementDisplayed(getCssSelector()); } private By getCssSelector() { @@ -60,5 +56,4 @@ private By getCssSelector() { private void setCssSelector(By cssSelector) { this.cssSelector = cssSelector; } - } diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/Button.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/Button.java index 31afc629..5166a4f9 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/Button.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/Button.java @@ -14,5 +14,4 @@ public void click() { ScrollUtils.scrollElementIntoView(getElement()); getElement().click(); } - } diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/CheckBox.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/CheckBox.java index 754621d1..72b514af 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/CheckBox.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/CheckBox.java @@ -1,90 +1,89 @@ package com.capgemini.mrchecker.selenium.core.newDrivers.elementType; +import java.util.Arrays; +import java.util.List; + import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import com.capgemini.mrchecker.selenium.core.exceptions.BFComponentStateException; import com.capgemini.mrchecker.selenium.core.exceptions.BFElementNotFoundException; -import java.util.Arrays; -import java.util.List; - public class CheckBox extends BasicElement { private By inputChildsSelector; - public CheckBox(By cssSelector) /** * @param cssSelector * - selector of CheckBox element's set **/ - { + public CheckBox(By cssSelector) { this(cssSelector, By.cssSelector("input")); } + /** + * @param cssSelector + * - selector of CheckBox element's set + * @param inputChildsSelector + * - selector of relative path from CheckBox element's set to basic input element + **/ public CheckBox(By cssSelector, By inputChildsSelector) { - /** - * @param cssSelector - * - selector of CheckBox element's set - * @param inputChildsSelector - * - selector of relative path from CheckBox element's set to basic input element - **/ super(ElementType.CHECKBOX, cssSelector); setInputChildsSelector(inputChildsSelector); } public void setCheckBoxByIndex(int index) { - this.setCheckBoxByIndexTo(index, true); + setCheckBoxByIndexTo(index, true); } public void setCheckBoxByValue(String value) { - this.setCheckBoxByValueTo(value, true); + setCheckBoxByValueTo(value, true); } public void setCheckBoxByText(String text) { - this.setCheckBoxByTextTo(text, true); + setCheckBoxByTextTo(text, true); } public void unsetCheckBoxByIndex(int index) { - this.setCheckBoxByIndexTo(index, false); + setCheckBoxByIndexTo(index, false); } public void unsetCheckBoxByValue(String value) { - this.setCheckBoxByValueTo(value, false); + setCheckBoxByValueTo(value, false); } public void unsetCheckBoxByText(String text) { - this.setCheckBoxByTextTo(text, false); + setCheckBoxByTextTo(text, false); } public void setAllCheckBoxes() { - this.setAllCheckBoxesTo(true); + setAllCheckBoxesTo(true); } public void unsetAllCheckBoxes() { - this.setAllCheckBoxesTo(false); + setAllCheckBoxesTo(false); } public boolean isCheckBoxSetByIndex(int index) { - return this.getCheckBoxesList() + return getCheckBoxesList() .get(index) .isSelected(); } public boolean isCheckBoxSetByValue(String value) { - return this.getCheckBoxesList() - .get(this.getCheckBoxIndexByValue(value)) + return getCheckBoxesList() + .get(getCheckBoxIndexByValue(value)) .isSelected(); } public boolean isCheckBoxSetByText(String text) { - return this.getCheckBoxesList() - .get(this.getCheckBoxIndexByText(text)) + return getCheckBoxesList() + .get(getCheckBoxIndexByText(text)) .isSelected(); } public boolean isAllCheckboxesSet() { - return this.isAllCheckBoxesSetTo(true); + return isAllCheckBoxesSetTo(true); } public List getTextList() { @@ -92,20 +91,20 @@ public List getTextList() { } private List getCheckBoxesList() { - return this.getElement() + return getElement() .findElements(inputChildsSelector); } private void setCheckBoxByIndexTo(int index, boolean destination) { - if (this.getCheckBoxesList() + if (getCheckBoxesList() .get(index) .isSelected() != destination) { - this.getCheckBoxesList() + getCheckBoxesList() .get(index) .click(); } - boolean currentState = this.getCheckBoxesList() + boolean currentState = getCheckBoxesList() .get(index) .isSelected(); if (currentState != destination) { @@ -115,15 +114,15 @@ private void setCheckBoxByIndexTo(int index, boolean destination) { } private void setCheckBoxByValueTo(String value, boolean destination) { - this.setCheckBoxToByAttribute(value, "value", destination); + setCheckBoxToByAttribute(value, destination); } private void setCheckBoxByTextTo(String text, boolean destination) { - this.setCheckBoxByIndexTo(this.getCheckBoxIndexByText(text), destination); + setCheckBoxByIndexTo(getCheckBoxIndexByText(text), destination); } private int getCheckBoxIndexByText(String text) { - List textsList = this.getTextList(); + List textsList = getTextList(); for (int i = 0; i < textsList.size(); i++) { if (textsList.get(i) .equals(text.trim())) { @@ -134,7 +133,7 @@ private int getCheckBoxIndexByText(String text) { } private int getCheckBoxIndexByValue(String value) { - List checkBoxesList = this.getCheckBoxesList(); + List checkBoxesList = getCheckBoxesList(); for (int i = 0; i < checkBoxesList.size(); i++) { if (checkBoxesList.get(i) .getAttribute("value") @@ -145,12 +144,12 @@ private int getCheckBoxIndexByValue(String value) { throw new BFElementNotFoundException("Checkbox with value " + value + " wasn't found."); } - private void setCheckBoxToByAttribute(String value, String attribute, boolean destination) { - List checkboxesList = this.getCheckBoxesList(); + private void setCheckBoxToByAttribute(String value, boolean destination) { + List checkboxesList = getCheckBoxesList(); WebElement currentElement; - for (int i = 0; i < checkboxesList.size(); i++) { - currentElement = checkboxesList.get(i); - if (currentElement.getAttribute(attribute) + for (WebElement webElement : checkboxesList) { + currentElement = webElement; + if (currentElement.getAttribute("value") .equals(value) && currentElement.isSelected() != destination) { currentElement.click(); } @@ -158,25 +157,25 @@ private void setCheckBoxToByAttribute(String value, String attribute, boolean de } private void setAllCheckBoxesTo(boolean destination) { - List checkboxesList = this.getCheckBoxesList(); - for (int i = 0; i < checkboxesList.size(); i++) { - if (checkboxesList.get(i) + List checkboxesList = getCheckBoxesList(); + for (WebElement webElement : checkboxesList) { + if (webElement .isSelected() != destination) { - checkboxesList.get(i) + webElement .click(); } } - if (!this.isAllCheckBoxesSetTo(destination)) { + if (!isAllCheckBoxesSetTo(destination)) { throw new BFComponentStateException(ElementType.CHECKBOX.toString(), "set/unset", - "setting to " + String.valueOf(destination)); + "setting to " + destination); } } private boolean isAllCheckBoxesSetTo(boolean destination) { - List checkboxesList = this.getCheckBoxesList(); - for (int i = 0; i < checkboxesList.size(); i++) { - if (checkboxesList.get(i) + List checkboxesList = getCheckBoxesList(); + for (WebElement webElement : checkboxesList) { + if (webElement .isSelected() != destination) { return false; } @@ -185,6 +184,6 @@ private boolean isAllCheckBoxesSetTo(boolean destination) { } private void setInputChildsSelector(By selector) { - this.inputChildsSelector = selector; + inputChildsSelector = selector; } } \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/DropdownListElement.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/DropdownListElement.java index c4d2a695..0e1e0f47 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/DropdownListElement.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/DropdownListElement.java @@ -16,32 +16,32 @@ public DropdownListElement(By cssSelector) { } public void selectDropdownByIndex(int index) { - this.getObject() + getObject() .selectByIndex(index); - List list = this.getObject() + List list = getObject() .getOptions(); if (!list.get(index) .isSelected()) { throw new BFComponentStateException(ElementType.DROPDOWN.toString(), "select", "Option with index: " - + String.valueOf(index) + " should be set from in " + this.getObject() + + index + " should be set from in " + getObject() .toString()); } } public boolean isDropdownElementSelectedByIndex(int index) { - return this.getPossibleOptions() + return getPossibleOptions() .get(index) .isSelected(); } public void selectDropdownByValue(String value) { - value.trim(); - this.getObject() + value = value.trim(); + getObject() .selectByValue(value); - if (!this.isDropdownElementSelectedByValue(value)) { + if (!isDropdownElementSelectedByValue(value)) { throw new BFComponentStateException(ElementType.DROPDOWN.toString(), "select", "Option with value: " - + String.valueOf(value) + " should be set from in " + this.getObject() + + value + " should be set from in " + getObject() .toString()); } } @@ -49,74 +49,74 @@ public void selectDropdownByValue(String value) { public void selectDropdownByVisibleText(String value) { boolean flag = false; - this.getObject() + getObject() .selectByVisibleText(value); - List list = this.getAllSelectedOptionsText(); - for (int i = 0; i < list.size(); i++) { - if (list.get(i) - .equals(value)) + List list = getAllSelectedOptionsText(); + for (String s : list) { + if (s.equals(value)) { flag = true; + break; + } } if (!flag) { throw new RuntimeException( - "Option with text: " + value + " wasn't selected in " + this.getObject() + "Option with text: " + value + " wasn't selected in " + getObject() .toString()); } } public List getAllSelectedOptionsText() { - List list = this.getObject() + List list = getObject() .getAllSelectedOptions(); - return this.getValuesFromWebElements(list); + return getValuesFromWebElements(list); } public String getFirstSelectedOptionText() { - String output = this.getObject() + return getObject() .getFirstSelectedOption() .getText() .trim(); - return output; } public int getAmountOfPossibleValues() { - List list = this.getObject() + List list = getObject() .getOptions(); return list.size(); } public boolean isDropdownElementSelectedByValue(String value) { - int index = this.getIndexDropdownElementByValue(value); - return this.getPossibleOptions() + int index = getIndexDropdownElementByValue(value); + return getPossibleOptions() .get(index) .isSelected(); } private List getPossibleOptions() { - return this.getObject() + return getObject() .getOptions(); } private List getPossibleValuesText() { - List list = this.getObject() + List list = getObject() .getOptions(); - return this.getValuesFromWebElements(list); + return getValuesFromWebElements(list); } private int getIndexDropdownElementByValue(String value) { - return this.getPossibleValuesText() + return getPossibleValuesText() .indexOf(value); } private Select getObject() { - return new Select(this.getElement()); + return new Select(getElement()); } private List getValuesFromWebElements(List list) { - List output = new ArrayList(); - for (int i = 0; i < list.size(); i++) { - output.add(list.get(i) + List output = new ArrayList<>(); + for (WebElement webElement : list) { + output.add(webElement .getText() .trim()); } diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/ElementType.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/ElementType.java index 5e1bbee2..a60addb8 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/ElementType.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/ElementType.java @@ -17,9 +17,9 @@ enum ElementType { HORIZONTAL_SLIDER("Horizontal Slider"), IMAGE("Image"); - private String value; + private final String value; - private ElementType(String value) { + ElementType(String value) { this.value = value; } diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/HorizontalSliderElement.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/HorizontalSliderElement.java index 2499afa7..a97613ae 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/HorizontalSliderElement.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/HorizontalSliderElement.java @@ -52,12 +52,12 @@ public HorizontalSliderElement(By sliderContainerSelector, By sliderSelector, By * * @return BigDecimal representing position's value. * @throws NumberFormatException + * e */ public BigDecimal getCurrentSliderValue() throws NumberFormatException { - @SuppressWarnings("deprecation") WebElement currentValueElement = this.getElement() - .findElement(this.valueSelector); + .findElement(this.valueSelector); String value = currentValueElement.getText(); if (value == null || value.isEmpty()) { value = getValueAttributeOfWebElement(currentValueElement); @@ -96,7 +96,7 @@ public BigDecimal getMaxRange() { /** * Sets the highest possible value of horizontal slider's position. * - * @param minRange + * @param maxRange * BigDecimal */ public void setMaxRange(BigDecimal maxRange) { @@ -140,8 +140,8 @@ public int getMaxNumberOfSteps() { */ public Dimension getDimensions() { return this.getElement() - .findElement(sliderSelector) - .getSize(); + .findElement(sliderSelector) + .getSize(); } /** @@ -161,7 +161,7 @@ public Integer getWidth() { public BigDecimal getStepWidth() { BigDecimal rangeDiff = maxRange.subtract(minRange); BigDecimal numberOfSteps = rangeDiff.setScale(1) - .divide(step.setScale(1)); + .divide(step.setScale(1)); return new BigDecimal(getWidth()).divide(numberOfSteps); } @@ -191,7 +191,7 @@ public void setSliderPositionTo(BigDecimal position, int method) { String message = "Chosen method doesn't exist."; int counter = 0; BasePage.getDriver() - .mouseLeftClick(getElement().findElement(sliderSelector)); + .mouseLeftClick(getElement().findElement(sliderSelector)); position = verifyAndCorrectPositionValue(position); while (position.compareTo(getCurrentSliderValue()) != 0 || counter > getMaxNumberOfSteps()) { if (position.compareTo(getCurrentSliderValue()) > 0) { @@ -246,10 +246,10 @@ public void setSliderPositionTo(BigDecimal position, int method) { * @see BigDecimal */ public BigDecimal verifyAndCorrectPositionValue(BigDecimal position) { - if (position.compareTo(getMinRange()) == -1) { + if (position.compareTo(getMinRange()) < 0) { BFLogger.logInfo("Position value: " + position + " will be set to minimum value: " + getMinRange()); position = getMinRange(); - } else if (position.compareTo(getMaxRange()) == 1) { + } else if (position.compareTo(getMaxRange()) > 0) { BFLogger.logInfo("Position value: " + position + " will be set to maximum value: " + getMaxRange()); position = getMaxRange(); } @@ -283,28 +283,28 @@ private String getValueAttributeOfWebElement(WebElement element) { private int calculateMaxNumberOfSteps() { return getMaxRange().subtract(getMinRange()) - .divide(getStep()) - .intValueExact(); + .divide(getStep()) + .intValueExact(); } private void performKeypress(CharSequence key) { BasePage.getAction() - .sendKeys(key) - .build() - .perform(); + .sendKeys(key) + .build() + .perform(); } private void performMouseMove(int side) { int offset = getStepWidth() - .intValue(); + .intValue(); if (side == MOUSE_MOVE_LEFT) offset = -offset; BasePage.getAction() - .clickAndHold() - .moveByOffset(offset, 0) - .release() - .build() - .perform(); + .clickAndHold() + .moveByOffset(offset, 0) + .release() + .build() + .perform(); } } diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/IBasicElement.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/IBasicElement.java index 1a12623f..cae31f59 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/IBasicElement.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/IBasicElement.java @@ -7,5 +7,4 @@ public interface IBasicElement { String getElementTypeName(); WebElement load(); - } diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/IFrame.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/IFrame.java index 52554d55..597490c3 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/IFrame.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/IFrame.java @@ -7,11 +7,8 @@ public class IFrame extends BasicElement implements IBasicElement { - private By cssSelector; - public IFrame(By cssSelector) { super(ElementType.IFRAME, cssSelector); - this.cssSelector = cssSelector; BasePage.getDriver() .switchTo() diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/ListElements.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/ListElements.java index 98eb4b00..b1cd7308 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/ListElements.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/ListElements.java @@ -10,7 +10,7 @@ public class ListElements extends BasicElement implements IBasicElement { - private By cssSelector; + private final By cssSelector; public ListElements(By cssSelector) { super(ElementType.LIST, cssSelector); @@ -19,20 +19,20 @@ public ListElements(By cssSelector) { public Integer getSize() { return BasePage.getDriver() - .findElementDynamics(this.cssSelector) - .size(); + .findElementDynamics(cssSelector) + .size(); } public List getList() { return BasePage.getDriver() - .findElementDynamics(this.cssSelector); + .findElementDynamics(cssSelector); } public List getTextList() { - return this.getList() - .stream() - .map(element -> element.getText()) - .collect(Collectors.toList()); + return getList() + .stream() + .map(WebElement::getText) + .collect(Collectors.toList()); } } diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/MenuElement.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/MenuElement.java index ef15e718..d739fb4d 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/MenuElement.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/MenuElement.java @@ -1,5 +1,8 @@ package com.capgemini.mrchecker.selenium.core.newDrivers.elementType; +import java.util.Arrays; +import java.util.List; + import org.openqa.selenium.By; import org.openqa.selenium.WebElement; @@ -7,17 +10,14 @@ import com.capgemini.mrchecker.selenium.core.exceptions.BFElementNotFoundException; import com.capgemini.mrchecker.test.core.exceptions.BFInputDataException; -import java.util.Arrays; -import java.util.List; - /** * Created by LKURZAJ on 08.03.2017. */ public class MenuElement extends BasicElement { - private By childsSelector; - private By subMenuSelector; - private By childsSubMenuSelector; + private final By childsSelector; + private final By subMenuSelector; + private final By childsSubMenuSelector; public MenuElement(By cssSelector) { this(cssSelector, By.cssSelector("li")); @@ -39,12 +39,12 @@ public MenuElement(By cssSelector, By childsSelector, By subMenuSelector, By chi } public void selectItemByIndex(int index) { - this.getItemByIndex(index) + getItemByIndex(index) .click(); } public void selectItemByText(String text) { - this.getItemByText(text) + getItemByText(text) .click(); } @@ -57,30 +57,30 @@ public String getItemLinkByText(String text) { } public List getItemsTextList() { - return Arrays.asList(this.getText() + return Arrays.asList(getText() .split("\n")); } public void selectSubMenuItemByText(String itemText, String subItemText) { - this.getSubItemByText(itemText, subItemText) + getSubItemByText(itemText, subItemText) .click(); } public void selectSubMenuItemByIndex(int itemIndex, int subItemIndex) { - this.getSubItemByIndex(itemIndex, subItemIndex) + getSubItemByIndex(itemIndex, subItemIndex) .click(); } public String getSubMenuItemLinkByText(String itemText, String subItemText) { - return getLinkItemFromWebElement(this.getSubItemByText(itemText, subItemText)).getAttribute("href"); + return getLinkItemFromWebElement(getSubItemByText(itemText, subItemText)).getAttribute("href"); } public String getSubMenuItemLinkByIndex(int itemIndex, int subItemIndex) { - return getLinkItemFromWebElement(this.getSubItemByIndex(itemIndex, subItemIndex)).getAttribute("href"); + return getLinkItemFromWebElement(getSubItemByIndex(itemIndex, subItemIndex)).getAttribute("href"); } public int getItemsCount() { - return this.getItems() + return getItems() .size(); } @@ -90,7 +90,7 @@ private void clickMenuItemAndWaitForSubMenuVisible(WebElement menuItem) { .moveToElement(menuItem) .perform(); BasePage.getDriver() - .waitForElementVisible(this.subMenuSelector); + .waitForElementVisible(subMenuSelector); } private WebElement getLinkItemFromWebElement(WebElement webElement) { @@ -99,52 +99,52 @@ private WebElement getLinkItemFromWebElement(WebElement webElement) { } private WebElement getSubItemByIndex(int itemIndex, int subItemIndex) { - WebElement elem = this.getItemByIndex(itemIndex); - this.clickMenuItemAndWaitForSubMenuVisible(elem); - return this.getElementByIndex(this.getItemSubItems(elem), subItemIndex); + WebElement elem = getItemByIndex(itemIndex); + clickMenuItemAndWaitForSubMenuVisible(elem); + return getElementByIndex(getItemSubItems(elem), subItemIndex); } private WebElement getSubItemByText(String itemText, String subItemText) { WebElement webElement = getItemByText(itemText); - this.clickMenuItemAndWaitForSubMenuVisible(webElement); - return this.getElementByText(this.getItemSubItems(webElement), subItemText); + clickMenuItemAndWaitForSubMenuVisible(webElement); + return getElementByText(getItemSubItems(webElement), subItemText); } private List getItemSubItems(WebElement webElement) { - return webElement.findElements(this.childsSubMenuSelector); + return webElement.findElements(childsSubMenuSelector); } private List getItemSubItemsByText(WebElement webElement) { - this.clickMenuItemAndWaitForSubMenuVisible(webElement); - return this.getItemSubItems(webElement); + clickMenuItemAndWaitForSubMenuVisible(webElement); + return getItemSubItems(webElement); } private WebElement getItemByText(String text) { - return getElementByText(this.getItems(), text); + return getElementByText(getItems(), text); } private WebElement getItemByIndex(int index) { - return this.getElementByIndex(this.getItems(), index); + return getElementByIndex(getItems(), index); } private List getItems() { - return this.getElement() - .findElements(this.childsSelector); + return getElement() + .findElements(childsSelector); } private WebElement getElementByIndex(List listElements, int index) { if (index < 0 || index >= listElements.size()) { - throw new BFInputDataException("Index out of range: 0 - " + String.valueOf(listElements.size() - 1)); + throw new BFInputDataException("Index out of range: 0 - " + (listElements.size() - 1)); } return listElements.get(index); } private WebElement getElementByText(List listElements, String text) { - for (int i = 0; i < listElements.size(); i++) { - if (listElements.get(i) + for (WebElement listElement : listElements) { + if (listElement .getText() .equals(text)) { - return listElements.get(i); + return listElement; } } throw new BFElementNotFoundException("Item with text: " + text + " not found in " + listElements.toString()); diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/NavigationBarElement.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/NavigationBarElement.java index b9298684..cb88402d 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/NavigationBarElement.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/NavigationBarElement.java @@ -1,115 +1,115 @@ package com.capgemini.mrchecker.selenium.core.newDrivers.elementType; +import java.util.ArrayList; +import java.util.List; + import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import com.capgemini.mrchecker.selenium.core.exceptions.BFElementNotFoundException; import com.capgemini.mrchecker.test.core.exceptions.BFInputDataException; -import java.util.ArrayList; -import java.util.List; - /** * Created by LKURZAJ on 07.03.2017. */ public class NavigationBarElement extends BasicElement { - private By inputChildsSelector; + private final By inputChildsSelector; + /** + * @param cssSelector + * - selector of Navigation Bar element's set + **/ public NavigationBarElement(By cssSelector) { - /** - * @param cssSelector - * - selector of Navigation Bar element's set - **/ this(cssSelector, By.cssSelector("li")); } + /** + * @param cssSelector + * - selector of Navigation Bar element's set + **/ public NavigationBarElement(By cssSelector, By inputChildsSelector) { - /** - * @param cssSelector - * - selector of Navigation Bar element's set - **/ super(ElementType.NAVIGATION_BAR, cssSelector); this.inputChildsSelector = inputChildsSelector; } public List getItemsTextList() { - List listElems = this.getItems(); + List listElems = getItems(); List out = new ArrayList<>(); - for (int i = 0; i < listElems.size(); i++) { - out.add(listElems.get(i) + for (WebElement listElem : listElems) { + out.add(listElem .getText()); } return out; } public String getFirstItemText() { - return this.getItemsTextList() + return getItemsTextList() .get(0); } public String getActiveItemText() { - List listItems = this.getItems(); - for (int i = 0; i < listItems.size(); i++) { - if (listItems.get(i) + List listItems = getItems(); + for (WebElement listItem : listItems) { + if (listItem .getAttribute("class") .contains("active")) { - return listItems.get(i) + return listItem .getText(); } } - throw new BFElementNotFoundException("Any active item was found in " + this.getElement() + throw new BFElementNotFoundException("Any active item was found in " + getElement() .toString()); } public void clickFirstItem() { - this.getItems() + getItems() .get(0) .click(); } public void clickActiveItem() { - this.getItems() - .get(this.getDepth() - 1) + getItems() + .get(getDepth() - 1) .click(); } public void clickItemByIndex(int index) { - if (index > 0 && index >= this.getItems() + if (index > 0 && index >= getItems() .size()) { - throw new BFInputDataException("Index " + String.valueOf(index) + " larger than list's size: " - + String.valueOf(this.getItems() - .size())); + throw new BFInputDataException("Index " + index + " larger than list's size: " + + getItems() + .size()); } - this.getItems() + getItems() .get(index) .click(); } public void clickItemByText(String text) { - for (int i = 0; i < this.getItems() + for (int i = 0; i < getItems() .size(); i++) { - if (this.getItems() + if (getItems() .get(i) .getText() .equals(text)) { - this.getItems() + getItems() .get(i) .click(); return; } } - throw new BFElementNotFoundException("Item with text: " + text + " wasn't found in " + this.getText()); + throw new BFElementNotFoundException("Item with text: " + text + " wasn't found in " + getText()); } public int getDepth() { - return this.getItems() + return getItems() .size(); } private List getItems() { - return this.getElement() - .findElements(this.inputChildsSelector); + return getElement() + .findElements(inputChildsSelector); } } diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/RadioButtonElement.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/RadioButtonElement.java index adaa8ee6..31e6c7b9 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/RadioButtonElement.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/RadioButtonElement.java @@ -1,6 +1,7 @@ package com.capgemini.mrchecker.selenium.core.newDrivers.elementType; import java.util.Arrays; +import java.util.Collections; import java.util.List; import org.openqa.selenium.By; @@ -10,59 +11,58 @@ public class RadioButtonElement extends BasicElement implements IBasicElement { - private By inputChildsSelector; - private List listElements; - private List listSelectedAttributes; + private By inputChildsSelector; + private List listElements; + private List listSelectedAttributes; - public RadioButtonElement(By cssSelector) /** * @param cssSelector * - selector of Radio Button element's set **/ - { - this(cssSelector, By.cssSelector("input"), Arrays.asList("selected")); + public RadioButtonElement(By cssSelector) { + this(cssSelector, By.cssSelector("input"), Collections.singletonList("selected")); } + /** + * @param cssSelector + * - selector of Radio Button element's set + * @param inputChildsSelector + * - selector of relative path from Radio Button element's set to basic input element + **/ public RadioButtonElement(By cssSelector, By inputChildsSelector) { - /** - * @param cssSelector - * - selector of Radio Button element's set - * @param inputChildsSelector - * - selector of relative path from Radio Button element's set to basic input element - **/ - this(ElementType.INPUT_TEXT, cssSelector, inputChildsSelector, Arrays.asList("selected")); + this(ElementType.INPUT_TEXT, cssSelector, inputChildsSelector, Collections.singletonList("selected")); } + /** + * @param cssSelector + * - selector of Radio Button element's set + * @param inputChildsSelector + * - selector of relative path from Radio Button element's set to basic input element + * @param listSelectedAttributes + * - list of class name describing selected item + **/ public RadioButtonElement(By cssSelector, By inputChildsSelector, List listSelectedAttributes) { - /** - * @param cssSelector - * - selector of Radio Button element's set - * @param inputChildsSelector - * - selector of relative path from Radio Button element's set to basic input element - * @param listSelectedAttributes - * - list of class name describing selected item - **/ this(ElementType.INPUT_TEXT, cssSelector, inputChildsSelector, listSelectedAttributes); } + /** + * @param cssSelector + * - selector of Radio Button element's set + * @param inputChildsSelector + * - selector of relative path from Radio Button element's set to basic input element + * @param listSelectedAttributes + * - list of class name describing selected item + **/ protected RadioButtonElement(ElementType elemType, By cssSelector, By inputChildsSelector, List listSelectedAttributes) { - /** - * @param cssSelector - * - selector of Radio Button element's set - * @param inputChildsSelector - * - selector of relative path from Radio Button element's set to basic input element - * @param listSelectedAttributes - * - list of class name describing selected item - **/ super(elemType, cssSelector); setInputChildsSelector(inputChildsSelector); setSelectedAttributes(listSelectedAttributes); } public int getSelectedItemIndex() { - this.setItems(); - return this.listElements.indexOf(getSelectedItem()); + setItems(); + return listElements.indexOf(getSelectedItem()); } public String getSelectedItemText() { @@ -74,61 +74,61 @@ public String getSelectedItemValue() { } public List getTextList() { - return Arrays.asList(this.getTextArray()); + return Arrays.asList(getTextArray()); } public int getItemsCount() { - this.setItems(); - return this.listElements.size(); + setItems(); + return listElements.size(); } public boolean isItemSelectedByText(String elementText) { - return this.getSelectedItemText() + return getSelectedItemText() .equals(elementText); } public boolean isItemSelectedByIndex(int elementIndex) { - return this.getSelectedItemIndex() == elementIndex; + return getSelectedItemIndex() == elementIndex; } public boolean isItemSelectedByValue(String elementValue) { - return this.getSelectedItemValue() + return getSelectedItemValue() .equals(elementValue); } public void selectItemByText(String elementText) { - WebElement elementToClick = this.getItemByText(elementText); + WebElement elementToClick = getItemByText(elementText); elementToClick.click(); - this.checkIsItemClicked(elementToClick); + checkIsItemClicked(elementToClick); } public void selectItemByIndex(int elementIndex) { - WebElement elementToClick = this.getItemByIndex(elementIndex); + WebElement elementToClick = getItemByIndex(elementIndex); elementToClick.click(); - this.checkIsItemClicked(elementToClick); + checkIsItemClicked(elementToClick); } public void selectItemByValue(String elementValue) { - WebElement elementToClick = this.getItemByValue(elementValue); + WebElement elementToClick = getItemByValue(elementValue); elementToClick.click(); - this.checkIsItemClicked(elementToClick); + checkIsItemClicked(elementToClick); } private void checkIsItemClicked(WebElement element) { - if (this.isItemSelected(element)) { - System.out.println(getElementTypeName() + ": " + this.toString() + " isn't clicked."); + if (isItemSelected(element)) { + System.out.println(getElementTypeName() + ": " + toString() + " isn't clicked."); } } private String[] getTextArray() { - return this.getElement() + return getElement() .getText() .trim() .split("\n"); } private void setInputChildsSelector(By selector) { - this.inputChildsSelector = selector; + inputChildsSelector = selector; } private void setSelectedAttributes(List listSelectedAttributes) { @@ -144,50 +144,48 @@ private boolean isItemSelected(WebElement el) { } private void setItems() { - setListItems(this.getElement() + setListItems(getElement() .findElements(inputChildsSelector)); } private WebElement getItemByIndex(int index) { - this.setItems(); + setItems(); - if (this.listElements.isEmpty()) { + if (listElements.isEmpty()) { throw new BFElementNotFoundException("Any " + getElementTypeName() + " element was found."); } - return this.listElements.get(index); + return listElements.get(index); } private WebElement getItemByText(String visibleText) { - for (int i = 0; i < this.getItemsCount(); i++) { - if (this.listElements.get(i) + for (int i = 0; i < getItemsCount(); i++) { + if (listElements.get(i) .getText() .equals(visibleText)) { - return this.listElements.get(i); + return listElements.get(i); } } throw new BFElementNotFoundException(getElementTypeName() + " with text: " + visibleText + " wasn't found in " - + this.getTextArray() - .toString()); + + Arrays.toString(getTextArray())); } private WebElement getItemByValue(String value) { - this.setItems(); - for (int i = 0; i < this.getItemsCount(); i++) { - if (this.listElements.get(i) + setItems(); + for (int i = 0; i < getItemsCount(); i++) { + if (listElements.get(i) .getAttribute("value") .equals(value)) { - return this.listElements.get(i); + return listElements.get(i); } } throw new BFElementNotFoundException( - getElementTypeName() + " with value: " + value + " wasn't found in " + this.getTextArray() - .toString()); + getElementTypeName() + " with value: " + value + " wasn't found in " + Arrays.toString(getTextArray())); } private boolean isClassContainSelectionAttributes(String classAttribute) { - for (int i = 0; i < this.listSelectedAttributes.size(); i++) { - if (classAttribute.contains(this.listSelectedAttributes.get(i))) { + for (String listSelectedAttribute : listSelectedAttributes) { + if (classAttribute.contains(listSelectedAttribute)) { return true; } } @@ -195,15 +193,14 @@ private boolean isClassContainSelectionAttributes(String classAttribute) { } private WebElement getSelectedItem() { - this.setItems(); - for (int i = 0; i < this.listElements.size(); i++) { - if (this.isItemSelected(this.listElements.get(i)) - || isClassContainSelectionAttributes(this.listElements.get(i) + setItems(); + for (WebElement listElement : listElements) { + if (isItemSelected(listElement) + || isClassContainSelectionAttributes(listElement .getAttribute("class"))) { - return this.listElements.get(i); + return listElement; } } - throw new BFElementNotFoundException("Any element is selected in " + this.getTextArray() - .toString()); + throw new BFElementNotFoundException("Any element is selected in " + Arrays.toString(getTextArray())); } } \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/TabElement.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/TabElement.java index 6be24169..7ce8cb02 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/TabElement.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/newDrivers/elementType/TabElement.java @@ -1,43 +1,42 @@ package com.capgemini.mrchecker.selenium.core.newDrivers.elementType; -import org.openqa.selenium.By; - -import java.util.Arrays; +import java.util.Collections; import java.util.List; +import org.openqa.selenium.By; + /** * Created by LKURZAJ on 06.03.2017. */ public class TabElement extends RadioButtonElement implements IBasicElement { - public TabElement(By cssSelector) /** * @param cssSelector * - selector of Tab element's set **/ - { + public TabElement(By cssSelector) { this(cssSelector, By.cssSelector("li")); } + /** + * @param cssSelector + * - selector of Tab element's set + * @param inputChildsSelector + * - selector of relative path from Tab element's set to basic input element + **/ public TabElement(By cssSelector, By inputChildsSelector) { - /** - * @param cssSelector - * - selector of Tab element's set - * @param inputChildsSelector - * - selector of relative path from Tab element's set to basic input element - **/ - super(ElementType.TAB, cssSelector, inputChildsSelector, Arrays.asList("ui-tabs-active ui-state-active")); + super(ElementType.TAB, cssSelector, inputChildsSelector, Collections.singletonList("ui-tabs-active ui-state-active")); } + /** + * @param cssSelector + * - selector of Tab element's set + * @param inputChildsSelector + * - selector of relative path from Tab element's set to basic input element + * @param listSelectedAttributes + * - list of class name describing selected item + **/ public TabElement(By cssSelector, By inputChildsSelector, List listSelectedAttributes) { - /** - * @param cssSelector - * - selector of Tab element's set - * @param inputChildsSelector - * - selector of relative path from Tab element's set to basic input element - * @param listSelectedAttributes - * - list of class name describing selected item - **/ super(ElementType.TAB, cssSelector, inputChildsSelector, listSelectedAttributes); } } diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/utils/ColorsUtils.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/utils/ColorsUtils.java index f0d10631..15bc199b 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/utils/ColorsUtils.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/utils/ColorsUtils.java @@ -15,14 +15,10 @@ private ColorsUtils() { * @param color * from ColorsEnum * @return True if element text is displayed in black, false otherwise - * @author */ public static boolean isElementTextInGivenColor(WebElement element, ColorsEnum color) { String elementColor = element.getCssValue("color"); - if (elementColor == null || !elementColor.contains(color.toString())) { - return false; - } - return true; + return elementColor != null && elementColor.contains(color.toString()); } /** @@ -31,7 +27,6 @@ public static boolean isElementTextInGivenColor(WebElement element, ColorsEnum c * @param validator * - IColorValidator * @return True if element has correct color coresponding to IColorValidator, false otherwise - * @author */ public static boolean isColorCorrectForValue(WebElement element, IColorValidator validator) { return validator.isValid(element); diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/utils/DateUtils.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/utils/DateUtils.java index 33ffbbba..8c5fef50 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/utils/DateUtils.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/utils/DateUtils.java @@ -15,8 +15,6 @@ /** * This class contains utility functions related to date (matching, conversion etc.). - * - * @author */ public class DateUtils { @@ -28,15 +26,15 @@ private DateUtils() { // MM/DD/YYYY regexp public static final String DATE_REGEX = "(0?[1-9]|1[012])/(0?[1-9]|[12][0-9]|3[01])/((19|20)\\d\\d)"; // timestamp with 'AS OF' prefix regexp: AS OF MM/DD/YYYY HH:MM A/PM ET - public static final String AS_OF_TIMESTAMPT_REGEX = "(AS OF )" + DateUtils.DATE_REGEX + " " + public static final String AS_OF_TIMESTAMPT_REGEX = "(AS OF )" + DateUtils.DATE_REGEX + " " + DateUtils.TIME_12H_REGEX + "( ET)"; - public static final String COMMON_DATE_REGEX = "\\d{2}/\\d{2}/\\d{4}"; - public static final String US_DATE_FORMAT = "MM/dd/yyyy"; - public static final String[] MOTHS = new String[] { "January", "February", "March", "April", "May", "June", "July", - "August", "September", "October", "November", "December" }; + public static final String COMMON_DATE_REGEX = "\\d{2}/\\d{2}/\\d{4}"; + public static final String US_DATE_FORMAT = "MM/dd/yyyy"; + public static final String[] MOTHS = new String[] { "January", "February", "March", "April", "May", "June", "July", + "August", "September", "October", "November", "December" }; - private static final String HTTP_RESPONSE_DATE_REGEX = "(\\w+,\\s\\d{1,2}\\s\\w+\\s\\d{4}\\s\\d{2}:\\d{2}:\\d{2}\\s\\w{2,6})"; - private static final String HTTP_RESPONSE_DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss zzz"; + private static final String HTTP_RESPONSE_DATE_REGEX = "(\\w+,\\s\\d{1,2}\\s\\w+\\s\\d{4}\\s\\d{2}:\\d{2}:\\d{2}\\s\\w{2,6})"; + private static final String HTTP_RESPONSE_DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss zzz"; /** * Matches date with MM/DD/YYYY pattern diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/utils/ImageUtils.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/utils/ImageUtils.java index acfcd02a..0e924a69 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/utils/ImageUtils.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/utils/ImageUtils.java @@ -1,13 +1,18 @@ package com.capgemini.mrchecker.selenium.core.utils; import java.awt.image.BufferedImage; -import java.io.*; -import java.util.*; +import java.io.File; +import java.io.IOException; +import java.util.Date; import javax.imageio.ImageIO; import org.apache.commons.io.FileUtils; -import org.openqa.selenium.*; +import org.openqa.selenium.JavascriptExecutor; +import org.openqa.selenium.OutputType; +import org.openqa.selenium.Point; +import org.openqa.selenium.TakesScreenshot; +import org.openqa.selenium.WebElement; import com.capgemini.mrchecker.selenium.core.BasePage; diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/utils/TestUtils.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/utils/TestUtils.java index 947b7be8..cb49a2c7 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/utils/TestUtils.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/utils/TestUtils.java @@ -6,7 +6,7 @@ import org.openqa.selenium.By; import com.capgemini.mrchecker.selenium.core.BasePage; -import com.capgemini.mrchecker.selenium.core.enums.SubUrl; +import com.capgemini.mrchecker.selenium.core.enums.ISubUrl; import com.capgemini.mrchecker.test.core.exceptions.BFInputDataException; import com.capgemini.mrchecker.test.core.logger.BFLogger; @@ -20,7 +20,7 @@ public class TestUtils { * @param pageSubUrl * @return Returns true if current URL contains subURL specified by parameter */ - public static boolean isOnPage(SubUrl pageSubUrl) { + public static boolean isOnPage(ISubUrl pageSubUrl) { return isCurrentUrlContains(pageSubUrl.subURL()); } @@ -30,14 +30,14 @@ public static boolean isOnPage(SubUrl pageSubUrl) { */ public static boolean isCurrentUrlContains(String url) { if (BasePage.getDriver() - .getCurrentUrl() - .contains(url)) { + .getCurrentUrl() + .contains(url)) { BFLogger.logDebug("Current page as expected: " + BasePage.getDriver() - .getCurrentUrl()); + .getCurrentUrl()); return true; } else { BFLogger.logDebug("Not on " + url + " page. Current page: " + BasePage.getDriver() - .getCurrentUrl()); + .getCurrentUrl()); return false; } } @@ -49,8 +49,8 @@ public static boolean isCurrentUrlContains(String url) { public static boolean isCurrentUrlMatchesPattern(String toMatch) { Pattern pattern = Pattern.compile(toMatch); return pattern.matcher(BasePage.getDriver() - .getCurrentUrl()) - .matches(); + .getCurrentUrl()) + .matches(); } public static boolean isCurrentUrlContains(String[] pageSubUrls) { @@ -65,14 +65,14 @@ public static boolean isCurrentUrlContains(String[] pageSubUrls) { public static boolean isCurrentPageTitle(String title) { if (BasePage.getDriver() - .getTitle() - .contains(title)) { + .getTitle() + .contains(title)) { BFLogger.logDebug("Current page as expected: " + BasePage.getDriver() - .getTitle()); + .getTitle()); return true; } else { BFLogger.logDebug("Not on " + title + " page. Current page: " + BasePage.getDriver() - .getTitle()); + .getTitle()); return false; } } @@ -84,12 +84,12 @@ public static boolean isCurrentPageTitle(String title) { */ public void goToPage(String pageUrl) { BasePage.getDriver() - .get(pageUrl); + .get(pageUrl); } public String getCurrentPageURL() { return BasePage.getDriver() - .getCurrentUrl(); + .getCurrentUrl(); } /** @@ -100,9 +100,9 @@ public String getCurrentPageURL() { @SuppressWarnings("deprecation") public boolean isTextOnPage(String text) { return BasePage.getDriver() - .findElement(By.cssSelector("body")) - .getText() - .contains(text); + .findElement(By.cssSelector("body")) + .getText() + .contains(text); } /** @@ -113,8 +113,8 @@ public static String getAbsolutePathFor(String path) { String absolutePath = ""; try { String resourceFile = TestUtils.class.getClassLoader() - .getResource(path) - .getFile(); + .getResource(path) + .getFile(); absolutePath = new File(resourceFile).getAbsolutePath(); } catch (NullPointerException e) { throw new BFInputDataException("Given path: (" + path + ") does not exists in src/test/resources"); diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/utils/WebElementUtils.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/utils/WebElementUtils.java index fd435ac7..10346697 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/utils/WebElementUtils.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/utils/WebElementUtils.java @@ -81,7 +81,7 @@ public static boolean isWebElementHighlightedInColor(WebElement webElement, Stri public static WebElement hoverOnElement(By elementSelector, By waitForSelector) { @SuppressWarnings("deprecation") WebElement element = BasePage.getDriver() - .findElement(elementSelector); + .findElement(elementSelector); return hoverOnElement(element, waitForSelector); } @@ -98,11 +98,11 @@ public static WebElement hoverOnElement(By elementSelector, By waitForSelector) public static WebElement hoverOnElement(WebElement elementToHoverOn, By waitForSelector) { long startTime = System.currentTimeMillis(); BasePage.getAction() - .moveToElement(elementToHoverOn) - .build() - .perform(); + .moveToElement(elementToHoverOn) + .build() + .perform(); - WebDriverWait wait = new WebDriverWait(BasePage.getDriver(), BasePage.EXPLICITYWAITTIMER); + WebDriverWait wait = new WebDriverWait(BasePage.getDriver(), BasePage.EXPLICIT_WAIT_TIMER); WebElement element = wait.until((Function) ExpectedConditions.visibilityOfElementLocated(waitForSelector)); BFLogger.logTime(startTime, "hoverOnElement", waitForSelector.toString()); return element; @@ -120,11 +120,11 @@ public static WebElement hoverOnElement(WebElement elementToHoverOn, By waitForS public static WebElement hoverOnElement(WebElement elementToHoverOn, WebElement waitForElement) { long startTime = System.currentTimeMillis(); BasePage.getAction() - .moveToElement(elementToHoverOn) - .build() - .perform(); + .moveToElement(elementToHoverOn) + .build() + .perform(); - WebDriverWait wait = new WebDriverWait(BasePage.getDriver(), BasePage.EXPLICITYWAITTIMER); + WebDriverWait wait = new WebDriverWait(BasePage.getDriver(), BasePage.EXPLICIT_WAIT_TIMER); WebElement element = wait.until((Function) ExpectedConditions.visibilityOf(waitForElement)); BFLogger.logTime(startTime, "hoverOnElement", waitForElement.toString()); return element; @@ -139,7 +139,7 @@ public static WebElement hoverOnElement(WebElement elementToHoverOn, WebElement * after {@link BasePage.EXPLICITYWAITTIMER} */ public static void waitForElementVisible(By elementToWaitFor) { - waitForElementVisible(elementToWaitFor, BasePage.EXPLICITYWAITTIMER); + waitForElementVisible(elementToWaitFor, BasePage.EXPLICIT_WAIT_TIMER); } /** @@ -167,7 +167,7 @@ public static void waitForElementVisible(By elementToWaitFor, int tiemout) { */ public static WebElement waitForElementVisible(WebElement elementToWaitFor) { long startTime = System.currentTimeMillis(); - WebDriverWait wait = new WebDriverWait(BasePage.getDriver(), BasePage.EXPLICITYWAITTIMER); + WebDriverWait wait = new WebDriverWait(BasePage.getDriver(), BasePage.EXPLICIT_WAIT_TIMER); WebElement element = wait.until((Function) ExpectedConditions.visibilityOf(elementToWaitFor)); BFLogger.logTime(startTime, "waitForElementVisible", elementToWaitFor.toString()); return element; @@ -183,7 +183,7 @@ public static WebElement waitForElementVisible(WebElement elementToWaitFor) { */ public static boolean waitForElementNotVisible(By elementToWaitFor) { long startTime = System.currentTimeMillis(); - WebDriverWait wait = new WebDriverWait(BasePage.getDriver(), BasePage.EXPLICITYWAITTIMER); + WebDriverWait wait = new WebDriverWait(BasePage.getDriver(), BasePage.EXPLICIT_WAIT_TIMER); Boolean elementInvisibility = wait.until((Function) ExpectedConditions.invisibilityOfElementLocated(elementToWaitFor)); BFLogger.logTime(startTime, "waitForElementNotVisible", elementToWaitFor.toString()); return elementInvisibility; @@ -197,9 +197,9 @@ public static boolean waitForElementNotVisible(By elementToWaitFor) { */ public static boolean waitForElementNotVisible(WebElement elementToWaitFor) { long startTime = System.currentTimeMillis(); - WebDriverWait wait = new WebDriverWait(BasePage.getDriver(), BasePage.EXPLICITYWAITTIMER); + WebDriverWait wait = new WebDriverWait(BasePage.getDriver(), BasePage.EXPLICIT_WAIT_TIMER); Boolean elementInvisibility = wait - .until((Function) ExpectedConditions.not(ExpectedConditions.visibilityOf(elementToWaitFor))); + .until((Function) ExpectedConditions.not(ExpectedConditions.visibilityOf(elementToWaitFor))); BFLogger.logTime(startTime, "waitForElementNotVisible", elementToWaitFor.toString()); return elementInvisibility; } @@ -211,8 +211,8 @@ public static boolean waitForElementNotVisible(WebElement elementToWaitFor) { */ public static void dynamicClick(By selector) { BasePage.getDriver() - .waitUntilElementIsClickable(selector) - .click(); + .waitUntilElementIsClickable(selector) + .click(); } /** @@ -225,9 +225,9 @@ public static void dynamicClick(By selector) { */ public static void moveMousePointer(int xOffset, int yOffset) { BasePage.getAction() - .moveByOffset(xOffset, yOffset) - .build() - .perform(); + .moveByOffset(xOffset, yOffset) + .build() + .perform(); } /** @@ -280,15 +280,15 @@ public static void sendNewKeys(WebElement field, String keys) { * @return WebElement matching selector */ public static WebElement getExpectedElement(WebElement parent, - By selector, - Class retriever, - String expectedElementDescription) { + By selector, + Class retriever, + String expectedElementDescription) { WebElement e; try { e = parent.findElement(selector); } catch (NoSuchElementException ex) { throw new BFComponentStateException(retriever.getSimpleName(), "get " + expectedElementDescription, - "not found"); + "not found"); } return e; } @@ -328,11 +328,11 @@ public static void waitForAnimationEnd(By selector) { long startTime = System.currentTimeMillis(); @SuppressWarnings("deprecation") WebElement sliderElement = BasePage.getDriver() - .findElement(selector); + .findElement(selector); String leftOffset = ""; while (!leftOffset.equals(sliderElement.getAttribute("style"))) { - if (System.currentTimeMillis() - startTime > BasePage.EXPLICITYWAITTIMER * 1000) { - throw new BFWaitingTimeoutException("Animation is to long", BasePage.EXPLICITYWAITTIMER * 1000); + if (System.currentTimeMillis() - startTime > BasePage.EXPLICIT_WAIT_TIMER * 1000) { + throw new BFWaitingTimeoutException("Animation is to long", BasePage.EXPLICIT_WAIT_TIMER * 1000); } leftOffset = sliderElement.getAttribute("style"); TimeUtills.waitMiliseconds(100); @@ -352,8 +352,8 @@ public static void waitForAnimationEnd(By selector) { public static void clickIfVisible(By selector, String elementName) { if (BasePage.isElementDisplayedNoException(selector)) { BasePage.getDriver() - .findElement(selector) - .click(); + .findElement(selector) + .click(); } else { throw new BFComponentStateException(elementName, "click", "element not found"); } diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/utils/WindowUtils.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/utils/WindowUtils.java index 79a945bc..4853632c 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/utils/WindowUtils.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/core/utils/WindowUtils.java @@ -56,7 +56,7 @@ public static void switchWindow(String url, boolean switchToGivenURL) { * * @param title * - title/part of title, at which you want to get driver - * @param switchToGivenURL + * @param switchToGiven * - true if you want switch on this window, false if the another one */ public static void switchToWindowByTitle(String title, boolean switchToGiven) { @@ -244,7 +244,7 @@ public static Set waitForOpeningSecondBrowserWindow(String timeoutDescri long startTime = System.currentTimeMillis(); Set allBrowserWindows = BasePage.getDriver() .getWindowHandles(); - int tmp_timeout = BasePage.PROGRESSBARWAITTIMER; + int tmp_timeout = BasePage.PROGRESS_BAR_WAIT_TIMER; while (allBrowserWindows.size() < 2) { TimeUtills.waitMiliseconds(1000); if (tmp_timeout-- <= 0) diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/jsoupHelper/JsoupHelper.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/jsoupHelper/JsoupHelper.java index 975c0ff4..7e9424e3 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/jsoupHelper/JsoupHelper.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/main/java/com/capgemini/mrchecker/selenium/jsoupHelper/JsoupHelper.java @@ -180,12 +180,12 @@ public static List getSelectors(By elementToReturn, By elementToCheck, S String selector = createStringSelector(elementToReturn); Elements rowListE = doc.body() - .select(selector); + .select(selector); for (Element row : rowListE) { String selectorOfElementTocheck = createStringSelector(elementToCheck); String containsQuery = valueToCheck == null || valueToCheck.isEmpty() - ? "" - : ":contains(" + valueToCheck + ")"; + ? "" + : ":contains(" + valueToCheck + ")"; Elements returnCandidates = row.select(selectorOfElementTocheck + containsQuery); if (!returnCandidates.isEmpty()) result.add(row.cssSelector()); @@ -266,7 +266,7 @@ private static List getElements(String text, List selectors) By elementSelector = By.cssSelector(selector); @SuppressWarnings("deprecation") WebElement foundElement = BasePage.getDriver() - .findElement(elementSelector); + .findElement(elementSelector); elementsToReturn.add(foundElement); } return elementsToReturn; @@ -294,8 +294,7 @@ private static Document initDocument(WebElement searchArea) { } else if (isConversionToListRequired(innerHtml)) { innerHtml = convertToList(innerHtml); } - Document doc = Jsoup.parse("" + innerHtml + ""); - return doc; + return Jsoup.parse("" + innerHtml + ""); } private static boolean isConversionToTableRequired(String innerHtml) { @@ -312,46 +311,38 @@ private static boolean isConversionToTableRequired(String innerHtml) { } private static String convertToTable(String innerHtml) { - innerHtml = "" + innerHtml + "
    "; - return innerHtml; + return "" + innerHtml + "
    "; } private static boolean isConversionToListRequired(String innerHtml) { if (innerHtml.contains(""; - return innerHtml; + return "

      " + innerHtml + "
    "; } private static Document initDocument() { Document doc = Jsoup.parse(BasePage.getDriver() - .getPageSource()); + .getPageSource()); return doc; } private static String createStringSelector(By from) { String selector = from.toString(); int substringBegin = from.toString() - .indexOf(":") + 2; + .indexOf(":") + 2; selector = selector.substring(substringBegin); selector = removeQuotes(selector); return selector; } private static String removeQuotes(String selector) { - String openingQuote = "=\\s*'"; - String closingQuote = "'\\s*\\]"; - selector = selector.replaceAll(openingQuote, "="); - selector = selector.replaceAll(closingQuote, "]"); - return selector; + return selector.replaceAll("=\\s*'", "=") + .replaceAll("'\\s*]", "]"); } - } \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/resources/settings.properties b/mrchecker-framework-modules/mrchecker-selenium-module/src/resources/settings.properties index d056fcf9..f6e30fad 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/resources/settings.properties +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/resources/settings.properties @@ -6,7 +6,7 @@ selenium.opera=./lib/webdrivers/opera/operadriver.exe selenium.webdrivers=./lib/webdrivers selenium.proxy= selenium.driverAutoUpdate=true -wdm.chromeDriverVersion=75.0.3770.90 +wdm.chromeDriverVersion=83.0.4103.39 wdm.internetExplorerDriverVersion= wdm.geckoDriverVersion= wdm.edgeVersion= diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/base/runtime/RuntimeParametersTest.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/base/runtime/RuntimeParametersTest.java deleted file mode 100644 index 250ae651..00000000 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/base/runtime/RuntimeParametersTest.java +++ /dev/null @@ -1,185 +0,0 @@ -package com.capgemini.mrchecker.selenium.core.base.runtime; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.commons.lang.BooleanUtils; -import org.hamcrest.Matchers; -import org.hamcrest.core.IsInstanceOf; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - -public class RuntimeParametersTest { - - private Map values = new HashMap(); - - @Rule - public ExpectedException exceptionGrabber = ExpectedException.none(); - - @Before - public void setUp() throws Exception { - - values.put("browser", "magicBrowser"); - values.put("browserVersion", "11.0"); - values.put("seleniumGrid", "smth"); - values.put("os", "linux"); - values.put("browserOptions", "headless;window-size=1200x600;testEquals=FirstEquals=SecondEquals;--testMe;acceptInsecureCerts=true;maxInstances=3"); - - values.forEach(System::setProperty); - - RuntimeParametersSelenium.BROWSER.refreshParameterValue(); - RuntimeParametersSelenium.BROWSER_VERSION.refreshParameterValue(); - RuntimeParametersSelenium.OS.refreshParameterValue(); - RuntimeParametersSelenium.SELENIUM_GRID.refreshParameterValue(); - RuntimeParametersSelenium.BROWSER_OPTIONS.refreshParameterValue(); - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testGetProperty() { - - assertThat("System parameters for empty property 'browser' should be 'magicbrowser'", RuntimeParametersSelenium.BROWSER.getValue(), Matchers.equalTo("magicbrowser")); - assertThat("System parameters for empty property 'browserVersion' should be '11.0'", RuntimeParametersSelenium.BROWSER_VERSION.getValue(), Matchers.equalTo("11.0")); - assertThat("System parameters for empty property 'seleniumGrid' should be 'smth'", RuntimeParametersSelenium.SELENIUM_GRID.getValue(), Matchers.equalTo("smth")); - assertThat("System parameters for empty property 'os' should be 'linux'", RuntimeParametersSelenium.OS.getValue(), Matchers.equalTo("linux")); - assertThat( - "System parameters for empty property 'browserOptions' should be 'headless;window-size=1200x600;testEquals=FirstEquals=SecondEquals;--testMe;acceptInsecureCerts=true;maxInstances=3'", - RuntimeParametersSelenium.BROWSER_OPTIONS.getValue(), - Matchers.equalTo("headless;window-size=1200x600;testEquals=FirstEquals=SecondEquals;--testMe;acceptInsecureCerts=true;maxInstances=3")); - - } - - @Test - public void testConvertToCorrectTypeBoolean() throws Exception { - - // validate type as Boolean - String value = "true"; - Object convertToCorrectType = RuntimeParametersSelenium.convertToCorrectType(value); - assertThat(BooleanUtils.toBooleanObject((boolean) convertToCorrectType), IsInstanceOf.instanceOf(Boolean.class)); - - value = "false"; - convertToCorrectType = RuntimeParametersSelenium.convertToCorrectType(value); - assertThat(BooleanUtils.toBooleanObject((boolean) convertToCorrectType), IsInstanceOf.instanceOf(Boolean.class)); - - value = "blue"; - convertToCorrectType = RuntimeParametersSelenium.convertToCorrectType(value); - exceptionGrabber.expect(ClassCastException.class); - exceptionGrabber.expectMessage("java.lang.String cannot be cast to java.lang.Boolean"); - assertThat(BooleanUtils.toBooleanObject((boolean) convertToCorrectType), Matchers.not(IsInstanceOf.instanceOf(Boolean.class))); - - } - - @Test - public void testConvertToCorrectTypeInteger() throws Exception { - - String value = "1"; - Object convertToCorrectType = RuntimeParametersSelenium.convertToCorrectType(value); - assertThat((Integer) convertToCorrectType, IsInstanceOf.instanceOf(Integer.class)); - - value = "0.23"; - convertToCorrectType = RuntimeParametersSelenium.convertToCorrectType(value); - assertThat((Float) convertToCorrectType, IsInstanceOf.instanceOf(Float.class)); - - value = "blue"; - convertToCorrectType = RuntimeParametersSelenium.convertToCorrectType(value); - exceptionGrabber.expect(ClassCastException.class); - exceptionGrabber.expectMessage("java.lang.String cannot be cast to java.lang.Integer"); - assertThat((Integer) convertToCorrectType, IsInstanceOf.instanceOf(Integer.class)); - } - - @Test - public void testConvertToCorrectTypeString() throws Exception { - - String value = "hello"; - Object convertToCorrectType = RuntimeParametersSelenium.convertToCorrectType(value); - assertThat((String) convertToCorrectType, IsInstanceOf.instanceOf(String.class)); - - value = ""; - convertToCorrectType = RuntimeParametersSelenium.convertToCorrectType(value); - assertThat((String) convertToCorrectType, IsInstanceOf.instanceOf(String.class)); - - value = null; - convertToCorrectType = RuntimeParametersSelenium.convertToCorrectType(value); - assertThat((String) convertToCorrectType, Matchers.isEmptyOrNullString()); - - } - - @Test - public void testBrowserOptionsVariable() throws Exception { - - Map expected = new HashMap(); - expected.put("testEquals", "FirstEquals=SecondEquals"); - expected.put("headless", ""); - expected.put("--testMe", ""); - expected.put("window-size", "1200x600"); - expected.put("acceptInsecureCerts", true); - expected.put("maxInstances", 3); - - assertThat(RuntimeParametersSelenium.BROWSER_OPTIONS.getValues() - .size(), - Matchers.is(6)); - - assertThat(RuntimeParametersSelenium.BROWSER_OPTIONS.getValues() - .toString(), - Matchers.is(expected.toString())); - - } - - @Test - public void testBrowserOptionsSet() throws Exception { - - RuntimeParametersSelenium.BROWSER_OPTIONS.getValues() - .forEach((key, value) -> { - String item = (value.toString() - .isEmpty()) ? key : key + "=" + value; - System.out.println(item); - }); - - } - - @Test - public void testBrowserIE() throws Exception { - System.setProperty("browser", "ie"); - RuntimeParametersSelenium.BROWSER.refreshParameterValue(); - - assertEquals("System parameters for empty property 'browser' should be 'internet explorer'", "internet explorer", RuntimeParametersSelenium.BROWSER.getValue()); - - } - - @Test - public void testGetEmptyProperty() { - values.forEach((String key, String value) -> System.clearProperty(key)); - - RuntimeParametersSelenium.BROWSER.refreshParameterValue(); - RuntimeParametersSelenium.BROWSER_VERSION.refreshParameterValue(); - RuntimeParametersSelenium.OS.refreshParameterValue(); - RuntimeParametersSelenium.SELENIUM_GRID.refreshParameterValue(); - RuntimeParametersSelenium.BROWSER_OPTIONS.refreshParameterValue(); - - assertThat("System parameters for empty property 'browser' should be 'chrome'", RuntimeParametersSelenium.BROWSER.getValue(), Matchers.equalTo("chrome")); - assertThat("System parameters for empty property 'browserVersion' should be 'null'", RuntimeParametersSelenium.BROWSER_VERSION.getValue(), Matchers.isEmptyString()); - assertThat("System parameters for empty property 'seleniumGrid' should be 'false'", RuntimeParametersSelenium.SELENIUM_GRID.getValue(), Matchers.isEmptyString()); - assertThat("System parameters for empty property 'os' should be 'null'", RuntimeParametersSelenium.OS.getValue(), Matchers.isEmptyString()); - assertThat("System parameters for empty property 'browserOptions' should be 'null'", RuntimeParametersSelenium.BROWSER_OPTIONS.getValue(), Matchers.isEmptyString()); - - } - - @Test - public void testParamsToString() throws Exception { - - RuntimeParametersSelenium.valueOf("BROWSER") - .toString() - .equals("browser=magicBrowser"); - - } - -} diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/newDrivers/DriverManagerTest.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/newDrivers/DriverManagerTest.java index b9c273af..2db99875 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/newDrivers/DriverManagerTest.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/newDrivers/DriverManagerTest.java @@ -2,30 +2,31 @@ import static org.junit.Assert.assertTrue; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import com.capgemini.mrchecker.selenium.core.base.properties.PropertiesSelenium; -import com.capgemini.mrchecker.selenium.core.newDrivers.DriverManager; import com.capgemini.mrchecker.test.core.base.properties.PropertiesSettingsModule; import com.google.inject.Guice; +@Disabled public class DriverManagerTest { private DriverManager driverManager; - @BeforeClass + @BeforeAll public static void setUpBeforeClass() throws Exception { } - @AfterClass + @AfterAll public static void tearDownAfterClass() throws Exception { } - @Before + @BeforeEach public void setUp() throws Exception { PropertiesSelenium propertiesSelenium = Guice.createInjector(PropertiesSettingsModule.init()) @@ -35,7 +36,7 @@ public void setUp() throws Exception { } - @After + @AfterEach public void tearDown() throws Exception { driverManager.stop(); } diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/ButtonTest.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/ButtonTest.java index dfc5d04b..92e19839 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/ButtonTest.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/ButtonTest.java @@ -1,39 +1,43 @@ package com.capgemini.mrchecker.selenium.core.tests.webElements; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.openqa.selenium.By; + import com.capgemini.mrchecker.selenium.core.BasePage; import com.capgemini.mrchecker.selenium.core.enums.PageSubURLsEnum; import com.capgemini.mrchecker.test.core.BaseTest; -import org.junit.AfterClass; -import org.junit.Test; -import org.openqa.selenium.By; - -import static junit.framework.TestCase.assertEquals; -import static junit.framework.TestCase.assertTrue; /** * Created by LKURZAJ on 03.03.2017. */ +@Disabled public class ButtonTest extends BaseTest { - private QuickFixSeleniumPage quickFixSeleniumPage = new QuickFixSeleniumPage(); - private static By buttonSubmit = By.cssSelector("button#submit"); - - @AfterClass - public static void tearDownAll() { - + private QuickFixSeleniumPage quickFixSeleniumPage = new QuickFixSeleniumPage(); + private static By buttonSubmit = By.cssSelector("button#submit"); + + @Override + public void setUp() { + quickFixSeleniumPage = new QuickFixSeleniumPage(); + BasePage.getDriver() + .get(PageSubURLsEnum.TOOLS_QA.subURL() + PageSubURLsEnum.AUTOMATION_PRACTICE_FORM.subURL()); } - + @Test public void test() { // check if element is displayed assertTrue(BasePage.getDriver() .elementButton(ButtonTest.buttonSubmit) .isDisplayed()); - + // check if element type equals Button assertEquals("Button", BasePage.getDriver() .elementButton(ButtonTest.buttonSubmit) .getElementTypeName()); - + // click on button and verify if url was changed BasePage.getDriver() .elementButton(ButtonTest.buttonSubmit) @@ -42,17 +46,4 @@ public void test() { .getCurrentUrl() .contains("&submit=")); } - - @Override - public void setUp() { - quickFixSeleniumPage = new QuickFixSeleniumPage(); - BasePage.getDriver() - .get(PageSubURLsEnum.TOOLS_QA.subURL() + PageSubURLsEnum.AUTOMATION_PRACTICE_FORM.subURL()); - return; - } - - @Override - public void tearDown() { - // TODO Auto-generated method stub - } } diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/CheckBoxTest.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/CheckBoxTest.java index dfa731a1..8190813a 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/CheckBoxTest.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/CheckBoxTest.java @@ -1,29 +1,36 @@ package com.capgemini.mrchecker.selenium.core.tests.webElements; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.openqa.selenium.By; + import com.capgemini.mrchecker.selenium.core.BasePage; import com.capgemini.mrchecker.selenium.core.enums.PageSubURLsEnum; import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.CheckBox; import com.capgemini.mrchecker.test.core.BaseTest; -import org.junit.AfterClass; -import org.junit.Test; -import org.openqa.selenium.By; - -import static org.junit.Assert.*; /** * Created by LKURZAJ on 06.03.2017. */ +@Disabled public class CheckBoxTest extends BaseTest { - private QuickFixSeleniumPage quickFixSeleniumPage = new QuickFixSeleniumPage(); - private static final By hobbyCheckBoxSelector = By + private QuickFixSeleniumPage quickFixSeleniumPage = new QuickFixSeleniumPage(); + private static final By hobbyCheckBoxSelector = By .cssSelector("li.fields.pageFields_1:nth-child(3) div.radio_wrap"); - CheckBox checkBoxElement; - - @AfterClass - public static void tearDownAll() { - + CheckBox checkBoxElement; + + @Override + public void setUp() { + BasePage.getDriver() + .get(PageSubURLsEnum.WWW_FONT_URL.subURL() + PageSubURLsEnum.REGISTRATION.subURL()); + checkBoxElement = BasePage.getDriver() + .elementCheckbox(CheckBoxTest.hobbyCheckBoxSelector); } - + @Test public void testCheckBoxByIndex() { checkBoxElement.setCheckBoxByIndex(0); @@ -31,7 +38,7 @@ public void testCheckBoxByIndex() { checkBoxElement.unsetCheckBoxByIndex(0); assertFalse(checkBoxElement.isCheckBoxSetByIndex(0)); } - + @Test public void testCheckBoxByValue() { checkBoxElement.setCheckBoxByValue("reading"); @@ -39,22 +46,22 @@ public void testCheckBoxByValue() { checkBoxElement.unsetCheckBoxByValue("reading"); assertFalse(checkBoxElement.isCheckBoxSetByValue("reading")); } - + @Test public void testCheckBoxByText() { checkBoxElement.setCheckBoxByText("Cricket"); assertTrue(checkBoxElement.isCheckBoxSetByText("Cricket")); checkBoxElement.unsetCheckBoxByText("Cricket"); assertFalse(checkBoxElement.isCheckBoxSetByText("Cricket")); - + } - + @Test public void testNumberOfCheckBoxes() { assertEquals(checkBoxElement.getTextList() .size(), 3); } - + @Test public void testCheckBoxAllValues() { checkBoxElement.setAllCheckBoxes(); @@ -62,16 +69,5 @@ public void testCheckBoxAllValues() { checkBoxElement.unsetAllCheckBoxes(); assertFalse(checkBoxElement.isAllCheckboxesSet()); } - - @Override - public void setUp() { - BasePage.getDriver() - .get(PageSubURLsEnum.WWW_FONT_URL.subURL() + PageSubURLsEnum.REGISTRATION.subURL()); - this.checkBoxElement = BasePage.getDriver() - .elementCheckbox(CheckBoxTest.hobbyCheckBoxSelector); - } - - @Override - public void tearDown() { - } + } diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/DropdownListTest.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/DropdownListTest.java index 18430f8a..5bf819fa 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/DropdownListTest.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/DropdownListTest.java @@ -1,70 +1,68 @@ package com.capgemini.mrchecker.selenium.core.tests.webElements; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.openqa.selenium.By; + import com.capgemini.mrchecker.selenium.core.BasePage; import com.capgemini.mrchecker.selenium.core.enums.PageSubURLsEnum; import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.DropdownListElement; import com.capgemini.mrchecker.test.core.BaseTest; -import org.junit.AfterClass; -import org.junit.Test; -import org.openqa.selenium.By; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; /** * Created by LKURZAJ on 06.03.2017. */ +@Disabled public class DropdownListTest extends BaseTest { QuickFixSeleniumPage quickFixSeleniumPage = new QuickFixSeleniumPage(); - - private static final By dropdownSelector = By.cssSelector("select#dropdown_7"); - private DropdownListElement dropdownObject; - - @AfterClass + + private static final By dropdownSelector = By.cssSelector("select#dropdown_7"); + private DropdownListElement dropdownObject; + + @Override + public void setUp() { + BasePage.getDriver() + .get(PageSubURLsEnum.WWW_FONT_URL.subURL() + PageSubURLsEnum.REGISTRATION.subURL()); + dropdownObject = BasePage.getDriver() + .elementDropdownList(DropdownListTest.dropdownSelector); + } + + @AfterAll public static void tearDownAll() { } - + @Test public void testPossibleOptionsNumber() { assertTrue(dropdownObject.isDisplayed()); assertEquals(dropdownObject.getAmountOfPossibleValues(), 204); } - + @Test public void testSelectOptionByIndex() { dropdownObject.selectDropdownByIndex(0); assertTrue(dropdownObject.isDropdownElementSelectedByIndex(0)); } - + @Test public void testSelectOptionByValue() { dropdownObject.selectDropdownByValue("Vietnam"); assertTrue(dropdownObject.isDropdownElementSelectedByValue("Vietnam")); } - + @Test public void testSelectOptionByText() { dropdownObject.selectDropdownByVisibleText("Vietnam"); assertEquals(dropdownObject.getFirstSelectedOptionText(), "Vietnam"); } - + @Test public void testAllSelectedOptions() { dropdownObject.selectDropdownByIndex(5); assertEquals(dropdownObject.getAllSelectedOptionsText() .size(), 1); } - - @Override - public void setUp() { - BasePage.getDriver() - .get(PageSubURLsEnum.WWW_FONT_URL.subURL() + PageSubURLsEnum.REGISTRATION.subURL()); - this.dropdownObject = BasePage.getDriver() - .elementDropdownList(DropdownListTest.dropdownSelector); - } - - @Override - public void tearDown() { - - } } diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/HorizontalSliderTest.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/HorizontalSliderTest.java index 089cd6e4..c5924a7e 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/HorizontalSliderTest.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/HorizontalSliderTest.java @@ -1,51 +1,49 @@ package com.capgemini.mrchecker.selenium.core.tests.webElements; -import com.capgemini.mrchecker.selenium.core.BasePage; -import com.capgemini.mrchecker.selenium.core.enums.PageSubURLsEnum; -import com.capgemini.mrchecker.test.core.BaseTest; -import org.junit.Test; -import org.openqa.selenium.By; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import java.math.BigDecimal; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.openqa.selenium.By; -public class HorizontalSliderTest extends BaseTest { - QuickFixSeleniumPage quickFixSeleniumPage = new QuickFixSeleniumPage(); - private static final By sliderParent = By.cssSelector("div#tabs-2"); - private static final By sliderSelector = By.cssSelector("div#slider-range-max"); - private static final By valueSelector = By.cssSelector("#amount1"); +import com.capgemini.mrchecker.selenium.core.BasePage; +import com.capgemini.mrchecker.selenium.core.enums.PageSubURLsEnum; +import com.capgemini.mrchecker.test.core.BaseTest; +@Disabled +public class HorizontalSliderTest extends BaseTest { + QuickFixSeleniumPage quickFixSeleniumPage = new QuickFixSeleniumPage(); + private static final By sliderParent = By.cssSelector("div#tabs-2"); + private static final By sliderSelector = By.cssSelector("div#slider-range-max"); + private static final By valueSelector = By.cssSelector("#amount1"); + private static final String HORIZONTAL_SLIDER_INITIAL_VALUE = "2"; - + + @Override + public void setUp() { + BasePage.getDriver() + .get(PageSubURLsEnum.WWW_FONT_URL.subURL() + PageSubURLsEnum.SLIDER.subURL()); + } + @Test public void test() { // check if element is displayed assertTrue(BasePage.getDriver() .elementHorizontalSlider(sliderParent) .isDisplayed()); - + // check if element type equals HoizontalSlider assertEquals("Horizontal Slider", BasePage.getDriver() .elementHorizontalSlider(sliderParent, sliderSelector, valueSelector) .getElementTypeName()); - + // check if element's initial value is equal to 2 assertEquals(new BigDecimal(HORIZONTAL_SLIDER_INITIAL_VALUE), BasePage.getDriver() .elementHorizontalSlider(sliderParent, sliderSelector, valueSelector) .getCurrentSliderValue()); } - - @Override - public void setUp() { - BasePage.getDriver() - .get(PageSubURLsEnum.WWW_FONT_URL.subURL() + PageSubURLsEnum.SLIDER.subURL()); - } - - @Override - public void tearDown() { - - } - + } diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/ImageTest.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/ImageTest.java index 8042c33e..a487fc1e 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/ImageTest.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/ImageTest.java @@ -1,26 +1,29 @@ package com.capgemini.mrchecker.selenium.core.tests.webElements; +import static org.junit.Assert.assertTrue; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.openqa.selenium.By; + import com.capgemini.mrchecker.selenium.core.BasePage; import com.capgemini.mrchecker.selenium.core.enums.PageSubURLsEnum; import com.capgemini.mrchecker.test.core.BaseTest; -import org.junit.AfterClass; -import org.junit.Test; -import org.openqa.selenium.By; - -import static junit.framework.TestCase.assertTrue; /** * Created by TTRZCINSKI on 19.10.2018. */ +@Disabled public class ImageTest extends BaseTest { - QuickFixSeleniumPage quickFixSeleniumPage = new QuickFixSeleniumPage(); - private static By img1 = By.cssSelector("img"); - - @AfterClass - public static void tearDownAll() { - + QuickFixSeleniumPage quickFixSeleniumPage = new QuickFixSeleniumPage(); + private static By img1 = By.cssSelector("img"); + + @Override + public void setUp() { + BasePage.getDriver() + .get(PageSubURLsEnum.TOOLS_QA.subURL() + PageSubURLsEnum.AUTOMATION_PRACTICE_FORM.subURL()); } - + @Test public void test() { // check if label is displayed @@ -28,16 +31,4 @@ public void test() { .elementImage(ImageTest.img1) .isDisplayed()); } - - @Override - public void setUp() { - BasePage.getDriver() - .get(PageSubURLsEnum.TOOLS_QA.subURL() + PageSubURLsEnum.AUTOMATION_PRACTICE_FORM.subURL()); - return; - } - - @Override - public void tearDown() { - // TODO Auto-generated method stub - } } diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/InputTextTest.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/InputTextTest.java index fe727d53..fc0bd814 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/InputTextTest.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/InputTextTest.java @@ -1,55 +1,46 @@ package com.capgemini.mrchecker.selenium.core.tests.webElements; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.openqa.selenium.By; + import com.capgemini.mrchecker.selenium.core.BasePage; import com.capgemini.mrchecker.selenium.core.enums.PageSubURLsEnum; import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.InputTextElement; import com.capgemini.mrchecker.test.core.BaseTest; -import org.junit.AfterClass; -import org.junit.Test; -import org.openqa.selenium.By; - -import static junit.framework.TestCase.assertTrue; -import static org.junit.Assert.assertEquals; /** * Created by LKURZAJ on 03.03.2017. */ +@Disabled public class InputTextTest extends BaseTest { - QuickFixSeleniumPage quickFixSeleniumPage = new QuickFixSeleniumPage(); - private static By firstNameInputText = By.cssSelector("input[id='name_3_firstname']"); - - @AfterClass - public static void tearDownAll() { - + QuickFixSeleniumPage quickFixSeleniumPage = new QuickFixSeleniumPage(); + private static By firstNameInputText = By.cssSelector("input[id='name_3_firstname']"); + + @Override + public void setUp() { + BasePage.getDriver() + .get(PageSubURLsEnum.WWW_FONT_URL.subURL() + PageSubURLsEnum.REGISTRATION.subURL()); } - + @Test() public void testInputData() { InputTextElement inputElement = BasePage.getDriver() .elementInputText(InputTextTest.firstNameInputText); - + // verify if input text is displayed assertTrue(inputElement.isDisplayed()); - + // clear current text and verify (what to call getValue() or getText() depends // on implementation) inputElement.clearInputText(); assertEquals("", inputElement.getValue()); - + // input some text into input text and verify value inputElement.setInputText("John"); assertEquals("John", inputElement.getValue()); } - - @Override - public void setUp() { - BasePage.getDriver() - .get(PageSubURLsEnum.WWW_FONT_URL.subURL() + PageSubURLsEnum.REGISTRATION.subURL()); - return; - } - - @Override - public void tearDown() { - // TODO Auto-generated method stub - } } diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/LabelTest.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/LabelTest.java index d6b7d826..66b3aac4 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/LabelTest.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/LabelTest.java @@ -1,55 +1,46 @@ package com.capgemini.mrchecker.selenium.core.tests.webElements; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.openqa.selenium.By; + import com.capgemini.mrchecker.selenium.core.BasePage; import com.capgemini.mrchecker.selenium.core.enums.PageSubURLsEnum; import com.capgemini.mrchecker.test.core.BaseTest; -import org.junit.AfterClass; -import org.junit.Test; -import org.openqa.selenium.By; - -import static junit.framework.TestCase.assertEquals; -import static junit.framework.TestCase.assertTrue; /** * Created by LKURZAJ on 03.03.2017. */ +@Disabled public class LabelTest extends BaseTest { QuickFixSeleniumPage quickFixSeleniumPage = new QuickFixSeleniumPage(); - + private static By text1Label = By.cssSelector("span.bcd"); - - @AfterClass - public static void tearDownAll() { - + + @Override + public void setUp() { + BasePage.getDriver() + .get(PageSubURLsEnum.TOOLS_QA.subURL() + PageSubURLsEnum.AUTOMATION_PRACTICE_FORM.subURL()); } - + @Test public void test() { // check if label is displayed assertTrue(BasePage.getDriver() .elementLabel(LabelTest.text1Label) .isDisplayed()); - + // check if label has properly text assertEquals("Text1", BasePage.getDriver() .elementLabel(LabelTest.text1Label) .getText()); - + // check if label has properly class field assertEquals("bcd", BasePage.getDriver() .elementLabel(LabelTest.text1Label) .getClassName()); } - - @Override - public void setUp() { - BasePage.getDriver() - .get(PageSubURLsEnum.TOOLS_QA.subURL() + PageSubURLsEnum.AUTOMATION_PRACTICE_FORM.subURL()); - return; - } - - @Override - public void tearDown() { - // TODO Auto-generated method stub - } } diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/MenuTest.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/MenuTest.java index 1c10a43d..38abe601 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/MenuTest.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/MenuTest.java @@ -1,37 +1,40 @@ package com.capgemini.mrchecker.selenium.core.tests.webElements; +import static org.junit.Assert.assertEquals; + +import java.util.Arrays; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.openqa.selenium.By; + import com.capgemini.mrchecker.selenium.core.BasePage; import com.capgemini.mrchecker.selenium.core.enums.PageSubURLsEnum; import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.MenuElement; import com.capgemini.mrchecker.test.core.BaseTest; -import org.junit.AfterClass; -import org.junit.Test; -import org.openqa.selenium.By; - -import java.util.Arrays; - -import static org.junit.Assert.assertEquals; /** * Created by LKURZAJ on 08.03.2017. */ +@Disabled public class MenuTest extends BaseTest { QuickFixSeleniumPage quickFixSeleniumPage = new QuickFixSeleniumPage(); - - private final static By menuSelector = By.cssSelector("div#tabs-1 ul.top-level"); - private final static By menu2Selector = By.cssSelector("div#tabs-2 ul.top-level"); - private final static By menuChildsSelector = By.cssSelector("li"); - private final static By subMenuSelector = By.cssSelector("ul"); - private final static By subMenuChildsSelector = By.cssSelector("li"); - private final static By subMenuTabSelector = By.cssSelector("li[aria-controls='tabs-2']"); - private MenuElement menuElement; - private MenuElement menu2Element; - - @AfterClass - public static void tearDownAll() { - + + private final static By menuSelector = By.cssSelector("div#tabs-1 ul.top-level"); + private final static By menu2Selector = By.cssSelector("div#tabs-2 ul.top-level"); + private final static By menuChildsSelector = By.cssSelector("li"); + private final static By subMenuSelector = By.cssSelector("ul"); + private final static By subMenuChildsSelector = By.cssSelector("li"); + private final static By subMenuTabSelector = By.cssSelector("li[aria-controls='tabs-2']"); + private MenuElement menuElement; + private MenuElement menu2Element; + + @Override + public void setUp() { + BasePage.getDriver() + .get(PageSubURLsEnum.WWW_FONT_URL.subURL() + PageSubURLsEnum.MENU.subURL()); } - + @Test public void testMenuByIndex() { menuElement = BasePage.getDriver() @@ -39,7 +42,7 @@ public void testMenuByIndex() { menuElement.selectItemByIndex(0); assertEquals(this.getCurrentURL() + "#", menuElement.getItemLinkByIndex(0)); } - + @Test public void testMenuByText() { menuElement = BasePage.getDriver() @@ -47,21 +50,21 @@ public void testMenuByText() { menuElement.selectItemByText("About"); assertEquals(this.getCurrentURL() + "#", menuElement.getItemLinkByText("About")); } - + @Test public void testMenuItemsCount() { menuElement = BasePage.getDriver() .elementMenu(MenuTest.menuSelector); assertEquals(5, menuElement.getItemsCount()); } - + @Test public void testMenuItemsText() { menuElement = BasePage.getDriver() .elementMenu(MenuTest.menuSelector); assertEquals(Arrays.asList("Home", "About", "Contact", "FAQ", "News"), menuElement.getItemsTextList()); } - + @Test public void testSelectSubMenuItemByText() { BasePage.getDriver() @@ -72,7 +75,7 @@ public void testSelectSubMenuItemByText() { MenuTest.subMenuSelector); assertEquals(getCurrentURL() + "#", menu2Element.getSubMenuItemLinkByText("FAQ", "Sub Menu Item 3")); } - + @Test public void testSelectSubMenuItemByIndex() { BasePage.getDriver() @@ -82,7 +85,7 @@ public void testSelectSubMenuItemByIndex() { .elementMenu(MenuTest.menu2Selector, MenuTest.menuChildsSelector); menu2Element.selectSubMenuItemByIndex(0, 1); } - + @Test public void testLinkSubMenuItemByIndex() { BasePage.getDriver() @@ -92,7 +95,7 @@ public void testLinkSubMenuItemByIndex() { .elementMenu(MenuTest.menu2Selector, MenuTest.menuChildsSelector); assertEquals(getCurrentURL() + "#", menu2Element.getSubMenuItemLinkByIndex(0, 1)); } - + @Test public void testLinkSubMenuItemByText() { BasePage.getDriver() @@ -103,18 +106,7 @@ public void testLinkSubMenuItemByText() { MenuTest.subMenuSelector, MenuTest.subMenuChildsSelector); menu2Element.selectSubMenuItemByText("FAQ", "Sub Menu Item 3"); } - - @Override - public void setUp() { - BasePage.getDriver() - .get(PageSubURLsEnum.WWW_FONT_URL.subURL() + PageSubURLsEnum.MENU.subURL()); - } - - @Override - public void tearDown() { - - } - + private String getCurrentURL() { return PageSubURLsEnum.WWW_FONT_URL.subURL() + PageSubURLsEnum.MENU.subURL(); } diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/NavigationBarTest.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/NavigationBarTest.java index abf1ee97..080e3b24 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/NavigationBarTest.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/NavigationBarTest.java @@ -1,48 +1,53 @@ package com.capgemini.mrchecker.selenium.core.tests.webElements; +import static org.junit.Assert.assertEquals; + +import java.util.Arrays; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.openqa.selenium.By; + import com.capgemini.mrchecker.selenium.core.BasePage; import com.capgemini.mrchecker.selenium.core.enums.PageSubURLsEnum; import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.NavigationBarElement; import com.capgemini.mrchecker.test.core.BaseTest; -import org.junit.AfterClass; -import org.junit.Test; -import org.openqa.selenium.By; - -import java.util.Arrays; - -import static org.junit.Assert.assertEquals; /** * Created by LKURZAJ on 07.03.2017. */ +@Disabled public class NavigationBarTest extends BaseTest { - private NavigationBarElement navigationBarElement; - private final static By navigationBarSelector = By.cssSelector("ol#breadcrumbs"); - private final static By childsSelector = By.cssSelector("li"); - - @AfterClass - public static void tearDownAll() { - + private NavigationBarElement navigationBarElement; + private final static By navigationBarSelector = By.cssSelector("ol#breadcrumbs"); + private final static By childsSelector = By.cssSelector("li"); + + @Override + public void setUp() { + BasePage.getDriver() + .get(PageSubURLsEnum.WWW_FONT_URL.subURL() + PageSubURLsEnum.TABS.subURL()); + navigationBarElement = BasePage.getDriver() + .elementNavigationBar(NavigationBarTest.navigationBarSelector); } - + @Test public void testGets() { assertEquals("Home", this.navigationBarElement.getFirstItemText()); assertEquals("Tabs", this.navigationBarElement.getActiveItemText()); } - + @Test public void testClickByIndex() { this.navigationBarElement.clickItemByIndex(1); assertEquals("Tabs", this.navigationBarElement.getActiveItemText()); } - + @Test public void testClickByText() { this.navigationBarElement.clickItemByText("Home"); assertEquals("Home", this.navigationBarElement.getActiveItemText()); } - + @Test public void testClickActiveItem() { String url = BasePage.getDriver() @@ -51,30 +56,17 @@ public void testClickActiveItem() { assertEquals(url, BasePage.getDriver() .getCurrentUrl()); } - + @Test public void testClickFirstItem() { this.navigationBarElement.clickFirstItem(); assertEquals(1, this.navigationBarElement.getDepth()); } - + @Test public void testConstructor() { NavigationBarElement navBarElem = BasePage.getDriver() .elementNavigationBar(NavigationBarTest.navigationBarSelector, NavigationBarTest.childsSelector); assertEquals(Arrays.asList("Home", "Tabs"), navBarElem.getItemsTextList()); } - - @Override - public void setUp() { - BasePage.getDriver() - .get(PageSubURLsEnum.WWW_FONT_URL.subURL() + PageSubURLsEnum.TABS.subURL()); - this.navigationBarElement = BasePage.getDriver() - .elementNavigationBar(NavigationBarTest.navigationBarSelector); - } - - @Override - public void tearDown() { - - } } diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/QuickFixSeleniumPage.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/QuickFixSeleniumPage.java index 6b4d47fa..279c406a 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/QuickFixSeleniumPage.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/QuickFixSeleniumPage.java @@ -1,22 +1,25 @@ package com.capgemini.mrchecker.selenium.core.tests.webElements; +import org.junit.jupiter.api.Disabled; + import com.capgemini.mrchecker.selenium.core.BasePage; +@Disabled public class QuickFixSeleniumPage extends BasePage { - //This page is created to fix Selenium Session Exception from tes.WebElements test cases. - //When the test cases are refactored, this page should be deleted. - + // This page is created to fix Selenium Session Exception from tes.WebElements test cases. + // When the test cases are refactored, this page should be deleted. + @Override public boolean isLoaded() { getDriver().waitForPageLoaded(); return true; } - + @Override public void load() { - + } - + @Override public String pageTitle() { return getActualPageTitle(); diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/RadioButtonTest.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/RadioButtonTest.java index b16a8068..6f9f5fa7 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/RadioButtonTest.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/RadioButtonTest.java @@ -1,40 +1,45 @@ package com.capgemini.mrchecker.selenium.core.tests.webElements; -import com.capgemini.mrchecker.selenium.core.BasePage; -import com.capgemini.mrchecker.selenium.core.enums.PageSubURLsEnum; -import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.RadioButtonElement; -import com.capgemini.mrchecker.test.core.BaseTest; -import org.junit.AfterClass; -import org.junit.Test; -import org.openqa.selenium.By; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.openqa.selenium.By; + +import com.capgemini.mrchecker.selenium.core.BasePage; +import com.capgemini.mrchecker.selenium.core.enums.PageSubURLsEnum; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.RadioButtonElement; +import com.capgemini.mrchecker.test.core.BaseTest; /** * Created by LKURZAJ on 28.02.2017. */ +@Disabled public class RadioButtonTest extends BaseTest { - QuickFixSeleniumPage quickFixSeleniumPage = new QuickFixSeleniumPage(); - private RadioButtonElement maritalStatusRadioButton; - private final static By selectorMaritalStatus = By.cssSelector("div[class='radio_wrap']"); - private final static int radioElementsCount = 3; - private final static List possibleValues = Arrays.asList("Single", "Married", "Divorced"); - - @AfterClass - public static void tearDownAll() { - + QuickFixSeleniumPage quickFixSeleniumPage = new QuickFixSeleniumPage(); + private RadioButtonElement maritalStatusRadioButton; + private final static By selectorMaritalStatus = By.cssSelector("div[class='radio_wrap']"); + private final static int radioElementsCount = 3; + private final static List possibleValues = Arrays.asList("Single", "Married", "Divorced"); + + @Override + public void setUp() { + BasePage.getDriver() + .get(PageSubURLsEnum.WWW_FONT_URL.subURL() + PageSubURLsEnum.REGISTRATION.subURL()); + maritalStatusRadioButton = BasePage.getDriver() + .elementRadioButton(selectorMaritalStatus); } - + @Test public void testRadioButtonElementsCount() { // check if appropriate number of radio button elements is displayed assertEquals(radioElementsCount, maritalStatusRadioButton.getItemsCount()); } - + @Test public void testPossibleValues() { List elementValues = this.maritalStatusRadioButton.getTextList(); @@ -42,20 +47,20 @@ public void testPossibleValues() { assertEquals(RadioButtonTest.possibleValues.get(i), elementValues.get(i)); } } - + @Test public void testSelection() { // select and check by index maritalStatusRadioButton.selectItemByIndex(0); assertEquals(maritalStatusRadioButton.getSelectedItemIndex(), 0); assertTrue(maritalStatusRadioButton.isItemSelectedByIndex(0)); - + // select and check by value maritalStatusRadioButton.selectItemByValue("married"); assertEquals(maritalStatusRadioButton.getSelectedItemValue(), "married"); assertTrue(maritalStatusRadioButton.isItemSelectedByValue("married")); } - + @Test public void testSelectionSpecifiedItem() { // example of usage Radio Button with other constructor's arguments @@ -66,18 +71,5 @@ public void testSelectionSpecifiedItem() { assertEquals(maritalStatusRadioButton.getSelectedItemIndex(), 2); assertTrue(maritalStatusRadioButton.isItemSelectedByIndex(2)); } - - @Override - public void setUp() { - BasePage.getDriver() - .get(PageSubURLsEnum.WWW_FONT_URL.subURL() + PageSubURLsEnum.REGISTRATION.subURL()); - this.maritalStatusRadioButton = BasePage.getDriver() - .elementRadioButton(selectorMaritalStatus); - } - - @Override - public void tearDown() { - // TODO Auto-generated method stub - } - + } diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/TabTest.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/TabTest.java index 3e26e421..a8f05fc2 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/TabTest.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/TabTest.java @@ -1,41 +1,47 @@ package com.capgemini.mrchecker.selenium.core.tests.webElements; -import com.capgemini.mrchecker.selenium.core.BasePage; -import com.capgemini.mrchecker.selenium.core.enums.PageSubURLsEnum; -import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.TabElement; -import com.capgemini.mrchecker.test.core.BaseTest; -import org.junit.AfterClass; -import org.junit.Test; -import org.openqa.selenium.By; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.openqa.selenium.By; + +import com.capgemini.mrchecker.selenium.core.BasePage; +import com.capgemini.mrchecker.selenium.core.enums.PageSubURLsEnum; +import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.TabElement; +import com.capgemini.mrchecker.test.core.BaseTest; /** * Created by LKURZAJ on 06.03.2017. */ -public class TabTest extends BaseTest { - QuickFixSeleniumPage quickFixSeleniumPage = new QuickFixSeleniumPage(); - private final static By tabSelector = By.cssSelector("ul[role='tablist']"); - private TabElement tabObject; - private final static List possibleValues = Arrays.asList("Tab 1", "Tab 2", "Tab 3"); - private final static By tabChildsSelector = By.cssSelector("li"); - private final static List listSelectedAttributes = Arrays.asList("ui-tabs-active ui-state-active"); - - @AfterClass - public static void tearDownAll() { +@Disabled +public class TabTest extends BaseTest { + QuickFixSeleniumPage quickFixSeleniumPage = new QuickFixSeleniumPage(); + private final static By tabSelector = By.cssSelector("ul[role='tablist']"); + private TabElement tabObject; + private final static List possibleValues = Arrays.asList("Tab 1", "Tab 2", "Tab 3"); + private final static By tabChildsSelector = By.cssSelector("li"); + private final static List listSelectedAttributes = Arrays.asList("ui-tabs-active ui-state-active"); + + @Override + public void setUp() { + BasePage.getDriver() + .get(PageSubURLsEnum.WWW_FONT_URL.subURL() + PageSubURLsEnum.TABS.subURL()); + tabObject = BasePage.getDriver() + .elementTab(TabTest.tabSelector); } - + @Test public void testRadioButtonElementsCount() { // check if appropriate number of radio button elements is displayed assertEquals(3, tabObject.getItemsCount()); } - + @Test public void testPossibleValues() { List elementValues = this.tabObject.getTextList(); @@ -43,19 +49,19 @@ public void testPossibleValues() { assertEquals(TabTest.possibleValues.get(i), elementValues.get(i)); } } - + @Test public void testSelection() { // select and check by index tabObject.selectItemByIndex(2); assertEquals(tabObject.getSelectedItemIndex(), 2); assertTrue(tabObject.isItemSelectedByIndex(2)); - + // select and check by text tabObject.selectItemByText("Tab 1"); assertEquals(tabObject.getSelectedItemText(), "Tab 1"); } - + @Test public void testSelectionSpecifiedItem() { tabObject = BasePage.getDriver() @@ -65,16 +71,5 @@ public void testSelectionSpecifiedItem() { assertEquals(tabObject.getSelectedItemIndex(), 1); assertTrue(tabObject.isItemSelectedByIndex(1)); } - - @Override - public void setUp() { - BasePage.getDriver() - .get(PageSubURLsEnum.WWW_FONT_URL.subURL() + PageSubURLsEnum.TABS.subURL()); - this.tabObject = BasePage.getDriver() - .elementTab(TabTest.tabSelector); - } - - @Override - public void tearDown() { - } + } diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/TooltipTest.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/TooltipTest.java index fc4ea286..6677e3fa 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/TooltipTest.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/TooltipTest.java @@ -1,28 +1,32 @@ package com.capgemini.mrchecker.selenium.core.tests.webElements; +import static org.junit.Assert.assertTrue; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.openqa.selenium.By; + import com.capgemini.mrchecker.selenium.core.BasePage; import com.capgemini.mrchecker.selenium.core.enums.PageSubURLsEnum; import com.capgemini.mrchecker.selenium.core.newDrivers.elementType.TooltipElement; import com.capgemini.mrchecker.test.core.BaseTest; -import org.junit.AfterClass; -import org.junit.Test; -import org.openqa.selenium.By; - -import static org.junit.Assert.assertTrue; /** * Created by LKURZAJ on 08.03.2017. */ +@Disabled public class TooltipTest extends BaseTest { - QuickFixSeleniumPage quickFixSeleniumPage = new QuickFixSeleniumPage(); - private final static By tooltipSelector = By.cssSelector("div.ui-tooltip"); - private final static By inputTextSelector = By.cssSelector("input[id='age']"); - TooltipElement tooltipElement; - - @AfterClass - public static void tearDownAll() { + QuickFixSeleniumPage quickFixSeleniumPage = new QuickFixSeleniumPage(); + private final static By tooltipSelector = By.cssSelector("div.ui-tooltip"); + private final static By inputTextSelector = By.cssSelector("input[id='age']"); + TooltipElement tooltipElement; + + @Override + public void setUp() { + BasePage.getDriver() + .get(PageSubURLsEnum.WWW_FONT_URL.subURL() + PageSubURLsEnum.TOOLTIP.subURL()); } - + @Test public void test() { // hover mouse on input text element @@ -32,21 +36,11 @@ public void test() { .perform(); this.tooltipElement = BasePage.getDriver() .elementTooltip(TooltipTest.tooltipSelector); - + // check if tooltip is displayed assertTrue(this.tooltipElement.isDisplayed()); - + // check if tooltip text contains appropriate expression assertTrue(this.tooltipElement.isTextContains("We ask for your age")); } - - @Override - public void setUp() { - BasePage.getDriver() - .get(PageSubURLsEnum.WWW_FONT_URL.subURL() + PageSubURLsEnum.TOOLTIP.subURL()); - } - - @Override - public void tearDown() { - } } diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/_TestSuiteRemote.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/_TestSuiteRemote.java deleted file mode 100644 index e0894191..00000000 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/tests/webElements/_TestSuiteRemote.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.capgemini.mrchecker.selenium.core.tests.webElements; - -import org.junit.runner.RunWith; - -import com.googlecode.junittoolbox.ExcludeCategories; -import com.googlecode.junittoolbox.SuiteClasses; -import com.googlecode.junittoolbox.WildcardPatternSuite; - -@RunWith(WildcardPatternSuite.class) -@ExcludeCategories({}) -@SuiteClasses({ "*Test.class" }) - -public class _TestSuiteRemote { - -} diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/utils/OperationsOnFilesTest.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/utils/OperationsOnFilesTest.java index f297f505..1d66c8d1 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/utils/OperationsOnFilesTest.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/utils/OperationsOnFilesTest.java @@ -3,13 +3,13 @@ import java.io.File; import java.io.IOException; -import org.junit.After; import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import com.capgemini.mrchecker.selenium.core.utils.OperationsOnFiles; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +@Disabled public class OperationsOnFilesTest { private String testSourceFile = "sourceTest.txt"; @@ -25,7 +25,7 @@ public class OperationsOnFilesTest { File goodTargetFile; File badTargetfile; - @Before + @BeforeEach public void setUp() throws IOException { goodSourceFile = new File(goodSourceFilePath); badSourceFile = new File(badSourceFilePath); @@ -33,13 +33,13 @@ public void setUp() throws IOException { badTargetfile = new File(badTargetFilePath); Assert.assertTrue("Failed to create source directories.", goodSourceFile.getParentFile() - .mkdirs()); + .mkdirs()); Assert.assertTrue("Failed to create source file.", goodSourceFile.createNewFile()); Assert.assertTrue("Failed to create target directories.", goodTargetFile.getParentFile() - .mkdirs()); + .mkdirs()); } - @After + @AfterEach public void tearDown() throws IOException { OperationsOnFiles.removeFileAndParentsIfEmpty(goodSourceFile.toPath()); OperationsOnFiles.removeFileAndParentsIfEmpty(goodTargetFile.toPath()); diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/tags/IntegrationTest.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/tags/IntegrationTest.java new file mode 100644 index 00000000..5940fd0f --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/tags/IntegrationTest.java @@ -0,0 +1,14 @@ +package com.capgemini.mrchecker.selenium.tags; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import org.junit.jupiter.api.Tag; + +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +@Tag("IntegrationTest") +public @interface IntegrationTest { +} \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/tags/UnitTest.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/tags/UnitTest.java new file mode 100644 index 00000000..aba7915d --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/tags/UnitTest.java @@ -0,0 +1,14 @@ +package com.capgemini.mrchecker.selenium.tags; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import org.junit.jupiter.api.Tag; + +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +@Tag("UnitTest") +public @interface UnitTest { +} \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/testsuites/UnitTestsSuite.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/testsuites/UnitTestsSuite.java new file mode 100644 index 00000000..6788bfb5 --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/testsuites/UnitTestsSuite.java @@ -0,0 +1,12 @@ +package com.capgemini.mrchecker.selenium.testsuites; + +import org.junit.platform.runner.JUnitPlatform; +import org.junit.platform.suite.api.IncludeTags; +import org.junit.platform.suite.api.SelectPackages; +import org.junit.runner.RunWith; + +@RunWith(JUnitPlatform.class) +@IncludeTags({ "UnitTest" }) +@SelectPackages("com.capgemini.mrchecker.selenium") +public class UnitTestsSuite { +} diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/BasePageTest.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/unit/BasePageTest.java similarity index 57% rename from mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/BasePageTest.java rename to mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/unit/BasePageTest.java index 775d7460..dd09af76 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/BasePageTest.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/unit/BasePageTest.java @@ -1,33 +1,28 @@ -package com.capgemini.mrchecker.selenium; +package com.capgemini.mrchecker.selenium.unit; import static org.junit.Assert.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.ResourceLock; import com.capgemini.mrchecker.selenium.core.BasePage; +import com.capgemini.mrchecker.selenium.tags.UnitTest; import com.capgemini.mrchecker.test.core.BaseTest; +import com.capgemini.mrchecker.test.core.utils.PageFactory; +@UnitTest +@ResourceLock(value = "SingleThread") public class BasePageTest extends BaseTest { - @Override - public void setUp() { - - } - - @Override - public void tearDown() { - - } - @Test public void testGetDriver() { - TestPage testPage = new TestPage(); + TestPage testPage = PageFactory.getPageInstance(TestPage.class); assertEquals("", "Google", testPage.pageTitle()); } - private class TestPage extends BasePage { + public static class TestPage extends BasePage { @Override public boolean isLoaded() { diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/base/properties/PropertiesManagerTest.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/unit/base/properties/PropertiesManagerTest.java similarity index 59% rename from mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/base/properties/PropertiesManagerTest.java rename to mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/unit/base/properties/PropertiesManagerTest.java index 1c08ae72..39de6456 100644 --- a/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/core/base/properties/PropertiesManagerTest.java +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/unit/base/properties/PropertiesManagerTest.java @@ -1,72 +1,93 @@ -package com.capgemini.mrchecker.selenium.core.base.properties; +package com.capgemini.mrchecker.selenium.unit.base.properties; -import com.capgemini.mrchecker.test.core.base.properties.PropertiesSettingsModule; -import com.google.inject.Guice; -import com.google.inject.Injector; -import org.junit.*; +import static org.junit.Assert.assertEquals; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.InputStream; import java.nio.file.Paths; -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.ResourceLock; -public class PropertiesManagerTest { +import com.capgemini.mrchecker.selenium.core.base.properties.PropertiesSelenium; +import com.capgemini.mrchecker.selenium.tags.UnitTest; +import com.capgemini.mrchecker.test.core.base.properties.PropertiesSettingsModule; +import com.capgemini.mrchecker.test.core.exceptions.BFInputDataException; +import com.google.inject.Guice; +import com.google.inject.Injector; - @BeforeClass +@UnitTest +@ResourceLock(value = "SingleThread") +public class PropertiesManagerTest { + + @BeforeAll public static void setUpBeforeClass() { } - - @AfterClass + + @AfterAll public static void tearDownAfterClass() { } - + private PropertiesSelenium propertiesSelenium; - - @Before + + @BeforeEach public void setUp() { String path = System.getProperty("user.dir") + Paths.get("/src/test/resources/settings.properties"); - Injector i = Guice.createInjector(PropertiesSettingsModule.init(path)); - this.propertiesSelenium = i.getInstance(PropertiesSelenium.class); + try { + InputStream fileSource = new FileInputStream(path); + + Injector i = Guice.createInjector(PropertiesSettingsModule.init(fileSource)); + this.propertiesSelenium = i.getInstance(PropertiesSelenium.class); + } catch (FileNotFoundException e) { + throw new BFInputDataException("Default file not found in: " + path); + } + } - - @After + + @AfterEach public void tearDown() { PropertiesSettingsModule.delInstance(); } - + @Test public void testParamterGetChrome() { assertEquals("", "chromedriver.exe", propertiesSelenium.getSeleniumChrome()); } - + @Test public void testParamterGetFirefox() { assertEquals("", "geckodriver.exe", propertiesSelenium.getSeleniumFirefox()); } - + @Test public void testParamterGetIE() { assertEquals("", "IEDriverServer.exe", propertiesSelenium.getSeleniumIE()); } - + @Test public void testParamterGetEdge() { assertEquals("", "edgedriver.exe", propertiesSelenium.getSeleniumEdge()); } - + @Test public void testParamterGetOpera() { assertEquals("", "operadriver.exe", propertiesSelenium.getSeleniumOpera()); } - + // @Ignore @Test public void testDefaultParamters() { PropertiesSettingsModule.delInstance(); - + Injector i = Guice.createInjector(PropertiesSettingsModule.init()); PropertiesSelenium propertiesSelenium = i.getInstance(PropertiesSelenium.class); - + assertEquals("", "./lib/webdrivers/chrome/chromedriver.exe", propertiesSelenium.getSeleniumChrome()); } - + } diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/unit/base/runtime/RuntimeParametersTest.java b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/unit/base/runtime/RuntimeParametersTest.java new file mode 100644 index 00000000..16c02361 --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/java/com/capgemini/mrchecker/selenium/unit/base/runtime/RuntimeParametersTest.java @@ -0,0 +1,189 @@ +package com.capgemini.mrchecker.selenium.unit.base.runtime; + +import static com.capgemini.mrchecker.selenium.core.base.runtime.RuntimeParametersSelenium.INVALID_IE_NAME; +import static com.capgemini.mrchecker.selenium.core.base.runtime.RuntimeParametersSelenium.VALID_IE_NAME; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.hamcrest.core.IsInstanceOf.instanceOf; +import static org.hamcrest.core.IsNull.nullValue; +import static org.junit.Assert.fail; + +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.function.Consumer; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.ResourceLock; + +import com.capgemini.mrchecker.selenium.core.base.runtime.RuntimeParametersSelenium; +import com.capgemini.mrchecker.selenium.tags.UnitTest; + +@UnitTest +@ResourceLock(value = "SingleThread") +public class RuntimeParametersTest { + + private static final Map STARTUP_PARAMETERS_VALUES = new LinkedHashMap() { + { + put("browser", "magicbrowser"); + put("browserVersion", "11.0"); + put("seleniumGrid", "smth"); + put("os", "linux"); + put("browserOptions", + "headless;window-size=1200x600;testEquals=FirstEquals=SecondEquals;--testMe;acceptInsecureCerts=true;maxInstances=3"); + } + }; + + public static final String DEFAULT_BROWSER_VALUE = "chrome"; + public static final String BROWSER_OPTIONS_TEST_KEY = "browserOptionsTestKey"; + + @BeforeEach + public void setUp() { + STARTUP_PARAMETERS_VALUES.forEach(System::setProperty); + refreshAllParameters(); + } + + @AfterEach + public void tearDown() { + STARTUP_PARAMETERS_VALUES.forEach((k, v) -> System.clearProperty(k)); + refreshAllParameters(); + } + + private static void refreshAllParameters() { + doForEachParam(RuntimeParametersSelenium::refreshParameterValue); + } + + private static void doForEachParam(Consumer applyFunction) { + Arrays.stream(RuntimeParametersSelenium.values()) + .forEach(applyFunction); + } + + @Test + public void shouldGetAllStartupProperties() { + doForEachParam((e) -> assertThat(e.toString() + " failed!", e.getValue(), is(equalTo(STARTUP_PARAMETERS_VALUES.get(e.getKey()))))); + } + + @Test + public void shouldGetReturnLowercaseBrowserValue() { + System.setProperty("browser", STARTUP_PARAMETERS_VALUES.get("browser") + .toUpperCase()); + + refreshAllParameters(); + String browserValue = RuntimeParametersSelenium.BROWSER.getValue(); + + assertThat(browserValue, is(equalTo(STARTUP_PARAMETERS_VALUES.get(RuntimeParametersSelenium.BROWSER.getKey())))); + } + + @Test + public void shouldGetReturnDefaultBrowserValue() { + Arrays.stream(new String[] { "", "null" }) + .forEach((s) -> { + System.setProperty("browser", s); + + refreshAllParameters(); + String browserValue = RuntimeParametersSelenium.BROWSER.getValue(); + + assertThat("Failed for '" + s + "'!", browserValue, is(equalTo(DEFAULT_BROWSER_VALUE))); + }); + } + + @Test + public void shouldGetReturnDefaultBrowserValueWhenNoSystemProperty() { + System.clearProperty("browser"); + + refreshAllParameters(); + String browserValue = RuntimeParametersSelenium.BROWSER.getValue(); + + assertThat(browserValue, is(equalTo(DEFAULT_BROWSER_VALUE))); + } + + @Test + public void shouldGetValidIEName() { + System.setProperty("browser", INVALID_IE_NAME); + + refreshAllParameters(); + String browserValue = RuntimeParametersSelenium.BROWSER.getValue(); + + assertThat(browserValue, is(equalTo(VALID_IE_NAME))); + + } + + @Test + public void shouldBrowserOptionBeBoolean() { + shouldBrowserOptionBeOfClass("true", Boolean.class); + } + + @Test + public void shouldBrowserOptionBeInteger() { + shouldBrowserOptionBeOfClass("123", Integer.class); + } + + @Test + public void shouldBrowserOptionBeIntegerFloat() { + shouldBrowserOptionBeOfClass("123.321", Float.class); + } + + @Test + public void shouldBrowserOptionBeIntegerString() { + shouldBrowserOptionBeOfClass("blue", String.class); + } + + private void shouldBrowserOptionBeOfClass(String value, Class clazz) { + System.setProperty("browserOptions", BROWSER_OPTIONS_TEST_KEY + "=" + value); + + refreshAllParameters(); + Map browserOptionsValues = RuntimeParametersSelenium.BROWSER_OPTIONS.getValues(); + Object optionValue = browserOptionsValues.get(BROWSER_OPTIONS_TEST_KEY); + + assertThat(optionValue, is(instanceOf(clazz))); + } + + @Test + public void shouldGetProperBrowserOptionsValuesSize() { + final String[] browserOptions = STARTUP_PARAMETERS_VALUES.get(RuntimeParametersSelenium.BROWSER_OPTIONS.getKey()) + .split(";"); + + int browserOptionsCount = RuntimeParametersSelenium.BROWSER_OPTIONS.getValues() + .size(); + + assertThat(browserOptionsCount, is(equalTo(browserOptions.length))); + } + + @Test + public void shouldGetProperBrowserOptionsValuesContents() { + final String[] browserOptions = STARTUP_PARAMETERS_VALUES.get(RuntimeParametersSelenium.BROWSER_OPTIONS.getKey()) + .split(";"); + + Map browserOptionsValues = RuntimeParametersSelenium.BROWSER_OPTIONS.getValues(); + + browserOptionsValues.forEach((key, value) -> { + try { + String browserOption = Arrays.stream(browserOptions) + .filter(s -> s.startsWith(key)) + .findFirst() + .orElseThrow(Exception::new); + + assertThat(browserOption.endsWith(value.toString()), is(equalTo(true))); + } catch (Exception e) { + fail(key + " does NOT exist"); + } + }); + } + + @Test + public void shouldGetProperBrowserOptionsValuesBeNull() { + Map browserOptionsValues = RuntimeParametersSelenium.BROWSER.getValues(); + + assertThat(browserOptionsValues, is(nullValue())); + } + + @Test + public void shouldToStringReturnKeyValue() { + String toStringValue = RuntimeParametersSelenium.BROWSER.toString(); + + assertThat(toStringValue, is(equalTo("browser=" + STARTUP_PARAMETERS_VALUES.get("browser")))); + } +} \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/test/resources/allure.properties b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/resources/allure.properties new file mode 100644 index 00000000..6c1e0bb1 --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/resources/allure.properties @@ -0,0 +1 @@ +allure.results.directory=target/allure-results \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-selenium-module/src/test/resources/junit-platform.properties b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/resources/junit-platform.properties new file mode 100644 index 00000000..0a5f88f7 --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-selenium-module/src/test/resources/junit-platform.properties @@ -0,0 +1,8 @@ +junit.jupiter.extensions.autodetection.enabled=true +junit.jupiter.execution.parallel.enabled=true +#junit.jupiter.execution.parallel.mode.default=concurrent +junit.jupiter.execution.parallel.mode.default=same_thread +junit.jupiter.execution.parallel.mode.classes.default=concurrent +#junit.jupiter.execution.parallel.mode.classes.default=same_thread +junit.jupiter.execution.parallel.config.strategy=dynamic +junit.jupiter.execution.parallel.config.dynamic.factor=1 diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/pom.xml b/mrchecker-framework-modules/mrchecker-webapi-module/pom.xml index 5e1717b6..6e1caeda 100644 --- a/mrchecker-framework-modules/mrchecker-webapi-module/pom.xml +++ b/mrchecker-framework-modules/mrchecker-webapi-module/pom.xml @@ -1,25 +1,25 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 mrchecker-test-framework com.capgemini.mrchecker - 2.4.2-SNAPSHOT + 3.0.1-SNAPSHOT mrchecker-webapi-module - 1.2.3-SNAPSHOT + 1.2.4-SNAPSHOT jar MrChecker - WebApi - Module - + MrChecker WebApi supports: - testing REST and SOAP services, - sending REST queries (POST, GET, PUT, PATCH, DELETE), - parsing XML, JSON and HTML documents, - handling Cookies, - - SSO (Single Sign-On) authentication process. + - SSO (Single Sign-On) authentication process. https://github.com/devonfw/devonfw-testing @@ -32,21 +32,21 @@ Lukasz Stefaniszyn lukasz.stefaniszyn@capgemini.com - Capgemini - Nearshore Test Center - Poland + Capgemini - Nearshore Test Center - Poland http://nsc.capgemini.com/nearshoretestcenter Tomasz Supel tomasz.supel@capgemini.com - Capgemini - Nearshore Test Center - Poland + Capgemini - Nearshore Test Center - Poland http://nsc.capgemini.com/nearshoretestcenter Pawel Szczesny pawel.szczesny@capgemini.com - Capgemini - Nearshore Test Center - Poland + Capgemini - Nearshore Test Center - Poland http://nsc.capgemini.com/nearshoretestcenter @@ -65,12 +65,9 @@ - - UTF8 - 4.12.1.4-SNAPSHOT - + 5.6.2.1-SNAPSHOT 2.21.0 @@ -123,6 +120,24 @@ jasypt + + + + io.qameta.allure + allure-junit5 + test + + + + io.qameta.allure + allure-junit-platform + + + + io.qameta.allure + allure-java-commons + + diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/core/BasePageWebAPI.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/core/BasePageWebAPI.java index bbf13022..d4c532fa 100644 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/core/BasePageWebAPI.java +++ b/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/core/BasePageWebAPI.java @@ -1,16 +1,7 @@ package com.capgemini.mrchecker.webapi.core; -import com.capgemini.mrchecker.test.core.BaseTest; -import com.capgemini.mrchecker.test.core.BaseTestWatcher; -import com.capgemini.mrchecker.test.core.ITestObserver; -import com.capgemini.mrchecker.test.core.ModuleType; -import com.capgemini.mrchecker.test.core.analytics.IAnalytics; -import com.capgemini.mrchecker.test.core.base.properties.PropertiesSettingsModule; -import com.capgemini.mrchecker.test.core.logger.BFLogger; -import com.capgemini.mrchecker.webapi.core.base.driver.DriverManager; -import com.capgemini.mrchecker.webapi.core.base.properties.PropertiesFileSettings; -import com.capgemini.mrchecker.webapi.core.base.runtime.RuntimeParameters; import java.io.IOException; +import java.util.Objects; import javax.xml.parsers.FactoryConfigurationError; import javax.xml.parsers.ParserConfigurationException; @@ -20,21 +11,30 @@ import org.xml.sax.SAXException; -import com.capgemini.mrchecker.webapi.soap.SoapMessageGenerator; +import com.capgemini.mrchecker.test.core.BaseTest; +import com.capgemini.mrchecker.test.core.ModuleType; +import com.capgemini.mrchecker.test.core.Page; +import com.capgemini.mrchecker.test.core.analytics.IAnalytics; +import com.capgemini.mrchecker.test.core.base.properties.PropertiesSettingsModule; +import com.capgemini.mrchecker.test.core.logger.BFLogger; +import com.capgemini.mrchecker.webapi.core.base.driver.DriverManager; +import com.capgemini.mrchecker.webapi.core.base.properties.PropertiesFileSettings; +import com.capgemini.mrchecker.webapi.core.base.runtime.RuntimeParameters; +import com.capgemini.mrchecker.webapi.core.soap.SoapMessageGenerator; import com.google.inject.Guice; import com.jamesmurty.utils.XMLBuilder; -abstract public class BasePageWebAPI implements ITestObserver, IWebAPI { +public abstract class BasePageWebAPI extends Page implements IWebAPI { private static DriverManager driver = null; private final static PropertiesFileSettings propertiesFileSettings; - private final static IAnalytics analytics; - public final static String analitycsCategoryName = "WebAPI-Module"; + private final static IAnalytics ANALYTICS; + public final static String ANALYTICS_CATEGORY_NAME = "WebAPI-Module"; static { // Get analytics instance created in BaseTets - analytics = BaseTest.getAnalytics(); + ANALYTICS = BaseTest.getAnalytics(); // Get and then set properties information from selenium.settings file propertiesFileSettings = setPropertiesSettings(); @@ -43,53 +43,15 @@ abstract public class BasePageWebAPI implements ITestObserver, IWebAPI { setRuntimeParametersWebApi(); // Read Environment variables either from environmnets.csv or any other input data. - setEnvironmetInstance(); + setEnvironmentInstance(); } public static IAnalytics getAnalytics() { - return BasePageWebAPI.analytics; + return ANALYTICS; } public BasePageWebAPI() { - this(getDriver()); - } - - public BasePageWebAPI(DriverManager driver) { - // Add given module to Test core Observable list - this.addObserver(); - } - - @Override - public void addObserver() { - BaseTestWatcher.addObserver(this); - } - - @Override - public void onTestFailure() { - BFLogger.logDebug("BasePage.onTestFailure " + this.getClass() - .getSimpleName()); - } - - @Override - public void onTestSuccess() { - // All actions needed while test method is success - BFLogger.logDebug("BasePage.onTestSuccess " + this.getClass() - .getSimpleName()); - } - - @Override - public void onTestFinish() { - // All actions needed while test class is finishing - BFLogger.logDebug("BasePage.onTestFinish " + this.getClass() - .getSimpleName()); - BaseTestWatcher.removeObserver(this); - } - - @Override - public void onTestClassFinish() { - BFLogger.logDebug("BasePage.onTestClassFinish " + this.getClass() - .getSimpleName()); - BFLogger.logDebug("driver:" + getDriver().toString()); + getDriver(); } @Override @@ -98,7 +60,7 @@ public ModuleType getModuleType() { } public static DriverManager getDriver() { - if (BasePageWebAPI.driver == null) { + if (Objects.isNull(BasePageWebAPI.driver)) { // Create module driver BasePageWebAPI.driver = new DriverManager(propertiesFileSettings); } @@ -107,19 +69,18 @@ public static DriverManager getDriver() { private static PropertiesFileSettings setPropertiesSettings() { // Get and then set properties information from settings.properties file - PropertiesFileSettings propertiesFileSettings = Guice.createInjector(PropertiesSettingsModule.init()) - .getInstance(PropertiesFileSettings.class); - return propertiesFileSettings; + return Guice.createInjector(PropertiesSettingsModule.init()) + .getInstance(PropertiesFileSettings.class); } private static void setRuntimeParametersWebApi() { // Read System or maven parameters BFLogger.logDebug(java.util.Arrays.asList(RuntimeParameters.values()) - .toString()); + .toString()); } - private static void setEnvironmetInstance() { + private static void setEnvironmentInstance() { /* * Environment variables either from environmnets.csv or any other input data. For now there is no properties * settings file for Selenium module. In future, please have a look on Core Module IEnvironmentService @@ -128,7 +89,7 @@ private static void setEnvironmetInstance() { } - public class SOAPTemplate { + public static class SOAPTemplate { private XMLBuilder xmlBody; @@ -146,9 +107,10 @@ public String getMessage() { String message = ""; try { SOAPMessage soapMessage = SoapMessageGenerator.createSOAPmessage(this.getRoot() - .asString()); + .asString()); message = SoapMessageGenerator.printSoapMessage(soapMessage); } catch (SOAPException | SAXException | IOException | ParserConfigurationException | TransformerException e) { + // TODO: refactor that new Exception(e); } return message; @@ -170,6 +132,7 @@ private void setRoot(String nodeName) { try { this.xmlBody = XMLBuilder.create(nodeName); } catch (ParserConfigurationException | FactoryConfigurationError e) { + // TODO: refactor that new Exception(e); } } diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/core/BasePageWebAPIAutoRegistration.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/core/BasePageWebAPIAutoRegistration.java new file mode 100644 index 00000000..0672fde3 --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/core/BasePageWebAPIAutoRegistration.java @@ -0,0 +1,14 @@ +package com.capgemini.mrchecker.webapi.core; + +/** + * The instances of BasePageWebAPIAutoRegistration class are added to the test execution observer automatically in + * constructor. + * Although this operation is unsafe, it's been added to support migration from MrChecker Junit4 to Junit5. + */ +@Deprecated +public abstract class BasePageWebAPIAutoRegistration extends BasePageWebAPI { + + public BasePageWebAPIAutoRegistration() { + addToTestExecutionObserver(); + } +} diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/core/IWebAPI.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/core/IWebAPI.java index dbb159eb..7a34a42e 100644 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/core/IWebAPI.java +++ b/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/core/IWebAPI.java @@ -5,5 +5,5 @@ public interface IWebAPI { /** * @return URL Endpoint in String format */ - public String getEndpoint(); + String getEndpoint(); } diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/core/base/driver/DriverManager.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/core/base/driver/DriverManager.java index 2850ca6e..98c8ad46 100644 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/core/base/driver/DriverManager.java +++ b/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/core/base/driver/DriverManager.java @@ -5,6 +5,7 @@ import java.io.IOException; import java.net.ServerSocket; +import java.util.Objects; import com.capgemini.mrchecker.test.core.logger.BFLogger; import com.capgemini.mrchecker.webapi.core.base.properties.PropertiesFileSettings; @@ -30,16 +31,14 @@ public class DriverManager { @Inject public DriverManager(@Named("properties") PropertiesFileSettings propertiesFileSettings) { - - if (null == DriverManager.propertiesFileSettings) { + if (Objects.isNull(DriverManager.propertiesFileSettings)) { DriverManager.propertiesFileSettings = propertiesFileSettings; } - this.start(); + start(); } public void start() { - if (DriverManager.propertiesFileSettings.isVirtualServerEnabled()) { DriverManager.getDriverVirtualService(); } @@ -51,19 +50,21 @@ public void stop() { closeDriverVirtualServer(); BFLogger.logDebug("Closing Driver in stop()"); } catch (Exception e) { + // TODO: refactor that e.printStackTrace(); } } + // TODO: refactor that @Override protected void finalize() throws Throwable { super.finalize(); - this.stop(); + stop(); } public static void clearAllDrivers() { - driverVirtualizedService = new ThreadLocal(); -// driverVirtualizedService.remove(); + driverVirtualizedService = new ThreadLocal<>(); + // driverVirtualizedService.remove(); } public static WireMock getDriverVirtualService() { @@ -89,7 +90,7 @@ public static String getHttpHost() { VirtualizedService virtualizedService = getVirtualizedService(); return virtualizedService.getHttpHost(); } - + public static String getEndpointBaseUri() { VirtualizedService virtualizedService = getVirtualizedService(); return virtualizedService.getEndpointBaseUri(); @@ -97,7 +98,7 @@ public static String getEndpointBaseUri() { private static VirtualizedService getVirtualizedService() { VirtualizedService virtualizedService = driverVirtualizedService.get(); - if (null == virtualizedService) { + if (Objects.isNull(virtualizedService)) { virtualizedService = createDriverVirtualServer(); driverVirtualizedService.set(virtualizedService); } @@ -113,18 +114,18 @@ public static RequestSpecification getDriverWebAPI() { public static void closeDriverVirtualServer() { VirtualizedService virtualizedService = driverVirtualizedService.get(); - if (null != virtualizedService) { + if (!Objects.isNull(virtualizedService)) { WireMock driver = virtualizedService.getDriver(); WireMockServer driverServer = virtualizedService.getDriverServer(); BFLogger.logDebug( "Closing communication to Virualize Service under: " + driver.toString()); try { - if (null != driver) { + if (!Objects.isNull(driver)) { // driver.shutdown(); } - if (null != driverServer) { + if (!Objects.isNull(driverServer)) { driverServer.stop(); } @@ -195,7 +196,7 @@ private String getHost() { private int getPort() { return RuntimeParameters.MOCK_HTTP_PORT.getValue() .isEmpty() - ? this.findFreePort() + ? findFreePort() : getInteger(RuntimeParameters.MOCK_HTTP_PORT.getValue()); } @@ -210,9 +211,7 @@ private int getPort() { * if unable to find a free port */ private int findFreePort() throws IllegalStateException { - ServerSocket socket = null; - try { - socket = new ServerSocket(0); + try (ServerSocket socket = new ServerSocket(0)) { socket.setReuseAddress(true); int port = socket.getLocalPort(); try { @@ -222,14 +221,7 @@ private int findFreePort() throws IllegalStateException { } return port; } catch (IOException e) { - } finally { - if (socket != null) { - try { - socket.close(); - } catch (IOException e) { - // Ignore IOException on close() - } - } + // TODO: refactor that } throw new IllegalStateException("Could not find a free TCP/IP port to start embedded Jetty HTTP Server on"); } @@ -249,6 +241,5 @@ private int getInteger(String value) { public VirtualizedService getDriver() { return null; } - } } diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/core/base/driver/VirtualizedService.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/core/base/driver/VirtualizedService.java index fec7d799..d1db627e 100644 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/core/base/driver/VirtualizedService.java +++ b/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/core/base/driver/VirtualizedService.java @@ -5,10 +5,10 @@ public class VirtualizedService { - private WireMock driver; - private WireMockServer driverServer; - private String httpHost; - private int httpPort; + private final WireMock driver; + private final WireMockServer driverServer; + private final String httpHost; + private final int httpPort; VirtualizedService(WireMock driver, WireMockServer driverServer, String httpHost, int httpPort) { this.driver = driver; @@ -33,13 +33,11 @@ public int getHttpPort() { public String getHttpHost() { return httpHost; } - - public String getEndpointBaseUri(){ + + public String getEndpointBaseUri() { return getHttpHost() + ":" + getHttpPort(); } - - - + @Override public String toString() { return "Service for host " + getEndpointBaseUri(); diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/core/base/properties/PropertiesFileSettings.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/core/base/properties/PropertiesFileSettings.java index 7353204a..74efa671 100644 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/core/base/properties/PropertiesFileSettings.java +++ b/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/core/base/properties/PropertiesFileSettings.java @@ -5,16 +5,16 @@ public class PropertiesFileSettings { - private boolean isVirtualServerEnabled = true; // default value + private boolean isVirtualServerEnabled = true; @Inject(optional = true) private void setProperty_isVirtualServerEnabled(@Named("webapi.isVirtualServerEnabled") String value) { - this.isVirtualServerEnabled = value.toLowerCase() - .equals("false") ? false : true; + this.isVirtualServerEnabled = !value.toLowerCase() + .equals("false"); } public boolean isVirtualServerEnabled() { - return this.isVirtualServerEnabled; + return isVirtualServerEnabled; } } diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/core/base/runtime/RuntimeParameters.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/core/base/runtime/RuntimeParameters.java index bb10a8f9..f6f40aab 100644 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/core/base/runtime/RuntimeParameters.java +++ b/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/core/base/runtime/RuntimeParameters.java @@ -1,6 +1,8 @@ package com.capgemini.mrchecker.webapi.core.base.runtime; -import com.capgemini.mrchecker.test.core.base.runtime.RuntimeParametersI; +import org.apache.commons.lang.StringUtils; + +import com.capgemini.mrchecker.test.core.base.runtime.IRuntimeParameters; /** * This class stores various system properties These parameters are accessible while test case executes Example : @@ -8,37 +10,35 @@ * * @author LUSTEFAN */ -public enum RuntimeParameters implements RuntimeParametersI { +public enum RuntimeParameters implements IRuntimeParameters { // NAME(, ) MOCK_HTTP_PORT("mock_http_port", ""), // -Dmock_http_port="" Default random - MOCK_HTTP_HOST("mock_http_host", "http://localhost"), // -Dmock_http_host="" Default localhost - ; + MOCK_HTTP_HOST("mock_http_host", "http://localhost"); // -Dmock_http_host="" Default localhost - private String paramName; - private String paramValue; - private String defaultValue; + private final String paramName; + private String paramValue; + private final String defaultValue; - private RuntimeParameters(String paramName, String defaultValue) { + RuntimeParameters(String paramName, String defaultValue) { this.paramName = paramName; this.defaultValue = defaultValue; setValue(); - } @Override public String getValue() { - return this.paramValue; + return paramValue; } - + @Override public String getKey() { - return this.paramName; + return paramName; } - + @Override public String toString() { - return paramName + "=" + this.getValue(); + return getKey() + "=" + getValue(); } @Override @@ -50,11 +50,10 @@ private void setValue() { String paramValue = System.getProperty(this.paramName); paramValue = isSystemParameterEmpty(paramValue) ? this.defaultValue : paramValue.toLowerCase(); this.paramValue = paramValue; - } private boolean isSystemParameterEmpty(String systemParameterValue) { - return (null == systemParameterValue || "".equals(systemParameterValue) || "null".equals(systemParameterValue)); + return (StringUtils.isEmpty(systemParameterValue) || "null".equals(systemParameterValue)); } } diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/soap/SoapMessageGenerator.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/core/soap/SoapMessageGenerator.java similarity index 90% rename from mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/soap/SoapMessageGenerator.java rename to mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/core/soap/SoapMessageGenerator.java index 2d9eae53..6cd6ac8b 100644 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/soap/SoapMessageGenerator.java +++ b/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/core/soap/SoapMessageGenerator.java @@ -1,4 +1,4 @@ -package com.capgemini.mrchecker.webapi.soap; +package com.capgemini.mrchecker.webapi.core.soap; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -50,7 +50,7 @@ public class SoapMessageGenerator { * * * - * + * * @param xmlRequestBody * the body of the SOAP message pasted in XML format * @@ -63,7 +63,7 @@ public class SoapMessageGenerator { * @throws SAXException */ public static SOAPMessage createSOAPmessage(String xmlRequestBody) - throws SOAPException, SAXException, IOException, ParserConfigurationException { + throws SOAPException, SAXException, IOException, ParserConfigurationException { SOAPElement body = stringToSOAPElement(xmlRequestBody); @@ -88,8 +88,8 @@ public static SOAPMessage createSOAPmessage(String xmlRequestBody) } public static String printSoapMessage(final SOAPMessage soapMessage) - throws TransformerFactoryConfigurationError, - TransformerConfigurationException, SOAPException, TransformerException { + throws TransformerFactoryConfigurationError, + TransformerConfigurationException, SOAPException, TransformerException { final TransformerFactory transformerFactory = TransformerFactory.newInstance(); final Transformer transformer = transformerFactory.newTransformer(); @@ -98,7 +98,7 @@ public static String printSoapMessage(final SOAPMessage soapMessage) transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); final Source soapContent = soapMessage.getSOAPPart() - .getContent(); + .getContent(); final ByteArrayOutputStream streamOut = new ByteArrayOutputStream(); final StreamResult result = new StreamResult(streamOut); @@ -109,7 +109,7 @@ public static String printSoapMessage(final SOAPMessage soapMessage) /** * Transform a String to a SOAP element - * + * * @param xmlRequestBody * the string body representation * @return a SOAP element @@ -119,17 +119,17 @@ public static String printSoapMessage(final SOAPMessage soapMessage) * @throws ParserConfigurationException */ private static SOAPElement stringToSOAPElement(String xmlRequestBody) - throws SOAPException, SAXException, IOException, - ParserConfigurationException { + throws SOAPException, SAXException, IOException, + ParserConfigurationException { // Load the XML text into a DOM Document final DocumentBuilderFactory builderFactory = DocumentBuilderFactory - .newInstance(); + .newInstance(); builderFactory.setNamespaceAware(true); final InputStream stream = new ByteArrayInputStream( - xmlRequestBody.getBytes()); + xmlRequestBody.getBytes()); final Document doc = builderFactory.newDocumentBuilder() - .parse(stream); + .parse(stream); // Use SAAJ to convert Document to SOAPElement // Create SoapMessage diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/core/utils/HTMLParser.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/core/utils/HTMLParser.java index 9fed78fd..90760e1b 100644 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/core/utils/HTMLParser.java +++ b/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/core/utils/HTMLParser.java @@ -1,35 +1,39 @@ package com.capgemini.mrchecker.webapi.core.utils; +import java.util.List; +import java.util.stream.Collectors; + import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; -import java.util.List; -import java.util.stream.Collectors; - public final class HTMLParser { - + private HTMLParser() { } - + public static Document parse(String html) { return Jsoup.parse(html); } - + public static Elements getElements(String html, String tag) { return getElements(parse(html), tag); } - + public static Elements getElements(Document document, String tag) { return document.select(tag); } - + public static List getAttributeValueFromElements(Elements elements, String attributeKey) { - return elements.stream().map(el -> el.attr(attributeKey)).collect(Collectors.toList()); + return elements.stream() + .map(el -> el.attr(attributeKey)) + .collect(Collectors.toList()); } - + public static List getTextFromElements(Elements elements) { - return elements.stream().map(Element::text).collect(Collectors.toList()); + return elements.stream() + .map(Element::text) + .collect(Collectors.toList()); } } \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/utils/SimpleXMLParser.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/core/utils/SimpleXMLParser.java similarity index 92% rename from mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/utils/SimpleXMLParser.java rename to mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/core/utils/SimpleXMLParser.java index ff21c7de..a33c8cbb 100644 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/utils/SimpleXMLParser.java +++ b/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/core/utils/SimpleXMLParser.java @@ -1,4 +1,4 @@ -package com.capgemini.mrchecker.webapi.pages.utils; +package com.capgemini.mrchecker.webapi.core.utils; import java.io.IOException; import java.io.InputStream; @@ -35,7 +35,9 @@ public class SimpleXMLParser { * - input stream XML document representation * @return - normalized Document representation of XML * @throws IOException + * IOException * @throws SAXException + * SAXException */ public static Document convertToDocumentNormalized(InputStream inputStream) throws IOException, SAXException { Document simpleXMLPageDocument = dBuilder.parse(inputStream); diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/endpoint/soap/FarenheitToCelsiusMethod_Request_FromCode.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/endpoint/soap/FarenheitToCelsiusMethod_Request_FromCode.java deleted file mode 100644 index 8ef33519..00000000 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/endpoint/soap/FarenheitToCelsiusMethod_Request_FromCode.java +++ /dev/null @@ -1,110 +0,0 @@ -package com.capgemini.mrchecker.webapi.endpoint.soap; - -import java.io.IOException; - -import javax.xml.parsers.FactoryConfigurationError; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.soap.SOAPException; -import javax.xml.soap.SOAPMessage; -import javax.xml.transform.TransformerException; - -import org.xml.sax.SAXException; - -import com.capgemini.mrchecker.webapi.core.BasePageWebAPI; -import com.capgemini.mrchecker.webapi.soap.SoapMessageGenerator; -import com.jamesmurty.utils.XMLBuilder; - -/** - * SOAP endpoint for a SOAP web service that matches a request body with the following SOAP envelope: - * - * - * - * - * 100 - * - * - * - **/ -public class FarenheitToCelsiusMethod_Request_FromCode extends BasePageWebAPI { - - /* - * SOAP response built from Java code - */ - - public FarenheitToCelsiusMethod_Request_FromCode() { - setRoot("FahrenheitToCelsius"); - } - - /** - * @return Generate SOAP request in String format - */ - public String getMessage() { - String message = ""; - try { - SOAPMessage soapMessage = SoapMessageGenerator.createSOAPmessage(this.getRoot() - .asString()); - message = SoapMessageGenerator.printSoapMessage(soapMessage); - } catch (SOAPException | SAXException | IOException | ParserConfigurationException | TransformerException e) { - new Exception(e); - } - return message; - } - - /** - * @return Root XML structure - */ - public XMLBuilder getRoot() { - return xmlBody; - } - - // Set any type of "nodes" under xml Root - /** - * Set "Fahrenheit" node under xml Root - * - * @param fahrenheit - * @return - * 100 - * - */ - public FarenheitToCelsiusMethod_Request_FromCode setFahrenheit(int fahrenheit) { - getRoot().element("Fahrenheit") - .text(Integer.toString(fahrenheit)); - return this; - } - - // Set any nodes under xml Root - /** - * Set "Smth" node under xml Root - * - * @param fahrenheit - * @return - * Hello - * - */ - public FarenheitToCelsiusMethod_Request_FromCode setSmth(String Smth) { - getRoot().element("Smth") - .text(Smth); - return this; - } - - /* - * ---------------------------------- - * Any handy actions after this point - * ---------------------------------- - */ - private XMLBuilder xmlBody; - - private void setRoot(String nodeName) { - try { - this.xmlBody = XMLBuilder.create(nodeName); - } catch (ParserConfigurationException | FactoryConfigurationError e) { - new Exception(e); - } - } - - public String getEndpoint() { - // Useful only for REST Tests - return null; - } -} diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/endpoint/soap/FarenheitToCelsiusMethod_Request_FromFile.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/endpoint/soap/FarenheitToCelsiusMethod_Request_FromFile.java deleted file mode 100644 index 3f247989..00000000 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/endpoint/soap/FarenheitToCelsiusMethod_Request_FromFile.java +++ /dev/null @@ -1,80 +0,0 @@ -package com.capgemini.mrchecker.webapi.endpoint.soap; - -import java.io.File; -import java.io.IOException; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Paths; - -import com.capgemini.mrchecker.webapi.core.BasePageWebAPI; - -/** - * SOAP endpoint for a SOAP web service that matches a response body with the following SOAP envelope: - * - * - * - * - * 100 - * - * - * - **/ -public class FarenheitToCelsiusMethod_Request_FromFile extends BasePageWebAPI { - - /* - * SOAP response built from Java code - */ - // optional parameters - private String path = "/src/test/resources/soapInput/farenheittocelsius/samplerequest.xml"; - - public FarenheitToCelsiusMethod_Request_FromFile() { - } - - public FarenheitToCelsiusMethod_Request_FromFile setFilePath(String path) { - this.path = path; - return this; - } - - public String getMessage() { - String message = ""; - try { - message = getStringOutOfFile(this.path); - } catch (IOException e) { - new Exception(e); - } - return message; - } - - /* - * ------------ - * Util methods - * ------------ - */ - - private String getStringOutOfFile(final String filePath) throws IOException { - String path = System.getProperty("user.dir") + Paths.get(filePath); - if (!exists(path)) { - throw new IOException("Could not find file. Path='" + path + "' does not exist"); - } - - String responseEnvelope = readFile(path, StandardCharsets.UTF_8); - return responseEnvelope; - } - - private boolean exists(String path) { - File f = new File(path); - return f.exists(); - } - - private String readFile(String path, Charset encoding) throws IOException { - byte[] encoded = Files.readAllBytes(Paths.get(path)); - return new String(encoded, encoding); - } - - public String getEndpoint() { - // Useful only for REST Tests - return null; - } -} diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/endpoint/soap/FarenheitToCelsiusMethod_Response_FromCode.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/endpoint/soap/FarenheitToCelsiusMethod_Response_FromCode.java deleted file mode 100644 index d3cdf359..00000000 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/endpoint/soap/FarenheitToCelsiusMethod_Response_FromCode.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.capgemini.mrchecker.webapi.endpoint.soap; - -import java.io.IOException; - -import javax.xml.parsers.FactoryConfigurationError; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.soap.SOAPException; -import javax.xml.soap.SOAPMessage; -import javax.xml.transform.TransformerException; - -import org.xml.sax.SAXException; - -import com.capgemini.mrchecker.webapi.core.BasePageWebAPI; -import com.capgemini.mrchecker.webapi.soap.SoapMessageGenerator; -import com.jamesmurty.utils.XMLBuilder; - -public class FarenheitToCelsiusMethod_Response_FromCode extends BasePageWebAPI { - - /* - * SOAP response built from Java code - */ - - public FarenheitToCelsiusMethod_Response_FromCode() { - setRoot("FahrenheitToCelsiusResponse"); - } - - /** - * @return Generate SOAP request in String format - */ - public String getMessage() { - String message = ""; - try { - SOAPMessage soapMessage = SoapMessageGenerator.createSOAPmessage(this.getRoot() - .asString()); - message = SoapMessageGenerator.printSoapMessage(soapMessage); - } catch (SOAPException | SAXException | IOException | ParserConfigurationException | TransformerException e) { - new Exception(e); - } - return message; - } - - /** - * @return Root XML structure - */ - public XMLBuilder getRoot() { - return xmlBody; - } - - // Set any nodes type under xml Root - - /** - * Set "FahrenheitToCelsiusResult" node under xml Root - * - * @param fahrenheit - * @return - * 37.777 - * - */ - public FarenheitToCelsiusMethod_Response_FromCode setFahrenheitToCelsiusResult(double value) { - getRoot() - .element("FahrenheitToCelsiusResult") - .text(Double.toString(value)); - return this; - } - - /** - * Set "Smth" node under xml Root - * - * @param fahrenheit - * @return - * Hello - * - */ - public FarenheitToCelsiusMethod_Response_FromCode setSmth(String Smth) { - getRoot().element("Smth") - .text(Smth); - return this; - } - - /* - * ---------------------------------- - * Any handy actions after this point - * ---------------------------------- - */ - private XMLBuilder xmlBody; - - private void setRoot(String nodeName) { - try { - this.xmlBody = XMLBuilder.create(nodeName); - } catch (ParserConfigurationException | FactoryConfigurationError e) { - new Exception(e); - } - } - - public String getEndpoint() { - // Useful only for REST Tests - return null; - } -} diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/endpoint/soap/FarenheitToCelsiusMethod_Response_FromFile.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/endpoint/soap/FarenheitToCelsiusMethod_Response_FromFile.java deleted file mode 100644 index 7d794fda..00000000 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/endpoint/soap/FarenheitToCelsiusMethod_Response_FromFile.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.capgemini.mrchecker.webapi.endpoint.soap; - -import java.io.File; -import java.io.IOException; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Paths; - -import com.capgemini.mrchecker.webapi.core.BasePageWebAPI; - -public class FarenheitToCelsiusMethod_Response_FromFile extends BasePageWebAPI { - - /* - * SOAP response built from Java code - */ - private String path = "/src/test/resources/soapInput/farenheittocelsius/sampleresponse.xml"; - - public FarenheitToCelsiusMethod_Response_FromFile() { - } - - public FarenheitToCelsiusMethod_Response_FromFile setFilePath(String path) { - this.path = path; - return this; - } - - public String getMessage() { - String message = ""; - try { - message = getStringOutOfFile(this.path); - } catch (IOException e) { - new Exception(e); - } - return message; - } - - /* - * ------------ - * Util methods - * ------------ - */ - - private String getStringOutOfFile(final String filePath) throws IOException { - String path = System.getProperty("user.dir") + Paths.get(filePath); - if (!exists(path)) { - throw new IOException("Could not find file. Path='" + path + "' does not exist"); - } - - String responseEnvelope = readFile(path, StandardCharsets.UTF_8); - return responseEnvelope; - } - - private boolean exists(String path) { - File f = new File(path); - return f.exists(); - } - - private String readFile(String path, Charset encoding) throws IOException { - byte[] encoded = Files.readAllBytes(Paths.get(path)); - return new String(encoded, encoding); - } - - public String getEndpoint() { - // Useful only for REST Tests - return null; - } -} \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/endpoint/stubs/StubREST_Builder.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/endpoint/stubs/StubREST_Builder.java deleted file mode 100644 index 63f77105..00000000 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/endpoint/stubs/StubREST_Builder.java +++ /dev/null @@ -1,165 +0,0 @@ -package com.capgemini.mrchecker.webapi.endpoint.stubs; - -import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; -import static com.github.tomakehurst.wiremock.client.WireMock.any; -import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl; -import static com.github.tomakehurst.wiremock.client.WireMock.delete; -import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; -import static com.github.tomakehurst.wiremock.client.WireMock.get; -import static com.github.tomakehurst.wiremock.client.WireMock.post; -import static com.github.tomakehurst.wiremock.client.WireMock.put; -import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; - -import java.util.UUID; - -import com.capgemini.mrchecker.test.core.logger.BFLogger; -import com.capgemini.mrchecker.webapi.core.base.driver.DriverManager; -import com.github.tomakehurst.wiremock.client.WireMock; - -import io.restassured.http.ContentType; - -public class StubREST_Builder { - - // required parameters - private String endpointURI; - - // optional parameters - private int statusCode; - - //Driver config - private final String endpointBaseUri; - - public String getEndpointURI() { - return endpointURI; - } - - public String getEndpointBaseUri() { - return this.endpointBaseUri; - } - - - - public int getStatusCode() { - return statusCode; - } - - private StubREST_Builder(StubBuilder builder) { - this.endpointURI = builder.endpointURI; - this.statusCode = builder.statusCode; - this.endpointBaseUri = builder.endpointBaseUri; - - } - - // Builder Class - public static class StubBuilder { - - // required parameters - private String endpointURI; - - // optional parameters - private int statusCode = 200; - private String response = "{ \"message\": \"Hello\" }"; - - ///Driver config - private String endpointBaseUri; - - public StubBuilder(String endpointURI) { - this.endpointURI = endpointURI; - } - - public StubBuilder setStatusCode(int statusCode) { - this.statusCode = statusCode; - return this; - } - - public StubBuilder setResponse(String response) { - this.response = response; - return this; - } - - public StubREST_Builder build() { - UUID id; - - // Bind all stubbers to running WireMock client connection - WireMock driver = DriverManager.getDriverVirtualService(); - this.endpointBaseUri = DriverManager.getEndpointBaseUri(); - WireMock.configureFor(driver); - - // GET - id = WireMock - .givenThat( - // Given that request with ... - get(urlMatching(this.endpointURI)) - .withHeader("Content-Type", equalTo(ContentType.JSON.toString())) - // Return given response ... - .willReturn(aResponse() - .withStatus(this.statusCode) - .withHeader("Content-Type", ContentType.JSON.toString()) - .withBody(this.response) - .withTransformers("body-transformer"))) - .getId(); - BFLogger.logDebug("Mapped GET with ID=" + id.toString()); - - // POST - id = WireMock - .givenThat( - // Given that request with ... - post(urlMatching(this.endpointURI)) - .withHeader("Content-Type", equalTo(ContentType.JSON.toString())) - // Return given response ... - .willReturn(aResponse() - .withStatus(this.statusCode) - .withHeader("Content-Type", ContentType.JSON.toString()) - .withBody(this.response) - .withTransformers("body-transformer"))) - .getId(); - BFLogger.logDebug("Mapped POST with ID=" + id.toString()); - - // PUT - id = WireMock - .givenThat( - // Given that request with ... - put(urlMatching(this.endpointURI)) - .withHeader("Content-Type", equalTo(ContentType.JSON.toString())) - // Return given response ... - .willReturn(aResponse() - .withStatus(this.statusCode) - .withHeader("Content-Type", ContentType.JSON.toString()) - .withBody(this.response) - .withTransformers("body-transformer"))) - .getId(); - BFLogger.logDebug("Mapped PUT with ID=" + id.toString()); - - // DELETE - id = WireMock - .givenThat( - // Given that request with ... - delete(urlMatching(this.endpointURI)) - .withHeader("Content-Type", equalTo(ContentType.JSON.toString())) - // Return given response ... - .willReturn(aResponse() - .withStatus(this.statusCode) - .withHeader("Content-Type", ContentType.JSON.toString()) - .withBody(this.response) - .withTransformers("body-transformer"))) - .getId(); - BFLogger.logDebug("Mapped DELETE with ID=" + id.toString()); - - // CATCH any other requests - id = WireMock - .givenThat( - any(anyUrl()) - .atPriority(10) - .willReturn(aResponse() - .withStatus(404) - .withHeader("Content-Type", ContentType.JSON.toString()) - .withBody("{\"status\":\"Error\",\"message\":\"Endpoint not found\"}") - .withTransformers("body-transformer"))) - .getId(); - BFLogger.logDebug("Mapped AnyOther with ID=" + id.toString()); - return new StubREST_Builder(this); - } - - } - -} diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/endpoint/stubs/StubSOAP_Builder.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/endpoint/stubs/StubSOAP_Builder.java deleted file mode 100644 index 5b267163..00000000 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/endpoint/stubs/StubSOAP_Builder.java +++ /dev/null @@ -1,160 +0,0 @@ -package com.capgemini.mrchecker.webapi.endpoint.stubs; - -import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; -import static com.github.tomakehurst.wiremock.client.WireMock.any; -import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl; -import static com.github.tomakehurst.wiremock.client.WireMock.delete; -import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; -import static com.github.tomakehurst.wiremock.client.WireMock.get; -import static com.github.tomakehurst.wiremock.client.WireMock.matchingXPath; -import static com.github.tomakehurst.wiremock.client.WireMock.post; -import static com.github.tomakehurst.wiremock.client.WireMock.put; -import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; - -import com.capgemini.mrchecker.webapi.core.base.driver.DriverManager; -import com.github.tomakehurst.wiremock.client.WireMock; - -public class StubSOAP_Builder { - - // required parameters - private String endpointURI; - - // optional parameters - private int statusCode; - - //Driver config - private final String endpointBaseUri; - - public String getEndpointURI() { - return endpointURI; - } - - public int getStatusCode() { - return statusCode; - } - - public String getEndpointBaseUri() { - return this.endpointBaseUri; - } - - private StubSOAP_Builder(StubBuilder builder) { - this.endpointURI = builder.endpointURI; - this.statusCode = builder.statusCode; - this.endpointBaseUri = builder.endpointBaseUri; - } - - // Builder Class - public static class StubBuilder { - - // required parameters - private String endpointURI; - - // optional parameters - private int statusCode = 200; - private String response = "Hello"; - private String requestXPathQuery = ""; - - ///Driver config - private String endpointBaseUri; - - public StubBuilder(String endpointURI) { - this.endpointURI = endpointURI; - } - - public StubBuilder setStatusCode(int statusCode) { - this.statusCode = statusCode; - return this; - } - - public StubBuilder setResponse(String response) { - this.response = response; - return this; - } - - public StubBuilder setRequestXPathQuery(String requestXPathQuery) { - this.requestXPathQuery = requestXPathQuery; - return this; - - } - - public StubSOAP_Builder build() { - - // Bind all stubbers to running WireMock client connection - WireMock driver = DriverManager.getDriverVirtualService(); - this.endpointBaseUri = DriverManager.getEndpointBaseUri(); - WireMock.configureFor(driver); - - // GET - WireMock - .givenThat( - // Given that request with ... - get(urlMatching(this.endpointURI)) - .withHeader("Content-Type", equalTo("application/soap+xml")) - .withRequestBody(matchingXPath(this.requestXPathQuery)) - // Return given response ... - .willReturn(aResponse().withStatus(this.statusCode) - .withStatus(this.statusCode) - .withHeader("Content-Type", "application/soap+xml") - .withBody(this.response) - .withTransformers("body-transformer"))); - - // POST - WireMock - .givenThat( - // Given that request with ... - // post(urlEqualTo(this.endpointURI)) - post(urlMatching(this.endpointURI)) - .withHeader("Content-Type", equalTo("application/soap+xml")) - .withRequestBody(matchingXPath(this.requestXPathQuery)) - // Return given response ... - .willReturn(aResponse().withStatus(this.statusCode) - .withStatus(this.statusCode) - .withHeader("Content-Type", "application/soap+xml") - .withBody(this.response) - .withTransformers("body-transformer"))); - - // PUT - WireMock - .givenThat( - // Given that request with ... - put(urlMatching(this.endpointURI)) - .withHeader("Content-Type", equalTo("application/soap+xml")) - .withRequestBody(matchingXPath(this.requestXPathQuery)) - // Return given response ... - .willReturn(aResponse().withStatus(this.statusCode) - .withStatus(this.statusCode) - .withHeader("Content-Type", "application/soap+xml") - .withBody(this.response) - .withTransformers("body-transformer"))); - - // DELETE - WireMock - .givenThat( - // Given that request with ... - delete(urlMatching(this.endpointURI)) - .withHeader("Content-Type", equalTo("application/soap+xml")) - .withRequestBody(matchingXPath(this.requestXPathQuery)) - // Return given response ... - .willReturn(aResponse().withStatus(this.statusCode) - .withStatus(this.statusCode) - .withHeader("Content-Type", "application/soap+xml") - .withBody(this.response) - .withTransformers("body-transformer"))); - - // CATCH any other requests - WireMock - .givenThat( - any(anyUrl()) - .atPriority(10) - .willReturn(aResponse() - .withStatus(404) - .withHeader("Content-Type", "application/soap+xml") - .withBody("Endpoint not found") - .withTransformers("body-transformer"))); - - return new StubSOAP_Builder(this); - } - - } - -} diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/calculator_soap/AddPage.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/calculator_soap/AddPage.java deleted file mode 100644 index 78d69c96..00000000 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/calculator_soap/AddPage.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.capgemini.mrchecker.webapi.pages.calculator_soap; - -import com.capgemini.mrchecker.webapi.core.BasePageWebAPI; -import com.capgemini.mrchecker.webapi.core.base.driver.DriverManager; - -import io.restassured.response.Response; - -public class AddPage extends BasePageWebAPI { - - private final static String HOSTNAME = "http://www.dneonline.com"; - private final static String PATH = "/calculator.asmx?op=Add"; - private final static String ENDPOINT = HOSTNAME + PATH; - - private final static String ROOT = "Add"; - - private SOAPTemplate soapTemplate = new SOAPTemplate(ROOT); - - { - soapTemplate.addAttributeToRoot("xmlns", "http://tempuri.org/"); - } - - public Response sendPOST() { - return DriverManager.getDriverWebAPI() - .with() - .contentType("text/xml; charset=utf-8") - .header("SOAPAction", "http://tempuri.org/Add") - .body(soapTemplate.getMessage()) - .log() - .all() - .when() - .post(ENDPOINT) - .thenReturn(); - } - - public void setIntA(int numberA) { - soapTemplate.getRoot() - .element("intA") - .text(String.valueOf(numberA)); - } - - public void setIntB(int numberB) { - soapTemplate.getRoot() - .element("intB") - .text(String.valueOf(numberB)); - } - - @Override - public String getEndpoint() { - return ENDPOINT; - } - - /* - * SAMPLE REQUEST: - * - * - * - * int - * int - * - * - * - */ - - /* - * SAMPLE RESPONSE: - * - * - * - * int - * - * - * - */ -} diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/calculator_soap/DividePage.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/calculator_soap/DividePage.java deleted file mode 100644 index c568f853..00000000 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/calculator_soap/DividePage.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.capgemini.mrchecker.webapi.pages.calculator_soap; - -import com.capgemini.mrchecker.webapi.core.BasePageWebAPI; -import com.capgemini.mrchecker.webapi.core.base.driver.DriverManager; - -import io.restassured.response.Response; - -public class DividePage extends BasePageWebAPI { - - private final static String HOSTNAME = "http://www.dneonline.com"; - private final static String PATH = "/calculator.asmx?op=Divide"; - private final static String ENDPOINT = HOSTNAME + PATH; - - private final static String ROOT = "Divide"; - - private SOAPTemplate soapTemplate = new SOAPTemplate(ROOT); - - { - soapTemplate.addAttributeToRoot("xmlns", "http://tempuri.org/"); - } - - public Response sendPOST() { - return DriverManager.getDriverWebAPI() - .with() - .contentType("text/xml; charset=utf-8") - .header("SOAPAction", "http://tempuri.org/Divide") - .body(soapTemplate.getMessage()) - .log() - .all() - .when() - .post(ENDPOINT) - .thenReturn(); - } - - public void setIntA(int numberA) { - soapTemplate.getRoot() - .element("intA") - .text(String.valueOf(numberA)); - } - - public void setIntB(int numberB) { - soapTemplate.getRoot() - .element("intB") - .text(String.valueOf(numberB)); - } - - @Override - public String getEndpoint() { - return ENDPOINT; - } - - /* - * SAMPLE REQUEST: - * - * - * - * int - * int - * - * - * - */ - - /* - * SAMPLE RESPONSE: - * - * - * - * int - * - * - * - */ -} diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/calculator_soap/MultiplyPage.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/calculator_soap/MultiplyPage.java deleted file mode 100644 index bb5db04e..00000000 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/calculator_soap/MultiplyPage.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.capgemini.mrchecker.webapi.pages.calculator_soap; - -import com.capgemini.mrchecker.webapi.core.BasePageWebAPI; -import com.capgemini.mrchecker.webapi.core.base.driver.DriverManager; - -import io.restassured.response.Response; - -public class MultiplyPage extends BasePageWebAPI { - - private final static String HOSTNAME = "http://www.dneonline.com"; - private final static String PATH = "/calculator.asmx?op=Multiply"; - private final static String ENDPOINT = HOSTNAME + PATH; - - private final static String ROOT = "Multiply"; - - private SOAPTemplate soapTemplate = new SOAPTemplate(ROOT); - - { - soapTemplate.addAttributeToRoot("xmlns", "http://tempuri.org/"); - } - - public Response sendPOST() { - return DriverManager.getDriverWebAPI() - .with() - .contentType("text/xml; charset=utf-8") - .header("SOAPAction", "http://tempuri.org/Multiply") - .body(soapTemplate.getMessage()) - .log() - .all() - .when() - .post(ENDPOINT) - .thenReturn(); - } - - public void setIntA(int numberA) { - soapTemplate.getRoot() - .element("intA") - .text(String.valueOf(numberA)); - } - - public void setIntB(int numberB) { - soapTemplate.getRoot() - .element("intB") - .text(String.valueOf(numberB)); - } - - @Override - public String getEndpoint() { - return ENDPOINT; - } - - /* - * SAMPLE REQUEST: - * - * - * - * int - * int - * - * - * - */ - - /* - * SAMPLE RESPONSE: - * - * - * - * int - * - * - * - */ -} diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/calculator_soap/SubtractPage.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/calculator_soap/SubtractPage.java deleted file mode 100644 index 8d0b1728..00000000 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/calculator_soap/SubtractPage.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.capgemini.mrchecker.webapi.pages.calculator_soap; - -import com.capgemini.mrchecker.webapi.core.BasePageWebAPI; -import com.capgemini.mrchecker.webapi.core.base.driver.DriverManager; - -import io.restassured.response.Response; - -public class SubtractPage extends BasePageWebAPI { - - private final static String HOSTNAME = "http://www.dneonline.com"; - private final static String PATH = "/calculator.asmx?op=Subtract"; - private final static String ENDPOINT = HOSTNAME + PATH; - - private final static String ROOT = "Subtract"; - - private SOAPTemplate soapTemplate = new SOAPTemplate(ROOT); - - { - soapTemplate.addAttributeToRoot("xmlns", "http://tempuri.org/"); - } - - public Response sendPOST() { - return DriverManager.getDriverWebAPI() - .with() - .contentType("text/xml; charset=utf-8") - .header("SOAPAction", "http://tempuri.org/Subtract") - .body(soapTemplate.getMessage()) - .log() - .all() - .when() - .post(ENDPOINT) - .thenReturn(); - } - - public void setIntA(int numberA) { - soapTemplate.getRoot() - .element("intA") - .text(String.valueOf(numberA)); - } - - public void setIntB(int numberB) { - soapTemplate.getRoot() - .element("intB") - .text(String.valueOf(numberB)); - } - - @Override - public String getEndpoint() { - return ENDPOINT; - } - - /* - * SAMPLE REQUEST: - * - * - * - * int - * int - * - * - * - */ - - /* - * SAMPLE RESPONSE: - * - * - * - * int - * - * - * - */ -} diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/environment/GetEnvironmentParam.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/environment/GetEnvironmentParam.java deleted file mode 100644 index 90b2941b..00000000 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/environment/GetEnvironmentParam.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.capgemini.mrchecker.webapi.pages.environment; - -import com.capgemini.mrchecker.test.core.BaseTest; -import com.capgemini.mrchecker.test.core.exceptions.BFInputDataException; - -public enum GetEnvironmentParam { - - // Name if enum must be in line with cell name in /src/resources/vironments/environment.csv - HTTPBIN; - - public String getValue() { - - if (null == BaseTest.getEnvironmentService()) { - throw new BFInputDataException("Environment Parameters class wasn't initialized properly"); - } - - return BaseTest.getEnvironmentService() - .getValue(this.name()); - - } - - @Override - public String toString() { - - return this.getValue(); - - } - -} diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/httbin/Base64Page.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/httbin/Base64Page.java deleted file mode 100644 index 4f1a5eac..00000000 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/httbin/Base64Page.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.capgemini.mrchecker.webapi.pages.httbin; - -import com.capgemini.mrchecker.webapi.core.BasePageWebAPI; -import com.capgemini.mrchecker.webapi.core.base.driver.DriverManager; -import com.capgemini.mrchecker.webapi.pages.environment.GetEnvironmentParam; -import io.restassured.response.Response; - -public class Base64Page extends BasePageWebAPI { - private final static String HOSTNAME = GetEnvironmentParam.HTTPBIN.getValue(); - private final static String PATH = "/base64/{value}"; - private final static String ENDPOINT = HOSTNAME + PATH; - - private Response sendGETQuery(String value) { - return DriverManager.getDriverWebAPI() - .given().pathParam("value", value) - .get(ENDPOINT); - } - - public String getDecodedValue(String base64Data) { - Response response = sendGETQuery(base64Data); - if (response.statusCode() == 200 && !response.body().equals(null)) { - return response.body().asString(); - } - return null; - } - - @Override - public String getEndpoint() { - return ENDPOINT; - } -} \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/httbin/BasicAuthPage.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/httbin/BasicAuthPage.java deleted file mode 100644 index 763ef1b3..00000000 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/httbin/BasicAuthPage.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.capgemini.mrchecker.webapi.pages.httbin; - -import com.capgemini.mrchecker.webapi.core.BasePageWebAPI; -import com.capgemini.mrchecker.webapi.core.base.driver.DriverManager; -import com.capgemini.mrchecker.webapi.pages.environment.GetEnvironmentParam; - -import io.restassured.response.Response; - -public class BasicAuthPage extends BasePageWebAPI { - - private final static String HOSTNAME = GetEnvironmentParam.HTTPBIN.getValue(); - private final static String PATH = "/basic-auth/user/passwd"; - private final static String ENDPOINT = HOSTNAME + PATH; - - public Response sendBasicAuthGETQuery(String username, String password) { - return DriverManager.getDriverWebAPI() - .auth() - .basic(username, password) - .when() - .get(ENDPOINT); - } - - @Override - public String getEndpoint() { - return ENDPOINT; - } -} \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/httbin/HtmlPage.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/httbin/HtmlPage.java deleted file mode 100644 index dbce7023..00000000 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/httbin/HtmlPage.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.capgemini.mrchecker.webapi.pages.httbin; - -import com.capgemini.mrchecker.webapi.core.BasePageWebAPI; -import com.capgemini.mrchecker.webapi.core.base.driver.DriverManager; -import com.capgemini.mrchecker.webapi.pages.environment.GetEnvironmentParam; -import io.restassured.response.Response; - -public class HtmlPage extends BasePageWebAPI { - private final static String HOSTNAME = GetEnvironmentParam.HTTPBIN.getValue(); - private final static String PATH = "/html"; - private final static String ENDPOINT = HOSTNAME + PATH; - - public Response getHtmlDocument() { - return DriverManager.getDriverWebAPI() - .get(ENDPOINT); - } - - @Override - public String getEndpoint() { - return ENDPOINT; - } -} diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/httbin/LinksPage.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/httbin/LinksPage.java deleted file mode 100644 index 05afd654..00000000 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/httbin/LinksPage.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.capgemini.mrchecker.webapi.pages.httbin; - -import com.capgemini.mrchecker.webapi.core.BasePageWebAPI; -import com.capgemini.mrchecker.webapi.core.base.driver.DriverManager; -import com.capgemini.mrchecker.webapi.pages.environment.GetEnvironmentParam; -import io.restassured.response.Response; - -public class LinksPage extends BasePageWebAPI { - private final static String HOSTNAME = GetEnvironmentParam.HTTPBIN.getValue(); - private final static String PATH = "/links/{n}/{offset}"; - private final static String ENDPOINT = HOSTNAME + PATH; - - public Response getHtmlDocument(int n, int offset) { - return DriverManager.getDriverWebAPI() - .pathParam("n", n) - .pathParam("offset", offset) - .get(ENDPOINT); - } - - @Override - public String getEndpoint() { - return ENDPOINT; - } -} diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/httbin/RandomNBytesPage.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/httbin/RandomNBytesPage.java deleted file mode 100644 index 414104b4..00000000 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/httbin/RandomNBytesPage.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.capgemini.mrchecker.webapi.pages.httbin; - -import com.capgemini.mrchecker.webapi.core.BasePageWebAPI; -import com.capgemini.mrchecker.webapi.core.base.driver.DriverManager; -import com.capgemini.mrchecker.webapi.pages.environment.GetEnvironmentParam; -import io.restassured.response.Response; - -public class RandomNBytesPage extends BasePageWebAPI { - private final static String HOSTNAME = GetEnvironmentParam.HTTPBIN.getValue(); - private final static String PATH = "/bytes/{length}"; - private final static String ENDPOINT = HOSTNAME + PATH; - private Response response = null; - - public void sendGETQuery(String length) { - response = DriverManager.getDriverWebAPI() - .given().pathParam("length", length) - .get(ENDPOINT); - } - - public byte[] getBytesFromResponse() { - if (response != null) { - return response.body().asByteArray(); - } - return null; - } - - public int getStatusCodeFromResponse() { - if (response != null) { - return response.getStatusCode(); - } - return -1; - } - - @Override - public String getEndpoint() { - return ENDPOINT; - } -} diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/httbin/SimpleFormPOSTPage.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/httbin/SimpleFormPOSTPage.java deleted file mode 100644 index efbd9074..00000000 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/httbin/SimpleFormPOSTPage.java +++ /dev/null @@ -1,112 +0,0 @@ -package com.capgemini.mrchecker.webapi.pages.httbin; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import com.capgemini.mrchecker.webapi.core.BasePageWebAPI; -import com.capgemini.mrchecker.webapi.core.base.driver.DriverManager; -import com.capgemini.mrchecker.webapi.pages.environment.GetEnvironmentParam; - -import io.restassured.response.Response; - -public class SimpleFormPOSTPage extends BasePageWebAPI { - - private final static String HOSTNAME = GetEnvironmentParam.HTTPBIN.getValue(); - private final static String PATH = "/post"; - private final static String ENDPOINT = HOSTNAME + PATH; - - private Map requestFields = new HashMap<>(); - - { - requestFields.put("custname", ""); - requestFields.put("custtel", ""); - requestFields.put("custemail", ""); - requestFields.put("comments", ""); - requestFields.put("delivery", ""); - requestFields.put("size", ""); - requestFields.put("topping", ""); - } - - public Response submitForm() { - return DriverManager.getDriverWebAPI() - .formParams(requestFields) - .when() - .post(ENDPOINT); - } - - @Override - public String getEndpoint() { - return ENDPOINT; - } - - public void setCustomerName(String customerName) { - requestFields.replace("custname", customerName); - } - - public void setTelephoneNumber(String telephoneNumber) { - requestFields.replace("custtel", telephoneNumber); - } - - public void setEmailAddress(String emailAddress) { - requestFields.replace("custemail", emailAddress); - } - - public void pickPizzaSize(PizzaSize pizzaSize) { - requestFields.replace("size", pizzaSize.getPizzaSizeValue()); - } - - public void pickPizzaToppings(PizzaToppings... pizzaToppings) { - List toppings = new ArrayList<>(Arrays.asList(pizzaToppings)); - List toppingsStrings = toppings.stream() - .map(element -> element.getPizzaToppingValue()) - .collect(Collectors.toList()); - requestFields.replace("topping", toppingsStrings); - - } - - public void setPrefferedDeliveryTime(int hours, int minutes) { - requestFields.replace("delivery", hours + ":" + minutes); - } - - public void setDeliveryInstruction(String deliveryInstruction) { - requestFields.put("comments", deliveryInstruction); - } - - public enum PizzaSize { - SMALL("small"), - MEDIUM("medium"), - LARGE("large"); - - private String pizzaSizeValue; - - PizzaSize(String pizzaSizeValue) { - this.pizzaSizeValue = pizzaSizeValue; - } - - public String getPizzaSizeValue() { - return pizzaSizeValue; - } - } - - public enum PizzaToppings { - BACON("bacon"), - EXTRA_CHEESE("cheese"), - ONION("onion"), - MUSHROOM("mushroom"); - - private String pizzaToppingValue; - - PizzaToppings(String pizzaToppingValue) { - this.pizzaToppingValue = pizzaToppingValue; - } - - public String getPizzaToppingValue() { - return pizzaToppingValue; - } - } - -} \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/httbin/SimpleGETPage.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/httbin/SimpleGETPage.java deleted file mode 100644 index c0421738..00000000 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/httbin/SimpleGETPage.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.capgemini.mrchecker.webapi.pages.httbin; - -import com.capgemini.mrchecker.webapi.core.BasePageWebAPI; -import com.capgemini.mrchecker.webapi.core.base.driver.DriverManager; -import com.capgemini.mrchecker.webapi.pages.environment.GetEnvironmentParam; - -import io.restassured.response.Response; - -public class SimpleGETPage extends BasePageWebAPI { - - private final static String HOSTNAME = GetEnvironmentParam.HTTPBIN.getValue(); - private final static String PATH = "/get"; - private final static String ENDPOINT = HOSTNAME + PATH; - - public Response sendGETQuery() { - return DriverManager.getDriverWebAPI() - .when() - .get(ENDPOINT); - } - - public String getEndpoint() { - return ENDPOINT; - } -} diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/httbin/SimpleXMLPage.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/httbin/SimpleXMLPage.java deleted file mode 100644 index dac419a1..00000000 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/httbin/SimpleXMLPage.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.capgemini.mrchecker.webapi.pages.httbin; - -import com.capgemini.mrchecker.webapi.core.BasePageWebAPI; -import com.capgemini.mrchecker.webapi.core.base.driver.DriverManager; -import com.capgemini.mrchecker.webapi.pages.environment.GetEnvironmentParam; - -import io.restassured.response.Response; - -public class SimpleXMLPage extends BasePageWebAPI { - - private final static String HOSTNAME = GetEnvironmentParam.HTTPBIN.getValue(); - private final static String PATH = "/xml"; - private final static String ENDPOINT = HOSTNAME + PATH; - - public Response getXMLDocument() { - return DriverManager.getDriverWebAPI() - .get(ENDPOINT); - } - - @Override - public String getEndpoint() { - return ENDPOINT; - } - - /** - * Elements of XML that can be used in searches - */ - public enum XML_ELEMENT { - SLIDESHOW("slideshow"), - ITEM("item"); - private String element; - - XML_ELEMENT(String element) { - this.element = element; - } - - public String getElementKey() { - return element; - } - } - - /** - * Attribute keys that can be used in tests - */ - public enum XML_ATTRIBUTE { - DATE("date"); - - private String attribute; - - XML_ATTRIBUTE(String attribute) { - this.attribute = attribute; - } - - public String getAttributeKey() { - return attribute; - } - } -} \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/httbin/cookies/CookieSession.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/httbin/cookies/CookieSession.java deleted file mode 100644 index 54696065..00000000 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/httbin/cookies/CookieSession.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.capgemini.mrchecker.webapi.pages.httbin.cookies; - -import io.restassured.filter.cookie.CookieFilter; - -public class CookieSession { - - private static CookieFilter cookieSession = null; - - private CookieSession() { - } - - public static CookieFilter getSession() { - if (cookieSession == null) { - cookieSession = createSession(); - } - return cookieSession; - } - - public static void createNewSession() { - cookieSession = createSession(); - } - - private static CookieFilter createSession() { - return new CookieFilter(); - } - -} diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/httbin/cookies/DeleteCookiesPage.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/httbin/cookies/DeleteCookiesPage.java deleted file mode 100644 index 99bd6691..00000000 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/httbin/cookies/DeleteCookiesPage.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.capgemini.mrchecker.webapi.pages.httbin.cookies; - -import com.capgemini.mrchecker.webapi.core.BasePageWebAPI; -import com.capgemini.mrchecker.webapi.core.base.driver.DriverManager; -import com.capgemini.mrchecker.webapi.pages.environment.GetEnvironmentParam; - -import io.restassured.config.RedirectConfig; -import io.restassured.config.RestAssuredConfig; -import io.restassured.response.Response; - -public class DeleteCookiesPage extends BasePageWebAPI { - private final static String HOSTNAME = GetEnvironmentParam.HTTPBIN.getValue(); - private final static String PATH = "/cookies/delete"; - private final static String ENDPOINT = HOSTNAME + PATH; - - private String deleteCookiesEndpointWithValues; - - public Response deleteCookie(String name, String value) { - deleteCookiesEndpointWithValues = ENDPOINT - .concat("?") - .concat(name) - .concat("=") - .concat(value); - - return DriverManager.getDriverWebAPI() - .config(RestAssuredConfig.newConfig() - .redirect(RedirectConfig.redirectConfig() - .followRedirects(false))) - .filter(CookieSession.getSession()) - .when() - .get(deleteCookiesEndpointWithValues); - } - - public String getEndpoint() { - return deleteCookiesEndpointWithValues == null ? ENDPOINT : deleteCookiesEndpointWithValues; - } -} diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/httbin/cookies/GetCookiesPage.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/httbin/cookies/GetCookiesPage.java deleted file mode 100644 index f3ebe77b..00000000 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/httbin/cookies/GetCookiesPage.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.capgemini.mrchecker.webapi.pages.httbin.cookies; - -import com.capgemini.mrchecker.webapi.core.BasePageWebAPI; -import com.capgemini.mrchecker.webapi.core.base.driver.DriverManager; -import com.capgemini.mrchecker.webapi.pages.environment.GetEnvironmentParam; - -import io.restassured.response.Response; - -public class GetCookiesPage extends BasePageWebAPI { - private final static String HOSTNAME = GetEnvironmentParam.HTTPBIN.getValue(); - private final static String PATH = "/cookies"; - private final static String ENDPOINT = HOSTNAME + PATH; - - public Response getCookies() { - return DriverManager.getDriverWebAPI() - .filter(CookieSession.getSession()) - .when() - .get(ENDPOINT); - } - - public String getEndpoint() { - return ENDPOINT; - } -} \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/httbin/cookies/SetCookiesPage.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/httbin/cookies/SetCookiesPage.java deleted file mode 100644 index 47959538..00000000 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/main/java/com/capgemini/mrchecker/webapi/pages/httbin/cookies/SetCookiesPage.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.capgemini.mrchecker.webapi.pages.httbin.cookies; - -import com.capgemini.mrchecker.webapi.core.BasePageWebAPI; -import com.capgemini.mrchecker.webapi.core.base.driver.DriverManager; -import com.capgemini.mrchecker.webapi.pages.environment.GetEnvironmentParam; - -import io.restassured.config.RedirectConfig; -import io.restassured.config.RestAssuredConfig; -import io.restassured.response.Response; - -public class SetCookiesPage extends BasePageWebAPI { - private final static String HOSTNAME = GetEnvironmentParam.HTTPBIN.getValue(); - private final static String PATH = "/cookies/set"; - private final static String ENDPOINT = HOSTNAME + PATH; - - private String setCookiesEndpointWithValues; - - public Response setCookie(String name, String value) { - setCookiesEndpointWithValues = ENDPOINT - .concat("?") - .concat(name) - .concat("=") - .concat(value); - - return DriverManager.getDriverWebAPI() - .config(RestAssuredConfig.newConfig() - .redirect(RedirectConfig.redirectConfig() - .followRedirects(false))) - .filter(CookieSession.getSession()) - .when() - .get(setCookiesEndpointWithValues); - } - - public String getEndpoint() { - return setCookiesEndpointWithValues == null ? ENDPOINT : setCookiesEndpointWithValues; - } -} diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/endpoint/rest/REST_FarenheitToCelsiusMethod_DynamicResponse.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/endpoint/rest/REST_FarenheitToCelsiusMethod_DynamicResponse.java deleted file mode 100644 index fb1c7e61..00000000 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/endpoint/rest/REST_FarenheitToCelsiusMethod_DynamicResponse.java +++ /dev/null @@ -1,125 +0,0 @@ -package com.capgemini.mrchecker.endpoint.rest; - -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; - -import org.junit.BeforeClass; -import org.junit.Test; - -import com.capgemini.mrchecker.test.core.BaseTest; -import com.capgemini.mrchecker.test.core.logger.BFLogger; -import com.capgemini.mrchecker.webapi.core.base.driver.DriverManager; -import com.capgemini.mrchecker.webapi.endpoint.stubs.StubREST_Builder; -import com.github.tomakehurst.wiremock.client.WireMock; - -import io.restassured.http.ContentType; -import io.restassured.response.Response; - -public class REST_FarenheitToCelsiusMethod_DynamicResponse extends BaseTest { - - private static String endpointBaseUri; - - @BeforeClass - public static void beforeClass() { - DriverManager.clearAllDrivers(); - - // Start Virtual Server - WireMock driverVirtualService = DriverManager.getDriverVirtualService(); - - // Get Virtual Server running http and https ports - int httpPort = DriverManager.getHttpPort(); - String baseURI = DriverManager.getHttpHost(); - endpointBaseUri = baseURI + ":" + httpPort; - } - - @Override - public void setUp() { - } - - @Override - public void tearDown() { - } - - @Test - public void testRestMock_post_ResponseBodyBasedOnRequestBody() throws Exception { - - /* - * ---------- - * Mock response. Map request with virtual asset from file - * ----------- - */ - BFLogger.logInfo("#1 Create Stub content message"); - BFLogger.logInfo("#2 Add resource to wiremock server"); - new StubREST_Builder.StubBuilder("/some/thing") - .setResponse("{ \"FahrenheitToCelsiusResponse\":{\"FahrenheitToCelsiusResult\":$(FahrenheitToCelsius.Fahrenheit)}}") - .setStatusCode(200) - .build(); - - /* - * ---------- - * Time to validate virtual response. Send POST request and validate response - * ----------- - */ - BFLogger.logInfo("#3 Send request to generated stub"); - Response response = DriverManager.getDriverWebAPI() - .with() - .header("Content-Type", ContentType.JSON.toString()) - .body("{\"FahrenheitToCelsius\":{\"Fahrenheit\":500}}") - .log() - .all() - .when() - .post(endpointBaseUri + "/some/thing") - .thenReturn(); - - BFLogger.logInfo("#4 Validate response "); - BFLogger.logDebug("/some/thing: " + response.jsonPath() - .prettyPrint()); - assertThat(response.statusCode(), is(200)); - assertThat(response.body() - .jsonPath() - .get("FahrenheitToCelsiusResponse.FahrenheitToCelsiusResult"), is(500)); - } - - @Test - public void testRestMock_post_ResponseBodyBasedOnRequestUrlArgs() throws Exception { - - /* - * ---------- - * Mock response. Map request with virtual asset from file - * ----------- - */ - BFLogger.logInfo("#1 Create Stub content message"); - BFLogger.logInfo("#2 Add resource to wiremock server"); - new StubREST_Builder.StubBuilder("/some/thing.*") - .setResponse("{ \"FahrenheitToCelsiusResponse\":{\"FahrenheitToCelsiusResult\":$(one), \"Value2\":\"$(two)\"} }") - .setStatusCode(200) - .build(); - - /* - * ---------- - * Time to validate virtual response. Send POST request and validate response - * ----------- - */ - BFLogger.logInfo("#3 Send request to generated stub"); - Response response = DriverManager.getDriverWebAPI() - .with() - .header("Content-Type", ContentType.JSON.toString()) - .log() - .all() - .when() - .post(endpointBaseUri + "/some/thing?one=100&two=HelloWorld") - .thenReturn(); - - BFLogger.logInfo("#4 Validate response "); - BFLogger.logDebug("/some/thing?one=100&two=HelloWorld: " + response.jsonPath() - .prettyPrint()); - assertThat(response.statusCode(), is(200)); - assertThat(response.getBody() - .jsonPath() - .get("FahrenheitToCelsiusResponse.FahrenheitToCelsiusResult"), is(100)); - assertThat(response.getBody() - .jsonPath() - .get("FahrenheitToCelsiusResponse.Value2"), is("HelloWorld")); - } - -} diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/endpoint/rest/REST_FarenheitToCelsiusMethod_Test.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/endpoint/rest/REST_FarenheitToCelsiusMethod_Test.java deleted file mode 100644 index 67b437b0..00000000 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/endpoint/rest/REST_FarenheitToCelsiusMethod_Test.java +++ /dev/null @@ -1,113 +0,0 @@ -package com.capgemini.mrchecker.endpoint.rest; - -import com.capgemini.mrchecker.test.core.BaseTest; -import com.capgemini.mrchecker.test.core.logger.BFLogger; -import com.capgemini.mrchecker.webapi.core.base.driver.DriverManager; -import com.capgemini.mrchecker.webapi.endpoint.stubs.StubREST_Builder; -import io.restassured.http.ContentType; -import io.restassured.response.Response; -import org.junit.BeforeClass; -import org.junit.Test; - -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; - -public class REST_FarenheitToCelsiusMethod_Test extends BaseTest { - - private static String endpointBaseUri; - - @BeforeClass - public static void beforeClass() { - // DriverManager.clearAllDrivers(); - // - // // Start Virtual Server - // WireMock driverVirtualService = DriverManager.getDriverVirtualService(); - // - // // Get Virtual Server running http port - // int httpPort = DriverManager.getHttpPort(); - // String baseURI = DriverManager.getHttpHost(); - // endpointBaseUri = baseURI + ":" + httpPort; - } - - @Override - public void setUp() { - /* - * ---------- - * Mock response. Map request with virtual asset from file - * ----------- - */ - BFLogger.logInfo("#1 Create Stub content message"); - BFLogger.logInfo("#2 Add resource to wiremock server"); - StubREST_Builder stubREST_builder = new StubREST_Builder.StubBuilder("/some/thing") - .setResponse("{ \"FahrenheitToCelsiusResponse\":{\"FahrenheitToCelsiusResult\":37.7777777777778}}") - .setStatusCode(200) - .build(); - - // Get Virtual Server running endpoint URI - endpointBaseUri = stubREST_builder.getEndpointBaseUri(); - - - } - - @Override - public void tearDown() { - } - - @Test - public void testRestMock_UrlExists() { - - BFLogger.logInfo("#3 Send request to generated stub"); - Response response = DriverManager.getDriverWebAPI() - .with() - .header("Content-Type", ContentType.JSON.toString()) - .log() - .all() - .when() - .get(endpointBaseUri + "/some/thing") - .thenReturn(); - - BFLogger.logInfo("#4 Validate response "); - BFLogger.logDebug("/some/thing: " + response.jsonPath() - .prettyPrint()); - assertThat(response.statusCode(), is(200)); - } - - @Test - public void testRestMock_UrlDoesNotExist() throws Exception { - - BFLogger.logInfo("#3 Send request to generated stub"); - Response response = DriverManager.getDriverWebAPI() - .with() - .header("Content-Type", ContentType.JSON.toString()) - .log() - .all() - .when() - .get(endpointBaseUri + "/notexisting") - .thenReturn(); - - BFLogger.logInfo("#4 Validate response "); - assertThat(response.statusCode(), is(404)); - - } - - @Test - public void testRestMock_post() throws Exception { - - BFLogger.logInfo("#3 Send request to generated stub"); - Response response = DriverManager.getDriverWebAPI() - .with() - .header("Content-Type", ContentType.JSON.toString()) - .body("{\"FahrenheitToCelsius\":{\"Fahrenheit\":10}}") - .log() - .all() - .when() - .post(endpointBaseUri + "/some/thing") - .thenReturn(); - - BFLogger.logInfo("#4 Validate response "); - BFLogger.logDebug("/some/thing: " + response.jsonPath() - .prettyPrint()); - assertThat(response.statusCode(), is(200)); - } - -} diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/endpoint/soap/SOAP_FarenheitToCelsiusMethod_Test.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/endpoint/soap/SOAP_FarenheitToCelsiusMethod_Test.java deleted file mode 100644 index 102e4536..00000000 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/endpoint/soap/SOAP_FarenheitToCelsiusMethod_Test.java +++ /dev/null @@ -1,152 +0,0 @@ -package com.capgemini.mrchecker.endpoint.soap; - -import com.capgemini.mrchecker.test.core.BaseTest; -import com.capgemini.mrchecker.test.core.logger.BFLogger; -import com.capgemini.mrchecker.webapi.core.base.driver.DriverManager; -import com.capgemini.mrchecker.webapi.endpoint.soap.FarenheitToCelsiusMethod_Request_FromCode; -import com.capgemini.mrchecker.webapi.endpoint.soap.FarenheitToCelsiusMethod_Request_FromFile; -import com.capgemini.mrchecker.webapi.endpoint.soap.FarenheitToCelsiusMethod_Response_FromCode; -import com.capgemini.mrchecker.webapi.endpoint.soap.FarenheitToCelsiusMethod_Response_FromFile; -import com.capgemini.mrchecker.webapi.endpoint.stubs.StubSOAP_Builder; -import com.github.tomakehurst.wiremock.client.WireMock; -import io.restassured.RestAssured; -import io.restassured.config.EncoderConfig; -import io.restassured.config.RestAssuredConfig; -import io.restassured.response.Response; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.io.IOException; - -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; - -public class SOAP_FarenheitToCelsiusMethod_Test extends BaseTest { - - - @BeforeClass - public static void beforeClass() { -// DriverManager.clearAllDrivers(); -// -// // Start Virtual Server -// BFLogger.logInfo("#1 Start wiremock server"); -// WireMock driverVirtualService = DriverManager.getDriverVirtualService(); -// -// // Get Virtual Server running http port -// int httpPort = DriverManager.getHttpPort(); -// String baseURI = DriverManager.getHttpHost(); -// endpointBaseUri = baseURI + ":" + httpPort; -// -// RestAssured.config = new RestAssuredConfig().encoderConfig(new EncoderConfig().appendDefaultContentCharsetToContentTypeIfUndefined(false)); - - } - - @Override - public void setUp() { - } - - @Override - public void tearDown() { - } - - @Test - public void testSoapMessageFromFileWithVitualResponse() throws IOException { - - BFLogger.logInfo("#2 Create Stub content message"); - final String responseMessage = new FarenheitToCelsiusMethod_Response_FromFile().getMessage(); - String requestXPathQuery = "//soap12:Envelope | //soap12:Body | //FahrenheitToCelsius | //Fahrenheit"; - - /* - * ---------- - * Mock response. Map request with virtual asset from file - * ----------- - */ - BFLogger.logInfo("#3 Add resource to wiremock server"); - String endpointUriRegExp = "/tempconvert.asmx.*"; - StubSOAP_Builder stubSOAP_builder = new StubSOAP_Builder.StubBuilder(endpointUriRegExp) - .setRequestXPathQuery(requestXPathQuery) - .setResponse(responseMessage) - .setStatusCode(200) - .build(); - - // Get Virtual Server running endpoint URI - String endpointBaseUri = stubSOAP_builder.getEndpointBaseUri(); - - /* - * ---------- - * Time to validate virtual response - * ----------- - */ - BFLogger.logInfo("#4 Send request to generated stub"); - String endpointUri = "/tempconvert.asmx"; - Response response = DriverManager.getDriverWebAPI() - .with() - .contentType("application/soap+xml") - .body(new FarenheitToCelsiusMethod_Request_FromCode() - .setFahrenheit(30) - .setSmth("Hello") - .getMessage()) - .log() - .all() - .when() - .post(endpointBaseUri + endpointUri) - .thenReturn(); - - BFLogger.logInfo("#5 Validate reposponse "); - BFLogger.logDebug("NEW RESPONSE /tempconvert.asmx?op=FahrenheitToCelsius: " + response.xmlPath() - .prettyPrint()); - assertThat(response.statusCode(), is(200)); - } - - @Test - public void testSoapMessageFromClassObjectWithVitualResponse() throws Exception { - BFLogger.logInfo("#1 Start wiremock server"); - DriverManager.getDriverVirtualService(); - - BFLogger.logInfo("#2 Create Stub content message"); - final String responseMessage = new FarenheitToCelsiusMethod_Response_FromCode().setFahrenheitToCelsiusResult(37.8888) - .getMessage(); - String requestXPathQuery = "//soap12:Envelope | //soap12:Body | //FahrenheitToCelsius | //Fahrenheit"; - - /* - * ---------- - * Mock response. Map request with virtual asset from Object SOAP representation - * ----------- - */ - BFLogger.logInfo("#3 Add resource to wiremock server"); - String endpointUriRegExp = "/tempconvert.asmx\\?op=FahrenheitToCelsius"; - - StubSOAP_Builder stubSOAP_builder = new StubSOAP_Builder.StubBuilder(endpointUriRegExp) - .setRequestXPathQuery(requestXPathQuery) - .setResponse(responseMessage) - .setStatusCode(200) - .build(); - - // Get Virtual Server running endpoint URI - String endpointBaseUri = stubSOAP_builder.getEndpointBaseUri(); - - - /* - * ---------- - * Time to validate virtual response - * ----------- - */ - BFLogger.logInfo("#4 Send request to generated stub"); - String endpointUri = "/tempconvert.asmx?op=FahrenheitToCelsius"; - Response response = DriverManager.getDriverWebAPI() - .with() - .contentType("application/soap+xml") - .body(new FarenheitToCelsiusMethod_Request_FromFile().getMessage()) - .log() - .all() - .when() - .post(endpointBaseUri + endpointUri) - .thenReturn(); - - BFLogger.logInfo("#5 Validate reposponse "); - BFLogger.logDebug("NEW RESPONSE /tempconvert.asmx?op=FahrenheitToCelsius: " + response.xmlPath() - .prettyPrint()); - assertThat(response.statusCode(), is(200)); - } - -} diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/calculator_soap/AddTest.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/calculator_soap/AddTest.java deleted file mode 100644 index 069c2d34..00000000 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/calculator_soap/AddTest.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.capgemini.mrchecker.webapi.calculator_soap; - -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; - -import org.junit.Test; - -import com.capgemini.mrchecker.test.core.logger.BFLogger; -import com.capgemini.mrchecker.webapi.BasePageWebApiTest; -import com.capgemini.mrchecker.webapi.pages.calculator_soap.AddPage; - -import io.restassured.response.Response; - -public class AddTest extends BasePageWebApiTest { - - private AddPage addPage = new AddPage(); - - @Test - public void addTwoPositiveNumbers() { - int firstNumberToAdd = 10; - int secondNumberToAdd = 11; - - runAddingTest(firstNumberToAdd, secondNumberToAdd); - } - - @Test - public void addTwoNegativeNumbers() { - int firstNumberToAdd = -10; - int secondNumberToAdd = -11; - - runAddingTest(firstNumberToAdd, secondNumberToAdd); - } - - @Test - public void addTwoMixedNumbers() { - int firstNumberToAdd = 10; - int secondNumberToAdd = -11; - - runAddingTest(firstNumberToAdd, secondNumberToAdd); - } - - private void runAddingTest(int firstNumberToAdd, int secondNumberToAdd) { - BFLogger.logInfo("Step 1 - Setting first number to add: " + firstNumberToAdd); - addPage.setIntA(firstNumberToAdd); - - BFLogger.logInfo("Step 2 - Setting second number to add: " + secondNumberToAdd); - addPage.setIntB(secondNumberToAdd); - - BFLogger.logInfo("Step 3 - Sending SOAP query to add two numbers. Endpoint: " + addPage.getEndpoint()); - Response response = addPage.sendPOST(); - - BFLogger.logInfo("Step 4 - Validating the response status code"); - assertThat(response.statusCode(), is(200)); - - BFLogger.logInfo("Step 5 - Validating the response result of adding"); - assertThat(response.xmlPath() - .getInt("Envelope.Body.AddResponse"), is(firstNumberToAdd + secondNumberToAdd)); - } -} diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/calculator_soap/DivideTest.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/calculator_soap/DivideTest.java deleted file mode 100644 index 5c888db3..00000000 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/calculator_soap/DivideTest.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.capgemini.mrchecker.webapi.calculator_soap; - -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; - -import org.junit.Test; - -import com.capgemini.mrchecker.test.core.logger.BFLogger; -import com.capgemini.mrchecker.webapi.BasePageWebApiTest; -import com.capgemini.mrchecker.webapi.pages.calculator_soap.DividePage; - -import io.restassured.response.Response; - -public class DivideTest extends BasePageWebApiTest { - - private DividePage dividePage = new DividePage(); - - @Test - public void divideTwoPositiveNumbers() { - int firstNumberToDivide = 100; - int secondNumberToDivide = 10; - - runDividingTest(firstNumberToDivide, secondNumberToDivide); - } - - @Test - public void divideTwoNegativeNumbers() { - int firstNumberToDivide = -100; - int secondNumberToDivide = -10; - - runDividingTest(firstNumberToDivide, secondNumberToDivide); - } - - @Test - public void divideTwoMixedNumbers() { - int firstNumberToDivide = 100; - int secondNumberToDivide = -10; - - runDividingTest(firstNumberToDivide, secondNumberToDivide); - } - - private void runDividingTest(int firstNumberToDivide, int secondNumberToDivide) { - BFLogger.logInfo("Step 1 - Setting first number to divide: " + firstNumberToDivide); - dividePage.setIntA(firstNumberToDivide); - - BFLogger.logInfo("Step 2 - Setting second number to divide: " + secondNumberToDivide); - dividePage.setIntB(secondNumberToDivide); - - BFLogger.logInfo("Step 3 - Sending SOAP query to divide two numbers. Endpoint: " + dividePage.getEndpoint()); - Response response = dividePage.sendPOST(); - - BFLogger.logInfo("Step 4 - Validating the response status code"); - assertThat(response.statusCode(), is(200)); - - BFLogger.logInfo("Step 5 - Validating the response result of dividing"); - assertThat(response.xmlPath() - .getInt("Envelope.Body.DivideResponse"), is(firstNumberToDivide / secondNumberToDivide)); - } -} diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/calculator_soap/MultiplyTest.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/calculator_soap/MultiplyTest.java deleted file mode 100644 index a19e11a1..00000000 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/calculator_soap/MultiplyTest.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.capgemini.mrchecker.webapi.calculator_soap; - -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; - -import org.junit.Test; - -import com.capgemini.mrchecker.test.core.logger.BFLogger; -import com.capgemini.mrchecker.webapi.BasePageWebApiTest; -import com.capgemini.mrchecker.webapi.pages.calculator_soap.MultiplyPage; - -import io.restassured.response.Response; - -public class MultiplyTest extends BasePageWebApiTest { - - private MultiplyPage multiplyPage = new MultiplyPage(); - - @Test - public void multiplyTwoPositiveNumbers() { - int firstNumberToMultiply = 15; - int secondNumberToMultiply = 20; - - runMultiplicationTest(firstNumberToMultiply, secondNumberToMultiply); - } - - @Test - public void multiplyTwoNegativeNumbers() { - int firstNumberToMultiply = -15; - int secondNumberToMultiply = -20; - - runMultiplicationTest(firstNumberToMultiply, secondNumberToMultiply); - } - - @Test - public void multiplyTwoMixedNumbers() { - int firstNumberToMultiply = 15; - int secondNumberToMultiply = -20; - - runMultiplicationTest(firstNumberToMultiply, secondNumberToMultiply); - } - - private void runMultiplicationTest(int firstNumberToMultiply, int secondNumberToMultiply) { - BFLogger.logInfo("Step 1 - Setting first number to multiply: " + firstNumberToMultiply); - multiplyPage.setIntA(firstNumberToMultiply); - - BFLogger.logInfo("Step 2 - Setting second number to multiply: " + secondNumberToMultiply); - multiplyPage.setIntB(secondNumberToMultiply); - - BFLogger.logInfo("Step 3 - Sending SOAP query to multiplication two numbers. Endpoint: " + multiplyPage.getEndpoint()); - Response response = multiplyPage.sendPOST(); - - BFLogger.logInfo("Step 4 - Validating the response status code"); - assertThat(response.statusCode(), is(200)); - - BFLogger.logInfo("Step 5 - Validating the response result of multiplication"); - assertThat(response.xmlPath() - .getInt("Envelope.Body.MultiplyResponse"), is(firstNumberToMultiply * secondNumberToMultiply)); - } -} diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/calculator_soap/SubtractTest.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/calculator_soap/SubtractTest.java deleted file mode 100644 index 5af12ed0..00000000 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/calculator_soap/SubtractTest.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.capgemini.mrchecker.webapi.calculator_soap; - -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; - -import org.junit.Test; - -import com.capgemini.mrchecker.test.core.logger.BFLogger; -import com.capgemini.mrchecker.webapi.BasePageWebApiTest; -import com.capgemini.mrchecker.webapi.pages.calculator_soap.SubtractPage; - -import io.restassured.response.Response; - -public class SubtractTest extends BasePageWebApiTest { - - private SubtractPage subtractPage = new SubtractPage(); - - @Test - public void subtractTwoPositiveNumbers() { - int firstNumberToSubtract = 29; - int secondNumberToSubtract = 40; - - runSubtractingTest(firstNumberToSubtract, secondNumberToSubtract); - } - - @Test - public void SubtractTwoNegativeNumbers() { - int firstNumberToSubtract = -29; - int secondNumberToSubtract = -40; - - runSubtractingTest(firstNumberToSubtract, secondNumberToSubtract); - } - - @Test - public void SubtractTwoMixedNumbers() { - int firstNumberToSubtract = 29; - int secondNumberToSubtract = -40; - - runSubtractingTest(firstNumberToSubtract, secondNumberToSubtract); - } - - private void runSubtractingTest(int firstNumberToSubtract, int secondNumberToSubtract) { - BFLogger.logInfo("Step 1 - Setting first number to subtract: " + firstNumberToSubtract); - subtractPage.setIntA(firstNumberToSubtract); - - BFLogger.logInfo("Step 2 - Setting second number to subtract: " + secondNumberToSubtract); - subtractPage.setIntB(secondNumberToSubtract); - - BFLogger.logInfo("Step 3 - Sending SOAP query to subtract two numbers. Endpoint: " + subtractPage.getEndpoint()); - Response response = subtractPage.sendPOST(); - - BFLogger.logInfo("Step 4 - Validating the response status code"); - assertThat(response.statusCode(), is(200)); - - BFLogger.logInfo("Step 5 - Validating the response result of subtracting"); - assertThat(response.xmlPath() - .getInt("Envelope.Body.SubtractResponse"), is(firstNumberToSubtract - secondNumberToSubtract)); - } -} diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/core/base/driver/DriverManagerTest.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/core/base/driver/DriverManagerTest.java index e467d551..ecedc597 100644 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/core/base/driver/DriverManagerTest.java +++ b/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/core/base/driver/DriverManagerTest.java @@ -1,81 +1,79 @@ package com.capgemini.mrchecker.webapi.core.base.driver; +import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.ResourceLock; + import com.capgemini.mrchecker.test.core.BaseTest; import com.capgemini.mrchecker.webapi.core.base.runtime.RuntimeParameters; +import com.capgemini.mrchecker.webapi.tags.UnitTest; import com.github.tomakehurst.wiremock.WireMockServer; import com.github.tomakehurst.wiremock.common.FatalStartupException; -import org.junit.AfterClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +@UnitTest +@ResourceLock("PropertiesFileSettings.class") public class DriverManagerTest extends BaseTest { - + WireMockServer driver; - + @Override public void setUp() { DriverManager.closeDriverVirtualServer(); driver = null; } - + @Override public void tearDown() { DriverManager.closeDriverVirtualServer(); - + System.clearProperty("mock_http_host"); RuntimeParameters.MOCK_HTTP_HOST.refreshParameterValue(); - + System.clearProperty("mock_http_port"); RuntimeParameters.MOCK_HTTP_PORT.refreshParameterValue(); - + try { driver.shutdown(); } catch (Exception e) { } } - - @AfterClass + + @AfterAll public static void afterAll() { DriverManager.clearAllDrivers(); } - - @Rule - public ExpectedException thrown = ExpectedException.none(); - + @Test public void testRuntimeEnvironmentHostHttp() { System.setProperty("mock_http_host", "http://test.org"); RuntimeParameters.MOCK_HTTP_HOST.refreshParameterValue(); assertEquals("System parameters for 'mock_http_host' should be 'http://test.org'", "http://test.org", RuntimeParameters.MOCK_HTTP_HOST.getValue()); } - + @Test public void testRuntimeEnvironmentHostHttpDefaultValue() { System.clearProperty("mock_http_host"); RuntimeParameters.MOCK_HTTP_HOST.refreshParameterValue(); assertEquals("System parameters for 'mock_http_host' should be 'http://localhost'", "http://localhost", RuntimeParameters.MOCK_HTTP_HOST.getValue()); } - + @Test public void testRuntimeEnvironmentPortHttp() { System.setProperty("mock_http_port", "8080"); RuntimeParameters.MOCK_HTTP_PORT.refreshParameterValue(); assertEquals("System parameters for 'mock_http_port' should be '8080'", "8080", RuntimeParameters.MOCK_HTTP_PORT.getValue()); } - + @Test public void testRuntimeEnvironmentPortHttpDefaultValue() { System.clearProperty("mock_http_port"); RuntimeParameters.MOCK_HTTP_PORT.refreshParameterValue(); assertEquals("Default value for system parameters 'mock_http_port' should be ''", "", RuntimeParameters.MOCK_HTTP_PORT.getValue()); } - + @Test public void testWireMockStartPortHttpRandomPortHttps() { System.setProperty("mock_http_port", "8090"); @@ -85,26 +83,25 @@ public void testWireMockStartPortHttpRandomPortHttps() { WireMockServer driver = DriverManager.getDriverVirtualServerService(); assertEquals("Mock server for http does not run o specified port", 8090, driver.port()); } - + @Test public void testWireMockStartTwoServersWithTheSameHttpPort() { System.setProperty("mock_http_port", "8081"); RuntimeParameters.MOCK_HTTP_PORT.refreshParameterValue(); - + DriverManager.closeDriverVirtualServer(); - + // Start #1 server driver = DriverManager.getDriverVirtualServerService(); assertEquals("Mock server for http does not run o port 8081", 8081, driver.port()); - + // Enable to add new server instances in this thread. Simulation of multi thread and bind to the same port DriverManager.clearAllDrivers(); - + // Start #2 server and expect Error - thrown.expect(FatalStartupException.class); - thrown.expectMessage(containsString("Address already in use")); - driver = DriverManager.getDriverVirtualServerService(); + assertThrows(FatalStartupException.class, DriverManager::getDriverVirtualServerService); + // thrown.expectMessage(containsString("Address already in use")); assertEquals("Mock server for http does not run o port 8081", 8081, driver.port()); } - + } diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/core/base/driver/DriverManagerTest_standaloneWiremock.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/core/base/driver/DriverManagerTest_standaloneWiremock.java index 2e88a4d5..42ec106b 100644 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/core/base/driver/DriverManagerTest_standaloneWiremock.java +++ b/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/core/base/driver/DriverManagerTest_standaloneWiremock.java @@ -1,14 +1,7 @@ package com.capgemini.mrchecker.webapi.core.base.driver; -import com.capgemini.mrchecker.test.core.BaseTest; -import com.capgemini.mrchecker.test.core.base.runtime.RuntimeParametersCore; -import com.capgemini.mrchecker.webapi.core.base.runtime.RuntimeParameters; -import com.github.tomakehurst.wiremock.client.WireMock; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.File; import java.io.IOException; @@ -17,17 +10,22 @@ import java.net.UnknownHostException; import java.nio.file.Paths; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.ResourceLock; +import com.capgemini.mrchecker.test.core.BaseTest; +import com.capgemini.mrchecker.webapi.core.base.runtime.RuntimeParameters; +import com.capgemini.mrchecker.webapi.tags.UnitTest; +import com.github.tomakehurst.wiremock.client.WireMock; +@UnitTest +@ResourceLock("PropertiesFileSettings.class") public class DriverManagerTest_standaloneWiremock extends BaseTest { - - private static Process process_wiremock = null; - private static final String WIREMOCK_STANDALONE_PORT = "8111"; - - @Rule - public ExpectedException thrown = ExpectedException.none(); + + private static Process process_wiremock = null; + private static final String WIREMOCK_STANDALONE_PORT = "8111"; @Test public void testStandaloneWireMockStartDedicatedPortHttp() throws UnknownHostException { @@ -36,9 +34,7 @@ public void testStandaloneWireMockStartDedicatedPortHttp() throws UnknownHostExc System.out.println("IP Address:- " + hostAddress); String hostName = inetAddress.getHostName(); System.out.println("Host Name:- " + hostName); - - - + System.setProperty("mock_http_host", hostAddress); RuntimeParameters.MOCK_HTTP_HOST.refreshParameterValue(); assertEquals("System parameters for 'mock_http_host'", hostAddress, RuntimeParameters.MOCK_HTTP_HOST.getValue()); @@ -58,11 +54,11 @@ public void testStandaloneWireMockWrongHostname() { RuntimeParameters.MOCK_HTTP_HOST.refreshParameterValue(); System.setProperty("mock_http_port", "8100"); - RuntimeParameters.MOCK_HTTP_PORT.refreshParameterValue(); + RuntimeParameters.MOCK_HTTP_HOST.refreshParameterValue(); + + assertThrows(java.net.UnknownHostException.class, DriverManager::getDriverVirtualService); + // thrown.expectMessage(startsWith("http")); - thrown.expect(java.net.UnknownHostException.class); - thrown.expectMessage(startsWith("http")); - WireMock driver = DriverManager.getDriverVirtualService(); } @Test @@ -73,59 +69,51 @@ public void testStandaloneWireMockStartRandomPortHttp() { System.setProperty("mock_http_port", "1000"); RuntimeParameters.MOCK_HTTP_PORT.refreshParameterValue(); - thrown.expect(java.net.UnknownHostException.class); - thrown.expectMessage(startsWith("http")); - WireMock driver = DriverManager.getDriverVirtualService(); + assertThrows(java.net.UnknownHostException.class, DriverManager::getDriverVirtualService); + // thrown.expectMessage(startsWith("http")); } - - @BeforeClass + + @BeforeAll public static void beforeAll() throws IOException { startWiremockStandalone(); - } - - - - @AfterClass - public static void afterAll(){ + + @AfterAll + public static void afterAll() { try { process_wiremock.destroyForcibly(); - }catch (Exception e){ - //No need to catch Exception + } catch (Exception e) { + // No need to catch Exception } DriverManager.clearAllDrivers(); - + System.clearProperty("mock_http_host"); RuntimeParameters.MOCK_HTTP_HOST.refreshParameterValue(); - + System.clearProperty("mock_http_port"); RuntimeParameters.MOCK_HTTP_PORT.refreshParameterValue(); - + } - + @Override public void setUp() { DriverManager.closeDriverVirtualServer(); - - - - + } @Override public void tearDown() { DriverManager.closeDriverVirtualServer(); } - - + private static void startWiremockStandalone() throws IOException { String path = System.getProperty("user.dir") + Paths.get("/src/test/resources/wiremock/wiremock-standalone-2.21.0.jar"); File file = new File(path); - + ProcessBuilder processBuilder = new ProcessBuilder("java", "-jar", file.getAbsolutePath(), "--port", WIREMOCK_STANDALONE_PORT); processBuilder.redirectOutput(Redirect.INHERIT); processBuilder.redirectError(Redirect.INHERIT); - + process_wiremock = processBuilder.start(); } } diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/core/base/properties/PropertiesFileSettingsTest.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/core/base/properties/PropertiesFileSettingsTest.java index 913ce085..cfa2af09 100644 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/core/base/properties/PropertiesFileSettingsTest.java +++ b/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/core/base/properties/PropertiesFileSettingsTest.java @@ -2,80 +2,85 @@ import static org.junit.Assert.assertEquals; +import java.io.FileInputStream; +import java.io.FileNotFoundException; import java.nio.file.Paths; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.ResourceLock; import com.capgemini.mrchecker.test.core.base.properties.PropertiesSettingsModule; -import com.capgemini.mrchecker.webapi.core.base.properties.PropertiesFileSettings; +import com.capgemini.mrchecker.webapi.tags.UnitTest; import com.google.inject.Guice; import com.google.inject.Injector; +@UnitTest +@ResourceLock("PropertiesFileSettings.class") public class PropertiesFileSettingsTest { - @BeforeClass + @BeforeAll public static void setUpBeforeClass() throws Exception { } - @AfterClass + @AfterAll public static void tearDownAfterClass() throws Exception { } private PropertiesFileSettings propertiesFileSettings; - @Before + @BeforeEach public void setUp() throws Exception { } - @After + @AfterEach public void tearDown() throws Exception { PropertiesSettingsModule.delInstance(); } @Test - public void testParameterEnableVirtualServer_True() { + public void testParameterEnableVirtualServer_True() throws FileNotFoundException { String path = System.getProperty("user.dir") + Paths.get("/src/test/resources/settings.properties"); - Injector i = Guice.createInjector(PropertiesSettingsModule.init(path)); + Injector i = Guice.createInjector(PropertiesSettingsModule.init(new FileInputStream(path))); this.propertiesFileSettings = i.getInstance(PropertiesFileSettings.class); assertEquals("", true, propertiesFileSettings.isVirtualServerEnabled()); } @Test - public void testParameterEnableVirtualServer_False() { + public void testParameterEnableVirtualServer_False() throws FileNotFoundException { String path = System.getProperty("user.dir") + Paths.get("/src/test/resources/settings2.properties"); - Injector i = Guice.createInjector(PropertiesSettingsModule.init(path)); + Injector i = Guice.createInjector(PropertiesSettingsModule.init(new FileInputStream(path))); this.propertiesFileSettings = i.getInstance(PropertiesFileSettings.class); assertEquals("", false, propertiesFileSettings.isVirtualServerEnabled()); } @Test - public void testParameterEnableVirtualServer_NoValue() { + public void testParameterEnableVirtualServer_NoValue() throws FileNotFoundException { String path = System.getProperty("user.dir") + Paths.get("/src/test/resources/settings3.properties"); - Injector i = Guice.createInjector(PropertiesSettingsModule.init(path)); + Injector i = Guice.createInjector(PropertiesSettingsModule.init(new FileInputStream(path))); this.propertiesFileSettings = i.getInstance(PropertiesFileSettings.class); assertEquals("", true, propertiesFileSettings.isVirtualServerEnabled()); } @Test - public void testParameterEnableVirtualServer_Text() { + public void testParameterEnableVirtualServer_Text() throws FileNotFoundException { String path = System.getProperty("user.dir") + Paths.get("/src/test/resources/settings4.properties"); - Injector i = Guice.createInjector(PropertiesSettingsModule.init(path)); + Injector i = Guice.createInjector(PropertiesSettingsModule.init(new FileInputStream(path))); this.propertiesFileSettings = i.getInstance(PropertiesFileSettings.class); assertEquals("", true, propertiesFileSettings.isVirtualServerEnabled()); } @Test - public void testParameterEnableVirtualServer_NoParameter() { + public void testParameterEnableVirtualServer_NoParameter() throws FileNotFoundException { String path = System.getProperty("user.dir") + Paths.get("/src/test/resources/settings5.properties"); - Injector i = Guice.createInjector(PropertiesSettingsModule.init(path)); + Injector i = Guice.createInjector(PropertiesSettingsModule.init(new FileInputStream(path))); this.propertiesFileSettings = i.getInstance(PropertiesFileSettings.class); assertEquals("", true, propertiesFileSettings.isVirtualServerEnabled()); diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/core/utils/HTMLParserTest.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/core/utils/HTMLParserTest.java index 44e82aa9..976b0e70 100644 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/core/utils/HTMLParserTest.java +++ b/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/core/utils/HTMLParserTest.java @@ -1,39 +1,44 @@ package com.capgemini.mrchecker.webapi.core.utils; -import org.jsoup.nodes.Document; -import org.jsoup.select.Elements; -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import org.jsoup.nodes.Document; +import org.jsoup.select.Elements; +import org.junit.jupiter.api.Test; + +import com.capgemini.mrchecker.webapi.tags.UnitTest; +@UnitTest public class HTMLParserTest { private final String SAMPLE_HTML = "My titleBody content
    Contents of a first div element
    Contents of a second div element
    "; - + @Test public void testHTMLParser_parse_checkTitle() { Document doc = HTMLParser.parse(SAMPLE_HTML); assertNotNull(doc); assertEquals(doc.title(), "My title"); } - + @Test public void testHTMLParser_getElements_html_checkTitle() { Elements elements = HTMLParser.getElements(SAMPLE_HTML, "title"); assertEquals(elements.size(), 1); - assertEquals(elements.first().ownText(), "My title"); + assertEquals(elements.first() + .ownText(), "My title"); } - + @Test public void testHTMLParser_getElements_doc_checkTitle() { Document doc = HTMLParser.parse(SAMPLE_HTML); Elements elements = HTMLParser.getElements(doc, "title"); assertEquals(elements.size(), 1); - assertEquals(elements.first().ownText(), "My title"); + assertEquals(elements.first() + .ownText(), "My title"); } - + @Test public void testHTMLParser_getElements_html_allDiv_text() { Elements elements = HTMLParser.getElements(SAMPLE_HTML, "div"); @@ -42,7 +47,7 @@ public void testHTMLParser_getElements_html_allDiv_text() { assertEquals(texts.get(0), "Contents of a first div element"); assertEquals(texts.get(1), "Contents of a second div element"); } - + @Test public void testHTMLParser_getElements_html_allDiv_attributesId() { Elements elements = HTMLParser.getElements(SAMPLE_HTML, "div"); diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/httpbin/Base64Test.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/httpbin/Base64Test.java deleted file mode 100644 index 76885915..00000000 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/httpbin/Base64Test.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.capgemini.mrchecker.webapi.httpbin; - -import com.capgemini.mrchecker.test.core.logger.BFLogger; -import com.capgemini.mrchecker.webapi.BasePageWebApiTest; -import com.capgemini.mrchecker.webapi.pages.httbin.Base64Page; -import junitparams.JUnitParamsRunner; -import junitparams.Parameters; -import org.junit.Test; -import org.junit.runner.RunWith; - -import java.text.MessageFormat; - -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; - -@RunWith(JUnitParamsRunner.class) -public class Base64Test extends BasePageWebApiTest { - private Base64Page base64Page = new Base64Page(); - - @Test - @Parameters({ - "SFRUUEJJTiBpcyBhd2Vzb21l, HTTPBIN is awesome", - "TXIuQ2hlY2tlcg==, Mr.Checker", - "WmHFvMOzxYLEhyBnxJnFm2zEhSBqYcW6xYQ= , Zażółć gęślą jaźń" - }) - public void sendGetWithBase64DataAndValidateDecodedResponse(String base64Data, String expectedResult) { - BFLogger.logInfo(MessageFormat.format("Step 1 - Sending GET query to {0} with valid base 64 data: {1}", base64Page.getEndpoint(), base64Data)); - String response = base64Page.getDecodedValue(base64Data); - - BFLogger.logInfo(MessageFormat.format("Step 2 - Validate response body (should be {0}): ", expectedResult)); - assertThat(response, is(expectedResult)); - } -} \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/httpbin/BasicAuthTest.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/httpbin/BasicAuthTest.java deleted file mode 100644 index d8abfa7e..00000000 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/httpbin/BasicAuthTest.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.capgemini.mrchecker.webapi.httpbin; - -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; - -import org.junit.Test; - -import com.capgemini.mrchecker.test.core.logger.BFLogger; -import com.capgemini.mrchecker.webapi.BasePageWebApiTest; -import com.capgemini.mrchecker.webapi.pages.httbin.BasicAuthPage; - -import io.restassured.response.Response; - -public class BasicAuthTest extends BasePageWebApiTest { - - private final String validUsername = "user"; - private final String validPassword = "passwd"; - - private final String invalidUsername = "invalidUser"; - private final String invalidPassword = "invalidPassword"; - - private BasicAuthPage basicAuthPage = new BasicAuthPage(); - - @Test - public void basicAuthSuccessfulLogin() { - - BFLogger.logInfo("Step 1 - Sending GET query to " + basicAuthPage.getEndpoint() + - " with valid credentials: " + validUsername + ", " + validPassword); - Response response = basicAuthPage.sendBasicAuthGETQuery(validUsername, validPassword); - - BFLogger.logInfo("Step 2 - Validate response status code (should be 200): "); - assertThat(response.statusCode(), is(200)); - } - - @Test - public void basicAuthFailedLogin() { - - BFLogger.logInfo("Step 1 - Sending GET query to " + basicAuthPage.getEndpoint() + - " with invalid credentials: " + invalidUsername + ", " + invalidPassword); - Response response = basicAuthPage.sendBasicAuthGETQuery(invalidUsername, invalidPassword); - - BFLogger.logInfo("Step 2 - Validate response status code (should be 401): "); - assertThat(response.statusCode(), is(401)); - } - -} diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/httpbin/CookiesTest.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/httpbin/CookiesTest.java deleted file mode 100644 index d3d90a6b..00000000 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/httpbin/CookiesTest.java +++ /dev/null @@ -1,142 +0,0 @@ -package com.capgemini.mrchecker.webapi.httpbin; - -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import java.util.Map; - -import org.junit.Before; -import org.junit.Test; - -import com.capgemini.mrchecker.test.core.logger.BFLogger; -import com.capgemini.mrchecker.webapi.BasePageWebApiTest; -import com.capgemini.mrchecker.webapi.pages.httbin.cookies.CookieSession; -import com.capgemini.mrchecker.webapi.pages.httbin.cookies.DeleteCookiesPage; -import com.capgemini.mrchecker.webapi.pages.httbin.cookies.GetCookiesPage; -import com.capgemini.mrchecker.webapi.pages.httbin.cookies.SetCookiesPage; - -import io.restassured.response.Response; - -public class CookiesTest extends BasePageWebApiTest { - - private GetCookiesPage getCookiesPage = new GetCookiesPage(); - private SetCookiesPage setCookiesPage = new SetCookiesPage(); - private DeleteCookiesPage deleteCookiesPage = new DeleteCookiesPage(); - - @Before - public void testSetUp() { - BFLogger.logInfo("Step 1 - Create new cookie session"); - CookieSession.createNewSession(); - BFLogger.logInfo("Created session id: " + CookieSession.getSession() - .hashCode()); - } - - @Test - public void getCookiesTestStatusCode() { - int expectedStatusCode = 200; - - BFLogger.logInfo("Step 2 - GET Cookies. Send GET to " + getCookiesPage.getEndpoint()); - Response response = getCookiesPage.getCookies(); - BFLogger.logInfo("Step 3 - Validate response status code. Expected was " + expectedStatusCode + "."); - assertThat(response.statusCode(), is(expectedStatusCode)); - } - - @Test - public void setCookiesTestStatusCode() { - // After set some cookie httpbin.org trying to redirect for /cookies endpoint. - // To keep same cookie session redirect must be turned off. - // That's why 302(REDIRECT) is expected. - int expectedStatusCode = 302; - - BFLogger.logInfo("Step 2 - SET Cookies. Send GET to " + setCookiesPage.getEndpoint()); - Response response = setCookiesPage.setCookie("cookiesOne", "1"); - BFLogger.logInfo("Step 3 - Validate response status code. Expected was " + expectedStatusCode + "."); - assertThat(response.statusCode(), is(expectedStatusCode)); - } - - @Test - public void deleteCookiesTestStatusCode() { - // After delete some cookie httpbin.org trying to redirect for /cookies endpoint. - // To keep same cookie session redirect must be turned off. - // That's why 302(REDIRECT) is expected. - int expectedStatusCode = 302; - - BFLogger.logInfo("Step 2 - DELETE Cookies. Send GET to " + deleteCookiesPage.getEndpoint()); - Response response = deleteCookiesPage.deleteCookie("cookiesTwo", "2"); - - BFLogger.logInfo("Step 3 - Validate response status code. Expected was " + expectedStatusCode + "."); - assertThat(response.statusCode(), is(expectedStatusCode)); - } - - @Test - public void setTwoCookies() { - String firstCookieKey = "firstCookie"; - String firstCookieValue = "1"; - - String secondCookieKey = "secondCookie"; - String secondCookieValue = "2"; - - int expectedSizeOfCookiesResponseMap = 2; - - BFLogger.logInfo("Step 2 - SET Cookies. Send GET to " + setCookiesPage.getEndpoint()); - setCookiesPage.setCookie(firstCookieKey, firstCookieValue); - setCookiesPage.setCookie(secondCookieKey, secondCookieValue); - - BFLogger.logInfo("Step 3 - GET Cookies. Send GET to " + getCookiesPage.getEndpoint()); - Map cookies = getCookiesPage.getCookies() - .jsonPath() - .getMap("cookies"); - - BFLogger.logInfo("Step 4 - Validate 'cookies' response"); - assertThat(cookies.size(), equalTo(expectedSizeOfCookiesResponseMap)); - assertTrue(cookies.keySet() - .contains(firstCookieKey)); - assertEquals(firstCookieValue, cookies.get(firstCookieKey)); - assertTrue(cookies.keySet() - .contains(secondCookieKey)); - assertEquals(secondCookieValue, cookies.get(secondCookieKey)); - } - - @Test - public void deleteCookie() { - String firstCookieKey = "firstCookie"; - String firstCookieValue = "1"; - - int expectedSizeOfCookiesResponseMap = 1; - String expectedValueAfterDelete = ""; - - BFLogger.logInfo("Step 2 - SET Cookies. Send GET to " + setCookiesPage.getEndpoint()); - setCookiesPage.setCookie(firstCookieKey, firstCookieValue); - - BFLogger.logInfo("Step 3 - GET Cookies. Send GET to " + getCookiesPage.getEndpoint()); - Map cookies = getCookiesPage.getCookies() - .jsonPath() - .getMap("cookies"); - - BFLogger.logInfo("Step 4 - Validate 'cookies' response"); - assertThat(cookies.size(), equalTo(expectedSizeOfCookiesResponseMap)); - assertTrue(cookies.keySet() - .contains(firstCookieKey)); - assertTrue(cookies.get(firstCookieKey) - .equals(firstCookieValue)); - - BFLogger.logInfo("Step 5 - DELETE Cookies. Send GET to " + deleteCookiesPage.getEndpoint()); - deleteCookiesPage.deleteCookie(firstCookieKey, firstCookieValue); - - BFLogger.logInfo("Step 6 - GET Cookies. Send GET to " + getCookiesPage.getEndpoint()); - Map cookiesAfterDelete = getCookiesPage.getCookies() - .jsonPath() - .getMap("cookies"); - - BFLogger.logInfo("Step 7 - Validate 'cookies' response after deletion"); - // httpbin.org/delete remove only value from provided cookie. - // So expected value after delete is empty String. - assertThat(cookies.size(), equalTo(expectedSizeOfCookiesResponseMap)); - assertTrue(cookiesAfterDelete.keySet() - .contains(firstCookieKey)); - assertEquals(expectedValueAfterDelete, cookiesAfterDelete.get(firstCookieKey)); - } -} diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/httpbin/HtmlLinksTest.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/httpbin/HtmlLinksTest.java deleted file mode 100644 index 5d258a5e..00000000 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/httpbin/HtmlLinksTest.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.capgemini.mrchecker.webapi.httpbin; - -import com.capgemini.mrchecker.test.core.logger.BFLogger; -import com.capgemini.mrchecker.webapi.BasePageWebApiTest; -import com.capgemini.mrchecker.webapi.core.utils.HTMLParser; -import com.capgemini.mrchecker.webapi.pages.httbin.LinksPage; -import io.restassured.response.Response; -import io.restassured.response.ResponseBody; -import junitparams.JUnitParamsRunner; -import junitparams.Parameters; -import org.jsoup.select.Elements; -import org.junit.Test; -import org.junit.runner.RunWith; - -import java.text.MessageFormat; -import java.util.List; - -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; - -@RunWith(JUnitParamsRunner.class) -public class HtmlLinksTest extends BasePageWebApiTest { - private LinksPage linksPage = new LinksPage(); - - @Test - @Parameters({ - "-1, 5", - "5, -1", - "-1, -1" - }) - public void sendGetWithNegativeParamAndValidateNotFoundStatusCode(int n, int offset) { - BFLogger.logInfo(MessageFormat.format("Step 1 - Sending GET query to {0} with positive n param: {1} and negative offset: {2}", linksPage.getEndpoint(), n, offset)); - Response response = linksPage.getHtmlDocument(n, offset); - - BFLogger.logInfo("Step 2 - Validate response status code (should be 404): "); - assertThat(response.statusCode(), is(404)); - } - - @Test - @Parameters({ - "10, 5", - "5, 10", - "10, 10", - "0, 5", - "5, 0", - "0, 0" - }) - public void sendGetWithPositiveParamsAndValidateHTMLPage(int n, int offset) { - BFLogger.logInfo(MessageFormat.format("Step 1 - Sending GET query to {0} with n param: {1} and offset: {2}", linksPage.getEndpoint(), n, offset)); - Response response = linksPage.getHtmlDocument(n, offset); - - BFLogger.logInfo("Step 2 - Validate response status code (should be 200): "); - assertThat(response.statusCode(), is(200)); - - //When n is equal 0 there is still one link - int initLinkCount = n == 0 ? 1 : n; - - //Offset cuts count of links if it is lower than n - int properLinkCount = offset >= initLinkCount ? initLinkCount : initLinkCount - 1; - BFLogger.logInfo("Step 3 - Validate links in html response - count should be " + properLinkCount); - ResponseBody body = response.body(); - String htmlText = body.asString(); - Elements links = HTMLParser.getElements(htmlText, "a"); - - assertThat(links.size(), is(properLinkCount)); - - BFLogger.logInfo("Step 4 - Validate links in html response - text"); - List linksText = HTMLParser.getTextFromElements(links); - linksText.forEach(link -> { - int j = linksText.indexOf(link); - if (j >= offset) { - j++; - } - assertThat(link, is(String.valueOf(j))); - }); - - BFLogger.logInfo("Step 5 - Validate links in html response - href attribute"); - List linksLink = HTMLParser.getAttributeValueFromElements(links, "href"); - linksLink.forEach(link -> { - int j = linksLink.indexOf(link); - if (j >= offset) { - j++; - } - assertThat(link, is(MessageFormat.format("/links/{0}/{1}", initLinkCount, j))); - }); - - //When offset cuts some link - if (offset < n) { - BFLogger.logInfo(MessageFormat.format("Step 6 - Validate that there is text equal to offset: {0}", offset)); - String bodyText = HTMLParser.getElements(htmlText, "body").first().ownText(); - assertThat(bodyText, is(String.valueOf(offset))); - } - } -} \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/httpbin/HtmlTest.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/httpbin/HtmlTest.java deleted file mode 100644 index b305bc6a..00000000 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/httpbin/HtmlTest.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.capgemini.mrchecker.webapi.httpbin; - -import com.capgemini.mrchecker.test.core.logger.BFLogger; -import com.capgemini.mrchecker.webapi.BasePageWebApiTest; -import com.capgemini.mrchecker.webapi.core.utils.HTMLParser; -import com.capgemini.mrchecker.webapi.pages.httbin.HtmlPage; -import io.restassured.response.Response; -import io.restassured.response.ResponseBody; -import org.jsoup.select.Elements; -import org.junit.Test; - -import java.util.List; - -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; - -public class HtmlTest extends BasePageWebApiTest { - private HtmlPage htmlPage = new HtmlPage(); - - @Test - public void validateCorrectnessOfHtmlPage() { - int h1ElementsCount = 1; - String h1ElementText = "Herman Melville - Moby-Dick"; - int pElementCount = 1; - int pElementTextLength = 3566; - - BFLogger.logInfo("Step 1 - Sending GET query to " + htmlPage.getEndpoint()); - Response response = htmlPage.getHtmlDocument(); - - BFLogger.logInfo("Step 2 - Validate response status code: "); - assertThat(response.statusCode(), is(200)); - - BFLogger.logInfo("Step 3 - Validate response body is html that contains proper h1 tag content (count and value)"); - ResponseBody body = response.body(); - String htmlText = body.asString(); - Elements headings = HTMLParser.getElements(htmlText, "h1"); - List headingsText = HTMLParser.getTextFromElements(headings); - assertThat(headings.size(), is(h1ElementsCount)); - assertThat(headingsText.get(0), is(h1ElementText)); - - BFLogger.logInfo("Step 4 - Validate response body is html that contains proper p tag content (count and length)"); - Elements paragraphs = HTMLParser.getElements(htmlText, "p"); - List paragraphsText = HTMLParser.getTextFromElements(paragraphs); - assertThat(paragraphs.size(), is(pElementCount)); - assertThat(paragraphsText.get(0).length(), is(pElementTextLength)); - } -} \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/httpbin/RandomNBytesTest.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/httpbin/RandomNBytesTest.java deleted file mode 100644 index af0a9100..00000000 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/httpbin/RandomNBytesTest.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.capgemini.mrchecker.webapi.httpbin; - -import com.capgemini.mrchecker.test.core.logger.BFLogger; -import com.capgemini.mrchecker.webapi.BasePageWebApiTest; -import com.capgemini.mrchecker.webapi.pages.httbin.RandomNBytesPage; -import junitparams.JUnitParamsRunner; -import junitparams.Parameters; -import org.junit.Test; -import org.junit.runner.RunWith; - -import java.text.MessageFormat; - -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; - -@RunWith(JUnitParamsRunner.class) -public class RandomNBytesTest extends BasePageWebApiTest { - private RandomNBytesPage randomNBytesPage = new RandomNBytesPage(); - - @Test - @Parameters({ "1", "6", "30", "90" }) - public void randomNBytesGenerationTest(Integer length) { - validateNBytesOfData(length); - } - - private void validateNBytesOfData(Integer size) { - BFLogger.logInfo(MessageFormat.format("Step 1 - Sending GET query to {0} with valid value(size): {1}", randomNBytesPage.getEndpoint(), size)); - randomNBytesPage.sendGETQuery(Integer.toString(size)); - - BFLogger.logInfo("Step 2 - Validate response status code (should be 200): "); - assertThat(randomNBytesPage.getStatusCodeFromResponse(), is(200)); - - BFLogger.logInfo(MessageFormat.format("Step 3 - Validate response body (should be {0}): ", size)); - assertThat(randomNBytesPage.getBytesFromResponse().length, is(size)); - } -} diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/httpbin/SimpleFormPOSTTest.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/httpbin/SimpleFormPOSTTest.java deleted file mode 100644 index fbd2357b..00000000 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/httpbin/SimpleFormPOSTTest.java +++ /dev/null @@ -1,171 +0,0 @@ -package com.capgemini.mrchecker.webapi.httpbin; - -import static com.capgemini.mrchecker.webapi.core.utils.RegexMatcher.matches; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.greaterThanOrEqualTo; -import static org.hamcrest.Matchers.lessThan; -import static org.hamcrest.Matchers.lessThanOrEqualTo; -import static org.junit.Assert.assertThat; - -import java.util.List; -import java.util.Map; - -import org.hamcrest.core.StringContains; -import org.junit.BeforeClass; -import org.junit.Test; - -import com.capgemini.mrchecker.test.core.logger.BFLogger; -import com.capgemini.mrchecker.webapi.BasePageWebApiTest; -import com.capgemini.mrchecker.webapi.pages.httbin.SimpleFormPOSTPage; -import com.capgemini.mrchecker.webapi.pages.httbin.SimpleFormPOSTPage.PizzaSize; -import com.capgemini.mrchecker.webapi.pages.httbin.SimpleFormPOSTPage.PizzaToppings; - -import io.restassured.response.Response; - -/* - * This example covering only positive cases because 'httpbin.org/post' doesn't include server-side validations. - * On the other hand 'httpbin.org/forms/post' including client-side validations. Below tests will cover them. - */ - -public class SimpleFormPOSTTest extends BasePageWebApiTest { - - private static SimpleFormPOSTPage simplePOSTPage = new SimpleFormPOSTPage(); - private static Response response; - - // Valid data to fill the form - private static final String CUSTOMER_NAME = "Jan Kowalski"; - private static final String TELEPHONE_NUMBER = "123456789"; - private static final String EMAIL_ADDRESS = "jan.kowalski@email.com"; - private static final PizzaSize PIZZA_SIZE = PizzaSize.LARGE; - private static final PizzaToppings PIZZA_TOPPING_1 = PizzaToppings.BACON; - private static final PizzaToppings PIZZA_TOPPING_2 = PizzaToppings.EXTRA_CHEESE; - private static final int DELIVERY_TIME_HOUR = 12; - private static final int DELIVERY_TIME_MINUTE = 30; - private static final String DELIVERY_INSTRUCTION = "8 floor"; - - @BeforeClass - public static void submitFormWithValidData() { - BFLogger.logInfo("Step 1 - Setting up CustomerName field: " + CUSTOMER_NAME); - simplePOSTPage.setCustomerName(CUSTOMER_NAME); - - BFLogger.logInfo("Step 2 - Setting up Telephone Number field: " + TELEPHONE_NUMBER); - simplePOSTPage.setTelephoneNumber(TELEPHONE_NUMBER); - - BFLogger.logInfo("Step 3 - Setting up EmailAddress field: " + EMAIL_ADDRESS); - simplePOSTPage.setEmailAddress(EMAIL_ADDRESS); - - BFLogger.logInfo("Step 4 - Setting up PizzaSize field: " + PIZZA_SIZE.getPizzaSizeValue()); - simplePOSTPage.pickPizzaSize(PIZZA_SIZE); - - BFLogger.logInfo("Step 5 - Setting up PizzaToppings field: " + - PIZZA_TOPPING_1.getPizzaToppingValue() + ", " + PIZZA_TOPPING_2.getPizzaToppingValue()); - simplePOSTPage.pickPizzaToppings(PIZZA_TOPPING_1, PIZZA_TOPPING_2); - - BFLogger.logInfo("Step 6 - Setting up DeliveryTime field: " + DELIVERY_TIME_HOUR + ":" + DELIVERY_TIME_MINUTE); - simplePOSTPage.setPrefferedDeliveryTime(DELIVERY_TIME_HOUR, DELIVERY_TIME_MINUTE); - - BFLogger.logInfo("Step 7 - Setting up DeliveryInstruction field: " + DELIVERY_INSTRUCTION); - simplePOSTPage.setDeliveryInstruction(DELIVERY_INSTRUCTION); - - BFLogger.logInfo("Step 8 - Submiting the form - sending POST query to " + simplePOSTPage.getEndpoint()); - response = simplePOSTPage.submitForm(); - - BFLogger.logInfo("Step 9 - Validate response status code (should be 200)"); - assertThat(response.statusCode(), equalTo(200)); - - BFLogger.logInfo("RESPONSE Body: "); - response.getBody() - .prettyPrint(); - } - - @Test - public void responseFormShouldIncludeSevenFields() { - Map formFields = response.jsonPath() - .getMap("form"); - - BFLogger.logInfo("Validate response 'form' - should contains 7 fields"); - assertThat(formFields.size(), equalTo(7)); - } - - @Test - public void validateCorrectnessOfCustomerNameResponse() { - String customerName = response.path("form.custname"); - - BFLogger.logInfo("Validate response 'form.custname' - should be equal to: " + CUSTOMER_NAME); - assertThat(customerName, equalTo(CUSTOMER_NAME)); - } - - @Test - public void validateCorrectnessOfTelephoneResponse() { - String customerTelephone = response.path("form.custtel"); - - BFLogger.logInfo("Validate response 'form.custtel' - should be equal to: " + TELEPHONE_NUMBER); - assertThat(customerTelephone, equalTo(TELEPHONE_NUMBER)); - - BFLogger.logInfo("Validate response 'form.custtel' - should matches 9 numbers"); - assertThat(customerTelephone, matches("\\d{9}")); - } - - @Test - public void validateCorrectnessOfEmailAddressResponse() { - String customerEmailAddress = response.path("form.custemail"); - - BFLogger.logInfo("Validate response 'form.custemail' - should be equal to: " + EMAIL_ADDRESS); - assertThat(customerEmailAddress, equalTo(EMAIL_ADDRESS)); - - BFLogger.logInfo("Validate response 'form.custemail' - should contains '@' char"); - assertThat(customerEmailAddress, StringContains.containsString("@")); - - BFLogger.logInfo("Validate response 'form.custemail' - should matches with standard emails"); - assertThat(customerEmailAddress, matches("[a-zA-Z0-9.]+@[a-zA-Z0-9.]+")); - } - - @Test - public void validateCorrectnessOfPizzaSizeResponse() { - String pizzaSize = response.path("form.size"); - - BFLogger.logInfo("Validate response 'form.size' - should be equal to: " + PIZZA_SIZE.getPizzaSizeValue()); - assertThat(pizzaSize, equalTo(PIZZA_SIZE.getPizzaSizeValue())); - } - - @Test - public void validateCorrectnessOfPizzaToppingsResponse() { - List pizzaToppings = response.jsonPath() - .getList("form.topping"); - - BFLogger.logInfo("Validate response 'form.topping' - should contains less than 4 fields"); - assertThat(pizzaToppings.size(), lessThan(4)); - - BFLogger.logInfo("Validate response 'form.topping' - should matches with provided Pizza Toppings"); - for (String topping : pizzaToppings) { - assertThat(topping, matches("(" + PIZZA_TOPPING_1.getPizzaToppingValue() + - "|" + PIZZA_TOPPING_2.getPizzaToppingValue() + ")")); - } - } - - @Test - public void validateCorrectnessOfDeliveryTimeResponse() { - String deliveryTime = response.path("form.delivery"); - - BFLogger.logInfo("Validate response 'form.delivery' - should matches with standard HH:MM"); - assertThat(deliveryTime, matches("\\d\\d:\\d\\d")); - - BFLogger.logInfo("Validate response 'form.delivery' - should be equal to: " + DELIVERY_TIME_HOUR + ":" + DELIVERY_TIME_MINUTE); - assertThat(deliveryTime, equalTo(DELIVERY_TIME_HOUR + ":" + DELIVERY_TIME_MINUTE)); - - BFLogger.logInfo("Validate response 'form.delivery' - delivery time should be provided in open hours (11 - 21)"); - assertThat(DELIVERY_TIME_HOUR, lessThanOrEqualTo(21)); - assertThat(DELIVERY_TIME_HOUR, greaterThanOrEqualTo(11)); - - assertThat(DELIVERY_TIME_MINUTE, lessThan(60)); - assertThat(DELIVERY_TIME_MINUTE, greaterThanOrEqualTo(0)); - } - - @Test - public void validateCorrectnessOfDeliveryInstructionsResponse() { - String pizzaSize = response.path("form.comments"); - - BFLogger.logInfo("Validate response 'form.comments' - should be equal to: " + DELIVERY_INSTRUCTION); - assertThat(pizzaSize, equalTo(DELIVERY_INSTRUCTION)); - } -} diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/httpbin/SimpleGETTest.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/httpbin/SimpleGETTest.java deleted file mode 100644 index 656a243d..00000000 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/httpbin/SimpleGETTest.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.capgemini.mrchecker.webapi.httpbin; - -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; - -import org.junit.Test; - -import com.capgemini.mrchecker.test.core.logger.BFLogger; -import com.capgemini.mrchecker.webapi.BasePageWebApiTest; -import com.capgemini.mrchecker.webapi.pages.httbin.SimpleGETPage; - -import io.restassured.response.Response; - -public class SimpleGETTest extends BasePageWebApiTest { - - private SimpleGETPage simpleGETPage; - - @Test - public void sendSimpleGETQuery() { - simpleGETPage = new SimpleGETPage(); - - BFLogger.logInfo("Step 1 - Sending GET query to " + simpleGETPage.getEndpoint()); - Response response = simpleGETPage.sendGETQuery(); - - BFLogger.logInfo("Step 2 - Validate response status code: "); - assertThat(response.statusCode(), is(200)); - } - -} diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/httpbin/SimpleXMLTest.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/httpbin/SimpleXMLTest.java deleted file mode 100644 index ab72fd96..00000000 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/httpbin/SimpleXMLTest.java +++ /dev/null @@ -1,86 +0,0 @@ -package com.capgemini.mrchecker.webapi.httpbin; - -import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.assertThat; - -import java.io.IOException; - -import org.junit.BeforeClass; -import org.junit.Test; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.NodeList; -import org.xml.sax.SAXException; - -import com.capgemini.mrchecker.test.core.logger.BFLogger; -import com.capgemini.mrchecker.webapi.BasePageWebApiTest; -import com.capgemini.mrchecker.webapi.pages.httbin.SimpleXMLPage; -import com.capgemini.mrchecker.webapi.pages.httbin.SimpleXMLPage.XML_ATTRIBUTE; -import com.capgemini.mrchecker.webapi.pages.httbin.SimpleXMLPage.XML_ELEMENT; -import com.capgemini.mrchecker.webapi.pages.utils.SimpleXMLParser; - -public class SimpleXMLTest extends BasePageWebApiTest { - - // data to check for in tests - private final static XML_ELEMENT ROOT_ELEMENT = XML_ELEMENT.SLIDESHOW; - private final static XML_ELEMENT ITEM_ELEMENT = XML_ELEMENT.ITEM; - private final static XML_ATTRIBUTE DATE_ATTRIBUTE = XML_ATTRIBUTE.DATE; - private final static String XML_ENCODING = "us-ascii"; - private final static String DATE_ATTRIBUTE_VALUE = "Date of publication"; - - private static SimpleXMLPage simpleXMLPage = new SimpleXMLPage(); - private static Document simpleXMLPageDocument; - - @BeforeClass - public static void setup() { - BFLogger.logDebug("Reading " + simpleXMLPage.getEndpoint()); - try { - simpleXMLPageDocument = SimpleXMLParser.convertToDocumentNormalized(simpleXMLPage.getXMLDocument() - .asInputStream()); - } catch (IOException e) { - BFLogger.logInfo("Cannot convert and normalize XML document due to IO Exception. " + e.toString()); - } catch (SAXException e) { - BFLogger.logInfo("Cannot convert XML document due to parsing problem. " + e.toString()); - } - - } - - @Test - public void validateXMLPageRequestHTTPResponseCode() { - final int HTTP_OK = 200; - BFLogger.logInfo("Validating that request for " + simpleXMLPage.getEndpoint() + " completed with status code: " + HTTP_OK); - assertThat(simpleXMLPage.getXMLDocument() - .getStatusCode(), equalTo(HTTP_OK)); - } - - @Test - public void validateRootElementName() { - BFLogger.logInfo("Validating that document root is " + ROOT_ELEMENT.getElementKey() + " element"); - assertThat(simpleXMLPageDocument.getDocumentElement() - .getNodeName(), equalTo(ROOT_ELEMENT.getElementKey())); - } - - @Test - public void validateElementsNumberWhenSearchingByTag() { - BFLogger.logInfo("Validating that " + ITEM_ELEMENT.getElementKey() + " element number is 3"); - NodeList itemsList = simpleXMLPageDocument.getElementsByTagName(ITEM_ELEMENT.getElementKey()); - assertThat(itemsList.getLength(), equalTo(3)); - } - - @Test - public void validateRootElementAttributeValueAndNumberWhenSearchingByTag() { - BFLogger.logInfo("Validating " + DATE_ATTRIBUTE.getAttributeKey() + " attribute value"); - NodeList itemsList = simpleXMLPageDocument.getElementsByTagName(ROOT_ELEMENT.getElementKey()); - // there can be only 1 - assertThat(itemsList.getLength(), equalTo(1)); - Element rootElement = (Element) (itemsList.item(0)); - - assertThat(rootElement.getAttribute(DATE_ATTRIBUTE.getAttributeKey()), equalTo(DATE_ATTRIBUTE_VALUE)); - } - - @Test - public void validateXmlDocumentEncoding() { - BFLogger.logInfo("Validating document encoding to be " + XML_ENCODING); - assertThat(simpleXMLPageDocument.getXmlEncoding(), equalTo(XML_ENCODING)); - } -} diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/tags/IntegrationTest.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/tags/IntegrationTest.java new file mode 100644 index 00000000..c45ede7a --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/tags/IntegrationTest.java @@ -0,0 +1,14 @@ +package com.capgemini.mrchecker.webapi.tags; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import org.junit.jupiter.api.Tag; + +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +@Tag("IntegrationTest") +public @interface IntegrationTest { +} \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/tags/UnitTest.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/tags/UnitTest.java new file mode 100644 index 00000000..9f23da50 --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/tags/UnitTest.java @@ -0,0 +1,14 @@ +package com.capgemini.mrchecker.webapi.tags; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import org.junit.jupiter.api.Tag; + +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +@Tag("UnitTest") +public @interface UnitTest { +} \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/testsuites/UnitTestsSuite.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/testsuites/UnitTestsSuite.java new file mode 100644 index 00000000..3c855d3c --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/testsuites/UnitTestsSuite.java @@ -0,0 +1,12 @@ +package com.capgemini.mrchecker.webapi.testsuites; + +import org.junit.platform.runner.JUnitPlatform; +import org.junit.platform.suite.api.IncludeTags; +import org.junit.platform.suite.api.SelectPackages; +import org.junit.runner.RunWith; + +@RunWith(JUnitPlatform.class) +@IncludeTags({ "UnitTest" }) +@SelectPackages("com.capgemini.mrchecker.webapi") +public class UnitTestsSuite { +} diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/BasePageWebApiTest.java b/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/unit/BasePageWebApiTest.java similarity index 51% rename from mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/BasePageWebApiTest.java rename to mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/unit/BasePageWebApiTest.java index f369aad5..fff2cfd6 100644 --- a/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/BasePageWebApiTest.java +++ b/mrchecker-framework-modules/mrchecker-webapi-module/src/test/java/com/capgemini/mrchecker/webapi/unit/BasePageWebApiTest.java @@ -1,10 +1,15 @@ -package com.capgemini.mrchecker.webapi; +package com.capgemini.mrchecker.webapi.unit; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.ResourceLock; import com.capgemini.mrchecker.test.core.BaseTest; +import com.capgemini.mrchecker.test.core.utils.PageFactory; import com.capgemini.mrchecker.webapi.core.BasePageWebAPI; +import com.capgemini.mrchecker.webapi.tags.UnitTest; +@UnitTest +@ResourceLock("PropertiesFileSettings.class") public class BasePageWebApiTest extends BaseTest { @Override @@ -19,12 +24,11 @@ public void tearDown() { @Test public void test() { - MyPage myPage = new MyPage(); - + MyPage myPage = PageFactory.getPageInstance(MyPage.class); myPage.myMethod(); } - private static class MyPage extends BasePageWebAPI { + public static class MyPage extends BasePageWebAPI { public String myMethod() { return "Welcome"; diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/test/resources/allure.properties b/mrchecker-framework-modules/mrchecker-webapi-module/src/test/resources/allure.properties new file mode 100644 index 00000000..6c1e0bb1 --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-webapi-module/src/test/resources/allure.properties @@ -0,0 +1 @@ +allure.results.directory=target/allure-results \ No newline at end of file diff --git a/mrchecker-framework-modules/mrchecker-webapi-module/src/test/resources/junit-platform.properties b/mrchecker-framework-modules/mrchecker-webapi-module/src/test/resources/junit-platform.properties new file mode 100644 index 00000000..0a5f88f7 --- /dev/null +++ b/mrchecker-framework-modules/mrchecker-webapi-module/src/test/resources/junit-platform.properties @@ -0,0 +1,8 @@ +junit.jupiter.extensions.autodetection.enabled=true +junit.jupiter.execution.parallel.enabled=true +#junit.jupiter.execution.parallel.mode.default=concurrent +junit.jupiter.execution.parallel.mode.default=same_thread +junit.jupiter.execution.parallel.mode.classes.default=concurrent +#junit.jupiter.execution.parallel.mode.classes.default=same_thread +junit.jupiter.execution.parallel.config.strategy=dynamic +junit.jupiter.execution.parallel.config.dynamic.factor=1 diff --git a/mrchecker-framework-modules/pom.xml b/mrchecker-framework-modules/pom.xml index 9bcef615..6a23d1c4 100644 --- a/mrchecker-framework-modules/pom.xml +++ b/mrchecker-framework-modules/pom.xml @@ -5,9 +5,11 @@ 4.0.0 com.capgemini.mrchecker mrchecker-test-framework - 2.4.2-SNAPSHOT + 3.0.1-SNAPSHOT MrChecker - MrChecker Test Framework is an automated testing framework for functional testing of web applications, native mobile apps, webservices and database. + MrChecker Test Framework is an automated testing framework for functional testing of web applications, + native mobile apps, webservices and database. + https://github.com/devonfw/devonfw-testing pom @@ -40,11 +42,12 @@ - + mrchecker-core-module + mrchecker-selenium-module + mrchecker-security-module + mrchecker-webapi-module + mrchecker-mobile-module + mrchecker-database-module @@ -67,30 +70,35 @@ - - UTF8 3.7.1 3.0.0 + + 0.8.3 + 1.8 - 2.19.1 - 1.0.0-M2 - 8 + 3.0.0-M3 + 1.3.2 1.3 - 4.12 - 1.8.5 + 5.6.2 + 1.6.2 + 5.6.2 + 5.6.2 + 2.27.0 2.9.9 - 1.1 + 1.8 + 3.1 1.0.4 + 4.1.0 @@ -100,6 +108,8 @@ 1.9.2 + 2.11.0 + 2.7.1 ${pom.basedir}/../../resources/style_format @@ -108,62 +118,26 @@ 3.0.6 - 2.6.0 + 1.9.5 + 2.13.3 + 2.13.3 + 2.13.3 + 2.10.0 - - - com.google.inject - guice - ${guice.version} - - - - - org.hamcrest - hamcrest-all - ${hamcrest.version} - test - - - - org.apache.commons - commons-csv - ${commons-csv.version} - - - - - - junit - junit - ${junit.version} - - - pl.pragmatists - JUnitParams - ${JUnitParams.version} - - org.junit.platform junit-platform-surefire-provider ${surefire.provider.version} - - org.mockito - mockito-core - ${mockito.version} - - - joda-time - joda-time - ${joda-time.version} + pl.pragmatists + JUnitParams + ${JUnitParams.version} @@ -196,8 +170,37 @@ io.qameta.allure - allure-junit4 - ${allure-junit4-listener.version} + allure-junit5 + ${allure-junit5.version} + test + + + + + io.qameta.allure + allure-junit-platform + ${allure-junit-platform.version} + test + + + + + io.qameta.allure + allure-maven + ${allure-maven.version} + test + + + + io.qameta.allure + allure-java-commons + ${allure-java-commons.version} + + + + org.aspectj + aspectjweaver + ${aspectj.version} @@ -205,6 +208,86 @@ + + + + + + com.google.inject + guice + ${guice.version} + + + + + org.junit.jupiter + junit-jupiter-engine + ${junit.jupiter.version} + + + + org.junit.jupiter + junit-jupiter-api + ${junit.jupiter.version} + + + + org.junit.jupiter + junit-jupiter-params + ${junit.params.version} + test + + + + org.junit.platform + junit-platform-runner + ${junit.platform.version} + test + + + + org.junit.vintage + junit-vintage-engine + ${junit.vintage.version} + test + + + + + org.hamcrest + hamcrest-all + ${hamcrest.version} + test + + + + org.mockito + mockito-core + ${mockito.version} + + + + + org.apache.commons + commons-csv + ${commons-csv.version} + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + + + joda-time + joda-time + ${joda-time.version} + + + + @@ -228,7 +311,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.6.1 + 3.8.1 ${java.compiler.version} ${java.compiler.version} @@ -269,9 +352,6 @@ maven-surefire-plugin ${maven-surefire-plugin.version} - classes - false - ${thread.count} **/*.class @@ -279,10 +359,31 @@ **/RawTest.* **/OutboxDocumentTest.* + + -javaagent:"${settings.localRepository}/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar" + ${surefireArgLine} + + + + listener + io.qameta.allure.junit5.AllureJunit5 + + + + + org.aspectj + aspectjweaver + ${aspectj.version} + + + org.apache.maven.surefire + surefire-api + ${maven-surefire-plugin.version} + + - org.apache.maven.plugins @@ -296,7 +397,14 @@ ${maven-project-info-reports-plugin.version} - + + io.qameta.allure + allure-maven + ${allure-maven.version} + + 2.4.1 + + @@ -309,12 +417,34 @@ 8 + + org.jacoco + jacoco-maven-plugin + ${jacoco-maven-plugin.version} + + + prepare-tests + + prepare-agent + + + ${project.build.directory}/jacoco.exec + surefireArgLine + + + + coverage-report + post-integration-test + + report + + + + - - release @@ -451,6 +581,7 @@ + true @@ -520,6 +651,7 @@ + true