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