Search in sources :

Example 1 with StateService

use of com.commercetools.sync.services.StateService in project commercetools-sync-java by commercetools.

the class StateServiceImplIT method createState_WithDuplicateKey_ShouldHaveEmptyOptionalAsAResult.

@Test
void createState_WithDuplicateKey_ShouldHaveEmptyOptionalAsAResult() {
    // preparation
    final StateDraft newStateDraft = StateDraftBuilder.of(OLD_STATE_KEY, STATE_TYPE).name(STATE_NAME_1).description(STATE_DESCRIPTION_1).build();
    final StateSyncOptions options = StateSyncOptionsBuilder.of(CTP_TARGET_CLIENT).errorCallback((exception, oldResource, newResource, updateActions) -> {
        errorCallBackMessages.add(exception.getMessage());
        errorCallBackExceptions.add(exception.getCause());
    }).build();
    final StateService stateService = new StateServiceImpl(options);
    // test
    final Optional<State> result = stateService.createState(newStateDraft).toCompletableFuture().join();
    // assertion
    assertThat(result).isEmpty();
    assertThat(errorCallBackMessages).hasSize(1).singleElement(as(STRING)).contains("A duplicate value");
    assertThat(errorCallBackExceptions).hasSize(1).singleElement().matches(exception -> {
        assertThat(exception).isExactlyInstanceOf(ErrorResponseException.class);
        final ErrorResponseException errorResponseException = (ErrorResponseException) exception;
        final List<DuplicateFieldError> fieldErrors = errorResponseException.getErrors().stream().map(sphereError -> {
            assertThat(sphereError.getCode()).isEqualTo(DuplicateFieldError.CODE);
            return sphereError.as(DuplicateFieldError.class);
        }).collect(toList());
        return fieldErrors.size() == 1;
    });
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) Reference(io.sphere.sdk.models.Reference) StateITUtils.createState(com.commercetools.sync.integration.commons.utils.StateITUtils.createState) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) SetName(io.sphere.sdk.states.commands.updateactions.SetName) StringUtils(org.apache.commons.lang3.StringUtils) Collections.singletonList(java.util.Collections.singletonList) AfterAll(org.junit.jupiter.api.AfterAll) Collections.singleton(java.util.Collections.singleton) SphereClient(io.sphere.sdk.client.SphereClient) StateType(io.sphere.sdk.states.StateType) BadGatewayException(io.sphere.sdk.client.BadGatewayException) STATE_KEY_1(com.commercetools.sync.integration.commons.utils.StateITUtils.STATE_KEY_1) CompletionStageUtil.executeBlocking(com.commercetools.tests.utils.CompletionStageUtil.executeBlocking) Set(java.util.Set) StateITUtils.clearTransitions(com.commercetools.sync.integration.commons.utils.StateITUtils.clearTransitions) StateService(com.commercetools.sync.services.StateService) StateServiceImpl(com.commercetools.sync.services.impl.StateServiceImpl) State(io.sphere.sdk.states.State) Test(org.junit.jupiter.api.Test) List(java.util.List) LocalizedString.ofEnglish(io.sphere.sdk.models.LocalizedString.ofEnglish) Optional(java.util.Optional) StateDraft(io.sphere.sdk.states.StateDraft) STATE_NAME_1(com.commercetools.sync.integration.commons.utils.StateITUtils.STATE_NAME_1) 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) StateQuery(io.sphere.sdk.states.queries.StateQuery) Mockito.spy(org.mockito.Mockito.spy) CompletableFutureUtils(io.sphere.sdk.utils.CompletableFutureUtils) DuplicateFieldError(io.sphere.sdk.models.errors.DuplicateFieldError) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Assertions.as(org.assertj.core.api.Assertions.as) StateDraftBuilder(io.sphere.sdk.states.StateDraftBuilder) StateSyncOptionsBuilder(com.commercetools.sync.states.StateSyncOptionsBuilder) ChangeKey(io.sphere.sdk.states.commands.updateactions.ChangeKey) Mockito.times(org.mockito.Mockito.times) Mockito.when(org.mockito.Mockito.when) StateSyncOptions(com.commercetools.sync.states.StateSyncOptions) Mockito.verify(org.mockito.Mockito.verify) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Collectors.toList(java.util.stream.Collectors.toList) ErrorResponseException(io.sphere.sdk.client.ErrorResponseException) ChangeType(io.sphere.sdk.states.commands.updateactions.ChangeType) STATE_DESCRIPTION_1(com.commercetools.sync.integration.commons.utils.StateITUtils.STATE_DESCRIPTION_1) STRING(org.assertj.core.api.InstanceOfAssertFactories.STRING) Collections(java.util.Collections) StateDraft(io.sphere.sdk.states.StateDraft) StateService(com.commercetools.sync.services.StateService) StateITUtils.createState(com.commercetools.sync.integration.commons.utils.StateITUtils.createState) State(io.sphere.sdk.states.State) DuplicateFieldError(io.sphere.sdk.models.errors.DuplicateFieldError) ErrorResponseException(io.sphere.sdk.client.ErrorResponseException) StateServiceImpl(com.commercetools.sync.services.impl.StateServiceImpl) StateSyncOptions(com.commercetools.sync.states.StateSyncOptions) Test(org.junit.jupiter.api.Test)

Example 2 with StateService

use of com.commercetools.sync.services.StateService in project commercetools-sync-java by commercetools.

the class StateSyncTest method sync_WithErrorCachingKeys_ShouldExecuteCallbackOnErrorAndIncreaseFailedCounter.

@Test
void sync_WithErrorCachingKeys_ShouldExecuteCallbackOnErrorAndIncreaseFailedCounter() {
    // preparation
    final StateDraft stateDraft = StateDraftBuilder.of("state-1", StateType.LINE_ITEM_STATE).build();
    final List<String> errorMessages = new ArrayList<>();
    final List<Throwable> exceptions = new ArrayList<>();
    final StateSyncOptions syncOptions = StateSyncOptionsBuilder.of(mock(SphereClient.class)).errorCallback((exception, oldResource, newResource, updateActions) -> {
        errorMessages.add(exception.getMessage());
        exceptions.add(exception.getCause());
    }).build();
    final StateService stateService = spy(new StateServiceImpl(syncOptions));
    when(stateService.cacheKeysToIds(anySet())).thenReturn(supplyAsync(() -> {
        throw new SphereException();
    }));
    final StateSync stateSync = new StateSync(syncOptions, stateService);
    // test
    final StateSyncStatistics stateSyncStatistics = stateSync.sync(singletonList(stateDraft)).toCompletableFuture().join();
    // assertions
    assertThat(errorMessages).hasSize(1).singleElement(as(STRING)).contains("Failed to build a cache of keys to ids.");
    assertThat(exceptions).hasSize(1).singleElement(as(THROWABLE)).isExactlyInstanceOf(CompletionException.class).hasCauseExactlyInstanceOf(SphereException.class);
    assertThat(stateSyncStatistics).hasValues(1, 0, 0, 1);
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) ArgumentMatchers.anySet(org.mockito.ArgumentMatchers.anySet) StateSyncStatistics(com.commercetools.sync.states.helpers.StateSyncStatistics) StateQuery(io.sphere.sdk.states.queries.StateQuery) CompletableFuture.completedFuture(java.util.concurrent.CompletableFuture.completedFuture) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) AssertionsForStatistics.assertThat(com.commercetools.sync.commons.asserts.statistics.AssertionsForStatistics.assertThat) HashMap(java.util.HashMap) Mockito.spy(org.mockito.Mockito.spy) Collections.singletonList(java.util.Collections.singletonList) ArrayList(java.util.ArrayList) Collections.singleton(java.util.Collections.singleton) Mockito.verifyNoMoreInteractions(org.mockito.Mockito.verifyNoMoreInteractions) Arrays.asList(java.util.Arrays.asList) Assertions.as(org.assertj.core.api.Assertions.as) CompletableFuture.supplyAsync(java.util.concurrent.CompletableFuture.supplyAsync) Map(java.util.Map) THROWABLE(org.assertj.core.api.InstanceOfAssertFactories.THROWABLE) SphereClient(io.sphere.sdk.client.SphereClient) SphereException(io.sphere.sdk.models.SphereException) StateType(io.sphere.sdk.states.StateType) StateDraftBuilder(io.sphere.sdk.states.StateDraftBuilder) Collections.emptyMap(java.util.Collections.emptyMap) Collections.emptySet(java.util.Collections.emptySet) CompletionException(java.util.concurrent.CompletionException) Mockito.when(org.mockito.Mockito.when) StateService(com.commercetools.sync.services.StateService) UUID(java.util.UUID) StateServiceImpl(com.commercetools.sync.services.impl.StateServiceImpl) State(io.sphere.sdk.states.State) Mockito.verify(org.mockito.Mockito.verify) Test(org.junit.jupiter.api.Test) LocalizedString(io.sphere.sdk.models.LocalizedString) Mockito.never(org.mockito.Mockito.never) List(java.util.List) Optional(java.util.Optional) StateDraft(io.sphere.sdk.states.StateDraft) STRING(org.assertj.core.api.InstanceOfAssertFactories.STRING) Mockito.mock(org.mockito.Mockito.mock) StateService(com.commercetools.sync.services.StateService) StateSyncStatistics(com.commercetools.sync.states.helpers.StateSyncStatistics) ArrayList(java.util.ArrayList) LocalizedString(io.sphere.sdk.models.LocalizedString) StateServiceImpl(com.commercetools.sync.services.impl.StateServiceImpl) SphereException(io.sphere.sdk.models.SphereException) StateDraft(io.sphere.sdk.states.StateDraft) SphereClient(io.sphere.sdk.client.SphereClient) CompletionException(java.util.concurrent.CompletionException) Test(org.junit.jupiter.api.Test)

Example 3 with StateService

use of com.commercetools.sync.services.StateService in project commercetools-sync-java by commercetools.

the class StateSyncTest method sync_WithErrorFetchingExistingKeys_ShouldExecuteCallbackOnErrorAndIncreaseFailedCounter.

@Test
void sync_WithErrorFetchingExistingKeys_ShouldExecuteCallbackOnErrorAndIncreaseFailedCounter() {
    // preparation
    final StateDraft stateDraft = StateDraftBuilder.of("state-1", StateType.LINE_ITEM_STATE).build();
    final List<String> errorMessages = new ArrayList<>();
    final List<Throwable> exceptions = new ArrayList<>();
    final SphereClient mockClient = mock(SphereClient.class);
    when(mockClient.execute(any(StateQuery.class))).thenReturn(supplyAsync(() -> {
        throw new SphereException();
    }));
    final StateSyncOptions syncOptions = StateSyncOptionsBuilder.of(mockClient).errorCallback((exception, oldResource, newResource, updateActions) -> {
        errorMessages.add(exception.getMessage());
        exceptions.add(exception.getCause());
    }).build();
    final StateService stateService = spy(new StateServiceImpl(syncOptions));
    final Map<String, String> keyToIds = new HashMap<>();
    keyToIds.put(stateDraft.getKey(), UUID.randomUUID().toString());
    when(stateService.cacheKeysToIds(anySet())).thenReturn(completedFuture(keyToIds));
    final StateSync stateSync = new StateSync(syncOptions, stateService);
    // test
    final StateSyncStatistics stateSyncStatistics = stateSync.sync(singletonList(stateDraft)).toCompletableFuture().join();
    // assertions
    assertThat(errorMessages).hasSize(1).singleElement(as(STRING)).contains("Failed to fetch existing states");
    assertThat(exceptions).hasSize(1).singleElement(as(THROWABLE)).isExactlyInstanceOf(CompletionException.class).hasCauseExactlyInstanceOf(SphereException.class);
    assertThat(stateSyncStatistics).hasValues(1, 0, 0, 1);
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) ArgumentMatchers.anySet(org.mockito.ArgumentMatchers.anySet) StateSyncStatistics(com.commercetools.sync.states.helpers.StateSyncStatistics) StateQuery(io.sphere.sdk.states.queries.StateQuery) CompletableFuture.completedFuture(java.util.concurrent.CompletableFuture.completedFuture) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) AssertionsForStatistics.assertThat(com.commercetools.sync.commons.asserts.statistics.AssertionsForStatistics.assertThat) HashMap(java.util.HashMap) Mockito.spy(org.mockito.Mockito.spy) Collections.singletonList(java.util.Collections.singletonList) ArrayList(java.util.ArrayList) Collections.singleton(java.util.Collections.singleton) Mockito.verifyNoMoreInteractions(org.mockito.Mockito.verifyNoMoreInteractions) Arrays.asList(java.util.Arrays.asList) Assertions.as(org.assertj.core.api.Assertions.as) CompletableFuture.supplyAsync(java.util.concurrent.CompletableFuture.supplyAsync) Map(java.util.Map) THROWABLE(org.assertj.core.api.InstanceOfAssertFactories.THROWABLE) SphereClient(io.sphere.sdk.client.SphereClient) SphereException(io.sphere.sdk.models.SphereException) StateType(io.sphere.sdk.states.StateType) StateDraftBuilder(io.sphere.sdk.states.StateDraftBuilder) Collections.emptyMap(java.util.Collections.emptyMap) Collections.emptySet(java.util.Collections.emptySet) CompletionException(java.util.concurrent.CompletionException) Mockito.when(org.mockito.Mockito.when) StateService(com.commercetools.sync.services.StateService) UUID(java.util.UUID) StateServiceImpl(com.commercetools.sync.services.impl.StateServiceImpl) State(io.sphere.sdk.states.State) Mockito.verify(org.mockito.Mockito.verify) Test(org.junit.jupiter.api.Test) LocalizedString(io.sphere.sdk.models.LocalizedString) Mockito.never(org.mockito.Mockito.never) List(java.util.List) Optional(java.util.Optional) StateDraft(io.sphere.sdk.states.StateDraft) STRING(org.assertj.core.api.InstanceOfAssertFactories.STRING) Mockito.mock(org.mockito.Mockito.mock) HashMap(java.util.HashMap) StateService(com.commercetools.sync.services.StateService) StateSyncStatistics(com.commercetools.sync.states.helpers.StateSyncStatistics) ArrayList(java.util.ArrayList) LocalizedString(io.sphere.sdk.models.LocalizedString) StateQuery(io.sphere.sdk.states.queries.StateQuery) SphereException(io.sphere.sdk.models.SphereException) StateServiceImpl(com.commercetools.sync.services.impl.StateServiceImpl) StateDraft(io.sphere.sdk.states.StateDraft) SphereClient(io.sphere.sdk.client.SphereClient) CompletionException(java.util.concurrent.CompletionException) Test(org.junit.jupiter.api.Test)

Example 4 with StateService

use of com.commercetools.sync.services.StateService in project commercetools-sync-java by commercetools.

the class StateReferenceResolverTest method resolveReferences_WithStateKeys_ShouldResolveReferences.

@Test
void resolveReferences_WithStateKeys_ShouldResolveReferences() {
    // preparation
    final StateSyncOptions stateSyncOptions = StateSyncOptionsBuilder.of(mock(SphereClient.class)).build();
    final int nStates = 10;
    final List<State> states = IntStream.range(0, nStates).mapToObj(i -> i + "").map(key -> {
        final State state = mock(State.class);
        when(state.getKey()).thenReturn(key);
        when(state.getId()).thenReturn(key);
        when(state.toReference()).thenReturn(State.referenceOfId(key));
        return state;
    }).collect(Collectors.toList());
    final StateService mockStateService = mock(StateService.class);
    when(mockStateService.fetchMatchingStatesByKeysWithTransitions(any())).thenReturn(CompletableFuture.completedFuture(new HashSet<>(states)));
    final Set<Reference<State>> stateReferences = states.stream().map(State::toReference).collect(Collectors.toSet());
    final StateDraft stateDraft = StateDraftBuilder.of("state-key", StateType.LINE_ITEM_STATE).transitions(stateReferences).build();
    final StateReferenceResolver stateReferenceResolver = new StateReferenceResolver(stateSyncOptions, mockStateService);
    // test
    final StateDraft resolvedDraft = stateReferenceResolver.resolveReferences(stateDraft).toCompletableFuture().join();
    // assertion
    assertThat(resolvedDraft.getTransitions()).isNotNull();
    assertThat(resolvedDraft.getTransitions()).hasSize(nStates);
    assertThat(resolvedDraft.getTransitions()).hasSameElementsAs(stateReferences);
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) IntStream(java.util.stream.IntStream) ArgumentMatchers.anySet(org.mockito.ArgumentMatchers.anySet) BLANK_ID_VALUE_ON_REFERENCE(com.commercetools.sync.commons.helpers.BaseReferenceResolver.BLANK_ID_VALUE_ON_REFERENCE) Reference(io.sphere.sdk.models.Reference) ReferenceResolutionException(com.commercetools.sync.commons.exceptions.ReferenceResolutionException) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) CompletableFuture(java.util.concurrent.CompletableFuture) HashSet(java.util.HashSet) Collections.singleton(java.util.Collections.singleton) SphereClient(io.sphere.sdk.client.SphereClient) SphereException(io.sphere.sdk.models.SphereException) StateType(io.sphere.sdk.states.StateType) StateDraftBuilder(io.sphere.sdk.states.StateDraftBuilder) StateSyncOptionsBuilder(com.commercetools.sync.states.StateSyncOptionsBuilder) Set(java.util.Set) Mockito.when(org.mockito.Mockito.when) StateService(com.commercetools.sync.services.StateService) StateSyncOptions(com.commercetools.sync.states.StateSyncOptions) State(io.sphere.sdk.states.State) Collectors(java.util.stream.Collectors) String.format(java.lang.String.format) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) List(java.util.List) StateDraft(io.sphere.sdk.states.StateDraft) Mockito.mock(org.mockito.Mockito.mock) StateDraft(io.sphere.sdk.states.StateDraft) State(io.sphere.sdk.states.State) StateService(com.commercetools.sync.services.StateService) Reference(io.sphere.sdk.models.Reference) StateSyncOptions(com.commercetools.sync.states.StateSyncOptions) HashSet(java.util.HashSet) Test(org.junit.jupiter.api.Test)

Example 5 with StateService

use of com.commercetools.sync.services.StateService in project commercetools-sync-java by commercetools.

the class StateReferenceResolverTest method resolveReferences_WithExceptionStateFetch_ShouldNotResolveReference.

@Test
void resolveReferences_WithExceptionStateFetch_ShouldNotResolveReference() {
    final StateSyncOptions stateSyncOptions = StateSyncOptionsBuilder.of(mock(SphereClient.class)).build();
    final StateService mockStateService = mock(StateService.class);
    final State state = mock(State.class);
    when(state.getKey()).thenReturn("state-key");
    when(state.getId()).thenReturn("state-id");
    when(state.toReference()).thenReturn(State.referenceOfId("state-id"));
    when(mockStateService.fetchMatchingStatesByKeysWithTransitions(any())).thenReturn(CompletableFuture.completedFuture(singleton(state)));
    final StateDraft stateDraft = StateDraftBuilder.of("state-key", StateType.LINE_ITEM_STATE).transitions(singleton(state.toReference())).build();
    final CompletableFuture<Set<State>> futureThrowingSphereException = new CompletableFuture<>();
    futureThrowingSphereException.completeExceptionally(new SphereException("CTP error on fetch"));
    when(mockStateService.fetchMatchingStatesByKeysWithTransitions(anySet())).thenReturn(futureThrowingSphereException);
    final StateReferenceResolver stateReferenceResolver = new StateReferenceResolver(stateSyncOptions, mockStateService);
    // test and assertion
    assertThat(stateReferenceResolver.resolveReferences(stateDraft).toCompletableFuture()).failsWithin(1, TimeUnit.SECONDS).withThrowableOfType(ExecutionException.class).withCauseExactlyInstanceOf(SphereException.class).withMessageContaining("CTP error on fetch");
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) StateDraft(io.sphere.sdk.states.StateDraft) ArgumentMatchers.anySet(org.mockito.ArgumentMatchers.anySet) HashSet(java.util.HashSet) Set(java.util.Set) StateService(com.commercetools.sync.services.StateService) State(io.sphere.sdk.states.State) SphereException(io.sphere.sdk.models.SphereException) StateSyncOptions(com.commercetools.sync.states.StateSyncOptions) Test(org.junit.jupiter.api.Test)

Aggregations

StateService (com.commercetools.sync.services.StateService)17 StateDraft (io.sphere.sdk.states.StateDraft)16 Test (org.junit.jupiter.api.Test)16 StateSyncOptions (com.commercetools.sync.states.StateSyncOptions)11 State (io.sphere.sdk.states.State)11 HashSet (java.util.HashSet)11 SphereClient (io.sphere.sdk.client.SphereClient)9 StateDraftBuilder (io.sphere.sdk.states.StateDraftBuilder)9 StateType (io.sphere.sdk.states.StateType)9 Collections.singleton (java.util.Collections.singleton)9 List (java.util.List)9 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)9 ArgumentMatchers.any (org.mockito.ArgumentMatchers.any)9 Mockito.when (org.mockito.Mockito.when)9 StateServiceImpl (com.commercetools.sync.services.impl.StateServiceImpl)8 StateQuery (io.sphere.sdk.states.queries.StateQuery)8 ArrayList (java.util.ArrayList)8 Collections.singletonList (java.util.Collections.singletonList)8 Optional (java.util.Optional)8 Assertions.as (org.assertj.core.api.Assertions.as)8