PageRenderTime 51ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/Vita.Data.UnitTests/BooksDemo/BooksDemoTest.cs

#
C# | 224 lines | 168 code | 22 blank | 34 comment | 12 complexity | b8d08f6c6995c354b7ef6dac3e067f47 MD5 | raw file
  1. using System;
  2. using System.Linq;
  3. using System.Diagnostics;
  4. using Vita.Data;
  5. namespace Vita.Data.UnitTests.BooksDemo {
  6. #if USE_NUNIT
  7. using NUnit.Framework;
  8. #else
  9. using Microsoft.VisualStudio.TestTools.UnitTesting;
  10. using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
  11. using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
  12. using SetUp = Microsoft.VisualStudio.TestTools.UnitTesting.TestInitializeAttribute;
  13. #endif
  14. [TestFixture]
  15. public class BooksDemoTest {
  16. [SetUp]
  17. public void Setup() {
  18. TestHelper.CheckCanConnect(true);
  19. TestHelper.DropSchemaObjects("books");
  20. }
  21. [Test]
  22. public void TestBooksDemo() {
  23. TestHelper.CheckCanConnect();
  24. Write(" ");
  25. Write(" ");
  26. //Setup model, initialize Books module, create database model, update schema -------------------------------------------------
  27. Write("Constructing Entity model...");
  28. var modelSetup = TestHelper.CreateModelSetup("Books");
  29. // The following settings are in fact defaults;
  30. // change it to run without stored procs (direct SQL only) or without ref integrity in database;
  31. modelSetup.DbSettings.Options = DbModelOptions.UseStoredProcs | DbModelOptions.UseRefIntegrity;
  32. var booksModule = new BooksModule(modelSetup, "books");
  33. var model = modelSetup.CreateModel(); //created Entity Model
  34. var db = model.Connect(TestHelper.TestConnectionString); //created Database object
  35. Write("Updating database schema...");
  36. db.UpdateSchema();
  37. model.CheckActivationLog();
  38. //Delete old records so they do not impact record counts in assertions below
  39. Write("Deleting all old data...");
  40. booksModule.DeleteAll(db);
  41. Write(" ");
  42. //Create some entities in database: publishers, authors, books -----------------------------------------------------
  43. var session = db.OpenSession();
  44. Write("Creating test data in database...");
  45. session = db.OpenSession();
  46. var msPub = session.NewPublisher("MS Books"); //we are using extension method here
  47. var kidPub = session.NewPublisher("Kids Books");
  48. var john = session.NewAuthor("John", "Sharp");
  49. var jack = session.NewAuthor("Jack", "Pound");
  50. //Books on programming from MS Books
  51. var csBook = session.NewBook(BookType.Paperback, "c# Programming", "Expert programming in c#", msPub, 20.0, 10);
  52. csBook.Authors.Add(john); //this is many-to-many
  53. csBook.Authors.Add(jack);
  54. var vbBook = session.NewBook(BookType.Paperback, "VB Programming", "Expert programming in VB", msPub, 25.0, 10);
  55. vbBook.Authors.Add(jack);
  56. //Folk tale, no authors
  57. var kidBook = session.NewBook(BookType.Hardcover, "Three little pigs", "Folk tale", kidPub, 10.0, 15);
  58. //Let's remember some ID's, we'll use them later
  59. var msPubId = msPub.Id;
  60. var csBookId = csBook.Id;
  61. var vbBookId = vbBook.Id;
  62. var kidBookId = kidBook.Id;
  63. session.SaveChanges(); //Save all
  64. Write(" Done. Created 2 authors, 2 publishers and 3 books.");
  65. Write(" ");
  66. //Load all books and print titles
  67. Write("Reading back all books:");
  68. session = db.OpenSession();
  69. var allBooks = session.GetAll<IBook>().ToList();
  70. AssertTrue(3 == allBooks.Count, "Invalid # of books");
  71. foreach (var bk in allBooks)
  72. Write(" Book: " + bk.Title + " from " + bk.Publisher.Name);
  73. Write(" ");
  74. //Loading entities by primary key --------------------------------------------------------
  75. // Verify that parent objects referenced by the same FK value result in the same object
  76. Write("Loading books by Book Id:");
  77. session = db.OpenSession();
  78. // load book by ID, check the title
  79. csBook = session.GetEntity<IBook>(csBookId);
  80. AssertTrue(csBook != null, "Failed to find the book by Id.");
  81. AssertTrue(csBook.Title == "c# Programming", "Loading book by Id: wrong book loaded, title mismatch.");
  82. vbBook = session.GetEntity<IBook>(vbBookId);
  83. AssertTrue(vbBook != null, "Failed to find the book by Id.");
  84. Write(" Done: Loaded and verified 2 programming books.");
  85. //Compare publishers as objects
  86. object csPubObj = csBook.Publisher;
  87. object vbPubObj = vbBook.Publisher;
  88. AssertTrue(csPubObj != null, "Publisher is null!");
  89. AssertTrue(csPubObj == vbPubObj, "c# and vb books publishers is not the same Publisher instance.");
  90. Write(" Verified: both loaded books reference the same Publisher instance.");
  91. Write(" ");
  92. // Validation ------------------------------------------------------------------------------------
  93. Write("Entity validation: trying to save entities with errors.");
  94. session = db.OpenSession();
  95. var invalidAuthor = session.NewAuthor(null, "VeryLoooooooooooooooooooooooooooongLastName");
  96. var invalidBook = session.NewBook(BookType.EBook, "Not valid book", "Some invalid book", null, -5.0, 10);
  97. //We expect 4 errors: Author's first name should not be null; Author's last name is too long; Publisher cannot be null;
  98. // Price must be > 1 cent. The first 3 errors are found by built-in validation; the last error, price check, is added
  99. // by custom validation method.
  100. try {
  101. session.SaveChanges();
  102. } catch (ValidationException vex) {
  103. AssertTrue(vex.Errors.Count == 4, "Found validation errors.");
  104. foreach (var err in vex.Errors)
  105. Write(" Error: " + err.ToString());
  106. }
  107. Write(" ");
  108. // Entity lists, one-to-many -----------------------------------------------------------------------
  109. // For a publisher, get the books (Publisher.Books)
  110. Write("Entity Lists, one-to-many. ");
  111. Write("Loading a publisher and enumerating its Books property: ");
  112. session = db.OpenSession();
  113. msPub = session.GetEntity<IPublisher>(msPubId);
  114. AssertTrue(2 == msPub.Books.Count, "Invalid # of books from MS Books");
  115. foreach (var bk in msPub.Books)
  116. Write(" Book: " + bk.Title);
  117. Write(" ");
  118. //Entity lists, many-to-many -----------------------------------------------------------------------
  119. Write("Entity Lists, many-to-many... ");
  120. Write("Loading a book (about c#) and enumerating its Authors property: ");
  121. session = db.OpenSession();
  122. csBook = session.GetEntity<IBook>(csBookId);
  123. AssertTrue(2 == csBook.Authors.Count, "Invalid authors count for c# book");
  124. foreach (var a in csBook.Authors)
  125. Console.WriteLine(" Author: " + a.FullName);
  126. Write(" ");
  127. //Direct LINQ query ----------------------------------------------------------------------------------
  128. Write("Direct LINQ query... ");
  129. Write(" Finding books by publisher's name 'MS Books':");
  130. session = db.OpenSession();
  131. var books = session.Linq.EntitySet<IBook>();
  132. //let's find books by publisher's name
  133. var msbooks = from b in books
  134. where b.Publisher.Name == "MS Books"
  135. orderby b.Title
  136. select b;
  137. var msBookList = msbooks.ToList();
  138. foreach (var b in msBookList)
  139. Console.WriteLine(" Book: " + b.Title);
  140. //Records retrieved by LINQ are attached to session, they are updatable.
  141. // Change the price of c# book (from 20 to 10) and save it; read it again and check that the price has changed
  142. Write("Updating a book retrieved by LINQ query: ");
  143. Write(" Changing price of c# book from 20 to 10.");
  144. csBook = msBookList[0]; //we know it's the first book, we sort by title
  145. csBook.Price = 10.00;
  146. session.SaveChanges();
  147. session = db.OpenSession(); //start another session to make sure we load fresh version
  148. csBook = session.GetEntity<IBook>(csBookId);
  149. AssertTrue(Math.Abs(csBook.Price - 10) < 0.01, "Book price did not change to 10.");
  150. Write(" Done, verified. ");
  151. Write(" ");
  152. // Using SELECT custom stored proc ------------------------------------------------------------------
  153. Write("Using SELECT custom stored procedure BooksGetByAuthor.");
  154. // Get books by author name
  155. session = db.OpenSession();
  156. var booksByJack = booksModule.GetBooksByAuthor(session, "Pound");
  157. AssertTrue(2 == booksByJack.Count, "Found wrong # of books by Jack Pound.");
  158. Write(" Done, found 2 books by Jack.");
  159. Write(" ");
  160. #if !SQL_CE
  161. // Using UPDATE custom stored proc ------------------------------------------------------------------
  162. Write("Using UPDATE custom stored procedure BooksChangePrice.");
  163. Write(" Reducing price by 20% on all hardcover books.");
  164. //Use stored proc to reduce the price by 20% on all hardcovers
  165. // We have Kid book in Hardcovers, original price 10
  166. booksModule.ChangePrice(session, BookType.Hardcover, -20);
  167. //check that changes actually took place
  168. session = db.OpenSession();
  169. kidBook = session.GetEntity<IBook>(kidBookId);
  170. //Original price 10, now it should be 8
  171. AssertTrue(Math.Abs(8 - kidBook.Price) < 0.01, "Kids book price is not reduced after discount.");
  172. Write(" Done, verified - hardcover book price changed from 10 to 8.");
  173. Write(" ");
  174. // Using DELETE custom stored proc -------------------------------------------------------------------
  175. Write("Using DELETE custom stored procedure BooksDeleteZeroQuantity.");
  176. Write(" Preparation: load a book, change its quantity to 0, update it.");
  177. // Set kids book quantity to zero, then delete all books with zero quantity using stored procedure
  178. session = db.OpenSession();
  179. kidBook = session.GetEntity<IBook>(kidBookId);
  180. kidBook.Quantity = 0;
  181. session.SaveChanges();
  182. Write(" Done.");
  183. Write(" Now delete books with zero quantity using stored proc BooksDeleteZeroQuantity.");
  184. booksModule.DeleteBooksWithZeroQuantity(session);
  185. //check it is deleted
  186. session = db.OpenSession();
  187. kidBook = session.GetEntity<IBook>(kidBookId);
  188. AssertTrue(kidBook == null, "Books with zero quantity were not deleted");
  189. Write(" Done, verified - book deleted.");
  190. #endif
  191. Write(" ");
  192. Write("End Demo");
  193. Write("Have a look at the database populated by this demo - tables, indexes, stored procedures, data, etc.");
  194. }//method
  195. private static void Write(string text) {
  196. Debug.WriteLine(text);
  197. }
  198. private static void AssertTrue(bool condition, string message) {
  199. Assert.IsTrue(condition, message);
  200. }
  201. }//class
  202. }