uci-websocket/test/usocket-default.test.js

84 lines
2.5 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 SOCKET_FILE = 'usocket-default'
let consumer = new Consumer({path:true,name:'unix-consumer'})
let consumer2 = new Consumer({path:true, name:'unix-consumer2'})
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()
})
const TIMES = 3000
it(`Tests unix socket with default echo JSON packet procssing with ${TIMES} packets sent`, async function () {
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')
}
consumer.registerPacketProcessor(async function (packet) {
return new Promise((resolve) => {
packet.times += 1
if (packet.times === TIMES) packet.payload = 'local1:'+packet.payload
resolve(packet)})
})
let packet = {payload:'payload', times:0}
for (let i = 1; i <= TIMES; i++) {
packet = await consumer.send(packet)
}
expect(packet.payload+':'+packet.times).to.equal('local1:payload:'+TIMES)
}) // end unix socket test
it(`unix socket with two consumers alternating packets, ${TIMES} packets each and local processing`, async function () {
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')
}
consumer2.registerPacketProcessor(async function (packet) {
return new Promise((resolve) => {
packet.times += 1
if (packet.times === TIMES) packet.payload = 'local2:'+packet.payload
resolve(packet)})
})
let packet = {consumer:1, payload:'payload', times:-1}
for (let i = 0; i < TIMES; i++) {
packet = await consumer.send(packet)
if (packet.times === TIMES) packet.times = 1
packet = await consumer2.send(packet)
}
expect(packet.payload+':'+packet.times).to.equal('local2:local1:payload:'+TIMES)
}) // end unix socket test
}) // end describe