Merge "Validations in different tests for audit log"
[vid.git] / vid-automation / src / main / java / org / onap / vid / api / BaseApiTest.java
1 package org.onap.vid.api;
2
3 import static java.util.Collections.singletonList;
4 import static net.javacrumbs.jsonunit.JsonMatchers.jsonEquals;
5 import static net.javacrumbs.jsonunit.core.Option.IGNORING_ARRAY_ORDER;
6 import static org.apache.commons.text.StringEscapeUtils.unescapeJson;
7 import static org.hamcrest.MatcherAssert.assertThat;
8 import static org.hamcrest.Matchers.isEmptyOrNullString;
9 import static org.hamcrest.Matchers.not;
10
11 import com.fasterxml.jackson.core.JsonProcessingException;
12 import com.fasterxml.jackson.databind.ObjectMapper;
13 import com.fasterxml.jackson.databind.SerializationFeature;
14 import java.io.IOException;
15 import java.io.InputStream;
16 import java.net.URI;
17 import java.net.URL;
18 import java.util.List;
19 import java.util.Properties;
20 import java.util.Random;
21 import java.util.TimeZone;
22 import javax.ws.rs.client.Client;
23 import javax.ws.rs.client.ClientBuilder;
24 import org.apache.commons.io.IOUtils;
25 import org.apache.logging.log4j.LogManager;
26 import org.apache.logging.log4j.Logger;
27 import org.glassfish.jersey.client.ClientProperties;
28 import org.glassfish.jersey.uri.internal.JerseyUriBuilder;
29 import org.onap.sdc.ci.tests.datatypes.UserCredentials;
30 import org.springframework.http.client.ClientHttpRequestInterceptor;
31 import org.springframework.http.client.ClientHttpResponse;
32 import org.springframework.web.client.DefaultResponseErrorHandler;
33 import org.springframework.web.client.HttpStatusCodeException;
34 import org.springframework.web.client.RestTemplate;
35 import org.testng.annotations.BeforeClass;
36 import org.testng.annotations.Listeners;
37 import vid.automation.reportportal.ReportPortalListenerDelegator;
38 import vid.automation.test.infra.FeaturesTogglingConfiguration;
39 import vid.automation.test.services.UsersService;
40 import vid.automation.test.utils.CookieAndJsonHttpHeadersInterceptor;
41
42 @Listeners(ReportPortalListenerDelegator.class)
43 public class BaseApiTest {
44     protected static final Logger LOGGER = LogManager.getLogger(BaseApiTest.class);
45
46     @SuppressWarnings("WeakerAccess")
47     protected URI uri;
48     @SuppressWarnings("WeakerAccess")
49     protected ObjectMapper objectMapper = new ObjectMapper();
50     @SuppressWarnings("WeakerAccess")
51     protected Client client;
52     protected Random random;
53     protected final RestTemplate restTemplate = new RestTemplate();
54
55     protected final UsersService usersService = new UsersService();
56     protected final RestTemplate restTemplateErrorAgnostic = new RestTemplate();
57
58     @BeforeClass
59     public void init() {
60         uri = getUri();
61         objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
62         client = ClientBuilder.newClient();
63         client.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
64         random = new Random(System.currentTimeMillis());
65         FeaturesTogglingConfiguration.initializeFeatureManager();
66     }
67
68     private URI getUri() {
69         String host = System.getProperty("VID_HOST", "127.0.0.1");
70         int port = Integer.valueOf(System.getProperty("VID_PORT", "8080"));
71         String protocol = System.getProperty("VID_PROTOCOL", "http");
72         return new JerseyUriBuilder().host(host).port(port).scheme(protocol).path("vid").build();
73     }
74
75     public void login() {
76         login(getUserCredentials());
77     }
78
79     public void login(UserCredentials userCredentials) {
80         final List<ClientHttpRequestInterceptor> interceptors = loginWithChosenRESTClient(userCredentials, restTemplate);
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     public List<ClientHttpRequestInterceptor> loginWithChosenRESTClient(UserCredentials userCredentials,RestTemplate givenRestTemplate) {
91         final List<ClientHttpRequestInterceptor> interceptors = singletonList(new CookieAndJsonHttpHeadersInterceptor(getUri(), userCredentials));
92         givenRestTemplate.setInterceptors(interceptors);
93         givenRestTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
94             @Override
95             public void handleError(ClientHttpResponse response) throws IOException {
96                 try {
97                     super.handleError(response);
98                 } catch (HttpStatusCodeException e) {
99                     LOGGER.error("HTTP {}: {}", e.getStatusCode(), e.getResponseBodyAsString(), e);
100                     throw e;
101                 }
102             }
103         });
104         return interceptors;
105     }
106
107
108     //set time zone to UTC so clock will go closely with VID app
109     @BeforeClass
110     public void setDefaultTimeZoneToUTC() {
111         System.setProperty("user.timezone", "UTC");
112         TimeZone.setDefault(TimeZone.getTimeZone("UTC")); //since TimeZone cache previous user.timezone
113     }
114
115     public UserCredentials getUserCredentials() {
116         final Properties configProp = new Properties();
117         try {
118             InputStream input = ClassLoader.getSystemResourceAsStream("test_config.properties");
119             configProp.load(input);
120         } catch (IOException e) {
121             throw new RuntimeException(e);
122         }
123
124         String loginId = configProp.getProperty("test.loginId", "i'm illegal");
125         String loginPassword = configProp.getProperty("test.loginPassword", "i'm illegal");
126         return new UserCredentials(loginId, loginPassword, null, null, null);
127     }
128
129
130
131
132     protected String getCleanJsonString(String jsonString) {
133         // remove leading/trailing double-quotes and unescape
134         String res = unescapeJson(jsonString.replaceAll("^\"|\"$", ""));
135         LOGGER.debug("getCleanJsonString: " + jsonString + " ==> " + res);
136         return res;
137     }
138
139     protected String getCleanJsonString(Object object) throws JsonProcessingException {
140         if (object instanceof String) {
141             return getCleanJsonString((String) object);
142         } else {
143             return new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(object);
144         }
145     }
146
147     protected String buildUri(String path) {
148         return uri + "/" + path;
149     }
150
151     public static String getResourceAsString(String resourcePath) {
152         // load expected result
153         final URL resource = BaseApiTest.class.getClassLoader().getResource(resourcePath);
154         if (resource == null) throw new RuntimeException("resource file not found: " + resourcePath);
155         try {
156             return IOUtils.toString(resource, "UTF-8");
157         } catch (IOException e) {
158             throw new RuntimeException(e);
159         }
160     }
161
162     protected void assertJsonEquals(String actual, String expected) {
163         LOGGER.info(actual);
164         assertThat(actual, not(isEmptyOrNullString()));
165
166         assertThat(actual, jsonEquals(expected)
167                 .when(IGNORING_ARRAY_ORDER)
168         );
169     }
170
171 }