Wed Feb 24 15:47:16 CET 2010 Paolo Molaro <lupus@ximian.com>
[mono.git] / mcs / class / System.Web / Test / mainsoft / NunitWeb / NunitWeb / WebTest.cs
1 #if TARGET_JVM_FOR_WEBTEST
2 #define TARGET_JVM
3 #endif
4
5 using System;
6 using System.Reflection;
7 using System.IO;
8 using System.Web;
9 using System.Web.Hosting;
10 using System.Web.UI;
11 using System.Threading;
12
13 namespace MonoTests.SystemWeb.Framework
14 {
15         /// <summary>
16         /// The most important class from user perspective. See <see cref="Request"/>,
17         /// <see cref="Response"/>, <see cref="Invoker"/>, <see cref="Run"/> for
18         /// more information.
19         /// </summary>
20         /// <seealso cref="Request"/>
21         /// <seealso cref="Response"/>
22         /// <seealso cref="Invoker"/>
23         /// <seealso cref="Run"/>
24         [Serializable]
25         public class WebTest
26         {
27                 /// <summary>
28                 /// Thrown when trying to copy a resource after appdomain was created. Please call
29                 /// WebTest.Unload before copying resource.
30                 /// </summary>
31                 public class DomainUpException : Exception
32                 {
33                 }
34
35                 object _userData;
36                 /// <summary>
37                 /// Any user-defined data. Must be serializable to pass between appdomains.
38                 /// </summary>
39                 /// <example>
40                 /// [Test]
41                 /// public void SampleTest ()
42                 /// {
43                 ///     WebTest t = new WebTest (new HandlerInvoker (MyCallback));
44                 ///     t.Run ();
45                 ///     Assert.AreEqual ("Was here", t.UserData.ToString());
46                 /// }
47                 /// 
48                 /// static public void MyCallback ()
49                 /// {
50                 ///     WebTest.CurrentTest.UserData = "Was here";
51                 /// }
52                 /// </example>
53
54                 public object UserData
55                 {
56                         get { return _userData; }
57                         set { _userData = value; }
58                 }
59
60                 Response _response;
61                 /// <summary>
62                 /// The result of the last <see cref="Run"/>. See <see cref="MonoTests.SystemWeb.Framework.Response"/>,
63                 /// <see cref="FormRequest"/>.
64                 /// </summary>
65                 /// <seealso cref="Run"/>
66                 /// <seealso cref="MonoTests.SystemWeb.Framework.Response"/>
67                 /// <seealso cref="FormRequest"/>
68                 public Response Response
69                 {
70                         get { return _response; }
71                         set { _response = value; }
72                 }
73
74                 BaseInvoker _invoker;
75                 /// <summary>
76                 /// Set the invoker, which is executed in the web context by <see cref="Invoke"/>
77                 /// method. Most commonly used <see cref="PageInvoker"/>. See also: <see cref="BaseInvoker"/>,
78                 /// <see cref="HandlerInvoker"/>
79                 /// </summary>
80                 /// <seealso cref="Invoke"/>
81                 /// <seealso cref="PageInvoker"/>
82                 /// <seealso cref="BaseInvoker"/>
83                 /// <seealso cref="HandlerInvoker"/>
84                 public BaseInvoker Invoker
85                 {
86                         get { return _invoker; }
87                         set { _invoker = value; }
88                 }
89
90                 BaseRequest _request;
91                 /// <summary>
92                 /// Contains all the data necessary to create an <see cref="System.Web.HttpWorkerRequest"/> in
93                 /// the application appdomain. See also <see cref="BaseRequest"/>,
94                 /// <see cref="PostableRequest"/>, <see cref="FormRequest"/>.
95                 /// </summary>
96                 /// <seealso cref="System.Web.HttpWorkerRequest"/>
97                 /// <seealso cref="BaseRequest"/>
98                 /// <seealso cref="PostableRequest"/>
99                 /// <seealso cref="FormRequest"/>
100                 public BaseRequest Request
101                 {
102                         get { return _request; }
103                         set { _request = value; }
104                 }
105
106                 static MyHost host;
107                 internal static MyHost Host
108                 {
109                         get {
110                                 EnsureHosting ();
111                                 return host;
112                         }
113                 }
114
115                 /// <summary>
116                 /// Run the request using <see cref="Request"/> and <see cref="Invoker"/>
117                 /// values. Keep the result of the request in <see cref="Response"/> property.
118                 /// </summary>
119                 /// <returns>The body of the HTTP response (<see cref="MonoTests.SystemWeb.Framework.Response.Body"/>).</returns>
120                 /// <seealso cref="Request"/>
121                 /// <seealso cref="Invoker"/>
122                 /// <seealso cref="Response"/>
123                 /// <seealso cref="MonoTests.SystemWeb.Framework.Response.Body"/>
124                 public string Run ()
125                 {
126                         SystemWebTestShim.BuildManager.SuppressDebugModeMessages ();
127
128                         if (Request.Url == null)
129                                 Request.Url = Invoker.GetDefaultUrl ();
130                         _unloadHandler.StartingRequest();
131                         try {
132                                 WebTest newTestInstance = Host.Run (this);
133                                 CopyFrom (newTestInstance);
134                         } finally {
135                                 _unloadHandler.FinishedRequest();
136                         }
137                         return _response.Body;
138                 }
139                 
140                 private void CopyFrom (WebTest newTestInstance)
141                 {
142                         this._invoker = newTestInstance._invoker;
143                         this._request = newTestInstance._request;
144                         this._response = newTestInstance._response;
145                         this._userData = newTestInstance._userData;
146                 }
147
148                 /// <summary>
149                 /// The instance of the currently running test. Defined only in the web appdomain.
150                 /// In different threads this property may have different values.
151                 /// </summary>
152                 public static WebTest CurrentTest
153                 {
154                         get { return MyHost.GetCurrentTest (); }
155                 }
156
157                 /// <summary>
158                 /// This method must be called when custom <see cref="System.Web.IHttpHandler.ProcessRequest"/> or aspx code behind is used,
159                 /// to allow the framework to invoke all user supplied delegates.
160                 /// </summary>
161                 /// <param name="param">Parameter defined by the <see cref="BaseInvoker"/> subclass. For example,
162                 /// <see cref="PageInvoker"/> expects to receive a <see cref="System.Web.UI.Page"/> instance here.</param>
163                 /// <seealso cref="System.Web.IHttpHandler.ProcessRequest"/>
164                 /// <seealso cref="BaseInvoker"/>
165                 /// <seealso cref="PageInvoker"/>
166                 public void Invoke (object param)
167                 {
168                         try {
169                                 Invoker.DoInvoke (param);
170                         }
171                         catch (Exception ex) {
172                                 RegisterException (ex);
173                                 throw;
174                         }
175                 }
176
177                 public void SendHeaders ()
178                 {
179                         Host.SendHeaders (this);
180                 }
181
182                 /// <summary>
183                 /// This method is intended for use from <see cref="MonoTests.SystemWeb.Framework.BaseInvoker.DoInvoke"/> when
184                 /// the invocation causes an exception. In such cases, the exception must be registered
185                 /// with this method, and then swallowed. Before returning, <see cref="WebTest.Run"/>
186                 /// will rethrow this exception. This is done to hide the exception from <see cref="System.Web.HttpRuntime"/>,
187                 /// which normally swallows the exception and returns 500 ERROR http result.
188                 /// </summary>
189                 /// <param name="ex">The exception to be registered and rethrown.</param>
190                 /// <seealso cref="MonoTests.SystemWeb.Framework.BaseInvoker.DoInvoke"/>
191                 /// <seealso cref="WebTest.Run"/>
192                 /// <seealso cref="System.Web.HttpRuntime"/>
193                 public static void RegisterException (Exception ex)
194                 {
195                         Host.RegisterException (ex);
196                 }
197
198                 /// <summary>
199                 /// Unload the web appdomain and delete the temporary application root
200                 /// directory.
201                 /// </summary>
202                 public static void CleanApp ()
203                 {
204 #if !TARGET_JVM
205                         if (host != null) {
206                                 lock (_appUnloadedSync) {
207                                         EventHandler handler = new EventHandler(PulseAppUnloadedSync);
208                                         WebTest.AppUnloaded += handler;
209                                         WebTest t = new WebTest (PageInvoker.CreateOnLoad (new PageDelegate (UnloadAppDomain_OnLoad)));
210                                         t.Run ();
211                                         Monitor.Wait(_appUnloadedSync);
212                                         WebTest.AppUnloaded -= handler;
213                                 }                       
214                         }
215                         if (baseDir != null) {
216                                 Directory.Delete (baseDir, true);
217                                 baseDir = null;
218                                 binDir = null;
219                         }
220 #endif
221                 }
222                 
223                 private static object _appUnloadedSync = new object();
224                 
225                 private static void PulseAppUnloadedSync(object source, EventArgs args)
226                 {
227                         lock (_appUnloadedSync)
228                                 Monitor.PulseAll(_appUnloadedSync);
229                 }
230
231                 public static void UnloadAppDomain_OnLoad (Page p) 
232                 {
233                         HttpRuntime.UnloadAppDomain();
234                 }
235
236                 public static void Unload () {}
237
238                 /// <summary>
239                 /// Default constructor. Initializes <see cref="Invoker"/> with a new
240                 /// <see cref="BaseInvoker"/> and <see cref="Request"/> with an empty
241                 /// <see cref="BaseRequest"/>.
242                 /// </summary>
243                 /// <seealso cref="Invoker"/>
244                 /// <seealso cref="BaseInvoker"/>
245                 /// <seealso cref="Request"/>
246                 /// <seealso cref="BaseRequest"/>
247                 public WebTest ()
248                 {
249                         Invoker = new BaseInvoker ();
250                         Request = new BaseRequest ();
251                 }
252
253                 /// <summary>
254                 /// Same as <see cref="WebTest()"/>, and set <see cref="MonoTests.SystemWeb.Framework.BaseRequest.Url"/> to
255                 /// the specified Url.
256                 /// </summary>
257                 /// <param name="url">The URL used for the next <see cref="Run"/></param>
258                 /// <seealso cref="MonoTests.SystemWeb.Framework.BaseRequest.Url"/>
259                 /// <seealso cref="Run"/>
260                 public WebTest (string url)
261                         : this ()
262                 {
263                         Request.Url = url;
264                 }
265
266                 /// <summary>
267                 /// Create a new instance, initializing <see cref="Invoker"/> with the given
268                 /// value, and the <see cref="Request"/> with <see cref="BaseRequest"/>.
269                 /// </summary>
270                 /// <param name="invoker">The invoker used for this test.</param>
271                 /// <seealso cref="Invoker"/>
272                 /// <seealso cref="Request"/>
273                 /// <seealso cref="BaseRequest"/>
274                 public WebTest (BaseInvoker invoker)
275                         : this ()
276                 {
277                         Invoker = invoker;
278                 }
279
280                 /// <summary>
281                 /// Create a new instance, initializing <see cref="Request"/> with the given
282                 /// value, and the <see cref="Invoker"/> with <see cref="BaseInvoker"/>.
283                 /// </summary>
284                 /// <param name="request">The request used for this test.</param>
285                 /// <seealso cref="Request"/>
286                 /// <seealso cref="Invoker"/>
287                 /// <seealso cref="BaseInvoker"/>
288                 public WebTest (BaseRequest request)
289                         : this ()
290                 {
291                         Request = request;
292                 }
293
294
295                 /// <summary>
296                 /// Copy a resource embedded in the assembly into the web application
297                 /// </summary>
298                 /// <param name="type">A type in the assembly that contains the embedded resource.</param>
299                 /// <param name="resourceName">The name of the resource.</param>
300                 /// <param name="targetUrl">The URL where the resource will be available</param>
301                 /// <exception cref="System.ArgumentException">Thrown when resource with name resourceName is not found.</exception>
302                 /// <example><code>CopyResource (GetType (), "Default.skin", "App_Themes/Black/Default.skin");</code></example>
303                 public static void CopyResource (Type type, string resourceName, string targetUrl)
304                 {
305 #if !TARGET_JVM
306                         using (Stream source = type.Assembly.GetManifestResourceStream (resourceName)) {
307                                 if (source == null)
308                                         throw new ArgumentException ("resource not found: " + resourceName, "resourceName");
309                                 byte[] array = new byte[source.Length];
310                                 source.Read (array, 0, array.Length);
311                                 CopyBinary (array, targetUrl);
312                         }
313 #endif
314                 }
315
316                 /// <summary>
317                 /// Copy a chunk of data as a file into the web application.
318                 /// </summary>
319                 /// <param name="sourceArray">The array that contains the data to be written.</param>
320                 /// <param name="targetUrl">The URL where the data will be available.</param>
321                 /// <returns>The target filename where the data was stored.</returns>
322                 /// <example><code>CopyBinary (System.Text.Encoding.UTF8.GetBytes ("Hello"), "App_Data/Greeting.txt");</code></example>
323                 public static string CopyBinary (byte[] sourceArray, string targetUrl)
324                 {
325 #if TARGET_JVM
326                         return null;
327 #else
328                         EnsureWorkingDirectories ();
329                         EnsureDirectoryExists (Path.Combine (baseDir, Path.GetDirectoryName (targetUrl)));
330                         string targetFile = Path.Combine (baseDir, targetUrl);
331
332                         if (File.Exists(targetFile)) {
333                                 using (FileStream existing = File.OpenRead(targetFile)) {
334                                         bool equal = false;
335                                         if (sourceArray.Length == existing.Length) {
336                                                 byte[] existingArray = new byte[sourceArray.Length];
337                                                 existing.Read (existingArray, 0, existingArray.Length);
338                                                 
339                                                 equal = true;
340                                                 for (int i = 0; i < sourceArray.Length; i ++) {
341                                                         if (sourceArray[i] != existingArray[i]) {
342                                                                 equal = false;
343                                                                 break;
344                                                         }
345                                                 }
346                                         }
347                                         
348                                         if (equal) {
349                                                 existing.Close ();
350                                                 File.SetLastWriteTime (targetFile, DateTime.Now);
351                                                 return targetFile;
352                                         }
353                                         
354                                 }
355                                 
356                                 CheckDomainIsDown ();
357                         }
358
359                         using (FileStream target = new FileStream (targetFile, FileMode.Create)) {
360                                 target.Write (sourceArray, 0, sourceArray.Length);
361                         }
362
363                         return targetFile;
364 #endif
365                 }
366
367                 static WebTestResourcesSetupAttribute.SetupHandler CheckResourcesSetupHandler ()
368                 {
369                         // It is assumed WebTest is included in the same assembly which contains the
370                         // tests themselves
371                         object[] attributes = typeof (WebTest).Assembly.GetCustomAttributes (typeof (WebTestResourcesSetupAttribute), true);
372                         if (attributes == null || attributes.Length == 0)
373                                 return null;
374                         
375                         WebTestResourcesSetupAttribute attr = attributes [0] as WebTestResourcesSetupAttribute;
376                         if (attr == null)
377                                 return null;
378
379                         return attr.Handler;
380                 }
381                 
382                 public static void EnsureHosting ()
383                 {
384                         if (host != null)
385                                 return;
386 #if TARGET_JVM
387                         host = new MyHost ();
388                         return;
389 #else
390                         host = AppDomain.CurrentDomain.GetData (HOST_INSTANCE_NAME) as MyHost;
391                         if (host == null)
392                                 SetupHosting ();
393 #endif
394                 }
395                 
396                 public static void SetupHosting ()
397                 {
398                         SetupHosting (null);
399                 }
400                 
401                 public static void SetupHosting (WebTestResourcesSetupAttribute.SetupHandler resHandler)
402                 {
403 #if !TARGET_JVM
404                         if (host == null)
405                                 host = AppDomain.CurrentDomain.GetData (HOST_INSTANCE_NAME) as MyHost;
406 #endif
407                         if (host != null)
408                                 CleanApp ();
409 #if TARGET_JVM
410                         host = new MyHost ();
411                         return;
412 #else
413                         if (resHandler == null)
414                                 resHandler = CheckResourcesSetupHandler ();
415                         if (resHandler == null)
416                                 CopyResources ();
417                         else
418                                 resHandler ();
419                         
420                         foreach (Assembly ass in AppDomain.CurrentDomain.GetAssemblies ())
421                                 LoadAssemblyRecursive (ass);
422
423                         foreach (Assembly ass in AppDomain.CurrentDomain.GetAssemblies ())
424                                 CopyAssembly (ass, binDir);
425
426                         host = (MyHost) ApplicationHost.CreateApplicationHost (typeof (MyHost), VIRTUAL_BASE_DIR, baseDir);
427                         AppDomain.CurrentDomain.SetData (HOST_INSTANCE_NAME, host);
428                         host.AppDomain.SetData (HOST_INSTANCE_NAME, host);
429                         host.AppDomain.DomainUnload += new EventHandler (_unloadHandler.OnUnload);
430 #endif
431                 }
432
433                 private static UnloadHandler _unloadHandler = new UnloadHandler();
434                                 
435                 public class UnloadHandler : MarshalByRefObject
436                 {
437                         AutoResetEvent _unloaded = new AutoResetEvent(false);
438                         
439                         int _numRequestsPending = 0;
440                         object _syncUnloading = new object();
441                         object _syncNumRequestsPending = new object();
442                         
443                         internal void StartingRequest()
444                         {
445                                 // If the app domain is about to unload, wait
446                                 lock (_syncUnloading)
447                                         lock (_syncNumRequestsPending)
448                                                 _numRequestsPending++;
449                         }
450                         
451                         internal void FinishedRequest()
452                         {
453                                 // Let any unloading continue once there are not requests pending
454                                 lock (_syncNumRequestsPending) {
455                                         _numRequestsPending--;
456                                         if (_numRequestsPending == 0)
457                                                 Monitor.PulseAll(_syncNumRequestsPending);
458                                 }
459                         }
460                         
461                         public void OnUnload (object o, EventArgs args)
462                         {
463 #if !TARGET_JVM
464                 // Block new requests from starting
465                                 lock (_syncUnloading) {
466                                         // Wait for pending requests to finish
467                                         lock (_syncNumRequestsPending) {
468                                                 while (_numRequestsPending > 0)
469                                                         Monitor.Wait(_syncNumRequestsPending);
470                                         }
471                                         // Clear the host so that it will be created again on the next request
472                                         AppDomain.CurrentDomain.SetData (HOST_INSTANCE_NAME, null);
473                                         WebTest.host = null;
474                                         
475                                         EventHandler handler = WebTest.AppUnloaded;
476                                         if (handler != null)
477                                                 handler(this, null);
478                                 }
479 #endif
480             }
481                 }
482
483                 public static event EventHandler AppUnloaded;
484
485                 public static string TestBaseDir {
486                         get {
487 #if !TARGET_JVM
488                                 return baseDir;
489 #else
490                                 return String.Empty;
491 #endif
492                         }
493                 }
494                 
495 #if !TARGET_JVM
496                 const string VIRTUAL_BASE_DIR = "/NunitWeb";
497                 private static string baseDir;
498                 private static string binDir;
499                 const string HOST_INSTANCE_NAME = "MonoTests/SysWeb/Framework/Host";
500                 
501                 static void LoadAssemblyRecursive (Assembly ass)
502                 {
503                         if (ass.GlobalAssemblyCache)
504                                 return;
505                         foreach (AssemblyName ran in ass.GetReferencedAssemblies ()) {
506                                 bool found = false;
507                                 foreach (Assembly domain_ass in AppDomain.CurrentDomain.GetAssemblies ()) {
508                                         if (domain_ass.FullName == ran.FullName) {
509                                                 found = true;
510                                                 break;
511                                         }
512                                 }
513                                 if (found)
514                                         continue;
515                                 Assembly ra = Assembly.Load (ran, null);
516                                 LoadAssemblyRecursive (ra);
517                         }
518                 }
519
520                 private static void CopyAssembly (Assembly ass, string dir)
521                 {
522                         if (ass.GlobalAssemblyCache)
523                                 return;
524                         string oldfn = ass.Location;
525                         if (oldfn.EndsWith (".exe"))
526                                 return;
527                         string newfn = Path.Combine (dir, Path.GetFileName (oldfn));
528                         if (File.Exists (newfn))
529                                 return;
530                         EnsureDirectoryExists (dir);
531                         File.Copy (oldfn, newfn);
532                         if (File.Exists (oldfn + ".mdb"))
533                                 File.Copy (oldfn + ".mdb", newfn + ".mdb");
534                         if (File.Exists (oldfn + ".pdb"))
535                                 File.Copy (oldfn + ".pdb", newfn + ".pdb");
536                 }
537                 
538                 private static void EnsureDirectoryExists (string directory)
539                 {
540                         if (directory == string.Empty)
541                                 return;
542                         if (Directory.Exists (directory))
543                                 return;
544                         EnsureDirectoryExists (Path.GetDirectoryName (directory));
545                         Directory.CreateDirectory (directory);
546                 }
547
548                 private static void CheckDomainIsDown ()
549                 {
550                         if (host != null)
551                                 throw new DomainUpException ();
552                 }
553
554                 private static void EnsureWorkingDirectories ()
555                 {
556                         if (baseDir != null)
557                                 return;
558                         CreateWorkingDirectories ();
559                 }
560
561                 private static void CreateWorkingDirectories ()
562                 {
563                         string tmpFile = Path.GetTempFileName ();
564                         File.Delete (tmpFile);
565                         baseDir = tmpFile;
566                         Directory.CreateDirectory (tmpFile);
567                         binDir = Path.Combine (baseDir, "bin");
568                         Directory.CreateDirectory (binDir);
569                 }
570
571                 public static void CopyResources ()
572                 {
573                         CopyResource (typeof (WebTest), "My.ashx", "My.ashx");
574                         CopyResource (typeof (WebTest), "Global.asax", "Global.asax");
575 #if NET_2_0
576 #if INSIDE_SYSTEM_WEB
577                         CopyResource (typeof (WebTest), "Common.resx", "App_GlobalResources/Common.resx");
578                         CopyResource (typeof (WebTest), "Common.fr-FR.resx", "App_GlobalResources/Common.fr-FR.resx");
579                         CopyResource (typeof (WebTest), "Resource1.resx", "App_GlobalResources/Resource1.resx");
580                         CopyResource (typeof (WebTest), "EnumConverterControl.cs", "App_Code/EnumConverterControl.cs");
581 #endif
582                         CopyResource (typeof (WebTest), "Web.mono.config", "Web.config");
583 #else
584                         CopyResource (typeof (WebTest), "Web.mono.config.1.1", "Web.config");
585 #endif
586                         CopyResource (typeof (WebTest), "MyPage.aspx", "MyPage.aspx");
587                         CopyResource (typeof (WebTest), "MyPage.aspx.cs", "MyPage.aspx.cs");
588                         CopyResource (typeof (WebTest), "MyPageWithMaster.aspx", "MyPageWithMaster.aspx");
589                         CopyResource (typeof (WebTest), "My.master", "My.master");
590                 }
591 #endif
592         }
593 }