提交 ee0c8803 编写于 作者: Huan (李卓桓)'s avatar Huan (李卓桓)

try to fix get port race condition unit test fail (no idea why yet)

上级 cbbaccd6
......@@ -20,16 +20,14 @@
// tslint:disable:no-shadowed-variable
import test from 'blue-tape'
// import http from 'http'
// import express from 'express'
import net from 'net'
import { getPort } from './get-port'
test('getPort() for an available socket port', async t => {
const PORT = 8788
// const PORT = 8788
let port = await getPort(PORT)
let port = await getPort()
let ttl = 17
const serverList = []
......@@ -42,7 +40,7 @@ test('getPort() for an available socket port', async t => {
server.listen(port, '127.0.0.1')
serverList.push(server)
port = await getPort(PORT)
port = await getPort()
} catch (e) {
t.fail('should not exception: ' + e.message + ', ' + e.stack)
......
import net from 'net'
const DEFAULT_PORT = 38788
/**
*
* @param port is just a suggestion.
......@@ -11,8 +13,8 @@ import net from 'net'
* const DEFAULT_IANA_RANGE = {min: 49152, max: 65535}
*
*/
export function getPort (port: number): Promise<number> {
let tryPort = nextPort(port || 38788)
export function getPort (port = DEFAULT_PORT): Promise<number> {
let tryPort = nextPort(port)
return new Promise(resolve => {
// https://gist.github.com/mikeal/1840641
......@@ -39,13 +41,13 @@ export function getPort (port: number): Promise<number> {
function nextPort (currentPort: number): number {
const RANGE = 1733
// do not use Math.random() here, because AVA will fork, then here will get the same random number, cause a race condition for socket listen
// const n = Math.floor(Math.random() * BETWEEN_RANGE)
const n = Math.floor(Math.random() * RANGE)
/**
* nano seconds from node: http://stackoverflow.com/a/18197438/1123955
*/
const [, nanoSeed] = process.hrtime()
const n = 1 + nanoSeed % RANGE // +1 to prevent same port
// const [, nanoSeed] = process.hrtime()
// const n = 1 + nanoSeed % RANGE // +1 to prevent same port
if (currentPort + n > 65000) {
return currentPort + n - RANGE
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册