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