/Vita.Data.UnitTests/BooksDemo/BooksDemoTest.cs
C# | 224 lines | 168 code | 22 blank | 34 comment | 12 complexity | b8d08f6c6995c354b7ef6dac3e067f47 MD5 | raw file
- using System;
- using System.Linq;
- using System.Diagnostics;
- using Vita.Data;
-
-
- namespace Vita.Data.UnitTests.BooksDemo {
- #if USE_NUNIT
- using NUnit.Framework;
- #else
- using Microsoft.VisualStudio.TestTools.UnitTesting;
- using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
- using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
- using SetUp = Microsoft.VisualStudio.TestTools.UnitTesting.TestInitializeAttribute;
- #endif
-
-
- [TestFixture]
- public class BooksDemoTest {
-
- [SetUp]
- public void Setup() {
- TestHelper.CheckCanConnect(true);
- TestHelper.DropSchemaObjects("books");
- }
-
- [Test]
- public void TestBooksDemo() {
- TestHelper.CheckCanConnect();
- Write(" ");
- Write(" ");
- //Setup model, initialize Books module, create database model, update schema -------------------------------------------------
- Write("Constructing Entity model...");
- var modelSetup = TestHelper.CreateModelSetup("Books");
- // The following settings are in fact defaults;
- // change it to run without stored procs (direct SQL only) or without ref integrity in database;
- modelSetup.DbSettings.Options = DbModelOptions.UseStoredProcs | DbModelOptions.UseRefIntegrity;
- var booksModule = new BooksModule(modelSetup, "books");
- var model = modelSetup.CreateModel(); //created Entity Model
- var db = model.Connect(TestHelper.TestConnectionString); //created Database object
- Write("Updating database schema...");
- db.UpdateSchema();
- model.CheckActivationLog();
-
- //Delete old records so they do not impact record counts in assertions below
- Write("Deleting all old data...");
- booksModule.DeleteAll(db);
- Write(" ");
-
- //Create some entities in database: publishers, authors, books -----------------------------------------------------
- var session = db.OpenSession();
- Write("Creating test data in database...");
- session = db.OpenSession();
- var msPub = session.NewPublisher("MS Books"); //we are using extension method here
- var kidPub = session.NewPublisher("Kids Books");
- var john = session.NewAuthor("John", "Sharp");
- var jack = session.NewAuthor("Jack", "Pound");
- //Books on programming from MS Books
- var csBook = session.NewBook(BookType.Paperback, "c# Programming", "Expert programming in c#", msPub, 20.0, 10);
- csBook.Authors.Add(john); //this is many-to-many
- csBook.Authors.Add(jack);
- var vbBook = session.NewBook(BookType.Paperback, "VB Programming", "Expert programming in VB", msPub, 25.0, 10);
- vbBook.Authors.Add(jack);
- //Folk tale, no authors
- var kidBook = session.NewBook(BookType.Hardcover, "Three little pigs", "Folk tale", kidPub, 10.0, 15);
- //Let's remember some ID's, we'll use them later
- var msPubId = msPub.Id;
- var csBookId = csBook.Id;
- var vbBookId = vbBook.Id;
- var kidBookId = kidBook.Id;
- session.SaveChanges(); //Save all
- Write(" Done. Created 2 authors, 2 publishers and 3 books.");
- Write(" ");
-
- //Load all books and print titles
- Write("Reading back all books:");
- session = db.OpenSession();
- var allBooks = session.GetAll<IBook>().ToList();
- AssertTrue(3 == allBooks.Count, "Invalid # of books");
- foreach (var bk in allBooks)
- Write(" Book: " + bk.Title + " from " + bk.Publisher.Name);
- Write(" ");
-
- //Loading entities by primary key --------------------------------------------------------
- // Verify that parent objects referenced by the same FK value result in the same object
- Write("Loading books by Book Id:");
- session = db.OpenSession();
- // load book by ID, check the title
- csBook = session.GetEntity<IBook>(csBookId);
- AssertTrue(csBook != null, "Failed to find the book by Id.");
- AssertTrue(csBook.Title == "c# Programming", "Loading book by Id: wrong book loaded, title mismatch.");
- vbBook = session.GetEntity<IBook>(vbBookId);
- AssertTrue(vbBook != null, "Failed to find the book by Id.");
- Write(" Done: Loaded and verified 2 programming books.");
- //Compare publishers as objects
- object csPubObj = csBook.Publisher;
- object vbPubObj = vbBook.Publisher;
- AssertTrue(csPubObj != null, "Publisher is null!");
- AssertTrue(csPubObj == vbPubObj, "c# and vb books publishers is not the same Publisher instance.");
- Write(" Verified: both loaded books reference the same Publisher instance.");
- Write(" ");
-
- // Validation ------------------------------------------------------------------------------------
- Write("Entity validation: trying to save entities with errors.");
- session = db.OpenSession();
- var invalidAuthor = session.NewAuthor(null, "VeryLoooooooooooooooooooooooooooongLastName");
- var invalidBook = session.NewBook(BookType.EBook, "Not valid book", "Some invalid book", null, -5.0, 10);
- //We expect 4 errors: Author's first name should not be null; Author's last name is too long; Publisher cannot be null;
- // Price must be > 1 cent. The first 3 errors are found by built-in validation; the last error, price check, is added
- // by custom validation method.
- try {
- session.SaveChanges();
- } catch (ValidationException vex) {
- AssertTrue(vex.Errors.Count == 4, "Found validation errors.");
- foreach (var err in vex.Errors)
- Write(" Error: " + err.ToString());
- }
- Write(" ");
-
- // Entity lists, one-to-many -----------------------------------------------------------------------
- // For a publisher, get the books (Publisher.Books)
- Write("Entity Lists, one-to-many. ");
- Write("Loading a publisher and enumerating its Books property: ");
- session = db.OpenSession();
- msPub = session.GetEntity<IPublisher>(msPubId);
- AssertTrue(2 == msPub.Books.Count, "Invalid # of books from MS Books");
- foreach (var bk in msPub.Books)
- Write(" Book: " + bk.Title);
- Write(" ");
-
- //Entity lists, many-to-many -----------------------------------------------------------------------
- Write("Entity Lists, many-to-many... ");
- Write("Loading a book (about c#) and enumerating its Authors property: ");
- session = db.OpenSession();
- csBook = session.GetEntity<IBook>(csBookId);
- AssertTrue(2 == csBook.Authors.Count, "Invalid authors count for c# book");
- foreach (var a in csBook.Authors)
- Console.WriteLine(" Author: " + a.FullName);
- Write(" ");
-
- //Direct LINQ query ----------------------------------------------------------------------------------
- Write("Direct LINQ query... ");
- Write(" Finding books by publisher's name 'MS Books':");
- session = db.OpenSession();
- var books = session.Linq.EntitySet<IBook>();
- //let's find books by publisher's name
- var msbooks = from b in books
- where b.Publisher.Name == "MS Books"
- orderby b.Title
- select b;
- var msBookList = msbooks.ToList();
- foreach (var b in msBookList)
- Console.WriteLine(" Book: " + b.Title);
- //Records retrieved by LINQ are attached to session, they are updatable.
- // Change the price of c# book (from 20 to 10) and save it; read it again and check that the price has changed
- Write("Updating a book retrieved by LINQ query: ");
- Write(" Changing price of c# book from 20 to 10.");
- csBook = msBookList[0]; //we know it's the first book, we sort by title
- csBook.Price = 10.00;
- session.SaveChanges();
- session = db.OpenSession(); //start another session to make sure we load fresh version
- csBook = session.GetEntity<IBook>(csBookId);
- AssertTrue(Math.Abs(csBook.Price - 10) < 0.01, "Book price did not change to 10.");
- Write(" Done, verified. ");
- Write(" ");
-
- // Using SELECT custom stored proc ------------------------------------------------------------------
- Write("Using SELECT custom stored procedure BooksGetByAuthor.");
- // Get books by author name
- session = db.OpenSession();
- var booksByJack = booksModule.GetBooksByAuthor(session, "Pound");
- AssertTrue(2 == booksByJack.Count, "Found wrong # of books by Jack Pound.");
- Write(" Done, found 2 books by Jack.");
- Write(" ");
-
- #if !SQL_CE
- // Using UPDATE custom stored proc ------------------------------------------------------------------
- Write("Using UPDATE custom stored procedure BooksChangePrice.");
- Write(" Reducing price by 20% on all hardcover books.");
- //Use stored proc to reduce the price by 20% on all hardcovers
- // We have Kid book in Hardcovers, original price 10
- booksModule.ChangePrice(session, BookType.Hardcover, -20);
- //check that changes actually took place
- session = db.OpenSession();
- kidBook = session.GetEntity<IBook>(kidBookId);
- //Original price 10, now it should be 8
- AssertTrue(Math.Abs(8 - kidBook.Price) < 0.01, "Kids book price is not reduced after discount.");
- Write(" Done, verified - hardcover book price changed from 10 to 8.");
- Write(" ");
-
- // Using DELETE custom stored proc -------------------------------------------------------------------
- Write("Using DELETE custom stored procedure BooksDeleteZeroQuantity.");
- Write(" Preparation: load a book, change its quantity to 0, update it.");
- // Set kids book quantity to zero, then delete all books with zero quantity using stored procedure
- session = db.OpenSession();
- kidBook = session.GetEntity<IBook>(kidBookId);
- kidBook.Quantity = 0;
- session.SaveChanges();
- Write(" Done.");
- Write(" Now delete books with zero quantity using stored proc BooksDeleteZeroQuantity.");
- booksModule.DeleteBooksWithZeroQuantity(session);
- //check it is deleted
- session = db.OpenSession();
- kidBook = session.GetEntity<IBook>(kidBookId);
- AssertTrue(kidBook == null, "Books with zero quantity were not deleted");
- Write(" Done, verified - book deleted.");
- #endif
-
- Write(" ");
- Write("End Demo");
- Write("Have a look at the database populated by this demo - tables, indexes, stored procedures, data, etc.");
- }//method
-
- private static void Write(string text) {
- Debug.WriteLine(text);
- }
-
- private static void AssertTrue(bool condition, string message) {
- Assert.IsTrue(condition, message);
- }
-
-
- }//class
- }