@relaybus/testing 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,9 +1,9 @@
1
1
  'use strict';
2
2
 
3
+ var chunkIOWTZMTG_cjs = require('./chunk-IOWTZMTG.cjs');
3
4
  var vitest = require('vitest');
4
5
  var core = require('@relaybus/core');
5
6
 
6
- // src/event-store-contract.ts
7
7
  function createDeferred() {
8
8
  let resolve;
9
9
  const promise = new Promise((onResolve) => {
@@ -1244,6 +1244,103 @@ function lostLeasesContract(suite) {
1244
1244
  });
1245
1245
  });
1246
1246
  }
1247
+ function unsortedPayload() {
1248
+ return {
1249
+ zulu: "last letter first",
1250
+ b: { yankee: [{ zz: 1, a: 2, mm: { q: null, c: true } }, [], {}], alpha: {} },
1251
+ longestKeyOfTheObject: 1,
1252
+ a: '\xE7\u011F\u0131\xF6\u015F\xFC \u{1F680} \u2028 "quoted" \\ tab ',
1253
+ exponent: 1e21,
1254
+ tiny: 5e-324,
1255
+ fraction: 0.1 + 0.2,
1256
+ negative: -42.5,
1257
+ maxSafe: Number.MAX_SAFE_INTEGER,
1258
+ minSafe: Number.MIN_SAFE_INTEGER,
1259
+ emptyObject: {},
1260
+ emptyArray: [],
1261
+ "7": "integer-like key",
1262
+ mixed: ["z", { d: 4, c: 3 }, 0, false, null]
1263
+ };
1264
+ }
1265
+ function payloadFidelityContract(suite) {
1266
+ const { append, claim } = suite;
1267
+ vitest.describe("payload fidelity", () => {
1268
+ vitest.it("hands out the payload and headers with their key order, as published", async () => {
1269
+ const event = createEnvelope({
1270
+ payload: unsortedPayload(),
1271
+ headers: { zz: "last", traceparent: "00-abc-def-01", a: "first", tenant: "acme" }
1272
+ });
1273
+ await append([{ event, deliveries: [createDelivery("handler-a")] }]);
1274
+ const [claimed] = await claim(["handler-a"]);
1275
+ vitest.expect(JSON.stringify(claimed.event.payload)).toBe(JSON.stringify(event.payload));
1276
+ vitest.expect(JSON.stringify(claimed.event.headers)).toBe(JSON.stringify(event.headers));
1277
+ });
1278
+ vitest.it("keeps the order of a payload appended in a batch and of a top-level array", async () => {
1279
+ const object = createEnvelope({ payload: unsortedPayload() });
1280
+ const list = createEnvelope({ payload: [{ zz: 1, a: { y: 2, b: 1 } }, "x", 1e21] });
1281
+ const scalar = createEnvelope({ payload: "plain text" });
1282
+ await append([
1283
+ { event: object, deliveries: [createDelivery("handler-a", at(1))] },
1284
+ { event: list, deliveries: [createDelivery("handler-a", at(2))] },
1285
+ { event: scalar, deliveries: [createDelivery("handler-a", at(3))] }
1286
+ ]);
1287
+ const claimed = await claim(["handler-a"], at(10));
1288
+ vitest.expect(claimed.map((delivery) => JSON.stringify(delivery.event.payload))).toEqual(
1289
+ [object, list, scalar].map((event) => JSON.stringify(event.payload))
1290
+ );
1291
+ });
1292
+ vitest.it("keeps the order for a handler added to an event that already exists", async () => {
1293
+ const event = createEnvelope({ payload: unsortedPayload() });
1294
+ await append([{ event, deliveries: [createDelivery("handler-a")] }]);
1295
+ await append([{ event, deliveries: [createDelivery("handler-b")] }]);
1296
+ const [claimed] = await claim(["handler-b"]);
1297
+ vitest.expect(JSON.stringify(claimed.event.payload)).toBe(JSON.stringify(event.payload));
1298
+ });
1299
+ });
1300
+ }
1301
+ function transactionIsolationContract(suite) {
1302
+ let store;
1303
+ vitest.beforeEach(() => {
1304
+ store = suite.store();
1305
+ });
1306
+ vitest.describe("transaction isolation levels", () => {
1307
+ vitest.it("recognizes no unrelated error as a serialization failure", () => {
1308
+ for (const error of [new Error("boom"), void 0, null, "text", { code: "23505" }]) {
1309
+ vitest.expect(store.isSerializationFailure?.(error) ?? false).toBe(false);
1310
+ }
1311
+ });
1312
+ vitest.it("commits and rolls back at every level it lists", async () => {
1313
+ for (const isolationLevel of store.isolationLevels ?? []) {
1314
+ const committed = createEnvelope();
1315
+ await store.transaction(
1316
+ (transaction) => store.append(
1317
+ transaction,
1318
+ [{ event: committed, deliveries: [createDelivery("h")] }],
1319
+ /* @__PURE__ */ new Date(0)
1320
+ ),
1321
+ { timeoutMs: 5e3, isolationLevel }
1322
+ );
1323
+ const abandoned = createEnvelope();
1324
+ await vitest.expect(
1325
+ store.transaction(
1326
+ async (transaction) => {
1327
+ await store.append(
1328
+ transaction,
1329
+ [{ event: abandoned, deliveries: [createDelivery("h")] }],
1330
+ /* @__PURE__ */ new Date(0)
1331
+ );
1332
+ throw new Error(`rolled back at ${isolationLevel}`);
1333
+ },
1334
+ { timeoutMs: 5e3, isolationLevel }
1335
+ )
1336
+ ).rejects.toThrow(`rolled back at ${isolationLevel}`);
1337
+ const stored = (await store.listDeliveries({})).map((delivery) => delivery.event.id);
1338
+ vitest.expect(stored).toContain(committed.id);
1339
+ vitest.expect(stored).not.toContain(abandoned.id);
1340
+ }
1341
+ });
1342
+ });
1343
+ }
1247
1344
 
1248
1345
  // src/event-store-contract.ts
1249
1346
  function eventStoreContract(name, options) {
@@ -1292,6 +1389,8 @@ function eventStoreContract(name, options) {
1292
1389
  orderingAndLeasesContract(suite);
1293
1390
  completionContract(suite);
1294
1391
  lostLeasesContract(suite);
1392
+ payloadFidelityContract(suite);
1393
+ transactionIsolationContract(suite);
1295
1394
  });
1296
1395
  }
1297
1396
 
@@ -1360,6 +1459,8 @@ var FakeClock = class {
1360
1459
  var InMemoryTransport = class {
1361
1460
  name;
1362
1461
  published = [];
1462
+ /** Wire names (event type to name) that routes and catalogs declared; the transport sends events as they are. */
1463
+ declaredWireTypes = {};
1363
1464
  #subscribers = /* @__PURE__ */ new Map();
1364
1465
  #failNextPublishes = 0;
1365
1466
  connected = false;
@@ -1370,6 +1471,11 @@ var InMemoryTransport = class {
1370
1471
  async connect() {
1371
1472
  this.connected = true;
1372
1473
  }
1474
+ declareWireTypes(wireTypes) {
1475
+ return () => {
1476
+ Object.assign(this.declaredWireTypes, wireTypes);
1477
+ };
1478
+ }
1373
1479
  /** Makes the next `count` publishes reject, simulating a broker outage. */
1374
1480
  failNextPublishes(count) {
1375
1481
  this.#failNextPublishes = count;
@@ -1406,186 +1512,52 @@ var InMemoryTransport = class {
1406
1512
  }
1407
1513
  };
1408
1514
  async function deliverWithRedeliveries(handler, delivery) {
1409
- for (let attempt2 = 0; ; attempt2 += 1) {
1515
+ for (let attempt = 0; ; attempt += 1) {
1410
1516
  try {
1411
1517
  await handler(delivery.envelope, { destination: delivery.destination });
1412
- return attempt2 + 1;
1518
+ return attempt + 1;
1413
1519
  } catch (error) {
1414
- if (attempt2 >= delivery.maxRedeliveries) {
1520
+ if (attempt >= delivery.maxRedeliveries) {
1415
1521
  throw error;
1416
1522
  }
1417
1523
  }
1418
1524
  }
1419
1525
  }
1420
- function toBuffer(bytes) {
1421
- return typeof bytes === "string" ? Buffer.from(bytes, "utf8") : Buffer.from(bytes);
1422
- }
1423
- function canonicalJson(value) {
1424
- return JSON.stringify(sortKeys(JSON.parse(JSON.stringify(value) ?? "null")));
1425
- }
1426
- function sortKeys(value) {
1427
- if (Array.isArray(value)) {
1428
- return value.map(sortKeys);
1429
- }
1430
- if (typeof value !== "object" || value === null) {
1431
- return value;
1432
- }
1433
- return Object.fromEntries(
1434
- Object.keys(value).sort().map((name) => [name, sortKeys(value[name])])
1435
- );
1436
- }
1437
- function compareBodies(label, {
1438
- expected,
1439
- encoded,
1440
- comparison
1441
- }) {
1442
- const text = (bytes) => bytes === null ? "null" : toBuffer(bytes).toString("utf8");
1443
- const same = expected === null || encoded === null ? expected === encoded : comparison === "json" ? canonicalJson(JSON.parse(text(expected))) === canonicalJson(JSON.parse(text(encoded))) : toBuffer(expected).equals(toBuffer(encoded));
1444
- return same ? [] : [`${label}: expected ${text(expected)}, encoded ${text(encoded)}`];
1445
- }
1446
- function compareObjects(label, {
1447
- expected,
1448
- encoded,
1449
- ignored
1450
- }) {
1451
- const kept = (object) => canonicalJson(
1452
- Object.fromEntries(Object.entries(object).filter(([name]) => !ignored.includes(name)))
1453
- );
1454
- const [left, right] = [kept(expected), kept(encoded)];
1455
- return left === right ? [] : [`${label}: expected ${left}, encoded ${right}`];
1456
- }
1457
- function compareDecoded(expected, decoded) {
1458
- const [left, right] = [canonicalJson(expected), canonicalJson(decoded)];
1459
- return left === right ? [] : [`decoded: expected ${left}, decoded ${right}`];
1460
- }
1461
- async function attempt(label, step) {
1462
- try {
1463
- return { result: await step(), mismatches: [] };
1464
- } catch (error) {
1465
- return { mismatches: [`${label} threw: ${core.toErrorInfo(error).message}`] };
1466
- }
1467
- }
1468
-
1469
- // src/codec-contract/kafka.ts
1470
- async function kafkaCodecMismatches(options, testCase) {
1471
- const { record } = testCase;
1472
- const encoding = testCase.only === "decode" ? { mismatches: [] } : await attempt("encode", () => options.encode(testCase.envelope));
1473
- const encoded = encoding.result;
1474
- const decoding = testCase.only === "encode" ? { mismatches: [] } : await attempt("decode", () => options.decode(delivered(record)));
1475
- return [
1476
- ...encoding.mismatches,
1477
- ...encoded === void 0 ? [] : compareRecords(options, { record, encoded }),
1478
- ...decoding.mismatches,
1479
- ...decoding.result === void 0 ? [] : compareDecoded(testCase.decoded ?? testCase.envelope, decoding.result)
1480
- ];
1481
- }
1482
1526
  function kafkaCodecContract(name, options) {
1483
- vitest.describe(`${name} writes and reads the captured Kafka records`, () => {
1484
- vitest.it.each(options.cases.map((testCase) => [testCase.name, testCase]))(
1485
- "%s",
1486
- async (_name, testCase) => {
1487
- vitest.expect(await kafkaCodecMismatches(options, testCase)).toEqual([]);
1488
- }
1489
- );
1490
- });
1491
- }
1492
- function compareRecords(options, {
1493
- record,
1494
- encoded
1495
- }) {
1496
- const text = (bytes) => bytes === null ? null : toBuffer(bytes).toString("utf8");
1497
- const timestamp = encoded.timestamp;
1498
- return [
1499
- ...text(record.key) === text(encoded.key) ? [] : [`key: expected ${text(record.key)}, encoded ${text(encoded.key)}`],
1500
- ...compareBodies("value", {
1501
- expected: record.value,
1502
- encoded: encoded.value,
1503
- comparison: options.compare ?? "bytes"
1504
- }),
1505
- ...compareObjects("headers", {
1506
- expected: textHeaders(record.headers ?? {}),
1507
- encoded: textHeaders(encoded.headers),
1508
- ignored: options.ignoreHeaders ?? []
1509
- }),
1510
- ...timestamp === void 0 || timestamp === record.timestamp ? [] : [`timestamp: expected ${record.timestamp}, encoded ${timestamp}`]
1511
- ];
1512
- }
1513
- function textHeaders(headers) {
1514
- return Object.fromEntries(
1515
- Object.entries(headers).map(([name, value]) => [
1516
- name,
1517
- toBuffer(Array.isArray(value) ? value.at(-1) : value).toString(
1518
- "utf8"
1519
- )
1520
- ])
1521
- );
1522
- }
1523
- function delivered(record) {
1524
- return {
1525
- topic: record.topic,
1526
- partition: record.partition ?? 0,
1527
- offset: record.offset ?? "0",
1528
- key: record.key === null ? null : toBuffer(record.key),
1529
- value: record.value === null ? null : toBuffer(record.value),
1530
- headers: Object.fromEntries(
1531
- Object.entries(record.headers ?? {}).map(([name, value]) => [name, toBuffer(value)])
1532
- ),
1533
- ...record.timestamp === void 0 ? {} : { timestamp: record.timestamp }
1534
- };
1535
- }
1536
- async function rabbitMqCodecMismatches(options, testCase) {
1537
- const { message } = testCase;
1538
- const encoding = testCase.only === "decode" ? { mismatches: [] } : await attempt("encode", () => options.encode(testCase.envelope));
1539
- const encoded = encoding.result;
1540
- const decoding = testCase.only === "encode" ? { mismatches: [] } : await attempt("decode", () => options.decode(delivered2(message)));
1541
- return [
1542
- ...encoding.mismatches,
1543
- ...encoded === void 0 ? [] : compareMessages(options, { message, encoded }),
1544
- ...decoding.mismatches,
1545
- ...decoding.result === void 0 ? [] : compareDecoded(testCase.decoded ?? testCase.envelope, decoding.result)
1546
- ];
1527
+ chunkIOWTZMTG_cjs.registerKafkaCodecContract({ describe: vitest.describe, it: vitest.it }, { name, options });
1547
1528
  }
1548
1529
  function rabbitMqCodecContract(name, options) {
1549
- vitest.describe(`${name} writes and reads the captured RabbitMQ messages`, () => {
1550
- vitest.it.each(options.cases.map((testCase) => [testCase.name, testCase]))(
1551
- "%s",
1552
- async (_name, testCase) => {
1553
- vitest.expect(await rabbitMqCodecMismatches(options, testCase)).toEqual([]);
1554
- }
1555
- );
1556
- });
1557
- }
1558
- function compareMessages(options, {
1559
- message,
1560
- encoded
1561
- }) {
1562
- const { headers, ...properties } = encoded.options;
1563
- return [
1564
- ...compareObjects("properties", {
1565
- expected: message.properties ?? {},
1566
- encoded: properties,
1567
- ignored: options.ignoreProperties ?? []
1568
- }),
1569
- ...compareObjects("headers", {
1570
- expected: message.headers ?? {},
1571
- encoded: headers ?? {},
1572
- ignored: options.ignoreHeaders ?? []
1573
- }),
1574
- ...compareBodies("body", {
1575
- expected: message.body,
1576
- encoded: encoded.content,
1577
- comparison: options.compare ?? "bytes"
1578
- })
1579
- ];
1580
- }
1581
- function delivered2(message) {
1582
- return {
1583
- content: toBuffer(message.body),
1584
- fields: { routingKey: message.routingKey },
1585
- properties: { ...message.properties, headers: { ...message.headers } }
1586
- };
1530
+ chunkIOWTZMTG_cjs.registerRabbitMqCodecContract({ describe: vitest.describe, it: vitest.it }, { name, options });
1587
1531
  }
1588
1532
 
1533
+ Object.defineProperty(exports, "CodecContractError", {
1534
+ enumerable: true,
1535
+ get: function () { return chunkIOWTZMTG_cjs.CodecContractError; }
1536
+ });
1537
+ Object.defineProperty(exports, "assertKafkaCodecCase", {
1538
+ enumerable: true,
1539
+ get: function () { return chunkIOWTZMTG_cjs.assertKafkaCodecCase; }
1540
+ });
1541
+ Object.defineProperty(exports, "assertRabbitMqCodecCase", {
1542
+ enumerable: true,
1543
+ get: function () { return chunkIOWTZMTG_cjs.assertRabbitMqCodecCase; }
1544
+ });
1545
+ Object.defineProperty(exports, "kafkaCodecMismatches", {
1546
+ enumerable: true,
1547
+ get: function () { return chunkIOWTZMTG_cjs.kafkaCodecMismatches; }
1548
+ });
1549
+ Object.defineProperty(exports, "rabbitMqCodecMismatches", {
1550
+ enumerable: true,
1551
+ get: function () { return chunkIOWTZMTG_cjs.rabbitMqCodecMismatches; }
1552
+ });
1553
+ Object.defineProperty(exports, "registerKafkaCodecContract", {
1554
+ enumerable: true,
1555
+ get: function () { return chunkIOWTZMTG_cjs.registerKafkaCodecContract; }
1556
+ });
1557
+ Object.defineProperty(exports, "registerRabbitMqCodecContract", {
1558
+ enumerable: true,
1559
+ get: function () { return chunkIOWTZMTG_cjs.registerRabbitMqCodecContract; }
1560
+ });
1589
1561
  exports.FakeClock = FakeClock;
1590
1562
  exports.InMemoryTransport = InMemoryTransport;
1591
1563
  exports.at = at;
@@ -1593,8 +1565,6 @@ exports.createDelivery = createDelivery;
1593
1565
  exports.createEnvelope = createEnvelope;
1594
1566
  exports.eventStoreContract = eventStoreContract;
1595
1567
  exports.kafkaCodecContract = kafkaCodecContract;
1596
- exports.kafkaCodecMismatches = kafkaCodecMismatches;
1597
1568
  exports.rabbitMqCodecContract = rabbitMqCodecContract;
1598
- exports.rabbitMqCodecMismatches = rabbitMqCodecMismatches;
1599
1569
  //# sourceMappingURL=index.cjs.map
1600
1570
  //# sourceMappingURL=index.cjs.map