forked from commercetools/commercetools-sync-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCustomObjectSyncIT.java
More file actions
469 lines (406 loc) · 19.6 KB
/
Copy pathCustomObjectSyncIT.java
File metadata and controls
469 lines (406 loc) · 19.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
package com.commercetools.sync.integration.externalsource.customobjects;
import static com.commercetools.sync.commons.asserts.statistics.AssertionsForStatistics.assertThat;
import static com.commercetools.sync.integration.commons.utils.CustomObjectITUtils.createCustomObject;
import static com.commercetools.sync.integration.commons.utils.CustomObjectITUtils.deleteCustomObject;
import static com.commercetools.sync.integration.commons.utils.ITUtils.createBadGatewayException;
import static com.commercetools.sync.integration.commons.utils.ITUtils.createConcurrentModificationException;
import static com.commercetools.sync.integration.commons.utils.TestClientUtils.CTP_TARGET_CLIENT;
import static java.lang.String.format;
import com.commercetools.api.client.ProjectApiRoot;
import com.commercetools.api.defaultconfig.ApiRootBuilder;
import com.commercetools.api.models.category.CategoryReference;
import com.commercetools.api.models.category.CategoryReferenceBuilder;
import com.commercetools.api.models.common.CentPrecisionMoneyDraft;
import com.commercetools.api.models.common.CentPrecisionMoneyDraftBuilder;
import com.commercetools.api.models.custom_object.CustomObjectDraft;
import com.commercetools.api.models.custom_object.CustomObjectDraftBuilder;
import com.commercetools.api.models.error.ErrorResponse;
import com.commercetools.api.models.error.ErrorResponseBuilder;
import com.commercetools.sync.customobjects.CustomObjectSync;
import com.commercetools.sync.customobjects.CustomObjectSyncOptions;
import com.commercetools.sync.customobjects.CustomObjectSyncOptionsBuilder;
import com.commercetools.sync.customobjects.helpers.CustomObjectCompositeIdentifier;
import com.commercetools.sync.customobjects.helpers.CustomObjectSyncStatistics;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.vrap.rmf.base.client.ApiHttpMethod;
import io.vrap.rmf.base.client.ApiHttpResponse;
import io.vrap.rmf.base.client.error.BadGatewayException;
import io.vrap.rmf.base.client.error.NotFoundException;
import io.vrap.rmf.base.client.utils.CompletableFutureUtils;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletionException;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@SuppressWarnings("unchecked")
public class CustomObjectSyncIT {
private static final String CUSTOM_OBJECT_KEY_1 = "key1";
private static final String CUSTOM_OBJECT_CONTAINER_1 = "container1";
private final ObjectNode CUSTOM_OBJECT_VALUE_JSON_1 =
JsonNodeFactory.instance.objectNode().put("name", "value1");
@BeforeEach
void setup() {
deleteCustomObject(CTP_TARGET_CLIENT, CUSTOM_OBJECT_KEY_1, CUSTOM_OBJECT_CONTAINER_1);
deleteCustomObject(CTP_TARGET_CLIENT, "key2", "container2");
createCustomObject(
CTP_TARGET_CLIENT,
CUSTOM_OBJECT_KEY_1,
CUSTOM_OBJECT_CONTAINER_1,
CUSTOM_OBJECT_VALUE_JSON_1);
}
@AfterAll
static void tearDown() {
deleteCustomObject(CTP_TARGET_CLIENT, "key1", "container1");
deleteCustomObject(CTP_TARGET_CLIENT, "key2", "container2");
}
@Test
void sync_withNewCustomObject_shouldCreateCustomObject() {
final CustomObjectSyncOptions customObjectSyncOptions =
CustomObjectSyncOptionsBuilder.of(CTP_TARGET_CLIENT).build();
final CustomObjectSync customObjectSync = new CustomObjectSync(customObjectSyncOptions);
final ObjectNode customObject2Value =
JsonNodeFactory.instance.objectNode().put("name", "value1");
final CustomObjectDraft customObjectDraft =
CustomObjectDraftBuilder.of()
.container("container2")
.key("key2")
.value(customObject2Value)
.build();
final CustomObjectSyncStatistics customObjectSyncStatistics =
customObjectSync
.sync(Collections.singletonList(customObjectDraft))
.toCompletableFuture()
.join();
assertThat(customObjectSyncStatistics).hasValues(1, 1, 0, 0);
}
@Test
void sync_withExistingCustomObjectThatHasDifferentJsonValue_shouldUpdateCustomObject() {
final CustomObjectSyncOptions customObjectSyncOptions =
CustomObjectSyncOptionsBuilder.of(CTP_TARGET_CLIENT).build();
final CustomObjectSync customObjectSync = new CustomObjectSync(customObjectSyncOptions);
final ObjectNode customObject2Value =
JsonNodeFactory.instance.objectNode().put("name", "value2");
final CustomObjectDraft customObjectDraft =
CustomObjectDraftBuilder.of()
.container(CUSTOM_OBJECT_CONTAINER_1)
.key(CUSTOM_OBJECT_KEY_1)
.value(customObject2Value)
.build();
final CustomObjectSyncStatistics customObjectSyncStatistics =
customObjectSync
.sync(Collections.singletonList(customObjectDraft))
.toCompletableFuture()
.join();
assertThat(customObjectSyncStatistics).hasValues(1, 0, 1, 0);
}
@Test
void sync_withExistingCustomObjectThatHasDifferentMoneyValue_shouldUpdateCustomObject() {
final CentPrecisionMoneyDraft originalMoneyValue =
CentPrecisionMoneyDraftBuilder.of()
.centAmount(100L)
.currencyCode("EUR")
.fractionDigits(2)
.build();
// Change value of exiting CustomObject before test
createCustomObject(
CTP_TARGET_CLIENT, CUSTOM_OBJECT_KEY_1, CUSTOM_OBJECT_CONTAINER_1, originalMoneyValue);
final CustomObjectSyncOptions customObjectSyncOptions =
CustomObjectSyncOptionsBuilder.of(CTP_TARGET_CLIENT).build();
final CustomObjectSync customObjectSync = new CustomObjectSync(customObjectSyncOptions);
final CentPrecisionMoneyDraft newMoneyValue =
CentPrecisionMoneyDraftBuilder.of()
.centAmount(200L)
.currencyCode("EUR")
.fractionDigits(2)
.build();
final CustomObjectDraft customObjectDraft =
CustomObjectDraftBuilder.of()
.container(CUSTOM_OBJECT_CONTAINER_1)
.key(CUSTOM_OBJECT_KEY_1)
.value(newMoneyValue)
.build();
final CustomObjectSyncStatistics customObjectSyncStatistics =
customObjectSync
.sync(Collections.singletonList(customObjectDraft))
.toCompletableFuture()
.join();
assertThat(customObjectSyncStatistics).hasValues(1, 0, 1, 0);
}
@Test
void sync_withExistingCustomObjectThatHasSameJsonValue_shouldNotUpdateCustomObject() {
final CustomObjectDraft customObjectDraft =
CustomObjectDraftBuilder.of()
.container(CUSTOM_OBJECT_CONTAINER_1)
.key(CUSTOM_OBJECT_KEY_1)
.value(CUSTOM_OBJECT_VALUE_JSON_1)
.build();
final CustomObjectSyncOptions customObjectSyncOptions =
CustomObjectSyncOptionsBuilder.of(CTP_TARGET_CLIENT).build();
final CustomObjectSync customObjectSync = new CustomObjectSync(customObjectSyncOptions);
final CustomObjectSyncStatistics customObjectSyncStatistics =
customObjectSync
.sync(Collections.singletonList(customObjectDraft))
.toCompletableFuture()
.join();
assertThat(customObjectSyncStatistics).hasValues(1, 0, 0, 0);
}
@Test
void
sync_withChangedCustomObjectAndConcurrentModificationException_shouldRetryAndUpdateCustomObject() {
final ProjectApiRoot mockClient =
buildClientWithConcurrentModificationAndOptionalExceptionOnFetch(null);
final List<String> errorCallBackMessages = new ArrayList<>();
final List<String> warningCallBackMessages = new ArrayList<>();
final List<Throwable> errorCallBackExceptions = new ArrayList<>();
final CustomObjectSyncOptions spyOptions =
CustomObjectSyncOptionsBuilder.of(mockClient)
.errorCallback(
(exception, oldResource, newResource, updateActions) -> {
errorCallBackMessages.add(exception.getMessage());
errorCallBackExceptions.add(exception.getCause());
})
.build();
final CustomObjectSync customObjectSync = new CustomObjectSync(spyOptions);
final CategoryReference newCustomObjectValue =
CategoryReferenceBuilder.of().id("category-id").build();
final CustomObjectDraft customObjectDraft =
CustomObjectDraftBuilder.of()
.container(CUSTOM_OBJECT_CONTAINER_1)
.key(CUSTOM_OBJECT_KEY_1)
.value(newCustomObjectValue)
.build();
// test
final CustomObjectSyncStatistics customObjectSyncStatistics =
customObjectSync
.sync(Collections.singletonList(customObjectDraft))
.toCompletableFuture()
.join();
assertThat(customObjectSyncStatistics).hasValues(1, 0, 1, 0);
Assertions.assertThat(errorCallBackExceptions).isEmpty();
Assertions.assertThat(errorCallBackMessages).isEmpty();
Assertions.assertThat(warningCallBackMessages).isEmpty();
}
@Test
void sync_withChangedCustomObjectWithBadGatewayExceptionInsideUpdateRetry_shouldFailToUpdate() {
final ErrorResponse errorResponse =
ErrorResponseBuilder.of()
.statusCode(500)
.errors(Collections.emptyList())
.message("test")
.build();
final String responseJsonString = getResponseJsonString(errorResponse);
final ProjectApiRoot mockClient =
buildClientWithConcurrentModificationAndOptionalExceptionOnFetch(responseJsonString);
final List<String> errorCallBackMessages = new ArrayList<>();
final List<Throwable> errorCallBackExceptions = new ArrayList<>();
final CustomObjectSyncOptions spyOptions =
CustomObjectSyncOptionsBuilder.of(mockClient)
.errorCallback(
(exception, oldResource, newResource, updateActions) -> {
errorCallBackMessages.add(exception.getMessage());
errorCallBackExceptions.add(exception.getCause());
})
.build();
final CustomObjectSync customObjectSync = new CustomObjectSync(spyOptions);
final ObjectNode newCustomObjectValue =
JsonNodeFactory.instance.objectNode().put("name", "value2");
final CustomObjectDraft customObjectDraft =
CustomObjectDraftBuilder.of()
.container(CUSTOM_OBJECT_CONTAINER_1)
.key(CUSTOM_OBJECT_KEY_1)
.value(newCustomObjectValue)
.build();
final CustomObjectSyncStatistics customObjectSyncStatistics =
customObjectSync
.sync(Collections.singletonList(customObjectDraft))
.toCompletableFuture()
.join();
assertThat(customObjectSyncStatistics).hasValues(1, 0, 0, 1);
Assertions.assertThat(errorCallBackMessages).hasSize(1);
Assertions.assertThat(errorCallBackExceptions).hasSize(1);
Assertions.assertThat(errorCallBackMessages.get(0))
.contains(
format(
"Failed to update custom object with key: '%s'. Reason: Failed to fetch from CTP while retrying "
+ "after concurrency modification.",
CustomObjectCompositeIdentifier.of(customObjectDraft)));
}
@Test
void sync_withConcurrentModificationExceptionAndUnexpectedDelete_shouldFailToReFetchAndUpdate() {
final ErrorResponse errorResponse =
ErrorResponseBuilder.of()
.statusCode(404)
.errors(Collections.emptyList())
.message("test")
.build();
final String responseJsonString = getResponseJsonString(errorResponse);
final ProjectApiRoot mockClient =
buildClientWithConcurrentModificationAndOptionalExceptionOnFetch(responseJsonString);
final List<String> errorCallBackMessages = new ArrayList<>();
final List<Throwable> errorCallBackExceptions = new ArrayList<>();
final CustomObjectSyncOptions spyOptions =
CustomObjectSyncOptionsBuilder.of(mockClient)
.errorCallback(
(exception, oldResource, newResource, updateActions) -> {
errorCallBackMessages.add(exception.getMessage());
errorCallBackExceptions.add(exception.getCause());
})
.build();
final CustomObjectSync customObjectSync = new CustomObjectSync(spyOptions);
final ObjectNode newCustomObjectValue =
JsonNodeFactory.instance.objectNode().put("name", "value2");
final CustomObjectDraft customObjectDraft =
CustomObjectDraftBuilder.of()
.container(CUSTOM_OBJECT_CONTAINER_1)
.key(CUSTOM_OBJECT_KEY_1)
.value(newCustomObjectValue)
.build();
final CustomObjectSyncStatistics customObjectSyncStatistics =
customObjectSync
.sync(Collections.singletonList(customObjectDraft))
.toCompletableFuture()
.join();
assertThat(customObjectSyncStatistics).hasValues(1, 0, 0, 1);
Assertions.assertThat(errorCallBackMessages).hasSize(1);
Assertions.assertThat(errorCallBackExceptions).hasSize(1);
Assertions.assertThat(errorCallBackMessages.get(0))
.contains(
format(
"Failed to update custom object with key: '%s'. Reason: Not found when attempting to fetch while"
+ " retrying after concurrency modification.",
CustomObjectCompositeIdentifier.of(customObjectDraft)));
}
@Test
void sync_withNewCustomObjectAndBadRequest_shouldNotCreateButHandleError() {
final ProjectApiRoot mockClient = buildClientWithExceptionOnUpsert();
final ObjectNode newCustomObjectValue =
JsonNodeFactory.instance.objectNode().put("name", "value2");
final CustomObjectDraft customObjectDraft =
CustomObjectDraftBuilder.of()
.container("container2")
.key("key2")
.value(newCustomObjectValue)
.build();
final List<String> errorCallBackMessages = new ArrayList<>();
final List<Throwable> errorCallBackExceptions = new ArrayList<>();
final CustomObjectSyncOptions spyOptions =
CustomObjectSyncOptionsBuilder.of(mockClient)
.errorCallback(
(exception, oldResource, newResource, updateActions) -> {
errorCallBackMessages.add(exception.getMessage());
errorCallBackExceptions.add(exception.getCause());
})
.build();
final CustomObjectSync customObjectSync = new CustomObjectSync(spyOptions);
final CustomObjectSyncStatistics customObjectSyncStatistics =
customObjectSync
.sync(Collections.singletonList(customObjectDraft))
.toCompletableFuture()
.join();
assertThat(customObjectSyncStatistics).hasValues(1, 0, 0, 1);
Assertions.assertThat(errorCallBackMessages).hasSize(1);
Assertions.assertThat(errorCallBackExceptions).hasSize(1);
Assertions.assertThat(errorCallBackExceptions.get(0))
.isExactlyInstanceOf(CompletionException.class);
Assertions.assertThat(errorCallBackExceptions.get(0).getCause())
.isExactlyInstanceOf(BadGatewayException.class);
Assertions.assertThat(errorCallBackMessages.get(0))
.contains(
format(
"Failed to create custom object with key: '%s'.",
CustomObjectCompositeIdentifier.of(customObjectDraft)));
}
@Nonnull
private ProjectApiRoot buildClientWithConcurrentModificationAndOptionalExceptionOnFetch(
@Nullable final String responseString) {
// Reference assignment to have an atomic string reference
final String responseAsJson = responseString;
// Helps to count invocation of a request and used to decide execution or mocking response
final AtomicInteger postRequestInvocationCounter = new AtomicInteger(0);
final AtomicInteger getRequestInvocationCounter = new AtomicInteger(0);
final ProjectApiRoot testClient =
ApiRootBuilder.of(
request -> {
final String uri = request.getUri() != null ? request.getUri().toString() : "";
final ApiHttpMethod method = request.getMethod();
if (uri.contains("custom-objects") && ApiHttpMethod.POST.equals(method)) {
if (postRequestInvocationCounter.getAndIncrement() == 0) {
return CompletableFutureUtils.exceptionallyCompletedFuture(
createConcurrentModificationException());
}
}
if (uri.contains("custom-objects")
&& ApiHttpMethod.GET.equals(method)
&& responseAsJson != null) {
if (getRequestInvocationCounter.getAndIncrement() > 0) {
if (responseAsJson.contains("500")) {
return CompletableFutureUtils.exceptionallyCompletedFuture(
new BadGatewayException(
500,
"",
null,
"",
new ApiHttpResponse<>(
500, null, responseAsJson.getBytes(StandardCharsets.UTF_8))));
} else if (responseAsJson.contains("404")) {
return CompletableFutureUtils.exceptionallyCompletedFuture(
new NotFoundException(
404,
"",
null,
"",
new ApiHttpResponse<>(
404, null, responseAsJson.getBytes(StandardCharsets.UTF_8))));
}
}
}
return CTP_TARGET_CLIENT.getApiHttpClient().execute(request);
})
.withApiBaseUrl(CTP_TARGET_CLIENT.getApiHttpClient().getBaseUri())
.build(CTP_TARGET_CLIENT.getProjectKey());
return testClient;
}
@Nonnull
private ProjectApiRoot buildClientWithExceptionOnUpsert() {
// Helps to count invocation of a request and used to decide execution or mocking response
final AtomicInteger requestInvocationCounter = new AtomicInteger(0);
final ProjectApiRoot testClient =
ApiRootBuilder.of(
request -> {
final String uri = request.getUri() != null ? request.getUri().toString() : "";
final ApiHttpMethod method = request.getMethod();
if (uri.contains("custom-objects") && ApiHttpMethod.POST.equals(method)) {
if (requestInvocationCounter.getAndIncrement() == 0) {
return CompletableFutureUtils.exceptionallyCompletedFuture(
createBadGatewayException());
}
}
return CTP_TARGET_CLIENT.getApiHttpClient().execute(request);
})
.withApiBaseUrl(CTP_TARGET_CLIENT.getApiHttpClient().getBaseUri())
.build(CTP_TARGET_CLIENT.getProjectKey());
return testClient;
}
private String getResponseJsonString(@Nonnull final Object response) {
final ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json;
try {
json = ow.writeValueAsString(response);
} catch (JsonProcessingException e) {
// ignore the error
json = null;
}
return json;
}
}