PropertyCompareConstraint.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections;
  29. using System.Collections.Generic;
  30. using System.Drawing;
  31. using System.Linq;
  32. using System.Linq.Expressions;
  33. using System.Reflection;
  34. using NUnit.Framework;
  35. using NUnit.Framework.Constraints;
  36. using OpenMetaverse;
  37. using OpenSim.Framework;
  38. namespace OpenSim.Data.Tests
  39. {
  40. public static class Constraints
  41. {
  42. //This is here because C# has a gap in the language, you can't infer type from a constructor
  43. public static PropertyCompareConstraint<T> PropertyCompareConstraint<T>(T expected)
  44. {
  45. return new PropertyCompareConstraint<T>(expected);
  46. }
  47. }
  48. public class PropertyCompareConstraint<T> : NUnit.Framework.Constraints.Constraint
  49. {
  50. private readonly object _expected;
  51. //the reason everywhere uses propertyNames.Reverse().ToArray() is because the stack is backwards of the order we want to display the properties in.
  52. private string failingPropertyName = string.Empty;
  53. private object failingExpected;
  54. private object failingActual;
  55. public PropertyCompareConstraint(T expected)
  56. {
  57. _expected = expected;
  58. }
  59. public override bool Matches(object actual)
  60. {
  61. return ObjectCompare(_expected, actual, new Stack<string>());
  62. }
  63. private bool ObjectCompare(object expected, object actual, Stack<string> propertyNames)
  64. {
  65. //If they are both null, they are equal
  66. if (actual == null && expected == null)
  67. return true;
  68. //If only one is null, then they aren't
  69. if (actual == null || expected == null)
  70. {
  71. failingPropertyName = string.Join(".", propertyNames.Reverse().ToArray());
  72. failingActual = actual;
  73. failingExpected = expected;
  74. return false;
  75. }
  76. //prevent loops...
  77. if (propertyNames.Count > 50)
  78. {
  79. failingPropertyName = string.Join(".", propertyNames.Reverse().ToArray());
  80. failingActual = actual;
  81. failingExpected = expected;
  82. return false;
  83. }
  84. if (actual.GetType() != expected.GetType())
  85. {
  86. propertyNames.Push("GetType()");
  87. failingPropertyName = string.Join(".", propertyNames.Reverse().ToArray());
  88. propertyNames.Pop();
  89. failingActual = actual.GetType();
  90. failingExpected = expected.GetType();
  91. return false;
  92. }
  93. if (actual.GetType() == typeof(Color))
  94. {
  95. Color actualColor = (Color) actual;
  96. Color expectedColor = (Color) expected;
  97. if (actualColor.R != expectedColor.R)
  98. {
  99. propertyNames.Push("R");
  100. failingPropertyName = string.Join(".", propertyNames.Reverse().ToArray());
  101. propertyNames.Pop();
  102. failingActual = actualColor.R;
  103. failingExpected = expectedColor.R;
  104. return false;
  105. }
  106. if (actualColor.G != expectedColor.G)
  107. {
  108. propertyNames.Push("G");
  109. failingPropertyName = string.Join(".", propertyNames.Reverse().ToArray());
  110. propertyNames.Pop();
  111. failingActual = actualColor.G;
  112. failingExpected = expectedColor.G;
  113. return false;
  114. }
  115. if (actualColor.B != expectedColor.B)
  116. {
  117. propertyNames.Push("B");
  118. failingPropertyName = string.Join(".", propertyNames.Reverse().ToArray());
  119. propertyNames.Pop();
  120. failingActual = actualColor.B;
  121. failingExpected = expectedColor.B;
  122. return false;
  123. }
  124. if (actualColor.A != expectedColor.A)
  125. {
  126. propertyNames.Push("A");
  127. failingPropertyName = string.Join(".", propertyNames.Reverse().ToArray());
  128. propertyNames.Pop();
  129. failingActual = actualColor.A;
  130. failingExpected = expectedColor.A;
  131. return false;
  132. }
  133. return true;
  134. }
  135. IComparable comp = actual as IComparable;
  136. if (comp != null)
  137. {
  138. if (comp.CompareTo(expected) != 0)
  139. {
  140. failingPropertyName = string.Join(".", propertyNames.Reverse().ToArray());
  141. failingActual = actual;
  142. failingExpected = expected;
  143. return false;
  144. }
  145. return true;
  146. }
  147. //Now try the much more annoying IComparable<T>
  148. Type icomparableInterface = actual.GetType().GetInterface("IComparable`1");
  149. if (icomparableInterface != null)
  150. {
  151. int result = (int)icomparableInterface.GetMethod("CompareTo").Invoke(actual, new[] { expected });
  152. if (result != 0)
  153. {
  154. failingPropertyName = string.Join(".", propertyNames.Reverse().ToArray());
  155. failingActual = actual;
  156. failingExpected = expected;
  157. return false;
  158. }
  159. return true;
  160. }
  161. IEnumerable arr = actual as IEnumerable;
  162. if (arr != null)
  163. {
  164. List<object> actualList = arr.Cast<object>().ToList();
  165. List<object> expectedList = ((IEnumerable)expected).Cast<object>().ToList();
  166. if (actualList.Count != expectedList.Count)
  167. {
  168. propertyNames.Push("Count");
  169. failingPropertyName = string.Join(".", propertyNames.Reverse().ToArray());
  170. failingActual = actualList.Count;
  171. failingExpected = expectedList.Count;
  172. propertyNames.Pop();
  173. return false;
  174. }
  175. //actualList and expectedList should be the same size.
  176. for (int i = 0; i < actualList.Count; i++)
  177. {
  178. propertyNames.Push("[" + i + "]");
  179. if (!ObjectCompare(expectedList[i], actualList[i], propertyNames))
  180. return false;
  181. propertyNames.Pop();
  182. }
  183. //Everything seems okay...
  184. return true;
  185. }
  186. //Skip static properties. I had a nasty problem comparing colors because of all of the public static colors.
  187. PropertyInfo[] properties = expected.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
  188. foreach (var property in properties)
  189. {
  190. if (ignores.Contains(property.Name))
  191. continue;
  192. object actualValue = property.GetValue(actual, null);
  193. object expectedValue = property.GetValue(expected, null);
  194. propertyNames.Push(property.Name);
  195. if (!ObjectCompare(expectedValue, actualValue, propertyNames))
  196. return false;
  197. propertyNames.Pop();
  198. }
  199. return true;
  200. }
  201. public override void WriteDescriptionTo(MessageWriter writer)
  202. {
  203. writer.WriteExpectedValue(failingExpected);
  204. }
  205. public override void WriteActualValueTo(MessageWriter writer)
  206. {
  207. writer.WriteActualValue(failingActual);
  208. writer.WriteLine();
  209. writer.Write(" On Property: " + failingPropertyName);
  210. }
  211. //These notes assume the lambda: (x=>x.Parent.Value)
  212. //ignores should really contain like a fully dotted version of the property name, but I'm starting with small steps
  213. readonly List<string> ignores = new List<string>();
  214. public PropertyCompareConstraint<T> IgnoreProperty(Expression<Func<T, object>> func)
  215. {
  216. Expression express = func.Body;
  217. PullApartExpression(express);
  218. return this;
  219. }
  220. private void PullApartExpression(Expression express)
  221. {
  222. //This deals with any casts... like implicit casts to object. Not all UnaryExpression are casts, but this is a first attempt.
  223. if (express is UnaryExpression)
  224. PullApartExpression(((UnaryExpression)express).Operand);
  225. if (express is MemberExpression)
  226. {
  227. //If the inside of the lambda is the access to x, we've hit the end of the chain.
  228. // We should track by the fully scoped parameter name, but this is the first rev of doing this.
  229. ignores.Add(((MemberExpression)express).Member.Name);
  230. }
  231. }
  232. }
  233. [TestFixture]
  234. public class PropertyCompareConstraintTest
  235. {
  236. public class HasInt
  237. {
  238. public int TheValue { get; set; }
  239. }
  240. [Test]
  241. public void IntShouldMatch()
  242. {
  243. HasInt actual = new HasInt { TheValue = 5 };
  244. HasInt expected = new HasInt { TheValue = 5 };
  245. var constraint = Constraints.PropertyCompareConstraint(expected);
  246. Assert.That(constraint.Matches(actual), Is.True);
  247. }
  248. [Test]
  249. public void IntShouldNotMatch()
  250. {
  251. HasInt actual = new HasInt { TheValue = 5 };
  252. HasInt expected = new HasInt { TheValue = 4 };
  253. var constraint = Constraints.PropertyCompareConstraint(expected);
  254. Assert.That(constraint.Matches(actual), Is.False);
  255. }
  256. [Test]
  257. public void IntShouldIgnore()
  258. {
  259. HasInt actual = new HasInt { TheValue = 5 };
  260. HasInt expected = new HasInt { TheValue = 4 };
  261. var constraint = Constraints.PropertyCompareConstraint(expected).IgnoreProperty(x => x.TheValue);
  262. Assert.That(constraint.Matches(actual), Is.True);
  263. }
  264. [Test]
  265. public void AssetShouldMatch()
  266. {
  267. UUID uuid1 = UUID.Random();
  268. AssetBase actual = new AssetBase(uuid1, "asset one", (sbyte)AssetType.Texture, UUID.Zero.ToString());
  269. AssetBase expected = new AssetBase(uuid1, "asset one", (sbyte)AssetType.Texture, UUID.Zero.ToString());
  270. var constraint = Constraints.PropertyCompareConstraint(expected);
  271. Assert.That(constraint.Matches(actual), Is.True);
  272. }
  273. [Test]
  274. public void AssetShouldNotMatch()
  275. {
  276. UUID uuid1 = UUID.Random();
  277. AssetBase actual = new AssetBase(uuid1, "asset one", (sbyte)AssetType.Texture, UUID.Zero.ToString());
  278. AssetBase expected = new AssetBase(UUID.Random(), "asset one", (sbyte)AssetType.Texture, UUID.Zero.ToString());
  279. var constraint = Constraints.PropertyCompareConstraint(expected);
  280. Assert.That(constraint.Matches(actual), Is.False);
  281. }
  282. [Test]
  283. public void AssetShouldNotMatch2()
  284. {
  285. UUID uuid1 = UUID.Random();
  286. AssetBase actual = new AssetBase(uuid1, "asset one", (sbyte)AssetType.Texture, UUID.Zero.ToString());
  287. AssetBase expected = new AssetBase(uuid1, "asset two", (sbyte)AssetType.Texture, UUID.Zero.ToString());
  288. var constraint = Constraints.PropertyCompareConstraint(expected);
  289. Assert.That(constraint.Matches(actual), Is.False);
  290. }
  291. [Test]
  292. public void UUIDShouldMatch()
  293. {
  294. UUID uuid1 = UUID.Random();
  295. UUID uuid2 = UUID.Parse(uuid1.ToString());
  296. var constraint = Constraints.PropertyCompareConstraint(uuid1);
  297. Assert.That(constraint.Matches(uuid2), Is.True);
  298. }
  299. [Test]
  300. public void UUIDShouldNotMatch()
  301. {
  302. UUID uuid1 = UUID.Random();
  303. UUID uuid2 = UUID.Random();
  304. var constraint = Constraints.PropertyCompareConstraint(uuid1);
  305. Assert.That(constraint.Matches(uuid2), Is.False);
  306. }
  307. [Test]
  308. public void TestColors()
  309. {
  310. Color actual = Color.Red;
  311. Color expected = Color.FromArgb(actual.A, actual.R, actual.G, actual.B);
  312. var constraint = Constraints.PropertyCompareConstraint(expected);
  313. Assert.That(constraint.Matches(actual), Is.True);
  314. }
  315. [Test]
  316. public void ShouldCompareLists()
  317. {
  318. List<int> expected = new List<int> { 1, 2, 3 };
  319. List<int> actual = new List<int> { 1, 2, 3 };
  320. var constraint = Constraints.PropertyCompareConstraint(expected);
  321. Assert.That(constraint.Matches(actual), Is.True);
  322. }
  323. [Test]
  324. public void ShouldFailToCompareListsThatAreDifferent()
  325. {
  326. List<int> expected = new List<int> { 1, 2, 3 };
  327. List<int> actual = new List<int> { 1, 2, 4 };
  328. var constraint = Constraints.PropertyCompareConstraint(expected);
  329. Assert.That(constraint.Matches(actual), Is.False);
  330. }
  331. [Test]
  332. public void ShouldFailToCompareListsThatAreDifferentLengths()
  333. {
  334. List<int> expected = new List<int> { 1, 2, 3 };
  335. List<int> actual = new List<int> { 1, 2 };
  336. var constraint = Constraints.PropertyCompareConstraint(expected);
  337. Assert.That(constraint.Matches(actual), Is.False);
  338. }
  339. public class Recursive
  340. {
  341. public Recursive Other { get; set; }
  342. }
  343. [Test]
  344. public void ErrorsOutOnRecursive()
  345. {
  346. Recursive parent = new Recursive();
  347. Recursive child = new Recursive();
  348. parent.Other = child;
  349. child.Other = parent;
  350. var constraint = Constraints.PropertyCompareConstraint(child);
  351. Assert.That(constraint.Matches(child), Is.False);
  352. }
  353. }
  354. }