PageRenderTime 39ms CodeModel.GetById 24ms app.highlight 12ms RepoModel.GetById 1ms app.codeStats 0ms

/mcs/class/System.Web/Test/mainsoft/MainsoftWebTest/NunitWebTest.cs

https://github.com/iainlane/mono
C# | 301 lines | 222 code | 35 blank | 44 comment | 48 complexity | fb69beadeb0a32fc256677e89cff2a4a MD5 | raw file
  1//
  2// Authors:
  3//   Rafael Mizrahi   <rafim@mainsoft.com>
  4//   Erez Lotan       <erezl@mainsoft.com>
  5//   Vladimir Krasnov <vladimirk@mainsoft.com>
  6//   
  7// 
  8// Copyright (c) 2002-2005 Mainsoft Corporation.
  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
 30
 31
 32using System;
 33using System.IO;
 34using System.Xml;
 35using System.Net;
 36using System.Text;
 37using System.Collections;
 38using System.Reflection;
 39
 40using NUnit.Framework;
 41
 42namespace MonoTests.stand_alone.WebHarness
 43{
 44	public class HtmlDiff
 45	{
 46		public const string BEGIN_TAG = "begint";
 47		public const string END_TAG = "endt";
 48
 49		private XmlDocument _xmlIgnoreList = null;
 50		private string _compareStatus = "";
 51		private static string _compareActual = "";
 52		private static string _compareExpect = "";
 53		private string _ignoreListFile = "";
 54
 55		
 56
 57		public HtmlDiff()
 58		{
 59		}
 60
 61		public string IgnoreListFile
 62		{
 63			get {return _ignoreListFile;}
 64			set {_ignoreListFile = value;}
 65		}
 66
 67		public string CompareStatus
 68		{
 69			get {return _compareStatus.ToString();}
 70		}
 71
 72		public static string GetControlFromPageHtml (string str)
 73		{
 74			return GetControlFromPageHtml (str, BEGIN_TAG, END_TAG);
 75		}
 76		
 77		public static string GetControlFromPageHtml (string str, string beginTag, string endTag)
 78		{
 79			if (str == null || str.Length == 0)
 80				throw new ArgumentException ("internal error: str is null or empty");
 81			if (beginTag == null || beginTag.Length == 0)
 82				throw new ArgumentNullException ("beginTag");
 83			if (endTag == null || endTag.Length == 0)
 84				throw new ArgumentNullException ("endTag");
 85			
 86			int beginPos = str.IndexOf (beginTag);
 87			int endPos = str.IndexOf (endTag);
 88			if (beginPos == -1)
 89				throw new InvalidOperationException (String.Format ("internal error: begin tag ('{0}') is missing. Full source: {1}", beginTag, str));
 90			if (endPos == -1)
 91				throw new InvalidOperationException (String.Format ("internal error: end tag ('{0}') is missing. Full source: {1}", endTag, str));
 92				
 93			StringBuilder sb = new StringBuilder ();
 94			sb.Append (str.Substring (beginPos + beginTag.Length, endPos - beginPos - beginTag.Length));
 95			return sb.ToString ();
 96		}
 97
 98		public static void AssertAreEqual (string origin, string derived, string msg)
 99		{
100			bool test = false;
101			try {
102				test = HtmlComparer (origin, derived);
103			}
104			catch (Exception e) {
105				//swallow e when there is XML error and fallback
106				//to the text comparison
107				Assert.AreEqual (origin, derived, msg);
108			}
109			if (!test) {
110				Assert.AreEqual (_compareExpect, _compareActual, msg);
111			}
112		}
113
114		private static bool HtmlComparer (string origin, string derived)
115		{
116			XmlDocument or = new XmlDocument ();
117			MonoTests.stand_alone.WebHarness.HtmlDiff helper = new MonoTests.stand_alone.WebHarness.HtmlDiff ();
118			or.LoadXml (helper.HtmltoXml (origin));
119			XmlDocument dr = new XmlDocument ();
120			dr.LoadXml (helper.HtmltoXml (derived));
121			return helper.XmlCompare (or, dr, false);
122		}
123
124		private bool XmlCompare(XmlDocument expected, XmlDocument actual, bool ignoreAlmost)
125		{
126			XmlComparer comparer = new XmlComparer();
127			if (ignoreAlmost == false)
128			{
129				DoAlmost(expected);
130				DoAlmost(actual);
131			}
132			bool c = comparer.AreEqual(expected, actual);
133			_compareStatus = comparer.LastCompare;
134			_compareActual = comparer.Actual;
135			_compareExpect = comparer.Expected;
136			return c;
137		}
138
139		public string HtmltoXml (string html) //throws XmlException
140		{
141			HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument ();
142			doc.LoadHtml (html.Trim (new char[] { '\r', '\n', ' ' })); // bug in HtmlAgilityPack
143
144			StringBuilder fixedxml = new StringBuilder ();
145			StringWriter sw = new StringWriter (fixedxml);
146
147			StringBuilder tempxml = new StringBuilder ();
148			StringWriter tsw = new StringWriter (tempxml);
149
150			doc.OptionOutputAsXml = true;
151			doc.Save (tsw);
152
153			// fix style attribute
154			// the reason is that style attribute name-value pairs come in different order
155			// in .NET and GH
156			// Here I will sort the values of style attribute
157			XmlDocument tempDoc = new XmlDocument ();
158			tempDoc.LoadXml (tempxml.ToString ());
159
160			XmlNodeList allNodes = tempDoc.SelectNodes ("//*");
161			foreach (XmlNode n in allNodes) {
162				if (n.Attributes["style"] != null) {
163					string att = n.Attributes["style"].Value;
164					string[] style = att.Trim (new char[] { ' ', ';' }).Split (';');
165
166					for (int styleIndex = 0; styleIndex < style.Length; styleIndex++) {
167						style[styleIndex] = FixStyleNameValue (style[styleIndex]);
168					}
169					Array.Sort (style);
170					n.Attributes["style"].Value = string.Join (";", style);
171				}
172			}
173			tempDoc.Save (sw);
174			return fixedxml.ToString ();
175		}
176
177		private string FixStyleNameValue(string nameValue)
178		{
179			string [] nv = nameValue.Split(':');
180			// value may contain spaces in case of
181			// multiple values for one key
182			string [] nvalue = nv[1].Trim().Split(' ');
183			Array.Sort(nvalue);
184			nv[1] = string.Join(" ", nvalue);
185			return nv[0].Trim().ToLower() + ":" + nv[1].Trim().ToLower();
186		}
187
188		private void DoAlmost(XmlDocument xmlDocument)
189		{
190			XmlNode XmlIgnoreNode;
191			IEnumerator xmlIgnoreEnum;
192
193
194			if (_xmlIgnoreList == null)
195			{
196				_xmlIgnoreList = new XmlDocument();
197				string xml;
198
199				Stream source = Assembly.GetExecutingAssembly ()
200					.GetManifestResourceStream ("HtmlCompare.nunitweb_config.xml");
201				if (source == null) {
202					source = Assembly.GetExecutingAssembly ()
203					.GetManifestResourceStream ("nunitweb_config.xml");
204				}
205								
206				try {
207					using (StreamReader sr = new StreamReader (source))
208						xml = sr.ReadToEnd ();
209				}
210				finally {
211					source.Close ();
212				}
213				
214				_xmlIgnoreList.LoadXml (xml);
215			}
216			// Remove by Id or Name
217			// search by tag and if id or name match, remove all attributes
218			// must be the first almost since the following almost delete the id and name
219			
220			xmlIgnoreEnum = _xmlIgnoreList.SelectSingleNode("Almost/RemoveById").GetEnumerator();
221			while (xmlIgnoreEnum.MoveNext())
222			{
223				XmlNodeList DocNodeList;
224				XmlIgnoreNode = (XmlNode)xmlIgnoreEnum.Current;
225				DocNodeList = xmlDocument.GetElementsByTagName("*");
226				if (DocNodeList != null)
227				{
228					foreach (XmlElement tmpXmlElement in DocNodeList)
229					{
230						foreach (XmlAttribute tmpIgnoreAttr in XmlIgnoreNode.Attributes)
231						{
232							if (tmpXmlElement.Name.ToLower() == XmlIgnoreNode.Name.ToLower()) 
233							{
234								if (tmpXmlElement.Attributes[tmpIgnoreAttr.Name] != null )
235								{
236									if (tmpXmlElement.Attributes[tmpIgnoreAttr.Name].Value.ToLower() == tmpIgnoreAttr.Value.ToLower())
237									{
238										tmpXmlElement.RemoveAllAttributes();
239									}
240								}
241							}
242						}
243					}
244				}	
245			}
246			// remove ignored attributes
247			// search for tag and remove it's attributes
248			xmlIgnoreEnum = _xmlIgnoreList.SelectSingleNode("Almost/IgnoreList").GetEnumerator(); //FirstChild.GetEnumerator
249			while (xmlIgnoreEnum.MoveNext())
250			{
251				XmlIgnoreNode = (XmlNode)xmlIgnoreEnum.Current;
252				XmlNodeList DocNodeList;
253				//clean specific element
254
255				DocNodeList = xmlDocument.GetElementsByTagName("*");
256				if (DocNodeList != null)
257				{
258					foreach (XmlElement tmpXmlElement in DocNodeList)
259					{
260						if (tmpXmlElement.Name.ToLower() == XmlIgnoreNode.Name.ToLower()) 
261						{
262							foreach (XmlAttribute tmpIgnoreAttr in XmlIgnoreNode.Attributes)
263							{
264								tmpXmlElement.RemoveAttribute(tmpIgnoreAttr.Name);
265							}
266						}
267					}
268				}
269			}
270
271			// clean javascript attribute value
272			xmlIgnoreEnum = _xmlIgnoreList.SelectSingleNode("Almost/CleanJavaScriptValueList").GetEnumerator(); //FirstChild.GetEnumerator
273			while (xmlIgnoreEnum.MoveNext())
274			{
275				XmlIgnoreNode = (XmlNode)xmlIgnoreEnum.Current;
276				XmlNodeList DocNodeList;
277				//clean Java Script attribute values
278				DocNodeList = xmlDocument.GetElementsByTagName("*");
279				if (DocNodeList != null)
280				{
281					foreach (XmlElement tmpXmlElement in DocNodeList)
282					{
283						if (tmpXmlElement.Name.ToLower() == XmlIgnoreNode.Name.ToLower()) 
284						{
285							foreach (XmlAttribute tmpIgnoreAttr in XmlIgnoreNode.Attributes)
286							{
287								if (tmpXmlElement.Attributes[tmpIgnoreAttr.Name] != null )
288								{
289									if (tmpXmlElement.Attributes[tmpIgnoreAttr.Name].Value.ToLower().IndexOf("javascript") >= 0 )
290									{
291										tmpXmlElement.SetAttribute(tmpIgnoreAttr.Name, "");
292									}
293								}
294							}
295						}
296					}
297				}
298			}
299		}
300	}
301}