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