Move some tests from group 3 to group 5
[vid.git] / vid-automation / src / main / java / vid / automation / test / test / VidBaseTestCase.java
1 package vid.automation.test.test;
2
3 import static java.util.Collections.emptySet;
4 import static java.util.Collections.singletonList;
5 import static java.util.stream.Collectors.groupingBy;
6 import static java.util.stream.Collectors.mapping;
7 import static java.util.stream.Collectors.toSet;
8 import static org.hamcrest.CoreMatchers.not;
9 import static org.hamcrest.Matchers.contains;
10 import static org.hamcrest.Matchers.containsInAnyOrder;
11 import static org.hamcrest.collection.IsEmptyCollection.empty;
12 import static org.hamcrest.core.Is.is;
13 import static org.junit.Assert.assertThat;
14 import static org.onap.simulator.presetGenerator.presets.mso.PresetMSOOrchestrationRequestGet.COMPLETE;
15 import static org.testng.Assert.assertEquals;
16 import static org.testng.AssertJUnit.fail;
17 import static vid.automation.test.utils.TestHelper.GET_SERVICE_MODELS_BY_DISTRIBUTION_STATUS;
18 import static vid.automation.test.utils.TestHelper.GET_TENANTS;
19
20 import com.fasterxml.jackson.databind.ObjectMapper;
21 import com.google.common.collect.ImmutableList;
22 import java.io.File;
23 import java.lang.reflect.Method;
24 import java.net.URI;
25 import java.net.URISyntaxException;
26 import java.sql.Connection;
27 import java.sql.DriverManager;
28 import java.sql.ResultSet;
29 import java.sql.SQLException;
30 import java.sql.Statement;
31 import java.util.ArrayList;
32 import java.util.Arrays;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.Set;
36 import java.util.concurrent.TimeUnit;
37 import org.apache.commons.lang3.StringUtils;
38 import org.glassfish.jersey.uri.internal.JerseyUriBuilder;
39 import org.junit.Assert;
40 import org.onap.sdc.ci.tests.datatypes.Configuration;
41 import org.onap.sdc.ci.tests.datatypes.UserCredentials;
42 import org.onap.sdc.ci.tests.execute.setup.SetupCDTest;
43 import org.onap.sdc.ci.tests.utilities.FileHandling;
44 import org.onap.sdc.ci.tests.utilities.GeneralUIUtils;
45 import org.onap.simulator.presetGenerator.presets.BasePresets.BaseMSOPreset;
46 import org.onap.simulator.presetGenerator.presets.BasePresets.BasePreset;
47 import org.onap.simulator.presetGenerator.presets.aai.PresetAAICloudRegionAndSourceFromConfigurationPut;
48 import org.onap.simulator.presetGenerator.presets.aai.PresetAAIGetNetworkZones;
49 import org.onap.simulator.presetGenerator.presets.aai.PresetAAIGetPortMirroringSourcePorts;
50 import org.onap.simulator.presetGenerator.presets.aai.PresetAAIGetServicesGet;
51 import org.onap.simulator.presetGenerator.presets.aai.PresetAAIGetSubDetailsGet;
52 import org.onap.simulator.presetGenerator.presets.aai.PresetAAIGetSubDetailsWithoutInstancesGet;
53 import org.onap.simulator.presetGenerator.presets.aai.PresetAAIGetSubscribersGet;
54 import org.onap.simulator.presetGenerator.presets.aai.PresetAAIGetTenants;
55 import org.onap.simulator.presetGenerator.presets.aai.PresetAAIPostNamedQueryForViewEdit;
56 import org.onap.simulator.presetGenerator.presets.aai.PresetAAIServiceDesignAndCreationPut;
57 import org.onap.simulator.presetGenerator.presets.ecompportal_att.EcompPortalPresetsUtils;
58 import org.onap.simulator.presetGenerator.presets.ecompportal_att.PresetGetSessionSlotCheckIntervalGet;
59 import org.onap.simulator.presetGenerator.presets.mso.PresetMSOCreateServiceInstanceGen2;
60 import org.onap.simulator.presetGenerator.presets.mso.PresetMSOCreateServiceInstancePost;
61 import org.onap.simulator.presetGenerator.presets.mso.PresetMSOOrchestrationRequestGet;
62 import org.onap.simulator.presetGenerator.presets.sdc.PresetSDCGetServiceMetadataGet;
63 import org.onap.simulator.presetGenerator.presets.sdc.PresetSDCGetServiceToscaModelGet;
64 import org.openqa.selenium.By;
65 import org.openqa.selenium.JavascriptExecutor;
66 import org.openqa.selenium.WebElement;
67 import org.springframework.http.client.ClientHttpRequestInterceptor;
68 import org.springframework.web.client.RestTemplate;
69 import org.testng.ITestContext;
70 import org.testng.annotations.BeforeMethod;
71 import org.testng.annotations.BeforeSuite;
72 import org.testng.annotations.Listeners;
73 import org.testng.annotations.Test;
74 import vid.automation.reportportal.ReportPortalListenerDelegator;
75 import vid.automation.test.Constants;
76 import vid.automation.test.Constants.ViewEdit;
77 import vid.automation.test.infra.Click;
78 import vid.automation.test.infra.Exists;
79 import vid.automation.test.infra.Features;
80 import vid.automation.test.infra.Get;
81 import vid.automation.test.infra.ModelInfo;
82 import vid.automation.test.infra.SelectOption;
83 import vid.automation.test.infra.Wait;
84 import vid.automation.test.model.Credentials;
85 import vid.automation.test.model.User;
86 import vid.automation.test.sections.LoginExternalPage;
87 import vid.automation.test.sections.SearchExistingPage;
88 import vid.automation.test.sections.SideMenu;
89 import vid.automation.test.sections.VidBasePage;
90 import vid.automation.test.sections.ViewEditPage;
91 import vid.automation.test.sections.deploy.DeployModernUIMacroDialog;
92 import vid.automation.test.services.CategoryParamsService;
93 import vid.automation.test.services.SimulatorApi;
94 import vid.automation.test.services.UsersService;
95 import vid.automation.test.utils.CookieAndJsonHttpHeadersInterceptor;
96 import vid.automation.test.utils.DB_CONFIG;
97 import vid.automation.test.utils.InsecureHttpsClient;
98 import vid.automation.test.utils.TestConfigurationHelper;
99 import vid.automation.test.utils.TestHelper;
100
101 @Listeners(ReportPortalListenerDelegator.class)
102 public class VidBaseTestCase extends SetupCDTest{
103
104     protected static final UsersService usersService = new UsersService();
105     protected static final CategoryParamsService categoryParamsService = new CategoryParamsService();
106     protected final RestTemplate restTemplate = InsecureHttpsClient.newRestTemplate();
107     protected final URI uri;
108     protected final URI envUrI;
109
110     public VidBaseTestCase() {
111         try {
112             this.envUrI = new URI(System.getProperty("ENV_URL"));
113         } catch (URISyntaxException e) {
114             throw new RuntimeException(e);
115         }
116         this.uri = new JerseyUriBuilder().host(envUrI.getHost()).port(envUrI.getPort()).scheme(envUrI.getScheme()).path("vid").build();
117     }
118
119     public void login() {
120         UserCredentials userCredentials = getUserCredentials();
121         final List<ClientHttpRequestInterceptor> interceptors = singletonList(new CookieAndJsonHttpHeadersInterceptor(uri, userCredentials));
122         restTemplate.setInterceptors(interceptors);
123     }
124
125     public void invalidateSdcModelsCache() {
126         if (Features.FLAG_SERVICE_MODEL_CACHE.isActive()) {
127             restTemplate.postForObject(uri + "/rest/models/reset", "", Object.class);
128         }
129     }
130
131     protected void resetGetServicesCache() {
132         login();
133         TestHelper.resetAaiCache(GET_SERVICE_MODELS_BY_DISTRIBUTION_STATUS, restTemplate, uri);
134     }
135
136     protected void resetGetTenantsCache() {
137         login();
138         TestHelper.resetAaiCache(GET_TENANTS, restTemplate, uri);
139     }
140
141     @Override
142     protected UserCredentials getUserCredentials() {
143         ObjectMapper mapper = new ObjectMapper().enableDefaultTyping();
144         try {
145             File configFile = FileHandling.getConfigFile("credentials");
146             if(!configFile.exists()) {
147                 String basePath = System.getProperty("BASE_PATH");
148                 configFile = new File( basePath + File.separator + "conf" + File.separator + "credentials");
149             }
150             Credentials credentials = mapper.readValue(configFile, Credentials.class);
151             User user = usersService.getUser(credentials.userId);
152             return new UserCredentials(user.credentials.userId, user.credentials.password, credentials.userId, "", "");
153         } catch (Exception e) {
154             e.printStackTrace();
155             return null;
156         }
157     }
158
159     @Override
160     protected Configuration getEnvConfiguration() {
161
162         return TestConfigurationHelper.getEnvConfiguration();
163     }
164
165     @BeforeMethod(alwaysRun = true)
166     public void setBrowserBeforeTestIfDataProvider(Method method, ITestContext context, Object[] params) {
167         // Hack to overcome limitations of SetupCDTest.setBrowserBeforeTest(java.lang.reflect.Method, org.testng.ITestContext)
168         // that skips over dataProvided methods
169         boolean emptyDataProvider = method.getAnnotation(Test.class).dataProvider().isEmpty();
170         if (!emptyDataProvider) {
171             final String testName = method.getName();
172             final String listOfParams = Arrays.deepToString(params)
173                     .replace('[', '(')
174                     .replace(']', ')')
175                     .replaceAll("[\\\\/:*?\"<>|]", "_");
176
177             setLog(testName+listOfParams);
178         }
179     }
180
181     @BeforeSuite(alwaysRun = true)
182     public void screenShotsForReportPortal(){
183         try {
184             ReportPortalListenerDelegator.setScreenShotsWebDriver(getDriver());
185             System.out.println("Called to ReportPortalListener to set ScreenShotsProvider");
186         } catch (Exception e) {
187             e.printStackTrace();
188         }
189     }
190
191     @BeforeSuite(alwaysRun = true)
192     public void setSmallDefaultTimeout() throws Exception {
193         getDriver().manage().timeouts().implicitlyWait(500, TimeUnit.MILLISECONDS);
194     }
195
196     @Override
197     protected void loginToLocalSimulator(UserCredentials userCredentials) {
198         LoginExternalPage.performLoginExternal(userCredentials);
199     }
200
201     protected void registerExpectationForLegacyServiceDeployment(ModelInfo modelInfo, String subscriberId) {
202         List<BasePreset> presets = new ArrayList<>(Arrays.asList(
203                 new PresetAAIPostNamedQueryForViewEdit(BaseMSOPreset.DEFAULT_INSTANCE_ID, true, false),
204                 new PresetAAIGetPortMirroringSourcePorts("9533-config-LB1113", "myRandomInterfaceId", ViewEdit.COMMON_PORT_MIRRORING_PORT_NAME, true)
205         ));
206
207         presets.add(new PresetMSOCreateServiceInstancePost());
208         presets.add(new PresetMSOOrchestrationRequestGet(COMPLETE, false));
209
210         presets.addAll(getPresetForServiceBrowseAndDesign(ImmutableList.of(modelInfo), subscriberId));
211
212         SimulatorApi.registerExpectationFromPresets(presets, SimulatorApi.RegistrationStrategy.CLEAR_THEN_SET);
213     }
214
215     protected void registerExpectationForServiceDeployment(List<ModelInfo> modelInfoList, String subscriberId, PresetMSOCreateServiceInstanceGen2 createServiceInstancePreset) {
216         List<BasePreset> presets = new ArrayList<>(Arrays.asList(
217                 new PresetAAIPostNamedQueryForViewEdit(BaseMSOPreset.DEFAULT_INSTANCE_ID, true, false),
218                 new PresetAAIGetPortMirroringSourcePorts("9533-config-LB1113", "myRandomInterfaceId", ViewEdit.COMMON_PORT_MIRRORING_PORT_NAME, true)
219         ));
220
221         if (createServiceInstancePreset != null) {
222             presets.add(createServiceInstancePreset);
223         }
224         presets.add(new PresetMSOOrchestrationRequestGet("IN_PROGRESS"));
225
226         presets.addAll(getPresetForServiceBrowseAndDesign(modelInfoList, subscriberId));
227
228         SimulatorApi.registerExpectationFromPresets(presets, SimulatorApi.RegistrationStrategy.CLEAR_THEN_SET);
229     }
230
231     protected void registerExpectationForServiceBrowseAndDesign(List<ModelInfo> modelInfoList, String subscriberId) {
232         SimulatorApi.registerExpectationFromPresets(getPresetForServiceBrowseAndDesign(modelInfoList, subscriberId), SimulatorApi.RegistrationStrategy.CLEAR_THEN_SET);
233     }
234
235     protected List<BasePreset> getPresetForServiceBrowseAndDesign(List<ModelInfo> modelInfoList, String subscriberId) {
236
237         List<BasePreset> presets = new ArrayList<>(Arrays.asList(
238                     new PresetGetSessionSlotCheckIntervalGet(),
239                     new PresetAAIGetSubDetailsGet(subscriberId),
240                     new PresetAAIGetSubDetailsWithoutInstancesGet(subscriberId),
241                     new PresetAAIGetSubscribersGet(),
242                     new PresetAAIGetServicesGet(),
243                     new PresetAAICloudRegionAndSourceFromConfigurationPut("9533-config-LB1113", "myRandomCloudRegionId"),
244                     new PresetAAIGetNetworkZones(),
245                     new PresetAAIGetTenants(),
246                     new PresetAAIServiceDesignAndCreationPut()
247                     ));
248
249         presets.addAll(EcompPortalPresetsUtils.getEcompPortalPresets());
250
251         modelInfoList.forEach(modelInfo -> {
252             presets.add(new PresetSDCGetServiceMetadataGet(modelInfo.modelVersionId, modelInfo.modelInvariantId, modelInfo.zipFileName));
253             presets.add(new PresetSDCGetServiceToscaModelGet(modelInfo.modelVersionId, modelInfo.zipFileName));
254         });
255
256         return presets;
257     }
258
259     protected void relogin(Credentials credentials)  {
260         // `getWindowTest().getPreviousUser()` is SetupCDTest's state of previous user used
261         if (!credentials.userId.equals(getWindowTest().getPreviousUser())) {
262             UserCredentials userCredentials = new UserCredentials(credentials.userId,
263                     credentials.password, "", "", "");
264             reloginWithNewRole(userCredentials);
265         } else {
266             System.out.println(String.format("VidBaseTestCase.relogin() " +
267                     "-> '%s' is already logged in, so skipping", credentials.userId));
268         }
269     }
270
271     /**
272      * Validates that permitted options are enabled and others are disabled.
273      *
274      * @param permittedItems           the list of permitted items.
275      * @param dropdownOptionsClassName the class name of the specific dropdown options.
276      * @return true, if all dropdown options disabled state is according to the permissions.
277      */
278     protected void assertDropdownPermittedItemsByValue(ArrayList<String> permittedItems, String dropdownOptionsClassName) {
279         assertDropdownPermittedItemsByValue(permittedItems, dropdownOptionsClassName, "value");
280     }
281
282     protected void assertDropdownPermittedItemsByLabel(ArrayList<String> permittedItems, String dropdownOptionsClassName) {
283         assertDropdownPermittedItemsByValue(permittedItems, dropdownOptionsClassName, "label");
284     }
285
286     /**
287      * Validates that permitted options are enabled and others are disabled.
288      *
289      * @param permittedItems           the list of permitted items.
290      * @param dropdownOptionsClassName the class name of the specific dropdown options.
291      * @param attribute
292      * @return true, if all dropdown options disabled state is according to the permissions.
293      */
294     private void assertDropdownPermittedItemsByValue(ArrayList<String> permittedItems, String dropdownOptionsClassName, String attribute) {
295         GeneralUIUtils.ultimateWait();
296         List<WebElement> optionsList =
297                 GeneralUIUtils.getWebElementsListBy(By.className(dropdownOptionsClassName), 30);
298
299         final Map<Boolean, Set<String>> optionsMap = optionsList.stream()
300                 .collect(groupingBy(WebElement::isEnabled, mapping(option -> option.getAttribute(attribute), toSet())));
301
302         assertGroupedPermissionsAreCorrect(permittedItems, optionsMap);
303     }
304
305     private void assertGroupedPermissionsAreCorrect(ArrayList<String> permittedItems, Map<Boolean, Set<String>> optionsMap) {
306         if (permittedItems.isEmpty()) {
307             assertThat(Constants.DROPDOWN_PERMITTED_ASSERT_FAIL_MESSAGE, optionsMap.getOrDefault(Boolean.TRUE, emptySet()), is(empty()));
308         }else {
309             assertThat(Constants.DROPDOWN_PERMITTED_ASSERT_FAIL_MESSAGE, optionsMap.getOrDefault(Boolean.TRUE, emptySet()), containsInAnyOrder(permittedItems.toArray()));
310             assertThat(Constants.DROPDOWN_PERMITTED_ASSERT_FAIL_MESSAGE, optionsMap.getOrDefault(Boolean.FALSE, emptySet()), not(contains(permittedItems.toArray())));
311         }
312     }
313
314     protected void assertAllIsPermitted(String dropdownOptionsClassName) {
315         GeneralUIUtils.ultimateWait();
316         List<WebElement> optionsList =
317                 GeneralUIUtils.getWebElementsListBy(By.className(dropdownOptionsClassName), 30);
318         for (WebElement option :
319                 optionsList) {
320             //String optionValue = option.getAttribute("value");
321             if (!option.isEnabled()) {
322                 fail(Constants.DROPDOWN_PERMITTED_ASSERT_FAIL_MESSAGE);
323             }
324         }
325     }
326
327     protected void assertDropdownPermittedItemsByName(ArrayList<String> permittedItems, String dropdownOptionsClassName) {
328         GeneralUIUtils.ultimateWait();
329         List<WebElement> optionsList =
330                 GeneralUIUtils.getWebElementsListBy(By.className(dropdownOptionsClassName), 30);
331
332         final Map<Boolean, Set<String>> optionsMap = optionsList.stream()
333                 .collect(groupingBy(WebElement::isEnabled, mapping(WebElement::getText, toSet())));
334
335         assertGroupedPermissionsAreCorrect(permittedItems, optionsMap);
336     }
337
338     protected void assertViewEditButtonState(String expectedButtonText, String UUID) {
339         WebElement viewEditWebElement = GeneralUIUtils.getWebElementByTestID(Constants.VIEW_EDIT_TEST_ID_PREFIX + UUID, 100);
340         Assert.assertEquals(expectedButtonText, viewEditWebElement.getText());
341         GeneralUIUtils.ultimateWait();
342     }
343
344
345     protected void addNetwork(Map<String, String> metadata,String instanceName, String name, String lcpRegion, String cloudOwner, String productFamily,String platform, String lineOfBusiness, String tenant, String suppressRollback,
346                                String legacyRegion, ArrayList<String> permittedTenants) {
347         ViewEditPage viewEditPage = new ViewEditPage();
348
349         viewEditPage.selectNetworkToAdd(name);
350         assertModelInfo(metadata, false);
351         viewEditPage.setInstanceName(instanceName);
352         viewEditPage.selectLcpRegion(lcpRegion, cloudOwner);
353         viewEditPage.selectProductFamily(productFamily);
354         viewEditPage.selectLineOfBusiness(lineOfBusiness);
355         assertDropdownPermittedItemsByValue(permittedTenants, Constants.ViewEdit.TENANT_OPTION_CLASS);
356         viewEditPage.selectTenant(tenant);
357
358         viewEditPage.selectSuppressRollback(suppressRollback);
359         if(platform != null){
360             viewEditPage.selectPlatform(platform);
361         }
362         viewEditPage.clickConfirmButton();
363         viewEditPage.assertMsoRequestModal(Constants.ViewEdit.MSO_SUCCESSFULLY_TEXT);
364         viewEditPage.clickCloseButton();
365         GeneralUIUtils.ultimateWait();
366     }
367
368     void assertSuccessfulVNFCreation() {
369         boolean byText = GeneralUIUtils.findAndWaitByText(Constants.ViewEdit.VNF_CREATED_SUCCESSFULLY_TEXT, 100);
370         Assert.assertTrue(Constants.ViewEdit.VNF_CREATION_FAILED_MESSAGE, byText);
371     }
372
373     void assertSuccessfulPNFAssociation() {
374         //TODO
375         boolean byText = GeneralUIUtils.findAndWaitByText(Constants.PnfAssociation.PNF_ASSOCIATED_SUCCESSFULLY_TEXT, 100);
376         Assert.assertTrue(Constants.PnfAssociation.PNF_ASSOCIATED_FAILED_MESSAGE, byText);
377     }
378     void assertSuccessfulVolumeGroupCreation() {
379         boolean byText = GeneralUIUtils.findAndWaitByText(Constants.ViewEdit.VOLUME_GROUP_CREATED_SUCCESSFULLY_TEXT, 100);
380         Assert.assertTrue(Constants.ViewEdit.VOLUME_GROUP_CREATION_FAILED_MESSAGE, byText);
381     }
382
383     void assertSuccessfulVFModuleCreation() {
384         boolean byText = GeneralUIUtils.findAndWaitByText(Constants.ViewEdit.VF_MODULE_CREATED_SUCCESSFULLY_TEXT, 100);
385         Assert.assertTrue(Constants.ViewEdit.VF_MODULE_CREATION_FAILED_MESSAGE, byText);
386     }
387
388     //@Step("${method}: ${instanceUUID}")
389     void goToExistingInstanceById(String instanceUUID) {
390         SearchExistingPage searchExistingPage = searchExistingInstanceById(instanceUUID);
391         assertViewEditButtonState( Constants.VIEW_EDIT_BUTTON_TEXT, instanceUUID);
392
393         searchExistingPage.clickEditViewByInstanceId(instanceUUID);
394         GeneralUIUtils.ultimateWait();
395     }
396
397     void searchForExistingInstanceByIdReadonlyMode(String instanceUUID) {
398         searchExistingInstanceById(instanceUUID);
399         assertViewEditButtonState( Constants.VIEW_BUTTON_TEXT, instanceUUID);
400     }
401
402     SearchExistingPage searchExistingInstanceById(String instanceUUID){
403         SearchExistingPage searchExistingPage = new SearchExistingPage();
404         SideMenu.navigateToSearchExistingPage();
405         searchExistingPage.searchForInstanceByUuid(instanceUUID);
406         return searchExistingPage;
407     }
408
409
410     void goToExistingInstanceByIdNoWait(String instanceUUID) {
411         SearchExistingPage searchExistingPage = searchExistingInstanceById(instanceUUID);
412         searchExistingPage.clickEditViewByInstanceId(instanceUUID);
413     }
414
415     void resumeVFModule(String vfModuleName, String lcpRegion, String cloudOwner, String tenant, String legacyRegion, ArrayList<String> permittedTenants){
416         ViewEditPage viewEditPage = new ViewEditPage();
417         viewEditPage.clickResumeButton(vfModuleName);
418         viewEditPage.selectLcpRegion(lcpRegion, cloudOwner);
419         assertDropdownPermittedItemsByValue(permittedTenants, Constants.ViewEdit.TENANT_OPTION_CLASS);
420         viewEditPage.selectTenant(tenant);
421         viewEditPage.setLegacyRegion(legacyRegion);
422         viewEditPage.clickConfirmButtonInResumeDelete();
423         assertSuccessfulVFModuleCreation();
424         viewEditPage.clickCommitCloseButton();
425         GeneralUIUtils.ultimateWait();
426     }
427
428     void goToExistingInstanceByName(String instanceName) {
429         SearchExistingPage searchExistingPage = new SearchExistingPage();
430         SideMenu.navigateToSearchExistingPage();
431         searchExistingPage.searchForInstanceByName(instanceName);
432         WebElement instanceIdRow = GeneralUIUtils.getWebElementByTestID(Constants.INSTANCE_ID_FOR_NAME_TEST_ID_PREFIX + instanceName, 30);
433         String instanceId = instanceIdRow.getText();
434         assertViewEditButtonState( Constants.VIEW_EDIT_BUTTON_TEXT, instanceId);
435         searchExistingPage.clickEditViewByInstanceId(instanceId);
436         GeneralUIUtils.ultimateWait();
437     }
438
439     String confirmFilterById(String instanceName, String instanceUUID) {
440         WebElement filter = GeneralUIUtils.getWebElementByTestID(Constants.FILTER_SUBSCRIBER_DETAILS_ID, 30);
441         filter.sendKeys(instanceUUID);
442
443         WebElement firstElement = GeneralUIUtils.getWebElementByTestID(Constants.INSTANCE_ID_FOR_NAME_TEST_ID_PREFIX + instanceName, 30);
444         String filteredId = firstElement.getText();
445         Assert.assertTrue(filteredId.equals(instanceUUID));
446         return filteredId;
447     }
448
449     void goToExistingInstanceBySubscriber(String subscriberName,String instanceName,String instanceUUID) {
450         SearchExistingPage searchExistingPage = new SearchExistingPage();
451         SideMenu.navigateToSearchExistingPage();
452         SelectOption.byIdAndVisibleText(Constants.EditExistingInstance.SELECT_SUBSCRIBER, subscriberName);
453         searchExistingPage.clickSubmitButton();
454         GeneralUIUtils.ultimateWait();
455         confirmFilterById(instanceName, instanceUUID);
456         searchExistingPage.clickEditViewByInstanceId(instanceUUID);
457         GeneralUIUtils.ultimateWait();
458     }
459
460     void selectMsoTestApiOption(String msoTestApiOption) {
461         final String id = "selectTestApi";
462         final String sectionId = "selectTestApiSection";
463
464         SideMenu.navigateToWelcomePage();
465
466         if (Exists.byId(sectionId)) {
467             final JavascriptExecutor javascriptExecutor = (JavascriptExecutor) GeneralUIUtils.getDriver();
468             javascriptExecutor.executeScript(
469                     "document.getElementById('" + sectionId + "').style.visibility = 'inherit';"
470             );
471
472             if (null == SelectOption.byIdAndVisibleText(id, msoTestApiOption)) {
473                 Assert.fail("selectMsoTestApiOptionIfPossible couldnt apply " + msoTestApiOption);
474             }
475         }
476     }
477
478     protected void assertModelInfo(Map<String, String> expectedMetadata, boolean withPrefix) {
479         Wait.angularHttpRequestsLoaded();
480         GeneralUIUtils.ultimateWait();
481         for (Map.Entry<String, String> item: expectedMetadata.entrySet()) {
482             assertMetadataItem(item.getKey(), item.getValue(), withPrefix);
483         }
484     }
485
486     protected <T> void assertModelDataCorrect(Map<String, String> modelKeyToDataTestsIdMap, String prefix, T model) {
487         modelKeyToDataTestsIdMap.forEach((fieldName, dataTestsId) -> {
488             WebElement webElement = Get.byTestId(prefix + dataTestsId);
489             assertEquals(webElement.getText(), getServiceFieldByName(fieldName, model));
490         });
491     }
492
493     protected <T> void setNewInstance_leftPane_assertModelLabelsVisibilityCorrect(Map<String, String> modelKeyToDataTestsIdMap, String prefix, T model) {
494         modelKeyToDataTestsIdMap.forEach((fieldName, dataTestsId) -> {
495             WebElement webElement = Get.byTestId(prefix + dataTestsId);
496             String field = getServiceFieldByName(fieldName, model);
497             assertEquals(webElement.isDisplayed(), !(StringUtils.isEmpty(field)) , dataTestsId + " label shouldn't appear when " + fieldName + " is empty");
498         });
499     }
500
501     private <T> String getServiceFieldByName(String name, T model) {
502         try {
503             return model.getClass().getField(name).get(model).toString();
504         } catch (IllegalAccessException | NoSuchFieldException e) {
505             throw new RuntimeException(e);
506         }
507     }
508
509     private void assertMetadataItem(String keyTestId, String value, boolean withPrefix) {
510         String elementTestId = (withPrefix ? Constants.ServiceModelInfo.INFO_TEST_ID_PREFIX:"") + keyTestId;
511         String infoItemText = GeneralUIUtils.getWebElementByTestID(elementTestId, 60).getText();
512         assertThat(String.format(Constants.ServiceModelInfo.METADETA_ERROR_MESSAGE, elementTestId),  infoItemText, is(value));
513     }
514
515     protected void loadServicePopup(ModelInfo modelInfo) {
516         loadServicePopup(modelInfo.modelVersionId);
517     }
518
519
520     protected void loadServicePopup(String modelVersionId) {
521         SideMenu.navigateToBrowseASDCPage();
522         GeneralUIUtils.ultimateWait();
523         loadServicePopupOnBrowseASDCPage(modelVersionId);
524     }
525
526     protected void loadServicePopupOnBrowseASDCPage(String modelVersionId) {
527         loadServicePopupOnBrowseASDCPage(modelVersionId, "Model version");
528     }
529
530     protected void loadTemplatesPopupOnBrowseASDCPage (String modelVersionId) {
531         loadServicePopupOnBrowseASDCPage(modelVersionId, "Templates");
532     }
533
534     protected void loadServicePopupOnBrowseASDCPage(String modelVersionId, String expectedText) {
535         DeployModernUIMacroDialog deployMacroDialog = new DeployModernUIMacroDialog();
536         VidBasePage.goOutFromIframe();
537         deployMacroDialog.clickDeployServiceButtonByServiceUUID(modelVersionId);
538         deployMacroDialog.goToIframe();
539         GeneralUIUtils.ultimateWait();
540         Wait.byText(expectedText);
541     }
542
543     public void assertSetButtonDisabled(String buttonTestId) {
544         WebElement webElement = Get.byTestId(buttonTestId);
545         org.testng.Assert.assertFalse(webElement.isEnabled(), "Set button should be disabled if not all mandatory fields are field.");
546     }
547
548     public void assertSetButtonEnabled(String buttonTestId) {
549
550         WebElement webElement = Get.byTestId(buttonTestId);
551         org.testng.Assert.assertTrue(webElement.isEnabled(), "Set button should be enabled if all mandatory fields are field.");
552     }
553
554     public void assertElementDisabled(String id) {
555         WebElement webElement = Get.byId(id);
556         assert webElement != null;
557         org.testng.Assert.assertFalse(webElement.isEnabled(), "field should be disabled if the field it depends on was not selected yet.");
558     }
559
560     public boolean isElementByIdRequired(String id)  {
561         return Get.byId(id).getAttribute("class").contains("required");
562     }
563
564     protected int getUserIdNumberFromDB(User user) {
565         try (Connection connection = DriverManager.getConnection(DB_CONFIG.url, DB_CONFIG.username, DB_CONFIG.password)) {
566             Statement stmt = connection.createStatement();
567             ResultSet userIdResultSet;
568             userIdResultSet = stmt.executeQuery("SELECT USER_ID FROM fn_user where LOGIN_ID = '" + user.credentials.userId + "'");
569             Assert.assertTrue("Exactly one user should be found", userIdResultSet.next());
570             int userId = userIdResultSet.getInt("USER_ID");
571             Assert.assertFalse("There are more than one user for id " + userId, userIdResultSet.next());
572             return userId;
573         } catch (SQLException e) {
574             throw new IllegalStateException("Cannot connect the database!", e);
575         }
576     }
577
578     protected List<Integer> getRoleIDsAssignedToUser(int userId) {
579         try (Connection connection = DriverManager.getConnection(DB_CONFIG.url, DB_CONFIG.username, DB_CONFIG.password)) {
580             Statement stmt = connection.createStatement();
581             ResultSet userRolesResultSet;
582             userRolesResultSet = stmt.executeQuery("SELECT ROLE_ID FROM fn_user_role where USER_ID = '" + userId + "' order by ROLE_ID");
583
584             List<Integer> userRoles = new ArrayList<Integer>();
585             while (userRolesResultSet.next()) {
586                 userRoles.add(userRolesResultSet.getInt("ROLE_ID"));
587             }
588             return userRoles;
589         } catch (SQLException e) {
590             throw new IllegalStateException("Cannot connect the database!", e);
591         }
592     }
593
594     protected void navigateToViewEditPageOfuspVoiceVidTest444(String aaiModelVersionId) {
595         navigateToViewEditPage("3f93c7cb-2fd0-4557-9514-e189b7b04f9d", aaiModelVersionId);
596     }
597
598     protected void navigateToViewEditPageOf_test_sssdad() {
599         navigateToViewEditPage("c187e9fe-40c3-4862-b73e-84ff056205f6", "ee6d61be-4841-4f98-8f23-5de9da846ca7");
600     }
601
602     protected void navigateToViewEditPage(final String serviceInstanceId, String aaiModelVersionId) {
603         VidBasePage vidBasePage = new VidBasePage();
604         SideMenu.navigateToWelcomePage();
605         vidBasePage.navigateTo("serviceModels.htm#/instantiate?" +
606                 "subscriberId=e433710f-9217-458d-a79d-1c7aff376d89&" +
607                 "subscriberName=SILVIA%20ROBBINS&" +
608                 "serviceType=TYLER%20SILVIA&" +
609                 "serviceInstanceId=" + serviceInstanceId + "&" +
610                 "aaiModelVersionId=" + aaiModelVersionId + "&" +
611                 "isPermitted=true");
612         GeneralUIUtils.ultimateWait();
613     }
614
615
616     public void hoverAndClickMenuByName(String nodeName, String nodeToEdit, String contextMenuItem ) {
617         String buttonOfEdit = Constants.DrawingBoard.NODE_PREFIX + nodeToEdit + Constants.DrawingBoard.CONTEXT_MENU_BUTTON;
618
619         WebElement rightTreeNode = getTreeNodeByName(nodeName);
620         WebElement menuButton = Get.byXpath(rightTreeNode, ".//span[@data-tests-id='" + buttonOfEdit + "']");
621
622         GeneralUIUtils.clickElementUsingActions(menuButton);
623         Click.byTestId(contextMenuItem);
624     }
625
626     private WebElement getTreeNodeByName(String nodeName) {
627         return Get.byXpath("//tree-node-content[.//*[contains(text(), '" + nodeName + "')]]");
628     }
629 }