Merge "aaiSubscriberController Test"
[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 vid.automation.test.infra.FeaturesTogglingConfiguration;
37 import vid.automation.test.services.UsersService;
38 import vid.automation.test.utils.CookieAndJsonHttpHeadersInterceptor;
39
40 public class BaseApiTest {
41     protected static final Logger LOGGER = LogManager.getLogger(BaseApiTest.class);
42
43     @SuppressWarnings("WeakerAccess")
44     protected URI uri;
45     @SuppressWarnings("WeakerAccess")
46     protected ObjectMapper objectMapper = new ObjectMapper();
47     @SuppressWarnings("WeakerAccess")
48     protected Client client;
49     protected Random random;
50     protected final RestTemplate restTemplate = new RestTemplate();
51
52     protected final UsersService usersService = new UsersService();
53     protected final RestTemplate restTemplateErrorAgnostic = new RestTemplate();
54
55     @BeforeClass
56     public void init() {
57         uri = getUri();
58         objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
59         client = ClientBuilder.newClient();
60         client.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
61         random = new Random(System.currentTimeMillis());
62         FeaturesTogglingConfiguration.initializeFeatureManager();
63     }
64
65     private URI getUri() {
66         String host = System.getProperty("VID_HOST", "10.0.0.10");
67         int port = Integer.valueOf(System.getProperty("VID_PORT", "8080"));
68         return new JerseyUriBuilder().host(host).port(port).scheme("http").path("vid").build();
69     }
70
71     public void login() {
72         login(getUserCredentials());
73     }
74
75     public void login(UserCredentials userCredentials) {
76         final List<ClientHttpRequestInterceptor> interceptors = singletonList(new CookieAndJsonHttpHeadersInterceptor(getUri(), userCredentials));
77         restTemplate.setInterceptors(interceptors);
78         restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
79             @Override
80             public void handleError(ClientHttpResponse response) throws IOException {
81                 try {
82                     super.handleError(response);
83                 } catch (HttpStatusCodeException e) {
84                     LOGGER.error("HTTP {}: {}", e.getStatusCode(), e.getResponseBodyAsString(), e);
85                     throw e;
86                 }
87             }
88         });
89
90         restTemplateErrorAgnostic.setInterceptors(interceptors);
91         restTemplateErrorAgnostic.setErrorHandler(new DefaultResponseErrorHandler() {
92             @Override
93             public boolean hasError(ClientHttpResponse response) {
94                 return false;
95             }
96         });
97     }
98
99
100     //set time zone to UTC so clock will go closely with VID app
101     @BeforeClass
102     public void setDefaultTimeZoneToUTC() {
103         System.setProperty("user.timezone", "UTC");
104         TimeZone.setDefault(TimeZone.getTimeZone("UTC")); //since TimeZone cache previous user.timezone
105     }
106
107     public UserCredentials getUserCredentials() {
108         final Properties configProp = new Properties();
109         try {
110             InputStream input = ClassLoader.getSystemResourceAsStream("test_config.properties");
111             configProp.load(input);
112         } catch (IOException e) {
113             throw new RuntimeException(e);
114         }
115
116         String loginId = configProp.getProperty("test.loginId", "i'm illegal");
117         String loginPassword = configProp.getProperty("test.loginPassword", "i'm illegal");
118         return new UserCredentials(loginId, loginPassword, null, null, null);
119     }
120
121
122
123
124     protected String getCleanJsonString(String jsonString) {
125         // remove leading/trailing double-quotes and unescape
126         String res = unescapeJson(jsonString.replaceAll("^\"|\"$", ""));
127         LOGGER.debug("getCleanJsonString: " + jsonString + " ==> " + res);
128         return res;
129     }
130
131     protected String getCleanJsonString(Object object) throws JsonProcessingException {
132         if (object instanceof String) {
133             return getCleanJsonString((String) object);
134         } else {
135             return new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(object);
136         }
137     }
138
139     protected String buildUri(String path) {
140         return uri + "/" + path;
141     }
142
143     public static String getResourceAsString(String resourcePath) {
144         // load expected result
145         final URL resource = BaseApiTest.class.getClassLoader().getResource(resourcePath);
146         if (resource == null) throw new RuntimeException("resource file not found: " + resourcePath);
147         try {
148             return IOUtils.toString(resource, "UTF-8");
149         } catch (IOException e) {
150             throw new RuntimeException(e);
151         }
152     }
153
154     protected void assertJsonEquals(String actual, String expected) {
155         LOGGER.info(actual);
156         assertThat(actual, not(isEmptyOrNullString()));
157
158         assertThat(actual, jsonEquals(expected)
159                 .when(IGNORING_ARRAY_ORDER)
160         );
161     }
162
163 }