use of com.commercetools.sync.products.ProductSyncMockUtils.PRODUCT_KEY_1_RESOURCE_PATH in project commercetools-sync-java by commercetools.
the class ProductSyncIT method sync_withProductTypeReference_ShouldUpdateProducts.
@Test
void sync_withProductTypeReference_ShouldUpdateProducts() {
// Preparation
// Create custom options with whitelisting and action filter callback..
final ProductSyncOptions customSyncOptions = ProductSyncOptionsBuilder.of(CTP_TARGET_CLIENT).errorCallback((exception, oldResource, newResource, updateActions) -> errorCallback(exception.getMessage(), exception.getCause())).warningCallback((exception, oldResource, newResources) -> warningCallBackMessages.add(exception.getMessage())).beforeUpdateCallback(this::beforeUpdateCallback).syncFilter(SyncFilter.ofWhiteList(ATTRIBUTES)).build();
final ProductSync customSync = new ProductSync(customSyncOptions);
// Create 3 existing products in target project with keys (productKey1, productKey2 and
// productKey3)
final ProductDraft existingProductDraft = createProductDraft(PRODUCT_KEY_1_RESOURCE_PATH, targetProductType.toReference(), targetTaxCategory.toReference(), targetProductState.toReference(), targetCategoryReferencesWithIds, createRandomCategoryOrderHints(targetCategoryReferencesWithIds));
CTP_TARGET_CLIENT.execute(ProductCreateCommand.of(existingProductDraft)).toCompletableFuture().join();
final ProductDraft existingProductDraft2 = createProductDraft(PRODUCT_KEY_2_RESOURCE_PATH, targetProductType.toReference(), targetTaxCategory.toReference(), targetProductState.toReference(), targetCategoryReferencesWithIds, createRandomCategoryOrderHints(targetCategoryReferencesWithIds));
CTP_TARGET_CLIENT.execute(ProductCreateCommand.of(existingProductDraft2)).toCompletableFuture().join();
final ProductDraft existingProductDraft3 = createProductDraftBuilder(PRODUCT_KEY_2_RESOURCE_PATH, targetProductType.toReference()).slug(ofEnglish("newSlug3")).key("productKey3").masterVariant(ProductVariantDraftBuilder.of().key("v3").sku("s3").build()).taxCategory(null).state(null).categories(Collections.emptySet()).categoryOrderHints(null).build();
CTP_TARGET_CLIENT.execute(ProductCreateCommand.of(existingProductDraft3)).toCompletableFuture().join();
// Create 2 existing products in source project with keys (productKey2 and productKey3)
final ProductDraft newProductDraft2 = createProductDraft(PRODUCT_KEY_2_RESOURCE_PATH, sourceProductType.toReference(), sourceTaxCategory.toReference(), sourceProductState.toReference(), sourceCategoryReferencesWithIds, createRandomCategoryOrderHints(sourceCategoryReferencesWithIds));
final Product product2 = CTP_SOURCE_CLIENT.execute(ProductCreateCommand.of(newProductDraft2)).toCompletableFuture().join();
final ProductDraft newProductDraft3 = createProductDraftBuilder(PRODUCT_KEY_2_RESOURCE_PATH, sourceProductType.toReference()).slug(ofEnglish("newSlug3")).key("productKey3").masterVariant(ProductVariantDraftBuilder.of().key("v3").sku("s3").build()).taxCategory(null).state(null).categories(Collections.emptySet()).categoryOrderHints(null).build();
final Product product3 = CTP_SOURCE_CLIENT.execute(ProductCreateCommand.of(newProductDraft3)).toCompletableFuture().join();
// Create existing product with productKey1 in source project that has references to products
// with keys
// (productKey2 and productKey3).
final ObjectNode productReferenceValue1 = getProductReferenceWithId(product2.getId());
final ObjectNode productReferenceValue2 = getProductReferenceWithId(product3.getId());
final AttributeDraft productRefAttr = AttributeDraft.of("product-reference", productReferenceValue1);
final AttributeDraft productSetRefAttr = getReferenceSetAttributeDraft("product-reference-set", productReferenceValue1, productReferenceValue2);
final List<AttributeDraft> attributeDrafts = existingProductDraft.getMasterVariant().getAttributes();
attributeDrafts.addAll(Arrays.asList(productRefAttr, productSetRefAttr));
final ProductVariantDraft masterVariant = ProductVariantDraftBuilder.of().key("v1").sku("s1").attributes(attributeDrafts).build();
final ProductDraft newProductDraftWithProductReference = createProductDraftBuilder(PRODUCT_KEY_1_CHANGED_RESOURCE_PATH, sourceProductType.toReference()).masterVariant(masterVariant).taxCategory(sourceTaxCategory.toReference()).state(sourceProductState.toReference()).categories(Collections.emptySet()).categoryOrderHints(null).build();
CTP_SOURCE_CLIENT.execute(ProductCreateCommand.of(newProductDraftWithProductReference)).toCompletableFuture().join();
// Test
final List<ProductProjection> products = CTP_SOURCE_CLIENT.execute(ProductProjectionQuery.ofStaged()).toCompletableFuture().join().getResults();
final List<ProductDraft> productDrafts = ProductTransformUtils.toProductDrafts(CTP_SOURCE_CLIENT, referenceIdToKeyCache, products).join();
final ProductSyncStatistics syncStatistics = customSync.sync(productDrafts).toCompletableFuture().join();
// Assertion
assertThat(syncStatistics).hasValues(3, 0, 1, 0);
assertThat(errorCallBackMessages).isEmpty();
assertThat(errorCallBackExceptions).isEmpty();
assertThat(warningCallBackMessages).isEmpty();
final Product targetProduct2 = CTP_TARGET_CLIENT.execute(ProductByKeyGet.of("productKey2")).toCompletableFuture().join();
final Product targetProduct3 = CTP_TARGET_CLIENT.execute(ProductByKeyGet.of("productKey3")).toCompletableFuture().join();
final ObjectNode targetProductReferenceValue2 = getProductReferenceWithId(targetProduct2.getId());
final ObjectNode targetProductReferenceValue3 = getProductReferenceWithId(targetProduct3.getId());
final AttributeDraft targetProductRefAttr = AttributeDraft.of("product-reference", targetProductReferenceValue2);
final AttributeDraft targetProductSetRefAttr = getReferenceSetAttributeDraft("product-reference-set", targetProductReferenceValue2, targetProductReferenceValue3);
assertThat(updateActions).containsExactlyInAnyOrder(SetAttributeInAllVariants.of(targetProductRefAttr.getName(), targetProductRefAttr.getValue(), true), SetAttributeInAllVariants.of(targetProductSetRefAttr.getName(), targetProductSetRefAttr.getValue(), true), Publish.of());
}
use of com.commercetools.sync.products.ProductSyncMockUtils.PRODUCT_KEY_1_RESOURCE_PATH in project commercetools-sync-java by commercetools.
the class ProductServiceImplIT method createProduct_WithDuplicateSlug_ShouldNotCreateProduct.
@Test
void createProduct_WithDuplicateSlug_ShouldNotCreateProduct() {
// Create product with same slug as existing product
final String newKey = "newKey";
final ProductDraft productDraft1 = createProductDraftBuilder(PRODUCT_KEY_1_RESOURCE_PATH, productType.toReference()).key(newKey).taxCategory(null).state(null).categories(emptyList()).categoryOrderHints(null).masterVariant(ProductVariantDraftBuilder.of().build()).build();
final Optional<ProductProjection> createdProductOptional = productService.createProduct(productDraft1).toCompletableFuture().join();
assertThat(createdProductOptional).isEmpty();
final String duplicatedSlug = "english-slug";
assertThat(errorCallBackExceptions).hasSize(1).allSatisfy(exception -> {
assertThat(exception).isExactlyInstanceOf(ErrorResponseException.class);
final ErrorResponseException errorResponse = ((ErrorResponseException) exception);
final List<DuplicateFieldError> fieldErrors = errorResponse.getErrors().stream().map(sphereError -> {
assertThat(sphereError.getCode()).isEqualTo(DuplicateFieldError.CODE);
return sphereError.as(DuplicateFieldError.class);
}).collect(toList());
assertThat(fieldErrors).hasSize(1);
assertThat(fieldErrors).allSatisfy(error -> {
assertThat(error.getField()).isEqualTo("slug.en");
assertThat(error.getDuplicateValue()).isEqualTo(duplicatedSlug);
});
});
assertThat(errorCallBackMessages).hasSize(1).allSatisfy(errorMessage -> {
assertThat(errorMessage).contains("\"code\" : \"DuplicateField\"");
assertThat(errorMessage).contains("\"field\" : \"slug.en\"");
assertThat(errorMessage).contains("\"duplicateValue\" : \"" + duplicatedSlug + "\"");
});
// assert CTP state
final Optional<ProductProjection> productOptional = CTP_TARGET_CLIENT.execute(ProductProjectionQuery.ofStaged().withPredicates(QueryPredicate.of(format("key = \"%s\"", newKey)))).toCompletableFuture().join().head();
assertThat(productOptional).isEmpty();
}
use of com.commercetools.sync.products.ProductSyncMockUtils.PRODUCT_KEY_1_RESOURCE_PATH in project commercetools-sync-java by commercetools.
the class CleanupUnresolvedReferenceCustomObjectsIT method createSampleUnresolvedReferences.
void createSampleUnresolvedReferences() {
final ProductDraft sampleProductDraft = SphereJsonUtils.readObjectFromResource(PRODUCT_KEY_1_RESOURCE_PATH, ProductDraft.class);
final CategoryDraft sampleCategoryDraft = SphereJsonUtils.readObjectFromResource(CATEGORY_KEY_1_RESOURCE_PATH, CategoryDraft.class);
final Set<Reference<State>> sampleTransitions = new HashSet<>(Arrays.asList(State.referenceOfId("id1"), State.referenceOfId("id2")));
final List<WaitingToBeResolvedProducts> productUnresolvedReferences = new ArrayList<>();
final List<WaitingToBeResolvedCategories> categoryUnresolvedReferences = new ArrayList<>();
final List<WaitingToBeResolvedTransitions> transitionUnresolvedReferences = new ArrayList<>();
for (int i = 1; i <= 5; i++) {
productUnresolvedReferences.add(new WaitingToBeResolvedProducts(ProductDraftBuilder.of(sampleProductDraft).key(format("productKey%s", i)).build(), asSet("foo", "bar")));
categoryUnresolvedReferences.add(new WaitingToBeResolvedCategories(CategoryDraftBuilder.of(sampleCategoryDraft).key(format("categoryKey%s", i)).build(), asSet("foo", "bar")));
transitionUnresolvedReferences.add(new WaitingToBeResolvedTransitions(StateDraftBuilder.of(format("stateKeys%s", i), StateType.LINE_ITEM_STATE).transitions(sampleTransitions).build(), asSet("foo", "bar")));
}
CompletableFuture.allOf(CompletableFuture.allOf(productUnresolvedReferences.stream().map(draft -> unresolvedReferencesServiceForProducts.save(draft, CUSTOM_OBJECT_PRODUCT_CONTAINER_KEY, WaitingToBeResolvedProducts.class)).map(CompletionStage::toCompletableFuture).toArray(CompletableFuture[]::new)), CompletableFuture.allOf(categoryUnresolvedReferences.stream().map(draft -> unresolvedReferencesServiceForCategories.save(draft, CUSTOM_OBJECT_CATEGORY_CONTAINER_KEY, WaitingToBeResolvedCategories.class)).map(CompletionStage::toCompletableFuture).toArray(CompletableFuture[]::new)), CompletableFuture.allOf(transitionUnresolvedReferences.stream().map(draft -> unresolvedReferencesServiceForTransitions.save(draft, CUSTOM_OBJECT_TRANSITION_CONTAINER_KEY, WaitingToBeResolvedTransitions.class)).map(CompletionStage::toCompletableFuture).toArray(CompletableFuture[]::new))).join();
}
use of com.commercetools.sync.products.ProductSyncMockUtils.PRODUCT_KEY_1_RESOURCE_PATH in project commercetools-sync-java by commercetools.
the class ProductServiceImplIT method setupTest.
/**
* Deletes Products and Types from target CTP projects, then it populates target CTP project with
* product test data.
*/
@BeforeEach
void setupTest() {
errorCallBackMessages = new ArrayList<>();
errorCallBackExceptions = new ArrayList<>();
warningCallBackMessages = new ArrayList<>();
deleteAllProducts(CTP_TARGET_CLIENT);
final ProductSyncOptions productSyncOptions = ProductSyncOptionsBuilder.of(CTP_TARGET_CLIENT).errorCallback((exception, oldResource, newResource, updateActions) -> {
errorCallBackMessages.add(exception.getMessage());
errorCallBackExceptions.add(exception.getCause());
}).warningCallback((exception, oldResource, newResource) -> warningCallBackMessages.add(exception.getMessage())).build();
// Create a mock new product in the target project.
final ProductDraft productDraft = createProductDraft(PRODUCT_KEY_1_RESOURCE_PATH, productType.toReference(), null, null, categoryReferencesWithIds, createRandomCategoryOrderHints(categoryReferencesWithIds));
product = CTP_TARGET_CLIENT.execute(ProductCreateCommand.of(productDraft)).thenApply(p -> p.toProjection(ProductProjectionType.STAGED)).toCompletableFuture().join();
productService = new ProductServiceImpl(productSyncOptions);
}
use of com.commercetools.sync.products.ProductSyncMockUtils.PRODUCT_KEY_1_RESOURCE_PATH in project commercetools-sync-java by commercetools.
the class ProductSyncIT method sync_withProductContainingAttributeChanges_shouldSyncProductCorrectly.
@Test
void sync_withProductContainingAttributeChanges_shouldSyncProductCorrectly() {
// preparation
final List<UpdateAction<Product>> updateActions = new ArrayList<>();
final TriConsumer<SyncException, Optional<ProductDraft>, Optional<ProductProjection>> warningCallBack = (exception, newResource, oldResource) -> warningCallBackMessages.add(exception.getMessage());
final ProductSyncOptions customOptions = ProductSyncOptionsBuilder.of(CTP_TARGET_CLIENT).errorCallback((exception, oldResource, newResource, actions) -> collectErrors(exception.getMessage(), exception.getCause())).warningCallback(warningCallBack).beforeUpdateCallback((actions, draft, old) -> {
updateActions.addAll(actions);
return actions;
}).build();
final ProductDraft productDraft = createProductDraftBuilder(PRODUCT_KEY_1_RESOURCE_PATH, ProductType.referenceOfId(productType.getKey())).categories(emptyList()).taxCategory(null).state(null).build();
// Creating the attribute draft with the changes
final AttributeDraft priceInfoAttrDraft = AttributeDraft.of("priceInfo", JsonNodeFactory.instance.textNode("100/kg"));
final AttributeDraft angebotAttrDraft = AttributeDraft.of("angebot", JsonNodeFactory.instance.textNode("big discount"));
final AttributeDraft unknownAttrDraft = AttributeDraft.of("unknown", JsonNodeFactory.instance.textNode("unknown"));
// Creating the product variant draft with the product reference attribute
final List<AttributeDraft> attributes = asList(priceInfoAttrDraft, angebotAttrDraft, unknownAttrDraft);
final ProductVariantDraft masterVariant = ProductVariantDraftBuilder.of(productDraft.getMasterVariant()).attributes(attributes).build();
final ProductDraft productDraftWithChangedAttributes = ProductDraftBuilder.of(productDraft).masterVariant(masterVariant).build();
// test
final ProductSync productSync = new ProductSync(customOptions);
final ProductSyncStatistics syncStatistics = executeBlocking(productSync.sync(singletonList(productDraftWithChangedAttributes)));
// assertion
assertThat(syncStatistics).hasValues(1, 0, 1, 0, 0);
final String causeErrorMessage = format(ATTRIBUTE_NOT_IN_ATTRIBUTE_METADATA, unknownAttrDraft.getName());
final String expectedErrorMessage = format(FAILED_TO_BUILD_ATTRIBUTE_UPDATE_ACTION, unknownAttrDraft.getName(), productDraft.getMasterVariant().getKey(), productDraft.getKey(), causeErrorMessage);
assertThat(errorCallBackExceptions).hasSize(1);
assertThat(errorCallBackExceptions.get(0).getMessage()).isEqualTo(expectedErrorMessage);
assertThat(errorCallBackExceptions.get(0).getCause().getMessage()).isEqualTo(causeErrorMessage);
assertThat(errorCallBackMessages).containsExactly(expectedErrorMessage);
assertThat(warningCallBackMessages).isEmpty();
assertThat(updateActions).filteredOn(updateAction -> !(updateAction instanceof SetTaxCategory)).filteredOn(updateAction -> !(updateAction instanceof RemoveFromCategory)).containsExactlyInAnyOrder(SetAttributeInAllVariants.of(priceInfoAttrDraft, true), SetAttribute.of(1, angebotAttrDraft, true), SetAttributeInAllVariants.ofUnsetAttribute("size", true), SetAttributeInAllVariants.ofUnsetAttribute("rinderrasse", true), SetAttributeInAllVariants.ofUnsetAttribute("herkunft", true), SetAttributeInAllVariants.ofUnsetAttribute("teilstueck", true), SetAttributeInAllVariants.ofUnsetAttribute("fuetterung", true), SetAttributeInAllVariants.ofUnsetAttribute("reifung", true), SetAttributeInAllVariants.ofUnsetAttribute("haltbarkeit", true), SetAttributeInAllVariants.ofUnsetAttribute("verpackung", true), SetAttributeInAllVariants.ofUnsetAttribute("anlieferung", true), SetAttributeInAllVariants.ofUnsetAttribute("zubereitung", true), SetAttribute.ofUnsetAttribute(1, "localisedText", true), Publish.of());
}
Aggregations