summaryrefslogtreecommitdiffstats
path: root/vid-app-common/src/test/java/org/onap
diff options
context:
space:
mode:
authorIttay Stern <ittay.stern@att.com>2018-12-31 17:21:27 +0200
committerIttay Stern <ittay.stern@att.com>2019-01-09 20:19:55 +0200
commit6ad41e3ccd398a2721f41ad61c80b7bb03f7d127 (patch)
tree3bd672dff83e3218232cd8665680416b7fc26a5d /vid-app-common/src/test/java/org/onap
parent5ec29ff5e3864f1ba6ecac71f8bffbefa400cf27 (diff)
Merge from ECOMP's repository
Main Features -------------- - Async-Instantiation jobs mechanism major update; still WIP (package `org.onap.vid.job`) - New features in View/Edit: Activate fabric configuration; show related networks; soft delete - Support AAI service-tree traversal (`AAIServiceTree`) - In-memory cache for SDC models and certain A&AI queries (`CacheProviderWithLoadingCache`) - Upgrade TOSCA Parser and add parsing options; fix malformed TOSCA models - Resolve Cloud-Owner values for MSO - Pass X-ONAP headers to MSO Infrastructure -------------- - Remove codehaus' jackson mapper; use soley fasterxml 2.9.7 - Surefire invokes both TestNG and JUnit tests - Support Kotlin source files - AaiController2 which handles errors in a "Spring manner" - Inline generated-sources and remove jsonschema2pojo Quality -------- - Cumulative bug fixes (A&AI API, UI timeouts, and many more) - Many Sonar issues cleaned-up - Some unused classes removed - Minor changes in vid-automation project, allowing some API verification to run Hard Merges ------------ - HTTP Clients (MSO, A&AI, WebConfig, OutgoingRequestHeadersTest) - Moved `package org.onap.vid.controllers` to `controller`, without plural -- just to keep semantic sync with ECOMP. Reference commit in ECOMP: 3d1141625 Issue-ID: VID-378 Change-Id: I9c8d1e74caa41815891d441fc0760bb5f29c5788 Signed-off-by: Ittay Stern <ittay.stern@att.com>
Diffstat (limited to 'vid-app-common/src/test/java/org/onap')
-rw-r--r--vid-app-common/src/test/java/org/onap/ecomp/vid/selenium/FirstClass.java606
-rw-r--r--vid-app-common/src/test/java/org/onap/ecomp/vid/selenium/LogOutLeftPane.java242
-rw-r--r--vid-app-common/src/test/java/org/onap/fusion/core/MockApplicationContextTestSuite.java177
-rw-r--r--vid-app-common/src/test/java/org/onap/fusionapp/controller/NetMapTest.java49
-rw-r--r--vid-app-common/src/test/java/org/onap/fusionapp/service/ProfileServiceTest.java75
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/RelatedToTest.java37
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/aai/AaiClientTest.java531
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/aai/AaiOverTLSClientServerTest.java72
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/aai/AaiOverTLSClientTest.java12
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/aai/OperationalEnvironmentTest.java18
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/aai/VnfResultTest.java5
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/aai/model/AaiGetPnfResponseTest.java10
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/aai/model/PnfPropertiesTest.java4
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/aai/model/PnfResultTest.java6
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/aai/util/CacheConfigTest.java32
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/aai/util/CacheProviderTest.java41
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/aai/util/CacheProviderWithLoadingCacheTest.java313
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/aai/util/HttpsAuthClientTest.java41
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/aai/util/NonCachingCacheProvider.java14
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/aai/util/ServiceInstanceStandardQueryTest.java405
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/aai/util/SingleAAIRestInterfaceTest.java75
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/asdc/beans/tosca/PropertyTest.java112
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/asdc/parser/ToscaParserImpl2Test.java281
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/asdc/parser/ToscaParserInflatorTest.java120
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/asdc/parser/VidNotionsBuilderTest.java290
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/bl/AaiServiceTest.java2
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/client/HttpsBasicClientTest.java17
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/config/DataSourceConfig.java7
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/config/JobCommandsConfigWithMockedMso.java207
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/controller/AaiControllerTest.java12
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/controller/AaiServiceInstanceStandardQueryControllerTest.java120
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/controller/ChangeManagementControllerTest.java (renamed from vid-app-common/src/test/java/org/onap/vid/controllers/ChangeManagementControllerTest.java)63
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/controller/ClientCredentialsFilterTest.java1
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/controller/HealthCheckControllerTest.java (renamed from vid-app-common/src/test/java/org/onap/vid/controllers/HealthCheckControllerTest.java)2
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/controller/LocalWebConfig.java23
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/controller/LoggerControllerTest.java (renamed from vid-app-common/src/test/java/org/onap/vid/controllers/LoggerControllerTest.java)11
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/controller/MaintenanceControllerTest.java (renamed from vid-app-common/src/test/java/org/onap/vid/controllers/MaintenanceControllerTest.java)4
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/controller/MsoControllerNewTest.java (renamed from vid-app-common/src/test/java/org/onap/vid/controllers/MsoControllerNewTest.java)15
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/controller/MsoControllerTest.java17
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/controller/PropertyControllerTest.java (renamed from vid-app-common/src/test/java/org/onap/vid/controllers/PropertyControllerTest.java)7
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/controller/RoleGeneratorControllerTest.java (renamed from vid-app-common/src/test/java/org/onap/vid/controllers/RoleGeneratorControllerTest.java)2
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/controller/ServicePermissionsTest.java48
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/controller/ToscaParserMockHelper.java37
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/controller/VersionControllerTest.java31
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/controller/VidControllerTest.java (renamed from vid-app-common/src/test/java/org/onap/vid/controllers/VidControllerTest.java)4
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/controller/ViewEditSubControllerTest.java (renamed from vid-app-common/src/test/java/org/onap/vid/controllers/ViewEditSubControllerTest.java)2
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/controllers/AaiControllerTest.java440
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/controllers/LocalWebConfig.java70
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/controllers/MsoControllerTest.java109
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/controllers/PolicyControllerTest.java30
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/controllers/PromiseEcompRequestIdFilterTest.java169
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/controllers/ToscaParserMockHelper.java42
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/job/command/CommandUtilsTest.java88
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/job/command/InProgressStatusCommandTest.java143
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/job/command/InProgressStatusServiceTest.java83
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/job/command/InstanceGroupCommandTest.java85
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/job/command/JobCommandFactoryTest.java36
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/job/command/ResourceCommandTest.java303
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/job/command/ResourceInProgressStatusCommandTest.java40
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/job/command/ServiceInProgressStatusCommandTest.java208
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/job/command/ServiceInstantiationCommandTest.java157
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/job/command/WatchChildrenJobsBLTest.java98
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/job/command/WatchingCommandTest.java77
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/job/impl/AsyncInstantiationIntegrationTest.java925
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/job/impl/JobAdapterImplTest.java110
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/job/impl/JobAdapterTest.java100
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/job/impl/JobSchedulerInitializerTest.java121
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/job/impl/JobWorkerTest.java9
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/model/JobAuditStatusTest.java40
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/model/RequestReferencesContainerTest.java6
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/mso/MsoBusinessLogicImplTest.java22
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/mso/MsoOperationalEnvironmentTest.java14
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/mso/RequestDetailsTest.java63
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/mso/RestMsoImplementationTest.java108
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/mso/model/OperationalEnvironmentActivateInfoTest.java6
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/mso/rest/AsyncRequestStatusTest.java2
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientNewTest.java14
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientTest.java14
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/mso/rest/OutgoingRequestHeadersTest.java (renamed from vid-app-common/src/test/java/org/onap/vid/mso/rest/OutgoingRequestIdTest.java)104
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/mso/rest/RelatedInstanceTest.java6
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/mso/rest/RelatedModelTest.java93
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/mso/rest/RequestDetailsTest.java8
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/mso/rest/RequestTest.java2
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/policy/PolicyResponseWrapperTest.java70
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/policy/PolicyRestIntTest.java22
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/policy/PolicyRestInterfaceFactoryTest.java18
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/policy/PolicyRestInterfaceTest.java32
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/policy/PolicyUtilTest.java51
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/policy/RestObjectTest.java48
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/policy/rest/RequestDetailsTest.java33
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/roles/RoleProviderTest.java14
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/scheduler/RestObjectTest.java20
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/scheduler/RestObjects/RestObjectTest.java1
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/scheduler/SchedulerRestInterfaceTest.java9
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/selenium/FirstClass.java605
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/selenium/LogOutLeftPane.java242
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/services/AAIServiceTreeTest.java160
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/services/AAITreeConverterTest.java222
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/services/AAITreeNodeBuilderTest.java131
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/services/AaiResponseTranslatorTest.java5
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/services/AsyncInstantiationBaseTest.java220
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/services/AsyncInstantiationBusinessLogicTest.java877
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/services/AuditServiceImplTest.java36
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/services/BulkInstantiationServiceImplTest.java36
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/services/ChangeManagementServiceImplTest.java20
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/services/ChangeManagementServiceTest.java29
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/services/ChangeManagementServiceUnitTest.java9
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/services/CloudOwnerServiceTest.java125
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/services/CsvServiceTest.java162
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/services/JobsBrokerServiceTest.java1287
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/services/PortDetailsTranslatorTest.java261
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/services/SchedulerServiceImplTest.java179
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/testUtils/TestUtils.java58
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/utils/LoggingTest.java10
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/utils/LoggingUtilsTest.java10
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/utils/TimeUtilsTest.java67
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/utils/TreeTest.java63
117 files changed, 7432 insertions, 5845 deletions
diff --git a/vid-app-common/src/test/java/org/onap/ecomp/vid/selenium/FirstClass.java b/vid-app-common/src/test/java/org/onap/ecomp/vid/selenium/FirstClass.java
deleted file mode 100644
index d0da08c58..000000000
--- a/vid-app-common/src/test/java/org/onap/ecomp/vid/selenium/FirstClass.java
+++ /dev/null
@@ -1,606 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * VID
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.ecomp.vid.selenium;
-
-import org.testng.annotations.AfterClass;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.AfterSuite;
-import org.testng.annotations.BeforeClass;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.BeforeSuite;
-import org.testng.annotations.BeforeTest;
-import org.testng.annotations.Test;
-
-
-import org.openqa.selenium.By;
-import org.openqa.selenium.WebDriver;
-import org.openqa.selenium.WebElement;
-import org.openqa.selenium.firefox.FirefoxDriver;
-import org.openqa.selenium.ie.InternetExplorerDriver;
-import org.openqa.selenium.support.ui.Select;
-
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.List;
-import java.util.Properties;
-import java.util.concurrent.TimeUnit;
-import org.apache.log4j.Logger;
-import org.testng.Assert;
-import org.testng.asserts.*;
-
-/**
- * The Class FirstClass.
- */
-public class FirstClass {
-
- /** The login button. */
- WebElement loginButton;
-
- /** The eg. */
- String eg;
-
- /** The login. */
- WebElement login;
-
- /** The pwd. */
- WebElement pwd;
-
- /** The log. */
- Logger log;
-
- /** The errormessage. */
- WebElement errormessage;
-
-
- /** The driver. */
- WebDriver driver=new FirefoxDriver();
-
-
-
- /** The config prop. */
- private final Properties configProp = new Properties();
-
-
- /**
- * Instantiates a new first class.
- */
- private FirstClass() {
- // TODO Auto-generated constructor stub
- //
- try{
- // InputStream input =this.getClass().getClassLoader().getResourceAsStream("objectmap.properties");
- //FileInputStream input1 = new FileInputStream("objectmap.properties");
-
- InputStream input =new FileInputStream("objectconfig.properties");
- System.out.println("Read all properties from file");
- configProp.load(input);
- System.out.println("Read all properties from file completed");
- }
- catch(IOException e) {
-
- e.printStackTrace();
- }
- }
-
-
- /*
-
-
- @BeforeClass
- public void setUp() {
- System.out.println("*******************");
- System.out.println("launching IE browser");
- System.setProperty("webdriver.ie.driver", driverPath+"IEDriverServer.exe");
- driver = new InternetExplorerDriver();
- driver.findElement(By.className());
- driver.manage().window().maximize();
-
-
- login = driver.findElement(By.xpath("//input[@class='fn-ebz-text ng-pristine ng-valid']"));
- pwd = driver.findElement(By.xpath("//input[@class='span3 ng-pristine ng-valid']"));
- loginButton = driver.findElement(By.id("loginBtn"));
- }
-
-
- */
- /**
- * Sets the up.
- */
- // TODO Auto-generated method stub
- @BeforeClass
- public void setUp()
- {
-
-
- //WebDriver driver=new FirefoxDriver();
-
- log = Logger.getLogger(FirstClass.class.getName());
-
-
-
- // Get url
- driver.get(configProp.getProperty("baseURL"));
- driver.manage().window().maximize();
-
-
- login = driver.findElement(By.xpath(configProp.getProperty("login")));
-
- pwd = driver.findElement(By.xpath(configProp.getProperty("pwd")));
- loginButton = driver.findElement(By.id(configProp.getProperty("loginButton")));
- }
-
-
- /**
- * Empty username password.
- */
- @Test(priority=1)
- public void emptyUsernamePassword()
- {
-
-
- //User Name and Password field is empty
- log.info("-----VID-11 TC-8----Username and password empty");
- loginButton.click();
- errormessage=driver.findElement(By.xpath("//*[@id='errorInfo']/span"));
- String errmsg= errormessage.getText();
- //System.out.println("Error message is"+errmsg);
- //String expected = "Invaild username or password, Please try again";
-
- //Assert.assertEquals(errmsg,expected);
-
- Boolean str = driver.getPageSource().contains("Invalid username or password, Please try again");
- System.out.println(driver.getPageSource().contains("Invalid username or password, Please try again"));
-
- if(str==true)
- {
- log.info("Error message validated");
- log.info("VID-11 TC-8 PASSED");
-
- }else
- log.error("Failed validation");
-
- }
-
-
-
- /**
- * Invalid user name.
- */
- @Test(priority=2)
- public void invalidUserName()
- {
-
- log.info("-----VID-11 TC-6----Invalid Username and Valid Password");
-
-
- login.sendKeys("xxx");
- pwd.sendKeys("abc123");
- loginButton.click();
- try {
- Thread.sleep(5000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- String errmsg= errormessage.getText();
- String expected = "Invalid username or password, Please try again";
- Assert.assertEquals(errmsg,expected);
- //Boolean str1 = driver.getPageSource().contains("Invalid username or password, Please try again");
- //System.out.print(str1);
-
- log.info("VID-11 TC-6 PASSED");
-
- }
-
-
- /**
- * Invalid password.
- */
- @Test(priority=3)
- public void invalidPassword()
- {
- log.info("-----VID-11 TC-7----Valid Username and Invalid Password");
- // Valid user name and Invalid password.
- login.clear();
- pwd.clear();
- login.sendKeys("testuser");
- pwd.sendKeys("xxx");
- loginButton.click();
- driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
-
-
- String errmsg= errormessage.getText();
- String expected = "Invalid username or password, Please try again";
- Assert.assertEquals(errmsg,expected);
-
- //Boolean str2 = driver.getPageSource().contains("Invaild username or password, Please try again");
- //System.out.print(str2);
-
- log.info("VID-11 TC-7 PASSED");
- }
-
-
- /**
- * Login successful.
- */
- @Test(priority=4)
- public void loginSuccessful()
- {
- log.info("-----VID-11 TC-1----Valid Username and Valid Password");
- //Login with valid user name and password.
- login.clear();
- login.sendKeys("su");
- pwd.clear();
- pwd.sendKeys("fusion");
-
-
- loginButton.click();
- driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
-
- try {
- Thread.sleep(6000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- Assert.assertTrue(driver.getPageSource().contains("Search Existing Service Instances"));
- log.info("VID-11 TC-1 PASSED");
-
- }
-
-
- /**
- * Verify home page elements left pane.
- */
- @Test(priority=5)
- public void verifyHomePageElementsLeftPane()
-
- {
-
-
- log.info("VID-10 TC 1 ");
- //VID Home
- log.info("VID 11 TC-2");
- driver.findElement(By.xpath("html/body/div[1]/div[1]/div/div/div[2]/div/div/div[1]/div/div/accordion/div/div[1]/a/span")).isDisplayed();
- //Create New Service Instance
- driver.findElement(By.xpath("html/body/div[1]/div[1]/div/div/div[2]/div/div/div[1]/div/div/accordion/div/div[2]/a/span")).isDisplayed();
-
- //Browse Service Type
- driver.findElement(By.xpath("html/body/div[1]/div[1]/div/div/div[2]/div/div/div[1]/div/div/accordion/div/div[3]/a/span")).isDisplayed();
- //View Log
- driver.findElement(By.xpath("html/body/div[1]/div[1]/div/div/div[2]/div/div/div[1]/div/div/accordion/div/div[4]/a/span")).isDisplayed();
-
- //Profile
- driver.findElement(By.xpath("html/body/div[1]/div[1]/div/div/div[2]/div/div/div[1]/div/div/accordion/div/div[5]/a/span")).isDisplayed();
- //Admin
- driver.findElement(By.xpath("html/body/div[1]/div[1]/div/div/div[2]/div/div/div[1]/div/div/accordion/div/div[6]/a/span")).isDisplayed();
- //Logout
- driver.findElement(By.xpath("html/body/div[1]/div[1]/div/div/div[2]/div/div/div[1]/div/div/accordion/div/div[7]/a/span")).isDisplayed();
-
- //Infrastructure Subscriber Name
- driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[1]/td[1]/div/label")).isDisplayed();
- //Infrastructure Subscriber Name Select Drop down
- driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[1]/td[2]/div/select")).isDisplayed();
- //Infrastructure Service Type
- driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[2]/td[1]/div/label")).isDisplayed();
- //Infrastructure Service Type Select Drop down
- driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[2]/td[2]/div/select")).isDisplayed();
- //Submit button
- driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[3]/td/div/button")).isDisplayed();
-
- //Login Snippet Icon
- driver.findElement(By.xpath(".//*[@class='icon-user-small login-snippet-icon']")).isDisplayed();
-
-
- //String bodyText = driver.findElement(By.tagName("body")).getText();
- //Assert.assertTrue("Text not found!", bodyText.contains("Search Existing Service Instances"));
- //Assert.IsTrue(driver.getPageSource.Contains("Search Existing Service Instances"));
-
- log.info("VID-12 TC-1");
- Assert.assertTrue(driver.getPageSource().contains("Search Existing Service Instances"));
- Assert.assertTrue(driver.getPageSource().contains("Please search by the Subscriber name or Service Type from below:"));
- log.info("VID-12 TC-1 PASSED");
- log.info("VID-10 TC 1 PASSED");
- log.info("VID-11 TC-2 PASSED");
- }
-
-
- /**
- * Disabled submit button.
- */
- @Test(priority=6)
- public void disabledSubmitButton()
- {
- log.info("VID-12 TC-13");
- //Assert submit button disabled.
- Assert.assertFalse(driver.findElement(By.xpath(configProp.getProperty("submitButton"))).isEnabled());
- log.info("VID-12 TC-13 PASSED");
-
- }
-
- /**
- * Default list box value.
- */
- @Test(priority=7)
- public void defaultListBoxValue()
- {
- log.info("VID-12 TC-2");
-
-
- //WebElement subscribername =driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[1]/td[2]/div/select"));
-
- Select oSelect = new Select(driver.findElement(By.xpath(configProp.getProperty("subscriberNameDropDown"))));
- Select iSelect = new Select(driver.findElement(By.xpath(configProp.getProperty("serviceTypeDropDown"))));
-
-
- WebElement ielement=iSelect.getFirstSelectedOption();
- WebElement oelement=oSelect.getFirstSelectedOption();
- String defaultsubscribername=oelement.getText();
- String defaultservicetype=ielement.getText();
-
- Assert.assertEquals(defaultsubscribername,"Select Subscriber Name");
- Assert.assertEquals(defaultservicetype,"Select Service Type");
-
-
-
-
- //Verify Select Subscriber Name isDisplayed.
- //driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[1]/td[2]/div/select/option[1]")).isSelected();
-
- //Verify Select Service Type isDisplayed.
- //driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[2]/td[2]/div/select/option[1]")).isSelected();
-
-
- log.info("VID-12 TC-2 PASSED");
-
- }
-
-
-
- /**
- * Select subscriber name drop down.
- *
- * @throws InterruptedException the interrupted exception
- */
- @Test(priority=8)
- public void selectSubscriberNameDropDown() throws InterruptedException
- {
- log.info("------------------VID-10 TC-2,VID-12 TC-11, VID-12 TC-9, VID 12 TC-10,VID-12 TC-6, VID 12 TC-5--------------------");
-
-
- driver.findElement(By.xpath(configProp.getProperty("subscriberNameDropDown")));
-
- driver.findElement(By.xpath(configProp.getProperty("serviceTypeDropDown")));
- Thread.sleep(5000);
-
- //Infrastructure Subscriber Name
- Select oSelect = new Select(driver.findElement(By.xpath(configProp.getProperty("subscriberNameDropDown"))));
-
- List <WebElement> elementCount = oSelect.getOptions();
- log.info("Select Element Count of Service Name");
- System.out.println(elementCount.size());
-
-
- //Verifying getInfrastructureSubscribersList
- log.info("VID-29 TC-1");
- Assert.assertTrue(elementCount.size()>0);
- log.info("VID-29 TC-1 PASSED");
-
- oSelect.selectByIndex(2);
- String selectedOption = new Select(driver.findElement(By.xpath(configProp.getProperty("subscriberNameDropDown")))).getFirstSelectedOption().getText();
-
- System.out.println("Service Name selected is " +selectedOption);
- log.info("VID-10 TC-2 PASSED");
-
- //Submit button is clicked
- driver.findElement(By.xpath(configProp.getProperty("submitButton"))).click();
-
-
- //Verify whether the page header is displayed "Selected Subscriber's Service Instance Details:"
- driver.findElement(By.xpath(".//*[@id='mContent']/div/div/div/h1")).isDisplayed();
- //Assert.assertTrue(driver.getPageSource().contains("Selected Subscriber's Service Instance Details:"))
-
-
- //Verify whether the page header is displayed "Global Customer ID"
- driver.findElement(By.xpath(".//*[@id='mContent']/div/div/div/div/table/thead/tr/th[2]/div")).isDisplayed();
- Assert.assertTrue(driver.getPageSource().contains("Global Customer ID"));
- Assert.assertTrue(driver.getPageSource().contains("Subscriber Name"));
- Assert.assertTrue(driver.getPageSource().contains("Service Type"));
- Assert.assertTrue(driver.getPageSource().contains("Service Instance ID"));
-
- log.info("VID-12 TC-5 PASSED");
- log.info("VID-12 TC-11 PASSED");
-
- WebElement serviceinstancetable =driver.findElement(By.xpath("//table[@class='tablesorter tablesorter-default ng-isolate-scope']"));
-
- List<WebElement> rows_table = serviceinstancetable.findElements(By.tagName("tr"));
- //To calculate no of rows In table.
- int rows_count = rows_table.size();
-
- //Loop will execute till the last row of table.
- for (int row=0; row<rows_count; row++){
- //To locate columns(cells) of that specific row.
- List<WebElement> Columns_row = rows_table.get(row).findElements(By.tagName("td"));
- //To calculate no of columns(cells) In that specific row.
- int columns_count = Columns_row.size();
- //System.out.println("Number of cells In Row "+row+" are "+columns_count);
-
- //Loop will execute till the last cell of that specific row.
- for (int column=0; column<columns_count; column++){
- //To retrieve text from that specific cell.
- String celtext = Columns_row.get(column).getText();
- //System.out.println("Cell Value Of row number "+row+" and column number "+column+" Is "+celtext);
-
-
-
- //log.info("Testing Get column and row value");
- List <WebElement> exx= rows_table.get(1).findElements(By.tagName("td"));
- eg=Columns_row.get(2).getText();
- // System.out.println("Cell value of row 1 and column 2 is" +eg);
- }
- }
-
-
-
-
- //Verify View/Edit isDisplayed and Click
-
- driver.findElement(By.xpath("//a[@alt='View/Edit']")).isDisplayed();
-
- driver.findElement(By.xpath(".//*[@id='mContent']/div/div/div/div/table/tbody/tr[1]/td[1]/div/a")).click();
-
- log.info("User clicked View/Edit");
-
- //Verify the Subscriber Name displayed.
- String header= driver.findElement(By.xpath("//h1[@class='heading1 ng-binding']")).getText();
- //System.out.println(header);
-
-
- if(header.contains(eg))
- {
- System.out.println("Header contains the subscriber name");
- }else
- System.out.println("Header does not contain the subscriber name");
-
-
-
- Assert.assertTrue(driver.getPageSource().contains("PerfTest Subscriber00020021"));
- log.info("VID-12 TC-6 PASSED");
-
-
-
- driver.navigate().back();
- //Cancel button isDisplayed
- driver.findElement(By.xpath("//button[@class='button button--small button--primary']")).isDisplayed();
- log.info("VID-12 TC-9 PASSED");
-
- //Cancel button is clicked
- driver.findElement(By.xpath("//button[@class='button button--small button--primary']")).click();
- log.info("Cancel button is clicked");
-
- //Verifying VID Home page is displayed
- Assert.assertTrue(driver.getPageSource().contains("Search Existing Service Instances"));
- log.info("VID-12 TC-10 PASSED");
-
- }
-
-
- /**
- * Refresh subscriber name.
- */
- @Test(priority=9)
- public void refreshSubscriberName()
- {
- log.info("VID-10 TC-4");
-
-
- driver.findElement(By.xpath(configProp.getProperty("refreshButtonSubscriberName"))).isDisplayed();
-
- log.info("VID-10 TC-4 PASSED");
-
-
- }
-
-
- /**
- * Select subscriber type drop down.
- *
- * @throws InterruptedException the interrupted exception
- */
- @Test(priority=9)
- public void selectSubscriberTypeDropDown() throws InterruptedException
- {
- Thread.sleep(5000);
- log.info("------------------VID-10 TC-3, VID-12 TC-12,--------------------");
- //Infrastructure Subscriber Type
- Select iSelect = new Select(driver.findElement(By.xpath(configProp.getProperty("serviceTypeDropDown"))));
-
- List <WebElement> ielementCount = iSelect.getOptions();
- log.info("Select Element Count of Service type");
- System.out.println(ielementCount.size());
- iSelect.selectByIndex(1);
-
- log.info("VID-10 TC-3 PASSED");
-
-
- //Submit button is clicked
- driver.findElement(By.xpath(configProp.getProperty("submitButton"))).click();
-
- //Verify whether the page header is displayed "Selected Subscriber's Service Instance Details:"
- driver.findElement(By.xpath(".//*[@id='mContent']/div/div/div/h1")).isDisplayed();
- //Assert.assertTrue(driver.getPageSource().contains("Selected Subscriber's Service Instance Details:"))
- log.info("Page Header: Selected Subscriber's Service Instance Details");
-
-
- //Verify whether the page header is displayed "Global Customer ID"
- driver.findElement(By.xpath(".//*[@id='mContent']/div/div/div/div/table/thead/tr/th[2]/div")).isDisplayed();
-
- //Assert.assertTrue(driver.getPageSource().contains("Global Customer ID"));
- log.info("Table is displayed");
-
- log.info("VID-12 TC-12 PASSED");
-
- }
-
-
-
- /**
- * Logout under profile.
- */
- @Test(priority=10)
- public void logoutUnderProfile()
- {
-
- log.info("-----------VID-11 TC-5---------------------");
- //driver.findElement(By.partialLinkText("Click here to login")).click();
- //driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
-
-
- driver.findElement(By.xpath(".//*[@class='icon-user-small login-snippet-icon']")).click();
- driver.findElement(By.xpath(".//*[@id='reg-logout-div']/a")).click();
- //Validate that the user has logged out of VID. Displays "Portal"
- Assert.assertTrue(driver.getPageSource().contains("Portal"));
-
- log.info("VID-11 TC-5 PASSED");
-
- }
-
-
-
- /**
- * Tear down.
- */
- @AfterClass
- public void tearDown()
- {
- driver.close();
-
- }
-
-
-
- }
-
-
-
-
diff --git a/vid-app-common/src/test/java/org/onap/ecomp/vid/selenium/LogOutLeftPane.java b/vid-app-common/src/test/java/org/onap/ecomp/vid/selenium/LogOutLeftPane.java
deleted file mode 100644
index fdd5ea38d..000000000
--- a/vid-app-common/src/test/java/org/onap/ecomp/vid/selenium/LogOutLeftPane.java
+++ /dev/null
@@ -1,242 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * VID
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.ecomp.vid.selenium;
-
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.List;
-import java.util.Properties;
-import java.util.concurrent.TimeUnit;
-
-import org.apache.log4j.Logger;
-import org.openqa.selenium.By;
-import org.openqa.selenium.WebDriver;
-import org.openqa.selenium.WebElement;
-import org.openqa.selenium.firefox.FirefoxDriver;
-import org.openqa.selenium.support.ui.Select;
-import org.testng.Assert;
-import org.testng.annotations.BeforeTest;
-import org.testng.annotations.Test;
-
-/**
- * The Class LogOutLeftPane.
- */
-@Test(enabled=false)
-public class LogOutLeftPane {
-
- /** The login button. */
- WebElement loginButton;
-
- /** The login. */
- WebElement login;
-
- /** The pwd. */
- WebElement pwd;
-
- /** The log. */
- Logger log;
-
- /** The errormessage. */
- WebElement errormessage;
-
- /** The driver. */
- WebDriver driver=new FirefoxDriver();
-
-
- /** The config prop. */
- private final Properties configProp = new Properties();
-
-
- /**
- * Instantiates a new log out left pane.
- */
- private LogOutLeftPane() {
- // TODO Auto-generated constructor stub
- //
- try{
- // InputStream input =this.getClass().getClassLoader().getResourceAsStream("objectmap.properties");
- //FileInputStream input1 = new FileInputStream("objectmap.properties");
-
- InputStream input =new FileInputStream("objectconfig.properties");
- System.out.println("Read all properties from file");
- configProp.load(input);
- System.out.println("Read all properties from file completed");
- }
- catch(IOException e) {
-
- e.printStackTrace();
- }
- }
-
-
-
-
- /**
- * Do before test.
- */
- // TODO Auto-generated method stub
- @BeforeTest
- public void doBeforeTest()
- {
- //WebDriver driver=new FirefoxDriver();
-
- log = Logger.getLogger(LogOutLeftPane.class.getName());
-
-
-
- // Get url
- driver.get("http://vid.onap.org:9080/vid/login_external.htm");
- driver.manage().window().maximize();
-
-
- login = driver.findElement(By.xpath("//input[@class='fn-ebz-text ng-pristine ng-valid']"));
- pwd = driver.findElement(By.xpath("//input[@class='span3 ng-pristine ng-valid']"));
- loginButton = driver.findElement(By.id("loginBtn"));
- }
-
-
- /**
- * Expand collapse panel.
- *
- * @throws InterruptedException the interrupted exception
- */
- @Test(priority=1)
- public void expandCollapsePanel() throws InterruptedException
- {
-
-
-
- login.clear();
- login.sendKeys("su");
- pwd.clear();
- pwd.sendKeys("fusion");
- //driver.findElement(By.partialLinkText("Click here to login")).click();
- //driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
-
- loginButton.click();
- driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
-
-
- log.info("Clicking Profile link from left pane");
- Thread.sleep(3000);
- System.out.println("properties file details --->"+configProp.getProperty("profilelink"));
- driver.findElement(By.xpath(configProp.getProperty("profilelink"))).click();
- Thread.sleep(3000);
-
- //Verify whether the sub panel is displayed
- //To verify the following :Search import from webphone and Self
- driver.findElement(By.xpath(".//*[@id='panel4']")).isDisplayed();
- log.info("Expand and collapse passed for Profile link");
-
- //For Admin
- //Verify expand and collapse working for ADMIN
- log.info("Clicking Admin link from left pane");
- driver.findElement(By.xpath("html/body/div[1]/div[1]/div/div/div[2]/div/div/div[1]/div/div/accordion/div/div[6]/a/span")).click();
- //To verify the following: Roles, Roles Functions, Usages
- driver.findElement(By.xpath(".//*[@id='panel5']")).isDisplayed();
-
-
- log.info("Expand and collapse passed for ADMIN link");
-
- log.info("VID-11 TC-3 PASSED");
-
- }
-
-
- /**
- * Drop down list.
- *
- * @throws InterruptedException the interrupted exception
- */
- @Test(priority=2)
- public void dropDownList() throws InterruptedException
- {
- //VID-12 TC-3
- log.info("VID-12 TC-3");
- //driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[1]/td[2]/div/select"));
-
- //driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[2]/td[2]/div/select"));
- Thread.sleep(5000);
-
- //Infrastructure Subscriber Name
- Select oSelect = new Select(driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[1]/td[2]/div/select")));
- Select iSelect = new Select(driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[2]/td[2]/div/select")));
-
- List <WebElement> elementCount = oSelect.getOptions();
- log.info("Subscriber Name Drop Down");
- System.out.println(elementCount.size());
- oSelect.selectByIndex(1);
- log.info("Subscriber name selected");
- //String selectedOption = new Select(driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[1]/td[2]/div/select"))).getFirstSelectedOption().getText();
-
-
- List <WebElement> count = iSelect.getOptions();
- log.info("Subscriber type drop down");
- System.out.println(count.size());
- oSelect.selectByIndex(1);
- log.info("Subscriber type selected");
-
-
-
- //Submit button is clicked
- driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[3]/td/div/button")).click();
-
-
- //Verify whether the page header is displayed "Selected Subscriber's Service Instance Details:"
- driver.findElement(By.xpath(".//*[@id='mContent']/div/div/div/h1")).isDisplayed();
- log.info("VID-12 TC-3 PASSED");
- }
-
-
-
-
- /**
- * Logout left pane.
- */
- @Test(priority=3)
- public void logoutLeftPane()
- {
- //To Verify if the logout link redirects to Login page when clicked.
-
-
- /*log.info("----------------VID-11 TC-4----------------");
- login.clear();
- login.sendKeys("testuser");
- pwd.clear();
- pwd.sendKeys("abc123");
- //driver.findElement(By.partialLinkText("Click here to login")).click();
- //driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
-
- loginButton.click();
- driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);*/
- log.info("----------------VID-11 TC-4----------------");
- driver.findElement(By.xpath("html/body/div[1]/div[1]/div/div/div[2]/div/div/div[1]/div/div/accordion/div/div[7]/a")).click();
- //Validate that the user has logged out of VID. Displays "Portal"
- Assert.assertTrue(driver.getPageSource().contains("Portal"));
-
- log.info("VID 11 TC-4 PASSED");
-
- driver.close();
-
- }
-
-}
diff --git a/vid-app-common/src/test/java/org/onap/fusion/core/MockApplicationContextTestSuite.java b/vid-app-common/src/test/java/org/onap/fusion/core/MockApplicationContextTestSuite.java
deleted file mode 100644
index 1d61340eb..000000000
--- a/vid-app-common/src/test/java/org/onap/fusion/core/MockApplicationContextTestSuite.java
+++ /dev/null
@@ -1,177 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * VID
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.fusion.core;
-
-import java.io.IOException;
-
-import org.junit.Before;
-import org.junit.runner.RunWith;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.ComponentScan;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.Profile;
-import org.springframework.test.context.ActiveProfiles;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import org.springframework.test.context.web.AnnotationConfigWebContextLoader;
-import org.springframework.test.context.web.WebAppConfiguration;
-import org.springframework.test.web.servlet.MockMvc;
-import org.springframework.test.web.servlet.setup.MockMvcBuilders;
-import org.springframework.web.context.WebApplicationContext;
-import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
-import org.testng.annotations.Test;
-import org.onap.portalsdk.core.conf.AppConfig;
-import org.onap.portalsdk.core.objectcache.AbstractCacheManager;
-import org.onap.portalsdk.core.util.SystemProperties;
-import org.onap.portalsdk.core.util.CacheManager;
-
-/**
- *
- *
- *
- * In order to write a unit test,
- * 1. inherit this class - See SanityTest.java
- * 2. place the "war" folder on your test class's classpath
- * 3. run the test with the following VM argument; This is important because when starting the application from Container, the System Properties file (SystemProperties.java) can have the direct path
- * but, when running from the Mock Junit container, the path should be prefixed with "classpath" to enable the mock container to search for the file in the classpath
- * -Dcontainer.classpath="classpath:"
- *
- */
-
-@RunWith(SpringJUnit4ClassRunner.class)
-@WebAppConfiguration
-@ContextConfiguration(loader = AnnotationConfigWebContextLoader.class, classes = {MockAppConfig.class})
-@ActiveProfiles(value="test")
-@Test(enabled=false)
-public class MockApplicationContextTestSuite {
-
- /** The wac. */
- @Autowired
- public WebApplicationContext wac;
-
- /** The mock mvc. */
- private MockMvc mockMvc;
-
- /**
- * Setup.
- */
- @Before
- public void setup() {
- if(mockMvc == null) {
- this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
-
- }
- }
-
- /**
- * Gets the bean.
- *
- * @param name the name
- * @return the bean
- */
- public Object getBean(String name) {
- return this.wac.getBean(name);
- }
-
-
- /**
- * Gets the mock mvc.
- *
- * @return the mock mvc
- */
- public MockMvc getMockMvc() {
- return mockMvc;
- }
-
- /**
- * Sets the mock mvc.
- *
- * @param mockMvc the new mock mvc
- */
- public void setMockMvc(MockMvc mockMvc) {
- this.mockMvc = mockMvc;
- }
-
- /**
- * Gets the web application context.
- *
- * @return the web application context
- */
- public WebApplicationContext getWebApplicationContext() {
- return wac;
- }
-
-
-
-
-}
-
-
- @Configuration
- @ComponentScan(basePackages = "org.onap",
- excludeFilters = {
- // the following source configurations should not be scanned; instead of using Exclusion filter, we can use the @Profile annotation to exclude them
- // see AppConfig class
- //@ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.onap.portalsdk.core.*AppConfig*")//,
- //@ComponentScan.Filter(type = FilterType.REGEX, pattern = org.onap.*.*AppConfig*")
- }
- )
- @Profile("test")
- class MockAppConfig extends AppConfig {
-
- @Bean
- public SystemProperties systemProperties(){
- return new MockSystemProperties();
- }
-
- @Bean
- public AbstractCacheManager cacheManager() {
- return new CacheManager() {
-
- public void configure() throws IOException {
-
- }
- };
- }
-
- protected String[] tileDefinitions() {
- return new String[] {"classpath:/WEB-INF/fusion/defs/definitions.xml", "classpath:/WEB-INF/defs/definitions.xml"};
- }
-
- @Override
- public void addInterceptors(InterceptorRegistry registry) {
- //registry.addInterceptor(new SessionTimeoutInterceptor()).excludePathPatterns(getExcludeUrlPathsForSessionTimeout());
- //registry.addInterceptor(resourceInterceptor());
- }
-
- public static class MockSystemProperties extends SystemProperties {
-
- public MockSystemProperties() {
- }
-
- }
-
- }
-
-
-
-
diff --git a/vid-app-common/src/test/java/org/onap/fusionapp/controller/NetMapTest.java b/vid-app-common/src/test/java/org/onap/fusionapp/controller/NetMapTest.java
deleted file mode 100644
index 7a4c56019..000000000
--- a/vid-app-common/src/test/java/org/onap/fusionapp/controller/NetMapTest.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * VID
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.fusionapp.controller;
-
-import org.junit.Assert;
-import org.junit.Test;
-import org.springframework.test.web.servlet.ResultActions;
-import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
-
-import org.onap.fusion.core.MockApplicationContextTestSuite;
-
-/**
- * The Class NetMapTest.
- */
-
-public class NetMapTest extends MockApplicationContextTestSuite {
-
- /**
- * Test get net map.
- *
- * @throws Exception the exception
- */
-// @Test
- public void testGetNetMap() throws Exception {
- ResultActions ra =getMockMvc().perform(MockMvcRequestBuilders.get("/net_map"));
- //Assert.assertEquals(UrlAccessRestrictedException.class,ra.andReturn().getResolvedException().getClass());
- Assert.assertEquals("net_map_int",ra.andReturn().getModelAndView().getModel().get("frame_int"));
- }
-
-
-}
diff --git a/vid-app-common/src/test/java/org/onap/fusionapp/service/ProfileServiceTest.java b/vid-app-common/src/test/java/org/onap/fusionapp/service/ProfileServiceTest.java
deleted file mode 100644
index c486e7b01..000000000
--- a/vid-app-common/src/test/java/org/onap/fusionapp/service/ProfileServiceTest.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * VID
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.fusionapp.service;
-
-import java.util.List;
-
-import org.junit.Assert;
-import org.junit.Test;
-import org.springframework.beans.factory.annotation.Autowired;
-
-import org.onap.fusion.core.MockApplicationContextTestSuite;
-import org.onap.portalsdk.core.domain.Profile;
-import org.onap.portalsdk.core.domain.User;
-import org.onap.portalsdk.core.service.ProfileService;
-import org.onap.portalsdk.core.service.UserProfileService;
-
-
-/**
- * The Class ProfileServiceTest.
- */
-
-public class ProfileServiceTest extends MockApplicationContextTestSuite {
-
- /** The service. */
- @Autowired
- ProfileService service;
-
- /** The user profile service. */
- @Autowired
- UserProfileService userProfileService;
-
- /**
- * Test find all.
- */
- //@Test
- public void testFindAll() {
- try {
- List<Profile> profiles = service.findAll();
- Assert.assertTrue(profiles.size() > 0);
-
- }
- catch (Exception e) {
- // TODO: handle exception
- }
- }
-
- /**
- * Test find all active.
- */
-// @Test
- public void testFindAllActive() {
-
- List<User> users = userProfileService.findAllActive();
- List<User> activeUsers = userProfileService.findAllActive();
- Assert.assertTrue(users.size() - activeUsers.size() >= 0);
- }
-}
diff --git a/vid-app-common/src/test/java/org/onap/vid/RelatedToTest.java b/vid-app-common/src/test/java/org/onap/vid/RelatedToTest.java
deleted file mode 100644
index ca4ac1b81..000000000
--- a/vid-app-common/src/test/java/org/onap/vid/RelatedToTest.java
+++ /dev/null
@@ -1,37 +0,0 @@
-package org.onap.vid;
-
-import java.util.Map;
-
-import org.junit.Test;
-import org.onap.vid.RelatedTo;
-
-
-public class RelatedToTest {
-
- private RelatedTo createTestSubject() {
- return new RelatedTo();
- }
-
-
- @Test
- public void testGetAdditionalProperties() throws Exception {
- RelatedTo testSubject;
- Map<String, Object> result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getAdditionalProperties();
- }
-
-
- @Test
- public void testSetAdditionalProperty() throws Exception {
- RelatedTo testSubject;
- String name = "";
- Object value = null;
-
- // default test
- testSubject = createTestSubject();
- testSubject.setAdditionalProperty(name, value);
- }
-} \ No newline at end of file
diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/AaiClientTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/AaiClientTest.java
index 201ec0981..2656532f4 100644
--- a/vid-app-common/src/test/java/org/onap/vid/aai/AaiClientTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/aai/AaiClientTest.java
@@ -1,26 +1,6 @@
-/*-
- * ============LICENSE_START=======================================================
- * VID
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2018 Nokia. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
package org.onap.vid.aai;
+import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableList;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
@@ -28,18 +8,15 @@ import org.apache.commons.lang3.builder.ToStringStyle;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.commons.lang3.tuple.Pair;
+import org.apache.http.HttpStatus;
import org.mockito.Mockito;
import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
import org.onap.portalsdk.core.util.SystemProperties;
+import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.RelatedToProperty;
import org.onap.vid.aai.model.AaiGetTenatns.GetTenantsResponse;
-import org.onap.vid.aai.model.AaiNodeQueryResponse;
-import org.onap.vid.aai.model.PortDetailsTranslator;
-import org.onap.vid.aai.model.ResourceType;
-import org.onap.vid.aai.util.AAIRestInterface;
-import org.onap.vid.aai.util.HttpsAuthClient;
-import org.onap.vid.aai.util.ServletRequestHelper;
-import org.onap.vid.aai.util.SystemPropertyHelper;
-import org.onap.vid.controllers.LocalWebConfig;
+import org.onap.vid.aai.model.*;
+import org.onap.vid.aai.util.*;
+import org.onap.vid.controller.LocalWebConfig;
import org.onap.vid.exceptions.GenericUncheckedException;
import org.onap.vid.model.Subscriber;
import org.onap.vid.model.SubscriberList;
@@ -47,6 +24,7 @@ import org.onap.vid.model.probes.ExternalComponentStatus;
import org.onap.vid.model.probes.HttpRequestMetadata;
import org.onap.vid.model.probes.StatusMetadata;
import org.onap.vid.testUtils.TestUtils;
+import org.onap.vid.utils.Unchecked;
import org.springframework.http.HttpMethod;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.web.WebAppConfiguration;
@@ -65,42 +43,53 @@ import javax.ws.rs.client.Client;
import javax.ws.rs.core.Response;
import java.io.FileNotFoundException;
import java.io.IOException;
+import java.net.URI;
import java.security.cert.CertificateException;
import java.util.ArrayList;
+import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.apache.commons.lang3.StringUtils.equalsIgnoreCase;
-import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.*;
+import static org.hamcrest.Matchers.*;
+import static org.mockito.ArgumentMatchers.nullable;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyBoolean;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Matchers.argThat;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Matchers.isNull;
import static org.mockito.Mockito.*;
+import static org.onap.vid.utils.Unchecked.toURI;
import static org.testng.Assert.*;
@ContextConfiguration(classes = {LocalWebConfig.class, SystemProperties.class})
@WebAppConfiguration
public class AaiClientTest {
+ private final String NO_LCP_REGION_AND_TENANTS_MSG = "A&AI has no LCP Region & Tenants associated to subscriber 'subscriberId' and service type 'serviceType'";
private AaiClient aaiClientMock;
private ServletContext servletContext;
@BeforeMethod
- public void initMocks() {
+ public void initMocks(){
aaiClientMock = mock(AaiClient.class);
aaiClientMock.logger = mock(EELFLoggerDelegate.class);
+ aaiClientMock.objectMapper = new ObjectMapper();
servletContext = mock(ServletContext.class);
when(servletContext.getRealPath(any(String.class))).thenReturn("");
- when(aaiClientMock.doAaiGet(any(String.class), any(Boolean.class))).thenReturn(null);
+ when(aaiClientMock.doAaiGet(any(String.class),any(Boolean.class))).thenReturn(null);
+ when(aaiClientMock.doAaiGet(any(URI.class), anyBoolean(), anyBoolean())).thenReturn(null);
}
@DataProvider
public static Object[][] logicalLinkData() {
- return new Object[][]{
+ return new Object[][] {
{"", "network/logical-links/logical-link/"},
{"link", "network/logical-links/logical-link/link"}
};
@@ -111,26 +100,21 @@ public class AaiClientTest {
when(aaiClientMock.getLogicalLink(any(String.class))).thenCallRealMethod();
aaiClientMock.getLogicalLink(link);
- Mockito.verify(aaiClientMock).doAaiGet(argThat(s -> equalsIgnoreCase(s, expectedUrl)), any(Boolean.class));
+ verify(aaiClientMock).doAaiGet(argThat(s -> equalsIgnoreCase(s, expectedUrl)),any(Boolean.class));
}
@DataProvider
public static Object[][] subscribersResults() {
- return new Object[][]{
- {new SubscriberList(new ArrayList<Subscriber>() {{
- add(new Subscriber());
- add(new Subscriber());
- }}), true},
- {new SubscriberList(new ArrayList<Subscriber>() {{
- add(new Subscriber());
- }}), true},
+ return new Object[][] {
+ {new SubscriberList(new ArrayList<Subscriber>() {{ add(new Subscriber()); add(new Subscriber()); }}), true},
+ {new SubscriberList(new ArrayList<Subscriber>() {{ add(new Subscriber()); }}), true},
{new SubscriberList(new ArrayList<Subscriber>()), false}
};
}
@Test(dataProvider = "subscribersResults")
- public void testProbeAaiGetAllSubscribers_returnsTwoToZeroSubscribers_ResultsAsExpected(SubscriberList subscribers, boolean isAvailable) {
- ExternalComponentStatus expectedStatus = new ExternalComponentStatus(ExternalComponentStatus.Component.AAI, isAvailable, new HttpRequestMetadata(
+ public void testProbeAaiGetAllSubscribers_returnsTwoToZeroSubscribers_ResultsAsExpected(SubscriberList subscribers, boolean isAvailable){
+ ExternalComponentStatus expectedStatus = new ExternalComponentStatus(ExternalComponentStatus.Component.AAI,isAvailable, new HttpRequestMetadata(
HttpMethod.GET,
200,
"url",
@@ -143,9 +127,79 @@ public class AaiClientTest {
HttpMethod.GET, "url", new AaiResponse<>(subscribers, null, 200),
"rawData"));
Mockito.when(aaiClientMock.probeAaiGetAllSubscribers()).thenCallRealMethod();
- ExternalComponentStatus result = aaiClientMock.probeAaiGetAllSubscribers();
- assertThat(statusDataReflected(result), is(statusDataReflected(expectedStatus)));
- assertThat(requestMetadataReflected(result.getMetadata()), is(requestMetadataReflected(expectedStatus.getMetadata())));
+ ExternalComponentStatus result = aaiClientMock.probeAaiGetAllSubscribers();
+ assertThat(statusDataReflected(result),is(statusDataReflected(expectedStatus)));
+ assertThat(requestMetadataReflected(result.getMetadata()),is(requestMetadataReflected(expectedStatus.getMetadata())));
+ }
+
+ @Test(expectedExceptions = Exception.class)
+ public void typedAaiGet_aaiRestInterfaceRestGetReturnsError_exceptionIsThrown() {
+ AAIRestInterface aaiRestInterface = mock(AAIRestInterface.class);
+ final ResponseWithRequestInfo responseWithRequestInfo = mockedResponseWithRequestInfo(Response.Status.INTERNAL_SERVER_ERROR, "entity");
+ mockForGetRequest(aaiRestInterface, responseWithRequestInfo);
+ final AaiClient aaiClient = new AaiClient(aaiRestInterface, null, null);
+
+ try {
+
+ aaiClient.typedAaiGet(toURI("/irrelevant/url"), RelatedToProperty.class);
+
+ } catch (Exception e) {
+ assertThat(ExceptionUtils.getStackTrace(e), e, instanceOf(ExceptionWithRequestInfo.class));
+ ExceptionWithRequestInfo e2 = ((ExceptionWithRequestInfo) e);
+ assertThat(e2.getHttpCode(), is(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
+ assertThat(e2.getRawData(), is("entity"));
+ assertThat(e2.getHttpMethod(), is(HttpMethod.GET));
+ assertThat(e2.getRequestedUrl(), is("/my/mocked/url"));
+
+ throw e;
+ }
+ }
+
+ @Test(expectedExceptions = Exception.class)
+ public void typedAaiGet_aaiRestInterfaceRestGetReturnsInparsableResponse_exceptionIsThrown() {
+ AAIRestInterface aaiRestInterface = mock(AAIRestInterface.class);
+ final ResponseWithRequestInfo responseWithRequestInfo = mockedResponseWithRequestInfo(Response.Status.OK, "entity");
+ mockForGetRequest(aaiRestInterface, responseWithRequestInfo);
+ final AaiClient aaiClient = new AaiClient(aaiRestInterface, null, null);
+
+ try {
+
+ aaiClient.typedAaiGet(toURI("/irrelevant/url"), RelatedToProperty.class);
+
+ } catch (Exception e) {
+ assertThat(ExceptionUtils.getStackTrace(e), e, instanceOf(ExceptionWithRequestInfo.class));
+ assertThat(e.getCause(),
+ hasProperty("cause", is(instanceOf(com.fasterxml.jackson.core.JsonParseException.class)))
+ );
+ throw e;
+ }
+ }
+
+ @Test
+ public void typedAaiGet_aaiRestInterfaceRestGetReturns_objectIsFine() {
+ AAIRestInterface aaiRestInterface = mock(AAIRestInterface.class);
+ final ResponseWithRequestInfo responseWithRequestInfo = mockedResponseWithRequestInfo(Response.Status.OK,
+ "{ \"property-key\": \"foo\", \"property-value\": \"bar\" }");
+ mockForGetRequest(aaiRestInterface, responseWithRequestInfo);
+
+ final AaiClient aaiClient = new AaiClient(aaiRestInterface, null, null);
+
+ final RelatedToProperty relatedToPropertyAaiResponse = aaiClient.typedAaiGet(toURI("/irrelevant/url"), RelatedToProperty.class);
+
+ assertThat(relatedToPropertyAaiResponse.getPropertyKey(), is("foo"));
+ assertThat(relatedToPropertyAaiResponse.getPropertyValue(), is("bar"));
+ }
+
+ private ResponseWithRequestInfo mockedResponseWithRequestInfo(Response.Status status, String entity) {
+ return mockedResponseWithRequestInfo(status, entity, "/my/mocked/url", HttpMethod.GET);
+ }
+
+ private ResponseWithRequestInfo mockedResponseWithRequestInfo(Response.Status status, String entity, String requestUrl, HttpMethod method) {
+ final Response mockResponse = mock(Response.class);
+ when(mockResponse.getStatus()).thenReturn(status.getStatusCode());
+ when(mockResponse.getStatusInfo()).thenReturn(status);
+ when(mockResponse.readEntity(String.class)).thenReturn(entity);
+ return new ResponseWithRequestInfo(mockResponse, requestUrl, method);
}
//serialize fields except of fields we cannot know ahead of time
@@ -164,12 +218,12 @@ public class AaiClientTest {
@DataProvider
public static Object[][] rawData() {
return new Object[][]{
- {"errorMessage",}, {""}, {null}
+ {"errorMessage", }, {""}, {null}
};
}
@Test(dataProvider = "rawData")
- public void testProbeAaiGetFullSubscribersWithNullResponse_returnsNotAvailableWithErrorRawData(String rawData) {
+ public void testProbeAaiGetFullSubscribersWithNullResponse_returnsNotAvailableWithErrorRawData(String rawData){
Mockito.when(aaiClientMock.getAllSubscribers(true)).thenReturn(
new AaiResponseWithRequestInfo<>(HttpMethod.GET, "url", null,
rawData));
@@ -180,7 +234,7 @@ public class AaiClientTest {
@DataProvider
public static Object[][] exceptions() {
- return new Object[][]{
+ return new Object[][] {
{"NullPointerException", "errorMessage",
new ExceptionWithRequestInfo(HttpMethod.GET, "url",
"errorMessage", null, new NullPointerException())},
@@ -193,7 +247,7 @@ public class AaiClientTest {
}
@Test(dataProvider = "exceptions")
- public void testProbeAaiGetFullSubscribersWithNullResponse_returnsNotAvailableWithErrorRawData(String description, String expectedRawData, Exception exception) {
+ public void testProbeAaiGetFullSubscribersWithNullResponse_returnsNotAvailableWithErrorRawData(String description, String expectedRawData, Exception exception){
Mockito.when(aaiClientMock.getAllSubscribers(true)).thenThrow(exception);
ExternalComponentStatus result = callProbeAaiGetAllSubscribersAndAssertNotAvailable();
if (exception instanceof ExceptionWithRequestInfo) {
@@ -205,7 +259,7 @@ public class AaiClientTest {
private ExternalComponentStatus callProbeAaiGetAllSubscribersAndAssertNotAvailable() {
Mockito.when(aaiClientMock.probeAaiGetAllSubscribers()).thenCallRealMethod();
- ExternalComponentStatus result = aaiClientMock.probeAaiGetAllSubscribers();
+ ExternalComponentStatus result = aaiClientMock.probeAaiGetAllSubscribers();
assertFalse(result.isAvailable());
return result;
}
@@ -226,56 +280,55 @@ public class AaiClientTest {
assertEquals(response.getErrorMessage(), "{\"statusText\":\" Failed to retrieve LCP Region & Tenants from A&AI, Subscriber ID or Service Type is missing.\"}");
}
- @Test
+ @Test(expectedExceptions = AaiClient.ParsingGetTenantsResponseFailure.class, expectedExceptionsMessageRegExp = NO_LCP_REGION_AND_TENANTS_MSG)
public void getTenants_Arguments_Are_Valid_But_Tenants_Not_Exist() {
- when(aaiClientMock.getTenants(any(String.class), any(String.class))).thenCallRealMethod();
+ when(aaiClientMock.getTenantsNonCached(any(String.class),any(String.class))).thenCallRealMethod();
Response generalEmptyResponse = mock(Response.class);
- when(aaiClientMock.doAaiGet(any(String.class), any(Boolean.class))).thenReturn(generalEmptyResponse);
+ when(aaiClientMock.doAaiGet(any(String.class),any(Boolean.class))).thenReturn(generalEmptyResponse);
- AaiResponse response = aaiClientMock.getTenants("subscriberId", "serviceType");
-
- assertEquals(response.getErrorMessage(), "{\"statusText\":\" A&AI has no LCP Region & Tenants associated to subscriber 'subscriberId' and service type 'serviceType'\"}");
+ aaiClientMock.getTenantsNonCached("subscriberId", "serviceType");
+ }
+ @Test
+ public void whenCacheThrowException_thenGetTenantReturnAaiResponse() {
+ CacheProvider mockCacheProvider = mock(CacheProvider.class);
+ CacheProvider.Cache mockCache = mock(CacheProvider.Cache.class);
+ AaiClient aaiClientUnderTest = new AaiClient(null, null, mockCacheProvider);
+
+ when(mockCacheProvider.aaiClientCacheFor(any(), any())).thenReturn(mockCache);
+ when(mockCache.get(any())).thenThrow(new AaiClient.ParsingGetTenantsResponseFailure(NO_LCP_REGION_AND_TENANTS_MSG));
+ AaiResponse aaiResponse = aaiClientUnderTest.getTenants("subscriberId", "serviceType");
+ assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, aaiResponse.getHttpCode());
+ assertEquals("{\"statusText\":\""+NO_LCP_REGION_AND_TENANTS_MSG+"\"}", aaiResponse.getErrorMessage());
}
@Test
public void getTenants_Arguments_Are_Valid_Get_The_Tenanats() {
- when(aaiClientMock.getTenants(any(String.class), any(String.class))).thenCallRealMethod();
+ when(aaiClientMock.getTenantsNonCached(any(String.class),any(String.class))).thenCallRealMethod();
Response generalEmptyResponse = mock(Response.class);
when(generalEmptyResponse.readEntity(String.class)).thenReturn(tenantResponseRaw);
when(generalEmptyResponse.getStatus()).thenReturn(200);
- when(generalEmptyResponse.getStatusInfo()).thenReturn(new Response.StatusType() {
- @Override
- public int getStatusCode() {
- return 200;
- }
+ when(generalEmptyResponse.getStatusInfo()).thenReturn(Response.Status.OK);
- @Override
- public Response.Status.Family getFamily() {
- return Response.Status.Family.SUCCESSFUL;
- }
- @Override
- public String getReasonPhrase() {
- return null;
- }
- });
+ when(aaiClientMock.doAaiGet(any(String.class),any(Boolean.class))).thenReturn(generalEmptyResponse);
+ AaiResponse<GetTenantsResponse[]> response = aaiClientMock.getTenantsNonCached("subscriberId", "serviceType");
- when(aaiClientMock.doAaiGet(any(String.class), any(Boolean.class))).thenReturn(generalEmptyResponse);
+ GetTenantsResponse[] tenants = response.getT();
- AaiResponse<GetTenantsResponse[]> response = aaiClientMock.getTenants("subscriberId", "serviceType");
+ Assert.assertTrue(response.t.length> 0);
- Assert.assertTrue(response.t.length > 0);
+ Assert.assertEquals(tenants[0].cloudOwner,"att-aic-cloud-owner");
}
- final String tenantResponseRaw = "" +
+ final String tenantResponseRaw ="" +
"{" +
"\"service-type\": \"VIRTUAL USP\"," +
"\"resource-version\": \"1494001841964\"," +
@@ -285,7 +338,7 @@ public class AaiClientTest {
"\"related-link\": \"/aai/v11/cloud-infrastructure/cloud-regions/cloud-region/att-aic/AAIAIC25/tenants/tenant/092eb9e8e4b7412e8787dd091bc58e86\"," +
"\"relationship-data\": [{" +
"\"relationship-key\": \"cloud-region.cloud-owner\"," +
- "\"relationship-value\": \"att-aic\"" +
+ "\"relationship-value\": \"att-aic-cloud-owner\"" +
"}," +
"{" +
"\"relationship-key\": \"cloud-region.cloud-region-id\"," +
@@ -304,51 +357,179 @@ public class AaiClientTest {
"}" +
"}";
+ final String vfModuleHomingResponseRaw ="{" +
+ " \"vf-module-id\": \"ed02354a-3217-45ce-a1cd-e0b69b7a8cea\"," +
+ " \"vf-module-name\": \"apndns_az_02_module_1\"," +
+ " \"heat-stack-id\": \"apndns_az_02_module_1/97a319f3-b095-4fff-befa-c657508ecaf8\"," +
+ " \"orchestration-status\": \"active\"," +
+ " \"is-base-vf-module\": false," +
+ " \"resource-version\": \"1530559380383\"," +
+ " \"model-invariant-id\": \"74450b48-0aa0-4743-8314-9163e92b7862\"," +
+ " \"model-version-id\": \"6bc01a2b-bc48-4991-b9fe-e22c2215d801\"," +
+ " \"model-customization-id\": \"74f638c2-0368-4212-8f73-e961005af17c\"," +
+ " \"module-index\": 0," +
+ " \"relationship-list\": {" +
+ " \"relationship\": [" +
+ " {" +
+ " \"related-to\": \"l3-network\"," +
+ " \"relationship-label\": \"org.onap.relationships.inventory.DependsOn\"," +
+ " \"related-link\": \"/aai/v12/network/l3-networks/l3-network/335e62be-73a3-41e8-930b-1a677bcafea5\"," +
+ " \"relationship-data\": [" +
+ " {" +
+ " \"relationship-key\": \"l3-network.network-id\"," +
+ " \"relationship-value\": \"335e62be-73a3-41e8-930b-1a677bcafea5\"" +
+ " }" +
+ " ]," +
+ " \"related-to-property\": [" +
+ " {" +
+ " \"property-key\": \"l3-network.network-name\"," +
+ " \"property-value\": \"MNS-FN-25180-T-02Shared_oam_protected_net_1\"" +
+ " }" +
+ " ]" +
+ " }," +
+ " {" +
+ " \"related-to\": \"l3-network\"," +
+ " \"relationship-label\": \"org.onap.relationships.inventory.DependsOn\"," +
+ " \"related-link\": \"/aai/v12/network/l3-networks/l3-network/2db4ee3e-2ac7-4fc3-8739-ecf53416459e\"," +
+ " \"relationship-data\": [" +
+ " {" +
+ " \"relationship-key\": \"l3-network.network-id\"," +
+ " \"relationship-value\": \"2db4ee3e-2ac7-4fc3-8739-ecf53416459e\"" +
+ " }" +
+ " ]," +
+ " \"related-to-property\": [" +
+ " {" +
+ " \"property-key\": \"l3-network.network-name\"," +
+ " \"property-value\": \"Mobisupport-FN-27099-T-02_int_apn_dns_net_1\"" +
+ " }" +
+ " ]" +
+ " }," +
+ " {" +
+ " \"related-to\": \"volume-group\"," +
+ " \"relationship-label\": \"org.onap.relationships.inventory.Uses\"," +
+ " \"related-link\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/att-aic/rdm5b/volume-groups/volume-group/66013ebe-0c81-44b9-a24f-7c6acba73a39\"," +
+ " \"relationship-data\": [" +
+ " {" +
+ " \"relationship-key\": \"cloud-region.cloud-owner\"," +
+ " \"relationship-value\": \"att-aic\"" +
+ " }," +
+ " {" +
+ " \"relationship-key\": \"cloud-region.cloud-region-id\"," +
+ " \"relationship-value\": \"rdm5b\"" +
+ " }," +
+ " {" +
+ " \"relationship-key\": \"volume-group.volume-group-id\"," +
+ " \"relationship-value\": \"66013ebe-0c81-44b9-a24f-7c6acba73a39\"" +
+ " }" +
+ " ]" +
+ " }," +
+ " {" +
+ " \"related-to\": \"vserver\"," +
+ " \"relationship-label\": \"org.onap.relationships.inventory.Uses\"," +
+ " \"related-link\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/att-aic/rdm5b/tenants/tenant/db1818f7f2e34862b378bfb2cc520f91/vservers/vserver/5eef9f6d-9933-4bc6-9a1a-862d61309437\"," +
+ " \"relationship-data\": [" +
+ " {" +
+ " \"relationship-key\": \"cloud-region.cloud-owner\"," +
+ " \"relationship-value\": \"att-aic\"" +
+ " }," +
+ " {" +
+ " \"relationship-key\": \"cloud-region.cloud-region-id\"," +
+ " \"relationship-value\": \"rdm5b\"" +
+ " }," +
+ " {" +
+ " \"relationship-key\": \"tenant.tenant-id\"," +
+ " \"relationship-value\": \"db1818f7f2e34862b378bfb2cc520f91\"" +
+ " }," +
+ " {" +
+ " \"relationship-key\": \"vserver.vserver-id\"," +
+ " \"relationship-value\": \"5eef9f6d-9933-4bc6-9a1a-862d61309437\"" +
+ " }" +
+ " ]," +
+ " \"related-to-property\": [" +
+ " {" +
+ " \"property-key\": \"vserver.vserver-name\"," +
+ " \"property-value\": \"zrdm5bfapn01dns002\"" +
+ " }" +
+ " ]" +
+ " }" +
+ " ]" +
+ " }" +
+ "}";
+ @Test
+ public void get_homingDataForVfModule() {
+ when(aaiClientMock.getHomingDataByVfModule(any(String.class), any(String.class))).thenCallRealMethod();
+
+ Response homingResponse = mock(Response.class);
+
+ when(homingResponse.readEntity(String.class)).thenReturn(vfModuleHomingResponseRaw);
+ when(homingResponse.getStatus()).thenReturn(200);
+ when(homingResponse.getStatusInfo()).thenReturn(Response.Status.OK);
+
+
+ when(aaiClientMock.doAaiGet(any(String.class), any(Boolean.class))).thenReturn(homingResponse);
+
+ GetTenantsResponse tenant = aaiClientMock.getHomingDataByVfModule("vnfInstanceId", "vfModuleId");
+
+ Assert.assertEquals(tenant.cloudOwner,"att-aic");
+ Assert.assertEquals(tenant.cloudRegionID,"rdm5b");
+ Assert.assertEquals(tenant.tenantID,"db1818f7f2e34862b378bfb2cc520f91");
+
+ }
+ @Test(expectedExceptions = GenericUncheckedException.class, expectedExceptionsMessageRegExp = "A&AI has no homing data associated to vfModule 'vfModuleId' of vnf 'vnfInstanceId'")
+ public void getVfMoudule_Homing_Arguments_Are_Valid_But_Not_Exists() {
+ when(aaiClientMock.getHomingDataByVfModule(any(String.class), any(String.class))).thenCallRealMethod();
+
+ Response generalEmptyResponse = mock(Response.class);
+ when(aaiClientMock.doAaiGet(any(String.class),any(Boolean.class))).thenReturn(generalEmptyResponse);
+
+ aaiClientMock.getHomingDataByVfModule("vnfInstanceId", "vfModuleId");
+ }
+
@DataProvider
- public static Object[][] resourceTypesProvider() {
- return new Object[][]{
- {"service-instance", ResourceType.SERVICE_INSTANCE},
- {"generic-vnf", ResourceType.GENERIC_VNF},
- {"vf-module", ResourceType.VF_MODULE}
+ public static Object[][] invalidDataId() {
+ return new String[][] {
+ {""},
+ {null}
};
}
- @Test(dataProvider = "resourceTypesProvider")
- public void aaiNodeQueryResponseDeserializationTest(String resourceType, ResourceType expectedResourceType) throws IOException {
- String link = "/aai/v12/business/customers/customer/a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb/service-subscriptions/service-subscription/Nimbus/service-instances/service-instance/7131d483-b450-406f-8e30-0c650645fc67";
- String json =
- "{\"result-data\": [{" +
- "\"resource-type\": \"" + resourceType + "\"," +
- "\"resource-link\": \"" + link + "\"" +
- "}]}";
-
- AaiNodeQueryResponse nodeQueryResponse = new ObjectMapper().readValue(json, AaiNodeQueryResponse.class);
- assertThat(nodeQueryResponse.resultData.get(0).resourceLink, equalTo(link));
- assertThat(nodeQueryResponse.resultData.get(0).resourceType, is(expectedResourceType));
+ @Test(dataProvider = "invalidDataId", expectedExceptions = GenericUncheckedException.class, expectedExceptionsMessageRegExp = "Failed to retrieve homing data associated to vfModule from A&AI, VNF InstanceId or VF Module Id is missing.")
+ public void getVfMoudule_Homing_Arguments_Are_Empty_Or_Null(String data) {
+ when(aaiClientMock.getHomingDataByVfModule(any(), any())).thenCallRealMethod();
+ aaiClientMock.getHomingDataByVfModule(data, data);
}
- @Test
- public void aaiNodeQueryEmptyResponseDeserializationTest() throws IOException {
- String json = "{}";
- AaiNodeQueryResponse nodeQueryResponse = new ObjectMapper().readValue(json, AaiNodeQueryResponse.class);
- assertNull(nodeQueryResponse.resultData);
+ @DataProvider
+ public static Object[][] resourceTypesProvider() {
+ return new Object[][] {
+ {"service-instance", ResourceType.SERVICE_INSTANCE},
+ {"generic-vnf", ResourceType.GENERIC_VNF},
+ {"vf-module", ResourceType.VF_MODULE}
+ };
}
@DataProvider
public static Object[][] nameAndResourceTypeProvider() {
- return new Object[][]{
- {"SRIOV_SVC", ResourceType.SERVICE_INSTANCE, "search/nodes-query?search-node-type=service-instance&filter=service-instance-name:EQUALS:SRIOV_SVC"},
- {"b1707vidnf", ResourceType.GENERIC_VNF, "search/nodes-query?search-node-type=generic-vnf&filter=vnf-name:EQUALS:b1707vidnf"},
- {"connectivity_test", ResourceType.VF_MODULE, "search/nodes-query?search-node-type=vf-module&filter=vf-module-name:EQUALS:connectivity_test"},
- {"MjVg1234", ResourceType.VOLUME_GROUP, "search/nodes-query?search-node-type=volume-group&filter=volume-group-name:EQUALS:MjVg1234"}
+ return new Object[][] {
+ {"SRIOV_SVC", ResourceType.SERVICE_INSTANCE, "nodes/service-instances?service-instance-name=SRIOV_SVC"},
+ {"b1707vidnf", ResourceType.GENERIC_VNF, "nodes/generic-vnfs?vnf-name=b1707vidnf"},
+ {"connectivity_test", ResourceType.VF_MODULE, "nodes/vf-modules?vf-module-name=connectivity_test"},
+ {"ByronPace", ResourceType.INSTANCE_GROUP, "nodes/instance-groups?instance-group-name=ByronPace"},
+ {"MjVg1234", ResourceType.VOLUME_GROUP, "nodes/volume-groups?volume-group-name=MjVg1234"}
};
}
@Test(dataProvider = "nameAndResourceTypeProvider")
public void whenSearchNodeTypeByName_callRightAaiPath(String name, ResourceType type, String expectedUrl) {
- when(aaiClientMock.searchNodeTypeByName(any(String.class), any(ResourceType.class))).thenCallRealMethod();
- aaiClientMock.searchNodeTypeByName(name, type);
- Mockito.verify(aaiClientMock).doAaiGet(eq(expectedUrl), eq(false));
+ AAIRestInterface aaiRestInterface = mock(AAIRestInterface.class);
+ ResponseWithRequestInfo responseWithRequestInfo = mockedResponseWithRequestInfo(Response.Status.OK, "{}");
+
+ when(aaiRestInterface.RestGet(anyString(), anyString(), eq(toURI(expectedUrl)), anyBoolean(), anyBoolean()))
+ .thenReturn(responseWithRequestInfo);
+
+ AaiClient aaiClient = new AaiClient(aaiRestInterface, null, null);
+
+ aaiClient.isNodeTypeExistsByName(name, type);
}
@DataProvider
@@ -381,20 +562,20 @@ public class AaiClientTest {
// Exception out of javax's Client
Pair.of(SSLHandshakeException.class, (httpsAuthClientMock, javaxClientMock) -> {
- when(javaxClientMock.target(anyString())).thenThrow(
+ when(javaxClientMock.target(nullable(String.class))).thenThrow(
new ProcessingException(new SSLHandshakeException("Received fatal alert: certificate_expired"))
);
}),
Pair.of(SunCertPathBuilderException.class, (httpsAuthClientMock, javaxClientMock) -> {
SunCertPathBuilderException e0 = new SunCertPathBuilderException("unable to find valid certification path to requested target");
- when(javaxClientMock.target(anyString())).thenThrow(
+ when(javaxClientMock.target(nullable(String.class))).thenThrow(
new ProcessingException(new ValidatorException("PKIX path building failed: " + e0.toString(), e0))
);
}),
Pair.of(GenericUncheckedException.class, (httpsAuthClientMock, javaxClientMock) ->
- when(javaxClientMock.target(anyString())).thenThrow(new GenericUncheckedException("basa")))
+ when(javaxClientMock.target(nullable(String.class))).thenThrow(new GenericUncheckedException("basa")))
).flatMap(l -> Stream.of(
// double each case to propagateExceptions = true/false, to verify that "don't propagate" really still work
@@ -426,8 +607,8 @@ public class AaiClientTest {
Response responseMock = mocks.getFakeResponse();
// prepare real AAIRestInterface and AaiClient, and wire mocks
- AAIRestInterface aaiRestInterface = new AAIRestInterface(httpsAuthClientMock, new ServletRequestHelper(), new SystemPropertyHelper());
- final AaiClient aaiClient = new AaiClient(aaiRestInterface, null);
+ AAIRestInterface aaiRestInterface = new AAIRestInterface(httpsAuthClientMock, mock(ServletRequestHelper.class), mock(SystemPropertyHelper.class));
+ final AaiClient aaiClient = new AaiClient(aaiRestInterface, null, null);
when(httpsAuthClientMock.getClient(any())).thenReturn(javaxClientMock);
// define atomic method under test, including reset of "aaiRestInterface.client"
@@ -465,6 +646,121 @@ public class AaiClientTest {
assertFalse(propagateExceptions, "calling doAaiGet when propagateExceptions is 'true' must result with an exception (in this test)");
}
+ @DataProvider
+ public static Object[][] aaiClientGetCloudOwnerByCloudRegionId() {
+
+ final String cloudRegion = "{" +
+ " \"cloud-owner\": \"mure-royo-ru22\"," +
+ " \"cloud-region-id\": \"ravitu\"," +
+ " \"cloud-type\": \"openstack\"," +
+ " \"resource-version\": \"1523631256125\"," +
+ " \"relationship-list\": {" +
+ " \"relationship\": [{" +
+ " \"related-to\": \"pserver\"" +
+ " }" +
+ " ]" +
+ " }" +
+ " }";
+
+ String bodyWith0 = "{ \"cloud-region\": [" + " ]}";
+ String bodyWith1 = "{ \"cloud-region\": [" + cloudRegion + " ]}";
+ String bodyWith2 = "{ \"cloud-region\": [" + cloudRegion + ", " + cloudRegion + " ]}";
+ String bodyWithDifferent2 = "{ \"cloud-region\": [" + cloudRegion + ", " +
+ cloudRegion.replace("mure-royo-ru22", "nolay-umaxo") +
+ "]}";
+
+ return new Object[][] {
+ { "regular single result", bodyWith1, false },
+ { "exceptional empty result", bodyWith0, true },
+ { "two same results", bodyWith2, false },
+ { "two incoherent results", bodyWithDifferent2, true },
+ };
+ }
+
+ @Test(dataProvider = "aaiClientGetCloudOwnerByCloudRegionId")
+ public void getCloudOwnerByCloudRegionIdNonCached(String desc, String body, boolean expectingException) {
+ final String cloudRegion = "ravitu";
+ AAIRestInterface aaiRestInterface = mock(AAIRestInterface.class);
+ final ResponseWithRequestInfo responseWithRequestInfo = mockedResponseWithRequestInfo(Response.Status.OK, body);
+ when(aaiRestInterface.doRest(anyString(), anyString(), eq(Unchecked.toURI("cloud-infrastructure/cloud-regions?cloud-region-id=" + cloudRegion)),
+ isNull(), eq(HttpMethod.GET), anyBoolean(), anyBoolean()))
+ .thenReturn(responseWithRequestInfo);
+
+ final AaiClient aaiClient = new AaiClient(aaiRestInterface, null, null);
+
+ try {
+ final String result = aaiClient.getCloudOwnerByCloudRegionIdNonCached(cloudRegion);
+ if (expectingException) fail("expected failure on " + desc + ", got " + result);
+ else {
+ assertThat(result, is("mure-royo-ru22"));
+ }
+ } catch (Exception e) {
+ if (!expectingException) throw e;
+ else {
+ assertThat(e.toString(), either(
+ containsString("No cloud-owner found for " + cloudRegion))
+ .or(containsString("Conflicting cloud-owner found for " + cloudRegion)));
+ }
+ }
+ }
+
+ @DataProvider
+ public static Object[][] cloudRegionAndTenantDataProvider() {
+ return new Object[][] {
+ { "APPC-24595-T-IST-02C", "mtn23b" },
+ { "APPC-24595-T-IST-02C", null },
+ { null, "mtn23b" },
+ { null, null },
+ };
+ }
+
+ @Test(dataProvider = "cloudRegionAndTenantDataProvider")
+ public void getCloudRegionAndTenantByVnfId(String tenantName, String cloudRegionId) throws JsonProcessingException {
+ SimpleResult tenant = new SimpleResult();
+ if (tenantName != null) {
+ tenant.setJsonNodeType("tenant");
+ Properties tenantProps = new Properties();
+ tenantProps.setTenantName(tenantName);
+ tenant.setJsonProperties(tenantProps);
+ }
+
+ SimpleResult cloudRegion = new SimpleResult();
+ if (cloudRegionId != null) {
+ cloudRegion.setJsonNodeType("cloud-region");
+ Properties cloudRegionProps = new Properties();
+ cloudRegionProps.setCloudRegionId(cloudRegionId);
+ cloudRegion.setJsonProperties(cloudRegionProps);
+ }
+
+ CustomQuerySimpleResult customQuerySimpleResult = new CustomQuerySimpleResult(ImmutableList.of(tenant, cloudRegion));
+ String mockedBody = new ObjectMapper().writeValueAsString(customQuerySimpleResult);
+
+ AAIRestInterface aaiRestInterface = mock(AAIRestInterface.class);
+ final ResponseWithRequestInfo responseWithRequestInfo = mockedResponseWithRequestInfo(Response.Status.OK, mockedBody, "query?format=simple", HttpMethod.PUT);
+ when(aaiRestInterface.doRest(anyString(), anyString(), eq(Unchecked.toURI("query?format=simple")),
+ any(), eq(HttpMethod.PUT), anyBoolean(), anyBoolean()))
+ .thenReturn(responseWithRequestInfo);
+
+ final AaiClient aaiClient = new AaiClient(aaiRestInterface, null, null);
+ Map<String, Properties> result = aaiClient.getCloudRegionAndTenantByVnfId("anyVnfId");
+ if (tenantName != null) {
+ assertEquals(result.get("tenant").getTenantName(), tenantName);
+ } else {
+ assertNull(result.get("tenant"));
+ }
+
+ if (cloudRegionId != null) {
+ assertEquals(result.get("cloud-region").getCloudRegionId(), cloudRegionId);
+ } else {
+ assertNull(result.get("cloud-region"));
+ }
+ }
+
+ protected void mockForGetRequest(AAIRestInterface aaiRestInterface, ResponseWithRequestInfo responseWithRequestInfo) {
+ when(aaiRestInterface.doRest(anyString(), anyString(), any(URI.class), isNull(), eq(HttpMethod.GET) ,anyBoolean(), anyBoolean()))
+ .thenReturn(responseWithRequestInfo);
+ }
+
@Test
public void shouldProperlyReadResponseOnceWhenSubscribersAreNotPresent() {
AAIRestInterface restInterface = mock(AAIRestInterface.class);
@@ -475,8 +771,8 @@ public class AaiClientTest {
when(response.getStatusInfo()).thenReturn(Response.Status.NOT_FOUND);
ResponseWithRequestInfo responseWithRequestInfo = new ResponseWithRequestInfo(response, "test", HttpMethod.GET);
when(restInterface.RestGet(eq("VidAaiController"), any(String.class),
- eq("business/customers?subscriber-type=INFRA&depth=0"), eq(false), eq(true))).thenReturn(responseWithRequestInfo);
- AaiClient aaiClient = new AaiClient(restInterface, portDetailsTranslator);
+ eq(Unchecked.toURI("business/customers?subscriber-type=INFRA&depth=0")), eq(false), eq(true))).thenReturn(responseWithRequestInfo);
+ AaiClient aaiClient = new AaiClient(restInterface, portDetailsTranslator, null);
aaiClient.getAllSubscribers(true);
@@ -497,4 +793,5 @@ public class AaiClientTest {
void acceptThrows(T t, U u) throws Exception;
}
+
}
diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/AaiOverTLSClientServerTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/AaiOverTLSClientServerTest.java
index d4f59e7da..da08ed866 100644
--- a/vid-app-common/src/test/java/org/onap/vid/aai/AaiOverTLSClientServerTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/aai/AaiOverTLSClientServerTest.java
@@ -34,7 +34,6 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
-import org.onap.vid.aai.model.AaiNodeQueryResponse;
import org.onap.vid.aai.model.ResourceType;
import org.onap.vid.client.SyncRestClient;
import org.onap.vid.model.SubscriberList;
@@ -50,31 +49,15 @@ public class AaiOverTLSClientServerTest {
private static StubServerUtil serverUtil;
- private String searchNodesQueryResponsePayload =
- "{\n"
- + "\"result-data\": [\n"
- + " {\n"
- + "\"resource-type\": \"generic-vnf\",\n"
- + "\"resource-link\": \"/aai/v13/network/generic-vnfs/generic-vnf/6eac8e69-c98d-4ac5-ab90-69fe0cabda76\"\n"
- + "},\n"
- + " {\n"
- + "\"resource-type\": \"generic-vnf\",\n"
- + "\"resource-link\": \"/aai/v13/network/generic-vnfs/generic-vnf/e3766bc5-40a7-4dbe-9d4a-1d8c8f284913\"\n"
- + "},\n"
- + " {\n"
- + "\"resource-type\": \"generic-vnf\",\n"
- + "\"resource-link\": \"/aai/v13/network/generic-vnfs/generic-vnf/6aa153ee-6637-4b49-beb5-a5e756e00393\"\n"
- + "},\n"
- + " {\n"
- + "\"resource-type\": \"generic-vnf\",\n"
- + "\"resource-link\": \"/aai/v13/network/generic-vnfs/generic-vnf/5a981c30-de25-4ea9-98fa-ed398f13ea41\"\n"
- + "},\n"
- + " {\n"
- + "\"resource-type\": \"generic-vnf\",\n"
- + "\"resource-link\": \"/aai/v13/network/generic-vnfs/generic-vnf/b0ef2271-8ac0-4268-b9a5-09cb50c20c85\"\n"
- + "}\n"
- + "],\n"
- + "}";
+ private String searchNodesQueryResponsePayload = "" +
+ "{" +
+ "\"result-data\": [" +
+ " {" +
+ " \"resource-type\": \"generic-vnf\"," +
+ " \"resource-link\": \"/aai/v13/network/generic-vnfs/generic-vnf/6eac8e69-c98d-4ac5-ab90-69fe0cabda76\"" +
+ " }" +
+ " ]" +
+ "}";
private String subscribersResponsePayload =
"{\n"
@@ -122,19 +105,17 @@ public class AaiOverTLSClientServerTest {
ObjectMapper objectMapper = getFasterXmlObjectMapper();
AaiOverTLSClient aaiOverTLSClient = new AaiOverTLSClient(new SyncRestClient(objectMapper), propertySupplier, serverUtil.constructTargetUrl("http", ""));
- serverUtil.prepareGetCall("/search/nodes-query", new JSONParser().parse(searchNodesQueryResponsePayload), Action.status(HttpStatus.OK_200));
+ serverUtil.prepareGetCall("/nodes/generic-vnfs", new JSONParser().parse(searchNodesQueryResponsePayload), Action.status(HttpStatus.OK_200));
- HttpResponse<AaiNodeQueryResponse> aaiNodeQueryResponseHttpResponse = aaiOverTLSClient
- .searchNodeTypeByName("any", ResourceType.GENERIC_VNF);
+ boolean aaiNodeQueryResponseHttpResponse = aaiOverTLSClient
+ .isNodeTypeExistsByName("any", ResourceType.GENERIC_VNF);
- AaiNodeQueryResponse body = aaiNodeQueryResponseHttpResponse.getBody();
- Assertions.assertThat(body.resultData.size()).isEqualTo(5);
- Assertions.assertThat(aaiNodeQueryResponseHttpResponse.getStatus()).isEqualTo(200);
+ Assertions.assertThat(aaiNodeQueryResponseHttpResponse).isEqualTo(true);
}
@Test
public void shouldGetSubscribers() throws ParseException, JsonProcessingException {
- ObjectMapper objectMapper = getCodehausObjectMapper();
+ ObjectMapper objectMapper = getFasterXmlObjectMapper();
AaiOverTLSClient aaiOverTLSClient = new AaiOverTLSClient(new SyncRestClient(objectMapper), propertySupplier, serverUtil.constructTargetUrl("http", ""));
serverUtil.prepareGetCall("/business/customers", new JSONParser().parse(subscribersResponsePayload), Action.status(HttpStatus.OK_200));
@@ -146,31 +127,6 @@ public class AaiOverTLSClientServerTest {
Assertions.assertThat(allSubscribers.getStatus()).isEqualTo(200);
}
- private ObjectMapper getCodehausObjectMapper() {
- return new ObjectMapper() {
-
- org.codehaus.jackson.map.ObjectMapper om = new org.codehaus.jackson.map.ObjectMapper();
-
- @Override
- public <T> T readValue(String s, Class<T> aClass) {
- try {
- return om.readValue(s, aClass);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- @Override
- public String writeValue(Object o) {
- try {
- return om.writeValueAsString(o);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
- };
- }
-
private ObjectMapper getFasterXmlObjectMapper() {
return new ObjectMapper() {
diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/AaiOverTLSClientTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/AaiOverTLSClientTest.java
index f281e84b6..52556a1a3 100644
--- a/vid-app-common/src/test/java/org/onap/vid/aai/AaiOverTLSClientTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/aai/AaiOverTLSClientTest.java
@@ -24,10 +24,10 @@ import com.google.common.collect.ImmutableMap;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
-import org.onap.vid.aai.model.AaiNodeQueryResponse;
import org.onap.vid.aai.model.ResourceType;
import org.onap.vid.client.SyncRestClient;
import org.onap.vid.model.SubscriberList;
@@ -41,11 +41,11 @@ import static org.mockito.ArgumentMatchers.eq;
@RunWith(MockitoJUnitRunner.class)
public class AaiOverTLSClientTest {
- private static final String SEARCH_NODES_QUERY_SEARCH_NODE_TYPE = "search/nodes-query?search-node-type=generic-vnf&filter=vnf-name:EQUALS:name";
+ private static final String SEARCH_NODES_QUERY_SEARCH_NODE_TYPE = "nodes/generic-vnfs?vnf-name=name";
private static final String SUBSCRIBERS = "business/customers?subscriber-type=INFRA&depth=0";
private AaiOverTLSClient aaiRestClient;
- @Mock
+ @Mock(answer = Answers.RETURNS_MOCKS)
private SyncRestClient syncRestClient;
@Mock
private AaiOverTLSPropertySupplier propertySupplier;
@@ -56,12 +56,12 @@ public class AaiOverTLSClientTest {
}
@Test
- public void testSearchNodeTypeByName() {
+ public void testIsNodeTypeExistsByName() {
mockPropertyReader();
- aaiRestClient.searchNodeTypeByName("name", ResourceType.GENERIC_VNF);
+ aaiRestClient.isNodeTypeExistsByName("name", ResourceType.GENERIC_VNF);
Mockito.verify(syncRestClient).get(contains(SEARCH_NODES_QUERY_SEARCH_NODE_TYPE),
- eq(getHeaders()), eq(Collections.emptyMap()), eq(AaiNodeQueryResponse.class));
+ eq(getHeaders()), eq(Collections.emptyMap()));
}
@Test
diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/OperationalEnvironmentTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/OperationalEnvironmentTest.java
index c2ccec008..3d649bb69 100644
--- a/vid-app-common/src/test/java/org/onap/vid/aai/OperationalEnvironmentTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/aai/OperationalEnvironmentTest.java
@@ -2,8 +2,6 @@ package org.onap.vid.aai;
import org.junit.Test;
import org.onap.vid.aai.model.RelationshipList;
-import java.util.*;
-import org.junit.Assert;
public class OperationalEnvironmentTest {
@@ -28,7 +26,7 @@ public class OperationalEnvironmentTest {
// default test
testSubject = createTestSubject();
- testSubject.setOperationalEnvironmentId(operationalEnvironmentId);
+ testSubject.setJsonOperationalEnvironmentId(operationalEnvironmentId);
}
@Test
@@ -48,7 +46,7 @@ public class OperationalEnvironmentTest {
// default test
testSubject = createTestSubject();
- testSubject.setOperationalEnvironmentName(operationalEnvironmentName);
+ testSubject.setJsonOperationalEnvironmentName(operationalEnvironmentName);
}
@Test
@@ -68,7 +66,7 @@ public class OperationalEnvironmentTest {
// default test
testSubject = createTestSubject();
- testSubject.setOperationalEnvironmentType(operationalEnvironmentType);
+ testSubject.setJsonOperationalEnvironmentType(operationalEnvironmentType);
}
@Test
@@ -88,7 +86,7 @@ public class OperationalEnvironmentTest {
// default test
testSubject = createTestSubject();
- testSubject.setOperationalEnvironmentStatus(operationalEnvironmentStatus);
+ testSubject.setJsonOperationalEnvironmentStatus(operationalEnvironmentStatus);
}
@Test
@@ -108,7 +106,7 @@ public class OperationalEnvironmentTest {
// default test
testSubject = createTestSubject();
- testSubject.setTenantContext(tenantContext);
+ testSubject.setJsonTenantContext(tenantContext);
}
@Test
@@ -128,7 +126,7 @@ public class OperationalEnvironmentTest {
// default test
testSubject = createTestSubject();
- testSubject.setWorkloadContext(workloadContext);
+ testSubject.setJsonWorkloadContext(workloadContext);
}
@Test
@@ -148,7 +146,7 @@ public class OperationalEnvironmentTest {
// default test
testSubject = createTestSubject();
- testSubject.setResourceVersion(resourceVersion);
+ testSubject.setJsonResourceVersion(resourceVersion);
}
@Test
@@ -168,7 +166,7 @@ public class OperationalEnvironmentTest {
// default test
testSubject = createTestSubject();
- testSubject.setRelationshipList(relationshipList);
+ testSubject.setJsonRelationshipList(relationshipList);
}
@Test
diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/VnfResultTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/VnfResultTest.java
index 2b7a60429..72a5e193e 100644
--- a/vid-app-common/src/test/java/org/onap/vid/aai/VnfResultTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/aai/VnfResultTest.java
@@ -1,10 +1,10 @@
package org.onap.vid.aai;
-import java.util.Map;
-
import org.junit.Test;
import org.onap.vid.aai.model.VnfResult;
+import java.util.Map;
+
public class VnfResultTest {
private VnfResult createTestSubject() {
@@ -29,6 +29,5 @@ public class VnfResultTest {
// default test
testSubject = createTestSubject();
- testSubject.setAdditionalProperty(name, value);
}
} \ No newline at end of file
diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/model/AaiGetPnfResponseTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/model/AaiGetPnfResponseTest.java
index 7b5b8aa39..d7394632a 100644
--- a/vid-app-common/src/test/java/org/onap/vid/aai/model/AaiGetPnfResponseTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/aai/model/AaiGetPnfResponseTest.java
@@ -1,15 +1,15 @@
package org.onap.vid.aai.model;
-import java.io.IOException;
-import java.util.ArrayList;
-
-import org.codehaus.jackson.map.ObjectMapper;
+import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
+import java.io.IOException;
+import java.util.ArrayList;
+
import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.core.StringContains.containsString;
import static org.hamcrest.core.IsEqual.equalTo;
+import static org.hamcrest.core.StringContains.containsString;
public class AaiGetPnfResponseTest {
diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/model/PnfPropertiesTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/model/PnfPropertiesTest.java
index e2a62c0e8..a59b52078 100644
--- a/vid-app-common/src/test/java/org/onap/vid/aai/model/PnfPropertiesTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/aai/model/PnfPropertiesTest.java
@@ -1,13 +1,11 @@
package org.onap.vid.aai.model;
-import org.codehaus.jackson.map.ObjectMapper;
+import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
-import java.util.ArrayList;
-import static com.google.code.beanmatchers.BeanMatchers.hasValidGettersAndSetters;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.StringContains.containsString;
diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/model/PnfResultTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/model/PnfResultTest.java
index 912eea9d7..4f2762c32 100644
--- a/vid-app-common/src/test/java/org/onap/vid/aai/model/PnfResultTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/aai/model/PnfResultTest.java
@@ -1,11 +1,11 @@
package org.onap.vid.aai.model;
-import java.io.IOException;
-
-import org.codehaus.jackson.map.ObjectMapper;
+import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
+import java.io.IOException;
+
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.StringContains.containsString;
diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/util/CacheConfigTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/util/CacheConfigTest.java
new file mode 100644
index 000000000..1faaee3aa
--- /dev/null
+++ b/vid-app-common/src/test/java/org/onap/vid/aai/util/CacheConfigTest.java
@@ -0,0 +1,32 @@
+package org.onap.vid.aai.util;
+
+import org.testng.annotations.Test;
+
+import static org.testng.AssertJUnit.assertEquals;
+
+public class CacheConfigTest {
+
+ @Test
+ public void whenDeserializeJson_ValuesReadAsExpected() {
+ CacheConfigProvider cacheConfigProvider = new CacheConfigProviderImpl();
+ CacheConfig cacheConfigA = cacheConfigProvider.getCacheConfig("a");
+ assertEquals(true, cacheConfigA.isActive());
+ assertEquals(6L, cacheConfigA.getExpireAfterWriteHours());
+ assertEquals(9L, cacheConfigA.getRefreshAfterWriteSeconds());
+
+ //entry exist in configuration, but with no values
+ CacheConfig cacheConfigB = cacheConfigProvider.getCacheConfig("b");
+ assertEquals(cacheConfigB.isActive(), CacheConfig.Companion.getDefaultCacheConfig().isActive());
+ assertEquals(cacheConfigB.getExpireAfterWriteHours(), CacheConfig.Companion.getDefaultCacheConfig().getExpireAfterWriteHours());
+ assertEquals(cacheConfigB.getRefreshAfterWriteSeconds(), CacheConfig.Companion.getDefaultCacheConfig().getRefreshAfterWriteSeconds());
+
+
+ //entry doesn't exist in configuration
+ CacheConfig cacheConfigC = cacheConfigProvider.getCacheConfig("c");
+ assertEquals(CacheConfig.Companion.getDefaultCacheConfig(), cacheConfigC);
+
+ CacheConfig cacheConfigD = cacheConfigProvider.getCacheConfig("d");
+ assertEquals(false, cacheConfigD.isActive());
+
+ }
+}
diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/util/CacheProviderTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/util/CacheProviderTest.java
new file mode 100644
index 000000000..95daf9038
--- /dev/null
+++ b/vid-app-common/src/test/java/org/onap/vid/aai/util/CacheProviderTest.java
@@ -0,0 +1,41 @@
+package org.onap.vid.aai.util;
+
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.hamcrest.Matchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.onap.vid.aai.util.CacheProvider.compileKey;
+import static org.onap.vid.aai.util.CacheProvider.decompileKey;
+
+public class CacheProviderTest {
+ @Test(dataProvider = "aaiClientCompileDecompileKeySameData")
+ public void compileDecompileKeySameTest(List<String> args) {
+ assertThat(decompileKey(compileKey(args)), is(args.toArray()));
+ }
+
+ @Test(dataProvider = "aaiClientCompileDecompileKeyDifferentData")
+ public void compileDecompileKeyDifferentTest(List<String> expectedResult, List<String> args) {
+ assertThat(decompileKey(compileKey(args)), is(expectedResult.toArray()));
+ }
+
+ @DataProvider
+ public static Object[][] aaiClientCompileDecompileKeySameData() {
+ return new Object[][] {
+ {Arrays.asList( "a", "b", "c")},
+ {Arrays.asList("a")},
+ {Arrays.asList("a!", "@#?b")},
+ {Arrays.asList("a", "", "c")}
+ };
+ }
+
+ @DataProvider
+ public static Object[][] aaiClientCompileDecompileKeyDifferentData() {
+ return new Object[][] {
+ {Arrays.asList("a", "", "c"), Arrays.asList("a", null, "c")}
+ };
+ }
+}
diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/util/CacheProviderWithLoadingCacheTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/util/CacheProviderWithLoadingCacheTest.java
new file mode 100644
index 000000000..9a9b28905
--- /dev/null
+++ b/vid-app-common/src/test/java/org/onap/vid/aai/util/CacheProviderWithLoadingCacheTest.java
@@ -0,0 +1,313 @@
+package org.onap.vid.aai.util;
+
+import com.google.common.cache.CacheBuilder;
+import com.google.common.collect.ImmutableList;
+import org.apache.commons.lang3.RandomUtils;
+import org.apache.commons.lang3.mutable.MutableInt;
+import org.apache.commons.lang3.reflect.FieldUtils;
+import org.apache.commons.lang3.tuple.Pair;
+import org.onap.vid.exceptions.GenericUncheckedException;
+import org.onap.vid.properties.Features;
+import org.testng.Assert;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+import org.togglz.core.manager.FeatureManager;
+
+import java.util.concurrent.TimeUnit;
+import java.util.function.Consumer;
+import java.util.function.Function;
+
+import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
+import static org.hamcrest.CoreMatchers.sameInstance;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.contains;
+import static org.hamcrest.Matchers.*;
+import static org.hamcrest.core.Is.is;
+import static org.mockito.Mockito.any;
+import static org.mockito.Mockito.*;
+import static org.testng.AssertJUnit.assertEquals;
+
+public class CacheProviderWithLoadingCacheTest {
+ private final FeatureManager featureManager = mock(FeatureManager.class);
+ private final CacheConfigProvider cacheConfigProvider = mock(CacheConfigProvider.class);
+
+ @BeforeMethod
+ public void activateCacheFeatureFlag() {
+ reset(featureManager);
+ when(featureManager.isActive(Features.FLAG_1810_AAI_LOCAL_CACHE)).thenReturn(true);
+ when(cacheConfigProvider.getCacheConfig(any())).thenReturn(CacheConfig.Companion.getDefaultCacheConfig());
+ }
+
+ private CacheProviderWithLoadingCache createNewCacheProvider() {
+ return new CacheProviderWithLoadingCache(featureManager, cacheConfigProvider);
+ }
+
+ private String RAND() {
+ return randomAlphanumeric(5);
+ }
+
+ @Test
+ public void cacheProvider_requestingCache_CreatesNewCache() {
+ final CacheProviderWithLoadingCache provider = createNewCacheProvider();
+ final CacheProvider.Cache<Integer, Integer> integerIntegerCache = provider.aaiClientCacheFor(RAND(), (Integer i) -> i + 4);
+
+ assertThat(integerIntegerCache, notNullValue());
+ assertThat(integerIntegerCache.get(5), is(9));
+ }
+
+ @Test
+ public void cacheProvider_requestingCacheSameNameTwice_ReturnsFirstCacheInstance() {
+ final CacheProviderWithLoadingCache provider = createNewCacheProvider();
+ final String name = RAND();
+ final CacheProvider.Cache<Integer, Integer> integerIntegerCache = provider.aaiClientCacheFor(name, (Integer i) -> i + 4);
+ final CacheProvider.Cache<Integer, Integer> integerIntegerCache2 = provider.aaiClientCacheFor(name, (Integer i) -> i + 6);
+
+ assertThat(integerIntegerCache2, sameInstance(integerIntegerCache));
+ assertThat(integerIntegerCache.get(5), is(9)); // as the first one
+ }
+
+ @Test
+ public void cacheProvider_requestingCacheSameNameTwiceOutOfSeveral_ReturnsFirstCacheInstance() {
+ final CacheProviderWithLoadingCache provider = createNewCacheProvider();
+
+ final String name = RAND();
+ provider.aaiClientCacheFor(RAND(), (Integer i) -> i + 2);
+ provider.aaiClientCacheFor(RAND(), (Integer i) -> i + 3);
+ final CacheProvider.Cache<Integer, Integer> integerIntegerCache = provider.aaiClientCacheFor(name, (Integer i) -> i + 4);
+ provider.aaiClientCacheFor(RAND(), (Integer i) -> i + 5);
+ provider.aaiClientCacheFor(RAND(), (Integer i) -> i + 6);
+ final CacheProvider.Cache<Integer, Integer> integerIntegerCache2 = provider.aaiClientCacheFor(name, (Integer i) -> i + 4);
+
+ assertThat(integerIntegerCache2, sameInstance(integerIntegerCache));
+ }
+
+ @Test
+ public void cacheProvider_sameProviderSupportDifferentKV() {
+ final CacheProviderWithLoadingCache provider = createNewCacheProvider();
+
+ assertThat(provider.aaiClientCacheFor(RAND(),
+ (Integer i) -> i + 2).get(0), is(2));
+ assertThat(provider.aaiClientCacheFor(RAND(),
+ (Integer i) -> i + 3).get(0), is(3));
+ assertThat(provider.aaiClientCacheFor(RAND(),
+ (String s) -> s + 5).get("0"), is("05"));
+ assertThat(provider.aaiClientCacheFor(RAND(),
+ (Integer i) -> "0" + i).get(0), is("00"));
+ assertThat(provider.aaiClientCacheFor(RAND(),
+ (Pair p) -> ImmutableList.of(p.getLeft(), p.getRight())).get(Pair.of(7, "B")), contains(7, "B"));
+ }
+
+ @Test
+ public void cache_callMultiTimesGetFromCahce_loaderCalledOncePairValue(){
+ final CacheProviderWithLoadingCache provider = createNewCacheProvider();
+ final CacheProvider.Cache<Integer, Integer> integerIntegerCache = provider.aaiClientCacheFor(RAND(), (Integer i) -> RandomUtils.nextInt());
+ int key = RandomUtils.nextInt();
+ Integer result1 = integerIntegerCache.get(key);
+ Integer result2 = integerIntegerCache.get(key + 1);
+ Integer result3 = integerIntegerCache.get(key);
+
+ Assert.assertNotEquals(result1,result2);
+ Assert.assertEquals(result1,result3);
+ }
+
+ @Test
+ public void cache_callMultiTimesGetFromCahce_loaderCalledOnce(){
+ final CacheProviderWithLoadingCache provider = createNewCacheProvider();
+ final MutableInt counter = new MutableInt();
+ final CacheProvider.Cache<Integer, Integer> integerIntegerCache = provider.aaiClientCacheFor(RAND(), (Integer i) -> {
+ counter.increment();
+ return i;
+ });
+
+ int key = RandomUtils.nextInt();
+ Integer result1 = integerIntegerCache.get(key);
+ Integer result2 = integerIntegerCache.get(key);
+ Integer result3 = integerIntegerCache.get(key);
+
+ Assert.assertEquals(result1.intValue(),key);
+ Assert.assertEquals(result2.intValue(),key);
+ Assert.assertEquals(result3.intValue(),key);
+ Assert.assertEquals(counter.intValue(),1);
+ }
+
+ @Test(expectedExceptions = GenericUncheckedException.class, expectedExceptionsMessageRegExp ="boom" )
+ public void cache_inCaseLoaderMethodThrowsException_cacheThrowsSameException(){
+ final CacheProviderWithLoadingCache provider = createNewCacheProvider();
+ final CacheProvider.Cache<String, Integer> stringIntegerCache = provider.aaiClientCacheFor(RAND(), (String s) -> { throw new GenericUncheckedException("boom");});
+
+ stringIntegerCache.get("Whatever");
+ }
+
+ @Test
+ public void cache_inCaseLoaderMethodThrowsException_nextCallUseLoaderMethod(){
+ final CacheProviderWithLoadingCache provider = createNewCacheProvider();
+ final CacheProvider.Cache<Integer, Integer> integerIntegerCache = provider.aaiClientCacheFor(RAND(), new Function<Integer, Integer>() {
+ private boolean firstTime = true;
+ @Override
+ public Integer apply(Integer i) {
+ if (firstTime) {
+ firstTime = false;
+ throw new GenericUncheckedException("boom");
+ }
+ else {
+ return i;
+ }
+ }
+ });
+
+ try {
+ integerIntegerCache.get(1);
+ }
+ catch (GenericUncheckedException e) {}
+
+ assertEquals(new Integer(1), integerIntegerCache.get(1));
+ }
+
+ @Test
+ public void cache_getIsCalledMoreThanOnce_loaderNotCalledAgainForSameInputValue(){
+ final CacheProviderWithLoadingCache provider = createNewCacheProvider();
+ final MutableInt counter = new MutableInt();
+ final CacheProvider.Cache<Integer, Integer> integerIntegerCache = provider.aaiClientCacheFor(RAND(), (Integer i) -> { counter.increment(); return i; });
+
+ int key1 = RandomUtils.nextInt();
+ int key2 = RandomUtils.nextInt();
+ integerIntegerCache.get(key1);
+ Assert.assertEquals(counter.intValue(),1);
+ integerIntegerCache.get(key2);
+ Assert.assertEquals(counter.intValue(),2);
+ integerIntegerCache.get(key1);
+ Assert.assertEquals(counter.intValue(),2);
+ }
+
+ @Test
+ public void cache_getIsCalledMoreThanOnce_loaderIsCalledAgainAfterReset(){
+ final CacheProviderWithLoadingCache provider = createNewCacheProvider();
+ final MutableInt counter = new MutableInt();
+ String cacheName = RAND();
+
+ int key1 = RandomUtils.nextInt();
+ provider.aaiClientCacheFor(cacheName, (Integer i) -> { counter.increment(); return i; }).get(key1);
+ Assert.assertEquals(counter.intValue(), 1);
+ provider.aaiClientCacheFor(cacheName, (Integer i) -> { counter.increment(); return i; }).get(key1);
+ Assert.assertEquals(counter.intValue(), 1);
+
+ provider.resetCache(cacheName);
+ provider.aaiClientCacheFor(cacheName, (Integer i) -> { counter.increment(); return i; }).get(key1);
+ Assert.assertEquals(counter.intValue(), 2);
+
+ }
+
+
+ public static class TestData {
+ public FeatureManager featureManager;
+ public String cacheName;
+ public CacheConfigProvider cacheConfigProvider;
+
+ public TestData(FeatureManager featureManager, String cacheName, CacheConfigProvider cacheConfigProvider) {
+ this.featureManager = featureManager;
+ this.cacheName = cacheName;
+ this.cacheConfigProvider = cacheConfigProvider;
+ }
+ }
+
+
+ @DataProvider
+ public static Object[][] mockForCacheIsNotActive() {
+
+ Consumer<TestData> mockFeatureOff = (testData)->{
+ when(testData.featureManager.isActive(Features.FLAG_1810_AAI_LOCAL_CACHE)).thenReturn(false);
+ when(testData.cacheConfigProvider.getCacheConfig(testData.cacheName)).thenReturn(new CacheConfig(true, 10L, 10L));
+ };
+ Consumer<TestData> mockFeatureOnCacheOff = (testData)->{
+ when(testData.featureManager.isActive(Features.FLAG_1810_AAI_LOCAL_CACHE)).thenReturn(true);
+ when(testData.cacheConfigProvider.getCacheConfig(testData.cacheName)).thenReturn(new CacheConfig(false, 10L, 10L));
+ };
+
+
+ return new Object[][]{
+ {mockFeatureOff},
+ {mockFeatureOnCacheOff}
+ };
+ }
+
+
+ @Test(dataProvider = "mockForCacheIsNotActive")
+ public void cache_featureFlagToggleIsOff_loaderIsCalledForEachGet(Consumer<TestData> mocker){
+ final CacheProviderWithLoadingCache provider = createNewCacheProvider();
+ final MutableInt counter = new MutableInt();
+ String cacheName = RAND();
+
+ final CacheProvider.Cache<Integer, Integer> integerIntegerCache = provider.aaiClientCacheFor(cacheName, (Integer i) -> {
+ counter.increment();
+ return i;
+ });
+
+ mocker.accept(new TestData(featureManager, cacheName, cacheConfigProvider));
+ counter.setValue(0);
+ int key = RandomUtils.nextInt();
+ integerIntegerCache.get(key);
+ integerIntegerCache.get(key);
+
+ Assert.assertEquals(counter.intValue(),2);
+ }
+
+ @Test
+ public void cache_loaderReturnsRandomValue_sameValueIsReturnedForSameKey() {
+ final CacheProviderWithLoadingCache provider = createNewCacheProvider();
+ final String name = RAND();
+ final CacheProvider.Cache<Integer, String> integerRandomStringCache = provider.aaiClientCacheFor(name, (Integer i) -> RAND());
+
+ String firstGet = integerRandomStringCache.get(1);
+ String secondGet = integerRandomStringCache.get(1);
+
+ Assert.assertEquals(firstGet,secondGet);
+ }
+
+ @Test(dataProvider = "mockForCacheIsNotActive")
+ public void cache_toggleFlagOff_ResetCache(Consumer<TestData> mocker){
+ final CacheProviderWithLoadingCache provider = createNewCacheProvider();
+ final String cacheName = RAND();
+ final CacheProvider.Cache<Integer, String> integerRandomStringCache = provider.aaiClientCacheFor(cacheName, (Integer i) -> RAND());
+ int key = RandomUtils.nextInt();
+ String result1 = integerRandomStringCache.get(key);
+ String result2 = integerRandomStringCache.get(key);
+ Assert.assertEquals(result1,result2);
+
+ mocker.accept(new TestData(featureManager, cacheName, cacheConfigProvider));
+ String result3 = integerRandomStringCache.get(key);
+ Assert.assertNotEquals(result1, result3);
+ }
+
+ @DataProvider
+ public static Object[][] mockForCacheBuilderConfig() {
+ return new Object[][]{
+ {2L, 2L, 3L, 3L},
+ {null, 10L, null, 24L} //null meaning use the default, which is 10L,24L
+ };
+ }
+
+ @Test(dataProvider = "mockForCacheBuilderConfig")
+ public void cacheBuilderConfiguredWithValues_andWithDefaults(
+ Long refreshAfterWriteSeconds,
+ long expectedRefreshAfterWriteSeconds,
+ Long expireAfterWriteHours,
+ long expectedExpireAfterWriteHours
+ ) throws IllegalAccessException {
+ final String cacheName = RAND();
+ when(cacheConfigProvider.getCacheConfig(cacheName)).thenReturn(new CacheConfig(true, expireAfterWriteHours, refreshAfterWriteSeconds));
+ final CacheProviderWithLoadingCache provider = createNewCacheProvider();
+ CacheBuilder<Object, Object> cacheBuilder = provider.createCacheBuilder(cacheName);
+
+
+ //Unfortunately CacheBuilder doesn't expose public getters
+ //Since it's only unit test I let myself do some fouls and use reflection
+ Long actualRefreshNanos = (Long)FieldUtils.readDeclaredField(cacheBuilder, "refreshNanos", true);
+ assertThat(actualRefreshNanos, equalTo(TimeUnit.NANOSECONDS.convert(expectedRefreshAfterWriteSeconds, TimeUnit.SECONDS)));
+
+ Long actualExpireAfterWriteNanos = (Long)FieldUtils.readDeclaredField(cacheBuilder, "expireAfterWriteNanos", true);
+ assertThat(actualExpireAfterWriteNanos, equalTo(TimeUnit.NANOSECONDS.convert(expectedExpireAfterWriteHours, TimeUnit.HOURS)));
+
+ }
+}
+
diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/util/HttpsAuthClientTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/util/HttpsAuthClientTest.java
index ce957ab67..44678ec24 100644
--- a/vid-app-common/src/test/java/org/onap/vid/aai/util/HttpsAuthClientTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/aai/util/HttpsAuthClientTest.java
@@ -21,11 +21,20 @@
package org.onap.vid.aai.util;
+import org.junit.Before;
+import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
+import org.onap.vid.aai.exceptions.HttpClientBuilderException;
+import org.onap.vid.exceptions.GenericUncheckedException;
+import org.togglz.core.manager.FeatureManager;
import javax.net.ssl.SSLContext;
+import java.util.Optional;
+
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.*;
@RunWith(MockitoJUnitRunner.class)
public class HttpsAuthClientTest {
@@ -38,47 +47,43 @@ public class HttpsAuthClientTest {
public static final String CERT_FILE_PATH = "any_path";
- /*
- TO BE IMPLEMENTED
-
private HttpsAuthClient createTestSubject() {
- return new HttpsAuthClient(systemPropertyHelper, sslContextProvider);
+ return new HttpsAuthClient(CERT_FILE_PATH, systemPropertyHelper, sslContextProvider, mock(FeatureManager.class));
}
@Before
public void setUp() throws Exception {
when(systemPropertyHelper.getAAITruststoreFilename()).thenReturn(Optional.of("filename"));
- when(systemPropertyHelper.getEncodedTruststorePassword()).thenReturn("password");
+ when(systemPropertyHelper.getDecryptedKeystorePassword()).thenReturn("password");
+ when(systemPropertyHelper.getDecryptedTruststorePassword()).thenReturn("password");
}
@Test(expected = HttpClientBuilderException.class)
- public void testHttpClientBuilderExceptionOnGetClient() throws HttpClientBuilderException {
+ public void testHttpClientBuilderExceptionOnGetClient() throws Exception {
//when
- when(systemPropertyHelper.getAAIUseClientCert()).thenReturn(Optional.of("true"));
- when(sslContextProvider.getSslContext(anyString(), anyString())).thenThrow(new HttpClientBuilderException());
- createTestSubject().getClient("nonExistingFile");
+ when(systemPropertyHelper.isClientCertEnabled()).thenReturn(true);
+ when(sslContextProvider.getSslContext(anyString(), anyString(), any())).thenThrow(new HttpClientBuilderException(new GenericUncheckedException("msg")));
+ createTestSubject().getClient(HttpClientMode.WITH_KEYSTORE);
}
@Test
public void testGetSecuredClient() throws Exception {
// when
- when(systemPropertyHelper.getAAIUseClientCert()).thenReturn(Optional.of("true"));
- when(sslContextProvider.getSslContext(anyString(), anyString())).thenReturn(sslContext);
- createTestSubject().getClient(CERT_FILE_PATH);
+ when(systemPropertyHelper.isClientCertEnabled()).thenReturn(true);
+ when(sslContextProvider.getSslContext(anyString(), anyString(), any())).thenReturn(sslContext);
+ createTestSubject().getClient(HttpClientMode.WITH_KEYSTORE);
//then
- verify(sslContextProvider).getSslContext(anyString(), anyString());
+ verify(sslContextProvider).getSslContext(anyString(), anyString(), any());
}
@Test
public void testGetUnsecuredClient() throws Exception {
// when
- when(systemPropertyHelper.getAAIUseClientCert()).thenReturn(Optional.of("false"));
- when(sslContextProvider.getSslContext(anyString(), anyString())).thenReturn(sslContext);
- createTestSubject().getClient(CERT_FILE_PATH);
+ when(systemPropertyHelper.isClientCertEnabled()).thenReturn(false);
+ createTestSubject().getClient(HttpClientMode.WITH_KEYSTORE);
//then
- verify(sslContextProvider, never()).getSslContext(anyString(), anyString());
+ verify(sslContextProvider, never()).getSslContext(anyString(), anyString(), any());
}
- */
} \ No newline at end of file
diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/util/NonCachingCacheProvider.java b/vid-app-common/src/test/java/org/onap/vid/aai/util/NonCachingCacheProvider.java
new file mode 100644
index 000000000..b43370763
--- /dev/null
+++ b/vid-app-common/src/test/java/org/onap/vid/aai/util/NonCachingCacheProvider.java
@@ -0,0 +1,14 @@
+package org.onap.vid.aai.util;
+
+import java.util.function.Function;
+
+public class NonCachingCacheProvider implements CacheProvider {
+
+ @Override
+ public <K, V> Cache<K, V> aaiClientCacheFor(String name, Function<K, V> loader) {
+ return loader::apply;
+ }
+
+ @Override
+ public void resetCache(String name) {}
+}
diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/util/ServiceInstanceStandardQueryTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/util/ServiceInstanceStandardQueryTest.java
new file mode 100644
index 000000000..99cd928c2
--- /dev/null
+++ b/vid-app-common/src/test/java/org/onap/vid/aai/util/ServiceInstanceStandardQueryTest.java
@@ -0,0 +1,405 @@
+package org.onap.vid.aai.util;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.collect.ImmutableList;
+import org.apache.log4j.LogManager;
+import org.apache.log4j.Logger;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.onap.vid.aai.AaiClientInterface;
+import org.onap.vid.aai.ExceptionWithRequestInfo;
+import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.Network;
+import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.ServiceInstance;
+import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.Vlan;
+import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.Vnf;
+import org.onap.vid.utils.Multival;
+import org.springframework.http.HttpMethod;
+import org.springframework.http.HttpStatus;
+import org.springframework.web.client.HttpClientErrorException;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import java.io.IOException;
+import java.net.URI;
+import java.util.List;
+import java.util.stream.Collectors;
+
+import static org.hamcrest.CoreMatchers.everyItem;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.*;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.when;
+import static org.onap.vid.utils.Unchecked.toURI;
+
+
+public class ServiceInstanceStandardQueryTest {
+ private static final Logger logger = LogManager.getLogger(ServiceInstanceStandardQueryTest.class);
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+ private final String serviceInstanceId = "9cdd1b2a-43a7-47bc-a88e-759ba2399f0b";
+ private final String vnfInstanceId_1 = "c015cc0f-0f37-4488-aabf-53795fd93cd3";
+ private final String vnfInstanceId_2 = "0846287b-65bf-45a6-88f6-6a1af4149fac";
+ private final String networkInstanceId_1 = "7989a6d2-ba10-4a5d-8f15-4520bc833090";
+ private final String networkInstanceId_2 = "82373aaa-c561-4e2b-96f1-7ef6f7f7b0e9";
+ private final String vlanTagInstanceId_1 = "701edbb2-37e4-4473-a2a6-405cb3ab2e37";
+ private final String vlanTagInstanceId_2 = "531571f4-e133-4780-8ba8-d79e63804084";
+ private final String vlanTagInstanceId_3 = "df674e8c-1773-4d39-a9e9-bddd2b339d0a";
+ private final String SERVICE_TYPE = "service";
+ private final String VNF_TYPE = "vnf";
+
+ @Mock
+ AaiClientInterface aaiClient;
+ @InjectMocks
+ private ServiceInstanceStandardQuery serviceInstanceStandardQuery;
+
+ @BeforeMethod
+ public void initMocks() {
+ MockitoAnnotations.initMocks(this);
+
+ when(aaiClient.typedAaiGet(any(URI.class), any(Class.class)))
+ .thenAnswer(invocationOnMock -> {
+ final URI uri = (URI) invocationOnMock.getArguments()[0];
+ final String lastPart = uri.toString().replaceAll(".*/", "");
+ switch (lastPart) {
+ case serviceInstanceId:
+ return getAaiObject(ServiceInstance.class);
+ case vnfInstanceId_1:
+ case vnfInstanceId_2:
+ return getAaiObject(Vnf.class);
+ case networkInstanceId_1:
+ case networkInstanceId_2:
+ return getAaiObject(Network.class);
+ case vlanTagInstanceId_1:
+ case vlanTagInstanceId_2:
+ case vlanTagInstanceId_3:
+ return getAaiObject(Vlan.class);
+ default:
+ throw new ExceptionWithRequestInfo(HttpMethod.GET, uri.toASCIIString(), getAaiObjectString(true), 404,
+ new HttpClientErrorException(HttpStatus.NOT_FOUND));
+ }
+ });
+ }
+
+ @Test
+ public void pathToObject_serviceInstanceUri_yieldsAaiObject() {
+ final ServiceInstance serviceInstance = serviceInstanceStandardQuery.objectByUri(ServiceInstance.class, toURI("/aai/v12/business/customers/customer/a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb/service-subscriptions/service-subscription/vMOG/service-instances/service-instance/" + serviceInstanceId));
+ assertThat(serviceInstance.getServiceInstanceId(), is(serviceInstanceId));
+ assertThat(serviceInstance.getServiceInstanceName(), is("Network_repl_vMOG_rk"));
+ }
+
+ @Test
+ public void pathToObject_networkUri_yieldsAaiObject() {
+ final Network network = serviceInstanceStandardQuery.objectByUri(Network.class, toURI("/aai/v12/network/l3-networks/l3-network/" + networkInstanceId_1 + ""));
+ assertThat(network.getNetworkId(), is(networkInstanceId_1));
+ assertThat(network.getNetworkName(), is("APPC-24595-T-IST-02AShared_cor_direct_net_1"));
+ }
+
+ @Test
+ public void pathToObject_vlanTagUri_yieldsAaiObject() {
+ final Vlan vlan = serviceInstanceStandardQuery.objectByUri(Vlan.class, toURI("/this is an invented link/aai/v12/tag/vlan-tags/vlan-tag/" + vlanTagInstanceId_1 + ""));
+ assertThat(vlan.getVlanInterface(), is("US-10688-genvnf-vlan-interface1"));
+ assertThat(vlan.getVlanIdInner(), is("917"));
+ }
+
+ @Test(expectedExceptions = Exception.class)
+ public void pathToObject_oneUnknownUri_throwsException() {
+ serviceInstanceStandardQuery.objectByUri(ServiceInstance.class, toURI("/aai/v12/non existing path"));
+ }
+
+ @Test
+ public void vnfsForServiceInstance_noRelatedButManyOthers_emptyResult() {
+ final Multival<ServiceInstance, Vnf> vnfs =
+ serviceInstanceStandardQuery.fetchRelatedVnfs(getAaiObject(false, ServiceInstance.class));
+ assertThat(vnfs.getValues(), is(empty()));
+ }
+
+ @Test
+ public void vnfsForServiceInstance_2RelatedAndManyOthers_Result2CorrectPath2() {
+ final Multival<ServiceInstance, Vnf> vnfs =
+ serviceInstanceStandardQuery.fetchRelatedVnfs(getAaiObject(ServiceInstance.class));
+
+ assertThat(vnfs.getValues(), hasSize(2));
+ }
+
+ @Test
+ public void serviceInstanceToL3Networks_noRelatedButManyOthers_emptyResult() {
+ final Multival<ServiceInstance, Network> l3Networks =
+ serviceInstanceStandardQuery.fetchRelatedL3Networks(SERVICE_TYPE, getAaiObject(false, ServiceInstance.class));
+ assertThat(l3Networks.getValues(), is(empty()));
+ }
+
+ @Test
+ public void serviceInstanceToL3Networks_2RelatedAndManyOthers_Result2CorrectPath2() {
+ final Multival<ServiceInstance, Network> l3Networks =
+ serviceInstanceStandardQuery.fetchRelatedL3Networks(SERVICE_TYPE, getAaiObject(ServiceInstance.class));
+
+ assertThat(l3Networks.getValues(), hasSize(2));
+ }
+
+ @Test
+ public void l3NetworkToVlanTags_noRelatedButManyOthers_emptyResult() {
+ final Multival<Network, Vlan> vlanTags =
+ serviceInstanceStandardQuery.fetchRelatedVlanTags(getAaiObject(false, Network.class));
+ assertThat(vlanTags.getValues(), is(empty()));
+ }
+
+ @Test
+ public void l3NetworkToVlanTags__2RelatedAndManyOthers_Result2CorrectPath() {
+ final Multival<Network, Vlan> vlanTags =
+ serviceInstanceStandardQuery.fetchRelatedVlanTags(getAaiObject(Network.class));
+
+ assertThat(vlanTags.getValues(), hasSize(3));
+ }
+
+ private <T> T getAaiObject(Class<T> valueType) {
+ return getAaiObject(true, valueType);
+ }
+
+ private <T> T getAaiObject(boolean withRelated, Class<T> valueType) {
+ try {
+ return MAPPER.readValue(getAaiObjectString(withRelated), valueType);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Test
+ public void integrativeUsageWithLinearInvocation() throws JsonProcessingException {
+ final ServiceInstanceStandardQuery srv = this.serviceInstanceStandardQuery;
+ final ServiceInstance service = srv.fetchServiceInstance(toURI("path of service/" + serviceInstanceId + ""));
+ final Network l3Network = ImmutableList.copyOf(srv.fetchRelatedL3Networks(SERVICE_TYPE, service).getValues()).get(0);
+ final Vlan vlanTag = ImmutableList.copyOf(srv.fetchRelatedVlanTags(l3Network).getValues()).get(0);
+
+ assertThat(vlanTag.getVlanInterface(), is("US-10688-genvnf-vlan-interface1"));
+ assertThat(vlanTag.getVlanIdInner(), is("917"));
+ }
+
+ @Test
+ public void integrativeUsageWithGenericAccessors() throws JsonProcessingException {
+ final ServiceInstanceStandardQuery srv = this.serviceInstanceStandardQuery;
+
+ final ServiceInstance serviceInstance = srv.fetchServiceInstance(toURI("path of service/" + serviceInstanceId + ""));
+
+ final Multival<ServiceInstance, Network> serviceToNetworks =
+ srv.fetchRelatedL3Networks(SERVICE_TYPE, serviceInstance);
+
+ final Multival<ServiceInstance, Multival<Network, Vlan>> serviceToNetworksToVlans =
+ serviceToNetworks.mapEachVal(srv::fetchRelatedVlanTags);
+
+ logger.info(MAPPER.writeValueAsString(serviceToNetworksToVlans));
+
+ // check all tags are in place
+ final List<Vlan> vlanTags = serviceToNetworksToVlans
+ .getValues().stream()
+ .flatMap(networkVlanMultival -> networkVlanMultival.getValues().stream())
+ .collect(Collectors.toList());
+
+ assertThat(vlanTags, hasSize(6)); // 2 networks, with 3 vlans each
+ assertThat(vlanTags, everyItem(hasProperty("vlanInterface", is("US-10688-genvnf-vlan-interface1"))));
+ assertThat(vlanTags, everyItem(hasProperty("vlanIdInner", is("917"))));
+ }
+
+ private String getAaiObjectString(boolean withRelated) {
+ final String relatedToVnfs = "" +
+ " { " +
+ " \"related-to\": \"generic-vnf\", " +
+ " \"relationship-label\": \"org.onap.relationships.inventory.ComposedOf\", " +
+ " \"related-link\": \"/aai/v12/network/generic-vnfs/generic-vnf/" + vnfInstanceId_1 + "\", " +
+ " \"relationship-data\": [{ " +
+ " \"relationship-key\": \"generic-vnf.vnf-id\", " +
+ " \"relationship-value\": \"" + vlanTagInstanceId_1 + "\" " +
+ " } " +
+ " ], " +
+ " \"related-to-property\": [{ " +
+ " \"property-key\": \"generic-vnf.vnf-name\", " +
+ " \"property-value\": \"\" " +
+ " } " +
+ " ] " +
+ " }, { " +
+ " \"related-to\": \"generic-vnf\", " +
+ " \"relationship-label\": \"org.onap.relationships.inventory.ComposedOf\", " +
+ " \"related-link\": \"/aai/v12/network/generic-vnfs/generic-vnf/" + vnfInstanceId_2 + "\", " +
+ " \"relationship-data\": [{ " +
+ " \"relationship-key\": \"generic-vnf.vnf-id\", " +
+ " \"relationship-value\": \"" + vlanTagInstanceId_2 + "\" " +
+ " } " +
+ " ], " +
+ " \"related-to-property\": [{ " +
+ " \"property-key\": \"generic-vnf.vnf-name\", " +
+ " \"property-value\": \"\" " +
+ " } " +
+ " ] " +
+ " }, ";
+
+
+ final String relatedToL3Networks = "" +
+ " { " +
+ " \"related-to\": \"l3-network\", " +
+ " \"relationship-label\": \"org.onap.relationships.inventory.ComposedOf\", " +
+ " \"related-link\": \"/aai/v12/network/l3-networks/l3-network/" + networkInstanceId_1 + "\", " +
+ " \"relationship-data\": [{ " +
+ " \"relationship-key\": \"l3-network.network-id\", " +
+ " \"relationship-value\": \"" + networkInstanceId_1 + "\" " +
+ " } " +
+ " ], " +
+ " \"related-to-property\": [{ " +
+ " \"property-key\": \"l3-network.network-name\", " +
+ " \"property-value\": \"APPC-24595-T-IST-02AShared_cor_direct_net_1\" " +
+ " } " +
+ " ] " +
+ " }, { " +
+ " \"related-to\": \"l3-network\", " +
+ " \"relationship-label\": \"org.onap.relationships.inventory.ComposedOf\", " +
+ " \"related-link\": \"/aai/v12/network/l3-networks/l3-network/" + networkInstanceId_2 + "\", " +
+ " \"relationship-data\": [{ " +
+ " \"relationship-key\": \"l3-network.network-id\", " +
+ " \"relationship-value\": \"" + networkInstanceId_2 + "\" " +
+ " } " +
+ " ], " +
+ " \"related-to-property\": [{ " +
+ " \"property-key\": \"l3-network.network-name\", " +
+ " \"property-value\": \"APPC-24595-T-IST-02AShared_cor_direct_net_1\" " +
+ " } " +
+ " ] " +
+ " }, ";
+
+ final String relatedToVlanTags = "" +
+ " { " +
+ " \"related-to\": \"vlan-tag\", " +
+ " \"relationship-label\": \"org.onap.relationships.inventory.ComposedOf\", " +
+ " \"related-link\": \"/this is an invented link/aai/v12/tag/vlan-tags/vlan-tag/" + vlanTagInstanceId_2 + "\", " +
+ " \"relationship-data\": [{ " +
+ " \"relationship-key\": \"vlan-tag.vlan-tag-id\", " +
+ " \"relationship-value\": \"" + vlanTagInstanceId_2 + "\" " +
+ " } " +
+ " ], " +
+ " \"related-to-property\": [{ " +
+ " \"property-key\": \"vlan-tag.vlan-tag-name\", " +
+ " \"property-value\": \"Behram_smeralda_56\" " +
+ " } " +
+ " ] " +
+ " }, { " +
+ " \"related-to\": \"vlan-tag\", " +
+ " \"relationship-label\": \"org.onap.relationships.inventory.ComposedOf\", " +
+ " \"related-link\": \"/this is an invented link/aai/v12/tag/vlan-tags/vlan-tag/" + vlanTagInstanceId_3 + "\" " +
+ " }, { " +
+ " \"related-to\": \"vlan-tag\", " +
+ " \"relationship-label\": \"org.onap.relationships.inventory.ComposedOf\", " +
+ " \"related-link\": \"/this is an invented link/aai/v12/tag/vlan-tags/vlan-tag/" + vlanTagInstanceId_1 + "\", " +
+ " \"relationship-data\": [{ " +
+ " \"relationship-key\": \"vlan-tag.vlan-tag-id\", " +
+ " \"relationship-value\": \"" + vlanTagInstanceId_1 + "\" " +
+ " } " +
+ " ], " +
+ " \"related-to-property\": [{ " +
+ " \"property-key\": \"vlan-tag.vlan-tag-name\", " +
+ " \"property-value\": \"Alexandra_Liron_3\" " +
+ " } " +
+ " ] " +
+ " }, ";
+
+ return "" +
+ "{ " +
+
+ // vlan props
+ " \"vlan-interface\": \"US-10688-genvnf-vlan-interface1\", " +
+ " \"vlan-id-inner\": 917, " +
+ " \"resource-version\": \"1518934744675\", " +
+ " \"in-maint\": false, " +
+ " \"is-ip-unnumbered\": false, " +
+ // imaginary vlan props
+ " \"vlan-tag-id\": \"" + vlanTagInstanceId_2 + "\", " +
+ " \"vlan-tag-name\": \"Alexandra_Liron_3\", " +
+ " \"vlan-tag-type\": \"SUNIWOBA\", " +
+
+ // service-instance props
+ " \"service-instance-name\": \"Network_repl_vMOG_rk\", " +
+ " \"service-instance-id\": \"" + serviceInstanceId + "\", " +
+ " \"environment-context\": \"General_Revenue-Bearing\", " +
+ " \"workload-context\": \"Production\", " +
+ " \"model-invariant-id\": \"92a72881-0a97-4d16-8c29-4831062e7e9b\", " +
+ " \"model-version-id\": \"5a3ad576-c01d-4bed-8194-0e72b4a3d020\", " +
+ " \"resource-version\": \"1516045827731\", " +
+ " \"orchestration-status\": \"Active\", " +
+
+ // network props
+ " \"network-id\": \"" + networkInstanceId_1 + "\", " +
+ " \"network-name\": \"APPC-24595-T-IST-02AShared_cor_direct_net_1\", " +
+ " \"network-type\": \"CONTRAIL30_BASIC\", " +
+ " \"network-role\": \"repl\", " +
+ " \"network-technology\": \"contrail\", " +
+ " \"neutron-network-id\": \"66ee6123-1c45-4e71-b6c0-a748ae0fee88\", " +
+ " \"is-bound-to-vpn\": true, " +
+ " \"service-id\": \"db171b8f-115c-4992-a2e3-ee04cae357e0\", " +
+ " \"network-role-instance\": 0, " +
+ " \"resource-version\": \"1516046029762\", " +
+ " \"heat-stack-id\": \"APPC-24595-T-IST-02AShared_cor_direct_net_1/e8b256aa-8ce1-4384-9d99-6606eaca9eac\", " +
+ " \"contrail-network-fqdn\": \"default-domain:APPC-24595-T-IST-02C:APPC-24595-T-IST-02AShared_cor_direct_net_1\", " +
+ " \"physical-network-name\": \"FALSE\", " +
+ " \"is-provider-network\": false, " +
+ " \"is-shared-network\": true, " +
+ " \"is-external-network\": true, " +
+
+ " \"relationship-list\": { " +
+ " \"relationship\": [{ " +
+ " \"related-to\": \"service-instance\", " +
+ " \"relationship-label\": \"org.onap.relationships.inventory.ComposedOf\", " +
+ " \"related-link\": \"/aai/v12/business/customers/customer/a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb/service-subscriptions/service-subscription/vMOG/service-instances/service-instance/" + serviceInstanceId + "\", " +
+ " \"relationship-data\": [{ " +
+ " \"relationship-key\": \"customer.global-customer-id\", " +
+ " \"relationship-value\": \"a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb\" " +
+ " }, { " +
+ " \"relationship-key\": \"service-subscription.service-type\", " +
+ " \"relationship-value\": \"vMOG\" " +
+ " }, { " +
+ " \"relationship-key\": \"service-instance.service-instance-id\", " +
+ " \"relationship-value\": \"" + serviceInstanceId + "\" " +
+ " } " +
+ " ], " +
+ " \"related-to-property\": [{ " +
+ " \"property-key\": \"service-instance.service-instance-name\", " +
+ " \"property-value\": \"Network_repl_vMOG_rk\" " +
+ " } " +
+ " ] " +
+ " }, { " +
+ " \"related-to\": \"vpn-binding\", " +
+ " \"relationship-label\": \"org.onap.relationships.inventory.Uses\", " +
+ " \"related-link\": \"/aai/v12/network/vpn-bindings/vpn-binding/13e94b71-3ce1-4988-ab0e-61208fc91f1c\", " +
+ " \"relationship-data\": [{ " +
+ " \"relationship-key\": \"vpn-binding.vpn-id\", " +
+ " \"relationship-value\": \"13e94b71-3ce1-4988-ab0e-61208fc91f1c\" " +
+ " } " +
+ " ], " +
+ " \"related-to-property\": [{ " +
+ " \"property-key\": \"vpn-binding.vpn-name\", " +
+ " \"property-value\": \"vMDNS\" " +
+ " }, { " +
+ " \"property-key\": \"vpn-binding.vpn-type\" " +
+ " } " +
+ " ] " +
+ " }, " + (withRelated ? relatedToVlanTags : "") + "{ " +
+ " \"related-to\": \"project\", " +
+ " \"relationship-label\": \"org.onap.relationships.inventory.Uses\", " +
+ " \"related-link\": \"/aai/v12/business/projects/project/project1\", " +
+ " \"relationship-data\": [{ " +
+ " \"relationship-key\": \"project.project-name\", " +
+ " \"relationship-value\": \"project1\" " +
+ " } " +
+ " ] " +
+ " }, " + (withRelated ? relatedToL3Networks + relatedToVnfs : "") + "{ " +
+ " \"related-to\": \"owning-entity\", " +
+ " \"relationship-label\": \"org.onap.relationships.inventory.BelongsTo\", " +
+ " \"related-link\": \"/aai/v12/business/owning-entities/owning-entity/589fe0db-26c4-45e5-9f4e-a246c74fce76\", " +
+ " \"relationship-data\": [{ " +
+ " \"relationship-key\": \"owning-entity.owning-entity-id\", " +
+ " \"relationship-value\": \"589fe0db-26c4-45e5-9f4e-a246c74fce76\" " +
+ " } " +
+ " ] " +
+ " } " +
+ " ] " +
+ " } " +
+ "} ";
+ }
+}
diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/util/SingleAAIRestInterfaceTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/util/SingleAAIRestInterfaceTest.java
index 7fad9019c..b5f8ff942 100644
--- a/vid-app-common/src/test/java/org/onap/vid/aai/util/SingleAAIRestInterfaceTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/aai/util/SingleAAIRestInterfaceTest.java
@@ -26,7 +26,11 @@ import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
+import org.onap.vid.aai.ExceptionWithRequestInfo;
import org.onap.vid.aai.exceptions.InvalidPropertyException;
+import org.onap.vid.exceptions.GenericUncheckedException;
+import org.onap.vid.utils.Unchecked;
+import org.springframework.http.HttpMethod;
import org.testng.Assert;
import javax.servlet.http.HttpServletRequest;
@@ -37,10 +41,14 @@ import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.UnsupportedEncodingException;
+import java.net.URI;
import java.util.Optional;
import java.util.UUID;
import static javax.ws.rs.core.Response.Status.*;
+import static junit.framework.TestCase.fail;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -56,6 +64,8 @@ public class SingleAAIRestInterfaceTest {
@Mock
private Invocation.Builder builder;
@Mock
+ private Invocation invocation;
+ @Mock
private ServletRequestHelper servletRequestHelper;
@Mock
private HttpsAuthClient httpsAuthClient;
@@ -76,6 +86,9 @@ public class SingleAAIRestInterfaceTest {
when(webTarget.request()).thenReturn(builder);
when(builder.accept(Mockito.anyString())).thenReturn(builder);
when(builder.header(Mockito.anyString(), Mockito.anyString())).thenReturn(builder);
+ when(builder.build(Mockito.anyString())).thenReturn(invocation);
+ when(builder.build(Mockito.anyString(), any(Entity.class))).thenReturn(invocation);
+ when(invocation.invoke()).thenReturn(response);
when(servletRequestHelper.extractOrGenerateRequestId()).thenReturn(UUID.randomUUID().toString());
}
@@ -90,70 +103,67 @@ public class SingleAAIRestInterfaceTest {
}
@Test
- public void testSetRestSrvrBaseURLWithNullValue() throws Exception {
+ public void testSetRestSrvrBaseURLWithNullValue() {
testSubject.SetRestSrvrBaseURL(null);
}
@Test
- public void testSetRestSrvrBaseURL() throws Exception {
+ public void testSetRestSrvrBaseURL() {
String baseUrl = "anything";
testSubject.SetRestSrvrBaseURL(baseUrl);
Assert.assertEquals(testSubject.getRestSrvrBaseURL(), baseUrl);
}
@Test
- public void testRestJsonPutWithResponse200() throws Exception {
+ public void testRestJsonPutWithResponse200() {
// given
String methodName = "RestPut";
String payload = "{\"id\": 1}";
Entity<String> entity = Entity.entity(payload, MediaType.APPLICATION_JSON);
// when
- when(builder.put(Mockito.any(Entity.class))).thenReturn(response);
when(response.getStatusInfo()).thenReturn(OK);
- Response finalResponse = testSubject.RestPut("", PATH, payload, false);
+ Response finalResponse = testSubject.RestPut("", PATH, payload, false, true).getResponse();
// then
- verify(builder).put(entity);
+ verify(builder).build(HttpMethod.PUT.name(), entity);
Assert.assertEquals(response, finalResponse);
}
- @Test
- public void testFailedRestJsonPut() throws Exception {
+ @Test(expected = ExceptionWithRequestInfo.class)
+ public void testFailedRestJsonPut() {
// given
String methodName = "RestPut";
String payload = "{\"id\": 1}";
Entity<String> entity = Entity.entity(payload, MediaType.APPLICATION_JSON);
// when
- when(builder.put(Mockito.any(Entity.class))).thenThrow(new RuntimeException());
- Response finalResponse = testSubject.RestPut("", PATH, payload, false);
+ when(builder.build(eq(HttpMethod.PUT.name()), any(Entity.class))).thenThrow(new GenericUncheckedException("msg"));
+ Response finalResponse = testSubject.RestPut("", PATH, payload, false, true).getResponse();
// then
- verify(builder).put(entity);
- Assert.assertEquals(finalResponse, null);
+ fail("expected unreachable: exception to be thrown");
}
@Test
- public void testRestJsonPutWithResponse400() throws Exception {
+ public void testRestJsonPutWithResponse400() {
// given
String methodName = "RestPut";
String payload = "{\"id\": 1}";
Entity<String> entity = Entity.entity(payload, MediaType.APPLICATION_JSON);
// when
- when(builder.put(Mockito.any(Entity.class))).thenReturn(response);
when(response.getStatusInfo()).thenReturn(BAD_REQUEST);
when(response.getStatus()).thenReturn(BAD_REQUEST.getStatusCode());
- Response finalResponse = testSubject.RestPut("", PATH, payload, false);
+ Response finalResponse = testSubject.RestPut("", PATH, payload, false, true).getResponse();
// then
- verify(builder).put(entity);
+ verify(builder).build(HttpMethod.PUT.name(), entity);
Assert.assertEquals(response, finalResponse);
}
@Test
- public void testRestPostWithResponse200() throws Exception {
+ public void testRestPostWithResponse200() {
// given
String methodName = "RestPost";
String payload = "{\"id\": 1}";
@@ -170,7 +180,7 @@ public class SingleAAIRestInterfaceTest {
}
@Test
- public void testRestPostWithResponse400() throws Exception {
+ public void testRestPostWithResponse400() {
// given
String methodName = "RestPost";
String payload = "{\"id\": 1}";
@@ -188,7 +198,7 @@ public class SingleAAIRestInterfaceTest {
}
@Test
- public void testFailedRestPost() throws Exception {
+ public void testFailedRestPost() {
// given
String methodName = "RestPost";
String payload = "{\"id\": 1}";
@@ -204,7 +214,7 @@ public class SingleAAIRestInterfaceTest {
}
@Test
- public void testRestDeleteWithResponse400() throws Exception {
+ public void testRestDeleteWithResponse400() {
// given
String methodName = "Delete";
@@ -222,7 +232,7 @@ public class SingleAAIRestInterfaceTest {
}
@Test
- public void testRestDeleteWithResponse404() throws Exception {
+ public void testRestDeleteWithResponse404() {
// given
String methodName = "Delete";
@@ -240,7 +250,7 @@ public class SingleAAIRestInterfaceTest {
}
@Test
- public void testFailedRestDelete() throws Exception {
+ public void testFailedRestDelete() {
// given
String methodName = "Delete";
@@ -254,54 +264,49 @@ public class SingleAAIRestInterfaceTest {
}
@Test
- public void testRestJsonGetWithResponse200() throws Exception {
+ public void testRestJsonGetWithResponse200() {
// given
String methodName = "RestGet";
// when
- when(builder.get()).thenReturn(response);
when(response.getStatusInfo()).thenReturn(OK);
- Response finalResponse = testSubject.RestGet("", "", PATH, false).getResponse();
+ Response finalResponse = testSubject.RestGet("", "", Unchecked.toURI(PATH), false).getResponse();
// then
Assert.assertEquals(response, finalResponse);
}
@Test
- public void testRestJsonGetWithResponse400() throws Exception {
+ public void testRestJsonGetWithResponse400() {
// given
String methodName = "RestGet";
// when
- when(builder.get()).thenReturn(response);
when(response.getStatusInfo()).thenReturn(BAD_REQUEST);
when(response.getStatus()).thenReturn(BAD_REQUEST.getStatusCode());
- Response finalResponse = testSubject.RestGet("", "", PATH, false).getResponse();
+ Response finalResponse = testSubject.RestGet("", "", Unchecked.toURI(PATH), false).getResponse();
// then
Assert.assertEquals(response, finalResponse);
}
@Test
- public void testFailedRestGet() throws Exception {
+ public void testFailedRestGet() {
// given
String methodName = "RestGet";
// when
- when(builder.get()).thenThrow(new RuntimeException());
- Response finalResponse = testSubject.RestGet("", "", PATH, false).getResponse();
+ when(builder.build(HttpMethod.GET.name())).thenThrow(new RuntimeException());
+ Response finalResponse = testSubject.RestGet("", "", Unchecked.toURI(PATH), false).getResponse();
// then
Assert.assertEquals(finalResponse, null);
}
private void mockSystemProperties() throws UnsupportedEncodingException, InvalidPropertyException {
- when(systemPropertyHelper.getAAIServerUrl()).thenReturn(Optional.of(HTTP_LOCALHOST));
- when(systemPropertyHelper.getAAIUseClientCert()).thenReturn(Optional.of("cert"));
- when(systemPropertyHelper.getAAIVIDPasswd()).thenReturn(Optional.of("passwd"));
- when(systemPropertyHelper.getAAIVIDUsername()).thenReturn(Optional.of("user"));
when(systemPropertyHelper.getEncodedCredentials()).thenReturn("someCredentials");
when(systemPropertyHelper.getFullServicePath(Mockito.anyString())).thenReturn("http://localhost/path");
+ when(systemPropertyHelper.getFullServicePath(Mockito.any(URI.class))).thenReturn("http://localhost/path");
when(systemPropertyHelper.getServiceBasePath(Mockito.anyString())).thenReturn("http://localhost/path");
}
diff --git a/vid-app-common/src/test/java/org/onap/vid/asdc/beans/tosca/PropertyTest.java b/vid-app-common/src/test/java/org/onap/vid/asdc/beans/tosca/PropertyTest.java
deleted file mode 100644
index cb68eac92..000000000
--- a/vid-app-common/src/test/java/org/onap/vid/asdc/beans/tosca/PropertyTest.java
+++ /dev/null
@@ -1,112 +0,0 @@
-package org.onap.vid.asdc.beans.tosca;
-
-import org.junit.Test;
-
-public class PropertyTest {
-
- private Property createTestSubject() {
- return new Property();
- }
-
- @Test
- public void testGetType() throws Exception {
- Property testSubject;
- String result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getType();
- }
-
- @Test
- public void testGetDescription() throws Exception {
- Property testSubject;
- String result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getDescription();
- }
-
- @Test
- public void testGetEntry_schema() throws Exception {
- Property testSubject;
- Schema result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getEntry_schema();
- }
-
-
- @Test
- public void testSetType() throws Exception {
- Property testSubject;
- String type = "";
-
- // default test
- testSubject = createTestSubject();
- testSubject.setType(type);
- }
-
- @Test
- public void testSetDescription() throws Exception {
- Property testSubject;
- String description = "";
-
- // default test
- testSubject = createTestSubject();
- testSubject.setDescription(description);
- }
-
- @Test
- public void testSetEntry_schema() throws Exception {
- Property testSubject;
- Schema entry_schema = null;
-
- // default test
- testSubject = createTestSubject();
- testSubject.setEntry_schema(entry_schema);
- }
-
-
- @Test
- public void testGetDefault() throws Exception {
- Property testSubject;
- String result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getDefault();
- }
-
- @Test
- public void testIsRequired() throws Exception {
- Property testSubject;
- boolean result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.isRequired();
- }
-
- @Test
- public void testSetDefault() throws Exception {
- Property testSubject;
- String _default = "";
-
- // default test
- testSubject = createTestSubject();
- testSubject.setDefault(_default);
- }
-
- @Test
- public void testSetRequired() throws Exception {
- Property testSubject;
- boolean required = false;
-
- // default test
- testSubject = createTestSubject();
- testSubject.setRequired(required);
- }
-} \ No newline at end of file
diff --git a/vid-app-common/src/test/java/org/onap/vid/asdc/parser/ToscaParserImpl2Test.java b/vid-app-common/src/test/java/org/onap/vid/asdc/parser/ToscaParserImpl2Test.java
index e1c5e923b..40c0f6093 100644
--- a/vid-app-common/src/test/java/org/onap/vid/asdc/parser/ToscaParserImpl2Test.java
+++ b/vid-app-common/src/test/java/org/onap/vid/asdc/parser/ToscaParserImpl2Test.java
@@ -4,46 +4,64 @@ import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
import net.javacrumbs.jsonunit.JsonAssert;
import org.apache.commons.io.IOUtils;
+import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.json.JSONTokener;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
import org.onap.sdc.tosca.parser.api.ISdcCsarHelper;
import org.onap.sdc.toscaparser.api.Group;
import org.onap.sdc.toscaparser.api.NodeTemplate;
+import org.onap.sdc.toscaparser.api.Property;
+import org.onap.sdc.toscaparser.api.elements.Metadata;
import org.onap.vid.asdc.AsdcCatalogException;
import org.onap.vid.asdc.AsdcClient;
import org.onap.vid.asdc.local.LocalAsdcClient;
-import org.onap.vid.controllers.ToscaParserMockHelper;
+import org.onap.vid.controller.ToscaParserMockHelper;
import org.onap.vid.model.*;
+import org.onap.vid.properties.Features;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
+import org.togglz.core.manager.FeatureManager;
import java.io.IOException;
import java.io.InputStream;
-import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.*;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import static com.google.common.collect.Lists.newArrayList;
import static org.hamcrest.Matchers.*;
+import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
+import static org.onap.vid.asdc.parser.ToscaParserImpl2.Constants.ECOMP_GENERATED_NAMING_PROPERTY;
import static org.onap.vid.testUtils.TestUtils.assertJsonStringEqualsIgnoreNulls;
-@Test
public class ToscaParserImpl2Test {
private final String myUUID = "myUUID";
- private static final Logger log = Logger.getLogger(ToscaParserImpl2Test.class);
+ private static final Logger log = LogManager.getLogger(ToscaParserImpl2Test.class);
- private ToscaParserImpl2 toscaParserImpl2 = new ToscaParserImpl2();
+ @InjectMocks
+ private ToscaParserImpl2 toscaParserImpl2;
private AsdcClient asdcClient;
private ObjectMapper om = new ObjectMapper();
+ @Mock
+ private VidNotionsBuilder vidNotionsBuilder;
+
@BeforeClass
void init() throws IOException {
@@ -56,60 +74,56 @@ public class ToscaParserImpl2Test {
}
- //@Test
- public void assertEqualsBetweenServices() throws Exception {
- for (ToscaParserMockHelper mockHelper : getExpectedServiceModel()) {
- Service expectedService = mockHelper.getNewServiceModel().getService();
- Service actualService = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getService();
- assertJsonStringEqualsIgnoreNulls(om.writeValueAsString(expectedService), om.writeValueAsString(actualService));
- }
+ @BeforeMethod
+ public void initMocks() {
+ MockitoAnnotations.initMocks(this);
}
- //@Test
- public void assertEqualBetweenObjects() throws Exception {
- for (ToscaParserMockHelper mockHelper : getExpectedServiceModel()) {
- final Path csarPath = getCsarPath(mockHelper.getUuid());
- System.out.println("Comparing for csar " + csarPath);
- ServiceModel actualServiceModel = toscaParserImpl2.makeServiceModel(csarPath, getServiceByUuid(mockHelper.getUuid()));
- assertJsonStringEqualsIgnoreNulls(om.writeValueAsString(mockHelper.getNewServiceModel()), om.writeValueAsString(actualServiceModel));
- }
+ @Test(dataProvider = "expectedServiceModel")
+ public void assertEqualsBetweenServices(String uuid, ToscaParserMockHelper mockHelper) throws Exception {
+ Service expectedService = mockHelper.getNewServiceModel().getService();
+ Service actualService = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getService();
+ assertJsonStringEqualsIgnoreNulls(om.writeValueAsString(expectedService), om.writeValueAsString(actualService));
}
- //@Test
- public void assertEqualsBetweenNetworkNodes() throws Exception {
- for (ToscaParserMockHelper mockHelper : getExpectedServiceModel()) {
- Map<String, Network> expectedNetworksMap = mockHelper.getNewServiceModel().getNetworks();
- Map<String, Network> actualNetworksMap = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getNetworks();
- for (Map.Entry<String, Network> entry : expectedNetworksMap.entrySet()) {
- Network expectedNetwork = entry.getValue();
- Network actualNetwork = actualNetworksMap.get(entry.getKey());
- Assert.assertEquals(expectedNetwork.getModelCustomizationName(), actualNetwork.getModelCustomizationName());
- verifyBaseNodeProperties(expectedNetwork, actualNetwork);
- compareProperties(expectedNetwork.getProperties(), actualNetwork.getProperties());
- }
+ @Test(dataProvider = "expectedServiceModel")
+ public void assertEqualBetweenObjects(String uuid, ToscaParserMockHelper mockHelper) throws Exception {
+ final Path csarPath = getCsarPath(mockHelper.getUuid());
+ log.info("Comparing for csar " + csarPath);
+ ServiceModel actualServiceModel = toscaParserImpl2.makeServiceModel(csarPath, getServiceByUuid(mockHelper.getUuid()));
+ assertJsonStringEqualsIgnoreNulls(om.writeValueAsString(mockHelper.getNewServiceModel()), om.writeValueAsString(actualServiceModel));
+ }
+
+ @Test(dataProvider = "expectedServiceModel")
+ public void assertEqualsBetweenNetworkNodes(String uuid, ToscaParserMockHelper mockHelper) throws Exception {
+ Map<String, Network> expectedNetworksMap = mockHelper.getNewServiceModel().getNetworks();
+ Map<String, Network> actualNetworksMap = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getNetworks();
+ for (Map.Entry<String, Network> entry : expectedNetworksMap.entrySet()) {
+ Network expectedNetwork = entry.getValue();
+ Network actualNetwork = actualNetworksMap.get(entry.getKey());
+ Assert.assertEquals(expectedNetwork.getModelCustomizationName(), actualNetwork.getModelCustomizationName());
+ verifyBaseNodeMetadata(expectedNetwork, actualNetwork);
+ compareProperties(expectedNetwork.getProperties(), actualNetwork.getProperties());
}
}
//Because we are not supporting the old flow, the JSON are different by definition.
- //@Test
- public void assertEqualsBetweenVnfsOfTosca() throws Exception {
- for (ToscaParserMockHelper mockHelper : getExpectedServiceModel()) {
- Map<String, VNF> expectedVnfsMap = mockHelper.getNewServiceModel().getVnfs();
- Map<String, VNF> actualVnfsMap = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getVnfs();
- for (Map.Entry<String, VNF> entry : expectedVnfsMap.entrySet()) {
- VNF expectedVnf = entry.getValue();
- VNF actualVnf = actualVnfsMap.get(entry.getKey());
- verifyBaseNodeProperties(expectedVnf, actualVnf);
- Assert.assertEquals(expectedVnf.getModelCustomizationName(), actualVnf.getModelCustomizationName());
- compareProperties(expectedVnf.getProperties(), actualVnf.getProperties());
- assertJsonStringEqualsIgnoreNulls(om.writeValueAsString(expectedVnf), om.writeValueAsString(actualVnf));
- }
+ @Test(dataProvider = "expectedServiceModel")
+ public void assertEqualsBetweenVnfsOfTosca(String uuid, ToscaParserMockHelper mockHelper) throws Exception {
+ Map<String, VNF> expectedVnfsMap = mockHelper.getNewServiceModel().getVnfs();
+ Map<String, VNF> actualVnfsMap = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getVnfs();
+ for (Map.Entry<String, VNF> entry : expectedVnfsMap.entrySet()) {
+ VNF expectedVnf = entry.getValue();
+ VNF actualVnf = actualVnfsMap.get(entry.getKey());
+ verifyBaseNodeMetadata(expectedVnf, actualVnf);
+ Assert.assertEquals(expectedVnf.getModelCustomizationName(), actualVnf.getModelCustomizationName());
+ compareProperties(expectedVnf.getProperties(), actualVnf.getProperties());
+ assertJsonStringEqualsIgnoreNulls(om.writeValueAsString(expectedVnf), om.writeValueAsString(actualVnf));
}
}
- //@Test
- public void assertEqualsBetweenCollectionResourcesOfTosca() throws Exception {
- for (ToscaParserMockHelper mockHelper : getExpectedServiceModel()) {
+ @Test(dataProvider = "expectedServiceModel")
+ public void assertEqualsBetweenCollectionResourcesOfTosca(String uuid, ToscaParserMockHelper mockHelper) throws Exception {
Map<String, CR> expectedVnfsMap = mockHelper.getNewServiceModel().getCollectionResource();
Map<String, CR> actualCRsMap = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getCollectionResource();
if(!actualCRsMap.isEmpty()) {
@@ -122,11 +136,20 @@ public class ToscaParserImpl2Test {
assertJsonStringEqualsIgnoreNulls(om.writeValueAsString(expectedCR), om.writeValueAsString(actualCR));
}
}
- }
}
+// @Test
+// public void verifyFabricConfiguration() throws Exception {
+// ToscaParserMockHelper toscaParserMockHelper = Arrays.stream(getExpectedServiceModel()).filter(x -> x.getUuid().equals(Constants.fabricConfigurationUuid)).findFirst().get();
+// ServiceModel actualServiceModel = toscaParserImpl2.makeServiceModel(getCsarPath(Constants.fabricConfigurationUuid), getServiceByUuid(Constants.fabricConfigurationUuid));
+// final Map<String, Node> fabricConfigurations = actualServiceModel.getFabricConfigurations();
+// String fabricConfigName = "Fabric Configuration 0";
+// Map<String, Node> expectedFC = toscaParserMockHelper.getNewServiceModel().getFabricConfigurations();
+// verifyBaseNodeMetadata(expectedFC.get(fabricConfigName), fabricConfigurations.get(fabricConfigName));
+// }
+
private void verifyCollectionResource(CR expectedCR, CR actualCR) {
- verifyBaseNodeProperties(expectedCR, actualCR);
+ verifyBaseNodeMetadata(expectedCR, actualCR);
Assert.assertEquals(expectedCR.getCategory(), actualCR.getCategory());
Assert.assertEquals(expectedCR.getSubcategory(), actualCR.getSubcategory());
Assert.assertEquals(expectedCR.getResourceVendor(), actualCR.getResourceVendor());
@@ -155,39 +178,30 @@ public class ToscaParserImpl2Test {
}
- //@Test
- public void assertEqualsBetweenVolumeGroups() throws Exception {
- for (ToscaParserMockHelper mockHelper : getExpectedServiceModel()) {
+ @Test(dataProvider = "expectedServiceModel")
+ public void assertEqualsBetweenVolumeGroups(String uuid, ToscaParserMockHelper mockHelper) throws Exception {
Map<String, VolumeGroup> actualVolumeGroups = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getVolumeGroups();
Map<String, VolumeGroup> expectedVolumeGroups = mockHelper.getNewServiceModel().getVolumeGroups();
assertJsonStringEqualsIgnoreNulls(om.writeValueAsString(expectedVolumeGroups), om.writeValueAsString(actualVolumeGroups));
- }
}
- //@Test
- public void assertEqualsBetweenVfModules() throws Exception {
- for (ToscaParserMockHelper mockHelper : getExpectedServiceModel()) {
+ @Test(dataProvider = "expectedServiceModel")
+ public void assertEqualsBetweenVfModules(String uuid, ToscaParserMockHelper mockHelper) throws Exception {
Map<String, VfModule> actualVfModules = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getVfModules();
Map<String, VfModule> expectedVfModules = mockHelper.getNewServiceModel().getVfModules();
assertJsonStringEqualsIgnoreNulls(om.writeValueAsString(expectedVfModules), om.writeValueAsString(actualVfModules));
- }
}
- //@Test
- public void assertEqualsBetweenPolicyConfigurationNodes() throws Exception {
- for (ToscaParserMockHelper mockHelper : getExpectedServiceModel()) {
+ @Test(dataProvider = "expectedServiceModel")
+ public void assertEqualsBetweenPolicyConfigurationNodes(String uuid, ToscaParserMockHelper mockHelper) throws Exception {
Map<String, PortMirroringConfig> actualConfigurations = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getConfigurations();
Map<String, PortMirroringConfig> expectedConfigurations = mockHelper.getNewServiceModel().getConfigurations();
JsonAssert.assertJsonEquals(actualConfigurations, expectedConfigurations);
- }
}
- //@Test
+
+ @Test
public void assertEqualsBetweenPolicyConfigurationByPolicyFalse() throws Exception {
ToscaParserMockHelper mockHelper = new ToscaParserMockHelper(Constants.configurationByPolicyFalseUuid, Constants.configurationByPolicyFalseFilePath);
- InputStream jsonFile = this.getClass().getClassLoader().getResourceAsStream(mockHelper.getFilePath());
- String expectedJsonAsString = IOUtils.toString(jsonFile, StandardCharsets.UTF_8.name());
- NewServiceModel newServiceModel1 = om.readValue(expectedJsonAsString, NewServiceModel.class);
- mockHelper.setNewServiceModel(newServiceModel1);
Map<String, PortMirroringConfig> expectedConfigurations = mockHelper.getNewServiceModel().getConfigurations();
Map<String, PortMirroringConfig> actualConfigurations = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getConfigurations();
@@ -197,11 +211,26 @@ public class ToscaParserImpl2Test {
}
@Test
+ public void once5GInNewInstantiationFlagIsActive_vidNotionsIsAppended() throws Exception {
+ FeatureManager featureManager = mock(FeatureManager.class);
+ when(featureManager.isActive(Features.FLAG_5G_IN_NEW_INSTANTIATION_UI)).thenReturn(true);
+
+ ToscaParserImpl2 toscaParserImpl2_local = new ToscaParserImpl2(new VidNotionsBuilder(featureManager));
+
+ final ToscaParserMockHelper mockHelper = new ToscaParserMockHelper(Constants.vlUuid, Constants.vlFilePath);
+ final ServiceModel serviceModel = toscaParserImpl2_local.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid()));
+
+ assertThat(serviceModel.getService().getVidNotions().getInstantiationUI(), is(VidNotions.InstantiationUI.LEGACY));
+ assertThat(serviceModel.getService().getVidNotions().getModelCategory(), is(VidNotions.ModelCategory.OTHER));
+ assertJsonStringEqualsIgnoreNulls("{ service: { vidNotions: { instantiationUI: \"legacy\", modelCategory: \"other\" } } }", om.writeValueAsString(serviceModel));
+ }
+
+ @Test
public void modelWithAnnotatedInputWithTwoProperties_vfModuleGetsTheInput() throws Exception {
final ToscaParserMockHelper mockHelper = new ToscaParserMockHelper("90fe6842-aa76-4b68-8329-5c86ff564407", "empty.json");
final ServiceModel serviceModel = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid()));
- assertJsonStringEqualsIgnoreNulls("{ vfModules: { 201712488_adiodvpe10..201712488AdiodVpe1..ADIOD_vRE_BV..module-1: { inputs: { 201712488_adiodvpe10_availability_zone_0: { } } } } }", om.writeValueAsString(serviceModel));
+ assertJsonStringEqualsIgnoreNulls("{ vfModules: { 201712488_adiodvpe10..201712488AdiodVpe1..ADIOD_vRE_BV..module-1: { inputs: { availability_zone_0: { } } } } }", om.writeValueAsString(serviceModel));
}
@Test
@@ -226,16 +255,21 @@ public class ToscaParserImpl2Test {
pmconfig.setCollectorNodes(new ArrayList<>(Arrays.asList("pprobeservice_proxy 4")));
}
- //@Test
- public void assertEqualsBetweenServiceProxyNodes() throws Exception {
- for (ToscaParserMockHelper mockHelper : getExpectedServiceModel()) {
+ @Test(dataProvider = "expectedServiceModel")
+ public void assertEqualsBetweenServiceProxyNodes(String uuid, ToscaParserMockHelper mockHelper) throws Exception {
Map<String, ServiceProxy> actualServiceProxies = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getServiceProxies();
Map<String, ServiceProxy> expectedServiceProxies = mockHelper.getNewServiceModel().getServiceProxies();
JsonAssert.assertJsonEquals(actualServiceProxies, expectedServiceProxies);
- }
}
- private void verifyBaseNodeProperties(Node expectedNode, Node actualNode) {
+ @Test(dataProvider = "expectedServiceModel")
+ public void assertEqualsBetweenVnfGroups(String uuid, ToscaParserMockHelper mockHelper) throws Exception {
+ Map<String, ResourceGroup> actualVnfGroups = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getVnfGroups();
+ Map<String, ResourceGroup> expectedVnfGroups = mockHelper.getNewServiceModel().getVnfGroups();
+ JsonAssert.assertJsonEquals(actualVnfGroups, expectedVnfGroups);
+ }
+
+ private void verifyBaseNodeMetadata(Node expectedNode, Node actualNode) {
Assert.assertEquals(expectedNode.getName(), actualNode.getName());
Assert.assertEquals(expectedNode.getCustomizationUuid(), actualNode.getCustomizationUuid());
Assert.assertEquals(expectedNode.getDescription(), actualNode.getDescription());
@@ -245,14 +279,16 @@ public class ToscaParserImpl2Test {
}
private void compareProperties(Map<String, String> expectedProperties, Map<String, String> actualProperties) {
- for (Map.Entry<String, String> property : expectedProperties.entrySet()) {
- String expectedValue = property.getValue();
- String key = property.getKey();
- String actualValue = actualProperties.get(key);
- Assert.assertEquals(expectedValue, actualValue);
- }
+ JsonAssert.assertJsonEquals(expectedProperties, actualProperties);
}
+ @DataProvider
+ public Object[][] expectedServiceModel() throws IOException {
+ return Stream.of(getExpectedServiceModel())
+ .map(l -> ImmutableList.of(l.getUuid(), l).toArray()).collect(Collectors.toList()).toArray(new Object[][]{});
+ }
+
+
private ToscaParserMockHelper[] getExpectedServiceModel() throws IOException {
ToscaParserMockHelper[] mockHelpers = {
new ToscaParserMockHelper(Constants.vlUuid, Constants.vlFilePath),
@@ -260,15 +296,12 @@ public class ToscaParserImpl2Test {
new ToscaParserMockHelper(Constants.crUuid, Constants.crFilePath),
new ToscaParserMockHelper(Constants.vfWithAnnotationUuid, Constants.vfWithAnnotationFilePath),
new ToscaParserMockHelper(Constants.vfWithVfcGroup, Constants.vfWithVfcGroupFilePath),
- new ToscaParserMockHelper(Constants.configurationUuid, Constants.configurationFilePath)
+ new ToscaParserMockHelper(Constants.configurationUuid, Constants.configurationFilePath),
+// new ToscaParserMockHelper(Constants.fabricConfigurationUuid, Constants.fabricConfigurationFilePath),
+// new ToscaParserMockHelper(Constants.vlanTaggingUuid, Constants.vlanTaggingFilePath),
+// new ToscaParserMockHelper(Constants.vnfGroupingUuid, Constants.vnfGroupingFilePath)
};
- for (ToscaParserMockHelper mockHelper : mockHelpers) {
- InputStream jsonFile = this.getClass().getClassLoader().getResourceAsStream(mockHelper.getFilePath());
- System.out.println(jsonFile);
- String expectedJsonAsString = IOUtils.toString(jsonFile, StandardCharsets.UTF_8.name());
- NewServiceModel newServiceModel1 = om.readValue(expectedJsonAsString, NewServiceModel.class);
- mockHelper.setNewServiceModel(newServiceModel1);
- }
+
return mockHelpers;
}
@@ -284,11 +317,11 @@ public class ToscaParserImpl2Test {
public class Constants {
public static final String configurationUuid = "ee6d61be-4841-4f98-8f23-5de9da846ca7";
public static final String configurationFilePath = "policy-configuration-csar.JSON";
- static final String vfUuid = "48a52540-8772-4368-9cdb-1f124ea5c931";
+ static final String vfUuid = "48a52540-8772-4368-9cdb-1f124ea5c931"; //service-vf-csar.zip
static final String vfWithAnnotationUuid = "f4d84bb4-a416-4b4e-997e-0059973630b9";
static final String vlUuid = "cb49608f-5a24-4789-b0f7-2595473cb997";
static final String crUuid = "76f27dfe-33e5-472f-8e0b-acf524adc4f0";
- static final String vfWithVfcGroup = "6bce7302-70bd-4057-b48e-8d5b99e686ca";
+ static final String vfWithVfcGroup = "6bce7302-70bd-4057-b48e-8d5b99e686ca"; //service-VdbeSrv-csar.zip
// public static final String PNFUuid = "68101369-6f08-4e99-9a28-fa6327d344f3";
static final String vfFilePath = "vf-csar.JSON";
static final String vlFilePath = "vl-csar.JSON";
@@ -297,7 +330,12 @@ public class ToscaParserImpl2Test {
static final String vfWithVfcGroupFilePath = "vf-with-vfcInstanceGroups.json";
public static final String configurationByPolicyFalseUuid = "ee6d61be-4841-4f98-8f23-5de9da845544";
public static final String configurationByPolicyFalseFilePath = "policy-configuration-by-policy-false.JSON";
-
+ //public static final String fabricConfigurationUuid = "12344bb4-a416-4b4e-997e-0059973630b9";
+ //public static final String fabricConfigurationFilePath = "fabric-configuration.json";
+ //public static final String vlanTaggingUuid = "1837481c-fa7d-4362-8ce1-d05fafc87bd1";
+ //public static final String vlanTaggingFilePath = "vlan-tagging.json";
+ //public static final String vnfGroupingUuid = "4117a0b6-e234-467d-b5b9-fe2f68c8b0fc";
+ //public static final String vnfGroupingFilePath = "vnf-grouping-csar.json";
}
@@ -305,7 +343,7 @@ public class ToscaParserImpl2Test {
@Test
public void testGetNFModuleFromVf() {
- ISdcCsarHelper csarHelper = getMockedSdcCsarHelper();
+ ISdcCsarHelper csarHelper = getMockedSdcCsarHelper(myUUID);
Map<String, VfModule> vfModulesFromVF = toscaParserImpl2.getVfModulesFromVF(csarHelper, myUUID);
@@ -318,7 +356,7 @@ public class ToscaParserImpl2Test {
@Test
public void testGetVolumeGroupsFromVF() {
- ISdcCsarHelper csarHelper = getMockedSdcCsarHelper();
+ ISdcCsarHelper csarHelper = getMockedSdcCsarHelper(myUUID);
Map<String, VolumeGroup> volumeGroupsFromVF = toscaParserImpl2.getVolumeGroupsFromVF(csarHelper, myUUID);
@@ -328,12 +366,67 @@ public class ToscaParserImpl2Test {
));
}
- private ISdcCsarHelper getMockedSdcCsarHelper() {
+// @DataProvider
+// public Object[][] expectedPoliciesTargets() {
+// return new Object[][] {
+// {Constants.vnfGroupingUuid, newArrayList("groupingservicefortest..ResourceInstanceGroup..0", "groupingservicefortest..ResourceInstanceGroup..1")},
+// {Constants.vfUuid, newArrayList()},
+// {Constants.vlanTaggingUuid, newArrayList()}
+// };
+// }
+//
+// @Test(dataProvider = "expectedPoliciesTargets")
+// public void testExtractNamingPoliciesTargets(String uuid, ArrayList<String> expectedTargets) throws AsdcCatalogException, SdcToscaParserException {
+// ISdcCsarHelper sdcCsarHelper = toscaParserImpl2.getSdcCsarHelper(getCsarPath(uuid));
+// List<String> policiesTargets = toscaParserImpl2.extractNamingPoliciesTargets(sdcCsarHelper);
+//
+// assertEquals(expectedTargets, policiesTargets);
+// }
+
+ @DataProvider
+ public Object[][] expectedEcompGeneratedNaming() {
+ return new Object[][] {
+ {"nf_naming property false", "nf_naming", "false", "false"},
+ {"nf_naming property true", "nf_naming", "true", "true"},
+ {"nf_naming property doesn't exist", "nf_naming", null, "false"},
+ {"exVL_naming property false", "exVL_naming", "false", "false"},
+ {"exVL_naming property true", "exVL_naming", "true", "true"},
+ {"exVL_naming property doesn't exist", "exVL_naming", null, "false"},
+ };
+ }
+
+ @Test(dataProvider = "expectedEcompGeneratedNaming")
+ public void testEcompGeneratedNamingForNode(String description, String parentProperty, String ecompNamingProperty, String expectedResult) {
+ Property property = mock(Property.class);
+ when(property.getName()).thenReturn("any_key");
+ when(property.getValue()).thenReturn("any_value");
+ ArrayList<Property> properties = newArrayList(property);
+
+ if (ecompNamingProperty != null) {
+ Property nfNamingProperty = mock(Property.class);
+ when(nfNamingProperty.getName()).thenReturn(parentProperty);
+ when(nfNamingProperty.getValue()).thenReturn(ImmutableMap.of(ECOMP_GENERATED_NAMING_PROPERTY, ecompNamingProperty));
+ properties.add(nfNamingProperty);
+ }
+
+ NodeTemplate node = mock(NodeTemplate.class);
+ when(node.getName()).thenReturn("node_name");
+ when(node.getPropertiesObjects()).thenReturn(properties);
+
+ String result = ToscaNamingPolicy.getEcompNamingValueForNode(node, parentProperty);
+ assertEquals(expectedResult, result);
+ }
+
+ public static ISdcCsarHelper getMockedSdcCsarHelper(String myUUID) {
ISdcCsarHelper csarHelper = mock(ISdcCsarHelper.class);
Group withVol = createMinimalGroup("withVol", true);
Group withoutVol = createMinimalGroup("withoutVol", false);
+ when(csarHelper.getServiceMetadata()).thenReturn(new Metadata(ImmutableMap.of(
+ "instantiationType", "A-La-Carte"
+ )));
+
when(csarHelper.getVfModulesByVf(myUUID))
.thenReturn(ImmutableList.of(withVol, withoutVol));
@@ -379,7 +472,7 @@ public class ToscaParserImpl2Test {
try {
log.info(String.format("Built a group: %s",
- (new com.fasterxml.jackson.databind.ObjectMapper())
+ (new ObjectMapper())
.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
.writeValueAsString(group)
));
diff --git a/vid-app-common/src/test/java/org/onap/vid/asdc/parser/ToscaParserInflatorTest.java b/vid-app-common/src/test/java/org/onap/vid/asdc/parser/ToscaParserInflatorTest.java
new file mode 100644
index 000000000..af9029e52
--- /dev/null
+++ b/vid-app-common/src/test/java/org/onap/vid/asdc/parser/ToscaParserInflatorTest.java
@@ -0,0 +1,120 @@
+package org.onap.vid.asdc.parser;
+
+import com.google.common.collect.ImmutableMap;
+import org.apache.commons.io.IOUtils;
+import org.apache.log4j.LogManager;
+import org.apache.log4j.Logger;
+import org.jetbrains.annotations.NotNull;
+import org.json.JSONObject;
+import org.json.JSONTokener;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.onap.sdc.tosca.parser.exceptions.SdcToscaParserException;
+import org.onap.vid.asdc.AsdcCatalogException;
+import org.onap.vid.asdc.AsdcClient;
+import org.onap.vid.asdc.beans.Service;
+import org.onap.vid.asdc.local.LocalAsdcClient;
+import org.onap.vid.asdc.parser.ServiceModelInflator.Names;
+import org.onap.vid.model.ServiceModel;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Path;
+import java.util.Map;
+import java.util.UUID;
+
+import static java.util.Collections.emptyMap;
+import static org.hamcrest.Matchers.is;
+import static org.junit.Assert.assertThat;
+
+public class ToscaParserInflatorTest {
+
+ private static final Logger log = LogManager.getLogger(ToscaParserInflatorTest.class);
+
+ @InjectMocks
+ private ToscaParserImpl2 toscaParserImpl2;
+
+ @Mock
+ private VidNotionsBuilder vidNotionsBuilder;
+
+ private AsdcClient asdcClient;
+
+ @BeforeClass
+ void init() throws IOException {
+
+ final InputStream asdcServicesFile = this.getClass().getClassLoader().getResourceAsStream("sdcservices.json");
+
+ final JSONTokener jsonTokener = new JSONTokener(IOUtils.toString(asdcServicesFile));
+ final JSONObject sdcServicesCatalog = new JSONObject(jsonTokener);
+
+ asdcClient = new LocalAsdcClient.Builder().catalog(sdcServicesCatalog).build();
+
+ }
+
+ @BeforeMethod
+ public void initMocks() {
+ MockitoAnnotations.initMocks(this);
+ }
+
+
+ @Test
+ public void inflateFabricConfigurationModel_allIdsAreGiven() throws Exception {
+ final String fabricConfigurationUuid = "90fe6842-aa76-4b68-8329-5c86ff564407";
+ final Map<String, Names> inflated = inflateModelByUuid(fabricConfigurationUuid);
+
+ // see vf-with-annotation-csar.json
+ assertThat(inflated, is(ImmutableMap.of(
+ "8df1892c-377d-460b-8a8d-fc8a116e9d92", doubleName("201712-488_ADIOD-vPE-1 0"),
+ "8d521692-7661-4296-b77e-a2058bb62e87", new Names("201712488AdiodVpe1..ADIOD_vRE_BV..module-1", "201712488_adiodvpe10..201712488AdiodVpe1..ADIOD_vRE_BV..module-1"),
+ "79fbee20-7fba-4166-ae4b-b94c869e7d8b", new Names("201712488AdiodVpe1..ADIOD_vPFE_BV..module-2","201712488_adiodvpe10..201712488AdiodVpe1..ADIOD_vPFE_BV..module-2"),
+ "806505b8-7a7c-47a2-acef-b4d26fe95a92", new Names("201712488AdiodVpe1..ADIOD_base_vPE_BV..module-0","201712488_adiodvpe10..201712488AdiodVpe1..ADIOD_base_vPE_BV..module-0")
+ )));
+ }
+
+
+ @Test
+ public void inflateVlModel_allIdsAreGiven() throws Exception {
+ final String fabricConfigurationUuid = "cb49608f-5a24-4789-b0f7-2595473cb997";
+ final Map<String, Names> inflated = inflateModelByUuid(fabricConfigurationUuid);
+
+ // see vl-csar.json
+ assertThat(inflated, is(ImmutableMap.of(
+ "af584529-d7f0-420e-a6f3-c38b689c030f", doubleName("ExtVL 0")
+ )));
+ }
+
+ @NotNull
+ private Names doubleName(String modelCustomizationName) {
+ return new Names(modelCustomizationName, modelCustomizationName);
+ }
+
+ @Test
+ public void inflateConfigurationByPolicyFalseUuid_allIdsAreGiven() throws Exception {
+ final String configurationByPolicyFalseUuid = "ee6d61be-4841-4f98-8f23-5de9da845544";
+ final Map<String, Names> inflated = inflateModelByUuid(configurationByPolicyFalseUuid);
+
+ // see policy-configuration-by-policy-false.json
+ // no relevant model here
+ assertThat(inflated, is(emptyMap()));
+ }
+
+ private Map<String, Names> inflateModelByUuid(String fabricConfigurationUuid) throws SdcToscaParserException, AsdcCatalogException {
+ ServiceModel actualServiceModel = serviceModelByUuid(fabricConfigurationUuid);
+
+ ServiceModelInflator serviceModelInflator = new ServiceModelInflator();
+ return serviceModelInflator.toNamesByVersionId(actualServiceModel);
+ }
+
+ private ServiceModel serviceModelByUuid(String uuid) throws SdcToscaParserException, AsdcCatalogException {
+ final Path modelPath = asdcClient.getServiceToscaModel(UUID.fromString(uuid));
+ final Service modelMetadata = asdcClient.getService(UUID.fromString(uuid));
+
+ return toscaParserImpl2.makeServiceModel(modelPath, modelMetadata);
+ }
+
+
+}
diff --git a/vid-app-common/src/test/java/org/onap/vid/asdc/parser/VidNotionsBuilderTest.java b/vid-app-common/src/test/java/org/onap/vid/asdc/parser/VidNotionsBuilderTest.java
new file mode 100644
index 000000000..26fb2cf17
--- /dev/null
+++ b/vid-app-common/src/test/java/org/onap/vid/asdc/parser/VidNotionsBuilderTest.java
@@ -0,0 +1,290 @@
+package org.onap.vid.asdc.parser;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import org.apache.commons.lang3.tuple.Pair;
+import org.jetbrains.annotations.NotNull;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.MockitoAnnotations;
+import org.onap.sdc.tosca.parser.api.ISdcCsarHelper;
+import org.onap.sdc.tosca.parser.exceptions.SdcToscaParserException;
+import org.onap.sdc.tosca.parser.impl.SdcToscaParserFactory;
+import org.onap.sdc.toscaparser.api.NodeTemplate;
+import org.onap.sdc.toscaparser.api.Property;
+import org.onap.sdc.toscaparser.api.elements.Metadata;
+import org.onap.vid.model.*;
+import org.onap.vid.properties.Features;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+import org.togglz.core.manager.FeatureManager;
+
+import java.util.LinkedHashMap;
+import java.util.UUID;
+import java.util.function.BiConsumer;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.hasProperty;
+import static org.hamcrest.Matchers.is;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import static org.testng.Assert.assertEquals;
+
+public class VidNotionsBuilderTest {
+
+ @InjectMocks
+ VidNotionsBuilder vidNotionsBuilder;
+
+ @Mock
+ private FeatureManager featureManagerMock;
+
+ @BeforeClass
+ public void initMocks() {
+ MockitoAnnotations.initMocks(this);
+ }
+
+ @AfterMethod
+ public void reset() {
+ Mockito.reset(featureManagerMock);
+ }
+
+ @Test
+ public void VLNetworkWithPropertyNetworkTechnologyOVS_UIHintIsPositive() {
+ ISdcCsarHelper csarHelper = mockForNonLegacyInstantiationUI();
+
+ assertThat(vidNotionsBuilder.suggestInstantiationUI(csarHelper), is(VidNotions.InstantiationUI.NETWORK_WITH_PROPERTY_NETWORK_TECHNOLOGY_EQUALS_STANDARD_SRIOV_OR_OVS));
+ assertThat(vidNotionsBuilder.suggestModelCategory(csarHelper) , is(VidNotions.ModelCategory.IS_5G_PROVIDER_NETWORK_MODEL));
+ }
+
+ @NotNull
+ protected ISdcCsarHelper mockForNonLegacyInstantiationUI() {
+ ISdcCsarHelper csarHelper = ToscaParserImpl2Test.getMockedSdcCsarHelper(UUID.randomUUID().toString());
+
+ NodeTemplate nodeTemplate = mock(NodeTemplate.class);
+
+ when(nodeTemplate.getProperties()).thenReturn(new LinkedHashMap<>(ImmutableMap.of(
+ "dummy_val", mock(Property.class),
+ "network_technology", new Property(Pair.of("network_technology","ovs"))
+ )));
+
+ when(csarHelper.getServiceVlList()).thenReturn(ImmutableList.of(nodeTemplate));
+ when(featureManagerMock.isActive(Features.FLAG_5G_IN_NEW_INSTANTIATION_UI)).thenReturn(true);
+ return csarHelper;
+ }
+
+ @DataProvider
+ public static Object[][] anyAlacarteDataProvider() {
+ return new Object[][] {
+ {"A-La-Carte", VidNotions.InstantiationUI.ANY_ALACARTE_NEW_UI},
+ {"Macro", VidNotions.InstantiationUI.LEGACY},
+ };
+ }
+
+ @Test(dataProvider = "anyAlacarteDataProvider")
+ public void FLAG_EXP_ANY_ALACARTE_NEW_INSTANTIATION_UI_is_active_UIHintIsPositive(String instantiationType, VidNotions.InstantiationUI expectedInstantiationUI) {
+ when(featureManagerMock.isActive(Features.FLAG_EXP_ANY_ALACARTE_NEW_INSTANTIATION_UI)).thenReturn(true);
+ ISdcCsarHelper csarHelper = ToscaParserImpl2Test.getMockedSdcCsarHelper(UUID.randomUUID().toString());
+ when(csarHelper.getServiceMetadata()).thenReturn(new Metadata(ImmutableMap.of(
+ "instantiationType", instantiationType
+ )));
+ NodeTemplate nodeTemplate = mock(NodeTemplate.class);
+
+ when(nodeTemplate.getProperties()).thenReturn(new LinkedHashMap<>(ImmutableMap.of(
+ "dummy_val", mock(Property.class),
+ "network_technology", new Property(Pair.of("network_technology","ovs"))
+ )));
+
+ when(csarHelper.getServiceVlList()).thenReturn(ImmutableList.of(nodeTemplate));
+
+ assertThat(vidNotionsBuilder.suggestInstantiationUI(csarHelper), is(expectedInstantiationUI));
+ }
+
+ @Test
+ public void VLNetworkWithPropertyNetworkTechnologyNot5G_UIHintIsNegative() {
+ ISdcCsarHelper csarHelper = ToscaParserImpl2Test.getMockedSdcCsarHelper(UUID.randomUUID().toString());
+
+ NodeTemplate nodeTemplate = mock(NodeTemplate.class);
+
+ when(nodeTemplate.getProperties()).thenReturn(new LinkedHashMap<>(ImmutableMap.of(
+ "dummy_val", mock(Property.class),
+ "network_technology", new Property(Pair.of("network_technology","old_value"))
+ )));
+
+ when(csarHelper.getServiceVlList()).thenReturn(ImmutableList.of(nodeTemplate));
+
+ assertThat(vidNotionsBuilder.suggestInstantiationUI(csarHelper), is(VidNotions.InstantiationUI.LEGACY));
+ assertThat(vidNotionsBuilder.suggestModelCategory(csarHelper) , is(VidNotions.ModelCategory.OTHER));
+ }
+
+ @Test
+ public void withoutMocks_givenZippedToscaFile_hasAnyNetworkWithPropertyEqualsToAnyOfYieldsTrue() throws SdcToscaParserException {
+ SdcToscaParserFactory factory = SdcToscaParserFactory.getInstance();
+ ISdcCsarHelper csarHelper = factory.getSdcCsarHelper(getClass().getClassLoader().getResource("service-vl-csar.zip").getPath(),false);
+
+ assertThat(vidNotionsBuilder.isALaCarte(csarHelper), is(false));
+ assertThat(vidNotionsBuilder.hasAnyNetworkWithPropertyEqualsToAnyOf(csarHelper, "unexpected_property_name"), is(false));
+ assertThat(vidNotionsBuilder.hasAnyNetworkWithPropertyEqualsToAnyOf(csarHelper, "network_technology","Standard-SR-IOV"), is(true));
+ assertThat(vidNotionsBuilder.suggestInstantiationUI(csarHelper), is(VidNotions.InstantiationUI.LEGACY));
+ }
+
+ //@Test
+ //public void withoutMocks_givenZippedToscaFile_hasFabricConfigurationYieldsTrue() throws SdcToscaParserException {
+ // SdcToscaParserFactory factory = SdcToscaParserFactory.getInstance();
+ // ISdcCsarHelper csarHelper = factory.getSdcCsarHelper(getClass().getClassLoader().getResource("service-fabric-configuration.zip").getPath(),false);
+ //
+ // assertThat(vidNotionsBuilder.isALaCarte(csarHelper), is(false));
+ // assertThat(vidNotionsBuilder.hasFabricConfiguration(csarHelper), is(true));
+ // assertThat(vidNotionsBuilder.suggestInstantiationUI(csarHelper), is(VidNotions.InstantiationUI.LEGACY));
+ //}
+
+
+ @Test
+ public void uuidIsExactly1ffce89fEtc_UIHintIsPositive() {
+ ISdcCsarHelper csarHelper = ToscaParserImpl2Test.getMockedSdcCsarHelper(UUID.randomUUID().toString());
+
+ when(csarHelper.getServiceMetadata()).thenReturn(new Metadata(ImmutableMap.of(
+ "UUID", "95eb2c44-bff2-4e8b-ad5d-8266870b7717"
+ )));
+ when(featureManagerMock.isActive(Features.FLAG_5G_IN_NEW_INSTANTIATION_UI)).thenReturn(true);
+ assertThat(vidNotionsBuilder.suggestInstantiationUI(csarHelper), is(VidNotions.InstantiationUI.SERVICE_UUID_IS_1ffce89f_ef3f_4cbb_8b37_82134590c5de));
+ }
+
+
+ @DataProvider
+ public static Object[][] trueAndFalse() {
+ return new Object[][] {{true}, {false}};
+ }
+
+ @Test(dataProvider = "trueAndFalse")
+ public void buildVidNotions_nullByFlag(boolean flagValue) {
+ ISdcCsarHelper csarHelper = ToscaParserImpl2Test.getMockedSdcCsarHelper(UUID.randomUUID().toString());
+
+ when(featureManagerMock.isActive(Features.FLAG_5G_IN_NEW_INSTANTIATION_UI)).thenReturn(flagValue);
+ assertThat(vidNotionsBuilder.buildVidNotions(csarHelper, null), hasProperty("instantiationUI", is(VidNotions.InstantiationUI.LEGACY)));
+ }
+
+ @DataProvider
+ public static Object[][] ServiceRoleTypesDataProvider() {
+ return new Object[][] {
+ {"gROUPING", VidNotions.InstantiationUI.SERVICE_WITH_VNF_GROUPING},
+ {"", VidNotions.InstantiationUI.LEGACY},
+ };
+ }
+
+ @Test(dataProvider = "ServiceRoleTypesDataProvider")
+ public void testGetViewEditUITypeForResourceGroup(String serviceRole, VidNotions.InstantiationUI expectedViewEditUI) {
+ when(featureManagerMock.isActive(Features.FLAG_ASYNC_INSTANTIATION)).thenReturn(true);
+ when(featureManagerMock.isActive(Features.FLAG_1902_VNF_GROUPING)).thenReturn(true);
+ ISdcCsarHelper csarHelper = ToscaParserImpl2Test.getMockedSdcCsarHelper(UUID.randomUUID().toString());
+ when(csarHelper.getServiceMetadata()).thenReturn(new Metadata(ImmutableMap.of(
+ "serviceRole", serviceRole
+ )));
+
+ assertThat(vidNotionsBuilder.suggestViewEditUI(csarHelper, null), is(expectedViewEditUI));
+ }
+
+ @DataProvider
+ public static Object[][] macroToViewEditDataProvider() {
+ return new Object[][] {
+ {"macro service + not excluded + needed flags are open", true, false, true, true, VidNotions.InstantiationUI.MACRO_SERVICE},
+ {"not macro service", false, false, true, true, VidNotions.InstantiationUI.LEGACY},
+ {"macro that shall be excluded because it has pnf", true, true, true, true, VidNotions.InstantiationUI.LEGACY},
+ {"macro service + FLAG_ASYNC_INSTANTIATION off", true, false, false, true, VidNotions.InstantiationUI.LEGACY},
+ {"macro service + FLAG_1902_NEW_VIEW_EDIT off", true, false, true, false, VidNotions.InstantiationUI.LEGACY},
+ };
+ }
+
+ @Test(dataProvider="macroToViewEditDataProvider")
+ public void whenServiceIsMacro_viewEditIsRight(
+ String testDescription,
+ boolean isMacro,
+ boolean isExcluded,
+ boolean isFlagAsyncInstantiationActive,
+ boolean isFlag1902NewViewEdit,
+ VidNotions.InstantiationUI expectedViewEditUi) {
+
+ ISdcCsarHelper csarHelper = mock(ISdcCsarHelper.class);
+ ServiceModel serviceModel = mock(ServiceModel.class);
+
+ //mock for is Macro
+ String instantiationType = isMacro ? ToscaParserImpl2.Constants.MACRO : ToscaParserImpl2.Constants.A_LA_CARTE;
+ Service service = mock(Service.class);
+ when(serviceModel.getService()).thenReturn(service);
+ when(service.getInstantiationType()).thenReturn(instantiationType);
+ when(featureManagerMock.isActive(Features.FLAG_ASYNC_INSTANTIATION)).thenReturn(isFlagAsyncInstantiationActive);
+ when(featureManagerMock.isActive(Features.FLAG_1902_NEW_VIEW_EDIT)).thenReturn(isFlag1902NewViewEdit);
+
+ //mock for isExcluded
+ if (isExcluded) {
+ when(serviceModel.getPnfs()).thenReturn(ImmutableMap.of("a", mock(Node.class)));
+ }
+
+ VidNotions.InstantiationUI result = vidNotionsBuilder.suggestViewEditUI(csarHelper, serviceModel);
+ assertEquals(expectedViewEditUi, result);
+ }
+
+ @DataProvider
+ public static Object[][] instantiationUIToViewEditDataProvider() {
+ return new Object[][] {
+ {"network cloud(5G) service + needed flags are open", true, true, true, VidNotions.InstantiationUI.NETWORK_WITH_PROPERTY_NETWORK_TECHNOLOGY_EQUALS_STANDARD_SRIOV_OR_OVS},
+ {"mocked service + needed flags are open", false, true, true, VidNotions.InstantiationUI.LEGACY},
+ {"network cloud(5G) service + FLAG_ASYNC_INSTANTIATION is off", true, false, true, VidNotions.InstantiationUI.LEGACY},
+ {"network cloud(5G) service + FLAG_1902_NEW_VIEW_EDIT is off", true, true, false, VidNotions.InstantiationUI.LEGACY},
+ };
+ }
+
+
+ @Test(dataProvider="instantiationUIToViewEditDataProvider")
+ public void whenInstantiationUIIsNotLegacy_viewEditIsRight(
+ String testDescription,
+ boolean isInstantiationUINotLegacy,
+ boolean isFlagAsyncInstantiationActive,
+ boolean isFlag1902NewViewEdit,
+ VidNotions.InstantiationUI expectedViewEditUi) {
+
+ ISdcCsarHelper csarHelper = isInstantiationUINotLegacy ? mockForNonLegacyInstantiationUI() : mock(ISdcCsarHelper.class);
+ when(featureManagerMock.isActive(Features.FLAG_ASYNC_INSTANTIATION)).thenReturn(isFlagAsyncInstantiationActive);
+ when(featureManagerMock.isActive(Features.FLAG_1902_NEW_VIEW_EDIT)).thenReturn(isFlag1902NewViewEdit);
+
+ ServiceModel serviceModel = mock(ServiceModel.class);
+ Service service = mock(Service.class);
+ when(serviceModel.getService()).thenReturn(service);
+ when(service.getInstantiationType()).thenReturn(ToscaParserImpl2.Constants.A_LA_CARTE);
+
+ VidNotions.InstantiationUI result = vidNotionsBuilder.suggestViewEditUI(csarHelper, serviceModel);
+ assertEquals(expectedViewEditUi, result);
+ }
+
+ @DataProvider
+ public static Object[][] mockerForMacroExcluded() {
+ return new Object[][] {
+ {"service with pnfs", (BiConsumer<ServiceModel, FeatureManager>) (serviceModel, fm)->when(serviceModel.getPnfs()).thenReturn(ImmutableMap.of("a", mock(Node.class))), true},
+ {"service with collection resource", (BiConsumer<ServiceModel, FeatureManager>) (serviceModel, fm)->when(serviceModel.getCollectionResource()).thenReturn(ImmutableMap.of("a", mock(CR.class))), true},
+ {"service with network + FLAG_NETWORK_TO_ASYNC_INSTANTIATION false ", (BiConsumer<ServiceModel, FeatureManager>) (serviceModel, fm)->{
+ when(serviceModel.getNetworks()).thenReturn(ImmutableMap.of("a", mock(Network.class)));
+ when(fm.isActive(Features.FLAG_NETWORK_TO_ASYNC_INSTANTIATION)).thenReturn(false);}
+ , true},
+ {"service with network + FLAG_NETWORK_TO_ASYNC_INSTANTIATION true", (BiConsumer<ServiceModel, FeatureManager>) (serviceModel, fm)->{
+ when(serviceModel.getNetworks()).thenReturn(ImmutableMap.of("a", mock(Network.class)));
+ when(fm.isActive(Features.FLAG_NETWORK_TO_ASYNC_INSTANTIATION)).thenReturn(true);}
+ , false},
+ {"empty service + FLAG_NETWORK_TO_ASYNC_INSTANTIATION false", (BiConsumer<ServiceModel, FeatureManager>) (serviceModel, fm)->when(fm.isActive(Features.FLAG_NETWORK_TO_ASYNC_INSTANTIATION)).thenReturn(false), false},
+ };
+ }
+
+ @Test(dataProvider="mockerForMacroExcluded")
+ public void testIsMacroExcludedFromAsyncFlow(String testDescription, BiConsumer<ServiceModel, FeatureManager> mocker, boolean shallBeExcluded) {
+ ServiceModel serviceModel = mock(ServiceModel.class);
+ mocker.accept(serviceModel, featureManagerMock);
+ assertEquals(shallBeExcluded, vidNotionsBuilder.isMacroExcludedFromAsyncFlow(serviceModel));
+ }
+
+
+
+
+
+
+} \ No newline at end of file
diff --git a/vid-app-common/src/test/java/org/onap/vid/bl/AaiServiceTest.java b/vid-app-common/src/test/java/org/onap/vid/bl/AaiServiceTest.java
index 113b9f1f3..11c02fe9b 100644
--- a/vid-app-common/src/test/java/org/onap/vid/bl/AaiServiceTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/bl/AaiServiceTest.java
@@ -20,11 +20,11 @@ import java.util.Arrays;
import java.util.Collections;
import java.util.List;
+import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.arrayWithSize;
import static org.hamcrest.Matchers.equalTo;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
-import static org.hamcrest.MatcherAssert.assertThat;
public class AaiServiceTest {
diff --git a/vid-app-common/src/test/java/org/onap/vid/client/HttpsBasicClientTest.java b/vid-app-common/src/test/java/org/onap/vid/client/HttpsBasicClientTest.java
deleted file mode 100644
index 75bb01980..000000000
--- a/vid-app-common/src/test/java/org/onap/vid/client/HttpsBasicClientTest.java
+++ /dev/null
@@ -1,17 +0,0 @@
-package org.onap.vid.client;
-
-import org.junit.Test;
-
-public class HttpsBasicClientTest {
-
- private HttpsBasicClient createTestSubject() {
- return new HttpsBasicClient();
- }
-
- @Test
- public void testGetClient() throws Exception {
-
- // default test
- HttpsBasicClient.getClient();
- }
-} \ No newline at end of file
diff --git a/vid-app-common/src/test/java/org/onap/vid/config/DataSourceConfig.java b/vid-app-common/src/test/java/org/onap/vid/config/DataSourceConfig.java
index eb9239e17..ba8060da7 100644
--- a/vid-app-common/src/test/java/org/onap/vid/config/DataSourceConfig.java
+++ b/vid-app-common/src/test/java/org/onap/vid/config/DataSourceConfig.java
@@ -25,20 +25,19 @@ public class DataSourceConfig {
public LocalSessionFactoryBean sessionFactory(DataSource dataSource) {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
- //I used this class org.openecomp.portalsdk.core.conf.HibernateConfiguration to learn how to config the session factory
+ //I used this class org.onap.portalsdk.core.conf.HibernateConfiguration to learn how to config the session factory
// and use the following url for actual h2 properties
//https://github.com/levi-putna/Hibernate-H2-Example/blob/master/hibernate-h2-example/src/hibernate.cfg.xml
Properties properties = getH2Properties();
- properties.put("hibernate.default_schema", "PUBLIC");
properties.put("connection.pool_size", 10);
properties.put("cache.provider_class", "org.hibernate.cache.internal.NoCacheProvider");
properties.put("hibernate.show_sql", false);
properties.put("hbm2ddl.auto", "create");
properties.put("hibernate.hbm2ddl.auto", "create");
- sessionFactory.setHibernateProperties(properties);
sessionFactory.setPackagesToScan("org.onap");
+ sessionFactory.setHibernateProperties(properties);
return sessionFactory;
}
@@ -55,6 +54,7 @@ public class DataSourceConfig {
public Properties getH2Properties() {
Properties properties = new Properties();
properties.put("dialect", "org.hibernate.dialect.H2Dialect");
+ properties.put("hibernate.default_schema", "PUBLIC");
return properties;
}
@@ -64,6 +64,7 @@ public class DataSourceConfig {
properties.put("connection.url", "jdbc:sqlite:memory:myDb");
properties.put("connection.username", "sa");
properties.put("connection.password", "sa");
+ properties.put("hibernate.default_schema", "PUBLIC");
properties.put("dialect", "com.enigmabridge.hibernate.dialect.SQLiteDialect");
return properties;
}
diff --git a/vid-app-common/src/test/java/org/onap/vid/config/JobCommandsConfigWithMockedMso.java b/vid-app-common/src/test/java/org/onap/vid/config/JobCommandsConfigWithMockedMso.java
index c1ac6a219..9cb9b33db 100644
--- a/vid-app-common/src/test/java/org/onap/vid/config/JobCommandsConfigWithMockedMso.java
+++ b/vid-app-common/src/test/java/org/onap/vid/config/JobCommandsConfigWithMockedMso.java
@@ -1,57 +1,27 @@
-/*-
- * ============LICENSE_START=======================================================
- * VID
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2018 Nokia. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
package org.onap.vid.config;
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import java.io.IOException;
import org.hibernate.SessionFactory;
import org.mockito.Mockito;
import org.onap.portalsdk.core.service.DataAccessService;
-import org.onap.vid.aai.AaiOverTLSClient;
-import org.onap.vid.aai.AaiOverTLSClientInterface;
-import org.onap.vid.aai.AaiOverTLSPropertySupplier;
+import org.onap.vid.aai.AaiClientInterface;
import org.onap.vid.aai.util.HttpsAuthClient;
import org.onap.vid.aai.util.SSLContextProvider;
+import org.onap.vid.aai.util.ServletRequestHelper;
import org.onap.vid.aai.util.SystemPropertyHelper;
-import org.onap.vid.client.SyncRestClient;
import org.onap.vid.job.JobAdapter;
import org.onap.vid.job.JobsBrokerService;
-import org.onap.vid.job.command.InProgressStatusCommand;
-import org.onap.vid.job.command.JobCommandFactory;
-import org.onap.vid.job.command.ServiceInstantiationCommand;
+import org.onap.vid.job.command.*;
import org.onap.vid.job.impl.JobAdapterImpl;
import org.onap.vid.job.impl.JobWorker;
import org.onap.vid.job.impl.JobsBrokerServiceInDatabaseImpl;
import org.onap.vid.mso.RestMsoImplementation;
-import org.onap.vid.services.AsyncInstantiationBusinessLogic;
-import org.onap.vid.services.AsyncInstantiationBusinessLogicImpl;
-import org.onap.vid.services.AuditService;
-import org.onap.vid.services.AuditServiceImpl;
+import org.onap.vid.services.*;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
+import org.togglz.core.manager.FeatureManager;
@Configuration
public class JobCommandsConfigWithMockedMso {
@@ -67,8 +37,23 @@ public class JobCommandsConfigWithMockedMso {
}
@Bean
- public HttpsAuthClient httpsAuthClientFactory(){
- return new HttpsAuthClient("some random path", new SystemPropertyHelper(), new SSLContextProvider());
+ public SSLContextProvider sslContextProvider() {
+ return new SSLContextProvider();
+ }
+
+ @Bean
+ public SystemPropertyHelper systemPropertyHelper() {
+ return new SystemPropertyHelper();
+ }
+
+ @Bean
+ public ServletRequestHelper servletRequestHelper() {
+ return new ServletRequestHelper();
+ }
+
+ @Bean
+ public HttpsAuthClient httpsAuthClientFactory(SystemPropertyHelper systemPropertyHelper, SSLContextProvider sslContextProvider, FeatureManager featureManager){
+ return new HttpsAuthClient("some random path", systemPropertyHelper, sslContextProvider, featureManager);
}
@Bean
@@ -90,31 +75,8 @@ public class JobCommandsConfigWithMockedMso {
}
@Bean
- public AaiOverTLSClientInterface AaiOverTLSClient(){
- io.joshworks.restclient.http.mapper.ObjectMapper objectMapper = new io.joshworks.restclient.http.mapper.ObjectMapper() {
-
- ObjectMapper om = new ObjectMapper();
-
- @Override
- public <T> T readValue(String s, Class<T> aClass) {
- try {
- return om.readValue(s, aClass);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- @Override
- public String writeValue(Object o) {
- try {
- return om.writeValueAsString(o);
- } catch (JsonProcessingException e) {
- throw new RuntimeException(e);
- }
- }
- };
-
- return new AaiOverTLSClient(new SyncRestClient(objectMapper), new AaiOverTLSPropertySupplier());
+ public FeatureManager featureManager() {
+ return Mockito.mock(FeatureManager.class);
}
@Bean
@@ -122,25 +84,130 @@ public class JobCommandsConfigWithMockedMso {
JobAdapter jobAdapter,
JobsBrokerService jobsBrokerService,
SessionFactory sessionFactory,
- AaiOverTLSClientInterface aaiOverTLSClientInterface) {
- return new AsyncInstantiationBusinessLogicImpl(dataAccessService, jobAdapter, jobsBrokerService, sessionFactory, aaiOverTLSClientInterface);
+ AaiClientInterface aaiClient,
+ FeatureManager featureManager,
+ CloudOwnerService cloudOwnerService) {
+ return new AsyncInstantiationBusinessLogicImpl(dataAccessService, jobAdapter, jobsBrokerService, sessionFactory, aaiClient, featureManager, cloudOwnerService);
+ }
+
+ @Bean
+ @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
+ public MacroServiceInstantiationCommand serviceInstantiationCommand() {
+ return new MacroServiceInstantiationCommand();
+ }
+
+ @Bean
+ @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
+ public ServiceInProgressStatusCommand inProgressStatusCommand() {
+ return new ServiceInProgressStatusCommand();
+ }
+
+ @Bean
+ @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
+ public ALaCarteServiceInstantiationCommand aLaCarteServiceInstantiationCommand() {
+ return new ALaCarteServiceInstantiationCommand();
+ }
+
+ @Bean
+ @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
+ public ALaCarteServiceCommand aLaCarteServiceCommand(
+ AsyncInstantiationBusinessLogic asyncInstantiationBusinessLogic,
+ JobsBrokerService jobsBrokerService,
+ MsoResultHandlerService msoResultHandlerService,
+ JobAdapter jobAdapter,
+ InProgressStatusService inProgressStatusService,
+ WatchChildrenJobsBL watchChildrenJobsBL,
+ RestMsoImplementation restMso) {
+ return new ALaCarteServiceCommand(inProgressStatusService, watchChildrenJobsBL, asyncInstantiationBusinessLogic, jobsBrokerService, msoResultHandlerService, jobAdapter, restMso);
+ }
+
+ @Bean
+ @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
+ public InstanceGroupCommand instanceGroupCommand(
+ AsyncInstantiationBusinessLogic asyncInstantiationBusinessLogic,
+ MsoResultHandlerService msoResultHandlerService, InProgressStatusService inProgressStatusService,
+ WatchChildrenJobsBL watchChildrenJobsBL,
+ RestMsoImplementation restMso) {
+ return new InstanceGroupCommand(asyncInstantiationBusinessLogic, restMso, msoResultHandlerService, inProgressStatusService, watchChildrenJobsBL);
+ }
+
+ @Bean
+ @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
+ public VnfInstantiationCommand vnfInstantiationCommand() {
+ return new VnfInstantiationCommand();
+ }
+
+ @Bean
+ @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
+ public VolumeGroupInstantiationCommand volumeGroupInstantiationCommand() {
+ return new VolumeGroupInstantiationCommand();
}
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
- public ServiceInstantiationCommand serviceInstantiationCommand() {
- return new ServiceInstantiationCommand();
+ public WatchingCommandBaseModule watchingCommandBaseModule() {
+ return new WatchingCommandBaseModule();
}
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
- public InProgressStatusCommand inProgressStatusCommand() {
- return new InProgressStatusCommand();
+ public VolumeGroupInProgressStatusCommand volumeGroupInProgressStatusCommand() {
+ return new VolumeGroupInProgressStatusCommand();
+ }
+
+ @Bean
+ @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
+ public VfmoduleInstantiationCommand vfmoduleInstantiationCommand() {
+ return new VfmoduleInstantiationCommand();
+ }
+
+ @Bean
+ @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
+ public WatchingCommand watchingCommandCommand() {
+ return new WatchingCommand();
+ }
+
+ @Bean
+ @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
+ public ResourceInProgressStatusCommand resourceInProgressStatusCommand() {
+ return new ResourceInProgressStatusCommand();
+ }
+
+ @Bean
+ @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
+ public VnfInProgressStatusCommand vnfInProgressStatusCommand() {
+ return new VnfInProgressStatusCommand();
+ }
+
+ @Bean
+ @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
+ public InstanceGroupInstantiationCommand instanceGroupInstantiationCommand() {
+ return new InstanceGroupInstantiationCommand();
+ }
+
+ @Bean
+ public AuditService auditService(AsyncInstantiationBusinessLogic asyncInstantiationBL, RestMsoImplementation msoClient) {
+ return new AuditServiceImpl(asyncInstantiationBL, msoClient);
+ }
+
+ @Bean
+ public InProgressStatusService inProgressStatusService(AsyncInstantiationBusinessLogic asyncInstantiationBL, RestMsoImplementation restMso, AuditService auditService) {
+ return new InProgressStatusService(asyncInstantiationBL, restMso, auditService);
+ }
+
+ @Bean
+ public MsoResultHandlerService rootCommandService(AsyncInstantiationBusinessLogic asyncInstantiationBL, AuditService auditService) {
+ return new MsoResultHandlerService(asyncInstantiationBL, auditService);
+ }
+
+ @Bean
+ public CommandUtils commandUtils() {
+ return Mockito.mock(CommandUtils.class);
}
@Bean
- public AuditService auditService() {
- return new AuditServiceImpl();
+ public WatchChildrenJobsBL watchChildrenJobsService(DataAccessService dataAccessService) {
+ return new WatchChildrenJobsBL(dataAccessService);
}
}
diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/AaiControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/AaiControllerTest.java
index 4076b3de9..d86ab78ab 100644
--- a/vid-app-common/src/test/java/org/onap/vid/controller/AaiControllerTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/controller/AaiControllerTest.java
@@ -7,9 +7,6 @@ import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.onap.vid.aai.AaiResponseTranslator;
-import org.onap.vid.aai.AaiResponseTranslator.PortMirroringConfigDataError;
-import org.onap.vid.aai.AaiResponseTranslator.PortMirroringConfigDataOk;
-import org.onap.vid.controllers.AaiController;
import org.onap.vid.services.AaiService;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
@@ -19,7 +16,6 @@ import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
-
public class AaiControllerTest {
@InjectMocks
@@ -36,9 +32,9 @@ public class AaiControllerTest {
@Test
public void getPortMirroringConfigData_givenThreeIds_ReturnsThreeResults() {
- final PortMirroringConfigDataOk toBeReturnedForA = new PortMirroringConfigDataOk("foobar");
- final PortMirroringConfigDataError toBeReturnedForB = new PortMirroringConfigDataError("foo", "{ baz: qux }");
- final PortMirroringConfigDataOk toBeReturnedForC = new PortMirroringConfigDataOk("corge");
+ final AaiResponseTranslator.PortMirroringConfigDataOk toBeReturnedForA = new AaiResponseTranslator.PortMirroringConfigDataOk("foobar");
+ final AaiResponseTranslator.PortMirroringConfigDataError toBeReturnedForB = new AaiResponseTranslator.PortMirroringConfigDataError("foo", "{ baz: qux }");
+ final AaiResponseTranslator.PortMirroringConfigDataOk toBeReturnedForC = new AaiResponseTranslator.PortMirroringConfigDataOk("corge");
Mockito
.doReturn(toBeReturnedForA)
@@ -57,4 +53,4 @@ public class AaiControllerTest {
-}
+} \ No newline at end of file
diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/AaiServiceInstanceStandardQueryControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/AaiServiceInstanceStandardQueryControllerTest.java
new file mode 100644
index 000000000..9a5ee3ecb
--- /dev/null
+++ b/vid-app-common/src/test/java/org/onap/vid/controller/AaiServiceInstanceStandardQueryControllerTest.java
@@ -0,0 +1,120 @@
+package org.onap.vid.controller;
+
+import org.mockito.Answers;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.onap.vid.aai.util.ServiceInstanceStandardQuery;
+import org.onap.vid.asdc.AsdcCatalogException;
+import org.onap.vid.model.Service;
+import org.onap.vid.model.ServiceModel;
+import org.onap.vid.model.VidNotions;
+import org.onap.vid.model.VidNotions.ModelCategory;
+import org.onap.vid.properties.Features;
+import org.onap.vid.services.VidService;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.Test;
+import org.togglz.core.manager.FeatureManager;
+
+import java.util.UUID;
+
+import static org.hamcrest.Matchers.hasSize;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.*;
+
+public class AaiServiceInstanceStandardQueryControllerTest {
+
+ @InjectMocks
+ private AaiServiceInstanceStandardQueryController aaiServiceInstanceStandardQueryController;
+
+ @Mock
+ private FeatureManager featureManager;
+
+ @Mock
+ private VidService sdcService;
+
+ @Mock(answer = Answers.RETURNS_MOCKS)
+ private ServiceInstanceStandardQuery serviceInstanceStandardQuery;
+
+ //Don't use initMocks with @BeforeMethod
+ //because AaiServiceInstanceStandardQueryController contains final members that can not be injected twice
+ //See https://stackoverflow.com/questions/20046210/mockito-injectmocks-strange-behaviour-with-final-fields?answertab=active#tab-top
+ @BeforeClass
+ public void initMocks() {
+ MockitoAnnotations.initMocks(this);
+ }
+
+ @AfterMethod
+ public void resetMocks() {
+ reset(sdcService, featureManager, serviceInstanceStandardQuery);
+ }
+
+ @Test
+ public void getNetworksToVlansByServiceInstance_given5G_PROVIDER_NETWORK_aaiIsAccessed() throws AsdcCatalogException {
+ // - turn on FLAG_PRESENT_PROVIDER_NETWORKS
+ // - mock an model with 5G_PROVIDER_NETWORK
+ // - request it's AAI network->vlan mapping
+ // - assert that AAI was accessed
+
+ when(featureManager.isActive(Features.FLAG_PRESENT_PROVIDER_NETWORKS_ASSOCIATIONS)).thenReturn(true);
+
+ final UUID randomModelUuid = UUID.randomUUID();
+ mockServiceModel(ModelCategory.IS_5G_PROVIDER_NETWORK_MODEL, randomModelUuid);
+
+ doGetNetworksToVlansByServiceInstance(randomModelUuid);
+
+ verify(serviceInstanceStandardQuery).fetchServiceInstance(any(), any(), any());
+ }
+
+ @Test
+ public void getNetworksToVlansByServiceInstance_givenNon5G_PROVIDER_NETWORK_aaiIsNotAccessed() throws AsdcCatalogException {
+ // - turn on FLAG_PRESENT_PROVIDER_NETWORKS
+ // - mock an model without 5G_PROVIDER_NETWORK (i.e. OTHER)
+ // - request it's AAI network->vlan mapping
+ // - assert that AAI was not accessed
+ // - empty result was responded
+
+ when(featureManager.isActive(Features.FLAG_PRESENT_PROVIDER_NETWORKS_ASSOCIATIONS)).thenReturn(true);
+
+ final UUID randomModelUuid = UUID.randomUUID();
+ mockServiceModel(ModelCategory.OTHER, randomModelUuid);
+
+ assertThat(doGetNetworksToVlansByServiceInstance(randomModelUuid).serviceNetworks, hasSize(0));
+ verifyZeroInteractions(serviceInstanceStandardQuery);
+ }
+
+ @Test
+ public void isModelOf5g_givenServiceWithFabricConfiguration_returnTrue() throws AsdcCatalogException {
+ final UUID randomModelUuid = UUID.randomUUID();
+ mockServiceModel(ModelCategory.IS_5G_FABRIC_CONFIGURATION_MODEL, randomModelUuid, VidNotions.InstantiationUI.SERVICE_WITH_FABRIC_CONFIGURATION);
+
+ assertTrue(aaiServiceInstanceStandardQueryController.isModelOf5g(randomModelUuid));
+ }
+
+ private void mockServiceModel(ModelCategory modelCategory, UUID randomModelUuid) throws AsdcCatalogException {
+ mockServiceModel(modelCategory, randomModelUuid, VidNotions.InstantiationUI.LEGACY);
+ }
+
+ private void mockServiceModel(ModelCategory modelCategory, UUID randomModelUuid, VidNotions.InstantiationUI instantiationUI) throws AsdcCatalogException {
+ ServiceModel mockedModel = mock(ServiceModel.class);
+ Service mockedService = mock(Service.class);
+ when(mockedModel.getService()).thenReturn(mockedService);
+ when(mockedService.getVidNotions()).thenReturn(
+ new VidNotions(instantiationUI, modelCategory, VidNotions.InstantiationUI.LEGACY)
+ );
+
+ when(sdcService.getService(randomModelUuid.toString())).thenReturn(mockedModel);
+ }
+
+ private AaiServiceInstanceStandardQueryController.VlansByNetworksHierarchy doGetNetworksToVlansByServiceInstance(UUID randomModelUuid) throws AsdcCatalogException {
+ return aaiServiceInstanceStandardQueryController.getNetworksToVlansByServiceInstance(
+ new MockHttpServletRequest(),
+ randomModelUuid,
+ "my global customer id",
+ "my service type",
+ "my instance id");
+ }
+} \ No newline at end of file
diff --git a/vid-app-common/src/test/java/org/onap/vid/controllers/ChangeManagementControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/ChangeManagementControllerTest.java
index 3c8250b26..420b61ed1 100644
--- a/vid-app-common/src/test/java/org/onap/vid/controllers/ChangeManagementControllerTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/controller/ChangeManagementControllerTest.java
@@ -20,57 +20,29 @@
* ============LICENSE_END=========================================================
*/
-package org.onap.vid.controllers;
-
-import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.BDDMockito.given;
-import static org.mockito.BDDMockito.willThrow;
-import static org.mockito.Matchers.argThat;
-import static org.mockito.Matchers.isA;
-import static org.onap.vid.controllers.ChangeManagementController.CHANGE_MANAGEMENT;
-import static org.onap.vid.controllers.ChangeManagementController.GET_VNF_WORKFLOW_RELATION;
-import static org.onap.vid.controllers.ChangeManagementController.SCHEDULER_BY_SCHEDULE_ID;
-import static org.onap.vid.controllers.ChangeManagementController.VNF_WORKFLOW_RELATION;
-import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
-import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
-import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
-import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
-import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+package org.onap.vid.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
import com.google.common.collect.ImmutableList;
-import java.io.IOException;
-import java.io.InputStream;
-import java.nio.charset.StandardCharsets;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Scanner;
-import javax.ws.rs.WebApplicationException;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.log4j.BasicConfigurator;
-import org.json.simple.JSONArray;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatcher;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
-import org.onap.vid.changeManagement.GetVnfWorkflowRelationRequest;
-import org.onap.vid.changeManagement.GetWorkflowsResponse;
-import org.onap.vid.changeManagement.VnfDetailsWithWorkflows;
-import org.onap.vid.changeManagement.VnfWorkflowRelationAllResponse;
-import org.onap.vid.changeManagement.VnfWorkflowRelationResponse;
-import org.onap.vid.domain.mso.InstanceIds;
-import org.onap.vid.domain.mso.RequestStatus;
+import org.onap.vid.changeManagement.*;
import org.onap.vid.exceptions.NotFoundException;
import org.onap.vid.model.ExceptionResponse;
+import org.onap.vid.mso.rest.InstanceIds;
import org.onap.vid.mso.rest.Request;
+import org.onap.vid.mso.rest.RequestStatus;
import org.onap.vid.services.ChangeManagementService;
import org.onap.vid.services.WorkflowService;
import org.springframework.http.HttpStatus;
@@ -81,6 +53,26 @@ import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.multipart.MultipartFile;
+import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Scanner;
+
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.BDDMockito.given;
+import static org.mockito.BDDMockito.willThrow;
+import static org.mockito.Matchers.argThat;
+import static org.mockito.Matchers.isA;
+import static org.onap.vid.controller.ChangeManagementController.*;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
@RunWith(MockitoJUnitRunner.class)
public class ChangeManagementControllerTest {
@@ -236,7 +228,8 @@ public class ChangeManagementControllerTest {
@Test
public void getSchedulerChangeManagements_shouldReturnJsonArray_whenServiceReturnsCorrectValue() throws Exception {
- JSONArray array = new JSONArray();
+ ObjectMapper mapper = new ObjectMapper();
+ ArrayNode array = mapper.createArrayNode();
array.add("element1");
array.add("element2");
@@ -244,7 +237,7 @@ public class ChangeManagementControllerTest {
mockMvc.perform(get(SCHEDULER_URL))
.andExpect(status().isOk())
- .andExpect(content().json(array.toJSONString()));
+ .andExpect(content().json(mapper.writeValueAsString(array)));
}
@Test
diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/ClientCredentialsFilterTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/ClientCredentialsFilterTest.java
index 113bf2bf9..1b22d7738 100644
--- a/vid-app-common/src/test/java/org/onap/vid/controller/ClientCredentialsFilterTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/controller/ClientCredentialsFilterTest.java
@@ -19,7 +19,6 @@ import static org.mockito.ArgumentMatchers.any;
/**
* Created by amichai on 16/05/2018.
*/
-@Test
public class ClientCredentialsFilterTest {
@DataProvider
diff --git a/vid-app-common/src/test/java/org/onap/vid/controllers/HealthCheckControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/HealthCheckControllerTest.java
index 4894f35ea..4f915ec49 100644
--- a/vid-app-common/src/test/java/org/onap/vid/controllers/HealthCheckControllerTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/controller/HealthCheckControllerTest.java
@@ -1,4 +1,4 @@
-package org.onap.vid.controllers;
+package org.onap.vid.controller;
import org.apache.log4j.BasicConfigurator;
import org.junit.Before;
diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/LocalWebConfig.java b/vid-app-common/src/test/java/org/onap/vid/controller/LocalWebConfig.java
index f63580d27..e0ab34cd1 100644
--- a/vid-app-common/src/test/java/org/onap/vid/controller/LocalWebConfig.java
+++ b/vid-app-common/src/test/java/org/onap/vid/controller/LocalWebConfig.java
@@ -29,6 +29,7 @@ import org.onap.vid.aai.model.PortDetailsTranslator;
import org.onap.vid.aai.util.*;
import org.onap.vid.asdc.AsdcClient;
import org.onap.vid.asdc.parser.ToscaParserImpl2;
+import org.onap.vid.asdc.parser.VidNotionsBuilder;
import org.onap.vid.services.AaiService;
import org.onap.vid.services.AaiServiceImpl;
import org.onap.vid.services.VidService;
@@ -81,9 +82,14 @@ public class LocalWebConfig {
}
@Bean
- public HttpsAuthClient httpsAuthClientFactory(ServletContext servletContext, SystemPropertyHelper systemPropertyHelper, SSLContextProvider sslContextProvider) {
+ public HttpsAuthClient httpsAuthClientFactory(ServletContext servletContext, SystemPropertyHelper systemPropertyHelper, SSLContextProvider sslContextProvider, FeatureManager featureManager) {
final String certFilePath = new File(servletContext.getRealPath("/WEB-INF/cert/")).getAbsolutePath();
- return new HttpsAuthClient(certFilePath, systemPropertyHelper, sslContextProvider);
+ return new HttpsAuthClient(certFilePath, systemPropertyHelper, sslContextProvider, featureManager);
+ }
+
+ @Bean
+ public CacheProvider cacheProvider() {
+ return new NonCachingCacheProvider();
}
@Bean(name = "aaiRestInterface")
@@ -92,13 +98,18 @@ public class LocalWebConfig {
}
@Bean
- public AaiClientInterface getAaiClientInterface(@Qualifier("aaiRestInterface")AAIRestInterface aaiRestInterface, PortDetailsTranslator portDetailsTranslator) {
- return new AaiClient(aaiRestInterface, portDetailsTranslator);
+ public AaiClientInterface getAaiClientInterface(@Qualifier("aaiRestInterface") AAIRestInterface aaiRestInterface, PortDetailsTranslator portDetailsTranslator, CacheProvider cacheProvider) {
+ return new AaiClient(aaiRestInterface, portDetailsTranslator, cacheProvider);
+ }
+
+ @Bean
+ public VidNotionsBuilder vidNotionsBuilder(FeatureManager featureManager) {
+ return new VidNotionsBuilder(featureManager);
}
@Bean
- public ToscaParserImpl2 getToscaParser() {
- return new ToscaParserImpl2();
+ public ToscaParserImpl2 getToscaParser(VidNotionsBuilder vidNotionsBuilder) {
+ return new ToscaParserImpl2(vidNotionsBuilder);
}
@Bean
diff --git a/vid-app-common/src/test/java/org/onap/vid/controllers/LoggerControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/LoggerControllerTest.java
index 5a3002aba..b79f84ad8 100644
--- a/vid-app-common/src/test/java/org/onap/vid/controllers/LoggerControllerTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/controller/LoggerControllerTest.java
@@ -1,13 +1,8 @@
-package org.onap.vid.controllers;
+package org.onap.vid.controller;
-import static org.junit.Assert.*;
-import java.util.*;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.NotAuthorizedException;
-
-import org.junit.Assert;
import org.junit.Test;
-import org.onap.vid.model.ExceptionResponse;
+
+import javax.ws.rs.NotAuthorizedException;
public class LoggerControllerTest {
diff --git a/vid-app-common/src/test/java/org/onap/vid/controllers/MaintenanceControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/MaintenanceControllerTest.java
index 3a9d88f07..6933a2f8d 100644
--- a/vid-app-common/src/test/java/org/onap/vid/controllers/MaintenanceControllerTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/controller/MaintenanceControllerTest.java
@@ -1,4 +1,4 @@
-package org.onap.vid.controllers;
+package org.onap.vid.controller;
/*-
* ============LICENSE_START=======================================================
@@ -22,10 +22,10 @@ package org.onap.vid.controllers;
* ============LICENSE_END=========================================================
*/
+import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import org.apache.log4j.BasicConfigurator;
-import org.codehaus.jackson.map.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
diff --git a/vid-app-common/src/test/java/org/onap/vid/controllers/MsoControllerNewTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/MsoControllerNewTest.java
index d1e09ce8d..747783d52 100644
--- a/vid-app-common/src/test/java/org/onap/vid/controllers/MsoControllerNewTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/controller/MsoControllerNewTest.java
@@ -1,20 +1,23 @@
-package org.onap.vid.controllers;
-
-import static org.junit.Assert.*;
-
-import javax.servlet.http.HttpServletRequest;
+package org.onap.vid.controller;
import org.junit.Test;
import org.onap.vid.mso.MsoBusinessLogicImpl;
+import org.onap.vid.mso.MsoInterface;
import org.onap.vid.mso.rest.RequestDetails;
import org.onap.vid.mso.rest.RequestDetailsWrapper;
+import org.onap.vid.services.CloudOwnerServiceImpl;
import org.springframework.http.ResponseEntity;
+import org.togglz.core.manager.FeatureManager;
+
+import javax.servlet.http.HttpServletRequest;
+
+import static org.mockito.Mockito.mock;
public class MsoControllerNewTest {
private MsoController createTestSubject() {
try {
- return new MsoController(new MsoBusinessLogicImpl(null,null));
+ return new MsoController(new MsoBusinessLogicImpl(mock(MsoInterface.class),mock(FeatureManager.class)), new CloudOwnerServiceImpl(null, null));
} catch (Exception e) {
return null;
}
diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/MsoControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/MsoControllerTest.java
index 4645a83ad..c69bce32b 100644
--- a/vid-app-common/src/test/java/org/onap/vid/controller/MsoControllerTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/controller/MsoControllerTest.java
@@ -2,10 +2,8 @@ package org.onap.vid.controller;
import org.apache.commons.lang.StringEscapeUtils;
import org.onap.portalsdk.core.util.SystemProperties;
-import org.onap.vid.controllers.MsoConfig;
-import org.onap.vid.controllers.MsoController;
-import org.onap.vid.domain.mso.RequestInfo;
import org.onap.vid.factories.MsoRequestFactory;
+import org.onap.vid.mso.model.RequestInfo;
import org.onap.vid.mso.rest.Request;
import org.onap.vid.mso.rest.RequestDetails;
import org.onap.vid.mso.rest.Task;
@@ -15,7 +13,6 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.springframework.test.context.web.WebAppConfiguration;
import org.testng.Assert;
-import org.testng.Assert.*;
import org.testng.annotations.Test;
import java.util.List;
@@ -32,7 +29,7 @@ public class MsoControllerTest extends AbstractTestNGSpringContextTests {
public void testInstanceCreationNew() throws Exception {
RequestDetails requestDetails = msoRequestFactory.createMsoRequest("msoRequest.json");
- MsoController msoController = new MsoController(null);
+ MsoController msoController = new MsoController(null, null);
//TODO: make ths test to really test something
//ResponseEntity<String> responseEntityNew = msoController.createSvcInstanceNew(null, requestDetails);
ResponseEntity<String> responseEntity = msoController.createSvcInstance(null, requestDetails);
@@ -44,7 +41,7 @@ public class MsoControllerTest extends AbstractTestNGSpringContextTests {
public void testInstanceCreationLocalWithRest() throws Exception {
RequestDetails requestDetails = msoRequestFactory.createMsoRequest("msoRequest.json");
- MsoController msoController = new MsoController(null);
+ MsoController msoController = new MsoController(null, null);
ResponseEntity<String> responseEntityNew = msoController.createSvcInstance(null, requestDetails);
//TODO: make ths test to really test something
// ResponseEntity<String> responseEntityRest = msoController.createSvcInstanceNewRest(null, requestDetails);
@@ -57,7 +54,7 @@ public class MsoControllerTest extends AbstractTestNGSpringContextTests {
public void testInstanceCreation() throws Exception {
RequestDetails requestDetails = msoRequestFactory.createMsoRequest("msoRequest.json");
- MsoController msoController = new MsoController(null);
+ MsoController msoController = new MsoController(null, null);
ResponseEntity<String> responseEntity = msoController.createSvcInstance(null, requestDetails);
@@ -72,7 +69,7 @@ public class MsoControllerTest extends AbstractTestNGSpringContextTests {
@Test(enabled = false)
public void testGetOrchestrationRequestsForDashboard() throws Exception {
- MsoController msoController = new MsoController(null);
+ MsoController msoController = new MsoController(null, null);
List<Request> orchestrationRequestsForDashboard = msoController.getOrchestrationRequestsForDashboard();
Assert.assertEquals(orchestrationRequestsForDashboard.size(), 2);
@@ -80,7 +77,7 @@ public class MsoControllerTest extends AbstractTestNGSpringContextTests {
@Test(enabled = false)
public void testGetManualTasksByRequestId() throws Exception {
- MsoController msoController = new MsoController(null);
+ MsoController msoController = new MsoController(null, null);
List<Task> orchestrationRequestsForDashboard = msoController.getManualTasksByRequestId("za1234d1-5a33-55df-13ab-12abad84e335");
Assert. assertEquals(orchestrationRequestsForDashboard.get(0).getTaskId(), "daf4dd84-b77a-42da-a051-3239b7a9392c");
@@ -94,7 +91,7 @@ public class MsoControllerTest extends AbstractTestNGSpringContextTests {
requestInfo.setSource("VID");
RequestDetails requestDetails = new RequestDetails();
requestDetails.setRequestInfo(requestInfo);
- MsoController msoController = new MsoController(null);
+ MsoController msoController = new MsoController(null, null);
ResponseEntity<String> responseEntity = msoController.manualTaskComplete("daf4dd84-b77a-42da-a051-3239b7a9392c", requestDetails);
String assertString = "{ \\\"status\\\": 200, \\\"entity\\\": {\\n\" +\n" +
" \" \\\"taskRequestReference\\\": {\\n\" +\n" +
diff --git a/vid-app-common/src/test/java/org/onap/vid/controllers/PropertyControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/PropertyControllerTest.java
index b4a6a8f96..e9d2cfd44 100644
--- a/vid-app-common/src/test/java/org/onap/vid/controllers/PropertyControllerTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/controller/PropertyControllerTest.java
@@ -1,12 +1,11 @@
-package org.onap.vid.controllers;
-
-import javax.servlet.http.HttpServletRequest;
+package org.onap.vid.controller;
import org.junit.Test;
-import org.onap.vid.controllers.PropertyController;
import org.springframework.http.ResponseEntity;
import org.springframework.web.servlet.ModelAndView;
+import javax.servlet.http.HttpServletRequest;
+
public class PropertyControllerTest {
private PropertyController createTestSubject() {
diff --git a/vid-app-common/src/test/java/org/onap/vid/controllers/RoleGeneratorControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/RoleGeneratorControllerTest.java
index 11ab2fccc..c19b810d0 100644
--- a/vid-app-common/src/test/java/org/onap/vid/controllers/RoleGeneratorControllerTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/controller/RoleGeneratorControllerTest.java
@@ -1,4 +1,4 @@
-package org.onap.vid.controllers;
+package org.onap.vid.controller;
import org.junit.Test;
import org.springframework.http.ResponseEntity;
diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/ServicePermissionsTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/ServicePermissionsTest.java
new file mode 100644
index 000000000..f9f80d1b7
--- /dev/null
+++ b/vid-app-common/src/test/java/org/onap/vid/controller/ServicePermissionsTest.java
@@ -0,0 +1,48 @@
+package org.onap.vid.controller;
+
+import org.jetbrains.annotations.NotNull;
+import org.onap.vid.aai.model.Permissions;
+import org.onap.vid.roles.RoleProvider;
+import org.onap.vid.roles.RoleValidator;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+import static java.lang.Boolean.FALSE;
+import static java.lang.Boolean.TRUE;
+import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.is;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+public class ServicePermissionsTest {
+
+ @DataProvider
+ public static Object[][] trueAndFalse() {
+ return new Object[][]{{TRUE}, {FALSE}};
+ }
+
+
+ @Test(dataProvider = "trueAndFalse")
+ public void servicePermissions_responseMatchesMockedRoleValidator(boolean expected) {
+ String subscriberId = randomAlphanumeric(8);
+ String serviceType = randomAlphanumeric(8);
+
+ RoleProvider roleProvider = mock(RoleProvider.class);
+ RoleValidator roleValidator = mock(RoleValidator.class);
+ when(roleProvider.getUserRolesValidator(any())).thenReturn(roleValidator);
+ when(roleValidator.isServicePermitted(subscriberId, serviceType)).thenReturn(expected);
+
+ AaiController2 aaiController2 = new AaiController2(null, roleProvider, null);
+
+ Permissions permissions = aaiController2.servicePermissions(unimportantRequest(), subscriberId, serviceType);
+ assertThat(permissions, is(new Permissions(expected)));
+ }
+
+ @NotNull
+ private MockHttpServletRequest unimportantRequest() {
+ return new MockHttpServletRequest("", "");
+ }
+} \ No newline at end of file
diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/ToscaParserMockHelper.java b/vid-app-common/src/test/java/org/onap/vid/controller/ToscaParserMockHelper.java
index 36a179109..5751852af 100644
--- a/vid-app-common/src/test/java/org/onap/vid/controller/ToscaParserMockHelper.java
+++ b/vid-app-common/src/test/java/org/onap/vid/controller/ToscaParserMockHelper.java
@@ -1,42 +1,47 @@
package org.onap.vid.controller;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.module.kotlin.KotlinModule;
+import org.apache.commons.io.IOUtils;
+import org.apache.log4j.LogManager;
+import org.apache.log4j.Logger;
import org.onap.vid.model.NewServiceModel;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+
/**
* Created by moriya1 on 04/07/2017.
*/
public class ToscaParserMockHelper {
+ private static final Logger logger = LogManager.getLogger(ToscaParserMockHelper.class);
- private String uuid;
- private String filePath;
- private NewServiceModel newServiceModel;
+ private static final ObjectMapper om = new ObjectMapper();
+ private final String uuid;
+ private final String filePath;
+ private final NewServiceModel newServiceModel;
- public ToscaParserMockHelper(String uuid, String filePath) {
+ public ToscaParserMockHelper(String uuid, String filePath) throws IOException {
this.uuid = uuid;
this.filePath = filePath;
+
+ InputStream jsonFile = this.getClass().getClassLoader().getResourceAsStream(getFilePath());
+ logger.info(jsonFile);
+ String expectedJsonAsString = IOUtils.toString(jsonFile, StandardCharsets.UTF_8.name());
+ om.registerModule(new KotlinModule());
+ this.newServiceModel = om.readValue(expectedJsonAsString, NewServiceModel.class);
}
public String getUuid() {
return uuid;
}
- public void setUuid(String uuid) {
- this.uuid = uuid;
- }
-
public String getFilePath() {
return filePath;
}
- public void setFilePath(String filePath) {
- this.filePath = filePath;
- }
-
public NewServiceModel getNewServiceModel() {
return newServiceModel;
}
-
- public void setNewServiceModel(NewServiceModel newServiceModel) {
- this.newServiceModel = newServiceModel;
- }
}
diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/VersionControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/VersionControllerTest.java
new file mode 100644
index 000000000..f57ba8a7f
--- /dev/null
+++ b/vid-app-common/src/test/java/org/onap/vid/controller/VersionControllerTest.java
@@ -0,0 +1,31 @@
+package org.onap.vid.controller;
+
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+
+
+public class VersionControllerTest {
+
+ @DataProvider
+ public static Object[][] majorVersionContainer() {
+ return new Object[][]{
+ {"features.properties", "1.0.2000", "features.properties.2000"},
+ {"", "1.0.2000", ".2000"},
+ {"kuku", "1.0.2000", "kuku.2000"},
+ {"/kuku", "1.0.2000", "kuku.2000"},
+ {"1810p.features.properties", "1.0.2000", "1810p.2000"},
+ {"/opt/app/dev.features.properties", "1.0.2000", "dev.2000"},
+ {"foo", "2000", "foo.2000"},
+ };
+ }
+
+ final VersionController versionController = new VersionController(null);
+
+ @Test(dataProvider = "majorVersionContainer")
+ public void testGetDisplayVersion(String majorVersionContainer, String buildNumberContainer, String expected) {
+ assertThat(versionController.getDisplayVersion(majorVersionContainer, buildNumberContainer), is(expected));
+ }
+}
diff --git a/vid-app-common/src/test/java/org/onap/vid/controllers/VidControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/VidControllerTest.java
index 198680afc..aeb03b60c 100644
--- a/vid-app-common/src/test/java/org/onap/vid/controllers/VidControllerTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/controller/VidControllerTest.java
@@ -18,13 +18,13 @@
* ============LICENSE_END=========================================================
*/
-package org.onap.vid.controllers;
+package org.onap.vid.controller;
+import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import org.apache.log4j.BasicConfigurator;
-import org.codehaus.jackson.map.ObjectMapper;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
diff --git a/vid-app-common/src/test/java/org/onap/vid/controllers/ViewEditSubControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/ViewEditSubControllerTest.java
index 7d61f98f9..9729c4e7b 100644
--- a/vid-app-common/src/test/java/org/onap/vid/controllers/ViewEditSubControllerTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/controller/ViewEditSubControllerTest.java
@@ -1,4 +1,4 @@
-package org.onap.vid.controllers;
+package org.onap.vid.controller;
//package org.onap.vid.controller;
//
//import javax.servlet.http.HttpServletRequest;
diff --git a/vid-app-common/src/test/java/org/onap/vid/controllers/AaiControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controllers/AaiControllerTest.java
deleted file mode 100644
index 2a398b361..000000000
--- a/vid-app-common/src/test/java/org/onap/vid/controllers/AaiControllerTest.java
+++ /dev/null
@@ -1,440 +0,0 @@
-package org.onap.vid.controllers;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.json.simple.JSONObject;
-import org.junit.Test;
-import org.onap.vid.aai.AaiResponse;
-import org.onap.vid.aai.model.AaiGetOperationalEnvironments.OperationalEnvironmentList;
-import org.onap.vid.controllers.AaiController;
-import org.onap.vid.model.VersionByInvariantIdsRequest;
-import org.springframework.http.ResponseEntity;
-import org.springframework.web.servlet.ModelAndView;
-import java.util.*;
-import org.junit.Assert;
-
-public class AaiControllerTest {
-
- private AaiController createTestSubject() {
- return new AaiController();
- }
-
- @Test
- public void testWelcome() throws Exception {
- AaiController testSubject;
- HttpServletRequest request = null;
- ModelAndView result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.welcome(request);
- }
-
- @Test
- public void testGetTargetProvStatus() throws Exception {
- AaiController testSubject;
- ResponseEntity<String> result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getTargetProvStatus();
- }
-
- @Test
- public void testViewEditGetTenantsFromServiceType() throws Exception {
- AaiController testSubject;
- HttpServletRequest request = null;
- String globalCustomerId = "";
- String serviceType = "";
- ResponseEntity<String> result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.viewEditGetTenantsFromServiceType(request, globalCustomerId, serviceType);
- }
-
-
-
-
-
- @Test
- public void testGetAicZones() throws Exception {
- AaiController testSubject;
- HttpServletRequest request = null;
- ResponseEntity<String> result;
-
- // default test
- try {
- testSubject = createTestSubject();
- result = testSubject.getAicZones(request);
- } catch (Exception e) {
- }
- }
-
- @Test
- public void testGetAicZoneForPnf() throws Exception {
- AaiController testSubject;
- String globalCustomerId = "";
- String serviceType = "";
- String serviceId = "";
- HttpServletRequest request = null;
- ResponseEntity<String> result;
-
- // default test
- try {
- testSubject = createTestSubject();
- result = testSubject.getAicZoneForPnf(globalCustomerId, serviceType, serviceId, request);
- } catch (Exception e) {
- }
- }
-
- @Test
- public void testGetUserID() throws Exception {
- AaiController testSubject;
- HttpServletRequest request = null;
- ResponseEntity<String> result;
-
- // default test
- try {
- testSubject = createTestSubject();
- result = testSubject.getUserID(request);
- } catch (Exception e) {
- }
- }
-
- @Test
- public void testDoGetServices() throws Exception {
- AaiController testSubject;
- HttpServletRequest request = null;
- ResponseEntity<String> result;
-
- // default test
- try {
- testSubject = createTestSubject();
- result = testSubject.doGetServices(request);
- } catch (Exception e) {
- }
- }
-
- @Test
- public void testGetVersionByInvariantId() throws Exception {
- AaiController testSubject;
- HttpServletRequest request = null;
- VersionByInvariantIdsRequest versions = null;
- ResponseEntity<String> result;
-
- // default test
- try {
- testSubject = createTestSubject();
- result = testSubject.getVersionByInvariantId(request, versions);
- } catch (Exception e) {
- }
- }
-
- // @Test
- // public void testAaiResponseToResponseEntity() throws Exception {
- // AaiController testSubject;AaiResponse aaiResponseData = null;
- // ResponseEntity<String> result;
- //
- // // default test
- // }
-
- @Test
- public void testDoGetServiceInstance() throws Exception {
- AaiController testSubject;
- String serviceInstanceId = "";
- String serviceInstanceType = "";
- ResponseEntity<String> result;
-
- // default test
- try {
- testSubject = createTestSubject();
- result = testSubject.doGetServiceInstance(serviceInstanceId, serviceInstanceType);
- } catch (Exception e) {
- }
- }
-
- @Test
- public void testDoGetServices_1() throws Exception {
- AaiController testSubject;
- String globalCustomerId = "";
- String serviceSubscriptionId = "";
- ResponseEntity<String> result;
-
- // default test
- try {
- testSubject = createTestSubject();
- result = testSubject.doGetServices(globalCustomerId, serviceSubscriptionId);
- } catch (Exception e) {
- }
- }
-
- @Test
- public void testDoGetSubscriberList() throws Exception {
- AaiController testSubject;
- HttpServletRequest request = null;
- String fullSet = "";
- ResponseEntity<String> result;
-
- // default test
- try {
- testSubject = createTestSubject();
- result = testSubject.doGetSubscriberList(request, fullSet);
- } catch (Exception e) {
- }
- }
-
- @Test
- public void testGetOperationalEnvironments() throws Exception {
- AaiController testSubject;
- String operationalEnvironmentType = "";
- String operationalEnvironmentStatus = "";
- AaiResponse<OperationalEnvironmentList> result;
-
- // default test
- try {
- testSubject = createTestSubject();
- result = testSubject.getOperationalEnvironments(operationalEnvironmentType, operationalEnvironmentStatus);
- } catch (Exception e) {
- }
- }
-
- @Test
- public void testGetFullSubscriberList() throws Exception {
- AaiController testSubject;
- HttpServletRequest request = null;
- ResponseEntity<String> result;
-
- // default test
- try {
- testSubject = createTestSubject();
- result = testSubject.getFullSubscriberList(request);
- } catch (Exception e) {
- }
- }
-
- @Test
- public void testGetVnfDataByGlobalIdAndServiceType() throws Exception {
- AaiController testSubject;
- HttpServletRequest request = null;
- String globalCustomerId = "";
- String serviceType = "";
- ResponseEntity<String> result;
-
- // default test
- try {
- testSubject = createTestSubject();
- result = testSubject.getVnfDataByGlobalIdAndServiceType(request, globalCustomerId, serviceType);
- } catch (Exception e) {
- }
- }
-
- @Test
- public void testDoRefreshSubscriberList() throws Exception {
- AaiController testSubject;
- ResponseEntity<String> result;
-
- // default test
- try {
- testSubject = createTestSubject();
- result = testSubject.doRefreshSubscriberList();
- } catch (Exception e) {
- }
- }
-
- @Test
- public void testDoRefreshFullSubscriberList() throws Exception {
- AaiController testSubject;
- ResponseEntity<String> result;
-
- // default test
- try {
- testSubject = createTestSubject();
- result = testSubject.doRefreshFullSubscriberList();
- } catch (Exception e) {
- }
- }
-
- @Test
- public void testGetSubscriberDetails() throws Exception {
- AaiController testSubject;
- HttpServletRequest request = null;
- String subscriberId = "";
- ResponseEntity<String> result;
-
- // default test
- try {
- testSubject = createTestSubject();
- result = testSubject.GetSubscriberDetails(request, subscriberId);
- } catch (Exception e) {
- }
- }
-
- @Test
- public void testSearchServiceInstances() throws Exception {
- AaiController testSubject;
- HttpServletRequest request = null;
- String subscriberId = "";
- String instanceIdentifier = "";
- List<String> projects = null;
- List<String> owningEntities = null;
- ResponseEntity<String> result;
-
- // default test
- try {
- testSubject = createTestSubject();
- result = testSubject.SearchServiceInstances(request, subscriberId, instanceIdentifier, projects,
- owningEntities);
- } catch (Exception e) {
- }
- }
-
- @Test
- public void testViewEditGetComponentList() throws Exception {
- AaiController testSubject;
- String namedQueryId = "";
- String globalCustomerId = "";
- String serviceType = "";
- String serviceInstance = "";
- ResponseEntity<String> result;
-
- // default test
- try {
- testSubject = createTestSubject();
- result = testSubject.viewEditGetComponentList(namedQueryId, globalCustomerId, serviceType, serviceInstance);
- } catch (Exception e) {
- }
- }
-
- @Test
- public void testGetVnfData() throws Exception {
- AaiController testSubject;
- String globalCustomerId = "";
- String serviceType = "";
- String serviceInstanceId = "";
- AaiResponse<String> result;
-
- // default test
- try {
- testSubject = createTestSubject();
- result = testSubject.getVnfData(globalCustomerId, serviceType, serviceInstanceId);
- } catch (Exception e) {
- }
- }
-
- @Test
- public void testViewEditGetComponentList_1() throws Exception {
- AaiController testSubject;
- String namedQueryId = "";
- String globalCustomerId = "";
- String serviceType = "";
- ResponseEntity<String> result;
-
- // default test
- try {
- testSubject = createTestSubject();
- result = testSubject.viewEditGetComponentList(namedQueryId, globalCustomerId, serviceType);
- } catch (Exception e) {
- }
- }
-
- @Test
- public void testGetNodeTemplateInstances() throws Exception {
- AaiController testSubject;
- String globalCustomerId = "";
- String serviceType = "";
- String modelVersionId = "";
- String modelInvariantId = "";
- String cloudRegion = "";
- ResponseEntity<String> result;
-
- // default test
- try {
- testSubject = createTestSubject();
- result = testSubject.getNodeTemplateInstances(globalCustomerId, serviceType, modelVersionId,
- modelInvariantId, cloudRegion);
- } catch (Exception e) {
- }
- }
-
- @Test
- public void testGetByUri() throws Exception {
- AaiController testSubject;
- HttpServletRequest request = null;
- ResponseEntity<String> result;
-
- // default test
- try {
- testSubject = createTestSubject();
- result = testSubject.getByUri(request);
- } catch (Exception e) {
- }
- }
-
- @Test
- public void testGetSpecificConfiguration() throws Exception {
- AaiController testSubject;
- String configurationId = "";
- ResponseEntity<String> result;
-
- // default test
- try {
- testSubject = createTestSubject();
- result = testSubject.getSpecificConfiguration(configurationId);
- } catch (Exception e) {
- }
- }
-
- @Test
- public void testGetServiceInstanceAssociatedPnfs() throws Exception {
- AaiController testSubject;
- String globalCustomerId = "";
- String serviceType = "";
- String serviceInstanceId = "";
- List<String> result;
-
- // default test
- try {
- testSubject = createTestSubject();
- result = testSubject.getServiceInstanceAssociatedPnfs(globalCustomerId, serviceType, serviceInstanceId);
- } catch (Exception e) {
- }
- }
-
- @Test
- public void testGetSpecificPnf() throws Exception {
- AaiController testSubject;
- String pnfId = "";
- ResponseEntity result;
-
- // default test
- try {
- testSubject = createTestSubject();
- result = testSubject.getSpecificPnf(pnfId);
- } catch (Exception e) {
- }
- }
-
- @Test
- public void testGetPnfInstances() throws Exception {
- AaiController testSubject;
- String globalCustomerId = "";
- String serviceType = "";
- String modelVersionId = "";
- String modelInvariantId = "";
- String cloudRegion = "";
- String equipVendor = "";
- String equipModel = "";
- ResponseEntity<String> result;
-
- // default test
- try {
- testSubject = createTestSubject();
- result = testSubject.getPnfInstances(globalCustomerId, serviceType, modelVersionId, modelInvariantId,
- cloudRegion, equipVendor, equipModel);
- } catch (Exception e) {
- }
-
- }
-
-} \ No newline at end of file
diff --git a/vid-app-common/src/test/java/org/onap/vid/controllers/LocalWebConfig.java b/vid-app-common/src/test/java/org/onap/vid/controllers/LocalWebConfig.java
deleted file mode 100644
index 59fed3343..000000000
--- a/vid-app-common/src/test/java/org/onap/vid/controllers/LocalWebConfig.java
+++ /dev/null
@@ -1,70 +0,0 @@
-package org.onap.vid.controllers;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-import org.apache.commons.io.IOUtils;
-import org.json.JSONObject;
-import org.json.JSONTokener;
-import org.onap.vid.aai.AaiClient;
-import org.onap.vid.aai.AaiClientInterface;
-import org.onap.vid.asdc.AsdcClient;
-import org.onap.vid.asdc.local.LocalAsdcClient;
-import org.onap.vid.asdc.parser.ToscaParserImpl2;
-import org.onap.vid.controllers.VidController;
-import org.onap.vid.services.AaiService;
-import org.onap.vid.services.AaiServiceImpl;
-import org.onap.vid.services.VidService;
-import org.onap.vid.services.VidServiceImpl;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-@Configuration
-public class LocalWebConfig {
-
- /**
- * Gets the object mapper.
- *
- * @return the object mapper
- */
- @Bean
- public ObjectMapper getObjectMapper() {
- return new ObjectMapper();
- }
-
-
- @Bean
- public VidService vidService(AsdcClient asdcClient) {
- return new VidServiceImpl(asdcClient, null);
- }
-
- @Bean
- public AaiService getAaiService() {
- return new AaiServiceImpl();
- }
-
- @Bean
- public AaiClientInterface getAaiClientInterface() {
- return new AaiClient(null,null);
- }
-
- @Bean
- public AsdcClient asdcClient() throws IOException {
-
-
- final InputStream asdcServicesFile = VidController.class.getClassLoader().getResourceAsStream("sdcservices.json");
-
- final JSONTokener jsonTokener = new JSONTokener(IOUtils.toString(asdcServicesFile));
- final JSONObject sdcServicesCatalog = new JSONObject(jsonTokener);
-
- return new LocalAsdcClient.Builder().catalog(sdcServicesCatalog).build();
-
- }
-
- @Bean
- public ToscaParserImpl2 getToscaParser() {
- return new ToscaParserImpl2();
- }
-
-}
diff --git a/vid-app-common/src/test/java/org/onap/vid/controllers/MsoControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controllers/MsoControllerTest.java
deleted file mode 100644
index 0d1559548..000000000
--- a/vid-app-common/src/test/java/org/onap/vid/controllers/MsoControllerTest.java
+++ /dev/null
@@ -1,109 +0,0 @@
-package org.onap.vid.controllers;
-
-import org.apache.commons.lang.StringEscapeUtils;
-import org.onap.portalsdk.core.util.SystemProperties;
-import org.onap.vid.controllers.MsoConfig;
-import org.onap.vid.controllers.MsoController;
-import org.onap.vid.domain.mso.RequestInfo;
-import org.onap.vid.factories.MsoRequestFactory;
-import org.onap.vid.mso.rest.Request;
-import org.onap.vid.mso.rest.RequestDetails;
-import org.onap.vid.mso.rest.Task;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.http.ResponseEntity;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
-import org.springframework.test.context.web.WebAppConfiguration;
-import org.testng.Assert;
-import org.testng.Assert.*;
-import org.testng.annotations.Test;
-
-import java.util.List;
-
-
-@WebAppConfiguration
-@ContextConfiguration(classes = {SystemProperties.class, MsoConfig.class})
-public class MsoControllerTest extends AbstractTestNGSpringContextTests {
-
- @Autowired
- MsoRequestFactory msoRequestFactory;
-
- @Test(enabled = false)
- public void testInstanceCreationNew() throws Exception {
-
- RequestDetails requestDetails = msoRequestFactory.createMsoRequest("msoRequest.json");
- MsoController msoController = new MsoController(null);
- //TODO: make ths test to really test something
- //ResponseEntity<String> responseEntityNew = msoController.createSvcInstanceNew(null, requestDetails);
- ResponseEntity<String> responseEntity = msoController.createSvcInstance(null, requestDetails);
- //Assert.assertEquals(responseEntityNew, responseEntity);
-
- }
-
- @Test(enabled = false)
- public void testInstanceCreationLocalWithRest() throws Exception {
-
- RequestDetails requestDetails = msoRequestFactory.createMsoRequest("msoRequest.json");
- MsoController msoController = new MsoController(null);
- ResponseEntity<String> responseEntityNew = msoController.createSvcInstance(null, requestDetails);
- //TODO: make ths test to really test something
-// ResponseEntity<String> responseEntityRest = msoController.createSvcInstanceNewRest(null, requestDetails);
-//
-// Assert.assertEquals(responseEntityNew.getBody(), responseEntityRest.getBody());
-
- }
-
- @Test(enabled = false)
- public void testInstanceCreation() throws Exception {
-
- RequestDetails requestDetails = msoRequestFactory.createMsoRequest("msoRequest.json");
- MsoController msoController = new MsoController(null);
- ResponseEntity<String> responseEntity = msoController.createSvcInstance(null, requestDetails);
-
-
- Assert.assertEquals(responseEntity.getBody(), "{ \"status\": 200, \"entity\": {\n" +
- " \"requestReferences\": {\n" +
- " \"instanceId\": \"ba00de9b-3c3e-4b0a-a1ad-0c5489e711fb\",\n" +
- " \"requestId\": \"311cc766-b673-4a50-b9c5-471f68914586\"\n" +
- " }\n" +
- "}}");
-
- }
-
- @Test(enabled = false)
- public void testGetOrchestrationRequestsForDashboard() throws Exception {
- MsoController msoController = new MsoController(null);
- List<Request> orchestrationRequestsForDashboard = msoController.getOrchestrationRequestsForDashboard();
-
- Assert.assertEquals(orchestrationRequestsForDashboard.size(), 2);
- }
-
- @Test(enabled = false)
- public void testGetManualTasksByRequestId() throws Exception {
- MsoController msoController = new MsoController(null);
- List<Task> orchestrationRequestsForDashboard = msoController.getManualTasksByRequestId("za1234d1-5a33-55df-13ab-12abad84e335");
-
- Assert. assertEquals(orchestrationRequestsForDashboard.get(0).getTaskId(), "daf4dd84-b77a-42da-a051-3239b7a9392c");
- }
-
-
- public void testCompleteManualTask() throws Exception { // TODO not done yet
- RequestInfo requestInfo = new RequestInfo();
- requestInfo.setResponseValue("rollback");
- requestInfo.setRequestorId("abc");
- requestInfo.setSource("VID");
- RequestDetails requestDetails = new RequestDetails();
- requestDetails.setRequestInfo(requestInfo);
- MsoController msoController = new MsoController(null);
- ResponseEntity<String> responseEntity = msoController.manualTaskComplete("daf4dd84-b77a-42da-a051-3239b7a9392c", requestDetails);
- String assertString = "{ \\\"status\\\": 200, \\\"entity\\\": {\\n\" +\n" +
- " \" \\\"taskRequestReference\\\": {\\n\" +\n" +
- " \" \\\"taskId\\\": \\\"daf4dd84-b77a-42da-a051-3239b7a9392c\\\"\\n\" +\n" +
- " \" }\\n\" +\n" +
- " \"}\\n\" +\n" +
- " \"}";
- Assert.assertEquals(responseEntity.getBody(), StringEscapeUtils.unescapeJava(assertString));
- }
-
-
-}
diff --git a/vid-app-common/src/test/java/org/onap/vid/controllers/PolicyControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controllers/PolicyControllerTest.java
deleted file mode 100644
index 33bed45ec..000000000
--- a/vid-app-common/src/test/java/org/onap/vid/controllers/PolicyControllerTest.java
+++ /dev/null
@@ -1,30 +0,0 @@
-package org.onap.vid.controllers;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.json.simple.JSONObject;
-import org.junit.Test;
-import org.onap.vid.policy.PolicyResponseWrapper;
-import org.springframework.http.ResponseEntity;
-
-public class PolicyControllerTest {
-
- private PolicyController createTestSubject() {
- return new PolicyController();
- }
-
- @Test
- public void testGetPolicyInfo() throws Exception {
- PolicyController testSubject;
- HttpServletRequest request = null;
- JSONObject policy_request = null;
- ResponseEntity<String> result;
-
- // default test
- try {
- testSubject = createTestSubject();
- result = testSubject.getPolicyInfo(request, policy_request);
- }catch(Exception e){}
- }
-
-} \ No newline at end of file
diff --git a/vid-app-common/src/test/java/org/onap/vid/controllers/PromiseEcompRequestIdFilterTest.java b/vid-app-common/src/test/java/org/onap/vid/controllers/PromiseEcompRequestIdFilterTest.java
deleted file mode 100644
index f17403955..000000000
--- a/vid-app-common/src/test/java/org/onap/vid/controllers/PromiseEcompRequestIdFilterTest.java
+++ /dev/null
@@ -1,169 +0,0 @@
-package org.onap.vid.controllers;
-
-import com.google.common.collect.ImmutableMap;
-import org.mockito.ArgumentCaptor;
-import org.mockito.Mockito;
-import org.mockito.stubbing.Answer;
-import org.onap.portalsdk.core.web.support.UserUtils;
-import org.onap.vid.controller.filter.PromiseEcompRequestIdFilter;
-import org.springframework.mock.web.MockHttpServletResponse;
-import org.testng.annotations.Test;
-
-import javax.servlet.FilterChain;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import java.io.IOException;
-import java.util.*;
-import java.util.function.Function;
-
-import static org.apache.commons.lang3.StringUtils.equalsIgnoreCase;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.*;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.argThat;
-import static org.onap.portalsdk.core.util.SystemProperties.ECOMP_REQUEST_ID;
-
-@Test
-public class PromiseEcompRequestIdFilterTest {
-
- private final String anotherHeader = "ANDREI_RUBLEV";
- private final String anotherValue = "foo value";
- private final String mixedCaseHeader = "x-ecomp-REQUESTID";
-
- @Test
- public void givenRequestIdHeader_headerValueNotChanged() throws IOException, ServletException {
-
- final String someTxId = "863850e2-8545-4efd-94b8-afba5f52b3d5";
-
- final ImmutableMap<String, String> incomingRequestHeaders = ImmutableMap.of(
- anotherHeader, anotherValue,
- ECOMP_REQUEST_ID, someTxId
- );
-
- buildRequestThenRunThroughFilterAndAssertResultRequestHeaders(incomingRequestHeaders, specificTxId(someTxId));
- }
-
- @Test
- public void givenMixedCaseRequestIdHeader_headerValueNotChanged() throws IOException, ServletException {
-
- final String someTxId = "729bbd8d-b0c2-4809-a794-dcccd9cda2c0";
-
- final ImmutableMap<String, String> incomingRequestHeaders = ImmutableMap.of(
- mixedCaseHeader, someTxId,
- anotherHeader, anotherValue
- );
-
- buildRequestThenRunThroughFilterAndAssertResultRequestHeaders(incomingRequestHeaders, specificTxId(someTxId));
- }
-
- @Test
- public void givenNoRequestIdHeader_headerValueWasGenerated() throws IOException, ServletException {
-
- final ImmutableMap<String, String> incomingRequestHeaders = ImmutableMap.of(
- anotherHeader, anotherValue
- );
-
- buildRequestThenRunThroughFilterAndAssertResultRequestHeaders(incomingRequestHeaders, UserUtils::getRequestId);
- }
-
-
- private void buildRequestThenRunThroughFilterAndAssertResultRequestHeaders(
- ImmutableMap<String, String> originalRequestHeaders,
- Function<HttpServletRequest, String> txIdExtractor
- ) throws IOException, ServletException {
- HttpServletRequest servletRequest = createMockedHttpServletRequest(originalRequestHeaders);
- HttpServletResponse servletResponse = createMockedHttpServletResponse();
-
- final FilterChain capturingFilterChain = Mockito.mock(FilterChain.class);
-
- //////////////////
- //
- // doFilter() is the function under test
- //
- new PromiseEcompRequestIdFilter().doFilter(servletRequest, servletResponse, capturingFilterChain);
- //
- //////////////////
-
- final ServletRequest capturedServletRequest = extractCapturedServletRequest(capturingFilterChain);
- final ServletResponse capturedServletResponse = extractCapturedServletResponse(capturingFilterChain);
- final String expectedTxId = txIdExtractor.apply((HttpServletRequest) capturedServletRequest);
-
- assertRequestObjectHeaders(capturedServletRequest, expectedTxId);
- assertResponseObjectHeaders(capturedServletResponse, expectedTxId);
- }
-
-
- private void assertRequestObjectHeaders(ServletRequest request, String expectedTxId) {
- /*
- Assert that:
- - Two headers are in place
- - Direct value extraction is as expected
- - UserUtils.getRequestId() returns correct and valid value
- */
- final HttpServletRequest httpServletRequest = (HttpServletRequest) request;
-
- assertThat(Collections.list(httpServletRequest.getHeaderNames()),
- containsInAnyOrder(equalToIgnoringCase(ECOMP_REQUEST_ID), equalToIgnoringCase(anotherHeader)));
-
- assertThat(httpServletRequest.getHeader(anotherHeader), is(anotherValue));
-
- assertThat(httpServletRequest.getHeader(ECOMP_REQUEST_ID), is(expectedTxId));
- assertThat(httpServletRequest.getHeader(mixedCaseHeader), is(expectedTxId));
-
- assertThat(UserUtils.getRequestId(httpServletRequest), is(expectedTxId));
- assertThat(UserUtils.getRequestId(httpServletRequest), is(not(emptyOrNullString())));
- }
-
- private void assertResponseObjectHeaders(ServletResponse response, String txId) {
- final String REQUEST_ID_HEADER_NAME_IN_RESPONSE = mixedCaseHeader + "-echo";
- final HttpServletResponse httpServletResponse = (HttpServletResponse) response;
-
- assertThat("header " + REQUEST_ID_HEADER_NAME_IN_RESPONSE.toLowerCase() + " in response must be provided",
- httpServletResponse.getHeader(REQUEST_ID_HEADER_NAME_IN_RESPONSE), is(txId));
- }
-
-
-
- private HttpServletRequest createMockedHttpServletRequest(Map<String, String> requestHeaders) {
- HttpServletRequest servletRequest = Mockito.mock(HttpServletRequest.class);
- requestHeaders.forEach((k, v) -> {
- Mockito.when(servletRequest.getHeader(argThat(s -> equalsIgnoreCase(s, k)))).thenReturn(v);
- Mockito.when(servletRequest.getHeaders(argThat(s -> equalsIgnoreCase(s, k)))).then(returnEnumerationAnswer(v));
- });
- Mockito.when(servletRequest.getHeaderNames()).then(returnEnumerationAnswer(requestHeaders.keySet()));
- return servletRequest;
- }
-
- private HttpServletResponse createMockedHttpServletResponse() {
- return new MockHttpServletResponse();
- }
-
- private static Answer<Enumeration<String>> returnEnumerationAnswer(String ... items) {
- return returnEnumerationAnswer(Arrays.asList(items));
- }
-
- private static Answer<Enumeration<String>> returnEnumerationAnswer(Collection<String> items) {
- return invocation -> Collections.enumeration(items);
- }
-
- private Function<HttpServletRequest, String> specificTxId(String someTxId) {
- return r -> someTxId;
- }
-
- private ServletRequest extractCapturedServletRequest(FilterChain capturingFilterChain) throws IOException, ServletException {
- ArgumentCaptor<ServletRequest> captor = ArgumentCaptor.forClass(ServletRequest.class);
- Mockito.verify(capturingFilterChain).doFilter(captor.capture(), any());
- return captor.getValue();
- }
-
- private ServletResponse extractCapturedServletResponse(FilterChain capturingFilterChain) throws IOException, ServletException {
- ArgumentCaptor<ServletResponse> captor = ArgumentCaptor.forClass(ServletResponse.class);
- Mockito.verify(capturingFilterChain).doFilter(any(), captor.capture());
- return captor.getValue();
- }
-
-}
diff --git a/vid-app-common/src/test/java/org/onap/vid/controllers/ToscaParserMockHelper.java b/vid-app-common/src/test/java/org/onap/vid/controllers/ToscaParserMockHelper.java
deleted file mode 100644
index 317c8e505..000000000
--- a/vid-app-common/src/test/java/org/onap/vid/controllers/ToscaParserMockHelper.java
+++ /dev/null
@@ -1,42 +0,0 @@
-package org.onap.vid.controllers;
-
-import org.onap.vid.model.NewServiceModel;
-
-/**
- * Created by moriya1 on 04/07/2017.
- */
-public class ToscaParserMockHelper {
-
- private String uuid;
- private String filePath;
- private NewServiceModel newServiceModel;
-
- public ToscaParserMockHelper(String uuid, String filePath) {
- this.uuid = uuid;
- this.filePath = filePath;
- }
-
- public String getUuid() {
- return uuid;
- }
-
- public void setUuid(String uuid) {
- this.uuid = uuid;
- }
-
- public String getFilePath() {
- return filePath;
- }
-
- public void setFilePath(String filePath) {
- this.filePath = filePath;
- }
-
- public NewServiceModel getNewServiceModel() {
- return newServiceModel;
- }
-
- public void setNewServiceModel(NewServiceModel newServiceModel) {
- this.newServiceModel = newServiceModel;
- }
-}
diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/CommandUtilsTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/CommandUtilsTest.java
new file mode 100644
index 000000000..61a54f250
--- /dev/null
+++ b/vid-app-common/src/test/java/org/onap/vid/job/command/CommandUtilsTest.java
@@ -0,0 +1,88 @@
+package org.onap.vid.job.command;
+
+import com.google.common.collect.ImmutableMap;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.onap.vid.asdc.AsdcCatalogException;
+import org.onap.vid.model.GroupProperties;
+import org.onap.vid.model.ServiceModel;
+import org.onap.vid.model.VfModule;
+import org.onap.vid.services.VidService;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+import java.util.Collections;
+import java.util.Map;
+import java.util.UUID;
+
+import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.equalTo;
+import static org.mockito.Mockito.*;
+
+public class CommandUtilsTest {
+
+ @InjectMocks
+ CommandUtils commandUtils;
+
+ @Mock
+ VidService vidService;
+
+ @BeforeClass
+ public void initMocks() {
+ MockitoAnnotations.initMocks(this);
+ }
+
+ @AfterMethod
+ public void resetVidService() {
+ reset(vidService);
+ }
+
+ @DataProvider
+ public static Object[][] trueAndFalse() {
+ return new Object[][]{ {true}, {false} };
+ }
+
+ @Test(dataProvider="trueAndFalse")
+ void testIsVfModelIsBaseModule(boolean isBase) throws AsdcCatalogException {
+ final String serviceModelUuid = UUID.randomUUID().toString();
+ final String vfModuleUuid = UUID.randomUUID().toString();
+
+ ServiceModel mockedServiceModel = mock(ServiceModel.class);
+ VfModule mockedVfModule = mock(VfModule.class);
+ GroupProperties mockedGroupProperties = mock(GroupProperties.class);
+ Map<String, VfModule> vfModulesMap = ImmutableMap.of(randomAlphanumeric(10), mockedVfModule);
+
+ when(vidService.getService(serviceModelUuid)).thenReturn(mockedServiceModel);
+ when(mockedServiceModel.getVfModules()).thenReturn(vfModulesMap);
+ when(mockedVfModule.getUuid()).thenReturn(vfModuleUuid);
+ when(mockedVfModule.getProperties()).thenReturn(mockedGroupProperties);
+ when(mockedGroupProperties.getBaseModule()).thenReturn(isBase);
+
+ assertThat(commandUtils.isVfModuleBaseModule(serviceModelUuid, vfModuleUuid), equalTo(isBase));
+ }
+
+ @Test(expectedExceptions = AsdcCatalogException.class)
+ void whenCantFindModelInSdc_thenExceptionIsThrown() throws AsdcCatalogException {
+ String serviceModelUuid = UUID.randomUUID().toString();
+ when(vidService.getService(serviceModelUuid)).thenReturn(null);
+ commandUtils.isVfModuleBaseModule(serviceModelUuid, "abc");
+ }
+
+ @Test(expectedExceptions = AsdcCatalogException.class)
+ void whenCantFindVfModuleInModel_thenExceptionIsThrown() throws AsdcCatalogException {
+
+ String serviceModelUuid = UUID.randomUUID().toString();
+
+ ServiceModel mockedServiceModel = mock(ServiceModel.class);
+ Map<String, VfModule> emptyMap = Collections.emptyMap();
+
+ when(vidService.getService(serviceModelUuid)).thenReturn(mockedServiceModel);
+ when(mockedServiceModel.getVfModules()).thenReturn(emptyMap);
+
+ commandUtils.isVfModuleBaseModule(serviceModelUuid, "abc");
+ }
+}
diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/InProgressStatusCommandTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/InProgressStatusCommandTest.java
deleted file mode 100644
index bc623928c..000000000
--- a/vid-app-common/src/test/java/org/onap/vid/job/command/InProgressStatusCommandTest.java
+++ /dev/null
@@ -1,143 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * VID
- * ================================================================================
- * Copyright (C) 2018 Nokia Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.vid.job.command;
-
-
-import io.joshworks.restclient.http.HttpResponse;
-import org.mockito.Mock;
-import org.onap.vid.job.Job;
-import org.onap.vid.job.NextCommand;
-import org.onap.vid.mso.MsoInterface;
-import org.onap.vid.mso.rest.AsyncRequestStatus;
-import org.onap.vid.services.AsyncInstantiationBusinessLogic;
-import org.onap.vid.services.AuditService;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import javax.ws.rs.ProcessingException;
-import java.util.UUID;
-
-
-import static org.assertj.core.api.Java6Assertions.assertThat;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-import static org.mockito.MockitoAnnotations.initMocks;
-
-public class InProgressStatusCommandTest {
-
- @Mock
- private AsyncInstantiationBusinessLogic asyncInstantiationBusinessLogic;
-
- @Mock
- private MsoInterface msoInterface;
-
- @Mock
- private AuditService auditService;
-
- @Mock
- private HttpResponse<AsyncRequestStatus> msoResponse;
-
- @Mock
- private AsyncRequestStatus asyncRequestStatus;
-
- @Mock
- private AsyncRequestStatus.Request request;
-
- private UUID uuid = UUID.randomUUID();
-
- private InProgressStatusCommand inProgressStatusCommand;
-
- @BeforeMethod
- public void setUp() {
- initMocks(this);
-
- inProgressStatusCommand = new InProgressStatusCommand(asyncInstantiationBusinessLogic, msoInterface, auditService, uuid, "sampleRequestId");
-
- when(asyncInstantiationBusinessLogic.getOrchestrationRequestsPath()).thenReturn("http://localhost:8080/samplePath");
- when(msoInterface.get("http://localhost:8080/samplePath/sampleRequestId", AsyncRequestStatus.class)).thenReturn(msoResponse);
- when(msoResponse.getBody()).thenReturn(asyncRequestStatus);
- }
-
-
- @Test
- public void whenSOReturnsErrorShouldSetProperFailureStateAndReturnRetryCommand() {
- when(msoResponse.getStatus()).thenReturn(500);
-
- NextCommand call = inProgressStatusCommand.call();
-
- assertThat(call.getStatus()).isEqualTo(Job.JobStatus.IN_PROGRESS);
- assertThat(call.getCommand()).isEqualTo(inProgressStatusCommand);
-
- verify(auditService).setFailedAuditStatusFromMso(uuid, "sampleRequestId", 500, asyncRequestStatus.toString());
- }
-
- @Test
- public void shouldProperlyHandleFailedInstantiation() {
- when(msoResponse.getStatus()).thenReturn(200);
- when(asyncInstantiationBusinessLogic.calcStatus(asyncRequestStatus)).thenReturn(Job.JobStatus.FAILED);
- asyncRequestStatus.request = request;
-
- NextCommand call = inProgressStatusCommand.call();
-
- assertThat(call.getCommand()).isEqualTo(inProgressStatusCommand);
- assertThat(call.getStatus()).isEqualTo(Job.JobStatus.FAILED);
-
- verify(asyncInstantiationBusinessLogic).handleFailedInstantiation(uuid);
- verify(asyncInstantiationBusinessLogic).auditMsoStatus(uuid, request);
- }
-
- @Test
- public void shouldRetryCommandWithPausedState() {
- when(msoResponse.getStatus()).thenReturn(200);
- when(asyncInstantiationBusinessLogic.calcStatus(asyncRequestStatus)).thenReturn(Job.JobStatus.PAUSE);
- asyncRequestStatus.request = request;
-
- NextCommand call = inProgressStatusCommand.call();
-
- assertThat(call.getCommand()).isEqualTo(inProgressStatusCommand);
- assertThat(call.getStatus()).isEqualTo(Job.JobStatus.IN_PROGRESS);
-
- verify(asyncInstantiationBusinessLogic).auditMsoStatus(uuid, request);
- verify(asyncInstantiationBusinessLogic).updateServiceInfoAndAuditStatus(uuid, Job.JobStatus.PAUSE);
- }
-
- @Test
- public void shouldRetryCommandExitedWithProcessingException() {
- when(msoResponse.getStatus()).thenReturn(200);
- when(asyncInstantiationBusinessLogic.calcStatus(asyncRequestStatus)).thenThrow(new ProcessingException(""));
-
- NextCommand call = inProgressStatusCommand.call();
-
- assertThat(call.getCommand()).isEqualTo(inProgressStatusCommand);
- assertThat(call.getStatus()).isEqualTo(Job.JobStatus.IN_PROGRESS);
- }
-
- @Test
- public void shouldSetStoppedStatusWhenRuntimeExceptionOccurs() {
- when(msoResponse.getStatus()).thenReturn(200);
- when(asyncInstantiationBusinessLogic.calcStatus(asyncRequestStatus)).thenThrow(new RuntimeException());
-
- NextCommand call = inProgressStatusCommand.call();
-
- assertThat(call.getCommand()).isEqualTo(inProgressStatusCommand);
- assertThat(call.getStatus()).isEqualTo(Job.JobStatus.STOPPED);
- }
-} \ No newline at end of file
diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/InProgressStatusServiceTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/InProgressStatusServiceTest.java
new file mode 100644
index 000000000..2e8139716
--- /dev/null
+++ b/vid-app-common/src/test/java/org/onap/vid/job/command/InProgressStatusServiceTest.java
@@ -0,0 +1,83 @@
+package org.onap.vid.job.command;
+
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.onap.vid.job.Job;
+import org.onap.vid.job.impl.JobSharedData;
+import org.onap.vid.model.serviceInstantiation.ServiceInstantiation;
+import org.onap.vid.mso.RestMsoImplementation;
+import org.onap.vid.mso.RestObject;
+import org.onap.vid.mso.rest.AsyncRequestStatus;
+import org.onap.vid.services.AsyncInstantiationBaseTest;
+import org.onap.vid.services.AsyncInstantiationBusinessLogic;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+import java.util.UUID;
+import java.util.stream.Stream;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.*;
+import static org.testng.AssertJUnit.assertEquals;
+
+public class InProgressStatusServiceTest {
+
+ @Mock
+ private RestMsoImplementation restMso;
+
+ @Mock
+ private AsyncInstantiationBusinessLogic asyncInstantiationBL;
+
+ @InjectMocks
+ private InProgressStatusService inProgressStatusService;
+
+ @BeforeClass
+ public void initMocks() {
+ MockitoAnnotations.initMocks(this);
+ }
+
+ @DataProvider
+ public static Object[][] jobStatuses() {
+ return Stream.of(Job.JobStatus.values())
+ .map(student -> new Object[] { student })
+ .toArray(Object[][]::new);
+ }
+
+ @Test(dataProvider = "jobStatuses")
+ public void whenGetFromMsoRequestStatus_returnItToCaller(Job.JobStatus expectedJobStatus) {
+
+ UUID jobUuid = UUID.randomUUID();
+ String userId = "mockedUserID";
+ String requestId = UUID.randomUUID().toString();
+ ServiceInstantiation serviceInstantiation = mock(ServiceInstantiation.class);
+
+ when(asyncInstantiationBL.getOrchestrationRequestsPath()).thenReturn("");
+
+ RestObject<AsyncRequestStatus> msoResponse = mock(RestObject.class);
+ AsyncRequestStatus requestStatus = AsyncInstantiationBaseTest.asyncRequestStatusResponse("");
+
+ when(msoResponse.getStatusCode()).thenReturn(200);
+ when(msoResponse.get()).thenReturn(requestStatus);
+ when(restMso.GetForObject(contains(requestId), eq(AsyncRequestStatus.class))).thenReturn(msoResponse);
+
+ when(asyncInstantiationBL.calcStatus(any())).thenReturn(expectedJobStatus);
+
+ ExpiryChecker expiryChecker = mock(ExpiryChecker.class);
+ when(expiryChecker.isExpired(any())).thenReturn(false);
+
+ JobSharedData sharedData = new JobSharedData(jobUuid, userId, serviceInstantiation);
+ Job.JobStatus actualJobStatus = inProgressStatusService.call(expiryChecker, sharedData, requestId);
+ assertEquals(expectedJobStatus, actualJobStatus);
+
+ verify(asyncInstantiationBL).auditMsoStatus(eq(jobUuid), same(requestStatus.request));
+
+ //verify we don't update service info during this case, which shall stay in_progress
+ verify(asyncInstantiationBL, never()).updateServiceInfo(any(), any());
+
+
+ }
+
+}
diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/InstanceGroupCommandTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/InstanceGroupCommandTest.java
new file mode 100644
index 000000000..4cd00174a
--- /dev/null
+++ b/vid-app-common/src/test/java/org/onap/vid/job/command/InstanceGroupCommandTest.java
@@ -0,0 +1,85 @@
+package org.onap.vid.job.command;
+
+import com.google.common.collect.ImmutableMap;
+import org.apache.commons.beanutils.BeanUtils;
+import org.mockito.Answers;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.onap.vid.job.impl.JobSharedData;
+import org.onap.vid.model.RequestReferencesContainer;
+import org.onap.vid.model.serviceInstantiation.InstanceGroup;
+import org.onap.vid.mso.RestMsoImplementation;
+import org.onap.vid.mso.model.ModelInfo;
+import org.onap.vid.services.AsyncInstantiationBusinessLogic;
+import org.springframework.http.HttpMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import java.util.Optional;
+import java.util.Set;
+
+import static java.util.function.Function.identity;
+import static java.util.stream.Collectors.toMap;
+import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.*;
+
+public class InstanceGroupCommandTest {
+
+ @Mock(answer = Answers.RETURNS_MOCKS)
+ RestMsoImplementation restMso;
+
+ @Mock InstanceGroup instanceGroupRequest;
+
+ @Mock(answer = Answers.RETURNS_MOCKS)
+ MsoResultHandlerService msoResultHandlerService;
+
+ @Mock WatchChildrenJobsBL watchChildrenJobsBL;
+
+ @Mock(answer = Answers.RETURNS_MOCKS)
+ AsyncInstantiationBusinessLogic asyncInstantiationBL;
+
+ @Mock InProgressStatusService inProgressStatusService;
+
+ @InjectMocks
+ private InstanceGroupCommand command;
+
+ @BeforeMethod
+ public void initMocks() {
+ command = null;
+ MockitoAnnotations.initMocks(this);
+ }
+
+ @Test
+ public void createMyself_callsMso() {
+ final ModelInfo serviceModelInfo = setRandomStrings(new ModelInfo());
+ final String serviceInstanceId = "service-instance-id";
+ final String userId = "ff3223";
+
+ command.init(new JobSharedData(
+ null, userId, instanceGroupRequest
+ ), ImmutableMap.of(
+ "resourceModelInfos", ImmutableMap.of("SERVICE_MODEL_INFO", serviceModelInfo),
+ "resourceInstancesIds", ImmutableMap.of("SERVICE_INSTANCE_ID", serviceInstanceId)
+ ));
+
+ command.createMyself();
+
+ verify(asyncInstantiationBL).generateInstanceGroupInstantiationRequest(
+ same(instanceGroupRequest), eq(serviceModelInfo), eq(serviceInstanceId), eq(userId));
+ verify(restMso, only()).restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), any(), eq(Optional.empty()));
+
+ }
+
+ private ModelInfo setRandomStrings(ModelInfo object) {
+ try {
+ Set<String> fields = BeanUtils.describe(object).keySet();
+ BeanUtils.populate(object,
+ fields.stream().collect(toMap(identity(), s -> randomAlphanumeric(4))));
+ return object;
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+}
diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/JobCommandFactoryTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/JobCommandFactoryTest.java
index b51553be7..2138b77cd 100644
--- a/vid-app-common/src/test/java/org/onap/vid/job/command/JobCommandFactoryTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/job/command/JobCommandFactoryTest.java
@@ -1,17 +1,22 @@
package org.onap.vid.job.command;
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.collect.ImmutableMap;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.onap.vid.job.Job;
+import org.onap.vid.job.JobAdapter;
import org.onap.vid.job.JobCommand;
import org.onap.vid.job.JobType;
+import org.onap.vid.job.impl.JobSharedData;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.util.Arrays;
import java.util.Map;
+import java.util.Objects;
import java.util.UUID;
import java.util.stream.Collectors;
@@ -48,19 +53,48 @@ public class JobCommandFactoryTest {
}
+ public static class MockedRequest implements JobAdapter.AsyncJobRequest {
+
+ final public int x;
+ final public String y;
+
+ @JsonCreator
+ public MockedRequest(@JsonProperty("x")int x, @JsonProperty("y")String y) {
+ this.x = x;
+ this.y = y;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (!(o instanceof MockedRequest)) return false;
+ MockedRequest that = (MockedRequest) o;
+ return x == that.x &&
+ Objects.equals(y, that.y);
+ }
+
+ @Override
+ public int hashCode() {
+
+ return Objects.hash(x, y);
+ }
+ }
+
@Test(dataProvider = "jobTypes")
public void givenJob_createCommandCallsTheInitAndReturnsTheInstance(JobType jobType) {
final UUID uuid = UUID.randomUUID();
final Map<String, Object> data = ImmutableMap.of("foo", "bar");
+ final JobSharedData sharedData = new JobSharedData(uuid, "userid", new MockedRequest(1,"a"));
when(job.getType()).thenReturn(jobType);
when(job.getUuid()).thenReturn(uuid);
when(job.getData()).thenReturn(data);
+ when(job.getSharedData()).thenReturn(sharedData);
final JobCommand command = jobCommandFactory.toCommand(job);
- verify(mockCommand).init(uuid, data);
+ verify(mockCommand).init(sharedData, data);
assertThat(command, equalTo(mockCommand));
}
diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/ResourceCommandTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/ResourceCommandTest.java
new file mode 100644
index 000000000..29be48edc
--- /dev/null
+++ b/vid-app-common/src/test/java/org/onap/vid/job/command/ResourceCommandTest.java
@@ -0,0 +1,303 @@
+package org.onap.vid.job.command;
+
+import com.google.common.collect.ImmutableMap;
+import org.jetbrains.annotations.NotNull;
+import org.onap.vid.exceptions.GenericUncheckedException;
+import org.onap.vid.job.Job;
+import org.onap.vid.job.JobAdapter;
+import org.onap.vid.job.NextCommand;
+import org.onap.vid.job.impl.JobSharedData;
+import org.onap.vid.model.Action;
+import org.onap.vid.model.serviceInstantiation.BaseResource;
+import org.onap.vid.mso.RestMsoImplementation;
+import org.springframework.http.HttpMethod;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+import javax.ws.rs.ProcessingException;
+import java.util.Collections;
+import java.util.Optional;
+import java.util.stream.Stream;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.*;
+import static org.onap.vid.job.command.ResourceCommandKt.ACTION_PHASE;
+import static org.onap.vid.job.command.ResourceCommandKt.INTERNAL_STATE;
+import static org.onap.vid.utils.Logging.getMethodCallerName;
+import static org.testng.Assert.assertNull;
+import static org.testng.Assert.assertTrue;
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertFalse;
+
+public class ResourceCommandTest {
+
+ public static class MockCommand extends ResourceCommand {
+
+ public MockCommand(InternalState mockState, Action mockPhase, Job.JobStatus mockedJobStatus) {
+ super(mock(RestMsoImplementation.class, RETURNS_MOCKS), mock(InProgressStatusService.class), mock(MsoResultHandlerService.class, RETURNS_MOCKS), mock(WatchChildrenJobsBL.class));
+
+ this.mockedJobStatus = mockedJobStatus;
+ this.mockState = mockState;
+ this.mockPhase = mockPhase;
+ if (mockState==InternalState.INITIAL) {
+ init(mock(JobSharedData.class), Collections.emptyMap());
+ }
+ else {
+ init(mock(JobSharedData.class), ImmutableMap.of(INTERNAL_STATE, mockState.name(), ACTION_PHASE, mockPhase.name()));
+ }
+ when(this.getWatchChildrenJobsBL().cumulateJobStatus(any(), any())).thenReturn(mockedJobStatus);
+ }
+
+ private final Job.JobStatus mockedJobStatus;
+ private final InternalState mockState;
+ private final Action mockPhase;
+
+
+ @NotNull
+ @Override
+ public Job.JobStatus createChildren() {
+ if (mockState == InternalState.CREATING_CHILDREN || (mockState == InternalState.INITIAL && mockPhase== Action.Delete))
+ return mockedJobStatus;
+ throw (new RuntimeException("Not expected to call "+getMethodCallerName()));
+ }
+
+ protected Job.JobStatus mockedStatusOrThrow(InternalState expectedState) {
+ if (mockState == expectedState)
+ return mockedJobStatus;
+ throw (new RuntimeException("Not expected to call "+getMethodCallerName()));
+ }
+
+ protected MsoRestCallPlan mockedPlanOrThrow(InternalState expectedState) {
+ if (mockState == expectedState)
+ return new MsoRestCallPlan(HttpMethod.POST, "path", Optional.empty(), Optional.empty(), "nothing");
+ throw (new RuntimeException("Not expected to call "+getMethodCallerName()));
+ }
+
+ @NotNull
+ @Override
+ public MsoRestCallPlan planCreateMyselfRestCall(@NotNull CommandParentData commandParentData, @NotNull JobAdapter.AsyncJobRequest request, @NotNull String userId) {
+ return mockedPlanOrThrow(InternalState.CREATE_MYSELF);
+ }
+
+ @NotNull
+ @Override
+ public MsoRestCallPlan planDeleteMyselfRestCall(@NotNull CommandParentData commandParentData, @NotNull JobAdapter.AsyncJobRequest request, @NotNull String userId) {
+ return mockedPlanOrThrow(InternalState.DELETE_MYSELF);
+ }
+ }
+
+ public static class MockCommandTestingStateMachine extends MockCommand {
+
+ private final JobSharedData sharedData;
+
+ public MockCommandTestingStateMachine(InternalState mockState, Action mockPhase, Job.JobStatus mockedJobStatus, boolean mockedNeedToDeleteMySelf) {
+ this(mockState, mockPhase, mockedJobStatus, mockedNeedToDeleteMySelf, false);
+ }
+
+ public MockCommandTestingStateMachine(InternalState mockState, Action mockPhase, Job.JobStatus mockedJobStatus, boolean mockedNeedToDeleteMySelf, boolean isService) {
+ super(mockState, mockPhase, mockedJobStatus);
+ this.mockedNeedToDeleteMySelf = mockedNeedToDeleteMySelf;
+ this.isService = isService;
+ this.sharedData = mock(JobSharedData.class, RETURNS_MOCKS);
+ }
+
+ protected final boolean mockedNeedToDeleteMySelf;
+ private final boolean isService;
+
+ @NotNull
+ @Override
+ public Job.JobStatus inProgress() {
+ return mockedStatusOrThrow(InternalState.IN_PROGRESS);
+ }
+
+ @NotNull
+ @Override
+ public Job.JobStatus watchChildren() {
+ return mockedStatusOrThrow(InternalState.WATCHING);
+ }
+
+ @Override
+ public boolean isNeedToDeleteMyself() {
+ return mockedNeedToDeleteMySelf;
+ }
+
+ @Override
+ protected boolean isServiceCommand() {
+ return isService;
+ }
+
+ @Override
+ public JobSharedData getSharedData() {
+ return sharedData;
+ }
+ }
+
+ @DataProvider
+ public static Object[][] nextStateDeletePhaseProvider() {
+ return new Object[][]{
+ {InternalState.CREATING_CHILDREN, Job.JobStatus.COMPLETED, InternalState.WATCHING},
+ {InternalState.WATCHING, Job.JobStatus.COMPLETED, InternalState.DELETE_MYSELF},
+ {InternalState.WATCHING, Job.JobStatus.IN_PROGRESS, InternalState.WATCHING},
+ {InternalState.WATCHING, Job.JobStatus.RESOURCE_IN_PROGRESS, InternalState.WATCHING},
+ {InternalState.DELETE_MYSELF, Job.JobStatus.COMPLETED, InternalState.IN_PROGRESS},
+ {InternalState.IN_PROGRESS, Job.JobStatus.COMPLETED, InternalState.TERMINAL},
+ {InternalState.IN_PROGRESS, Job.JobStatus.IN_PROGRESS, InternalState.IN_PROGRESS},
+ {InternalState.IN_PROGRESS, Job.JobStatus.RESOURCE_IN_PROGRESS, InternalState.IN_PROGRESS},
+ };
+ }
+
+ @Test(dataProvider = "nextStateDeletePhaseProvider")
+ public void whenCalcNextStateDeletePhase_expectedStateIsReturned(
+ InternalState internalState, Job.JobStatus jobStatus, InternalState expectedState) {
+
+ //there is no meaning to the constructor inputs here
+ MockCommandTestingStateMachine underTest = new MockCommandTestingStateMachine(InternalState.TERMINAL, Action.Delete, Job.JobStatus.FAILED, true);
+ assertEquals(expectedState, underTest.calcNextStateDeletePhase(jobStatus, internalState));
+ }
+
+ @Test
+ public void whenNoNeedToDeleteMyself_internalStateMovesFromWatchingToTerminal() {
+ MockCommandTestingStateMachine underTest = new MockCommandTestingStateMachine(InternalState.WATCHING, Action.Delete, Job.JobStatus.COMPLETED, false);
+ assertEquals(InternalState.TERMINAL, underTest.calcNextStateDeletePhase(Job.JobStatus.COMPLETED, InternalState.WATCHING));
+ }
+
+ @DataProvider
+ public static Object[][] testShallStopJobDataProvider() {
+ return new Object[][]{
+ {Job.JobStatus.IN_PROGRESS, Action.None, false, false},
+ {Job.JobStatus.COMPLETED_WITH_NO_ACTION, Action.None, false, false},
+ {Job.JobStatus.COMPLETED, Action.None, false, false},
+ {Job.JobStatus.FAILED, Action.None, false, true},
+ {Job.JobStatus.COMPLETED_WITH_ERRORS, Action.None, false, true},
+ {Job.JobStatus.COMPLETED_WITH_ERRORS, Action.None, true, false},
+ {Job.JobStatus.FAILED, Action.None, true, false},
+ {Job.JobStatus.FAILED, Action.Delete, true, true},
+ {Job.JobStatus.FAILED, Action.Create, true, true},
+ };
+ }
+
+
+ @Test(dataProvider = "testShallStopJobDataProvider")
+ public void testShallStopJob(Job.JobStatus jobStatus, Action action, boolean isService, boolean expectedResult) {
+ //in this test, there is no meaning to constructor parameters besides isService
+ MockCommandTestingStateMachine underTest = new MockCommandTestingStateMachine(InternalState.WATCHING, Action.Delete, Job.JobStatus.COMPLETED, false, isService);
+
+ BaseResource mockedRequest = mock(BaseResource.class);
+ when(underTest.getSharedData().getRequest()).thenReturn(mockedRequest);
+ when(mockedRequest.getAction()).thenReturn(action);
+
+ assertEquals(expectedResult, underTest.shallStopJob(jobStatus));
+ }
+
+ @DataProvider
+ public static Object[][] testCallDataProvider() {
+ return new Object[][]{
+ {"initial state with successful creating children" ,InternalState.INITIAL, Job.JobStatus.COMPLETED, InternalState.WATCHING, Job.JobStatus.RESOURCE_IN_PROGRESS},
+ {"initial state with failed creating children", InternalState.INITIAL, Job.JobStatus.FAILED, null, Job.JobStatus.FAILED},
+ {"watching state with children still in progress" ,InternalState.WATCHING, Job.JobStatus.RESOURCE_IN_PROGRESS, InternalState.WATCHING, Job.JobStatus.RESOURCE_IN_PROGRESS},
+ {"watching state with children that completed with errors" ,InternalState.WATCHING, Job.JobStatus.COMPLETED_WITH_ERRORS, null, Job.JobStatus.COMPLETED_WITH_ERRORS},
+ {"watching state with children that completed with no action" ,InternalState.WATCHING, Job.JobStatus.COMPLETED_WITH_NO_ACTION, InternalState.DELETE_MYSELF, Job.JobStatus.RESOURCE_IN_PROGRESS},
+ {"watching state with children that has completed" ,InternalState.WATCHING, Job.JobStatus.COMPLETED, InternalState.DELETE_MYSELF, Job.JobStatus.RESOURCE_IN_PROGRESS},
+ {"mso call state that failed" ,InternalState.DELETE_MYSELF, Job.JobStatus.FAILED, null, Job.JobStatus.FAILED},
+ //TODO handle AAI get unique name state {"mso call state that still in progress" ,InternalState.DELETE_MYSELF, Job.JobStatus.FAILED, null, Job.JobStatus.FAILED, false},
+ {"mso call state that success" ,InternalState.DELETE_MYSELF, Job.JobStatus.COMPLETED, InternalState.IN_PROGRESS, Job.JobStatus.RESOURCE_IN_PROGRESS},
+ {"in progress return in progress" ,InternalState.IN_PROGRESS, Job.JobStatus.IN_PROGRESS, InternalState.IN_PROGRESS, Job.JobStatus.RESOURCE_IN_PROGRESS},
+ {"in progress return in pause" ,InternalState.IN_PROGRESS, Job.JobStatus.PAUSE, InternalState.IN_PROGRESS, Job.JobStatus.RESOURCE_IN_PROGRESS},
+ {"in progress return in pause" ,InternalState.IN_PROGRESS, Job.JobStatus.STOPPED, null, Job.JobStatus.STOPPED},
+ {"in progress return in pause" ,InternalState.IN_PROGRESS, Job.JobStatus.FAILED, null, Job.JobStatus.FAILED},
+ {"in progress return in pause" ,InternalState.IN_PROGRESS, Job.JobStatus.COMPLETED, null, Job.JobStatus.COMPLETED},
+
+ };
+ }
+
+ @Test(dataProvider = "testCallDataProvider")
+ public void whenCallCommandWithDeletePhase_nextJobStatusAndInternalStateAreAsExpected(
+ String description, InternalState internalState, Job.JobStatus currentStateResult,
+ InternalState expectedNextState, Job.JobStatus expectedNextStatus) {
+
+ MockCommandTestingStateMachine underTest = new MockCommandTestingStateMachine(internalState, Action.Delete, currentStateResult, true);
+ NextCommand nextCommand = underTest.call();
+ assertEquals(expectedNextStatus, nextCommand.getStatus());
+
+ //expectedNextState == null means nextCommand has no real command
+ if (expectedNextState!=null) {
+ assertEquals(expectedNextState, (nextCommand.getCommand().getData().get(INTERNAL_STATE)));
+ assertFalse(nextCommand.getStatus().isFinal());
+ }
+ else {
+ assertNull(nextCommand.getCommand());
+ assertTrue(nextCommand.getStatus().isFinal());
+ }
+ }
+
+ @Test(expectedExceptions = IllegalStateException.class)
+ public void whenCommandInUnMappedState_exceptionIsThrown() {
+ MockCommandTestingStateMachine underTest = new MockCommandTestingStateMachine(InternalState.TERMINAL, Action.Delete, Job.JobStatus.COMPLETED, true);
+ underTest.call();
+ }
+
+ @DataProvider
+ public static Object[][] InProgressDataProvider() {
+ return Stream.of(Job.JobStatus.values())
+ .map(status -> new Object[] { status })
+ .toArray(Object[][]::new);
+ }
+
+ @Test(dataProvider = "InProgressDataProvider")
+ public void whenGetResultFromMso_InProgressReturnThem(Job.JobStatus mockedJobStatus) {
+ Job.JobStatus expectedJobStatus = (mockedJobStatus== Job.JobStatus.PAUSE) ? Job.JobStatus.IN_PROGRESS : mockedJobStatus;
+ MockCommand underTest = new MockCommand(InternalState.IN_PROGRESS, Action.Delete, mockedJobStatus);
+ when(underTest.getInProgressStatusService().call(any(), any(), any())).thenReturn(mockedJobStatus);
+ assertEquals(expectedJobStatus, underTest.inProgress());
+ }
+
+ @DataProvider
+ public static Object[][] InProgressExceptionsDataProvider() {
+ return new Object[][]{
+ {new ProcessingException(""), Job.JobStatus.IN_PROGRESS},
+ {new InProgressStatusService.BadResponseFromMso(null), Job.JobStatus.IN_PROGRESS},
+ {new GenericUncheckedException(""),Job.JobStatus.STOPPED }
+ };
+ }
+
+ @Test(dataProvider = "InProgressExceptionsDataProvider")
+ public void whenInProgressStatusServiceThrowException_InProgressReturnStatus(Exception exception, Job.JobStatus expectedJobStatus) {
+ MockCommand underTest = new MockCommand(InternalState.IN_PROGRESS, Action.Delete, expectedJobStatus);
+ when(underTest.getInProgressStatusService().call(any(), any(), any())).thenThrow(exception);
+ assertEquals(expectedJobStatus, underTest.inProgress());
+ }
+
+ @DataProvider
+ public static Object[][] testIsNeedToDeleteMySelfDataProvider() {
+ return Stream.of(Action.values())
+ .map(status -> new Object[] { status })
+ .toArray(Object[][]::new);
+ }
+
+ @Test(dataProvider = "testIsNeedToDeleteMySelfDataProvider")
+ public void testIsNeedToDeleteMySelf(Action action) {
+ boolean expectedResult = (action== Action.Delete);
+ MockCommand underTest = new MockCommand(InternalState.DELETE_MYSELF, Action.Delete, Job.JobStatus.IN_PROGRESS);
+ BaseResource mockedBaseResource = mock(BaseResource.class);
+ when(underTest.getSharedData().getRequest()).thenReturn(mockedBaseResource);
+ when(mockedBaseResource.getAction()).thenReturn(action);
+ assertEquals(expectedResult, underTest.isNeedToDeleteMyself());
+ }
+
+ @DataProvider
+ public static Object[][] testWatchingDataProvider() {
+ return new Object[][]{
+ {"all children final, no failed child ", Job.JobStatus.COMPLETED, Job.JobStatus.COMPLETED},
+ {"all children final, there is failed child ", Job.JobStatus.COMPLETED_WITH_ERRORS, Job.JobStatus.COMPLETED_WITH_ERRORS},
+ {"not all children final", Job.JobStatus.IN_PROGRESS, Job.JobStatus.IN_PROGRESS},
+ };
+ }
+
+ @Test(dataProvider = "testWatchingDataProvider")
+ public void testWatching(String desc, Job.JobStatus childrenJobsStatus, Job.JobStatus expectedJobStatus) {
+ MockCommand underTest = new MockCommand(InternalState.WATCHING, Action.Delete, Job.JobStatus.IN_PROGRESS);
+ when(underTest.getWatchChildrenJobsBL().retrieveChildrenJobsStatus(any())).thenReturn(childrenJobsStatus);
+ assertEquals(expectedJobStatus, underTest.watchChildren());
+ }
+
+}
diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/ResourceInProgressStatusCommandTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/ResourceInProgressStatusCommandTest.java
new file mode 100644
index 000000000..9ec49a2e5
--- /dev/null
+++ b/vid-app-common/src/test/java/org/onap/vid/job/command/ResourceInProgressStatusCommandTest.java
@@ -0,0 +1,40 @@
+package org.onap.vid.job.command;
+
+import org.mockito.InjectMocks;
+import org.mockito.MockitoAnnotations;
+import org.onap.vid.job.Job;
+import org.onap.vid.job.NextCommand;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.core.Is.is;
+
+
+public class ResourceInProgressStatusCommandTest {
+
+ @InjectMocks
+ private ResourceInProgressStatusCommand commandUnderTest = new ResourceInProgressStatusCommand();
+
+ @BeforeMethod
+ public void initMocks() {
+ MockitoAnnotations.initMocks(this);
+ }
+
+ @DataProvider
+ public static Object[][] givenStatusToExpectedStatus() {
+ return new Object[][]{
+ {Job.JobStatus.IN_PROGRESS, Job.JobStatus.IN_PROGRESS},
+ {Job.JobStatus.FAILED, Job.JobStatus.FAILED},
+ {Job.JobStatus.COMPLETED, Job.JobStatus.COMPLETED}
+ };
+ }
+
+ @Test(dataProvider = "givenStatusToExpectedStatus")
+ public void whenGetStatusFromMso_returnExpectedNextCommand(Job.JobStatus jobStatus, Job.JobStatus expectedNextStatus) {
+ NextCommand nextCommand = commandUnderTest.processJobStatus(jobStatus);
+ assertThat(nextCommand.getStatus(), is(expectedNextStatus));
+ assertThat(nextCommand.getCommand(), is(commandUnderTest));
+ }
+}
diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/ServiceInProgressStatusCommandTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/ServiceInProgressStatusCommandTest.java
new file mode 100644
index 000000000..bfda6cf34
--- /dev/null
+++ b/vid-app-common/src/test/java/org/onap/vid/job/command/ServiceInProgressStatusCommandTest.java
@@ -0,0 +1,208 @@
+package org.onap.vid.job.command;
+
+import com.google.common.collect.ImmutableMap;
+import org.mockito.ArgumentCaptor;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.onap.vid.job.*;
+import org.onap.vid.job.impl.JobSharedData;
+import org.onap.vid.model.serviceInstantiation.Network;
+import org.onap.vid.model.serviceInstantiation.ServiceInstantiation;
+import org.onap.vid.model.serviceInstantiation.Vnf;
+import org.onap.vid.mso.model.ModelInfo;
+import org.onap.vid.properties.Features;
+import org.onap.vid.properties.VidProperties;
+import org.onap.vid.services.AsyncInstantiationBusinessLogic;
+import org.springframework.core.env.Environment;
+import org.testng.Assert;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+import org.togglz.core.manager.FeatureManager;
+
+import java.time.Instant;
+import java.time.ZoneOffset;
+import java.time.ZonedDateTime;
+import java.time.temporal.ChronoUnit;
+import java.util.Arrays;
+import java.util.Map;
+import java.util.TreeMap;
+import java.util.UUID;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.containsInAnyOrder;
+import static org.hamcrest.core.Is.is;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.*;
+import static org.onap.vid.job.Job.JobStatus.*;
+
+public class ServiceInProgressStatusCommandTest {
+
+
+ @Mock
+ private AsyncInstantiationBusinessLogic asyncInstantiationBL;
+
+ @Mock
+ private JobsBrokerService jobsBrokerService;
+
+ @Mock
+ private JobAdapter jobAdapter;
+
+ @Mock
+ private FeatureManager featureManager;
+
+ @Mock
+ private JobSharedData sharedData;
+
+ @Mock
+ private Environment environment;
+
+ @Mock
+ private ServiceInstantiation request;
+
+ @Mock
+ private InProgressStatusService inProgressStatusService;
+
+ @InjectMocks
+ private ServiceInProgressStatusCommand command = new ServiceInProgressStatusCommand();
+
+ @DataProvider
+ public static Object[][] isNeedToCreateChildJobsDataProvider() {
+ return new Object[][]{
+ {new TreeMap<String,Vnf>() , true, true, false},
+ {null , true, true, false},
+ {ImmutableMap.of("a",mock(Vnf.class)), false, true, false},
+ {ImmutableMap.of("a",mock(Vnf.class)), true, false, false},
+ {ImmutableMap.of("a",mock(Vnf.class)), true, true, true},
+ };
+ }
+
+ @DataProvider
+ public static Object[][] processJobStatusData() {
+ return new Object[][]{
+ /* {MSO jobStatus, jobStartTime, isNeedToCreateChildJobs(), property vid.job.max.hoursInProgress, expected nextCommand.getStatus() } */
+ {IN_PROGRESS, false, IN_PROGRESS},
+ {FAILED, false, FAILED},
+ {PAUSE, false, IN_PROGRESS},
+ {COMPLETED, false, COMPLETED},
+ {COMPLETED, true, IN_PROGRESS},
+ {RESOURCE_IN_PROGRESS, false, RESOURCE_IN_PROGRESS},
+ {PENDING, false, PENDING},
+ {STOPPED, false, STOPPED},
+ {COMPLETED_WITH_ERRORS, false, COMPLETED_WITH_ERRORS},
+ {CREATING, false, CREATING}
+ };
+ }
+
+ @DataProvider
+ public static Object[][] isExpiredJobStatusData() {
+ return new Object[][]{
+ {ZonedDateTime.now(), "24", false},
+ {getTimeNowMinus(2), "1", true},
+ {getTimeNowMinus(24), "24", true},
+ {getTimeNowMinus(2), "0", false},
+ {getTimeNowMinus(2), "-1", false},
+ {getTimeNowMinus(2), "", false},
+ {getTimeNowMinus(2), "a", false}
+ };
+ }
+
+ private static ZonedDateTime getTimeNowMinus(int hoursAgo) {
+ return ZonedDateTime.ofInstant(Instant.now().minus(hoursAgo, ChronoUnit.HOURS), ZoneOffset.UTC);
+ }
+
+ @BeforeMethod
+ public void initMocks() {
+ MockitoAnnotations.initMocks(this);
+ }
+
+ @Test(dataProvider = "isNeedToCreateChildJobsDataProvider" )
+ public void testIsNeedToCreateChildJobs(Map<String, Vnf> serviceVnfs, boolean isALaCarte,
+ boolean isFeatureEnabled, boolean expected) {
+ MockitoAnnotations.initMocks(this);
+ ServiceInstantiation serviceInstantiation = mock(ServiceInstantiation.class);
+ when(serviceInstantiation.getVnfs()).thenReturn(serviceVnfs);
+ when(serviceInstantiation.isALaCarte()).thenReturn(isALaCarte);
+ when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VNF)).thenReturn(isFeatureEnabled);
+ assertThat(command.isNeedToCreateChildJobs(serviceInstantiation), is(expected));
+ }
+
+ @Test
+ public void whenGetFromMsoCompletedAndALaCarte_generateNewJobsForVnfs() {
+ UUID uuid = UUID.randomUUID();
+ String userId = "mockedUserID";
+ Vnf vnf1 = mock(Vnf.class);
+ Vnf vnf2 = mock(Vnf.class);
+ Network network1 = mock(Network.class);
+ ServiceInstantiation serviceInstantiation = mock(ServiceInstantiation.class);
+ when(serviceInstantiation.getVnfs()).thenReturn(ImmutableMap.of("a", vnf1, "b", vnf2));
+ when(serviceInstantiation.getNetworks()).thenReturn(ImmutableMap.of("c", network1));
+ when(serviceInstantiation.isALaCarte()).thenReturn(true);
+ when(serviceInstantiation.getModelInfo()).thenReturn(new ModelInfo());
+
+ when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VNF)).thenReturn(true);
+
+ UUID uuid1 = UUID.fromString("12345678-1234-1234-1234-123456789012");
+ UUID uuid2 = UUID.fromString("12345678-1234-1234-1234-123456789013");
+ UUID uuid3 = UUID.fromString("12345678-1234-1234-1234-123456789014");
+ when(jobsBrokerService.add(any())).thenReturn(uuid1).thenReturn(uuid2).thenReturn(uuid3);
+
+ JobSharedData sharedData = new JobSharedData(uuid, userId, serviceInstantiation);
+ command.init(sharedData, "", "");
+ when(inProgressStatusService.call(any(), eq(sharedData), any())).thenReturn(Job.JobStatus.COMPLETED);
+ NextCommand nextCommand = command.call();
+
+ ArgumentCaptor<JobAdapter.AsyncJobRequest> argumentCaptor = ArgumentCaptor.forClass(JobAdapter.AsyncJobRequest.class);
+ verify(jobAdapter, times(2)).createChildJob(eq(JobType.VnfInstantiation), eq(Job.JobStatus.CREATING), argumentCaptor.capture(), eq(sharedData), any());
+ verify(jobAdapter, times(1)).createChildJob(eq(JobType.NetworkInstantiation), eq(Job.JobStatus.CREATING), argumentCaptor.capture(), eq(sharedData), any());
+ assertThat(argumentCaptor.getAllValues(), containsInAnyOrder(vnf1, vnf2, network1));
+
+ verify(jobsBrokerService, times(3)).add(any());
+
+ //verify we don't update service info during this case, which shall stay in_progress
+ verify(asyncInstantiationBL, never()).updateServiceInfo(any(), any());
+
+ assertThat(nextCommand.getStatus(), is(Job.JobStatus.IN_PROGRESS));
+ assertThat(nextCommand.getCommand().getType(), is(new WatchingCommand().getType()));
+ assertThat(nextCommand.getCommand().getData().get("childrenJobs"), is(Arrays.asList(uuid1.toString(), uuid2.toString(), uuid3.toString())));
+ assertThat(nextCommand.getCommand().getData().get("isService"), is(true));
+ }
+
+ @Test(dataProvider = "processJobStatusData")
+ public void processJobStatusTest(Job.JobStatus jobStatus, boolean isNeedToCreateChildJobs, Job.JobStatus expectedStatus) {
+
+ when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VNF)).thenReturn(true);
+ // All mocks under are used for isNeedToCreateChildJobs=true case
+ when(sharedData.getRequest()).thenReturn(request);
+ when(request.isALaCarte()).thenReturn(true);
+ Map vnfs = mock(Map.class);
+ ModelInfo modelInfo = mock(ModelInfo.class);
+
+ // if vnfs.isEmpty -> isNeedToCreateChildJobs will return false
+ when(vnfs.isEmpty()).thenReturn(!isNeedToCreateChildJobs);
+
+ when(request.getVnfs()).thenReturn(vnfs);
+ when(request.getModelInfo()).thenReturn(modelInfo);
+ command.instanceId = "MockInstId";
+
+ NextCommand nextCommand = command.processJobStatus(jobStatus);
+ Assert.assertEquals(nextCommand.getStatus(), expectedStatus);
+ if (isNeedToCreateChildJobs) {
+ Assert.assertEquals(nextCommand.getCommand().getClass(), WatchingCommand.class);
+ } else {
+ Assert.assertEquals(nextCommand.getCommand(), command);
+ }
+ }
+
+ @Test(dataProvider = "isExpiredJobStatusData")
+ public void isExpiredJobStatusTest(ZonedDateTime jobStartTime, String configValue, boolean expectedResult) {
+ SystemProperties systemProperties = new SystemProperties();
+ systemProperties.setEnvironment(environment);
+ when(environment.getRequiredProperty(VidProperties.VID_JOB_MAX_HOURS_IN_PROGRESS)).thenReturn(configValue);
+ when(environment.containsProperty(VidProperties.VID_JOB_MAX_HOURS_IN_PROGRESS)).thenReturn(true);
+ Assert.assertEquals(command.getExpiryChecker().isExpired(jobStartTime), expectedResult);
+ }
+}
diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/ServiceInstantiationCommandTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/ServiceInstantiationCommandTest.java
deleted file mode 100644
index e7ab4f098..000000000
--- a/vid-app-common/src/test/java/org/onap/vid/job/command/ServiceInstantiationCommandTest.java
+++ /dev/null
@@ -1,157 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * VID
- * ================================================================================
- * Copyright (C) 2018 Nokia Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.vid.job.command;
-
-
-import io.joshworks.restclient.http.HttpResponse;
-import org.mockito.Mock;
-import org.onap.vid.aai.AaiResponse;
-import org.onap.vid.aai.exceptions.InvalidAAIResponseException;
-import org.onap.vid.changeManagement.RequestDetailsWrapper;
-import org.onap.vid.domain.mso.RequestReferences;
-import org.onap.vid.exceptions.MaxRetriesException;
-import org.onap.vid.job.Job;
-import org.onap.vid.job.NextCommand;
-import org.onap.vid.model.RequestReferencesContainer;
-import org.onap.vid.model.serviceInstantiation.ServiceInstantiation;
-import org.onap.vid.mso.MsoInterface;
-import org.onap.vid.mso.model.ServiceInstantiationRequestDetails;
-import org.onap.vid.services.AsyncInstantiationBusinessLogic;
-import org.onap.vid.services.AuditService;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import java.util.UUID;
-
-import static org.hamcrest.CoreMatchers.instanceOf;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.nullValue;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.core.IsEqual.equalTo;
-import static org.mockito.Mockito.doThrow;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-import static org.mockito.MockitoAnnotations.initMocks;
-
-public class ServiceInstantiationCommandTest {
- @Mock
- private AsyncInstantiationBusinessLogic asyncInstantiationBusinessLogic;
-
- @Mock
- private MsoInterface msoInterface;
-
- @Mock
- private AuditService auditService;
-
- @Mock
- private ServiceInstantiation serviceInstantiation;
-
- @Mock
- private HttpResponse<RequestReferencesContainer> msoResponse;
-
- @Mock
- private RequestDetailsWrapper<ServiceInstantiationRequestDetails> requestDetailsWrapper;
-
- @Mock
- private AaiResponse aaiResponse;
-
- @Mock
- private RequestReferencesContainer requestReferencesContainer;
-
-
- private UUID uuid = UUID.randomUUID();
-
-
- private ServiceInstantiationCommand serviceInstantiationCommand;
-
- @BeforeMethod
- public void setUp() {
- initMocks(this);
- serviceInstantiationCommand = new ServiceInstantiationCommand(asyncInstantiationBusinessLogic, auditService, msoInterface, uuid, serviceInstantiation, "sampleUserId");
- }
-
-
- @Test
- public void shouldProperlyHandleMaxRetriesException() {
- when(asyncInstantiationBusinessLogic.generateServiceInstantiationRequest(uuid, serviceInstantiation, "sampleUserId")).thenThrow(new MaxRetriesException("", 2));
-
- NextCommand call = serviceInstantiationCommand.call();
-
- assertThat(call.getCommand(), is(nullValue()));
- assertThat(call.getStatus(), is(equalTo(Job.JobStatus.FAILED)));
-
- verify(asyncInstantiationBusinessLogic).handleFailedInstantiation(uuid);
- }
-
- @Test
- public void shouldProperlyHandleInvalidAAIResponseException() {
- doThrow(new InvalidAAIResponseException(aaiResponse)).when(asyncInstantiationBusinessLogic).generateServiceInstantiationRequest(uuid, serviceInstantiation, "sampleUserId");
-
- NextCommand call = serviceInstantiationCommand.call();
-
- assertThat(call.getCommand(), is(serviceInstantiationCommand));
- assertThat(call.getStatus(), is(equalTo(Job.JobStatus.IN_PROGRESS)));
- }
-
-
- @Test
- public void shouldProperlyHandleInvalidSOResponse() {
- when(asyncInstantiationBusinessLogic.generateServiceInstantiationRequest(uuid, serviceInstantiation, "sampleUserId")).thenReturn(requestDetailsWrapper);
- when(asyncInstantiationBusinessLogic.getServiceInstantiationPath(serviceInstantiation)).thenReturn("samplePath");
- when(msoInterface.post("samplePath", requestDetailsWrapper, RequestReferencesContainer.class)).thenReturn(msoResponse);
- when(msoResponse.getStatus()).thenReturn(500);
- when(msoResponse.getBody()).thenReturn(requestReferencesContainer);
-
- NextCommand call = serviceInstantiationCommand.call();
-
- assertThat(call.getCommand(), is(nullValue()));
- assertThat(call.getStatus(), is(equalTo(Job.JobStatus.FAILED)));
-
- verify(auditService).setFailedAuditStatusFromMso(uuid, null, 500, requestReferencesContainer.toString());
- }
-
-
- @Test
- public void shouldProperlyUpdateServiceStatusAndReturnInProgressCommand() {
- RequestReferences requestReferences = createRequestReferences();
-
- when(asyncInstantiationBusinessLogic.generateServiceInstantiationRequest(uuid, serviceInstantiation, "sampleUserId")).thenReturn(requestDetailsWrapper);
- when(asyncInstantiationBusinessLogic.getServiceInstantiationPath(serviceInstantiation)).thenReturn("samplePath");
- when(msoInterface.post("samplePath", requestDetailsWrapper, RequestReferencesContainer.class)).thenReturn(msoResponse);
- when(msoResponse.getStatus()).thenReturn(200);
- when(msoResponse.getBody()).thenReturn(requestReferencesContainer);
- when(requestReferencesContainer.getRequestReferences()).thenReturn(requestReferences);
-
-
- NextCommand call = serviceInstantiationCommand.call();
-
- assertThat(call.getCommand(), instanceOf(InProgressStatusCommand.class));
- assertThat(call.getStatus(), is(equalTo(Job.JobStatus.IN_PROGRESS)));
-
- }
-
- private RequestReferences createRequestReferences() {
- RequestReferences requestReferences = new RequestReferences();
- requestReferences.setInstanceId("sampleInstanceId");
- requestReferences.setRequestId("sampleRequestId");
- return requestReferences;
- }
-} \ No newline at end of file
diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/WatchChildrenJobsBLTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/WatchChildrenJobsBLTest.java
new file mode 100644
index 000000000..98524c7db
--- /dev/null
+++ b/vid-app-common/src/test/java/org/onap/vid/job/command/WatchChildrenJobsBLTest.java
@@ -0,0 +1,98 @@
+package org.onap.vid.job.command;
+
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.onap.portalsdk.core.service.DataAccessService;
+import org.onap.vid.job.Job.JobStatus;
+import org.onap.vid.job.impl.JobDaoImpl;
+import org.onap.vid.utils.DaoUtils;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.UUID;
+import java.util.stream.Collectors;
+
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.when;
+import static org.testng.AssertJUnit.assertEquals;
+
+public class WatchChildrenJobsBLTest {
+ @Mock
+ private DataAccessService dataAccessService;
+
+ @InjectMocks
+ private WatchChildrenJobsBL watchChildrenJobsBL;
+
+ @BeforeClass
+ public void initMocks() {
+ MockitoAnnotations.initMocks(this);
+ }
+
+ public static Object[][] dataProviderForChildrenStatusOnly() {
+ return new Object[][]{
+ {Arrays.asList(JobStatus.STOPPED, JobStatus.COMPLETED_WITH_NO_ACTION, JobStatus.COMPLETED), JobStatus.COMPLETED_WITH_ERRORS},
+ {Arrays.asList(JobStatus.COMPLETED, JobStatus.FAILED, JobStatus.COMPLETED_WITH_NO_ACTION), JobStatus.COMPLETED_WITH_ERRORS},
+ {Arrays.asList(null, JobStatus.COMPLETED), JobStatus.COMPLETED_WITH_ERRORS},
+ {Arrays.asList(null, JobStatus.IN_PROGRESS), JobStatus.IN_PROGRESS},
+ {Arrays.asList(null, JobStatus.FAILED), JobStatus.FAILED},
+ {new ArrayList<>(), JobStatus.COMPLETED_WITH_NO_ACTION}
+ };
+ }
+
+ @DataProvider
+ public static Object[][] childrenStatusDataProvider() {
+
+ List<Object[]> result = new ArrayList<>();
+ result.addAll(Arrays.asList(dataProviderForChildrenStatusOnly()));
+ result.addAll(Arrays.asList(inputsStatusAndExpectedOutputDataProvider()));
+ return result.toArray(new Object[result.size()][]);
+ }
+
+ @DataProvider
+ public static Object[][] inputsStatusAndExpectedOutputDataProvider() {
+ return new Object[][]{
+ {Arrays.asList(JobStatus.COMPLETED, JobStatus.COMPLETED), JobStatus.COMPLETED},
+ {Arrays.asList(JobStatus.COMPLETED, JobStatus.COMPLETED_WITH_NO_ACTION), JobStatus.COMPLETED},
+ {Arrays.asList(JobStatus.FAILED, JobStatus.COMPLETED_WITH_NO_ACTION), JobStatus.FAILED},
+ {Arrays.asList(JobStatus.FAILED, JobStatus.COMPLETED), JobStatus.COMPLETED_WITH_ERRORS},
+ {Arrays.asList(JobStatus.RESOURCE_IN_PROGRESS, JobStatus.FAILED), JobStatus.IN_PROGRESS},
+ {Arrays.asList(JobStatus.PAUSE, JobStatus.FAILED), JobStatus.IN_PROGRESS},
+ {Arrays.asList(JobStatus.PENDING, JobStatus.FAILED), JobStatus.IN_PROGRESS},
+ {Arrays.asList(JobStatus.IN_PROGRESS, JobStatus.COMPLETED), JobStatus.IN_PROGRESS},
+ {Arrays.asList(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS), JobStatus.IN_PROGRESS},
+ {Arrays.asList(JobStatus.COMPLETED, JobStatus.COMPLETED_WITH_ERRORS), JobStatus.COMPLETED_WITH_ERRORS},
+ {Arrays.asList(JobStatus.COMPLETED_WITH_ERRORS, JobStatus.FAILED), JobStatus.COMPLETED_WITH_ERRORS},
+ {Arrays.asList(JobStatus.COMPLETED_WITH_ERRORS, JobStatus.COMPLETED_WITH_ERRORS), JobStatus.COMPLETED_WITH_ERRORS},
+ {Arrays.asList(JobStatus.COMPLETED_WITH_ERRORS, JobStatus.COMPLETED_WITH_NO_ACTION), JobStatus.COMPLETED_WITH_ERRORS},
+ {Arrays.asList(JobStatus.COMPLETED_WITH_NO_ACTION, JobStatus.COMPLETED_WITH_NO_ACTION), JobStatus.COMPLETED_WITH_NO_ACTION},
+
+
+ };
+ }
+
+ @Test(dataProvider = "childrenStatusDataProvider")
+ public void whenRetrieveListOfChildrenWithStatues_thenAccumulatedChildrenStatusAsExpected(List<JobStatus> childJobs, JobStatus expectedChildrenJobsStatus) {
+ //init sql result mock
+ List<JobDaoImpl> mockChildren = childJobs.stream().map(st -> {
+ JobDaoImpl job = new JobDaoImpl();
+ job.setUuid(UUID.randomUUID());
+ job.setStatus(st);
+ return job;
+ }).collect(Collectors.toList());
+ when(dataAccessService.getList(eq(JobDaoImpl.class), anyString(), any(), eq(DaoUtils.getPropsMap())))
+ .thenReturn(mockChildren);
+
+ List<String> uuids = mockChildren.stream().map(job -> job.getUuid().toString()).collect(Collectors.toList());
+ assertEquals(expectedChildrenJobsStatus, watchChildrenJobsBL.retrieveChildrenJobsStatus(uuids));
+ }
+
+ @Test(dataProvider = "inputsStatusAndExpectedOutputDataProvider")
+ public void whenCumulate2JobStatus_thenResultAsExpected(List<JobStatus> jobs, JobStatus expectedChildrenJobsStatus) {
+ assertEquals(expectedChildrenJobsStatus, watchChildrenJobsBL.cumulateJobStatus(jobs.get(0), jobs.get(1)));
+ }
+}
diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/WatchingCommandTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/WatchingCommandTest.java
new file mode 100644
index 000000000..f47a18d5f
--- /dev/null
+++ b/vid-app-common/src/test/java/org/onap/vid/job/command/WatchingCommandTest.java
@@ -0,0 +1,77 @@
+package org.onap.vid.job.command;
+
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.onap.portalsdk.core.service.DataAccessService;
+import org.onap.vid.job.Job;
+import org.onap.vid.job.NextCommand;
+import org.onap.vid.job.impl.JobSharedData;
+import org.onap.vid.model.serviceInstantiation.ServiceInstantiation;
+import org.onap.vid.services.AsyncInstantiationBusinessLogic;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+import java.util.List;
+import java.util.UUID;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.core.Is.is;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.*;
+
+public class WatchingCommandTest {
+
+ @Mock
+ private AsyncInstantiationBusinessLogic asyncInstantiationBL;
+
+ @Mock
+ private DataAccessService dataAccessService;
+
+ @Mock
+ private WatchChildrenJobsBL watchChildrenJobsBL;
+
+ @InjectMocks
+ private WatchingCommand watchingCommand = new WatchingCommand();
+
+
+
+ @BeforeClass
+ public void initMocks() {
+ MockitoAnnotations.initMocks(this);
+ }
+
+ @DataProvider
+ public static Object[][] testWatchingDataProvider() {
+ return new Object[][]{
+ {"all children final, no failed child, is service", Job.JobStatus.COMPLETED, true, Job.JobStatus.COMPLETED},
+ {"all children final, there is failed child, is service", Job.JobStatus.COMPLETED_WITH_ERRORS, true, Job.JobStatus.COMPLETED_WITH_ERRORS},
+ {"not all children final, is service", Job.JobStatus.IN_PROGRESS, true, Job.JobStatus.IN_PROGRESS},
+ {"all children final, no failed child, not service", Job.JobStatus.COMPLETED, false, Job.JobStatus.COMPLETED},
+ {"all children final, there is failed child, not service", Job.JobStatus.COMPLETED_WITH_ERRORS, false, Job.JobStatus.COMPLETED_WITH_ERRORS},
+ {"not all children final, not service", Job.JobStatus.IN_PROGRESS, false, Job.JobStatus.RESOURCE_IN_PROGRESS},
+ };
+ }
+
+
+
+ @Test(dataProvider = "testWatchingDataProvider")
+ public void whenGetChildrenStatus_thenJobStatusAsExpected(String desc, Job.JobStatus childrenComulativeStatus, boolean isService, Job.JobStatus expectedCommandStatus) {
+ UUID jobUUID = UUID.randomUUID();
+ JobSharedData sharedData = new JobSharedData(jobUUID, "mockedUserID", mock(ServiceInstantiation.class));
+ List<String> uuids = mock(List.class);
+ watchingCommand.init(sharedData, uuids, isService);
+ when(watchChildrenJobsBL.retrieveChildrenJobsStatus(eq(uuids))).thenReturn(childrenComulativeStatus);
+ when(watchChildrenJobsBL.cumulateJobStatus(eq(childrenComulativeStatus),eq(Job.JobStatus.COMPLETED))).thenReturn(childrenComulativeStatus);
+
+ //execute command and verify
+ NextCommand nextCommand = watchingCommand.call();
+ assertThat(nextCommand.getStatus(), is(expectedCommandStatus));
+ if (!expectedCommandStatus.equals(Job.JobStatus.IN_PROGRESS) && isService) {
+ verify(asyncInstantiationBL).updateServiceInfoAndAuditStatus(jobUUID, expectedCommandStatus);
+ } else {
+ verify(asyncInstantiationBL, never()).updateServiceInfoAndAuditStatus(jobUUID, expectedCommandStatus);
+ }
+ }
+}
diff --git a/vid-app-common/src/test/java/org/onap/vid/job/impl/AsyncInstantiationIntegrationTest.java b/vid-app-common/src/test/java/org/onap/vid/job/impl/AsyncInstantiationIntegrationTest.java
new file mode 100644
index 000000000..f7f83bdfe
--- /dev/null
+++ b/vid-app-common/src/test/java/org/onap/vid/job/impl/AsyncInstantiationIntegrationTest.java
@@ -0,0 +1,925 @@
+package org.onap.vid.job.impl;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import org.apache.commons.lang3.StringUtils;
+import org.mockito.Mockito;
+import org.onap.portalsdk.core.service.DataAccessService;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.onap.vid.asdc.AsdcCatalogException;
+import org.onap.vid.config.DataSourceConfig;
+import org.onap.vid.config.JobCommandsConfigWithMockedMso;
+import org.onap.vid.config.MockedAaiClientAndFeatureManagerConfig;
+import org.onap.vid.job.Job;
+import org.onap.vid.job.Job.JobStatus;
+import org.onap.vid.job.JobType;
+import org.onap.vid.job.JobsBrokerService;
+import org.onap.vid.job.command.CommandUtils;
+import org.onap.vid.job.command.InternalState;
+import org.onap.vid.model.Action;
+import org.onap.vid.model.NameCounter;
+import org.onap.vid.model.RequestReferencesContainer;
+import org.onap.vid.model.ServiceInfo;
+import org.onap.vid.model.serviceInstantiation.ServiceInstantiation;
+import org.onap.vid.mso.RestMsoImplementation;
+import org.onap.vid.mso.RestObject;
+import org.onap.vid.mso.model.RequestReferences;
+import org.onap.vid.mso.rest.AsyncRequestStatus;
+import org.onap.vid.properties.Features;
+import org.onap.vid.services.AsyncInstantiationBaseTest;
+import org.onap.vid.services.AsyncInstantiationBusinessLogic;
+import org.onap.vid.utils.DaoUtils;
+import org.springframework.test.context.ContextConfiguration;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.DataProvider;
+import org.togglz.core.manager.FeatureManager;
+
+import javax.inject.Inject;
+import javax.ws.rs.ProcessingException;
+import java.lang.reflect.Method;
+import java.util.*;
+import java.util.function.BiConsumer;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+import java.util.stream.Stream;
+
+import static java.util.stream.Collectors.*;
+import static net.javacrumbs.jsonunit.JsonMatchers.jsonPartEquals;
+import static org.hamcrest.CoreMatchers.*;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.hasProperty;
+import static org.hamcrest.Matchers.hasSize;
+import static org.hamcrest.core.Every.everyItem;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.endsWith;
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.*;
+import static org.onap.vid.job.Job.JobStatus.*;
+import static org.onap.vid.model.JobAuditStatus.SourceStatus.MSO;
+import static org.onap.vid.model.JobAuditStatus.SourceStatus.VID;
+import static org.testng.AssertJUnit.*;
+
+//it's more like integration test than UT
+//But it's very hard to test in API test so I use UT
+@ContextConfiguration(classes = {DataSourceConfig.class, SystemProperties.class, MockedAaiClientAndFeatureManagerConfig.class, JobCommandsConfigWithMockedMso.class})
+public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTest {
+
+ private static final String FAILED_STR = "FAILED";
+ private static final String COMPLETE_STR = "COMPLETE";
+ private static final String IN_PROGRESS_STR = "IN_PROGRESS";
+ private static final String REQUESTED = "REQUESTED";
+ private static final String PENDING_MANUAL_TASK = "PENDING_MANUAL_TASK";
+ public static final String RAW_DATA_FROM_MSO = "RAW DATA FROM MSO";
+ private static String USER_ID = "123";
+ public static String REQUEST_ID = UUID.randomUUID().toString();
+ public static String SERVICE_INSTANCE_ID = UUID.randomUUID().toString();
+
+ @Inject
+ private JobsBrokerService jobsBrokerService;
+
+ @Inject
+ private JobWorker jobWorker;
+
+ @Inject
+ private FeatureManager featureManager;
+
+ @Inject
+ private AsyncInstantiationBusinessLogic asyncInstantiationBL;
+
+ @Inject
+ private RestMsoImplementation restMso;
+
+ @Inject
+ private DataAccessService dataAccessService;
+
+ @Inject
+ private CommandUtils commandUtils;
+
+ @BeforeClass
+ void initServicesInfoService() {
+ createInstanceParamsMaps();
+ }
+
+ @BeforeMethod
+ void clearDb() {
+ dataAccessService.deleteDomainObjects(ServiceInfo.class, "1=1", DaoUtils.getPropsMap());
+ dataAccessService.deleteDomainObjects(JobDaoImpl.class, "1=1", DaoUtils.getPropsMap());
+ dataAccessService.deleteDomainObjects(NameCounter.class, "1=1", DaoUtils.getPropsMap());
+ }
+
+ @BeforeMethod
+ void defineMocks() {
+ mockAaiClientAnyNameFree();
+ }
+
+ //@Test
+ public void whenPushNewBulk_thenAllServicesAreInPending() {
+
+ pushMacroBulk();
+ List<ServiceInfo> serviceInfoList = asyncInstantiationBL.getAllServicesInfo();
+ assertThat( serviceInfoList, everyItem(hasProperty("jobStatus", is(PENDING))));
+ }
+
+ private List<UUID> pushMacroBulk() {
+ ServiceInstantiation serviceInstantiation = generateMockMacroServiceInstantiationPayload(false,
+ createVnfList(instanceParamsMapWithoutParams, Collections.EMPTY_LIST, true),
+ 3, true,PROJECT_NAME, true);
+ return asyncInstantiationBL.pushBulkJob(serviceInstantiation, USER_ID);
+ }
+
+ private UUID pushALaCarteWithVnf() {
+ ServiceInstantiation serviceInstantiation = generateALaCarteWithVnfsServiceInstantiationPayload();
+ List<UUID> uuids = asyncInstantiationBL.pushBulkJob(serviceInstantiation, USER_ID);
+ assertThat(uuids, hasSize(1));
+ return uuids.get(0);
+ }
+
+ private UUID pushALaCarteUpdateWithGroups() {
+ ServiceInstantiation serviceInstantiation = generateALaCarteUpdateWith1ExistingGroup2NewGroupsPayload();
+ List<UUID> uuids = asyncInstantiationBL.pushBulkJob(serviceInstantiation, USER_ID);
+ assertThat(uuids, hasSize(1));
+ return uuids.get(0);
+ }
+
+ public static RestObject<RequestReferencesContainer> createResponse(int statusCode) {
+ return createResponse(statusCode, SERVICE_INSTANCE_ID, REQUEST_ID);
+ }
+
+ public static RestObject<RequestReferencesContainer> createResponse(int statusCode, String instanceId, String requestId) {
+ RequestReferences requestReferences = new RequestReferences();
+ requestReferences.setRequestId(requestId);
+ requestReferences.setInstanceId(instanceId);
+ RestObject<RequestReferencesContainer> restObject = new RestObject<>();
+ restObject.set(new RequestReferencesContainer(requestReferences));
+ restObject.setStatusCode(statusCode);
+ restObject.setRaw(RAW_DATA_FROM_MSO);
+ return restObject;
+ }
+
+ ImmutableList<String> statusesToStrings(JobStatus... jobStatuses) {
+ return Stream.of(jobStatuses).map(
+ Enum::toString).collect(ImmutableList.toImmutableList());
+ }
+
+ /*
+ Make sure service state is in progress once request has sent to MSO
+ Make sure service state is in progress once request has sent to MSO and MSO status is in_progress
+ Make sure service state is Failed once we got from MSO failure state, and that job's are not collected any more.
+ Make sure service state is Completed successfully once we got from MSO complete, and that next job is peeked.
+ Once a service in the bulk is failed, other services moved to Stopped, and no other jobs from the bulk are peeked.
+ */
+ //@Test
+ public void testStatusesOfMacroServiceInBulkDuringBulkLifeCycle() {
+ when(restMso.PostForObject(any(), any(), eq(RequestReferencesContainer.class))).thenReturn(createResponse(200));
+ ImmutableList<ImmutableList<String>> expectedStatusesForVid = ImmutableList.of(
+ statusesToStrings(PENDING, IN_PROGRESS, COMPLETED),
+ statusesToStrings(PENDING, IN_PROGRESS, FAILED),
+ statusesToStrings(PENDING, STOPPED)
+ );
+
+ ImmutableList<ImmutableList<String>> expectedStatusesForMso = ImmutableList.of(
+ ImmutableList.of(REQUESTED, IN_PROGRESS_STR, "not a state", FAILED_STR ,COMPLETE_STR),
+ ImmutableList.of(REQUESTED, FAILED_STR),
+ ImmutableList.of()
+ );
+
+ List<UUID> uuids = pushMacroBulk();
+ pullPendingJobAndAssertJobStatus(JobStatus.IN_PROGRESS, PENDING);
+
+ //assert that when get ProcessingException from restMso, status remain the same
+ when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))).thenThrow(new ProcessingException("fake message"));
+ Job job = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS);
+ UUID firstHandledJobUUID = job.getUuid();
+ listServicesAndAssertStatus(JobStatus.IN_PROGRESS, PENDING, job);
+
+ //assert that when get IN_PROGRESS status from restMso, status remain IN_PROGRESS
+ when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))).thenReturn(asyncRequestStatusResponseAsRestObject(IN_PROGRESS_STR));
+ job = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS);
+ listServicesAndAssertStatus(JobStatus.IN_PROGRESS, PENDING, job);
+
+ //assert that when get unrecognized status from restMso, status remain IN_PROGRESS
+ when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))).thenReturn(asyncRequestStatusResponseAsRestObject("not a state"));
+ job = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS);
+ listServicesAndAssertStatus(JobStatus.IN_PROGRESS, PENDING, job);
+
+ //assert that when get non 200 status code during IN_PROGRESS, status remain IN_PROGRESS
+ when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))).thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR, 404));
+ job = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS);
+ listServicesAndAssertStatus(JobStatus.IN_PROGRESS, PENDING, job);
+
+ //when get job COMPLETE from MSO, service status become COMPLETED
+ when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))).
+ thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR));
+ job = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, COMPLETED);
+ List<ServiceInfo> serviceInfoList = listServicesAndAssertStatus(COMPLETED, PENDING, job);
+
+
+ //for use later in the test
+ Map<UUID, JobStatus> expectedJobStatusMap = serviceInfoList.stream().collect(
+ Collectors.toMap(ServiceInfo::getJobId, x-> PENDING));
+ expectedJobStatusMap.put(job.getUuid(), COMPLETED);
+
+ //when handling another PENDING job, statuses are : COMPLETED, IN_PROGRESS, PENDING
+ job = pullJobProcessAndPushBack(PENDING, JobStatus.IN_PROGRESS);
+ assertThat(job.getUuid(), not(equalTo(firstHandledJobUUID))); //assert different job was handled now
+ expectedJobStatusMap.put(job.getUuid(), JobStatus.IN_PROGRESS);
+ listServicesAndAssertStatus(expectedJobStatusMap);
+
+ //when get FAILED status from MSO statuses are : COMPLETED, FAILED, STOPPED
+ when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))).
+ thenReturn(asyncRequestStatusResponseAsRestObject(FAILED_STR));
+ job = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, JobStatus.FAILED);
+ expectedJobStatusMap.put(job.getUuid(), JobStatus.FAILED);
+ expectedJobStatusMap = expectedJobStatusMap.entrySet().stream().collect(Collectors.toMap(
+ e -> e.getKey(), e -> e.getValue() == PENDING ? JobStatus.STOPPED : e.getValue()
+ ));
+
+ listServicesAndAssertStatus(expectedJobStatusMap);
+ IntStream.range(0, uuids.size()).forEach(i -> {
+ UUID uuid = uuids.get(i);
+ List<String> msoStatuses = asyncInstantiationBL.getAuditStatuses(uuid, MSO).stream().map(x -> x.getJobStatus()).collect(Collectors.toList());
+ List<String> vidStatuses = asyncInstantiationBL.getAuditStatuses(uuid, VID).stream().map(x -> x.getJobStatus()).collect(Collectors.toList());
+ assertThat(msoStatuses, is(expectedStatusesForMso.get(i)));
+ assertThat(vidStatuses, is(expectedStatusesForVid.get(i)));
+ });
+ //
+ assertFalse(jobsBrokerService.pull(PENDING, randomUuid()).isPresent());
+ assertFalse(jobsBrokerService.pull(JobStatus.IN_PROGRESS, randomUuid()).isPresent());
+ }
+
+
+ @DataProvider
+ public static Object[][] AlaCarteStatuses(Method test) {
+ return new Object[][]{
+ {COMPLETE_STR, JobStatus.COMPLETED, JobStatus.COMPLETED},
+ {FAILED_STR, JobStatus.COMPLETED_WITH_ERRORS, JobStatus.FAILED},
+ };
+ }
+
+ /*
+ Make sure service state is in progress once request has sent to MSO
+ Make sure service state is watching until state changes to complemented
+ Make sure service state is watching until vnf state changes to completed
+ Make sure service state is Completed successfully once we got from MSO complete for the vnf job.
+ status Creating
+ */
+ //@Test(dataProvider = "AlaCarteStatuses")
+ public void testStatusesOfServiceDuringALaCarteLifeCycleIgnoringVfModules(String msoVnfStatus, JobStatus expectedServiceStatus, JobStatus expectedVnfStatus) {
+ /*
+ [v] + push alacarte with 1 vnf
+ [v] verify STATUS pending
+ [v] + pull+execute (should post to MSO)
+ [v] verify STATUS in progress
+ [v] + pull+execute (should GET completed from MSO)
+ [v] verify STATUS in progress; TYPE watching
+ [v] verify job#2 *new* VNF job STATUS creating
+ [v] + pull+execute job#2 (should post to MSO)
+ [v] verify job#2 STATUS resource in progress
+ [v] verify job#1 STATUS in progress
+ [v] + pull+execute job#2 (should GET completed from MSO)
+ [v] verify job#2 STATUS completed
+ [v] + pull+execute job#1
+ [v] verify job#1 STATUS completed
+
+ * not looking on audit (yet)
+ */
+ when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VNF)).thenReturn(true);
+ when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VFMODULE)).thenReturn(false);
+ final String SERVICE_REQUEST_ID = UUID.randomUUID().toString();
+ final String SERVICE_INSTANCE_ID = UUID.randomUUID().toString();
+ final String VNF_REQUEST_ID = UUID.randomUUID().toString();
+
+
+ //push alacarte with 1 vnf, verify STATUS pending
+ UUID uuid = pushALaCarteWithVnf();
+ singleServicesAndAssertStatus(JobStatus.PENDING, uuid);
+
+ //mock mso to answer 200 of create service instance request, verify STATUS in progress
+ when(restMso.PostForObject(any(), endsWith("serviceInstances"), eq(RequestReferencesContainer.class))).thenReturn(
+ createResponse(200, SERVICE_INSTANCE_ID, SERVICE_REQUEST_ID));
+ pullJobProcessAndPushBackWithTypeAssertion(JobStatus.PENDING, JobStatus.IN_PROGRESS, JobType.InProgressStatus);
+ singleServicesAndAssertStatus(JobStatus.IN_PROGRESS, uuid);
+
+ //mock mso to answer COMPLETE for service instance create, job status shall remain IN_PROGRESS and type shall be Watching
+ reset(restMso);
+ when(restMso.GetForObject(endsWith(SERVICE_REQUEST_ID), eq(AsyncRequestStatus.class))).
+ thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR));
+ pullJobProcessAndPushBackWithTypeAssertion(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS, JobType.Watching);
+ singleServicesAndAssertStatus(JobStatus.IN_PROGRESS, uuid);
+
+ //mock mso to answer 200 of create vnf instance request, pull+execute vnf job, STATUS resource in progress
+ reset(restMso);
+ when(restMso.PostForObject(any(), endsWith(SERVICE_INSTANCE_ID + "/vnfs"), eq(RequestReferencesContainer.class))).thenReturn(
+ createResponse(200, UUID.randomUUID().toString(), VNF_REQUEST_ID));
+ pullJobProcessAndPushBackWithTypeAssertion(JobStatus.CREATING, JobStatus.RESOURCE_IN_PROGRESS, JobType.VnfInProgressStatus);
+
+ //verify service job STATUS in progress
+ pullJobProcessAndPushBackWithTypeAssertion(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS, JobType.Watching);
+ singleServicesAndAssertStatus(JobStatus.IN_PROGRESS, uuid);
+
+ //mock mso to answer msoVnfStatus (COMPLETE/FAILED) for vnf creation status,
+ //job status shall be final (COMPLETE/COMPLETE_WITH_ERRORS)
+ reset(restMso);
+ when(restMso.GetForObject(endsWith(VNF_REQUEST_ID), eq(AsyncRequestStatus.class))).thenReturn(
+ asyncRequestStatusResponseAsRestObject(msoVnfStatus));
+ pullJobProcessAndPushBack(JobStatus.RESOURCE_IN_PROGRESS, expectedVnfStatus, false);
+ singleServicesAndAssertStatus(JobStatus.IN_PROGRESS, uuid);
+ pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, expectedServiceStatus, true);
+ singleServicesAndAssertStatus(expectedServiceStatus, uuid);
+
+ }
+
+ /*
+ this test is almost duplication of testStatusesOfServiceDuringALaCarteLifeCycleIgnoringVfModules.
+
+ IgnoringVfModules test check the scenario while FLAG_ASYNC_ALACARTE_VFMODULE is off
+ WithVfModules test check the scenario while FLAG_ASYNC_ALACARTE_VFMODULE is on
+
+ We shall consider later to remove testStatusesOfServiceDuringALaCarteLifeCycleIgnoringVfModules
+ And union these tests to single one.
+ */
+
+ //@Test
+ public void testALaCarteLifeCycle1Vnf2VfModules() {
+
+
+ String msoVnfStatus = COMPLETE_STR;
+ JobStatus expectedServiceStatus = IN_PROGRESS;
+ JobStatus expectedVnfStatus = RESOURCE_IN_PROGRESS;
+ when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VNF)).thenReturn(true);
+ when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VFMODULE)).thenReturn(true);
+ final String SERVICE_REQUEST_ID = UUID.randomUUID().toString();
+ final String SERVICE_INSTANCE_ID = UUID.randomUUID().toString();
+ final String VNF_REQUEST_ID = UUID.randomUUID().toString();
+ final String VNF_INSTANCE_ID = UUID.randomUUID().toString();
+ final String VG_REQUEST_ID = UUID.randomUUID().toString();
+ final String VG_INSTANCE_ID = UUID.randomUUID().toString();
+ final String VF_MODULE_REQUEST_ID = UUID.randomUUID().toString();
+ final String VF_MODULE_REQUEST_ID2 = UUID.randomUUID().toString();
+
+
+ //push alacarte with 1 vnf, verify STATUS pending
+ UUID uuid = pushALaCarteWithVnf();
+ singleServicesAndAssertStatus(JobStatus.PENDING, uuid);
+
+ /*---------- service -----------*/
+
+ //mock mso to answer 200 of create service instance request, verify STATUS in progress
+ when(restMso.PostForObject(any(), endsWith("serviceInstances"), eq(RequestReferencesContainer.class))).thenReturn(
+ createResponse(200, SERVICE_INSTANCE_ID, SERVICE_REQUEST_ID));
+ pullJobProcessAndPushBackWithTypeAssertion(JobStatus.PENDING, JobStatus.IN_PROGRESS, JobType.InProgressStatus);
+ singleServicesAndAssertStatus(JobStatus.IN_PROGRESS, uuid);
+
+ //mock mso to answer COMPLETE for service instance create, job status shall remain IN_PROGRESS and type shall be Watching
+ reset(restMso);
+ when(restMso.GetForObject(endsWith(SERVICE_REQUEST_ID), eq(AsyncRequestStatus.class))).
+ thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR));
+ pullJobProcessAndPushBackWithTypeAssertion(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS, JobType.Watching);
+ singleServicesAndAssertStatus(JobStatus.IN_PROGRESS, uuid);
+
+ /*---------- vnf -----------*/
+
+ //mock mso to answer 200 of create vnf instance request, pull+execute vnf job, STATUS resource in progress
+ reset(restMso);
+ when(restMso.PostForObject(any(), endsWith(SERVICE_INSTANCE_ID + "/vnfs"), eq(RequestReferencesContainer.class))).thenReturn(
+ createResponse(200, VNF_INSTANCE_ID, VNF_REQUEST_ID));
+ pullJobProcessAndPushBackWithTypeAssertion(JobStatus.CREATING, JobStatus.RESOURCE_IN_PROGRESS, JobType.VnfInProgressStatus);
+
+ //verify service job STATUS in progress
+ pullJobProcessAndPushBackWithTypeAssertion(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS, JobType.Watching);
+ singleServicesAndAssertStatus(JobStatus.IN_PROGRESS, uuid);
+
+ //mock mso to answer msoVnfStatus (COMPLETE/FAILED) for vnf creation status,
+ //job status shall be final (COMPLETE/COMPLETE_WITH_ERRORS)
+ reset(restMso);
+ when(restMso.GetForObject(endsWith(VNF_REQUEST_ID), eq(AsyncRequestStatus.class))).
+ thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR));
+
+ try {
+ reset(commandUtils);
+ when(commandUtils.isVfModuleBaseModule(SERVICE_MODEL_VERSION_ID, VF_MODULE_0_MODEL_VERSION_ID)).thenReturn(true);
+ when(commandUtils.isVfModuleBaseModule(SERVICE_MODEL_VERSION_ID, VF_MODULE_1_MODEL_VERSION_ID)).thenReturn(false);
+ } catch (AsdcCatalogException e) {
+
+ }
+
+ pullJobProcessAndPushBackWithTypeAssertion(JobStatus.RESOURCE_IN_PROGRESS, JobStatus.RESOURCE_IN_PROGRESS, JobType.WatchingBaseModule);
+ singleServicesAndAssertStatus(JobStatus.IN_PROGRESS, uuid);
+ pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS, true);
+ singleServicesAndAssertStatus(JobStatus.IN_PROGRESS, uuid);
+
+ /*---------- vf Module without volume group name (base) -----------*/
+
+ //vg name not exist, so vf module created immediately
+ pullJobProcessAndPushBackWithTypeAssertion(JobStatus.CREATING, JobStatus.RESOURCE_IN_PROGRESS, JobType.Watching);
+
+ //verify vnf/volumeGroup job STATUS still watching with resource in progress
+ pullMultipleJobsFindExpectedProcessAndPushBack(JobStatus.RESOURCE_IN_PROGRESS, JobType.Watching, JobStatus.RESOURCE_IN_PROGRESS, JobType.Watching);
+
+ //mock mso to answer 200 of create vfModule instance request, pull+execute volumeGroup job, STATUS resource in progress
+ reset(restMso);
+ when(restMso.PostForObject(any(), endsWith(SERVICE_INSTANCE_ID + "/vnfs/" + VNF_INSTANCE_ID + "/vfModules"), eq(RequestReferencesContainer.class))).thenReturn(
+ createResponse(200, UUID.randomUUID().toString(), VF_MODULE_REQUEST_ID));
+ pullJobProcessAndPushBackWithTypeAssertion(JobStatus.CREATING, JobStatus.RESOURCE_IN_PROGRESS, JobType.ResourceInProgressStatus);
+
+ //mock mso to answer for vf module orchestration request
+ reset(restMso);
+ when(restMso.GetForObject(endsWith(VF_MODULE_REQUEST_ID), eq(AsyncRequestStatus.class))).thenReturn(
+ asyncRequestStatusResponseAsRestObject(COMPLETE_STR));
+ pullMultipleJobsFindExpectedProcessAndPushBack(JobStatus.RESOURCE_IN_PROGRESS, JobType.ResourceInProgressStatus, JobStatus.COMPLETED, JobType.ResourceInProgressStatus);
+
+ //verify volume group become completed
+ pullMultipleJobsFindExpectedProcessAndPushBack(JobStatus.RESOURCE_IN_PROGRESS, JobType.Watching, JobStatus.COMPLETED, JobType.Watching);
+
+ //vnf become watching after volume group completed, and new volume group created
+ pullMultipleJobsFindExpectedProcessAndPushBack(JobStatus.RESOURCE_IN_PROGRESS, JobType.WatchingBaseModule, JobStatus.RESOURCE_IN_PROGRESS, JobType.Watching);
+
+ /*---------- volume group & vf module (non base) -----------*/
+
+ /*---------- volume group -----------*/
+
+ //mock mso to answer 200 of create volumeGroup instance request, pull+execute volumeGroup job, STATUS resource in progress
+ reset(restMso);
+ when(restMso.PostForObject(any(), endsWith(SERVICE_INSTANCE_ID + "/vnfs/" + VNF_INSTANCE_ID + "/volumeGroups"), eq(RequestReferencesContainer.class))).thenReturn(
+ createResponse(200, VG_INSTANCE_ID, VG_REQUEST_ID));
+ pullJobProcessAndPushBackWithTypeAssertion(JobStatus.CREATING, JobStatus.RESOURCE_IN_PROGRESS, JobType.VolumeGroupInProgressStatus);
+
+ //verify vnf job STATUS still watching with resource in progress
+ pullMultipleJobsFindExpectedProcessAndPushBack(JobStatus.RESOURCE_IN_PROGRESS, JobType.Watching, JobStatus.RESOURCE_IN_PROGRESS, JobType.Watching);
+
+ //mock mso to answer for volume group orchestration request
+ reset(restMso);
+ when(restMso.GetForObject(endsWith(VG_REQUEST_ID), eq(AsyncRequestStatus.class))).thenReturn(
+ asyncRequestStatusResponseAsRestObject(msoVnfStatus));
+ pullMultipleJobsFindExpectedProcessAndPushBack(JobStatus.RESOURCE_IN_PROGRESS, JobType.VolumeGroupInProgressStatus, JobStatus.RESOURCE_IN_PROGRESS, JobType.Watching);
+
+ /*---------- vfModule -----------*/
+
+ //mock mso to answer 200 of create vfModule instance request, pull+execute volumeGroup job, STATUS resource in progress
+ reset(restMso);
+ when(restMso.PostForObject(any(), endsWith(SERVICE_INSTANCE_ID + "/vnfs/" + VNF_INSTANCE_ID + "/vfModules"), eq(RequestReferencesContainer.class))).thenReturn(
+ createResponse(200, UUID.randomUUID().toString(), VF_MODULE_REQUEST_ID2));
+ pullJobProcessAndPushBackWithTypeAssertion(JobStatus.CREATING, JobStatus.RESOURCE_IN_PROGRESS, JobType.ResourceInProgressStatus);
+
+ //mock mso to answer for vf module orchestration request
+ reset(restMso);
+ when(restMso.GetForObject(endsWith(VF_MODULE_REQUEST_ID2), eq(AsyncRequestStatus.class))).thenReturn(
+ asyncRequestStatusResponseAsRestObject(COMPLETE_STR));
+ pullMultipleJobsFindExpectedProcessAndPushBack(JobStatus.RESOURCE_IN_PROGRESS, JobType.ResourceInProgressStatus, JobStatus.COMPLETED, JobType.ResourceInProgressStatus);
+
+ //execute twice - 1 for parent volume group, 1 for parent vnf
+ pullAllJobProcessAndPushBackByType(JobStatus.RESOURCE_IN_PROGRESS, JobType.Watching , JobStatus.COMPLETED);
+
+ singleServicesAndAssertStatus(JobStatus.IN_PROGRESS, uuid);
+ pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, JobStatus.COMPLETED, true);
+ singleServicesAndAssertStatus(JobStatus.COMPLETED, uuid);
+ }
+
+ //@Test
+ public void testBadAaiResponseForSearchNamesAndBackToNormal() {
+ when(aaiClient.isNodeTypeExistsByName(any(), any())).thenThrow(aaiNodeQueryBadResponseException());
+ pushMacroBulk(); //JOB shall become IN_PROGRESS but service info is still pending
+ Job job = pullJobProcessAndPushBack(PENDING, JobStatus.IN_PROGRESS, true);
+ listServicesAndAssertStatus(PENDING, PENDING, job);
+
+ //JOB shall remain in IN_PROGRESS
+ job = pullJobProcessAndPushBack( JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS, true);
+ //make sure the job command is still ServiceInstantiation
+ assertThat(job.getType(), is(JobType.MacroServiceInstantiation));
+ listServicesAndAssertStatus(PENDING, PENDING, job);
+
+ //simulate AAI back to normal, AAI return name is free, and MSO return good response
+ Mockito.reset(aaiClient); // must forget the "thenThrow"
+ when(aaiClient.isNodeTypeExistsByName(any(), any())).thenReturn(false);
+ when(restMso.PostForObject(any(),any(), eq(RequestReferencesContainer.class))).thenReturn(createResponse(200));
+ job = pullJobProcessAndPushBack( JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS, true);
+ listServicesAndAssertStatus(JobStatus.IN_PROGRESS, PENDING, job);
+
+ //when get job COMPLETE from MSO, service status become COMPLETED
+ when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))).
+ thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR));
+ job = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, COMPLETED);
+ listServicesAndAssertStatus(COMPLETED, PENDING, job);
+ }
+
+ //@Test
+ public void testAaiResponseNameUsedTillMaxRetries() {
+ when(aaiClient.isNodeTypeExistsByName(any(), any())).thenReturn(true);
+ asyncInstantiationBL.setMaxRetriesGettingFreeNameFromAai(10);
+ pushMacroBulk();
+ //JOB shall become IN_PROGRESS but service info is still pending
+ Job job = pullJobProcessAndPushBack(PENDING, JobStatus.FAILED, true);
+ listServicesAndAssertStatus(JobStatus.FAILED, JobStatus.STOPPED, job);
+ }
+
+ private Job pullJobProcessAndPushBack(JobStatus topic, JobStatus expectedNextJobStatus) {
+ return pullJobProcessAndPushBack(topic, expectedNextJobStatus, true);
+ }
+
+ //return the pulled job (and not the pushed job)
+ private Job pullJobProcessAndPushBack(JobStatus topic, JobStatus expectedNextJobStatus, boolean pullingAssertion) {
+ Optional<Job> job = pullJob(topic, pullingAssertion);
+
+ Job nextJob = jobWorker.executeJobAndGetNext(job.get());
+
+ try {
+ assertThat("next job not ok: " + nextJob.getData(), nextJob.getStatus(), is(expectedNextJobStatus));
+
+ if (pullingAssertion) {
+ //assert another pulling on same topic return no result (before push back)
+ assertFalse(jobsBrokerService.pull(topic, randomUuid()).isPresent());
+ }
+
+ } finally {
+ jobsBrokerService.pushBack(nextJob); // push back to let retries - even if any assertion failure
+ }
+ assertThat(jobsBrokerService.peek(job.get().getUuid()).getStatus(), is(expectedNextJobStatus));
+ return job.get();
+ }
+
+ private Job pullJobProcessAndPushBackWithTypeAssertion(JobStatus topic, JobStatus expectedNextJobStatus,
+ JobType expectedNextJobType) {
+ Job job = pullJobProcessAndPushBack(topic, expectedNextJobStatus, false);
+ assertThat("job not ok: " + job.getData(), job.getType(), is(expectedNextJobType));
+ return job;
+ }
+
+ private Job pullJobProcessAndPushBackWithTypeAssertion(JobStatus topic, JobStatus expectedNextJobStatus,
+ JobType expectedNextJobType, int retries) {
+ return retryWithAssertionsLimit(retries, () -> {
+ return pullJobProcessAndPushBackWithTypeAssertion(topic, expectedNextJobStatus, expectedNextJobType);
+ });
+ }
+
+ private Job pullJobProcessAndPushBackWithTypeAssertion(JobStatus topic, JobStatus expectedNextJobStatus,
+ JobType expectedNextJobType, Action actionPhase, InternalState internalState, int retries) {
+ return retryWithAssertionsLimit(retries, () -> {
+ Job job = pullJobProcessAndPushBackWithTypeAssertion(topic, expectedNextJobStatus, expectedNextJobType);
+ assertThat("job not ok: " + job.getData(), job.getData(), is(jsonPartEquals("actionPhase", actionPhase.name())));
+ if (internalState != null) {
+ assertThat("job not ok: " + job.getData(), job.getData(), is(jsonPartEquals("internalState", internalState.name())));
+ }
+ return job;
+ });
+ }
+
+ private Job retryWithAssertionsLimit(int retries, Supplier<Job> supplier) {
+ java.util.Stack<AssertionError> history = new Stack<>();
+
+ do {
+ try {
+ return supplier.get();
+ } catch (AssertionError assertionError) {
+ history.push(assertionError);
+ }
+ } while (history.size() < retries);
+
+ // No success:
+ throw new AssertionError("No luck while all of these assertion errors: " + history.stream()
+ .map(Throwable::getMessage)
+ .map(s -> s.replace('\n', ' '))
+ .map(s -> s.replaceAll("\\s{2,}"," "))
+ .distinct()
+ .collect(joining("\n ", "\n ", "")), history.peek());
+ }
+
+ private Job pullMultipleJobsFindExpectedProcessAndPushBack(JobStatus topic, JobType expectedCurrentJobType, JobStatus expectedNextJobStatus,
+ JobType expectedNextJobType) {
+ List<Job> pulledJobs = new ArrayList<>();
+ Job lastJob = null;
+ while (lastJob == null || lastJob.getType() != expectedCurrentJobType) {
+ lastJob = pullJob(topic, false).get();
+ if (lastJob.getType() != expectedCurrentJobType) {
+ pulledJobs.add(lastJob);
+ }
+ }
+
+ Job nextJob = jobWorker.executeJobAndGetNext(lastJob);
+ assertThat(nextJob.getStatus(), is(expectedNextJobStatus));
+ assertThat(nextJob.getType(), is(expectedNextJobType));
+
+ jobsBrokerService.pushBack(nextJob);
+ assertThat(jobsBrokerService.peek(nextJob.getUuid()).getStatus(), is(expectedNextJobStatus));
+
+ pulledJobs.forEach(job ->
+ jobsBrokerService.pushBack(job)
+ );
+
+ return nextJob;
+ }
+
+ private void pullAllJobProcessAndPushBackByType(JobStatus topic, JobType commandType, JobStatus expectedFinalStatus) {
+ Map<UUID, JobStatus> jobStatusMap = new HashMap<>();
+ Optional<Job> job = pullJob(topic, false);
+ for (int i=0; i<1000 && job.isPresent() && job.get().getType() == commandType; i++) {
+ Job nextJob = jobWorker.executeJobAndGetNext(job.get());
+ jobStatusMap.put(nextJob.getUuid(), nextJob.getStatus());
+ jobsBrokerService.pushBack(nextJob);
+ job = jobsBrokerService.pull(topic, UUID.randomUUID().toString());
+ }
+ assertThat(jobStatusMap.values(), everyItem(is(expectedFinalStatus)));
+
+ }
+
+ private Optional<Job> pullJob(JobStatus topic, boolean pullingAssertion) {
+ if (pullingAssertion) {
+ //assert pulling on inverse topic return no result
+ assertFalse(jobsBrokerService.pull(inverseTopic(topic), randomUuid()).isPresent());
+ }
+
+ Optional<Job> job = jobsBrokerService.pull(topic, randomUuid());
+ assertTrue("no job fetched", job.isPresent());
+
+ if (pullingAssertion) {
+ //assert another pulling on same topic return no result
+ assertFalse(jobsBrokerService.pull(topic, randomUuid()).isPresent());
+ }
+
+ return job;
+ }
+
+ private JobStatus inverseTopic(JobStatus topic) {
+ return topic==JobStatus.IN_PROGRESS ? PENDING : JobStatus.IN_PROGRESS;
+ }
+
+
+ //@Test
+ public void whenPushNewBulk_andGetNoResponseFromMsoOnCreation_thenServiceMoveToFailedAndOtherToStopped() {
+ when(restMso.PostForObject(any(), any(), eq(RequestReferencesContainer.class))).thenReturn(createResponse(500));
+ pushBulkPullPendingJobAndAssertJobStatus(JobStatus.FAILED, JobStatus.STOPPED);
+ }
+
+ //@Test
+ public void whenMsoStatusIsPendingManualTask_ThenJobStatusIsPaused() {
+ when(restMso.PostForObject(any(), any(), eq(RequestReferencesContainer.class))).thenReturn(createResponse(200));
+
+ Job firstJob = pushBulkPullPendingJobAndAssertJobStatus(JobStatus.IN_PROGRESS, PENDING);
+
+ //assert that when get ProcessingException from restMso, status remain the same
+ when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))).
+ thenReturn(asyncRequestStatusResponseAsRestObject(PENDING_MANUAL_TASK));
+ Job job = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS);
+ listServicesAndAssertStatus(PAUSE, PENDING, job);
+
+ //The paused job is pulled and remain in pause state. Other jobs from bulk remain pending
+ job = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS);
+ listServicesAndAssertStatus(PAUSE, PENDING, job);
+
+ //the job get IN_PROGRESS response (simulate activate operation) and status changed to IN_PROGRESS
+ when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))).
+ thenReturn(asyncRequestStatusResponseAsRestObject(IN_PROGRESS_STR));
+ job = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS);
+ listServicesAndAssertStatus(JobStatus.IN_PROGRESS, PENDING, job);
+
+ when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))).
+ thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR));
+ job = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, COMPLETED);
+ listServicesAndAssertStatus(COMPLETED, PENDING, job);
+
+ //Pulling PENDING job return another job
+ assertThat(jobsBrokerService.pull(PENDING, randomUuid()).get().getUuid(), not(equalTo(job.getUuid())));
+
+
+ ImmutableList<String> expectedStatusesForMso = ImmutableList.of(REQUESTED, PENDING_MANUAL_TASK, IN_PROGRESS_STR, COMPLETE_STR);
+ List<String> msoStatuses = asyncInstantiationBL.getAuditStatuses(firstJob.getUuid(), MSO).stream().map(x -> x.getJobStatus()).collect(Collectors.toList());
+ assertThat(msoStatuses, is(expectedStatusesForMso));
+
+ ImmutableList<String> expectedStatusesForVid = statusesToStrings(PENDING, IN_PROGRESS, PAUSE, IN_PROGRESS, COMPLETED);
+ List<String> vidStatuses = asyncInstantiationBL.getAuditStatuses(firstJob.getUuid(), VID).stream().map(x -> x.getJobStatus()).collect(Collectors.toList());
+ assertThat(vidStatuses, is(expectedStatusesForVid));
+ }
+
+ private Job pushBulkPullPendingJobAndAssertJobStatus(JobStatus pulledJobStatus, JobStatus otherJobsStatus) {
+ pushMacroBulk();
+ return pullPendingJobAndAssertJobStatus(pulledJobStatus, otherJobsStatus);
+ }
+
+ private Job pullPendingJobAndAssertJobStatus(JobStatus pulledJobStatus, JobStatus otherJobsStatus) {
+ Job job = pullJobProcessAndPushBack(PENDING, pulledJobStatus, false);
+ listServicesAndAssertStatus(pulledJobStatus, otherJobsStatus, job);
+ return job;
+ }
+
+ //@Test
+ public void test2BulksLifeCyclesAreIndependent() {
+ pushMacroBulk();
+ when(restMso.PostForObject(any(), any(), eq(RequestReferencesContainer.class))).thenReturn(createResponse(200));
+ //push 2nd job, then when pulling first job the job become in_progress, other jobs (from 2 bulks) remain pending
+ Job firstJob = pushBulkPullPendingJobAndAssertJobStatus(JobStatus.IN_PROGRESS, PENDING);
+
+ //assert we can pull another job from pending from other template id
+ Job secondJob = pullJobProcessAndPushBack(PENDING, JobStatus.IN_PROGRESS, false);
+ assertThat(firstJob.getTemplateId(), not(equalTo(secondJob.getTemplateId())));
+
+ //assert no more PENDING jobs to pull
+ assertFalse(jobsBrokerService.pull(PENDING, randomUuid()).isPresent());
+
+ //when get FAILED status from MSO statuses for failed bulk are: FAILED, STOPPED, for other bulk: IN_PROGRESS, 2 pending
+ when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))).
+ thenReturn(asyncRequestStatusResponseAsRestObject(FAILED_STR));
+ Job failedJob = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, JobStatus.FAILED, false);
+ Map<UUID, List<ServiceInfo>> servicesByTemplateId =
+ asyncInstantiationBL.getAllServicesInfo()
+ .stream().collect(groupingBy(ServiceInfo::getTemplateId));
+ assertServicesStatus(servicesByTemplateId.get(failedJob.getTemplateId()), JobStatus.FAILED, JobStatus.STOPPED, failedJob);
+ Job successJob = failedJob.getUuid().equals(firstJob.getUuid()) ? secondJob : firstJob;
+ assertServicesStatus(servicesByTemplateId.get(successJob.getTemplateId()), JobStatus.IN_PROGRESS, PENDING, successJob);
+
+ //yet no more PENDING jobs to pull
+ assertFalse(jobsBrokerService.pull(PENDING, randomUuid()).isPresent());
+
+ //assert that job from non failed bulk can progress.
+ //When completed, failed bulk statuses: FAILED, STOPPED. Succeeded bulk statuses are : COMPLETED, 2 pending
+ when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))).
+ thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR));
+ pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, COMPLETED, false);
+ servicesByTemplateId =
+ asyncInstantiationBL.getAllServicesInfo()
+ .stream().collect(groupingBy(ServiceInfo::getTemplateId));
+ assertServicesStatus(servicesByTemplateId.get(failedJob.getTemplateId()), JobStatus.FAILED, JobStatus.STOPPED, failedJob);
+ assertServicesStatus(servicesByTemplateId.get(successJob.getTemplateId()), COMPLETED, PENDING, successJob);
+
+ //advance other jobs of succeeded bulk till al of them reach to COMPLETED
+ pullJobProcessAndPushBack(PENDING, JobStatus.IN_PROGRESS, false);
+ pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, COMPLETED, false);
+ pullJobProcessAndPushBack(PENDING, JobStatus.IN_PROGRESS, false);
+ pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, COMPLETED, false);
+ servicesByTemplateId =
+ asyncInstantiationBL.getAllServicesInfo()
+ .stream().collect(groupingBy(ServiceInfo::getTemplateId));
+ assertServicesStatus(servicesByTemplateId.get(failedJob.getTemplateId()), JobStatus.FAILED, JobStatus.STOPPED, failedJob);
+ assertServicesStatus(servicesByTemplateId.get(successJob.getTemplateId()), COMPLETED, COMPLETED, successJob);
+
+ //assert no more PENDING jobs nor IN_PROGRESS jobs to pull
+ assertFalse(jobsBrokerService.pull(PENDING, randomUuid()).isPresent());
+ assertFalse(jobsBrokerService.pull(JobStatus.IN_PROGRESS, randomUuid()).isPresent());
+ }
+
+ public void deploy2NewGroupsToServiceWith1ExistingGroup() {
+
+ /*
+ new feature: skip service (existing impl) and skip group (new impl)
+ service+group aren't touched, 2 groups ARE created
+
+ [v] success if all GROUPs success
+
+ Next test variation should:
+ [ ] error if all GROUPs error
+ [ ] completed with error if 1 GROUP error
+
+
+ [v] + service with 3 groups - 1 action=none, 2 action=create; service's action=none
+ [v] verify STATUS pending
+ [v] + pull+execute (should NOT post to MSO)
+ [v] verify STATUS in progress; TYPE watching
+ ...
+ [v] verify job#2 *new* GROUP job STATUS completed with no action TYPE group INTERNAL STATE terminal PHASE delete
+ [v] verify job#3 *new* GROUP job STATUS completed with no action TYPE group INTERNAL STATE terminal PHASE delete
+ [v] verify job#4 *new* GROUP job STATUS completed with no action TYPE group INTERNAL STATE terminal PHASE delete
+
+ [v] + pull+execute job#1 (should NOT post to MSO)
+ [v] verify STATUS in progress; TYPE watching
+ [v] verify job#5 *new* GROUP job STATUS creating TYPE group INTERNAL STATE initial PHASE create
+ [v] verify job#6 *new* GROUP job STATUS creating TYPE group INTERNAL STATE initial PHASE create
+ [v] verify job#7 *new* GROUP job STATUS creating TYPE group INTERNAL STATE initial PHASE create
+
+ [v] + pull+execute job#5 (should NOT post to MSO)
+ [v] verify job#5 STATUS completed with no action TYPE group INTERNAL STATE terminal PHASE create
+ [v] + pull+execute job#1
+ [v] verify job#1 STATUS in progress; TYPE watching
+
+ [v] + pull+execute job#6 (should post to MSO)
+ [v] verify job#6 STATUS resource in progress
+ [v] + pull+execute job#1
+ [v] verify job#1 STATUS in progress; TYPE watching
+ [v] + pull+execute job#6 (should get from MSO)
+ [v] verify job#6 STATUS completed
+ [v] + pull+execute job#1
+ [v] verify job#1 STATUS in progress; TYPE watching
+
+ [v] + pull+execute job#7 (should post to MSO)
+ [v] verify job#7 STATUS resource in progress
+ [v] + pull+execute job#1
+ [v] verify job#1 STATUS in progress; TYPE watching
+ [v] + pull+execute job#7 (should get from MSO)
+ [v] verify job#7 STATUS completed
+ [v] + pull+execute job#1
+ [v] verify job#1 STATUS completed
+
+ */
+
+ final String GROUP1_REQUEST_ID = UUID.randomUUID().toString();
+ final String GROUP1_INSTANCE_ID = UUID.randomUUID().toString();
+ final String GROUP2_REQUEST_ID = UUID.randomUUID().toString();
+ final String GROUP2_INSTANCE_ID = UUID.randomUUID().toString();
+
+ // Utility method
+ final BiConsumer<Action, JobStatus> verify_Job1InProgress = (phase, nextJobStatus) -> {
+ pullJobProcessAndPushBackWithTypeAssertion(IN_PROGRESS, nextJobStatus, JobType.ALaCarteService, phase, InternalState.WATCHING, 2);
+ };
+
+ //service with 3 groups - 1 action=none, 2 action=create; service's action=none
+ UUID uuid = pushALaCarteUpdateWithGroups();
+ singleServicesAndAssertStatus(PENDING, uuid);
+
+ // take from pending, put in-progress -> 3 delete-child were born
+ pullJobProcessAndPushBackWithTypeAssertion(PENDING, IN_PROGRESS, JobType.ALaCarteService, Action.Delete, InternalState.WATCHING, 1);
+ verifyQueueSizes(ImmutableMap.of(
+ IN_PROGRESS, 1, CREATING, 3
+ ));
+
+ Stream.of(1, 2, 3).forEach(i -> {
+ // take each child creating, put in-progress
+ verify_Job1InProgress.accept(Action.Delete, IN_PROGRESS);
+ pullJobProcessAndPushBackWithTypeAssertion(CREATING, RESOURCE_IN_PROGRESS, JobType.InstanceGroup, Action.Delete, null, 1);
+
+ // execute each in-progress -> job is completed
+ verify_Job1InProgress.accept(Action.Delete, IN_PROGRESS);
+ pullJobProcessAndPushBackWithTypeAssertion(RESOURCE_IN_PROGRESS, COMPLETED/*_WITH_NO_ACTION*/, JobType.InstanceGroup,1);
+ });
+ verifyQueueSizes(ImmutableMap.of(
+ IN_PROGRESS, 1, COMPLETED, 3
+ ));
+
+ // take job #1 from phase delete to phase create -> 3 create-child were born
+ verify_Job1InProgress.accept(Action.Create, IN_PROGRESS);
+ verifyQueueSizes(ImmutableMap.of(
+ IN_PROGRESS, 1, CREATING, 3, COMPLETED, 3
+ ));
+
+ // prepare MSO mock
+ when(restMso.PostForObject(any(), endsWith("instanceGroups"), eq(RequestReferencesContainer.class)))
+ .thenReturn(createResponse(200, GROUP1_INSTANCE_ID, GROUP1_REQUEST_ID))
+ .thenReturn(createResponse(200, GROUP2_INSTANCE_ID, GROUP2_REQUEST_ID))
+ .thenReturn(null);
+ when(restMso.GetForObject(argThat(uri -> StringUtils.endsWithAny(uri, GROUP1_REQUEST_ID, GROUP2_REQUEST_ID)), eq(AsyncRequestStatus.class))).
+ thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR));
+
+ // take first "none" child from creating to completed
+ // note there's no concrete mechanism that makes the first child be
+ // the "action=None" case, but that's what happens, and following line
+ // relies on that fact.
+ pullJobProcessAndPushBackWithTypeAssertion(CREATING, COMPLETED_WITH_NO_ACTION, JobType.InstanceGroupInstantiation, 1);
+
+ // take each of next two children from creating to in-progress, then to completed
+ // verify job #1 is watching, and MSO is getting requests
+ Stream.of(1, 2).forEach(i -> {
+ verify_Job1InProgress.accept(Action.Create, IN_PROGRESS);
+ pullJobProcessAndPushBackWithTypeAssertion(CREATING, RESOURCE_IN_PROGRESS, JobType.ResourceInProgressStatus);
+ verify(restMso, times(i)).PostForObject(any(), any(), any());
+
+ verify_Job1InProgress.accept(Action.Create, IN_PROGRESS);
+ pullJobProcessAndPushBackWithTypeAssertion(RESOURCE_IN_PROGRESS, COMPLETED, JobType.ResourceInProgressStatus);
+ verify(restMso, times(i)).GetForObject(any(), any());
+ });
+
+ // job #1 is done as all children are done
+ verify_Job1InProgress.accept(Action.Create, COMPLETED);
+ verifyQueueSizes(ImmutableMap.of(COMPLETED, 7));
+ }
+
+ private void verifyQueueSizes(ImmutableMap<JobStatus, Integer> expected) {
+ final Collection<Job> peek = jobsBrokerService.peek();
+ final Map<JobStatus, Long> jobTypes = peek.stream().collect(groupingBy(Job::getStatus, counting()));
+ assertThat(jobTypes, is(expected));
+ }
+
+ private List<ServiceInfo> listServicesAndAssertStatus(JobStatus pulledJobStatus, JobStatus otherJobsStatus, Job job) {
+ List<ServiceInfo> serviceInfoList = asyncInstantiationBL.getAllServicesInfo();
+ assertServicesStatus(serviceInfoList, pulledJobStatus, otherJobsStatus, job);
+
+ return serviceInfoList;
+ }
+
+ private ServiceInfo singleServicesAndAssertStatus(JobStatus expectedStatus, UUID jobUUID) {
+ List<ServiceInfo> serviceInfoList = asyncInstantiationBL.getAllServicesInfo();
+ assertEquals(1, serviceInfoList.size());
+ ServiceInfo serviceInfo = serviceInfoList.get(0);
+ assertThat(serviceInfo.getJobStatus(), is(expectedStatus));
+ assertThat(serviceInfo.getJobId(), is(jobUUID));
+ return serviceInfo;
+ }
+
+ private void assertServicesStatus(List<ServiceInfo> serviceInfoList, JobStatus pulledJobStatus, JobStatus otherJobsStatus, Job job) {
+ serviceInfoList.forEach(si->{
+ if (si.getJobId().equals(job.getUuid())) {
+ assertThat(si.getJobStatus(), is(pulledJobStatus));
+ }
+ else {
+ assertThat(si.getJobStatus(), is(otherJobsStatus));
+ }
+ });
+ }
+
+ private void listServicesAndAssertStatus(Map<UUID, JobStatus> expectedJobStatusMap) {
+ Map<UUID, JobStatus> actualStatuses = asyncInstantiationBL.getAllServicesInfo()
+ .stream().collect(Collectors.toMap(ServiceInfo::getJobId, ServiceInfo::getJobStatus));
+ assertThat(actualStatuses.entrySet(), equalTo(expectedJobStatusMap.entrySet()));
+ }
+
+ private String randomUuid() {
+ return UUID.randomUUID().toString();
+ }
+}
diff --git a/vid-app-common/src/test/java/org/onap/vid/job/impl/JobAdapterImplTest.java b/vid-app-common/src/test/java/org/onap/vid/job/impl/JobAdapterImplTest.java
deleted file mode 100644
index dc2eafc9b..000000000
--- a/vid-app-common/src/test/java/org/onap/vid/job/impl/JobAdapterImplTest.java
+++ /dev/null
@@ -1,110 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * VID
- * ================================================================================
- * Copyright (C) 2018 Nokia Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.vid.job.impl;
-
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-import org.mockito.Mock;
-import org.onap.vid.job.Job;
-import org.onap.vid.job.JobAdapter;
-import org.onap.vid.job.JobType;
-import org.onap.vid.model.JobBulk;
-import org.onap.vid.model.JobModel;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import java.util.List;
-import java.util.UUID;
-import java.util.stream.Stream;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.mockito.Mockito.when;
-import static org.mockito.MockitoAnnotations.initMocks;
-
-public class JobAdapterImplTest {
-
-
- private static final int SAMPLE_INDEX = 10;
- private static final String SAMPLE_USER_ID = "sampleUserId";
-
- @Mock
- private Job job;
-
- @Mock
- private JobAdapter.AsyncJobRequest asyncJobRequest;
-
- private UUID sampleUuid=UUID.randomUUID();
-
- private JobAdapterImpl jobAdapter = new JobAdapterImpl();
-
- @BeforeMethod
- public void setUp() {
- initMocks(this);
-
- when(job.getUuid()).thenReturn(sampleUuid);
- when(job.getStatus()).thenReturn(Job.JobStatus.IN_PROGRESS);
- when(job.getTemplateId()).thenReturn(sampleUuid);
- }
-
- @Test
- public void shouldConvertJobToJobModel() {
-
-
- JobModel convertedJob = jobAdapter.toModel(job);
-
- assertThat(convertedJob.getUuid()).isEqualByComparingTo(sampleUuid);
- assertThat(convertedJob.getStatus()).isEqualByComparingTo(Job.JobStatus.IN_PROGRESS);
- assertThat(convertedJob.getTemplateId()).isEqualByComparingTo(sampleUuid);
- }
-
-
- @Test
- public void shouldProperlyCreateJob() {
- UUID uuid = UUID.randomUUID();
-
- Job createdJob = jobAdapter.createJob(JobType.ServiceInstantiation, asyncJobRequest, uuid, SAMPLE_USER_ID, SAMPLE_INDEX);
-
- assertThat(createdJob.getStatus()).isEqualByComparingTo(Job.JobStatus.PENDING);
- assertThat(createdJob.getTemplateId()).isEqualByComparingTo(uuid);
- assertThat(createdJob.getType()).isEqualByComparingTo(JobType.ServiceInstantiation);
- assertThat(createdJob.getData()).isEqualTo(ImmutableMap.of("request", asyncJobRequest, "userId", SAMPLE_USER_ID));
- }
-
- @Test
- public void shouldProperlyCreateBulkOfJobs(){
- List<Job> bulkOfJobs = jobAdapter.createBulkOfJobs(ImmutableMap.of("count", 5, "type", JobType.InProgressStatus.name()));
-
-
- assertThat(bulkOfJobs).hasSize(5);
-
- Stream<Job> jobStream = bulkOfJobs.stream().filter(x -> JobType.InProgressStatus.equals(x.getType()) && Job.JobStatus.PENDING.equals(x.getStatus()));
-
- assertThat(jobStream).hasSize(5);
- }
-
-
- @Test
- public void shouldConvertListToBulkJob(){
- JobBulk jobBulk = jobAdapter.toModelBulk(ImmutableList.of(job, job));
-
- assertThat(jobBulk.getJobs()).hasSize(2);
- }
-}
diff --git a/vid-app-common/src/test/java/org/onap/vid/job/impl/JobAdapterTest.java b/vid-app-common/src/test/java/org/onap/vid/job/impl/JobAdapterTest.java
new file mode 100644
index 000000000..95228476b
--- /dev/null
+++ b/vid-app-common/src/test/java/org/onap/vid/job/impl/JobAdapterTest.java
@@ -0,0 +1,100 @@
+package org.onap.vid.job.impl;
+
+import com.google.common.collect.ImmutableMap;
+import org.apache.commons.lang3.RandomUtils;
+import org.onap.vid.job.Job;
+import org.onap.vid.job.JobAdapter;
+import org.onap.vid.job.JobType;
+import org.onap.vid.job.command.JobCommandFactoryTest;
+import org.testng.annotations.Test;
+
+import java.util.UUID;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNotEquals;
+import static org.testng.AssertJUnit.assertNotNull;
+
+public class JobAdapterTest {
+
+ @Test
+ public void testCreateServiceInstantiationJob() {
+ JobAdapter jobAdapter = new JobAdapterImpl();
+
+ JobType jobType = JobType.NoOp;
+ JobAdapter.AsyncJobRequest request = new JobCommandFactoryTest.MockedRequest(42,"nothing");
+ UUID templateId = UUID.randomUUID();
+ String userId = "ou012t";
+ String optimisticUniqueServiceInstanceName = "optimisticUniqueServiceInstanceName";
+ int indexInBulk = RandomUtils.nextInt();
+ Job job = jobAdapter.createServiceInstantiationJob(
+ jobType,
+ request,
+ templateId,
+ userId,
+ optimisticUniqueServiceInstanceName,
+ indexInBulk
+ );
+
+ assertEquals(job.getType(), jobType);
+ assertEquals(job.getSharedData().getRequest(), request);
+ assertEquals(job.getSharedData().getRequestType(), request.getClass());
+ assertEquals(job.getSharedData().getUserId(), userId);
+ assertEquals(job.getSharedData().getJobUuid(), job.getUuid());
+ assertEquals(job.getSharedData().getRootJobId(), job.getUuid());
+ assertNotNull(job.getUuid());
+ assertEquals(job.getTemplateId(), templateId);
+ assertEquals(job.getData().get("optimisticUniqueServiceInstanceName"), optimisticUniqueServiceInstanceName);
+ assertEquals((int)job.getIndexInBulk(), indexInBulk );
+ assertEquals(job.getStatus(), Job.JobStatus.PENDING);
+ }
+
+ @Test
+ public void testCreateChildJob() {
+
+ JobAdapter jobAdapter = new JobAdapterImpl();
+
+ UUID templateId = UUID.randomUUID();
+ String userId = "ou012t";
+ String optimisticUniqueServiceInstanceName = "optimisticUniqueServiceInstanceName";
+ int indexInBulk = RandomUtils.nextInt();
+ Job grandJob = jobAdapter.createServiceInstantiationJob(
+ JobType.HttpCall,
+ new JobCommandFactoryTest.MockedRequest(99, "anything"),
+ templateId,
+ userId,
+ optimisticUniqueServiceInstanceName,
+ indexInBulk
+ );
+
+ Job.JobStatus jobStatus = Job.JobStatus.PAUSE;
+ JobType jobType = JobType.NoOp;
+ JobAdapter.AsyncJobRequest request = new JobCommandFactoryTest.MockedRequest(42,"nothing");
+ Job parentJob = jobAdapter.createChildJob(jobType, jobStatus, request, grandJob.getSharedData(), ImmutableMap.of());
+
+ assertEquals(parentJob.getType(), jobType);
+ assertEquals(parentJob.getSharedData().getRequest(), request);
+ assertEquals(parentJob.getSharedData().getRequestType(), request.getClass());
+ assertEquals(parentJob.getSharedData().getUserId(), userId);
+ assertEquals(parentJob.getSharedData().getJobUuid(), parentJob.getUuid());
+ assertNotNull(parentJob.getUuid());
+ assertNotEquals(parentJob.getUuid(), grandJob.getUuid());
+ assertEquals(parentJob.getStatus(), jobStatus);
+ assertEquals(parentJob.getSharedData().getRootJobId(), grandJob.getUuid());
+
+ Job.JobStatus jobStatus2 = Job.JobStatus.IN_PROGRESS;
+ JobType jobType2 = JobType.AggregateState;
+ JobAdapter.AsyncJobRequest request2 = new JobCommandFactoryTest.MockedRequest(66,"abc");
+ Job job = jobAdapter.createChildJob(jobType2, jobStatus2, request2, parentJob.getSharedData(), ImmutableMap.of());
+
+ assertEquals(job.getType(), jobType2);
+ assertEquals(job.getSharedData().getRequest(), request2);
+ assertEquals(job.getSharedData().getRequestType(), request2.getClass());
+ assertEquals(job.getSharedData().getUserId(), userId);
+ assertEquals(job.getSharedData().getJobUuid(), job.getUuid());
+ assertNotNull(job.getUuid());
+ assertNotEquals(job.getUuid(), parentJob.getUuid());
+ assertEquals(job.getStatus(), jobStatus2);
+ assertEquals(job.getSharedData().getRootJobId(), grandJob.getUuid());
+
+ }
+}
diff --git a/vid-app-common/src/test/java/org/onap/vid/job/impl/JobSchedulerInitializerTest.java b/vid-app-common/src/test/java/org/onap/vid/job/impl/JobSchedulerInitializerTest.java
deleted file mode 100644
index 93afd1709..000000000
--- a/vid-app-common/src/test/java/org/onap/vid/job/impl/JobSchedulerInitializerTest.java
+++ /dev/null
@@ -1,121 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * VID
- * ================================================================================
- * Copyright (C) 2018 Nokia Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.vid.job.impl;
-
-
-import org.mockito.ArgumentCaptor;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.onap.vid.job.JobsBrokerService;
-import org.onap.vid.job.command.JobCommandFactory;
-import org.onap.vid.properties.Features;
-import org.quartz.JobDetail;
-import org.quartz.Scheduler;
-import org.quartz.SchedulerException;
-import org.quartz.Trigger;
-import org.springframework.scheduling.quartz.SchedulerFactoryBean;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-import org.togglz.core.manager.FeatureManager;
-
-import java.util.List;
-import java.util.stream.Collectors;
-
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.verifyZeroInteractions;
-import static org.mockito.Mockito.when;
-import static org.mockito.MockitoAnnotations.initMocks;
-
-public class JobSchedulerInitializerTest {
-
- @Mock
- private JobsBrokerService brokerService;
-
- @Mock
- private SchedulerFactoryBean schedulerFactoryBean;
-
- @Mock
- private FeatureManager featureManager;
-
- @Mock
- private JobCommandFactory commandFactory;
-
- @Mock
- private Scheduler scheduler;
-
- @InjectMocks
- private JobSchedulerInitializer jobSchedulerInitializer;
-
- @BeforeMethod
- public void setUp() {
- initMocks(this);
- }
-
-
- @Test
- public void shouldNotInitializeSchedulerWhenAsyncJobsAreDisabled() {
- when(featureManager.isActive(Features.FLAG_ASYNC_JOBS)).thenReturn(false);
-
- jobSchedulerInitializer.init();
-
- verifyZeroInteractions(schedulerFactoryBean);
- }
-
-
- @Test
- public void shouldInitializeSchedulerWhenAsyncJobsAreEnabled() throws SchedulerException {
- ArgumentCaptor<JobDetail> jobDetailArgumentCaptor = ArgumentCaptor.forClass(JobDetail.class);
- ArgumentCaptor<Trigger> triggerArgumentCaptor = ArgumentCaptor.forClass(Trigger.class);
- when(featureManager.isActive(Features.FLAG_ASYNC_JOBS)).thenReturn(true);
- when(schedulerFactoryBean.getScheduler()).thenReturn(scheduler);
-
- jobSchedulerInitializer.init();
-
- verify(scheduler, times(2)).scheduleJob(jobDetailArgumentCaptor.capture(), triggerArgumentCaptor.capture());
-
- List<Object> topics = extractTopics(jobDetailArgumentCaptor);
-
- List<String> descriptions = extractDescription(triggerArgumentCaptor);
-
- assertThat(topics, containsInAnyOrder(org.onap.vid.job.Job.JobStatus.IN_PROGRESS, org.onap.vid.job.Job.JobStatus.PENDING));
- assertThat(descriptions, containsInAnyOrder("Trigger to run async worker for PENDING", "Trigger to run async worker for IN_PROGRESS"));
- }
-
- private List<Object> extractTopics(ArgumentCaptor<JobDetail> jobDetailArgumentCaptor) {
- return jobDetailArgumentCaptor
- .getAllValues()
- .stream()
- .map(JobDetail::getJobDataMap)
- .map(x -> x.get("topic"))
- .collect(Collectors.toList());
- }
-
- private List<String> extractDescription(ArgumentCaptor<Trigger> triggerArgumentCaptor) {
- return triggerArgumentCaptor
- .getAllValues()
- .stream()
- .map(Trigger::getDescription)
- .collect(Collectors.toList());
- }
-} \ No newline at end of file
diff --git a/vid-app-common/src/test/java/org/onap/vid/job/impl/JobWorkerTest.java b/vid-app-common/src/test/java/org/onap/vid/job/impl/JobWorkerTest.java
index e58b6ba03..3ff324d61 100644
--- a/vid-app-common/src/test/java/org/onap/vid/job/impl/JobWorkerTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/job/impl/JobWorkerTest.java
@@ -19,7 +19,7 @@ import java.util.UUID;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
-import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -47,12 +47,13 @@ public class JobWorkerTest {
public final String foobar = "aux";
};
- originalType = JobType.ServiceInstantiation;
- jobUnderTest = new JobAdapterImpl().createJob(
+ originalType = JobType.MacroServiceInstantiation;
+ jobUnderTest = new JobAdapterImpl().createServiceInstantiationJob(
originalType,
originalData,
UUID.randomUUID(),
"my user id",
+ "optimisticUniqueServiceInstanceName",
RandomUtils.nextInt()
);
}
@@ -62,7 +63,7 @@ public class JobWorkerTest {
assertNextJobAfterExecuteJob(null, new String[]{"status"}, allOf(
hasProperty("status", is(Job.JobStatus.STOPPED)),
- hasProperty("data", hasEntry("request", originalData)),
+ hasProperty("sharedData", hasProperty("request", is(originalData))),
hasProperty("type", is(originalType)))
);
}
diff --git a/vid-app-common/src/test/java/org/onap/vid/model/JobAuditStatusTest.java b/vid-app-common/src/test/java/org/onap/vid/model/JobAuditStatusTest.java
new file mode 100644
index 000000000..26db161d0
--- /dev/null
+++ b/vid-app-common/src/test/java/org/onap/vid/model/JobAuditStatusTest.java
@@ -0,0 +1,40 @@
+package org.onap.vid.model;
+
+import org.apache.commons.lang3.StringUtils;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+import java.util.Date;
+import java.util.UUID;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+public class JobAuditStatusTest {
+
+ @DataProvider
+ public static Object[][] AdditionalInfoSizes() {
+ return new Object[][]{
+ {5, 5},
+ {1999,1999},
+ {2000, 2000},
+ {2001, 2000},
+ {10000, 2000}
+ };
+ }
+
+ @Test(dataProvider = "AdditionalInfoSizes")
+ public void testAdditionalInfoMaxLength(int originalSize, int finalSize) {
+ JobAuditStatus jobAuditStatus = new JobAuditStatus();
+ jobAuditStatus.setAdditionalInfo(StringUtils.repeat("a", originalSize));
+ assertThat(jobAuditStatus.getAdditionalInfo().length(), is(finalSize));
+ }
+
+ @Test(dataProvider = "AdditionalInfoSizes")
+ public void testAdditionalInfoMaxLengthInConstructor(int originalSize, int finalSize) {
+ final String additionalInfo = StringUtils.repeat("a", originalSize);
+ JobAuditStatus jobAuditStatus = new JobAuditStatus(UUID.randomUUID(), "myJobStatus", JobAuditStatus.SourceStatus.MSO, UUID.randomUUID(), additionalInfo, new Date());
+ assertThat(jobAuditStatus.getAdditionalInfo().length(), is(finalSize));
+ }
+
+}
diff --git a/vid-app-common/src/test/java/org/onap/vid/model/RequestReferencesContainerTest.java b/vid-app-common/src/test/java/org/onap/vid/model/RequestReferencesContainerTest.java
index 4587f4e52..38bec90af 100644
--- a/vid-app-common/src/test/java/org/onap/vid/model/RequestReferencesContainerTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/model/RequestReferencesContainerTest.java
@@ -1,9 +1,9 @@
package org.onap.vid.model;
-import java.util.Map;
-
import org.junit.Test;
-import org.onap.vid.domain.mso.RequestReferences;
+import org.onap.vid.mso.model.RequestReferences;
+
+import java.util.Map;
public class RequestReferencesContainerTest {
diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/MsoBusinessLogicImplTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/MsoBusinessLogicImplTest.java
index 718e22fb4..8a821c27a 100644
--- a/vid-app-common/src/test/java/org/onap/vid/mso/MsoBusinessLogicImplTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/mso/MsoBusinessLogicImplTest.java
@@ -22,6 +22,7 @@ package org.onap.vid.mso;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.commons.io.IOUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -41,7 +42,6 @@ import org.togglz.core.manager.FeatureManager;
import java.io.IOException;
import java.net.URL;
-import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
@@ -206,7 +206,7 @@ public class MsoBusinessLogicImplTest {
String vnfEndpoint = String.format(endpointTemplate, serviceInstanceId, vnfInstanceId);
org.onap.vid.changeManagement.RequestDetails requestDetails = readRequest(
"scaleOutVfModulePayload.json");
- org.onap.vid.changeManagement.RequestDetailsWrapper expectedRequest = readExpectedRequest(
+ org.onap.vid.changeManagement.RequestDetailsWrapper<org.onap.vid.changeManagement.RequestDetails> expectedRequest = readExpectedRequest(
"scaleOutVfModulePayloadToMso.json");
MsoResponseWrapper expectedMsoResponseWrapper = createOkResponse();
given(
@@ -229,7 +229,7 @@ public class MsoBusinessLogicImplTest {
return objectMapper.readValue(url, org.onap.vid.changeManagement.RequestDetails.class);
}
- private org.onap.vid.changeManagement.RequestDetailsWrapper readExpectedRequest(String requestJsonFilename)
+ private org.onap.vid.changeManagement.RequestDetailsWrapper<org.onap.vid.changeManagement.RequestDetails> readExpectedRequest(String requestJsonFilename)
throws IOException {
Path path = Paths.get("payload_jsons", requestJsonFilename);
URL url = this.getClass().getClassLoader().getResource(path.toString());
@@ -252,15 +252,15 @@ public class MsoBusinessLogicImplTest {
}
@Test
- public void shouldFilterOutOrchestrationRequestsNotAllowedInDashboard() throws IOException {
+ public void shouldFilterOutOrchestrationRequestsNotAllowedInDashboard() throws Exception {
//given
String vnfModelTypeOrchestrationRequests = getFileContentAsString("mso_model_info_sample_response.json");
String scaleOutActionOrchestrationRequests = getFileContentAsString("mso_action_scaleout_sample_response.json");
MsoResponseWrapper msoResponseWrapperMock = mock(MsoResponseWrapper.class);
given(msoInterface
- .getOrchestrationRequestsForDashboard(any(String.class), any(String.class), any(String.class),
- any(RestObject.class)))
+ .getOrchestrationRequest(any(String.class), any(String.class), any(String.class),
+ any(RestObject.class), anyBoolean()))
.willReturn(msoResponseWrapperMock);
given(msoResponseWrapperMock.getEntity())
.willReturn(vnfModelTypeOrchestrationRequests, scaleOutActionOrchestrationRequests);
@@ -276,14 +276,14 @@ public class MsoBusinessLogicImplTest {
.map(el -> el.getRequestType().toUpperCase())
.collect(Collectors.toList()));
assertThat(filteredOrchestrationReqs)
- .extracting(org.onap.vid.domain.mso.Request::getRequestScope)
+ .extracting(Request::getRequestScope)
.containsOnly("vnf", "vfModule");
}
- private String getFileContentAsString(String resourceName) throws IOException {
- URL url = this.getClass().getClassLoader().getResource(".");
- Path path = Paths.get(url.getPath(), "payload_jsons", resourceName);
- return new String(Files.readAllBytes(path));
+ private String getFileContentAsString(String resourceName) throws Exception {
+ Path path = Paths.get("payload_jsons", resourceName);
+ URL url = this.getClass().getClassLoader().getResource(path.toString());
+ return IOUtils.toString(url.toURI(), "UTF-8");
}
private static class MsoRequestWrapperMatcher implements
diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/MsoOperationalEnvironmentTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/MsoOperationalEnvironmentTest.java
index 5c5d6fd41..b396507b8 100644
--- a/vid-app-common/src/test/java/org/onap/vid/mso/MsoOperationalEnvironmentTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/mso/MsoOperationalEnvironmentTest.java
@@ -6,11 +6,11 @@ import com.fasterxml.jackson.databind.SerializationFeature;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import org.apache.commons.io.IOUtils;
+import org.apache.log4j.LogManager;
+import org.apache.log4j.Logger;
import org.onap.vid.changeManagement.RequestDetailsWrapper;
-import org.onap.vid.controllers.OperationalEnvironmentController;
-import org.onap.vid.controllers.OperationalEnvironmentController.OperationalEnvironmentManifest;
-import org.onap.vid.mso.MsoBusinessLogic;
-import org.onap.vid.mso.MsoBusinessLogicImpl;
+import org.onap.vid.controller.OperationalEnvironmentController;
+import org.onap.vid.controller.OperationalEnvironmentController.OperationalEnvironmentManifest;
import org.onap.vid.mso.model.OperationalEnvironmentActivateInfo;
import org.onap.vid.mso.model.OperationalEnvironmentDeactivateInfo;
import org.onap.vid.mso.rest.OperationalEnvironment.OperationEnvironmentRequestDetails;
@@ -28,10 +28,10 @@ import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
-@Test
public class MsoOperationalEnvironmentTest {
private MsoBusinessLogic msoBusinessLogic = new MsoBusinessLogicImpl(null,null);
+ private static final Logger logger = LogManager.getLogger(MsoOperationalEnvironmentTest.class);
@Test(dataProvider = "getOperationalEnvironmentActivationPermutations")
public void testJsonResultOfOperationalEnvironmentActivationRequestDetails(HashMap<String, String> permutation) throws IOException {
@@ -170,8 +170,8 @@ public class MsoOperationalEnvironmentTest {
try {
JSONAssert.assertEquals("built mso request is not ok", expected, requestDetailsAsString, JSONCompareMode.STRICT);
} catch (AssertionError | Exception e) {
- System.out.println("requestDetailsAsString: \n" + requestDetailsAsString);
- System.out.println("expected: \n" + expected);
+ logger.info("requestDetailsAsString: \n" + requestDetailsAsString);
+ logger.info("expected: \n" + expected);
throw e;
}
}
diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/RequestDetailsTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/RequestDetailsTest.java
new file mode 100644
index 000000000..9d773d73c
--- /dev/null
+++ b/vid-app-common/src/test/java/org/onap/vid/mso/RequestDetailsTest.java
@@ -0,0 +1,63 @@
+package org.onap.vid.mso;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import org.onap.vid.exceptions.NotFoundException;
+import org.onap.vid.mso.rest.RequestDetails;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+import static org.testng.AssertJUnit.assertEquals;
+
+public class RequestDetailsTest {
+
+ private static final ImmutableList<String> LCP_CLOUD_REGION_ID_PATH = ImmutableList.of("requestDetails", "cloudConfiguration", "lcpCloudRegionId");
+
+ @DataProvider
+ public static Object[][] extractValueByPathDataProvider() {
+
+ RequestDetails requestDetails1 = new RequestDetails();
+ Map cloudConfiguration = ImmutableMap.of("lcpCloudRegionId", "lcp1");
+ requestDetails1.setAdditionalProperty("requestDetails",
+ ImmutableMap.of("cloudConfiguration", cloudConfiguration));
+
+
+ return new Object[][] {
+ { requestDetails1, LCP_CLOUD_REGION_ID_PATH, String.class, "lcp1" },
+ { requestDetails1, ImmutableList.of("requestDetails", "cloudConfiguration"), Map.class, cloudConfiguration },
+
+ };
+ }
+
+ @Test(dataProvider = "extractValueByPathDataProvider")
+ public void testExtractValueByPath(RequestDetails requestDetails, List<String> keys, Class clz, Object expectedValue) {
+ assertEquals(expectedValue, requestDetails.extractValueByPathUsingAdditionalProperties(keys, clz));
+ }
+
+ @DataProvider
+ public static Object[][] extractValueByPathDataProviderThrowException() {
+ RequestDetails requestDetails1 = new RequestDetails();
+ requestDetails1.setAdditionalProperty("requestDetails",
+ ImmutableMap.of("cloudConfiguration", "notMap"));
+
+ RequestDetails requestDetails2 = new RequestDetails();
+ requestDetails2.setAdditionalProperty("requestDetails",
+ ImmutableMap.of("cloudConfiguration", Collections.EMPTY_MAP));
+
+ return new Object[][] {
+ { new RequestDetails(), LCP_CLOUD_REGION_ID_PATH, String.class},
+ { requestDetails1, LCP_CLOUD_REGION_ID_PATH, String.class},
+ { requestDetails1, ImmutableList.of("requestDetails", "abc"), String.class},
+ { requestDetails2, LCP_CLOUD_REGION_ID_PATH, String.class},
+ };
+ }
+
+ @Test(dataProvider = "extractValueByPathDataProviderThrowException", expectedExceptions = NotFoundException.class)
+ public void testExtractValueByPathThrowException(RequestDetails requestDetails, List<String> keys, Class clz) {
+ requestDetails.extractValueByPathUsingAdditionalProperties(keys, clz);
+ }
+}
diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/RestMsoImplementationTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/RestMsoImplementationTest.java
deleted file mode 100644
index 3bcc01d63..000000000
--- a/vid-app-common/src/test/java/org/onap/vid/mso/RestMsoImplementationTest.java
+++ /dev/null
@@ -1,108 +0,0 @@
-package org.onap.vid.mso;
-
-import static org.junit.Assert.*;
-import org.junit.Test;
-import org.onap.vid.changeManagement.RequestDetailsWrapper;
-
-import java.util.*;
-
-import javax.ws.rs.core.MultivaluedHashMap;
-
-import org.junit.Assert;
-
-public class RestMsoImplementationTest {
-
- private RestMsoImplementation createTestSubject() {
- return new RestMsoImplementation();
- }
-
- @Test
- public void testInitMsoClient() throws Exception {
- RestMsoImplementation testSubject;
- MultivaluedHashMap<String, Object> result;
-
- // default test
- try {
- testSubject = createTestSubject();
- result = testSubject.initMsoClient();
- } catch (Exception e) {
- }
- }
-
-
- @Test
- public void testGetForObject() throws Exception {
- RestMsoImplementation testSubject;
- String sourceID = "";
- String path = "";
-
- // default test
- try {
- testSubject = createTestSubject();
- testSubject.GetForObject(sourceID, path, null);
- } catch (Exception e) {
- }
- }
-
- @Test
- public void testDelete() throws Exception {
- RestMsoImplementation testSubject;
- String sourceID = "";
- String path = "";
-
- // default test
- try {
- testSubject = createTestSubject();
- testSubject.Delete(null, null, sourceID, path, null);
- } catch (Exception e) {
- }
- }
-
- @Test
- public void testPostForObject() throws Exception {
- RestMsoImplementation testSubject;
- Object requestDetails = null;
- String sourceID = "";
- String path = "";
-
- // default test
- try {
- testSubject = createTestSubject();
- testSubject.PostForObject(requestDetails, sourceID, path, null);
- } catch (
-
- Exception e) {
- }
- }
-
-
-
- @Test
- public void testPrepareClient() throws Exception {
- RestMsoImplementation testSubject;
- String path = "";
- String methodName = "";
-
- // default test
- try {
- testSubject = createTestSubject();
- testSubject.prepareClient(path, methodName);
- } catch (
-
- Exception e) {
- }
- }
-
-
-
-
- // @Test
- // public void testInitMsoClient() throws Exception {
- // RestMsoImplementation testSubject;
- //
- // // default test
- // testSubject = createTestSubject();
- // testSubject.initMsoClient();
- // }
-
-} \ No newline at end of file
diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/model/OperationalEnvironmentActivateInfoTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/model/OperationalEnvironmentActivateInfoTest.java
index 9e00a7810..cac6d089e 100644
--- a/vid-app-common/src/test/java/org/onap/vid/mso/model/OperationalEnvironmentActivateInfoTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/mso/model/OperationalEnvironmentActivateInfoTest.java
@@ -1,9 +1,9 @@
package org.onap.vid.mso.model;
import org.junit.Test;
-import org.onap.vid.controllers.OperationalEnvironmentController;
-import org.onap.vid.controllers.OperationalEnvironmentController.OperationalEnvironmentActivateBody;
-import org.onap.vid.controllers.OperationalEnvironmentController.OperationalEnvironmentManifest;
+import org.onap.vid.controller.OperationalEnvironmentController;
+import org.onap.vid.controller.OperationalEnvironmentController.OperationalEnvironmentActivateBody;
+import org.onap.vid.controller.OperationalEnvironmentController.OperationalEnvironmentManifest;
public class OperationalEnvironmentActivateInfoTest {
diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/rest/AsyncRequestStatusTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/rest/AsyncRequestStatusTest.java
index 400a34e9b..c855be750 100644
--- a/vid-app-common/src/test/java/org/onap/vid/mso/rest/AsyncRequestStatusTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/mso/rest/AsyncRequestStatusTest.java
@@ -1,8 +1,6 @@
package org.onap.vid.mso.rest;
import org.junit.Test;
-import org.onap.vid.domain.mso.InstanceIds;
-import org.onap.vid.domain.mso.RequestStatus;
public class AsyncRequestStatusTest {
diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientNewTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientNewTest.java
index bfc82ce2a..73a3964dd 100644
--- a/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientNewTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientNewTest.java
@@ -20,6 +20,7 @@
*/
package org.onap.vid.mso.rest;
+import com.fasterxml.jackson.databind.ObjectMapper;
import com.xebialabs.restito.server.StubServer;
import org.glassfish.grizzly.http.util.HttpStatus;
import org.junit.AfterClass;
@@ -28,8 +29,8 @@ import org.junit.Ignore;
import org.junit.Test;
import org.onap.portalsdk.core.util.SystemProperties;
import org.onap.vid.client.SyncRestClient;
-import org.onap.vid.controllers.MsoController;
-import org.onap.vid.mso.MsoInterface;
+import org.onap.vid.controller.MsoController;
+import org.onap.vid.controller.WebConfig;
import org.onap.vid.mso.MsoProperties;
import org.onap.vid.mso.MsoResponseWrapper;
import org.onap.vid.mso.MsoResponseWrapperInterface;
@@ -44,8 +45,8 @@ import java.nio.file.Paths;
import java.util.Properties;
import java.util.UUID;
-import static org.onap.vid.controllers.MsoController.SVC_INSTANCE_ID;
-import static org.onap.vid.controllers.MsoController.VNF_INSTANCE_ID;
+import static org.onap.vid.controller.MsoController.SVC_INSTANCE_ID;
+import static org.onap.vid.controller.MsoController.VNF_INSTANCE_ID;
@ContextConfiguration(classes = {SystemProperties.class})
public class MsoRestClientNewTest {
@@ -304,7 +305,7 @@ public class MsoRestClientNewTest {
// default test
try {
testSubject = createTestSubject();
- result = testSubject.getOrchestrationRequestsForDashboard(t, sourceId, endpoint, restObject);
+ result = testSubject.getOrchestrationRequest(t, sourceId, endpoint, restObject, true);
} catch (Exception e) {
}
}
@@ -466,7 +467,8 @@ public class MsoRestClientNewTest {
}
private MsoRestClientNew msoRestClient() {
- return new MsoRestClientNew(new SyncRestClient(MsoInterface.objectMapper()), baseUrl());
+ final WebConfig webConfig = new WebConfig();
+ return new MsoRestClientNew(new SyncRestClient(webConfig.unirestFasterxmlObjectMapper(new ObjectMapper())), baseUrl());
}
private MsoRestClientNew createTestSubject() {
diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientTest.java
index 2b067b287..3d1937774 100644
--- a/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientTest.java
@@ -23,21 +23,19 @@ package org.onap.vid.mso.rest;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.json.JSONObject;
import org.junit.Assert;
+import org.onap.portalsdk.core.util.SystemProperties;
import org.onap.vid.changeManagement.RequestDetails;
import org.onap.vid.client.SyncRestClient;
-import org.onap.vid.domain.mso.CloudConfiguration;
-import org.onap.vid.domain.mso.ModelInfo;
-import org.onap.vid.domain.mso.RequestInfo;
-import org.onap.vid.domain.mso.RequestParameters;
+import org.onap.vid.controller.LocalWebConfig;
import org.onap.vid.mso.MsoBusinessLogic;
import org.onap.vid.mso.MsoBusinessLogicImpl;
-import org.onap.vid.mso.rest.MsoRestClientNew;
-import org.onap.vid.controllers.LocalWebConfig;
-import org.onap.portalsdk.core.util.SystemProperties;
+import org.onap.vid.mso.model.CloudConfiguration;
+import org.onap.vid.mso.model.ModelInfo;
+import org.onap.vid.mso.model.RequestInfo;
+import org.onap.vid.mso.model.RequestParameters;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.web.WebAppConfiguration;
import org.testng.annotations.Test;
-import org.togglz.core.manager.FeatureManager;
@ContextConfiguration(classes = {LocalWebConfig.class, SystemProperties.class})
diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/rest/OutgoingRequestIdTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/rest/OutgoingRequestHeadersTest.java
index 197bfe75d..e09ca807b 100644
--- a/vid-app-common/src/test/java/org/onap/vid/mso/rest/OutgoingRequestIdTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/mso/rest/OutgoingRequestHeadersTest.java
@@ -4,11 +4,11 @@ import com.google.common.collect.ImmutableList;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.mockito.*;
import org.onap.vid.aai.util.AAIRestInterface;
-import org.onap.vid.changeManagement.RequestDetailsWrapper;
+import org.onap.vid.aai.util.ServletRequestHelper;
+import org.onap.vid.aai.util.SystemPropertyHelper;
import org.onap.vid.controller.filter.PromiseEcompRequestIdFilter;
-import org.onap.vid.mso.RestMsoImplementation;
-import org.onap.vid.mso.RestObject;
import org.onap.vid.testUtils.TestUtils;
+import org.onap.vid.utils.Unchecked;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
@@ -22,6 +22,7 @@ import javax.ws.rs.client.Client;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.core.MultivaluedMap;
import java.util.Set;
+import java.util.UUID;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@@ -29,24 +30,31 @@ import java.util.stream.Stream;
import static org.apache.commons.lang3.StringUtils.equalsIgnoreCase;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
+import static org.mockito.Mockito.when;
-public class OutgoingRequestIdTest {
+public class OutgoingRequestHeadersTest {
- @InjectMocks
- private RestMsoImplementation restMsoImplementation;
+// @InjectMocks
+// private RestMsoImplementation restMsoImplementation;
+
+ @Mock
+ private SystemPropertyHelper systemPropertyHelper;
+
+ @Mock
+ private ServletRequestHelper servletRequestHelper;
@InjectMocks
private AAIRestInterface aaiRestInterface;
-
@Captor
private ArgumentCaptor<MultivaluedMap<String, Object>> multivaluedMapArgumentCaptor;
@BeforeClass
public void initMocks() {
MockitoAnnotations.initMocks(this);
+ when(servletRequestHelper.extractOrGenerateRequestId()).thenAnswer(invocation -> UUID.randomUUID().toString());
}
@BeforeMethod
@@ -54,47 +62,62 @@ public class OutgoingRequestIdTest {
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes((HttpServletRequest) PromiseEcompRequestIdFilter.wrapIfNeeded(new MockHttpServletRequest())));
}
- @DataProvider
- public Object[][] msoMethods() {
- return Stream.<ThrowingConsumer<RestMsoImplementation>>of(
-
- client -> client.Get(new Object(), "whatever source id", "/any path", new RestObject<>()),
- client -> client.GetForObject("whatever source id", "/any path", Object.class),
- client -> client.Post(new Object(), "some payload", "whatever source id", "/any path", new RestObject<>()),
- client -> client.PostForObject("some payload", "whatever source id", "/any path", Object.class),
- client -> client.Put(Object.class, new RequestDetailsWrapper(), "whatever source id", "/any path", new RestObject<>())
-
- ).map(l -> ImmutableList.of(l).toArray()).collect(Collectors.toList()).toArray(new Object[][]{});
- }
-
- @Test(dataProvider = "msoMethods")
- public void mso(Consumer<RestMsoImplementation> f) throws Exception {
- final TestUtils.JavaxRsClientMocks mocks = setAndGetMocksInsideRestImpl(restMsoImplementation);
-
- f.accept(restMsoImplementation);
-
- verifyRequestIdHeaderWasAdded(mocks.getFakeBuilder());
- }
+// @DataProvider
+// public Object[][] msoMethods() {
+// return Stream.<ThrowingConsumer<RestMsoImplementation>>of(
+//
+// client -> client.Get(new Object(), "/any path", new RestObject<>(), false),
+// client -> client.GetForObject("/any path", Object.class),
+// client -> client.Post("", "some payload", "/any path", new RestObject<>()),
+// client -> client.PostForObject("some payload", "/any path", Object.class),
+// client -> client.Put(Object.class, new RequestDetailsWrapper(), "/any path", new RestObject<>())
+//
+// ).map(l -> ImmutableList.of(l).toArray()).collect(Collectors.toList()).toArray(new Object[][]{});
+// }
+//
+// @Test(dataProvider = "msoMethods")
+// public void mso(Consumer<RestMsoImplementation> f) throws Exception {
+// final TestUtils.JavaxRsClientMocks mocks = setAndGetMocksInsideRestImpl(restMsoImplementation);
+//
+// f.accept(restMsoImplementation);
+//
+// Invocation.Builder fakeBuilder = mocks.getFakeBuilder();
+// Object requestIdValue = verifyXEcompRequestIdHeaderWasAdded(fakeBuilder);
+// assertEquals(requestIdValue, captureHeaderKeyAndReturnItsValue(fakeBuilder, "X-ONAP-RequestID"));
+//
+// assertThat((String) captureHeaderKeyAndReturnItsValue(fakeBuilder, "Authorization"), startsWith("Basic "));
+// assertThat(captureHeaderKeyAndReturnItsValue(fakeBuilder, "X-ONAP-PartnerName"), equalTo("VID"));
+// }
+//
+// @Test
+// public void whenProvideMsoRestCallUserId_builderHasXRequestorIDHeader() throws Exception {
+//
+// final TestUtils.JavaxRsClientMocks mocks = setAndGetMocksInsideRestImpl(restMsoImplementation);
+// String randomUserName = randomAlphabetic(10);
+//
+// restMsoImplementation.restCall(HttpMethod.DELETE, String.class, null, "abc", Optional.of(randomUserName));
+// assertEquals(randomUserName, captureHeaderKeyAndReturnItsValue(mocks.getFakeBuilder(), "X-RequestorID"));
+// }
@DataProvider
public Object[][] aaiMethods() {
return Stream.<ThrowingConsumer<AAIRestInterface>>of(
- client -> client.RestGet("from app id", "some transId", "/any path", false),
+ client -> client.RestGet("from app id", "some transId", Unchecked.toURI("/any path"), false),
client -> client.Delete("whatever source id", "some transId", "/any path"),
client -> client.RestPost("from app id", "/any path", "some payload", false),
- client -> client.RestPut("from app id", "/any path", "some payload", false)
+ client -> client.RestPut("from app id", "/any path", "some payload", false, false)
).map(l -> ImmutableList.of(l).toArray()).collect(Collectors.toList()).toArray(new Object[][]{});
}
- //@Test(dataProvider = "aaiMethods")
+ @Test(dataProvider = "aaiMethods")
public void aai(Consumer<AAIRestInterface> f) throws Exception {
final TestUtils.JavaxRsClientMocks mocks = setAndGetMocksInsideRestImpl(aaiRestInterface);
f.accept(aaiRestInterface);
- verifyRequestIdHeaderWasAdded(mocks.getFakeBuilder());
+ verifyXEcompRequestIdHeaderWasAdded(mocks.getFakeBuilder());
}
// @Test(dataProvider = "schedulerMethods")
@@ -107,10 +130,17 @@ public class OutgoingRequestIdTest {
//
// }
- private void verifyRequestIdHeaderWasAdded(Invocation.Builder fakeBuilder) {
+ private Object verifyXEcompRequestIdHeaderWasAdded(Invocation.Builder fakeBuilder) {
final String requestIdHeader = "x-ecomp-requestid";
final String uuidRegex = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
+ Object requestId = captureHeaderKeyAndReturnItsValue(fakeBuilder, requestIdHeader);
+
+ assertThat("header '" + requestIdHeader + "' should be a uuid", requestId,
+ allOf(instanceOf(String.class), hasToString(matchesPattern(uuidRegex))));
+ return requestId;
+ }
+ private Object captureHeaderKeyAndReturnItsValue(Invocation.Builder fakeBuilder, String headerName) {
// Checks that the builder was called with either one of header("x-ecomp-requestid", uuid)
// or the plural brother: headers(Map.of("x-ecomp-requestid", Set.of(uuid))
@@ -121,7 +151,7 @@ public class OutgoingRequestIdTest {
ArgumentCaptor<Object> argumentCaptor = ArgumentCaptor.forClass(Object.class);
Mockito.verify(fakeBuilder)
.header(
- Matchers.argThat(s -> equalsIgnoreCase(s, requestIdHeader)),
+ Matchers.argThat(s -> equalsIgnoreCase(s, headerName)),
argumentCaptor.capture()
);
requestId = argumentCaptor.getValue();
@@ -130,14 +160,12 @@ public class OutgoingRequestIdTest {
Mockito.verify(fakeBuilder).headers(multivaluedMapArgumentCaptor.capture());
final MultivaluedMap<String, Object> headersMap = multivaluedMapArgumentCaptor.getValue();
- final String thisRequestIdHeader = getFromSetCaseInsensitive(headersMap.keySet(), requestIdHeader);
+ final String thisRequestIdHeader = getFromSetCaseInsensitive(headersMap.keySet(), headerName);
assertThat(headersMap.keySet(), hasItem(thisRequestIdHeader));
requestId = headersMap.getFirst(thisRequestIdHeader);
}
-
- assertThat("header '" + requestIdHeader + "' should be a uuid", requestId,
- allOf(instanceOf(String.class), hasToString(matchesPattern(uuidRegex))));
+ return requestId;
}
private String getFromSetCaseInsensitive(Set<String> set, String key) {
diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/rest/RelatedInstanceTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/rest/RelatedInstanceTest.java
index 4b35430e0..1bedc1918 100644
--- a/vid-app-common/src/test/java/org/onap/vid/mso/rest/RelatedInstanceTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/mso/rest/RelatedInstanceTest.java
@@ -1,9 +1,9 @@
package org.onap.vid.mso.rest;
-import java.util.Map;
-
import org.junit.Test;
-import org.onap.vid.domain.mso.ModelInfo;
+import org.onap.vid.mso.model.ModelInfo;
+
+import java.util.Map;
public class RelatedInstanceTest {
diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/rest/RelatedModelTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/rest/RelatedModelTest.java
deleted file mode 100644
index 91d61bd9f..000000000
--- a/vid-app-common/src/test/java/org/onap/vid/mso/rest/RelatedModelTest.java
+++ /dev/null
@@ -1,93 +0,0 @@
-package org.onap.vid.mso.rest;
-
-import java.util.Map;
-
-import org.junit.Test;
-import org.onap.vid.domain.mso.ModelInfo;
-
-
-public class RelatedModelTest {
-
- private RelatedModel createTestSubject() {
- return new RelatedModel();
- }
-
-
- @Test
- public void testGetModelInfo() throws Exception {
- RelatedModel testSubject;
- ModelInfo result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getModelInfo();
- }
-
-
- @Test
- public void testSetModelInfo() throws Exception {
- RelatedModel testSubject;
- ModelInfo modelInfo = null;
-
- // default test
- testSubject = createTestSubject();
- testSubject.setModelInfo(modelInfo);
- }
-
-
- @Test
- public void testToString() throws Exception {
- RelatedModel testSubject;
- String result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.toString();
- }
-
-
- @Test
- public void testGetAdditionalProperties() throws Exception {
- RelatedModel testSubject;
- Map<String, Object> result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getAdditionalProperties();
- }
-
-
- @Test
- public void testSetAdditionalProperty() throws Exception {
- RelatedModel testSubject;
- String name = "";
- Object value = null;
-
- // default test
- testSubject = createTestSubject();
- testSubject.setAdditionalProperty(name, value);
- }
-
-
- @Test
- public void testHashCode() throws Exception {
- RelatedModel testSubject;
- int result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.hashCode();
- }
-
-
- @Test
- public void testEquals() throws Exception {
- RelatedModel testSubject;
- Object other = null;
- boolean result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.equals(other);
- }
-} \ No newline at end of file
diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/rest/RequestDetailsTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/rest/RequestDetailsTest.java
index e4716d587..f6b7c584f 100644
--- a/vid-app-common/src/test/java/org/onap/vid/mso/rest/RequestDetailsTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/mso/rest/RequestDetailsTest.java
@@ -1,11 +1,13 @@
package org.onap.vid.mso.rest;
+import org.junit.Test;
+import org.onap.vid.mso.model.CloudConfiguration;
+import org.onap.vid.mso.model.ModelInfo;
+import org.onap.vid.mso.model.RequestInfo;
+
import java.util.List;
import java.util.Map;
-import org.junit.Test;
-import org.onap.vid.domain.mso.*;
-
public class RequestDetailsTest {
diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/rest/RequestTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/rest/RequestTest.java
index f07fd1ab2..9250340a6 100644
--- a/vid-app-common/src/test/java/org/onap/vid/mso/rest/RequestTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/mso/rest/RequestTest.java
@@ -1,8 +1,6 @@
package org.onap.vid.mso.rest;
import org.junit.Test;
-import org.onap.vid.domain.mso.InstanceIds;
-import org.onap.vid.domain.mso.RequestStatus;
public class RequestTest {
diff --git a/vid-app-common/src/test/java/org/onap/vid/policy/PolicyResponseWrapperTest.java b/vid-app-common/src/test/java/org/onap/vid/policy/PolicyResponseWrapperTest.java
deleted file mode 100644
index 4e2676c6a..000000000
--- a/vid-app-common/src/test/java/org/onap/vid/policy/PolicyResponseWrapperTest.java
+++ /dev/null
@@ -1,70 +0,0 @@
-package org.onap.vid.policy;
-
-import org.junit.Test;
-
-public class PolicyResponseWrapperTest {
-
- private PolicyResponseWrapper createTestSubject() {
- return new PolicyResponseWrapper();
- }
-
- @Test
- public void testGetEntity() throws Exception {
- PolicyResponseWrapper testSubject;
- String result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getEntity();
- }
-
- @Test
- public void testGetStatus() throws Exception {
- PolicyResponseWrapper testSubject;
- int result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getStatus();
- }
-
- @Test
- public void testSetStatus() throws Exception {
- PolicyResponseWrapper testSubject;
- int v = 0;
-
- // default test
- testSubject = createTestSubject();
- testSubject.setStatus(v);
- }
-
- @Test
- public void testSetEntity() throws Exception {
- PolicyResponseWrapper testSubject;
- String v = "";
-
- // default test
- testSubject = createTestSubject();
- testSubject.setEntity(v);
- }
-
- @Test
- public void testToString() throws Exception {
- PolicyResponseWrapper testSubject;
- String result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.toString();
- }
-
- @Test
- public void testGetResponse() throws Exception {
- PolicyResponseWrapper testSubject;
- String result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getResponse();
- }
-} \ No newline at end of file
diff --git a/vid-app-common/src/test/java/org/onap/vid/policy/PolicyRestIntTest.java b/vid-app-common/src/test/java/org/onap/vid/policy/PolicyRestIntTest.java
deleted file mode 100644
index b94d21b91..000000000
--- a/vid-app-common/src/test/java/org/onap/vid/policy/PolicyRestIntTest.java
+++ /dev/null
@@ -1,22 +0,0 @@
-package org.onap.vid.policy;
-
-import org.junit.Test;
-import org.onap.vid.policy.rest.RequestDetails;
-
-public class PolicyRestIntTest {
-
- private PolicyRestInt createTestSubject() {
- return new PolicyRestInt();
- }
-
- @Test
- public void testLogRequest() throws Exception {
- PolicyRestInt testSubject;
- RequestDetails r = null;
-
- // test 1
- testSubject = createTestSubject();
- r = null;
- testSubject.logRequest(r);
- }
-} \ No newline at end of file
diff --git a/vid-app-common/src/test/java/org/onap/vid/policy/PolicyRestInterfaceFactoryTest.java b/vid-app-common/src/test/java/org/onap/vid/policy/PolicyRestInterfaceFactoryTest.java
deleted file mode 100644
index bb21c89f0..000000000
--- a/vid-app-common/src/test/java/org/onap/vid/policy/PolicyRestInterfaceFactoryTest.java
+++ /dev/null
@@ -1,18 +0,0 @@
-package org.onap.vid.policy;
-
-import org.junit.Test;
-
-public class PolicyRestInterfaceFactoryTest {
-
- private PolicyRestInterfaceFactory createTestSubject() {
- return new PolicyRestInterfaceFactory();
- }
-
- @Test
- public void testGetInstance() throws Exception {
- PolicyRestInterfaceIfc result;
-
- // default test
- result = PolicyRestInterfaceFactory.getInstance();
- }
-} \ No newline at end of file
diff --git a/vid-app-common/src/test/java/org/onap/vid/policy/PolicyRestInterfaceTest.java b/vid-app-common/src/test/java/org/onap/vid/policy/PolicyRestInterfaceTest.java
deleted file mode 100644
index 05191fc5e..000000000
--- a/vid-app-common/src/test/java/org/onap/vid/policy/PolicyRestInterfaceTest.java
+++ /dev/null
@@ -1,32 +0,0 @@
-package org.onap.vid.policy;
-
-import org.json.simple.JSONObject;
-import org.junit.Test;
-import org.onap.vid.policy.rest.RequestDetails;
-
-public class PolicyRestInterfaceTest {
-
- private PolicyRestInterface createTestSubject() {
- return new PolicyRestInterface();
- }
-
- @Test
- public void testLogRequest() throws Exception {
- PolicyRestInterface testSubject;
- RequestDetails r = null;
-
- // default test
- testSubject = createTestSubject();
- testSubject.logRequest(r);
- }
-
- /*@Test
- public void testInitRestClient() throws Exception {
- PolicyRestInterface testSubject;
-
- // default test
- testSubject = createTestSubject();
- testSubject.initRestClient();
- }*/
-
-} \ No newline at end of file
diff --git a/vid-app-common/src/test/java/org/onap/vid/policy/PolicyUtilTest.java b/vid-app-common/src/test/java/org/onap/vid/policy/PolicyUtilTest.java
deleted file mode 100644
index 1629081a6..000000000
--- a/vid-app-common/src/test/java/org/onap/vid/policy/PolicyUtilTest.java
+++ /dev/null
@@ -1,51 +0,0 @@
-package org.onap.vid.policy;
-
-import org.glassfish.jersey.client.ClientResponse;
-import org.junit.Assert;
-import org.junit.Test;
-
-public class PolicyUtilTest {
-
- private PolicyUtil createTestSubject() {
- return new PolicyUtil();
- }
-
- @Test
- public void testWrapResponse() throws Exception {
- String body = "";
- int statusCode = 0;
- PolicyResponseWrapper result;
-
- // default test
- result = PolicyUtil.wrapResponse(body, statusCode);
- }
-
-
- @Test
- public void testWrapResponse_2() throws Exception {
- RestObject<String> rs = null;
- PolicyResponseWrapper result;
-
- // test 1
- rs = null;
- result = PolicyUtil.wrapResponse(rs);
- Assert.assertNotNull(result);
- }
-
- @Test
- public void testConvertPojoToString() throws Exception {
- String result;
-
- // test 1
- result = PolicyUtil.convertPojoToString(null);
- Assert.assertEquals("", result);
- }
-
- @Test
- public void testMain() throws Exception {
- String[] args = new String[] { "" };
-
- // default test
- PolicyUtil.main(args);
- }
-} \ No newline at end of file
diff --git a/vid-app-common/src/test/java/org/onap/vid/policy/RestObjectTest.java b/vid-app-common/src/test/java/org/onap/vid/policy/RestObjectTest.java
deleted file mode 100644
index eab343ab0..000000000
--- a/vid-app-common/src/test/java/org/onap/vid/policy/RestObjectTest.java
+++ /dev/null
@@ -1,48 +0,0 @@
-package org.onap.vid.policy;
-
-import org.junit.Test;
-
-public class RestObjectTest {
-
- private RestObject createTestSubject() {
- return new RestObject();
- }
-
- @Test
- public void testSet() throws Exception {
- RestObject testSubject;
-
- // default test
- testSubject = createTestSubject();
- testSubject.set(null);
- }
-
- @Test
- public void testGet() throws Exception {
- RestObject testSubject;
-
- // default test
- testSubject = createTestSubject();
- testSubject.get();
- }
-
- @Test
- public void testSetStatusCode() throws Exception {
- RestObject testSubject;
- int v = 0;
-
- // default test
- testSubject = createTestSubject();
- testSubject.setStatusCode(v);
- }
-
- @Test
- public void testGetStatusCode() throws Exception {
- RestObject testSubject;
- int result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getStatusCode();
- }
-} \ No newline at end of file
diff --git a/vid-app-common/src/test/java/org/onap/vid/policy/rest/RequestDetailsTest.java b/vid-app-common/src/test/java/org/onap/vid/policy/rest/RequestDetailsTest.java
deleted file mode 100644
index 3c17a66a0..000000000
--- a/vid-app-common/src/test/java/org/onap/vid/policy/rest/RequestDetailsTest.java
+++ /dev/null
@@ -1,33 +0,0 @@
-package org.onap.vid.policy.rest;
-
-import org.junit.Test;
-
-
-public class RequestDetailsTest {
-
- private RequestDetails createTestSubject() {
- return new RequestDetails();
- }
-
-
- @Test
- public void testGetPolicyName() throws Exception {
- RequestDetails testSubject;
- String result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getPolicyName();
- }
-
-
- @Test
- public void testSetPolicyName() throws Exception {
- RequestDetails testSubject;
- String policyName = "";
-
- // default test
- testSubject = createTestSubject();
- testSubject.setPolicyName(policyName);
- }
-} \ No newline at end of file
diff --git a/vid-app-common/src/test/java/org/onap/vid/roles/RoleProviderTest.java b/vid-app-common/src/test/java/org/onap/vid/roles/RoleProviderTest.java
index b023bc265..6fdc21f78 100644
--- a/vid-app-common/src/test/java/org/onap/vid/roles/RoleProviderTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/roles/RoleProviderTest.java
@@ -1,9 +1,5 @@
package org.onap.vid.roles;
-import java.util.List;
-
-import javax.servlet.http.HttpServletRequest;
-
import org.junit.Test;
@@ -14,16 +10,6 @@ public class RoleProviderTest {
}
- @Test
- public void testExtractRoleFromSession() throws Exception {
- HttpServletRequest request = null;
- List<String> result;
-
- // default test
- result = RoleProvider.extractRoleFromSession(request);
- }
-
-
// @Test
// public void testGetUserRoles() throws Exception {
// RoleProvider testSubject;
diff --git a/vid-app-common/src/test/java/org/onap/vid/scheduler/RestObjectTest.java b/vid-app-common/src/test/java/org/onap/vid/scheduler/RestObjectTest.java
index 8c8642e36..36e2b33d2 100644
--- a/vid-app-common/src/test/java/org/onap/vid/scheduler/RestObjectTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/scheduler/RestObjectTest.java
@@ -1,6 +1,7 @@
package org.onap.vid.scheduler;
import org.junit.Test;
+import org.onap.vid.mso.RestObject;
public class RestObjectTest {
@@ -46,23 +47,4 @@ public class RestObjectTest {
result = testSubject.getStatusCode();
}
- @Test
- public void testSetUUID() throws Exception {
- RestObject testSubject;
- String uuid = "";
-
- // default test
- testSubject = createTestSubject();
- testSubject.setUUID(uuid);
- }
-
- @Test
- public void testGetUUID() throws Exception {
- RestObject testSubject;
- String result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getUUID();
- }
} \ No newline at end of file
diff --git a/vid-app-common/src/test/java/org/onap/vid/scheduler/RestObjects/RestObjectTest.java b/vid-app-common/src/test/java/org/onap/vid/scheduler/RestObjects/RestObjectTest.java
index 13fc57f36..31335edf3 100644
--- a/vid-app-common/src/test/java/org/onap/vid/scheduler/RestObjects/RestObjectTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/scheduler/RestObjects/RestObjectTest.java
@@ -1,6 +1,7 @@
package org.onap.vid.scheduler.RestObjects;
import org.junit.Test;
+import org.onap.vid.mso.RestObject;
public class RestObjectTest {
diff --git a/vid-app-common/src/test/java/org/onap/vid/scheduler/SchedulerRestInterfaceTest.java b/vid-app-common/src/test/java/org/onap/vid/scheduler/SchedulerRestInterfaceTest.java
index 0655aca9e..3e1c89c7b 100644
--- a/vid-app-common/src/test/java/org/onap/vid/scheduler/SchedulerRestInterfaceTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/scheduler/SchedulerRestInterfaceTest.java
@@ -31,7 +31,7 @@ import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
-import org.onap.vid.exceptions.GenericUncheckedException;
+import org.onap.vid.mso.RestObject;
import org.onap.vid.testUtils.StubServerUtil;
import org.testng.annotations.AfterMethod;
@@ -82,19 +82,19 @@ public class SchedulerRestInterfaceTest {
RestObject<String> sampleRestObj = new RestObject<>();
serverUtil.prepareGetCall("/test", RESPONSE_CONTENT, Action.ok());
- schedulerInterface.Get("", SAMPLE_SOURCE_ID, "", sampleRestObj);
+ schedulerInterface.Get("", "", sampleRestObj);
assertResponseHasExpectedBodyAndStatus(sampleRestObj, RESPONSE_CONTENT, 200);
}
- @Test(expected = GenericUncheckedException.class)
+ @Test(expected = org.onap.vid.aai.ExceptionWithRequestInfo.class)
public void shouldRaiseExceptionWhenErrorOccursDuringGet() throws JsonProcessingException {
prepareEnvForTest();
RestObject<String> sampleRestObj = new RestObject<>();
serverUtil.prepareGetCall("/test", ERROR_RESPONSE, Action.status(HttpStatus.INTERNAL_SERVER_ERROR_500));
- schedulerInterface.Get("", SAMPLE_SOURCE_ID, "", sampleRestObj);
+ schedulerInterface.Get("", "", sampleRestObj);
}
@Test
@@ -125,7 +125,6 @@ public class SchedulerRestInterfaceTest {
assertThat(sampleRestObj.getStatusCode()).isEqualTo(expectedStatusCode);
assertThat(parsedResult).isInstanceOf(String.class).isEqualTo(expectedResponse);
- assertThat(sampleRestObj.getUUID()).isNull();
}
diff --git a/vid-app-common/src/test/java/org/onap/vid/selenium/FirstClass.java b/vid-app-common/src/test/java/org/onap/vid/selenium/FirstClass.java
deleted file mode 100644
index e3ccdd965..000000000
--- a/vid-app-common/src/test/java/org/onap/vid/selenium/FirstClass.java
+++ /dev/null
@@ -1,605 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * VID
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.vid.selenium;
-
-import org.testng.annotations.AfterClass;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.AfterSuite;
-import org.testng.annotations.BeforeClass;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.BeforeSuite;
-import org.testng.annotations.BeforeTest;
-import org.testng.annotations.Test;
-
-
-import org.openqa.selenium.By;
-import org.openqa.selenium.WebDriver;
-import org.openqa.selenium.WebElement;
-import org.openqa.selenium.firefox.FirefoxDriver;
-import org.openqa.selenium.support.ui.Select;
-
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.List;
-import java.util.Properties;
-import java.util.concurrent.TimeUnit;
-import org.apache.log4j.Logger;
-import org.testng.Assert;
-import org.testng.asserts.*;
-
-/**
- * The Class FirstClass.
- */
-public class FirstClass {
-
- /** The login button. */
- WebElement loginButton;
-
- /** The eg. */
- String eg;
-
- /** The login. */
- WebElement login;
-
- /** The pwd. */
- WebElement pwd;
-
- /** The log. */
- Logger log;
-
- /** The errormessage. */
- WebElement errormessage;
-
-
- /** The driver. */
- WebDriver driver=new FirefoxDriver();
-
-
-
- /** The config prop. */
- private final Properties configProp = new Properties();
-
-
- /**
- * Instantiates a new first class.
- */
- private FirstClass() {
- // TODO Auto-generated constructor stub
- //
- try{
- // InputStream input =this.getClass().getClassLoader().getResourceAsStream("objectmap.properties");
- //FileInputStream input1 = new FileInputStream("objectmap.properties");
-
- InputStream input =new FileInputStream("objectconfig.properties");
- System.out.println("Read all properties from file");
- configProp.load(input);
- System.out.println("Read all properties from file completed");
- }
- catch(IOException e) {
-
- e.printStackTrace();
- }
- }
-
-
- /*
-
-
- @BeforeClass
- public void setUp() {
- System.out.println("*******************");
- System.out.println("launching IE browser");
- System.setProperty("webdriver.ie.driver", driverPath+"IEDriverServer.exe");
- driver = new InternetExplorerDriver();
- driver.findElement(By.className());
- driver.manage().window().maximize();
-
-
- login = driver.findElement(By.xpath("//input[@class='fn-ebz-text ng-pristine ng-valid']"));
- pwd = driver.findElement(By.xpath("//input[@class='span3 ng-pristine ng-valid']"));
- loginButton = driver.findElement(By.id("loginBtn"));
- }
-
-
- */
- /**
- * Sets the up.
- */
- // TODO Auto-generated method stub
- @BeforeClass
- public void setUp()
- {
-
-
- //WebDriver driver=new FirefoxDriver();
-
- log = Logger.getLogger(FirstClass.class.getName());
-
-
-
- // Get url
- driver.get(configProp.getProperty("baseURL"));
- driver.manage().window().maximize();
-
-
- login = driver.findElement(By.xpath(configProp.getProperty("login")));
-
- pwd = driver.findElement(By.xpath(configProp.getProperty("pwd")));
- loginButton = driver.findElement(By.id(configProp.getProperty("loginButton")));
- }
-
-
- /**
- * Empty username password.
- */
- @Test(priority=1)
- public void emptyUsernamePassword()
- {
-
-
- //User Name and Password field is empty
- log.info("-----VID-11 TC-8----Username and password empty");
- loginButton.click();
- errormessage=driver.findElement(By.xpath("//*[@id='errorInfo']/span"));
- String errmsg= errormessage.getText();
- //System.out.println("Error message is"+errmsg);
- //String expected = "Invaild username or password, Please try again";
-
- //Assert.assertEquals(errmsg,expected);
-
- Boolean str = driver.getPageSource().contains("Invalid username or password, Please try again");
- System.out.println(driver.getPageSource().contains("Invalid username or password, Please try again"));
-
- if(str==true)
- {
- log.info("Error message validated");
- log.info("VID-11 TC-8 PASSED");
-
- }else
- log.error("Failed validation");
-
- }
-
-
-
- /**
- * Invalid user name.
- */
- @Test(priority=2)
- public void invalidUserName()
- {
-
- log.info("-----VID-11 TC-6----Invalid Username and Valid Password");
-
-
- login.sendKeys("xxx");
- pwd.sendKeys("abc123");
- loginButton.click();
- try {
- Thread.sleep(5000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- String errmsg= errormessage.getText();
- String expected = "Invalid username or password, Please try again";
- Assert.assertEquals(errmsg,expected);
- //Boolean str1 = driver.getPageSource().contains("Invalid username or password, Please try again");
- //System.out.print(str1);
-
- log.info("VID-11 TC-6 PASSED");
-
- }
-
-
- /**
- * Invalid password.
- */
- @Test(priority=3)
- public void invalidPassword()
- {
- log.info("-----VID-11 TC-7----Valid Username and Invalid Password");
- // Valid user name and Invalid password.
- login.clear();
- pwd.clear();
- login.sendKeys("testuser");
- pwd.sendKeys("xxx");
- loginButton.click();
- driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
-
-
- String errmsg= errormessage.getText();
- String expected = "Invalid username or password, Please try again";
- Assert.assertEquals(errmsg,expected);
-
- //Boolean str2 = driver.getPageSource().contains("Invaild username or password, Please try again");
- //System.out.print(str2);
-
- log.info("VID-11 TC-7 PASSED");
- }
-
-
- /**
- * Login successful.
- */
- @Test(priority=4)
- public void loginSuccessful()
- {
- log.info("-----VID-11 TC-1----Valid Username and Valid Password");
- //Login with valid user name and password.
- login.clear();
- login.sendKeys("su");
- pwd.clear();
- pwd.sendKeys("fusion");
-
-
- loginButton.click();
- driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
-
- try {
- Thread.sleep(6000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- Assert.assertTrue(driver.getPageSource().contains("Search Existing Service Instances"));
- log.info("VID-11 TC-1 PASSED");
-
- }
-
-
- /**
- * Verify home page elements left pane.
- */
- @Test(priority=5)
- public void verifyHomePageElementsLeftPane()
-
- {
-
-
- log.info("VID-10 TC 1 ");
- //VID Home
- log.info("VID 11 TC-2");
- driver.findElement(By.xpath("html/body/div[1]/div[1]/div/div/div[2]/div/div/div[1]/div/div/accordion/div/div[1]/a/span")).isDisplayed();
- //Create New Service Instance
- driver.findElement(By.xpath("html/body/div[1]/div[1]/div/div/div[2]/div/div/div[1]/div/div/accordion/div/div[2]/a/span")).isDisplayed();
-
- //Browse Service Type
- driver.findElement(By.xpath("html/body/div[1]/div[1]/div/div/div[2]/div/div/div[1]/div/div/accordion/div/div[3]/a/span")).isDisplayed();
- //View Log
- driver.findElement(By.xpath("html/body/div[1]/div[1]/div/div/div[2]/div/div/div[1]/div/div/accordion/div/div[4]/a/span")).isDisplayed();
-
- //Profile
- driver.findElement(By.xpath("html/body/div[1]/div[1]/div/div/div[2]/div/div/div[1]/div/div/accordion/div/div[5]/a/span")).isDisplayed();
- //Admin
- driver.findElement(By.xpath("html/body/div[1]/div[1]/div/div/div[2]/div/div/div[1]/div/div/accordion/div/div[6]/a/span")).isDisplayed();
- //Logout
- driver.findElement(By.xpath("html/body/div[1]/div[1]/div/div/div[2]/div/div/div[1]/div/div/accordion/div/div[7]/a/span")).isDisplayed();
-
- //Infrastructure Subscriber Name
- driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[1]/td[1]/div/label")).isDisplayed();
- //Infrastructure Subscriber Name Select Drop down
- driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[1]/td[2]/div/select")).isDisplayed();
- //Infrastructure Service Type
- driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[2]/td[1]/div/label")).isDisplayed();
- //Infrastructure Service Type Select Drop down
- driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[2]/td[2]/div/select")).isDisplayed();
- //Submit button
- driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[3]/td/div/button")).isDisplayed();
-
- //Login Snippet Icon
- driver.findElement(By.xpath(".//*[@class='icon-user-small login-snippet-icon']")).isDisplayed();
-
-
- //String bodyText = driver.findElement(By.tagName("body")).getText();
- //Assert.assertTrue("Text not found!", bodyText.contains("Search Existing Service Instances"));
- //Assert.IsTrue(driver.getPageSource.Contains("Search Existing Service Instances"));
-
- log.info("VID-12 TC-1");
- Assert.assertTrue(driver.getPageSource().contains("Search Existing Service Instances"));
- Assert.assertTrue(driver.getPageSource().contains("Please search by the Subscriber name or Service Type from below:"));
- log.info("VID-12 TC-1 PASSED");
- log.info("VID-10 TC 1 PASSED");
- log.info("VID-11 TC-2 PASSED");
- }
-
-
- /**
- * Disabled submit button.
- */
- @Test(priority=6)
- public void disabledSubmitButton()
- {
- log.info("VID-12 TC-13");
- //Assert submit button disabled.
- Assert.assertFalse(driver.findElement(By.xpath(configProp.getProperty("submitButton"))).isEnabled());
- log.info("VID-12 TC-13 PASSED");
-
- }
-
- /**
- * Default list box value.
- */
- @Test(priority=7)
- public void defaultListBoxValue()
- {
- log.info("VID-12 TC-2");
-
-
- //WebElement subscribername =driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[1]/td[2]/div/select"));
-
- Select oSelect = new Select(driver.findElement(By.xpath(configProp.getProperty("subscriberNameDropDown"))));
- Select iSelect = new Select(driver.findElement(By.xpath(configProp.getProperty("serviceTypeDropDown"))));
-
-
- WebElement ielement=iSelect.getFirstSelectedOption();
- WebElement oelement=oSelect.getFirstSelectedOption();
- String defaultsubscribername=oelement.getText();
- String defaultservicetype=ielement.getText();
-
- Assert.assertEquals(defaultsubscribername,"Select Subscriber Name");
- Assert.assertEquals(defaultservicetype,"Select Service Type");
-
-
-
-
- //Verify Select Subscriber Name isDisplayed.
- //driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[1]/td[2]/div/select/option[1]")).isSelected();
-
- //Verify Select Service Type isDisplayed.
- //driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[2]/td[2]/div/select/option[1]")).isSelected();
-
-
- log.info("VID-12 TC-2 PASSED");
-
- }
-
-
-
- /**
- * Select subscriber name drop down.
- *
- * @throws InterruptedException the interrupted exception
- */
- @Test(priority=8)
- public void selectSubscriberNameDropDown() throws InterruptedException
- {
- log.info("------------------VID-10 TC-2,VID-12 TC-11, VID-12 TC-9, VID 12 TC-10,VID-12 TC-6, VID 12 TC-5--------------------");
-
-
- driver.findElement(By.xpath(configProp.getProperty("subscriberNameDropDown")));
-
- driver.findElement(By.xpath(configProp.getProperty("serviceTypeDropDown")));
- Thread.sleep(5000);
-
- //Infrastructure Subscriber Name
- Select oSelect = new Select(driver.findElement(By.xpath(configProp.getProperty("subscriberNameDropDown"))));
-
- List <WebElement> elementCount = oSelect.getOptions();
- log.info("Select Element Count of Service Name");
- System.out.println(elementCount.size());
-
-
- //Verifying getInfrastructureSubscribersList
- log.info("VID-29 TC-1");
- Assert.assertTrue(elementCount.size()>0);
- log.info("VID-29 TC-1 PASSED");
-
- oSelect.selectByIndex(2);
- String selectedOption = new Select(driver.findElement(By.xpath(configProp.getProperty("subscriberNameDropDown")))).getFirstSelectedOption().getText();
-
- System.out.println("Service Name selected is " +selectedOption);
- log.info("VID-10 TC-2 PASSED");
-
- //Submit button is clicked
- driver.findElement(By.xpath(configProp.getProperty("submitButton"))).click();
-
-
- //Verify whether the page header is displayed "Selected Subscriber's Service Instance Details:"
- driver.findElement(By.xpath(".//*[@id='mContent']/div/div/div/h1")).isDisplayed();
- //Assert.assertTrue(driver.getPageSource().contains("Selected Subscriber's Service Instance Details:"))
-
-
- //Verify whether the page header is displayed "Global Customer ID"
- driver.findElement(By.xpath(".//*[@id='mContent']/div/div/div/div/table/thead/tr/th[2]/div")).isDisplayed();
- Assert.assertTrue(driver.getPageSource().contains("Global Customer ID"));
- Assert.assertTrue(driver.getPageSource().contains("Subscriber Name"));
- Assert.assertTrue(driver.getPageSource().contains("Service Type"));
- Assert.assertTrue(driver.getPageSource().contains("Service Instance ID"));
-
- log.info("VID-12 TC-5 PASSED");
- log.info("VID-12 TC-11 PASSED");
-
- WebElement serviceinstancetable =driver.findElement(By.xpath("//table[@class='tablesorter tablesorter-default ng-isolate-scope']"));
-
- List<WebElement> rows_table = serviceinstancetable.findElements(By.tagName("tr"));
- //To calculate no of rows In table.
- int rows_count = rows_table.size();
-
- //Loop will execute till the last row of table.
- for (int row=0; row<rows_count; row++){
- //To locate columns(cells) of that specific row.
- List<WebElement> Columns_row = rows_table.get(row).findElements(By.tagName("td"));
- //To calculate no of columns(cells) In that specific row.
- int columns_count = Columns_row.size();
- //System.out.println("Number of cells In Row "+row+" are "+columns_count);
-
- //Loop will execute till the last cell of that specific row.
- for (int column=0; column<columns_count; column++){
- //To retrieve text from that specific cell.
- String celtext = Columns_row.get(column).getText();
- //System.out.println("Cell Value Of row number "+row+" and column number "+column+" Is "+celtext);
-
-
-
- //log.info("Testing Get column and row value");
- List <WebElement> exx= rows_table.get(1).findElements(By.tagName("td"));
- eg=Columns_row.get(2).getText();
- // System.out.println("Cell value of row 1 and column 2 is" +eg);
- }
- }
-
-
-
-
- //Verify View/Edit isDisplayed and Click
-
- driver.findElement(By.xpath("//a[@alt='View/Edit']")).isDisplayed();
-
- driver.findElement(By.xpath(".//*[@id='mContent']/div/div/div/div/table/tbody/tr[1]/td[1]/div/a")).click();
-
- log.info("User clicked View/Edit");
-
- //Verify the Subscriber Name displayed.
- String header= driver.findElement(By.xpath("//h1[@class='heading1 ng-binding']")).getText();
- //System.out.println(header);
-
-
- if(header.contains(eg))
- {
- System.out.println("Header contains the subscriber name");
- }else
- System.out.println("Header does not contain the subscriber name");
-
-
-
- Assert.assertTrue(driver.getPageSource().contains("PerfTest Subscriber00020021"));
- log.info("VID-12 TC-6 PASSED");
-
-
-
- driver.navigate().back();
- //Cancel button isDisplayed
- driver.findElement(By.xpath("//button[@class='button button--small button--primary']")).isDisplayed();
- log.info("VID-12 TC-9 PASSED");
-
- //Cancel button is clicked
- driver.findElement(By.xpath("//button[@class='button button--small button--primary']")).click();
- log.info("Cancel button is clicked");
-
- //Verifying VID Home page is displayed
- Assert.assertTrue(driver.getPageSource().contains("Search Existing Service Instances"));
- log.info("VID-12 TC-10 PASSED");
-
- }
-
-
- /**
- * Refresh subscriber name.
- */
- @Test(priority=9)
- public void refreshSubscriberName()
- {
- log.info("VID-10 TC-4");
-
-
- driver.findElement(By.xpath(configProp.getProperty("refreshButtonSubscriberName"))).isDisplayed();
-
- log.info("VID-10 TC-4 PASSED");
-
-
- }
-
-
- /**
- * Select subscriber type drop down.
- *
- * @throws InterruptedException the interrupted exception
- */
- @Test(priority=9)
- public void selectSubscriberTypeDropDown() throws InterruptedException
- {
- Thread.sleep(5000);
- log.info("------------------VID-10 TC-3, VID-12 TC-12,--------------------");
- //Infrastructure Subscriber Type
- Select iSelect = new Select(driver.findElement(By.xpath(configProp.getProperty("serviceTypeDropDown"))));
-
- List <WebElement> ielementCount = iSelect.getOptions();
- log.info("Select Element Count of Service type");
- System.out.println(ielementCount.size());
- iSelect.selectByIndex(1);
-
- log.info("VID-10 TC-3 PASSED");
-
-
- //Submit button is clicked
- driver.findElement(By.xpath(configProp.getProperty("submitButton"))).click();
-
- //Verify whether the page header is displayed "Selected Subscriber's Service Instance Details:"
- driver.findElement(By.xpath(".//*[@id='mContent']/div/div/div/h1")).isDisplayed();
- //Assert.assertTrue(driver.getPageSource().contains("Selected Subscriber's Service Instance Details:"))
- log.info("Page Header: Selected Subscriber's Service Instance Details");
-
-
- //Verify whether the page header is displayed "Global Customer ID"
- driver.findElement(By.xpath(".//*[@id='mContent']/div/div/div/div/table/thead/tr/th[2]/div")).isDisplayed();
-
- //Assert.assertTrue(driver.getPageSource().contains("Global Customer ID"));
- log.info("Table is displayed");
-
- log.info("VID-12 TC-12 PASSED");
-
- }
-
-
-
- /**
- * Logout under profile.
- */
- @Test(priority=10)
- public void logoutUnderProfile()
- {
-
- log.info("-----------VID-11 TC-5---------------------");
- //driver.findElement(By.partialLinkText("Click here to login")).click();
- //driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
-
-
- driver.findElement(By.xpath(".//*[@class='icon-user-small login-snippet-icon']")).click();
- driver.findElement(By.xpath(".//*[@id='reg-logout-div']/a")).click();
- //Validate that the user has logged out of VID. Displays "Portal"
- Assert.assertTrue(driver.getPageSource().contains("Portal"));
-
- log.info("VID-11 TC-5 PASSED");
-
- }
-
-
-
- /**
- * Tear down.
- */
- @AfterClass
- public void tearDown()
- {
- driver.close();
-
- }
-
-
-
- }
-
-
-
-
diff --git a/vid-app-common/src/test/java/org/onap/vid/selenium/LogOutLeftPane.java b/vid-app-common/src/test/java/org/onap/vid/selenium/LogOutLeftPane.java
deleted file mode 100644
index 19c6b1996..000000000
--- a/vid-app-common/src/test/java/org/onap/vid/selenium/LogOutLeftPane.java
+++ /dev/null
@@ -1,242 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * VID
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.vid.selenium;
-
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.List;
-import java.util.Properties;
-import java.util.concurrent.TimeUnit;
-
-import org.apache.log4j.Logger;
-import org.openqa.selenium.By;
-import org.openqa.selenium.WebDriver;
-import org.openqa.selenium.WebElement;
-import org.openqa.selenium.firefox.FirefoxDriver;
-import org.openqa.selenium.support.ui.Select;
-import org.testng.Assert;
-import org.testng.annotations.BeforeTest;
-import org.testng.annotations.Test;
-
-/**
- * The Class LogOutLeftPane.
- */
-@Test(enabled=false)
-public class LogOutLeftPane {
-
- /** The login button. */
- WebElement loginButton;
-
- /** The login. */
- WebElement login;
-
- /** The pwd. */
- WebElement pwd;
-
- /** The log. */
- Logger log;
-
- /** The errormessage. */
- WebElement errormessage;
-
- /** The driver. */
- WebDriver driver=new FirefoxDriver();
-
-
- /** The config prop. */
- private final Properties configProp = new Properties();
-
-
- /**
- * Instantiates a new log out left pane.
- */
- private LogOutLeftPane() {
- // TODO Auto-generated constructor stub
- //
- try{
- // InputStream input =this.getClass().getClassLoader().getResourceAsStream("objectmap.properties");
- //FileInputStream input1 = new FileInputStream("objectmap.properties");
-
- InputStream input =new FileInputStream("objectconfig.properties");
- System.out.println("Read all properties from file");
- configProp.load(input);
- System.out.println("Read all properties from file completed");
- }
- catch(IOException e) {
-
- e.printStackTrace();
- }
- }
-
-
-
-
- /**
- * Do before test.
- */
- // TODO Auto-generated method stub
- @BeforeTest
- public void doBeforeTest()
- {
- //WebDriver driver=new FirefoxDriver();
-
- log = Logger.getLogger(LogOutLeftPane.class.getName());
-
-
-
- // Get url
- driver.get("http://vid.onap.org:9080/vid/login_external.htm");
- driver.manage().window().maximize();
-
-
- login = driver.findElement(By.xpath("//input[@class='fn-ebz-text ng-pristine ng-valid']"));
- pwd = driver.findElement(By.xpath("//input[@class='span3 ng-pristine ng-valid']"));
- loginButton = driver.findElement(By.id("loginBtn"));
- }
-
-
- /**
- * Expand collapse panel.
- *
- * @throws InterruptedException the interrupted exception
- */
- @Test(priority=1)
- public void expandCollapsePanel() throws InterruptedException
- {
-
-
-
- login.clear();
- login.sendKeys("su");
- pwd.clear();
- pwd.sendKeys("fusion");
- //driver.findElement(By.partialLinkText("Click here to login")).click();
- //driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
-
- loginButton.click();
- driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
-
-
- log.info("Clicking Profile link from left pane");
- Thread.sleep(3000);
- System.out.println("properties file details --->"+configProp.getProperty("profilelink"));
- driver.findElement(By.xpath(configProp.getProperty("profilelink"))).click();
- Thread.sleep(3000);
-
- //Verify whether the sub panel is displayed
- //To verify the following :Search import from webphone and Self
- driver.findElement(By.xpath(".//*[@id='panel4']")).isDisplayed();
- log.info("Expand and collapse passed for Profile link");
-
- //For Admin
- //Verify expand and collapse working for ADMIN
- log.info("Clicking Admin link from left pane");
- driver.findElement(By.xpath("html/body/div[1]/div[1]/div/div/div[2]/div/div/div[1]/div/div/accordion/div/div[6]/a/span")).click();
- //To verify the following: Roles, Roles Functions, Usages
- driver.findElement(By.xpath(".//*[@id='panel5']")).isDisplayed();
-
-
- log.info("Expand and collapse passed for ADMIN link");
-
- log.info("VID-11 TC-3 PASSED");
-
- }
-
-
- /**
- * Drop down list.
- *
- * @throws InterruptedException the interrupted exception
- */
- @Test(priority=2)
- public void dropDownList() throws InterruptedException
- {
- //VID-12 TC-3
- log.info("VID-12 TC-3");
- //driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[1]/td[2]/div/select"));
-
- //driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[2]/td[2]/div/select"));
- Thread.sleep(5000);
-
- //Infrastructure Subscriber Name
- Select oSelect = new Select(driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[1]/td[2]/div/select")));
- Select iSelect = new Select(driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[2]/td[2]/div/select")));
-
- List <WebElement> elementCount = oSelect.getOptions();
- log.info("Subscriber Name Drop Down");
- System.out.println(elementCount.size());
- oSelect.selectByIndex(1);
- log.info("Subscriber name selected");
- //String selectedOption = new Select(driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[1]/td[2]/div/select"))).getFirstSelectedOption().getText();
-
-
- List <WebElement> count = iSelect.getOptions();
- log.info("Subscriber type drop down");
- System.out.println(count.size());
- oSelect.selectByIndex(1);
- log.info("Subscriber type selected");
-
-
-
- //Submit button is clicked
- driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[3]/td/div/button")).click();
-
-
- //Verify whether the page header is displayed "Selected Subscriber's Service Instance Details:"
- driver.findElement(By.xpath(".//*[@id='mContent']/div/div/div/h1")).isDisplayed();
- log.info("VID-12 TC-3 PASSED");
- }
-
-
-
-
- /**
- * Logout left pane.
- */
- @Test(priority=3)
- public void logoutLeftPane()
- {
- //To Verify if the logout link redirects to Login page when clicked.
-
-
- /*log.info("----------------VID-11 TC-4----------------");
- login.clear();
- login.sendKeys("testuser");
- pwd.clear();
- pwd.sendKeys("abc123");
- //driver.findElement(By.partialLinkText("Click here to login")).click();
- //driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
-
- loginButton.click();
- driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);*/
- log.info("----------------VID-11 TC-4----------------");
- driver.findElement(By.xpath("html/body/div[1]/div[1]/div/div/div[2]/div/div/div[1]/div/div/accordion/div/div[7]/a")).click();
- //Validate that the user has logged out of VID. Displays "Portal"
- Assert.assertTrue(driver.getPageSource().contains("Portal"));
-
- log.info("VID 11 TC-4 PASSED");
-
- driver.close();
-
- }
-
-}
diff --git a/vid-app-common/src/test/java/org/onap/vid/services/AAIServiceTreeTest.java b/vid-app-common/src/test/java/org/onap/vid/services/AAIServiceTreeTest.java
new file mode 100644
index 000000000..815c6b9ee
--- /dev/null
+++ b/vid-app-common/src/test/java/org/onap/vid/services/AAIServiceTreeTest.java
@@ -0,0 +1,160 @@
+package org.onap.vid.services;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Streams;
+import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
+import org.apache.commons.lang3.builder.ToStringStyle;
+import org.jetbrains.annotations.NotNull;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.onap.vid.asdc.parser.ServiceModelInflator;
+import org.onap.vid.asdc.parser.ServiceModelInflator.Names;
+import org.onap.vid.model.aaiTree.AAITreeNode;
+import org.testng.annotations.BeforeTest;
+import org.testng.annotations.Test;
+
+import java.util.List;
+
+import static java.util.Collections.emptyList;
+import static java.util.Collections.emptyMap;
+import static java.util.stream.Collectors.toList;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.when;
+
+public class AAIServiceTreeTest {
+
+ @Mock
+ private VidService sdcService;
+ @Mock
+ private ServiceModelInflator serviceModelInflator;
+ @InjectMocks
+ private AAIServiceTree aaiServiceTree;
+
+ @BeforeTest
+ public void initMocks() {
+ MockitoAnnotations.initMocks(this);
+ }
+
+ private final static String nullString = "null placeholder";
+
+
+
+ @Test
+ public void enrichNodesWithModelCustomizationName_simple3NodesCase_nodesEnriched() {
+
+ when(serviceModelInflator.toNamesByVersionId(any())).thenReturn(ImmutableMap.of(
+ "version id a", new Names("name a", "key a"),
+ "version id b", new Names("name b", "key b"),
+ "version id c", new Names("name c", "key c")
+ ));
+
+ final ImmutableList<String> versionIds = ImmutableList.of("version id a", "version id b", "version id c");
+ final ImmutableList<Names> expectedNames = ImmutableList.of(
+ new Names("name a", "key a"),
+ new Names("name b", "key b"),
+ new Names("name c", "key c"));
+
+
+ final List<AAITreeNode> nodesUnderTest = nodesWithVersionIds(versionIds);
+ aaiServiceTree.enrichNodesWithModelCustomizationName(nodesUnderTest, null);
+
+ assertThat(toStrings(nodesUnderTest), containsInAnyOrder(toStringsArray(nodesWithVersionIdsAndCustomizationNames(versionIds, expectedNames))));
+ }
+
+ @Test
+ public void enrichNodesWithModelCustomizationName_noNodes_noError() {
+
+ when(serviceModelInflator.toNamesByVersionId(any())).thenReturn(ImmutableMap.of(
+ "11c6dc3e-cd6a-41b3-a50e-b5a10f7157d0", new Names("my model cust name", "my key")
+ ));
+
+ aaiServiceTree.enrichNodesWithModelCustomizationName(emptyList(), null);
+ }
+
+ @Test
+ public void enrichNodesWithModelCustomizationName_nothingInModel_nodesUnchanged() {
+
+ when(serviceModelInflator.toNamesByVersionId(any())).thenReturn(emptyMap());
+
+ final ImmutableList<String> versionIds = ImmutableList.of("version id a", "version id b", "version id c");
+ final Names nullNames = new Names(nullString, nullString);
+ final ImmutableList<Names> expectedNames = ImmutableList.of(nullNames, nullNames, nullNames);
+
+
+ final List<AAITreeNode> nodesUnderTest = nodesWithVersionIds(versionIds);
+
+ aaiServiceTree.enrichNodesWithModelCustomizationName(nodesUnderTest, null);
+
+ assertThat(toStrings(nodesUnderTest), containsInAnyOrder(toStringsArray(nodesWithVersionIdsAndCustomizationNames(versionIds, expectedNames))));
+ }
+
+ @Test
+ public void enrichNodesWithModelCustomizationName_staggered4NodesAndNull_3nodesEnriched2isNull() {
+
+ when(serviceModelInflator.toNamesByVersionId(any())).thenReturn(ImmutableMap.of(
+ "version id Z", new Names("name Z", "key Z"),
+ "version id d", new Names(null, "key d"),
+ "version id c", new Names("name c", null),
+ "version id a", new Names("name a", "key a")
+ ));
+
+ final ImmutableList<String> versionIds = ImmutableList.of("version id a", "version id b", "version id c", "version id d", nullString);
+ final ImmutableList<Names> expectedNames = ImmutableList.of(
+ new Names("name a", "key a"),
+ new Names(nullString, nullString),
+ new Names("name c", nullString),
+ new Names(nullString, "key d"),
+ new Names(nullString, nullString)
+ );
+
+
+ final List<AAITreeNode> nodesUnderTest = nodesWithVersionIds(versionIds);
+
+ aaiServiceTree.enrichNodesWithModelCustomizationName(nodesUnderTest, null);
+
+ assertThat(toStrings(nodesUnderTest), containsInAnyOrder(toStringsArray(nodesWithVersionIdsAndCustomizationNames(versionIds, expectedNames))));
+ }
+
+
+
+ @NotNull
+ private String[] toStringsArray(List<AAITreeNode> nodes) {
+ return toStrings(nodes).toArray(new String[] {});
+ }
+
+ @NotNull
+ private List<String> toStrings(List<AAITreeNode> nodes) {
+ return nodes.stream().map(n -> {
+ final ReflectionToStringBuilder reflectionToStringBuilder = new ReflectionToStringBuilder(n, ToStringStyle.SHORT_PREFIX_STYLE);
+ reflectionToStringBuilder.setExcludeNullValues(true);
+ return reflectionToStringBuilder.toString();
+ }).collect(toList());
+ }
+
+ @NotNull
+ private List<AAITreeNode> nodesWithVersionIdsAndCustomizationNames(List<String> versionIds, List<Names> customizationNames) {
+ return Streams
+ .zip(versionIds.stream(), customizationNames.stream(), this::nodeWithVersionIdAndCustomizationName)
+ .collect(toList());
+ }
+
+ @NotNull
+ private List<AAITreeNode> nodesWithVersionIds(List<String> versionIds) {
+ return versionIds.stream()
+ .map(versionId -> nodeWithVersionIdAndCustomizationName(versionId, new Names(nullString, nullString)))
+ .collect(toList());
+ }
+
+ private AAITreeNode nodeWithVersionIdAndCustomizationName(String versionId, Names names) {
+ AAITreeNode newNode = new AAITreeNode();
+ newNode.setModelVersionId(versionId.equals(nullString) ? null : versionId);
+ newNode.setModelCustomizationName(names.getModelCustomizationName().equals(nullString) ? null : names.getModelCustomizationName());
+ newNode.setKeyInModel(names.getModelKey().equals(nullString) ? null : names.getModelKey());
+ return newNode;
+ }
+
+} \ No newline at end of file
diff --git a/vid-app-common/src/test/java/org/onap/vid/services/AAITreeConverterTest.java b/vid-app-common/src/test/java/org/onap/vid/services/AAITreeConverterTest.java
new file mode 100644
index 000000000..0fac65e4f
--- /dev/null
+++ b/vid-app-common/src/test/java/org/onap/vid/services/AAITreeConverterTest.java
@@ -0,0 +1,222 @@
+package org.opencomp.vid.services;
+
+import com.google.common.collect.ImmutableList;
+import org.mockito.InjectMocks;
+import org.mockito.MockitoAnnotations;
+import org.onap.vid.aai.util.AAITreeConverter;
+import org.onap.vid.model.Action;
+import org.onap.vid.model.aaiTree.*;
+import org.testng.annotations.BeforeTest;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+import java.util.List;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.*;
+import static org.onap.vid.asdc.parser.ToscaParserImpl2.Constants.A_LA_CARTE;
+
+public class AAITreeConverterTest {
+
+ @InjectMocks
+ private AAITreeConverter aaiTreeConverter;
+
+ @BeforeTest
+ public void initMocks() {
+ MockitoAnnotations.initMocks(this);
+ }
+
+ @Test
+ public void testConvertTreeToUIModel_NoChildren() throws Exception {
+
+ AAITreeNode aaiTree = generateAaiTreeToConvert(0, 0);
+
+ ServiceInstance result = aaiTreeConverter.convertTreeToUIModel(aaiTree, "global-customer-id", "service-type", A_LA_CARTE);
+
+ assertService(result, 0, 0, true);
+ }
+
+ @Test
+ public void testConvertTreeToUIModel_MultipleChildren() throws Exception {
+
+ AAITreeNode aaiTree = generateAaiTreeToConvert(2, 2);
+
+ ServiceInstance serviceInstance = aaiTreeConverter.convertTreeToUIModel(aaiTree, "global-customer-id", "service-type", null);
+
+ assertService(serviceInstance, 2, 2, false);
+
+ int nodesCounter = 0;
+ assertThat(serviceInstance.getVnfs().entrySet(), hasSize(2));
+ assertVnf(serviceInstance.getVnfs().get("vnf-model-version-id:00"+(nodesCounter++)), 0, 0, false);
+ assertVnf(serviceInstance.getVnfs().get("vnf-model-version-id:00"+(nodesCounter++)), 0, 0, false);
+
+ assertThat(serviceInstance.getNetworks().entrySet(), hasSize(2));
+ assertNetwork(serviceInstance.getNetworks().get("network-model-version-id:00"+(nodesCounter++)), false);
+ assertNetwork(serviceInstance.getNetworks().get("network-model-version-id:00"+(nodesCounter)), false);
+ }
+
+ @DataProvider
+ public static Object[][] vnfWithChildren() {
+ return new Object[][]{
+ {ImmutableList.of(), ImmutableList.of()},
+ {ImmutableList.of(true, false), ImmutableList.of()},
+ {ImmutableList.of(), ImmutableList.of(false)}
+ };
+ }
+
+ @Test(dataProvider = "vnfWithChildren")
+ public void testComplexVnfConversion(List<Boolean> vfModules, List<Boolean> networks) {
+
+ AAITreeNode vnfTreeNode = createVnf(1, false);
+ int nodesCounter = 0;
+
+ for (Boolean customizationName: vfModules) {
+ vnfTreeNode.getChildren().add(createVfModule(nodesCounter++, customizationName));
+ }
+
+ for (Boolean customizationName: networks) {
+ vnfTreeNode.getChildren().add(createNetwork(nodesCounter++, customizationName));
+ }
+
+ Vnf actualVnf = Vnf.from(vnfTreeNode);
+
+ assertVnf(actualVnf, vfModules.size(), networks.size(), false);
+
+ nodesCounter = 0;
+ for (Boolean customizationName: vfModules) {
+ String key = customizationName ? "vfModule key in model" : "vfModule-model-version-id";
+
+ assertThat(actualVnf.getVfModules(), hasKey(key));
+ assertThat(actualVnf.getVfModules().get(key), hasKey(key + ":00" + nodesCounter));
+ VfModule actualVfModule = actualVnf.getVfModules().get(key).get(key + ":00" + nodesCounter);
+ assertVfModule(actualVfModule, customizationName);
+ nodesCounter++;
+ }
+
+ for (Boolean customizationName: networks) {
+ String key = customizationName ? "network key in model" : "network-model-version-id";
+
+ assertThat(actualVnf.getNetworks(), hasKey(key + ":00" + nodesCounter));
+ Network actualNetwork = actualVnf.getNetworks().get(key + ":00" + nodesCounter);
+ assertNetwork(actualNetwork, customizationName);
+ nodesCounter++;
+ }
+ }
+
+ @Test
+ public void testNetworkConversion() {
+ AAITreeNode networkTreeNode = createNetwork(1, true);
+
+ Network actualNetwork = Network.from(networkTreeNode);
+
+ assertNetwork(actualNetwork, true);
+ }
+
+ private AAITreeNode createVnf(int uniqueNumber, boolean hasCustomizationName) {
+ AAITreeNode vnfTreeNode = new AAITreeNode();
+ vnfTreeNode.setId("vnf-instance-id");
+ vnfTreeNode.setName("vnf-instance-name");
+ vnfTreeNode.setType("generic-vnf");
+ vnfTreeNode.setModelVersionId("vnf-model-version-id");
+ if (hasCustomizationName) {
+ vnfTreeNode.setModelCustomizationName("vnf model customization name");
+ vnfTreeNode.setKeyInModel("vnf key in model");
+ }
+ vnfTreeNode.setUniqueNumber(uniqueNumber);
+ return vnfTreeNode;
+ }
+
+ private AAITreeNode createVfModule(int uniqueNumber, boolean hasCustomizationName) {
+ AAITreeNode vfModuleTreeNode = new AAITreeNode();
+ vfModuleTreeNode.setId("vfModule-instance-id");
+ vfModuleTreeNode.setName("vfModule-instance-name");
+ vfModuleTreeNode.setType("vf-module");
+ vfModuleTreeNode.setModelVersionId("vfModule-model-version-id");
+ if (hasCustomizationName) {
+ vfModuleTreeNode.setModelCustomizationName("vfModule model customization name");
+ vfModuleTreeNode.setKeyInModel("vfModule key in model");
+ }
+ vfModuleTreeNode.setUniqueNumber(uniqueNumber);
+
+ return vfModuleTreeNode;
+ }
+
+ private AAITreeNode createNetwork(int uniqueNumber, boolean hasCustomizationName) {
+ AAITreeNode networkTreeNode = new AAITreeNode();
+ networkTreeNode.setId("network-instance-id");
+ networkTreeNode.setName("network-instance-name");
+ networkTreeNode.setType("l3-network");
+ networkTreeNode.setModelVersionId("network-model-version-id");
+ if (hasCustomizationName) {
+ networkTreeNode.setModelCustomizationName("network model customization name");
+ networkTreeNode.setKeyInModel("network key in model");
+ }
+ networkTreeNode.setUniqueNumber(uniqueNumber);
+
+ return networkTreeNode;
+ }
+
+ private void assertService(ServiceInstance serviceInstance, int expectedVnfs, int expectedNetworks, boolean isALaCarte) {
+ assertThat(serviceInstance.getInstanceId(), is("service-instance-id"));
+ assertThat(serviceInstance.getInstanceName(), is("service-instance-name"));
+ assertThat(serviceInstance.getAction(), is(Action.None));
+ assertThat(serviceInstance.getGlobalSubscriberId(), is("global-customer-id"));
+ assertThat(serviceInstance.getSubscriptionServiceType(), is("service-type"));
+ assertThat(serviceInstance.getModelInfo().getModelType(), is("service"));
+ assertThat(serviceInstance.getVnfs().entrySet(), hasSize(expectedVnfs));
+ assertThat(serviceInstance.getNetworks().entrySet(), hasSize(expectedNetworks));
+ assertThat(serviceInstance.getIsALaCarte(), is(isALaCarte));
+ }
+
+ private void assertVnf(Vnf actualVnf, int expectedVfModules, int expectedNetworks, boolean hasCustomizationName) {
+ assertThat(actualVnf.getInstanceId(), is("vnf-instance-id"));
+ assertThat(actualVnf.getInstanceName(), is("vnf-instance-name"));
+ assertThat(actualVnf.getAction(), is(Action.None));
+ assertThat(actualVnf.getModelInfo().getModelType(), is("vnf"));
+ assertThat(actualVnf.getModelInfo().getModelVersionId(), is("vnf-model-version-id"));
+ assertThat(actualVnf.getVfModules().entrySet(), hasSize(expectedVfModules));
+ assertThat(actualVnf.getNetworks().entrySet(), hasSize(expectedNetworks));
+ assertThat(actualVnf.getTrackById(), is(not(emptyOrNullString())));
+ String expectedCustomizationName = hasCustomizationName ? "vnf model customization name" : null;
+ assertThat(actualVnf.getModelInfo().getModelCustomizationName(), is(expectedCustomizationName));
+ }
+
+ private void assertVfModule(VfModule actualVfModule, boolean hasCustomizationName) {
+ assertThat(actualVfModule.getInstanceId(), is("vfModule-instance-id"));
+ assertThat(actualVfModule.getInstanceName(), is("vfModule-instance-name"));
+ assertThat(actualVfModule.getAction(), is(Action.None));
+ assertThat(actualVfModule.getModelInfo().getModelType(), is("vfModule"));
+ assertThat(actualVfModule.getModelInfo().getModelVersionId(), is("vfModule-model-version-id"));
+ assertThat(actualVfModule.getTrackById(), is(not(emptyOrNullString())));
+ String expectedCustomizationName = hasCustomizationName ? "vfModule model customization name" : null;
+ assertThat(actualVfModule.getModelInfo().getModelCustomizationName(), is(expectedCustomizationName));
+ }
+
+ private void assertNetwork(Network actualNetwork, boolean hasCustomizationName) {
+ assertThat(actualNetwork.getInstanceId(), is("network-instance-id"));
+ assertThat(actualNetwork.getInstanceName(), is("network-instance-name"));
+ assertThat(actualNetwork.getAction(), is(Action.None));
+ assertThat(actualNetwork.getModelInfo().getModelType(), is("network"));
+ assertThat(actualNetwork.getModelInfo().getModelVersionId(), is("network-model-version-id"));
+ assertThat(actualNetwork.getTrackById(), is(not(emptyOrNullString())));
+ String expectedCustomizationName = hasCustomizationName ? "network model customization name" : null;
+ assertThat(actualNetwork.getModelInfo().getModelCustomizationName(), is(expectedCustomizationName));
+ }
+
+ private AAITreeNode generateAaiTreeToConvert(int numberOfVnfs, int numberOfNetworks) {
+ int counter = 0;
+ AAITreeNode aaiTree = new AAITreeNode();
+ aaiTree.setId("service-instance-id");
+ aaiTree.setName("service-instance-name");
+
+ for (int i = 0; i < numberOfVnfs; i++) {
+ aaiTree.getChildren().add(createVnf(counter++, false));
+ }
+
+ for (int i = 0; i < numberOfNetworks; i++) {
+ aaiTree.getChildren().add(createNetwork(counter++, false));
+ }
+
+ return aaiTree;
+ }
+} \ No newline at end of file
diff --git a/vid-app-common/src/test/java/org/onap/vid/services/AAITreeNodeBuilderTest.java b/vid-app-common/src/test/java/org/onap/vid/services/AAITreeNodeBuilderTest.java
new file mode 100644
index 000000000..5eac5f924
--- /dev/null
+++ b/vid-app-common/src/test/java/org/onap/vid/services/AAITreeNodeBuilderTest.java
@@ -0,0 +1,131 @@
+package org.onap.vid.services;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.onap.vid.aai.AaiClientInterface;
+import org.onap.vid.model.aaiTree.AAITreeNode;
+import org.onap.vid.utils.Unchecked;
+import org.testng.Assert;
+import org.testng.annotations.BeforeTest;
+import org.testng.annotations.Test;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.ConcurrentSkipListSet;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import static java.util.Comparator.comparing;
+import static org.mockito.Mockito.when;
+import static org.onap.vid.services.AAIServiceTree.AAI_TREE_PATHS;
+
+public class AAITreeNodeBuilderTest {
+
+ AAITreeNodeBuilder aaiTreeNodeBuilder;
+
+ @Mock
+ AaiClientInterface aaiClientMock;
+
+ @Mock
+ ThreadPoolExecutor threadPoolMock;
+
+
+ @BeforeTest
+ public void initMocks() {
+ MockitoAnnotations.initMocks(this);
+ aaiTreeNodeBuilder = new AAITreeNodeBuilder(aaiClientMock);
+ }
+
+ @Test
+ public void buildNode_buildGroupNode_NodeIsAsExpected(){
+ ConcurrentSkipListSet<AAITreeNode> nodesAccumulator = new ConcurrentSkipListSet<>(comparing(AAITreeNode::getUniqueNodeKey));
+ ConcurrentLinkedQueue<String> visitedNodes = new ConcurrentLinkedQueue<>();
+ when(aaiClientMock.typedAaiGet(Unchecked.toURI("anyUrl"), JsonNode.class)).thenReturn(createGroupJson());
+
+ AAITreeNode groupNode = aaiTreeNodeBuilder.buildNode("instance-group",
+ "anyUrl",
+ nodesAccumulator,
+ threadPoolMock,
+ visitedNodes,
+ new AtomicInteger(0),
+ AAI_TREE_PATHS).get(0);
+
+ AAITreeNode expectedGroupNode = createExpectedGroupNode();
+ assertNodeIsAsExpected(expectedGroupNode,groupNode);
+ }
+
+ private void assertNodeIsAsExpected(AAITreeNode expectedGroupNode, AAITreeNode groupNode) {
+ Assert.assertEquals(groupNode.getId(), expectedGroupNode.getId());
+ Assert.assertEquals(groupNode.getType(), expectedGroupNode.getType());
+ Assert.assertEquals(groupNode.getName(), expectedGroupNode.getName());
+ Assert.assertEquals(groupNode.getModelVersionId(), expectedGroupNode.getModelVersionId());
+ Assert.assertEquals(groupNode.getModelInvariantId(), expectedGroupNode.getModelInvariantId());
+ Assert.assertEquals(groupNode.getInMaint(), expectedGroupNode.getInMaint());
+ Assert.assertEquals(groupNode.getAdditionalProperties(), expectedGroupNode.getAdditionalProperties());
+ }
+
+ private AAITreeNode createExpectedGroupNode() {
+ AAITreeNode expectedNode = new AAITreeNode();
+ expectedNode.setId("c4fcf022-31a0-470a-b5b8-c18335b7af32");
+ expectedNode.setType("instance-group");
+ expectedNode.setName("Test vE-Flex");
+ expectedNode.setModelVersionId("Test vE-Flex");
+ expectedNode.setModelInvariantId("dd182d7d-6949-4b90-b3cc-5befe400742e");
+ expectedNode.setInMaint(false);
+ HashMap<String,Object> additionalProperties = new HashMap<>();
+ additionalProperties.put("inMaint","false");
+ additionalProperties.put("description","Test vE-Flex instance-group");
+ additionalProperties.put("instance-group-type","ha");
+ additionalProperties.put("instance-group-role","test-IG-role");
+ additionalProperties.put("resource-version","1533315433086");
+ additionalProperties.put("instance-group-function","vTSBC Customer Landing Network Collection");
+ expectedNode.setAdditionalProperties(additionalProperties);
+
+
+ return expectedNode;
+ }
+
+ private JsonNode createGroupJson() {
+ ObjectMapper objectMapper = new ObjectMapper();
+ JsonNode groupNode = null;
+ try {
+ groupNode = objectMapper.readTree("" +
+ "{" +
+ " \"id\": \"c4fcf022-31a0-470a-b5b8-c18335b7af32\"," +
+ " \"instance-group-role\": \"test-IG-role\"," +
+ " \"description\": \"Test vE-Flex instance-group\"," +
+ " \"instance-group-type\": \"ha\"," +
+ " \"resource-version\": \"1533315433086\"," +
+ " \"instance-group-name\": \"Test vE-Flex\"," +
+ " \"model-invariant-id\": \"dd182d7d-6949-4b90-b3cc-5befe400742e\"," +
+ " \"model-version-id\": \"Test vE-Flex\"," +
+ " \"inMaint\": \"false\"," +
+ " \"instance-group-function\": \"vTSBC Customer Landing Network Collection\"," +
+ " \"relationship-list\": {" +
+ " \"relationship\": [{" +
+ " \"related-to\": \"generic-vnf\"," +
+ " \"relationship-label\": \"org.onap.relationships.inventory.MemberOf\" ," +
+ " \"related-link\": \"/aai/v14/network/generic-vnfs/generic-vnf/8c54c369-2876-4423-9b33-80f783f29082\" ," +
+ " \"relationship-data\": [{" +
+ " \"relationship-key\": \"generic-vnf.vnf-id\"," +
+ " \"relationship-value\": \"8c54c369-2876-4423-9b33-80f783f29082\"" +
+ " }" +
+ " ]," +
+ " \"related-to-property\": [{" +
+ " \"property-key\": \"generic-vnf.vnf-name\"," +
+ " \"property-value\": \"zrdm5bffad01\"" +
+ " }" +
+ " ]" +
+ " }" +
+ " ]" +
+ " }" +
+ " }");
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ return groupNode;
+ }
+}
diff --git a/vid-app-common/src/test/java/org/onap/vid/services/AaiResponseTranslatorTest.java b/vid-app-common/src/test/java/org/onap/vid/services/AaiResponseTranslatorTest.java
index 04890e339..841ea10ac 100644
--- a/vid-app-common/src/test/java/org/onap/vid/services/AaiResponseTranslatorTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/services/AaiResponseTranslatorTest.java
@@ -1,7 +1,7 @@
package org.onap.vid.services;
-import org.codehaus.jackson.JsonNode;
-import org.codehaus.jackson.map.ObjectMapper;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
import org.onap.vid.aai.AaiResponseTranslator;
import org.onap.vid.aai.AaiResponseTranslator.PortMirroringConfigData;
import org.onap.vid.aai.AaiResponseTranslator.PortMirroringConfigDataError;
@@ -13,7 +13,6 @@ import java.io.IOException;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
-@Test
public class AaiResponseTranslatorTest {
private static final ObjectMapper objectMapper = new ObjectMapper();
diff --git a/vid-app-common/src/test/java/org/onap/vid/services/AsyncInstantiationBaseTest.java b/vid-app-common/src/test/java/org/onap/vid/services/AsyncInstantiationBaseTest.java
index 5ead3fce4..ed8d91fe6 100644
--- a/vid-app-common/src/test/java/org/onap/vid/services/AsyncInstantiationBaseTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/services/AsyncInstantiationBaseTest.java
@@ -1,52 +1,25 @@
-/*-
- * ============LICENSE_START=======================================================
- * VID
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2018 Nokia. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
package org.onap.vid.services;
+import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
-import io.joshworks.restclient.http.HttpResponse;
-import jersey.repackaged.com.google.common.collect.ImmutableList;
-import org.apache.http.HttpStatus;
-import org.apache.http.HttpVersion;
-import org.apache.http.entity.StringEntity;
-import org.apache.http.impl.DefaultHttpResponseFactory;
-import org.apache.http.message.BasicStatusLine;
-import org.onap.vid.aai.AaiOverTLSClientInterface;
-import org.onap.vid.aai.AaiResponse;
-import org.onap.vid.aai.model.AaiNodeQueryResponse;
-import org.onap.vid.aai.model.ResourceType;
-import org.onap.vid.domain.mso.ModelInfo;
-import org.onap.vid.domain.mso.RequestStatus;
-import org.onap.vid.model.serviceInstantiation.ServiceInstantiation;
-import org.onap.vid.model.serviceInstantiation.VfModule;
-import org.onap.vid.model.serviceInstantiation.Vnf;
+import org.onap.vid.aai.AaiClientInterface;
+import org.onap.vid.aai.ExceptionWithRequestInfo;
+import org.onap.vid.model.Action;
+import org.onap.vid.model.serviceInstantiation.*;
import org.onap.vid.mso.RestObject;
+import org.onap.vid.mso.model.ModelInfo;
import org.onap.vid.mso.rest.AsyncRequestStatus;
+import org.onap.vid.mso.rest.RequestStatus;
+import org.onap.vid.utils.TimeUtils;
+import org.springframework.http.HttpMethod;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.togglz.core.manager.FeatureManager;
import javax.inject.Inject;
-import java.io.UnsupportedEncodingException;
+import java.time.ZonedDateTime;
import java.util.*;
+import static java.util.Collections.emptyMap;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
@@ -65,6 +38,14 @@ public class AsyncInstantiationBaseTest extends AbstractTestNGSpringContextTests
public static final String TENANT_NAME = "USP-SIP-IC-24335-T-01";
public static final String AIC_ZONE_ID = "NFT1";
public static final String AIC_ZONE_NAME = "NFTJSSSS-NFT1";
+ public static final String TEST_API = "GR_API";
+ public static final String SERVICE_MODEL_VERSION_ID = "3c40d244-808e-42ca-b09a-256d83d19d0a";
+ public static final String VF_MODULE_0_MODEL_CUSTOMIZATION_NAME = "a25e8e8c-58b8-4eec-810c-97dcc1f5cb7f";
+ public static final String VF_MODULE_1_MODEL_CUSTOMIZATION_NAME = "72d9d1cd-f46d-447a-abdb-451d6fb05fa8";
+ public static final String VF_MODULE_0_MODEL_VERSION_ID = "4c75f813-fa91-45a4-89d0-790ff5f1ae79";
+ public static final String VF_MODULE_1_MODEL_VERSION_ID = "56e2b103-637c-4d1a-adc8-3a7f4a6c3240";
+ public static final String VNF_NAME = "vmxnjr001";
+ public static final String VNF_GROUP_NAME = "VNF_GROUP_NAME";
protected HashMap<String, String> instanceParamsMapWithoutParams;
protected HashMap<String, String> vfModuleInstanceParamsMapWithParamsToRemove;
@@ -74,34 +55,53 @@ public class AsyncInstantiationBaseTest extends AbstractTestNGSpringContextTests
protected FeatureManager featureManager;
@Inject
- protected AaiOverTLSClientInterface aaiClient;
+ protected AaiClientInterface aaiClient;
+
+ @Inject
+ protected CloudOwnerService cloudOwnerService;
+
+ public ServiceInstantiation generateMockMacroServiceInstantiationPayload(boolean isPause, Map<String, Vnf> vnfs, int bulkSize, boolean isUserProvidedNaming, String projectName, boolean rollbackOnFailure) {
+ return generateMockServiceInstantiationPayload(isPause, vnfs, Collections.EMPTY_MAP, Collections.EMPTY_MAP, bulkSize, isUserProvidedNaming, projectName, rollbackOnFailure, false, null, Action.Create, null);
+ }
- public ServiceInstantiation generateMockServiceInstantiationPayload(boolean isPause, Map<String, Vnf> vnfs, int bulkSize, boolean isUserProvidedNaming, String projectName, boolean rollbackOnFailure) {
+ public ServiceInstantiation generateMockALaCarteServiceInstantiationPayload(boolean isPause, Map<String, Vnf> vnfs, Map<String, Network> networks, Map<String, InstanceGroup> vnfGroups, int bulkSize, boolean isUserProvidedNaming, String projectName, boolean rollbackOnFailure, String testApi) {
+ return generateMockServiceInstantiationPayload(isPause, vnfs, networks, vnfGroups, bulkSize, isUserProvidedNaming, projectName, rollbackOnFailure, true, testApi, Action.Create, null);
+ }
+
+ public ServiceInstantiation generateMockALaCarteServiceDeletionPayload(boolean isPause, Map<String, Vnf> vnfs, Map<String, Network> networks, Map<String, InstanceGroup> vnfGroups, int bulkSize, boolean isUserProvidedNaming, String projectName, boolean rollbackOnFailure, String testApi, String instanceId) {
+ return generateMockServiceInstantiationPayload(isPause, vnfs, networks, vnfGroups, bulkSize, isUserProvidedNaming, projectName, rollbackOnFailure, true, testApi, Action.Delete, instanceId);
+ }
+ private ServiceInstantiation generateMockServiceInstantiationPayload(boolean isPause, Map<String, Vnf> vnfs, Map<String, Network> networks, Map<String, InstanceGroup> vnfGroups, int bulkSize, boolean isUserProvidedNaming, String projectName, boolean rollbackOnFailure, boolean isAlacarte, String testApi, Action action, String instanceId) {
ModelInfo modelInfo = createModelInfo();
List<Map<String,String>> instanceParams = createInstanceParams();
- return new ServiceInstantiation (
- modelInfo,
+ return new ServiceInstantiation ( modelInfo,
AsyncInstantiationBusinessLogicTest.OWNING_ENTITY_ID,
AsyncInstantiationBusinessLogicTest.PACKET_CORE,
projectName,
AsyncInstantiationBusinessLogicTest.SUBSCRIBER_ID,
AsyncInstantiationBusinessLogicTest.SUBSCRIBER_NAME,
AsyncInstantiationBusinessLogicTest.PRODUCT_FAMILY_ID,
- isUserProvidedNaming ? AsyncInstantiationBusinessLogicTest.INSTANCE_NAME : "" ,
- isUserProvidedNaming,
+ isUserProvidedNaming ? AsyncInstantiationBusinessLogicTest.INSTANCE_NAME : null,
AsyncInstantiationBusinessLogicTest.SUBSCRIPTION_SERVICE_TYPE,
AsyncInstantiationBusinessLogicTest.LCP_CLOUD_REGION_ID,
+ null,
AsyncInstantiationBusinessLogicTest.A6CA3EE0394ADE9403F075DB23167E,
AsyncInstantiationBusinessLogicTest.TENANT_NAME,
AsyncInstantiationBusinessLogicTest.AIC_ZONE_ID,
AsyncInstantiationBusinessLogicTest.AIC_ZONE_NAME,
vnfs,
+ networks,
+ vnfGroups,
instanceParams,
isPause,
bulkSize,
- rollbackOnFailure
+ rollbackOnFailure,
+ isAlacarte,
+ testApi,
+ instanceId,
+ action.name()
);
}
@@ -114,30 +114,58 @@ public class AsyncInstantiationBaseTest extends AbstractTestNGSpringContextTests
return instanceParams;
}
- private VfModule createVfModule(String modelName, String modelVersionId, String modelCustomizationId,
- List<Map<String, String>> instanceParams, String instanceName, String volumeGroupInstanceName) {
+ protected VfModule createVfModule(String modelName, String modelVersionId, String modelCustomizationId,
+ List<Map<String, String>> instanceParams, Map<String, String> supplementaryParams, String instanceName, String volumeGroupInstanceName, boolean isAlacarte) {
ModelInfo vfModuleInfo = new ModelInfo();
vfModuleInfo.setModelType("vfModule");
vfModuleInfo.setModelName(modelName);
vfModuleInfo.setModelVersionId(modelVersionId);
vfModuleInfo.setModelCustomizationId(modelCustomizationId);
- return new VfModule(vfModuleInfo , instanceName, volumeGroupInstanceName, instanceParams);
+ vfModuleInfo.setModelCustomizationName(modelName);
+
+ if (isAlacarte) {
+ vfModuleInfo.setModelInvariantId("22222222-f63c-463e-ba94-286933b895f9");
+ vfModuleInfo.setModelVersion("10.0");
+ return new VfModule(vfModuleInfo, instanceName, volumeGroupInstanceName, Action.Create.name(), "mdt1", null, "88a6ca3ee0394ade9403f075db23167e", instanceParams, supplementaryParams, false, true, null);
+ }
+
+ return new VfModule(vfModuleInfo, instanceName, volumeGroupInstanceName, Action.Create.name(), null, null, null, instanceParams, supplementaryParams, false, false, null);
}
- private ModelInfo createVnfModelInfo() {
+ protected ModelInfo createVnfModelInfo(boolean isAlacarte) {
ModelInfo vnfModelInfo = new ModelInfo();
vnfModelInfo.setModelType("vnf");
vnfModelInfo.setModelName("2016-73_MOW-AVPN-vPE-BV-L");
vnfModelInfo.setModelVersionId("7f40c192-f63c-463e-ba94-286933b895f8");
vnfModelInfo.setModelCustomizationName("2016-73_MOW-AVPN-vPE-BV-L 0");
vnfModelInfo.setModelCustomizationId("ab153b6e-c364-44c0-bef6-1f2982117f04");
+ //added two conditional fields according to MSO AID - needed only in alacarte
+ if (isAlacarte) {
+ vnfModelInfo.setModelInvariantId("11111111-f63c-463e-ba94-286933b895f9");
+ vnfModelInfo.setModelVersion("10.0");
+ }
+ return vnfModelInfo;
+ }
+
+ private ModelInfo createNetworkModelInfo(boolean isAlacarte) {
+ ModelInfo vnfModelInfo = new ModelInfo();
+ vnfModelInfo.setModelType("network");
+ vnfModelInfo.setModelName("2016-73_MOW-AVPN-vPE-BV-L");
+ vnfModelInfo.setModelVersionId("7f40c192-f63c-463e-ba94-286933b895f8");
+ vnfModelInfo.setModelCustomizationName("2016-73_MOW-AVPN-vPE-BV-L 0");
+ vnfModelInfo.setModelCustomizationId("ab153b6e-c364-44c0-bef6-1f2982117f04");
+ //added two conditional fields according to MSO AID - needed only in alacarte
+ if (isAlacarte) {
+ vnfModelInfo.setModelInvariantId("11111111-f63c-463e-ba94-286933b895f9");
+ vnfModelInfo.setModelVersion("10.0");
+ }
return vnfModelInfo;
}
private ModelInfo createModelInfo() {
ModelInfo modelInfo = new ModelInfo();
modelInfo.setModelType("service");
- modelInfo.setModelVersionId("3c40d244-808e-42ca-b09a-256d83d19d0a");
+ modelInfo.setModelVersionId(SERVICE_MODEL_VERSION_ID);
modelInfo.setModelVersion("10.0");
modelInfo.setModelInvariantId("5d48acb5-097d-4982-aeb2-f4a3bd87d31b");
modelInfo.setModelName("MOW AVPN vMX BV vPE 1 Service");
@@ -145,29 +173,68 @@ public class AsyncInstantiationBaseTest extends AbstractTestNGSpringContextTests
}
protected Map<String, Vnf> createVnfList(HashMap<String, String> vfModuleInstanceParamsMap, List vnfInstanceParams, boolean isUserProvidedNaming) {
+ return createVnfList(vfModuleInstanceParamsMap, vnfInstanceParams, isUserProvidedNaming, false);
+ }
+
+ protected Map<String, Vnf> createVnfList(HashMap<String, String> vfModuleInstanceParamsMap, List vnfInstanceParams, boolean isUserProvidedNaming, boolean isAlacarte) {
Map<String, Vnf> vnfs = new HashMap<>();
- ModelInfo vnfModelInfo = createVnfModelInfo();
+ ModelInfo vnfModelInfo = createVnfModelInfo(isAlacarte);
Map<String, Map<String, VfModule>> vfModules = new HashMap<>();
- List<Map<String, String>> instanceParams1 =ImmutableList.of((ImmutableMap.of("vmx_int_net_len", "24")));
- VfModule vfModule1 = createVfModule("201673MowAvpnVpeBvL..AVPN_base_vPE_BV..module-0", "4c75f813-fa91-45a4-89d0-790ff5f1ae79", "a25e8e8c-58b8-4eec-810c-97dcc1f5cb7f", instanceParams1, "vmxnjr001_AVPN_base_vPE_BV_base", null);
+ List<Map<String, String>> instanceParams1 = ImmutableList.of((ImmutableMap.of("vmx_int_net_len", "24")));
+ VfModule vfModule1 = createVfModule("201673MowAvpnVpeBvL..AVPN_base_vPE_BV..module-0", VF_MODULE_0_MODEL_VERSION_ID, VF_MODULE_0_MODEL_CUSTOMIZATION_NAME, instanceParams1, new HashMap<>(), (isUserProvidedNaming ? "vmxnjr001_AVPN_base_vPE_BV_base" : null), null, isAlacarte);
List<Map<String, String>> instanceParams2 = ImmutableList.of(vfModuleInstanceParamsMap);
- VfModule vfModule2 = createVfModule("201673MowAvpnVpeBvL..AVPN_vRE_BV..module-1", "56e2b103-637c-4d1a-adc8-3a7f4a6c3240", "72d9d1cd-f46d-447a-abdb-451d6fb05fa8", instanceParams2, "vmxnjr001_AVPN_base_vRE_BV_expansion", "myVgName");
+ VfModule vfModule2 = createVfModule("201673MowAvpnVpeBvL..AVPN_vRE_BV..module-1", VF_MODULE_1_MODEL_VERSION_ID, VF_MODULE_1_MODEL_CUSTOMIZATION_NAME, instanceParams2, new HashMap<>(), (isUserProvidedNaming ? "vmxnjr001_AVPN_base_vRE_BV_expansion": null), (isUserProvidedNaming ? "myVgName" : null), isAlacarte);
String vfModuleModelName = vfModule1.getModelInfo().getModelName();
vfModules.put(vfModuleModelName, new LinkedHashMap<>());
- vfModules.get(vfModuleModelName).put(vfModule1.getInstanceName(),vfModule1);
- vfModules.get(vfModuleModelName).put(vfModule2.getInstanceName(), vfModule2);
+ vfModules.get(vfModuleModelName).put(vfModuleModelName + ":001", vfModule1);
+ vfModules.get(vfModuleModelName).put(vfModuleModelName + ":002", vfModule2);
- Vnf vnf = new Vnf(vnfModelInfo, "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb", "vmxnjr001", isUserProvidedNaming,
- "platformName", "mdt1", "88a6ca3ee0394ade9403f075db23167e", vnfInstanceParams,"lineOfBusinessName" ,vfModules);
+ Vnf vnf = new Vnf(vnfModelInfo, "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb", (isUserProvidedNaming ? VNF_NAME : null), Action.Create.name(),
+ "platformName", "mdt1", null, "88a6ca3ee0394ade9403f075db23167e", vnfInstanceParams,"lineOfBusinessName" , false, null, vfModules);
- vnfs.put(vnf.getInstanceName(), vnf);
+ vnfs.put(vnf.getModelInfo().getModelName(), vnf);
return vnfs;
}
+ protected Map<String, Network> createNetworkList(List vnfInstanceParams, boolean isUserProvidedNaming, boolean isALaCarte) {
+ Map<String, Network> networks = new HashMap<>();
+ ModelInfo networkModelInfo = createNetworkModelInfo(isALaCarte);
+
+ Network network = new Network(networkModelInfo, "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb", isUserProvidedNaming ? VNF_NAME : null, Action.Create.name(),
+ "platformName", "mdt1", null, "88a6ca3ee0394ade9403f075db23167e", vnfInstanceParams,"lineOfBusinessName" , false, null);
+
+ networks.put(network.getModelInfo().getModelName(), network);
+ return networks;
+ }
+
+ protected InstanceGroup createInstanceGroup(boolean isUserProvidedNaming, Action action) {
+ ModelInfo modelInfo = new ModelInfo();
+ modelInfo.setModelType("instanceGroup");
+ modelInfo.setModelName("2016-73_MOW-AVPN-vPE-BV-L");
+ modelInfo.setModelVersionId("7f40c192-f63c-463e-ba94-286933b895f8");
+ modelInfo.setModelCustomizationName("2016-73_MOW-AVPN-vPE-BV-L 0");
+ modelInfo.setModelCustomizationId("ab153b6e-c364-44c0-bef6-1f2982117f04");
+ modelInfo.setModelInvariantId("11111111-f63c-463e-ba94-286933b895f9");
+ modelInfo.setModelVersion("10.0");
+
+ return new InstanceGroup(modelInfo, (isUserProvidedNaming ? VNF_GROUP_NAME : null), action.name(), false, null);
+ }
+
+ protected ModelInfo createServiceModelInfo() {
+ ModelInfo siModelInfo = new ModelInfo();
+ siModelInfo.setModelName("sriov");
+ siModelInfo.setModelType("service");
+ siModelInfo.setModelInvariantId("ff3514e3-5a33-55df-13ab-12abad84e7ff");
+ siModelInfo.setModelVersionId("fe6985cd-ea33-3346-ac12-ab121484a3fe");
+ siModelInfo.setModelVersion("1.0");
+
+ return siModelInfo;
+ }
+
protected void createInstanceParamsMaps() {
instanceParamsMapWithoutParams = new HashMap<>();
instanceParamsMapWithoutParams.put("availability_zone_0" , "mtpocdv-kvm-az01");
@@ -182,10 +249,11 @@ public class AsyncInstantiationBaseTest extends AbstractTestNGSpringContextTests
vnfInstanceParamsMapWithParamsToRemove.put(AsyncInstantiationBusinessLogic.PARAMS_TO_IGNORE.get(1), "should be removed");
}
- protected AsyncRequestStatus asyncRequestStatusResponse(String msoStatus) {
+ public static AsyncRequestStatus asyncRequestStatusResponse(String msoStatus) {
AsyncRequestStatus asyncRequestStatus = new AsyncRequestStatus(new AsyncRequestStatus.Request(new RequestStatus()));
asyncRequestStatus.request.requestStatus.setRequestState(msoStatus);
asyncRequestStatus.request.requestId = UUID.randomUUID().toString();
+ asyncRequestStatus.request.startTime = TimeUtils.zonedDateTimeToString(ZonedDateTime.now());
return asyncRequestStatus;
}
@@ -200,23 +268,31 @@ public class AsyncInstantiationBaseTest extends AbstractTestNGSpringContextTests
return restObject;
}
- protected void mockAaiClientAnyNameFree() throws UnsupportedEncodingException {
- when(aaiClient.searchNodeTypeByName(any(), any())).thenReturn(aaiNodeQueryResponseNameFree());
+ protected void mockAaiClientAnyNameFree() {
+ when(aaiClient.isNodeTypeExistsByName(any(), any())).thenReturn(false);
}
- protected HttpResponse<AaiNodeQueryResponse> aaiNodeQueryResponseNameFree() throws UnsupportedEncodingException {
- org.apache.http.HttpResponse response = new DefaultHttpResponseFactory().newHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, null), null);
- response.setEntity(new StringEntity(""));
-
- return HttpResponse.fallback(new AaiNodeQueryResponse(null));
+ protected ExceptionWithRequestInfo aaiNodeQueryBadResponseException() {
+ return new ExceptionWithRequestInfo(HttpMethod.GET, "url", "raw data", 500, null);
}
- protected AaiResponse<AaiNodeQueryResponse> aaiNodeQueryBadResponse() {
- return new AaiResponse<>(null,"", 404);
+ protected ServiceInstantiation generateALaCarteWithVnfsServiceInstantiationPayload() {
+ Map<String, Vnf> vnfs = createVnfList(vfModuleInstanceParamsMapWithParamsToRemove, Collections.singletonList(vnfInstanceParamsMapWithParamsToRemove) , true);
+ ServiceInstantiation serviceInstantiation = generateMockALaCarteServiceInstantiationPayload(false, vnfs, emptyMap(), emptyMap(), 1, true, PROJECT_NAME, false, "VNF_API");
+ return serviceInstantiation;
}
- protected AaiResponse<AaiNodeQueryResponse> aaiNodeQueryResponseNameUsed(ResourceType type) {
- AaiNodeQueryResponse mockAaiNodeQuery = new AaiNodeQueryResponse(ImmutableList.of(new AaiNodeQueryResponse.ResultData(type, "/some/mocked/link")));
- return new AaiResponse<>(mockAaiNodeQuery,"", 200);
+ protected ServiceInstantiation generateALaCarteUpdateWith1ExistingGroup2NewGroupsPayload() {
+ final InstanceGroup instanceGroup1 = createInstanceGroup(true, Action.None);
+ final InstanceGroup instanceGroup2 = createInstanceGroup(false, Action.Create);
+ final InstanceGroup instanceGroup3 = createInstanceGroup(true, Action.Create);
+ Map<String, InstanceGroup> groups = ImmutableMap.of(
+ "foo:001", instanceGroup1,
+ "foo:002", instanceGroup2,
+ "foo:003", instanceGroup3
+ );
+ return generateMockServiceInstantiationPayload(false, emptyMap(), emptyMap(), groups,
+ 1, true, PROJECT_NAME, false, true, "VNF_API",
+ Action.None, "1234567890");
}
}
diff --git a/vid-app-common/src/test/java/org/onap/vid/services/AsyncInstantiationBusinessLogicTest.java b/vid-app-common/src/test/java/org/onap/vid/services/AsyncInstantiationBusinessLogicTest.java
index 9711fa858..96b39bcb1 100644
--- a/vid-app-common/src/test/java/org/onap/vid/services/AsyncInstantiationBusinessLogicTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/services/AsyncInstantiationBusinessLogicTest.java
@@ -1,29 +1,96 @@
package org.onap.vid.services;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import net.javacrumbs.jsonunit.JsonAssert;
+import org.apache.commons.io.IOUtils;
+import org.hibernate.SessionFactory;
+import org.json.JSONException;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.MockitoAnnotations;
+import org.mockito.stubbing.Answer;
+import org.onap.portalsdk.core.domain.FusionObject;
+import org.onap.portalsdk.core.service.DataAccessService;
import org.onap.portalsdk.core.util.SystemProperties;
+import org.onap.vid.aai.ExceptionWithRequestInfo;
+import org.onap.vid.aai.model.ResourceType;
+import org.onap.vid.changeManagement.RequestDetailsWrapper;
import org.onap.vid.config.DataSourceConfig;
import org.onap.vid.config.MockedAaiClientAndFeatureManagerConfig;
+import org.onap.vid.exceptions.GenericUncheckedException;
+import org.onap.vid.exceptions.MaxRetriesException;
+import org.onap.vid.exceptions.OperationNotAllowedException;
+import org.onap.vid.job.Job;
+import org.onap.vid.job.Job.JobStatus;
+import org.onap.vid.job.JobAdapter;
+import org.onap.vid.job.JobType;
+import org.onap.vid.job.JobsBrokerService;
+import org.onap.vid.job.impl.JobDaoImpl;
+import org.onap.vid.job.impl.JobSharedData;
+import org.onap.vid.model.Action;
+import org.onap.vid.model.JobAuditStatus;
+import org.onap.vid.model.JobAuditStatus.SourceStatus;
+import org.onap.vid.model.NameCounter;
+import org.onap.vid.model.ServiceInfo;
+import org.onap.vid.model.serviceInstantiation.*;
+import org.onap.vid.mso.MsoOperationalEnvironmentTest;
+import org.onap.vid.mso.model.*;
+import org.onap.vid.mso.rest.AsyncRequestStatus;
+import org.onap.vid.properties.Features;
+import org.onap.vid.testUtils.TestUtils;
+import org.onap.vid.utils.DaoUtils;
+import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
+import org.testng.Assert;
+import org.testng.annotations.*;
+
+import javax.inject.Inject;
+import java.io.IOException;
+import java.lang.reflect.Method;
+import java.net.URL;
+import java.time.Instant;
+import java.time.LocalDateTime;
+import java.time.ZoneId;
+import java.util.Optional;
+import java.util.*;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+import static com.google.common.collect.Maps.newHashMap;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.contains;
+import static org.hamcrest.Matchers.*;
+import static org.hamcrest.core.Every.everyItem;
+import static org.hamcrest.core.IsEqual.equalTo;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.*;
+import static org.onap.vid.job.Job.JobStatus.*;
+import static org.testng.Assert.*;
@ContextConfiguration(classes = {DataSourceConfig.class, SystemProperties.class, MockedAaiClientAndFeatureManagerConfig.class})
public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseTest {
-/*
-TO BE FIXED
+
@Inject
private DataAccessService dataAccessService;
@Mock
- private JobAdapter jobAdapter;
+ private JobAdapter jobAdapterMock;
@Mock
- private JobsBrokerService jobsBrokerService;
-
+ private JobsBrokerService jobsBrokerServiceMock;
@Autowired
private SessionFactory sessionFactory;
- private AsyncInstantiationBusinessLogic asyncInstantiationBL;
+ private AsyncInstantiationBusinessLogicImpl asyncInstantiationBL;
private int serviceCount = 0;
@@ -36,13 +103,27 @@ TO BE FIXED
@BeforeClass
void initServicesInfoService() {
MockitoAnnotations.initMocks(this);
- asyncInstantiationBL = new AsyncInstantiationBusinessLogicImpl(dataAccessService, jobAdapter, jobsBrokerService, sessionFactory, aaiClient);
+ asyncInstantiationBL = new AsyncInstantiationBusinessLogicImpl(dataAccessService, jobAdapterMock, jobsBrokerServiceMock, sessionFactory, aaiClient, featureManager, cloudOwnerService);
createInstanceParamsMaps();
}
@BeforeMethod
void defineMocks() {
+ Mockito.reset(aaiClient);
+ Mockito.reset(jobAdapterMock);
+ Mockito.reset(jobsBrokerServiceMock);
mockAaiClientAnyNameFree();
+ enableAddCloudOwnerOnMsoRequest();
+ }
+
+ private void enableAddCloudOwnerOnMsoRequest() {
+ enableAddCloudOwnerOnMsoRequest(true);
+ }
+
+ private void enableAddCloudOwnerOnMsoRequest(boolean isActive) {
+ // always turn on the feature flag
+ when(featureManager.isActive(Features.FLAG_1810_CR_ADD_CLOUD_OWNER_TO_MSO_REQUEST)).thenReturn(isActive);
+ when(aaiClient.getCloudOwnerByCloudRegionId(anyString())).thenReturn("att-aic");
}
@BeforeMethod
@@ -187,7 +268,7 @@ TO BE FIXED
dataAccessService.saveDomainObject(jobDao, getPropsMap());
}
- @Test
+ @Test(enabled = false)
public void testServiceInfoAreOrderedAsExpected() {
int userId = 2222;
createNewTestServicesInfo(String.valueOf(userId));
@@ -196,7 +277,7 @@ TO BE FIXED
assertThat("Services aren't ordered as expected", serviceInfoListResult, equalTo(expectedOrderServiceInfo));
}
- @Test
+ @Test(enabled = false)
public void testServiceInfoAreFilteredAsExpected() {
int userId = 2222;
createNewTestServicesInfoForFilter(String.valueOf(userId));
@@ -212,29 +293,32 @@ TO BE FIXED
assertThat("Services aren't ordered filtered as expected", serviceInfoFilteredByUser, equalTo(expectedFilterByUser));
}
- @Test(dataProvider = "pauseAndInstanceParams", enabled = false) //Test is irrelevant with unique names feature
- public void createServiceInstantiationMsoRequest(Boolean isPause, HashMap<String, String> vfModuleInstanceParamsMap, List vnfInstanceParams) throws Exception {
- ServiceInstantiation serviceInstantiationPayload = generateMockServiceInstantiationPayload(isPause, createVnfList(vfModuleInstanceParamsMap, vnfInstanceParams, true));
- final URL resource = this.getClass().getResource("/payload_jsons/bulk_service_request.json");
- RequestDetailsWrapper<ServiceInstantiationRequestDetails> result =
- asyncInstantiationBL.generateServiceInstantiationRequest(null, serviceInstantiationPayload, "az2016");
- String expected = IOUtils.toString(resource, "UTF-8");
- MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
- }
-
- @Test(dataProvider = "pauseAndInstanceParams")
- public void createServiceInstantiationMsoRequestUniqueName(Boolean isPause, HashMap<String, String> vfModuleInstanceParamsMap, List vnfInstanceParams) throws Exception {
- Mockito.reset(aaiClient);
- mockAaiClientAnyNameFree();
- ServiceInstantiation serviceInstantiationPayload = generateMockServiceInstantiationPayload(isPause, createVnfList(vfModuleInstanceParamsMap, vnfInstanceParams, true));
+ @Test(enabled = false, dataProvider = "pauseAndInstanceParams")
+ public void createMacroServiceInstantiationMsoRequestUniqueName(Boolean isPause, HashMap<String, String> vfModuleInstanceParamsMap, List vnfInstanceParams) throws Exception {
+ defineMocks();
+ ServiceInstantiation serviceInstantiationPayload = generateMockMacroServiceInstantiationPayload(isPause, createVnfList(vfModuleInstanceParamsMap, vnfInstanceParams, true), 2, true, PROJECT_NAME, false);
final URL resource = this.getClass().getResource("/payload_jsons/bulk_service_request_unique_names.json");
- List<UUID> uuids = new ArrayList<>();
+ when(jobAdapterMock.createServiceInstantiationJob(any(), any(), any(), any(), anyString(), any())).thenAnswer(invocation -> {
+ Object[] args = invocation.getArguments();
+ return new MockedJob((String)args[4]);
+ });
+
+ when(jobsBrokerServiceMock.add(any(MockedJob.class))).thenAnswer((Answer<UUID>) invocation -> {
+ Object[] args = invocation.getArguments();
+ MockedJob job = (MockedJob) args[0];
+ MockedJob.putJob(job.uuid, job);
+ return job.getUuid();
+ });
+
+ when(featureManager.isActive(Features.FLAG_SHIFT_VFMODULE_PARAMS_TO_VNF)).thenReturn(true);
+
+ List<UUID> uuids = asyncInstantiationBL.pushBulkJob(serviceInstantiationPayload, "az2016");
for (int i = 0; i < 2; i++) {
- UUID currentUuid = createJobAndServiceInfo();
- uuids.add(currentUuid);
+ UUID currentUuid = uuids.get(i);
RequestDetailsWrapper<ServiceInstantiationRequestDetails> result =
- asyncInstantiationBL.generateServiceInstantiationRequest(currentUuid, serviceInstantiationPayload, "az2016");
- String unique = String.format("00%s", i + 1);
+ asyncInstantiationBL.generateMacroServiceInstantiationRequest(currentUuid, serviceInstantiationPayload,
+ MockedJob.getJob(currentUuid).getOptimisticUniqueServiceInstanceName(), "az2016");
+ String unique = i==0 ? "" : String.format("_00%s", i);
String expected = IOUtils.toString(resource, "UTF-8")
.replace("{SERVICE_UNIQENESS}", unique)
.replace("{VNF_UNIQENESS}", unique)
@@ -243,17 +327,17 @@ TO BE FIXED
.replace("{VG_UNIQUENESS}", unique);
MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
Optional<ServiceInfo> optionalServiceInfo = getJobById(currentUuid);
- assertThat(optionalServiceInfo.get().getServiceInstanceName(), equalTo("vPE_Service_" + unique));
- verifySearchNodeTypeByName(unique, "vPE_Service_", ResourceType.SERVICE_INSTANCE);
- verifySearchNodeTypeByName(unique, "vmxnjr001_", ResourceType.GENERIC_VNF);
- verifySearchNodeTypeByName(unique, "vmxnjr001_AVPN_base_vPE_BV_base_", ResourceType.VF_MODULE);
- verifySearchNodeTypeByName(unique, "vmxnjr001_AVPN_base_vRE_BV_expansion_", ResourceType.VF_MODULE);
- verifySearchNodeTypeByName(unique, "myVgName_", ResourceType.VOLUME_GROUP);
+ assertThat(optionalServiceInfo.get().getServiceInstanceName(), equalTo("vPE_Service" + unique));
+ verifySearchNodeTypeByName(unique, "vPE_Service", ResourceType.SERVICE_INSTANCE);
+ verifySearchNodeTypeByName(unique, VNF_NAME, ResourceType.GENERIC_VNF);
+ verifySearchNodeTypeByName(unique, "vmxnjr001_AVPN_base_vPE_BV_base", ResourceType.VF_MODULE);
+ verifySearchNodeTypeByName(unique, "vmxnjr001_AVPN_base_vRE_BV_expansion", ResourceType.VF_MODULE);
+ verifySearchNodeTypeByName(unique, "myVgName", ResourceType.VOLUME_GROUP);
}
}
protected void verifySearchNodeTypeByName(String unique, String resourceName, ResourceType serviceInstance) {
- verify(aaiClient, times(1)).searchNodeTypeByName(resourceName + unique, serviceInstance);
+ verify(aaiClient, times(1)).isNodeTypeExistsByName(resourceName + unique, serviceInstance);
}
private HashMap<String, Object> getPropsMap() {
@@ -262,40 +346,37 @@ TO BE FIXED
return props;
}
- @Test(enabled = false) //probably not needed with name uniqueness feature
- public void pushBulkJob_bulkWithSize3_instancesNamesAreExactlyAsExpected() {
+
+ @DataProvider
+ public static Object[][] dataProviderForInstanceNames() {
+ return new Object[][]{
+ {true, ImmutableList.of("vPE_Service", "vPE_Service_001", "vPE_Service_002")},
+ {false, ImmutableList.of("", "", "")},
+ };
+ }
+
+ @Test(enabled = false, dataProvider="dataProviderForInstanceNames")
+ public void pushBulkJob_bulkWithSize3_instancesNamesAreExactlyAsExpected(boolean isUserProvidedNaming, List<String> expectedNames) {
int bulkSize = 3;
- final ServiceInstantiation request = generateMockServiceInstantiationPayload(
+ final ServiceInstantiation request = generateMockMacroServiceInstantiationPayload(
false,
createVnfList(instanceParamsMapWithoutParams, Collections.EMPTY_LIST, true),
- bulkSize, true,PROJECT_NAME, true
+ bulkSize, isUserProvidedNaming, PROJECT_NAME, true
);
- // in "createJob()" we will probe the service, with the generated names
- final Job job = mock(Job.class);
- when(job.getStatus()).thenReturn(PENDING);
- when(jobAdapter.createJob(any(), any(), any(), any(), any())).thenReturn(job);
-
-
- final List<UUID> uuids = asyncInstantiationBL.pushBulkJob(request, "myUserId");
-
+ // in "createServiceInstantiationJob()" we will probe the service, with the generated names
+ configureMockitoWithMockedJob();
- ArgumentCaptor<ServiceInstantiation> serviceInstantiationCaptor = new ArgumentCaptor<ServiceInstantiation>();
- verify(jobAdapter, times(bulkSize)).createJob(any(), serviceInstantiationCaptor.capture(), any(), any(), any());
- assertThat(serviceInstantiationCaptor.getAllValues().stream().map(v -> v.getInstanceName()).collect(Collectors.toList()),
- containsInAnyOrder("vPE_Service_001", "vPE_Service_002", "vPE_Service_003"));
+ asyncInstantiationBL.pushBulkJob(request, "myUserId");
- assertThat(uuids, hasSize(bulkSize));
+ List<ServiceInfo> serviceInfoList = dataAccessService.getList(ServiceInfo.class, getPropsMap());
+ assertEquals(serviceInfoList.stream().map(ServiceInfo::getServiceInstanceName).collect(Collectors.toList()), expectedNames);
}
- @Test
- public void generateMockServiceInstantiationPayload_serializeBackAndForth_sourceShouldBeTheSame() throws IOException {
- ServiceInstantiation serviceInstantiationPayload = generateMockServiceInstantiationPayload(
- false,
- createVnfList(instanceParamsMapWithoutParams, ImmutableList.of(vnfInstanceParamsMapWithParamsToRemove, vnfInstanceParamsMapWithParamsToRemove), true),
- 2, false,PROJECT_NAME, false);
+ @Test(enabled = false, dataProvider = "aLaCarteAndMacroPayload")
+ public void generateMockServiceInstantiationPayload_serializeBackAndForth_sourceShouldBeTheSame(ServiceInstantiation serviceInstantiationPayload) throws IOException {
ObjectMapper mapper = new ObjectMapper();
final String asString = mapper.writeValueAsString(serviceInstantiationPayload);
@@ -305,6 +386,20 @@ TO BE FIXED
JsonAssert.assertJsonEquals(asString, asString2);
}
+ @DataProvider
+ public Object[][] aLaCarteAndMacroPayload() {
+ ServiceInstantiation macroPayload = generateMockMacroServiceInstantiationPayload(
+ false,
+ createVnfList(instanceParamsMapWithoutParams, ImmutableList.of(vnfInstanceParamsMapWithParamsToRemove, vnfInstanceParamsMapWithParamsToRemove), true),
+ 2, false,PROJECT_NAME, false);
+ ServiceInstantiation aLaCartePayload = generateALaCarteServiceInstantiationPayload();
+
+ return new Object[][]{
+ {macroPayload},
+ {aLaCartePayload}
+ };
+ }
+
public static class ServiceInfoComparator implements Comparator<ServiceInfo> {
@Override
@@ -356,13 +451,13 @@ TO BE FIXED
};
}
- private ServiceInstantiation generateMockServiceInstantiationPayload(boolean isPause, Map<String, Vnf> vnfs) {
- return generateMockServiceInstantiationPayload(isPause, vnfs, 1, true, PROJECT_NAME, false);
+ private ServiceInstantiation generateMacroMockServiceInstantiationPayload(boolean isPause, Map<String, Vnf> vnfs) {
+ return generateMockMacroServiceInstantiationPayload(isPause, vnfs, 1, true, PROJECT_NAME, false);
}
- @Test
+ @Test(enabled = false)
public void testUpdateServiceInfo_WithExistingServiceInfo_ServiceInfoIsUpdated() {
- UUID uuid = createJobAndServiceInfo();
+ UUID uuid = createFakedJobAndServiceInfo();
final String STEPH_CURRY = "Steph Curry";
asyncInstantiationBL.updateServiceInfo(uuid, x -> {
x.setServiceInstanceName(STEPH_CURRY);
@@ -378,7 +473,7 @@ TO BE FIXED
return serviceInfoList.stream().filter(x -> jobId.equals(x.getJobId())).findFirst();
}
- private UUID createJobAndServiceInfo() {
+ private UUID createFakedJobAndServiceInfo() {
UUID uuid = UUID.randomUUID();
addNewJob(uuid);
ServiceInfo serviceInfo = new ServiceInfo();
@@ -389,14 +484,14 @@ TO BE FIXED
return uuid;
}
- @Test(expectedExceptions = GenericUncheckedException.class, expectedExceptionsMessageRegExp = UPDATE_SERVICE_INFO_EXCEPTION_MESSAGE)
+ @Test(enabled = false, expectedExceptions = GenericUncheckedException.class, expectedExceptionsMessageRegExp = UPDATE_SERVICE_INFO_EXCEPTION_MESSAGE)
public void testUpdateServiceInfo_WithNonExisting_ThrowException() {
asyncInstantiationBL.updateServiceInfo(UUID.randomUUID(), x -> x.setServiceInstanceName("not matter"));
}
- @Test(expectedExceptions = GenericUncheckedException.class, expectedExceptionsMessageRegExp = UPDATE_SERVICE_INFO_EXCEPTION_MESSAGE)
+ @Test(enabled = false, expectedExceptions = GenericUncheckedException.class, expectedExceptionsMessageRegExp = UPDATE_SERVICE_INFO_EXCEPTION_MESSAGE)
public void testUpdateServiceInfo_WithDoubleServiceWithSameJobUuid_ThrowException() {
- UUID uuid = createJobAndServiceInfo();
+ UUID uuid = createFakedJobAndServiceInfo();
ServiceInfo serviceInfo = new ServiceInfo();
serviceInfo.setJobId(uuid);
dataAccessService.saveDomainObject(serviceInfo, getPropsMap());
@@ -404,36 +499,45 @@ TO BE FIXED
}
+ @DataProvider
+ public static Object[][] isPauseAndPropertyDataProvider() {
+ return new Object[][]{
+ {true, "mso.restapi.serviceInstanceAssign"},
+ {false, "mso.restapi.serviceInstanceCreate"},
+ };
+ }
+
- @Test
- public void testRequestPath_WithPauseFlagTrue_RequestPathIsAsExpected() {
- ServiceInstantiation serviceInstantiationPauseFlagTrue = generateMockServiceInstantiationPayload(true, createVnfList(instanceParamsMapWithoutParams, Collections.EMPTY_LIST, true));
+ @Test(enabled = false, dataProvider = "isPauseAndPropertyDataProvider")
+ public void testServiceInstantiationPath_RequestPathIsAsExpected(boolean isPause, String expectedProperty) {
+ ServiceInstantiation serviceInstantiationPauseFlagTrue = generateMacroMockServiceInstantiationPayload(isPause, createVnfList(instanceParamsMapWithoutParams, Collections.EMPTY_LIST, true));
String path = asyncInstantiationBL.getServiceInstantiationPath(serviceInstantiationPauseFlagTrue);
- Assert.assertEquals(path, SystemProperties.getProperty("mso.restapi.serviceInstanceAssign"));
+ Assert.assertEquals(path, SystemProperties.getProperty(expectedProperty));
}
- @Test
- public void testRequestPath_WithPauseFlagFalse_RequestPathIsAsExpected() {
- ServiceInstantiation serviceInstantiationPauseFlagFalse = generateMockServiceInstantiationPayload(false, createVnfList(instanceParamsMapWithoutParams, Collections.EMPTY_LIST, true));
- String path = asyncInstantiationBL.getServiceInstantiationPath(serviceInstantiationPauseFlagFalse);
- Assert.assertEquals(path, SystemProperties.getProperty("mso.restapi.serviceInstanceCreate"));
+ @Test(enabled = false)
+ public void testCreateVnfEndpoint_useProvidedInstanceId() {
+ String path = asyncInstantiationBL.getVnfInstantiationPath("myGreatId");
+ assertThat(path, equalTo("/serviceInstances/v7/myGreatId/vnfs"));
}
- @Test
+ @Test(enabled = false)
public void createServiceInfo_WithUserProvidedNamingFalse_ServiceInfoIsAsExpected() throws IOException {
- createServiceInfo_WithUserProvidedNamingFalse_ServiceInfoIsAsExpected(true);
+ createMacroServiceInfo_WithUserProvidedNamingFalse_ServiceInfoIsAsExpected(true);
}
- @Test
+ @Test(enabled = false)
public void createServiceInfo_WithUserProvidedNamingFalseAndNoVfmodules_ServiceInfoIsAsExpected() throws IOException {
- createServiceInfo_WithUserProvidedNamingFalse_ServiceInfoIsAsExpected(false);
+ createMacroServiceInfo_WithUserProvidedNamingFalse_ServiceInfoIsAsExpected(false);
}
- private void createServiceInfo_WithUserProvidedNamingFalse_ServiceInfoIsAsExpected(boolean withVfmodules) throws IOException {
- ServiceInstantiation serviceInstantiationPayload = generateMockServiceInstantiationPayload(true,
+ private void createMacroServiceInfo_WithUserProvidedNamingFalse_ServiceInfoIsAsExpected(boolean withVfmodules) throws IOException {
+ when(featureManager.isActive(Features.FLAG_SHIFT_VFMODULE_PARAMS_TO_VNF)).thenReturn(true);
+
+ ServiceInstantiation serviceInstantiationPayload = generateMockMacroServiceInstantiationPayload(true,
createVnfList(vfModuleInstanceParamsMapWithParamsToRemove, Collections.EMPTY_LIST, false),
1,
- false,PROJECT_NAME, true);
+ false, PROJECT_NAME, true);
URL resource;
if (withVfmodules) {
resource = this.getClass().getResource("/payload_jsons/bulk_service_request_ecomp_naming.json");
@@ -444,27 +548,183 @@ TO BE FIXED
}
RequestDetailsWrapper<ServiceInstantiationRequestDetails> result =
- asyncInstantiationBL.generateServiceInstantiationRequest(null, serviceInstantiationPayload, "az2016");
+ asyncInstantiationBL.generateMacroServiceInstantiationRequest(null, serviceInstantiationPayload, serviceInstantiationPayload.getInstanceName(), "az2016");
String expected = IOUtils.toString(resource, "UTF-8");
MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
}
- @Test
+ @Test(enabled = false)
+ public void createALaCarteService_WithUserProvidedNamingFalse_RequestDetailsIsAsExpected() throws IOException {
+ ServiceInstantiation serviceInstantiationPayload = generateMockALaCarteServiceInstantiationPayload(false,
+ newHashMap(),
+ newHashMap(),
+ newHashMap(),
+ 1,
+ false, PROJECT_NAME, true, null);
+
+ RequestDetailsWrapper<ServiceInstantiationRequestDetails> result =
+ asyncInstantiationBL.generateALaCarteServiceInstantiationRequest(null, serviceInstantiationPayload, serviceInstantiationPayload.getInstanceName(), "az2016");
+
+ URL resource = this.getClass().getResource("/payload_jsons/bulk_alacarte_service_request_naming_false.json");
+ String expected = IOUtils.toString(resource, "UTF-8");
+ MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
+ }
+
+ @Test(enabled = false)
+ public void generateALaCarteServiceInstantiationRequest_withVnfList_HappyFllow() throws IOException {
+ ServiceInstantiation serviceInstantiationPayload = generateALaCarteWithVnfsServiceInstantiationPayload();
+ RequestDetailsWrapper<ServiceInstantiationRequestDetails> result =
+ asyncInstantiationBL.generateALaCarteServiceInstantiationRequest(null, serviceInstantiationPayload, serviceInstantiationPayload.getInstanceName(), "az2016");
+
+ String serviceExpected = IOUtils.toString(this.getClass().getResource("/payload_jsons/bulk_alacarte_service_request.json"), "UTF-8");
+ MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(serviceExpected, result);
+ }
+
+ @Test(enabled = false, dataProvider = "createVnfParameters")
+ public void createVnfRequestDetails_detailsAreAsExpected(boolean isFlagAddCloudOwnerActive, boolean isUserProvidedNaming, String file) throws IOException {
+
+ final List<Vnf> vnfList = new ArrayList<>(createVnfList(new HashMap<>(), null, isUserProvidedNaming, true).values());
+ ModelInfo siModelInfo = createServiceModelInfo();
+ String serviceInstanceId = "aa3514e3-5a33-55df-13ab-12abad84e7aa";
+
+ //we validate that the asyncInstantiationBL call to getUniqueName by simulate that aai retrun that original
+ //vnf name is used, and only next picked name is free.
+ Mockito.reset(aaiClient);
+ mockAaiClientAaiStatusOK();
+ when(aaiClient.isNodeTypeExistsByName(eq(VNF_NAME), eq(ResourceType.GENERIC_VNF))).thenReturn(true);
+ when(aaiClient.isNodeTypeExistsByName(eq(VNF_NAME+"_001"), eq(ResourceType.GENERIC_VNF))).thenReturn(false);
+ enableAddCloudOwnerOnMsoRequest(isFlagAddCloudOwnerActive);
+
+ String expected = IOUtils.toString(this.getClass().getResource(file), "UTF-8");
+ final RequestDetailsWrapper<VnfInstantiationRequestDetails> result = asyncInstantiationBL.generateVnfInstantiationRequest(vnfList.get(0), siModelInfo, serviceInstanceId, "pa0916");
+ MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
+ }
+
+ @DataProvider
+ public static Object[][] createVnfParameters() {
+ return new Object[][]{
+ {true, true, "/payload_jsons/bulk_vnf_request.json"},
+ {false, true, "/payload_jsons/bulk_vnf_request_without_cloud_owner.json"},
+ {true, false, "/payload_jsons/bulk_vnf_request_without_instance_name.json"},
+ };
+ }
+
+ @DataProvider
+ public static Object[][] vfModuleRequestDetails(Method test) {
+ return new Object[][]{
+ {"cc3514e3-5a33-55df-13ab-12abad84e7cc", true, "/payload_jsons/vfmodule_instantiation_request.json"},
+ {null, true, "/payload_jsons/vfmodule_instantiation_request_without_volume_group.json"},
+ {null, false, "/payload_jsons/vfmodule_instantiation_request_without_instance_name.json"}
+ };
+ }
+
+ @Test(enabled = false, dataProvider = "vfModuleRequestDetails")
+ public void createVfModuleRequestDetails_detailsAreAsExpected(String volumeGroupInstanceId, boolean isUserProvidedNaming, String fileName) throws IOException {
+
+ ModelInfo siModelInfo = createServiceModelInfo();
+ ModelInfo vnfModelInfo = createVnfModelInfo(true);
+ List<Map<String, String>> instanceParams = ImmutableList.of(ImmutableMap.of("vmx_int_net_len", "24",
+ "vre_a_volume_size_0" , "120"));
+ Map<String, String> supplementaryParams = ImmutableMap.of("vre_a_volume_size_0" , "100",
+ "availability_zone_0" , "mtpocdv-kvm-az01");
+ VfModule vfModule = createVfModule("201673MowAvpnVpeBvL..AVPN_vRE_BV..module-1", "56e2b103-637c-4d1a-adc8-3a7f4a6c3240",
+ "72d9d1cd-f46d-447a-abdb-451d6fb05fa8", instanceParams, supplementaryParams,
+ (isUserProvidedNaming ? "vmxnjr001_AVPN_base_vRE_BV_expansion": null), "myVgName", true);
+
+ String serviceInstanceId = "aa3514e3-5a33-55df-13ab-12abad84e7aa";
+ String vnfInstanceId = "bb3514e3-5a33-55df-13ab-12abad84e7bb";
+
+ Mockito.reset(aaiClient);
+ mockAaiClientAaiStatusOK();
+ enableAddCloudOwnerOnMsoRequest();
+ when(aaiClient.isNodeTypeExistsByName(eq("vmxnjr001_AVPN_base_vRE_BV_expansion"), eq(ResourceType.VF_MODULE))).thenReturn(false);
+
+ String expected = IOUtils.toString(this.getClass().getResource(fileName), "UTF-8");
+ final RequestDetailsWrapper<VfModuleInstantiationRequestDetails> result = asyncInstantiationBL.generateVfModuleInstantiationRequest(
+ vfModule, siModelInfo, serviceInstanceId,
+ vnfModelInfo, vnfInstanceId, volumeGroupInstanceId, "pa0916");
+ MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
+ }
+
+ @DataProvider
+ public static Object[][] expectedAggregatedParams() {
+ return new Object[][]{
+ {ImmutableMap.of("a", "b", "c", "d"), ImmutableMap.of("e", "f", "g", "h"), ImmutableList.of(ImmutableMap.of("c", "d", "a", "b", "e", "f", "g", "h"))},
+ {ImmutableMap.of("a", "b", "c", "g"), ImmutableMap.of("c", "d", "e", "f"), ImmutableList.of(ImmutableMap.of("a", "b", "c", "d", "e", "f"))},
+ {ImmutableMap.of(), ImmutableMap.of("c", "d", "e", "f"), ImmutableList.of(ImmutableMap.of("c", "d", "e", "f"))},
+ {ImmutableMap.of("a", "b", "c", "g"), ImmutableMap.of(), ImmutableList.of(ImmutableMap.of("a", "b", "c", "g"))},
+ {ImmutableMap.of(), ImmutableMap.of(), ImmutableList.of()},
+ {null, ImmutableMap.of(), ImmutableList.of()},
+ {ImmutableMap.of(), null, ImmutableList.of()},
+ };
+ }
+
+ @Test(enabled = false, dataProvider = "expectedAggregatedParams")
+ public void testAggregateInstanceParamsAndSuppFile(Map<String, String> instanceParams, Map<String, String> suppParams, List<VfModuleInstantiationRequestDetails.UserParamMap<String, String>> expected) {
+ List<VfModuleInstantiationRequestDetails.UserParamMap<String, String>> aggParams = ((AsyncInstantiationBusinessLogicImpl)asyncInstantiationBL).aggregateAllInstanceParams(instanceParams, suppParams);
+ assertThat("Aggregated params are not as expected", aggParams, equalTo(expected));
+ }
+
+ @DataProvider
+ public static Object[][] expectedNetworkRequestDetailsParameters() {
+ return new Object[][]{
+ {true, "/payload_jsons/network_instantiation_request.json"},
+ {false, "/payload_jsons/network_instantiation_request_without_instance_name.json"}
+ };
+ }
+
+ @Test(enabled = false, dataProvider = "expectedNetworkRequestDetailsParameters")
+ public void createNetworkRequestDetails_detailsAreAsExpected(boolean isUserProvidedNaming, String filePath) throws IOException {
+
+ final List<Network> networksList = new ArrayList<>(createNetworkList(null, isUserProvidedNaming, true).values());
+ ModelInfo siModelInfo = createServiceModelInfo();
+ String serviceInstanceId = "aa3514e3-5a33-55df-13ab-12abad84e7aa";
+
+ Mockito.reset(aaiClient);
+ mockAaiClientAaiStatusOK();
+ enableAddCloudOwnerOnMsoRequest();
+ when(aaiClient.isNodeTypeExistsByName(eq(VNF_NAME), eq(ResourceType.L3_NETWORK))).thenReturn(true);
+ when(aaiClient.isNodeTypeExistsByName(eq(VNF_NAME+"_001"), eq(ResourceType.L3_NETWORK))).thenReturn(false);
+
+ String expected = IOUtils.toString(this.getClass().getResource(filePath), "UTF-8");
+ final RequestDetailsWrapper<NetworkInstantiationRequestDetails> result = asyncInstantiationBL.generateNetworkInstantiationRequest(networksList.get(0), siModelInfo, serviceInstanceId, "pa0916");
+ MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
+ }
+
+ @Test(enabled = false)
+ public void createInstanceGroupRequestDetails_detailsAreAsExpected() throws IOException {
+
+ final InstanceGroup instanceGroup = createInstanceGroup(true, Action.Create);
+ ModelInfo siModelInfo = createServiceModelInfo();
+ String serviceInstanceId = "aa3514e3-5a33-55df-13ab-12abad84e7aa";
+
+ Mockito.reset(aaiClient);
+ mockAaiClientAaiStatusOK();
+ enableAddCloudOwnerOnMsoRequest();
+ when(aaiClient.isNodeTypeExistsByName(eq(VNF_GROUP_NAME), eq(ResourceType.INSTANCE_GROUP))).thenReturn(true);
+ when(aaiClient.isNodeTypeExistsByName(eq(VNF_GROUP_NAME+"_001"), eq(ResourceType.INSTANCE_GROUP))).thenReturn(false);
+
+ String expected = IOUtils.toString(this.getClass().getResource("/payload_jsons/instance_group_instantiation_request.json"), "UTF-8");
+ final RequestDetailsWrapper<InstanceGroupInstantiationRequestDetails> result = asyncInstantiationBL.generateInstanceGroupInstantiationRequest(instanceGroup, siModelInfo, serviceInstanceId, "az2018");
+ MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
+ }
+
+ @Test(enabled = false)
public void checkIfNullProjectNameSentToMso(){
- ServiceInstantiation serviceInstantiationPayload = generateMockServiceInstantiationPayload(true,
+ ServiceInstantiation serviceInstantiationPayload = generateMockMacroServiceInstantiationPayload(true,
createVnfList(vfModuleInstanceParamsMapWithParamsToRemove, Collections.EMPTY_LIST, false),
1,
false,null,false);
RequestDetailsWrapper<ServiceInstantiationRequestDetails> result =
- asyncInstantiationBL.generateServiceInstantiationRequest(null, serviceInstantiationPayload, "az2016");
+ asyncInstantiationBL.generateMacroServiceInstantiationRequest(null, serviceInstantiationPayload, serviceInstantiationPayload.getInstanceName(), "az2016");
JsonNode jsonNode = new ObjectMapper().valueToTree(result.requestDetails);
Assert.assertTrue(jsonNode.get("project").isNull());
- serviceInstantiationPayload = generateMockServiceInstantiationPayload(true,
+ serviceInstantiationPayload = generateMockMacroServiceInstantiationPayload(true,
createVnfList(vfModuleInstanceParamsMapWithParamsToRemove, Collections.EMPTY_LIST, false),
1,
false,"not null",false);
- result = asyncInstantiationBL.generateServiceInstantiationRequest(null, serviceInstantiationPayload, "az2016");
+ result = asyncInstantiationBL.generateMacroServiceInstantiationRequest(null, serviceInstantiationPayload, serviceInstantiationPayload.getInstanceName(), "az2016");
jsonNode = new ObjectMapper().valueToTree(result.requestDetails);
Assert.assertTrue(jsonNode.get("project").get("projectName").asText().equalsIgnoreCase("not null"));
@@ -472,19 +732,40 @@ TO BE FIXED
}
- @Test
- public void pushBulkJob_verifyCreatedDateBehavior_createdDateIsTheSameForAllServicesInSameBulk() {
+ @Test(enabled = false)
+ public void pushBulkJob_macroServiceverifyCreatedDateBehavior_createdDateIsTheSameForAllServicesInSameBulk() {
LocalDateTime startTestDate = LocalDateTime.now().withNano(0);
- final ServiceInstantiation request = generateMockServiceInstantiationPayload(
+ final ServiceInstantiation request = generateMockMacroServiceInstantiationPayload(
false,
createVnfList(instanceParamsMapWithoutParams, Collections.EMPTY_LIST, true),
100, true,PROJECT_NAME, true
);
- // in "createJob()" we will probe the service, with the generated names
- final Job job = mock(Job.class);
- when(job.getStatus()).thenReturn(PENDING);
- when(jobAdapter.createJob(any(), any(), any(), any(), any())).thenReturn(job);
+ pushJobAndAssertDates(startTestDate, request);
+ }
+
+ @Test(enabled = false)
+ public void whenCreateServiceInfo_thenModelId_isModelVersionId() {
+ ServiceInfo serviceInfo = asyncInstantiationBL.createServiceInfo("userID",
+ generateALaCarteWithVnfsServiceInstantiationPayload(),
+ UUID.randomUUID(),
+ UUID.randomUUID(),
+ new Date(),
+ "myName", ServiceInfo.ServiceAction.INSTANTIATE);
+ assertEquals(SERVICE_MODEL_VERSION_ID, serviceInfo.getServiceModelId());
+
+ }
+
+ @Test(enabled = false)
+ public void pushBulkJob_aLaCarteServiceverifyCreatedDateBehavior_createdDateIsTheSameForAllServicesInSameBulk() {
+ LocalDateTime startTestDate = LocalDateTime.now().withNano(0);
+ final ServiceInstantiation request = generateALaCarteServiceInstantiationPayload();
+ pushJobAndAssertDates(startTestDate, request);
+ }
+
+ protected void pushJobAndAssertDates(LocalDateTime startTestDate, ServiceInstantiation request) {
+ // in "createServiceInstantiationJob()" we will probe the service, with the generated names
+ configureMockitoWithMockedJob();
asyncInstantiationBL.pushBulkJob(request, "myUserId");
List<ServiceInfo> serviceInfoList = dataAccessService.getList(ServiceInfo.class, getPropsMap());
@@ -502,6 +783,13 @@ TO BE FIXED
assertFalse(creationDate.isAfter(endTestDate));
}
+ protected void configureMockitoWithMockedJob() {
+ Mockito.reset(jobAdapterMock);
+ final Job job = mock(Job.class);
+ when(job.getStatus()).thenReturn(PENDING);
+ when(jobAdapterMock.createServiceInstantiationJob(any(), any(), any(), any(), any(), any())).thenReturn(job);
+ }
+
@DataProvider
public static Object[][] msoToJobStatusDataProvider() {
return new Object[][]{
@@ -519,8 +807,8 @@ TO BE FIXED
};
}
- @Test(dataProvider = "msoToJobStatusDataProvider")
- void whenGetStatusFromMso_calcRightJobStatus(String msoStatus, Job.JobStatus expectedJobStatus) {
+ @Test(enabled = false, dataProvider = "msoToJobStatusDataProvider")
+ public void whenGetStatusFromMso_calcRightJobStatus(String msoStatus, Job.JobStatus expectedJobStatus) {
AsyncRequestStatus asyncRequestStatus = asyncRequestStatusResponse(msoStatus);
assertThat(asyncInstantiationBL.calcStatus(asyncRequestStatus), equalTo(expectedJobStatus));
}
@@ -564,7 +852,7 @@ TO BE FIXED
}
- @Test(dataProvider = "auditStatuses")
+ @Test(enabled = false, dataProvider = "auditStatuses")
public void givenSomeAuditStatuses_getStatusesOfSpecificSourceAndJobId_getSortedResultsMatchingToParameters(SourceStatus expectedSource, String [] expectedSortedStatuses){
UUID jobUuid = UUID.randomUUID();
List<JobAuditStatus> auditStatusList = com.google.common.collect.ImmutableList.of(
@@ -582,7 +870,7 @@ TO BE FIXED
- @Test
+ @Test(enabled = false)
public void addSomeVidStatuses_getThem_verifyGetInsertedWithoutDuplicates(){
ImmutableList<JobStatus> statusesToBeInserted = ImmutableList.of(PENDING, IN_PROGRESS, IN_PROGRESS, COMPLETED);
UUID jobUuid = UUID.randomUUID();
@@ -627,7 +915,7 @@ TO BE FIXED
};
}
- @Test(dataProvider = "msoAuditStatuses")
+ @Test(enabled = false, dataProvider = "msoAuditStatuses")
public void addSomeMsoStatuses_getThem_verifyGetInsertedWithoutDuplicates(UUID jobUuid, ImmutableList<JobAuditStatus> msoStatuses, ImmutableList<String> expectedStatuses, String assertionReason) {
msoStatuses.forEach(status -> {
asyncInstantiationBL.auditMsoStatus(status.getJobId(), status.getJobStatus(), status.getRequestId() != null ? status.getRequestId().toString() : null, status.getAdditionalInfo());
@@ -636,7 +924,7 @@ TO BE FIXED
assertThat( assertionReason, statusesFromDB, is(expectedStatuses));
}
- @Test
+ @Test(enabled = false)
public void addSameStatusOfVidAndMso_verifyThatBothWereAdded(){
UUID jobUuid = UUID.randomUUID();
JobStatus sameStatus = IN_PROGRESS;
@@ -650,45 +938,35 @@ TO BE FIXED
assertThat(list,everyItem(hasProperty("jobStatus", is(sameStatus.toString()))));
}
- @Test
- public void verifyAsyncRequestStatus_canBeReadFromSample() throws IOException {
- String body = "{" +
- " \"request\": {" +
- " \"requestId\": \"c0011670-0e1a-4b74-945d-8bf5aede1d9c\"," +
- " \"startTime\": \"Mon, 11 Dec 2017 07:27:49 GMT\"," +
- " \"requestScope\": \"service\"," +
- " \"requestType\": \"createInstance\"," +
- " \"instanceReferences\": {" +
- " \"serviceInstanceId\": \"f8791436-8d55-4fde-b4d5-72dd2cf13cfb\"," +
- " \"serviceInstanceName\": \"asdfasdf234234asdf\"," +
- " \"requestorId\": \"il883e\"" +
- " }," +
- " \"requestStatus\": {" +
- " \"requestState\": \"COMPLETE\"," +
- " \"statusMessage\": \"Service Instance was created successfully.\"," +
- " \"percentProgress\": 100," +
- " \"finishTime\": \"Mon, 11 Dec 2017 07:27:53 GMT\"" +
- " }" +
- " }" +
- "}";
- ObjectMapper objectMapper = new ObjectMapper();
- AsyncRequestStatus asyncRequestStatus = objectMapper.readValue(body, AsyncRequestStatus.class);
- assertThat(asyncRequestStatus.request.requestStatus.getRequestState(), equalTo("COMPLETE"));
+ @DataProvider
+ public static Object[][] msoRequestStatusFiles(Method test) {
+ return new Object[][]{
+ {"/responses/mso/orchestrationRequestsServiceInstance.json"},
+ {"/responses/mso/orchestrationRequestsVnf.json"},
+ {"/responses/mso/orchestrationRequestsMockedMinimalResponse.json"}
+ };
+ }
+ @Test(enabled = false, dataProvider="msoRequestStatusFiles")
+ public void verifyAsyncRequestStatus_canBeReadFromSample(String msoResponseFile) throws IOException {
+ AsyncRequestStatus asyncRequestStatus = TestUtils.readJsonResourceFileAsObject(
+ msoResponseFile,
+ AsyncRequestStatus.class);
+ assertThat(asyncRequestStatus.request.requestStatus.getRequestState(), equalTo("COMPLETE"));
}
- @Test
+ @Test(enabled = false)
public void deleteJobInfo_pending_deleted() {
- doNothing().when(jobsBrokerService).delete(any());
+ doNothing().when(jobsBrokerServiceMock).delete(any());
UUID uuid = createServicesInfoWithDefaultValues(PENDING);
asyncInstantiationBL.deleteJob(uuid);
assertNotNull(asyncInstantiationBL.getServiceInfoByJobId(uuid).getDeletedAt(), "service info wasn't deleted");
}
- @Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = DELETE_SERVICE_INFO_STATUS_EXCEPTION_MESSAGE)
+ @Test(enabled = false, expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = DELETE_SERVICE_INFO_STATUS_EXCEPTION_MESSAGE)
public void deleteJobInfo_notAllowdStatus_shouldSendError() {
UUID uuid = createServicesInfoWithDefaultValues(COMPLETED);
- doThrow(new IllegalStateException(DELETE_SERVICE_INFO_STATUS_EXCEPTION_MESSAGE)).when(jobsBrokerService).delete(any());
+ doThrow(new IllegalStateException(DELETE_SERVICE_INFO_STATUS_EXCEPTION_MESSAGE)).when(jobsBrokerServiceMock).delete(any());
try {
asyncInstantiationBL.deleteJob(uuid);
} catch (Exception e) {
@@ -704,7 +982,7 @@ TO BE FIXED
.map(v -> new Object[]{v}).collect(Collectors.toList()).toArray(new Object[][]{});
}
- @Test(dataProvider = "jobStatusesFinal")
+ @Test(enabled = false, dataProvider = "jobStatusesFinal")
public void whenHideService_theServiceNotReturnedInServiceList(JobStatus jobStatus) {
UUID uuidToHide = createServicesInfoWithDefaultValues(jobStatus);
UUID uuidToShown = createServicesInfoWithDefaultValues(jobStatus);
@@ -729,7 +1007,7 @@ TO BE FIXED
.map(v -> new Object[]{v}).collect(Collectors.toList()).toArray(new Object[][]{});
}
- @Test( dataProvider = "jobStatusesNotFinal",
+ @Test(enabled = false, dataProvider = "jobStatusesNotFinal",
expectedExceptions = OperationNotAllowedException.class,
expectedExceptionsMessageRegExp = "jobId.*Service status does not allow hide service, status = .*")
public void hideServiceInfo_notAllowedStatus_shouldSendError(JobStatus jobStatus) {
@@ -742,14 +1020,14 @@ TO BE FIXED
}
}
- @Test
+ @Test(enabled = false)
public void whenUseGetCounterInMultiThreads_EachThreadGetDifferentCounter() throws InterruptedException {
int SIZE = 200;
ExecutorService executor = Executors.newFixedThreadPool(SIZE);
- List<Callable<Integer>> tasks = IntStream.rangeClosed(1, SIZE)
+ List<Callable<Integer>> tasks = IntStream.rangeClosed(0, SIZE)
.mapToObj(x-> ((Callable<Integer>)() -> asyncInstantiationBL.getCounterForName("a")))
.collect(Collectors.toList());
- Set<Integer> expectedResults = IntStream.rangeClosed(1, SIZE).boxed().collect(Collectors.toSet());
+ Set<Integer> expectedResults = IntStream.rangeClosed(0, SIZE).boxed().collect(Collectors.toSet());
executor.invokeAll(tasks)
.forEach(future -> {
try {
@@ -763,23 +1041,23 @@ TO BE FIXED
assertThat(expectedResults.size(), is(0));
}
- @Test
+ @Test(enabled = false)
public void whenUseGetCounterForSameName_numbersReturnedByOrder() {
String name = UUID.randomUUID().toString();
int SIZE=10;
- for (int i=1; i<=SIZE; i++) {
+ for (int i=0; i<SIZE; i++) {
assertThat(asyncInstantiationBL.getCounterForName(name), is(i));
}
}
- @Test
+ @Test(enabled = false)
public void whenNamedInUsedInAai_getNextNumber() {
String name = someCommonStepsAndGetName();
ResourceType type = ResourceType.GENERIC_VNF;
- when(aaiClient.searchNodeTypeByName(name+"_001", type)).thenReturn(aaiNodeQueryResponseNameUsed(type));
- when(aaiClient.searchNodeTypeByName(name+"_002", type)).thenReturn(aaiNodeQueryResponseNameFree());
- assertThat(asyncInstantiationBL.getUniqueName(name, type), equalTo(name+"_002"));
+ when(aaiClient.isNodeTypeExistsByName(name, type)).thenReturn(true);
+ when(aaiClient.isNodeTypeExistsByName(name+"_001", type)).thenReturn(false);
+ assertThat(asyncInstantiationBL.getUniqueName(name, type), equalTo(name+"_001"));
}
private String someCommonStepsAndGetName() {
@@ -788,32 +1066,335 @@ TO BE FIXED
}
private void mockAaiClientAaiStatusOK() {
- when(aaiClient.searchNodeTypeByName(eq(AsyncInstantiationBusinessLogicImpl.NAME_FOR_CHECK_AAI_STATUS), any())).thenReturn(aaiNodeQueryResponseNameFree());
+ when(aaiClient.isNodeTypeExistsByName(eq(AsyncInstantiationBusinessLogicImpl.NAME_FOR_CHECK_AAI_STATUS), any())).thenReturn(false);
}
- @Test(expectedExceptions=InvalidAAIResponseException.class)
+ @Test(enabled = false, expectedExceptions=ExceptionWithRequestInfo.class)
public void whenAaiBadResponseCode_throwInvalidAAIResponseException() {
String name = someCommonStepsAndGetName();
ResourceType type = ResourceType.SERVICE_INSTANCE;
- when(aaiClient.searchNodeTypeByName(name+"_001", type)).thenReturn(aaiNodeQueryBadResponse());
+ when(aaiClient.isNodeTypeExistsByName(name, type)).thenThrow(aaiNodeQueryBadResponseException());
asyncInstantiationBL.getUniqueName(name, type);
}
- @Test(expectedExceptions=MaxRetriesException.class)
+ @Test(enabled = false, expectedExceptions=MaxRetriesException.class)
public void whenAaiAlwaysReturnNameUsed_throwInvalidAAIResponseException() {
String name = someCommonStepsAndGetName();
ResourceType type = ResourceType.VF_MODULE;
- when(aaiClient.searchNodeTypeByName(any(), eq(type))).thenReturn(aaiNodeQueryResponseNameUsed(type));
+ when(aaiClient.isNodeTypeExistsByName(any(), eq(type))).thenReturn(true);
asyncInstantiationBL.setMaxRetriesGettingFreeNameFromAai(10);
asyncInstantiationBL.getUniqueName(name, type);
}
- @Test
+ @Test(enabled = false)
public void testFormattingOfNameAndCounter() {
AsyncInstantiationBusinessLogicImpl bl = (AsyncInstantiationBusinessLogicImpl) asyncInstantiationBL;
+ assertThat(bl.formatNameAndCounter("x", 0), equalTo("x"));
assertThat(bl.formatNameAndCounter("x", 3), equalTo("x_003"));
assertThat(bl.formatNameAndCounter("x", 99), equalTo("x_099"));
assertThat(bl.formatNameAndCounter("x", 100), equalTo("x_100"));
assertThat(bl.formatNameAndCounter("x", 1234), equalTo("x_1234"));
- }*/
+ }
+
+ @Test(enabled = false)
+ public void pushBulkJob_verifyAlacarteFlow_useALaCartServiceInstantiationJobType(){
+ final ServiceInstantiation request = generateALaCarteServiceInstantiationPayload();
+
+ // in "createServiceInstantiationJob()" we will probe the service, with the generated names
+ configureMockitoWithMockedJob();
+
+ ArgumentCaptor<JobType> argumentCaptor = ArgumentCaptor.forClass(JobType.class);
+ asyncInstantiationBL.pushBulkJob(request, "myUserId");
+ verify(jobAdapterMock).createServiceInstantiationJob(argumentCaptor.capture(),any(),any(),anyString(), anyString(), anyInt());
+ assertTrue(argumentCaptor.getValue().equals(JobType.ALaCarteServiceInstantiation));
+ }
+
+ @Test(enabled = false)
+ public void pushBulkJob_verifyMacroFlow_useMacroServiceInstantiationJobType(){
+ final ServiceInstantiation request = generateMacroMockServiceInstantiationPayload(false, Collections.emptyMap());
+
+ // in "createServiceInstantiationJob()" we will probe the service, with the generated names
+ configureMockitoWithMockedJob();
+
+ ArgumentCaptor<JobType> argumentCaptor = ArgumentCaptor.forClass(JobType.class);
+ asyncInstantiationBL.pushBulkJob(request, "myUserId");
+ verify(jobAdapterMock).createServiceInstantiationJob(argumentCaptor.capture(),any(),any(),anyString(), anyString(), anyInt());
+ assertTrue(argumentCaptor.getValue().equals(JobType.MacroServiceInstantiation));
+ }
+
+ @Test(enabled = false)
+ public void generateALaCarteServiceInstantiationRequest_verifyRequestIsAsExpected() throws IOException {
+ ServiceInstantiation serviceInstantiationPayload = generateALaCarteServiceInstantiationPayload();
+ final URL resource = this.getClass().getResource("/payload_jsons/bulk_alacarte_service_request.json");
+ RequestDetailsWrapper<ServiceInstantiationRequestDetails> result =
+ asyncInstantiationBL.generateALaCarteServiceInstantiationRequest(null, serviceInstantiationPayload, serviceInstantiationPayload.getInstanceName(), "az2016");
+ String expected = IOUtils.toString(resource, "UTF-8");
+ MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
+ }
+
+ @Test(enabled = false)
+ public void generateALaCarteServiceDeletionRequest_verifyRequestIsAsExpected() throws IOException {
+ final URL resource = this.getClass().getResource("/payload_jsons/bulk_alacarte_service_deletion_request.json");
+ String expected = IOUtils.toString(resource, "UTF-8");
+
+ ServiceInstantiation serviceDeletionPayload = generateALaCarteServiceDeletionPayload();
+ RequestDetailsWrapper<ServiceDeletionRequestDetails> result =
+ asyncInstantiationBL.generateALaCarteServiceDeletionRequest(null, serviceDeletionPayload, "az2016");
+
+ MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
+ }
+
+ @Test(enabled = false)
+ public void getALaCarteServiceDeletionPath_verifyPathIsAsExpected() throws IOException {
+
+ String expected = "/serviceInstantiation/v7/serviceInstances/f36f5734-e9df-4fbf-9f35-61be13f028a1";
+
+ String result = asyncInstantiationBL.getServiceDeletionPath("f36f5734-e9df-4fbf-9f35-61be13f028a1");
+
+ assertThat(expected,equalTo(result));
+ }
+
+ @Test(enabled = false)
+ public void getInstanceGroupsDeletionPath_verifyPathIsAsExpected() {
+
+ assertEquals(asyncInstantiationBL.getInstanceGroupDeletePath("9aada4af-0f9b-424f-ae21-e693bd3e005b"),
+ "/serviceInstantiation/v7/instanceGroups/9aada4af-0f9b-424f-ae21-e693bd3e005b");
+ }
+
+ @DataProvider
+ public static Object[][] testBuildVnfInstanceParamsDataProvider(Method test) {
+ return new Object[][]{
+ {
+ Collections.EMPTY_LIST,
+ ImmutableList.of(
+ ImmutableList.of(ImmutableMap.of("k1","v1","k2","v2")),
+ ImmutableList.of(ImmutableMap.of("k3","v3","k2","v2"))
+ ),
+ true,
+ ImmutableList.of(ImmutableMap.of("k1","v1","k2","v2","k3","v3"))
+ },
+ {
+ ImmutableList.of(ImmutableMap.of("j1", "w1", "k1","v1", "vnf_name","w2", "vf_module_name","w3")), //vnf_name, vf_module_name are excluded
+ ImmutableList.of(
+ ImmutableList.of(ImmutableMap.of("k1","v1","k2","v2")),
+ ImmutableList.of(ImmutableMap.of("k3","v3","k2","v2")),
+ ImmutableList.of(Collections.EMPTY_MAP),
+ Collections.singletonList(null)
+ ),
+ true,
+ ImmutableList.of(ImmutableMap.of("k1","v1","k2","v2","k3","v3","j1", "w1"))
+ },
+ {
+ Collections.EMPTY_LIST,
+ Arrays.asList(null, null),
+ true,
+ Collections.EMPTY_LIST //mso is expect to empty list and not list with empty map
+ },
+ {
+ ImmutableList.of(Collections.EMPTY_MAP),
+ ImmutableList.of(
+ ImmutableList.of(Collections.EMPTY_MAP),
+ ImmutableList.of(Collections.EMPTY_MAP)
+ ),
+ true,
+ Collections.EMPTY_LIST //mso is expect to empty list and not list with empty map
+ },
+ {
+ Collections.EMPTY_LIST,
+ ImmutableList.of(
+ ImmutableList.of(ImmutableMap.of("k1","v1","k2","v2")),
+ ImmutableList.of(ImmutableMap.of("k3","v3","k2","v2"))
+ ),
+ false,
+ Collections.EMPTY_LIST //mso is expect to empty list and not list with empty map
+ },
+ {
+ ImmutableList.of(ImmutableMap.of("j1", "w1", "k1","v1", "vnf_name","w2", "vf_module_name","w3")),
+ ImmutableList.of(
+ ImmutableList.of(Collections.EMPTY_MAP)
+ ),
+ false,
+ ImmutableList.of(ImmutableMap.of("j1", "w1", "k1","v1"))
+ },
+ {
+ ImmutableList.of(ImmutableMap.of("vnf_name","w2", "vf_module_name", "w3", "j2", "w2", "j4","w4")),
+ ImmutableList.of(
+ ImmutableList.of(ImmutableMap.of("k1","v1","k2","v2")),
+ ImmutableList.of(ImmutableMap.of("k3","v3","k2","v2"))
+ ),
+ false,
+ ImmutableList.of(ImmutableMap.of("j2", "w2", "j4","w4"))
+ },
+
+ };
+ }
+
+ @Test(enabled = false, dataProvider="testBuildVnfInstanceParamsDataProvider")
+ public void testBuildVnfInstanceParams(List<Map<String, String>> currentVnfInstanceParams,
+ List<List<Map<String, String>>> vfModulesInstanceParams,
+ boolean isFeatureActive,
+ List<Map<String,String>> expectedResult){
+ when(featureManager.isActive(Features.FLAG_SHIFT_VFMODULE_PARAMS_TO_VNF)).thenReturn(isFeatureActive);
+ List<VfModuleMacro> vfModules =
+ vfModulesInstanceParams.stream().map(params-> new VfModuleMacro(new ModelInfo(), null, null, params)).collect(Collectors.toList());
+ List<Map<String,String>> actual = asyncInstantiationBL.buildVnfInstanceParams(currentVnfInstanceParams, vfModules);
+ assertThat(actual, equalTo(expectedResult));
+
+ }
+
+ @Test(enabled = false)
+ public void whenLcpRegionNotEmpty_thenCloudRegionIdOfResourceIsLegacy() {
+ String legacyCloudRegion = "legacyCloudRegion";
+ Vnf vnf = new Vnf(new ModelInfo(), null, null, Action.Create.name(), null, "anyCloudRegion", legacyCloudRegion, null, null, null, false, null, null);
+ assertThat(vnf.getLcpCloudRegionId(), equalTo(legacyCloudRegion));
+
+
+ }
+
+ @Test(enabled = false)
+ public void whenLcpRegionNotEmpty_thenCloudRegionIdOfServiceIsLegacy() {
+ String legacyCloudRegion = "legacyCloudRegion";
+ ServiceInstantiation service = new ServiceInstantiation(new ModelInfo(), null, null, null, null, null, null,
+ null, null, "anyCloudRegion", legacyCloudRegion, null, null, null, null, null, null, null, null,
+ false, 1,false, false, null, null, Action.Create.name());
+ assertThat(service.getLcpCloudRegionId(), equalTo(legacyCloudRegion));
+ }
+
+ @Test(enabled = false)
+ public void createVolumeGroup_verifyResultAsExpected() throws IOException {
+ final URL resource = this.getClass().getResource("/payload_jsons/volumegroup_instantiation_request.json");
+ VfModule vfModule = createVfModule("201673MowAvpnVpeBvL..AVPN_vRE_BV..module-1",
+ "56e2b103-637c-4d1a-adc8-3a7f4a6c3240",
+ "72d9d1cd-f46d-447a-abdb-451d6fb05fa8",
+ Collections.emptyList(),
+ Collections.emptyMap(),
+ "vmxnjr001_AVPN_base_vRE_BV_expansion",
+ "myVgName",
+ true);
+ vfModule.getModelInfo().setModelInvariantId("ff5256d2-5a33-55df-13ab-12abad84e7ff");
+ vfModule.getModelInfo().setModelVersion("1");
+ ModelInfo vnfModelInfo = createVnfModelInfo(true);
+ RequestDetailsWrapper<VolumeGroupRequestDetails> result =
+ asyncInstantiationBL.generateVolumeGroupInstantiationRequest(vfModule,
+ createServiceModelInfo(),
+ "ff3514e3-5a33-55df-13ab-12abad84e7ff",
+ vnfModelInfo,
+ "vnfInstanceId",
+ "az2016");
+ String expected = IOUtils.toString(resource, "UTF-8");
+ MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
+ }
+
+ @Test(enabled = false)
+ public void getJobTypeByRequest_verifyResultAsExpected(){
+ ServiceInstantiation service = new ServiceInstantiation(new ModelInfo(), null, null, null, null, null, null,
+ null, null, null, null, null, null, null, null, null, null, null, null,
+ false, 1,false, false, null, null, Action.Create.name());
+ JobType jobType = asyncInstantiationBL.getJobType(service) ;
+ assertThat(jobType, equalTo(JobType.MacroServiceInstantiation));
+ service = new ServiceInstantiation(new ModelInfo(), null, null, null, null, null, null,
+ null, null, null, null, null, null, null, null, null, null, null, null,
+ false, 1,false, true, null, null, Action.Create.name());
+ jobType = asyncInstantiationBL.getJobType(service);
+ assertThat(jobType, equalTo(JobType.ALaCarteServiceInstantiation));
+ service = new ServiceInstantiation(new ModelInfo(), null, null, null, null, null, null,
+ null, null, null, null, null, null, null, null, null, null, null, null,
+ false, 1,false, true, null, null, Action.Delete.name());
+ jobType = asyncInstantiationBL.getJobType(service);
+ assertThat(jobType, equalTo(JobType.ALaCarteService));
+ }
+
+ protected ServiceInstantiation generateALaCarteServiceInstantiationPayload() {
+ return generateMockALaCarteServiceInstantiationPayload(false, Collections.EMPTY_MAP, Collections.EMPTY_MAP, Collections.EMPTY_MAP, 1, true, PROJECT_NAME, false, "VNF_API");
+ }
+
+ private ServiceInstantiation generateALaCarteServiceDeletionPayload() {
+ return generateMockALaCarteServiceDeletionPayload(false, Collections.EMPTY_MAP, Collections.EMPTY_MAP, Collections.EMPTY_MAP, 1, true, PROJECT_NAME, false, "VNF_API", "1234567890");
+ }
+
+ static class MockedJob implements Job {
+
+ private static Map<UUID, MockedJob> uuidToJob = new HashMap<>();
+
+ public static void putJob(UUID uuid, MockedJob job) {
+ uuidToJob.put(uuid, job);
+ }
+
+ public static MockedJob getJob(UUID uuid) {
+ return uuidToJob.get(uuid);
+ }
+
+
+ private String optimisticUniqueServiceInstanceName;
+
+ public MockedJob(String optimisticUniqueServiceInstanceName) {
+ this.optimisticUniqueServiceInstanceName = optimisticUniqueServiceInstanceName;
+ }
+
+ private UUID uuid = UUID.randomUUID();
+
+ @Override
+ public UUID getUuid() {
+ return uuid;
+ }
+
+ @Override
+ public void setUuid(UUID uuid) {
+ this.uuid = uuid;
+ }
+
+ @Override
+ public JobStatus getStatus() {
+ return JobStatus.PENDING;
+ }
+
+ @Override
+ public void setStatus(JobStatus status) {
+
+ }
+
+ @Override
+ public Map<String, Object> getData() {
+ return null;
+ }
+
+ @Override
+ public JobSharedData getSharedData() {
+ return new JobSharedData(uuid, "", null);
+ }
+
+ @Override
+ public void setTypeAndData(JobType jobType, Map<String, Object> commandData) {
+
+ }
+
+ @Override
+ public UUID getTemplateId() {
+ return null;
+ }
+
+ @Override
+ public void setTemplateId(UUID templateId) {
+
+ }
+
+ @Override
+ public Integer getIndexInBulk() {
+ return null;
+ }
+
+ @Override
+ public void setIndexInBulk(Integer indexInBulk) {
+
+ }
+
+ @Override
+ public JobType getType() {
+ return null;
+ }
+
+ public String getOptimisticUniqueServiceInstanceName() {
+ return optimisticUniqueServiceInstanceName;
+ }
+ }
}
diff --git a/vid-app-common/src/test/java/org/onap/vid/services/AuditServiceImplTest.java b/vid-app-common/src/test/java/org/onap/vid/services/AuditServiceImplTest.java
index 3d2a20b63..a1e027f82 100644
--- a/vid-app-common/src/test/java/org/onap/vid/services/AuditServiceImplTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/services/AuditServiceImplTest.java
@@ -19,18 +19,28 @@
*/
package org.onap.vid.services;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.MockitoAnnotations.initMocks;
-
-import java.util.UUID;
import org.glassfish.grizzly.http.util.HttpStatus;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
+import org.onap.vid.model.JobAuditStatus;
+import org.onap.vid.mso.rest.AsyncRequestStatusList;
+import org.onap.vid.testUtils.TestUtils;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
+import java.io.IOException;
+import java.util.Date;
+import java.util.List;
+import java.util.UUID;
+
+import static java.util.stream.Collectors.toList;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.*;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.MockitoAnnotations.initMocks;
+
public class AuditServiceImplTest {
@Mock
private AsyncInstantiationBusinessLogic asyncInstantiationBL;
@@ -60,4 +70,20 @@ public class AuditServiceImplTest {
Mockito.anyString(),
Mockito.anyString());
}
+
+ @Test
+ public void testConvertMsoResponseStatusToJobAuditStatus_missingDateFromMso_shouldNoError() throws IOException {
+ final AsyncRequestStatusList asyncRequestStatusList = TestUtils.readJsonResourceFileAsObject("/orchestrationRequestsByServiceInstanceId.json", AsyncRequestStatusList.class);
+
+ AuditServiceImpl auditService = new AuditServiceImpl(null, null);
+
+ final List<JobAuditStatus> jobAuditStatuses = auditService.convertMsoResponseStatusToJobAuditStatus(asyncRequestStatusList.getRequestList(), "foo");
+
+ final List<Date> dates = jobAuditStatuses.stream().map(JobAuditStatus::getCreatedDate).collect(toList());
+ final List<String> statuses = jobAuditStatuses.stream().map(JobAuditStatus::getJobStatus).collect(toList());
+
+ assertThat(dates, containsInAnyOrder(notNullValue(), notNullValue(), nullValue()));
+ assertThat(statuses, containsInAnyOrder("COMPLETE", "COMPLETE", "IN_PROGRESS"));
+ }
+
}
diff --git a/vid-app-common/src/test/java/org/onap/vid/services/BulkInstantiationServiceImplTest.java b/vid-app-common/src/test/java/org/onap/vid/services/BulkInstantiationServiceImplTest.java
index 6677da357..76963facb 100644
--- a/vid-app-common/src/test/java/org/onap/vid/services/BulkInstantiationServiceImplTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/services/BulkInstantiationServiceImplTest.java
@@ -19,17 +19,6 @@
*/
package org.onap.vid.services;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.reset;
-import static org.mockito.Mockito.when;
-import static org.mockito.MockitoAnnotations.initMocks;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.UUID;
-import javax.ws.rs.NotFoundException;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.onap.vid.job.Job;
@@ -43,6 +32,14 @@ import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
+import javax.ws.rs.NotFoundException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.UUID;
+
+import static org.mockito.Mockito.*;
+import static org.mockito.MockitoAnnotations.initMocks;
+
public class BulkInstantiationServiceImplTest {
@Mock
@@ -66,23 +63,6 @@ public class BulkInstantiationServiceImplTest {
}
@Test
- public void saveBulkTest() {
- UUID uuid = UUID.randomUUID();
- Map<String, Object> bulkRequest = new HashMap<>();
- List<Job> jobList = new ArrayList<>();
- jobList.add(createJob(uuid));
- when(jobAdapter.createBulkOfJobs(bulkRequest)).thenReturn(jobList);
-
- JobBulk jobBulk = createJobBulk(jobList);
- when(jobAdapter.toModelBulk(jobList)).thenReturn(jobBulk);
-
- JobBulk result = testSubject.saveBulk(bulkRequest);
-
- Assert.assertEquals(result.getJobs().size(), jobList.size());
- Assert.assertEquals(result.getJobs().get(0).getUuid(), uuid);
- }
-
- @Test
public void getJobTest() {
UUID uuid = UUID.randomUUID();
Job job = createJob(uuid);
diff --git a/vid-app-common/src/test/java/org/onap/vid/services/ChangeManagementServiceImplTest.java b/vid-app-common/src/test/java/org/onap/vid/services/ChangeManagementServiceImplTest.java
index 00d9e1735..47411e2a2 100644
--- a/vid-app-common/src/test/java/org/onap/vid/services/ChangeManagementServiceImplTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/services/ChangeManagementServiceImplTest.java
@@ -15,7 +15,6 @@ import static org.mockito.Mockito.verify;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNull;
-@Test
public class ChangeManagementServiceImplTest {
@Mock
@@ -27,6 +26,9 @@ public class ChangeManagementServiceImplTest {
@Mock
SchedulerRestInterfaceIfc schedulerRestInterface;
+ @Mock
+ CloudOwnerService cloudOwnerService;
+
@BeforeMethod
public void initMocks(){
MockitoAnnotations.initMocks(this);
@@ -34,14 +36,14 @@ public class ChangeManagementServiceImplTest {
@Test
public void doChangeManagement_requestIsNull_returnsNull() throws Exception {
- ChangeManagementServiceImpl changeManagementService = new ChangeManagementServiceImpl(dataAccessServiceMock, msoBusinessLogicMock, schedulerRestInterface);
+ ChangeManagementServiceImpl changeManagementService = new ChangeManagementServiceImpl(dataAccessServiceMock, msoBusinessLogicMock, schedulerRestInterface, cloudOwnerService);
ResponseEntity<String> result = changeManagementService.doChangeManagement(null,"anyString");
assertNull(result);
}
@Test
public void doChangeManagement_currentRequestDetailsIsNull_returnsNull() throws Exception {
- ChangeManagementServiceImpl changeManagementService = new ChangeManagementServiceImpl(dataAccessServiceMock, msoBusinessLogicMock, schedulerRestInterface);
+ ChangeManagementServiceImpl changeManagementService = new ChangeManagementServiceImpl(dataAccessServiceMock, msoBusinessLogicMock, schedulerRestInterface, cloudOwnerService);
ChangeManagementServiceImpl changeManagementServiceSpied = Mockito.spy(changeManagementService);
Mockito.doReturn(null).when(changeManagementServiceSpied).findRequestByVnfName(Matchers.anyList(),Mockito.anyString());
@@ -59,7 +61,7 @@ public class ChangeManagementServiceImplTest {
ArgumentCaptor<RequestDetails> argumentCaptor = ArgumentCaptor.forClass(RequestDetails.class);
verify(msoBusinessLogicMock).updateVnf(argumentCaptor.capture(),Mockito.any(),Mockito.any());
- assertEquals(argumentCaptor.getValue().getVnfInstanceId(),requestDetails.getVnfInstanceId());
+ assertEquals(argumentCaptor.getValue().getVnfInstanceId(), requestDetails.getVnfInstanceId());
}
@Test
@@ -71,7 +73,7 @@ public class ChangeManagementServiceImplTest {
ArgumentCaptor<RequestDetails> argumentCaptor = ArgumentCaptor.forClass(RequestDetails.class);
verify(msoBusinessLogicMock).replaceVnf(argumentCaptor.capture(),Mockito.any(),Mockito.any());
- assertEquals(argumentCaptor.getValue().getVnfInstanceId(),requestDetails.getVnfInstanceId());
+ assertEquals(argumentCaptor.getValue().getVnfInstanceId(), requestDetails.getVnfInstanceId());
}
@Test
@@ -83,7 +85,7 @@ public class ChangeManagementServiceImplTest {
ArgumentCaptor<RequestDetails> argumentCaptor = ArgumentCaptor.forClass(RequestDetails.class);
verify(msoBusinessLogicMock).updateVnfSoftware(argumentCaptor.capture(),Mockito.any(),Mockito.any());
- assertEquals(argumentCaptor.getValue().getVnfInstanceId(),requestDetails.getVnfInstanceId());
+ assertEquals(argumentCaptor.getValue().getVnfInstanceId(), requestDetails.getVnfInstanceId());
}
@Test
@@ -95,11 +97,11 @@ public class ChangeManagementServiceImplTest {
ArgumentCaptor<RequestDetails> argumentCaptor = ArgumentCaptor.forClass(RequestDetails.class);
verify(msoBusinessLogicMock).updateVnfConfig(argumentCaptor.capture(),Mockito.any(),Mockito.any());
- assertEquals(argumentCaptor.getValue().getVnfInstanceId(),requestDetails.getVnfInstanceId());
+ assertEquals(argumentCaptor.getValue().getVnfInstanceId(), requestDetails.getVnfInstanceId());
}
private RequestDetails callChangeManagement(String requestType) throws Exception {
- ChangeManagementServiceImpl changeManagementService = new ChangeManagementServiceImpl(dataAccessServiceMock, msoBusinessLogicMock, schedulerRestInterface);
+ ChangeManagementServiceImpl changeManagementService = new ChangeManagementServiceImpl(dataAccessServiceMock, msoBusinessLogicMock, schedulerRestInterface, cloudOwnerService);
ChangeManagementServiceImpl changeManagementServiceSpied = Mockito.spy(changeManagementService);
ChangeManagementRequest updateRequest = new ChangeManagementRequest();
@@ -109,7 +111,7 @@ public class ChangeManagementServiceImplTest {
Mockito.doReturn("fakeId").when(changeManagementServiceSpied).extractServiceInstanceId(Mockito.any(),Mockito.any());
Mockito.doReturn(requestDetails).when(changeManagementServiceSpied).findRequestByVnfName(Matchers.any(),Mockito.any());
- changeManagementServiceSpied.doChangeManagement(updateRequest,"anyVnfName");
+ changeManagementServiceSpied.doChangeManagement(updateRequest, "anyVnfName");
return requestDetails;
}
diff --git a/vid-app-common/src/test/java/org/onap/vid/services/ChangeManagementServiceTest.java b/vid-app-common/src/test/java/org/onap/vid/services/ChangeManagementServiceTest.java
deleted file mode 100644
index f3df4c6a9..000000000
--- a/vid-app-common/src/test/java/org/onap/vid/services/ChangeManagementServiceTest.java
+++ /dev/null
@@ -1,29 +0,0 @@
-package org.onap.vid.services;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.onap.vid.changeManagement.ChangeManagementRequest;
-import org.onap.vid.changeManagement.ChangeManagementResponse;
-import org.springframework.http.ResponseEntity;
-
-import junit.framework.Assert;
-
-import static org.junit.Assert.*;
-
-
-public class ChangeManagementServiceTest {
- @Before
- public void setUp() throws Exception {
- }
-
- @After
- public void tearDown() throws Exception {
- }
-
- @Test
- public void doChangeManagement_requestTypeIsUpdateVnfNotFound_doUpdateAndReturnNull() throws Exception {
-
- }
-
-} \ No newline at end of file
diff --git a/vid-app-common/src/test/java/org/onap/vid/services/ChangeManagementServiceUnitTest.java b/vid-app-common/src/test/java/org/onap/vid/services/ChangeManagementServiceUnitTest.java
index d849869b0..9d11ad32a 100644
--- a/vid-app-common/src/test/java/org/onap/vid/services/ChangeManagementServiceUnitTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/services/ChangeManagementServiceUnitTest.java
@@ -29,8 +29,8 @@ import org.onap.portalsdk.core.util.SystemProperties;
import org.onap.vid.changeManagement.ChangeManagementRequest;
import org.onap.vid.changeManagement.RequestDetailsWrapper;
import org.onap.vid.client.SyncRestClient;
-import org.onap.vid.controllers.MsoConfig;
-import org.onap.vid.controllers.WebConfig;
+import org.onap.vid.controller.MsoConfig;
+import org.onap.vid.controller.WebConfig;
import org.onap.vid.model.RequestReferencesContainer;
import org.onap.vid.mso.MsoBusinessLogic;
import org.onap.vid.mso.MsoInterface;
@@ -116,15 +116,14 @@ public class ChangeManagementServiceUnitTest extends AbstractTestNGSpringContext
@Configuration
public static class TestMsoConfig extends MsoConfig {
- @Override
public MsoRestClientNew getMsoClient() {
MsoRestClientNew spyClient = spy(new MsoRestClientNew(new SyncRestClient(), ""));
return spyClient;
}
@Bean
- public ChangeManagementService getChangeManagementService(DataAccessService dataAccessService, MsoBusinessLogic msoInterface, SchedulerRestInterfaceIfc schedulerRestInterface) {
- return new ChangeManagementServiceImpl(dataAccessService, msoInterface, schedulerRestInterface);
+ public ChangeManagementService getChangeManagementService(DataAccessService dataAccessService, MsoBusinessLogic msoInterface, SchedulerRestInterfaceIfc schedulerRestInterface, CloudOwnerService cloudOwnerService) {
+ return new ChangeManagementServiceImpl(dataAccessService, msoInterface, schedulerRestInterface, cloudOwnerService);
}
}
}
diff --git a/vid-app-common/src/test/java/org/onap/vid/services/CloudOwnerServiceTest.java b/vid-app-common/src/test/java/org/onap/vid/services/CloudOwnerServiceTest.java
new file mode 100644
index 000000000..d6148bf28
--- /dev/null
+++ b/vid-app-common/src/test/java/org/onap/vid/services/CloudOwnerServiceTest.java
@@ -0,0 +1,125 @@
+package org.onap.vid.services;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.MockitoAnnotations;
+import org.onap.vid.aai.AaiClientInterface;
+import org.onap.vid.exceptions.GenericUncheckedException;
+import org.onap.vid.mso.model.CloudConfiguration;
+import org.onap.vid.mso.rest.RequestDetails;
+import org.onap.vid.properties.Features;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+import org.togglz.core.manager.FeatureManager;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.hasKey;
+import static org.hamcrest.Matchers.not;
+import static org.mockito.Mockito.when;
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNull;
+
+public class CloudOwnerServiceTest {
+
+ @Mock
+ private AaiClientInterface aaiClient;
+
+ @Mock
+ private FeatureManager featureManager;
+
+ @InjectMocks
+ private CloudOwnerServiceImpl cloudOwnerService;
+
+ @BeforeClass
+ public void initMocks() {
+ MockitoAnnotations.initMocks(this);
+ }
+
+ @AfterMethod
+ public void resetMocks() {
+ Mockito.reset(aaiClient);
+ Mockito.reset(featureManager);
+ }
+
+ @DataProvider
+ public static Object[][] testEnrichRequestDataProvider() {
+ return new Object[][]{{true}, {false}};
+ }
+
+ @Test(dataProvider = "testEnrichRequestDataProvider")
+ public void whenCloudConfigurationInAdditionalProperties_cloudConfigurationIsEnrichedWithCloudOwner(boolean isFeatureActive) {
+ when(featureManager.isActive(Features.FLAG_1810_CR_ADD_CLOUD_OWNER_TO_MSO_REQUEST)).thenReturn(isFeatureActive);
+ String lcpCloudRegionId = "lcp1";
+ RequestDetails requestDetails = createRequestDetailsWithCloudConfigurationInAdditionalProperties(lcpCloudRegionId);
+ String aaiCloudOwner = "myCloudOwner";
+ when(aaiClient.getCloudOwnerByCloudRegionId(lcpCloudRegionId)).thenReturn(aaiCloudOwner);
+ cloudOwnerService.enrichRequestWithCloudOwner(requestDetails);
+ if (isFeatureActive) {
+ assertEquals(aaiCloudOwner, requestDetails.extractValueByPathUsingAdditionalProperties(
+ ImmutableList.of("requestDetails", "cloudConfiguration", "cloudOwner"), String.class));
+ }
+ else {
+ Map<String,Object> cloudConfiguration = requestDetails.extractValueByPathUsingAdditionalProperties(
+ ImmutableList.of("requestDetails", "cloudConfiguration"), Map.class);
+ assertThat(cloudConfiguration, not(hasKey("cloudOwner")));
+ }
+ }
+
+ @Test(dataProvider = "testEnrichRequestDataProvider")
+ public void whenCloudConfigurationInRequestDetailsField_cloudConfigurationIsEnrichedWithCloudOwner(boolean isFeatureActive) {
+ when(featureManager.isActive(Features.FLAG_1810_CR_ADD_CLOUD_OWNER_TO_MSO_REQUEST)).thenReturn(isFeatureActive);
+ String lcpCloudRegionId = "lcp1";
+ RequestDetails requestDetails = createRequestDetailsWithCloudField(lcpCloudRegionId);
+ String aaiCloudOwner = "myCloudOwner";
+ when(aaiClient.getCloudOwnerByCloudRegionId(lcpCloudRegionId)).thenReturn(aaiCloudOwner);
+ cloudOwnerService.enrichRequestWithCloudOwner(requestDetails);
+ if (isFeatureActive) {
+ assertEquals(aaiCloudOwner, requestDetails.getCloudConfiguration().getCloudOwner());
+ }
+ else {
+ assertNull(requestDetails.getCloudConfiguration().getCloudOwner());
+ }
+ }
+
+ private RequestDetails createRequestDetailsWithCloudConfigurationInAdditionalProperties(String lcpCloudRegionId) {
+ RequestDetails requestDetails = new RequestDetails();
+ Map<String, Object> cloudConfiguration = new HashMap<>();
+ cloudConfiguration.put("lcpCloudRegionId", lcpCloudRegionId);
+ requestDetails.setAdditionalProperty("requestDetails",
+ ImmutableMap.of("cloudConfiguration", cloudConfiguration));
+ return requestDetails;
+ }
+
+ private RequestDetails createRequestDetailsWithCloudField(String lcpCloudRegionId) {
+ CloudConfiguration cloudConfiguration = new CloudConfiguration();
+ cloudConfiguration.setLcpCloudRegionId(lcpCloudRegionId);
+ RequestDetails requestDetails = new RequestDetails();
+ requestDetails.setCloudConfiguration(cloudConfiguration);
+ return requestDetails;
+ }
+
+ @Test(expectedExceptions= GenericUncheckedException.class)
+ public void whenAaiClientThrowException_thenExceptionIsPopulatedByEnrichMethod() {
+ when(featureManager.isActive(Features.FLAG_1810_CR_ADD_CLOUD_OWNER_TO_MSO_REQUEST)).thenReturn(true);
+ String lcpCloudRegionId = "lcp1";
+ RequestDetails requestDetails = createRequestDetailsWithCloudConfigurationInAdditionalProperties(lcpCloudRegionId);
+ when(aaiClient.getCloudOwnerByCloudRegionId(lcpCloudRegionId)).thenThrow(new RuntimeException());
+ cloudOwnerService.enrichRequestWithCloudOwner(requestDetails);
+ }
+
+ @Test
+ public void whenThereIsNoCloudConfiguration_enrichmentMethodNotFailed() {
+ when(featureManager.isActive(Features.FLAG_1810_CR_ADD_CLOUD_OWNER_TO_MSO_REQUEST)).thenReturn(true);
+ RequestDetails requestDetails = new RequestDetails();
+ cloudOwnerService.enrichRequestWithCloudOwner(requestDetails);
+ //if no exception was thrown test success
+ }
+}
diff --git a/vid-app-common/src/test/java/org/onap/vid/services/CsvServiceTest.java b/vid-app-common/src/test/java/org/onap/vid/services/CsvServiceTest.java
index 051a1cf45..d231de8b6 100644
--- a/vid-app-common/src/test/java/org/onap/vid/services/CsvServiceTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/services/CsvServiceTest.java
@@ -1,80 +1,82 @@
-//package org.onap.vid.services;
-//import org.apache.commons.io.IOUtils;
-//import org.onap.vid.services.CsvServiceImpl;
-//import org.skyscreamer.jsonassert.JSONAssert;
-//import org.skyscreamer.jsonassert.JSONCompareMode;
-//import org.testng.Assert;
-//import org.testng.annotations.DataProvider;
-//import org.testng.annotations.Test;
-//import org.json.JSONObject;
-//
-//import javax.ws.rs.BadRequestException;
-//import java.io.IOException;
-//import java.lang.reflect.Method;
-//import java.net.URL;
-//import java.util.List;
-//
-//@Test
-//public class CsvServiceTest {
-//
-// private CsvServiceImpl csvService = new CsvServiceImpl();
-// private final static String CSV_FOLDER = "csv_files/{CSV_FILE}";
-// private final static String VALID_CSV = "csv_to_json.csv";
-// private final static String ONE_LINE_CSV = "one_line.csv";
-// private final static String EMPTY_CSV = "empty_file.csv";
-// private final static String MISSING_CONTENT_CSV = "missing_content.csv";
-// private final static String MISSING_VALUES_CSV = "missing_values.csv";
-//
-//
-///*
-// @Test
-// public void parseValidCsv() throws IllegalAccessException, IOException, InstantiationException {
-// String expectedJson = getExpectation("vnfConfigUpdatePayload.json");
-// readAndParse(VALID_CSV,16,expectedJson);
-//
-// }*/
-//
-// private String getExpectation(String modelFileName) throws IOException {
-// // load expected result
-// final URL resource = this.getClass().getResource("/" + modelFileName);
-// String expected = IOUtils.toString(resource, "UTF-8");
-// return expected;
-// }
-///*
-// @Test
-// public void parseOneLineCsv() throws IllegalAccessException, IOException, InstantiationException {
-// String expectedJson ="{\"payload\":{\"request-parameters\":{\"vnf-name\":\"ibcx0099v\"}}}";
-// readAndParse(ONE_LINE_CSV,1,expectedJson);
-// }*/
-//
-// @DataProvider
-// public static Object[][] invalidFiles(Method test) {
-// return new Object[][]{
-// {MISSING_CONTENT_CSV}, {MISSING_VALUES_CSV}
-// };
-// }
-///*
-// @Test(dataProvider = "invalidFiles", expectedExceptions = {BadRequestException.class}, expectedExceptionsMessageRegExp = "Invalid csv file")
-// public void parseMissingContentCsv(String invalidFile) throws IllegalAccessException, IOException, InstantiationException {
-// readAndParse(invalidFile, 2, null);
-// }
-//
-//
-// @Test
-// public void parseEmptyCsv() throws IllegalAccessException, IOException, InstantiationException {
-// String expectedJson ="{}";
-// readAndParse(EMPTY_CSV,0,expectedJson);
-// }
-//
-// private void readAndParse(String fileName, int expectedNumRows, String expectedJson) throws IllegalAccessException, IOException, InstantiationException {
-// final URL resource = CsvServiceTest.class.getClassLoader().getResource(CSV_FOLDER.replaceFirst("\\{CSV_FILE\\}", fileName));
-// Assert.assertNotNull(resource, "The csv file was not found");
-// List<String[]> content = csvService.readCsv(resource.getPath());
-// Assert.assertEquals(content.size(), expectedNumRows, "The number of non-empty lines in file is wrong");
-// JSONObject json = csvService.convertCsvToJson (content);
-// JSONAssert.assertEquals(expectedJson, json, JSONCompareMode.STRICT);
-//
-// }*/
-//
-//
-//}
+package org.onap.vid.services;
+
+import org.apache.commons.io.IOUtils;
+import org.json.JSONObject;
+import org.skyscreamer.jsonassert.JSONAssert;
+import org.skyscreamer.jsonassert.JSONCompareMode;
+import org.testng.Assert;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+import javax.ws.rs.BadRequestException;
+import java.io.IOException;
+import java.lang.reflect.Method;
+import java.net.URL;
+import java.net.URLDecoder;
+import java.util.List;
+
+public class CsvServiceTest {
+
+ private CsvServiceImpl csvService = new CsvServiceImpl();
+ private final static String CSV_FOLDER = "csv_files/{CSV_FILE}";
+ private final static String VALID_CSV = "csv_to_json.csv";
+ private final static String ONE_LINE_CSV = "one_line.csv";
+ private final static String EMPTY_CSV = "empty_file.csv";
+ private final static String MISSING_CONTENT_CSV = "missing_content.csv";
+ private final static String MISSING_VALUES_CSV = "missing_values.csv";
+
+
+
+ @Test
+ public void parseValidCsv() throws IllegalAccessException, IOException, InstantiationException {
+ String expectedJson = getExpectation("vnfConfigUpdatePayload.json");
+ readAndParse(VALID_CSV,16,expectedJson);
+
+ }
+
+ private String getExpectation(String modelFileName) throws IOException {
+ // load expected result
+ final URL resource = this.getClass().getResource("/" + modelFileName);
+ String expected = IOUtils.toString(resource, "UTF-8");
+ return expected;
+ }
+
+ @Test
+ public void parseOneLineCsv() throws IllegalAccessException, IOException, InstantiationException {
+ String expectedJson ="{\"payload\":{\"request-parameters\":{\"vnf-name\":\"ibcx0099v\"}}}";
+ readAndParse(ONE_LINE_CSV,1,expectedJson);
+ }
+
+ @DataProvider
+ public static Object[][] invalidFiles(Method test) {
+ return new Object[][]{
+ {MISSING_CONTENT_CSV}, {MISSING_VALUES_CSV}
+ };
+ }
+
+ @Test(dataProvider = "invalidFiles", expectedExceptions = {BadRequestException.class}, expectedExceptionsMessageRegExp = "Invalid csv file")
+ public void parseMissingContentCsv(String invalidFile) throws IllegalAccessException, IOException, InstantiationException {
+ readAndParse(invalidFile, 2, null);
+ }
+
+
+ @Test
+ public void parseEmptyCsv() throws IllegalAccessException, IOException, InstantiationException {
+ String expectedJson ="{}";
+ readAndParse(EMPTY_CSV,0,expectedJson);
+ }
+
+ private void readAndParse(String fileName, int expectedNumRows, String expectedJson) throws IllegalAccessException, IOException, InstantiationException {
+ final URL resource = CsvServiceTest.class.getClassLoader().getResource(CSV_FOLDER.replaceFirst("\\{CSV_FILE\\}", fileName));
+ Assert.assertNotNull(resource, "The csv file was not found");
+ //using URLDecoder.decode to convert special characters from %XX to real character
+ //see https://stackoverflow.com/questions/32251251/java-classloader-getresource-with-special-characters-in-path
+ List<String[]> content = csvService.readCsv(URLDecoder.decode(resource.getPath(), "UTF-8"));
+ Assert.assertEquals(content.size(), expectedNumRows, "The number of non-empty lines in file is wrong");
+ JSONObject json = csvService.convertCsvToJson (content);
+ JSONAssert.assertEquals(expectedJson, json, JSONCompareMode.STRICT);
+
+ }
+
+
+}
diff --git a/vid-app-common/src/test/java/org/onap/vid/services/JobsBrokerServiceTest.java b/vid-app-common/src/test/java/org/onap/vid/services/JobsBrokerServiceTest.java
index ff4b34f5f..3686dc26e 100644
--- a/vid-app-common/src/test/java/org/onap/vid/services/JobsBrokerServiceTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/services/JobsBrokerServiceTest.java
@@ -1,616 +1,675 @@
package org.onap.vid.services;
-//
-//import com.google.common.collect.ImmutableList;
-//import com.google.common.collect.ImmutableMap;
-//import org.apache.commons.lang.RandomStringUtils;
-//import org.apache.commons.lang3.RandomUtils;
-//import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
-//import org.apache.commons.lang3.builder.ToStringStyle;
-//import org.hibernate.SessionFactory;
-//import org.onap.vid.exceptions.GenericUncheckedException;
-//import org.onap.vid.exceptions.OperationNotAllowedException;
-//import org.onap.vid.job.Job;
-//import org.onap.vid.job.JobAdapter;
-//import org.onap.vid.job.JobType;
-//import org.onap.vid.job.JobsBrokerService;
-//import org.onap.vid.job.impl.JobDaoImpl;
-//import org.onap.vid.job.impl.JobsBrokerServiceInDatabaseImpl;
-//import org.onap.vid.utils.DaoUtils;
-//import org.onap.vid.config.DataSourceConfig;
-//import org.onap.vid.config.JobAdapterConfig;
-//import org.onap.portalsdk.core.domain.support.DomainVo;
-//import org.onap.portalsdk.core.service.DataAccessService;
-//import org.onap.portalsdk.core.util.SystemProperties;
-//import org.springframework.test.context.ContextConfiguration;
-//import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
-//import org.testng.Assert;
-//import org.testng.annotations.AfterMethod;
-//import org.testng.annotations.BeforeMethod;
-//import org.testng.annotations.DataProvider;
-//import org.testng.annotations.Test;
-//
-//import javax.inject.Inject;
-//import java.lang.reflect.Method;
-//import java.time.LocalDateTime;
-//import java.time.ZoneId;
-//import java.util.*;
-//import java.util.concurrent.*;
-//import java.util.stream.Collectors;
-//import java.util.stream.IntStream;
-//import java.util.stream.Stream;
-//
-//import static java.util.concurrent.TimeUnit.MILLISECONDS;
-//import static org.hamcrest.CoreMatchers.equalTo;
-//import static org.hamcrest.CoreMatchers.is;
-//import static org.hamcrest.MatcherAssert.assertThat;
-//import static org.hamcrest.Matchers.both;
-//import static org.hamcrest.Matchers.containsInAnyOrder;
-//import static org.onap.vid.job.Job.JobStatus.*;
-//import static org.onap.vid.utils.Streams.not;
-//import static org.testng.Assert.assertNotNull;
-//import static org.testng.AssertJUnit.assertEquals;
-//
-//@ContextConfiguration(classes = {DataSourceConfig.class, SystemProperties.class, JobAdapterConfig.class})
-//public class JobsBrokerServiceTest extends AbstractTestNGSpringContextTests {
-//
-// private static final int JOBS_COUNT = 127;
-// private static final boolean DELETED = true;
-// private final ExecutorService executor = Executors.newFixedThreadPool(90);
-//
-// private final Set<Long> threadsIds = new ConcurrentSkipListSet<>();
-//
-// private final long FEW = 500;
-//
-// private final String JOBS_SHOULD_MATCH = "the jobs that added and those that pulled must be the same";
-// private final String JOBS_PEEKED_SHOULD_MATCH = "the jobs that added and those that peeked must be the same";
-// private static final String DELETE_SERVICE_INFO_STATUS_EXCEPTION_MESSAGE = "Service status does not allow deletion from the queue";
-// private static final String DELETE_SERVICE_NOT_EXIST_EXCEPTION_MESSAGE = "Service does not exist";
-// private JobsBrokerService broker;
-//
-// @Inject
-// JobAdapter jobAdapter;
-// @Inject
-// private DataAccessService dataAccessService;
-// @Inject
-// private SessionFactory sessionFactory;
-//
-// /*
-// - pulling jobs is limited to inserted ones
-// - putting back allows getting the job again
-// - multi threads safety
-// - any added job should be visible with view
-//
-// - edges:
-// - pulling with empty repo should return empty optional
-// - pulling more than expected should return empty optional
-// - putting one, over-pulling from a different thread
-// - take before inserting, then insert while waiting
-//
-// */
-//
-// private class NoJobException extends RuntimeException {
-// }
-//
-// private Future<Job> newJobAsync(JobsBrokerService b) {
-// return newJobAsync(b, createMockJob("user id"));
-// }
-//
-// private Future<Job> newJobAsync(JobsBrokerService b, Job.JobStatus status) {
-// return newJobAsync(b, createMockJob("user id", status));
-// }
-//
-// private Job createMockJob(String userId) {
-// return jobAdapter.createJob(
-// JobType.NoOp,
-// new JobAdapter.AsyncJobRequest() {
-// public int nothing = 42;
-// },
-// UUID.randomUUID(),
-// userId,
-// RandomUtils.nextInt());
-// }
-//
-// private Job createMockJob(String userId, Job.JobStatus jobStatus) {
-// Job job = createMockJob(userId);
-// job.setStatus(jobStatus);
-// return job;
-// }
-//
-// private Future<Job> newJobAsync(JobsBrokerService b, Job job) {
-// final Future<Job> jobFuture = executor.submit(() -> {
-// accountThreadId();
-//
-// b.add(job);
-//
-// return job;
-// });
-// return jobFuture;
-// }
-//
-// private void pushBackJobAsync(JobsBrokerService b, Job job) {
-// executor.submit(() -> {
-// accountThreadId();
-// b.pushBack(job);
-// return job;
-// });
-// }
-//
-// private Future<Optional<Job>> pullJobAsync(JobsBrokerService broker) {
-// final Future<Optional<Job>> job = executor.submit(() -> {
-// accountThreadId();
-// // Pull only pending jobs, as H2 database does not support our SQL for in-progress jobs
-// return broker.pull(Job.JobStatus.PENDING, UUID.randomUUID().toString());
-// });
-// return job;
-// }
-//
-// private Job waitForFutureOptionalJob(Future<Optional<Job>> retrievedOptionalJobFuture) {
-// try {
-// return retrievedOptionalJobFuture.get(FEW, MILLISECONDS).orElseThrow(NoJobException::new);
-// } catch (TimeoutException | InterruptedException | ExecutionException e) {
-// throw new RuntimeException(e);
-// }
-// }
-//
-// private Job waitForFutureJob(Future<Job> retrievedJobFuture) {
-// try {
-// return retrievedJobFuture.get(FEW, MILLISECONDS);
-// } catch (TimeoutException | InterruptedException | ExecutionException e) {
-// throw new RuntimeException(e);
-// }
-// }
-//
-// private List<Job> putAndGetALotOfJobs(JobsBrokerService broker) {
-// final List<Job> originalJobs = putALotOfJobs(broker);
-// final List<Job> retrievedJobs = getAlotOfJobs(broker);
-//
-// assertThat(JOBS_SHOULD_MATCH, retrievedJobs, containsInAnyOrder(originalJobs.toArray()));
-//
-// return retrievedJobs;
-// }
-//
-// private List<Job> putALotOfJobs(JobsBrokerService broker) {
-// int n = JOBS_COUNT;
-// return IntStream.range(0, n)
-// .mapToObj(i -> newJobAsync(broker))
-// .map(this::waitForFutureJob)
-// .collect(Collectors.toList());
-// }
-//
-// private List<Job> getAlotOfJobs(JobsBrokerService broker) {
-// int n = JOBS_COUNT;
-// return IntStream.range(0, n)
-// .mapToObj(i -> pullJobAsync(broker))
-// .map(this::waitForFutureOptionalJob)
-// .collect(Collectors.toList());
-// }
-//
-// private void pushBackJobs(List<Job> jobs, JobsBrokerService broker) {
-// jobs.forEach(job -> pushBackJobAsync(broker, job));
-// }
-//
-// private void accountThreadId() {
-// threadsIds.add(Thread.currentThread().getId());
-// }
-//
-// @AfterMethod
-// public void threadsCounter() {
-// System.out.println("participating threads count: " + threadsIds.size());
-// threadsIds.clear();
-// }
-//
-// @BeforeMethod
-// public void initializeBroker() {
-// broker = new JobsBrokerServiceInDatabaseImpl(dataAccessService, sessionFactory, 200, 0);
-// ((JobsBrokerServiceInDatabaseImpl) broker).deleteAll();
-// }
-//
-// @Test
-// public void givenSingleJob_getIt_verifySameJob() {
-// final Job originalJob = waitForFutureJob(newJobAsync(broker));
-//
-// final Job retrievedJob = waitForFutureOptionalJob(pullJobAsync(broker));
-// assertThat(JOBS_SHOULD_MATCH, retrievedJob, is(originalJob));
-// }
-//
-// @Test
-// public void givenManyJobs_getJobsAndPushThemBack_alwaysSeeAllOfThemWithPeek() throws InterruptedException {
-// final List<Job> originalJobs = putALotOfJobs(broker);
-//
-// MILLISECONDS.sleep(FEW);
-// assertThat(JOBS_PEEKED_SHOULD_MATCH, broker.peek(), containsInAnyOrder(originalJobs.toArray()));
-//
-// final Job retrievedJob = waitForFutureOptionalJob(pullJobAsync(broker));
-//
-// MILLISECONDS.sleep(FEW);
-// assertThat(JOBS_PEEKED_SHOULD_MATCH, broker.peek(), containsInAnyOrder(originalJobs.toArray()));
-//
-// pushBackJobAsync(broker, retrievedJob);
-//
-// MILLISECONDS.sleep(FEW);
-// assertThat(JOBS_PEEKED_SHOULD_MATCH, broker.peek(), containsInAnyOrder(originalJobs.toArray()));
-// }
-//
-// @Test
-// public void givenManyJobs_getThemAll_verifySameJobs() {
-// putAndGetALotOfJobs(broker);
-// }
-//
-// @Test
-// public void givenManyJobs_getThemAllThenPushBackandGet_verifySameJobs() {
-// final List<Job> retrievedJobs1 = putAndGetALotOfJobs(broker);
-//
-// pushBackJobs(retrievedJobs1, broker);
-// final List<Job> retrievedJobs2 = getAlotOfJobs(broker);
-//
-// assertThat(JOBS_SHOULD_MATCH, retrievedJobs2, containsInAnyOrder(retrievedJobs1.toArray()));
-// }
-//
-// private static Date toDate(LocalDateTime localDateTime) {
-// return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
-// }
-//
-// private void setModifiedDateToJob(UUID jobUuid, Date date) {
-// DomainVo job = dataAccessService.getDomainObject(JobDaoImpl.class, jobUuid, DaoUtils.getPropsMap());
-// job.setModified(date);
-// DaoUtils.tryWithSessionAndTransaction(sessionFactory, session -> {
-// session.saveOrUpdate(job);
-// return 1;
-// });
-// }
-//
-//
-// public static JobDaoImpl createNewJob(Integer indexInBulk, UUID templateId, String userId, Job.JobStatus status, String takenBy, LocalDateTime date) {
-// return createNewJob(indexInBulk, templateId, userId, status, takenBy, date, false);
-// }
-//
-// public static JobDaoImpl createNewJob(Integer indexInBulk, UUID templateId, String userId, Job.JobStatus status, String takenBy, LocalDateTime date, boolean deleted){
-// JobDaoImpl job = new JobDaoImpl();
-// job.setTypeAndData(JobType.NoOp, ImmutableMap.of("x", RandomStringUtils.randomAlphanumeric(15)));
-// job.setIndexInBulk(indexInBulk);
-// job.setTemplateId(templateId);
-// job.setType(JobType.NoOp);
-// job.setStatus(status);
-// job.setTakenBy(takenBy);
-// job.setCreated(toDate(date));
-// job.setModified(toDate(date));
-// job.setUserId(userId);
-// if (deleted) {
-// job.setDeletedAt(new Date());
-// }
-// return job;
-// }
-//
-// @DataProvider
-// public static Object[][] jobs(Method test) {
-// LocalDateTime oldestDate = LocalDateTime.now().minusHours(30);
-// UUID sameTemplate = UUID.randomUUID();
-// return new Object[][]{
-// {ImmutableList.of(
-// createNewJob(11, UUID.randomUUID(), "userId", PENDING, null, oldestDate),
-// createNewJob(22, UUID.randomUUID(), "userId", PENDING, null, oldestDate),
-// createNewJob(11, UUID.randomUUID(), "userId", PENDING, null, LocalDateTime.now().minusHours(2)),
-// createNewJob(44, UUID.randomUUID(), "userId", PENDING, null, LocalDateTime.now().minusHours(5))),
-// 4,
-// 0,
-// PENDING,
-// "Broker should pull the first pending job by oldest date then by job index"
-// },
-// { ImmutableList.of(
-// createNewJob(11, UUID.randomUUID(), "userId", COMPLETED,null, oldestDate),
-// createNewJob(11, UUID.randomUUID(), "userId", PENDING,null, oldestDate, DELETED),createNewJob(12, UUID.randomUUID(), "userId", FAILED,null, oldestDate),
-// createNewJob(13, UUID.randomUUID(), "userId", IN_PROGRESS,null, oldestDate),
-// createNewJob(14, UUID.randomUUID(), "userId", STOPPED,null, oldestDate),
-// createNewJob(22, UUID.randomUUID(), "userId", PENDING,null, oldestDate),
-// createNewJob(33, UUID.randomUUID(), "userId", PENDING,null, LocalDateTime.now().minusHours(2))),
-// 6,
-// 5,
-// PENDING,
-// "Broker should pull the only pending - first pending job by oldest job - ignore deleted,completed, failed, in-progress and stopped statuses"
-// },
-// {ImmutableList.of(
-// createNewJob(11, UUID.randomUUID(), "userId", IN_PROGRESS, UUID.randomUUID().toString(), oldestDate),
-// createNewJob(22, UUID.randomUUID(), "userId", IN_PROGRESS, UUID.randomUUID().toString(), oldestDate),
-// createNewJob(33, UUID.randomUUID(), "userId", PENDING, null, LocalDateTime.now().minusHours(2))),
-// 2,
-// -1,
-// PENDING,
-// "Broker should not pull any job when it exceeded mso limit with count (in-progress) statuses"
-// },
-// {ImmutableList.of(
-// createNewJob(11, UUID.randomUUID(), "userId", IN_PROGRESS, UUID.randomUUID().toString(), oldestDate),
-// createNewJob(22, UUID.randomUUID(), "userId", PENDING, UUID.randomUUID().toString(), oldestDate),
-// createNewJob(33, UUID.randomUUID(), "userId", PENDING, null, LocalDateTime.now().minusHours(2))),
-// 2,
-// -1,
-// PENDING,
-// "Broker should not pull any job when it exceeded mso limit with count(in-progress or pending && taken) statuses"
-// },
-// {ImmutableList.of(
-// createNewJob(11, UUID.randomUUID(), "userId", IN_PROGRESS, UUID.randomUUID().toString(), oldestDate),
-// createNewJob(22, UUID.randomUUID(), "userId", PENDING, UUID.randomUUID().toString(), oldestDate),
-// createNewJob(33, UUID.randomUUID(), "userId", PENDING, null, LocalDateTime.now().minusHours(2))),
-// 3,
-// 2,
-// PENDING,
-// "Broker should pull first job when it doesn't exceeded mso limit with count(in-progress or pending && taken) statuses"
-// },
-// {ImmutableList.of(
-// createNewJob(11, sameTemplate, "userId", PENDING, UUID.randomUUID().toString(), oldestDate),
-// createNewJob(22, sameTemplate, "userId", PENDING, null, oldestDate),
-// createNewJob(33, sameTemplate, "userId", PENDING, null, LocalDateTime.now().minusHours(2))),
-// 3,
-// -1,
-// PENDING,
-// "Broker should not pull any job when there is another job from this template that was taken"
-// },
-// {ImmutableList.of(
-// createNewJob(11, sameTemplate, "userId", IN_PROGRESS, null, oldestDate),
-// createNewJob(22, sameTemplate, "userId", PENDING, null, oldestDate),
-// createNewJob(33, sameTemplate, "userId", PENDING, null, LocalDateTime.now().minusHours(2))),
-// 3,
-// -1,
-// PENDING,
-// "Broker should not pull any job when there is another job from this template that in progress"
-// },
-// {ImmutableList.of(
-// createNewJob(11, sameTemplate, "userId", FAILED, null, oldestDate),
-// createNewJob(22, sameTemplate, "userId", STOPPED, null, oldestDate),
-// createNewJob(33, sameTemplate, "userId", PENDING, null, LocalDateTime.now().minusHours(2))),
-// 3,
-// -1,
-// PENDING,
-// "Broker should not pull any job when there is another job from this template that was failed"
-// },
-// {ImmutableList.of(
-// createNewJob(11, sameTemplate, "userId", FAILED, null, oldestDate, DELETED),
-// createNewJob(22, sameTemplate, "userId", STOPPED,null, oldestDate),
-// createNewJob(33, sameTemplate, "userId", PENDING,null, LocalDateTime.now().minusHours(2))),
-// 3,
-// 2,
-// PENDING,
-// "Broker should pull pending job when there is another job from this template that was deleted, although failed"
-// },
-// { ImmutableList.of(
-// createNewJob(11, UUID.randomUUID(), "userA", IN_PROGRESS, null, oldestDate),
-// createNewJob(22, UUID.randomUUID(), "userA", PENDING, null, oldestDate),
-// createNewJob(33, UUID.randomUUID(), "userB", PENDING, null, LocalDateTime.now().minusHours(2))),
-// 3,
-// 2,
-// PENDING,
-// "Broker should prioritize jobs of user that has no in-progress jobs"
-// },
-// {ImmutableList.of(
-// createNewJob(11, UUID.randomUUID(), "userA", PENDING, UUID.randomUUID().toString(), oldestDate),
-// createNewJob(22, UUID.randomUUID(), "userA", PENDING, null, oldestDate),
-// createNewJob(33, UUID.randomUUID(), "userB", PENDING, null, LocalDateTime.now().minusHours(2))),
-// 3,
-// 2,
-// PENDING,
-// "Broker should prioritize jobs of user that has no taken jobs"
-// },
-// {ImmutableList.of(
-// createNewJob(11, UUID.randomUUID(), "userA", IN_PROGRESS, UUID.randomUUID().toString(), oldestDate),
-// createNewJob(22, UUID.randomUUID(), "userA", PENDING, null, LocalDateTime.now().minusHours(2)),
-// createNewJob(31, UUID.randomUUID(), "userB", IN_PROGRESS, null, LocalDateTime.now().minusHours(2)),
-// createNewJob(32, UUID.randomUUID(), "userB", IN_PROGRESS, null, LocalDateTime.now().minusHours(2)),
-// createNewJob(33, UUID.randomUUID(), "userB", PENDING, null, oldestDate)),
-// 5,
-// 4,
-// PENDING,
-// "Broker should take oldest job when there is one in-progress job to each user"
-// },
-// {ImmutableList.of(
-// createNewJob(11, UUID.randomUUID(), UUID.randomUUID().toString(), IN_PROGRESS, null, oldestDate),
-// createNewJob(22, UUID.randomUUID(), UUID.randomUUID().toString(), IN_PROGRESS, null, oldestDate),
-// createNewJob(33, UUID.randomUUID(), UUID.randomUUID().toString(), PENDING, null, LocalDateTime.now().minusHours(2))),
-// 2,
-// -1,
-// PENDING,
-// "Broker should not pull any job when it exceeded mso limit with count(in-progress or pending && taken) statuses"
-// },
-// {ImmutableList.of(
-// createNewJob(11, UUID.randomUUID(), "userId", IN_PROGRESS, UUID.randomUUID().toString(), oldestDate),
-// createNewJob(22, UUID.randomUUID(), "userId", IN_PROGRESS, null, oldestDate),
-// createNewJob(11, UUID.randomUUID(), "userId", IN_PROGRESS, null, LocalDateTime.now().minusHours(2)),
-// createNewJob(44, UUID.randomUUID(), "userId", IN_PROGRESS, null, LocalDateTime.now().minusHours(5))),
-// 20,
-// 1,
-// IN_PROGRESS,
-// "Broker with in progress topic should pull the first in progress and not taken job by oldest date"
-// },
-// {ImmutableList.of(
-// createNewJob(11, UUID.randomUUID(), "userId", COMPLETED, null, oldestDate),
-// createNewJob(12, UUID.randomUUID(), "userId", FAILED, null, oldestDate),
-// createNewJob(13, UUID.randomUUID(), "userId", PENDING,null, oldestDate),
-// createNewJob(14, UUID.randomUUID(), "userId", STOPPED,null, oldestDate),
-// createNewJob(11, UUID.randomUUID(), "userId", IN_PROGRESS,null, oldestDate, DELETED),createNewJob(22, UUID.randomUUID(), "userId", IN_PROGRESS,null, oldestDate),
-// createNewJob(33, UUID.randomUUID(), "userId", IN_PROGRESS,null, LocalDateTime.now().minusHours(2))),
-// 20,
-// 5,
-// IN_PROGRESS,
-// "Broker with in progress topic should pull only in-progress jobs - first in-progress job by oldest date - ignore deleted,completed, failed, pending and stopped statuses"
-// },
-// {ImmutableList.of(
-// createNewJob(11, UUID.randomUUID(), "userId", IN_PROGRESS, null, LocalDateTime.now()),
-// createNewJob(22, UUID.randomUUID(), "userId", IN_PROGRESS, null, LocalDateTime.now().minusSeconds(1)),
-// createNewJob(33, UUID.randomUUID(), "userId", IN_PROGRESS, null, LocalDateTime.now().minusSeconds(2))),
-// 20,
-// -1,
-// IN_PROGRESS,
-// "Broker with in progress topic should not pull any job if its modified date is smaller than now-interval (20 seconds)"
-// }
-//
-// };
-// }
-//
-//
-// @Test(dataProvider = "jobs")
-// public void givenSomeJobs_pullNextJob_returnNextOrNothingAsExpected(List<JobDaoImpl> jobs, int msoLimit, int expectedIndexSelected, Job.JobStatus topic, String assertionReason) {
-// JobsBrokerServiceInDatabaseImpl broker = new JobsBrokerServiceInDatabaseImpl(dataAccessService, sessionFactory, msoLimit, 20);
-// for (JobDaoImpl job : jobs) {
-// Date modifiedDate = job.getModified();
-// broker.add(job);
-// setModifiedDateToJob(job.getUuid(), modifiedDate);
-// }
-// Optional<Job> nextJob = broker.pull(topic, UUID.randomUUID().toString());
-// boolean shouldAnyBeSelected = expectedIndexSelected >= 0;
-// Assert.assertEquals(nextJob.isPresent(), shouldAnyBeSelected, assertionReason);
-// if (shouldAnyBeSelected) {
-// Assert.assertEquals(jobs.get(expectedIndexSelected), nextJob.get(), assertionReason);
-// }
-// }
-//
-// @DataProvider
-// public Object[][] topics() {
-// return Arrays.stream(Job.JobStatus.values())
-// .filter(not(t -> ImmutableList.of(PENDING, IN_PROGRESS).contains(t)))
-// .map(v -> new Object[]{v}).collect(Collectors.toList()).toArray(new Object[][]{});
-// }
-//
-// @Test(dataProvider = "topics", expectedExceptions = GenericUncheckedException.class, expectedExceptionsMessageRegExp = "Unsupported topic.*")
-// public void pullUnexpectedTopic_exceptionIsThrown(Job.JobStatus topic) {
-// broker.pull(topic, UUID.randomUUID().toString());
-// }
-//
-// @Test(expectedExceptions = NoJobException.class)
-// public void givenNonPendingJobs_getJobAsPendingTopic_verifyNothingRetrieved() {
-// Stream.of(Job.JobStatus.values())
-// .filter(not(s -> s.equals(PENDING)))
-// .map(s -> createMockJob("some user id", s))
-// .map(job -> newJobAsync(broker, job))
-// .map(this::waitForFutureJob)
-// .collect(Collectors.toList());
-//
-// waitForFutureOptionalJob(pullJobAsync(broker));
-// }
-//
-// @Test
-// public void givenPendingAndNonPendingJobs_getJobAsPendingTopic_verifyAJobRetrieved() {
-// newJobAsync(broker); // this negated the expected result of the call below
-// givenNonPendingJobs_getJobAsPendingTopic_verifyNothingRetrieved();
-// }
-//
-// @Test(expectedExceptions = NoJobException.class)
-// public void givenManyJobs_pullThemAllAndAskOneMore_verifyFinallyNothingRetrieved() {
-// putAndGetALotOfJobs(broker);
-// waitForFutureOptionalJob(pullJobAsync(broker));
-// }
-//
-// @Test(expectedExceptions = NoJobException.class)
-// public void givenNoJob_requestJob_verifyNothingRetrieved() throws InterruptedException, ExecutionException, TimeoutException {
-// final Future<Optional<Job>> futureOptionalJob = pullJobAsync(broker);
-// assertThat("job should not be waiting yet", futureOptionalJob.get(FEW, MILLISECONDS).isPresent(), is(false));
-// waitForFutureOptionalJob(futureOptionalJob);
-// }
-//
-// @Test(expectedExceptions = IllegalStateException.class)
-// public void givenSinglePulledJob_pushBackDifferentJob_verifyPushingRejected() {
-// waitForFutureJob(newJobAsync(broker));
-// waitForFutureJob(newJobAsync(broker));
-// waitForFutureOptionalJob(pullJobAsync(broker));
-//
-// Job myJob = createMockJob("user id");
-// myJob.setUuid(UUID.randomUUID());
-//
-// broker.pushBack(myJob); //Should fail
-// }
-//
-// @Test
-// public void givenSingleJob_pushBackModifiedJob_verifyPulledIsVeryVeryTheSame() {
-// final ImmutableMap<String, Object> randomDataForMostRecentJobType =
-// ImmutableMap.of("42", 42, "complex", ImmutableList.of("a", "b", "c"));
-//
-// waitForFutureJob(newJobAsync(broker));
-// final Job job = waitForFutureOptionalJob(pullJobAsync(broker));
-//
-// job.setStatus(Job.JobStatus.PENDING);
-// job.setTypeAndData(JobType.NoOp, ImmutableMap.of("good", "morning"));
-// job.setTypeAndData(JobType.HttpCall, ImmutableMap.of());
-// job.setTypeAndData(JobType.ServiceInstantiation, randomDataForMostRecentJobType);
-//
-// broker.pushBack(job);
-// final Job retrievedJob = waitForFutureOptionalJob(pullJobAsync(broker));
-//
-// assertThat(JOBS_SHOULD_MATCH, retrievedJob, is(job));
-// assertThat(JOBS_SHOULD_MATCH, retrievedJob.getData(), both(equalTo(job.getData())).and(equalTo(randomDataForMostRecentJobType)));
-// assertThat(JOBS_SHOULD_MATCH, jobDataReflected(retrievedJob), is(jobDataReflected(job)));
-// }
-//
-// private static String jobDataReflected(Job job) {
-// return new ReflectionToStringBuilder(job, ToStringStyle.SHORT_PREFIX_STYLE)
-// .setExcludeFieldNames("created", "modified", "takenBy")
-// .toString();
-// }
-//
-// @Test(expectedExceptions = IllegalStateException.class)
-// public void givenSingleJob_pushBackTwice_verifyPushingRejected() {
-// waitForFutureJob(newJobAsync(broker));
-// final Job job = waitForFutureOptionalJob(pullJobAsync(broker));
-//
-// broker.pushBack(job);
-// broker.pushBack(job); //Should fail
-// }
-//
-// @Test
-// public void addJob_PeekItById_verifySameJobWasPeeked() {
-// String userId = UUID.randomUUID().toString();
-// Job myJob = createMockJob(userId);
-// UUID uuid = broker.add(myJob);
-// Job peekedJob = broker.peek(uuid);
-// assertEquals("added testId is not the same as peeked TestsId",
-// userId,
-// peekedJob.getData().get("userId"));
-// }
-//
-// @Test(dataProvider = "jobStatusesForSuccessDelete", expectedExceptions = NoJobException.class)
-// public void givenOneJob_deleteIt_canPeekOnItButCantPull(Job.JobStatus status) {
-// final Job job = waitForFutureJob(newJobAsync(broker, status));
-// broker.delete(job.getUuid());
-// assertNotNull(((JobDaoImpl) broker.peek(job.getUuid())).getDeletedAt(), "job should be deleted");
-// waitForFutureOptionalJob(pullJobAsync(broker));
-// }
-//
-// @DataProvider
-// public static Object[][] jobStatusesForSuccessDelete() {
-// return new Object[][]{
-// {PENDING},
-// {STOPPED}
-// };
-// }
-//
-// @Test(
-// dataProvider = "jobStatusesForFailedDelete",
-// expectedExceptions = OperationNotAllowedException.class,
-// expectedExceptionsMessageRegExp=DELETE_SERVICE_INFO_STATUS_EXCEPTION_MESSAGE
-// )
-// public void deleteJob_notAllowedStatus_exceptionIsThrown(Job.JobStatus status, boolean taken) {
-// final Job job = waitForFutureJob(newJobAsync(broker, createMockJob("some user id", status)));
-//
-// if (taken) {
-// waitForFutureOptionalJob(pullJobAsync(broker));
-// }
-//
-//
-// broker.delete(job.getUuid());
-// }
-//
-// @DataProvider
-// public static Object[][] jobStatusesForFailedDelete() {
-// return new Object[][]{
-// {PENDING, true},
-// {IN_PROGRESS, false},
-// {COMPLETED, false},
-// {PAUSE, false},
-// {FAILED, false},
-// };
-// }
-//
-// @Test(expectedExceptions = OperationNotAllowedException.class, expectedExceptionsMessageRegExp = DELETE_SERVICE_NOT_EXIST_EXCEPTION_MESSAGE)
-// public void deleteJob_notExist_exceptionIsThrown() {
-// waitForFutureJob(newJobAsync(broker, createMockJob("some user id", PENDING)));
-// broker.delete(new UUID(111, 111));
-// }
-//
-//}
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import org.apache.commons.lang.RandomStringUtils;
+import org.apache.commons.lang3.RandomUtils;
+import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
+import org.apache.commons.lang3.builder.ToStringStyle;
+import org.apache.log4j.LogManager;
+import org.apache.log4j.Logger;
+import org.hibernate.SessionFactory;
+import org.onap.portalsdk.core.domain.support.DomainVo;
+import org.onap.portalsdk.core.service.DataAccessService;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.onap.vid.config.DataSourceConfig;
+import org.onap.vid.config.JobAdapterConfig;
+import org.onap.vid.exceptions.GenericUncheckedException;
+import org.onap.vid.exceptions.OperationNotAllowedException;
+import org.onap.vid.job.Job;
+import org.onap.vid.job.JobAdapter;
+import org.onap.vid.job.JobType;
+import org.onap.vid.job.JobsBrokerService;
+import org.onap.vid.job.command.JobCommandFactoryTest;
+import org.onap.vid.job.impl.JobDaoImpl;
+import org.onap.vid.job.impl.JobsBrokerServiceInDatabaseImpl;
+import org.onap.vid.utils.DaoUtils;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
+import org.testng.Assert;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+import javax.inject.Inject;
+import java.lang.reflect.Method;
+import java.time.LocalDateTime;
+import java.time.ZoneId;
+import java.util.*;
+import java.util.concurrent.*;
+import java.util.stream.IntStream;
+import java.util.stream.Stream;
+
+import static java.util.concurrent.TimeUnit.MILLISECONDS;
+import static java.util.stream.Collectors.toList;
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.both;
+import static org.hamcrest.Matchers.containsInAnyOrder;
+import static org.onap.vid.job.Job.JobStatus.*;
+import static org.onap.vid.utils.Streams.not;
+import static org.testng.Assert.assertNotNull;
+import static org.testng.AssertJUnit.assertEquals;
+
+@ContextConfiguration(classes = {DataSourceConfig.class, SystemProperties.class, JobAdapterConfig.class})
+public class JobsBrokerServiceTest extends AbstractTestNGSpringContextTests {
+
+ private static final Logger logger = LogManager.getLogger(JobsBrokerServiceTest.class);
+
+ private static final int JOBS_COUNT = 127;
+ private static final boolean DELETED = true;
+ private final ExecutorService executor = Executors.newFixedThreadPool(90);
+
+ private final Set<Long> threadsIds = new ConcurrentSkipListSet<>();
+
+ private final long FEW = 500;
+
+ private final String JOBS_SHOULD_MATCH = "the jobs that added and those that pulled must be the same";
+ private final String JOBS_PEEKED_SHOULD_MATCH = "the jobs that added and those that peeked must be the same";
+ private static final String DELETE_SERVICE_INFO_STATUS_EXCEPTION_MESSAGE = "Service status does not allow deletion from the queue";
+ private static final String DELETE_SERVICE_NOT_EXIST_EXCEPTION_MESSAGE = "Service does not exist";
+ private JobsBrokerService broker;
+
+ @Inject
+ JobAdapter jobAdapter;
+ @Inject
+ private DataAccessService dataAccessService;
+ @Inject
+ private SessionFactory sessionFactory;
+
+ /*
+ - pulling jobs is limited to inserted ones
+ - putting back allows getting the job again
+ - multi threads safety
+ - any added job should be visible with view
+
+ - edges:
+ - pulling with empty repo should return empty optional
+ - pulling more than expected should return empty optional
+ - putting one, over-pulling from a different thread
+ - take before inserting, then insert while waiting
+
+ */
+
+ private class NoJobException extends RuntimeException {
+ }
+
+ private Future<Job> newJobAsync(JobsBrokerService b) {
+ return newJobAsync(b, createMockJob("user id"));
+ }
+
+ private Future<Job> newJobAsync(JobsBrokerService b, Job.JobStatus status) {
+ return newJobAsync(b, createMockJob("user id", status));
+ }
+
+ private Job createMockJob(String userId) {
+ return jobAdapter.createServiceInstantiationJob(
+ JobType.NoOp,
+ new JobCommandFactoryTest.MockedRequest(42,"nothing") ,
+ UUID.randomUUID(),
+ userId,
+ "optimisticUniqueServiceInstanceName",
+ RandomUtils.nextInt());
+ }
+
+ private Job createMockJob(String userId, Job.JobStatus jobStatus) {
+ Job job = createMockJob(userId);
+ job.setStatus(jobStatus);
+ return job;
+ }
+
+ private Future<Job> newJobAsync(JobsBrokerService b, Job job) {
+ final Future<Job> jobFuture = executor.submit(() -> {
+ accountThreadId();
+
+ b.add(job);
+
+ return job;
+ });
+ return jobFuture;
+ }
+
+ private void pushBackJobAsync(JobsBrokerService b, Job job) {
+ executor.submit(() -> {
+ accountThreadId();
+ b.pushBack(job);
+ return job;
+ });
+ }
+
+ private Future<Optional<Job>> pullJobAsync(JobsBrokerService broker) {
+ final Future<Optional<Job>> job = executor.submit(() -> {
+ accountThreadId();
+ // Pull only pending jobs, as H2 database does not support our SQL for in-progress jobs
+ return broker.pull(Job.JobStatus.PENDING, UUID.randomUUID().toString());
+ });
+ return job;
+ }
+
+ private Job waitForFutureOptionalJob(Future<Optional<Job>> retrievedOptionalJobFuture) {
+ try {
+ return retrievedOptionalJobFuture.get(FEW, MILLISECONDS).orElseThrow(NoJobException::new);
+ } catch (TimeoutException | InterruptedException | ExecutionException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private Job waitForFutureJob(Future<Job> retrievedJobFuture) {
+ try {
+ return retrievedJobFuture.get(FEW, MILLISECONDS);
+ } catch (TimeoutException | InterruptedException | ExecutionException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private List<Job> putAndGetALotOfJobs(JobsBrokerService broker) {
+ final List<Job> originalJobs = putALotOfJobs(broker);
+ final List<Job> retrievedJobs = getAlotOfJobs(broker);
+
+ assertThat(JOBS_SHOULD_MATCH, retrievedJobs, containsInAnyOrder(originalJobs.toArray()));
+
+ return retrievedJobs;
+ }
+
+ private List<Job> putALotOfJobs(JobsBrokerService broker) {
+ int n = JOBS_COUNT;
+ return IntStream.range(0, n)
+ .mapToObj(i -> newJobAsync(broker))
+ .map(this::waitForFutureJob)
+ .collect(toList());
+ }
+
+ private List<Job> getAlotOfJobs(JobsBrokerService broker) {
+ int n = JOBS_COUNT;
+ return IntStream.range(0, n)
+ .mapToObj(i -> pullJobAsync(broker))
+ .map(this::waitForFutureOptionalJob)
+ .collect(toList());
+ }
+
+ private void pushBackJobs(List<Job> jobs, JobsBrokerService broker) {
+ jobs.forEach(job -> pushBackJobAsync(broker, job));
+ }
+
+ private void accountThreadId() {
+ threadsIds.add(Thread.currentThread().getId());
+ }
+
+ @AfterMethod
+ public void threadsCounter() {
+ logger.info("participating threads count: " + threadsIds.size());
+ threadsIds.clear();
+ }
+
+ @BeforeMethod
+ public void initializeBroker() {
+ broker = new JobsBrokerServiceInDatabaseImpl(dataAccessService, sessionFactory, 200, 0);
+ ((JobsBrokerServiceInDatabaseImpl) broker).deleteAll();
+ }
+
+ @Test(enabled = false)
+ public void givenSingleJob_getIt_verifySameJob() {
+ final Job originalJob = waitForFutureJob(newJobAsync(broker));
+
+ final Job retrievedJob = waitForFutureOptionalJob(pullJobAsync(broker));
+ assertThat(JOBS_SHOULD_MATCH, retrievedJob, is(originalJob));
+ }
+
+ @Test(enabled = false)
+ public void givenManyJobs_getJobsAndPushThemBack_alwaysSeeAllOfThemWithPeek() throws InterruptedException {
+ final List<Job> originalJobs = putALotOfJobs(broker);
+
+ MILLISECONDS.sleep(FEW);
+ assertThat(JOBS_PEEKED_SHOULD_MATCH, broker.peek(), containsInAnyOrder(originalJobs.toArray()));
+
+ final Job retrievedJob = waitForFutureOptionalJob(pullJobAsync(broker));
+
+ MILLISECONDS.sleep(FEW);
+ assertThat(JOBS_PEEKED_SHOULD_MATCH, broker.peek(), containsInAnyOrder(originalJobs.toArray()));
+
+ pushBackJobAsync(broker, retrievedJob);
+
+ MILLISECONDS.sleep(FEW);
+ assertThat(JOBS_PEEKED_SHOULD_MATCH, broker.peek(), containsInAnyOrder(originalJobs.toArray()));
+ }
+
+ @Test(enabled = false)
+ public void givenManyJobs_getThemAll_verifySameJobs() {
+ putAndGetALotOfJobs(broker);
+ }
+
+ @Test(enabled = false)
+ public void givenManyJobs_getThemAllThenPushBackandGet_verifySameJobs() {
+ final List<Job> retrievedJobs1 = putAndGetALotOfJobs(broker);
+
+ pushBackJobs(retrievedJobs1, broker);
+ final List<Job> retrievedJobs2 = getAlotOfJobs(broker);
+
+ assertThat(JOBS_SHOULD_MATCH, retrievedJobs2, containsInAnyOrder(retrievedJobs1.toArray()));
+ }
+
+ private static Date toDate(LocalDateTime localDateTime) {
+ return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
+ }
+
+ private void setModifiedDateToJob(UUID jobUuid, Date date) {
+ DomainVo job = dataAccessService.getDomainObject(JobDaoImpl.class, jobUuid, DaoUtils.getPropsMap());
+ job.setModified(date);
+ DaoUtils.tryWithSessionAndTransaction(sessionFactory, session -> {
+ session.saveOrUpdate(job);
+ return 1;
+ });
+ }
+
+
+ public static JobDaoImpl createNewJob(Integer indexInBulk, UUID templateId, String userId, Job.JobStatus status, String takenBy, LocalDateTime date) {
+ return createNewJob(indexInBulk, templateId, userId, status, takenBy, date, false);
+ }
+
+ public static JobDaoImpl createNewJob(Integer indexInBulk, UUID templateId, String userId, Job.JobStatus status, String takenBy, LocalDateTime date, boolean deleted){
+ JobDaoImpl job = new JobDaoImpl();
+ job.setUuid(UUID.randomUUID());
+ job.setTypeAndData(JobType.NoOp, ImmutableMap.of("x", RandomStringUtils.randomAlphanumeric(15)));
+ job.setIndexInBulk(indexInBulk);
+ job.setTemplateId(templateId);
+ job.setType(JobType.NoOp);
+ job.setStatus(status);
+ job.setTakenBy(takenBy);
+ job.setCreated(toDate(date));
+ job.setModified(toDate(date));
+ job.setUserId(userId);
+ if (deleted) {
+ job.setDeletedAt(new Date());
+ }
+ return job;
+ }
+
+ @DataProvider
+ public static Object[][] jobs(Method test) {
+ LocalDateTime oldestDate = LocalDateTime.now().minusHours(30);
+ UUID sameTemplate = UUID.randomUUID();
+ return new Object[][]{
+ {ImmutableList.of(
+ (Jobber)() -> createNewJob(11, UUID.randomUUID(), "userId", PENDING, null, oldestDate),
+ () -> createNewJob(22, UUID.randomUUID(), "userId", PENDING, null, oldestDate),
+ () -> createNewJob(11, UUID.randomUUID(), "userId", PENDING, null, LocalDateTime.now().minusHours(2)),
+ () -> createNewJob(44, UUID.randomUUID(), "userId", PENDING, null, LocalDateTime.now().minusHours(5))),
+ 4,
+ 0,
+ PENDING,
+ "Broker should pull the first pending job by oldest date then by job index"
+ },
+ { ImmutableList.of(
+ (Jobber)() -> createNewJob(11, UUID.randomUUID(), "userId", COMPLETED,null, oldestDate),
+ () -> createNewJob(11, UUID.randomUUID(), "userId", PENDING,null, oldestDate, DELETED),
+ () -> createNewJob(12, UUID.randomUUID(), "userId", FAILED,null, oldestDate),
+ () -> createNewJob(13, UUID.randomUUID(), "userId", IN_PROGRESS,null, oldestDate),
+ () -> createNewJob(14, UUID.randomUUID(), "userId", STOPPED,null, oldestDate),
+ () -> createNewJob(22, UUID.randomUUID(), "userId", PENDING,null, oldestDate),
+ () -> createNewJob(33, UUID.randomUUID(), "userId", PENDING,null, LocalDateTime.now().minusHours(2))),
+ 6,
+ 5,
+ PENDING,
+ "Broker should pull the only pending - first pending job by oldest job - ignore deleted,completed, failed, in-progress and stopped statuses"
+ },
+ {ImmutableList.of(
+ (Jobber)() -> createNewJob(11, UUID.randomUUID(), "userId", IN_PROGRESS, UUID.randomUUID().toString(), oldestDate),
+ () -> createNewJob(22, UUID.randomUUID(), "userId", IN_PROGRESS, UUID.randomUUID().toString(), oldestDate),
+ () -> createNewJob(33, UUID.randomUUID(), "userId", PENDING, null, LocalDateTime.now().minusHours(2))),
+ 2,
+ -1,
+ PENDING,
+ "Broker should not pull any job when it exceeded mso limit with count (in-progress) statuses"
+ },
+ {ImmutableList.of(
+ (Jobber)() -> createNewJob(11, UUID.randomUUID(), "userId", IN_PROGRESS, UUID.randomUUID().toString(), oldestDate),
+ () -> createNewJob(22, UUID.randomUUID(), "userId", PENDING, UUID.randomUUID().toString(), oldestDate),
+ () -> createNewJob(33, UUID.randomUUID(), "userId", PENDING, null, LocalDateTime.now().minusHours(2))),
+ 2,
+ -1,
+ PENDING,
+ "Broker should not pull any job when it exceeded mso limit with count(in-progress or pending && taken) statuses"
+ },
+ {ImmutableList.of(
+ (Jobber)() -> createNewJob(11, UUID.randomUUID(), "userId", IN_PROGRESS, UUID.randomUUID().toString(), oldestDate),
+ () -> createNewJob(22, UUID.randomUUID(), "userId", PENDING, UUID.randomUUID().toString(), oldestDate),
+ () -> createNewJob(33, UUID.randomUUID(), "userId", PENDING, null, LocalDateTime.now().minusHours(2)),
+ () -> createNewJob(12, UUID.randomUUID(), "userId", RESOURCE_IN_PROGRESS, UUID.randomUUID().toString(), oldestDate)
+ ),
+ 3,
+ 2,
+ PENDING,
+ "Broker should pull first job when it doesn't exceeded mso limit with count(in-progress or pending && taken) statuses"
+ },
+ {ImmutableList.of(
+ (Jobber)() -> createNewJob(11, sameTemplate, "userId", PENDING, UUID.randomUUID().toString(), oldestDate),
+ () -> createNewJob(22, sameTemplate, "userId", PENDING, null, oldestDate),
+ () -> createNewJob(33, sameTemplate, "userId", PENDING, null, LocalDateTime.now().minusHours(2))),
+ 3,
+ -1,
+ PENDING,
+ "Broker should not pull any job when there is another job from this template that was taken"
+ },
+ {ImmutableList.of(
+ (Jobber)() -> createNewJob(11, sameTemplate, "userId", IN_PROGRESS, null, oldestDate),
+ () -> createNewJob(22, sameTemplate, "userId", PENDING, null, oldestDate),
+ () -> createNewJob(33, sameTemplate, "userId", PENDING, null, LocalDateTime.now().minusHours(2))),
+ 3,
+ -1,
+ PENDING,
+ "Broker should not pull any job when there is another job from this template that in progress"
+ },
+ {ImmutableList.of(
+ (Jobber)() -> createNewJob(11, sameTemplate, "userId", FAILED, null, oldestDate),
+ () -> createNewJob(22, sameTemplate, "userId", STOPPED, null, oldestDate),
+ () -> createNewJob(33, sameTemplate, "userId", PENDING, null, LocalDateTime.now().minusHours(2))),
+ 3,
+ -1,
+ PENDING,
+ "Broker should not pull any job when there is another job from this template that was failed"
+ },
+ {ImmutableList.of(
+ (Jobber)() -> createNewJob(11, sameTemplate, "userId", FAILED, null, oldestDate, DELETED),
+ () -> createNewJob(22, sameTemplate, "userId", STOPPED,null, oldestDate),
+ () -> createNewJob(33, sameTemplate, "userId", PENDING,null, LocalDateTime.now().minusHours(2))),
+ 3,
+ 2,
+ PENDING,
+ "Broker should pull pending job when there is another job from this template that was deleted, although failed"
+ },
+ { ImmutableList.of(
+ (Jobber)() -> createNewJob(11, UUID.randomUUID(), "userA", IN_PROGRESS, null, oldestDate),
+ () -> createNewJob(22, UUID.randomUUID(), "userA", PENDING, null, oldestDate),
+ () -> createNewJob(33, UUID.randomUUID(), "userB", PENDING, null, LocalDateTime.now().minusHours(2))),
+ 3,
+ 2,
+ PENDING,
+ "Broker should prioritize jobs of user that has no in-progress jobs"
+ },
+ {ImmutableList.of(
+ (Jobber)() -> createNewJob(11, UUID.randomUUID(), "userA", PENDING, UUID.randomUUID().toString(), oldestDate),
+ () -> createNewJob(22, UUID.randomUUID(), "userA", PENDING, null, oldestDate),
+ () -> createNewJob(33, UUID.randomUUID(), "userB", PENDING, null, LocalDateTime.now().minusHours(2))),
+ 3,
+ 2,
+ PENDING,
+ "Broker should prioritize jobs of user that has no taken jobs"
+ },
+ {ImmutableList.of(
+ (Jobber)() -> createNewJob(11, UUID.randomUUID(), "userA", IN_PROGRESS, UUID.randomUUID().toString(), oldestDate),
+ () -> createNewJob(22, UUID.randomUUID(), "userA", PENDING, null, LocalDateTime.now().minusHours(2)),
+ () -> createNewJob(31, UUID.randomUUID(), "userB", IN_PROGRESS, null, LocalDateTime.now().minusHours(2)),
+ () -> createNewJob(32, UUID.randomUUID(), "userB", IN_PROGRESS, null, LocalDateTime.now().minusHours(2)),
+ () -> createNewJob(33, UUID.randomUUID(), "userB", PENDING, null, oldestDate)),
+ 5,
+ 4,
+ PENDING,
+ "Broker should take oldest job when there is one in-progress job to each user"
+ },
+ {ImmutableList.of(
+ (Jobber)() -> createNewJob(11, UUID.randomUUID(), UUID.randomUUID().toString(), IN_PROGRESS, null, oldestDate),
+ () -> createNewJob(22, UUID.randomUUID(), UUID.randomUUID().toString(), IN_PROGRESS, null, oldestDate),
+ () -> createNewJob(33, UUID.randomUUID(), UUID.randomUUID().toString(), PENDING, null, LocalDateTime.now().minusHours(2))),
+ 2,
+ -1,
+ PENDING,
+ "Broker should not pull any job when it exceeded mso limit with count(in-progress or pending && taken) statuses"
+ },
+ {ImmutableList.of(
+ (Jobber)() -> createNewJob(11, UUID.randomUUID(), "userId", IN_PROGRESS, UUID.randomUUID().toString(), oldestDate),
+ () -> createNewJob(22, UUID.randomUUID(), "userId", IN_PROGRESS, null, oldestDate),
+ () -> createNewJob(11, UUID.randomUUID(), "userId", IN_PROGRESS, null, LocalDateTime.now().minusHours(2)),
+ () -> createNewJob(44, UUID.randomUUID(), "userId", IN_PROGRESS, null, LocalDateTime.now().minusHours(5))),
+ 20,
+ 1,
+ IN_PROGRESS,
+ "Broker with in progress topic should pull the first in progress and not taken job by oldest date"
+ },
+ {ImmutableList.of(
+ (Jobber)() -> createNewJob(11, UUID.randomUUID(), "userId", COMPLETED, null, oldestDate),
+ () -> createNewJob(12, UUID.randomUUID(), "userId", FAILED, null, oldestDate),
+ () -> createNewJob(13, UUID.randomUUID(), "userId", PENDING, null, oldestDate),
+ () -> createNewJob(14, UUID.randomUUID(), "userId", STOPPED, null, oldestDate),
+ () -> createNewJob(15, UUID.randomUUID(), "userId", CREATING, null, oldestDate),
+ () -> createNewJob(11, UUID.randomUUID(), "userId", IN_PROGRESS, null, oldestDate, DELETED),
+ () -> createNewJob(22, UUID.randomUUID(), "userId", IN_PROGRESS, null, oldestDate),
+ () -> createNewJob(33, UUID.randomUUID(), "userId", IN_PROGRESS, null, LocalDateTime.now().minusHours(2)),
+ () -> createNewJob(16, UUID.randomUUID(), "userId", RESOURCE_IN_PROGRESS, null, oldestDate)
+ ),
+ 20,
+ 6,
+ IN_PROGRESS,
+ "Broker with in progress topic should pull only in-progress jobs - first in-progress job by oldest date - ignore all other statuses"
+ },
+ {ImmutableList.of(
+ (Jobber)() -> createNewJob(11, UUID.randomUUID(), "userId", COMPLETED, null, oldestDate),
+ () -> createNewJob(12, UUID.randomUUID(), "userId", FAILED, null, oldestDate),
+ () -> createNewJob(13, UUID.randomUUID(), "userId", PENDING, null, oldestDate),
+ () -> createNewJob(14, UUID.randomUUID(), "userId", STOPPED, null, oldestDate),
+ () -> createNewJob(15, UUID.randomUUID(), "userId", CREATING, null, oldestDate),
+ () -> createNewJob(11, UUID.randomUUID(), "userId", RESOURCE_IN_PROGRESS, null, oldestDate, DELETED),
+ () -> createNewJob(22, UUID.randomUUID(), "userId", RESOURCE_IN_PROGRESS, null, oldestDate),
+ () -> createNewJob(33, UUID.randomUUID(), "userId", RESOURCE_IN_PROGRESS, null, LocalDateTime.now().minusHours(2)),
+ () -> createNewJob(16, UUID.randomUUID(), "userId", IN_PROGRESS, null, oldestDate)
+ ),
+ 20,
+ 6,
+ RESOURCE_IN_PROGRESS,
+ "Broker with RESOURCE_IN_PROGRESS topic should pull only RESOURCE_IN_PROGRESS jobs - first RESOURCE_IN_PROGRESS job by oldest date - ignore all other statuses"
+ },
+ {ImmutableList.of(
+ (Jobber)() -> createNewJob(11, UUID.randomUUID(), "userId", IN_PROGRESS, null, LocalDateTime.now()),
+ () -> createNewJob(22, UUID.randomUUID(), "userId", IN_PROGRESS, null, LocalDateTime.now().minusSeconds(1)),
+ () -> createNewJob(33, UUID.randomUUID(), "userId", IN_PROGRESS, null, LocalDateTime.now().minusSeconds(2))),
+ 20,
+ -1,
+ IN_PROGRESS,
+ "Broker with in progress topic should not pull any job if its modified date is smaller than now-interval (20 seconds)"
+ },
+ {ImmutableList.of(
+ (Jobber)() -> createNewJob(11, UUID.randomUUID(), "userId", RESOURCE_IN_PROGRESS, null, LocalDateTime.now()),
+ () -> createNewJob(22, UUID.randomUUID(), "userId", RESOURCE_IN_PROGRESS, null, LocalDateTime.now().minusSeconds(1)),
+ () -> createNewJob(33, UUID.randomUUID(), "userId", RESOURCE_IN_PROGRESS, null, LocalDateTime.now().minusSeconds(2))),
+ 20,
+ -1,
+ RESOURCE_IN_PROGRESS,
+ "Broker with RESOURCE_IN_PROGRESS topic should not pull any job if its modified date is smaller than now-interval (20 seconds)"
+ },
+ {ImmutableList.of(
+ (Jobber)() -> createNewJob(11, UUID.randomUUID(), "userId", PENDING, null, LocalDateTime.now()),
+ () -> createNewJob(22, UUID.randomUUID(), "userId", CREATING, null, LocalDateTime.now().minusSeconds(1)),
+ () -> createNewJob(33, UUID.randomUUID(), "userId", CREATING, null, LocalDateTime.now().minusHours(2))),
+ 1,
+ 2,
+ CREATING,
+ "Broker with creating topic should pull oldest creating job and ignore mso limit"
+ },
+ {ImmutableList.of(
+ (Jobber)() -> createNewJob(33, UUID.randomUUID(), "userId", CREATING, null, LocalDateTime.now())),
+ 1,
+ 0,
+ CREATING,
+ "Broker with CREATING topic should pull CREATING job that was just modified"
+ }
+
+ };
+ }
+
+ public interface Jobber {
+ // Will defer LocalDateTime.now() to test's "real-time"
+ JobDaoImpl toJob();
+ }
+
+ @Test(enabled = false, dataProvider = "jobs")
+ public void givenSomeJobs_pullNextJob_returnNextOrNothingAsExpected(List<Jobber> jobbers, int msoLimit, int expectedIndexSelected, Job.JobStatus topic, String assertionReason) {
+ JobsBrokerServiceInDatabaseImpl broker = new JobsBrokerServiceInDatabaseImpl(dataAccessService, sessionFactory, msoLimit, 20);
+ final List<JobDaoImpl> jobs = jobbers.stream().map(Jobber::toJob).collect(toList());
+ for (JobDaoImpl job : jobs) {
+ Date modifiedDate = job.getModified();
+ broker.add(job);
+ setModifiedDateToJob(job.getUuid(), modifiedDate);
+ }
+ Optional<Job> nextJob = broker.pull(topic, UUID.randomUUID().toString());
+ boolean shouldAnyBeSelected = expectedIndexSelected >= 0;
+ String pulledJobDesc = nextJob.map(job -> ". pulled job: " + job.toString()).orElse(". no job pulled");
+ Assert.assertEquals(nextJob.isPresent(), shouldAnyBeSelected, assertionReason+pulledJobDesc);
+ if (shouldAnyBeSelected) {
+ Assert.assertEquals(jobs.get(expectedIndexSelected), nextJob.get(), assertionReason);
+ }
+ }
+
+ @DataProvider
+ public Object[][] topics() {
+ return Arrays.stream(Job.JobStatus.values())
+ .filter(not(t -> ImmutableList.of(PENDING, IN_PROGRESS, CREATING, RESOURCE_IN_PROGRESS).contains(t)))
+ .map(v -> new Object[]{v}).collect(toList()).toArray(new Object[][]{});
+ }
+
+ @Test(enabled = false, dataProvider = "topics", expectedExceptions = GenericUncheckedException.class, expectedExceptionsMessageRegExp = "Unsupported topic.*")
+ public void pullUnexpectedTopic_exceptionIsThrown(Job.JobStatus topic) {
+ broker.pull(topic, UUID.randomUUID().toString());
+ }
+
+ @Test(enabled = false, expectedExceptions = NoJobException.class)
+ public void givenNonPendingJobs_getJobAsPendingTopic_verifyNothingRetrieved() {
+ Stream.of(Job.JobStatus.values())
+ .filter(not(s -> s.equals(PENDING)))
+ .map(s -> createMockJob("some user id", s))
+ .map(job -> newJobAsync(broker, job))
+ .map(this::waitForFutureJob)
+ .collect(toList());
+
+ waitForFutureOptionalJob(pullJobAsync(broker));
+ }
+
+ @Test(enabled = false)
+ public void givenPendingAndNonPendingJobs_getJobAsPendingTopic_verifyAJobRetrieved() {
+ newJobAsync(broker); // this negated the expected result of the call below
+ givenNonPendingJobs_getJobAsPendingTopic_verifyNothingRetrieved();
+ }
+
+ @Test(enabled = false, expectedExceptions = NoJobException.class)
+ public void givenManyJobs_pullThemAllAndAskOneMore_verifyFinallyNothingRetrieved() {
+ putAndGetALotOfJobs(broker);
+ waitForFutureOptionalJob(pullJobAsync(broker));
+ }
+
+ @Test(enabled = false, expectedExceptions = NoJobException.class)
+ public void givenNoJob_requestJob_verifyNothingRetrieved() throws InterruptedException, ExecutionException, TimeoutException {
+ final Future<Optional<Job>> futureOptionalJob = pullJobAsync(broker);
+ assertThat("job should not be waiting yet", futureOptionalJob.get(FEW, MILLISECONDS).isPresent(), is(false));
+ waitForFutureOptionalJob(futureOptionalJob);
+ }
+
+ @Test(enabled = false, expectedExceptions = IllegalStateException.class)
+ public void givenSinglePulledJob_pushBackDifferentJob_verifyPushingRejected() {
+ waitForFutureJob(newJobAsync(broker));
+ waitForFutureJob(newJobAsync(broker));
+ waitForFutureOptionalJob(pullJobAsync(broker));
+
+ Job myJob = createMockJob("user id");
+ myJob.setUuid(UUID.randomUUID());
+
+ broker.pushBack(myJob); //Should fail
+ }
+
+ @Test(enabled = false)
+ public void givenSingleJob_pushBackModifiedJob_verifyPulledIsVeryVeryTheSame() {
+ final ImmutableMap<String, Object> randomDataForMostRecentJobType =
+ ImmutableMap.of("42", 42, "complex", ImmutableList.of("a", "b", "c"));
+
+ waitForFutureJob(newJobAsync(broker));
+ final Job job = waitForFutureOptionalJob(pullJobAsync(broker));
+
+ job.setStatus(Job.JobStatus.PENDING);
+ job.setTypeAndData(JobType.NoOp, ImmutableMap.of("good", "morning"));
+ job.setTypeAndData(JobType.HttpCall, ImmutableMap.of());
+ job.setTypeAndData(JobType.MacroServiceInstantiation, randomDataForMostRecentJobType);
+
+ broker.pushBack(job);
+ final Job retrievedJob = waitForFutureOptionalJob(pullJobAsync(broker));
+
+ assertThat(JOBS_SHOULD_MATCH, retrievedJob, is(job));
+ assertThat(JOBS_SHOULD_MATCH, retrievedJob.getData(), both(equalTo(job.getData())).and(equalTo(randomDataForMostRecentJobType)));
+ assertThat(JOBS_SHOULD_MATCH, jobDataReflected(retrievedJob), is(jobDataReflected(job)));
+ }
+
+ private static String jobDataReflected(Job job) {
+ return new ReflectionToStringBuilder(job, ToStringStyle.SHORT_PREFIX_STYLE)
+ .setExcludeFieldNames("created", "modified", "takenBy")
+ .toString();
+ }
+
+ @Test(enabled = false, expectedExceptions = IllegalStateException.class)
+ public void givenSingleJob_pushBackTwice_verifyPushingRejected() {
+ waitForFutureJob(newJobAsync(broker));
+ final Job job = waitForFutureOptionalJob(pullJobAsync(broker));
+
+ broker.pushBack(job);
+ broker.pushBack(job); //Should fail
+ }
+
+ @Test(enabled = false)
+ public void addJob_PeekItById_verifySameJobWasPeeked() {
+ String userId = UUID.randomUUID().toString();
+ Job myJob = createMockJob(userId);
+ UUID uuid = broker.add(myJob);
+ Job peekedJob = broker.peek(uuid);
+ assertEquals("added testId is not the same as peeked TestsId",
+ userId,
+ peekedJob.getSharedData().getUserId());
+ }
+
+ @Test(enabled = false, dataProvider = "jobStatusesForSuccessDelete", expectedExceptions = NoJobException.class)
+ public void givenOneJob_deleteIt_canPeekOnItButCantPull(Job.JobStatus status) {
+ final Job job = waitForFutureJob(newJobAsync(broker, status));
+ broker.delete(job.getUuid());
+ assertNotNull(((JobDaoImpl) broker.peek(job.getUuid())).getDeletedAt(), "job should be deleted");
+ waitForFutureOptionalJob(pullJobAsync(broker));
+ }
+
+ @DataProvider
+ public static Object[][] jobStatusesForSuccessDelete() {
+ return new Object[][]{
+ {PENDING},
+ {STOPPED}
+ };
+ }
+
+ @Test(enabled = false,
+ dataProvider = "jobStatusesForFailedDelete",
+ expectedExceptions = OperationNotAllowedException.class,
+ expectedExceptionsMessageRegExp=DELETE_SERVICE_INFO_STATUS_EXCEPTION_MESSAGE
+ )
+ public void deleteJob_notAllowedStatus_exceptionIsThrown(Job.JobStatus status, boolean taken) {
+ final Job job = waitForFutureJob(newJobAsync(broker, createMockJob("some user id", status)));
+
+ if (taken) {
+ waitForFutureOptionalJob(pullJobAsync(broker));
+ }
+
+
+ broker.delete(job.getUuid());
+ }
+
+ @DataProvider
+ public static Object[][] jobStatusesForFailedDelete() {
+ return new Object[][]{
+ {PENDING, true},
+ {IN_PROGRESS, false},
+ {COMPLETED, false},
+ {PAUSE, false},
+ {FAILED, false},
+ };
+ }
+
+ @Test(enabled = false, expectedExceptions = OperationNotAllowedException.class, expectedExceptionsMessageRegExp = DELETE_SERVICE_NOT_EXIST_EXCEPTION_MESSAGE)
+ public void deleteJob_notExist_exceptionIsThrown() {
+ waitForFutureJob(newJobAsync(broker, createMockJob("some user id", PENDING)));
+ broker.delete(new UUID(111, 111));
+ }
+
+}
diff --git a/vid-app-common/src/test/java/org/onap/vid/services/PortDetailsTranslatorTest.java b/vid-app-common/src/test/java/org/onap/vid/services/PortDetailsTranslatorTest.java
index cb9eb93d0..004977347 100644
--- a/vid-app-common/src/test/java/org/onap/vid/services/PortDetailsTranslatorTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/services/PortDetailsTranslatorTest.java
@@ -1,19 +1,12 @@
package org.onap.vid.services;
+import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableList;
-import org.codehaus.jackson.map.ObjectMapper;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-import org.onap.vid.aai.model.AaiGetPortMirroringSourcePorts;
+import org.onap.vid.aai.model.CustomQuerySimpleResult;
import org.onap.vid.aai.model.PortDetailsTranslator;
import org.onap.vid.aai.model.RelatedTo;
import org.onap.vid.aai.model.SimpleResult;
-import org.onap.vid.properties.Features;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
-import org.togglz.core.manager.FeatureManager;
import java.io.IOException;
import java.util.List;
@@ -25,49 +18,38 @@ import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.collection.IsEmptyCollection.empty;
-import static org.mockito.Mockito.when;
public class PortDetailsTranslatorTest {
private static final ObjectMapper om = new ObjectMapper();
- @InjectMocks
private PortDetailsTranslator portDetailsTranslator = new PortDetailsTranslator();
- @Mock
- private FeatureManager featureManager;
-
- @BeforeMethod
- public void initMocks() throws Exception {
- MockitoAnnotations.initMocks(this);
- when(featureManager.isActive(Features.FLAG_ADVANCED_PORTS_FILTER)).thenReturn(true);
- }
-
@Test
public void extractPortDetailsFromProperties_givenValidAaiResponse() throws IOException {
- final String aaiResponse = "{\n" +
- " \"results\": [\n" +
- " {\n" +
- " \"id\": \"4876980240\",\n" +
- " \"node-type\": \"l-interface\",\n" +
- " \"url\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/att-aic/rdm5b/tenants/tenant/460f35aeb53542dc9f77105066483e83/vservers/vserver/15e46e2f-4b98-4e06-9644-f0e6e35cc79a/l-interfaces/l-interface/zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\",\n" +
- " \"properties\": {\n" +
- " \"interface-name\": \"zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\",\n" +
- " \"selflink\": \"https://network-aic.rdm5b.cci.att.com:9696/v2.0/ports/6de7bf87-6faa-4984-9492-18d1188b3d4a\",\n" +
- " \"interface-id\": \"6de7bf87-6faa-4984-9492-18d1188b3d4a\",\n" +
- " \"macaddr\": \"02:6d:e7:bf:87:6f\",\n" +
- " \"network-name\": \"APP-C-24595-D-T001-vprobe_int_pktmirror_net_1\",\n" +
- " \"is-port-mirrored\": false,\n" +
- " \"resource-version\": \"1519383879190\",\n" +
- " \"in-maint\": false,\n" +
- " \"is-ip-unnumbered\": false\n" +
- " }\n" +
- " }\n" +
- " ]\n" +
+ final String aaiResponse = "{" +
+ " \"results\": [" +
+ " {" +
+ " \"id\": \"4876980240\"," +
+ " \"node-type\": \"l-interface\"," +
+ " \"url\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/att-aic/rdm5b/tenants/tenant/460f35aeb53542dc9f77105066483e83/vservers/vserver/15e46e2f-4b98-4e06-9644-f0e6e35cc79a/l-interfaces/l-interface/zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\"," +
+ " \"properties\": {" +
+ " \"interface-name\": \"zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\"," +
+ " \"selflink\": \"https://network-aic.rdm5b.cci.att.com:9696/v2.0/ports/6de7bf87-6faa-4984-9492-18d1188b3d4a\"," +
+ " \"interface-id\": \"6de7bf87-6faa-4984-9492-18d1188b3d4a\"," +
+ " \"macaddr\": \"02:6d:e7:bf:87:6f\"," +
+ " \"network-name\": \"APP-C-24595-D-T001-vprobe_int_pktmirror_net_1\"," +
+ " \"is-port-mirrored\": false," +
+ " \"resource-version\": \"1519383879190\"," +
+ " \"in-maint\": false," +
+ " \"is-ip-unnumbered\": false" +
+ " }" +
+ " }" +
+ " ]" +
"}";
- AaiGetPortMirroringSourcePorts aaiGetPortMirroringSourcePorts = om.readValue(aaiResponse, AaiGetPortMirroringSourcePorts.class);
+ CustomQuerySimpleResult aaiGetPortMirroringSourcePorts = om.readValue(aaiResponse, CustomQuerySimpleResult.class);
PortDetailsTranslator.PortDetails portDetails = PortDetailsTranslator.extractPortDetailsFromProperties(aaiGetPortMirroringSourcePorts.getResults().get(0).getProperties(), aaiResponse);
@@ -82,29 +64,29 @@ public class PortDetailsTranslatorTest {
@Test
public void extractPortDetailsFromProperties_givenAaiResponseWithInstanceNameNull_yieldException() throws IOException {
- final String aaiResponse = "{\n" +
- " \"results\": [\n" +
- " {\n" +
- " \"id\": \"4876980240\",\n" +
- " \"node-type\": \"l-interface\",\n" +
- " \"url\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/att-aic/rdm5b/tenants/tenant/460f35aeb53542dc9f77105066483e83/vservers/vserver/15e46e2f-4b98-4e06-9644-f0e6e35cc79a/l-interfaces/l-interface/zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\",\n" +
- " \"properties\": {\n" +
- " \"interface-name\": null,\n" +
- " \"selflink\": \"https://network-aic.rdm5b.cci.att.com:9696/v2.0/ports/6de7bf87-6faa-4984-9492-18d1188b3d4a\",\n" +
- " \"interface-id\": \"6de7bf87-6faa-4984-9492-18d1188b3d4a\",\n" +
- " \"macaddr\": \"02:6d:e7:bf:87:6f\",\n" +
- " \"network-name\": \"APP-C-24595-D-T001-vprobe_int_pktmirror_net_1\",\n" +
- " \"is-port-mirrored\": false,\n" +
- " \"resource-version\": \"1519383879190\",\n" +
- " \"in-maint\": false,\n" +
- " \"is-ip-unnumbered\": false\n" +
- " }\n" +
- " }\n" +
- " ]\n" +
+ final String aaiResponse = "{" +
+ " \"results\": [" +
+ " {" +
+ " \"id\": \"4876980240\"," +
+ " \"node-type\": \"l-interface\"," +
+ " \"url\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/att-aic/rdm5b/tenants/tenant/460f35aeb53542dc9f77105066483e83/vservers/vserver/15e46e2f-4b98-4e06-9644-f0e6e35cc79a/l-interfaces/l-interface/zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\"," +
+ " \"properties\": {" +
+ " \"interface-name\": null," +
+ " \"selflink\": \"https://network-aic.rdm5b.cci.att.com:9696/v2.0/ports/6de7bf87-6faa-4984-9492-18d1188b3d4a\"," +
+ " \"interface-id\": \"6de7bf87-6faa-4984-9492-18d1188b3d4a\"," +
+ " \"macaddr\": \"02:6d:e7:bf:87:6f\"," +
+ " \"network-name\": \"APP-C-24595-D-T001-vprobe_int_pktmirror_net_1\"," +
+ " \"is-port-mirrored\": false," +
+ " \"resource-version\": \"1519383879190\"," +
+ " \"in-maint\": false," +
+ " \"is-ip-unnumbered\": false" +
+ " }" +
+ " }" +
+ " ]" +
"}";
- AaiGetPortMirroringSourcePorts aaiGetPortMirroringSourcePorts = om.readValue(aaiResponse, AaiGetPortMirroringSourcePorts.class);
- PortDetailsTranslator.PortDetails portDetails = PortDetailsTranslator.extractPortDetailsFromProperties(aaiGetPortMirroringSourcePorts.getResults().get(0).getProperties(),aaiResponse);
+ CustomQuerySimpleResult aaiGetPortMirroringSourcePorts = om.readValue(aaiResponse, CustomQuerySimpleResult.class);
+ PortDetailsTranslator.PortDetails portDetails = PortDetailsTranslator.extractPortDetailsFromProperties(aaiGetPortMirroringSourcePorts.getResults().get(0).getProperties(), aaiResponse);
assertThat(portDetails, is(instanceOf(PortDetailsTranslator.PortDetailsError.class)));
@@ -115,29 +97,29 @@ public class PortDetailsTranslatorTest {
@Test
public void extractPortDetailsFromProperties_givenAaiResponseWithInstanceIdNull_yieldException() throws IOException {
- final String aaiResponse = "{\n" +
- " \"results\": [\n" +
- " {\n" +
- " \"id\": \"4876980240\",\n" +
- " \"node-type\": \"l-interface\",\n" +
- " \"url\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/att-aic/rdm5b/tenants/tenant/460f35aeb53542dc9f77105066483e83/vservers/vserver/15e46e2f-4b98-4e06-9644-f0e6e35cc79a/l-interfaces/l-interface/zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\",\n" +
- " \"properties\": {\n" +
- " \"interface-name\": \"zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\",\n" +
- " \"selflink\": \"https://network-aic.rdm5b.cci.att.com:9696/v2.0/ports/6de7bf87-6faa-4984-9492-18d1188b3d4a\",\n" +
- " \"interface-id\": null,\n" +
- " \"macaddr\": \"02:6d:e7:bf:87:6f\",\n" +
- " \"network-name\": \"APP-C-24595-D-T001-vprobe_int_pktmirror_net_1\",\n" +
- " \"is-port-mirrored\": false,\n" +
- " \"resource-version\": \"1519383879190\",\n" +
- " \"in-maint\": false,\n" +
- " \"is-ip-unnumbered\": false\n" +
- " }\n" +
- " }\n" +
- " ]\n" +
+ final String aaiResponse = "{" +
+ " \"results\": [" +
+ " {" +
+ " \"id\": \"4876980240\"," +
+ " \"node-type\": \"l-interface\"," +
+ " \"url\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/att-aic/rdm5b/tenants/tenant/460f35aeb53542dc9f77105066483e83/vservers/vserver/15e46e2f-4b98-4e06-9644-f0e6e35cc79a/l-interfaces/l-interface/zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\"," +
+ " \"properties\": {" +
+ " \"interface-name\": \"zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\"," +
+ " \"selflink\": \"https://network-aic.rdm5b.cci.att.com:9696/v2.0/ports/6de7bf87-6faa-4984-9492-18d1188b3d4a\"," +
+ " \"interface-id\": null," +
+ " \"macaddr\": \"02:6d:e7:bf:87:6f\"," +
+ " \"network-name\": \"APP-C-24595-D-T001-vprobe_int_pktmirror_net_1\"," +
+ " \"is-port-mirrored\": false," +
+ " \"resource-version\": \"1519383879190\"," +
+ " \"in-maint\": false," +
+ " \"is-ip-unnumbered\": false" +
+ " }" +
+ " }" +
+ " ]" +
"}";
- AaiGetPortMirroringSourcePorts aaiGetPortMirroringSourcePorts = om.readValue(aaiResponse, AaiGetPortMirroringSourcePorts.class);
- PortDetailsTranslator.PortDetails portDetails = PortDetailsTranslator.extractPortDetailsFromProperties(aaiGetPortMirroringSourcePorts.getResults().get(0).getProperties(),aaiResponse);
+ CustomQuerySimpleResult aaiGetPortMirroringSourcePorts = om.readValue(aaiResponse, CustomQuerySimpleResult.class);
+ PortDetailsTranslator.PortDetails portDetails = PortDetailsTranslator.extractPortDetailsFromProperties(aaiGetPortMirroringSourcePorts.getResults().get(0).getProperties(), aaiResponse);
assertThat(portDetails, is(instanceOf(PortDetailsTranslator.PortDetailsError.class)));
@@ -148,29 +130,29 @@ public class PortDetailsTranslatorTest {
@Test
public void extractPortDetailsFromProperties_givenAaiResponseWithEmptyInstanceId_yieldException() throws IOException {
- final String aaiResponse = "{\n" +
- " \"results\": [\n" +
- " {\n" +
- " \"id\": \"4876980240\",\n" +
- " \"node-type\": \"l-interface\",\n" +
- " \"url\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/att-aic/rdm5b/tenants/tenant/460f35aeb53542dc9f77105066483e83/vservers/vserver/15e46e2f-4b98-4e06-9644-f0e6e35cc79a/l-interfaces/l-interface/zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\",\n" +
- " \"properties\": {\n" +
- " \"interface-name\": \"\",\n" +
- " \"selflink\": \"https://network-aic.rdm5b.cci.att.com:9696/v2.0/ports/6de7bf87-6faa-4984-9492-18d1188b3d4a\",\n" +
- " \"interface-id\": \"6de7bf87-6faa-4984-9492-18d1188b3d4a\",\n" +
- " \"macaddr\": \"02:6d:e7:bf:87:6f\",\n" +
- " \"network-name\": \"APP-C-24595-D-T001-vprobe_int_pktmirror_net_1\",\n" +
- " \"is-port-mirrored\": false,\n" +
- " \"resource-version\": \"1519383879190\",\n" +
- " \"in-maint\": false,\n" +
- " \"is-ip-unnumbered\": false\n" +
- " }\n" +
- " }\n" +
- " ]\n" +
+ final String aaiResponse = "{" +
+ " \"results\": [" +
+ " {" +
+ " \"id\": \"4876980240\"," +
+ " \"node-type\": \"l-interface\"," +
+ " \"url\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/att-aic/rdm5b/tenants/tenant/460f35aeb53542dc9f77105066483e83/vservers/vserver/15e46e2f-4b98-4e06-9644-f0e6e35cc79a/l-interfaces/l-interface/zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\"," +
+ " \"properties\": {" +
+ " \"interface-name\": \"\"," +
+ " \"selflink\": \"https://network-aic.rdm5b.cci.att.com:9696/v2.0/ports/6de7bf87-6faa-4984-9492-18d1188b3d4a\"," +
+ " \"interface-id\": \"6de7bf87-6faa-4984-9492-18d1188b3d4a\"," +
+ " \"macaddr\": \"02:6d:e7:bf:87:6f\"," +
+ " \"network-name\": \"APP-C-24595-D-T001-vprobe_int_pktmirror_net_1\"," +
+ " \"is-port-mirrored\": false," +
+ " \"resource-version\": \"1519383879190\"," +
+ " \"in-maint\": false," +
+ " \"is-ip-unnumbered\": false" +
+ " }" +
+ " }" +
+ " ]" +
"}";
- AaiGetPortMirroringSourcePorts aaiGetPortMirroringSourcePorts = om.readValue(aaiResponse, AaiGetPortMirroringSourcePorts.class);
- PortDetailsTranslator.PortDetails portDetails = PortDetailsTranslator.extractPortDetailsFromProperties(aaiGetPortMirroringSourcePorts.getResults().get(0).getProperties(),aaiResponse);
+ CustomQuerySimpleResult aaiGetPortMirroringSourcePorts = om.readValue(aaiResponse, CustomQuerySimpleResult.class);
+ PortDetailsTranslator.PortDetails portDetails = PortDetailsTranslator.extractPortDetailsFromProperties(aaiGetPortMirroringSourcePorts.getResults().get(0).getProperties(), aaiResponse);
assertThat(portDetails, is(instanceOf(PortDetailsTranslator.PortDetailsError.class)));
@@ -181,29 +163,29 @@ public class PortDetailsTranslatorTest {
@Test
public void extractPortDetailsFromProperties_givenAaiResponseWithIsPortMirroredNull_yieldException() throws IOException {
- final String aaiResponse = "{\n" +
- " \"results\": [\n" +
- " {\n" +
- " \"id\": \"4876980240\",\n" +
- " \"node-type\": \"l-interface\",\n" +
- " \"url\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/att-aic/rdm5b/tenants/tenant/460f35aeb53542dc9f77105066483e83/vservers/vserver/15e46e2f-4b98-4e06-9644-f0e6e35cc79a/l-interfaces/l-interface/zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\",\n" +
- " \"properties\": {\n" +
- " \"interface-name\": \"zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\",\n" +
- " \"selflink\": \"https://network-aic.rdm5b.cci.att.com:9696/v2.0/ports/6de7bf87-6faa-4984-9492-18d1188b3d4a\",\n" +
- " \"interface-id\": \"6de7bf87-6faa-4984-9492-18d1188b3d4a\",\n" +
- " \"macaddr\": \"02:6d:e7:bf:87:6f\",\n" +
- " \"network-name\": \"APP-C-24595-D-T001-vprobe_int_pktmirror_net_1\",\n" +
- " \"is-port-mirrored\": null,\n" +
- " \"resource-version\": \"1519383879190\",\n" +
- " \"in-maint\": false,\n" +
- " \"is-ip-unnumbered\": false\n" +
- " }\n" +
- " }\n" +
- " ]\n" +
+ final String aaiResponse = "{" +
+ " \"results\": [" +
+ " {" +
+ " \"id\": \"4876980240\"," +
+ " \"node-type\": \"l-interface\"," +
+ " \"url\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/att-aic/rdm5b/tenants/tenant/460f35aeb53542dc9f77105066483e83/vservers/vserver/15e46e2f-4b98-4e06-9644-f0e6e35cc79a/l-interfaces/l-interface/zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\"," +
+ " \"properties\": {" +
+ " \"interface-name\": \"zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\"," +
+ " \"selflink\": \"https://network-aic.rdm5b.cci.att.com:9696/v2.0/ports/6de7bf87-6faa-4984-9492-18d1188b3d4a\"," +
+ " \"interface-id\": \"6de7bf87-6faa-4984-9492-18d1188b3d4a\"," +
+ " \"macaddr\": \"02:6d:e7:bf:87:6f\"," +
+ " \"network-name\": \"APP-C-24595-D-T001-vprobe_int_pktmirror_net_1\"," +
+ " \"is-port-mirrored\": null," +
+ " \"resource-version\": \"1519383879190\"," +
+ " \"in-maint\": false," +
+ " \"is-ip-unnumbered\": false" +
+ " }" +
+ " }" +
+ " ]" +
"}";
- AaiGetPortMirroringSourcePorts aaiGetPortMirroringSourcePorts = om.readValue(aaiResponse, AaiGetPortMirroringSourcePorts.class);
- PortDetailsTranslator.PortDetails portDetails = PortDetailsTranslator.extractPortDetailsFromProperties(aaiGetPortMirroringSourcePorts.getResults().get(0).getProperties(),aaiResponse);
+ CustomQuerySimpleResult aaiGetPortMirroringSourcePorts = om.readValue(aaiResponse, CustomQuerySimpleResult.class);
+ PortDetailsTranslator.PortDetails portDetails = PortDetailsTranslator.extractPortDetailsFromProperties(aaiGetPortMirroringSourcePorts.getResults().get(0).getProperties(), aaiResponse);
assertThat(portDetails, is(instanceOf(PortDetailsTranslator.PortDetailsError.class)));
@@ -221,17 +203,8 @@ public class PortDetailsTranslatorTest {
assertThat("List size if different than expected", result, is(empty()));
}
- @DataProvider
- public static Object[][] trueAndFalse() {
- return new Object[][]{
- { Boolean.TRUE }, { Boolean.FALSE }
- };
- }
-
- @Test(dataProvider = "trueAndFalse")
- public void getFilteredPortList_givenFeatureFlagIsOff_returnAllLInterfaces(Boolean advancedPortsFilterFlag) throws IOException {
- when(featureManager.isActive(Features.FLAG_ADVANCED_PORTS_FILTER)).thenReturn(advancedPortsFilterFlag);
-
+ @Test
+ public void getFilteredPortList_givenFeatureFlagIsOff_returnAllLInterfaces() {
final String relationshipLabelSource = "org.onap.relationships.inventory.Source";
final String nodeTypeLInterface = "l-interface";
@@ -258,22 +231,16 @@ public class PortDetailsTranslatorTest {
List<SimpleResult> result = portDetailsTranslator.getFilteredPortList(input);
- if (advancedPortsFilterFlag) {
- assertThat("List should contain all l-interfaces with a related source", result, containsInAnyOrder(
- lInterfaceWithSource, lInterfaceWithSourceAndMore,
- lInterfaceWithTwoSources));
- } else {
- assertThat("List should contain all l-interfaces", result, containsInAnyOrder(
- lInterfaceWithSource, lInterfaceWithoutSource,
- lInterfaceWithoutRelations, lInterfaceWithSourceAndMore,
- lInterfaceWithTwoSources));
- }
+ assertThat("List should contain all l-interfaces with a related source", result, containsInAnyOrder(
+ lInterfaceWithSource, lInterfaceWithSourceAndMore,
+ lInterfaceWithTwoSources));
+
}
private SimpleResult buildSimpleResult(String nodeType, String... relationshipLabels) {
SimpleResult simpleResult = new SimpleResult();
- simpleResult.setNodeType(nodeType);
- simpleResult.setRelatedTo(Stream.of(relationshipLabels).map(label ->
+ simpleResult.setJsonNodeType(nodeType);
+ simpleResult.setJsonRelatedTo(Stream.of(relationshipLabels).map(label ->
new RelatedTo("my foo id", label, "logical-link", "foo url"))
.collect(Collectors.toList())
);
diff --git a/vid-app-common/src/test/java/org/onap/vid/services/SchedulerServiceImplTest.java b/vid-app-common/src/test/java/org/onap/vid/services/SchedulerServiceImplTest.java
new file mode 100644
index 000000000..c4f77e3e1
--- /dev/null
+++ b/vid-app-common/src/test/java/org/onap/vid/services/SchedulerServiceImplTest.java
@@ -0,0 +1,179 @@
+package org.onap.vid.services;
+
+import com.fasterxml.jackson.core.JsonParseException;
+import org.apache.xmlbeans.SystemProperties;
+import org.hamcrest.Matcher;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.MockitoAnnotations;
+import org.onap.vid.aai.ExceptionWithRequestInfo;
+import org.onap.vid.exceptions.GenericUncheckedException;
+import org.onap.vid.exceptions.NotFoundException;
+import org.onap.vid.model.probes.ErrorMetadata;
+import org.onap.vid.model.probes.ExternalComponentStatus;
+import org.onap.vid.model.probes.HttpRequestMetadata;
+import org.onap.vid.mso.RestObject;
+import org.onap.vid.mso.RestObjectWithRequestInfo;
+import org.onap.vid.scheduler.SchedulerServiceImpl;
+import org.springframework.http.HttpMethod;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
+import org.springframework.test.context.web.WebAppConfiguration;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeTest;
+import org.testng.annotations.Test;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.*;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import static org.onap.vid.model.probes.ExternalComponentStatus.Component.SCHEDULER;
+
+@ContextConfiguration(classes = {SystemProperties.class})
+@WebAppConfiguration
+public class SchedulerServiceImplTest extends AbstractTestNGSpringContextTests {
+
+ @InjectMocks
+ private SchedulerServiceImpl schedulerService;
+
+ @Mock
+ private ChangeManagementService changeManagementService;
+
+
+ @BeforeTest
+ public void initMocks() {
+ MockitoAnnotations.initMocks(this);
+ }
+
+ @AfterMethod
+ public void reset() {
+ Mockito.reset(changeManagementService);
+ }
+
+ @Test
+ public void probeGetSchedulerChangeManegements_verifyGoodRequest(){
+ String responseString = "[" +
+ " {" +
+ " \"vnfName\": \"dbox0001v\"," +
+ " \"status\": \"Triggered\"," +
+ " \"aotsChangeId\": \"CHG000000000001\"," +
+ " \"aotsApprovalStatus\": \"Approved\"," +
+ " \"groupId\": \"groupId\"," +
+ " \"dispatchTime\": \"2018-05-09T14:05:43Z\"," +
+ " \"msoRequestId\": \"2fb4edd1-01c4-4fee-bd4a-4ae6282aa213\"," +
+ " \"scheduleRequest\": {" +
+ " \"id\": 1," +
+ " \"createDateTime\": \"2018-05-09T14:05:34Z\"," +
+ " \"optimizerAttemptsToSchedule\": 0," +
+ " \"optimizerTransactionId\": \"70f05563-6705-4be0-802a-8b6b78a69d63\"," +
+ " \"scheduleId\": \"70f05563-6705-4be0-802a-8b6b78a69d63\"," +
+ " \"scheduleName\": \"70f05563-6705-4be0-802a-8b6b78a69d63\"," +
+ " \"status\": \"Notifications Initiated\"," +
+ " \"userId\": \"wl849v\"," +
+ " \"domain\": \"ChangeManagement\"," +
+ " \"domainData\": [" +
+ " {" +
+ " \"id\": 1," +
+ " \"name\": \"WorkflowName\"," +
+ " \"value\": \"VNF In Place Software Update\"" +
+ " }," +
+ " {" +
+ " \"id\": 2," +
+ " \"name\": \"CallbackUrl\"," +
+ " \"value\": \"https://vid-web-ete-new.ecomp.cci.att.com:8000/vid/change-management/workflow/\"" +
+ " }," +
+ " {" +
+ " \"id\": 3," +
+ " \"name\": \"CallbackData\"," +
+ " \"value\": \"{\\\"requestType\\\":\\\"VNF In Place Software Update\\\",\\\"requestDetails\\\":[{\\\"vnfName\\\":\\\"dbox0001v\\\",\\\"vnfInstanceId\\\":\\\"815d38c0-b686-491c-9a74-0b49add524ca\\\",\\\"modelInfo\\\":{\\\"modelType\\\":\\\"vnf\\\",\\\"modelInvariantId\\\":\\\"59f4e0b2-e1b0-4e3b-bae3-e7b8c5d32985\\\",\\\"modelVersionId\\\":\\\"345643c1-3a51-423f-aac1-502e027d8dab\\\",\\\"modelName\\\":\\\"dbox0001v\\\",\\\"modelCustomizationId\\\":\\\"01ce23cb-d276-4d71-a5f1-f9d42d0df543\\\"},\\\"cloudConfiguration\\\":{\\\"lcpCloudRegionId\\\":\\\"dpa2b\\\",\\\"tenantId\\\":\\\"b60da4f71c1d4b35b8113d4eca6deaa1\\\"},\\\"requestInfo\\\":{\\\"source\\\":\\\"VID\\\",\\\"suppressRollback\\\":false,\\\"requestorId\\\":\\\"wl849v\\\"},\\\"relatedInstanceList\\\":[{\\\"relatedInstance\\\":{\\\"instanceId\\\":\\\"eb774932-e9fa-4c7f-bbc1-229b6b2b11e2\\\",\\\"modelInfo\\\":{\\\"modelType\\\":\\\"service\\\",\\\"modelInvariantId\\\":\\\"57dd617b-d64e-4441-a287-4d158b24ba65\\\",\\\"modelVersionId\\\":\\\"345643c1-3a51-423f-aac1-502e027d8dab\\\",\\\"modelName\\\":\\\"control_loop_dbe_svc\\\",\\\"modelVersion\\\":\\\"2.0\\\"}}}],\\\"requestParameters\\\":{\\\"payload\\\":\\\"{\\\\\\\"existing_software_version\\\\\\\":\\\\\\\"2\\\\\\\",\\\\\\\"new_software_version\\\\\\\":\\\\\\\"1\\\\\\\",\\\\\\\"operations_timeout\\\\\\\":\\\\\\\"3\\\\\\\"}\\\",\\\"testApi\\\":\\\"GR_API\\\"}}]}\"" +
+ " }" +
+ " ]," +
+ " \"scheduleApprovals\": []" +
+ " }," +
+ " \"schedulesId\": 0" +
+ " }" +
+ "]";;
+
+ final RestObject mockedRestObject = mock(RestObject.class);
+
+ final RestObjectWithRequestInfo restObjectWithRequestInfo = new RestObjectWithRequestInfo(HttpMethod.GET, "my pretty url", mockedRestObject, 200, responseString);
+
+ when(changeManagementService.getSchedulerChangeManagementsWithRequestInfo()).thenReturn(
+ restObjectWithRequestInfo
+ );
+
+ final ExternalComponentStatus schedulerStatus = schedulerService.probeGetSchedulerChangeManagements();
+
+ assertSchedulerStatus(schedulerStatus, true);
+ assertMetadata(schedulerStatus, 200, startsWith(responseString.substring(0, 400)), "my pretty url", equalTo("OK"));
+ }
+
+ @Test
+ public void probeGetSchedulerChangeManegements_response200OkButEmptyPayload_shouldDescribeCorrectly() {
+ String responseString = "" +
+ "[]";
+
+ final RestObject mockedRestObject = mock(RestObject.class);
+
+ final RestObjectWithRequestInfo restObjectWithRequestInfo = new RestObjectWithRequestInfo(HttpMethod.GET, "my pretty url", mockedRestObject, 200, responseString);
+
+ when(changeManagementService.getSchedulerChangeManagementsWithRequestInfo()).thenReturn(
+ restObjectWithRequestInfo
+ );
+
+ final ExternalComponentStatus schedulerStatus = schedulerService.probeGetSchedulerChangeManagements();
+
+ assertSchedulerStatus(schedulerStatus, true);
+
+ assertMetadata(schedulerStatus, 200, equalTo(responseString), "my pretty url", containsString("OK"));
+ }
+
+ @Test
+ public void probeGetSchedulerChangeManegements_response200OkButInvalidPayload_shouldDescribeCorrectly() {
+ String responseString = "this payload is an invalid json";
+
+ final RestObject mockedRestObject = mock(RestObject.class);
+
+ final RestObjectWithRequestInfo restObjectWithRequestInfo = new RestObjectWithRequestInfo(HttpMethod.GET, "my pretty url", mockedRestObject, 200, responseString);
+
+ when(changeManagementService.getSchedulerChangeManagementsWithRequestInfo()).thenThrow(new ExceptionWithRequestInfo(HttpMethod.GET,
+ "my pretty url", responseString, 200, new JsonParseException(null, "Unrecognized token")));
+
+ final ExternalComponentStatus schedulerStatus = schedulerService.probeGetSchedulerChangeManagements();
+
+ assertSchedulerStatus(schedulerStatus, false);
+
+ assertMetadata(schedulerStatus, 200, equalTo(responseString), "my pretty url", containsString("JsonParseException: Unrecognized token"));
+ }
+
+ @Test
+ public void probeGetSchedulerChangeManegements_throwNotFoundException_resultIsWithErrorMetadata() {
+ when(changeManagementService.getSchedulerChangeManagementsWithRequestInfo()).thenThrow(
+ new GenericUncheckedException(new NotFoundException("Get with status = 400")));
+
+ final ExternalComponentStatus schedulerStatus = schedulerService.probeGetSchedulerChangeManagements();
+
+ assertThat(schedulerStatus.isAvailable(), is(false));
+ assertThat(schedulerStatus.getComponent(), is(SCHEDULER));
+ assertThat(schedulerStatus.getMetadata(), instanceOf(ErrorMetadata.class));
+
+ final ErrorMetadata metadata = ((ErrorMetadata) schedulerStatus.getMetadata());
+ org.junit.Assert.assertThat(metadata.getDescription(), containsString("NotFoundException: Get with status = 400"));
+ }
+
+ private void assertSchedulerStatus(ExternalComponentStatus schedulerStatus, boolean isAvailable) {
+ assertThat(schedulerStatus.isAvailable(), is(isAvailable));
+ assertThat(schedulerStatus.getComponent(), is(SCHEDULER));
+ assertThat(schedulerStatus.getMetadata(), instanceOf(HttpRequestMetadata.class));
+ }
+
+ private void assertMetadata(ExternalComponentStatus schedulerStatus, int httpCode, Matcher<String> rawData, String url, Matcher<String> descriptionMatcher) {
+ final HttpRequestMetadata metadata = ((HttpRequestMetadata) schedulerStatus.getMetadata());
+ org.junit.Assert.assertThat(metadata.getHttpMethod(), equalTo(HttpMethod.GET));
+ org.junit.Assert.assertThat(metadata.getHttpCode(), equalTo(httpCode));
+ org.junit.Assert.assertThat(metadata.getUrl(), equalTo(url));
+ org.junit.Assert.assertThat(metadata.getRawData(), rawData);
+ org.junit.Assert.assertThat(metadata.getDescription(), descriptionMatcher);
+ }
+}
diff --git a/vid-app-common/src/test/java/org/onap/vid/testUtils/TestUtils.java b/vid-app-common/src/test/java/org/onap/vid/testUtils/TestUtils.java
index b4c7828bc..b80c75e5e 100644
--- a/vid-app-common/src/test/java/org/onap/vid/testUtils/TestUtils.java
+++ b/vid-app-common/src/test/java/org/onap/vid/testUtils/TestUtils.java
@@ -3,6 +3,8 @@ package org.onap.vid.testUtils;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableList;
+import org.apache.log4j.LogManager;
+import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Assert;
@@ -10,20 +12,26 @@ import org.mockito.MockSettings;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
+import org.onap.portalsdk.core.util.SystemProperties;
import org.onap.vid.asdc.beans.Service;
+import org.springframework.mock.env.MockEnvironment;
+import javax.ws.rs.client.Client;
+import javax.ws.rs.client.Invocation;
+import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.GenericType;
+import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
+import java.net.URI;
import java.util.Iterator;
import java.util.List;
import static fj.parser.Parser.fail;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;
/**
@@ -31,6 +39,8 @@ import static org.mockito.Mockito.*;
*/
public class TestUtils {
+ private static final Logger logger = LogManager.getLogger(TestUtils.class);
+
/**
* The method compares between two jsons. the function assert that the actual object does not reduce or change the functionallity/parsing of the expected json.
* This means that if the expected JSON has a key which is null or the JSON doesn't have a key which contained in the expected JSON the assert will succeed and the will pass.
@@ -77,7 +87,7 @@ public class TestUtils {
}
}
else {
- Assert.assertEquals(expectedValue, actualValue);
+ Assert.assertEquals("assertion fail for key:"+key, expectedValue, actualValue);
}
}
}
@@ -99,6 +109,7 @@ public class TestUtils {
public static class JavaxRsClientMocks {
private final javax.ws.rs.client.Client fakeClient;
private final javax.ws.rs.client.Invocation.Builder fakeBuilder;
+ private final javax.ws.rs.client.Invocation fakeInvocation;
private final Response fakeResponse;
public javax.ws.rs.client.Client getFakeClient() {
@@ -118,6 +129,7 @@ public class TestUtils {
fakeClient = mock(javax.ws.rs.client.Client.class, mockSettings);
fakeBuilder = mock(javax.ws.rs.client.Invocation.Builder.class, mockSettings);
+ fakeInvocation = mock(javax.ws.rs.client.Invocation.class, mockSettings);
fakeResponse = mock(Response.class, mockSettings);
final javax.ws.rs.client.WebTarget fakeWebTarget = mock(javax.ws.rs.client.WebTarget.class, mockSettings);
@@ -125,16 +137,16 @@ public class TestUtils {
fakeClient,
fakeWebTarget,
fakeBuilder,
+ fakeInvocation,
fakeResponse
);
-
Mockito.when(fakeBuilder.get(any(Class.class))).thenReturn(null);
- Mockito.when(fakeBuilder.get(eq(InputStream.class))).thenReturn(new ByteArrayInputStream(new byte[]{}));
Mockito.when(fakeBuilder.get(any(GenericType.class))).thenReturn(null);
-
Mockito.when(fakeResponse.getStatus()).thenReturn(200);
Mockito.when(fakeResponse.getStatusInfo()).thenReturn(Response.Status.OK);
Mockito.when(fakeResponse.readEntity(Service.class)).thenReturn(null);
+ Mockito.when(fakeResponse.readEntity(InputStream.class)).thenReturn(new ByteArrayInputStream(new byte[]{}));
+ Mockito.when(fakeResponse.readEntity(String.class)).thenReturn(null);
}
}
@@ -155,9 +167,41 @@ public class TestUtils {
return availableMocks.stream()
.filter(mock -> methodReturnType.isAssignableFrom(mock.getClass()))
- //.peek(m -> System.out.println("found a mock: " + m.getClass().getName()))
+ //.peek(m -> logger.info("found a mock: " + m.getClass().getName()))
.findFirst()
.orElse(defaultReturn.answer(invocation));
}
}
+
+
+ //The method mocks only some methods used in my case
+ //You may add some other when for your test here
+ public static Response mockResponseForJavaxClient(Client javaxClientMock) {
+ Response mockResponse = mock(Response.class);
+ WebTarget webTarget = mock(WebTarget.class);
+ Invocation.Builder builder = mock(Invocation.Builder.class);
+ when(javaxClientMock.target(any(URI.class))).thenReturn(webTarget);
+ when(webTarget.path(any())).thenReturn(webTarget);
+ when(webTarget.request(any(MediaType.class))).thenReturn(builder);
+ when(builder.headers(any())).thenReturn(builder);
+ when(builder.header(any(), any())).thenReturn(builder);
+ when(builder.get()).thenReturn(mockResponse);
+ return mockResponse;
+ }
+
+
+ //Please use resetSystemProperties after using this method, so other test won't be affected
+ public static void mockSystemPropertyWithKeyValue(String key, String value) {
+ MockEnvironment mockEnvironment = new MockEnvironment();
+ mockEnvironment.setProperty(key, value);
+
+ SystemProperties systemProperties = new SystemProperties();
+ systemProperties.setEnvironment(mockEnvironment);
+ }
+
+ public static void resetSystemProperties() {
+ SystemProperties systemProperties = new SystemProperties();
+ systemProperties.setEnvironment(null);
+ }
+
}
diff --git a/vid-app-common/src/test/java/org/onap/vid/utils/LoggingTest.java b/vid-app-common/src/test/java/org/onap/vid/utils/LoggingTest.java
index 2cd0d0cc6..7fe25fe65 100644
--- a/vid-app-common/src/test/java/org/onap/vid/utils/LoggingTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/utils/LoggingTest.java
@@ -1,18 +1,10 @@
package org.onap.vid.utils;
-import javax.servlet.http.HttpServletRequest;
-
-import org.junit.Test;
-import org.springframework.http.HttpMethod;
-
import com.att.eelf.configuration.EELFLogger;
+import org.junit.Test;
public class LoggingTest {
- private Logging createTestSubject() {
- return new Logging();
- }
-
@Test
public void testGetMethodName() throws Exception {
String result;
diff --git a/vid-app-common/src/test/java/org/onap/vid/utils/LoggingUtilsTest.java b/vid-app-common/src/test/java/org/onap/vid/utils/LoggingUtilsTest.java
index 7bc3fca1d..ca27a2266 100644
--- a/vid-app-common/src/test/java/org/onap/vid/utils/LoggingUtilsTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/utils/LoggingUtilsTest.java
@@ -1,8 +1,8 @@
package org.onap.vid.utils;
+import com.fasterxml.jackson.core.JsonLocation;
+import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
-import org.codehaus.jackson.JsonLocation;
-import org.codehaus.jackson.JsonParseException;
import org.onap.vid.exceptions.GenericUncheckedException;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
@@ -47,15 +47,15 @@ public class LoggingUtilsTest {
" expected a valid value (number, String, array, object, 'true', 'false' or 'null')",
new JsonLocation("<html>i'm an error</html>", 25, 1, 1)));
String codehausParseDescription = "" +
- "org.codehaus.jackson.JsonParseException: Unexpected character ('<' (code 60)):" +
+ "com.fasterxml.jackson.core.JsonParseException: Unexpected character ('<' (code 60)):" +
" expected a valid value (number, String, array, object, 'true', 'false' or 'null')\n" +
- " at [Source: <html>i'm an error</html>; line: 1, column: 1]";
+ " at [Source: (String)\"<html>i'm an error</html>\"; line: 1, column: 1]";
RuntimeException fasterxmlMappingException = new RuntimeException(new JsonMappingException("Can not deserialize instance of java.lang.String out of START_ARRAY token",
new com.fasterxml.jackson.core.JsonLocation("{ example json }", 15, 1, 20)));
String fasterxmlMappingDescription = "" +
"com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_ARRAY token\n" +
- " at [Source: { example json }; line: 1, column: 20]";
+ " at [Source: (String)\"{ example json }\"; line: 1, column: 20]";
return new Object[][]{
{"javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No X509TrustManager implementation available",
diff --git a/vid-app-common/src/test/java/org/onap/vid/utils/TimeUtilsTest.java b/vid-app-common/src/test/java/org/onap/vid/utils/TimeUtilsTest.java
new file mode 100644
index 000000000..274ba2366
--- /dev/null
+++ b/vid-app-common/src/test/java/org/onap/vid/utils/TimeUtilsTest.java
@@ -0,0 +1,67 @@
+package org.onap.vid.utils;
+
+import org.apache.log4j.LogManager;
+import org.apache.log4j.Logger;
+import org.testng.Assert;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+import java.time.Instant;
+import java.time.ZoneId;
+import java.time.ZonedDateTime;
+import java.time.format.DateTimeParseException;
+
+public class TimeUtilsTest {
+ private static final Logger logger = LogManager.getLogger(TimeUtilsTest.class);
+
+ @DataProvider
+ public static Object[][] goodData() {
+ return new Object[][]{
+ {"Wed, 15 Oct 2014 13:01:52 GMT", 1413378112, "Timestamp as described in the documentation"},
+ {"Wed, 15 Oct 2014 14:01:52 +0100", 1413378112, "GMT +1"},
+ {"Wed, 15 Oct 2014 11:01:52 -0200", 1413378112, "GMT -2"}
+ };
+ }
+
+ @DataProvider
+ public static Object[][] goodDataToString() {
+ return new Object[][]{
+ {"Wed, 15 Oct 2014 13:01:52 GMT", 1413378112, "UTC", "Timestamp as described in the documentation"},
+ {"Wed, 15 Oct 2014 14:01:52 +0100", 1413378112, "+1", "GMT +1"},
+ {"Wed, 15 Oct 2014 11:01:52 -0200", 1413378112, "-2", "GMT -2"}
+ };
+ }
+
+ @DataProvider
+ public static Object[][] badData() {
+ return new Object[][]{
+ {"Wed, 15 Oct 2014 13:01:52", "No offset"},
+ {"Wed, 15 Oct 2014 13:01:52 UTC", "UTC"},
+ {"Wed, 15 Oct 2014 13:01:52 UT", "UT"},
+ {"Wed, 15 Oct 2014 13:01:52Z", "Zulu time"},
+ {"Wed, 15 Oct 2014 13:01:52 EST", "EST time"}
+ };
+ }
+
+ @Test(dataProvider = "goodData")
+ public void parseSuccessTest(String timestamp, long expectedResult, String description) {
+ logger.info(description);
+ ZonedDateTime parsedTime = TimeUtils.parseZonedDateTime(timestamp);
+ Assert.assertEquals(parsedTime.toEpochSecond(), expectedResult);
+ }
+
+ @Test(expectedExceptions = DateTimeParseException.class, dataProvider = "badData")
+ public void parseFailedTest(String timestamp, String description) {
+ logger.info(description);
+ TimeUtils.parseZonedDateTime(timestamp);
+ }
+
+ @Test(dataProvider = "goodDataToString")
+ public void toStringSuccessTest(String expectedResult, long epochTime, String zoneId, String description) {
+ logger.info(description);
+ Instant instant = Instant.ofEpochSecond(epochTime);
+ ZonedDateTime time = ZonedDateTime.ofInstant(instant, ZoneId.of(zoneId));
+ String timeStamp = TimeUtils.zonedDateTimeToString(time);
+ Assert.assertEquals(timeStamp, expectedResult);
+ }
+}
diff --git a/vid-app-common/src/test/java/org/onap/vid/utils/TreeTest.java b/vid-app-common/src/test/java/org/onap/vid/utils/TreeTest.java
new file mode 100644
index 000000000..8691032b2
--- /dev/null
+++ b/vid-app-common/src/test/java/org/onap/vid/utils/TreeTest.java
@@ -0,0 +1,63 @@
+package org.onap.vid.utils;
+
+import com.google.common.collect.ImmutableList;
+import org.jetbrains.annotations.NotNull;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+import java.util.List;
+
+import static org.junit.Assert.assertFalse;
+import static org.testng.Assert.*;
+
+public class TreeTest {
+
+ @NotNull
+ protected Tree<String> buildTreeForTest() {
+ Tree<String> tree = new Tree<>("a");
+ tree.addPath("b","c","d");
+ tree.addPath("b","cc","dd");
+ tree.addPath("1","2","dd");
+ return tree;
+ }
+
+ @DataProvider
+ public static Object[][] pathsToFind() {
+ return new Object[][]{
+ {ImmutableList.of("b","c","d"), true},
+ {ImmutableList.of("b","c"), true},
+ {ImmutableList.of("b","cc","dd"), true},
+ {ImmutableList.of("b","cc","d"), false},
+ {ImmutableList.of("1","2","dd"), true},
+ {ImmutableList.of("b"), true},
+ {ImmutableList.of("c"), false},
+ {ImmutableList.of("z", "z", "z", "z", "z"), false},
+ };
+ }
+
+ @Test(dataProvider="pathsToFind")
+ public void whenBuildTree_nodesFoundsInRoute(List<String> path, boolean isFound) {
+ Tree<String> tree = buildTreeForTest();
+ assertEquals(isFound, tree.isPathExist(path));
+ }
+
+ @Test(dataProvider="pathsToFind")
+ public void whenBuildTree_subTreeGetRight(List<String> path, boolean isFound) {
+ Tree<String> tree = buildTreeForTest();
+ if (isFound) {
+ assertNotNull(tree.getSubTree(path));
+ }
+ else {
+ assertNull(tree.getSubTree(path));
+ }
+ }
+
+ @Test
+ public void whenBuildTree_getSubTreeAsExpected() {
+ Tree<String> tree = buildTreeForTest();
+ Tree<String> subTree = tree.getSubTree("b","c");
+ assertEquals(subTree.getRootValue(), "c");
+ assertTrue(subTree.isPathExist("d"));
+ assertFalse(subTree.isPathExist("b","c","d"));
+ }
+}