7ce29446c083fe543d0701ff088e2fa865bb9cd6
[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.automation.common.report_portal_integration.listeners.ReportPortalListener;
12 import com.fasterxml.jackson.core.JsonProcessingException;
13 import com.fasterxml.jackson.databind.ObjectMapper;
14 import com.fasterxml.jackson.databind.SerializationFeature;
15 import java.io.IOException;
16 import java.io.InputStream;
17 import java.net.URI;
18 import java.net.URL;
19 import java.util.List;
20 import java.util.Properties;
21 import java.util.Random;
22 import java.util.TimeZone;
23 import javax.ws.rs.client.Client;
24 import javax.ws.rs.client.ClientBuilder;
25 import org.apache.commons.io.IOUtils;
26 import org.apache.logging.log4j.LogManager;
27 import org.apache.logging.log4j.Logger;
28 import org.glassfish.jersey.client.ClientProperties;
29 import org.glassfish.jersey.uri.internal.JerseyUriBuilder;
30 import org.onap.sdc.ci.tests.datatypes.UserCredentials;
31 import org.springframework.http.client.ClientHttpRequestInterceptor;
32 import org.springframework.http.client.ClientHttpResponse;
33 import org.springframework.web.client.DefaultResponseErrorHandler;
34 import org.springframework.web.client.HttpStatusCodeException;
35 import org.springframework.web.client.RestTemplate;
36 import org.testng.annotations.BeforeClass;
37 import org.testng.annotations.Listeners;
38 import vid.automation.test.infra.FeaturesTogglingConfiguration;
39 import vid.automation.test.services.UsersService;
40 import vid.automation.test.utils.CookieAndJsonHttpHeadersInterceptor;
41
42 //@Listeners(ReportPortalListener.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         return new JerseyUriBuilder().host(host).port(port).scheme("http").path("vid").build();
72     }
73
74     public void login() {
75         login(getUserCredentials());
76     }
77
78     public void login(UserCredentials userCredentials) {
79         final List<ClientHttpRequestInterceptor> interceptors = singletonList(new CookieAndJsonHttpHeadersInterceptor(getUri(), userCredentials));
80         restTemplate.setInterceptors(interceptors);
81         restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
82             @Override
83             public void handleError(ClientHttpResponse response) throws IOException {
84                 try {
85                     super.handleError(response);
86                 } catch (HttpStatusCodeException e) {
87                     LOGGER.error("HTTP {}: {}", e.getStatusCode(), e.getResponseBodyAsString(), e);
88                     throw e;
89                 }
90             }
91         });
92
93         restTemplateErrorAgnostic.setInterceptors(interceptors);
94         restTemplateErrorAgnostic.setErrorHandler(new DefaultResponseErrorHandler() {
95             @Override
96             public boolean hasError(ClientHttpResponse response) {
97                 return false;
98             }
99         });
100     }
101
102
103     //set time zone to UTC so clock will go closely with VID app
104     @BeforeClass
105     public void setDefaultTimeZoneToUTC() {
106         System.setProperty("user.timezone", "UTC");
107         TimeZone.setDefault(TimeZone.getTimeZone("UTC")); //since TimeZone cache previous user.timezone
108     }
109
110     public UserCredentials getUserCredentials() {
111         final Properties configProp = new Properties();
112         try {
113             InputStream input = ClassLoader.getSystemResourceAsStream("test_config.properties");
114             configProp.load(input);
115         } catch (IOException e) {
116             throw new RuntimeException(e);
117         }
118
119         String loginId = configProp.getProperty("test.loginId", "i'm illegal");
120         String loginPassword = configProp.getProperty("test.loginPassword", "i'm illegal");
121         return new UserCredentials(loginId, loginPassword, null, null, null);
122     }
123
124
125
126
127     protected String getCleanJsonString(String jsonString) {
128         // remove leading/trailing double-quotes and unescape
129         String res = unescapeJson(jsonString.replaceAll("^\"|\"$", ""));
130         LOGGER.debug("getCleanJsonString: " + jsonString + " ==> " + res);
131         return res;
132     }
133
134     protected String getCleanJsonString(Object object) throws JsonProcessingException {
135         if (object instanceof String) {
136             return getCleanJsonString((String) object);
137         } else {
138             return new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(object);
139         }
140     }
141
142     protected String buildUri(String path) {
143         return uri + "/" + path;
144     }
145
146     public static String getResourceAsString(String resourcePath) {
147         // load expected result
148         final URL resource = BaseApiTest.class.getClassLoader().getResource(resourcePath);
149         if (resource == null) throw new RuntimeException("resource file not found: " + resourcePath);
150         try {
151             return IOUtils.toString(resource, "UTF-8");
152         } catch (IOException e) {
153             throw new RuntimeException(e);
154         }
155     }
156
157     protected void assertJsonEquals(String actual, String expected) {
158         LOGGER.info(actual);
159         assertThat(actual, not(isEmptyOrNullString()));
160
161         assertThat(actual, jsonEquals(expected)
162                 .when(IGNORING_ARRAY_ORDER)
163         );
164     }
165
166 }