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