Add some timed grace for assertion on log-lines
[vid.git] / vid-automation / src / main / java / org / onap / vid / api / TestUtils.java
1 package org.onap.vid.api;
2
3 import static org.apache.commons.text.CharacterPredicates.DIGITS;
4 import static org.apache.commons.text.CharacterPredicates.LETTERS;
5 import static org.hamcrest.CoreMatchers.is;
6 import static org.hamcrest.Matchers.hasEntry;
7 import static org.hamcrest.Matchers.hasKey;
8 import static org.hamcrest.Matchers.not;
9 import static vid.automation.test.utils.RegExMatcher.matchesRegEx;
10
11 import com.fasterxml.jackson.core.JsonParser;
12 import com.fasterxml.jackson.databind.ObjectMapper;
13 import com.fasterxml.jackson.databind.SerializationFeature;
14 import com.google.common.util.concurrent.Uninterruptibles;
15 import java.io.IOException;
16 import java.io.InputStream;
17 import java.time.Instant;
18 import java.util.Map;
19 import java.util.Scanner;
20 import java.util.concurrent.TimeUnit;
21 import javax.ws.rs.client.WebTarget;
22 import javax.ws.rs.core.Response;
23 import org.apache.commons.text.RandomStringGenerator;
24 import org.hamcrest.Matcher;
25 import org.springframework.core.io.Resource;
26 import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
27 import org.springframework.core.io.support.ResourcePatternResolver;
28 import org.springframework.http.HttpStatus;
29 import org.testng.annotations.DataProvider;
30
31 public class TestUtils {
32
33     protected static ObjectMapper objectMapper = new ObjectMapper();
34
35     public static void assertStatusOK(Object request, WebTarget webTarget, Response response) throws IOException {
36         assertHttpStatus(request, webTarget, response, HttpStatus.OK);
37     }
38
39     public static void assertHttpStatus(Object request, WebTarget webTarget, Response response, HttpStatus exceptedHttpStatus) throws IOException {
40         objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
41
42         org.testng.Assert.assertEquals(response.getStatus(), exceptedHttpStatus.value(),
43                 String.format("Failed post URI: %s with request %s. Got Status:%d and body: %s",
44                         webTarget.getUri(),
45                         objectMapper.writeValueAsString(request),
46                         response.getStatus(),
47                         objectMapper.writeValueAsString(response.getEntity())));
48     }
49
50     public static String convertRequest(ObjectMapper objectMapper, String msoRequestDetailsFileName) {
51
52         ClassLoader cl = TestUtils.class.getClassLoader();
53         ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(cl);
54         Resource[] resources;
55         try {
56             resources = resolver.getResources(msoRequestDetailsFileName);
57             //using InputStream and not file. see https://stackoverflow.com/questions/14876836/file-inside-jar-is-not-visible-for-spring/51131841#51131841
58             InputStream inputStream = resources[0].getInputStream();
59             String content = new Scanner(inputStream).useDelimiter("\\Z").next();
60             objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
61             return objectMapper.writeValueAsString(objectMapper.readValue(content, Object.class));
62         }
63         catch (IOException e) {
64             e.printStackTrace();
65             throw new RuntimeException(e);
66         }
67     }
68
69     public static String getNestedPropertyInMap(Object item, String path) {
70         return getNestedPropertyInMap(item, path, String.class, "/");
71     }
72
73     public static <T> T getNestedPropertyInMap(Object item, String path, Class<T> valueType) {
74         return getNestedPropertyInMap(item, path, valueType, "/");
75     }
76
77     /*
78     Use this method to extract item from Map that represent Json hierarchy (Map<String,Map>)
79      */
80     public static <T> T getNestedPropertyInMap(Object item, String path, Class<T> valueType, String delimeter) {
81         String[] pathes  = path.split(delimeter);
82         return valueType.cast(getNestedPropertyInMap(item,pathes,0));
83     }
84
85     private static Object getNestedPropertyInMap(Object item, String[] pathes, int index) {
86         if (index==pathes.length) {
87             return item;
88         }
89         return getNestedPropertyInMap(((Map<String,Object>)item).get(pathes[index]), pathes, ++index);
90     }
91
92     static Matcher hasOrLacksOfEntry(String pathRegex, Long expectedCounter) {
93         return expectedCounter.equals(0L) ? not(hasKey(matchesRegEx(pathRegex))) : hasEntry(matchesRegEx(pathRegex), is(expectedCounter));
94     }
95
96     private static RandomStringGenerator generator = new RandomStringGenerator.Builder()
97             .withinRange('0', 'z')
98             .filteredBy(LETTERS, DIGITS)
99             .build();
100
101     public static String generateRandomAlphaNumeric(int length) {
102         return generator.generate(length);
103     }
104
105     public static void assertAndRetryIfNeeded(long timeoutInSeconds, Runnable asserter) {
106         final Instant expiry = Instant.now().plusSeconds(timeoutInSeconds);
107         while (true) {
108             try {
109                 asserter.run();
110                 break; // we're cool, assertion passed
111             } catch (AssertionError fail) {
112                 Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
113                 if (Instant.now().isAfter(expiry)) {
114                     throw fail;
115                 } else {
116                     System.out.println("retrying after: " + fail);
117                 }
118             }
119         }
120     }
121
122     @DataProvider
123     public static Object[][] trueAndFalse() {
124         return new Object[][]{{true}, {false}};
125     }
126
127 }