@onify/fake-amqplib 0.8.2

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.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +67 -0
  3. package/index.js +410 -0
  4. package/package.json +45 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2021 Onify
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,67 @@
1
+ Onify fake-amqplib
2
+ ==================
3
+
4
+ [![Built latest](https://github.com/onify/fake-amqplib/actions/workflows/build-latest.yaml/badge.svg)](https://github.com/onify/fake-amqplib/actions/workflows/build-latest.yaml)
5
+
6
+ Mocked version of https://www.npmjs.com/package/amqplib.
7
+
8
+ ### Overriding amqplib
9
+
10
+ You might want to override `amqplib` with `@onify/fake-amqplib` in tests. This can be done this way:
11
+
12
+ ```javascript
13
+ const amqplib = require('amqplib');
14
+ const fakeAmqp = require('@onify/fake-amqplib');
15
+
16
+ amqplib.connect = fakeAmqp.connect;
17
+ ```
18
+
19
+ If you are using version 2 or higher of [exp-amqp-connection](https://www.npmjs.com/package/exp-amqp-connection)
20
+ you can use [mock-require](https://www.npmjs.com/package/mock-require) to replace `amqplib` with `@onify/fake-amqplib` in your tests like this:
21
+
22
+ ```javascript
23
+ const mock = require('mock-require');
24
+ const fakeAmqp = require('@onify/fake-amqplib');
25
+
26
+ mock('amqplib/callback_api', fakeAmqp);
27
+ ```
28
+
29
+ or just mock the entire amqplib with
30
+
31
+ ```javascript
32
+ const mock = require('mock-require');
33
+ const fakeAmqp = require('@onify/fake-amqplib');
34
+
35
+ mock('amqplib', fakeAmqp);
36
+ ```
37
+
38
+ ### RabbitMQ versions
39
+
40
+ Some behaviour differs between versions. To specify your version of RabbitMQ you can call `setVersion(minorVersionFloatOrString)`. Default version is 3.5.
41
+
42
+ Example:
43
+ ```js
44
+ var fakeAmqp = require('@onify/fake-amqplib');
45
+
46
+ // prepare your connections
47
+ (async () => {
48
+ fakeAmqp.setVersion('2.2');
49
+ const conn2 = await fakeAmqp.connect('amqp://rabbit2-2');
50
+
51
+ fakeAmqp.setVersion('3.2');
52
+ const conn3 = await fakeAmqp.connect('amqp://rabbit3-1');
53
+
54
+ fakeAmqp.setVersion('3.7');
55
+ const conn37 = await fakeAmqp.connect('amqp://rabbit3-7');
56
+ })()
57
+ ```
58
+
59
+ ### Fake api
60
+
61
+ List of available methods and a property
62
+
63
+ - `connections`: property with all faked connections
64
+ - `connectSync(amqpurl[, ...otherOptions])`: helper method to create a connection without waiting for promise to resolve - synchronous
65
+ - `resetMock()`: reset all connections and brokers
66
+ - `setVersion(minor)`: next connection will be to a amqp of a specific version
67
+ - `async connect(amqpurl[, ...otherOptions, callback])`: make a fake connection
package/index.js ADDED
@@ -0,0 +1,410 @@
1
+ 'use strict';
2
+
3
+ const {Broker} = require('smqp');
4
+ const {EventEmitter} = require('events');
5
+ const {URL} = require('url');
6
+
7
+ class FakeAmqpError extends Error {
8
+ constructor(message, code, killChannel, killConnection) {
9
+ super(message);
10
+ this.code = code;
11
+ this._killChannel = killChannel;
12
+ this._killConnection = killConnection;
13
+ }
14
+ }
15
+
16
+ class FakeAmqpNotFoundError extends FakeAmqpError {
17
+ constructor(type, name, killConnection = false) {
18
+ super(`Channel closed by server: 404 (NOT-FOUND) with message "NOT_FOUND - no ${type} '${name}' in vhost '/'`, 404, true, killConnection);
19
+ }
20
+ }
21
+
22
+ const connections = [];
23
+
24
+ module.exports = Fake('3.5');
25
+
26
+ function Fake(minorVersion) {
27
+ let defaultVersion = Number(minorVersion);
28
+ return {
29
+ connections,
30
+ resetMock,
31
+ connectSync,
32
+ setVersion(minor) {
33
+ const n = Number(minor);
34
+ if (!isNaN(n)) defaultVersion = n;
35
+ },
36
+ connect,
37
+ };
38
+
39
+ function connect(amqpUrl, ...args) {
40
+ const connection = connectSync(amqpUrl, ...args);
41
+ return resolveOrCallback(args.slice(-1)[0], null, connection);
42
+ }
43
+
44
+ function connectSync(amqpUrl, ...args) {
45
+ const {_broker} = connections.find((conn) => compareConnectionString(conn.options[0], amqpUrl)) || {};
46
+ const broker = _broker || Broker();
47
+ const connection = Connection(broker, defaultVersion, amqpUrl, ...args);
48
+ connections.push(connection);
49
+ return connection;
50
+ }
51
+
52
+ function resetMock() {
53
+ for (const connection of connections.splice(0)) {
54
+ connection._broker.reset();
55
+ }
56
+ }
57
+
58
+ function Connection(broker, version, ...connArgs) {
59
+ const emitter = new EventEmitter();
60
+ const options = connArgs.filter((a) => typeof a !== 'function');
61
+ let closed = false;
62
+ const channels = [];
63
+
64
+ return {
65
+ _id: generateId(),
66
+ _broker: broker,
67
+ _version: version,
68
+ get _closed() {
69
+ return closed;
70
+ },
71
+ get _emitter() {
72
+ return emitter;
73
+ },
74
+ options,
75
+ createChannel(...args) {
76
+ if (closed) return resolveOrCallback(args.slice(-1)[0], unavailable());
77
+
78
+ const channel = Channel(broker, this);
79
+ channels.push(channel);
80
+ return resolveOrCallback(args.slice(-1)[0], null, channel);
81
+ },
82
+ createConfirmChannel(...args) {
83
+ if (closed) return resolveOrCallback(args.slice(-1)[0], unavailable());
84
+
85
+ const channel = Channel(broker, this, true);
86
+ channels.push(channel);
87
+ return resolveOrCallback(args.slice(-1)[0], null, channel);
88
+ },
89
+ async close(...args) {
90
+ closed = true;
91
+
92
+ const idx = connections.indexOf(this);
93
+ if (idx > -1) connections.splice(idx, 1);
94
+ channels.splice(0).forEach((channel) => channel.close());
95
+
96
+ emitter.emit('close');
97
+
98
+ return resolveOrCallback(args.slice(-1)[0]);
99
+ },
100
+ on(...args) {
101
+ return emitter.on(...args);
102
+ },
103
+ once(...args) {
104
+ return emitter.once(...args);
105
+ },
106
+ };
107
+
108
+ function unavailable() {
109
+ return new FakeAmqpError('Connection closed: 504', 504);
110
+ }
111
+ }
112
+
113
+ function Channel(broker, connection, confirmChannel) {
114
+ let closed = false, prefetch = 10000;
115
+ const emitter = new EventEmitter();
116
+ const channelName = 'channel-' + generateId();
117
+ const version = connection._version;
118
+
119
+ broker.on('return', emitReturn);
120
+
121
+ return {
122
+ _broker: broker,
123
+ _version: version,
124
+ get _emitter() {
125
+ return emitter;
126
+ },
127
+ get _closed() {
128
+ return closed;
129
+ },
130
+ assertExchange(...args) {
131
+ return callBroker(assertExchange, ...args);
132
+
133
+ function assertExchange(exchange, ...args) {
134
+ broker.assertExchange(exchange, ...args);
135
+ return {
136
+ exchange,
137
+ };
138
+ }
139
+ },
140
+ assertQueue(...args) {
141
+ return callBroker(assertQueue, ...args);
142
+
143
+ function assertQueue(queueName, ...args) {
144
+ const name = queueName ? queueName : 'amqp.gen-' + generateId();
145
+ const options = typeof args[0] === 'object' ? args.shift() : {};
146
+ const queue = broker.assertQueue(queueName, {...options, _connectionId: connection._id}, ...args);
147
+ return {
148
+ ...(!queueName ? {queue: name} : undefined),
149
+ messageCount: queue.messageCount,
150
+ consumerCount: queue.consumerCount,
151
+ };
152
+ }
153
+ },
154
+ bindExchange(destination, source, ...args) {
155
+ return Promise.all([this.checkExchange(source), this.checkExchange(destination)]).then(() => {
156
+ return callBroker(broker.bindExchange, source, destination, ...args);
157
+ });
158
+ },
159
+ bindQueue(queue, source, ...args) {
160
+ return Promise.all([this.checkQueue(queue), this.checkExchange(source)]).then(() => {
161
+ return callBroker(broker.bindQueue, queue, source, ...args);
162
+ });
163
+ },
164
+ checkExchange(name, ...args) {
165
+ return callBroker(check, ...args);
166
+
167
+ function check() {
168
+ if (!broker.getExchange(name)) throw new FakeAmqpError(`Channel closed by server: 404 (NOT-FOUND) with message "NOT_FOUND - no exchange '${name}' in vhost '/'`, 404, true);
169
+ return true;
170
+ }
171
+ },
172
+ checkQueue(name, ...args) {
173
+ return callBroker(check, ...args);
174
+
175
+ function check() {
176
+ let queue;
177
+ if (!(queue = broker.getQueue(name))) {
178
+ throw new FakeAmqpNotFoundError('queue', name);
179
+ }
180
+
181
+ return {
182
+ messageCount: queue.messageCount,
183
+ consumerCount: queue.consumerCount,
184
+ };
185
+ }
186
+ },
187
+ get(queue, ...args) {
188
+ return callBroker(getMessage, ...args);
189
+
190
+ function getMessage(...getargs) {
191
+ const q = broker.getQueue(queue);
192
+ if (!q) throw new FakeAmqpNotFoundError('queue');
193
+ return q.get(...getargs) || false;
194
+ }
195
+ },
196
+ deleteExchange(exchange, ...args) {
197
+ return callBroker(check, ...args);
198
+
199
+ function check() {
200
+ const result = broker.deleteExchange(exchange, ...args);
201
+ if (!result && version < 3.2) throw new FakeAmqpNotFoundError('exchange', exchange);
202
+ return result;
203
+ }
204
+ },
205
+ deleteQueue(queue, ...args) {
206
+ return callBroker(check, ...args);
207
+
208
+ function check() {
209
+ const result = broker.deleteQueue(queue, ...args);
210
+ if (!result && version < 3.2) throw new FakeAmqpNotFoundError('queue', queue);
211
+ return result;
212
+ }
213
+ },
214
+ publish(exchange, routingKey, content, options, callback) {
215
+ if (!Buffer.isBuffer(content)) throw new TypeError('content is not a buffer');
216
+ if (confirmChannel) {
217
+ options = {...options, confirm: makeConfirmCallback(callback)};
218
+ }
219
+
220
+ this.checkExchange(exchange).then(() => {
221
+ return callBroker(broker.publish, exchange, routingKey, content, options);
222
+ }).catch((err) => {
223
+ emitter.emit('error', err);
224
+ });
225
+
226
+ return true;
227
+ },
228
+ purgeQueue(queue, ...args) {
229
+ return callBroker(check, ...args);
230
+
231
+ function check() {
232
+ const result = broker.purgeQueue(queue);
233
+ if (!result && version < 3.2) throw new FakeAmqpNotFoundError('queue', queue);
234
+ return result === undefined ? undefined : {messageCount: result};
235
+ }
236
+ },
237
+ sendToQueue(queue, content, options, callback) {
238
+ if (!Buffer.isBuffer(content)) throw new TypeError('content is not a buffer');
239
+ if (confirmChannel) {
240
+ options = {...options, confirm: makeConfirmCallback(callback)};
241
+ }
242
+
243
+ this.checkQueue(queue).then(() => {
244
+ return callBroker(broker.sendToQueue, queue, content, options);
245
+ }).catch((err) => {
246
+ emitter.emit('error', err);
247
+ });
248
+
249
+ return true;
250
+ },
251
+ unbindExchange(destination, source, pattern, ...args) {
252
+ return callBroker(check, ...args);
253
+
254
+ function check() {
255
+ const q = broker.getExchange(destination);
256
+ if (!q) throw new FakeAmqpNotFoundError('exchange', destination);
257
+
258
+ const exchange = broker.getExchange(source);
259
+ if (!exchange) throw new FakeAmqpNotFoundError('exchange', source);
260
+
261
+ const result = broker.unbindExchange(source, destination, pattern);
262
+ if (!result && version <= 3.2) throw new FakeAmqpNotFoundError('binding', pattern);
263
+
264
+ return true;
265
+ }
266
+ },
267
+ unbindQueue(queue, source, pattern, ...args) {
268
+ return callBroker(check, ...args);
269
+
270
+ function check() {
271
+ const q = broker.getQueue(queue);
272
+ if (!q) throw new FakeAmqpNotFoundError('queue', queue);
273
+
274
+ const exchange = broker.getExchange(source);
275
+ if (!exchange) throw new FakeAmqpNotFoundError('exchange', source);
276
+
277
+ const binding = exchange.getBinding(queue, pattern);
278
+ if (!binding && version <= 3.2) throw new FakeAmqpNotFoundError('binding', pattern, version < 3.2);
279
+
280
+ broker.unbindQueue(queue, source, pattern);
281
+ return true;
282
+ }
283
+ },
284
+ consume(queue, onMessage, options = {}, callback) {
285
+ return callBroker(check, callback);
286
+
287
+ function check() {
288
+ const q = queue && broker.getQueue(queue);
289
+ if (queue && !q) {
290
+ throw new FakeAmqpNotFoundError('queue', queue);
291
+ }
292
+
293
+ if (q) {
294
+ if (q.exclusive || (q.options.exclusive && q.options._connectionId !== connection._id)) {
295
+ throw new FakeAmqpError(`Channel closed by server: 403 (ACCESS-REFUSED) with message "ACCESS_REFUSED - queue '${queue}' in vhost '/' in exclusive use"`, 403, true, true);
296
+ }
297
+ }
298
+
299
+ const {consumerTag} = broker.consume(queue, onMessage && handler, {...options, channelName, prefetch});
300
+ return {consumerTag};
301
+ }
302
+
303
+ function handler(_, msg) {
304
+ onMessage(msg);
305
+ }
306
+ },
307
+ cancel(consumerTag, ...args) {
308
+ return callBroker(broker.cancel, consumerTag, ...args);
309
+ },
310
+ close(callback) {
311
+ if (closed) return;
312
+ broker.off('return', emitReturn);
313
+ const channelConsumers = broker.getConsumers().filter((f) => f.options.channelName === channelName);
314
+ channelConsumers.forEach((c) => broker.cancel(c.consumerTag));
315
+ closed = true;
316
+ emitter.emit('close');
317
+ return resolveOrCallback(callback);
318
+ },
319
+ ack: broker.ack,
320
+ ackAll: broker.ackAll,
321
+ ...(version >= 2.3 ? {
322
+ nack(message, ...args) {
323
+ return broker.nack(message, ...args);
324
+ }
325
+ } : undefined),
326
+ reject: broker.reject,
327
+ nackAll: broker.nackAll,
328
+ prefetch(val) {
329
+ prefetch = val;
330
+ },
331
+ on(...args) {
332
+ return emitter.on(...args);
333
+ },
334
+ once(...args) {
335
+ return emitter.once(...args);
336
+ },
337
+ };
338
+
339
+ function makeConfirmCallback(callback) {
340
+ const confirm = 'msg.' + generateId();
341
+ const consumerTag = 'ct-' + confirm;
342
+ broker.on('message.*', onConsumeMessage, {consumerTag});
343
+
344
+ function onConsumeMessage(event) {
345
+ if (event.properties.confirm !== confirm) return;
346
+
347
+ switch(event.name) {
348
+ case 'message.nack':
349
+ return confirmCallback(new Error('message nacked'));
350
+ case 'message.undelivered':
351
+ return confirmCallback(new Error('message undelivered'));
352
+ case 'message.ack':
353
+ return confirmCallback(null, true);
354
+ }
355
+
356
+ function confirmCallback(err, ok) {
357
+ broker.off('message.*', {consumerTag});
358
+ callback(err, ok);
359
+ }
360
+ }
361
+
362
+ return confirm;
363
+ }
364
+
365
+ function callBroker(fn, ...args) {
366
+ let [poppedCb] = args.slice(-1);
367
+ if (typeof poppedCb === 'function') args.splice(-1);
368
+ else poppedCb = null;
369
+
370
+ if (connection._closed) throw new FakeAmqpError('Connection is closed', 504);
371
+ if (closed) throw new Error('Channel is closed');
372
+
373
+ return new Promise((resolve, reject) => {
374
+ try {
375
+ const result = fn.call(broker, ...args);
376
+ if (poppedCb) poppedCb(null, result);
377
+ return resolve(result);
378
+ } catch (err) {
379
+ if (err._killConnection) connection.close();
380
+ else if (err._killChannel) closed = true;
381
+ if (!poppedCb) return reject(err);
382
+ poppedCb(err);
383
+ return resolve();
384
+ }
385
+ });
386
+ }
387
+
388
+ function emitReturn({fields, content, properties}) {
389
+ process.nextTick(() => {
390
+ emitter.emit('return', {fields, content, properties});
391
+ });
392
+ }
393
+ }
394
+ }
395
+
396
+ function resolveOrCallback(optionalCb, err, ...args) {
397
+ if (typeof optionalCb === 'function') optionalCb(err, ...args);
398
+ if (err) return Promise.reject(err);
399
+ return Promise.resolve(...args);
400
+ }
401
+
402
+ function generateId() {
403
+ return Math.random().toString(16).substring(2, 12);
404
+ }
405
+
406
+ function compareConnectionString(url1, url2) {
407
+ const parsedUrl1 = new URL(url1);
408
+ const parsedUrl2 = new URL(url2);
409
+ return parsedUrl1.host === parsedUrl2.host && parsedUrl1.pathname === parsedUrl2.pathname;
410
+ }
package/package.json ADDED
@@ -0,0 +1,45 @@
1
+ {
2
+ "name": "@onify/fake-amqplib",
3
+ "version": "0.8.2",
4
+ "description": "Fake amqplib",
5
+ "main": "index.js",
6
+ "scripts": {
7
+ "test": "mocha",
8
+ "posttest": "eslint . --cache",
9
+ "cov:html": "nyc mocha && nyc report --reporter=html"
10
+ },
11
+ "author": {
12
+ "name": "Onify",
13
+ "url": "https://github.com/onify"
14
+ },
15
+ "engines": {
16
+ "node": ">=10"
17
+ },
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git://github.com/onify/fake-amqplib.git"
21
+ },
22
+ "license": "MIT",
23
+ "dependencies": {
24
+ "smqp": "^5.0.0"
25
+ },
26
+ "keywords": [
27
+ "fake",
28
+ "mock",
29
+ "amqp",
30
+ "amqplib",
31
+ "rabbitmq"
32
+ ],
33
+ "devDependencies": {
34
+ "chai": "^4.2.0",
35
+ "eslint": "^7.32.0",
36
+ "mocha": "^9.1.1",
37
+ "nyc": "^15.1.0"
38
+ },
39
+ "files": [
40
+ "index.js"
41
+ ],
42
+ "directories": {
43
+ "test": "test"
44
+ }
45
+ }