|
5 | 5 | using ModelContextProtocol.Tests.Utils; |
6 | 6 | using System.Net; |
7 | 7 | using System.Reflection; |
| 8 | +using System.Reflection.Metadata; |
8 | 9 |
|
9 | 10 | namespace ModelContextProtocol.Tests.Transport; |
10 | 11 |
|
@@ -107,12 +108,53 @@ public async Task ConnectAsync_Should_Connect_Successfully() |
107 | 108 | [Fact] |
108 | 109 | public async Task ConnectAsync_Throws_If_Already_Connected() |
109 | 110 | { |
110 | | - await using var transport = new SseClientTransport(_transportOptions, _serverConfig, NullLoggerFactory.Instance); |
111 | | - transport.GetType().BaseType!.GetField("_isConnected", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)?.SetValue(transport, true); |
| 111 | + using var mockHttpHandler = new MockHttpHandler(); |
| 112 | + using var httpClient = new HttpClient(mockHttpHandler); |
| 113 | + await using var transport = new SseClientTransport(_transportOptions, _serverConfig, httpClient, NullLoggerFactory.Instance); |
| 114 | + using var mreConnected = new ManualResetEventSlim(false); |
| 115 | + using var mreDone = new ManualResetEventSlim(false); |
| 116 | + var callIndex = 0; |
| 117 | + |
| 118 | + mockHttpHandler.RequestHandler = (request) => |
| 119 | + { |
| 120 | + switch (callIndex++) |
| 121 | + { |
| 122 | + case 0: |
| 123 | + return Task.FromResult(new HttpResponseMessage |
| 124 | + { |
| 125 | + StatusCode = HttpStatusCode.OK, |
| 126 | + Content = new StringContent("event: endpoint\r\ndata: http://localhost\r\n\r\n") |
| 127 | + }); |
| 128 | + case 1: |
| 129 | + mreConnected.Set(); |
| 130 | + mreDone.Wait(); |
| 131 | + return Task.FromResult(new HttpResponseMessage |
| 132 | + { |
| 133 | + StatusCode = HttpStatusCode.OK, |
| 134 | + Content = new StringContent("") |
| 135 | + }); |
| 136 | + default: |
| 137 | + return Task.FromResult(new HttpResponseMessage |
| 138 | + { |
| 139 | + StatusCode = HttpStatusCode.OK, |
| 140 | + Content = new StringContent("") |
| 141 | + }); |
| 142 | + } |
| 143 | + }; |
112 | 144 |
|
| 145 | + var task = Task.Run(async () => |
| 146 | + { |
| 147 | + await transport.ConnectAsync(TestContext.Current.CancellationToken); |
| 148 | + }, TestContext.Current.CancellationToken); |
| 149 | + |
| 150 | + mreConnected.Wait(TestContext.Current.CancellationToken); |
| 151 | + Assert.True(transport.IsConnected); |
113 | 152 | var action = async () => await transport.ConnectAsync(); |
114 | 153 | var exception = await Assert.ThrowsAsync<McpTransportException>(action); |
115 | 154 | Assert.Equal("Transport is already connected", exception.Message); |
| 155 | + mreDone.Set(); |
| 156 | + await transport.CloseAsync(); |
| 157 | + await task; |
116 | 158 | } |
117 | 159 |
|
118 | 160 | [Fact] |
|
0 commit comments