NetworkTests.cs 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. using CefGlue.Tests.Helpers;
  2. using NUnit.Framework;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Threading.Tasks;
  8. using Xilium.CefGlue;
  9. using Xilium.CefGlue.Common.Events;
  10. using Xilium.CefGlue.Common.Handlers;
  11. namespace CefGlue.Tests.Network
  12. {
  13. public class NetworkTests : TestBase
  14. {
  15. private class TestsRequestHandler : RequestHandler
  16. {
  17. private readonly TestsResourceRequestHandler _resourceRequestHandler;
  18. public TestsRequestHandler(Func<CefRequest, DefaultResourceHandler> resourceHandler)
  19. {
  20. _resourceRequestHandler = new TestsResourceRequestHandler(resourceHandler);
  21. }
  22. protected override CefResourceRequestHandler GetResourceRequestHandler(CefBrowser browser, CefFrame frame, CefRequest request, bool isNavigation, bool isDownload, string requestInitiator, ref bool disableDefaultHandling)
  23. {
  24. return _resourceRequestHandler;
  25. }
  26. }
  27. private class TestsResourceRequestHandler : CefResourceRequestHandler
  28. {
  29. private readonly Func<CefRequest, DefaultResourceHandler> _resourceHandler;
  30. public TestsResourceRequestHandler(Func<CefRequest, DefaultResourceHandler> resourceHandler)
  31. {
  32. _resourceHandler = resourceHandler;
  33. }
  34. protected override CefCookieAccessFilter GetCookieAccessFilter(CefBrowser browser, CefFrame frame, CefRequest request)
  35. {
  36. return null;
  37. }
  38. protected override CefResourceHandler GetResourceHandler(CefBrowser browser, CefFrame frame, CefRequest request)
  39. {
  40. return _resourceHandler(request);
  41. }
  42. }
  43. private class TestsResourceHandler : DefaultResourceHandler
  44. {
  45. public void Read()
  46. {
  47. Read(new MemoryStream(), 10, out var bytesRead, null);
  48. }
  49. }
  50. private class CustomStream : Stream
  51. {
  52. public event Action ReadStarted;
  53. public override bool CanRead => true;
  54. public override bool CanSeek => true;
  55. public override bool CanWrite => true;
  56. public override long Length => 1000;
  57. public override long Position { get; set; }
  58. public override void Flush() { }
  59. public override int Read(byte[] buffer, int offset, int count)
  60. {
  61. ReadStarted?.Invoke();
  62. Position += count;
  63. return count;
  64. }
  65. public override long Seek(long offset, SeekOrigin origin) => throw new NotImplementedException();
  66. public override void SetLength(long value) { }
  67. public override void Write(byte[] buffer, int offset, int count) => throw new NotImplementedException();
  68. }
  69. private class Response
  70. {
  71. public string AllowOrigin { get; set; }
  72. public string Status { get; set; }
  73. public string Data { get; set; }
  74. public string RedirectUrl { get; set; }
  75. }
  76. private Task<Response> GetResponse()
  77. {
  78. var taskCompletion = new TaskCompletionSource<Response>();
  79. Browser.ConsoleMessage += OnConsoleMessage;
  80. void OnConsoleMessage(object sender, ConsoleMessageEventArgs message)
  81. {
  82. Browser.ConsoleMessage -= OnConsoleMessage;
  83. var messageParts = message.Message.Split("|");
  84. if (messageParts.Length == 4)
  85. {
  86. taskCompletion.SetResult(new Response()
  87. {
  88. AllowOrigin = messageParts[0],
  89. Status = messageParts[1],
  90. RedirectUrl = messageParts[2],
  91. Data = messageParts[3]
  92. });
  93. }
  94. else
  95. {
  96. taskCompletion.SetResult(new Response()
  97. {
  98. Data = message.Message
  99. });
  100. }
  101. }
  102. var script =
  103. "fetch('https://tests/resource').then(response => {" +
  104. " let result = [ response.headers.get('Access-Control-Allow-Origin'), response.status, response.url ];" +
  105. " try {" +
  106. " if (response.status === 200) {" +
  107. " response.text().then(data => console.log(result.concat([ data ]).join('|')));" +
  108. " return;" +
  109. " }" +
  110. " } catch {}" +
  111. " console.log(result.concat([ '' ]).join('|'));" +
  112. "})";
  113. EvaluateJavascript<int>(script);
  114. return taskCompletion.Task.ContinueWith(t =>
  115. {
  116. Browser.ConsoleMessage -= OnConsoleMessage;
  117. return t.Result;
  118. });
  119. }
  120. [Test]
  121. public async Task ResourceHandlerIsCalledWithStatusOk()
  122. {
  123. const string Data = "test";
  124. Browser.RequestHandler = new TestsRequestHandler(_ =>
  125. {
  126. var handler = new DefaultResourceHandler();
  127. handler.Response = StreamHelper.GetStream(Data);
  128. return handler;
  129. });
  130. var response = await GetResponse();
  131. Assert.AreEqual("*", response.AllowOrigin);
  132. Assert.AreEqual("200", response.Status);
  133. Assert.AreEqual(Data, response.Data);
  134. }
  135. [Test]
  136. public async Task ResourceHandlerIsCalledWithError()
  137. {
  138. Browser.RequestHandler = new TestsRequestHandler(_ => new DefaultResourceHandler());
  139. var response = await GetResponse();
  140. StringAssert.Contains("Error", response.Data);
  141. }
  142. [Test]
  143. public async Task ResourceHandlerWithRedirectUrl()
  144. {
  145. const string RedirectUrl = "http://test/otherurl";
  146. Browser.RequestHandler = new TestsRequestHandler(request =>
  147. {
  148. var handler = new DefaultResourceHandler();
  149. if (request.Url == RedirectUrl)
  150. {
  151. handler.Response = StreamHelper.GetStream("ok");
  152. }
  153. else
  154. {
  155. handler.RedirectUrl = RedirectUrl;
  156. }
  157. return handler;
  158. });
  159. var response = await GetResponse();
  160. StringAssert.Contains(RedirectUrl, response.RedirectUrl);
  161. }
  162. [Test]
  163. public async Task ResourceHandlerStreamsAreNotReadAtSameTime()
  164. {
  165. var checkPoints = new List<int>();
  166. var stream = new CustomStream();
  167. var handler1 = new TestsResourceHandler();
  168. var handler2 = new TestsResourceHandler();
  169. // both handlers share the same stream
  170. handler1.Response = stream;
  171. handler2.Response = stream;
  172. Task concurrentReadTask = null;
  173. void OnStreamReadStarted()
  174. {
  175. checkPoints.Add(2);
  176. stream.ReadStarted -= OnStreamReadStarted;
  177. var concurrentReadTaskStarted = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
  178. concurrentReadTask = Task.Run(() =>
  179. {
  180. checkPoints.Add(3);
  181. concurrentReadTaskStarted.SetResult(true);
  182. handler2.Read();
  183. checkPoints.Add(5);
  184. });
  185. concurrentReadTaskStarted.Task.Wait();
  186. // simulate read with 1s duration
  187. Task.Delay(TimeSpan.FromSeconds(1)).Wait();
  188. checkPoints.Add(4);
  189. }
  190. stream.ReadStarted += () => Assert.AreEqual(0, stream.Position, "Streams Position on Reads must be 0");
  191. stream.ReadStarted += OnStreamReadStarted;
  192. checkPoints.Add(1);
  193. handler1.Read();
  194. Assert.IsNotNull(concurrentReadTask);
  195. await concurrentReadTask;
  196. checkPoints.Add(6);
  197. CollectionAssert.AreEqual(Enumerable.Range(1, 6), checkPoints);
  198. }
  199. }
  200. }