public static void assertEventually(final Duration maxWaitTime, final Duration waitBeforeRetry, final Runnable block) { final long timeOutAt = System.currentTimeMillis() + maxWaitTime.toMillis(); while (true) { try { block.run(); // the block executed without throwing an exception, return return; } catch (AssertionError | ErrorResponseException e) { if (e instanceof ErrorResponseException && !((ErrorResponseException) e).hasErrorCode("SearchFacetPathNotFound")) { throw e; } if (System.currentTimeMillis() > timeOutAt) { throw e; } } try { Thread.sleep(waitBeforeRetry.toMillis()); } catch (InterruptedException e) { throw new RuntimeException(e); } } }
@Test public void invalidCurrentPassword() throws Exception { withCustomer(client(), customer -> { final String oldPassword = PASSWORD + randomInt(); final String newPassword = "newSecret"; final Throwable throwable = catchThrowable(() -> client().executeBlocking(CustomerChangePasswordCommand.of(customer, oldPassword, newPassword))); assertThat(throwable).isInstanceOf(ErrorResponseException.class); final ErrorResponseException errorResponseException = (ErrorResponseException) throwable; assertThat(errorResponseException.hasErrorCode(CustomerInvalidCurrentPassword.CODE)).isTrue(); }); }
@Test public void executionWithInvalidEmail() throws Exception { withCustomer(client(), customer -> { assertThatThrownBy(() -> client().executeBlocking(CustomerSignInCommand.of("notpresent@null.sphere.io", PASSWORD))) .isInstanceOf(ErrorResponseException.class) .matches(e -> ((ErrorResponseException) e).hasErrorCode(CustomerInvalidCredentials.CODE)); }); }
@Test public void updateWithWrongType() throws Exception { final Product product = createProduct(); assertThatThrownBy(() -> client().executeBlocking(ProductUpdateCommand.of(product, SetAttribute.of(1, AttributeDraft.of(LAUNDRY_SYMBOLS_ATTR_NAME, "cold"))))) .isInstanceOf(ErrorResponseException.class) .matches(e -> ((ErrorResponseException)e).hasErrorCode(InvalidField.CODE)); }
@Test public void order() { withDiscountCodeOfPredicate("totalPrice > \"800.00 EUR\"", (DiscountCode discountCode) -> withFilledCart(client(), cart -> { final Cart cartWithDiscountCode = client().executeBlocking(CartUpdateCommand.of(cart, AddDiscountCode.of(discountCode))); assertThat(cartWithDiscountCode.getTotalPrice()).isEqualTo(MoneyImpl.of("37.02", EUR)); assertThat(cartWithDiscountCode.getDiscountCodes()).hasSize(1); assertThat(cartWithDiscountCode.getDiscountCodes().get(0).getState()) .as("the discount (code) does not match the cart") .isEqualTo(DOES_NOT_MATCH_CART); final Throwable throwable = catchThrowable(() -> client().executeBlocking(OrderFromCartCreateCommand.of(cartWithDiscountCode))); assertThat(throwable).isInstanceOf(ErrorResponseException.class); final ErrorResponseException e = (ErrorResponseException) throwable; assertThat(e.hasErrorCode(DiscountCodeNonApplicableError.CODE)).isTrue(); })); }
private void demo(final SphereClient client, final String email) { final String wrongPassword = "wrong password"; final CustomerSignInCommand signInCommand = CustomerSignInCommand.of(email, wrongPassword); final CompletionStage<CustomerSignInResult> future = client.execute(signInCommand); future.whenCompleteAsync((signInResult, exception) -> { if (signInResult != null) { println("Signing worked"); } else if (exception instanceof ErrorResponseException) { final ErrorResponseException errorResponseException = (ErrorResponseException) exception; final String code = CustomerInvalidCredentials.CODE; if (errorResponseException.hasErrorCode(code)) { println("customer has invalid credentials"); } } }); }
@Test public void execution() throws Exception { withCustomer(client(), customer -> { final String oldPassword = PASSWORD; final String newPassword = "newSecret"; final Customer updatedCustomer = client().executeBlocking(CustomerChangePasswordCommand.of(customer, oldPassword, newPassword)); assertThat(customer.getPassword()).isNotEqualTo(updatedCustomer.getPassword()); final CustomerSignInResult signInResult = client().executeBlocking(CustomerSignInCommand.of(customer.getEmail(), newPassword)); assertThat(signInResult.getCustomer().hasSameIdAs(updatedCustomer)) .overridingErrorMessage("sign in works with new password") .isTrue(); final Throwable throwable = catchThrowable(() -> client().executeBlocking(CustomerSignInCommand.of(customer.getEmail(), oldPassword))); assertThat(throwable).isInstanceOf(ErrorResponseException.class); final ErrorResponseException errorResponseException = (ErrorResponseException) throwable; assertThat(errorResponseException.hasErrorCode(CustomerInvalidCredentials.CODE)).isTrue(); }); }
@Test public void order() { withTaxedProduct(client(), product -> { final int itemsLeft = 3; final String sku = getSku(product); client().executeBlocking(InventoryEntryCreateCommand.of(InventoryEntryDraft.of(sku, itemsLeft))); final int itemCountToOrder = 5; final CartDraftDsl draft = CartDraft.of(DefaultCurrencyUnits.EUR) .withCountry(CountryCode.DE) .withInventoryMode(InventoryMode.RESERVE_ON_ORDER) .withShippingAddress(Address.of(CountryCode.DE)) .withLineItems(Collections.singletonList(LineItemDraft.of(product, 1, itemCountToOrder))); final Cart cart = client().executeBlocking(CartCreateCommand.of(draft)); final Throwable throwable = catchThrowable(() -> client().executeBlocking(OrderFromCartCreateCommand.of(cart))); assertThat(throwable).isInstanceOf(ErrorResponseException.class); final ErrorResponseException e = (ErrorResponseException) throwable; assertThat(e.hasErrorCode(OutOfStockError.CODE)); final OutOfStockError outOfStockError = e.getErrors().stream() .filter(err -> err.getCode().equals(OutOfStockError.CODE)) .findFirst().get().as(OutOfStockError.class); assertThat(outOfStockError.getSkus()).containsExactly(sku); assertThat(outOfStockError.getLineItems()).containsExactly(cart.getLineItems().get(0).getId()); }); }
@Test public void invalidTypeCausesException() throws Exception { final ProductType productType = fetchProductTypeByName(); final ProductVariantDraft masterVariantDraft = ProductVariantDraftBuilder.of() .plusAttribute(COLOR_ATTR_NAME, 1)//1 is of illegal type and of illegal key .build(); final ProductDraft draft = ProductDraftBuilder .of(productType, en("basic shirt"), randomSlug(), masterVariantDraft) .build(); assertThatThrownBy(() -> client().executeBlocking(ProductCreateCommand.of(draft))) .isInstanceOf(ErrorResponseException.class) .matches(e -> ((ErrorResponseException)e).hasErrorCode(InvalidField.CODE)); }
assertThat(throwable).isInstanceOf(ErrorResponseException.class); final ErrorResponseException e = (ErrorResponseException) throwable; assertThat(e.hasErrorCode(PriceChangedError.CODE)); final PriceChangedError error = e.getErrors().stream() .filter(err -> err.getCode().equals(PriceChangedError.CODE))
@Test public void requiredValidation() { final FieldDefinition stringFieldDefinition = FieldDefinition.of(StringFieldType.of(), STRING_FIELD_NAME, en("label"), true, TextInputHint.SINGLE_LINE); final String typeKey = randomKey(); final TypeDraft typeDraft = TypeDraftBuilder.of(typeKey, en("name of the custom type"), TYPE_IDS) .description(en("description")) .fieldDefinitions(asList(stringFieldDefinition)) .build(); final Type type = client().executeBlocking(TypeCreateCommand.of(typeDraft)); withCategory(client(), category -> { assertThatThrownBy(() -> client().executeBlocking(CategoryUpdateCommand.of(category, SetCustomType.ofTypeIdAndObjects(type.getId(), Collections.emptyMap())))) .isInstanceOf(ErrorResponseException.class) .matches(e -> { final ErrorResponseException errorResponseException = (ErrorResponseException) e; final String errorCode = RequiredField.CODE; return errorResponseException.hasErrorCode(errorCode) && errorResponseException.getErrors().stream() .filter(err -> err.getCode().equals(errorCode)) .anyMatch(err -> STRING_FIELD_NAME.equals(err.as(RequiredField.class).getField())); }); }); client().executeBlocking(TypeDeleteCommand.of(type)); }
@Test public void executionDemo() throws Exception { withCustomer(client(), customer -> { final SphereClient client = client(); demo(client, customer.getEmail()); final String oldPassword = PASSWORD; final String newPassword = "newSecret"; final Customer updatedCustomer = client().executeBlocking(CustomerChangePasswordCommand.of(customer, oldPassword, newPassword)); assertThat(customer.getPassword()).isNotEqualTo(updatedCustomer.getPassword()); final CustomerSignInResult signInResult = client().executeBlocking(CustomerSignInCommand.of(customer.getEmail(), newPassword)); assertThat(signInResult.getCustomer().hasSameIdAs(updatedCustomer)) .overridingErrorMessage("sign in works with new password") .isTrue(); try { client().executeBlocking(CustomerSignInCommand.of(customer.getEmail(), oldPassword)); fail(); } catch (final ErrorResponseException e) { assertThat(e.hasErrorCode(CustomerInvalidCredentials.CODE)).isTrue(); } }); }