WebClientTestAsync.cs 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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. [Category("InetAccess")]
  76. public void DownloadFileTaskAsync ()
  77. {
  78. WebClient wc = new WebClient ();
  79. string filename = Path.GetTempFileName ();
  80. var task = wc.DownloadFileTaskAsync ("http://www.mono-project.com/", filename);
  81. Assert.IsTrue (task.Wait (15000));
  82. Assert.IsTrue (task.IsCompleted);
  83. File.Delete (filename);
  84. }
  85. [Test]
  86. [Category("InetAccess")]
  87. [Category ("AndroidNotWorking")] // Fails when ran as part of the entire BCL test suite. Works when only this fixture is ran
  88. public void Cancellation ()
  89. {
  90. WebClient wc = new WebClient ();
  91. var progress = new ManualResetEvent (false);
  92. wc.DownloadProgressChanged += delegate {
  93. progress.Set ();
  94. };
  95. // Try downloading some large file, so we don't finish early.
  96. 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";
  97. var task = wc.DownloadDataTaskAsync (url);
  98. Assert.IsTrue (progress.WaitOne (15000), "#1");
  99. wc.CancelAsync ();
  100. try {
  101. task.Wait ();
  102. Assert.Fail ("#2");
  103. } catch (Exception ex) {
  104. if (ex is AggregateException)
  105. ex = ((AggregateException)ex).InnerException;
  106. Assert.That (ex is WebException || ex is OperationCanceledException, "#4");
  107. Assert.IsTrue (task.IsCanceled || task.IsFaulted, "#5");
  108. }
  109. }
  110. [Test]
  111. [Category("InetAccess")]
  112. [Category ("AndroidNotWorking")] // Fails when ran as part of the entire BCL test suite. Works when only this fixture is ran
  113. public void DownloadMultiple ()
  114. {
  115. WebClient wc = new WebClient ();
  116. var t1 = wc.OpenReadTaskAsync ("http://www.google.com/");
  117. Assert.That (t1.Wait (15000));
  118. Assert.IsTrue (t1.IsCompleted, "#1");
  119. var t2 = wc.OpenReadTaskAsync ("http://www.mono-project.com/");
  120. Assert.That (t2.Wait (15000));
  121. Assert.IsTrue (t2.IsCompleted, "#2");
  122. var t3 = wc.DownloadStringTaskAsync ("http://www.google.com/");
  123. Assert.That (t3.Wait (15000));
  124. Assert.IsTrue (t3.IsCompleted, "#3");
  125. }
  126. [Test]
  127. [Category("InetAccess")]
  128. [Category ("AndroidNotWorking")] // Fails when ran as part of the entire BCL test suite. Works when only this fixture is ran
  129. public void DownloadMultiple2 ()
  130. {
  131. WebClient wc = new WebClient ();
  132. MessagePumpSyncContext.Run (async () => {
  133. await wc.DownloadStringTaskAsync ("http://www.google.com/");
  134. await wc.DownloadDataTaskAsync ("http://www.mono-project.com/");
  135. }, null, 15000);
  136. }
  137. [Test]
  138. [Category("InetAccess")]
  139. [Category ("AndroidNotWorking")] // Fails when ran as part of the entire BCL test suite. Works when only this fixture is ran
  140. public void DownloadMultiple3 ()
  141. {
  142. WebClient wc = new WebClient ();
  143. int thread_id = Thread.CurrentThread.ManagedThreadId;
  144. bool data_completed = false;
  145. bool string_completed = false;
  146. bool error = false;
  147. wc.DownloadDataCompleted += delegate {
  148. if (data_completed || (Thread.CurrentThread.ManagedThreadId != thread_id))
  149. error = true;
  150. data_completed = true;
  151. };
  152. wc.DownloadStringCompleted += delegate {
  153. if (string_completed || (Thread.CurrentThread.ManagedThreadId != thread_id))
  154. error = true;
  155. string_completed = true;
  156. };
  157. MessagePumpSyncContext.Run (async () => {
  158. await wc.DownloadStringTaskAsync ("http://www.google.com/");
  159. await wc.DownloadDataTaskAsync ("http://www.mono-project.com/");
  160. }, () => data_completed && string_completed, 15000);
  161. Assert.IsTrue (data_completed, "#1");
  162. Assert.IsTrue (string_completed, "#2");
  163. Assert.IsFalse (error, "#3");
  164. }
  165. public sealed class MessagePumpSyncContext : SynchronizationContext
  166. {
  167. private delegate void MyAction ();
  168. private readonly Queue<MyAction> queue = new Queue<MyAction> ();
  169. private readonly object sync = new object ();
  170. private readonly Func<bool> completed;
  171. private readonly int timeout;
  172. private bool running = true;
  173. MessagePumpSyncContext (Func<bool> completed, int timeout)
  174. {
  175. this.completed = completed;
  176. this.timeout = timeout;
  177. }
  178. public override void Send (SendOrPostCallback d, object state)
  179. {
  180. throw new InvalidOperationException ();
  181. }
  182. public override void Post (SendOrPostCallback d, object state)
  183. {
  184. lock (sync) {
  185. queue.Enqueue (() => d (state));
  186. Monitor.Pulse (sync);
  187. }
  188. }
  189. bool IsCompleted {
  190. get {
  191. if (running)
  192. return false;
  193. if (completed != null)
  194. return completed ();
  195. return true;
  196. }
  197. }
  198. void RunMessagePump ()
  199. {
  200. while (running) {
  201. MyAction action;
  202. lock (sync) {
  203. while (queue.Count == 0) {
  204. if (IsCompleted)
  205. return;
  206. if (!Monitor.Wait (sync, timeout))
  207. throw new TimeoutException ();
  208. }
  209. action = queue.Dequeue ();
  210. }
  211. action ();
  212. }
  213. }
  214. public void Cancel ()
  215. {
  216. lock (sync) {
  217. running = false;
  218. Monitor.Pulse (sync);
  219. }
  220. }
  221. public static void Run (Func<Task> action, Func<bool> completed, int timeout)
  222. {
  223. var old_ctx = SynchronizationContext.Current;
  224. var ctx = new MessagePumpSyncContext (completed, timeout);
  225. try {
  226. SynchronizationContext.SetSynchronizationContext (ctx);
  227. var thread_id = Thread.CurrentThread.ManagedThreadId;
  228. var task = action ();
  229. task.ContinueWith ((t) => {
  230. ctx.running = false;
  231. }, TaskScheduler.FromCurrentSynchronizationContext ());
  232. ctx.RunMessagePump ();
  233. if (task.IsFaulted)
  234. throw task.Exception;
  235. } finally {
  236. SynchronizationContext.SetSynchronizationContext (old_ctx);
  237. }
  238. }
  239. }
  240. }
  241. }