aboutsummaryrefslogtreecommitdiffstats
path: root/vid-app-common/src/test/java/org
diff options
context:
space:
mode:
Diffstat (limited to 'vid-app-common/src/test/java/org')
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/controller/AsyncInstantiationControllerTest.java178
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/job/command/VnfCommandTest.kt90
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/job/impl/AsyncInstantiationIntegrationTest.java20
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/model/serviceInstantiation/VfModuleTest.java62
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/testUtils/TestUtils.java38
5 files changed, 360 insertions, 28 deletions
diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/AsyncInstantiationControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/AsyncInstantiationControllerTest.java
new file mode 100644
index 000000000..9dcd1ec00
--- /dev/null
+++ b/vid-app-common/src/test/java/org/onap/vid/controller/AsyncInstantiationControllerTest.java
@@ -0,0 +1,178 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * VID
+ * ================================================================================
+ * Copyright (C) 2019 Nokia Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.vid.controller;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+import static org.mockito.Mockito.when;
+import static org.onap.vid.controller.AsyncInstantiationController.ASYNC_INSTANTIATION;
+import static org.springframework.http.MediaType.APPLICATION_JSON;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.UUID;
+import java.util.stream.Collectors;
+
+import org.checkerframework.checker.units.qual.A;
+import org.jeasy.random.EasyRandom;
+import org.jeasy.random.EasyRandomParameters;
+import org.jeasy.random.FieldPredicates;
+import org.jeasy.random.randomizers.misc.BooleanRandomizer;
+import org.jeasy.random.randomizers.text.StringRandomizer;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.ArgumentCaptor;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.onap.vid.dal.AsyncInstantiationRepository;
+import org.onap.vid.model.ServiceInfo;
+import org.onap.vid.model.serviceInstantiation.ServiceInstantiation;
+import org.onap.vid.mso.MsoResponseWrapper2;
+import org.onap.vid.roles.RoleProvider;
+import org.onap.vid.services.AsyncInstantiationBusinessLogic;
+import org.onap.vid.services.AuditService;
+import org.onap.vid.utils.SystemPropertiesWrapper;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+import org.togglz.core.manager.FeatureManager;
+
+public class AsyncInstantiationControllerTest {
+
+ private static final long STATIC_SEED = 5336L;
+ private final EasyRandomParameters parameters = new EasyRandomParameters()
+ .randomize(Boolean.class, new BooleanRandomizer(STATIC_SEED))
+ .randomize(String.class, new StringRandomizer(4, 4, STATIC_SEED))
+ .excludeField(FieldPredicates.ofType(Serializable.class))
+ .collectionSizeRange(1, 1);
+ private final EasyRandom modelGenerator = new EasyRandom(parameters);
+ private final ObjectMapper objectMapper = new ObjectMapper();
+
+ private MockMvc mockMvc;
+ private AsyncInstantiationBusinessLogic instantiationBusinessLogic;
+ private AsyncInstantiationRepository asyncInstantiationRepository;
+ private SystemPropertiesWrapper propertiesWrapper;
+ private AuditService auditService;
+
+ @Before
+ public void setUp() {
+ instantiationBusinessLogic = mock(AsyncInstantiationBusinessLogic.class);
+ RoleProvider roleProvider = mock(RoleProvider.class);
+ FeatureManager featureManager = mock(FeatureManager.class);
+ propertiesWrapper = mock(SystemPropertiesWrapper.class);
+ auditService = mock(AuditService.class);
+ asyncInstantiationRepository = mock(AsyncInstantiationRepository.class);
+ AsyncInstantiationController asyncInstantiationController = new AsyncInstantiationController(
+ instantiationBusinessLogic, asyncInstantiationRepository, roleProvider, featureManager, propertiesWrapper, auditService
+ );
+
+ mockMvc = MockMvcBuilders.standaloneSetup(asyncInstantiationController).build();
+ }
+
+ @Test
+ public void shouldReturnAllServiceInfos() throws Exception {
+ List<ServiceInfo> serviceInfos = modelGenerator.objects(ServiceInfo.class, 3).collect(Collectors.toList());
+ when(instantiationBusinessLogic.getAllServicesInfo()).thenReturn(serviceInfos);
+
+ mockMvc.perform(get("/" + ASYNC_INSTANTIATION))
+ .andExpect(content().json(asJson(serviceInfos)));
+
+ verify(instantiationBusinessLogic).getAllServicesInfo();
+ verifyNoMoreInteractions(instantiationBusinessLogic);
+ }
+
+ @Test
+ public void shouldRetryJobsWithGivenUuid() throws Exception {
+ when(propertiesWrapper.getProperty(SystemProperties.USER_ATTRIBUTE_NAME)).thenReturn("some user");
+
+ List<UUID> expectedUuids = new ArrayList<>();
+ expectedUuids.add(UUID.fromString("c195c600-a162-4655-9d88-d1a44518c4b5"));
+ expectedUuids.add(UUID.fromString("1a7ee2b5-ac2b-4dc7-a2a6-22e5d3b33d79"));
+ MsoResponseWrapper2<List<UUID>> expectedResponse = new MsoResponseWrapper2<>(200, expectedUuids);
+
+ ServiceInstantiation serviceInstantiation = modelGenerator.nextObject(ServiceInstantiation.class);
+
+ ArgumentCaptor<ServiceInstantiation> svcInstCaptor = ArgumentCaptor.forClass(ServiceInstantiation.class);
+ ArgumentCaptor<UUID> uuidCaptor = ArgumentCaptor.forClass(UUID.class);
+
+ when(instantiationBusinessLogic.retryJob(
+ svcInstCaptor.capture(),
+ uuidCaptor.capture(),
+ any()
+ )).thenReturn(expectedUuids);
+
+ mockMvc.perform(
+ post("/" + ASYNC_INSTANTIATION + "/retryJobWithChangedData/{jobId}",
+ "804d26c3-fbe9-426c-8eff-25c6ab18fdcf")
+ .content(asJson(serviceInstantiation))
+ .contentType(APPLICATION_JSON))
+ .andExpect(content().json(asJson(expectedResponse)));
+
+ assertThat(svcInstCaptor.getValue().getInstanceId()).isEqualTo(serviceInstantiation.getInstanceId());
+ assertThat(uuidCaptor.getValue()).isEqualTo(UUID.fromString("804d26c3-fbe9-426c-8eff-25c6ab18fdcf"));
+ }
+
+ @Test
+ public void shouldDeleteJob() throws Exception {
+ mockMvc.perform(
+ delete("/" + ASYNC_INSTANTIATION + "/job/{jobId}", "804d26c3-fbe9-426c-8eff-25c6ab18fdcf"));
+
+ verify(instantiationBusinessLogic).deleteJob(eq(UUID.fromString("804d26c3-fbe9-426c-8eff-25c6ab18fdcf")));
+ }
+
+ @Test
+ public void shouldHideServiceJob() throws Exception {
+ mockMvc.perform(
+ post("/" + ASYNC_INSTANTIATION + "/hide/{jobId}", "804d26c3-fbe9-426c-8eff-25c6ab18fdcf"));
+
+ verify(instantiationBusinessLogic).hideServiceInfo(eq(UUID.fromString("804d26c3-fbe9-426c-8eff-25c6ab18fdcf")));
+ }
+
+ @Test
+ public void shouldRetryJob() throws Exception {
+ when(propertiesWrapper.getProperty(SystemProperties.USER_ATTRIBUTE_NAME)).thenReturn("some user");
+
+ List<UUID> expectedUuids = new ArrayList<>();
+ expectedUuids.add(UUID.fromString("c195c600-a162-4655-9d88-d1a44518c4b5"));
+ expectedUuids.add(UUID.fromString("1a7ee2b5-ac2b-4dc7-a2a6-22e5d3b33d79"));
+ MsoResponseWrapper2<List<UUID>> expectedResponse = new MsoResponseWrapper2<>(200, expectedUuids);
+
+ when(instantiationBusinessLogic.retryJob(eq(UUID.fromString("804d26c3-fbe9-426c-8eff-25c6ab18fdcf")), any()))
+ .thenReturn(expectedUuids);
+
+ mockMvc.perform(
+ post("/" + ASYNC_INSTANTIATION + "/retry/{jobId}", "804d26c3-fbe9-426c-8eff-25c6ab18fdcf"))
+ .andExpect(content().json(asJson(expectedResponse)));
+ }
+
+ private <T> String asJson(T object) throws JsonProcessingException {
+ return objectMapper.writeValueAsString(object);
+ }
+} \ No newline at end of file
diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/VnfCommandTest.kt b/vid-app-common/src/test/java/org/onap/vid/job/command/VnfCommandTest.kt
new file mode 100644
index 000000000..660abe4d2
--- /dev/null
+++ b/vid-app-common/src/test/java/org/onap/vid/job/command/VnfCommandTest.kt
@@ -0,0 +1,90 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * VID
+ * ================================================================================
+ * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.vid.job.command
+
+import net.javacrumbs.jsonunit.JsonMatchers.jsonPartEquals
+import org.hamcrest.MatcherAssert.assertThat
+import org.hamcrest.core.AllOf.allOf
+import org.mockito.Answers
+import org.mockito.InjectMocks
+import org.mockito.Mock
+import org.onap.vid.job.JobAdapter
+import org.onap.vid.job.JobsBrokerService
+import org.onap.vid.job.command.ResourceCommandTest.FakeResourceCreator
+import org.onap.vid.job.impl.JobSharedData
+import org.onap.vid.model.Action
+import org.onap.vid.mso.RestMsoImplementation
+import org.onap.vid.properties.Features
+import org.onap.vid.services.AsyncInstantiationBusinessLogic
+import org.onap.vid.testUtils.TestUtils
+import org.onap.vid.testUtils.TestUtils.initMockitoMocks
+import org.testng.annotations.BeforeMethod
+import org.testng.annotations.Test
+import org.togglz.core.manager.FeatureManager
+import org.mockito.Mockito.`when` as _when
+
+class VnfCommandTest {
+
+ @Mock lateinit var asyncInstantiationBL: AsyncInstantiationBusinessLogic
+ @Mock lateinit var restMso: RestMsoImplementation
+ @Mock lateinit var msoRequestBuilder: MsoRequestBuilder
+ @Mock lateinit var msoResultHandlerService: MsoResultHandlerService
+ @Mock lateinit var inProgressStatusService:InProgressStatusService
+ @Mock lateinit var watchChildrenJobsBL: WatchChildrenJobsBL
+ @Mock lateinit var jobsBrokerService: JobsBrokerService
+ @Mock lateinit var jobAdapter: JobAdapter
+ @Mock lateinit var featureManager: FeatureManager
+
+ @Mock lateinit var jobSharedData: JobSharedData
+ @Mock(answer = Answers.RETURNS_MOCKS) lateinit var vnfJobRequest: org.onap.vid.model.serviceInstantiation.Vnf
+
+ @InjectMocks lateinit var vnfCommand: VnfCommand;
+
+ @BeforeMethod
+ fun initMocks() {
+ initMockitoMocks(this)
+ }
+
+ @Test(dataProvider = "trueAndFalse", dataProviderClass = TestUtils::class)
+ fun `childVfModuleWithVnfRegionAndTenant -- given vfmodule -- tenant and region are copied from vnf`(featureToggleOn: Boolean) {
+
+ val vfModule = FakeResourceCreator.createVfModule(Action.Create)
+ .cloneWith("vfmodule-lcp-cloud-region-id", "vfmodule-tenant-id")
+
+ _when(featureManager.isActive(Features.FLAG_2006_VFMODULE_TAKES_TENANT_AND_REGION_FROM_VNF)).thenReturn(featureToggleOn)
+
+ _when(vnfJobRequest.lcpCloudRegionId).thenReturn("vnf-lcp-cloud-region-id")
+ _when(vnfJobRequest.tenantId).thenReturn("vnf-tenant-id")
+ _when(jobSharedData.request).thenReturn(vnfJobRequest)
+
+ vnfCommand.init(jobSharedData, mapOf())
+
+ val expectedSource = if (featureToggleOn) "vnf" else "vfmodule"
+
+ assertThat(vnfCommand.childVfModuleWithVnfRegionAndTenant(vfModule),
+ allOf(
+ jsonPartEquals("lcpCloudRegionId", "${expectedSource}-lcp-cloud-region-id"),
+ jsonPartEquals("tenantId", "${expectedSource}-tenant-id")
+ )
+ )
+ }
+
+}
diff --git a/vid-app-common/src/test/java/org/onap/vid/job/impl/AsyncInstantiationIntegrationTest.java b/vid-app-common/src/test/java/org/onap/vid/job/impl/AsyncInstantiationIntegrationTest.java
index fe6cfafb4..642adb307 100644
--- a/vid-app-common/src/test/java/org/onap/vid/job/impl/AsyncInstantiationIntegrationTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/job/impl/AsyncInstantiationIntegrationTest.java
@@ -194,7 +194,12 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes
void defineMocks() {
Mockito.reset(restMso);
Mockito.reset(aaiClient);
+ Mockito.reset(commandUtils);
mockAaiClientAnyNameFree();
+
+ when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VNF)).thenReturn(true);
+ when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VFMODULE)).thenReturn(true);
+ when(featureManager.isActive(Features.FLAG_2006_VFMODULE_TAKES_TENANT_AND_REGION_FROM_VNF)).thenReturn(true);
}
@Test
@@ -376,9 +381,7 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes
* not looking on audit (yet)
*/
- reset(restMso);
- when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VNF)).thenReturn(true);
- when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VFMODULE)).thenReturn(false);
+ when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VFMODULE)).thenReturn(false); // this makes the test pass without mocking the vfModules
final String SERVICE_REQUEST_ID = UUID.randomUUID().toString();
final String SERVICE_INSTANCE_ID = UUID.randomUUID().toString();
final String VNF_REQUEST_ID = UUID.randomUUID().toString();
@@ -421,8 +424,6 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes
String msoVnfStatus = COMPLETE_STR;
- when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VNF)).thenReturn(true);
- when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VFMODULE)).thenReturn(true);
final String SERVICE_REQUEST_ID = UUID.randomUUID().toString();
final String SERVICE_INSTANCE_ID = UUID.randomUUID().toString();
final String VNF_REQUEST_ID = UUID.randomUUID().toString();
@@ -436,7 +437,6 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes
//push alacarte with 1 vnf, verify STATUS pending
UUID uuid = pushALaCarteWithVnf();
singleServicesAndAssertStatus(JobStatus.PENDING, uuid);
- reset(restMso);
/*---------- service -----------*/
@@ -519,8 +519,6 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes
NetworkDetails networkDetails1 = new NetworkDetails("LukaDoncic", "1");
NetworkDetails networkDetails2 = new NetworkDetails("KevinDurant", "2");
- reset(restMso);
-
/*---------- service -----------*/
//mock mso to answer 200 of create service instance request, verify STATUS in progress
@@ -1019,8 +1017,6 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes
JobStatus expectedJobStatus,
int getStatusCounter) throws IOException, AsdcCatalogException {
- when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VFMODULE)).thenReturn(true);
- reset(commandUtils);
when(commandUtils.isVfModuleBaseModule("6b528779-44a3-4472-bdff-9cd15ec93450", "f8360508-3f17-4414-a2ed-6bc71161e8db")).thenReturn(true);
when(commandUtils.isVfModuleBaseModule("6b528779-44a3-4472-bdff-9cd15ec93450", "25284168-24bb-4698-8cb4-3f509146eca5")).thenReturn(false);
@@ -1271,7 +1267,6 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes
asyncRequestStatusResponseAsRestObject(IN_PROGRESS_STR),
asyncRequestStatusResponseAsRestObject(COMPLETE_STR));
- when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VFMODULE)).thenReturn(true);
enableAddCloudOwnerOnMsoRequest();
@@ -1318,14 +1313,11 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes
public void deployService_failIt_retryDeploy_getRetryAsTemplate_makeSureFalsyIsFailedInTemplate() {
final String SERVICE_REQUEST_ID = UUID.randomUUID().toString();
- when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VNF)).thenReturn(true);
- when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VFMODULE)).thenReturn(true);
//push alacarte with 1 vnf, verify STATUS pending
UUID uuid = pushALaCarteWithVnf();
singleServicesAndAssertStatus(JobStatus.PENDING, uuid);
- reset(restMso);
//mock mso to answer 200 of create service instance request, verify STATUS in progress
when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), endsWith("serviceInstances"), any())).thenReturn(
createResponse(200, SERVICE_INSTANCE_ID, SERVICE_REQUEST_ID));
diff --git a/vid-app-common/src/test/java/org/onap/vid/model/serviceInstantiation/VfModuleTest.java b/vid-app-common/src/test/java/org/onap/vid/model/serviceInstantiation/VfModuleTest.java
new file mode 100644
index 000000000..a1c78c421
--- /dev/null
+++ b/vid-app-common/src/test/java/org/onap/vid/model/serviceInstantiation/VfModuleTest.java
@@ -0,0 +1,62 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * VID
+ * ================================================================================
+ * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.vid.model.serviceInstantiation;
+
+import static net.javacrumbs.jsonunit.JsonMatchers.jsonEquals;
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.beans.HasPropertyWithValue.hasProperty;
+import static org.hamcrest.core.AllOf.allOf;
+import static org.onap.vid.testUtils.TestUtils.setStringsInStringProperties;
+
+import org.onap.vid.mso.model.ModelInfo;
+import org.testng.annotations.Test;
+
+public class VfModuleTest {
+
+ @Test
+ public void cloneWithLcpCloudRegionIdAndTenantId() {
+ String targetLcpCloudRegionId = "dictated lcpCloudRegionId";
+ String targetTenantId = "dictated tenantId";
+
+ VfModule originVfModule = createVfModule();
+
+ assertThat(originVfModule.cloneWith(targetLcpCloudRegionId, targetTenantId), allOf(
+ hasProperty("lcpCloudRegionId", equalTo(targetLcpCloudRegionId)),
+ hasProperty("tenantId", equalTo(targetTenantId)),
+ jsonEquals(originVfModule).whenIgnoringPaths("lcpCloudRegionId", "tenantId")
+ ));
+
+ // verify vfModule did not mutate
+ assertThat(originVfModule, jsonEquals(createVfModule()));
+ }
+
+ private VfModule createVfModule() {
+ VfModule vfModule = new VfModule(
+ setStringsInStringProperties(new ModelInfo()),
+ null, null, null, null, null,
+ null, null, null, true, true,
+ null, null, true, null, true,
+ true, null, null);
+
+ return setStringsInStringProperties(vfModule);
+ }
+} \ No newline at end of file
diff --git a/vid-app-common/src/test/java/org/onap/vid/testUtils/TestUtils.java b/vid-app-common/src/test/java/org/onap/vid/testUtils/TestUtils.java
index 862b8db8f..71f7ee015 100644
--- a/vid-app-common/src/test/java/org/onap/vid/testUtils/TestUtils.java
+++ b/vid-app-common/src/test/java/org/onap/vid/testUtils/TestUtils.java
@@ -21,9 +21,7 @@
package org.onap.vid.testUtils;
import static com.fasterxml.jackson.module.kotlin.ExtensionsKt.jacksonObjectMapper;
-import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toList;
-import static java.util.stream.Collectors.toMap;
import static org.apache.commons.beanutils.PropertyUtils.getPropertyDescriptors;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.apache.commons.text.CharacterPredicates.DIGITS;
@@ -52,7 +50,9 @@ import java.lang.reflect.Field;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
+import java.util.Collections;
import java.util.Iterator;
+import java.util.LinkedList;
import java.util.List;
import java.util.function.Predicate;
import javax.ws.rs.client.Client;
@@ -61,7 +61,6 @@ import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
-import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.commons.lang3.reflect.FieldUtils;
@@ -174,15 +173,27 @@ public class TestUtils {
}
public static String[] allPropertiesOf(Class<?> aClass) {
- return Arrays.stream(getPropertyDescriptors(aClass))
+ return getPropertyDescriptorsRecursively(aClass).stream()
.map(PropertyDescriptor::getDisplayName)
+ .distinct()
.toArray(String[]::new);
}
+ private static List<PropertyDescriptor> getPropertyDescriptorsRecursively(Class<?> aClass) {
+ List<PropertyDescriptor> result = new LinkedList<>();
+
+ for (Class<?> i = aClass; i != null && i != Object.class; i = i.getSuperclass()) {
+ Collections.addAll(result, getPropertyDescriptors(i));
+ }
+
+ return result;
+ }
+
private static <T> List<String> allStringPropertiesOf(T object) {
- return Arrays.stream(getPropertyDescriptors(object.getClass()))
+ return getPropertyDescriptorsRecursively(object.getClass()).stream()
.filter(descriptor -> descriptor.getPropertyType().isAssignableFrom(String.class))
.map(PropertyDescriptor::getDisplayName)
+ .distinct()
.collect(toList());
}
@@ -221,16 +232,15 @@ public class TestUtils {
* @return The modified object
*/
public static <T> T setStringsInStringProperties(T object) {
- try {
- final List<String> stringFields = allStringPropertiesOf(object);
-
- BeanUtils.populate(object, stringFields.stream()
- .collect(toMap(identity(), identity())));
+ allStringPropertiesOf(object).forEach(it -> {
+ try {
+ FieldUtils.writeField(object, it, it, true);
+ } catch (IllegalAccessException e) {
+ // YOLO
+ }
+ });
- return object;
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
+ return object;
}
public static void registerCloudConfigurationValueGenerator() {