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