Search in sources :

Example 1 with ResourceKeyIdGraphQlResult

use of com.commercetools.sync.commons.models.ResourceKeyIdGraphQlResult in project commercetools-project-sync by commercetools.

the class SyncerFactoryTest method sync_AsProductsFullSyncWithExceptionDuringAttributeReferenceReplacement_ShouldContinueWithPages.

@Test
void sync_AsProductsFullSyncWithExceptionDuringAttributeReferenceReplacement_ShouldContinueWithPages() {
    // preparation
    final SphereClient sourceClient = mock(SphereClient.class);
    when(sourceClient.getConfig()).thenReturn(SphereClientConfig.of("foo", "foo", "foo"));
    final SphereClient targetClient = mock(SphereClient.class);
    when(targetClient.getConfig()).thenReturn(SphereClientConfig.of("bar", "bar", "bar"));
    final ProductProjection product1 = SphereJsonUtils.readObjectFromResource("product-key-7.json", Product.class).toProjection(STAGED);
    final ProductProjection product2 = SphereJsonUtils.readObjectFromResource("product-key-8.json", Product.class).toProjection(STAGED);
    final ProductProjection product3 = SphereJsonUtils.readObjectFromResource("product-key-9.json", Product.class).toProjection(STAGED);
    final List<ProductProjection> fullPageOfProducts = IntStream.range(0, 500).mapToObj(o -> product1).collect(Collectors.toList());
    when(sourceClient.execute(any(ProductProjectionQuery.class))).thenReturn(CompletableFuture.completedFuture(MockPagedQueryResult.of(fullPageOfProducts))).thenReturn(CompletableFuture.completedFuture(MockPagedQueryResult.of(asList(product3, product2))));
    when(targetClient.execute(any(ProductProjectionQuery.class))).thenReturn(CompletableFuture.completedFuture(MockPagedQueryResult.of(emptyList())));
    when(targetClient.execute(any(ProductTypeQuery.class))).thenReturn(CompletableFuture.completedFuture(MockPagedQueryResult.of(emptyList())));
    when(targetClient.execute(any(CategoryQuery.class))).thenReturn(CompletableFuture.completedFuture(MockPagedQueryResult.of(emptyList())));
    when(targetClient.execute(any(TaxCategoryQuery.class))).thenReturn(CompletableFuture.completedFuture(MockPagedQueryResult.of(emptyList())));
    when(targetClient.execute(any(StateQuery.class))).thenReturn(CompletableFuture.completedFuture(MockPagedQueryResult.of(emptyList())));
    when(targetClient.execute(any(CustomObjectQuery.class))).thenReturn(CompletableFuture.completedFuture(MockPagedQueryResult.of(emptyList())));
    final Product product4 = SphereJsonUtils.readObjectFromResource("product-key-8.json", Product.class);
    when(targetClient.execute(any(ProductCreateCommand.class))).thenReturn(CompletableFuture.completedFuture(product4));
    String jsonAsString = "{\"results\":[{\"id\":\"53c4a8b4-865f-4b95-b6f2-3e1e70e3d0c1\",\"key\":\"productKey3\"}]}";
    final ResourceKeyIdGraphQlResult productsResult = SphereJsonUtils.readObject(jsonAsString, ResourceKeyIdGraphQlResult.class);
    String jsonStringProductTypes = "{\"results\":[{\"id\":\"53c4a8b4-865f-4b95-b6f2-3e1e70e3d0c2\",\"key\":\"prodType1\"}]}";
    final ResourceKeyIdGraphQlResult productTypesResult = SphereJsonUtils.readObject(jsonStringProductTypes, ResourceKeyIdGraphQlResult.class);
    String jsonStringCategories = "{\"results\":[{\"id\":\"53c4a8b4-865f-4b95-b6f2-3e1e70e3d0c3\",\"key\":\"cat1\"}]}";
    final ResourceKeyIdGraphQlResult categoriesResult = SphereJsonUtils.readObject(jsonStringCategories, ResourceKeyIdGraphQlResult.class);
    final BadGatewayException badGatewayException = new BadGatewayException("Error!");
    when(sourceClient.execute(any(ResourceIdsGraphQlRequest.class))).thenReturn(CompletableFutureUtils.failed(badGatewayException)).thenReturn(CompletableFutureUtils.failed(badGatewayException)).thenReturn(CompletableFutureUtils.failed(badGatewayException)).thenReturn(CompletableFuture.completedFuture(productsResult)).thenReturn(CompletableFuture.completedFuture(categoriesResult)).thenReturn(CompletableFuture.completedFuture(productTypesResult));
    final ResourceKeyIdGraphQlResult resourceKeyIdGraphQlResult = mock(ResourceKeyIdGraphQlResult.class);
    when(resourceKeyIdGraphQlResult.getResults()).thenReturn(singleton(new ResourceKeyId("productKey3", "53c4a8b4-865f-4b95-b6f2-3e1e70e3d0c1")));
    when(targetClient.execute(any(ResourceKeyIdGraphQlRequest.class))).thenReturn(CompletableFuture.completedFuture(resourceKeyIdGraphQlResult));
    final SyncerFactory syncerFactory = SyncerFactory.of(() -> sourceClient, () -> targetClient, getMockedClock());
    // test
    syncerFactory.sync(new String[] { "products" }, "myRunnerName", true, false, null);
    // assertions
    verify(sourceClient, times(2)).execute(any(ProductProjectionQuery.class));
    verify(sourceClient, times(9)).execute(any(ResourceIdsGraphQlRequest.class));
    verifyInteractionsWithClientAfterSync(sourceClient, 1);
    final Condition<LoggingEvent> startLog = new Condition<>(loggingEvent -> Level.INFO.equals(loggingEvent.getLevel()) && loggingEvent.getMessage().contains("Starting ProductSync"), "start log");
    final Condition<LoggingEvent> statisticsLog = new Condition<>(loggingEvent -> Level.INFO.equals(loggingEvent.getLevel()) && loggingEvent.getMessage().contains("Summary: 2 product(s) were processed in total (2 created, 0 updated, " + "0 failed to sync and 0 product(s) with missing reference(s))."), "statistics log");
    assertThat(productSyncerTestLogger.getAllLoggingEvents()).hasSize(3).haveExactly(1, startLog).haveExactly(1, statisticsLog);
    assertThat(productSyncerTestLogger.getAllLoggingEvents()).anySatisfy(loggingEvent -> {
        assertThat(loggingEvent.getMessage()).contains(ReferenceTransformException.class.getCanonicalName() + ": Failed to replace referenced resource ids with keys on the attributes of the " + "products in the current fetched page from the source project. " + "This page will not be synced to the target project.");
        assertThat(loggingEvent.getThrowable().isPresent()).isTrue();
        assertThat(loggingEvent.getThrowable().get().getCause().getCause()).isEqualTo(badGatewayException);
    });
}
Also used : CustomObjectQuery(io.sphere.sdk.customobjects.queries.CustomObjectQuery) ProductProjectionQuery(io.sphere.sdk.products.queries.ProductProjectionQuery) BeforeEach(org.junit.jupiter.api.BeforeEach) STAGED(io.sphere.sdk.products.ProductProjectionType.STAGED) TestLoggerFactory(uk.org.lidalia.slf4jtest.TestLoggerFactory) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) ZonedDateTime(java.time.ZonedDateTime) DEFAULT_RUNNER_NAME(com.commercetools.project.sync.util.SyncUtils.DEFAULT_RUNNER_NAME) MockPagedQueryResult(com.commercetools.project.sync.util.MockPagedQueryResult) TestUtils.assertCategorySyncerLoggingEvents(com.commercetools.project.sync.util.TestUtils.assertCategorySyncerLoggingEvents) TestUtils.assertInventoryEntrySyncerLoggingEvents(com.commercetools.project.sync.util.TestUtils.assertInventoryEntrySyncerLoggingEvents) ShoppingListQuery(io.sphere.sdk.shoppinglists.queries.ShoppingListQuery) CartDiscountQuery(io.sphere.sdk.cartdiscounts.queries.CartDiscountQuery) CategoryQuery(io.sphere.sdk.categories.queries.CategoryQuery) CustomerQuery(io.sphere.sdk.customers.queries.CustomerQuery) Collections.singleton(java.util.Collections.singleton) ResourceKeyId(com.commercetools.sync.commons.models.ResourceKeyId) Arrays.asList(java.util.Arrays.asList) TestLogger(uk.org.lidalia.slf4jtest.TestLogger) TypeSyncer(com.commercetools.project.sync.type.TypeSyncer) Mockito.atLeast(org.mockito.Mockito.atLeast) SphereClient(io.sphere.sdk.client.SphereClient) ProductTypeSyncer(com.commercetools.project.sync.producttype.ProductTypeSyncer) ProductProjection(io.sphere.sdk.products.ProductProjection) SphereRequest(io.sphere.sdk.client.SphereRequest) BadGatewayException(io.sphere.sdk.client.BadGatewayException) ProductTypeQuery(io.sphere.sdk.producttypes.queries.ProductTypeQuery) TIMESTAMP_GENERATOR_KEY(com.commercetools.project.sync.service.impl.CustomObjectServiceImpl.TIMESTAMP_GENERATOR_KEY) TestUtils.assertProductSyncerLoggingEvents(com.commercetools.project.sync.util.TestUtils.assertProductSyncerLoggingEvents) ResourceKeyIdGraphQlRequest(com.commercetools.sync.commons.helpers.ResourceKeyIdGraphQlRequest) Collections.emptyList(java.util.Collections.emptyList) TestUtils.verifyInteractionsWithClientAfterSync(com.commercetools.project.sync.util.TestUtils.verifyInteractionsWithClientAfterSync) SyncUtils.getApplicationName(com.commercetools.project.sync.util.SyncUtils.getApplicationName) Product(io.sphere.sdk.products.Product) CategorySyncer(com.commercetools.project.sync.category.CategorySyncer) InventoryEntrySyncer(com.commercetools.project.sync.inventoryentry.InventoryEntrySyncer) Collectors(java.util.stream.Collectors) String.format(java.lang.String.format) CustomObjectUpsertCommand(io.sphere.sdk.customobjects.commands.CustomObjectUpsertCommand) TestUtils.assertTypeSyncerLoggingEvents(com.commercetools.project.sync.util.TestUtils.assertTypeSyncerLoggingEvents) Test(org.junit.jupiter.api.Test) List(java.util.List) ProductSyncStatistics(com.commercetools.sync.products.helpers.ProductSyncStatistics) CompletionStage(java.util.concurrent.CompletionStage) CartDiscountSyncer(com.commercetools.project.sync.cartdiscount.CartDiscountSyncer) StateSyncer(com.commercetools.project.sync.state.StateSyncer) ProductCreateCommand(io.sphere.sdk.products.commands.ProductCreateCommand) TestUtils.assertCartDiscountSyncerLoggingEvents(com.commercetools.project.sync.util.TestUtils.assertCartDiscountSyncerLoggingEvents) TestUtils.assertStateSyncerLoggingEvents(com.commercetools.project.sync.util.TestUtils.assertStateSyncerLoggingEvents) Mockito.mock(org.mockito.Mockito.mock) SYNC_MODULE_OPTION_DESCRIPTION(com.commercetools.project.sync.CliRunner.SYNC_MODULE_OPTION_DESCRIPTION) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) IntStream(java.util.stream.IntStream) TestUtils.stubClientsCustomObjectService(com.commercetools.project.sync.util.TestUtils.stubClientsCustomObjectService) CliException(com.commercetools.project.sync.exception.CliException) StateQuery(io.sphere.sdk.states.queries.StateQuery) Level(uk.org.lidalia.slf4jext.Level) CustomObject(io.sphere.sdk.customobjects.CustomObject) SphereJsonUtils(io.sphere.sdk.json.SphereJsonUtils) TaxCategoryQuery(io.sphere.sdk.taxcategories.queries.TaxCategoryQuery) CompletableFuture(java.util.concurrent.CompletableFuture) CustomerSyncer(com.commercetools.project.sync.customer.CustomerSyncer) CompletableFutureUtils(io.sphere.sdk.utils.CompletableFutureUtils) ArgumentCaptor(org.mockito.ArgumentCaptor) TestUtils.mockLastSyncCustomObject(com.commercetools.project.sync.util.TestUtils.mockLastSyncCustomObject) TestUtils.assertTaxCategorySyncerLoggingEvents(com.commercetools.project.sync.util.TestUtils.assertTaxCategorySyncerLoggingEvents) TypeQuery(io.sphere.sdk.types.queries.TypeQuery) InventoryEntryQuery(io.sphere.sdk.inventory.queries.InventoryEntryQuery) Nonnull(javax.annotation.Nonnull) LoggingEvent(uk.org.lidalia.slf4jtest.LoggingEvent) TestUtils.getMockedClock(com.commercetools.project.sync.util.TestUtils.getMockedClock) ResourceIdsGraphQlRequest(com.commercetools.sync.commons.models.ResourceIdsGraphQlRequest) TestUtils.assertProductTypeSyncerLoggingEvents(com.commercetools.project.sync.util.TestUtils.assertProductTypeSyncerLoggingEvents) CustomObjectSyncer(com.commercetools.project.sync.customobject.CustomObjectSyncer) InOrder(org.mockito.InOrder) TestUtils.assertCustomerSyncerLoggingEvents(com.commercetools.project.sync.util.TestUtils.assertCustomerSyncerLoggingEvents) CustomObjectDraft(io.sphere.sdk.customobjects.CustomObjectDraft) ResourceKeyIdGraphQlResult(com.commercetools.sync.commons.models.ResourceKeyIdGraphQlResult) QueryPredicate(io.sphere.sdk.queries.QueryPredicate) ProductSyncer(com.commercetools.project.sync.product.ProductSyncer) Mockito.times(org.mockito.Mockito.times) Mockito.when(org.mockito.Mockito.when) TestUtils.assertCustomObjectSyncerLoggingEvents(com.commercetools.project.sync.util.TestUtils.assertCustomObjectSyncerLoggingEvents) Mockito.verify(org.mockito.Mockito.verify) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Mockito(org.mockito.Mockito) ShoppingListSyncer(com.commercetools.project.sync.shoppinglist.ShoppingListSyncer) SphereClientConfig(io.sphere.sdk.client.SphereClientConfig) PagedQueryResult(io.sphere.sdk.queries.PagedQueryResult) LastSyncCustomObject(com.commercetools.project.sync.model.response.LastSyncCustomObject) Condition(org.assertj.core.api.Condition) TestUtils.assertShoppingListSyncerLoggingEvents(com.commercetools.project.sync.util.TestUtils.assertShoppingListSyncerLoggingEvents) TaxCategorySyncer(com.commercetools.project.sync.taxcategory.TaxCategorySyncer) ReferenceTransformException(com.commercetools.sync.commons.exceptions.ReferenceTransformException) Condition(org.assertj.core.api.Condition) CategoryQuery(io.sphere.sdk.categories.queries.CategoryQuery) TaxCategoryQuery(io.sphere.sdk.taxcategories.queries.TaxCategoryQuery) Product(io.sphere.sdk.products.Product) ResourceKeyIdGraphQlRequest(com.commercetools.sync.commons.helpers.ResourceKeyIdGraphQlRequest) StateQuery(io.sphere.sdk.states.queries.StateQuery) ResourceKeyId(com.commercetools.sync.commons.models.ResourceKeyId) ResourceIdsGraphQlRequest(com.commercetools.sync.commons.models.ResourceIdsGraphQlRequest) LoggingEvent(uk.org.lidalia.slf4jtest.LoggingEvent) ProductTypeQuery(io.sphere.sdk.producttypes.queries.ProductTypeQuery) ProductProjection(io.sphere.sdk.products.ProductProjection) ProductProjectionQuery(io.sphere.sdk.products.queries.ProductProjectionQuery) SphereClient(io.sphere.sdk.client.SphereClient) ResourceKeyIdGraphQlResult(com.commercetools.sync.commons.models.ResourceKeyIdGraphQlResult) BadGatewayException(io.sphere.sdk.client.BadGatewayException) TaxCategoryQuery(io.sphere.sdk.taxcategories.queries.TaxCategoryQuery) ProductCreateCommand(io.sphere.sdk.products.commands.ProductCreateCommand) CustomObjectQuery(io.sphere.sdk.customobjects.queries.CustomObjectQuery) Test(org.junit.jupiter.api.Test)

Example 2 with ResourceKeyIdGraphQlResult

use of com.commercetools.sync.commons.models.ResourceKeyIdGraphQlResult in project commercetools-project-sync by commercetools.

the class CategorySyncerTest method syncWithWarning_ShouldCallWarningCallback.

@Test
void syncWithWarning_ShouldCallWarningCallback() {
    // preparation: old category has category order hint,
    // new category does not have category order hint
    final SphereClient sourceClient = mock(SphereClient.class);
    final SphereClient targetClient = mock(SphereClient.class);
    when(sourceClient.getConfig()).thenReturn(SphereApiConfig.of("source-project"));
    when(targetClient.getConfig()).thenReturn(SphereApiConfig.of("target-project"));
    final List<Category> sourceCategories = Collections.singletonList(readObjectFromResource("category-key-2.json", Category.class));
    final List<Category> targetCategories = Collections.singletonList(readObjectFromResource("category-order-hint.json", Category.class));
    final PagedQueryResult<Category> sourcePagedQueryResult = mock(PagedQueryResult.class);
    when(sourcePagedQueryResult.getResults()).thenReturn(sourceCategories);
    when(sourceClient.execute(any(CategoryQuery.class))).thenReturn(CompletableFuture.completedFuture(sourcePagedQueryResult));
    final PagedQueryResult<Category> targetPagedQueryResult = mock(PagedQueryResult.class);
    when(targetPagedQueryResult.getResults()).thenReturn(targetCategories);
    when(targetClient.execute(any(CategoryQuery.class))).thenReturn(CompletableFuture.completedFuture(targetPagedQueryResult));
    when(targetPagedQueryResult.head()).thenReturn(Optional.of(targetCategories.get(0)));
    final ResourceKeyIdGraphQlResult resourceKeyIdGraphQlResult = mock(ResourceKeyIdGraphQlResult.class);
    when(resourceKeyIdGraphQlResult.getResults()).thenReturn(singleton(new ResourceKeyId("categoryKey2", "ba81a6da-cf83-435b-a89e-2afab579846f")));
    when(targetClient.execute(any(ResourceKeyIdGraphQlRequest.class))).thenReturn(CompletableFuture.completedFuture(resourceKeyIdGraphQlResult));
    // test
    final CategorySyncer categorySyncer = CategorySyncer.of(sourceClient, targetClient, mock(Clock.class));
    categorySyncer.sync(null, true).toCompletableFuture().join();
    // assertion
    final LoggingEvent errorLog = syncerTestLogger.getAllLoggingEvents().get(1);
    assertThat(errorLog.getMessage()).isEqualTo("Warning when trying to sync category. Existing key: categoryKey2");
    assertThat(errorLog.getThrowable().get().getMessage()).isEqualTo(format("Cannot unset 'orderHint' field of category with id '%s'.", sourceCategories.get(0).getId()));
}
Also used : LoggingEvent(uk.org.lidalia.slf4jtest.LoggingEvent) Category(io.sphere.sdk.categories.Category) SphereClient(io.sphere.sdk.client.SphereClient) CategoryQuery(io.sphere.sdk.categories.queries.CategoryQuery) ResourceKeyIdGraphQlResult(com.commercetools.sync.commons.models.ResourceKeyIdGraphQlResult) ResourceKeyIdGraphQlRequest(com.commercetools.sync.commons.helpers.ResourceKeyIdGraphQlRequest) TestUtils.getMockedClock(com.commercetools.project.sync.util.TestUtils.getMockedClock) Clock(java.time.Clock) ResourceKeyId(com.commercetools.sync.commons.models.ResourceKeyId) Test(org.junit.jupiter.api.Test)

Example 3 with ResourceKeyIdGraphQlResult

use of com.commercetools.sync.commons.models.ResourceKeyIdGraphQlResult in project commercetools-project-sync by commercetools.

the class CustomerSyncerTest method transform_ShouldReplaceCustomerReferenceIdsWithKeys.

@Test
void transform_ShouldReplaceCustomerReferenceIdsWithKeys() {
    // preparation
    final SphereClient sourceClient = mock(SphereClient.class);
    final CustomerSyncer customerSyncer = CustomerSyncer.of(sourceClient, mock(SphereClient.class), mock(Clock.class));
    final List<Customer> customers = Collections.singletonList(readObjectFromResource("customer-key-1.json", Customer.class));
    final String jsonStringCustomerGroups = "{\"results\":[{\"id\":\"d1229e6f-2b79-441e-b419-180311e52754\"," + "\"key\":\"customerGroupKey\"} ]}";
    final ResourceKeyIdGraphQlResult customerGroupsResult = SphereJsonUtils.readObject(jsonStringCustomerGroups, ResourceKeyIdGraphQlResult.class);
    when(sourceClient.execute(any(ResourceIdsGraphQlRequest.class))).thenReturn(CompletableFuture.completedFuture(customerGroupsResult));
    // test
    final CompletionStage<List<CustomerDraft>> draftsFromPageStage = customerSyncer.transform(customers);
    // assertion
    assertThat(draftsFromPageStage).isCompletedWithValue(toCustomerDrafts(sourceClient, referenceIdToKeyCache, customers).join());
}
Also used : Customer(io.sphere.sdk.customers.Customer) SphereClient(io.sphere.sdk.client.SphereClient) ResourceKeyIdGraphQlResult(com.commercetools.sync.commons.models.ResourceKeyIdGraphQlResult) List(java.util.List) Clock(java.time.Clock) ResourceIdsGraphQlRequest(com.commercetools.sync.commons.models.ResourceIdsGraphQlRequest) Test(org.junit.jupiter.api.Test)

Example 4 with ResourceKeyIdGraphQlResult

use of com.commercetools.sync.commons.models.ResourceKeyIdGraphQlResult in project commercetools-sync-java by commercetools.

the class ProductTypeTransformServiceImplTest method transform_ShouldReplaceProductTypeNestedAttributeReferenceIdsWithKeys.

@Test
void transform_ShouldReplaceProductTypeNestedAttributeReferenceIdsWithKeys() {
    // preparation
    final SphereClient sourceClient = mock(SphereClient.class);
    final ProductTypeTransformService productTypeTransformService = new ProductTypeTransformServiceImpl(sourceClient, referenceIdToKeyCache);
    final String referencedProductTypeId = UUID.randomUUID().toString();
    final String referencedProductTypeKey = "referencedProductTypeKey";
    final ProductType referencedProductType = mock(ProductType.class);
    when(referencedProductType.getKey()).thenReturn(referencedProductTypeKey);
    final Reference<ProductType> productTypeReference = spy(ProductType.reference(referencedProductType));
    when(productTypeReference.getId()).thenReturn(referencedProductTypeId);
    final AttributeDefinition nestedTypeAttr = AttributeDefinitionBuilder.of("nestedattr", ofEnglish("nestedattr"), SetAttributeType.of(NestedAttributeType.of(productTypeReference))).build();
    final ProductType productType = mock(ProductType.class);
    when(productType.getKey()).thenReturn("withNestedTypeAttr");
    when(productType.getAttributes()).thenReturn(singletonList(nestedTypeAttr));
    final List<ProductType> productTypes = singletonList(productType);
    String jsonStringProductTypes = "{\"results\":[{\"id\":\"" + referencedProductTypeId + "\"," + "\"key\":\"" + referencedProductTypeKey + "\"}]}";
    final ResourceKeyIdGraphQlResult productTypesResult = SphereJsonUtils.readObject(jsonStringProductTypes, ResourceKeyIdGraphQlResult.class);
    when(sourceClient.execute(any(ResourceIdsGraphQlRequest.class))).thenReturn(CompletableFuture.completedFuture(productTypesResult));
    // test
    final List<ProductTypeDraft> productTypeDrafts = productTypeTransformService.toProductTypeDrafts(productTypes).join();
    // assertion
    assertThat(productTypeDrafts).satisfies(productTypeDraft -> {
        final SetAttributeType setAttributeType = (SetAttributeType) productTypeDraft.get(0).getAttributes().get(0).getAttributeType();
        final NestedAttributeType nestedAttributeType = (NestedAttributeType) setAttributeType.getElementType();
        assertThat(nestedAttributeType.getTypeReference().getId()).isEqualTo(referencedProductType.getKey());
    });
}
Also used : ProductTypeTransformService(com.commercetools.sync.producttypes.service.ProductTypeTransformService) ProductType(io.sphere.sdk.producttypes.ProductType) AttributeDefinition(io.sphere.sdk.products.attributes.AttributeDefinition) NestedAttributeType(io.sphere.sdk.products.attributes.NestedAttributeType) ResourceIdsGraphQlRequest(com.commercetools.sync.commons.models.ResourceIdsGraphQlRequest) ProductTypeDraft(io.sphere.sdk.producttypes.ProductTypeDraft) SetAttributeType(io.sphere.sdk.products.attributes.SetAttributeType) SphereClient(io.sphere.sdk.client.SphereClient) ResourceKeyIdGraphQlResult(com.commercetools.sync.commons.models.ResourceKeyIdGraphQlResult) Test(org.junit.jupiter.api.Test)

Example 5 with ResourceKeyIdGraphQlResult

use of com.commercetools.sync.commons.models.ResourceKeyIdGraphQlResult in project commercetools-sync-java by commercetools.

the class CategorySyncTest method sync_WithFailOnFetchingCategories_ShouldTriggerErrorCallbackAndReturnProperStats.

@Test
void sync_WithFailOnFetchingCategories_ShouldTriggerErrorCallbackAndReturnProperStats() {
    // preparation
    final SphereClient mockClient = mock(SphereClient.class);
    final String categoryKey = "key";
    final Category mockCategory = getMockCategory("foo", categoryKey);
    ResourceKeyId resourceKeyId = new ResourceKeyId(categoryKey, "foo");
    @SuppressWarnings("unchecked") final ResourceKeyIdGraphQlResult resourceKeyIdGraphQlResult = mock(ResourceKeyIdGraphQlResult.class);
    when(resourceKeyIdGraphQlResult.getResults()).thenReturn(singleton(resourceKeyId));
    // successful caching
    when(mockClient.execute(any(ResourceKeyIdGraphQlRequest.class))).thenReturn(CompletableFuture.completedFuture(resourceKeyIdGraphQlResult));
    // exception on fetch.
    when(mockClient.execute(any(CategoryQuery.class))).thenReturn(supplyAsync(() -> {
        throw new SphereException();
    }));
    when(mockClient.execute(any(CategoryCreateCommand.class))).thenReturn(CompletableFuture.completedFuture(mockCategory));
    final CategorySyncOptions syncOptions = CategorySyncOptionsBuilder.of(mockClient).errorCallback((exception, oldResource, newResource, updateActions) -> {
        errorCallBackMessages.add(exception.getMessage());
        errorCallBackExceptions.add(exception.getCause());
    }).build();
    final CategoryService categoryServiceSpy = spy(new CategoryServiceImpl(syncOptions));
    final CategorySync mockCategorySync = new CategorySync(syncOptions, getMockTypeService(), categoryServiceSpy, mockUnresolvedReferencesService);
    final CategoryDraft categoryDraft = CategoryDraftBuilder.of(LocalizedString.of(Locale.ENGLISH, "name"), LocalizedString.of(Locale.ENGLISH, "name")).key(categoryKey).custom(CustomFieldsDraft.ofTypeKeyAndJson("customTypeId", new HashMap<>())).build();
    // test
    final CategorySyncStatistics syncStatistics = mockCategorySync.sync(singletonList(categoryDraft)).toCompletableFuture().join();
    // assertions
    assertThat(syncStatistics).hasValues(1, 0, 0, 1);
    assertThat(errorCallBackMessages).hasSize(1).singleElement(as(STRING)).contains("Failed to fetch existing categories");
    assertThat(errorCallBackExceptions).hasSize(1).singleElement(as(THROWABLE)).hasCauseExactlyInstanceOf(SphereException.class);
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) ReferenceResolutionException(com.commercetools.sync.commons.exceptions.ReferenceResolutionException) CompletableFuture.completedFuture(java.util.concurrent.CompletableFuture.completedFuture) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Collections.singletonList(java.util.Collections.singletonList) CategoryQuery(io.sphere.sdk.categories.queries.CategoryQuery) Collections.singleton(java.util.Collections.singleton) ResourceKeyId(com.commercetools.sync.commons.models.ResourceKeyId) Locale(java.util.Locale) Map(java.util.Map) THROWABLE(org.assertj.core.api.InstanceOfAssertFactories.THROWABLE) SphereClient(io.sphere.sdk.client.SphereClient) ResourceKeyIdGraphQlRequest(com.commercetools.sync.commons.helpers.ResourceKeyIdGraphQlRequest) Collections.emptyList(java.util.Collections.emptyList) Category(io.sphere.sdk.categories.Category) CategoryCreateCommand(io.sphere.sdk.categories.commands.CategoryCreateCommand) Set(java.util.Set) CategoryService(com.commercetools.sync.services.CategoryService) CompletionException(java.util.concurrent.CompletionException) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) String.format(java.lang.String.format) CategorySyncMockUtils.getMockCategoryDraft(com.commercetools.sync.categories.CategorySyncMockUtils.getMockCategoryDraft) Test(org.junit.jupiter.api.Test) LocalizedString(io.sphere.sdk.models.LocalizedString) List(java.util.List) CompletionStage(java.util.concurrent.CompletionStage) CATEGORY_KEY_1_RESOURCE_PATH(com.commercetools.sync.products.ProductSyncMockUtils.CATEGORY_KEY_1_RESOURCE_PATH) Optional(java.util.Optional) CategoryServiceImpl(com.commercetools.sync.services.impl.CategoryServiceImpl) Mockito.mock(org.mockito.Mockito.mock) ResourceIdentifier(io.sphere.sdk.models.ResourceIdentifier) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) IntStream(java.util.stream.IntStream) ArgumentMatchers.anySet(org.mockito.ArgumentMatchers.anySet) CategorySyncStatistics(com.commercetools.sync.categories.helpers.CategorySyncStatistics) SphereJsonUtils.readObjectFromResource(io.sphere.sdk.json.SphereJsonUtils.readObjectFromResource) AssertionsForStatistics.assertThat(com.commercetools.sync.commons.asserts.statistics.AssertionsForStatistics.assertThat) CategorySyncMockUtils.getMockCategory(com.commercetools.sync.categories.CategorySyncMockUtils.getMockCategory) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) Mockito.spy(org.mockito.Mockito.spy) WaitingToBeResolvedCategories(com.commercetools.sync.commons.models.WaitingToBeResolvedCategories) CategoryDraft(io.sphere.sdk.categories.CategoryDraft) CategoryDraftBuilder(io.sphere.sdk.categories.CategoryDraftBuilder) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Assertions.as(org.assertj.core.api.Assertions.as) CompletableFuture.supplyAsync(java.util.concurrent.CompletableFuture.supplyAsync) TypeService(com.commercetools.sync.services.TypeService) SphereException(io.sphere.sdk.models.SphereException) UnresolvedReferencesService(com.commercetools.sync.services.UnresolvedReferencesService) Nonnull(javax.annotation.Nonnull) Collections.emptySet(java.util.Collections.emptySet) ResourceKeyIdGraphQlResult(com.commercetools.sync.commons.models.ResourceKeyIdGraphQlResult) Mockito.times(org.mockito.Mockito.times) Mockito.when(org.mockito.Mockito.when) Mockito.verify(org.mockito.Mockito.verify) Mockito(org.mockito.Mockito) Mockito.never(org.mockito.Mockito.never) CustomFieldsDraft(io.sphere.sdk.types.CustomFieldsDraft) MockUtils.getMockTypeService(com.commercetools.sync.commons.MockUtils.getMockTypeService) STRING(org.assertj.core.api.InstanceOfAssertFactories.STRING) MockUtils.mockCategoryService(com.commercetools.sync.commons.MockUtils.mockCategoryService) Collections(java.util.Collections) BLANK_KEY_VALUE_ON_RESOURCE_IDENTIFIER(com.commercetools.sync.commons.helpers.BaseReferenceResolver.BLANK_KEY_VALUE_ON_RESOURCE_IDENTIFIER) Category(io.sphere.sdk.categories.Category) CategorySyncMockUtils.getMockCategory(com.commercetools.sync.categories.CategorySyncMockUtils.getMockCategory) CategoryQuery(io.sphere.sdk.categories.queries.CategoryQuery) ResourceKeyIdGraphQlRequest(com.commercetools.sync.commons.helpers.ResourceKeyIdGraphQlRequest) LocalizedString(io.sphere.sdk.models.LocalizedString) SphereException(io.sphere.sdk.models.SphereException) CategorySyncStatistics(com.commercetools.sync.categories.helpers.CategorySyncStatistics) ResourceKeyId(com.commercetools.sync.commons.models.ResourceKeyId) CategoryServiceImpl(com.commercetools.sync.services.impl.CategoryServiceImpl) SphereClient(io.sphere.sdk.client.SphereClient) ResourceKeyIdGraphQlResult(com.commercetools.sync.commons.models.ResourceKeyIdGraphQlResult) CategorySyncMockUtils.getMockCategoryDraft(com.commercetools.sync.categories.CategorySyncMockUtils.getMockCategoryDraft) CategoryDraft(io.sphere.sdk.categories.CategoryDraft) CategoryCreateCommand(io.sphere.sdk.categories.commands.CategoryCreateCommand) CategoryService(com.commercetools.sync.services.CategoryService) MockUtils.mockCategoryService(com.commercetools.sync.commons.MockUtils.mockCategoryService) Test(org.junit.jupiter.api.Test)

Aggregations

ResourceKeyIdGraphQlResult (com.commercetools.sync.commons.models.ResourceKeyIdGraphQlResult)36 Test (org.junit.jupiter.api.Test)35 SphereClient (io.sphere.sdk.client.SphereClient)22 List (java.util.List)18 ResourceIdsGraphQlRequest (com.commercetools.sync.commons.models.ResourceIdsGraphQlRequest)17 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)16 ArgumentMatchers.any (org.mockito.ArgumentMatchers.any)16 Mockito.mock (org.mockito.Mockito.mock)16 Mockito.when (org.mockito.Mockito.when)16 CompletableFuture (java.util.concurrent.CompletableFuture)15 ResourceKeyId (com.commercetools.sync.commons.models.ResourceKeyId)14 SphereJsonUtils (io.sphere.sdk.json.SphereJsonUtils)13 CaffeineReferenceIdToKeyCacheImpl (com.commercetools.sync.commons.utils.CaffeineReferenceIdToKeyCacheImpl)12 ReferenceIdToKeyCache (com.commercetools.sync.commons.utils.ReferenceIdToKeyCache)12 ResourceKeyIdGraphQlRequest (com.commercetools.sync.commons.helpers.ResourceKeyIdGraphQlRequest)11 Arrays.asList (java.util.Arrays.asList)11 Optional (java.util.Optional)11 CompletionStage (java.util.concurrent.CompletionStage)11 SphereJsonUtils.readObjectFromResource (io.sphere.sdk.json.SphereJsonUtils.readObjectFromResource)10 PagedQueryResult (io.sphere.sdk.queries.PagedQueryResult)10