import { spawn } from 'child_process' import chai from 'chai' import chaiAsPromised from 'chai-as-promised' import btc from 'better-try-catch' chai.use(chaiAsPromised) const expect = chai.expect import { Consumer } from '../src' const USOCKET = __dirname + '/sockets/test.sock' const SOCKET_FILE = 'usocket-default' let consumer = new Consumer(USOCKET, {name:'unix-consumer', log:false}) let consumer2 = new Consumer(USOCKET, {name:'unix-consumer2'}) const delay = time => new Promise(res=>setTimeout(()=>res(),time)) let socket = {} describe('Connects and Processes a payload via Unix Socket using JSON packet with defaults', function(){ before(async function(){ socket = spawn('node',['-r', '@std/esm', './test/sockets/'+SOCKET_FILE]) socket.stdout.on('data', function(buf) { console.log('[Socket]', String(buf)) }) }) after(async function(){ socket.kill() }) it('Tests unix socket with default echo JSON packet procssing, 10 packets with conect via connect', async function () { consumer.packet.times = 0 return new Promise(async function (resolve, reject) { let [err] = await btc(consumer.connect)() if (err) { console.log('unable to connect to socket to start test', consumer.path) process.kill(process.pid, 'SIGTERM') } setTimeout(() =>{ reject('10 packets not received in time')},1900) consumer.packet._process = function (packet) { this.times++ if (this.times!==11) return try { expect(packet.payload).to.equal('unix payload') resolve() } catch(error) { reject(error) } } for (var i = 0; i < 11; i++) { let packet = {payload:'unix payload'} consumer.send(packet) } }) //end promise }) // end unix socket test it('unix socket with two consumers alternating packets, 10 packets each with local and added context', async function () { consumer.packet.times = 0 consumer.packet.test = ':local' let [err] = await btc(consumer2.connect)() if (err) { console.log('unable to connect to socket to start test', consumer.path) process.kill(process.pid, 'SIGTERM') } return new Promise(async function (resolve, reject) { setTimeout(() =>{ reject('10 packets not received in time')},1900) consumer.registerPacketProcessor(function (packet) { this.times++ // console.log(this.times,packet.payload) if (this.times!==11) return packet.payload = packet.payload + this.test try { expect(packet.payload).to.equal('consumer 1 unix payload:local') resolve() } catch(error) { reject(error) } }) consumer2.packet._process = function (packet) { return packet } let packet1 = {payload:'consumer 1 unix payload'} let packet2 = {payload:'consumer2 unix payload'} for (var i = 0; i < 11; i++) { consumer.send(packet1) consumer2.send(packet2) } }) //end promise }) // end unix socket test }) // end describe