Search in sources :

Example 11 with ReferenceIdToKeyCache

use of com.commercetools.sync.commons.utils.ReferenceIdToKeyCache in project commercetools-sync-java by commercetools.

the class ProductTypeWithNestedAttributeSyncIT method setup.

/**
 * Deletes product types from source and target CTP projects. Populates source and target CTP
 * projects with test data.
 */
@BeforeEach
void setup() {
    removeAttributeReferencesAndDeleteProductTypes(CTP_SOURCE_CLIENT);
    removeAttributeReferencesAndDeleteProductTypes(CTP_TARGET_CLIENT);
    populateProjectWithNestedAttributes(CTP_SOURCE_CLIENT);
    builtUpdateActions = new ArrayList<>();
    errorMessages = new ArrayList<>();
    exceptions = new ArrayList<>();
    productTypeSyncOptions = ProductTypeSyncOptionsBuilder.of(CTP_TARGET_CLIENT).beforeUpdateCallback((actions, draft, oldProductType) -> {
        builtUpdateActions.addAll(actions);
        return actions;
    }).errorCallback((exception, oldResource, newResource, actions) -> {
        errorMessages.add(exception.getMessage());
        exceptions.add(exception);
    }).build();
    referenceIdToKeyCache = new CaffeineReferenceIdToKeyCacheImpl();
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) CTP_SOURCE_CLIENT(com.commercetools.sync.integration.commons.utils.SphereClientUtils.CTP_SOURCE_CLIENT) ProductTypeITUtils.removeAttributeReferencesAndDeleteProductTypes(com.commercetools.sync.integration.commons.utils.ProductTypeITUtils.removeAttributeReferencesAndDeleteProductTypes) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) ProductType(io.sphere.sdk.producttypes.ProductType) AssertionsForStatistics.assertThat(com.commercetools.sync.commons.asserts.statistics.AssertionsForStatistics.assertThat) UpdateAction(io.sphere.sdk.commands.UpdateAction) ArrayList(java.util.ArrayList) ProductTypeSyncOptionsBuilder(com.commercetools.sync.producttypes.ProductTypeSyncOptionsBuilder) AfterAll(org.junit.jupiter.api.AfterAll) ReferenceIdToKeyCache(com.commercetools.sync.commons.utils.ReferenceIdToKeyCache) ChangeAttributeDefinitionLabel(io.sphere.sdk.producttypes.commands.updateactions.ChangeAttributeDefinitionLabel) ProductTypeTransformUtils(com.commercetools.sync.producttypes.utils.ProductTypeTransformUtils) AttributeDefinitionDraftBuilder(io.sphere.sdk.products.attributes.AttributeDefinitionDraftBuilder) ProductTypeQuery(io.sphere.sdk.producttypes.queries.ProductTypeQuery) CaffeineReferenceIdToKeyCacheImpl(com.commercetools.sync.commons.utils.CaffeineReferenceIdToKeyCacheImpl) ProductTypeITUtils.populateProjectWithNestedAttributes(com.commercetools.sync.integration.commons.utils.ProductTypeITUtils.populateProjectWithNestedAttributes) ProductTypeDraftBuilder(io.sphere.sdk.producttypes.ProductTypeDraftBuilder) ProductTypeDraft(io.sphere.sdk.producttypes.ProductTypeDraft) Collectors(java.util.stream.Collectors) ProductTypeSyncOptions(com.commercetools.sync.producttypes.ProductTypeSyncOptions) Test(org.junit.jupiter.api.Test) NestedAttributeType(io.sphere.sdk.products.attributes.NestedAttributeType) List(java.util.List) LocalizedString.ofEnglish(io.sphere.sdk.models.LocalizedString.ofEnglish) ProductTypeSync(com.commercetools.sync.producttypes.ProductTypeSync) CTP_TARGET_CLIENT(com.commercetools.sync.integration.commons.utils.SphereClientUtils.CTP_TARGET_CLIENT) AttributeDefinitionDraft(io.sphere.sdk.products.attributes.AttributeDefinitionDraft) ProductTypeSyncStatistics(com.commercetools.sync.producttypes.helpers.ProductTypeSyncStatistics) CaffeineReferenceIdToKeyCacheImpl(com.commercetools.sync.commons.utils.CaffeineReferenceIdToKeyCacheImpl) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 12 with ReferenceIdToKeyCache

use of com.commercetools.sync.commons.utils.ReferenceIdToKeyCache in project commercetools-sync-java by commercetools.

the class StateSyncIT method sync_WithUpdatedTransitionAndClientThrowsError_ShouldAddErrorMessage.

@Test
void sync_WithUpdatedTransitionAndClientThrowsError_ShouldAddErrorMessage() {
    final StateDraft stateCDraft = createStateDraft(keyC);
    final State stateC = createStateInSource(stateCDraft);
    final StateDraft tagetStateCDraft = createStateDraft(keyC);
    final State targetStateC = createStateInTarget(tagetStateCDraft);
    final StateDraft stateBDraft = createStateDraft(keyB, stateC);
    final State stateB = createStateInSource(stateBDraft);
    final StateDraft tagetStateBDraft = createStateDraft(keyB, targetStateC);
    final State targetStateB = createStateInTarget(tagetStateBDraft);
    final StateDraft stateADraft = createStateDraft(keyA, stateB, stateC);
    final State stateA = createStateInSource(stateADraft);
    final StateDraft tagetStateADraft = createStateDraft(keyA, targetStateB);
    final State targetStateA = createStateInTarget(tagetStateADraft);
    Assertions.assertThat(targetStateB.getTransitions().size()).isEqualTo(1);
    Assertions.assertThat(targetStateA.getTransitions().size()).isEqualTo(1);
    final SphereClient spyClient = spy(CTP_TARGET_CLIENT);
    final StateUpdateCommand updateCommand = any(StateUpdateCommand.class);
    when(spyClient.execute(updateCommand)).thenReturn(exceptionallyCompletedFuture(new BadRequestException("a test exception"))).thenReturn(exceptionallyCompletedFuture(new ConcurrentModificationException())).thenCallRealMethod();
    final StateSyncOptions stateSyncOptions = StateSyncOptionsBuilder.of(spyClient).batchSize(3).errorCallback((exception, oldResource, newResource, updateActions) -> {
        errorCallBackMessages.add(exception.getMessage());
        errorCallBackExceptions.add(exception.getCause());
    }).warningCallback((exception, newResource, oldResource) -> warningCallBackMessages.add(exception.getMessage())).build();
    final StateSync stateSync = new StateSync(stateSyncOptions);
    final List<StateDraft> stateDrafts = StateTransformUtils.toStateDrafts(CTP_SOURCE_CLIENT, referenceIdToKeyCache, Arrays.asList(stateA, stateB, stateC)).join();
    // test
    final StateSyncStatistics stateSyncStatistics = stateSync.sync(stateDrafts).toCompletableFuture().join();
    assertThat(stateSyncStatistics).hasValues(3, 0, 0, 1, 0);
    Assertions.assertThat(errorCallBackExceptions).isNotEmpty();
    Assertions.assertThat(errorCallBackMessages).isNotEmpty();
    Assertions.assertThat(errorCallBackMessages.get(0)).contains(" detailMessage: a test exception");
    Assertions.assertThat(warningCallBackMessages).isEmpty();
}
Also used : StateUpdateCommand(io.sphere.sdk.states.commands.StateUpdateCommand) CustomObjectQuery(io.sphere.sdk.customobjects.queries.CustomObjectQuery) BeforeEach(org.junit.jupiter.api.BeforeEach) StateSyncStatistics(com.commercetools.sync.states.helpers.StateSyncStatistics) Arrays(java.util.Arrays) Reference(io.sphere.sdk.models.Reference) CTP_SOURCE_CLIENT(com.commercetools.sync.integration.commons.utils.SphereClientUtils.CTP_SOURCE_CLIENT) CompletableFuture.completedFuture(java.util.concurrent.CompletableFuture.completedFuture) Collections.singletonList(java.util.Collections.singletonList) AfterAll(org.junit.jupiter.api.AfterAll) ReferenceIdToKeyCache(com.commercetools.sync.commons.utils.ReferenceIdToKeyCache) StateTransformUtils(com.commercetools.sync.states.utils.StateTransformUtils) StateCreateCommand(io.sphere.sdk.states.commands.StateCreateCommand) Arrays.asList(java.util.Arrays.asList) StateITUtils.getStateByKey(com.commercetools.sync.integration.commons.utils.StateITUtils.getStateByKey) SphereClient(io.sphere.sdk.client.SphereClient) CompletableFutureUtils.exceptionallyCompletedFuture(io.sphere.sdk.utils.CompletableFutureUtils.exceptionallyCompletedFuture) StateType(io.sphere.sdk.states.StateType) Assertions(org.assertj.core.api.Assertions) UnresolvedReferencesServiceImpl(com.commercetools.sync.services.impl.UnresolvedReferencesServiceImpl) BadGatewayException(io.sphere.sdk.client.BadGatewayException) ThreadLocalRandom.current(java.util.concurrent.ThreadLocalRandom.current) CompletionStageUtil.executeBlocking(com.commercetools.tests.utils.CompletionStageUtil.executeBlocking) ResourceKeyIdGraphQlRequest(com.commercetools.sync.commons.helpers.ResourceKeyIdGraphQlRequest) StateUpdateCommand(io.sphere.sdk.states.commands.StateUpdateCommand) Set(java.util.Set) StateServiceImpl(com.commercetools.sync.services.impl.StateServiceImpl) State(io.sphere.sdk.states.State) Collectors(java.util.stream.Collectors) String.format(java.lang.String.format) StateITUtils.deleteStatesFromTargetAndSource(com.commercetools.sync.integration.commons.utils.StateITUtils.deleteStatesFromTargetAndSource) Test(org.junit.jupiter.api.Test) LocalizedString(io.sphere.sdk.models.LocalizedString) List(java.util.List) CUSTOM_OBJECT_TRANSITION_CONTAINER_KEY(com.commercetools.sync.services.impl.UnresolvedReferencesServiceImpl.CUSTOM_OBJECT_TRANSITION_CONTAINER_KEY) LocalizedString.ofEnglish(io.sphere.sdk.models.LocalizedString.ofEnglish) CompletionStage(java.util.concurrent.CompletionStage) SphereInternalUtils.asSet(io.sphere.sdk.utils.SphereInternalUtils.asSet) Optional(java.util.Optional) StateDraft(io.sphere.sdk.states.StateDraft) StateITUtils.deleteStates(com.commercetools.sync.integration.commons.utils.StateITUtils.deleteStates) CTP_TARGET_CLIENT(com.commercetools.sync.integration.commons.utils.SphereClientUtils.CTP_TARGET_CLIENT) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) IntStream(java.util.stream.IntStream) StateQuery(io.sphere.sdk.states.queries.StateQuery) BadRequestException(io.sphere.sdk.client.BadRequestException) AssertionsForStatistics.assertThat(com.commercetools.sync.commons.asserts.statistics.AssertionsForStatistics.assertThat) Mockito.spy(org.mockito.Mockito.spy) Function(java.util.function.Function) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) State.referenceOfId(io.sphere.sdk.states.State.referenceOfId) StateReferenceResolver(com.commercetools.sync.states.helpers.StateReferenceResolver) UnresolvedReferencesService(com.commercetools.sync.services.UnresolvedReferencesService) StateRole(io.sphere.sdk.states.StateRole) Nonnull(javax.annotation.Nonnull) StateDraftBuilder(io.sphere.sdk.states.StateDraftBuilder) StateQueryBuilder(io.sphere.sdk.states.queries.StateQueryBuilder) StateSyncOptionsBuilder(com.commercetools.sync.states.StateSyncOptionsBuilder) CaffeineReferenceIdToKeyCacheImpl(com.commercetools.sync.commons.utils.CaffeineReferenceIdToKeyCacheImpl) StateSync(com.commercetools.sync.states.StateSync) Mockito.when(org.mockito.Mockito.when) StateSyncOptions(com.commercetools.sync.states.StateSyncOptions) CtpQueryUtils(com.commercetools.sync.commons.utils.CtpQueryUtils) WaitingToBeResolvedTransitions(com.commercetools.sync.commons.models.WaitingToBeResolvedTransitions) PagedQueryResult(io.sphere.sdk.queries.PagedQueryResult) ConcurrentModificationException(io.sphere.sdk.client.ConcurrentModificationException) Collections(java.util.Collections) StateSync(com.commercetools.sync.states.StateSync) ConcurrentModificationException(io.sphere.sdk.client.ConcurrentModificationException) StateDraft(io.sphere.sdk.states.StateDraft) State(io.sphere.sdk.states.State) StateSyncStatistics(com.commercetools.sync.states.helpers.StateSyncStatistics) SphereClient(io.sphere.sdk.client.SphereClient) BadRequestException(io.sphere.sdk.client.BadRequestException) StateSyncOptions(com.commercetools.sync.states.StateSyncOptions) Test(org.junit.jupiter.api.Test)

Example 13 with ReferenceIdToKeyCache

use of com.commercetools.sync.commons.utils.ReferenceIdToKeyCache in project commercetools-sync-java by commercetools.

the class StateSyncIT method sync_WithFailureInKeysToIdCreation_ShouldAddErrorMessage.

@Test
void sync_WithFailureInKeysToIdCreation_ShouldAddErrorMessage() {
    final StateDraft stateCDraft = createStateDraft(keyC);
    final State stateC = createStateInSource(stateCDraft);
    final StateDraft tagetStateCDraft = createStateDraft(keyC);
    final State targetStateC = createStateInTarget(tagetStateCDraft);
    final StateDraft stateBDraft = createStateDraft(keyB, stateC);
    final State stateB = createStateInSource(stateBDraft);
    final StateDraft tagetStateBDraft = createStateDraft(keyB, targetStateC);
    final State targetStateB = createStateInTarget(tagetStateBDraft);
    final StateDraft stateADraft = createStateDraft(keyA, stateB, stateC);
    final State stateA = createStateInSource(stateADraft);
    final StateDraft tagetStateADraft = createStateDraft(keyA, targetStateB);
    final State targetStateA = createStateInTarget(tagetStateADraft);
    Assertions.assertThat(targetStateB.getTransitions().size()).isEqualTo(1);
    Assertions.assertThat(targetStateA.getTransitions().size()).isEqualTo(1);
    final SphereClient spyClient = spy(CTP_TARGET_CLIENT);
    when(spyClient.execute(any(ResourceKeyIdGraphQlRequest.class))).thenReturn(exceptionallyCompletedFuture(new BadRequestException("a test exception"))).thenReturn(exceptionallyCompletedFuture(new ConcurrentModificationException())).thenCallRealMethod();
    final StateSyncOptions stateSyncOptions = StateSyncOptionsBuilder.of(spyClient).batchSize(3).errorCallback((exception, oldResource, newResource, updateActions) -> {
        errorCallBackMessages.add(exception.getMessage());
        errorCallBackExceptions.add(exception.getCause());
    }).warningCallback((exception, newResource, oldResource) -> warningCallBackMessages.add(exception.getMessage())).build();
    final List<StateDraft> stateDrafts = StateTransformUtils.toStateDrafts(CTP_SOURCE_CLIENT, referenceIdToKeyCache, Arrays.asList(stateA, stateB, stateC)).join();
    // test
    final StateSyncStatistics stateSyncStatistics = new StateSync(stateSyncOptions).sync(stateDrafts).toCompletableFuture().join();
    assertThat(stateSyncStatistics).hasValues(3, 0, 0, 3, 0);
    Assertions.assertThat(errorCallBackExceptions).isNotEmpty();
    Assertions.assertThat(errorCallBackMessages).isNotEmpty();
    Assertions.assertThat(errorCallBackMessages.get(0)).isEqualTo("Failed to build a cache of keys to ids.");
    Assertions.assertThat(warningCallBackMessages).isEmpty();
}
Also used : CustomObjectQuery(io.sphere.sdk.customobjects.queries.CustomObjectQuery) BeforeEach(org.junit.jupiter.api.BeforeEach) StateSyncStatistics(com.commercetools.sync.states.helpers.StateSyncStatistics) Arrays(java.util.Arrays) Reference(io.sphere.sdk.models.Reference) CTP_SOURCE_CLIENT(com.commercetools.sync.integration.commons.utils.SphereClientUtils.CTP_SOURCE_CLIENT) CompletableFuture.completedFuture(java.util.concurrent.CompletableFuture.completedFuture) Collections.singletonList(java.util.Collections.singletonList) AfterAll(org.junit.jupiter.api.AfterAll) ReferenceIdToKeyCache(com.commercetools.sync.commons.utils.ReferenceIdToKeyCache) StateTransformUtils(com.commercetools.sync.states.utils.StateTransformUtils) StateCreateCommand(io.sphere.sdk.states.commands.StateCreateCommand) Arrays.asList(java.util.Arrays.asList) StateITUtils.getStateByKey(com.commercetools.sync.integration.commons.utils.StateITUtils.getStateByKey) SphereClient(io.sphere.sdk.client.SphereClient) CompletableFutureUtils.exceptionallyCompletedFuture(io.sphere.sdk.utils.CompletableFutureUtils.exceptionallyCompletedFuture) StateType(io.sphere.sdk.states.StateType) Assertions(org.assertj.core.api.Assertions) UnresolvedReferencesServiceImpl(com.commercetools.sync.services.impl.UnresolvedReferencesServiceImpl) BadGatewayException(io.sphere.sdk.client.BadGatewayException) ThreadLocalRandom.current(java.util.concurrent.ThreadLocalRandom.current) CompletionStageUtil.executeBlocking(com.commercetools.tests.utils.CompletionStageUtil.executeBlocking) ResourceKeyIdGraphQlRequest(com.commercetools.sync.commons.helpers.ResourceKeyIdGraphQlRequest) StateUpdateCommand(io.sphere.sdk.states.commands.StateUpdateCommand) Set(java.util.Set) StateServiceImpl(com.commercetools.sync.services.impl.StateServiceImpl) State(io.sphere.sdk.states.State) Collectors(java.util.stream.Collectors) String.format(java.lang.String.format) StateITUtils.deleteStatesFromTargetAndSource(com.commercetools.sync.integration.commons.utils.StateITUtils.deleteStatesFromTargetAndSource) Test(org.junit.jupiter.api.Test) LocalizedString(io.sphere.sdk.models.LocalizedString) List(java.util.List) CUSTOM_OBJECT_TRANSITION_CONTAINER_KEY(com.commercetools.sync.services.impl.UnresolvedReferencesServiceImpl.CUSTOM_OBJECT_TRANSITION_CONTAINER_KEY) LocalizedString.ofEnglish(io.sphere.sdk.models.LocalizedString.ofEnglish) CompletionStage(java.util.concurrent.CompletionStage) SphereInternalUtils.asSet(io.sphere.sdk.utils.SphereInternalUtils.asSet) Optional(java.util.Optional) StateDraft(io.sphere.sdk.states.StateDraft) StateITUtils.deleteStates(com.commercetools.sync.integration.commons.utils.StateITUtils.deleteStates) CTP_TARGET_CLIENT(com.commercetools.sync.integration.commons.utils.SphereClientUtils.CTP_TARGET_CLIENT) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) IntStream(java.util.stream.IntStream) StateQuery(io.sphere.sdk.states.queries.StateQuery) BadRequestException(io.sphere.sdk.client.BadRequestException) AssertionsForStatistics.assertThat(com.commercetools.sync.commons.asserts.statistics.AssertionsForStatistics.assertThat) Mockito.spy(org.mockito.Mockito.spy) Function(java.util.function.Function) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) State.referenceOfId(io.sphere.sdk.states.State.referenceOfId) StateReferenceResolver(com.commercetools.sync.states.helpers.StateReferenceResolver) UnresolvedReferencesService(com.commercetools.sync.services.UnresolvedReferencesService) StateRole(io.sphere.sdk.states.StateRole) Nonnull(javax.annotation.Nonnull) StateDraftBuilder(io.sphere.sdk.states.StateDraftBuilder) StateQueryBuilder(io.sphere.sdk.states.queries.StateQueryBuilder) StateSyncOptionsBuilder(com.commercetools.sync.states.StateSyncOptionsBuilder) CaffeineReferenceIdToKeyCacheImpl(com.commercetools.sync.commons.utils.CaffeineReferenceIdToKeyCacheImpl) StateSync(com.commercetools.sync.states.StateSync) Mockito.when(org.mockito.Mockito.when) StateSyncOptions(com.commercetools.sync.states.StateSyncOptions) CtpQueryUtils(com.commercetools.sync.commons.utils.CtpQueryUtils) WaitingToBeResolvedTransitions(com.commercetools.sync.commons.models.WaitingToBeResolvedTransitions) PagedQueryResult(io.sphere.sdk.queries.PagedQueryResult) ConcurrentModificationException(io.sphere.sdk.client.ConcurrentModificationException) Collections(java.util.Collections) StateSync(com.commercetools.sync.states.StateSync) ConcurrentModificationException(io.sphere.sdk.client.ConcurrentModificationException) StateDraft(io.sphere.sdk.states.StateDraft) State(io.sphere.sdk.states.State) StateSyncStatistics(com.commercetools.sync.states.helpers.StateSyncStatistics) SphereClient(io.sphere.sdk.client.SphereClient) ResourceKeyIdGraphQlRequest(com.commercetools.sync.commons.helpers.ResourceKeyIdGraphQlRequest) BadRequestException(io.sphere.sdk.client.BadRequestException) StateSyncOptions(com.commercetools.sync.states.StateSyncOptions) Test(org.junit.jupiter.api.Test)

Example 14 with ReferenceIdToKeyCache

use of com.commercetools.sync.commons.utils.ReferenceIdToKeyCache in project commercetools-sync-java by commercetools.

the class CartDiscountTransformServiceImplTest method transform_CartDiscountReferences_ShouldResolveReferencesUsingCacheAndMapToCartDiscountDraft.

@Test
void transform_CartDiscountReferences_ShouldResolveReferencesUsingCacheAndMapToCartDiscountDraft() {
    // preparation
    final SphereClient sourceClient = mock(SphereClient.class);
    final ReferenceIdToKeyCache referenceIdToKeyCache = new CaffeineReferenceIdToKeyCacheImpl();
    final CartDiscountTransformService cartDiscountTransformService = new CartDiscountTransformServiceImpl(sourceClient, referenceIdToKeyCache);
    final String cartDiscountKey = "cartDiscountKey";
    final String customTypeId = UUID.randomUUID().toString();
    final String customTypeKey = "customTypeKey";
    final List<CartDiscount> mockCartDiscountsPage = new ArrayList<>();
    for (int i = 0; i < 10; i++) {
        final CartDiscount mockCartDiscount = mock(CartDiscount.class);
        final CustomFields mockCustomFields = mock(CustomFields.class);
        final Reference<Type> typeReference = Reference.ofResourceTypeIdAndId("resourceTypeId", customTypeId);
        when(mockCustomFields.getType()).thenReturn(typeReference);
        when(mockCartDiscount.getCustom()).thenReturn(mockCustomFields);
        when(mockCartDiscount.getKey()).thenReturn(cartDiscountKey);
        mockCartDiscountsPage.add(mockCartDiscount);
    }
    final String jsonStringCustomTypes = "{\"results\":[{\"id\":\"" + customTypeId + "\"," + "\"key\":\"" + customTypeKey + "\"}]}";
    final ResourceKeyIdGraphQlResult customTypesResult = SphereJsonUtils.readObject(jsonStringCustomTypes, ResourceKeyIdGraphQlResult.class);
    when(sourceClient.execute(any(ResourceIdsGraphQlRequest.class))).thenReturn(CompletableFuture.completedFuture(customTypesResult));
    // test
    final List<CartDiscountDraft> cartDiscountsResolved = cartDiscountTransformService.toCartDiscountDrafts(mockCartDiscountsPage).toCompletableFuture().join();
    // assertions
    final Optional<CartDiscountDraft> cartDiscountKey1 = cartDiscountsResolved.stream().filter(cartDiscountDraft -> cartDiscountKey.equals(cartDiscountDraft.getKey())).findFirst();
    assertThat(cartDiscountKey1).hasValueSatisfying(cartDiscountDraft -> assertThat(cartDiscountDraft.getCustom().getType().getKey()).isEqualTo(customTypeKey));
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) ResourceIdsGraphQlRequest(com.commercetools.sync.commons.models.ResourceIdsGraphQlRequest) CustomFields(io.sphere.sdk.types.CustomFields) CaffeineReferenceIdToKeyCacheImpl(com.commercetools.sync.commons.utils.CaffeineReferenceIdToKeyCacheImpl) Reference(io.sphere.sdk.models.Reference) CartDiscount(io.sphere.sdk.cartdiscounts.CartDiscount) ResourceKeyIdGraphQlResult(com.commercetools.sync.commons.models.ResourceKeyIdGraphQlResult) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) SphereJsonUtils(io.sphere.sdk.json.SphereJsonUtils) CompletableFuture(java.util.concurrent.CompletableFuture) Mockito.when(org.mockito.Mockito.when) UUID(java.util.UUID) ArrayList(java.util.ArrayList) Test(org.junit.jupiter.api.Test) List(java.util.List) ReferenceIdToKeyCache(com.commercetools.sync.commons.utils.ReferenceIdToKeyCache) CartDiscountTransformService(com.commercetools.sync.cartdiscounts.service.CartDiscountTransformService) SphereClient(io.sphere.sdk.client.SphereClient) CartDiscountDraft(io.sphere.sdk.cartdiscounts.CartDiscountDraft) Optional(java.util.Optional) Mockito.mock(org.mockito.Mockito.mock) Type(io.sphere.sdk.types.Type) ReferenceIdToKeyCache(com.commercetools.sync.commons.utils.ReferenceIdToKeyCache) CartDiscountDraft(io.sphere.sdk.cartdiscounts.CartDiscountDraft) ArrayList(java.util.ArrayList) CartDiscountTransformService(com.commercetools.sync.cartdiscounts.service.CartDiscountTransformService) ResourceIdsGraphQlRequest(com.commercetools.sync.commons.models.ResourceIdsGraphQlRequest) CaffeineReferenceIdToKeyCacheImpl(com.commercetools.sync.commons.utils.CaffeineReferenceIdToKeyCacheImpl) CustomFields(io.sphere.sdk.types.CustomFields) Type(io.sphere.sdk.types.Type) SphereClient(io.sphere.sdk.client.SphereClient) ResourceKeyIdGraphQlResult(com.commercetools.sync.commons.models.ResourceKeyIdGraphQlResult) CartDiscount(io.sphere.sdk.cartdiscounts.CartDiscount) Test(org.junit.jupiter.api.Test)

Example 15 with ReferenceIdToKeyCache

use of com.commercetools.sync.commons.utils.ReferenceIdToKeyCache in project commercetools-sync-java by commercetools.

the class ProductTransformServiceImplTest method transform_WithAttributeReferences_ShouldReplaceAttributeReferenceIdsWithKeys.

@Test
void transform_WithAttributeReferences_ShouldReplaceAttributeReferenceIdsWithKeys() {
    // preparation
    final SphereClient sourceClient = mock(SphereClient.class);
    final ProductTransformService productTransformService = new ProductTransformServiceImpl(sourceClient, referenceIdToKeyCache);
    final List<ProductProjection> productPage = asList(readObjectFromResource("product-key-4.json", Product.class).toProjection(STAGED));
    String jsonStringProducts = "{\"results\":[{\"id\":\"53c4a8b4-754f-4b95-b6f2-3e1e70e3d0d2\",\"key\":\"prod1\"}," + "{\"id\":\"53c4a8b4-754f-4b95-b6f2-3e1e70e3d0d6\",\"key\":\"prod2\"}]}";
    final ResourceKeyIdGraphQlResult productsResult = SphereJsonUtils.readObject(jsonStringProducts, ResourceKeyIdGraphQlResult.class);
    String jsonStringProductTypes = "{\"results\":[{\"id\":\"53c4a8b4-754f-4b95-b6f2-3e1e70e3d0d3\"," + "\"key\":\"prodType1\"}]}";
    final ResourceKeyIdGraphQlResult productTypesResult = SphereJsonUtils.readObject(jsonStringProductTypes, ResourceKeyIdGraphQlResult.class);
    String jsonStringCategories = "{\"results\":[{\"id\":\"53c4a8b4-754f-4b95-b6f2-3e1e70e3d0d4\",\"key\":\"cat1\"}," + "{\"id\":\"53c4a8b4-754f-4b95-b6f2-3e1e70e3d0d5\",\"key\":\"cat2\"}]}";
    final ResourceKeyIdGraphQlResult categoriesResult = SphereJsonUtils.readObject(jsonStringCategories, ResourceKeyIdGraphQlResult.class);
    when(sourceClient.execute(any(ResourceIdsGraphQlRequest.class))).thenReturn(CompletableFuture.completedFuture(productsResult)).thenReturn(CompletableFuture.completedFuture(productTypesResult)).thenReturn(CompletableFuture.completedFuture(categoriesResult));
    // test
    final List<ProductDraft> productsResolved = productTransformService.toProductDrafts(productPage).toCompletableFuture().join();
    // assertions
    final Optional<ProductDraft> productKey1 = productsResolved.stream().filter(productDraft -> "productKey4".equals(productDraft.getKey())).findFirst();
    assertThat(productKey1).hasValueSatisfying(product -> assertThat(product.getMasterVariant().getAttributes()).anySatisfy(attribute -> {
        assertThat(attribute.getName()).isEqualTo("productReference");
        final JsonNode referenceSet = attribute.getValue();
        assertThat(referenceSet).anySatisfy(reference -> assertThat(reference.get("id").asText()).isEqualTo("prod1"));
        assertThat(referenceSet).anySatisfy(reference -> assertThat(reference.get("id").asText()).isEqualTo("prod2"));
    }));
    assertThat(productKey1).hasValueSatisfying(product -> assertThat(product.getMasterVariant().getAttributes()).anySatisfy(attribute -> {
        assertThat(attribute.getName()).isEqualTo("categoryReference");
        final JsonNode referenceSet = attribute.getValue();
        assertThat(referenceSet).anySatisfy(reference -> assertThat(reference.get("id").asText()).isEqualTo("cat1"));
        assertThat(referenceSet).anySatisfy(reference -> assertThat(reference.get("id").asText()).isEqualTo("cat2"));
    }));
    assertThat(productKey1).hasValueSatisfying(product -> assertThat(product.getMasterVariant().getAttributes()).anySatisfy(attribute -> {
        assertThat(attribute.getName()).isEqualTo("productTypeReference");
        assertThat(attribute.getValue().get("id").asText()).isEqualTo("prodType1");
    }));
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) CustomObjectQuery(io.sphere.sdk.customobjects.queries.CustomObjectQuery) SphereJsonUtils.readObjectFromResource(io.sphere.sdk.json.SphereJsonUtils.readObjectFromResource) STAGED(io.sphere.sdk.products.ProductProjectionType.STAGED) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) CustomObject(io.sphere.sdk.customobjects.CustomObject) SphereJsonUtils(io.sphere.sdk.json.SphereJsonUtils) KEY_IS_NOT_SET_PLACE_HOLDER(com.commercetools.sync.services.impl.BaseTransformServiceImpl.KEY_IS_NOT_SET_PLACE_HOLDER) CompletableFuture(java.util.concurrent.CompletableFuture) CompletableFutureUtils(io.sphere.sdk.utils.CompletableFutureUtils) Collections.singletonList(java.util.Collections.singletonList) ReferenceIdToKeyCache(com.commercetools.sync.commons.utils.ReferenceIdToKeyCache) Arrays.asList(java.util.Arrays.asList) SphereClient(io.sphere.sdk.client.SphereClient) JsonNode(com.fasterxml.jackson.databind.JsonNode) ProductTransformService(com.commercetools.sync.products.service.ProductTransformService) ProductDraft(io.sphere.sdk.products.ProductDraft) ProductProjection(io.sphere.sdk.products.ProductProjection) ResourceIdsGraphQlRequest(com.commercetools.sync.commons.models.ResourceIdsGraphQlRequest) BadGatewayException(io.sphere.sdk.client.BadGatewayException) CaffeineReferenceIdToKeyCacheImpl(com.commercetools.sync.commons.utils.CaffeineReferenceIdToKeyCacheImpl) ResourceKeyIdGraphQlResult(com.commercetools.sync.commons.models.ResourceKeyIdGraphQlResult) Mockito.times(org.mockito.Mockito.times) Mockito.when(org.mockito.Mockito.when) Product(io.sphere.sdk.products.Product) Mockito.verify(org.mockito.Mockito.verify) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) List(java.util.List) AfterEach(org.junit.jupiter.api.AfterEach) CompletionStage(java.util.concurrent.CompletionStage) PagedQueryResult(io.sphere.sdk.queries.PagedQueryResult) Optional(java.util.Optional) Mockito.mock(org.mockito.Mockito.mock) ReferenceTransformException(com.commercetools.sync.commons.exceptions.ReferenceTransformException) ProductTransformService(com.commercetools.sync.products.service.ProductTransformService) JsonNode(com.fasterxml.jackson.databind.JsonNode) ResourceIdsGraphQlRequest(com.commercetools.sync.commons.models.ResourceIdsGraphQlRequest) ProductProjection(io.sphere.sdk.products.ProductProjection) ProductDraft(io.sphere.sdk.products.ProductDraft) SphereClient(io.sphere.sdk.client.SphereClient) ResourceKeyIdGraphQlResult(com.commercetools.sync.commons.models.ResourceKeyIdGraphQlResult) Test(org.junit.jupiter.api.Test)

Aggregations

CaffeineReferenceIdToKeyCacheImpl (com.commercetools.sync.commons.utils.CaffeineReferenceIdToKeyCacheImpl)35 ReferenceIdToKeyCache (com.commercetools.sync.commons.utils.ReferenceIdToKeyCache)35 Test (org.junit.jupiter.api.Test)35 List (java.util.List)34 ArrayList (java.util.ArrayList)26 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)26 BeforeEach (org.junit.jupiter.api.BeforeEach)24 CTP_SOURCE_CLIENT (com.commercetools.sync.integration.commons.utils.SphereClientUtils.CTP_SOURCE_CLIENT)22 CTP_TARGET_CLIENT (com.commercetools.sync.integration.commons.utils.SphereClientUtils.CTP_TARGET_CLIENT)22 SphereClient (io.sphere.sdk.client.SphereClient)22 AfterAll (org.junit.jupiter.api.AfterAll)21 AssertionsForStatistics.assertThat (com.commercetools.sync.commons.asserts.statistics.AssertionsForStatistics.assertThat)20 Collectors (java.util.stream.Collectors)20 ArgumentMatchers.any (org.mockito.ArgumentMatchers.any)20 Mockito.when (org.mockito.Mockito.when)20 Arrays.asList (java.util.Arrays.asList)19 Collections.singletonList (java.util.Collections.singletonList)18 Collections (java.util.Collections)17 Optional (java.util.Optional)17 CompletionStage (java.util.concurrent.CompletionStage)17