forked from folio-org/mod-circulation-storage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRequestBatchAPITest.java
342 lines (270 loc) · 12.5 KB
/
RequestBatchAPITest.java
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
package org.folio.rest.api;
import static org.folio.rest.api.RequestsApiTest.requestStorageUrl;
import static org.folio.rest.api.StorageTestSuite.TENANT_ID;
import static org.folio.rest.api.StorageTestSuite.storageUrl;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.is;
import java.net.URL;
import java.util.Arrays;
import java.util.Comparator;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import org.folio.rest.impl.RequestsBatchAPI;
import org.folio.rest.jaxrs.model.Request;
import org.folio.rest.support.ApiTests;
import org.folio.rest.support.JsonResponse;
import org.folio.rest.support.Response;
import org.folio.rest.support.ResponseHandler;
import org.folio.rest.support.TextResponse;
import org.folio.rest.support.builders.RequestRequestBuilder;
import org.hamcrest.Matcher;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.client.HttpResponse;
public class RequestBatchAPITest extends ApiTests {
@Before
public void beforeEach() throws Exception {
StorageTestSuite.deleteAll(requestStorageUrl());
}
@After
public void checkIdsAfterEach() {
StorageTestSuite.checkForMismatchedIDs("request");
}
@Test
public void canUpdateRequestPositionsInBatch() throws Exception {
UUID itemId = UUID.randomUUID();
JsonObject firstRequest = createRequestForItemAtPosition(itemId, 1);
JsonObject secondRequest = createRequestForItemAtPosition(itemId, 2);
ReorderRequest firstReorderRequest = new ReorderRequest(firstRequest, 2);
ReorderRequest secondReorderRequest = new ReorderRequest(secondRequest, 1);
reorderRequests(
firstReorderRequest,
secondReorderRequest
);
JsonObject requestsForItemReply = getAllRequestsForItem(itemId);
assertThat(requestsForItemReply.getInteger("totalRecords"), is(2));
JsonArray requestsFromDb = requestsForItemReply.getJsonArray("requests");
assertThat(requestsFromDb.size(), is(2));
JsonObject [] r = new JsonObject [] { requestsFromDb.getJsonObject(0), requestsFromDb.getJsonObject(1) };
if (r[0].getInteger("position") == 2) {
r = new JsonObject [] { r[1], r[0] };
}
assertThat(r[0].getInteger("position"), is(1));
assertThat(r[1].getInteger("position"), is(2));
assertThat(r[0].getString("id"), is(secondRequest.getString("id")));
assertThat(r[1].getString("id"), is(firstRequest.getString("id")));
}
@Test
public void canCloseRequestsInBatch() throws Exception {
UUID itemId = UUID.randomUUID();
JsonObject firstRequest = createRequestForItemAtPosition(itemId, 1);
JsonObject secondRequest = createRequestForItemAtPosition(itemId, 2);
firstRequest.put("status", Request.Status.CLOSED_FILLED.value());
firstRequest.remove("position");
secondRequest.put("status", Request.Status.CLOSED_FILLED.value());
secondRequest.remove("position");
CompletableFuture<Response> postCompleted = new CompletableFuture<>();
client.post(batchRequestStorageUrl(),
buildBatchUpdateRequest(firstRequest, secondRequest),
TENANT_ID,
ResponseHandler.empty(postCompleted)
);
Response response = postCompleted.get(5, TimeUnit.SECONDS);
assertThat(response.getStatusCode(), is(201));
JsonObject allRequestsForItem = getAllRequestsForItem(itemId);
assertThat(allRequestsForItem.getInteger("totalRecords"), is(2));
JsonArray allRequests = allRequestsForItem.getJsonArray("requests");
assertEqualsWithUpdatedDateChange(firstRequest, allRequests.getJsonObject(0));
assertEqualsWithUpdatedDateChange(secondRequest, allRequests.getJsonObject(1));
}
@Test
public void canUpdateRequestFulfillmentPreferenceInBatch() throws Exception {
UUID itemId = UUID.randomUUID();
JsonObject firstRequest = createRequestForItemAtPosition(itemId, 1);
JsonObject secondRequest = createRequestForItemAtPosition(itemId, 2);
firstRequest.put("fulfillmentPreference", "Delivery");
secondRequest.put("fulfillmentPreference", "Delivery");
CompletableFuture<Response> postCompleted = new CompletableFuture<>();
client.post(batchRequestStorageUrl(),
buildBatchUpdateRequest(firstRequest, secondRequest),
TENANT_ID,
ResponseHandler.empty(postCompleted)
);
Response response = postCompleted.get(5, TimeUnit.SECONDS);
assertThat(response.getStatusCode(), is(201));
JsonObject allRequestsForItem = getAllRequestsForItem(itemId);
assertThat(allRequestsForItem.getInteger("totalRecords"), is(2));
JsonArray allRequests = allRequestsForItem.getJsonArray("requests");
assertEqualsWithUpdatedDateChange(firstRequest, allRequests.getJsonObject(0));
assertEqualsWithUpdatedDateChange(secondRequest, allRequests.getJsonObject(1));
}
@Test
public void willAbortBatchUpdateOnPopulateMetadataException() throws Exception {
CompletableFuture<TextResponse> postCompleted = new CompletableFuture<>();
new RequestsBatchAPI().postRequestStorageBatchRequests(
null, null,
result -> postCompleted.complete(new TextResponse(
result.result().getStatus(), result.result().getEntity().toString())),
null);
TextResponse response = postCompleted.get(5, TimeUnit.SECONDS);
assertThat(response.getStatusCode(), is(500));
assertThat(response.getBody(), containsString("Cannot populate metadata"));
}
@Test
public void willAbortBatchUpdateForRequestsAtTheSamePositionInAnItemsQueue() throws Exception {
UUID itemId = UUID.randomUUID();
JsonObject firstRequest = createRequestForItemAtPosition(itemId, 1);
JsonObject secondRequest = createRequestForItemAtPosition(itemId, 2);
JsonResponse reorderResponse = attemptReorderRequests(ResponseHandler::json,
new ReorderRequest(firstRequest, 1),
new ReorderRequest(secondRequest, 1)
);
assertPositionConstraintViolationError(reorderResponse);
assertRequestsNotUpdated(itemId, firstRequest, secondRequest);
}
@Test
public void willAbortBatchUpdateWhenOnlyOnePositionIsModified() throws Exception {
UUID itemId = UUID.randomUUID();
JsonObject firstRequest = createRequestForItemAtPosition(itemId, 1);
JsonObject secondRequest = createRequestForItemAtPosition(itemId, 2);
JsonResponse reorderResponse = attemptReorderRequests(ResponseHandler::json,
new ReorderRequest(firstRequest, 2)
);
assertPositionConstraintViolationError(reorderResponse);
assertRequestsNotUpdated(itemId, firstRequest, secondRequest);
}
@Test
public void willAbortBatchUpdateOnNullPointerExceptionDueToNoIdInRequest() throws Exception {
UUID itemId = UUID.randomUUID();
JsonObject firstRequest = createRequestForItemAtPosition(itemId, 1);
JsonObject secondRequest = createRequestForItemAtPosition(itemId, 2);
JsonObject firstRequestCopy = firstRequest.copy();
firstRequestCopy.remove("id");
TextResponse reorderResponse = attemptReorderRequests(ResponseHandler::text,
new ReorderRequest(firstRequestCopy, 3),
new ReorderRequest(secondRequest, 10)
);
assertThat(reorderResponse.getStatusCode(), is(500));
assertRequestsNotUpdated(itemId, firstRequest, secondRequest);
}
@Test
public void cannotInjectSqlThroughRequestId() throws Exception {
UUID itemId = UUID.randomUUID();
JsonObject firstRequest = createRequestForItemAtPosition(itemId, 1);
JsonObject firstRequestCopy = firstRequest.copy();
firstRequestCopy.put("id", "1'; DELETE FROM request where id::text is not '1");
JsonResponse reorderResponse = attemptReorderRequests(ResponseHandler::json,
new ReorderRequest(firstRequestCopy, 3)
);
assertValidationError(reorderResponse,
containsString("must match"));
assertRequestsNotUpdated(itemId, firstRequest);
}
private JsonObject getAllRequestsForItem(UUID itemId) throws Exception {
CompletableFuture<JsonResponse> getRequestsCompleted = new CompletableFuture<>();
client.get(requestStorageUrl() + String.format("?query=itemId==%s", itemId),
TENANT_ID, ResponseHandler.json(getRequestsCompleted));
return getRequestsCompleted.get(5, TimeUnit.SECONDS).getJson();
}
private JsonObject createRequestForItemAtPosition(UUID itemId, int position) throws Exception {
JsonObject request = createEntity(
new RequestRequestBuilder()
.withItemId(itemId)
.withPosition(position)
.recall()
.toHoldShelf()
.withStatus(RequestRequestBuilder.OPEN_AWAITING_PICKUP)
.create(),
requestStorageUrl()
).getJson();
assertThat(request.getString("itemId"), is(itemId.toString()));
assertThat(request.getInteger("position"), is(position));
return request;
}
private JsonObject buildBatchUpdateRequest(JsonObject... requestsToUpdate) {
return new JsonObject()
.put("requests", new JsonArray(Arrays.asList(requestsToUpdate)));
}
private URL batchRequestStorageUrl() throws Exception {
return storageUrl("/request-storage-batch/requests");
}
private <T> T attemptReorderRequests(
Function<CompletableFuture<T>, Handler<AsyncResult<HttpResponse<Buffer>>>> bodyHandler,
ReorderRequest... requests) throws Exception {
JsonObject[] requestsToReorder = Arrays.stream(requests)
.map(reorderRequest -> {
JsonObject requestCopy = reorderRequest.request.copy();
return requestCopy.put("position", reorderRequest.newPosition);
})
.toArray(JsonObject[]::new);
CompletableFuture<T> postCompleted = new CompletableFuture<>();
client.post(batchRequestStorageUrl(),
buildBatchUpdateRequest(requestsToReorder),
TENANT_ID,
bodyHandler.apply(postCompleted)
);
return postCompleted.get(5, TimeUnit.SECONDS);
}
private void reorderRequests(ReorderRequest... requests) throws Exception {
Response response = attemptReorderRequests(ResponseHandler::empty, requests);
assertThat(response.getStatusCode(), is(201));
}
private void assertRequestsNotUpdated(UUID itemId, JsonObject... requests) throws Exception {
JsonObject requestsForItemReply = getAllRequestsForItem(itemId);
assertThat(requestsForItemReply.getInteger("totalRecords"), is(requests.length));
JsonObject[] sortedExpectedRequests = Arrays.stream(requests)
.sorted(Comparator.comparingInt(rr -> rr.getInteger("position")))
.toArray(JsonObject[]::new);
JsonArray requestsFromDb = requestsForItemReply.getJsonArray("requests");
assertThat(requestsFromDb.size(), is(sortedExpectedRequests.length));
assertThat(requestsFromDb, hasItems(sortedExpectedRequests));
}
/**
* Asserts that json1 and json2 are the same with the exception of metadta.updatedDate
* String that must exists and must be different.
*/
private void assertEqualsWithUpdatedDateChange(JsonObject json1, JsonObject json2) {
String updatedDate1 = json1.getJsonObject("metadata").getString("updatedDate");
String updatedDate2 = json2.getJsonObject("metadata").getString("updatedDate");
assertThat("metadata.updatedDate should differ", updatedDate1, is(not(updatedDate2)));
JsonObject jsonStripped1 = json1.copy();
JsonObject jsonStripped2 = json2.copy();
jsonStripped1.getJsonObject("metadata").remove("updatedDate");
jsonStripped2.getJsonObject("metadata").remove("updatedDate");
assertThat(jsonStripped1, is(jsonStripped2));
}
private void assertPositionConstraintViolationError(JsonResponse response) {
assertValidationError(response,
is("Cannot have more than one request with the same position in the queue"));
}
private void assertValidationError(
JsonResponse response, Matcher<String> errorMessageMatcher) {
assertThat(response.getStatusCode(), is(422));
JsonArray errors = response.getJson().getJsonArray("errors");
assertThat(errors.size(), is(1));
assertThat(errors.getJsonObject(0).getString("message"),
errorMessageMatcher);
}
/**
* Holder for request reorder operation. Holds request and new position for it.
*/
private static class ReorderRequest {
private final JsonObject request;
private final Integer newPosition;
ReorderRequest(JsonObject request, Integer newPosition) {
this.request = request;
this.newPosition = newPosition;
}
}
}