[SDC-29] rebase continue work to align source
[sdc.git] / ui-ci-dev / src / main / java / org / openecomp / sdc / uici / tests / execute / base / SetupCDTest.java
1 package org.openecomp.sdc.uici.tests.execute.base;
2
3 import java.io.FileNotFoundException;
4 import java.util.ArrayList;
5 import java.util.HashSet;
6 import java.util.List;
7 import java.util.Map;
8 import java.util.Set;
9 import java.util.function.Function;
10 import java.util.stream.Collectors;
11 import java.util.stream.Stream;
12
13 import org.apache.commons.lang.NotImplementedException;
14 import org.apache.log4j.Logger;
15 import org.apache.tinkerpop.gremlin.structure.Edge;
16 import org.apache.tinkerpop.gremlin.structure.Vertex;
17 import org.junit.rules.TestName;
18 import org.openecomp.sdc.be.model.User;
19 import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
20 import org.openecomp.sdc.ci.tests.config.Config;
21 import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
22 import org.openecomp.sdc.ci.tests.run.StartTest;
23 import org.openecomp.sdc.ci.tests.utils.Utils;
24 import org.openecomp.sdc.common.datastructure.FunctionalInterfaces;
25 import org.openecomp.sdc.uici.tests.datatypes.CleanTypeEnum;
26 import org.openecomp.sdc.uici.tests.datatypes.UserCredentials;
27 import org.openecomp.sdc.uici.tests.utilities.FileHandling;
28 import org.openecomp.sdc.uici.tests.utilities.GeneralUIUtils;
29 import org.openqa.selenium.By;
30 import org.openqa.selenium.WebDriver;
31 import org.openqa.selenium.WebElement;
32 import org.testng.AssertJUnit;
33 import org.testng.ITestResult;
34 import org.testng.annotations.AfterMethod;
35 import org.testng.annotations.AfterSuite;
36 import org.testng.annotations.BeforeMethod;
37 import org.testng.annotations.BeforeSuite;
38 import org.testng.annotations.Optional;
39 import org.testng.annotations.Parameters;
40
41 import com.google.common.collect.Lists;
42 import com.thinkaurelius.titan.core.TitanGraph;
43
44 public abstract class SetupCDTest extends ComponentBaseTest {
45
46         private TitanSnapshot snapshot;
47         private static CleanTypeEnum cleanType;
48
49         public SetupCDTest() {
50                 super(new TestName(), SetupCDTest.class.getName());
51         }
52
53         public SetupCDTest(TestName name, String className) {
54                 super(name, className);
55         }
56
57         public static Logger logger = Logger.getLogger(SetupCDTest.class.getName());
58
59         /**************** CONSTANTS ****************/
60         private static final String CREDENTIALS_FILE = "src/main/resources/ci/conf/credentials.yaml";
61         public static final String SELENIUM_NODE_URL = "http://%s:%s/wd/hub";
62
63         /**************** PRIVATES ****************/
64         public static Config config;
65         private Map<?, ?> credentialsYamlFileMap;
66
67         private static String devUrl, cdUrl;
68
69         @BeforeSuite(alwaysRun = true)
70         public static void openTitan() throws FileNotFoundException {
71                 try {
72                         openTitanLogic();
73                 } catch (Exception e) {
74                         // TODO Auto-generated catch block
75                         e.printStackTrace();
76                 }
77         }
78         
79         @AfterSuite(alwaysRun = true)
80         public static void shutdownTitan() {
81                 shutdownTitanLogic();
82         }
83         
84         @BeforeSuite(alwaysRun = true)
85         @Parameters({ "clean-type" })
86         public void setEnvParameters(@Optional("PARTIAL") String cleanType) throws FileNotFoundException {
87                 this.cleanType = CleanTypeEnum.findByName(cleanType);
88                 System.out.println("setup before class");
89                 config = Utils.getConfig();
90                 loadCredentialsFile();
91                 setUrl();
92         }
93
94         @BeforeMethod(alwaysRun = true)
95         public void setBrowserBeforeTest() {
96                 setBrowserBeforeTest(getRole());
97         }
98
99         /**************** AFTER ****************/
100         @AfterMethod(alwaysRun = true)
101         public void quitAfterTest() {
102                 System.out.println("closing browser");
103                 GeneralUIUtils.getDriver().quit();
104         }
105
106         @BeforeMethod(alwaysRun = true)
107         public void beforeState(java.lang.reflect.Method method) throws Exception  {
108                 CleanTypeEnum cleanType = getCleanMode();
109                 switch (cleanType) {
110                 case FULL: {
111                         super.performeClean();
112                         break;
113                 }
114                 case PARTIAL: {
115                         takeTitanSnapshot();
116                         break;
117                 }
118                 case NONE: {
119                         // No Clean Up
120                         break;
121                 }
122                 default: {
123                         throw new NotImplementedException("Enum Value:" + cleanType.name() + " Is not handled");
124                 }
125                 }
126
127         }
128
129         @AfterMethod(alwaysRun = true)
130         public void afterState(ITestResult result) throws Exception {
131                 CleanTypeEnum cleanType = getCleanMode();
132                 switch (cleanType) {
133                 case FULL: {
134                         super.performeClean();
135                         break;
136                 }
137                 case PARTIAL: {
138                         resetToOriginalSnapshot();
139                         break;
140                 }
141                 case NONE: {
142                         // No Clean Up
143                         break;
144                 }
145                 default: {
146                         throw new NotImplementedException("Enum Value:" + cleanType.name() + " Is not handled");
147                 }
148                 }
149
150         }
151
152         private void takeTitanSnapshot() {
153                 List<Edge> edgeList = Lists.newArrayList(getTitanGraph().edges(null));
154                 List<Vertex> verList = Lists.newArrayList(getTitanGraph().vertices(null));
155                 setSnapshot(new TitanSnapshot(edgeList, verList));
156
157         }
158
159         private static class TitanSnapshot {
160                 List<Edge> edges;
161                 List<Vertex> vertices;
162
163                 public List<Edge> getEdges() {
164                         return edges;
165                 }
166
167                 public List<Vertex> getVertices() {
168                         return vertices;
169                 }
170
171                 private TitanSnapshot(List<Edge> edges, List<Vertex> vertices) {
172                         super();
173                         this.edges = edges;
174                         this.vertices = vertices;
175                 }
176         }
177
178         private void resetToOriginalSnapshot() {
179
180                 List<Edge> joinedEdges = new ArrayList<>();
181                 List<Vertex> joinedVertices = new ArrayList<>();
182                 TitanSnapshot original = getSnapshot();
183                 takeTitanSnapshot();
184                 TitanSnapshot current = getSnapshot();
185
186                 original.getEdges().stream().forEach(e -> addIfIdInList(e, current.getEdges(), joinedEdges, e2 -> e2.id()));
187                 original.getVertices().stream()
188                                 .forEach(e -> addIfIdInList(e, current.getVertices(), joinedVertices, e2 -> e2.id()));
189
190                 List<Edge> edgesToRemove = removeFromList(current.getEdges(), joinedEdges, e2 -> e2.id());
191                 List<Vertex> verticesToRemove = removeFromList(current.getVertices(), joinedVertices, e2 -> e2.id());
192
193                 List<Edge> edgesToAdd = removeFromList(original.getEdges(), joinedEdges, e2 -> e2.id());
194                 List<Vertex> verticesToAdd = removeFromList(original.getVertices(), joinedVertices, e2 -> e2.id());
195
196                 if (edgesToAdd.isEmpty() && verticesToAdd.isEmpty()) {
197                         edgesToRemove.stream().forEach(e -> e.remove());
198                         verticesToRemove.stream().forEach(v -> v.remove());
199                 }
200
201         }
202
203         private <Element, ID> List<Element> removeFromList(List<Element> listToRemoveFrom, List<Element> elementsToRemove,
204                         Function<Element, ID> idGetter) {
205                 Set<ID> idSet = new HashSet<>();
206                 // Fill The Set
207                 elementsToRemove.stream().map(e -> idGetter.apply(e)).forEach(e2 -> idSet.add(e2));
208                 return listToRemoveFrom.stream().filter(p -> !idSet.contains(idGetter.apply(p))).collect(Collectors.toList());
209
210         }
211
212         private <Element, ID> void addIfIdInList(Element e, List<Element> listToCheck, List<Element> listToAddTo,
213                         Function<Element, ID> idGetter) {
214                 Stream<Element> matchingElements = listToCheck.stream()
215                                 .filter(p -> idGetter.apply(e).equals(idGetter.apply(p)));
216                 listToAddTo.addAll(matchingElements.collect(Collectors.toList()));
217         }
218
219         /**************** MAIN ****************/
220         public static void main(String[] args) {
221                 System.out.println("---------------------");
222                 System.out.println("running test from CLI");
223                 System.out.println("---------------------");
224                 args = new String[] { "ui-ci.xml" };
225                 StartTest.main(args);
226         }
227
228         /***********************************************************************************/
229
230         protected void setBrowserBeforeTest(UserRoleEnum role) {
231                 System.out.println("setup before test");
232                 GeneralUIUtils.initDriver();
233                 setDevUrl(role);
234                 loginWithUser(role);
235         }
236
237         protected void setUrl() {
238                 cdUrl = config.getUrl();
239                 setDevUrl(getRole());
240         }
241
242         private Map<String, String> loadCredentialsFile() {
243                 final String credintialsFile = (System.getProperty("credentials.file") != null)
244                                 ? System.getProperty("credentials.file") : CREDENTIALS_FILE;
245                 System.out.println("credentials file is : " + credintialsFile);
246                 FunctionalInterfaces.swallowException(
247                                 () -> credentialsYamlFileMap = (Map<String, String>) FileHandling.parseYamlFile(credintialsFile));
248                 System.out.println(credentialsYamlFileMap.toString());
249                 return (Map<String, String>) credentialsYamlFileMap;
250         }
251
252         protected UserCredentials getUserCredentialsFromFile(String userRole) throws Exception {
253                 Map<String, String> credentialsMap = (Map<String, String>) credentialsYamlFileMap.get(userRole);
254                 String user = (String) credentialsMap.get("username");
255                 String password = (String) credentialsMap.get("password");
256                 String firstname = (String) credentialsMap.get("firstname");
257                 String lastname = (String) credentialsMap.get("lastname");
258
259                 return new UserCredentials(user, password, firstname, lastname);
260         }
261
262         public void navigateToUrl(String url) throws InterruptedException {
263                 WebDriver driver = GeneralUIUtils.getDriver();
264                 System.out.println("navigating to URL :" + url);
265                 driver.navigate().to(url);
266                 driver.manage().window().maximize();
267                 driver.manage().deleteAllCookies();
268         }
269
270         protected void loginToSystem(UserCredentials credentials) throws Exception {
271
272                 sendUserAndPasswordKeys(credentials);
273                 WebElement submitButton = GeneralUIUtils.getDriver().findElement(By.name("btnSubmit"));
274                 submitButton.click();
275                 WebElement buttonOK = GeneralUIUtils.getDriver().findElement(By.name("successOK"));
276                 AssertJUnit.assertTrue(buttonOK.isDisplayed());
277                 buttonOK.click();
278                 System.out.println("Entering to design studio");
279                 Thread.sleep(2000);
280                 WebElement enterToUserWorkspaceButton = GeneralUIUtils.getDriver()
281                                 .findElement(By.xpath("//button[@data-tests-id='Design Studio']"));
282                 enterToUserWorkspaceButton.click();
283         }
284
285         private void sendUserAndPasswordKeys(UserCredentials userId) {
286                 System.out.println("Login to system with user : " + userId.getUserId());
287                 WebElement userNameTextbox = GeneralUIUtils.getDriver().findElement(By.name("userid"));
288                 userNameTextbox.sendKeys(userId.getUserId());
289                 WebElement passwordTextbox = GeneralUIUtils.getDriver().findElement(By.name("password"));
290                 passwordTextbox.sendKeys(userId.getPassword());
291         }
292
293         public String getUrl() {
294                 String url;
295                 final CleanTypeEnum workMode = getCleanMode();
296                 switch (workMode) {
297                 case FULL: {
298                         url = devUrl;
299                         break;
300                 }
301                 case PARTIAL: {
302                         url = devUrl;
303                         break;
304                 }
305                 case NONE: {
306                         url = cdUrl;
307                         break;
308                 }
309                 default: {
310                         throw new NotImplementedException(workMode.name());
311                 }
312
313                 }
314                 return url;
315         }
316
317         public static void setDevUrl(UserRoleEnum role) {
318                 String url = SetupCDTest.devUrl;
319                 switch (role) {
320                 case ADMIN: {
321                         url = "http://localhost:8181/sdc1/proxy-admin1#/dashboard";
322                         break;
323                 }
324                 case DESIGNER: {
325                         url = "http://localhost:8181/sdc1/proxy-designer1#/dashboard";
326                         // url = "http://localhost:9000/#/dashboard";
327                         break;
328                 }
329                 case GOVERNOR: {
330                         url = "http://localhost:8181/sdc1/proxy-governor1#/dashboard";
331                         break;
332                 }
333                 case OPS: {
334                         url = "http://localhost:8181/sdc1/proxy-ops1#/dashboard";
335                         break;
336                 }
337                 case TESTER: {
338                         url = "http://localhost:8181/sdc1/proxy-tester1#/dashboard";
339                         break;
340                 }
341                 default: {
342                         break;
343                 }
344                 }
345                 SetupCDTest.devUrl = url;
346         }
347
348         public static Config getConfig() {
349                 return config;
350         }
351
352         private User user;
353
354         public void loginWithUser(UserRoleEnum role) {
355
356                 setUser(role);
357                 String url = getUrl();
358                 System.out.println("URL is : " + url);
359                 try {
360                         navigateToUrl(url);
361                         if (url.contains("https://www.e-access.att.com")) {
362                                 System.out.println("going to update designer user to mechIDs form...");
363                                 UserCredentials credentials = getUserCredentialsFromFile(role.name().toLowerCase());
364                                 loginToSystem(credentials);
365                         }
366                 } catch (Exception e) {
367                         throw new RuntimeException(e);
368                 }
369         }
370
371         private void setUser(UserRoleEnum role) {
372                 user = new User();
373                 user.setUserId(role.getUserId());
374                 user.setFirstName(role.getFirstName());
375                 user.setRole(role.name());
376         }
377
378         /**
379          * Current User Role
380          * 
381          * @return
382          */
383         public UserRoleEnum getRole() {
384                 return UserRoleEnum.DESIGNER;
385         }
386
387         /**
388          * To change clean type update configuration.<br>
389          * Do not override this method.
390          * 
391          * @return
392          */
393         protected final CleanTypeEnum getCleanMode() {
394                 return cleanType;
395         }
396
397         public User getUser() {
398                 return user;
399         }
400
401         protected void quitAndReLogin(UserRoleEnum role) {
402                 quitAfterTest();
403                 setBrowserBeforeTest(role);
404                 GeneralUIUtils.waitForLoader(30);
405         }
406
407         public TitanSnapshot getSnapshot() {
408                 return snapshot;
409         }
410
411         public void setSnapshot(TitanSnapshot snapshot) {
412                 this.snapshot = snapshot;
413         }
414
415         public static TitanGraph getTitanGraph() {
416                 return titanGraph;
417         }
418
419 }