forked from folio-org/mod-circulation-storage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTenantRefApiTests.java
656 lines (546 loc) · 24.5 KB
/
TenantRefApiTests.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
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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
package org.folio.rest.api;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.any;
import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl;
import static com.github.tomakehurst.wiremock.client.WireMock.created;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.ok;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.serverError;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
import static java.lang.String.format;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
import static org.folio.HttpStatus.HTTP_CREATED;
import static org.folio.rest.jaxrs.model.Request.Status.CLOSED_CANCELLED;
import static org.folio.rest.jaxrs.model.Request.Status.CLOSED_FILLED;
import static org.folio.rest.jaxrs.model.Request.Status.CLOSED_PICKUP_EXPIRED;
import static org.folio.rest.jaxrs.model.Request.Status.CLOSED_UNFILLED;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import org.apache.commons.io.IOUtils;
import org.folio.postgres.testing.PostgresTesterContainer;
import org.folio.rest.RestVerticle;
import org.folio.rest.client.TenantClient;
import org.folio.rest.jaxrs.model.Parameter;
import org.folio.rest.jaxrs.model.Request;
import org.folio.rest.jaxrs.model.TenantAttributes;
import org.folio.rest.jaxrs.model.TenantJob;
import org.folio.rest.persist.PostgresClient;
import org.folio.rest.tools.utils.NetworkUtils;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import com.github.tomakehurst.wiremock.stubbing.StubMapping;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.Future;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import io.vertx.ext.web.client.WebClient;
import io.vertx.sqlclient.Row;
import io.vertx.sqlclient.RowSet;
@RunWith(VertxUnitRunner.class)
public class TenantRefApiTests {
protected static final String TLR_MIGRATION_OLD_MODULE_VERSION = "13.0.0";
protected static final String TLR_MIGRATION_PREV_MODULE_VERSION = "13.1.0";
protected static final String TLR_MIGRATION_MODULE_VERSION = "14.0.0";
protected static final String TLR_MIGRATION_NEXT_MODULE_VERSION = "14.1.0";
protected static final String REQ_SEARCH_MIGRATION_OLD_MOD_VER = "15.0.0";
protected static final String REQ_SEARCH_MIGRATION_PREV_MOD_VER = "16.0.0";
protected static final String REQ_SEARCH_MIGRATION_MOD_VER = "16.1.0";
protected static final String REQ_SEARCH_MIGRATION_NEXT_MOD_VER = "16.2.0";
protected static final String MODULE_NAME = "mod_circulation_storage";
protected static final int PORT = NetworkUtils.nextFreePort();
protected static final String URL = "http://localhost:" + PORT;
protected static final String TENANT = "test_tenant";
protected static final String REQUEST_TABLE_NAME = "request";
protected static final String REQUEST_TABLE =
format("%s_%s.%s", TENANT, MODULE_NAME, REQUEST_TABLE_NAME);
protected static final String TOKEN = generateToken();
private static final int GET_TENANT_TIMEOUT_MS = 10000;
private static final String ITEM_STORAGE_URL = "/item-storage/items";
private static final String HOLDINGS_STORAGE_URL = "/holdings-storage/holdings";
private static final String SERVICE_PINTS_STORAGE_URL = "/service-points";
private static final String ANY_URL_PARAMS_REGEX_TEMPLATE = "\\?.*";
private static final String FAIL_SECOND_CALL_SCENARIO = "Test scenario";
private static final String FIRST_CALL_MADE_SCENARIO_STATE = "First call made";
private static final String DEFAULT_UUID = "00000000-0000-4000-8000-000000000000";
private static StubMapping itemStorageStub;
private static StubMapping holdingsStorageStub;
private static StubMapping servicePointsStorageStub;
private static List<JsonObject> items;
private static List<JsonObject> holdingRecords;
private static List<JsonObject> servicePoints;
protected static Vertx vertx;
protected static TenantClient tenantClient;
protected static PostgresClient postgresClient;
protected static String jobId;
private static Map<String, JsonObject> requestsBeforeMigration = new HashMap<>();
@ClassRule
public static WireMockRule wireMock = new WireMockRule(
new WireMockConfiguration().dynamicPort());
@BeforeClass
public static void beforeAll(final TestContext context) throws Exception {
Async async = context.async();
vertx = Vertx.vertx();
tenantClient = new TenantClient("http://localhost:" + wireMock.port(), TENANT, TOKEN,
WebClient.create(vertx));
PostgresClient.setPostgresTester(new PostgresTesterContainer());
StorageTestSuite.before();
DeploymentOptions deploymentOptions = new DeploymentOptions()
.setConfig(new JsonObject().put("http.port", PORT));
mockEndpoints();
vertx.deployVerticle(RestVerticle.class.getName(), deploymentOptions)
.compose(r -> postTenant(context, TLR_MIGRATION_OLD_MODULE_VERSION, TLR_MIGRATION_PREV_MODULE_VERSION))
.onFailure(context::fail)
.onSuccess(r -> {
postgresClient = PostgresClient.getInstance(vertx, TENANT);
async.complete();
});
}
@Before
public void beforeEach(TestContext context) throws Exception {
Async async = context.async();
loadRequests()
.compose(r -> getAllRequestsAsJson())
.onFailure(context::fail)
.onSuccess(requests -> {
requestsBeforeMigration = requests.stream()
.collect(toMap(TenantRefApiTests::getId, identity()));
// Need to reset all mocks before each test because some tests can remove stubs to mimic
// a failure on other modules' side
mockEndpoints();
async.complete();
});
}
@AfterClass
public static void afterAll(final TestContext context) throws Exception {
deleteTenant(tenantClient);
StorageTestSuite.after();
Async async = context.async();
vertx.close(context.asyncAssertSuccess(res -> {
PostgresClient.stopPostgresTester();
async.complete();
}));
}
@Test
public void tlrMigrationShouldBeSkippedWhenUpgradingToLowerVersion(final TestContext context) {
Async async = context.async();
postTenant(context, TLR_MIGRATION_OLD_MODULE_VERSION, TLR_MIGRATION_PREV_MODULE_VERSION)
.onSuccess(job -> {
assertThatNoRequestsWereUpdatedByTlrMigration(context);
async.complete();
});
}
@Test
public void tlrMigrationShouldBeSkippedWhenUpgradingFromAlreadyMigratedVersion(
final TestContext context) {
Async async = context.async();
postTenant(context, TLR_MIGRATION_MODULE_VERSION, TLR_MIGRATION_NEXT_MODULE_VERSION)
.onSuccess(job -> {
assertThatNoRequestsWereUpdatedByTlrMigration(context);
async.complete();
});
}
@Test
public void jobCompletedWhenTlrMigrationIsSuccessful(TestContext context) {
Async async = context.async();
postTenant(context, TLR_MIGRATION_PREV_MODULE_VERSION, TLR_MIGRATION_MODULE_VERSION)
.onSuccess(job -> {
context.assertNull(job.getError());
validateTlrMigrationResult(context, async);
});
}
@Test
public void requestSearchMigrationShouldBeSkippedWhenUpgradingToLowerVersion(final TestContext context) {
Async async = context.async();
postTenant(context, REQ_SEARCH_MIGRATION_OLD_MOD_VER, REQ_SEARCH_MIGRATION_PREV_MOD_VER)
.onSuccess(job -> {
assertThatNoRequestsWereUpdatedByRequestSearchMigration(context);
async.complete();
});
}
@Test
public void requestSearchMigrationShouldBeSkippedWhenUpgradingFromAlreadyMigratedVersion(
final TestContext context) {
Async async = context.async();
postTenant(context, REQ_SEARCH_MIGRATION_MOD_VER, REQ_SEARCH_MIGRATION_NEXT_MOD_VER)
.onSuccess(job -> {
assertThatNoRequestsWereUpdatedByRequestSearchMigration(context);
async.complete();
});
}
@Test
public void jobCompletedWhenRequestSearchMigrationIsSuccessful(TestContext context) {
Async async = context.async();
postTenant(context, REQ_SEARCH_MIGRATION_PREV_MOD_VER, REQ_SEARCH_MIGRATION_MOD_VER)
.onSuccess(job -> {
context.assertNull(job.getError());
validateRequestSearchMigrationResult(context, async);
});
}
@Test
public void tlrMigrationFailsWhenItemStorageCallFails(TestContext context) {
Async async = context.async();
wireMock.removeStub(itemStorageStub);
tlrMigrationFailsWhenRemoteCallFails(context, async);
}
@Test
public void tlrMigrationFailsWhenHoldingsStorageCallFails(TestContext context) {
Async async = context.async();
wireMock.removeStub(holdingsStorageStub);
tlrMigrationFailsWhenRemoteCallFails(context, async);
}
@Test
public void tlrMigrationFailsWhenItemWasNotFound(final TestContext context) {
Async async = context.async();
wireMock.removeStub(itemStorageStub);
tlrMigrationFailsWhenRemoteCallFails(context, async);
}
private void tlrMigrationFailsWhenRemoteCallFails(TestContext context, Async async) {
postTenant(context, TLR_MIGRATION_PREV_MODULE_VERSION, TLR_MIGRATION_MODULE_VERSION)
.onSuccess(job -> {
context.assertTrue(job.getError().contains("Request failed: GET"));
context.assertTrue(job.getError().contains("Response: [404]"));
assertThatNoRequestsWereUpdatedByTlrMigration(context);
async.complete();
});
}
////
@Test
public void requestSearchMigrationFailsWhenItemStorageCallFails(TestContext context) {
Async async = context.async();
wireMock.removeStub(itemStorageStub);
requestSearchMigrationFailsWhenRemoteCallFails(context, async);
}
@Test
public void requestSearchMigrationFailsWhenServicePointsStorageCallFails(TestContext context) {
Async async = context.async();
wireMock.removeStub(servicePointsStorageStub);
requestSearchMigrationFailsWhenRemoteCallFails(context, async);
}
private void requestSearchMigrationFailsWhenRemoteCallFails(TestContext context, Async async) {
postTenant(context, REQ_SEARCH_MIGRATION_PREV_MOD_VER, REQ_SEARCH_MIGRATION_MOD_VER)
.onSuccess(job -> {
context.assertTrue(job.getError().contains("Request failed: GET"));
context.assertTrue(job.getError().contains("Response: [404]"));
assertThatNoRequestsWereUpdatedByRequestSearchMigration(context);
async.complete();
});
}
///
@Test
public void useDefaultValuesForInstanceIdAndHoldingsRecordIdWhenItemWasNotFound(TestContext context) {
Async async = context.async();
JsonObject randomRequest = requestsBeforeMigration.values()
.stream()
.findAny()
.orElseThrow();
randomRequest.put("itemId", UUID.randomUUID());
String requestId = getId(randomRequest);
postgresClient.update(REQUEST_TABLE_NAME, randomRequest, requestId)
.compose(r -> postTenant(context, TLR_MIGRATION_PREV_MODULE_VERSION, TLR_MIGRATION_MODULE_VERSION))
.compose(job -> getRequestAsJson(requestId))
.onFailure(context::fail)
.onSuccess(updatedRequest -> {
context.assertEquals(DEFAULT_UUID, updatedRequest.getString("instanceId"));
context.assertEquals(DEFAULT_UUID, updatedRequest.getString("holdingsRecordId"));
validateTlrMigrationResult(context, async);
});
}
@Test
public void changesMadeForAllBatchesAreRevertedInCaseOfError(TestContext context) {
Async async = context.async();
wireMock.removeStub(itemStorageStub);
// first batch - return valid response
wireMock.stubFor(get(urlMatching(ITEM_STORAGE_URL + ANY_URL_PARAMS_REGEX_TEMPLATE))
.atPriority(0)
.inScenario(FAIL_SECOND_CALL_SCENARIO)
.willReturn(ok().withBody(new JsonObject().put("items", new JsonArray(items)).encodePrettily()))
.willSetStateTo(FIRST_CALL_MADE_SCENARIO_STATE));
// second batch - return 500
wireMock.stubFor(get(urlMatching(ITEM_STORAGE_URL + ANY_URL_PARAMS_REGEX_TEMPLATE))
.atPriority(0)
.inScenario(FAIL_SECOND_CALL_SCENARIO)
.whenScenarioStateIs(FIRST_CALL_MADE_SCENARIO_STATE)
.willReturn(serverError()));
postTenant(context, TLR_MIGRATION_PREV_MODULE_VERSION, TLR_MIGRATION_MODULE_VERSION)
.onSuccess(job -> {
context.assertFalse(job.getError().isEmpty());
assertThatNoRequestsWereUpdatedByTlrMigration(context);
async.complete();
});
}
@Test
public void jobFailsWhenRequestAlreadyHasTitleLevelRequestField(TestContext context) {
Async async = context.async();
JsonObject randomRequest = requestsBeforeMigration.values()
.stream()
.findAny()
.orElseThrow();
randomRequest.put("requestLevel", "item");
jobFailsWhenRequestValidationFails(context, async, randomRequest,
"request already contains TLR fields: " + getId(randomRequest));
}
@Test
public void jobFailsWhenRequestDoesNotHaveRequiredItemLevelRequestField(TestContext context) {
Async async = context.async();
JsonObject randomRequest = requestsBeforeMigration.values()
.stream()
.findAny()
.orElseThrow();
randomRequest.remove("itemId");
jobFailsWhenRequestValidationFails(context, async, randomRequest,
"request does not contain required ILR fields: " + getId(randomRequest));
}
@Test
public void migrationRemovesPositionFromClosedRequests(TestContext context) {
Async async = context.async();
List<String> closedStatuses = Stream.of(CLOSED_FILLED, CLOSED_UNFILLED, CLOSED_PICKUP_EXPIRED,
CLOSED_CANCELLED)
.map(Request.Status::value)
.collect(toList());
postTenant(context, TLR_MIGRATION_PREV_MODULE_VERSION, TLR_MIGRATION_MODULE_VERSION)
.compose(job -> getAllRequestsAsJson())
.onFailure(context::fail)
.onSuccess(requestsAfterMigration -> {
requestsAfterMigration.forEach(request -> {
Integer position = request.getInteger("position");
if (closedStatuses.contains(request.getString("status"))) {
context.assertNull(position);
} else {
context.assertNotNull(position);
}
async.complete();
});
});
}
private void jobFailsWhenRequestValidationFails(TestContext context, Async async,
JsonObject request, String expectedErrorMessage) {
postgresClient.update(REQUEST_TABLE_NAME, request, getId(request))
.compose(r -> postTenant(context, TLR_MIGRATION_PREV_MODULE_VERSION, TLR_MIGRATION_MODULE_VERSION))
.onFailure(context::fail)
.onSuccess(job -> {
context.assertTrue(job.getError().contains(expectedErrorMessage));
assertThatNoRequestsWereUpdatedByTlrMigration(context);
async.complete();
});
}
private static Future<TenantJob> postTenant(TestContext context, String fromVersion,
String toVersion) {
return tenantClient.postTenant(getTenantAttributes(fromVersion, toVersion))
.onSuccess(response -> context.assertEquals(response.statusCode(), HTTP_CREATED.toInt()))
.map(response -> response.bodyAsJson(TenantJob.class))
.compose(job -> tenantClient.getTenantByOperationId(job.getId(), GET_TENANT_TIMEOUT_MS))
.map(response -> response.bodyAsJson(TenantJob.class))
.onSuccess(job -> context.assertTrue(job.getComplete()))
.onFailure(context::fail);
}
private static void assertThatNoRequestsWereUpdatedByTlrMigration(TestContext context) {
selectRead("SELECT COUNT(*) " +
"FROM " + REQUEST_TABLE + " " +
"WHERE jsonb->>'requestLevel' IS NOT null")
.onFailure(context::fail)
.onSuccess(rowSet -> context.assertEquals(0, getCount(rowSet)));
}
private static void assertThatNoRequestsWereUpdatedByRequestSearchMigration(TestContext context) {
selectRead("SELECT COUNT(*) " +
"FROM " + REQUEST_TABLE + " " +
"WHERE jsonb->>'searchIndex' IS NOT null")
.onFailure(context::fail)
.onSuccess(rowSet -> context.assertEquals(0, getCount(rowSet)));
}
private static Future<List<JsonObject>> getAllRequestsAsJson() {
return selectRead("SELECT * FROM " + REQUEST_TABLE)
.map(rowSet -> StreamSupport.stream(rowSet.spliterator(), false)
.map(row -> row.getJsonObject("jsonb"))
.collect(toList()));
}
private static Future<RowSet<Row>> selectRead(String sql) {
return Future.future(promise -> postgresClient.selectRead(sql, 0, promise));
}
private static Future<JsonObject> getRequestAsJson(String requestId) {
return postgresClient.getById(REQUEST_TABLE_NAME, requestId);
}
private void validateTlrMigrationResult(TestContext context, Async async) {
getAllRequestsAsJson()
.onFailure(context::fail)
.onSuccess(requestsAfterMigration -> {
context.assertEquals(requestsBeforeMigration.size(), requestsAfterMigration.size());
requestsAfterMigration.forEach(request -> validateTlrMigrationResult(context, request));
async.complete();
});
}
private void validateTlrMigrationResult(TestContext context, JsonObject requestAfter) {
JsonObject requestBefore = requestsBeforeMigration.get(getId(requestAfter));
context.assertNotNull(requestBefore);
context.assertNotNull(requestAfter);
context.assertEquals(requestAfter.getString("requestLevel"), "Item");
context.assertNotNull(requestAfter.getString("instanceId"));
context.assertNotNull(requestAfter.getString("holdingsRecordId"));
if (requestBefore.containsKey("item")) {
JsonObject itemBefore = requestBefore.getJsonObject("item");
JsonObject itemAfter = requestAfter.getJsonObject("item");
JsonObject instance = requestAfter.getJsonObject("instance");
if (itemBefore.containsKey("title")) {
context.assertEquals(instance.getString("title"), itemBefore.getString("title"));
}
if (itemBefore.containsKey("identifiers")) {
context.assertEquals(instance.getJsonArray("identifiers"), itemBefore.getJsonArray("identifiers"));
}
context.assertFalse(itemAfter.containsKey("title"));
context.assertFalse(itemAfter.containsKey("identifiers"));
}
}
private void validateRequestSearchMigrationResult(TestContext context, Async async) {
getAllRequestsAsJson()
.onFailure(context::fail)
.onSuccess(requestsAfterMigration -> {
context.assertEquals(requestsBeforeMigration.size(), requestsAfterMigration.size());
requestsAfterMigration.forEach(request -> validateRequestSearchMigrationResult(context, request));
async.complete();
});
}
private void validateRequestSearchMigrationResult(TestContext context, JsonObject requestAfter) {
JsonObject requestBefore = requestsBeforeMigration.get(getId(requestAfter));
context.assertNotNull(requestBefore);
context.assertNotNull(requestAfter);
if (requestBefore.containsKey("pickupServicePointId")) {
context.assertEquals("testSpName", requestAfter.getJsonObject("searchIndex")
.getString("pickupServicePointName"));
}
context.assertEquals("testShelvingOrder", requestAfter.getJsonObject("searchIndex")
.getString("shelvingOrder"));
context.assertEquals("testCallNumber", requestAfter.getJsonObject("searchIndex")
.getJsonObject("callNumberComponents").getString("callNumber"));
context.assertEquals("testPrefix", requestAfter.getJsonObject("searchIndex")
.getJsonObject("callNumberComponents").getString("prefix"));
context.assertEquals("testSuffix", requestAfter.getJsonObject("searchIndex")
.getJsonObject("callNumberComponents").getString("suffix"));
}
static void deleteTenant(TenantClient tenantClient) {
CompletableFuture<Void> future = new CompletableFuture<>();
tenantClient.deleteTenantByOperationId(jobId, deleted -> {
if (deleted.failed()) {
future.completeExceptionally(new RuntimeException("Failed to delete tenant"));
return;
}
future.complete(null);
});
}
private static void mockEndpoints() {
items = new ArrayList<>();
holdingRecords = new ArrayList<>();
servicePoints = new ArrayList<>();
requestsBeforeMigration.values()
.forEach(request -> {
final String holdingsRecordId = randomId();
final String servicePointId = request.getString("pickupServicePointId");
items.add(new JsonObject()
.put("id", request.getString("itemId"))
.put("holdingsRecordId", holdingsRecordId)
.put("effectiveShelvingOrder", "testShelvingOrder")
.put("effectiveCallNumberComponents", new JsonObject()
.put("callNumber", "testCallNumber")
.put("prefix", "testPrefix")
.put("suffix", "testSuffix")
));
holdingRecords.add(new JsonObject()
.put("id", holdingsRecordId)
.put("instanceId", randomId()));
if (servicePointId != null) {
boolean servicePointDoesNotExists = servicePoints.stream()
.noneMatch(sp -> sp.getString("id").equals(servicePointId));
if (servicePointDoesNotExists) {
servicePoints.add(new JsonObject()
.put("id", servicePointId)
.put("name", "testSpName"));
}
}
});
String itemsResponse = new JsonObject()
.put("items", new JsonArray(items))
.encodePrettily();
String holdingRecordsResponse = new JsonObject()
.put("holdingsRecords", new JsonArray(holdingRecords))
.encodePrettily();
String servicePointsResponse = new JsonObject()
.put("servicepoints", new JsonArray(servicePoints))
.encodePrettily();
wireMock.resetAll();
wireMock.stubFor(post(urlEqualTo("/pubsub/event-types"))
.willReturn(created()));
wireMock.stubFor(post(urlEqualTo("/pubsub/event-types?"))
.willReturn(created()));
wireMock.stubFor(post(urlMatching("/pubsub/event-types/declare/(publisher|subscriber)"))
.willReturn(created()));
itemStorageStub = wireMock.stubFor(
get(urlMatching(ITEM_STORAGE_URL + ANY_URL_PARAMS_REGEX_TEMPLATE))
.willReturn(ok().withBody(itemsResponse)));
holdingsStorageStub = wireMock.stubFor(
get(urlMatching(HOLDINGS_STORAGE_URL + ANY_URL_PARAMS_REGEX_TEMPLATE))
.willReturn(ok().withBody(holdingRecordsResponse)));
servicePointsStorageStub = wireMock.stubFor(
get(urlMatching(SERVICE_PINTS_STORAGE_URL + ANY_URL_PARAMS_REGEX_TEMPLATE))
.willReturn(ok().withBody(servicePointsResponse)));
wireMock.stubFor(any(anyUrl())
.atPriority(Integer.MAX_VALUE)
.willReturn(aResponse().proxiedFrom(URL)));
}
protected static TenantAttributes getTenantAttributes(String moduleFrom, String moduleTo) {
final Parameter loadReferenceParameter = new Parameter()
.withKey("loadReference").withValue("true");
return new TenantAttributes()
.withModuleFrom(format("%s-%s", MODULE_NAME, moduleFrom))
.withModuleTo(format("%s-%s", MODULE_NAME, moduleTo))
.withParameters(Collections.singletonList(loadReferenceParameter));
}
protected static Future<List<String>> loadRequests() throws Exception {
InputStream tableInput = TenantRefApiTests.class.getClassLoader().getResourceAsStream(
"mocks/TlrDataMigrationTestData.sql");
String sqlFile = IOUtils.toString(Objects.requireNonNull(tableInput), StandardCharsets.UTF_8);
return postgresClient.runSQLFile(sqlFile, true);
}
private static String generateToken() {
final String payload = new JsonObject()
.put("user_id", randomId())
.put("tenant", TENANT)
.put("sub", "admin")
.toString();
return format("1.%s.3", Base64.getEncoder()
.encodeToString(payload.getBytes()));
}
protected static String randomId() {
return UUID.randomUUID().toString();
}
private static int getCount(RowSet<Row> rowSet) {
return rowSet.iterator()
.next()
.get(Integer.class, 0);
}
private static String getId(JsonObject jsonObject) {
return jsonObject.getString("id");
}
}