diff options
author | Benjamin, Max (mb388a) <mb388a@us.att.com> | 2019-04-08 14:14:34 -0400 |
---|---|---|
committer | Benjamin, Max (mb388a) <mb388a@us.att.com> | 2019-04-08 14:24:59 -0400 |
commit | f47919f1fe367b612fa9c96d34c59f01a541e882 (patch) | |
tree | 5b6aa2fc36747d868897e68ccbec0c6db0aee81c /adapters/mso-adapter-utils/src/test/java/org/onap | |
parent | 54452b80a1cf4d22ef750bc1377f8c1b05431d57 (diff) |
Replaced all tabs with spaces in java and pom.xml
Added in maven plugins to enforce coding style rules
Added in eclipse java formatting xml
Change-Id: I3727bbf4ce8dc66abfd8ad21b6cfd0890c5d3ff0
Issue-ID: SO-1765
Signed-off-by: Benjamin, Max (mb388a) <mb388a@us.att.com>
Diffstat (limited to 'adapters/mso-adapter-utils/src/test/java/org/onap')
35 files changed, 1526 insertions, 1657 deletions
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/AllTestsTestSuite.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/AllTestsTestSuite.java index a74dbf614b..a9365a3946 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/AllTestsTestSuite.java +++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/AllTestsTestSuite.java @@ -19,14 +19,14 @@ */ package org.onap.so; -import org.junit.runner.RunWith; +import org.junit.runner.RunWith; import com.googlecode.junittoolbox.SuiteClasses; import com.googlecode.junittoolbox.WildcardPatternSuite; @RunWith(WildcardPatternSuite.class) @SuiteClasses("**/*Test.class") public class AllTestsTestSuite { - // the class remains empty, - // used only as a holder for the above annotations + // the class remains empty, + // used only as a holder for the above annotations } diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/BaseTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/BaseTest.java index 82b18d86ed..ecdd052b73 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/BaseTest.java +++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/BaseTest.java @@ -26,13 +26,10 @@ package org.onap.so; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; - import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; - import javax.ws.rs.core.MediaType; - import org.apache.http.HttpHeaders; import org.apache.http.HttpStatus; import org.junit.After; @@ -48,7 +45,6 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cloud.contract.wiremock.AutoConfigureWireMock; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; - import com.github.tomakehurst.wiremock.WireMockServer; import com.github.tomakehurst.wiremock.client.WireMock; @@ -58,77 +54,74 @@ import com.github.tomakehurst.wiremock.client.WireMock; @AutoConfigureWireMock(port = 0) public abstract class BaseTest extends TestDataSetup { - @Value("${wiremock.server.port}") - protected int wireMockPort; - @Autowired - protected WireMockServer wireMockServer; - - @After - public void after() { - wireMockServer.resetAll(); - } - - protected static String getBody(String body, int port, String urlPath) throws IOException { - return body.replaceAll("port", "http://localhost:" + port + urlPath); - } - - @Before - public void init() throws IOException { - CloudIdentity identity = getCloudIdentity(); - CloudSite cloudSite = getCloudSite(identity); - mockCloud(identity, cloudSite); - } - - private void mockCloud(CloudIdentity identity, CloudSite cloudSite) throws IOException { - wireMockServer.stubFor(get(urlPathEqualTo("/cloudSite/MTN13")).willReturn(aResponse() - .withBody(getBody(mapper.writeValueAsString(cloudSite),wireMockPort, "")) - .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlPathEqualTo("/cloudSite/DEFAULT")).willReturn(aResponse() - .withBody(getBody(mapper.writeValueAsString(cloudSite),wireMockPort, "")) - .withHeader(HttpHeaders.CONTENT_TYPE,MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlPathEqualTo("/cloudIdentity/mtn13")).willReturn(aResponse() - .withBody(getBody(mapper.writeValueAsString(identity),wireMockPort, "")) - .withHeader(HttpHeaders.CONTENT_TYPE,MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - } - - protected CloudIdentity getCloudIdentity() { - CloudIdentity identity = new CloudIdentity(); - identity.setId("mtn13"); - identity.setMsoId("m93945"); - identity.setMsoPass("93937EA01B94A10A49279D4572B48369"); - identity.setAdminTenant("admin"); - identity.setMemberRole("admin"); - identity.setTenantMetadata(false); - identity.setIdentityUrl("http://localhost:"+wireMockPort+"/v2.0"); - identity.setIdentityAuthenticationType(AuthenticationType.USERNAME_PASSWORD); - identity.setIdentityServerType(ServerType.KEYSTONE); - return identity; - } - - protected CloudSite getCloudSite(CloudIdentity identity) { - CloudSite cloudSite = new CloudSite(); - cloudSite.setId("MTN13"); - cloudSite.setCloudVersion("3.0"); - cloudSite.setClli("MDT13"); - cloudSite.setRegionId("mtn13"); - cloudSite.setIdentityService(identity); - return cloudSite; - } - - private static String readFile(String fileName) throws IOException { - try (BufferedReader br = new BufferedReader(new FileReader(fileName))) { - StringBuilder sb = new StringBuilder(); - String line = br.readLine(); - - while (line != null) { - sb.append(line); - sb.append("\n"); - line = br.readLine(); - } - return sb.toString(); - } - } + @Value("${wiremock.server.port}") + protected int wireMockPort; + @Autowired + protected WireMockServer wireMockServer; + + @After + public void after() { + wireMockServer.resetAll(); + } + + protected static String getBody(String body, int port, String urlPath) throws IOException { + return body.replaceAll("port", "http://localhost:" + port + urlPath); + } + + @Before + public void init() throws IOException { + CloudIdentity identity = getCloudIdentity(); + CloudSite cloudSite = getCloudSite(identity); + mockCloud(identity, cloudSite); + } + + private void mockCloud(CloudIdentity identity, CloudSite cloudSite) throws IOException { + wireMockServer.stubFor(get(urlPathEqualTo("/cloudSite/MTN13")).willReturn(aResponse() + .withBody(getBody(mapper.writeValueAsString(cloudSite), wireMockPort, "")) + .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlPathEqualTo("/cloudSite/DEFAULT")).willReturn(aResponse() + .withBody(getBody(mapper.writeValueAsString(cloudSite), wireMockPort, "")) + .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlPathEqualTo("/cloudIdentity/mtn13")).willReturn(aResponse() + .withBody(getBody(mapper.writeValueAsString(identity), wireMockPort, "")) + .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).withStatus(HttpStatus.SC_OK))); + } + + protected CloudIdentity getCloudIdentity() { + CloudIdentity identity = new CloudIdentity(); + identity.setId("mtn13"); + identity.setMsoId("m93945"); + identity.setMsoPass("93937EA01B94A10A49279D4572B48369"); + identity.setAdminTenant("admin"); + identity.setMemberRole("admin"); + identity.setTenantMetadata(false); + identity.setIdentityUrl("http://localhost:" + wireMockPort + "/v2.0"); + identity.setIdentityAuthenticationType(AuthenticationType.USERNAME_PASSWORD); + identity.setIdentityServerType(ServerType.KEYSTONE); + return identity; + } + + protected CloudSite getCloudSite(CloudIdentity identity) { + CloudSite cloudSite = new CloudSite(); + cloudSite.setId("MTN13"); + cloudSite.setCloudVersion("3.0"); + cloudSite.setClli("MDT13"); + cloudSite.setRegionId("mtn13"); + cloudSite.setIdentityService(identity); + return cloudSite; + } + + private static String readFile(String fileName) throws IOException { + try (BufferedReader br = new BufferedReader(new FileReader(fileName))) { + StringBuilder sb = new StringBuilder(); + String line = br.readLine(); + + while (line != null) { + sb.append(line); + sb.append("\n"); + line = br.readLine(); + } + return sb.toString(); + } + } } diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/EmbeddedMariaDbConfig.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/EmbeddedMariaDbConfig.java index c1705508ce..75794efe79 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/EmbeddedMariaDbConfig.java +++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/EmbeddedMariaDbConfig.java @@ -28,11 +28,10 @@ import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; - import javax.sql.DataSource; @Configuration -@Profile({"test","local"}) +@Profile({"test", "local"}) public class EmbeddedMariaDbConfig { @Bean @@ -42,21 +41,16 @@ public class EmbeddedMariaDbConfig { @Bean DataSource dataSource(MariaDB4jSpringService mariaDB4jSpringService, - @Value("${mariaDB4j.databaseName}") String databaseName, - @Value("${spring.datasource.username}") String datasourceUsername, - @Value("${spring.datasource.password}") String datasourcePassword, - @Value("${spring.datasource.driver-class-name}") String datasourceDriver) throws ManagedProcessException { - //Create our database with default root user and no password + @Value("${mariaDB4j.databaseName}") String databaseName, + @Value("${spring.datasource.username}") String datasourceUsername, + @Value("${spring.datasource.password}") String datasourcePassword, + @Value("${spring.datasource.driver-class-name}") String datasourceDriver) throws ManagedProcessException { + // Create our database with default root user and no password mariaDB4jSpringService.getDB().createDB(databaseName); DBConfigurationBuilder config = mariaDB4jSpringService.getConfiguration(); - return DataSourceBuilder - .create() - .username(datasourceUsername) - .password(datasourcePassword) - .url(config.getURL(databaseName)) - .driverClassName(datasourceDriver) - .build(); + return DataSourceBuilder.create().username(datasourceUsername).password(datasourcePassword) + .url(config.getURL(databaseName)).driverClassName(datasourceDriver).build(); } } diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/StubOpenStack.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/StubOpenStack.java index ae3fb8271a..120c3e3493 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/StubOpenStack.java +++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/StubOpenStack.java @@ -29,49 +29,43 @@ import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.put; import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; - import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; - import org.apache.http.HttpStatus; - import com.github.tomakehurst.wiremock.WireMockServer; public class StubOpenStack { public static void mockOpenStackResponseAccess(WireMockServer wireMockServer, int port) throws IOException { - wireMockServer.stubFor(post(urlPathEqualTo("/v2.0/tokens")).willReturn(aResponse().withHeader("Content-Type", "application/json") - .withBody(getBodyFromFile("OpenstackResponse_Access.json", port, "/mockPublicUrl")) - .withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(post(urlPathEqualTo("/v2.0/tokens")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withBody(getBodyFromFile("OpenstackResponse_Access.json", port, "/mockPublicUrl")) + .withStatus(HttpStatus.SC_OK))); } public static void mockOpenStackResponseUnauthorized(WireMockServer wireMockServer, int port) throws IOException { - wireMockServer.stubFor( - post(urlPathEqualTo("/v2.0/tokens")) + wireMockServer.stubFor(post(urlPathEqualTo("/v2.0/tokens")) .willReturn(aResponse().withHeader("Content-Type", "application/json") - .withBody(getBodyFromFile("OpenstackResponse_Access.json", port, "/mockPublicUrl")) - .withStatus(HttpStatus.SC_UNAUTHORIZED))); + .withBody(getBodyFromFile("OpenstackResponse_Access.json", port, "/mockPublicUrl")) + .withStatus(HttpStatus.SC_UNAUTHORIZED))); } public static void mockOpenStackDelete(WireMockServer wireMockServer, String id) { - wireMockServer.stubFor(delete(urlMatching("/mockPublicUrl/stacks/" + id)).willReturn(aResponse() - .withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(delete(urlMatching("/mockPublicUrl/stacks/" + id)) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_OK))); } public static void mockOpenStackGet(WireMockServer wireMockServer, String id) { - wireMockServer.stubFor( - get(urlPathEqualTo("/mockPublicUrl/stacks/" + id)) + wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/" + id)) .willReturn(aResponse().withHeader("Content-Type", "application/json") - .withBodyFile("OpenstackResponse_Stack_Created.json") - .withStatus(HttpStatus.SC_OK))); + .withBodyFile("OpenstackResponse_Stack_Created.json").withStatus(HttpStatus.SC_OK))); } public static void mockOpenStackPostStack_200(WireMockServer wireMockServer, String filename) { wireMockServer.stubFor(post(urlPathEqualTo("/mockPublicUrl/stacks")).willReturn(aResponse() - .withHeader("Content-Type", "application/json") - .withBodyFile(filename).withStatus(HttpStatus.SC_OK))); + .withHeader("Content-Type", "application/json").withBodyFile(filename).withStatus(HttpStatus.SC_OK))); } public static void mockOpenStackPostTenantWithBodyFile_200(WireMockServer wireMockServer) throws IOException { @@ -79,7 +73,8 @@ public class StubOpenStack { .willReturn(aResponse().withBodyFile("OpenstackResponse_Tenant.json").withStatus(HttpStatus.SC_OK))); } - public static void mockOpenStackGetTenantByName(WireMockServer wireMockServer, String tenantName) throws IOException { + public static void mockOpenStackGetTenantByName(WireMockServer wireMockServer, String tenantName) + throws IOException { wireMockServer.stubFor(get(urlMatching("/mockPublicUrl/tenants/[?]name=" + tenantName)) .willReturn(aResponse().withBodyFile("OpenstackResponse_Tenant.json").withStatus(HttpStatus.SC_OK))); } @@ -90,55 +85,53 @@ public class StubOpenStack { } public static void mockOpenStackDeleteTenantById_200(WireMockServer wireMockServer, String tenantId) { - wireMockServer.stubFor(delete(urlPathEqualTo("/mockPublicUrl/tenants/" + tenantId)).willReturn(aResponse() - .withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(delete(urlPathEqualTo("/mockPublicUrl/tenants/" + tenantId)) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_OK))); } public static void mockOpenStackGetUserById(WireMockServer wireMockServer, String user) { - wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/users/" + user)).willReturn(aResponse() - .withHeader("Content-Type", "application/json") - .withBodyFile("OpenstackResponse_User.json").withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/users/" + user)) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withBodyFile("OpenstackResponse_User.json").withStatus(HttpStatus.SC_OK))); } public static void mockOpenStackGetUserByName(WireMockServer wireMockServer, String userName) { - wireMockServer.stubFor(get(urlMatching("/mockPublicUrl/users/[?]name=" + userName)).willReturn(aResponse() - .withHeader("Content-Type", "application/json") - .withBodyFile("OpenstackResponse_User.json").withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching("/mockPublicUrl/users/[?]name=" + userName)) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withBodyFile("OpenstackResponse_User.json").withStatus(HttpStatus.SC_OK))); } public static void mockOpenStackGetUserByName_500(WireMockServer wireMockServer, String userName) { - wireMockServer.stubFor(get(urlMatching("/mockPublicUrl/users/[?]name=" + userName)).willReturn(aResponse() - .withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR))); + wireMockServer.stubFor(get(urlMatching("/mockPublicUrl/users/[?]name=" + userName)) + .willReturn(aResponse().withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR))); } public static void mockOpenStackGetRoles_200(WireMockServer wireMockServer, String roleFor) { - wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/" + roleFor + "/roles")).willReturn(aResponse() - .withHeader("Content-Type", "application/json") - .withBodyFile("OpenstackResponse_Roles.json").withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/" + roleFor + "/roles")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withBodyFile("OpenstackResponse_Roles.json").withStatus(HttpStatus.SC_OK))); } public static void mockOpenstackPostNetwork(WireMockServer wireMockServer, String responseFile) { - wireMockServer.stubFor(post(urlPathEqualTo("/mockPublicUrl/v2.0/networks")).willReturn(aResponse() - .withHeader("Content-Type", "application/json") - .withBodyFile(responseFile) - .withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(post(urlPathEqualTo("/mockPublicUrl/v2.0/networks")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile(responseFile) + .withStatus(HttpStatus.SC_OK))); } public static void mockOpenstackPutNetwork(WireMockServer wireMockServer, String responseFile, String networkId) { - wireMockServer.stubFor(put(urlPathEqualTo("/mockPublicUrl/v2.0/networks/"+networkId)).willReturn(aResponse() - .withHeader("Content-Type", "application/json") - .withBodyFile(responseFile) - .withStatus(HttpStatus.SC_OK))); - } - - public static void mockOpenStackGetNeutronNetwork(WireMockServer wireMockServer, String filename,String networkId) { - wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/v2.0/networks/"+ networkId)) - .willReturn(aResponse().withHeader("Content-Type", "application/json") - .withBodyFile(filename).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(put(urlPathEqualTo("/mockPublicUrl/v2.0/networks/" + networkId)) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile(responseFile) + .withStatus(HttpStatus.SC_OK))); + } + + public static void mockOpenStackGetNeutronNetwork(WireMockServer wireMockServer, String filename, + String networkId) { + wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/v2.0/networks/" + networkId)).willReturn(aResponse() + .withHeader("Content-Type", "application/json").withBodyFile(filename).withStatus(HttpStatus.SC_OK))); } public static void mockOpenStackGetNeutronNetwork_500(WireMockServer wireMockServer, String networkId) { - wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/v2.0/networks/"+ networkId)) + wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/v2.0/networks/" + networkId)) .willReturn(aResponse().withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR))); } @@ -162,6 +155,7 @@ public class StubOpenStack { } public static String getBodyFromFile(String fileName, int port, String urlPath) throws IOException { - return readFile("src/test/resources/__files/" + fileName).replaceAll("port", "http://localhost:" + port + urlPath); + return readFile("src/test/resources/__files/" + fileName).replaceAll("port", + "http://localhost:" + port + urlPath); } } diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/TestApplication.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/TestApplication.java index 479731c870..f73c3a8e6c 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/TestApplication.java +++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/TestApplication.java @@ -28,12 +28,12 @@ import org.springframework.context.annotation.Profile; @SpringBootApplication @Profile("test") -@ComponentScan(basePackages = {"org.onap.so", "com.att"}, excludeFilters = { - @Filter(type = FilterType.ANNOTATION, classes = SpringBootApplication.class)}) +@ComponentScan(basePackages = {"org.onap.so", "com.att"}, + excludeFilters = {@Filter(type = FilterType.ANNOTATION, classes = SpringBootApplication.class)}) public class TestApplication { - public static void main(String... args) { - SpringApplication.run(TestApplication.class, args); - System.getProperties().setProperty("mso.db", "MARIADB"); - System.getProperties().setProperty("server.name", "Springboot"); - } + public static void main(String... args) { + SpringApplication.run(TestApplication.class, args); + System.getProperties().setProperty("mso.db", "MARIADB"); + System.getProperties().setProperty("server.name", "Springboot"); + } } diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/TestDataSetup.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/TestDataSetup.java index 21c4c225ba..61cc24b31a 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/TestDataSetup.java +++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/TestDataSetup.java @@ -23,18 +23,17 @@ package org.onap.so; import org.junit.Before; import org.junit.Rule; import org.junit.rules.ExpectedException; - import com.fasterxml.jackson.databind.ObjectMapper; public class TestDataSetup { - @Rule - public ExpectedException expectedException = ExpectedException.none(); - - public static final String RESOURCE_PATH = "src/test/resources/__files/"; - public ObjectMapper mapper; - - @Before - public void testDataSetupBefore() { - mapper = new ObjectMapper(); - } + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + public static final String RESOURCE_PATH = "src/test/resources/__files/"; + public ObjectMapper mapper; + + @Before + public void testDataSetupBefore() { + mapper = new ObjectMapper(); + } } diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/CloudConfigTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/CloudConfigTest.java index ea25fe580d..fb3b3e0dc5 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/CloudConfigTest.java +++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/CloudConfigTest.java @@ -21,9 +21,7 @@ package org.onap.so.cloud; import static org.junit.Assert.*; - import java.util.Optional; - import org.junit.Test; import org.onap.so.BaseTest; import org.onap.so.db.catalog.beans.AuthenticationType; @@ -38,35 +36,35 @@ import org.springframework.beans.factory.annotation.Autowired; * * */ -public class CloudConfigTest extends BaseTest{ +public class CloudConfigTest extends BaseTest { + + @Autowired + private CloudConfig con; - @Autowired - private CloudConfig con; + /** + * This method implements a test for the getCloudSite method. + */ + @Test + public final void testGetCloudSite() { + CloudSite site1 = con.getCloudSite("MTN13").get(); - /** - * This method implements a test for the getCloudSite method. - */ - @Test - public final void testGetCloudSite () { - CloudSite site1 = con.getCloudSite("MTN13").get(); + assertEquals("mtn13", site1.getRegionId()); + assertEquals("mtn13", site1.getIdentityServiceId()); + assertEquals("MDT13", site1.getClli()); + assertEquals("3.0", site1.getCloudVersion()); + } - assertEquals ("mtn13", site1.getRegionId()); - assertEquals ("mtn13", site1.getIdentityServiceId()); - assertEquals ("MDT13", site1.getClli()); - assertEquals ("3.0", site1.getCloudVersion()); - } + /** + * This method implements a test for the getCloudSite method. + */ + @Test + public final void testGetDefaultCloudSite() { + Optional<CloudSite> site = con.getCloudSite("NotThere"); + assertTrue(site.isPresent()); + CloudSite site1 = site.get(); + assertEquals("NotThere", site1.getRegionId()); + assertEquals("MDT13", site1.getClli()); + assertEquals("NotThere", site1.getId()); + } - /** - * This method implements a test for the getCloudSite method. - */ - @Test - public final void testGetDefaultCloudSite () { - Optional<CloudSite> site = con.getCloudSite("NotThere"); - assertTrue(site.isPresent()); - CloudSite site1 = site.get(); - assertEquals ("NotThere", site1.getRegionId()); - assertEquals("MDT13", site1.getClli()); - assertEquals("NotThere", site1.getId()); - } - } diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/CloudPojoTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/CloudPojoTest.java index 096d5dad8b..6c58cda2d1 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/CloudPojoTest.java +++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/CloudPojoTest.java @@ -25,7 +25,6 @@ import org.onap.so.db.catalog.beans.CloudIdentity; import org.onap.so.db.catalog.beans.CloudSite; import org.onap.so.db.catalog.beans.CloudifyManager; import org.onap.so.openpojo.rules.ToStringTester; - import com.openpojo.reflection.PojoClass; import com.openpojo.reflection.impl.PojoClassFactory; import com.openpojo.validation.Validator; @@ -37,23 +36,18 @@ import com.openpojo.validation.test.impl.GetterTester; import com.openpojo.validation.test.impl.SetterTester; public class CloudPojoTest { - @Test - public void pojoStructure() { - test(PojoClassFactory.getPojoClass(CloudIdentity.class)); - test(PojoClassFactory.getPojoClass(CloudifyManager.class)); - test(PojoClassFactory.getPojoClass(CloudSite.class)); - test(PojoClassFactory.getPojoClass(CloudConfig.class)); - } - - private void test(PojoClass pojoClass) { - Validator validator = ValidatorBuilder.create() - .with(new EqualsAndHashCodeMatchRule()) - .with(new NoPrimitivesRule()) - .with(new NoPublicFieldsRule()) - .with(new SetterTester()) - .with(new GetterTester()) - .with(new ToStringTester()) - .build(); - validator.validate(pojoClass); - } + @Test + public void pojoStructure() { + test(PojoClassFactory.getPojoClass(CloudIdentity.class)); + test(PojoClassFactory.getPojoClass(CloudifyManager.class)); + test(PojoClassFactory.getPojoClass(CloudSite.class)); + test(PojoClassFactory.getPojoClass(CloudConfig.class)); + } + + private void test(PojoClass pojoClass) { + Validator validator = ValidatorBuilder.create().with(new EqualsAndHashCodeMatchRule()) + .with(new NoPrimitivesRule()).with(new NoPublicFieldsRule()).with(new SetterTester()) + .with(new GetterTester()).with(new ToStringTester()).build(); + validator.validate(pojoClass); + } } diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/authentication/AuthenticationMethodTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/authentication/AuthenticationMethodTest.java index a5abe75af2..41aac0084c 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/authentication/AuthenticationMethodTest.java +++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/authentication/AuthenticationMethodTest.java @@ -23,17 +23,14 @@ package org.onap.so.cloud.authentication; import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; - import org.junit.Test; import org.onap.so.cloud.authentication.models.RackspaceAuthentication; import org.onap.so.db.catalog.beans.AuthenticationType; import org.onap.so.db.catalog.beans.CloudIdentity; import org.onap.so.utils.CryptoUtils; - import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; @@ -41,81 +38,83 @@ import com.woorea.openstack.keystone.model.Authentication; import com.woorea.openstack.keystone.model.authentication.UsernamePassword; /** - * A few JUnit tests to evaluate the new factory that manages authentication - * types and their associated wrapper classes. Here it is assumed that core types - * only are tested. + * A few JUnit tests to evaluate the new factory that manages authentication types and their associated wrapper classes. + * Here it is assumed that core types only are tested. * */ public class AuthenticationMethodTest { - private AuthenticationMethodFactory authenticationMethodFactory = new AuthenticationMethodFactory(); - /** - * - */ - public AuthenticationMethodTest() { - // TODO Auto-generated constructor stub - } - - @Test - public void testCustomRackspaceAuth() { - CloudIdentity ci = new CloudIdentity(); - ci.setIdentityAuthenticationType(AuthenticationType.RACKSPACE_APIKEY); - ci.setMsoPass("FD205490A48D48475607C36B9AD902BF"); - ci.setMsoId("test"); - - Authentication auth = authenticationMethodFactory.getAuthenticationFor(ci); - assertTrue(RackspaceAuthentication.class.equals(auth.getClass())); - - } - - @Test - public void testCoreUsernamePasswordAuth() { - CloudIdentity ci = new CloudIdentity(); - ci.setIdentityAuthenticationType(AuthenticationType.USERNAME_PASSWORD); - ci.setMsoPass("FD205490A48D48475607C36B9AD902BF"); - ci.setMsoId("someuser"); - - Authentication auth = authenticationMethodFactory.getAuthenticationFor(ci); - assertTrue(UsernamePassword.class.equals(auth.getClass())); - - } - - @Test - public void testCustomRackspaceAuthFromCloudIdentity() { - CloudIdentity ci = new CloudIdentity(); - ci.setIdentityAuthenticationType(AuthenticationType.RACKSPACE_APIKEY); - ci.setMsoPass("FD205490A48D48475607C36B9AD902BF"); - ci.setMsoId("test"); - - Authentication auth = authenticationMethodFactory.getAuthenticationFor(ci); - assertTrue(RackspaceAuthentication.class.equals(auth.getClass())); - } - - @Test - public void testCoreUsernamePasswordAuthFromCloudIdentity() { - CloudIdentity ci = new CloudIdentity(); - ci.setIdentityAuthenticationType(AuthenticationType.USERNAME_PASSWORD); - ci.setMsoPass("FD205490A48D48475607C36B9AD902BF"); - ci.setMsoId("someuser"); - - Authentication auth = authenticationMethodFactory.getAuthenticationFor(ci); - assertTrue(UsernamePassword.class.equals(auth.getClass())); - - } - - @Test - public void getAuthenticationForV3Test() throws JsonParseException, JsonMappingException, IOException { - - CloudIdentity identity = new CloudIdentity(); - identity.setMsoId("my-username"); - identity.setMsoPass(CryptoUtils.encryptCloudConfigPassword("my-password")); - identity.setProjectDomainName("test-domain"); - identity.setUserDomainName("user-domain"); - ObjectMapper mapper = new ObjectMapper(); - com.woorea.openstack.keystone.v3.model.Authentication expected = - mapper.readValue(new String(Files.readAllBytes(Paths.get("src/test/resources/__files/KeystoneV3Payload.json"))), com.woorea.openstack.keystone.v3.model.Authentication.class); - com.woorea.openstack.keystone.v3.model.Authentication actual = authenticationMethodFactory.getAuthenticationForV3(identity, "project-x"); - - assertThat(actual, sameBeanAs(expected)); - } + private AuthenticationMethodFactory authenticationMethodFactory = new AuthenticationMethodFactory(); + + /** + * + */ + public AuthenticationMethodTest() { + // TODO Auto-generated constructor stub + } + + @Test + public void testCustomRackspaceAuth() { + CloudIdentity ci = new CloudIdentity(); + ci.setIdentityAuthenticationType(AuthenticationType.RACKSPACE_APIKEY); + ci.setMsoPass("FD205490A48D48475607C36B9AD902BF"); + ci.setMsoId("test"); + + Authentication auth = authenticationMethodFactory.getAuthenticationFor(ci); + assertTrue(RackspaceAuthentication.class.equals(auth.getClass())); + + } + + @Test + public void testCoreUsernamePasswordAuth() { + CloudIdentity ci = new CloudIdentity(); + ci.setIdentityAuthenticationType(AuthenticationType.USERNAME_PASSWORD); + ci.setMsoPass("FD205490A48D48475607C36B9AD902BF"); + ci.setMsoId("someuser"); + + Authentication auth = authenticationMethodFactory.getAuthenticationFor(ci); + assertTrue(UsernamePassword.class.equals(auth.getClass())); + + } + + @Test + public void testCustomRackspaceAuthFromCloudIdentity() { + CloudIdentity ci = new CloudIdentity(); + ci.setIdentityAuthenticationType(AuthenticationType.RACKSPACE_APIKEY); + ci.setMsoPass("FD205490A48D48475607C36B9AD902BF"); + ci.setMsoId("test"); + + Authentication auth = authenticationMethodFactory.getAuthenticationFor(ci); + assertTrue(RackspaceAuthentication.class.equals(auth.getClass())); + } + + @Test + public void testCoreUsernamePasswordAuthFromCloudIdentity() { + CloudIdentity ci = new CloudIdentity(); + ci.setIdentityAuthenticationType(AuthenticationType.USERNAME_PASSWORD); + ci.setMsoPass("FD205490A48D48475607C36B9AD902BF"); + ci.setMsoId("someuser"); + + Authentication auth = authenticationMethodFactory.getAuthenticationFor(ci); + assertTrue(UsernamePassword.class.equals(auth.getClass())); + + } + + @Test + public void getAuthenticationForV3Test() throws JsonParseException, JsonMappingException, IOException { + + CloudIdentity identity = new CloudIdentity(); + identity.setMsoId("my-username"); + identity.setMsoPass(CryptoUtils.encryptCloudConfigPassword("my-password")); + identity.setProjectDomainName("test-domain"); + identity.setUserDomainName("user-domain"); + ObjectMapper mapper = new ObjectMapper(); + com.woorea.openstack.keystone.v3.model.Authentication expected = mapper.readValue( + new String(Files.readAllBytes(Paths.get("src/test/resources/__files/KeystoneV3Payload.json"))), + com.woorea.openstack.keystone.v3.model.Authentication.class); + com.woorea.openstack.keystone.v3.model.Authentication actual = + authenticationMethodFactory.getAuthenticationForV3(identity, "project-x"); + + assertThat(actual, sameBeanAs(expected)); + } } diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/authentication/KeystoneAuthHolderTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/authentication/KeystoneAuthHolderTest.java index 8469ad506c..5bd77d8e10 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/authentication/KeystoneAuthHolderTest.java +++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/authentication/KeystoneAuthHolderTest.java @@ -19,22 +19,17 @@ */ /* - * ============LICENSE_START========================================== - * ONAP - SO - * =================================================================== - * Copyright (c) 2019 IBM. - * =================================================================== - * 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 + * ============LICENSE_START========================================== ONAP - SO + * =================================================================== Copyright (c) 2019 IBM. + * =================================================================== 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 + * 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. + * 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============================================= * ==================================================================== @@ -42,9 +37,7 @@ package org.onap.so.cloud.authentication; import static org.junit.Assert.assertEquals; - import java.util.Calendar; - import org.junit.Before; import org.junit.Test; diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/beans/DeploymentInfoBuilderTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/beans/DeploymentInfoBuilderTest.java index ce13d98dd1..9fbb45a2c3 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/beans/DeploymentInfoBuilderTest.java +++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/beans/DeploymentInfoBuilderTest.java @@ -1,26 +1,20 @@ /* - * ============LICENSE_START======================================================= - * ONAP : SO - * ================================================================================ - * Copyright (C) 2018 Nokia. - * ============================================================================= - * 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 + * ============LICENSE_START======================================================= ONAP : SO + * ================================================================================ Copyright (C) 2018 Nokia. + * ============================================================================= 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 + * 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. + * 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.so.cloudify.beans; import static org.assertj.core.api.Assertions.assertThat; - import com.google.common.collect.ImmutableMap; import org.junit.Test; import org.onap.so.cloudify.v3.model.Execution; @@ -33,15 +27,10 @@ public class DeploymentInfoBuilderTest { @Test public void shouldConstructDeploymentInfo_withBasicValues() { - DeploymentInfo deploymentInfo = new DeploymentInfoBuilder() - .withId("id") - .withStatus(DeploymentStatus.CREATED) - .withDeploymentOutputs(ImmutableMap.of()) - .withDeploymentInputs(ImmutableMap.of()) - .withActionStatus("started") - .withLastAction(INSTALL_WORKFLOW_ID) - .withErrorMessage(ERROR_MESSAGE) - .build(); + DeploymentInfo deploymentInfo = new DeploymentInfoBuilder().withId("id").withStatus(DeploymentStatus.CREATED) + .withDeploymentOutputs(ImmutableMap.of()).withDeploymentInputs(ImmutableMap.of()) + .withActionStatus("started").withLastAction(INSTALL_WORKFLOW_ID).withErrorMessage(ERROR_MESSAGE) + .build(); assertThat(deploymentInfo.getId()).isEqualTo("id"); assertThat(deploymentInfo.getStatus()).isEqualTo(DeploymentStatus.CREATED); @@ -54,9 +43,7 @@ public class DeploymentInfoBuilderTest { @Test public void shouldConstructDeploymentInfo_withCreateDeploymentStatus_fromNullExecution() { - DeploymentInfo deploymentInfo = new DeploymentInfoBuilder() - .fromExecution(null) - .build(); + DeploymentInfo deploymentInfo = new DeploymentInfoBuilder().fromExecution(null).build(); assertThat(deploymentInfo.getStatus()).isEqualTo(DeploymentStatus.CREATED); } @@ -156,19 +143,17 @@ public class DeploymentInfoBuilderTest { } private void verifyDeploymentInfoConstruction(String workflowIdLastAction, String actionStatus, - DeploymentStatus expectedDeploymentStatus) { + DeploymentStatus expectedDeploymentStatus) { Execution execution = new Execution(); execution.setWorkflowId(workflowIdLastAction); execution.setStatus(actionStatus); execution.setError(ERROR_MESSAGE); - DeploymentInfo deploymentInfo = new DeploymentInfoBuilder() - .fromExecution(execution) - .build(); + DeploymentInfo deploymentInfo = new DeploymentInfoBuilder().fromExecution(execution).build(); assertThat(deploymentInfo.getLastAction()).isEqualTo(workflowIdLastAction); assertThat(deploymentInfo.getActionStatus()).isEqualTo(actionStatus); assertThat(deploymentInfo.getErrorMessage()).isEqualTo(ERROR_MESSAGE); assertThat(deploymentInfo.getStatus()).isEqualTo(expectedDeploymentStatus); } -}
\ No newline at end of file +} diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyExceptionTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyExceptionTest.java index 4bf087b7a4..d45f685795 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyExceptionTest.java +++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyExceptionTest.java @@ -1,39 +1,33 @@ /* -* ============LICENSE_START======================================================= - * ONAP : SO - * ================================================================================ - * Copyright (C) 2018 TechMahindra - * ================================================================================ - * 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 + * ============LICENSE_START======================================================= ONAP : SO + * ================================================================================ Copyright (C) 2018 TechMahindra + * ================================================================================ 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 + * 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. + * 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.so.cloudify.exceptions; import static org.junit.Assert.*; - import org.junit.Test; public class MsoCloudifyExceptionTest { - - @Test + + @Test public void test() { Exception e = null; - boolean pendingWorkflow=true; - MsoCloudifyException mce=new MsoCloudifyException(200, "message", "detail"); - MsoCloudifyException mcl=new MsoCloudifyException(200, "message", "detail", e); + boolean pendingWorkflow = true; + MsoCloudifyException mce = new MsoCloudifyException(200, "message", "detail"); + MsoCloudifyException mcl = new MsoCloudifyException(200, "message", "detail", e); mce.setPendingWorkflow(pendingWorkflow); - assert(mcl.toString()!=null); + assert (mcl.toString() != null); } } diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyTest.java index a1859e491a..08b2356fdc 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyTest.java +++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyTest.java @@ -1,35 +1,29 @@ /* -* ============LICENSE_START======================================================= - * ONAP : SO - * ================================================================================ - * Copyright (C) 2018 TechMahindra - * ================================================================================ - * 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 + * ============LICENSE_START======================================================= ONAP : SO + * ================================================================================ Copyright (C) 2018 TechMahindra + * ================================================================================ 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 + * 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. + * 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.so.cloudify.exceptions; import static org.junit.Assert.*; - import org.junit.Test; public class MsoCloudifyTest { - - @Test + + @Test public void test() { - MsoBlueprintAlreadyExists mbae=new MsoBlueprintAlreadyExists("blueprintId", "cloud"); - MsoCloudifyManagerNotFound mcm=new MsoCloudifyManagerNotFound("cloudSiteId"); - MsoDeploymentAlreadyExists mdae=new MsoDeploymentAlreadyExists("deploymentId", "cloud"); + MsoBlueprintAlreadyExists mbae = new MsoBlueprintAlreadyExists("blueprintId", "cloud"); + MsoCloudifyManagerNotFound mcm = new MsoCloudifyManagerNotFound("cloudSiteId"); + MsoDeploymentAlreadyExists mdae = new MsoDeploymentAlreadyExists("deploymentId", "cloud"); } } diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyTimeoutTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyTimeoutTest.java index 21c625feb3..48c5c877a5 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyTimeoutTest.java +++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyTimeoutTest.java @@ -1,38 +1,32 @@ /* -* ============LICENSE_START======================================================= - * ONAP : SO - * ================================================================================ - * Copyright (C) 2018 TechMahindra - * ================================================================================ - * 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 + * ============LICENSE_START======================================================= ONAP : SO + * ================================================================================ Copyright (C) 2018 TechMahindra + * ================================================================================ 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 + * 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. + * 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.so.cloudify.exceptions; import static org.junit.Assert.*; import static org.mockito.Mockito.mock; - import org.junit.Test; import org.onap.so.cloudify.v3.model.Execution; public class MsoCloudifyTimeoutTest { - - @Test + + @Test public void test() { - Execution execution=mock(Execution.class); - MsoCloudifyTimeout mct=new MsoCloudifyTimeout(execution); + Execution execution = mock(Execution.class); + MsoCloudifyTimeout mct = new MsoCloudifyTimeout(execution); mct.getExecution(); - assert(mct.toString()!=null); + assert (mct.toString() != null); } } diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyWorkflowExceptionTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyWorkflowExceptionTest.java index 68df574611..b8b2c97a65 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyWorkflowExceptionTest.java +++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyWorkflowExceptionTest.java @@ -1,36 +1,31 @@ /* -* ============LICENSE_START======================================================= - * ONAP : SO - * ================================================================================ - * Copyright (C) 2018 TechMahindra - * ================================================================================ - * 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 + * ============LICENSE_START======================================================= ONAP : SO + * ================================================================================ Copyright (C) 2018 TechMahindra + * ================================================================================ 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 + * 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. + * 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.so.cloudify.exceptions; import static org.junit.Assert.*; - import org.junit.Test; public class MsoCloudifyWorkflowExceptionTest { - - @Test + + @Test public void test() { - MsoCloudifyWorkflowException mcw=new MsoCloudifyWorkflowException("message", "id", "workflowId", "workflowStatus"); + MsoCloudifyWorkflowException mcw = + new MsoCloudifyWorkflowException("message", "id", "workflowId", "workflowStatus"); mcw.getWorkflowStatus(); assertFalse(mcw.isWorkflowStillRunning()); - + } } diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/utils/MsoCloudifyUtilsTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/utils/MsoCloudifyUtilsTest.java index 833b4ab760..d14115971c 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/utils/MsoCloudifyUtilsTest.java +++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/utils/MsoCloudifyUtilsTest.java @@ -33,7 +33,6 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; - import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; @@ -42,7 +41,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; - import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; @@ -67,7 +65,6 @@ import org.onap.so.db.catalog.beans.HeatTemplateParam; import org.onap.so.openstack.exceptions.MsoAdapterException; import org.onap.so.openstack.exceptions.MsoException; import org.skyscreamer.jsonassert.JSONAssert; - import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonMappingException; @@ -76,273 +73,264 @@ import com.fasterxml.jackson.databind.ObjectMapper; public class MsoCloudifyUtilsTest { - private static final String CLOUD_SITE_ID = "cloudSiteIdTest"; - private static final String BLUEPRINT_ID = "bluePrintIdTest"; - private static final String FILE_NAME = "fileName"; - - @Test - public void instantiateVduTest() throws MsoException { - VduInstance expected = new VduInstance(); - expected.setVduInstanceId("id"); - expected.setVduInstanceName("id"); - VduStatus status = new VduStatus(); - status.setState(VduStateType.INSTANTIATED); - status.setLastAction(new PluginAction(null, null, null)); - expected.setStatus(status); - - MsoCloudifyUtils cloudify = Mockito.spy(MsoCloudifyUtils.class); - CloudSite site = new CloudSite(); - Optional<CloudSite> opSite = Optional.ofNullable(site); - CloudConfig config = Mockito.mock(CloudConfig.class); - cloudify.cloudConfig = config; - Cloudify cloudifyClient = new Cloudify("cloudSite"); - CloudInfo cloudInfo = new CloudInfo(); - cloudInfo.setCloudSiteId("cloudSiteId"); - cloudInfo.setTenantId("tenantId"); - VduModelInfo vduModel = new VduModelInfo(); - vduModel.setModelCustomizationUUID("blueprintId"); - vduModel.setTimeoutMinutes(1); - VduArtifact artifact = new VduArtifact(); - artifact.setName("name"); - artifact.setType(ArtifactType.MAIN_TEMPLATE); - byte[] content = new byte[1]; - artifact.setContent(content); - List<VduArtifact> artifacts = new ArrayList<>(); - artifacts.add(artifact); - vduModel.setArtifacts(artifacts); - DeploymentInfo deployment = new DeploymentInfoBuilder() - .withId("id") - .withStatus(DeploymentStatus.INSTALLED) - .build(); - Map<String, byte[]> blueprintFiles = new HashMap<>(); - blueprintFiles.put(artifact.getName(), artifact.getContent()); - String instanceName = "instanceName"; - Map<String, Object> inputs = new HashMap<>(); - boolean rollbackOnFailure = true; - - when(config.getCloudSite(cloudInfo.getCloudSiteId())).thenReturn(opSite); - doReturn(false).when(cloudify).isBlueprintLoaded(cloudInfo.getCloudSiteId(), - vduModel.getModelCustomizationUUID()); - doReturn(cloudifyClient).when(cloudify).getCloudifyClient(site); - doReturn(true).when(cloudify).uploadBlueprint(cloudifyClient, vduModel.getModelCustomizationUUID(), - artifact.getName(), blueprintFiles); - doReturn(deployment).when(cloudify).createAndInstallDeployment(cloudInfo.getCloudSiteId(), - cloudInfo.getTenantId(), instanceName, vduModel.getModelCustomizationUUID(), inputs, true, - vduModel.getTimeoutMinutes(), rollbackOnFailure); - - VduInstance actual = cloudify.instantiateVdu(cloudInfo, instanceName, inputs, vduModel, rollbackOnFailure); - assertThat(actual, sameBeanAs(expected)); - } - - @Test - public void queryVduTest() throws MsoException { - VduInstance expected = new VduInstance(); - expected.setVduInstanceId("id"); - expected.setVduInstanceName("id"); - VduStatus status = new VduStatus(); - status.setState(VduStateType.INSTANTIATED); - status.setLastAction(new PluginAction(null, null, null)); - expected.setStatus(status); - - CloudInfo cloudInfo = new CloudInfo(); - cloudInfo.setCloudSiteId("cloudSiteId"); - cloudInfo.setTenantId("tenantId"); - DeploymentInfo deployment = new DeploymentInfoBuilder() - .withId("id") - .withStatus(DeploymentStatus.INSTALLED) - .build(); - String instanceId = "instanceId"; - - MsoCloudifyUtils cloudify = Mockito.spy(MsoCloudifyUtils.class); - - doReturn(deployment).when(cloudify).queryDeployment(cloudInfo.getCloudSiteId(), cloudInfo.getTenantId(), - instanceId); - - VduInstance actual = cloudify.queryVdu(cloudInfo, instanceId); - - assertThat(actual, sameBeanAs(expected)); - } - - @Test - public void deleteVduTest() throws MsoException { - VduInstance expected = new VduInstance(); - expected.setVduInstanceId("id"); - expected.setVduInstanceName("id"); - VduStatus status = new VduStatus(); - status.setState(VduStateType.DELETING); - status.setLastAction(new PluginAction("deleting", null, null)); - expected.setStatus(status); - - CloudInfo cloudInfo = new CloudInfo(); - cloudInfo.setCloudSiteId("cloudSiteId"); - cloudInfo.setTenantId("tenantId"); - String instanceId = "instanceId"; - int timeoutMinutes = 1; - DeploymentInfo deploymentInfo = new DeploymentInfoBuilder() - .withId("id") - .withStatus(DeploymentStatus.CREATED) - .withLastAction("deleting").build(); - MsoCloudifyUtils cloudify = Mockito.spy(MsoCloudifyUtils.class); - doReturn(deploymentInfo).when(cloudify).uninstallAndDeleteDeployment(cloudInfo.getCloudSiteId(), - cloudInfo.getTenantId(), instanceId, timeoutMinutes); - - VduInstance actual = cloudify.deleteVdu(cloudInfo, instanceId, timeoutMinutes); - - assertThat(actual, sameBeanAs(expected)); - } - - @Test - public void deploymentInfoToVduInstanceTest() { - VduInstance expected = new VduInstance(); - expected.setVduInstanceId("id"); - expected.setVduInstanceName("id"); - VduStatus status = new VduStatus(); - status.setState(VduStateType.DELETING); - status.setLastAction(new PluginAction("deleting", null, null)); - expected.setStatus(status); - - DeploymentInfo deploymentInfo = new DeploymentInfoBuilder() - .withId("id") - .withStatus(DeploymentStatus.CREATED) - .withLastAction("deleting").build(); - - MsoCloudifyUtils cloudify = new MsoCloudifyUtils(); - - VduInstance actual = cloudify.deploymentInfoToVduInstance(deploymentInfo); - - assertThat(actual, sameBeanAs(expected)); - } - - @Test - public void deploymentStatusToVduStatusTest() { - VduStatus expected = new VduStatus(); - expected.setState(VduStateType.DELETING); - expected.setLastAction(new PluginAction("deleting", null, null)); - - DeploymentInfo deploymentInfo = new DeploymentInfoBuilder() - .withId("id") - .withStatus(DeploymentStatus.CREATED) - .withLastAction("deleting").build(); - - MsoCloudifyUtils cloudify = new MsoCloudifyUtils(); - - VduStatus actual = cloudify.deploymentStatusToVduStatus(deploymentInfo); - - assertThat(actual, sameBeanAs(expected)); - } - - @Test - public void getAzureConfigTest() { - AzureConfig expected = new AzureConfig(); - expected.setSubscriptionId("subscriptionId"); - expected.setTenantId("tenantId"); - expected.setClientId("msoId"); - expected.setClientSecret("msoPass"); - - MsoCloudifyUtils cloudify = new MsoCloudifyUtils(); - CloudSite cloudSite = Mockito.mock(CloudSite.class); - CloudIdentity cloudIdentity = Mockito.mock(CloudIdentity.class); - when(cloudSite.getIdentityService()).thenReturn(cloudIdentity); - when(cloudIdentity.getAdminTenant()).thenReturn("subscriptionId"); - when(cloudIdentity.getMsoId()).thenReturn("msoId"); - when(cloudIdentity.getMsoPass()).thenReturn("msoPass"); - String tenantId = "tenantId"; - AzureConfig actual = cloudify.getAzureConfig(cloudSite, tenantId); - - assertThat(actual, sameBeanAs(expected)); - } - - @Test - public void uploadBlueprintSuccessful() throws MsoException { - // given - MsoCloudifyUtils testedObjectSpy = spy(MsoCloudifyUtils.class); - testedObjectSpy.cloudConfig = mock(CloudConfig.class); - Map<String, byte[]> blueprints = new HashMap<>(); - - mockCloudConfig(testedObjectSpy); - doReturn(true).when(testedObjectSpy).uploadBlueprint(any(Cloudify.class), eq(BLUEPRINT_ID), - eq(FILE_NAME), eq(blueprints)); - // when - testedObjectSpy.uploadBlueprint(CLOUD_SITE_ID, BLUEPRINT_ID, FILE_NAME, blueprints, true); - // then - verify(testedObjectSpy).uploadBlueprint(any(Cloudify.class), eq(BLUEPRINT_ID), eq(FILE_NAME), - eq(blueprints)); - } - - @Test - public void uploadBlueprint_exceptionThrown_blueprintExists() throws MsoException { - // given - MsoCloudifyUtils testedObjectSpy = spy(MsoCloudifyUtils.class); - testedObjectSpy.cloudConfig = mock(CloudConfig.class); - Map<String, byte[]> blueprints = new HashMap<>(); - - mockCloudConfig(testedObjectSpy); - doReturn(false).when(testedObjectSpy).uploadBlueprint(any(Cloudify.class), eq(BLUEPRINT_ID), - eq(FILE_NAME), eq(blueprints)); - // when - try { - testedObjectSpy.uploadBlueprint(CLOUD_SITE_ID, BLUEPRINT_ID, FILE_NAME, blueprints, true); - // then - fail("MsoAdapterException should be thrown"); - } catch (MsoAdapterException e) { - Assert.assertEquals(e.getMessage(), "Blueprint already exists"); - } - verify(testedObjectSpy).uploadBlueprint(any(Cloudify.class), eq(BLUEPRINT_ID), eq(FILE_NAME), - eq(blueprints)); - } - - @Test - public void convertInputValueTest() throws JsonParseException, JsonMappingException, IOException { - MsoCloudifyUtils utils = new MsoCloudifyUtils(); - ObjectMapper mapper = new ObjectMapper(); - HeatTemplateParam paramNum = new HeatTemplateParam(); - paramNum.setParamType("number"); - paramNum.setParamName("my-number"); - - HeatTemplateParam paramString = new HeatTemplateParam(); - paramString.setParamType("string"); - paramString.setParamName("my-string"); - - HeatTemplateParam paramJson = new HeatTemplateParam(); - paramJson.setParamType("json"); - paramJson.setParamName("my-json"); - - HeatTemplateParam paramJsonEscaped = new HeatTemplateParam(); - paramJsonEscaped.setParamType("json"); - paramJsonEscaped.setParamName("my-json-escaped"); - - Map<String, Object> jsonMap = mapper.readValue(getJson("free-form.json"), new TypeReference<Map<String, Object>>(){}); - - assertEquals(3, utils.convertInputValue("3", paramNum)); - assertEquals("hello", utils.convertInputValue("hello", paramString)); - assertTrue("expect no change in type", utils.convertInputValue(jsonMap, paramJson) instanceof Map); - assertTrue("expect string to become jsonNode", utils.convertInputValue(getJson("free-form.json"), paramJsonEscaped) instanceof JsonNode); - - JSONAssert.assertEquals(getJson("free-form.json"), mapper.writeValueAsString(utils.convertInputValue(getJson("free-form.json"), paramJsonEscaped)), false); - - } - - private String getJson(String filename) throws IOException { - return new String(Files.readAllBytes(Paths.get("src/test/resources/__files/MsoHeatUtils/" + filename))); - } - - private void mockCloudConfig(MsoCloudifyUtils testedObjectSpy) { - CloudifyManager cloudifyManager = createCloudifyManager(); - when(testedObjectSpy.cloudConfig.getCloudSite(CLOUD_SITE_ID)).thenReturn(Optional.of(createCloudSite())); - when(testedObjectSpy.cloudConfig.getCloudifyManager(CLOUD_SITE_ID)).thenReturn(cloudifyManager); - } - - private CloudifyManager createCloudifyManager() { - CloudifyManager cloudifyManager = new CloudifyManager(); - cloudifyManager.setCloudifyUrl("cloudUrlTest"); - cloudifyManager.setPassword("546573746F736973546573746F736973"); - return cloudifyManager; - } - - private CloudSite createCloudSite() { - CloudSite cloudSite = new CloudSite(); - cloudSite.setCloudifyId(CLOUD_SITE_ID); - return cloudSite; - } + private static final String CLOUD_SITE_ID = "cloudSiteIdTest"; + private static final String BLUEPRINT_ID = "bluePrintIdTest"; + private static final String FILE_NAME = "fileName"; + + @Test + public void instantiateVduTest() throws MsoException { + VduInstance expected = new VduInstance(); + expected.setVduInstanceId("id"); + expected.setVduInstanceName("id"); + VduStatus status = new VduStatus(); + status.setState(VduStateType.INSTANTIATED); + status.setLastAction(new PluginAction(null, null, null)); + expected.setStatus(status); + + MsoCloudifyUtils cloudify = Mockito.spy(MsoCloudifyUtils.class); + CloudSite site = new CloudSite(); + Optional<CloudSite> opSite = Optional.ofNullable(site); + CloudConfig config = Mockito.mock(CloudConfig.class); + cloudify.cloudConfig = config; + Cloudify cloudifyClient = new Cloudify("cloudSite"); + CloudInfo cloudInfo = new CloudInfo(); + cloudInfo.setCloudSiteId("cloudSiteId"); + cloudInfo.setTenantId("tenantId"); + VduModelInfo vduModel = new VduModelInfo(); + vduModel.setModelCustomizationUUID("blueprintId"); + vduModel.setTimeoutMinutes(1); + VduArtifact artifact = new VduArtifact(); + artifact.setName("name"); + artifact.setType(ArtifactType.MAIN_TEMPLATE); + byte[] content = new byte[1]; + artifact.setContent(content); + List<VduArtifact> artifacts = new ArrayList<>(); + artifacts.add(artifact); + vduModel.setArtifacts(artifacts); + DeploymentInfo deployment = + new DeploymentInfoBuilder().withId("id").withStatus(DeploymentStatus.INSTALLED).build(); + Map<String, byte[]> blueprintFiles = new HashMap<>(); + blueprintFiles.put(artifact.getName(), artifact.getContent()); + String instanceName = "instanceName"; + Map<String, Object> inputs = new HashMap<>(); + boolean rollbackOnFailure = true; + + when(config.getCloudSite(cloudInfo.getCloudSiteId())).thenReturn(opSite); + doReturn(false).when(cloudify).isBlueprintLoaded(cloudInfo.getCloudSiteId(), + vduModel.getModelCustomizationUUID()); + doReturn(cloudifyClient).when(cloudify).getCloudifyClient(site); + doReturn(true).when(cloudify).uploadBlueprint(cloudifyClient, vduModel.getModelCustomizationUUID(), + artifact.getName(), blueprintFiles); + doReturn(deployment).when(cloudify).createAndInstallDeployment(cloudInfo.getCloudSiteId(), + cloudInfo.getTenantId(), instanceName, vduModel.getModelCustomizationUUID(), inputs, true, + vduModel.getTimeoutMinutes(), rollbackOnFailure); + + VduInstance actual = cloudify.instantiateVdu(cloudInfo, instanceName, inputs, vduModel, rollbackOnFailure); + assertThat(actual, sameBeanAs(expected)); + } + + @Test + public void queryVduTest() throws MsoException { + VduInstance expected = new VduInstance(); + expected.setVduInstanceId("id"); + expected.setVduInstanceName("id"); + VduStatus status = new VduStatus(); + status.setState(VduStateType.INSTANTIATED); + status.setLastAction(new PluginAction(null, null, null)); + expected.setStatus(status); + + CloudInfo cloudInfo = new CloudInfo(); + cloudInfo.setCloudSiteId("cloudSiteId"); + cloudInfo.setTenantId("tenantId"); + DeploymentInfo deployment = + new DeploymentInfoBuilder().withId("id").withStatus(DeploymentStatus.INSTALLED).build(); + String instanceId = "instanceId"; + + MsoCloudifyUtils cloudify = Mockito.spy(MsoCloudifyUtils.class); + + doReturn(deployment).when(cloudify).queryDeployment(cloudInfo.getCloudSiteId(), cloudInfo.getTenantId(), + instanceId); + + VduInstance actual = cloudify.queryVdu(cloudInfo, instanceId); + + assertThat(actual, sameBeanAs(expected)); + } + + @Test + public void deleteVduTest() throws MsoException { + VduInstance expected = new VduInstance(); + expected.setVduInstanceId("id"); + expected.setVduInstanceName("id"); + VduStatus status = new VduStatus(); + status.setState(VduStateType.DELETING); + status.setLastAction(new PluginAction("deleting", null, null)); + expected.setStatus(status); + + CloudInfo cloudInfo = new CloudInfo(); + cloudInfo.setCloudSiteId("cloudSiteId"); + cloudInfo.setTenantId("tenantId"); + String instanceId = "instanceId"; + int timeoutMinutes = 1; + DeploymentInfo deploymentInfo = new DeploymentInfoBuilder().withId("id").withStatus(DeploymentStatus.CREATED) + .withLastAction("deleting").build(); + MsoCloudifyUtils cloudify = Mockito.spy(MsoCloudifyUtils.class); + doReturn(deploymentInfo).when(cloudify).uninstallAndDeleteDeployment(cloudInfo.getCloudSiteId(), + cloudInfo.getTenantId(), instanceId, timeoutMinutes); + + VduInstance actual = cloudify.deleteVdu(cloudInfo, instanceId, timeoutMinutes); + + assertThat(actual, sameBeanAs(expected)); + } + + @Test + public void deploymentInfoToVduInstanceTest() { + VduInstance expected = new VduInstance(); + expected.setVduInstanceId("id"); + expected.setVduInstanceName("id"); + VduStatus status = new VduStatus(); + status.setState(VduStateType.DELETING); + status.setLastAction(new PluginAction("deleting", null, null)); + expected.setStatus(status); + + DeploymentInfo deploymentInfo = new DeploymentInfoBuilder().withId("id").withStatus(DeploymentStatus.CREATED) + .withLastAction("deleting").build(); + + MsoCloudifyUtils cloudify = new MsoCloudifyUtils(); + + VduInstance actual = cloudify.deploymentInfoToVduInstance(deploymentInfo); + + assertThat(actual, sameBeanAs(expected)); + } + + @Test + public void deploymentStatusToVduStatusTest() { + VduStatus expected = new VduStatus(); + expected.setState(VduStateType.DELETING); + expected.setLastAction(new PluginAction("deleting", null, null)); + + DeploymentInfo deploymentInfo = new DeploymentInfoBuilder().withId("id").withStatus(DeploymentStatus.CREATED) + .withLastAction("deleting").build(); + + MsoCloudifyUtils cloudify = new MsoCloudifyUtils(); + + VduStatus actual = cloudify.deploymentStatusToVduStatus(deploymentInfo); + + assertThat(actual, sameBeanAs(expected)); + } + + @Test + public void getAzureConfigTest() { + AzureConfig expected = new AzureConfig(); + expected.setSubscriptionId("subscriptionId"); + expected.setTenantId("tenantId"); + expected.setClientId("msoId"); + expected.setClientSecret("msoPass"); + + MsoCloudifyUtils cloudify = new MsoCloudifyUtils(); + CloudSite cloudSite = Mockito.mock(CloudSite.class); + CloudIdentity cloudIdentity = Mockito.mock(CloudIdentity.class); + when(cloudSite.getIdentityService()).thenReturn(cloudIdentity); + when(cloudIdentity.getAdminTenant()).thenReturn("subscriptionId"); + when(cloudIdentity.getMsoId()).thenReturn("msoId"); + when(cloudIdentity.getMsoPass()).thenReturn("msoPass"); + String tenantId = "tenantId"; + AzureConfig actual = cloudify.getAzureConfig(cloudSite, tenantId); + + assertThat(actual, sameBeanAs(expected)); + } + + @Test + public void uploadBlueprintSuccessful() throws MsoException { + // given + MsoCloudifyUtils testedObjectSpy = spy(MsoCloudifyUtils.class); + testedObjectSpy.cloudConfig = mock(CloudConfig.class); + Map<String, byte[]> blueprints = new HashMap<>(); + + mockCloudConfig(testedObjectSpy); + doReturn(true).when(testedObjectSpy).uploadBlueprint(any(Cloudify.class), eq(BLUEPRINT_ID), eq(FILE_NAME), + eq(blueprints)); + // when + testedObjectSpy.uploadBlueprint(CLOUD_SITE_ID, BLUEPRINT_ID, FILE_NAME, blueprints, true); + // then + verify(testedObjectSpy).uploadBlueprint(any(Cloudify.class), eq(BLUEPRINT_ID), eq(FILE_NAME), eq(blueprints)); + } + + @Test + public void uploadBlueprint_exceptionThrown_blueprintExists() throws MsoException { + // given + MsoCloudifyUtils testedObjectSpy = spy(MsoCloudifyUtils.class); + testedObjectSpy.cloudConfig = mock(CloudConfig.class); + Map<String, byte[]> blueprints = new HashMap<>(); + + mockCloudConfig(testedObjectSpy); + doReturn(false).when(testedObjectSpy).uploadBlueprint(any(Cloudify.class), eq(BLUEPRINT_ID), eq(FILE_NAME), + eq(blueprints)); + // when + try { + testedObjectSpy.uploadBlueprint(CLOUD_SITE_ID, BLUEPRINT_ID, FILE_NAME, blueprints, true); + // then + fail("MsoAdapterException should be thrown"); + } catch (MsoAdapterException e) { + Assert.assertEquals(e.getMessage(), "Blueprint already exists"); + } + verify(testedObjectSpy).uploadBlueprint(any(Cloudify.class), eq(BLUEPRINT_ID), eq(FILE_NAME), eq(blueprints)); + } + + @Test + public void convertInputValueTest() throws JsonParseException, JsonMappingException, IOException { + MsoCloudifyUtils utils = new MsoCloudifyUtils(); + ObjectMapper mapper = new ObjectMapper(); + HeatTemplateParam paramNum = new HeatTemplateParam(); + paramNum.setParamType("number"); + paramNum.setParamName("my-number"); + + HeatTemplateParam paramString = new HeatTemplateParam(); + paramString.setParamType("string"); + paramString.setParamName("my-string"); + + HeatTemplateParam paramJson = new HeatTemplateParam(); + paramJson.setParamType("json"); + paramJson.setParamName("my-json"); + + HeatTemplateParam paramJsonEscaped = new HeatTemplateParam(); + paramJsonEscaped.setParamType("json"); + paramJsonEscaped.setParamName("my-json-escaped"); + + Map<String, Object> jsonMap = + mapper.readValue(getJson("free-form.json"), new TypeReference<Map<String, Object>>() {}); + + assertEquals(3, utils.convertInputValue("3", paramNum)); + assertEquals("hello", utils.convertInputValue("hello", paramString)); + assertTrue("expect no change in type", utils.convertInputValue(jsonMap, paramJson) instanceof Map); + assertTrue("expect string to become jsonNode", + utils.convertInputValue(getJson("free-form.json"), paramJsonEscaped) instanceof JsonNode); + + JSONAssert.assertEquals(getJson("free-form.json"), + mapper.writeValueAsString(utils.convertInputValue(getJson("free-form.json"), paramJsonEscaped)), false); + + } + + private String getJson(String filename) throws IOException { + return new String(Files.readAllBytes(Paths.get("src/test/resources/__files/MsoHeatUtils/" + filename))); + } + + private void mockCloudConfig(MsoCloudifyUtils testedObjectSpy) { + CloudifyManager cloudifyManager = createCloudifyManager(); + when(testedObjectSpy.cloudConfig.getCloudSite(CLOUD_SITE_ID)).thenReturn(Optional.of(createCloudSite())); + when(testedObjectSpy.cloudConfig.getCloudifyManager(CLOUD_SITE_ID)).thenReturn(cloudifyManager); + } + + private CloudifyManager createCloudifyManager() { + CloudifyManager cloudifyManager = new CloudifyManager(); + cloudifyManager.setCloudifyUrl("cloudUrlTest"); + cloudifyManager.setPassword("546573746F736973546573746F736973"); + return cloudifyManager; + } + + private CloudSite createCloudSite() { + CloudSite cloudSite = new CloudSite(); + cloudSite.setCloudifyId(CLOUD_SITE_ID); + return cloudSite; + } } diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/config/PoConfigTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/config/PoConfigTest.java index 1884b3243a..870b4d98f2 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/config/PoConfigTest.java +++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/config/PoConfigTest.java @@ -28,15 +28,15 @@ import org.springframework.beans.factory.annotation.Autowired; public class PoConfigTest extends BaseTest { - - @Autowired - private PoConfig poConfig; - - - @Test - public void tenantConfigValues() { - assertEquals("504", poConfig.getRetryCodes()); - assertEquals(5, poConfig.getRetryDelay()); - - } + + @Autowired + private PoConfig poConfig; + + + @Test + public void tenantConfigValues() { + assertEquals("504", poConfig.getRetryCodes()); + assertEquals(5, poConfig.getRetryDelay()); + + } } diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/HeatCacheEntryTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/HeatCacheEntryTest.java index b675f4814d..f8d07250f5 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/HeatCacheEntryTest.java +++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/HeatCacheEntryTest.java @@ -23,43 +23,41 @@ package org.onap.so.openstack.beans; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; - import java.util.Calendar; import java.util.GregorianCalendar; - import org.junit.Test; import org.onap.so.BaseTest; public class HeatCacheEntryTest { - - private static final String HEAT_URL = "testHeatUrl"; - private static final String TOKEN = "testToken"; - @Test - public void getHeatClientTest() { - Calendar expires = new GregorianCalendar(2013,0,31); - HeatCacheEntry heatCacheEntry = new HeatCacheEntry(HEAT_URL, TOKEN, expires); - assertNotNull(heatCacheEntry.getHeatClient()); - } - - @Test - public void isExpiredTrueTest() { - Calendar expires = new GregorianCalendar(2013,0,31); - HeatCacheEntry heatCacheEntry = new HeatCacheEntry(HEAT_URL, TOKEN, expires); - assertTrue(heatCacheEntry.isExpired()); - } - - @Test - public void isExpiredFalseTest() { - Calendar expires = new GregorianCalendar(2100,0,31); - HeatCacheEntry heatCacheEntry = new HeatCacheEntry(HEAT_URL, TOKEN, expires); - assertFalse(heatCacheEntry.isExpired()); - } - - @Test - public void isExpiredNullTest() { - Calendar expires = null; - HeatCacheEntry heatCacheEntry = new HeatCacheEntry(HEAT_URL, TOKEN, expires); - assertTrue(heatCacheEntry.isExpired()); - } + private static final String HEAT_URL = "testHeatUrl"; + private static final String TOKEN = "testToken"; + + @Test + public void getHeatClientTest() { + Calendar expires = new GregorianCalendar(2013, 0, 31); + HeatCacheEntry heatCacheEntry = new HeatCacheEntry(HEAT_URL, TOKEN, expires); + assertNotNull(heatCacheEntry.getHeatClient()); + } + + @Test + public void isExpiredTrueTest() { + Calendar expires = new GregorianCalendar(2013, 0, 31); + HeatCacheEntry heatCacheEntry = new HeatCacheEntry(HEAT_URL, TOKEN, expires); + assertTrue(heatCacheEntry.isExpired()); + } + + @Test + public void isExpiredFalseTest() { + Calendar expires = new GregorianCalendar(2100, 0, 31); + HeatCacheEntry heatCacheEntry = new HeatCacheEntry(HEAT_URL, TOKEN, expires); + assertFalse(heatCacheEntry.isExpired()); + } + + @Test + public void isExpiredNullTest() { + Calendar expires = null; + HeatCacheEntry heatCacheEntry = new HeatCacheEntry(HEAT_URL, TOKEN, expires); + assertTrue(heatCacheEntry.isExpired()); + } } diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/MsoTenantTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/MsoTenantTest.java index 379501f206..ece5b21f19 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/MsoTenantTest.java +++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/MsoTenantTest.java @@ -1,42 +1,36 @@ /* -* ============LICENSE_START======================================================= - * ONAP : SO - * ================================================================================ - * Copyright (C) 2018 TechMahindra - * ================================================================================ - * 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 + * ============LICENSE_START======================================================= ONAP : SO + * ================================================================================ Copyright (C) 2018 TechMahindra + * ================================================================================ 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 + * 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. + * 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.so.openstack.beans; import java.util.HashMap; import java.util.Map; - import org.junit.Test; public class MsoTenantTest { - MsoTenant ms = new MsoTenant(); - + MsoTenant ms = new MsoTenant(); + @Test public void test() { - Map<String, String> map = new HashMap<>(); - map.put("id","name"); - ms.setTenantId("tenantId"); - ms.setTenantName("tenantName"); - ms.setMetadata(map); - assert(ms.getMetadata().equals(map)); - assert(ms.getTenantId().equals("tenantId")); - assert(ms.getTenantName().equals("tenantName")); + Map<String, String> map = new HashMap<>(); + map.put("id", "name"); + ms.setTenantId("tenantId"); + ms.setTenantName("tenantName"); + ms.setMetadata(map); + assert (ms.getMetadata().equals(map)); + assert (ms.getTenantId().equals("tenantId")); + assert (ms.getTenantName().equals("tenantName")); } } diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/NetworkRollbackTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/NetworkRollbackTest.java index 5a5e2bb75e..142007089a 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/NetworkRollbackTest.java +++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/NetworkRollbackTest.java @@ -1,22 +1,17 @@ /* -* ============LICENSE_START======================================================= - * ONAP : SO - * ================================================================================ - * Copyright (C) 2018 TechMahindra - * ================================================================================ - * 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 + * ============LICENSE_START======================================================= ONAP : SO + * ================================================================================ Copyright (C) 2018 TechMahindra + * ================================================================================ 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 + * 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. + * 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.so.openstack.beans; @@ -34,12 +29,12 @@ public class NetworkRollbackTest { @InjectMocks NetworkRollback nr = new NetworkRollback(); - + @Test public void test() { List<Integer> vlans = new ArrayList(); - vlans.add(1); - vlans.add(2); + vlans.add(1); + vlans.add(2); nr.setCloudId("cloudId"); nr.setModelCustomizationUuid("modelCustomizationUuid"); nr.setNetworkId("networkId"); @@ -52,18 +47,18 @@ public class NetworkRollbackTest { nr.setNetworkCreated(false); nr.setVlans(vlans); nr.setMsoRequest(ms); - assert(nr.getCloudId().equals("cloudId")); - assert(nr.getModelCustomizationUuid().equals("modelCustomizationUuid")); - assert(nr.getNetworkId().equals("networkId")); - assert(nr.getNetworkName().equals("networkName")); - assert(nr.getNetworkStackId().equals("networkStackId")); - assert(nr.getNeutronNetworkId().equals("neutronNetworkId")); - assert(nr.getPhysicalNetwork().equals("physicalNetwork")); - assert(nr.getNetworkType().equals("networkType")); - assert(nr.getTenantId().equals("tenantId")); - assert(nr.getMsoRequest().equals(ms)); + assert (nr.getCloudId().equals("cloudId")); + assert (nr.getModelCustomizationUuid().equals("modelCustomizationUuid")); + assert (nr.getNetworkId().equals("networkId")); + assert (nr.getNetworkName().equals("networkName")); + assert (nr.getNetworkStackId().equals("networkStackId")); + assert (nr.getNeutronNetworkId().equals("neutronNetworkId")); + assert (nr.getPhysicalNetwork().equals("physicalNetwork")); + assert (nr.getNetworkType().equals("networkType")); + assert (nr.getTenantId().equals("tenantId")); + assert (nr.getMsoRequest().equals(ms)); assertFalse(nr.getNetworkCreated()); - assert(nr.getVlans().equals(vlans)); - assert(nr.toString()!=null); + assert (nr.getVlans().equals(vlans)); + assert (nr.toString() != null); } } diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/NeutronCacheEntryTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/NeutronCacheEntryTest.java index 8626e7d177..2c67431f02 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/NeutronCacheEntryTest.java +++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/NeutronCacheEntryTest.java @@ -22,36 +22,34 @@ package org.onap.so.openstack.beans; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; - import java.util.Calendar; import java.util.GregorianCalendar; - import org.junit.Test; import org.onap.so.BaseTest; public class NeutronCacheEntryTest { - - private static final String NEUTRON_URL = "testNeutronUrl"; - private static final String TOKEN = "testToken"; - - @Test - public void isExpiredTrueTest() { - Calendar expires = new GregorianCalendar(2013,0,31); - NeutronCacheEntry neutronCacheEntry = new NeutronCacheEntry(NEUTRON_URL, TOKEN, expires); - assertTrue(neutronCacheEntry.isExpired()); - } - - @Test - public void isExpiredFalseTest() { - Calendar expires = new GregorianCalendar(2100,0,31); - NeutronCacheEntry neutronCacheEntry = new NeutronCacheEntry(NEUTRON_URL, TOKEN, expires); - assertFalse(neutronCacheEntry.isExpired()); - } - - @Test - public void isExpiredNullTest() { - Calendar expires = null; - NeutronCacheEntry neutronCacheEntry = new NeutronCacheEntry(NEUTRON_URL, TOKEN, expires); - assertTrue(neutronCacheEntry.isExpired()); - } + + private static final String NEUTRON_URL = "testNeutronUrl"; + private static final String TOKEN = "testToken"; + + @Test + public void isExpiredTrueTest() { + Calendar expires = new GregorianCalendar(2013, 0, 31); + NeutronCacheEntry neutronCacheEntry = new NeutronCacheEntry(NEUTRON_URL, TOKEN, expires); + assertTrue(neutronCacheEntry.isExpired()); + } + + @Test + public void isExpiredFalseTest() { + Calendar expires = new GregorianCalendar(2100, 0, 31); + NeutronCacheEntry neutronCacheEntry = new NeutronCacheEntry(NEUTRON_URL, TOKEN, expires); + assertFalse(neutronCacheEntry.isExpired()); + } + + @Test + public void isExpiredNullTest() { + Calendar expires = null; + NeutronCacheEntry neutronCacheEntry = new NeutronCacheEntry(NEUTRON_URL, TOKEN, expires); + assertTrue(neutronCacheEntry.isExpired()); + } } diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/OpenstackBeansPojoTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/OpenstackBeansPojoTest.java index ac194ccee2..9c2ed66318 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/OpenstackBeansPojoTest.java +++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/OpenstackBeansPojoTest.java @@ -30,18 +30,15 @@ import com.openpojo.validation.test.impl.GetterTester; import com.openpojo.validation.test.impl.SetterTester; public class OpenstackBeansPojoTest { - @Test - public void pojoStructure() { - test(PojoClassFactory.getPojoClass(VnfRollback.class)); - test(PojoClassFactory.getPojoClass(NeutronCacheEntry.class)); - test(PojoClassFactory.getPojoClass(HeatCacheEntry.class)); - } - - private void test(PojoClass pojoClass) { - Validator validator = ValidatorBuilder.create() - .with(new SetterTester()) - .with(new GetterTester()) - .build(); - validator.validate(pojoClass); - } + @Test + public void pojoStructure() { + test(PojoClassFactory.getPojoClass(VnfRollback.class)); + test(PojoClassFactory.getPojoClass(NeutronCacheEntry.class)); + test(PojoClassFactory.getPojoClass(HeatCacheEntry.class)); + } + + private void test(PojoClass pojoClass) { + Validator validator = ValidatorBuilder.create().with(new SetterTester()).with(new GetterTester()).build(); + validator.validate(pojoClass); + } } diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/VnfRollbackTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/VnfRollbackTest.java index 444a9a8e94..f3614c1b09 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/VnfRollbackTest.java +++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/VnfRollbackTest.java @@ -21,73 +21,73 @@ package org.onap.so.openstack.beans; import static org.junit.Assert.assertEquals; - import org.junit.Test; import org.onap.so.BaseTest; import org.onap.so.entity.MsoRequest; import org.springframework.beans.factory.annotation.Autowired; public class VnfRollbackTest extends BaseTest { - @Autowired - private VnfRollback vnfRollback; - - private String vnfId = "testVnfId"; - private String tenantId = "testTenantId"; - private String cloudOwner = "testCloudOwner"; - private String cloudSiteId = "testCloudSiteId"; - private boolean tenantCreated = true; - private boolean vnfCreated = true; - private MsoRequest msoRequest = new MsoRequest(); - private String volumeGroupName = "testVolumeGroupName"; - private String volumeGroupId = "testVolumeGroupId"; - private String requestType = "testRequestType"; - private String modelCustomizationUuid = "testModelCustimizationUuid"; - private String orchestrationMode = "testOrchestrationMode"; - private static final String VNF_ROLLBACK_STRING = "VnfRollback: cloud=testCloudSiteId, cloudOwner=testCloudOwner, tenant=testTenantId, vnf=testVnfId, " - + "tenantCreated=true, vnfCreated=true, requestType = testRequestType, modelCustomizationUuid=testModelCustimizationUuid, mode=testOrchestrationMode"; - - @Test - public void VnfRollbackInstantiationTest() { - vnfRollback = new VnfRollback(vnfId, tenantId, cloudOwner, cloudSiteId, tenantCreated, vnfCreated, - msoRequest, volumeGroupName, volumeGroupId, requestType, modelCustomizationUuid); - - assertEquals(vnfId, vnfRollback.getVnfId()); - assertEquals(tenantId, vnfRollback.getTenantId()); - assertEquals(cloudOwner, vnfRollback.getCloudOwner()); - assertEquals(cloudSiteId, vnfRollback.getCloudSiteId()); - assertEquals(tenantCreated, vnfRollback.getTenantCreated()); - assertEquals(vnfCreated, vnfRollback.getVnfCreated()); - assertEquals(msoRequest, vnfRollback.getMsoRequest()); - assertEquals(volumeGroupName, vnfRollback.getVolumeGroupName()); - assertEquals(volumeGroupId, vnfRollback.getVolumeGroupId()); - assertEquals(requestType, vnfRollback.getRequestType()); - assertEquals(modelCustomizationUuid, vnfRollback.getModelCustomizationUuid()); - } - - @Test - public void VnfRollbackInstantiationOrchestrationModeTest() { - vnfRollback = new VnfRollback(vnfId, tenantId, cloudOwner, cloudSiteId, tenantCreated, vnfCreated, - msoRequest, volumeGroupName, volumeGroupId, requestType, modelCustomizationUuid, orchestrationMode); - - assertEquals(vnfId, vnfRollback.getVnfId()); - assertEquals(tenantId, vnfRollback.getTenantId()); - assertEquals(cloudOwner, vnfRollback.getCloudOwner()); - assertEquals(cloudSiteId, vnfRollback.getCloudSiteId()); - assertEquals(tenantCreated, vnfRollback.getTenantCreated()); - assertEquals(vnfCreated, vnfRollback.getVnfCreated()); - assertEquals(msoRequest, vnfRollback.getMsoRequest()); - assertEquals(volumeGroupName, vnfRollback.getVolumeGroupName()); - assertEquals(volumeGroupId, vnfRollback.getVolumeGroupId()); - assertEquals(requestType, vnfRollback.getRequestType()); - assertEquals(modelCustomizationUuid, vnfRollback.getModelCustomizationUuid()); - assertEquals(orchestrationMode, vnfRollback.getMode()); - } - - @Test - public void toStringTest() { - vnfRollback = new VnfRollback(vnfId, tenantId, cloudOwner, cloudSiteId, tenantCreated, vnfCreated, - msoRequest, volumeGroupName, volumeGroupId, requestType, modelCustomizationUuid, orchestrationMode); - - assertEquals(VNF_ROLLBACK_STRING, vnfRollback.toString()); - } + @Autowired + private VnfRollback vnfRollback; + + private String vnfId = "testVnfId"; + private String tenantId = "testTenantId"; + private String cloudOwner = "testCloudOwner"; + private String cloudSiteId = "testCloudSiteId"; + private boolean tenantCreated = true; + private boolean vnfCreated = true; + private MsoRequest msoRequest = new MsoRequest(); + private String volumeGroupName = "testVolumeGroupName"; + private String volumeGroupId = "testVolumeGroupId"; + private String requestType = "testRequestType"; + private String modelCustomizationUuid = "testModelCustimizationUuid"; + private String orchestrationMode = "testOrchestrationMode"; + private static final String VNF_ROLLBACK_STRING = + "VnfRollback: cloud=testCloudSiteId, cloudOwner=testCloudOwner, tenant=testTenantId, vnf=testVnfId, " + + "tenantCreated=true, vnfCreated=true, requestType = testRequestType, modelCustomizationUuid=testModelCustimizationUuid, mode=testOrchestrationMode"; + + @Test + public void VnfRollbackInstantiationTest() { + vnfRollback = new VnfRollback(vnfId, tenantId, cloudOwner, cloudSiteId, tenantCreated, vnfCreated, msoRequest, + volumeGroupName, volumeGroupId, requestType, modelCustomizationUuid); + + assertEquals(vnfId, vnfRollback.getVnfId()); + assertEquals(tenantId, vnfRollback.getTenantId()); + assertEquals(cloudOwner, vnfRollback.getCloudOwner()); + assertEquals(cloudSiteId, vnfRollback.getCloudSiteId()); + assertEquals(tenantCreated, vnfRollback.getTenantCreated()); + assertEquals(vnfCreated, vnfRollback.getVnfCreated()); + assertEquals(msoRequest, vnfRollback.getMsoRequest()); + assertEquals(volumeGroupName, vnfRollback.getVolumeGroupName()); + assertEquals(volumeGroupId, vnfRollback.getVolumeGroupId()); + assertEquals(requestType, vnfRollback.getRequestType()); + assertEquals(modelCustomizationUuid, vnfRollback.getModelCustomizationUuid()); + } + + @Test + public void VnfRollbackInstantiationOrchestrationModeTest() { + vnfRollback = new VnfRollback(vnfId, tenantId, cloudOwner, cloudSiteId, tenantCreated, vnfCreated, msoRequest, + volumeGroupName, volumeGroupId, requestType, modelCustomizationUuid, orchestrationMode); + + assertEquals(vnfId, vnfRollback.getVnfId()); + assertEquals(tenantId, vnfRollback.getTenantId()); + assertEquals(cloudOwner, vnfRollback.getCloudOwner()); + assertEquals(cloudSiteId, vnfRollback.getCloudSiteId()); + assertEquals(tenantCreated, vnfRollback.getTenantCreated()); + assertEquals(vnfCreated, vnfRollback.getVnfCreated()); + assertEquals(msoRequest, vnfRollback.getMsoRequest()); + assertEquals(volumeGroupName, vnfRollback.getVolumeGroupName()); + assertEquals(volumeGroupId, vnfRollback.getVolumeGroupId()); + assertEquals(requestType, vnfRollback.getRequestType()); + assertEquals(modelCustomizationUuid, vnfRollback.getModelCustomizationUuid()); + assertEquals(orchestrationMode, vnfRollback.getMode()); + } + + @Test + public void toStringTest() { + vnfRollback = new VnfRollback(vnfId, tenantId, cloudOwner, cloudSiteId, tenantCreated, vnfCreated, msoRequest, + volumeGroupName, volumeGroupId, requestType, modelCustomizationUuid, orchestrationMode); + + assertEquals(VNF_ROLLBACK_STRING, vnfRollback.toString()); + } } diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoCommonUtilsTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoCommonUtilsTest.java index dbce712cb0..5cf7c86522 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoCommonUtilsTest.java +++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoCommonUtilsTest.java @@ -27,10 +27,8 @@ import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; - import java.io.File; import java.io.IOException; - import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; @@ -42,7 +40,6 @@ import org.onap.so.openstack.exceptions.MsoIOException; import org.onap.so.openstack.exceptions.MsoOpenstackException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; - import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; @@ -59,149 +56,150 @@ import com.woorea.openstack.quantum.model.NeutronError; * This class implements test methods of the MsoCommonUtils */ public class MsoCommonUtilsTest extends BaseTest { - @Autowired - @Qualifier("CommonUtils") - private MsoCommonUtils commonUtils; - - @Mock - private OpenStackRequest openstackRequest; - - @Test + @Autowired + @Qualifier("CommonUtils") + private MsoCommonUtils commonUtils; + + @Mock + private OpenStackRequest openstackRequest; + + @Test public final void testExecuteAndRecordOpenstackRequest() { - Mockito.when(openstackRequest.endpoint()).thenReturn("localhost"); - Mockito.when(openstackRequest.path()).thenReturn("/test"); - //TODO:Must try a real connection - assertNull(commonUtils.executeAndRecordOpenstackRequest (openstackRequest)); - } - - @Test - public void testexecuteAndRecordOpenstackRequestResponseException() { - expectedException.expect(OpenStackResponseException.class); - - doThrow(OpenStackResponseException.class).when(openstackRequest).execute(); - - commonUtils.executeAndRecordOpenstackRequest(openstackRequest); - } - - @Test - public void testexecuteAndRecordOpenstackRequestConnectException() { - expectedException.expect(OpenStackConnectException.class); - - doThrow(OpenStackConnectException.class).when(openstackRequest).execute(); - - commonUtils.executeAndRecordOpenstackRequest(openstackRequest); - } - - @Test + Mockito.when(openstackRequest.endpoint()).thenReturn("localhost"); + Mockito.when(openstackRequest.path()).thenReturn("/test"); + // TODO:Must try a real connection + assertNull(commonUtils.executeAndRecordOpenstackRequest(openstackRequest)); + } + + @Test + public void testexecuteAndRecordOpenstackRequestResponseException() { + expectedException.expect(OpenStackResponseException.class); + + doThrow(OpenStackResponseException.class).when(openstackRequest).execute(); + + commonUtils.executeAndRecordOpenstackRequest(openstackRequest); + } + + @Test + public void testexecuteAndRecordOpenstackRequestConnectException() { + expectedException.expect(OpenStackConnectException.class); + + doThrow(OpenStackConnectException.class).when(openstackRequest).execute(); + + commonUtils.executeAndRecordOpenstackRequest(openstackRequest); + } + + @Test public final void testKeystoneErrorToMsoException() throws JsonParseException, JsonMappingException, IOException { - OpenStackBaseException openStackConnectException = new OpenStackConnectException("connect"); - - OpenStackBaseException openStackResponseException = new OpenStackResponseException("response",1); - - MsoException me = commonUtils.keystoneErrorToMsoException(openStackConnectException,"ContextError"); - - assertTrue(me instanceof MsoIOException); - assertTrue("connect".equals(me.getMessage())); - - - MsoException me2 = commonUtils.keystoneErrorToMsoException(openStackResponseException,"ContextError"); - assertTrue(me2 instanceof MsoOpenstackException); - assertTrue("ContextError".equals(me2.getContext())); - assertTrue(MsoExceptionCategory.OPENSTACK.equals(me2.getCategory())); - - - OpenStackResponse openStackResponse = Mockito.mock(OpenStackResponse.class); - Error error = mapper.readValue(new File(RESOURCE_PATH + "Error.json"), Error.class); - - doReturn(error).when(openStackResponse).getErrorEntity(eq(Error.class)); - - openStackResponseException = new OpenStackResponseException("response", 501, openStackResponse); - - MsoException me3 = commonUtils.keystoneErrorToMsoException(openStackResponseException,"ContextError"); - - assertTrue(me3 instanceof MsoOpenstackException); - assertEquals("1 title: message", me3.toString()); - } - - @Test - public final void testHeatExceptionToMsoException() throws JsonParseException, JsonMappingException, IOException { - OpenStackBaseException openStackConnectException = new OpenStackConnectException("connect"); - - OpenStackBaseException openStackResponseException = new OpenStackResponseException("response",1); - - MsoException me = commonUtils.heatExceptionToMsoException(openStackConnectException,"ContextError"); - - assertTrue(me instanceof MsoIOException); - assertTrue("connect".equals(me.getMessage())); - - - MsoException me2 = commonUtils.heatExceptionToMsoException(openStackResponseException,"ContextError"); - assertTrue(me2 instanceof MsoOpenstackException); - assertTrue("ContextError".equals(me2.getContext())); - assertTrue(MsoExceptionCategory.OPENSTACK.equals(me2.getCategory())); - - - OpenStackResponse openStackResponse = Mockito.mock(OpenStackResponse.class); - Explanation explanation = mapper.readValue(new File(RESOURCE_PATH + "Explanation.json"), Explanation.class); - - doReturn(explanation).when(openStackResponse).getErrorEntity(eq(Explanation.class)); - - openStackResponseException = new OpenStackResponseException("response", 501, openStackResponse); - - MsoException me3 = commonUtils.heatExceptionToMsoException(openStackResponseException,"ContextError"); - - assertTrue(me3 instanceof MsoOpenstackException); - assertEquals("1 title: explanation, error.type=null, error.message=null", me3.toString()); - } - - @Test - public final void testNeutronExceptionToMsoException() throws JsonParseException, JsonMappingException, IOException { - OpenStackBaseException openStackConnectException = new OpenStackConnectException("connect"); - - OpenStackBaseException openStackResponseException = new OpenStackResponseException("response",1); - - MsoException me = commonUtils.neutronExceptionToMsoException(openStackConnectException,"ContextError"); - - assertTrue(me instanceof MsoIOException); - assertTrue("connect".equals(me.getMessage())); - - MsoException me2 = commonUtils.neutronExceptionToMsoException(openStackResponseException,"ContextError"); - assertTrue(me2 instanceof MsoOpenstackException); - assertTrue("ContextError".equals(me2.getContext())); - assertTrue(MsoExceptionCategory.OPENSTACK.equals(me2.getCategory())); - - - OpenStackResponse openStackResponse = Mockito.mock(OpenStackResponse.class); - NeutronError explanation = mapper.readValue(new File(RESOURCE_PATH + "NeutronError.json"), NeutronError.class); - - doReturn(explanation).when(openStackResponse).getErrorEntity(eq(NeutronError.class)); - - openStackResponseException = new OpenStackResponseException("response", 501, openStackResponse); - - MsoException me3 = commonUtils.neutronExceptionToMsoException(openStackResponseException,"ContextError"); - - assertTrue(me3 instanceof MsoOpenstackException); - assertEquals("501 type: message", me3.toString()); - } - - @Test - public final void testRuntimeExceptionToMsoException() { - RuntimeException re = new RuntimeException("runtime"); - MsoException me = commonUtils.runtimeExceptionToMsoException(re, "ContextError"); - - assertTrue(me instanceof MsoAdapterException); - assertTrue("ContextError".equals(me.getContext())); + OpenStackBaseException openStackConnectException = new OpenStackConnectException("connect"); + + OpenStackBaseException openStackResponseException = new OpenStackResponseException("response", 1); + + MsoException me = commonUtils.keystoneErrorToMsoException(openStackConnectException, "ContextError"); + + assertTrue(me instanceof MsoIOException); + assertTrue("connect".equals(me.getMessage())); + + + MsoException me2 = commonUtils.keystoneErrorToMsoException(openStackResponseException, "ContextError"); + assertTrue(me2 instanceof MsoOpenstackException); + assertTrue("ContextError".equals(me2.getContext())); + assertTrue(MsoExceptionCategory.OPENSTACK.equals(me2.getCategory())); + + + OpenStackResponse openStackResponse = Mockito.mock(OpenStackResponse.class); + Error error = mapper.readValue(new File(RESOURCE_PATH + "Error.json"), Error.class); + + doReturn(error).when(openStackResponse).getErrorEntity(eq(Error.class)); + + openStackResponseException = new OpenStackResponseException("response", 501, openStackResponse); + + MsoException me3 = commonUtils.keystoneErrorToMsoException(openStackResponseException, "ContextError"); + + assertTrue(me3 instanceof MsoOpenstackException); + assertEquals("1 title: message", me3.toString()); + } + + @Test + public final void testHeatExceptionToMsoException() throws JsonParseException, JsonMappingException, IOException { + OpenStackBaseException openStackConnectException = new OpenStackConnectException("connect"); + + OpenStackBaseException openStackResponseException = new OpenStackResponseException("response", 1); + + MsoException me = commonUtils.heatExceptionToMsoException(openStackConnectException, "ContextError"); + + assertTrue(me instanceof MsoIOException); + assertTrue("connect".equals(me.getMessage())); + + + MsoException me2 = commonUtils.heatExceptionToMsoException(openStackResponseException, "ContextError"); + assertTrue(me2 instanceof MsoOpenstackException); + assertTrue("ContextError".equals(me2.getContext())); + assertTrue(MsoExceptionCategory.OPENSTACK.equals(me2.getCategory())); + + + OpenStackResponse openStackResponse = Mockito.mock(OpenStackResponse.class); + Explanation explanation = mapper.readValue(new File(RESOURCE_PATH + "Explanation.json"), Explanation.class); + + doReturn(explanation).when(openStackResponse).getErrorEntity(eq(Explanation.class)); + + openStackResponseException = new OpenStackResponseException("response", 501, openStackResponse); + + MsoException me3 = commonUtils.heatExceptionToMsoException(openStackResponseException, "ContextError"); + + assertTrue(me3 instanceof MsoOpenstackException); + assertEquals("1 title: explanation, error.type=null, error.message=null", me3.toString()); + } + + @Test + public final void testNeutronExceptionToMsoException() + throws JsonParseException, JsonMappingException, IOException { + OpenStackBaseException openStackConnectException = new OpenStackConnectException("connect"); + + OpenStackBaseException openStackResponseException = new OpenStackResponseException("response", 1); + + MsoException me = commonUtils.neutronExceptionToMsoException(openStackConnectException, "ContextError"); + + assertTrue(me instanceof MsoIOException); + assertTrue("connect".equals(me.getMessage())); + + MsoException me2 = commonUtils.neutronExceptionToMsoException(openStackResponseException, "ContextError"); + assertTrue(me2 instanceof MsoOpenstackException); + assertTrue("ContextError".equals(me2.getContext())); + assertTrue(MsoExceptionCategory.OPENSTACK.equals(me2.getCategory())); + + + OpenStackResponse openStackResponse = Mockito.mock(OpenStackResponse.class); + NeutronError explanation = mapper.readValue(new File(RESOURCE_PATH + "NeutronError.json"), NeutronError.class); + + doReturn(explanation).when(openStackResponse).getErrorEntity(eq(NeutronError.class)); + + openStackResponseException = new OpenStackResponseException("response", 501, openStackResponse); + + MsoException me3 = commonUtils.neutronExceptionToMsoException(openStackResponseException, "ContextError"); + + assertTrue(me3 instanceof MsoOpenstackException); + assertEquals("501 type: message", me3.toString()); + } + + @Test + public final void testRuntimeExceptionToMsoException() { + RuntimeException re = new RuntimeException("runtime"); + MsoException me = commonUtils.runtimeExceptionToMsoException(re, "ContextError"); + + assertTrue(me instanceof MsoAdapterException); + assertTrue("ContextError".equals(me.getContext())); assertTrue(MsoExceptionCategory.INTERNAL.equals(me.getCategory())); - } - - @Test - public void testIoExceptionToMsoException() { - IOException exception = new IOException("IOExceptionTestMessage"); - - MsoException msoException = commonUtils.ioExceptionToMsoException(exception, "ContextError"); - - assertTrue(msoException instanceof MsoAdapterException); - assertEquals("ContextError", msoException.getContext()); - assertTrue(MsoExceptionCategory.INTERNAL.equals(msoException.getCategory())); - } + } + + @Test + public void testIoExceptionToMsoException() { + IOException exception = new IOException("IOExceptionTestMessage"); + + MsoException msoException = commonUtils.ioExceptionToMsoException(exception, "ContextError"); + + assertTrue(msoException instanceof MsoAdapterException); + assertEquals("ContextError", msoException.getContext()); + assertTrue(MsoExceptionCategory.INTERNAL.equals(msoException.getCategory())); + } } diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatEnvironmentEntryTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatEnvironmentEntryTest.java index 700d03dad3..1b98f14e8c 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatEnvironmentEntryTest.java +++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatEnvironmentEntryTest.java @@ -25,16 +25,13 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; - import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.HashSet; - import org.junit.Test; import org.onap.so.TestDataSetup; import org.onap.so.db.catalog.beans.HeatTemplateParam; - import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; @@ -43,8 +40,8 @@ public class MsoHeatEnvironmentEntryTest extends TestDataSetup { private static final String PARAMETER_NAME = "keyTest"; private static final String VALUE_NAME = "valueTest"; private static final String NOT_EXISTING_PARAM = "notExistingParam"; - private static final String RAW_ENTRY_WITH_NO_RESOURCE_REGISTRY = "parameters: {" - + PARAMETER_NAME + ": " + VALUE_NAME + "}"; + private static final String RAW_ENTRY_WITH_NO_RESOURCE_REGISTRY = + "parameters: {" + PARAMETER_NAME + ": " + VALUE_NAME + "}"; private static final String RAW_ENTRY_WITH_RESOURCE_REGISTRY = "resource_registry: resourceTest"; private static final String RAW_ENTRY_INVALID = "invalidRawEntry"; @@ -57,13 +54,15 @@ public class MsoHeatEnvironmentEntryTest extends TestDataSetup { } @Test - public void toFullString_ResourceRegistryNotPresentInRawEntry() throws JsonParseException, JsonMappingException, IOException { + public void toFullString_ResourceRegistryNotPresentInRawEntry() + throws JsonParseException, JsonMappingException, IOException { StringBuilder sb = new StringBuilder(RAW_ENTRY_WITH_NO_RESOURCE_REGISTRY); - + MsoHeatEnvironmentEntry testedObject = new MsoHeatEnvironmentEntry(sb); - - HeatTemplateParam heatTemplateParam = mapper.readValue(new File(RESOURCE_PATH + "HeatTemplateParam.json"), HeatTemplateParam.class); - + + HeatTemplateParam heatTemplateParam = + mapper.readValue(new File(RESOURCE_PATH + "HeatTemplateParam.json"), HeatTemplateParam.class); + assertThat(testedObject.getRawEntry()).isEqualTo(sb); assertThat(testedObject.isValid()).isTrue(); assertThat(testedObject.containsParameter(PARAMETER_NAME)).isTrue(); @@ -71,18 +70,22 @@ public class MsoHeatEnvironmentEntryTest extends TestDataSetup { assertTrue(testedObject.containsParameter(PARAMETER_NAME, "dummyAlias")); assertTrue(testedObject.containsParameter("dummyName", PARAMETER_NAME)); assertFalse(testedObject.containsParameter("dummyName", "dummyAlias")); - assertEquals("parameters:\n " + PARAMETER_NAME + ": " + VALUE_NAME + "\n\n\n", testedObject.toFullString().toString()); - assertEquals("parameters:\n " + PARAMETER_NAME + ": " + VALUE_NAME + "\n\n\n", testedObject.toFullStringExcludeNonParams(new HashSet<HeatTemplateParam>(Arrays.asList(heatTemplateParam))).toString()); + assertEquals("parameters:\n " + PARAMETER_NAME + ": " + VALUE_NAME + "\n\n\n", + testedObject.toFullString().toString()); + assertEquals("parameters:\n " + PARAMETER_NAME + ": " + VALUE_NAME + "\n\n\n", + testedObject + .toFullStringExcludeNonParams(new HashSet<HeatTemplateParam>(Arrays.asList(heatTemplateParam))) + .toString()); assertEquals(1, testedObject.getNumberOfParameters()); assertFalse(testedObject.hasResources()); - + MsoHeatEnvironmentResource heatResource = new MsoHeatEnvironmentResource("resourceName", "resourceValue"); MsoHeatEnvironmentParameter heatParameter = new MsoHeatEnvironmentParameter("parameterName", "parameterValue"); testedObject.addResource(heatResource); testedObject.addParameter(heatParameter); assertEquals(1, testedObject.getNumberOfResources()); assertEquals(2, testedObject.getNumberOfParameters()); - + testedObject.setResources(null); testedObject.setParameters(null); assertNull(testedObject.getParameters()); @@ -91,7 +94,7 @@ public class MsoHeatEnvironmentEntryTest extends TestDataSetup { @Test public void toFullString_ExceptionOccurred() { - StringBuilder sb = new StringBuilder(RAW_ENTRY_INVALID); + StringBuilder sb = new StringBuilder(RAW_ENTRY_INVALID); MsoHeatEnvironmentEntry testedObject = new MsoHeatEnvironmentEntry(sb); assertThat(testedObject.getRawEntry()).isEqualTo(sb); assertThat(testedObject.isValid()).isFalse(); diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatEnvironmentParameterTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatEnvironmentParameterTest.java index 182a6d0e02..954f237ffe 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatEnvironmentParameterTest.java +++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatEnvironmentParameterTest.java @@ -1,46 +1,40 @@ /* -* ============LICENSE_START======================================================= - * ONAP : SO - * ================================================================================ - * Copyright (C) 2018 TechMahindra - * ================================================================================ - * 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 + * ============LICENSE_START======================================================= ONAP : SO + * ================================================================================ Copyright (C) 2018 TechMahindra + * ================================================================================ 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 + * 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. + * 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.so.openstack.utils; import static org.mockito.Mockito.mock; - import org.junit.Test; public class MsoHeatEnvironmentParameterTest { - @Test - public void test() { - MsoHeatEnvironmentParameter hep=mock(MsoHeatEnvironmentParameter.class); - Object op=hep.getName(); - MsoHeatEnvironmentParameter meo=new MsoHeatEnvironmentParameter(); - MsoHeatEnvironmentParameter mea=new MsoHeatEnvironmentParameter("name"); - MsoHeatEnvironmentParameter mep=new MsoHeatEnvironmentParameter("name"," value"); - mea.setName("name"); - mep.setValue("value"); - assert(mea.getName().equals("name")); - assert(mep.getValue().equals("value")); - assert(meo.toString()!=null); - //assertTrue(op.equals(hep)); - meo.equals(op); - meo.hashCode(); - } + @Test + public void test() { + MsoHeatEnvironmentParameter hep = mock(MsoHeatEnvironmentParameter.class); + Object op = hep.getName(); + MsoHeatEnvironmentParameter meo = new MsoHeatEnvironmentParameter(); + MsoHeatEnvironmentParameter mea = new MsoHeatEnvironmentParameter("name"); + MsoHeatEnvironmentParameter mep = new MsoHeatEnvironmentParameter("name", " value"); + mea.setName("name"); + mep.setValue("value"); + assert (mea.getName().equals("name")); + assert (mep.getValue().equals("value")); + assert (meo.toString() != null); + // assertTrue(op.equals(hep)); + meo.equals(op); + meo.hashCode(); + } } diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatEnvironmentResourceTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatEnvironmentResourceTest.java index 934c149055..2c67dfd009 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatEnvironmentResourceTest.java +++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatEnvironmentResourceTest.java @@ -1,49 +1,43 @@ /* -* ============LICENSE_START======================================================= - * ONAP : SO - * ================================================================================ - * Copyright (C) 2018 TechMahindra - * ================================================================================ - * 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 + * ============LICENSE_START======================================================= ONAP : SO + * ================================================================================ Copyright (C) 2018 TechMahindra + * ================================================================================ 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 + * 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. + * 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.so.openstack.utils; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; - import org.junit.Test; public class MsoHeatEnvironmentResourceTest { - @Test - public void test() { - Object op = true; + @Test + public void test() { + Object op = true; + + MsoHeatEnvironmentResource mre = new MsoHeatEnvironmentResource("name"); + MsoHeatEnvironmentResource mae = new MsoHeatEnvironmentResource("name", "maeValue"); + MsoHeatEnvironmentResource msoHER = new MsoHeatEnvironmentResource(); - MsoHeatEnvironmentResource mre = new MsoHeatEnvironmentResource("name"); - MsoHeatEnvironmentResource mae = new MsoHeatEnvironmentResource("name", "maeValue"); - MsoHeatEnvironmentResource msoHER = new MsoHeatEnvironmentResource(); - - msoHER.setName("msoHERName"); - msoHER.setValue("msoHERValue"); + msoHER.setName("msoHERName"); + msoHER.setValue("msoHERValue"); - assertEquals("name", mre.getName()); - assertEquals("maeValue", mae.getValue()); - assertEquals("\"msoHERName\": msoHERValue", msoHER.toString()); - assertEquals("\"name\": maeValue", mae.toString()); - assertFalse(mae.equals(op)); - assertTrue(mae.equals(mre)); - assertEquals("name".hashCode(), mae.hashCode()); - } + assertEquals("name", mre.getName()); + assertEquals("maeValue", mae.getValue()); + assertEquals("\"msoHERName\": msoHERValue", msoHER.toString()); + assertEquals("\"name\": maeValue", mae.toString()); + assertFalse(mae.equals(op)); + assertTrue(mae.equals(mre)); + assertEquals("name".hashCode(), mae.hashCode()); + } } diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsTest.java index 925365f00e..3f5402cc99 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsTest.java +++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsTest.java @@ -28,13 +28,11 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.shazam.shazamcrest.MatcherAssert.assertThat; import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; import static org.junit.Assert.assertNotNull; - import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - import org.apache.http.HttpStatus; import org.junit.Assert; import org.junit.Test; @@ -56,142 +54,142 @@ import org.onap.so.openstack.exceptions.MsoException; import org.onap.so.openstack.exceptions.MsoIOException; import org.onap.so.openstack.exceptions.MsoOpenstackException; import org.springframework.beans.factory.annotation.Autowired; - import com.woorea.openstack.heat.Heat; import com.woorea.openstack.heat.model.CreateStackParam; -public class MsoHeatUtilsTest extends BaseTest{ - - @Autowired - private MsoHeatUtils heatUtils; - - @Test - public void instantiateVduTest() throws MsoException, IOException { - VduInstance expected = new VduInstance(); - expected.setVduInstanceId("name/da886914-efb2-4917-b335-c8381528d90b"); - expected.setVduInstanceName("name"); - VduStatus status = new VduStatus(); - status.setState(VduStateType.INSTANTIATED); - status.setLastAction((new PluginAction("create", "complete", null))); - expected.setStatus(status); - - CloudInfo cloudInfo = new CloudInfo(); - cloudInfo.setCloudSiteId("MTN13"); - cloudInfo.setTenantId("tenantId"); - VduModelInfo vduModel = new VduModelInfo(); - vduModel.setModelCustomizationUUID("blueprintId"); - vduModel.setTimeoutMinutes(1); - VduArtifact artifact = new VduArtifact(); - artifact.setName("name"); - artifact.setType(ArtifactType.MAIN_TEMPLATE); - byte[] content = new byte[1]; - artifact.setContent(content); - List<VduArtifact> artifacts = new ArrayList<>(); - artifacts.add(artifact); - vduModel.setArtifacts(artifacts); - Map<String, byte[]> blueprintFiles = new HashMap<>(); - blueprintFiles.put(artifact.getName(), artifact.getContent()); - String instanceName = "instanceName"; - Map<String, Object> inputs = new HashMap<>(); - boolean rollbackOnFailure = true; - - StubOpenStack.mockOpenStackResponseAccess(wireMockServer, wireMockPort); - StubOpenStack.mockOpenStackPostStack_200(wireMockServer, "OpenstackResponse_Stack_Created.json"); - - wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/instanceName/stackId")) - .willReturn(aResponse().withHeader("Content-Type", "application/json") - .withBodyFile("OpenstackResponse_StackId.json") - .withStatus(HttpStatus.SC_OK))); - - VduInstance actual = heatUtils.instantiateVdu(cloudInfo, instanceName, inputs, vduModel, rollbackOnFailure); - - assertThat(actual, sameBeanAs(expected)); - } - - - @Test - public void queryVduTest() throws Exception { - VduInstance expected = new VduInstance(); - expected.setVduInstanceId("name/da886914-efb2-4917-b335-c8381528d90b"); - expected.setVduInstanceName("name"); - VduStatus status = new VduStatus(); - status.setState(VduStateType.INSTANTIATED); - status.setLastAction((new PluginAction("create", "complete",null))); - expected.setStatus(status); - - CloudInfo cloudInfo = new CloudInfo(); - cloudInfo.setCloudSiteId("mtn13"); - cloudInfo.setTenantId("tenantId"); - String instanceId = "instanceId"; - - StubOpenStack.mockOpenStackResponseAccess(wireMockServer, wireMockPort); - StubOpenStack.mockOpenStackPostStack_200(wireMockServer, "OpenstackResponse_Stack_Created.json"); - - wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/instanceId")) - .willReturn(aResponse().withHeader("Content-Type", "application/json") - .withBodyFile("OpenstackResponse_StackId.json") - .withStatus(HttpStatus.SC_OK))); - - VduInstance actual = heatUtils.queryVdu(cloudInfo, instanceId); - - assertThat(actual, sameBeanAs(expected)); - } - - @Test - public void deleteVduTest() throws Exception { - VduInstance expected = new VduInstance(); - expected.setVduInstanceId("instanceId"); - expected.setVduInstanceName("instanceId"); - VduStatus status = new VduStatus(); - status.setState(VduStateType.DELETED); - expected.setStatus(status); - - CloudInfo cloudInfo = new CloudInfo(); - cloudInfo.setCloudSiteId("mtn13"); - cloudInfo.setTenantId("tenantId"); - String instanceId = "instanceId"; - - int timeoutInMinutes = 1; - - StubOpenStack.mockOpenStackResponseAccess(wireMockServer, wireMockPort); - wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/instanceId")).willReturn(aResponse().withBodyFile("OpenstackResponse_StackId.json").withStatus(HttpStatus.SC_OK))); - StubOpenStack.mockOpenStackDelete(wireMockServer, "name/da886914-efb2-4917-b335-c8381528d90b"); - wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/name/da886914-efb2-4917-b335-c8381528d90b")).willReturn(aResponse().withBodyFile("OpenstackResponse_Stack_DeleteComplete.json").withStatus(HttpStatus.SC_OK))); - - VduInstance actual = heatUtils.deleteVdu(cloudInfo, instanceId, timeoutInMinutes); - - assertThat(actual, sameBeanAs(expected)); - } - - @Test - public final void requestToStringBuilderTest() { - CreateStackParam param = new CreateStackParam(); - param.setDisableRollback(false); - param.setEnvironment("environment"); - param.setFiles(new HashMap<String, Object>()); - param.setParameters(new HashMap<>()); - param.setStackName("stackName"); - param.setTemplate("template"); - param.setTemplateUrl("http://templateUrl"); - param.setTimeoutMinutes(1); - - StringBuilder stringBuilder = heatUtils.requestToStringBuilder(param); - - Assert.assertTrue(stringBuilder.toString().contains("StackName:")); - } - - @Test - public final void copyBaseOutputsToInputsTest() { - Map<String, Object> inputs = new HashMap<>(); - inputs.put("str1", "str"); - Map<String, Object> otherStackOutputs = new HashMap<>(); - otherStackOutputs.put("str", "str"); - List<String> paramNames = new ArrayList<>(); - Map<String, String> aliases = new HashMap<>(); - aliases.put("str", "str"); - heatUtils.copyBaseOutputsToInputs(inputs, otherStackOutputs, null, aliases); - Assert.assertEquals("str",otherStackOutputs.get("str")); - } +public class MsoHeatUtilsTest extends BaseTest { + + @Autowired + private MsoHeatUtils heatUtils; + + @Test + public void instantiateVduTest() throws MsoException, IOException { + VduInstance expected = new VduInstance(); + expected.setVduInstanceId("name/da886914-efb2-4917-b335-c8381528d90b"); + expected.setVduInstanceName("name"); + VduStatus status = new VduStatus(); + status.setState(VduStateType.INSTANTIATED); + status.setLastAction((new PluginAction("create", "complete", null))); + expected.setStatus(status); + + CloudInfo cloudInfo = new CloudInfo(); + cloudInfo.setCloudSiteId("MTN13"); + cloudInfo.setTenantId("tenantId"); + VduModelInfo vduModel = new VduModelInfo(); + vduModel.setModelCustomizationUUID("blueprintId"); + vduModel.setTimeoutMinutes(1); + VduArtifact artifact = new VduArtifact(); + artifact.setName("name"); + artifact.setType(ArtifactType.MAIN_TEMPLATE); + byte[] content = new byte[1]; + artifact.setContent(content); + List<VduArtifact> artifacts = new ArrayList<>(); + artifacts.add(artifact); + vduModel.setArtifacts(artifacts); + Map<String, byte[]> blueprintFiles = new HashMap<>(); + blueprintFiles.put(artifact.getName(), artifact.getContent()); + String instanceName = "instanceName"; + Map<String, Object> inputs = new HashMap<>(); + boolean rollbackOnFailure = true; + + StubOpenStack.mockOpenStackResponseAccess(wireMockServer, wireMockPort); + StubOpenStack.mockOpenStackPostStack_200(wireMockServer, "OpenstackResponse_Stack_Created.json"); + + wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/instanceName/stackId")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withBodyFile("OpenstackResponse_StackId.json").withStatus(HttpStatus.SC_OK))); + + VduInstance actual = heatUtils.instantiateVdu(cloudInfo, instanceName, inputs, vduModel, rollbackOnFailure); + + assertThat(actual, sameBeanAs(expected)); + } + + + @Test + public void queryVduTest() throws Exception { + VduInstance expected = new VduInstance(); + expected.setVduInstanceId("name/da886914-efb2-4917-b335-c8381528d90b"); + expected.setVduInstanceName("name"); + VduStatus status = new VduStatus(); + status.setState(VduStateType.INSTANTIATED); + status.setLastAction((new PluginAction("create", "complete", null))); + expected.setStatus(status); + + CloudInfo cloudInfo = new CloudInfo(); + cloudInfo.setCloudSiteId("mtn13"); + cloudInfo.setTenantId("tenantId"); + String instanceId = "instanceId"; + + StubOpenStack.mockOpenStackResponseAccess(wireMockServer, wireMockPort); + StubOpenStack.mockOpenStackPostStack_200(wireMockServer, "OpenstackResponse_Stack_Created.json"); + + wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/instanceId")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withBodyFile("OpenstackResponse_StackId.json").withStatus(HttpStatus.SC_OK))); + + VduInstance actual = heatUtils.queryVdu(cloudInfo, instanceId); + + assertThat(actual, sameBeanAs(expected)); + } + + @Test + public void deleteVduTest() throws Exception { + VduInstance expected = new VduInstance(); + expected.setVduInstanceId("instanceId"); + expected.setVduInstanceName("instanceId"); + VduStatus status = new VduStatus(); + status.setState(VduStateType.DELETED); + expected.setStatus(status); + + CloudInfo cloudInfo = new CloudInfo(); + cloudInfo.setCloudSiteId("mtn13"); + cloudInfo.setTenantId("tenantId"); + String instanceId = "instanceId"; + + int timeoutInMinutes = 1; + + StubOpenStack.mockOpenStackResponseAccess(wireMockServer, wireMockPort); + wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/instanceId")) + .willReturn(aResponse().withBodyFile("OpenstackResponse_StackId.json").withStatus(HttpStatus.SC_OK))); + StubOpenStack.mockOpenStackDelete(wireMockServer, "name/da886914-efb2-4917-b335-c8381528d90b"); + wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/name/da886914-efb2-4917-b335-c8381528d90b")) + .willReturn(aResponse().withBodyFile("OpenstackResponse_Stack_DeleteComplete.json") + .withStatus(HttpStatus.SC_OK))); + + VduInstance actual = heatUtils.deleteVdu(cloudInfo, instanceId, timeoutInMinutes); + + assertThat(actual, sameBeanAs(expected)); + } + + @Test + public final void requestToStringBuilderTest() { + CreateStackParam param = new CreateStackParam(); + param.setDisableRollback(false); + param.setEnvironment("environment"); + param.setFiles(new HashMap<String, Object>()); + param.setParameters(new HashMap<>()); + param.setStackName("stackName"); + param.setTemplate("template"); + param.setTemplateUrl("http://templateUrl"); + param.setTimeoutMinutes(1); + + StringBuilder stringBuilder = heatUtils.requestToStringBuilder(param); + + Assert.assertTrue(stringBuilder.toString().contains("StackName:")); + } + + @Test + public final void copyBaseOutputsToInputsTest() { + Map<String, Object> inputs = new HashMap<>(); + inputs.put("str1", "str"); + Map<String, Object> otherStackOutputs = new HashMap<>(); + otherStackOutputs.put("str", "str"); + List<String> paramNames = new ArrayList<>(); + Map<String, String> aliases = new HashMap<>(); + aliases.put("str", "str"); + heatUtils.copyBaseOutputsToInputs(inputs, otherStackOutputs, null, aliases); + Assert.assertEquals("str", otherStackOutputs.get("str")); + } @Test public final void getHeatClientSuccessTest() throws MsoException, IOException { @@ -231,8 +229,7 @@ public class MsoHeatUtilsTest extends BaseTest{ StubOpenStack.mockOpenStackPostStack_200(wireMockServer, "OpenstackResponse_Stack_Created.json"); StubOpenStack.mockOpenStackGet(wireMockServer, "TEST-stack/stackId"); StackInfo stackInfo = heatUtils.createStack(cloudSite.getId(), "CloudOwner", "tenantId", "TEST-stack", null, - "TEST-heat", new HashMap<>(), false, 1, "TEST-env", - new HashMap<>(), new HashMap<>(), false); + "TEST-heat", new HashMap<>(), false, 1, "TEST-env", new HashMap<>(), new HashMap<>(), false); assertNotNull(stackInfo); } } diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsUnitTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsUnitTest.java index 9edc805cf3..7a48dc092a 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsUnitTest.java +++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsUnitTest.java @@ -23,7 +23,6 @@ package org.onap.so.openstack.utils; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; @@ -33,12 +32,10 @@ import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; - import org.junit.Test; import org.onap.so.db.catalog.beans.HeatTemplate; import org.onap.so.db.catalog.beans.HeatTemplateParam; import org.skyscreamer.jsonassert.JSONAssert; - import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonMappingException; @@ -47,150 +44,153 @@ import com.fasterxml.jackson.databind.ObjectMapper; public class MsoHeatUtilsUnitTest { - - private ObjectMapper mapper = new ObjectMapper(); - @Test - public void convertInputMapTest() throws JsonParseException, JsonMappingException, IOException { - MsoHeatUtils utils = new MsoHeatUtils(); - - Map<String, Object> input = new HashMap<>(); - HeatTemplate template = new HeatTemplate(); - template.setArtifactUuid("my-uuid"); - Set<HeatTemplateParam> parameters = template.getParameters(); - HeatTemplateParam paramNum = new HeatTemplateParam(); - paramNum.setParamType("number"); - paramNum.setParamName("my-number"); - input.put("my-number", "3"); - - HeatTemplateParam paramString = new HeatTemplateParam(); - paramString.setParamType("string"); - paramString.setParamName("my-string"); - input.put("my-string", "hello"); - - HeatTemplateParam paramJson = new HeatTemplateParam(); - paramJson.setParamType("json"); - paramJson.setParamName("my-json"); - - HeatTemplateParam paramJsonEscaped = new HeatTemplateParam(); - paramJsonEscaped.setParamType("json"); - paramJsonEscaped.setParamName("my-json-escaped"); - - Map<String, Object> jsonMap = mapper.readValue(getJson("free-form.json"), new TypeReference<Map<String, Object>>(){}); - input.put("my-json", jsonMap); - - input.put("my-json-escaped", getJson("free-form.json")); - - parameters.add(paramNum); - parameters.add(paramString); - parameters.add(paramJson); - parameters.add(paramJsonEscaped); - - Map<String, Object> output = utils.convertInputMap(input, template); - - assertEquals(3, output.get("my-number")); - assertEquals("hello", output.get("my-string")); - assertTrue("expect no change in type", output.get("my-json") instanceof Map); - assertTrue("expect string to become jsonNode", output.get("my-json-escaped") instanceof JsonNode); - - JSONAssert.assertEquals(getJson("free-form.json"), mapper.writeValueAsString(output.get("my-json-escaped")), false); - } - - @Test - public final void convertInputMapValuesTest() { - MsoHeatUtils utils = new MsoHeatUtils(); - Map<String, Object> inputs = new HashMap<>(); - Set<HeatTemplateParam> params = new HashSet<>(); - HeatTemplate ht = new HeatTemplate(); - HeatTemplateParam htp = new HeatTemplateParam(); - htp.setParamName("vnf_name"); - htp.setParamType("string"); - params.add(htp); - inputs.put("vnf_name", "a_vnf_name"); - htp = new HeatTemplateParam(); - htp.setParamName("image_size"); - htp.setParamType("number"); - params.add(htp); - inputs.put("image_size", "1024"); - htp = new HeatTemplateParam(); - htp.setParamName("external"); - htp.setParamType("boolean"); - params.add(htp); - inputs.put("external", "false"); - htp = new HeatTemplateParam(); - htp.setParamName("oam_ips"); - htp.setParamType("comma_delimited_list"); - params.add(htp); - inputs.put("oam_ips", "a,b"); - htp = new HeatTemplateParam(); - htp.setParamName("oam_prefixes"); - htp.setParamType("json"); - params.add(htp); - String jsonEscInput = "[{\"prefix\": \"aValue\"}, {\"prefix\": \"aValue2\"}]"; - inputs.put("oam_prefixes", jsonEscInput); - ht.setParameters(params); - - Map<String, Object> output = utils.convertInputMap(inputs, ht); - - assertEquals("a_vnf_name", output.get("vnf_name")); - assertEquals(1024, output.get("image_size")); - assertEquals(false, output.get("external")); - List<String> cdl = new ArrayList<>(); - cdl.add(0, "a"); - cdl.add(1, "b"); - assertEquals(cdl, output.get("oam_ips")); - ObjectMapper JSON_MAPPER = new ObjectMapper(); - JsonNode jn = null; - try { - jn = JSON_MAPPER.readTree(jsonEscInput); - } catch (Exception e) { - } - assertEquals(jn, output.get("oam_prefixes")); - } - - @Test - public final void convertInputMapNullsTest() { - MsoHeatUtils utils = new MsoHeatUtils(); - Map<String, Object> inputs = new HashMap<>(); - Set<HeatTemplateParam> params = new HashSet<>(); - HeatTemplate ht = new HeatTemplate(); - HeatTemplateParam htp = new HeatTemplateParam(); - htp.setParamName("vnf_name"); - htp.setParamType("string"); - params.add(htp); - inputs.put("vnf_name", null); - htp = new HeatTemplateParam(); - htp.setParamName("image_size"); - htp.setParamType("number"); - params.add(htp); - inputs.put("image_size", null); - htp = new HeatTemplateParam(); - htp.setParamName("external"); - htp.setParamType("boolean"); - params.add(htp); - inputs.put("external", null); - htp = new HeatTemplateParam(); - htp.setParamName("oam_ips"); - htp.setParamType("comma_delimited_list"); - params.add(htp); - inputs.put("oam_ips", null); - htp = new HeatTemplateParam(); - htp.setParamName("oam_prefixes"); - htp.setParamType("json"); - params.add(htp); - inputs.put("oam_prefixes", null); - ht.setParameters(params); - - Map<String, Object> output = utils.convertInputMap(inputs, ht); - - assertNull(output.get("vnf_name")); - assertNull(output.get("image_size")); - assertEquals(false, output.get("external")); - assertNull(output.get("oam_ips")); - assertNull(output.get("oam_prefixes")); - } - - private String getJson(String filename) throws IOException { - return new String(Files.readAllBytes(Paths.get("src/test/resources/__files/MsoHeatUtils/" + filename))); - } - + + private ObjectMapper mapper = new ObjectMapper(); + + @Test + public void convertInputMapTest() throws JsonParseException, JsonMappingException, IOException { + MsoHeatUtils utils = new MsoHeatUtils(); + + Map<String, Object> input = new HashMap<>(); + HeatTemplate template = new HeatTemplate(); + template.setArtifactUuid("my-uuid"); + Set<HeatTemplateParam> parameters = template.getParameters(); + HeatTemplateParam paramNum = new HeatTemplateParam(); + paramNum.setParamType("number"); + paramNum.setParamName("my-number"); + input.put("my-number", "3"); + + HeatTemplateParam paramString = new HeatTemplateParam(); + paramString.setParamType("string"); + paramString.setParamName("my-string"); + input.put("my-string", "hello"); + + HeatTemplateParam paramJson = new HeatTemplateParam(); + paramJson.setParamType("json"); + paramJson.setParamName("my-json"); + + HeatTemplateParam paramJsonEscaped = new HeatTemplateParam(); + paramJsonEscaped.setParamType("json"); + paramJsonEscaped.setParamName("my-json-escaped"); + + Map<String, Object> jsonMap = + mapper.readValue(getJson("free-form.json"), new TypeReference<Map<String, Object>>() {}); + input.put("my-json", jsonMap); + + input.put("my-json-escaped", getJson("free-form.json")); + + parameters.add(paramNum); + parameters.add(paramString); + parameters.add(paramJson); + parameters.add(paramJsonEscaped); + + Map<String, Object> output = utils.convertInputMap(input, template); + + assertEquals(3, output.get("my-number")); + assertEquals("hello", output.get("my-string")); + assertTrue("expect no change in type", output.get("my-json") instanceof Map); + assertTrue("expect string to become jsonNode", output.get("my-json-escaped") instanceof JsonNode); + + JSONAssert.assertEquals(getJson("free-form.json"), mapper.writeValueAsString(output.get("my-json-escaped")), + false); + } + + @Test + public final void convertInputMapValuesTest() { + MsoHeatUtils utils = new MsoHeatUtils(); + Map<String, Object> inputs = new HashMap<>(); + Set<HeatTemplateParam> params = new HashSet<>(); + HeatTemplate ht = new HeatTemplate(); + HeatTemplateParam htp = new HeatTemplateParam(); + htp.setParamName("vnf_name"); + htp.setParamType("string"); + params.add(htp); + inputs.put("vnf_name", "a_vnf_name"); + htp = new HeatTemplateParam(); + htp.setParamName("image_size"); + htp.setParamType("number"); + params.add(htp); + inputs.put("image_size", "1024"); + htp = new HeatTemplateParam(); + htp.setParamName("external"); + htp.setParamType("boolean"); + params.add(htp); + inputs.put("external", "false"); + htp = new HeatTemplateParam(); + htp.setParamName("oam_ips"); + htp.setParamType("comma_delimited_list"); + params.add(htp); + inputs.put("oam_ips", "a,b"); + htp = new HeatTemplateParam(); + htp.setParamName("oam_prefixes"); + htp.setParamType("json"); + params.add(htp); + String jsonEscInput = "[{\"prefix\": \"aValue\"}, {\"prefix\": \"aValue2\"}]"; + inputs.put("oam_prefixes", jsonEscInput); + ht.setParameters(params); + + Map<String, Object> output = utils.convertInputMap(inputs, ht); + + assertEquals("a_vnf_name", output.get("vnf_name")); + assertEquals(1024, output.get("image_size")); + assertEquals(false, output.get("external")); + List<String> cdl = new ArrayList<>(); + cdl.add(0, "a"); + cdl.add(1, "b"); + assertEquals(cdl, output.get("oam_ips")); + ObjectMapper JSON_MAPPER = new ObjectMapper(); + JsonNode jn = null; + try { + jn = JSON_MAPPER.readTree(jsonEscInput); + } catch (Exception e) { + } + assertEquals(jn, output.get("oam_prefixes")); + } + + @Test + public final void convertInputMapNullsTest() { + MsoHeatUtils utils = new MsoHeatUtils(); + Map<String, Object> inputs = new HashMap<>(); + Set<HeatTemplateParam> params = new HashSet<>(); + HeatTemplate ht = new HeatTemplate(); + HeatTemplateParam htp = new HeatTemplateParam(); + htp.setParamName("vnf_name"); + htp.setParamType("string"); + params.add(htp); + inputs.put("vnf_name", null); + htp = new HeatTemplateParam(); + htp.setParamName("image_size"); + htp.setParamType("number"); + params.add(htp); + inputs.put("image_size", null); + htp = new HeatTemplateParam(); + htp.setParamName("external"); + htp.setParamType("boolean"); + params.add(htp); + inputs.put("external", null); + htp = new HeatTemplateParam(); + htp.setParamName("oam_ips"); + htp.setParamType("comma_delimited_list"); + params.add(htp); + inputs.put("oam_ips", null); + htp = new HeatTemplateParam(); + htp.setParamName("oam_prefixes"); + htp.setParamType("json"); + params.add(htp); + inputs.put("oam_prefixes", null); + ht.setParameters(params); + + Map<String, Object> output = utils.convertInputMap(inputs, ht); + + assertNull(output.get("vnf_name")); + assertNull(output.get("image_size")); + assertEquals(false, output.get("external")); + assertNull(output.get("oam_ips")); + assertNull(output.get("oam_prefixes")); + } + + private String getJson(String filename) throws IOException { + return new String(Files.readAllBytes(Paths.get("src/test/resources/__files/MsoHeatUtils/" + filename))); + } + } diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsWithUpdateTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsWithUpdateTest.java index 5691d9cd69..8951f8a304 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsWithUpdateTest.java +++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsWithUpdateTest.java @@ -26,13 +26,11 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.verify; - import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Optional; - import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -48,7 +46,6 @@ import org.onap.so.openstack.beans.HeatStatus; import org.onap.so.openstack.beans.StackInfo; import org.onap.so.openstack.exceptions.MsoException; import org.springframework.core.env.Environment; - import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.woorea.openstack.base.client.OpenStackRequest; @@ -57,109 +54,110 @@ import com.woorea.openstack.heat.model.Stack; @RunWith(MockitoJUnitRunner.class) public class MsoHeatUtilsWithUpdateTest extends TestDataSetup { - @Mock - private CloudConfig cloudConfig; - - @Mock - private Environment environment; - - @Spy - @InjectMocks - private MsoHeatUtilsWithUpdate heatUtils; - + @Mock + private CloudConfig cloudConfig; + + @Mock + private Environment environment; + + @Spy + @InjectMocks + private MsoHeatUtilsWithUpdate heatUtils; + private String cloudOwner; - private String cloudSiteId; - private String tenantId; - private String stackName; - private String heatTemplate; - private Map<String, Object> stackInputs; - private boolean pollForCompletion; - private int timeoutMinutes; - - @Before - public void before() { - MockitoAnnotations.initMocks(this); - + private String cloudSiteId; + private String tenantId; + private String stackName; + private String heatTemplate; + private Map<String, Object> stackInputs; + private boolean pollForCompletion; + private int timeoutMinutes; + + @Before + public void before() { + MockitoAnnotations.initMocks(this); + cloudOwner = "cloudOwner"; - cloudSiteId = "cloudSiteId"; - tenantId = "tenantId"; - stackName = "stackName"; - heatTemplate = "heatTemplate"; - stackInputs = new HashMap<>(); - pollForCompletion = true; - timeoutMinutes = 0; - } - - @Test - public void updateStackTest() throws MsoException, JsonParseException, JsonMappingException, IOException { - CloudSite cloudSite = new CloudSite(); - Heat heatClient = new Heat("endpoint"); - Stack heatStack = mapper.readValue(new File(RESOURCE_PATH + "HeatStack.json"), Stack.class); - Stack updateStack = mapper.readValue(new File(RESOURCE_PATH + "UpdateStack.json"), Stack.class); - - StackInfo expectedStackInfo = new StackInfo("stackName", HeatStatus.UPDATED, "stackStatusReason", null); - expectedStackInfo.setCanonicalName("stackName/id"); - - doReturn(Optional.of(cloudSite)).when(cloudConfig).getCloudSite(isA(String.class)); - doReturn(heatClient).when(heatUtils).getHeatClient(isA(CloudSite.class), isA(String.class)); - doReturn(null).when(heatUtils).executeAndRecordOpenstackRequest(isA(OpenStackRequest.class)); - doReturn("0").when(environment).getProperty(isA(String.class), isA(String.class)); - doReturn(updateStack).when(heatUtils).queryHeatStack(isA(Heat.class), isA(String.class)); - - StackInfo actualStackInfo = heatUtils.updateStack(cloudSiteId, cloudOwner, tenantId, stackName, - heatTemplate, stackInputs, pollForCompletion, timeoutMinutes); - - assertThat(actualStackInfo, sameBeanAs(expectedStackInfo)); - } - - @Test - public void updateStackWithEnvironmentTest() throws JsonParseException, JsonMappingException, IOException, MsoException { - String environmentString = "environmentString"; - - CloudSite cloudSite = new CloudSite(); - Heat heatClient = new Heat("endpoint"); - Stack heatStack = mapper.readValue(new File(RESOURCE_PATH + "HeatStack.json"), Stack.class); - Stack updateStack = mapper.readValue(new File(RESOURCE_PATH + "UpdateStack.json"), Stack.class); - - StackInfo expectedStackInfo = new StackInfo("stackName", HeatStatus.UPDATED, "stackStatusReason", null); - expectedStackInfo.setCanonicalName("stackName/id"); - - doReturn(Optional.of(cloudSite)).when(cloudConfig).getCloudSite(isA(String.class)); - doReturn(heatClient).when(heatUtils).getHeatClient(isA(CloudSite.class), isA(String.class)); - - doReturn(null).when(heatUtils).executeAndRecordOpenstackRequest(isA(OpenStackRequest.class)); - doReturn("0").when(environment).getProperty(isA(String.class), isA(String.class)); - doReturn(updateStack).when(heatUtils).queryHeatStack(isA(Heat.class), isA(String.class)); - - StackInfo actualStackInfo = heatUtils.updateStack(cloudSiteId, cloudOwner, tenantId, stackName, - heatTemplate, stackInputs, pollForCompletion, timeoutMinutes, environmentString); - - assertThat(actualStackInfo, sameBeanAs(expectedStackInfo)); - } - - @Test - public void updateStackWithFilesTest() throws MsoException, JsonParseException, JsonMappingException, IOException { - String environmentString = "environmentString"; - Map<String, Object> files = new HashMap<>(); - files.put("file1", new Object()); - - CloudSite cloudSite = new CloudSite(); - Heat heatClient = new Heat("endpoint"); - Stack heatStack = mapper.readValue(new File(RESOURCE_PATH + "HeatStack.json"), Stack.class); - Stack updateStack = mapper.readValue(new File(RESOURCE_PATH + "UpdateStack.json"), Stack.class); - - StackInfo expectedStackInfo = new StackInfo("stackName", HeatStatus.UPDATED, "stackStatusReason", null); - expectedStackInfo.setCanonicalName("stackName/id"); - - doReturn(Optional.of(cloudSite)).when(cloudConfig).getCloudSite(isA(String.class)); - doReturn(heatClient).when(heatUtils).getHeatClient(isA(CloudSite.class), isA(String.class)); - doReturn(null).when(heatUtils).executeAndRecordOpenstackRequest(isA(OpenStackRequest.class)); - doReturn("0").when(environment).getProperty(isA(String.class), isA(String.class)); - doReturn(updateStack).when(heatUtils).queryHeatStack(isA(Heat.class), isA(String.class)); - - StackInfo actualStackInfo = heatUtils.updateStack(cloudSiteId, cloudOwner, tenantId, stackName, - heatTemplate, stackInputs, pollForCompletion, timeoutMinutes , environmentString, files); - - assertThat(actualStackInfo, sameBeanAs(expectedStackInfo)); - } + cloudSiteId = "cloudSiteId"; + tenantId = "tenantId"; + stackName = "stackName"; + heatTemplate = "heatTemplate"; + stackInputs = new HashMap<>(); + pollForCompletion = true; + timeoutMinutes = 0; + } + + @Test + public void updateStackTest() throws MsoException, JsonParseException, JsonMappingException, IOException { + CloudSite cloudSite = new CloudSite(); + Heat heatClient = new Heat("endpoint"); + Stack heatStack = mapper.readValue(new File(RESOURCE_PATH + "HeatStack.json"), Stack.class); + Stack updateStack = mapper.readValue(new File(RESOURCE_PATH + "UpdateStack.json"), Stack.class); + + StackInfo expectedStackInfo = new StackInfo("stackName", HeatStatus.UPDATED, "stackStatusReason", null); + expectedStackInfo.setCanonicalName("stackName/id"); + + doReturn(Optional.of(cloudSite)).when(cloudConfig).getCloudSite(isA(String.class)); + doReturn(heatClient).when(heatUtils).getHeatClient(isA(CloudSite.class), isA(String.class)); + doReturn(null).when(heatUtils).executeAndRecordOpenstackRequest(isA(OpenStackRequest.class)); + doReturn("0").when(environment).getProperty(isA(String.class), isA(String.class)); + doReturn(updateStack).when(heatUtils).queryHeatStack(isA(Heat.class), isA(String.class)); + + StackInfo actualStackInfo = heatUtils.updateStack(cloudSiteId, cloudOwner, tenantId, stackName, heatTemplate, + stackInputs, pollForCompletion, timeoutMinutes); + + assertThat(actualStackInfo, sameBeanAs(expectedStackInfo)); + } + + @Test + public void updateStackWithEnvironmentTest() + throws JsonParseException, JsonMappingException, IOException, MsoException { + String environmentString = "environmentString"; + + CloudSite cloudSite = new CloudSite(); + Heat heatClient = new Heat("endpoint"); + Stack heatStack = mapper.readValue(new File(RESOURCE_PATH + "HeatStack.json"), Stack.class); + Stack updateStack = mapper.readValue(new File(RESOURCE_PATH + "UpdateStack.json"), Stack.class); + + StackInfo expectedStackInfo = new StackInfo("stackName", HeatStatus.UPDATED, "stackStatusReason", null); + expectedStackInfo.setCanonicalName("stackName/id"); + + doReturn(Optional.of(cloudSite)).when(cloudConfig).getCloudSite(isA(String.class)); + doReturn(heatClient).when(heatUtils).getHeatClient(isA(CloudSite.class), isA(String.class)); + + doReturn(null).when(heatUtils).executeAndRecordOpenstackRequest(isA(OpenStackRequest.class)); + doReturn("0").when(environment).getProperty(isA(String.class), isA(String.class)); + doReturn(updateStack).when(heatUtils).queryHeatStack(isA(Heat.class), isA(String.class)); + + StackInfo actualStackInfo = heatUtils.updateStack(cloudSiteId, cloudOwner, tenantId, stackName, heatTemplate, + stackInputs, pollForCompletion, timeoutMinutes, environmentString); + + assertThat(actualStackInfo, sameBeanAs(expectedStackInfo)); + } + + @Test + public void updateStackWithFilesTest() throws MsoException, JsonParseException, JsonMappingException, IOException { + String environmentString = "environmentString"; + Map<String, Object> files = new HashMap<>(); + files.put("file1", new Object()); + + CloudSite cloudSite = new CloudSite(); + Heat heatClient = new Heat("endpoint"); + Stack heatStack = mapper.readValue(new File(RESOURCE_PATH + "HeatStack.json"), Stack.class); + Stack updateStack = mapper.readValue(new File(RESOURCE_PATH + "UpdateStack.json"), Stack.class); + + StackInfo expectedStackInfo = new StackInfo("stackName", HeatStatus.UPDATED, "stackStatusReason", null); + expectedStackInfo.setCanonicalName("stackName/id"); + + doReturn(Optional.of(cloudSite)).when(cloudConfig).getCloudSite(isA(String.class)); + doReturn(heatClient).when(heatUtils).getHeatClient(isA(CloudSite.class), isA(String.class)); + doReturn(null).when(heatUtils).executeAndRecordOpenstackRequest(isA(OpenStackRequest.class)); + doReturn("0").when(environment).getProperty(isA(String.class), isA(String.class)); + doReturn(updateStack).when(heatUtils).queryHeatStack(isA(Heat.class), isA(String.class)); + + StackInfo actualStackInfo = heatUtils.updateStack(cloudSiteId, cloudOwner, tenantId, stackName, heatTemplate, + stackInputs, pollForCompletion, timeoutMinutes, environmentString, files); + + assertThat(actualStackInfo, sameBeanAs(expectedStackInfo)); + } } diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoKeystoneUtilsTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoKeystoneUtilsTest.java index 3526a68ef6..6ecabfd45a 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoKeystoneUtilsTest.java +++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoKeystoneUtilsTest.java @@ -28,7 +28,6 @@ import org.onap.so.BaseTest; import org.onap.so.openstack.beans.MsoTenant; import org.onap.so.openstack.exceptions.MsoException; import org.springframework.beans.factory.annotation.Autowired; - import java.io.IOException; import java.util.HashMap; diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoMulticloudUtilsTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoMulticloudUtilsTest.java index e066c4eec6..0d8f451a6d 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoMulticloudUtilsTest.java +++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoMulticloudUtilsTest.java @@ -30,11 +30,9 @@ import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.when; import static org.onap.so.openstack.utils.MsoMulticloudUtils.MULTICLOUD_QUERY_BODY_NULL; - import java.io.IOException; import java.util.HashMap; import java.util.Optional; - import org.apache.http.HttpStatus; import org.junit.Before; import org.junit.Ignore; @@ -67,43 +65,40 @@ public class MsoMulticloudUtilsTest extends BaseTest { private CloudConfig cloudConfigMock; private static final String CREATE_STACK_RESPONSE = "{\"template_type\": \"TEST-template\", \"workload_id\": " - + "\"TEST-workload\", \"template_response\": {\"stack\": {\"id\": \"TEST-stack\", \"links\": []}}}"; - private static final String UPDATE_STACK_RESPONSE = "{\"template_type\": \"TEST-template\", \"workload_id\": " - + "\"TEST-workload\"}"; + + "\"TEST-workload\", \"template_response\": {\"stack\": {\"id\": \"TEST-stack\", \"links\": []}}}"; + private static final String UPDATE_STACK_RESPONSE = + "{\"template_type\": \"TEST-template\", \"workload_id\": " + "\"TEST-workload\"}"; private static final String GET_CREATE_STACK_RESPONSE = "{\"template_type\": \"TEST-template\", \"workload_id\": " + "\"TEST-workload\", \"workload_status\": \"CREATE_COMPLETE\"}"; private static final String GET_UPDATE_STACK_RESPONSE = "{\"template_type\": \"TEST-template\", \"workload_id\": " + "\"TEST-workload\", \"workload_status\": \"UPDATE_COMPLETE\"}"; private static final String MULTICLOUD_CREATE_PATH = "/api/multicloud/v1/CloudOwner/MTN14/infra_workload"; - private static final String MULTICLOUD_UPDATE_PATH = "/api/multicloud/v1/CloudOwner/MTN14/infra_workload/TEST-workload"; - private static final String MULTICLOUD_GET_PATH = "/api/multicloud/v1/CloudOwner/MTN14/infra_workload/TEST-workload"; + private static final String MULTICLOUD_UPDATE_PATH = + "/api/multicloud/v1/CloudOwner/MTN14/infra_workload/TEST-workload"; + private static final String MULTICLOUD_GET_PATH = + "/api/multicloud/v1/CloudOwner/MTN14/infra_workload/TEST-workload"; @Test public void createStackSuccess() throws MsoException, IOException { - wireMockServer.stubFor(post(urlPathEqualTo(MULTICLOUD_CREATE_PATH)).inScenario("CREATE") - .willReturn(aResponse().withHeader("Content-Type", "application/json") - .withBody(CREATE_STACK_RESPONSE) - .withStatus(HttpStatus.SC_CREATED)) - .willSetStateTo("CREATING")); - wireMockServer.stubFor(get(urlPathEqualTo(MULTICLOUD_GET_PATH)) - .inScenario("CREATE").whenScenarioStateIs("CREATING") - .willReturn(aResponse().withHeader("Content-Type", "application/json") - .withBody(GET_CREATE_STACK_RESPONSE) - .withStatus(HttpStatus.SC_OK))); - wireMockServer.stubFor(post(urlPathEqualTo(MULTICLOUD_UPDATE_PATH)).inScenario("CREATE") - .willReturn(aResponse().withHeader("Content-Type", "application/json") - .withBody(UPDATE_STACK_RESPONSE) - .withStatus(HttpStatus.SC_ACCEPTED)) + wireMockServer + .stubFor(post(urlPathEqualTo(MULTICLOUD_CREATE_PATH)).inScenario("CREATE") + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withBody(CREATE_STACK_RESPONSE).withStatus(HttpStatus.SC_CREATED)) + .willSetStateTo("CREATING")); + wireMockServer.stubFor(get(urlPathEqualTo(MULTICLOUD_GET_PATH)).inScenario("CREATE") + .whenScenarioStateIs("CREATING").willReturn(aResponse().withHeader("Content-Type", "application/json") + .withBody(GET_CREATE_STACK_RESPONSE).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(post(urlPathEqualTo(MULTICLOUD_UPDATE_PATH)) + .inScenario("CREATE").willReturn(aResponse().withHeader("Content-Type", "application/json") + .withBody(UPDATE_STACK_RESPONSE).withStatus(HttpStatus.SC_ACCEPTED)) .willSetStateTo("UPDATING")); - wireMockServer.stubFor(get(urlPathEqualTo(MULTICLOUD_GET_PATH)) - .inScenario("CREATE").whenScenarioStateIs("UPDATING") - .willReturn(aResponse().withHeader("Content-Type", "application/json") - .withBody(GET_UPDATE_STACK_RESPONSE) - .withStatus(HttpStatus.SC_OK))); - StackInfo result = multicloudUtils.createStack("MTN14", "CloudOwner", "TEST-tenant", "TEST-stack", new VduModelInfo(), - "TEST-heat", new HashMap<>(), true, 200, "TEST-env", - new HashMap<>(), new HashMap<>(), false); + wireMockServer.stubFor(get(urlPathEqualTo(MULTICLOUD_GET_PATH)).inScenario("CREATE") + .whenScenarioStateIs("UPDATING").willReturn(aResponse().withHeader("Content-Type", "application/json") + .withBody(GET_UPDATE_STACK_RESPONSE).withStatus(HttpStatus.SC_OK))); + StackInfo result = + multicloudUtils.createStack("MTN14", "CloudOwner", "TEST-tenant", "TEST-stack", new VduModelInfo(), + "TEST-heat", new HashMap<>(), true, 200, "TEST-env", new HashMap<>(), new HashMap<>(), false); wireMockServer.resetScenarios(); assertNotNull(result); assertEquals("TEST-stack", result.getName()); @@ -125,9 +120,8 @@ public class MsoMulticloudUtilsTest extends BaseTest { @Test public void queryStackWithNullMulticloudQueryBody() throws MsoException { wireMockServer.stubFor(get(urlPathEqualTo("/api/multicloud/v1/CloudOwner/MTN13/infra_workload/instanceId")) - .willReturn(aResponse().withHeader("Content-Type", "application/json") - .withBody(CREATE_STACK_RESPONSE) - .withStatus(HttpStatus.SC_OK))); + .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(CREATE_STACK_RESPONSE) + .withStatus(HttpStatus.SC_OK))); StackInfo result = multicloudUtils.queryStack("MTN13", "CloudOwner", "TEST-tenant", "instanceId"); assertTrue(HeatStatus.FAILED == result.getStatus()); @@ -136,8 +130,7 @@ public class MsoMulticloudUtilsTest extends BaseTest { @Test(expected = VduException.class) public void updateVdu() throws MsoException { - multicloudUtils.updateVdu(new CloudInfo(), "instanceId", new HashMap<>(), new VduModelInfo(), - false); + multicloudUtils.updateVdu(new CloudInfo(), "instanceId", new HashMap<>(), new VduModelInfo(), false); } @Test @@ -148,17 +141,16 @@ public class MsoMulticloudUtilsTest extends BaseTest { assertTrue(VduStateType.DELETED == vduInstance.getStatus().getState()); } - @Ignore @Test + @Ignore + @Test public void createStackMulticloudClientIsNull() { try { multicloudUtilsMock.cloudConfig = cloudConfigMock; CloudSite cloudSite = new CloudSite(); cloudSite.setIdentityService(new CloudIdentity()); - when(cloudConfigMock.getCloudSite("MTN13")). - thenReturn(Optional.of(cloudSite)); + when(cloudConfigMock.getCloudSite("MTN13")).thenReturn(Optional.of(cloudSite)); multicloudUtilsMock.createStack("MNT14", "CloudOwner", "TEST-tenant", "TEST-stack", new VduModelInfo(), - "TEST-heat", new HashMap<>(), false, 200, "TEST-env", - new HashMap<>(), new HashMap<>(), false); + "TEST-heat", new HashMap<>(), false, 200, "TEST-env", new HashMap<>(), new HashMap<>(), false); } catch (MsoException e) { assertEquals("0 : Multicloud client could not be initialized", e.toString()); return; @@ -169,12 +161,10 @@ public class MsoMulticloudUtilsTest extends BaseTest { @Test public void createStackBadRequest() { try { - wireMockServer.stubFor(post(urlPathEqualTo(MULTICLOUD_CREATE_PATH)) - .willReturn(aResponse().withHeader("Content-Type", "application/json") - .withStatus(HttpStatus.SC_BAD_REQUEST))); + wireMockServer.stubFor(post(urlPathEqualTo(MULTICLOUD_CREATE_PATH)).willReturn( + aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_BAD_REQUEST))); multicloudUtils.createStack("MTN14", "CloudOwner", "TEST-tenant", "TEST-stack", new VduModelInfo(), - "TEST-heat", new HashMap<>(), false, 200, "TEST-env", - new HashMap<>(), new HashMap<>(), false); + "TEST-heat", new HashMap<>(), false, 200, "TEST-env", new HashMap<>(), new HashMap<>(), false); } catch (MsoException e) { assertEquals("0 : Bad Request", e.toString()); return; @@ -184,12 +174,11 @@ public class MsoMulticloudUtilsTest extends BaseTest { @Test public void createStackEmptyResponseEntity() throws MsoException { - wireMockServer.stubFor(post(urlPathEqualTo(MULTICLOUD_CREATE_PATH)) - .willReturn(aResponse().withHeader("Content-Type", "application/json") - .withStatus(HttpStatus.SC_CREATED))); - StackInfo result = multicloudUtils.createStack("MTN14", "CloudOwner", "TEST-tenant", "TEST-stack", new VduModelInfo(), - "TEST-heat", new HashMap<>(), false, 200, "TEST-env", - new HashMap<>(), new HashMap<>(), false); + wireMockServer.stubFor(post(urlPathEqualTo(MULTICLOUD_CREATE_PATH)).willReturn( + aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_CREATED))); + StackInfo result = + multicloudUtils.createStack("MTN14", "CloudOwner", "TEST-tenant", "TEST-stack", new VduModelInfo(), + "TEST-heat", new HashMap<>(), false, 200, "TEST-env", new HashMap<>(), new HashMap<>(), false); assertNotNull(result); assertEquals("TEST-stack/", result.getName()); } diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoNeutronUtilsTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoNeutronUtilsTest.java index 8c337865df..56cdb128aa 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoNeutronUtilsTest.java +++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoNeutronUtilsTest.java @@ -28,61 +28,63 @@ import org.onap.so.BaseTest; import org.onap.so.openstack.beans.NetworkInfo; import org.onap.so.openstack.exceptions.MsoException; import org.springframework.beans.factory.annotation.Autowired; - import java.io.IOException; import java.util.ArrayList; import java.util.List; -public class MsoNeutronUtilsTest extends BaseTest{ - +public class MsoNeutronUtilsTest extends BaseTest { + @Autowired private MsoNeutronUtils msoNeutronUtils; private List<Integer> vlans; - + @Before public void before() throws IOException { vlans = new ArrayList<>(); vlans.add(3014); StubOpenStack.mockOpenStackResponseAccess(wireMockServer, wireMockPort); } - + @Test public void createNetworkTest_OpenStackBaseException() throws Exception { expectedException.expect(MsoException.class); - msoNeutronUtils.createNetwork("MTN13", "tenantId", - MsoNeutronUtils.NetworkType.PROVIDER,"networkName", "PROVIDER", vlans); + msoNeutronUtils.createNetwork("MTN13", "tenantId", MsoNeutronUtils.NetworkType.PROVIDER, "networkName", + "PROVIDER", vlans); } @Test public void createNetworkTest_NetworkTypeAsMultiProvider() throws Exception { StubOpenStack.mockOpenstackPostNetwork(wireMockServer, "OpenstackCreateNeutronNetworkResponse.json"); NetworkInfo networkInfo = msoNeutronUtils.createNetwork("MTN13", "tenantId", - MsoNeutronUtils.NetworkType.MULTI_PROVIDER,"networkName","PROVIDER", vlans); + MsoNeutronUtils.NetworkType.MULTI_PROVIDER, "networkName", "PROVIDER", vlans); - Assert.assertEquals("2a4017ef-31ff-496a-9294-e96ecc3bc9c9",networkInfo.getId()); + Assert.assertEquals("2a4017ef-31ff-496a-9294-e96ecc3bc9c9", networkInfo.getId()); } @Test public void createNetworkTest() throws Exception { StubOpenStack.mockOpenstackPostNetwork(wireMockServer, "OpenstackCreateNeutronNetworkResponse.json"); NetworkInfo networkInfo = msoNeutronUtils.createNetwork("MTN13", "tenantId", - MsoNeutronUtils.NetworkType.PROVIDER,"networkName","PROVIDER", vlans); + MsoNeutronUtils.NetworkType.PROVIDER, "networkName", "PROVIDER", vlans); - Assert.assertEquals("2a4017ef-31ff-496a-9294-e96ecc3bc9c9",networkInfo.getId()); + Assert.assertEquals("2a4017ef-31ff-496a-9294-e96ecc3bc9c9", networkInfo.getId()); } @Test public void queryNetworkTest() throws Exception { - StubOpenStack.mockOpenStackGetNeutronNetwork(wireMockServer, "GetNeutronNetwork.json", "43173f6a-d699-414b-888f-ab243dda6dfe"); - NetworkInfo networkInfo = msoNeutronUtils.queryNetwork("43173f6a-d699-414b-888f-ab243dda6dfe", "tenantId","MTN13"); + StubOpenStack.mockOpenStackGetNeutronNetwork(wireMockServer, "GetNeutronNetwork.json", + "43173f6a-d699-414b-888f-ab243dda6dfe"); + NetworkInfo networkInfo = + msoNeutronUtils.queryNetwork("43173f6a-d699-414b-888f-ab243dda6dfe", "tenantId", "MTN13"); - Assert.assertEquals("net1",networkInfo.getName()); + Assert.assertEquals("net1", networkInfo.getName()); } @Test public void queryNetworkTest_404() throws Exception { - NetworkInfo networkInfo = msoNeutronUtils.queryNetwork("43173f6a-d699-414b-888f-ab243dda6dfe", "tenantId","MTN13"); + NetworkInfo networkInfo = + msoNeutronUtils.queryNetwork("43173f6a-d699-414b-888f-ab243dda6dfe", "tenantId", "MTN13"); Assert.assertNull(networkInfo); } @@ -90,36 +92,41 @@ public class MsoNeutronUtilsTest extends BaseTest{ public void queryNetworkTest_500() throws Exception { expectedException.expect(MsoException.class); StubOpenStack.mockOpenStackGetNeutronNetwork_500(wireMockServer, "43173f6a-d699-414b-888f-ab243dda6dfe"); - msoNeutronUtils.queryNetwork("43173f6a-d699-414b-888f-ab243dda6dfe", "tenantId","MTN13"); + msoNeutronUtils.queryNetwork("43173f6a-d699-414b-888f-ab243dda6dfe", "tenantId", "MTN13"); } @Test public void deleteNetworkkTest() throws Exception { - StubOpenStack.mockOpenStackGetNeutronNetwork(wireMockServer, "GetNeutronNetwork.json", "43173f6a-d699-414b-888f-ab243dda6dfe"); + StubOpenStack.mockOpenStackGetNeutronNetwork(wireMockServer, "GetNeutronNetwork.json", + "43173f6a-d699-414b-888f-ab243dda6dfe"); StubOpenStack.mockOpenStackDeleteNeutronNetwork(wireMockServer, "43173f6a-d699-414b-888f-ab243dda6dfe"); - Boolean result = msoNeutronUtils.deleteNetwork("43173f6a-d699-414b-888f-ab243dda6dfe", "tenantId","MTN13"); + Boolean result = msoNeutronUtils.deleteNetwork("43173f6a-d699-414b-888f-ab243dda6dfe", "tenantId", "MTN13"); Assert.assertTrue(result); } @Test public void updateNetworkTest() throws Exception { - StubOpenStack.mockOpenStackGetNeutronNetwork(wireMockServer, "GetNeutronNetwork.json", "43173f6a-d699-414b-888f-ab243dda6dfe"); - StubOpenStack.mockOpenstackPutNetwork(wireMockServer, "OpenstackCreateNeutronNetworkResponse.json", "43173f6a-d699-414b-888f-ab243dda6dfe"); + StubOpenStack.mockOpenStackGetNeutronNetwork(wireMockServer, "GetNeutronNetwork.json", + "43173f6a-d699-414b-888f-ab243dda6dfe"); + StubOpenStack.mockOpenstackPutNetwork(wireMockServer, "OpenstackCreateNeutronNetworkResponse.json", + "43173f6a-d699-414b-888f-ab243dda6dfe"); NetworkInfo networkInfo = msoNeutronUtils.updateNetwork("MTN13", "tenantId", - "43173f6a-d699-414b-888f-ab243dda6dfe",MsoNeutronUtils.NetworkType.PROVIDER,"PROVIDER", vlans); + "43173f6a-d699-414b-888f-ab243dda6dfe", MsoNeutronUtils.NetworkType.PROVIDER, "PROVIDER", vlans); - Assert.assertEquals("2a4017ef-31ff-496a-9294-e96ecc3bc9c9",networkInfo.getId()); + Assert.assertEquals("2a4017ef-31ff-496a-9294-e96ecc3bc9c9", networkInfo.getId()); } @Test public void updateNetworkTest_NetworkTypeAsMultiProvider() throws Exception { - StubOpenStack.mockOpenStackGetNeutronNetwork(wireMockServer, "GetNeutronNetwork.json", "43173f6a-d699-414b-888f-ab243dda6dfe"); - StubOpenStack.mockOpenstackPutNetwork(wireMockServer, "OpenstackCreateNeutronNetworkResponse.json", "43173f6a-d699-414b-888f-ab243dda6dfe"); + StubOpenStack.mockOpenStackGetNeutronNetwork(wireMockServer, "GetNeutronNetwork.json", + "43173f6a-d699-414b-888f-ab243dda6dfe"); + StubOpenStack.mockOpenstackPutNetwork(wireMockServer, "OpenstackCreateNeutronNetworkResponse.json", + "43173f6a-d699-414b-888f-ab243dda6dfe"); NetworkInfo networkInfo = msoNeutronUtils.updateNetwork("MTN13", "tenantId", - "43173f6a-d699-414b-888f-ab243dda6dfe",MsoNeutronUtils.NetworkType.MULTI_PROVIDER,"PROVIDER", vlans); + "43173f6a-d699-414b-888f-ab243dda6dfe", MsoNeutronUtils.NetworkType.MULTI_PROVIDER, "PROVIDER", vlans); - Assert.assertEquals("2a4017ef-31ff-496a-9294-e96ecc3bc9c9",networkInfo.getId()); + Assert.assertEquals("2a4017ef-31ff-496a-9294-e96ecc3bc9c9", networkInfo.getId()); } } diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoTenantUtilsFactoryTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoTenantUtilsFactoryTest.java index f2717ab7ce..c9f3a8a8a8 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoTenantUtilsFactoryTest.java +++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoTenantUtilsFactoryTest.java @@ -27,7 +27,6 @@ import static org.assertj.core.api.Assertions.catchThrowableOfType; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.mock; - import java.util.Optional; import org.junit.Test; import org.junit.runner.RunWith; @@ -59,7 +58,7 @@ public class MsoTenantUtilsFactoryTest { // WHEN MsoCloudSiteNotFound msoCloudSiteNotFound = catchThrowableOfType( - () -> msoTenantUtilsFactory.getTenantUtils(cloudSiteId), MsoCloudSiteNotFound.class); + () -> msoTenantUtilsFactory.getTenantUtils(cloudSiteId), MsoCloudSiteNotFound.class); // THEN assertThat(msoCloudSiteNotFound.getMessage()).contains(cloudSiteId); @@ -90,7 +89,7 @@ public class MsoTenantUtilsFactoryTest { } private <T extends MsoTenantUtils> void shouldReturnAppropriateUtilsInstanceForGivenServerType( - ServerType serverType, T expectedInstance) throws MsoCloudSiteNotFound { + ServerType serverType, T expectedInstance) throws MsoCloudSiteNotFound { // GIVEN String cloudSiteId = "CloudSiteId"; CloudSite cloudSite = mock(CloudSite.class, RETURNS_DEEP_STUBS); diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoYamlEditorWithEnvtTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoYamlEditorWithEnvtTest.java index 70b5f2699d..90e874fc84 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoYamlEditorWithEnvtTest.java +++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoYamlEditorWithEnvtTest.java @@ -1,95 +1,90 @@ /* -* ============LICENSE_START======================================================= - * ONAP : SO - * ================================================================================ - * Copyright (C) 2018 TechMahindra - * ================================================================================ - * 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 + * ============LICENSE_START======================================================= ONAP : SO + * ================================================================================ Copyright (C) 2018 TechMahindra + * ================================================================================ 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 + * 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. + * 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.so.openstack.utils; import static com.shazam.shazamcrest.MatcherAssert.assertThat; import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; import static org.junit.Assert.assertNull; - import java.io.File; import java.io.IOException; import java.util.Set; - import org.junit.Test; import org.onap.so.TestDataSetup; import org.onap.so.db.catalog.beans.HeatTemplateParam; - import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; public class MsoYamlEditorWithEnvtTest extends TestDataSetup { - private MsoYamlEditorWithEnvt yaml; + private MsoYamlEditorWithEnvt yaml; private static final String PARAMETER_NAME = "keyTest"; private static final String PARAMETER_VALUE = "{type : paramType}"; private static final String RESOURCE_NAME = "resourceKey"; private static final String RESOURCE_VALUE = "resourceValue"; - private static final String RAW_ENTRY_WITH_RESOURCE_REGISTRY = "resource_registry: {" + RESOURCE_NAME + " : " + RESOURCE_VALUE + "}"; - private static final String RAW_ENTRY_WITH_NO_RESOURCE_REGISTRY = "parameters: {" - + PARAMETER_NAME + ": " + PARAMETER_VALUE + "}"; - - @Test - public void getParameterListTest() throws JsonParseException, JsonMappingException, IOException { - yaml = new MsoYamlEditorWithEnvt(RAW_ENTRY_WITH_NO_RESOURCE_REGISTRY.getBytes()); - - MsoHeatEnvironmentParameter expectedHeatParam = mapper.readValue(new File(RESOURCE_PATH + "HeatEnvironmentParameter.json"), MsoHeatEnvironmentParameter.class); - - Set<MsoHeatEnvironmentParameter> heatEnvironmentSet = yaml.getParameterListFromEnvt(); - - for(MsoHeatEnvironmentParameter heatEnvironment : heatEnvironmentSet) { - assertThat(heatEnvironment, sameBeanAs(expectedHeatParam)); - } - } - - @Test - public void getResourceListFromEnvtTest() { - yaml = new MsoYamlEditorWithEnvt(RAW_ENTRY_WITH_RESOURCE_REGISTRY.getBytes()); - - MsoHeatEnvironmentResource expectedHeatResource = new MsoHeatEnvironmentResource(RESOURCE_NAME, RESOURCE_VALUE); - - Set<MsoHeatEnvironmentResource> heatResourceSet = yaml.getResourceListFromEnvt(); - - for(MsoHeatEnvironmentResource heatResource : heatResourceSet) { - assertThat(heatResource, sameBeanAs(expectedHeatResource)); - } - } - - @Test - public void getResourceListFromEnvtExceptionTest() { - yaml = new MsoYamlEditorWithEnvt(); - - Set<MsoHeatEnvironmentResource> heatResourceSet = yaml.getResourceListFromEnvt(); - - assertNull(heatResourceSet); - } - - @Test - public void getParameterListFromEnvtTest() throws JsonParseException, JsonMappingException, IOException { - yaml = new MsoYamlEditorWithEnvt(RAW_ENTRY_WITH_NO_RESOURCE_REGISTRY.getBytes()); - - HeatTemplateParam expectedHeatParam = mapper.readValue(new File(RESOURCE_PATH + "HeatTemplateParamExpected.json"), HeatTemplateParam.class); - - Set<HeatTemplateParam> heatParamSet = yaml.getParameterList(); - - for(HeatTemplateParam heatParam : heatParamSet) { - assertThat(heatParam, sameBeanAs(expectedHeatParam)); - } - } + private static final String RAW_ENTRY_WITH_RESOURCE_REGISTRY = + "resource_registry: {" + RESOURCE_NAME + " : " + RESOURCE_VALUE + "}"; + private static final String RAW_ENTRY_WITH_NO_RESOURCE_REGISTRY = + "parameters: {" + PARAMETER_NAME + ": " + PARAMETER_VALUE + "}"; + + @Test + public void getParameterListTest() throws JsonParseException, JsonMappingException, IOException { + yaml = new MsoYamlEditorWithEnvt(RAW_ENTRY_WITH_NO_RESOURCE_REGISTRY.getBytes()); + + MsoHeatEnvironmentParameter expectedHeatParam = mapper.readValue( + new File(RESOURCE_PATH + "HeatEnvironmentParameter.json"), MsoHeatEnvironmentParameter.class); + + Set<MsoHeatEnvironmentParameter> heatEnvironmentSet = yaml.getParameterListFromEnvt(); + + for (MsoHeatEnvironmentParameter heatEnvironment : heatEnvironmentSet) { + assertThat(heatEnvironment, sameBeanAs(expectedHeatParam)); + } + } + + @Test + public void getResourceListFromEnvtTest() { + yaml = new MsoYamlEditorWithEnvt(RAW_ENTRY_WITH_RESOURCE_REGISTRY.getBytes()); + + MsoHeatEnvironmentResource expectedHeatResource = new MsoHeatEnvironmentResource(RESOURCE_NAME, RESOURCE_VALUE); + + Set<MsoHeatEnvironmentResource> heatResourceSet = yaml.getResourceListFromEnvt(); + + for (MsoHeatEnvironmentResource heatResource : heatResourceSet) { + assertThat(heatResource, sameBeanAs(expectedHeatResource)); + } + } + + @Test + public void getResourceListFromEnvtExceptionTest() { + yaml = new MsoYamlEditorWithEnvt(); + + Set<MsoHeatEnvironmentResource> heatResourceSet = yaml.getResourceListFromEnvt(); + + assertNull(heatResourceSet); + } + + @Test + public void getParameterListFromEnvtTest() throws JsonParseException, JsonMappingException, IOException { + yaml = new MsoYamlEditorWithEnvt(RAW_ENTRY_WITH_NO_RESOURCE_REGISTRY.getBytes()); + + HeatTemplateParam expectedHeatParam = + mapper.readValue(new File(RESOURCE_PATH + "HeatTemplateParamExpected.json"), HeatTemplateParam.class); + + Set<HeatTemplateParam> heatParamSet = yaml.getParameterList(); + + for (HeatTemplateParam heatParam : heatParamSet) { + assertThat(heatParam, sameBeanAs(expectedHeatParam)); + } + } } |