WebClientTestAsync.cs 8.1 KB

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