Repository: authorjapps/zerocode
Pull request #160 (2018-12-08 07:37:49)

ISS-159 - Single instance of Http Client


Patch:
diff --git a/src/main/java/org/jsmart/zerocode/core/runner/ZeroCodeMultiStepsScenarioRunnerImpl.java b/src/main/java/org/jsmart/zerocode/core/runner/ZeroCodeMultiStepsScenarioRunnerImpl.java
index 4ce2cf19..ac1a6df0 100644
--- a/src/main/java/org/jsmart/zerocode/core/runner/ZeroCodeMultiStepsScenarioRunnerImpl.java
+++ b/src/main/java/org/jsmart/zerocode/core/runner/ZeroCodeMultiStepsScenarioRunnerImpl.java
@@ -1,6 +1,5 @@
 package org.jsmart.zerocode.core.runner;
 
-import com.fasterxml.jackson.databind.ObjectMapper;
 import com.google.inject.Inject;
 import com.google.inject.Singleton;
 import com.google.inject.name.Named;
@@ -29,6 +28,7 @@ import java.util.function.BiConsumer;
 import static org.apache.commons.lang.StringUtils.isEmpty;
 import static org.jsmart.zerocode.core.domain.builders.ZeroCodeExecResultBuilder.newInstance;
 import static org.jsmart.zerocode.core.engine.mocker.RestEndPointMocker.wireMockServer;
+import static org.jsmart.zerocode.core.utils.RunnerUtils.getFullyQualifiedUrl;
 import static org.jsmart.zerocode.core.utils.SmartUtils.prettyPrintJson;
 import static org.slf4j.LoggerFactory.getLogger;
 
@@ -133,7 +133,7 @@ public class ZeroCodeMultiStepsScenarioRunnerImpl implements ZeroCodeMultiStepsS
                         final LocalDateTime requestTimeStamp = LocalDateTime.now();
                         switch (serviceType(serviceName, operationName)) {
                             case REST_CALL:
-                                serviceName = getFullyQualifiedRestUrl(serviceName);
+                                serviceName = getFullyQualifiedUrl(serviceName, host, port, applicationContext);
                                 logCorrelationshipPrinter.aRequestBuilder()
                                         .stepLoop(i)
                                         .relationshipId(logPrefixRelationshipId)
@@ -340,19 +340,6 @@ public class ZeroCodeMultiStepsScenarioRunnerImpl implements ZeroCodeMultiStepsS
         return serviceType;
     }
 
-    private String getFullyQualifiedRestUrl(String serviceEndPoint) {
-        if (serviceEndPoint.startsWith("http://") || serviceEndPoint.startsWith("https://")) {
-            return serviceEndPoint;
-        } else {
-            /*
-             * Make sure your property file contains context-path with a front slash like "/google-map".
-             * -OR-
-             * Empty context path is also ok if it requires. In this case dont put front slash.
-             */
-            return String.format("%s:%s%s%s", host, port, applicationContext, serviceEndPoint);
-        }
-    }
-
     private void stopWireMockServer() {
         if (null != wireMockServer) {
             wireMockServer.stop();
diff --git a/src/main/java/org/jsmart/zerocode/core/runner/ZeroCodePackageRunner.java b/src/main/java/org/jsmart/zerocode/core/runner/ZeroCodePackageRunner.java
index 689794c2..5e07eb78 100644
--- a/src/main/java/org/jsmart/zerocode/core/runner/ZeroCodePackageRunner.java
+++ b/src/main/java/org/jsmart/zerocode/core/runner/ZeroCodePackageRunner.java
@@ -19,6 +19,7 @@ import org.junit.runner.Result;
 import org.junit.runner.notification.RunNotifier;
 import org.junit.runners.ParentRunner;
 import org.junit.runners.model.InitializationError;
+import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import java.util.List;
@@ -31,18 +32,17 @@ import static org.jsmart.zerocode.core.domain.reports.ZeroCodeReportProperties.Z
 import static org.jsmart.zerocode.core.utils.RunnerUtils.getEnvSpecificConfigFile;
 
 public class ZeroCodePackageRunner extends ParentRunner<ScenarioSpec> {
-    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(ZeroCodePackageRunner.class);
+    private static final Logger LOGGER = LoggerFactory.getLogger(ZeroCodePackageRunner.class);
 
-    private ZeroCodeMultiStepsScenarioRunner zeroCodeMultiStepsScenarioRunner;
     private final Class<?> testClass;
-    List<ScenarioSpec> scenarioSpecs;
-    Injector injector;
-    SmartUtils smartUtils;
-
+    private List<ScenarioSpec> scenarioSpecs;
+    private Injector injector;
+    private SmartUtils smartUtils;
     protected Description scenarioDescription;
     protected boolean isRunSuccess;
     protected boolean passed;
     protected boolean testRunCompleted;
+    private ZeroCodeMultiStepsScenarioRunner zeroCodeMultiStepsScenarioRunner;
 
     public ZeroCodePackageRunner(Class<?> testClass) throws InitializationError {
         super(testClass);
@@ -148,7 +148,7 @@ public class ZeroCodePackageRunner extends ParentRunner<ScenarioSpec> {
         // ----------------------------------------------
         notifier.fireTestStarted(description);
 
-        passed = getInjectedMultiStepsRunner().runScenario(child, notifier, description);
+        passed = zeroCodeMultiStepsScenarioRunner.runScenario(child, notifier, description);
 
         testRunCompleted = true;
 
@@ -162,15 +162,6 @@ public class ZeroCodePackageRunner extends ParentRunner<ScenarioSpec> {
     
     }
 
-    private ZeroCodeMultiStepsScenarioRunner getInjectedMultiStepsRunner() {
-        zeroCodeMultiStepsScenarioRunner = getInjector().getInstance(ZeroCodeMultiStepsScenarioRunner.class);
-        return zeroCodeMultiStepsScenarioRunner;
-    }
-
-    private ZeroCodeReportGenerator getInjectedReportGenerator() {
-        return getInjector().getInstance(ZeroCodeReportGenerator.class);
-    }
-
     public Injector getInjector() {
         //TODO: Synchronise this with e.g. synchronized (ZeroCodePackageRunner.class) {}
         final TargetEnv envAnnotation = testClass.getAnnotation(TargetEnv.class);
@@ -204,6 +195,15 @@ public class ZeroCodePackageRunner extends ParentRunner<ScenarioSpec> {
         this.zeroCodeMultiStepsScenarioRunner = zeroCodeMultiStepsScenarioRunner;
     }
 
+    private ZeroCodeMultiStepsScenarioRunner getInjectedMultiStepsRunner() {
+        zeroCodeMultiStepsScenarioRunner = getInjector().getInstance(ZeroCodeMultiStepsScenarioRunner.class);
+        return zeroCodeMultiStepsScenarioRunner;
+    }
+
+    private ZeroCodeReportGenerator getInjectedReportGenerator() {
+        return getInjector().getInstance(ZeroCodeReportGenerator.class);
+    }
+
     private void handleNoRunListenerReport(ZeroCodeTestReportListener reportListener) {
         if(CHARTS_AND_CSV.equals(getProperty(ZEROCODE_JUNIT))){
             /**
diff --git a/src/main/java/org/jsmart/zerocode/core/runner/ZeroCodeUnitRunner.java b/src/main/java/org/jsmart/zerocode/core/runner/ZeroCodeUnitRunner.java
index 7c22ea63..511ce38c 100644
--- a/src/main/java/org/jsmart/zerocode/core/runner/ZeroCodeUnitRunner.java
+++ b/src/main/java/org/jsmart/zerocode/core/runner/ZeroCodeUnitRunner.java
@@ -57,6 +57,8 @@ public class ZeroCodeUnitRunner extends BlockJUnit4ClassRunner {
 
     private LogCorrelationshipPrinter logCorrelationshipPrinter;
 
+    private ZeroCodeMultiStepsScenarioRunner multiStepsRunner;
+
     /**
      * Creates a BlockJUnit4ClassRunner to run {@code klass}
      *
@@ -69,34 +71,20 @@ public class ZeroCodeUnitRunner extends BlockJUnit4ClassRunner {
         this.testClass = klass;
         this.smartUtils = getInjectedSmartUtilsClass();
 
-        smartTestCaseNames = getSmartChildrenList();
+        this.smartTestCaseNames = getSmartChildrenList();
 
         /*
          * Read the host, port, context etc from the inline annotation instead of a properties file
          */
-        hostProperties = testClass.getAnnotation(HostProperties.class);
+        this.hostProperties = testClass.getAnnotation(HostProperties.class);
 
-        if (hostProperties != null) {
-            host = hostProperties.host();
-            port = hostProperties.port();
-            context = hostProperties.context();
+        if (this.hostProperties != null) {
+            this.host = hostProperties.host();
+            this.port = hostProperties.port();
+            this.context = hostProperties.context();
         }
-    }
-
-    private List<String> getSmartChildrenList() {
-        List<FrameworkMethod> children = getChildren();
-        children.forEach(
-                frameworkMethod -> {
-                    JsonTestCase annotation = frameworkMethod.getAnnotation(JsonTestCase.class);
-                    if (annotation != null) {
-                        smartTestCaseNames.add(annotation.value());
-                    } else {
-                        smartTestCaseNames.add(frameworkMethod.getName());
-                    }
-                }
-        );
 
-        return smartTestCaseNames;
+        this.multiStepsRunner = createZeroCodeMultiStepRunner();
     }
 
     @Override
@@ -149,25 +137,6 @@ public class ZeroCodeUnitRunner extends BlockJUnit4ClassRunner {
         return zeroCodeMultiStepsScenarioRunner;
     }
 
-    public Injector getMainModuleInjector() {
-        // Synchronise this with an object lock e.g. synchronized (ZeroCodeUnitRunner.class) {}
-        synchronized (this) {
-            final TargetEnv envAnnotation = testClass.getAnnotation(TargetEnv.class);
-            String serverEnv = envAnnotation != null ? envAnnotation.value() : "config_hosts.properties";
-
-            serverEnv = getEnvSpecificConfigFile(serverEnv, testClass);
-
-            final UseHttpClient httpClientAnnotated = testClass.getAnnotation(UseHttpClient.class);
-            Class<? extends BasicHttpClient> runtimeHttpClient =
-                    httpClientAnnotated != null ? httpClientAnnotated.value() : SslTrustHttpClient.class;
-
-            injector = Guice.createInjector(Modules.override(new ApplicationMainModule(serverEnv))
-                    .with(new RuntimeHttpClientModule(runtimeHttpClient)));
-
-            return injector;
-        }
-    }
-
     protected SmartUtils getInjectedSmartUtilsClass() {
         return getMainModuleInjector().getInstance(SmartUtils.class);
     }
@@ -191,17 +160,6 @@ public class ZeroCodeUnitRunner extends BlockJUnit4ClassRunner {
 
             LOGGER.debug("### Found currentTestCase : -" + child);
 
-            final ZeroCodeMultiStepsScenarioRunner multiStepsRunner = getInjectedMultiStepsRunner();
-
-            /*
-             * Override the properties file containing hosts and ports with HostProperties
-             * only if the annotation is present on the runner.
-             */
-            if (hostProperties != null) {
-                ((ZeroCodeMultiStepsScenarioRunnerImpl) multiStepsRunner).overrideHost(host);
-                ((ZeroCodeMultiStepsScenarioRunnerImpl) multiStepsRunner).overridePort(port);
-                ((ZeroCodeMultiStepsScenarioRunnerImpl) multiStepsRunner).overrideApplicationContext(context);
-            }
             passed = multiStepsRunner.runScenario(child, notifier, description);
 
         } catch (Exception ioEx) {
@@ -220,6 +178,56 @@ public class ZeroCodeUnitRunner extends BlockJUnit4ClassRunner {
         notifier.fireTestFinished(description);
     }
 
+    private Injector getMainModuleInjector() {
+        // Synchronise this with an object lock e.g. synchronized (ZeroCodeUnitRunner.class) {}
+        synchronized (this) {
+            final TargetEnv envAnnotation = testClass.getAnnotation(TargetEnv.class);
+            String serverEnv = envAnnotation != null ? envAnnotation.value() : "config_hosts.properties";
+
+            serverEnv = getEnvSpecificConfigFile(serverEnv, testClass);
+
+            final UseHttpClient httpClientAnnotated = testClass.getAnnotation(UseHttpClient.class);
+            Class<? extends BasicHttpClient> runtimeHttpClient =
+                    httpClientAnnotated != null ? httpClientAnnotated.value() : SslTrustHttpClient.class;
+
+            injector = Guice.createInjector(Modules.override(new ApplicationMainModule(serverEnv))
+                    .with(new RuntimeHttpClientModule(runtimeHttpClient)));
+
+            return injector;
+        }
+    }
+
+    private List<String> getSmartChildrenList() {
+        List<FrameworkMethod> children = getChildren();
+        children.forEach(
+                frameworkMethod -> {
+                    JsonTestCase annotation = frameworkMethod.getAnnotation(JsonTestCase.class);
+                    if (annotation != null) {
+                        smartTestCaseNames.add(annotation.value());
+                    } else {
+                        smartTestCaseNames.add(frameworkMethod.getName());
+                    }
+                }
+        );
+
+        return smartTestCaseNames;
+    }
+
+    private ZeroCodeMultiStepsScenarioRunner createZeroCodeMultiStepRunner() {
+        final ZeroCodeMultiStepsScenarioRunner multiStepsRunner = getInjectedMultiStepsRunner();
+
+        /*
+         * Override the properties file containing hosts and ports with HostProperties
+         * only if the annotation is present on the runner.
+         */
+        if (hostProperties != null) {
+            ((ZeroCodeMultiStepsScenarioRunnerImpl) multiStepsRunner).overrideHost(host);
+            ((ZeroCodeMultiStepsScenarioRunnerImpl) multiStepsRunner).overridePort(port);
+            ((ZeroCodeMultiStepsScenarioRunnerImpl) multiStepsRunner).overrideApplicationContext(context);
+        }
+        return multiStepsRunner;
+    }
+
     private final void runLeafJUnitTest(Statement statement, Description description,
                                         RunNotifier notifier) {
         LOGGER.info("Running a pure JUnit test...");
@@ -253,7 +261,6 @@ public class ZeroCodeUnitRunner extends BlockJUnit4ClassRunner {
 
             eachNotifier.fireTestFinished();
         }
-
     }
 
     private void buildReportAndPrintToFile(Description description) {
diff --git a/src/main/java/org/jsmart/zerocode/core/utils/RunnerUtils.java b/src/main/java/org/jsmart/zerocode/core/utils/RunnerUtils.java
index 5a48b2ff..705656aa 100644
--- a/src/main/java/org/jsmart/zerocode/core/utils/RunnerUtils.java
+++ b/src/main/java/org/jsmart/zerocode/core/utils/RunnerUtils.java
@@ -1,5 +1,6 @@
 package org.jsmart.zerocode.core.utils;
 
+import org.apache.commons.lang.StringUtils;
 import org.jsmart.zerocode.core.domain.EnvProperty;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -64,4 +65,25 @@ public class RunnerUtils {
         final String DOT_PROPERTIES = ".properties";
         return serverEnv.replace(DOT_PROPERTIES, resolvedEnvPropNameWithPrefix + DOT_PROPERTIES);
     }
+
+    public static String getFullyQualifiedUrl(String serviceEndPoint,
+                                              String host,
+                                              String port,
+                                              String applicationContext) {
+        if (serviceEndPoint.startsWith("http://") || serviceEndPoint.startsWith("https://")) {
+            return serviceEndPoint;
+
+        } else if(StringUtils.isEmpty(port)){
+            return String.format("%s%s%s", host, applicationContext, serviceEndPoint);
+
+        } else {
+            /*
+             * Make sure your property file contains context-path with a front slash like "/google-map".
+             * -OR-
+             * Empty context path is also ok if it requires. In this case do not put front slash.
+             */
+            return String.format("%s:%s%s%s", host, port, applicationContext, serviceEndPoint);
+        }
+    }
+
 }


Test patch:
diff --git a/src/test/java/org/jsmart/zerocode/core/utils/RunnerUtilsTest.java b/src/test/java/org/jsmart/zerocode/core/utils/RunnerUtilsTest.java
index 9c67f2c8..ecd57398 100644
--- a/src/test/java/org/jsmart/zerocode/core/utils/RunnerUtilsTest.java
+++ b/src/test/java/org/jsmart/zerocode/core/utils/RunnerUtilsTest.java
@@ -4,6 +4,7 @@ import org.junit.Test;
 
 import static org.hamcrest.MatcherAssert.assertThat;
 import static org.hamcrest.core.Is.is;
+import static org.jsmart.zerocode.core.utils.RunnerUtils.getFullyQualifiedUrl;
 
 public class RunnerUtilsTest {
 
@@ -22,4 +23,42 @@ public class RunnerUtilsTest {
         assertThat(RunnerUtils.suffixEnvValue("/myfolder/myapp.properties", ""), is("/myfolder/myapp.properties"));
 
     }
+
+    @Test
+    public void test_Fqdn() {
+        String fullyQualifiedUrl = getFullyQualifiedUrl("/abc",
+                "http://aws-host.com",
+                "8080",
+                "/acontext");
+        assertThat(fullyQualifiedUrl, is("http://aws-host.com:8080/acontext/abc"));
+
+        // Host having http/https
+        fullyQualifiedUrl = getFullyQualifiedUrl("http://aws-host.com:8080/acontext/abc",
+                "asdf",
+                "9090",
+                "asdf");
+        assertThat(fullyQualifiedUrl, is("http://aws-host.com:8080/acontext/abc"));
+
+        // Without port -http
+        fullyQualifiedUrl = getFullyQualifiedUrl("/abc",
+                "http://aws-host.com",
+                "",
+                "/acontext");
+        assertThat(fullyQualifiedUrl, is("http://aws-host.com/acontext/abc"));
+
+        // Without port -https
+        fullyQualifiedUrl = getFullyQualifiedUrl("/abc",
+                "https://aws-host.com",
+                "",
+                "/acontext");
+        assertThat(fullyQualifiedUrl, is("https://aws-host.com/acontext/abc"));
+
+        // Without context
+        fullyQualifiedUrl = getFullyQualifiedUrl("/abc",
+                "https://aws-host.com",
+                "",
+                "");
+        assertThat(fullyQualifiedUrl, is("https://aws-host.com/abc"));
+
+    }
 }
\ No newline at end of file
diff --git a/src/test/resources/github_host_test.properties b/src/test/resources/github_host_test.properties
index b203a31b..c7e6616b 100755
--- a/src/test/resources/github_host_test.properties
+++ b/src/test/resources/github_host_test.properties
@@ -1,4 +1,4 @@
 # GitHub api hosts
 web.application.endpoint.host=https://api.github.com
-web.application.endpoint.port=443
+web.application.endpoint.port=
 web.application.endpoint.context=
diff --git a/src/test/resources/load_config_test.properties b/src/test/resources/load_config_test.properties
index e1b4679a..6c269e4d 100755
--- a/src/test/resources/load_config_test.properties
+++ b/src/test/resources/load_config_test.properties
@@ -12,7 +12,7 @@ number.of.threads=3
 # at once at the same time. Note- If you want to fire more threads/user-requests in less ramp up time e.g. 5 threads
 # in 2secs(or 5 threads in 1 sec), then, use '@UseHttpClient(SslTrustHttpClient.class)' as this closes the connection
 # before making the next connection.
-ramp.up.period.in.seconds=3
+ramp.up.period.in.seconds=6
 
 # By specifying its value framework gets to know that how many times the test(s), i.e. the number of requests will be
 # repeated per every 'ramp.up.period.in.seconds'.