aboutsummaryrefslogtreecommitdiffstats
path: root/vid-automation/src/main/java/org/onap/vid/api/BaseApiTest.java
blob: 5b7b1b2145b5e0a735008e5c54b6adc1b13cd12d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
package org.onap.vid.api;

import static java.util.Collections.singletonList;
import static net.javacrumbs.jsonunit.JsonMatchers.jsonEquals;
import static net.javacrumbs.jsonunit.core.Option.IGNORING_ARRAY_ORDER;
import static org.apache.commons.text.StringEscapeUtils.unescapeJson;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.isEmptyOrNullString;
import static org.hamcrest.Matchers.not;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import java.util.TimeZone;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.glassfish.jersey.client.ClientProperties;
import org.glassfish.jersey.uri.internal.JerseyUriBuilder;
import org.onap.sdc.ci.tests.datatypes.UserCredentials;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestTemplate;
import org.testng.annotations.BeforeClass;
import vid.automation.test.infra.FeaturesTogglingConfiguration;
import vid.automation.test.services.UsersService;
import vid.automation.test.utils.CookieAndJsonHttpHeadersInterceptor;

public class BaseApiTest {
    protected static final Logger LOGGER = LogManager.getLogger(BaseApiTest.class);

    @SuppressWarnings("WeakerAccess")
    protected URI uri;
    @SuppressWarnings("WeakerAccess")
    protected ObjectMapper objectMapper = new ObjectMapper();
    @SuppressWarnings("WeakerAccess")
    protected Client client;
    protected Random random;
    protected final RestTemplate restTemplate = new RestTemplate();

    protected final UsersService usersService = new UsersService();
    protected final RestTemplate restTemplateErrorAgnostic = new RestTemplate();

    @BeforeClass
    public void init() {
        uri = getUri();
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        client = ClientBuilder.newClient();
        client.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
        random = new Random(System.currentTimeMillis());
        FeaturesTogglingConfiguration.initializeFeatureManager();
    }

    private URI getUri() {
        String host = System.getProperty("VID_HOST", "10.0.0.10");
        int port = Integer.valueOf(System.getProperty("VID_PORT", "8080"));
        return new JerseyUriBuilder().host(host).port(port).scheme("http").path("vid").build();
    }

    public void login() {
        login(getUserCredentials());
    }

    public void login(UserCredentials userCredentials) {
        final List<ClientHttpRequestInterceptor> interceptors = singletonList(new CookieAndJsonHttpHeadersInterceptor(getUri(), userCredentials));
        restTemplate.setInterceptors(interceptors);
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
            @Override
            public void handleError(ClientHttpResponse response) throws IOException {
                try {
                    super.handleError(response);
                } catch (HttpStatusCodeException e) {
                    LOGGER.error("HTTP {}: {}", e.getStatusCode(), e.getResponseBodyAsString(), e);
                    throw e;
                }
            }
        });

        restTemplateErrorAgnostic.setInterceptors(interceptors);
        restTemplateErrorAgnostic.setErrorHandler(new DefaultResponseErrorHandler() {
            @Override
            public boolean hasError(ClientHttpResponse response) {
                return false;
            }
        });
    }


    //set time zone to UTC so clock will go closely with VID app
    @BeforeClass
    public void setDefaultTimeZoneToUTC() {
        System.setProperty("user.timezone", "UTC");
        TimeZone.setDefault(TimeZone.getTimeZone("UTC")); //since TimeZone cache previous user.timezone
    }

    public UserCredentials getUserCredentials() {
        final Properties configProp = new Properties();
        try {
            InputStream input = ClassLoader.getSystemResourceAsStream("test_config.properties");
            configProp.load(input);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        String loginId = configProp.getProperty("test.loginId", "i'm illegal");
        String loginPassword = configProp.getProperty("test.loginPassword", "i'm illegal");
        return new UserCredentials(loginId, loginPassword, null, null, null);
    }




    protected String getCleanJsonString(String jsonString) {
        // remove leading/trailing double-quotes and unescape
        String res = unescapeJson(jsonString.replaceAll("^\"|\"$", ""));
        LOGGER.debug("getCleanJsonString: " + jsonString + " ==> " + res);
        return res;
    }

    protected String getCleanJsonString(Object object) throws JsonProcessingException {
        if (object instanceof String) {
            return getCleanJsonString((String) object);
        } else {
            return new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(object);
        }
    }

    protected String buildUri(String path) {
        return uri + "/" + path;
    }

    public static String getResourceAsString(String resourcePath) {
        // load expected result
        final URL resource = BaseApiTest.class.getClassLoader().getResource(resourcePath);
        if (resource == null) throw new RuntimeException("resource file not found: " + resourcePath);
        try {
            return IOUtils.toString(resource, "UTF-8");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    protected void assertJsonEquals(String actual, String expected) {
        LOGGER.info(actual);
        assertThat(actual, not(isEmptyOrNullString()));

        assertThat(actual, jsonEquals(expected)
                .when(IGNORING_ARRAY_ORDER)
        );
    }

}