WebClientTestAsync.cs 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. //
  2. // System.Net.WebClientTestAsync
  3. //
  4. // Authors:
  5. // Martin Baulig ([email protected])
  6. //
  7. // Copyright 2012 Xamarin Inc. (http://www.xamarin.com)
  8. //
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. using System;
  30. using System.IO;
  31. using System.Collections.Generic;
  32. using System.Threading;
  33. using System.Threading.Tasks;
  34. using System.Reflection;
  35. using System.Net;
  36. using NUnit.Framework;
  37. namespace MonoTests.System.Net
  38. {
  39. [TestFixture]
  40. public class WebClientTestAsync
  41. {
  42. [Test]
  43. [Category("Async")]
  44. [Category("AndroidNotWorking")] // Attempts to access the test dll which won't work on Android
  45. public void DownloadData ()
  46. {
  47. WebClient wc;
  48. bool progress_changed = false;
  49. bool completed = false;
  50. bool progress_changed_error = false;
  51. bool completed_error = false;
  52. int thread_id = Thread.CurrentThread.ManagedThreadId;
  53. wc = new WebClient ();
  54. wc.DownloadProgressChanged += delegate {
  55. progress_changed = true;
  56. if (Thread.CurrentThread.ManagedThreadId != thread_id)
  57. progress_changed_error = true;
  58. };
  59. wc.DownloadDataCompleted += delegate {
  60. completed = true;
  61. if (Thread.CurrentThread.ManagedThreadId != thread_id)
  62. completed_error = true;
  63. };
  64. MessagePumpSyncContext.Run (async () => {
  65. var url = Assembly.GetExecutingAssembly ().CodeBase;
  66. await wc.DownloadDataTaskAsync (url);
  67. Assert.AreEqual (Thread.CurrentThread.ManagedThreadId, thread_id);
  68. }, () => progress_changed && completed, 10000);
  69. Assert.IsTrue (progress_changed, "#1");
  70. Assert.IsFalse (progress_changed_error, "#2");
  71. Assert.IsTrue (completed, "#3");
  72. Assert.IsFalse (completed_error, "#4");
  73. }
  74. [Test]
  75. #if FEATURE_NO_BSD_SOCKETS
  76. [ExpectedException (typeof (AggregateException))] // Something catches the PlatformNotSupportedException and re-throws an AggregateException
  77. #endif
  78. [Category("InetAccess")]
  79. public void DownloadFileTaskAsync ()
  80. {
  81. WebClient wc = new WebClient ();
  82. string filename = Path.GetTempFileName ();
  83. var task = wc.DownloadFileTaskAsync ("http://www.mono-project.com/", filename);
  84. Assert.IsTrue (task.Wait (15000));
  85. Assert.IsTrue (task.IsCompleted);
  86. File.Delete (filename);
  87. }
  88. [Test]
  89. [Category ("NotWorking")] // Fails when ran as part of the entire BCL test suite. Works when only this fixture is ran
  90. [Category("InetAccess")]
  91. public void Cancellation ()
  92. {
  93. WebClient wc = new WebClient ();
  94. var progress = new ManualResetEvent (false);
  95. wc.DownloadProgressChanged += delegate {
  96. progress.Set ();
  97. };
  98. // Try downloading some large file, so we don't finish early.
  99. var url = "http://download.mono-project.com/archive/2.10.9/macos-10-x86/11/MonoFramework-MDK-2.10.9_11.macos10.xamarin.x86.dmg";
  100. var task = wc.DownloadDataTaskAsync (url);
  101. Assert.IsTrue (progress.WaitOne (15000), "#1");
  102. wc.CancelAsync ();
  103. try {
  104. task.Wait ();
  105. Assert.Fail ("#2");
  106. } catch (Exception ex) {
  107. if (ex is AggregateException)
  108. ex = ((AggregateException)ex).InnerException;
  109. Assert.That (ex is WebException || ex is OperationCanceledException, "#4");
  110. Assert.IsTrue (task.IsCanceled || task.IsFaulted, "#5");
  111. }
  112. }
  113. [Test]
  114. [Category ("NotWorking")] // Fails when ran as part of the entire BCL test suite. Works when only this fixture is ran
  115. [Category("InetAccess")]
  116. public void DownloadMultiple ()
  117. {
  118. WebClient wc = new WebClient ();
  119. var t1 = wc.OpenReadTaskAsync ("http://www.google.com/");
  120. Assert.That (t1.Wait (15000));
  121. Assert.IsTrue (t1.IsCompleted, "#1");
  122. var t2 = wc.OpenReadTaskAsync ("http://www.mono-project.com/");
  123. Assert.That (t2.Wait (15000));
  124. Assert.IsTrue (t2.IsCompleted, "#2");
  125. var t3 = wc.DownloadStringTaskAsync ("http://www.google.com/");
  126. Assert.That (t3.Wait (15000));
  127. Assert.IsTrue (t3.IsCompleted, "#3");
  128. }
  129. [Test]
  130. [Category ("InetAccess")]
  131. [Category ("NotWorking")] // Fails when ran as part of the entire BCL test suite. Works when only this fixture is ran
  132. public void DownloadMultiple2 ()
  133. {
  134. WebClient wc = new WebClient ();
  135. MessagePumpSyncContext.Run (async () => {
  136. await wc.DownloadStringTaskAsync ("http://www.google.com/");
  137. await wc.DownloadDataTaskAsync ("http://www.mono-project.com/");
  138. }, null, 15000);
  139. }
  140. [Test]
  141. [Category ("InetAccess")]
  142. [Category ("NotWorking")] // Fails when ran as part of the entire BCL test suite. Works when only this fixture is ran
  143. public void DownloadMultiple3 ()
  144. {
  145. WebClient wc = new WebClient ();
  146. int thread_id = Thread.CurrentThread.ManagedThreadId;
  147. bool data_completed = false;
  148. bool string_completed = false;
  149. bool error = false;
  150. wc.DownloadDataCompleted += delegate {
  151. if (data_completed || (Thread.CurrentThread.ManagedThreadId != thread_id))
  152. error = true;
  153. data_completed = true;
  154. };
  155. wc.DownloadStringCompleted += delegate {
  156. if (string_completed || (Thread.CurrentThread.ManagedThreadId != thread_id))
  157. error = true;
  158. string_completed = true;
  159. };
  160. MessagePumpSyncContext.Run (async () => {
  161. await wc.DownloadStringTaskAsync ("http://www.google.com/");
  162. await wc.DownloadDataTaskAsync ("http://www.mono-project.com/");
  163. }, () => data_completed && string_completed, 15000);
  164. Assert.IsTrue (data_completed, "#1");
  165. Assert.IsTrue (string_completed, "#2");
  166. Assert.IsFalse (error, "#3");
  167. }
  168. public sealed class MessagePumpSyncContext : SynchronizationContext
  169. {
  170. private delegate void MyAction ();
  171. private readonly Queue<MyAction> queue = new Queue<MyAction> ();
  172. private readonly object sync = new object ();
  173. private readonly Func<bool> completed;
  174. private readonly int timeout;
  175. private bool running = true;
  176. MessagePumpSyncContext (Func<bool> completed, int timeout)
  177. {
  178. this.completed = completed;
  179. this.timeout = timeout;
  180. }
  181. public override void Send (SendOrPostCallback d, object state)
  182. {
  183. throw new InvalidOperationException ();
  184. }
  185. public override void Post (SendOrPostCallback d, object state)
  186. {
  187. lock (sync) {
  188. queue.Enqueue (() => d (state));
  189. Monitor.Pulse (sync);
  190. }
  191. }
  192. bool IsCompleted {
  193. get {
  194. if (running)
  195. return false;
  196. if (completed != null)
  197. return completed ();
  198. return true;
  199. }
  200. }
  201. void RunMessagePump ()
  202. {
  203. while (running) {
  204. MyAction action;
  205. lock (sync) {
  206. while (queue.Count == 0) {
  207. if (IsCompleted)
  208. return;
  209. if (!Monitor.Wait (sync, timeout))
  210. throw new TimeoutException ();
  211. }
  212. action = queue.Dequeue ();
  213. }
  214. action ();
  215. }
  216. }
  217. public void Cancel ()
  218. {
  219. lock (sync) {
  220. running = false;
  221. Monitor.Pulse (sync);
  222. }
  223. }
  224. public static void Run (Func<Task> action, Func<bool> completed, int timeout)
  225. {
  226. var old_ctx = SynchronizationContext.Current;
  227. var ctx = new MessagePumpSyncContext (completed, timeout);
  228. try {
  229. SynchronizationContext.SetSynchronizationContext (ctx);
  230. var thread_id = Thread.CurrentThread.ManagedThreadId;
  231. var task = action ();
  232. task.ContinueWith ((t) => {
  233. ctx.running = false;
  234. }, TaskScheduler.FromCurrentSynchronizationContext ());
  235. ctx.RunMessagePump ();
  236. if (task.IsFaulted)
  237. throw task.Exception;
  238. } finally {
  239. SynchronizationContext.SetSynchronizationContext (old_ctx);
  240. }
  241. }
  242. }
  243. }
  244. }