WebClientTestAsync.cs 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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. public void DownloadFileTaskAsync ()
  79. {
  80. WebClient wc = new WebClient ();
  81. string filename = Path.GetTempFileName ();
  82. var task = wc.DownloadFileTaskAsync ("http://www.mono-project.com/", filename);
  83. Assert.IsTrue (task.Wait (15000));
  84. Assert.IsTrue (task.IsCompleted);
  85. File.Delete (filename);
  86. }
  87. [Test]
  88. [Category ("NotWorking")] // 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 ("NotWorking")] // 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 ("NotWorking")] // Fails when ran as part of the entire BCL test suite. Works when only this fixture is ran
  128. public void DownloadMultiple2 ()
  129. {
  130. WebClient wc = new WebClient ();
  131. MessagePumpSyncContext.Run (async () => {
  132. await wc.DownloadStringTaskAsync ("http://www.google.com/");
  133. await wc.DownloadDataTaskAsync ("http://www.mono-project.com/");
  134. }, null, 15000);
  135. }
  136. [Test]
  137. [Category ("NotWorking")] // Fails when ran as part of the entire BCL test suite. Works when only this fixture is ran
  138. public void DownloadMultiple3 ()
  139. {
  140. WebClient wc = new WebClient ();
  141. int thread_id = Thread.CurrentThread.ManagedThreadId;
  142. bool data_completed = false;
  143. bool string_completed = false;
  144. bool error = false;
  145. wc.DownloadDataCompleted += delegate {
  146. if (data_completed || (Thread.CurrentThread.ManagedThreadId != thread_id))
  147. error = true;
  148. data_completed = true;
  149. };
  150. wc.DownloadStringCompleted += delegate {
  151. if (string_completed || (Thread.CurrentThread.ManagedThreadId != thread_id))
  152. error = true;
  153. string_completed = true;
  154. };
  155. MessagePumpSyncContext.Run (async () => {
  156. await wc.DownloadStringTaskAsync ("http://www.google.com/");
  157. await wc.DownloadDataTaskAsync ("http://www.mono-project.com/");
  158. }, () => data_completed && string_completed, 15000);
  159. Assert.IsTrue (data_completed, "#1");
  160. Assert.IsTrue (string_completed, "#2");
  161. Assert.IsFalse (error, "#3");
  162. }
  163. public sealed class MessagePumpSyncContext : SynchronizationContext
  164. {
  165. private delegate void MyAction ();
  166. private readonly Queue<MyAction> queue = new Queue<MyAction> ();
  167. private readonly object sync = new object ();
  168. private readonly Func<bool> completed;
  169. private readonly int timeout;
  170. private bool running = true;
  171. MessagePumpSyncContext (Func<bool> completed, int timeout)
  172. {
  173. this.completed = completed;
  174. this.timeout = timeout;
  175. }
  176. public override void Send (SendOrPostCallback d, object state)
  177. {
  178. throw new InvalidOperationException ();
  179. }
  180. public override void Post (SendOrPostCallback d, object state)
  181. {
  182. lock (sync) {
  183. queue.Enqueue (() => d (state));
  184. Monitor.Pulse (sync);
  185. }
  186. }
  187. bool IsCompleted {
  188. get {
  189. if (running)
  190. return false;
  191. if (completed != null)
  192. return completed ();
  193. return true;
  194. }
  195. }
  196. void RunMessagePump ()
  197. {
  198. while (running) {
  199. MyAction action;
  200. lock (sync) {
  201. while (queue.Count == 0) {
  202. if (IsCompleted)
  203. return;
  204. if (!Monitor.Wait (sync, timeout))
  205. throw new TimeoutException ();
  206. }
  207. action = queue.Dequeue ();
  208. }
  209. action ();
  210. }
  211. }
  212. public void Cancel ()
  213. {
  214. lock (sync) {
  215. running = false;
  216. Monitor.Pulse (sync);
  217. }
  218. }
  219. public static void Run (Func<Task> action, Func<bool> completed, int timeout)
  220. {
  221. var old_ctx = SynchronizationContext.Current;
  222. var ctx = new MessagePumpSyncContext (completed, timeout);
  223. try {
  224. SynchronizationContext.SetSynchronizationContext (ctx);
  225. var thread_id = Thread.CurrentThread.ManagedThreadId;
  226. var task = action ();
  227. task.ContinueWith ((t) => {
  228. ctx.running = false;
  229. }, TaskScheduler.FromCurrentSynchronizationContext ());
  230. ctx.RunMessagePump ();
  231. if (task.IsFaulted)
  232. throw task.Exception;
  233. } finally {
  234. SynchronizationContext.SetSynchronizationContext (old_ctx);
  235. }
  236. }
  237. }
  238. }
  239. }