ClientWebSocketTest.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. using System;
  2. using System.Net;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. using System.Collections.Generic;
  6. using System.Net.WebSockets;
  7. using System.Reflection;
  8. using System.Text;
  9. using NUnit.Framework;
  10. using MonoTests.Helpers;
  11. namespace MonoTests.System.Net.WebSockets
  12. {
  13. [TestFixture]
  14. public class ClientWebSocketTest
  15. {
  16. const string EchoServerUrl = "ws://corefx-net.cloudapp.net/WebSocket/EchoWebSocket.ashx";
  17. int Port = NetworkHelpers.FindFreePort ();
  18. HttpListener _listener;
  19. HttpListener listener {
  20. get {
  21. if (_listener != null)
  22. return _listener;
  23. var tmp = new HttpListener ();
  24. tmp.Prefixes.Add ("http://localhost:" + Port + "/");
  25. tmp.Start ();
  26. return _listener = tmp;
  27. }
  28. }
  29. ClientWebSocket _socket;
  30. ClientWebSocket socket { get { return _socket ?? (_socket = new ClientWebSocket ()); } }
  31. MethodInfo headerSetMethod;
  32. [TearDown]
  33. public void Teardown ()
  34. {
  35. if (_listener != null) {
  36. _listener.Stop ();
  37. _listener = null;
  38. }
  39. if (_socket != null) {
  40. if (_socket.State == WebSocketState.Open)
  41. _socket.CloseAsync (WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None).Wait (2000);
  42. _socket.Dispose ();
  43. _socket = null;
  44. }
  45. }
  46. [Test]
  47. [Category ("MobileNotWorking")] // Fails when ran as part of the entire BCL test suite. Works when only this fixture is ran
  48. public void ServerHandshakeReturnCrapStatusCodeTest ()
  49. {
  50. // On purpose,
  51. #pragma warning disable 4014
  52. HandleHttpRequestAsync ((req, resp) => resp.StatusCode = 418);
  53. #pragma warning restore 4014
  54. try {
  55. Assert.IsTrue (socket.ConnectAsync (new Uri ("ws://localhost:" + Port), CancellationToken.None).Wait (5000));
  56. } catch (AggregateException e) {
  57. AssertWebSocketException (e, WebSocketError.Success, typeof (WebException));
  58. return;
  59. }
  60. Assert.Fail ("Should have thrown");
  61. }
  62. [Test]
  63. [Category ("MobileNotWorking")] // Fails when ran as part of the entire BCL test suite. Works when only this fixture is ran
  64. public void ServerHandshakeReturnWrongUpgradeHeader ()
  65. {
  66. #pragma warning disable 4014
  67. HandleHttpRequestAsync ((req, resp) => {
  68. resp.StatusCode = 101;
  69. resp.Headers["Upgrade"] = "gtfo";
  70. });
  71. #pragma warning restore 4014
  72. try {
  73. Assert.IsTrue (socket.ConnectAsync (new Uri ("ws://localhost:" + Port), CancellationToken.None).Wait (5000));
  74. } catch (AggregateException e) {
  75. AssertWebSocketException (e, WebSocketError.Success);
  76. return;
  77. }
  78. Assert.Fail ("Should have thrown");
  79. }
  80. [Test]
  81. [Category ("MobileNotWorking")] // Fails when ran as part of the entire BCL test suite. Works when only this fixture is ran
  82. public void ServerHandshakeReturnWrongConnectionHeader ()
  83. {
  84. #pragma warning disable 4014
  85. HandleHttpRequestAsync ((req, resp) => {
  86. resp.StatusCode = 101;
  87. resp.Headers["Upgrade"] = "websocket";
  88. // Mono http request doesn't like the forcing, test still valid since the default connection header value is empty
  89. //ForceSetHeader (resp.Headers, "Connection", "Foo");
  90. });
  91. #pragma warning restore 4014
  92. try {
  93. Assert.IsTrue (socket.ConnectAsync (new Uri ("ws://localhost:" + Port), CancellationToken.None).Wait (5000));
  94. } catch (AggregateException e) {
  95. AssertWebSocketException (e, WebSocketError.Success);
  96. return;
  97. }
  98. Assert.Fail ("Should have thrown");
  99. }
  100. [Test]
  101. [Category ("MobileNotWorking")] // The test hangs when ran as part of the entire BCL test suite. Works when only this fixture is ran
  102. public void EchoTest ()
  103. {
  104. const string Payload = "This is a websocket test";
  105. Assert.AreEqual (WebSocketState.None, socket.State);
  106. socket.ConnectAsync (new Uri (EchoServerUrl), CancellationToken.None).Wait ();
  107. Assert.AreEqual (WebSocketState.Open, socket.State);
  108. var sendBuffer = Encoding.ASCII.GetBytes (Payload);
  109. Assert.IsTrue (socket.SendAsync (new ArraySegment<byte> (sendBuffer), WebSocketMessageType.Text, true, CancellationToken.None).Wait (5000));
  110. var receiveBuffer = new byte[Payload.Length];
  111. var resp = socket.ReceiveAsync (new ArraySegment<byte> (receiveBuffer), CancellationToken.None).Result;
  112. Assert.AreEqual (Payload.Length, resp.Count);
  113. Assert.IsTrue (resp.EndOfMessage);
  114. Assert.AreEqual (WebSocketMessageType.Text, resp.MessageType);
  115. Assert.AreEqual (Payload, Encoding.ASCII.GetString (receiveBuffer, 0, resp.Count));
  116. Assert.IsTrue (socket.CloseAsync (WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None).Wait (5000));
  117. Assert.AreEqual (WebSocketState.Closed, socket.State);
  118. }
  119. [Test]
  120. [Category ("MobileNotWorking")] // Fails when ran as part of the entire BCL test suite. Works when only this fixture is ran
  121. public void CloseOutputAsyncTest ()
  122. {
  123. Assert.IsTrue (socket.ConnectAsync (new Uri (EchoServerUrl), CancellationToken.None).Wait (5000));
  124. Assert.AreEqual (WebSocketState.Open, socket.State);
  125. Assert.IsTrue (socket.CloseOutputAsync (WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None).Wait (5000));
  126. Assert.AreEqual (WebSocketState.CloseSent, socket.State);
  127. var resp = socket.ReceiveAsync (new ArraySegment<byte> (new byte[0]), CancellationToken.None).Result;
  128. Assert.AreEqual (WebSocketState.Closed, socket.State);
  129. Assert.AreEqual (WebSocketMessageType.Close, resp.MessageType);
  130. Assert.AreEqual (WebSocketCloseStatus.NormalClosure, resp.CloseStatus);
  131. Assert.AreEqual (string.Empty, resp.CloseStatusDescription);
  132. }
  133. [Test]
  134. [Category ("MobileNotWorking")] // Fails when ran as part of the entire BCL test suite. Works when only this fixture is ran
  135. public void CloseAsyncTest ()
  136. {
  137. Assert.IsTrue (socket.ConnectAsync (new Uri (EchoServerUrl), CancellationToken.None).Wait (5000));
  138. Assert.AreEqual (WebSocketState.Open, socket.State);
  139. Assert.IsTrue (socket.CloseAsync (WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None).Wait (5000));
  140. Assert.AreEqual (WebSocketState.Closed, socket.State);
  141. }
  142. [Test, ExpectedException (typeof (InvalidOperationException))]
  143. public void SendAsyncArgTest_NotConnected ()
  144. {
  145. socket.SendAsync (new ArraySegment<byte> (new byte[0]), WebSocketMessageType.Text, true, CancellationToken.None);
  146. }
  147. [Test, ExpectedException (typeof (ArgumentNullException))]
  148. [Category ("MobileNotWorking")] // Fails when ran as part of the entire BCL test suite. Works when only this fixture is ran
  149. public void SendAsyncArgTest_NoArray ()
  150. {
  151. Assert.IsTrue (socket.ConnectAsync (new Uri (EchoServerUrl), CancellationToken.None).Wait (5000));
  152. socket.SendAsync (new ArraySegment<byte> (), WebSocketMessageType.Text, true, CancellationToken.None);
  153. }
  154. [Test, ExpectedException (typeof (InvalidOperationException))]
  155. public void ReceiveAsyncArgTest_NotConnected ()
  156. {
  157. socket.ReceiveAsync (new ArraySegment<byte> (new byte[0]), CancellationToken.None);
  158. }
  159. [Test, ExpectedException (typeof (ArgumentNullException))]
  160. [Category ("MobileNotWorking")] // Fails when ran as part of the entire BCL test suite. Works when only this fixture is ran
  161. public void ReceiveAsyncArgTest_NoArray ()
  162. {
  163. Assert.IsTrue (socket.ConnectAsync (new Uri (EchoServerUrl), CancellationToken.None).Wait (5000));
  164. socket.ReceiveAsync (new ArraySegment<byte> (), CancellationToken.None);
  165. }
  166. [Test]
  167. [Category ("MobileNotWorking")] // Fails when ran as part of the entire BCL test suite. Works when only this fixture is ran
  168. public void ReceiveAsyncWrongState_Closed ()
  169. {
  170. try {
  171. Assert.IsTrue (socket.ConnectAsync (new Uri (EchoServerUrl), CancellationToken.None).Wait (5000));
  172. Assert.IsTrue (socket.CloseAsync (WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None).Wait (5000));
  173. Assert.IsTrue (socket.ReceiveAsync (new ArraySegment<byte> (new byte[0]), CancellationToken.None).Wait (5000));
  174. } catch (AggregateException e) {
  175. AssertWebSocketException (e, WebSocketError.Success);
  176. return;
  177. }
  178. Assert.Fail ("Should have thrown");
  179. }
  180. [Test]
  181. [Category ("MobileNotWorking")] // Fails when ran as part of the entire BCL test suite. Works when only this fixture is ran
  182. public void SendAsyncWrongState_Closed ()
  183. {
  184. try {
  185. Assert.IsTrue (socket.ConnectAsync (new Uri (EchoServerUrl), CancellationToken.None).Wait (5000));
  186. Assert.IsTrue (socket.CloseAsync (WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None).Wait (5000));
  187. Assert.IsTrue (socket.SendAsync (new ArraySegment<byte> (new byte[0]), WebSocketMessageType.Text, true, CancellationToken.None).Wait (5000));
  188. } catch (AggregateException e) {
  189. AssertWebSocketException (e, WebSocketError.Success);
  190. return;
  191. }
  192. Assert.Fail ("Should have thrown");
  193. }
  194. [Test]
  195. [Category ("MobileNotWorking")] // Fails when ran as part of the entire BCL test suite. Works when only this fixture is ran
  196. public void SendAsyncWrongState_CloseSent ()
  197. {
  198. try {
  199. Assert.IsTrue (socket.ConnectAsync (new Uri (EchoServerUrl), CancellationToken.None).Wait (5000));
  200. Assert.IsTrue (socket.CloseOutputAsync (WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None).Wait (5000));
  201. Assert.IsTrue (socket.SendAsync (new ArraySegment<byte> (new byte[0]), WebSocketMessageType.Text, true, CancellationToken.None).Wait (5000));
  202. } catch (AggregateException e) {
  203. AssertWebSocketException (e, WebSocketError.Success);
  204. return;
  205. }
  206. Assert.Fail ("Should have thrown");
  207. }
  208. [Test]
  209. [Category ("NotWorking")] // FIXME: test relies on unimplemented HttpListenerContext.AcceptWebSocketAsync (), reenable it when the method is implemented
  210. public void SendAsyncEndOfMessageTest ()
  211. {
  212. var cancellationToken = new CancellationTokenSource (TimeSpan.FromSeconds (30)).Token;
  213. SendAsyncEndOfMessageTest (false, WebSocketMessageType.Text, cancellationToken).Wait (5000);
  214. SendAsyncEndOfMessageTest (true, WebSocketMessageType.Text, cancellationToken).Wait (5000);
  215. SendAsyncEndOfMessageTest (false, WebSocketMessageType.Binary, cancellationToken).Wait (5000);
  216. SendAsyncEndOfMessageTest (true, WebSocketMessageType.Binary, cancellationToken).Wait (5000);
  217. }
  218. public async Task SendAsyncEndOfMessageTest (bool expectedEndOfMessage, WebSocketMessageType webSocketMessageType, CancellationToken cancellationToken)
  219. {
  220. using (var client = new ClientWebSocket ()) {
  221. // Configure the listener.
  222. var serverReceive = HandleHttpWebSocketRequestAsync<WebSocketReceiveResult> (async socket => await socket.ReceiveAsync (new ArraySegment<byte> (new byte[32]), cancellationToken), cancellationToken);
  223. // Connect to the listener and make the request.
  224. await client.ConnectAsync (new Uri ("ws://localhost:" + Port + "/"), cancellationToken);
  225. await client.SendAsync (new ArraySegment<byte> (Encoding.UTF8.GetBytes ("test")), webSocketMessageType, expectedEndOfMessage, cancellationToken);
  226. // Wait for the listener to handle the request and return its result.
  227. var result = await serverReceive;
  228. // Cleanup and check results.
  229. await client.CloseAsync (WebSocketCloseStatus.NormalClosure, "Finished", cancellationToken);
  230. Assert.AreEqual (expectedEndOfMessage, result.EndOfMessage, "EndOfMessage should be " + expectedEndOfMessage);
  231. }
  232. }
  233. async Task<T> HandleHttpWebSocketRequestAsync<T> (Func<WebSocket, Task<T>> action, CancellationToken cancellationToken)
  234. {
  235. var ctx = await this.listener.GetContextAsync ();
  236. var wsContext = await ctx.AcceptWebSocketAsync (null);
  237. var result = await action (wsContext.WebSocket);
  238. await wsContext.WebSocket.CloseOutputAsync (WebSocketCloseStatus.NormalClosure, "Finished", cancellationToken);
  239. return result;
  240. }
  241. async Task HandleHttpRequestAsync (Action<HttpListenerRequest, HttpListenerResponse> handler)
  242. {
  243. var ctx = await listener.GetContextAsync ();
  244. handler (ctx.Request, ctx.Response);
  245. ctx.Response.Close ();
  246. }
  247. void AssertWebSocketException (AggregateException e, WebSocketError error, Type inner = null)
  248. {
  249. var wsEx = e.InnerException as WebSocketException;
  250. Console.WriteLine (e.InnerException.ToString ());
  251. Assert.IsNotNull (wsEx, "Not a websocketexception");
  252. Assert.AreEqual (error, wsEx.WebSocketErrorCode);
  253. if (inner != null) {
  254. Assert.IsNotNull (wsEx.InnerException);
  255. Assert.IsTrue (inner.IsInstanceOfType (wsEx.InnerException));
  256. }
  257. }
  258. void ForceSetHeader (WebHeaderCollection headers, string name, string value)
  259. {
  260. if (headerSetMethod == null)
  261. headerSetMethod = typeof (WebHeaderCollection).GetMethod ("AddValue", BindingFlags.NonPublic);
  262. headerSetMethod.Invoke (headers, new[] { name, value });
  263. }
  264. }
  265. }