PageRenderTime 21ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/LLBL Pro v4.2/AW.Test/CSharpSerializerTests.cs

#
C# | 243 lines | 197 code | 23 blank | 23 comment | 10 complexity | a0fbacc29c6dfb11e409fba32121864b MD5 | raw file
Possible License(s): CC-BY-SA-3.0, BSD-3-Clause, MIT, GPL-2.0, Apache-2.0
  1. using System;
  2. using System.CodeDom.Compiler;
  3. using System.Collections.Generic;
  4. using System.ComponentModel;
  5. using System.Configuration;
  6. using System.Data;
  7. using System.Drawing;
  8. using System.Linq;
  9. using System.Windows.Forms;
  10. using System.Xml;
  11. using AW.Helper;
  12. using AW.Helper.LLBL;
  13. using AW.Tests.Properties;
  14. using Fasterflect;
  15. using FluentAssertions;
  16. using FluentAssertions.Equivalency;
  17. using Microsoft.CSharp;
  18. using Microsoft.VisualStudio.TestTools.UnitTesting;
  19. using Northwind.DAL.Linq;
  20. using Northwind.DAL.SqlServer;
  21. using SD.LLBLGen.Pro.ORMSupportClasses;
  22. namespace AW.Tests
  23. {
  24. [TestClass]
  25. public partial class CSharpSerializerTests
  26. {
  27. [TestMethod]
  28. public void SerializerToCSharpTest()
  29. {
  30. var order = GetOrder();
  31. var rootVariable = TestSerializerToCSharp(order, "Description");
  32. Assert.IsTrue(CompareOrders(order, rootVariable), "Error: Object Literal does not match");
  33. rootVariable.ShouldBeEquivalentTo(order, options => options.IgnoringCyclicReferences());
  34. }
  35. [TestMethod, Ignore]
  36. public void SerializeSettingsToCSharpTest()
  37. {
  38. var rootVariable = TestSerializerToCSharp(Settings.Default, "Context,Attributes,DefaultValue,PropertyType");
  39. rootVariable.ShouldBeEquivalentTo(Settings.Default, options => options.IgnoringCyclicReferences());
  40. }
  41. [TestMethod]
  42. public void SerializeControlsToCSharpTest()
  43. {
  44. var controls = new List<Control> {new Control("Control1"), new Control("Control2"), new Control("Control3")};
  45. var rootVariable = TestSerializerToCSharp(controls,
  46. "Anchor,AutoScrollOffset,BackColor,Bounds,Cursor,DataBindings,Font,ForeColor,Margin,WindowTarget,Padding,ClientSize,Location,MaximumSize,MinimumSize,Size,Handle,HandleInternal");
  47. for (var index = 0; index < rootVariable.Count; index++)
  48. {
  49. var control = rootVariable[index];
  50. control.ShouldBeEquivalentTo(controls[index], options => options.ExcludingNestedObjects().ExcludingFields().Excluding(m => m.Handle).Excluding(m => m.SelectedMemberPath == "HandleInternal")
  51. .Excluding(m => m.SelectedMemberPath == "InternalHandle").Excluding(m => m.SelectedMemberPath == "Properties").Excluding(m => m.SelectedMemberPath == "TopMostParent")
  52. .Excluding(m => m.SelectedMemberPath == "WindowTarget").Excluding(m => m.SelectedMemberPath == "AccessibilityObject"));
  53. }
  54. //rootVariable.ShouldAllBeEquivalentTo(controls, options => options.Excluding(m => m.Handle).ExcludingNestedObjects()
  55. //.Excluding(m => m.SelectedMemberPath == "[0].HandleInternal").Excluding(m => m.SelectedMemberPath == "[0].InternalHandle").IgnoringCyclicReferences());
  56. }
  57. private static T TestSerializerToCSharp<T>(T obj, string globalExcludeProperties = "", params Restriction[] entityRestrictions)
  58. {
  59. return CreateCompilableSourceAndCompile<T>(obj.SerializeToCSharp(OutputFormat.Snippet, globalExcludeProperties, entityRestrictions), typeof(GeneralHelper)
  60. , typeof(DataRow), typeof(ApplicationSettingsBase), typeof(Control), typeof(Point));
  61. }
  62. /// <summary>
  63. /// Tests the c sharp source code by adding file header and compiling it.
  64. /// </summary>
  65. /// <typeparam name="T"></typeparam>
  66. /// <param name="result">The result.</param>
  67. /// <param name="types">The types.</param>
  68. /// <returns></returns>
  69. private static T CreateCompilableSourceAndCompile<T>(string result, params Type[] types)
  70. {
  71. var compilableSource = CreateCompilableSource(result, typeof(T));
  72. return CompilableSource<T>(compilableSource, GetAssemblies<T>(types));
  73. }
  74. /// <summary>
  75. /// Compiles the source and executes and returns the output of CSharpSerializer.ResultMethodName.
  76. /// </summary>
  77. /// <typeparam name="T"></typeparam>
  78. /// <param name="compilableSource">The compilable source.</param>
  79. /// <param name="types">The types.</param>
  80. /// <returns></returns>
  81. private static T CompilableSource<T>(string compilableSource, params Type[] types)
  82. {
  83. return CompilableSource<T>(compilableSource, GetAssemblies<T>(types));
  84. }
  85. private static string[] GetAssemblies<T>(IEnumerable<Type> types)
  86. {
  87. return types.Select(t => t.Assembly.Location).ToArray();
  88. }
  89. /// <summary>
  90. /// Compiles the source and executes and returns the output of CSharpSerializer.ResultMethodName.
  91. /// </summary>
  92. /// <typeparam name="T"></typeparam>
  93. /// <param name="compilableSource">The compilable source.</param>
  94. /// <param name="referencedAssemblies">The referenced assemblies.</param>
  95. /// <returns></returns>
  96. private static T CompilableSource<T>(string compilableSource, params string[] referencedAssemblies)
  97. {
  98. var expectedType = typeof(T);
  99. var cSharpCodeProvider = new CSharpCodeProvider();
  100. var compilerParameters = new CompilerParameters();
  101. compilerParameters.ReferencedAssemblies.Add(expectedType.Assembly.Location);
  102. compilerParameters.ReferencedAssemblies.AddRange(referencedAssemblies);
  103. foreach (var genericTypeArgument in expectedType.GenericTypeArguments)
  104. compilerParameters.ReferencedAssemblies.Add(genericTypeArgument.Assembly.Location);
  105. var compileAssemblyFromSource = cSharpCodeProvider.CompileAssemblyFromSource(compilerParameters, compilableSource);
  106. Assert.AreEqual(0, compileAssemblyFromSource.Errors.Count, compileAssemblyFromSource.Errors.OfType<CompilerError>().JoinAsString());
  107. var compiledAssembly = compileAssemblyFromSource.CompiledAssembly;
  108. var type = compiledAssembly.GetType(CSharpSerializer.ResultClassName);
  109. var rootVariable = type.CallMethod(CSharpSerializer.ResultMethodName);
  110. Assert.IsInstanceOfType(rootVariable, expectedType);
  111. return (T) rootVariable;
  112. }
  113. private static string CreateCompilableSource(string result, Type expectedType)
  114. {
  115. var rootVariableName = result.Before("=");
  116. rootVariableName = rootVariableName.After("var").Trim();
  117. var compilableSource = CSharpSerializer.FileHeader1;
  118. if (expectedType.Namespace != null && !compilableSource.Contains(expectedType.Namespace))
  119. compilableSource += "using " + expectedType.Namespace + ";" + Environment.NewLine;
  120. compilableSource = expectedType.GenericTypeArguments.Aggregate(compilableSource, (current, genericTypeArgument) => current + ("using " + genericTypeArgument.Namespace + ";" + Environment.NewLine));
  121. compilableSource += Environment.NewLine + CSharpSerializer.FileHeader2 + result + Environment.NewLine + "return " + rootVariableName + ";}}";
  122. return compilableSource;
  123. }
  124. public static LinqMetaData GetNorthwindLinqMetaData()
  125. {
  126. return new LinqMetaData(new DataAccessAdapter(), DataAccessAdapter.StaticCustomFunctionMappings);
  127. }
  128. [TestMethod]
  129. public void SerializerAdapterEntityToCSharpTest()
  130. {
  131. var northwindLinqMetaData = GetNorthwindLinqMetaData();
  132. var customerEntity = northwindLinqMetaData.Customer.First();
  133. var rootVariable = TestSerializerLlbltoCSharp(customerEntity);
  134. rootVariable.ShouldBeEquivalentTo(customerEntity, ExcludingLlblProperties());
  135. }
  136. private static Func<EquivalencyAssertionOptions<EntityBase2>, EquivalencyAssertionOptions<EntityBase2>> ExcludingLlblProperties()
  137. {
  138. return LlblAssertionOptions;
  139. }
  140. private static EquivalencyAssertionOptions<EntityBase2> LlblAssertionOptions(EquivalencyAssertionOptions<EntityBase2> options)
  141. {
  142. return options.IncludingAllRuntimeProperties().IgnoringCyclicReferences().Excluding(o => o.Fields).Excluding(o => o.IsDirty).Excluding(o => o.IsNew)
  143. .Excluding(ctx => ctx.SelectedMemberPath.EndsWith("Fields")).Excluding(ctx => ctx.SelectedMemberPath.EndsWith("IsDirty"))
  144. .Excluding(ctx => ctx.SelectedMemberPath.EndsWith("IsNew")).Excluding(ctx => ctx.SelectedMemberPath.EndsWith("Internal"))
  145. .Excluding(ctx => ctx.SelectedMemberPath.EndsWith("Picture")).Excluding(ctx => ctx.SelectedMemberPath.EndsWith("Photo"));
  146. }
  147. private static Func<EquivalencyAssertionOptions<EntityBase2>, EquivalencyAssertionOptions<EntityBase2>> ExcludingLlblProperties(params string[] memberPaths)
  148. {
  149. return options =>
  150. {
  151. var equivalencyAssertionOptions = LlblAssertionOptions(options);
  152. return memberPaths.Aggregate(equivalencyAssertionOptions, (current, memberPath) => current.Excluding(ctx => ctx.SelectedMemberPath.EndsWith(memberPath)));
  153. };
  154. }
  155. [TestMethod]
  156. public void SerializerAdapterToEntityCollectionToCSharpTest()
  157. {
  158. var northwindLinqMetaData = GetNorthwindLinqMetaData();
  159. var expectedCustomerEntities = northwindLinqMetaData.Customer.Take(3).PrefetchOrders().ToEntityCollection2(); //.ToEntityCollection2();
  160. var actualCustomerEntities = TestSerializerLlbltoCSharp(expectedCustomerEntities);
  161. actualCustomerEntities.ShouldAllBeEquivalentTo(expectedCustomerEntities, ExcludingLlblProperties("Customer"));
  162. var expectedOrderEntities = expectedCustomerEntities[0].Orders;
  163. var actualOrderEntities = expectedCustomerEntities[0].Orders;
  164. Assert.AreEqual(expectedOrderEntities.Count, actualOrderEntities.Count, "Orders.Count");
  165. actualOrderEntities.ShouldAllBeEquivalentTo(expectedOrderEntities, ExcludingLlblProperties());
  166. }
  167. [TestMethod]
  168. public void SerializeAdapterEntityCollectionWithPrefetchToCSharpTest()
  169. {
  170. var northwindLinqMetaData = GetNorthwindLinqMetaData();
  171. var productEntities = northwindLinqMetaData.Product.Take(3).PrefetchCategorySupplier().ToEntityCollection2();
  172. var productEntitiesCompiled = TestSerializerLlbltoCSharp(productEntities);
  173. productEntitiesCompiled.ShouldAllBeEquivalentTo(productEntities, ExcludingLlblProperties("Category", "Supplier"));
  174. }
  175. private static T TestSerializerLlbltoCSharp<T>(T obj)
  176. {
  177. var result = obj.SerializeToCSharp(OutputFormat.Compileable, "Fields,EntityFactoryToUse,Picture,Photo");
  178. var rootVariable = CompilableSource<T>(result, typeof(EntityBase2), typeof(IEditableObject), typeof(XmlEntity),
  179. typeof(GeneralHelper), typeof(DataRow));
  180. return rootVariable;
  181. }
  182. [TestMethod]
  183. public void SerializerCustomerEntityWithOrderTest()
  184. {
  185. var customer = GetCustomerEntityWithOrder();
  186. var actualCustomer = TestSerializerLlbltoCSharp(customer);
  187. actualCustomer.ShouldBeEquivalentTo(customer, ExcludingLlblProperties());
  188. }
  189. [TestMethod]
  190. public void SerializerCustomerEntityCollectionWithOrderTest()
  191. {
  192. var customerEntities = GetCustomerEntityCollectionWithOrder();
  193. var rootVariable2 = TestSerializerLlbltoCSharp(customerEntities);
  194. rootVariable2.ShouldAllBeEquivalentTo(customerEntities, ExcludingLlblProperties());
  195. }
  196. [TestMethod]
  197. public void SerializeOrdersPrefetchAlltoCSharpTest()
  198. {
  199. var northwindLinqMetaData = GetNorthwindLinqMetaData();
  200. var orderEntities = northwindLinqMetaData.Order.Take(3).PrefetchAll().ToEntityCollection2();
  201. var actualOrders = TestSerializerLlbltoCSharp(orderEntities);
  202. actualOrders.ShouldAllBeEquivalentTo(orderEntities, ExcludingLlblProperties("Customer", "Employee", "Shipper", "OrderDetails"));
  203. }
  204. [TestMethod]
  205. public void SerializeEmployeesPrefetchAlltoCSharpTest()
  206. {
  207. var northwindLinqMetaData = GetNorthwindLinqMetaData();
  208. var employeeEntities = northwindLinqMetaData.Employee.Take(3).PrefetchAll().ToEntityCollection2();
  209. var actualEmployees = TestSerializerLlbltoCSharp(employeeEntities);
  210. actualEmployees.ShouldAllBeEquivalentTo(employeeEntities, ExcludingLlblProperties("Manager", "Orders", "Staff"));
  211. }
  212. [TestMethod]
  213. public void SerializerProductsWithCategoriesTest()
  214. {
  215. var productEntities = GetProductsWithCategories();
  216. var rootVariable2 = TestSerializerLlbltoCSharp(productEntities);
  217. rootVariable2.ShouldAllBeEquivalentTo(productEntities, ExcludingLlblProperties());
  218. }
  219. }
  220. }