-
Notifications
You must be signed in to change notification settings - Fork 270
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
chore: use random ports in p2p_client tests (#8624)
- Loading branch information
Showing
3 changed files
with
40 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,2 +1,3 @@ | ||
export * from './test_data.js'; | ||
export * from './snapshot_serializer.js'; | ||
export * from './port_allocator.js'; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
import net from 'net'; | ||
|
||
/** | ||
* Get a random port that is free to use. | ||
* Returns undefined if it fails to get a port. | ||
* | ||
* @attribution: adapted from https://stackoverflow.com/a/71178451 | ||
* | ||
* @returns a random port that is free to use. | ||
*/ | ||
export function getRandomPort(): Promise<number | undefined> { | ||
return new Promise(resolve => { | ||
const server = net.createServer(); | ||
server.listen(0, () => { | ||
const address = server.address(); | ||
if (address && typeof address === 'object' && 'port' in address) { | ||
const port = address.port; | ||
server.close(() => { | ||
resolve(port); | ||
}); | ||
} else { | ||
server.close(() => { | ||
resolve(undefined); | ||
}); | ||
} | ||
}); | ||
server.on('error', () => { | ||
resolve(undefined); | ||
}); | ||
}); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters