add more server tests

Signed-off-by: Andrey Platov <andrey@hardcoreeng.com>
This commit is contained in:
Andrey Platov 2021-08-04 09:56:34 +02:00
parent 63ba826b3e
commit 1860280e49
No known key found for this signature in database
GPG Key ID: C8787EFEB4B64AF0
3 changed files with 38 additions and 6 deletions

View File

@ -29,7 +29,7 @@ export class Request<P extends any[], M extends string = string> {
method: M
params: P
constructor (method: M, ...params: P) {
constructor (method: M, params: P, id?: ReqId) {
this.method = method
this.params = params
}

View File

@ -14,12 +14,15 @@
// limitations under the License.
//
import { Request, readResponse, serialize } from '@anticrm/platform'
import { start, _Token } from '../server'
import { encode } from 'jwt-simple'
import WebSocket from 'ws'
describe('server', () => {
start(async () => ({}), 3333)
start(async () => ({
ping: () => {}
}), 3333)
function connect (): WebSocket {
const payload: _Token = {
@ -36,4 +39,33 @@ describe('server', () => {
done()
})
})
it('should not connect to server without token', (done) => {
const conn = new WebSocket('ws://localhost:3333/xyz')
conn.on('error', () => {
console.log('error')
conn.close()
done()
})
})
it('should send many requests', (done) => {
const conn = connect()
const total = 10
// const start = Date.now()
conn.on('open', () => {
for (let i = 0; i < total; i++) {
conn.send(serialize(new Request('ping', [], i)))
}
})
let received = 0
conn.on('message', (msg: string) => {
readResponse(msg)
if (++received === total) {
// console.log('resp:', resp, ' Time: ', Date.now() - start)
conn.close()
done()
}
})
})
})

View File

@ -60,12 +60,12 @@ export function start<S> (serviceFactory: () => Promise<S>, port: number, host?:
const server = createServer()
server.on('upgrade', (request: IncomingMessage, socket, head: Buffer) => {
const token = request.url?.substring(1) // remove leading '/'
if (token === undefined) {
try {
const payload = decode(token ?? '', 'secret', false)
wss.handleUpgrade(request, socket, head, ws => wss.emit('connection', ws, request, payload))
} catch (err) {
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n')
socket.destroy()
} else {
const payload = decode(token, 'secret', false)
wss.handleUpgrade(request, socket, head, ws => wss.emit('connection', ws, request, payload))
}
})