Merge automation from ECOMP's repository
[vid.git] / vid-automation / src / main / java / org / onap / vid / api / BaseApiTest.java
@@ -1,47 +1,42 @@
 package org.onap.vid.api;
 
+import static java.util.Collections.singletonList;
+import static net.javacrumbs.jsonunit.JsonMatchers.jsonEquals;
+import static net.javacrumbs.jsonunit.core.Option.IGNORING_ARRAY_ORDER;
+import static org.apache.commons.text.StringEscapeUtils.unescapeJson;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.isEmptyOrNullString;
+import static org.hamcrest.Matchers.not;
+
 import com.fasterxml.jackson.core.JsonProcessingException;
-import com.google.common.primitives.Ints;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.SerializationFeature;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URI;
+import java.net.URL;
+import java.util.List;
+import java.util.Properties;
+import java.util.Random;
+import java.util.TimeZone;
+import javax.ws.rs.client.Client;
+import javax.ws.rs.client.ClientBuilder;
 import org.apache.commons.io.IOUtils;
-import org.apache.log4j.LogManager;
-import org.apache.log4j.Logger;
-import org.codehaus.jackson.map.ObjectMapper;
-import org.codehaus.jackson.map.SerializationConfig;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
 import org.glassfish.jersey.client.ClientProperties;
 import org.glassfish.jersey.uri.internal.JerseyUriBuilder;
-import org.openecomp.sdc.ci.tests.datatypes.UserCredentials;
-import org.springframework.http.HttpHeaders;
-import org.springframework.http.MediaType;
+import org.onap.sdc.ci.tests.datatypes.UserCredentials;
 import org.springframework.http.client.ClientHttpRequestInterceptor;
 import org.springframework.http.client.ClientHttpResponse;
 import org.springframework.web.client.DefaultResponseErrorHandler;
+import org.springframework.web.client.HttpStatusCodeException;
 import org.springframework.web.client.RestTemplate;
-import org.testng.annotations.AfterClass;
 import org.testng.annotations.BeforeClass;
 import vid.automation.test.infra.FeaturesTogglingConfiguration;
 import vid.automation.test.services.UsersService;
 import vid.automation.test.utils.CookieAndJsonHttpHeadersInterceptor;
 
-import javax.ws.rs.client.Client;
-import javax.ws.rs.client.ClientBuilder;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URI;
-import java.net.URL;
-import java.sql.Connection;
-import java.sql.DriverManager;
-import java.sql.SQLException;
-import java.sql.Statement;
-import java.util.List;
-import java.util.Properties;
-import java.util.Random;
-
-import static java.util.Collections.singletonList;
-import static org.apache.commons.text.StringEscapeUtils.unescapeJson;
-import static org.hamcrest.CoreMatchers.everyItem;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.greaterThan;
-
 public class BaseApiTest {
     protected static final Logger LOGGER = LogManager.getLogger(BaseApiTest.class);
 
@@ -60,7 +55,7 @@ public class BaseApiTest {
     @BeforeClass
     public void init() {
         uri = getUri();
-        objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
+        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
         client = ClientBuilder.newClient();
         client.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
         random = new Random(System.currentTimeMillis());
@@ -68,15 +63,29 @@ public class BaseApiTest {
     }
 
     private URI getUri() {
-        String host = System.getProperty("VID_HOST", "127.0.0.1");
-        Integer port = Integer.valueOf(System.getProperty("VID_PORT", "8080"));
+        String host = System.getProperty("VID_HOST", "10.0.0.10");
+        int port = Integer.valueOf(System.getProperty("VID_PORT", "8080"));
         return new JerseyUriBuilder().host(host).port(port).scheme("http").path("vid").build();
     }
 
     public void login() {
-        UserCredentials userCredentials = getUserCredentials();
+        login(getUserCredentials());
+    }
+
+    public void login(UserCredentials userCredentials) {
         final List<ClientHttpRequestInterceptor> interceptors = singletonList(new CookieAndJsonHttpHeadersInterceptor(getUri(), userCredentials));
         restTemplate.setInterceptors(interceptors);
+        restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
+            @Override
+            public void handleError(ClientHttpResponse response) throws IOException {
+                try {
+                    super.handleError(response);
+                } catch (HttpStatusCodeException e) {
+                    LOGGER.error("HTTP {}: {}", e.getStatusCode(), e.getResponseBodyAsString(), e);
+                    throw e;
+                }
+            }
+        });
 
         restTemplateErrorAgnostic.setInterceptors(interceptors);
         restTemplateErrorAgnostic.setErrorHandler(new DefaultResponseErrorHandler() {
@@ -88,70 +97,14 @@ public class BaseApiTest {
     }
 
 
-    static class DB_CONFIG {
-        static String url = String.format("jdbc:mariadb://%s:%d/vid_portal",
-                System.getProperty("DB_HOST", System.getProperty("VID_HOST", "127.0.0.1")),
-                Integer.valueOf(System.getProperty("DB_PORT", "3306"))
-        );
-        static String username = "euser";
-        static String password = "euser";
-
-        static final int userId = 2222;
-        static final String loginId = "vid1";
-        static final int roleId = 2222221;
-        static final int logRoleId = 2222222;
-    }
-
-
+    //set time zone to UTC so clock will go closely with VID app
     @BeforeClass
-    protected void createNewTestUser() {
-
-        deleteNewTestUser();
-
-        LOGGER.debug("Connecting database...");
-
-        try (Connection connection = DriverManager.getConnection(DB_CONFIG.url, DB_CONFIG.username, DB_CONFIG.password)) {
-
-            LOGGER.debug("Database connected!");
-            //create new user with specific role
-            Statement stmt = connection.createStatement();
-            stmt.addBatch("INSERT INTO `fn_user` (`USER_ID`, `ORG_USER_ID`, `LOGIN_ID`, `LOGIN_PWD`) VALUES (" + DB_CONFIG.userId + ", 'Porfirio Gerhardt', '" + DB_CONFIG.loginId + "', '" + DB_CONFIG.loginId + "')");
-            stmt.addBatch("INSERT INTO `fn_role` (`ROLE_ID`, `ROLE_NAME`, `ACTIVE_YN`, `PRIORITY`) VALUES (" + DB_CONFIG.roleId + ", 'PACKET CORE___vFlowLogic', 'Y', 5)");
-            stmt.addBatch("INSERT INTO `fn_role` (`ROLE_ID`, `ROLE_NAME`, `ACTIVE_YN`, `PRIORITY`) VALUES (" + DB_CONFIG.logRoleId + ", 'READ___LOGS___PERMITTED', 'Y', 5)");
-            stmt.addBatch("INSERT INTO `fn_user_role` (`USER_ID`, `ROLE_ID`, `PRIORITY`, `APP_ID`) VALUES (" + DB_CONFIG.userId + ", " + DB_CONFIG.roleId + ", NULL, 1)");
-            stmt.addBatch("INSERT INTO `fn_user_role` (`USER_ID`, `ROLE_ID`, `PRIORITY`, `APP_ID`) VALUES (" + DB_CONFIG.userId + ", " + DB_CONFIG.logRoleId + ", NULL, 1)");
-
-
-            int[] executeBatch = stmt.executeBatch();
-            assertThat(Ints.asList(executeBatch), everyItem(greaterThan(0)));
-
-        } catch (SQLException e) {
-            throw new IllegalStateException("Cannot connect the database!", e);
-        }
-
-    }
-
-    @AfterClass
-    protected void deleteNewTestUser() {
-        LOGGER.debug("Connecting database...");
-
-        try (Connection connection = DriverManager.getConnection(DB_CONFIG.url, DB_CONFIG.username, DB_CONFIG.password)) {
-            LOGGER.debug("Database connected!");
-            Statement stmt = connection.createStatement();
-            stmt.addBatch("DELETE FROM `fn_user_role` WHERE `USER_ID` = " + DB_CONFIG.userId);
-            stmt.addBatch("DELETE FROM `fn_user` WHERE `USER_ID` = " + DB_CONFIG.userId);
-            stmt.addBatch("DELETE FROM `fn_role` WHERE `ROLE_ID` = " + DB_CONFIG.roleId);
-            stmt.addBatch("DELETE FROM `fn_role` WHERE `ROLE_ID` = " + DB_CONFIG.logRoleId);
-
-
-            int[] executeBatch = stmt.executeBatch();
-
-        } catch (SQLException e) {
-            throw new IllegalStateException("Cannot connect the database!", e);
-        }
+    public void setDefaultTimeZoneToUTC() {
+        System.setProperty("user.timezone", "UTC");
+        TimeZone.setDefault(TimeZone.getTimeZone("UTC")); //since TimeZone cache previous user.timezone
     }
 
-    protected UserCredentials getUserCredentials() {
+    public UserCredentials getUserCredentials() {
         final Properties configProp = new Properties();
         try {
             InputStream input = ClassLoader.getSystemResourceAsStream("test_config.properties");
@@ -160,8 +113,6 @@ public class BaseApiTest {
             throw new RuntimeException(e);
         }
 
-        HttpHeaders loginRequestHeaders = new HttpHeaders();
-        loginRequestHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
         String loginId = configProp.getProperty("test.loginId", "i'm illegal");
         String loginPassword = configProp.getProperty("test.loginPassword", "i'm illegal");
         return new UserCredentials(loginId, loginPassword, null, null, null);
@@ -200,4 +151,13 @@ public class BaseApiTest {
         }
     }
 
+    protected void assertJsonEquals(String actual, String expected) {
+        LOGGER.info(actual);
+        assertThat(actual, not(isEmptyOrNullString()));
+
+        assertThat(actual, jsonEquals(expected)
+                .when(IGNORING_ARRAY_ORDER)
+        );
+    }
+
 }