33using k8s . Tests . Mock . Server ;
44using Microsoft . AspNetCore ;
55using Microsoft . AspNetCore . Hosting ;
6+ using Microsoft . AspNetCore . Hosting . Server . Features ;
67using Microsoft . Extensions . DependencyInjection ;
78using Microsoft . Extensions . Logging ;
89using System ;
910using System . IO ;
11+ using System . Linq ;
1012using System . Net . WebSockets ;
1113using System . Text ;
1214using System . Threading ;
@@ -21,10 +23,6 @@ namespace k8s.Tests
2123 /// </summary>
2224 public abstract class WebSocketTestBase : IDisposable
2325 {
24- /// <summary>
25- /// The next server port to use.
26- /// </summary>
27- private static int nextPort = 13255 ;
2826 private bool disposedValue ;
2927 private readonly ITestOutputHelper testOutput ;
3028
@@ -39,32 +37,41 @@ protected WebSocketTestBase(ITestOutputHelper testOutput)
3937 {
4038 this . testOutput = testOutput ;
4139
42- int port = Interlocked . Increment ( ref nextPort ) ;
43-
4440 // Useful to diagnose test timeouts.
4541 TestCancellation . Register (
4642 ( ) => testOutput . WriteLine ( "Test-level cancellation token has been canceled." ) ) ;
4743
48- ServerBaseAddress = new Uri ( $ "http://localhost:{ port } ") ;
49- WebSocketBaseAddress = new Uri ( $ "ws://localhost:{ port } ") ;
50-
44+ // Use port 0 to let the OS assign a free port dynamically
5145 Host = WebHost . CreateDefaultBuilder ( )
5246 . UseStartup < Startup > ( )
5347 . ConfigureServices ( ConfigureTestServerServices )
5448 . ConfigureLogging ( ConfigureTestServerLogging )
55- . UseUrls ( ServerBaseAddress . AbsoluteUri )
49+ . UseUrls ( "http://127.0.0.1:0" )
5650 . Build ( ) ;
51+
52+ // Start the host to get the actual assigned port
53+ Host . Start ( ) ;
54+
55+ // Get the actual server address after binding
56+ var serverAddress = Host . ServerFeatures . Get < IServerAddressesFeature > ( ) ? . Addresses . FirstOrDefault ( ) ;
57+ if ( serverAddress == null )
58+ {
59+ throw new InvalidOperationException ( "Failed to determine server address" ) ;
60+ }
61+
62+ ServerBaseAddress = new Uri ( serverAddress ) ;
63+ WebSocketBaseAddress = new Uri ( serverAddress . Replace ( "http://" , "ws://" ) ) ;
5764 }
5865
5966 /// <summary>
6067 /// The test server's base address (http://).
6168 /// </summary>
62- protected Uri ServerBaseAddress { get ; }
69+ protected Uri ServerBaseAddress { get ; private set ; }
6370
6471 /// <summary>
6572 /// The test server's base WebSockets address (ws://).
6673 /// </summary>
67- protected Uri WebSocketBaseAddress { get ; }
74+ protected Uri WebSocketBaseAddress { get ; private set ; }
6875
6976 /// <summary>
7077 /// The test server's web host.
0 commit comments