22365717098345708ac16a1da3a17773663164b9
[vid.git] / vid-automation / src / test / java / org / onap / vid / api / BaseApiTest.java
1 package org.onap.vid.api;
2
3 import com.att.automation.common.report_portal_integration.listeners.ReportPortalListener;
4 import com.fasterxml.jackson.core.JsonProcessingException;
5 import com.google.common.primitives.Ints;
6 import org.apache.commons.io.IOUtils;
7 import org.apache.logging.log4j.LogManager;
8 import org.apache.logging.log4j.Logger;
9 import org.codehaus.jackson.map.ObjectMapper;
10 import org.codehaus.jackson.map.SerializationConfig;
11 import org.glassfish.jersey.client.ClientProperties;
12 import org.glassfish.jersey.uri.internal.JerseyUriBuilder;
13 import org.openecomp.sdc.ci.tests.datatypes.UserCredentials;
14 import org.springframework.http.HttpHeaders;
15 import org.springframework.http.MediaType;
16 import org.springframework.http.client.ClientHttpRequestInterceptor;
17 import org.springframework.http.client.ClientHttpResponse;
18 import org.springframework.web.client.DefaultResponseErrorHandler;
19 import org.springframework.web.client.RestTemplate;
20 import org.testng.annotations.AfterClass;
21 import org.testng.annotations.BeforeClass;
22 import org.testng.annotations.Listeners;
23 import vid.automation.test.infra.FeaturesTogglingConfiguration;
24 import vid.automation.test.services.UsersService;
25 import vid.automation.test.utils.CookieAndJsonHttpHeadersInterceptor;
26
27 import javax.ws.rs.client.Client;
28 import javax.ws.rs.client.ClientBuilder;
29 import java.io.IOException;
30 import java.io.InputStream;
31 import java.net.URI;
32 import java.net.URL;
33 import java.sql.Connection;
34 import java.sql.DriverManager;
35 import java.sql.SQLException;
36 import java.sql.Statement;
37 import java.util.List;
38 import java.util.Properties;
39 import java.util.Random;
40
41 import static java.util.Collections.singletonList;
42 import static org.apache.commons.text.StringEscapeUtils.unescapeJson;
43 import static org.hamcrest.CoreMatchers.everyItem;
44 import static org.hamcrest.MatcherAssert.assertThat;
45 import static org.hamcrest.Matchers.greaterThan;
46
47 @Listeners(ReportPortalListener.class)
48 public class BaseApiTest {
49     protected static final Logger LOGGER = LogManager.getLogger(BaseApiTest.class);
50
51     @SuppressWarnings("WeakerAccess")
52     protected URI uri;
53     @SuppressWarnings("WeakerAccess")
54     protected ObjectMapper objectMapper = new ObjectMapper();
55     @SuppressWarnings("WeakerAccess")
56     protected Client client;
57     protected Random random;
58     protected final RestTemplate restTemplate = new RestTemplate();
59
60     protected final UsersService usersService = new UsersService();
61     protected final RestTemplate restTemplateErrorAgnostic = new RestTemplate();
62
63     @BeforeClass
64     public void init() {
65         uri = getUri();
66         objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
67         client = ClientBuilder.newClient();
68         client.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
69         random = new Random(System.currentTimeMillis());
70         FeaturesTogglingConfiguration.initializeFeatureManager();
71     }
72
73     private URI getUri() {
74         String host = System.getProperty("VID_HOST", "127.0.0.1");
75         Integer port = Integer.valueOf(System.getProperty("VID_PORT", "8080"));
76         return new JerseyUriBuilder().host(host).port(port).scheme("http").path("vid").build();
77     }
78
79     public void login() {
80         UserCredentials userCredentials = getUserCredentials();
81         final List<ClientHttpRequestInterceptor> interceptors = singletonList(new CookieAndJsonHttpHeadersInterceptor(getUri(), userCredentials));
82         restTemplate.setInterceptors(interceptors);
83
84         restTemplateErrorAgnostic.setInterceptors(interceptors);
85         restTemplateErrorAgnostic.setErrorHandler(new DefaultResponseErrorHandler() {
86             @Override
87             public boolean hasError(ClientHttpResponse response) {
88                 return false;
89             }
90         });
91     }
92
93
94     static class DB_CONFIG {
95         static String url = String.format("jdbc:mariadb://%s:%d/vid_portal",
96                 System.getProperty("DB_HOST", System.getProperty("VID_HOST", "127.0.0.1")),
97                 Integer.valueOf(System.getProperty("DB_PORT", "3306"))
98         );
99         static String username = "euser";
100         static String password = "euser";
101
102         static final int userId = 2222;
103         static final String loginId = "ab2222";
104         static final int roleId = 2222221;
105         static final int logRoleId = 2222222;
106     }
107
108
109     @BeforeClass
110     protected void createNewTestUser() {
111
112         deleteNewTestUser();
113
114         LOGGER.debug("Connecting database...");
115
116         try (Connection connection = DriverManager.getConnection(DB_CONFIG.url, DB_CONFIG.username, DB_CONFIG.password)) {
117
118             LOGGER.debug("Database connected!");
119             //create new user with specific role
120             Statement stmt = connection.createStatement();
121             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 + "')");
122             stmt.addBatch("INSERT INTO `fn_role` (`ROLE_ID`, `ROLE_NAME`, `ACTIVE_YN`, `PRIORITY`) VALUES (" + DB_CONFIG.roleId + ", 'PACKET CORE___vFlowLogic', 'Y', 5)");
123             stmt.addBatch("INSERT INTO `fn_role` (`ROLE_ID`, `ROLE_NAME`, `ACTIVE_YN`, `PRIORITY`) VALUES (" + DB_CONFIG.logRoleId + ", 'READ___LOGS___PERMITTED', 'Y', 5)");
124             stmt.addBatch("INSERT INTO `fn_user_role` (`USER_ID`, `ROLE_ID`, `PRIORITY`, `APP_ID`) VALUES (" + DB_CONFIG.userId + ", " + DB_CONFIG.roleId + ", NULL, 1)");
125             stmt.addBatch("INSERT INTO `fn_user_role` (`USER_ID`, `ROLE_ID`, `PRIORITY`, `APP_ID`) VALUES (" + DB_CONFIG.userId + ", " + DB_CONFIG.logRoleId + ", NULL, 1)");
126
127
128             int[] executeBatch = stmt.executeBatch();
129             assertThat(Ints.asList(executeBatch), everyItem(greaterThan(0)));
130
131         } catch (SQLException e) {
132             throw new IllegalStateException("Cannot connect the database!", e);
133         }
134
135     }
136
137     @AfterClass
138     protected void deleteNewTestUser() {
139         LOGGER.debug("Connecting database...");
140
141         try (Connection connection = DriverManager.getConnection(DB_CONFIG.url, DB_CONFIG.username, DB_CONFIG.password)) {
142             LOGGER.debug("Database connected!");
143             Statement stmt = connection.createStatement();
144             stmt.addBatch("DELETE FROM `fn_user_role` WHERE `USER_ID` = " + DB_CONFIG.userId);
145             stmt.addBatch("DELETE FROM `fn_user` WHERE `USER_ID` = " + DB_CONFIG.userId);
146             stmt.addBatch("DELETE FROM `fn_role` WHERE `ROLE_ID` = " + DB_CONFIG.roleId);
147             stmt.addBatch("DELETE FROM `fn_role` WHERE `ROLE_ID` = " + DB_CONFIG.logRoleId);
148
149
150             int[] executeBatch = stmt.executeBatch();
151
152         } catch (SQLException e) {
153             throw new IllegalStateException("Cannot connect the database!", e);
154         }
155     }
156
157     protected UserCredentials getUserCredentials() {
158         final Properties configProp = new Properties();
159         try {
160             InputStream input = ClassLoader.getSystemResourceAsStream("test_config.properties");
161             configProp.load(input);
162         } catch (IOException e) {
163             throw new RuntimeException(e);
164         }
165
166         HttpHeaders loginRequestHeaders = new HttpHeaders();
167         loginRequestHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
168         String loginId = configProp.getProperty("test.loginId", "i'm illegal");
169         String loginPassword = configProp.getProperty("test.loginPassword", "i'm illegal");
170         return new UserCredentials(loginId, loginPassword, null, null, null);
171     }
172
173
174
175
176     protected String getCleanJsonString(String jsonString) {
177         // remove leading/trailing double-quotes and unescape
178         String res = unescapeJson(jsonString.replaceAll("^\"|\"$", ""));
179         LOGGER.debug("getCleanJsonString: " + jsonString + " ==> " + res);
180         return res;
181     }
182
183     protected String getCleanJsonString(Object object) throws JsonProcessingException {
184         if (object instanceof String) {
185             return getCleanJsonString((String) object);
186         } else {
187             return new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(object);
188         }
189     }
190
191     protected String buildUri(String path) {
192         return uri + "/" + path;
193     }
194
195     public static String getResourceAsString(String resourcePath) {
196         // load expected result
197         final URL resource = BaseApiTest.class.getClassLoader().getResource(resourcePath);
198         if (resource == null) throw new RuntimeException("resource file not found: " + resourcePath);
199         try {
200             return IOUtils.toString(resource, "UTF-8");
201         } catch (IOException e) {
202             throw new RuntimeException(e);
203         }
204     }
205
206 }