@@ -34,6 +34,20 @@ function occupyPort(port) {
3434 } ) ;
3535}
3636
37+ function getServerPort ( server ) {
38+ let address = server . address ( ) ;
39+ return typeof address === 'object' && address ? address . port : null ;
40+ }
41+
42+ function closeServer ( server ) {
43+ return new Promise ( ( resolve , reject ) => {
44+ server . close ( error => {
45+ if ( error ) reject ( error ) ;
46+ else resolve ( ) ;
47+ } ) ;
48+ } ) ;
49+ }
50+
3751describe ( 'tdd/server-registry' , ( ) => {
3852 let testDir ;
3953 let registry ;
@@ -256,30 +270,35 @@ describe('tdd/server-registry', () => {
256270 } ) ;
257271
258272 it ( 'skips ports actually in use by other processes' , async ( ) => {
259- // Actually occupy port 47500 with a real TCP server
260- let occupyingServer = await occupyPort ( 47500 ) ;
273+ let occupyingServer = await occupyPort ( 0 ) ;
274+ let occupiedPort = getServerPort ( occupyingServer ) ;
261275
262276 try {
263- let port = await registry . findAvailablePort ( 47500 ) ;
264- assert . strictEqual ( port , 47501 ) ;
277+ let port = await registry . findAvailablePort ( occupiedPort ) ;
278+ assert . notStrictEqual ( port , occupiedPort ) ;
279+ assert . ok ( port > occupiedPort ) ;
265280 } finally {
266- occupyingServer . close ( ) ;
281+ await closeServer ( occupyingServer ) ;
267282 }
268283 } ) ;
269284
270285 it ( 'handles combination of registered and occupied ports' , async ( ) => {
271- // Register 47600 in registry
272- registry . register ( { pid : process . pid , port : 47600 , directory : '/a' } ) ;
273-
274- // Actually occupy 47601
275- let occupyingServer = await occupyPort ( 47601 ) ;
286+ let occupyingServer = await occupyPort ( 0 ) ;
287+ let occupiedPort = getServerPort ( occupyingServer ) ;
288+ let registeredPort = occupiedPort - 1 ;
289+ registry . register ( {
290+ pid : process . pid ,
291+ port : registeredPort ,
292+ directory : '/a' ,
293+ } ) ;
276294
277295 try {
278- let port = await registry . findAvailablePort ( 47600 ) ;
279- // Should skip 47600 (registered) and 47601 (occupied), return 47602
280- assert . strictEqual ( port , 47602 ) ;
296+ let port = await registry . findAvailablePort ( registeredPort ) ;
297+ assert . notStrictEqual ( port , registeredPort ) ;
298+ assert . notStrictEqual ( port , occupiedPort ) ;
299+ assert . ok ( port > occupiedPort ) ;
281300 } finally {
282- occupyingServer . close ( ) ;
301+ await closeServer ( occupyingServer ) ;
283302 }
284303 } ) ;
285304 } ) ;
0 commit comments