|
| 1 | +/* eslint-env mocha */ |
| 2 | +'use strict' |
| 3 | + |
| 4 | +const { expect } = require('aegir/utils/chai') |
| 5 | +const { AbortController } = require('native-abort-controller') |
| 6 | + |
| 7 | +const f = require('./utils/factory')() |
| 8 | + |
| 9 | +describe('.pubsub', function () { |
| 10 | + this.timeout(20 * 1000) |
| 11 | + describe('.subscribe', () => { |
| 12 | + let ipfs |
| 13 | + let ctl |
| 14 | + |
| 15 | + beforeEach(async function () { |
| 16 | + this.timeout(30 * 1000) // slow CI |
| 17 | + |
| 18 | + ctl = await await f.spawn({ |
| 19 | + args: '--enable-pubsub-experiment' |
| 20 | + }) |
| 21 | + |
| 22 | + ipfs = ctl.api |
| 23 | + }) |
| 24 | + |
| 25 | + afterEach(() => f.clean()) |
| 26 | + |
| 27 | + it('.onError when connection is closed', async () => { |
| 28 | + const topic = 'gossipboom' |
| 29 | + let messageCount = 0 |
| 30 | + let onError |
| 31 | + const error = new Promise(resolve => { onError = resolve }) |
| 32 | + |
| 33 | + await ipfs.pubsub.subscribe(topic, message => { |
| 34 | + messageCount++ |
| 35 | + |
| 36 | + if (messageCount === 2) { |
| 37 | + // Stop the daemon |
| 38 | + ctl.stop().catch() |
| 39 | + } |
| 40 | + }, { |
| 41 | + onError |
| 42 | + }) |
| 43 | + |
| 44 | + await ipfs.pubsub.publish(topic, 'hello') |
| 45 | + await ipfs.pubsub.publish(topic, 'bye') |
| 46 | + |
| 47 | + await expect(error).to.eventually.be.fulfilled().and.to.be.instanceOf(Error) |
| 48 | + }) |
| 49 | + |
| 50 | + it('does not call onError when aborted', async () => { |
| 51 | + const controller = new AbortController() |
| 52 | + const topic = 'gossipabort' |
| 53 | + const messages = [] |
| 54 | + let onError |
| 55 | + let onReceived |
| 56 | + |
| 57 | + const received = new Promise(resolve => { onReceived = resolve }) |
| 58 | + const error = new Promise(resolve => { onError = resolve }) |
| 59 | + |
| 60 | + await ipfs.pubsub.subscribe(topic, message => { |
| 61 | + messages.push(message) |
| 62 | + if (messages.length === 2) { |
| 63 | + onReceived() |
| 64 | + } |
| 65 | + }, { |
| 66 | + onError, |
| 67 | + signal: controller.signal |
| 68 | + }) |
| 69 | + |
| 70 | + await ipfs.pubsub.publish(topic, 'hello') |
| 71 | + await ipfs.pubsub.publish(topic, 'bye') |
| 72 | + |
| 73 | + await received |
| 74 | + controller.abort() |
| 75 | + |
| 76 | + // Stop the daemon |
| 77 | + await ctl.stop() |
| 78 | + // Just to make sure no error is caused by above line |
| 79 | + setTimeout(onError, 200, 'aborted') |
| 80 | + |
| 81 | + await expect(error).to.eventually.be.fulfilled().and.to.equal('aborted') |
| 82 | + }) |
| 83 | + }) |
| 84 | +}) |
0 commit comments