uci-socket/test/usocket-default.test.mjs

116 lines
3.1 KiB
JavaScript

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'})
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))
})
await delay(500) // wait for sockets to get going
})
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) {
setTimeout(() =>{ reject('10 packets not received in time')},1900)
consumer.packet._process = function (packet) {
this.times++
if (this.times!==11) return
packet.payload = packet.payload + this.context.test
try {
expect(packet.payload).to.equal('unix payload plus context at connect')
resolve()
}
catch(error) {
reject(error)
}
}
let [err] = await btc(consumer.connect)({test:' plus context at connect'})
if (err) reject(err)
let packet = {payload:'unix payload'}
for (var i = 0; i < 11; i++) {
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'
consumer.registerPacketContext({test:':added'})
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.context.test + this.test
try {
expect(packet.payload).to.equal('consumer 1 unix payload:added:local')
resolve()
}
catch(error) {
reject(error)
}
})
consumer2.packet._process = function (packet) {
return packet
}
let [err] = await btc(consumer2.connect)()
if (err) reject(err)
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