Esempio n. 1
0
        public void TestDeletePriceOffer()
        {
            //SETUP
            var inMemDb = new SqliteInMemory();

            using (var context = inMemDb.GetContextWithSetup())
            {
                context.SeedDatabaseFourBooks();
                var numPromotions = context.PriceOffers.Count();

                //ATTEMPT
                var promotion = context.PriceOffers //#A
                                .First();           //#A

                context.Remove(promotion);          //#B
                context.SaveChanges();              //#C

                /**********************************************************
                 #A I find the first PriceOffer
                 #B I then remove that PriceOffer from the application's DbContext. The DbContext works what to remove based on its type of its parameter
                 #C The SaveChanges calls DetectChanges which finds a tracked PriceOffer entity which is marked as deleted. It then deletes it from the database
                 * *******************************************************/

                //VERIFY
                context.PriceOffers.Count().ShouldEqual(numPromotions - 1);
            }
        }
Esempio n. 2
0
        public void UpdatePublicationDate()
        {
            //SETUP
            var inMemDb = new SqliteInMemory();

            using (var context = inMemDb.GetContextWithSetup())
            {
                context.SeedDatabaseFourBooks();

                //ATTEMPT
                var book = context.Books                                  //#A
                           .Single(p => p.Title == "Quantum Networking"); //#A
                book.PublishedOn = new DateTime(2058, 1, 1);              //#B
                context.SaveChanges();                                    //#C

                /**********************************************************
                 #A This finds the specific book we want to update. In the case our special book on Quantum Networking
                 #B Then it changes the expected publication date to year 2058 (it was 2057)
                 #C It calls SaveChanges which includes running a method called DetectChanges. This spots that the PublishedOn property has been changed
                 * *******************************************************/

                //VERIFY
                var bookAgain = context.Books                                  //#E
                                .Single(p => p.Title == "Quantum Networking"); //#E
                bookAgain.PublishedOn                                          //#F
                .ShouldEqual(new DateTime(2058, 1, 1));                        //#F
            }
        }
        public void ValidateOk()
        {
            //SETUP
            var inMemDb = new SqliteInMemory();

            using (var context = inMemDb.GetContextWithSetup())
            {
                context.SeedDatabaseFourBooks();
                //ATTEMPT
                var order = new Order
                {
                    CustomerName = Guid.NewGuid(),
                    LineItems    = new List <LineItem>
                    {
                        new LineItem
                        {
                            BookId    = context.Books.First().BookId,
                            LineNum   = 1,
                            BookPrice = 123,
                            NumBooks  = 1
                        }
                    }
                };
                context.Orders.Add(order);
                var errors = context.SaveChangesWithValidation();

                //VERIFY
                errors.Any().ShouldBeFalse();
                context.Orders.Count().ShouldEqual(1);
            }
        }
Esempio n. 4
0
        public void TestCreateOrderWithOneLineItems()
        {
            //SETUP
            var inMemDb = new SqliteInMemory();

            using (var context = inMemDb.GetContextWithSetup())
            {
                context.SeedDatabaseFourBooks();
                var userId = Guid.NewGuid();

                //ATTEMPT
                var order = new Order
                {
                    CustomerName = userId,
                    LineItems    = new List <LineItem>
                    {
                        new LineItem
                        {
                            BookId    = 1,
                            LineNum   = 0,
                            BookPrice = 123,
                            NumBooks  = 1
                        }
                    }
                };
                context.Orders.Add(order);
                context.SaveChanges();

                //VERIFY
                context.Orders.Count().ShouldEqual(1);
                order.LineItems.First().ChosenBook.ShouldNotBeNull();
            }
        }
Esempio n. 5
0
        public void SetupRestOfDto(BooksFilterBy filterBy, string filterValue, int pageSize,
                                   int expectedPageNum, int expectedNumPages)
        {
            //SETUP
            var       inMemDb  = new SqliteInMemory();
            const int numBooks = 12;

            using (var db = inMemDb.GetContextWithSetup())
            {
                db.Books.AddRange(EfTestData.CreateDummyBooks(numBooks, false));
                db.SaveChanges();

                var sfpDto = new SortFilterPageOptions
                {
                    FilterBy    = BooksFilterBy.ByVotes,
                    FilterValue = "Dummy",
                    PageNum     = 2
                };

                //need to do this to to setup PrevCheckState
                sfpDto.SetupRestOfDto(db.Books);

                //ATTEMPT
                sfpDto.PageNum     = 2;
                sfpDto.FilterBy    = filterBy;
                sfpDto.FilterValue = filterValue;
                sfpDto.PageSize    = pageSize;
                sfpDto.SetupRestOfDto(db.Books);

                //VERIFY
                sfpDto.PageNum.ShouldEqual(expectedPageNum);
                sfpDto.NumPages.ShouldEqual(expectedNumPages);
            }
        }
Esempio n. 6
0
        public void TestCreateBookWithExistingAuthorAddedButNotSavedToDatabase()
        {
            //SETUP
            var inMemDb = new SqliteInMemory();

            using (var context = inMemDb.GetContextWithSetup())
            {
                var oneBook =
                    EfTestData.CreateDummyBookOneAuthor();
                context.Add(oneBook);

                var book = new Book
                {
                    Title       = "Test Book",
                    PublishedOn = DateTime.Today
                };
                book.AuthorsLink = new List <BookAuthor>
                {
                    new BookAuthor
                    {
                        Book   = book,
                        Author = oneBook.AuthorsLink
                                 .First().Author
                    }
                };

                //ATTEMPT
                context.Add(book);
                context.SaveChanges();

                //VERIFY
                context.Books.Count().ShouldEqual(2);
                context.Authors.Count().ShouldEqual(1);
            }
        }
Esempio n. 7
0
        public void TestConnectedUpdateIncludeOk()
        {
            //SETUP
            var inMemDb = new SqliteInMemory();

            using (var context = inMemDb.GetContextWithSetup())
            {
                context.SeedDatabaseFourBooks();

                //ATTEMPT
                var book = context.Books
                           .Include(p => p.Promotion)
                           .First(p => p.Promotion != null);

                book.Promotion = new PriceOffer
                {
                    NewPrice        = book.Price / 2,
                    PromotionalText = "Half price today!"
                };
                context.SaveChanges();

                //VERIFY
                context.PriceOffers.Count().ShouldEqual(1); //there is only one promotion in the four book data
                context.PriceOffers.First().PromotionalText.ShouldEqual("Half price today!");
            }
        }
        public void ValidateLineNumNotSetBad()
        {
            //SETUP
            var inMemDb = new SqliteInMemory();

            using (var context = inMemDb.GetContextWithSetup())
            {
                context.SeedDatabaseFourBooks();
                //ATTEMPT
                var order = new Order
                {
                    CustomerName = Guid.NewGuid(),
                    LineItems    = new List <LineItem>
                    {
                        new LineItem
                        {
                            BookId    = context.Books.First().BookId,
                            LineNum   = 20,
                            BookPrice = 123,
                            NumBooks  = 1
                        }
                    }
                };
                context.Orders.Add(order);
                var errors = context.SaveChangesWithValidation();

                //VERIFY
                errors.Count.ShouldEqual(1);
                errors.First().ErrorMessage.ShouldEqual("This order is over the limit of 5 books.");
                context.Orders.Count().ShouldEqual(0);
            }
        }
Esempio n. 9
0
        public void FindBooksWithCSharpInTheirTitleLike()
        {
            //SETUP
            var sqlite = new SqliteInMemory();

            using (var context = sqlite.GetContextWithSetup())
            {
                context.SeedDatabase(TestFileHelpers.GetSolutionDirectory() + @"\EfCoreInAction\wwwroot\");
                sqlite.ClearLogs();

                //ATTEMPT
                var bookTitles = context.Books
                                 .Where(p => EF.Functions.Like(p.Title, "%C#%"))
                                 .Select(p => p.Title)
                                 .ToList();


                //VERIFY
                bookTitles.Count.ShouldEqual(5);
                foreach (var title in bookTitles)
                {
                    _output.WriteLine(title);
                }
            }
        }
Esempio n. 10
0
        public void TestDeleteBookInLineItemFails()
        {
            //SETUP
            var inMemDb = new SqliteInMemory();

            using (var context = inMemDb.GetContextWithSetup())
            {
                context.SeedDatabaseFourBooks();
                var userId = Guid.NewGuid();

                var order = new Order
                {
                    CustomerName = userId,
                    LineItems    = new List <LineItem>
                    {
                        new LineItem
                        {
                            ChosenBook = context.Books.First(),
                            LineNum    = 0,
                            BookPrice  = 123,
                            NumBooks   = 1
                        }
                    }
                };
                context.Orders.Add(order);
                context.SaveChanges();

                //ATTEMPT
                context.Books.Remove(context.Books.First());
                var ex = Assert.Throws <InvalidOperationException>(() => context.SaveChanges());

                //VERIFY
                ex.Message.ShouldEqual("The association between entity types 'Book' and 'LineItem' has been severed but the foreign key for this relationship cannot be set to null. If the dependent entity should be deleted, then setup the relationship to use cascade deletes.");
            }
        }
Esempio n. 11
0
        public void TestDeleteExistingRelationship()
        {
            //SETUP
            var inMemDb = new SqliteInMemory();

            using (var context = inMemDb.GetContextWithSetup())
            {
                context.SeedDatabaseFourBooks();

                var book = context.Books
                           .Include(p => p.Promotion)
                           .First(p => p.Promotion != null);

                //ATTEMPT
                book.Promotion = null;
                context.SaveChanges();

                //VERIFY
                var bookAgain = context.Books
                                .Include(p => p.Promotion)
                                .Single(p => p.BookId == book.BookId);
                bookAgain.Promotion.ShouldBeNull();
                context.PriceOffers.Count().ShouldEqual(0);
            }
        }
Esempio n. 12
0
        public void RunAction(MockBizActionTransact2Modes mode)
        {
            //SETUP
            var inMemDb = new SqliteInMemory();

            using (var context = inMemDb.GetContextWithSetup())
            {
                var action1 = new MockBizActionPart1(context);
                var action2 = new MockBizActionPart2(context);
                var runner  = new RunnerTransact2WriteDb <TransactBizActionDto, TransactBizActionDto, TransactBizActionDto>(context, action1, action2);

                //ATTEMPT
                var output = runner.RunAction(new TransactBizActionDto(mode));

                //VERIFY
                runner.HasErrors.ShouldEqual(mode != MockBizActionTransact2Modes.Ok);
                context.Authors.Count().ShouldEqual(mode != MockBizActionTransact2Modes.Ok ? 0 : 2);
                if (mode == MockBizActionTransact2Modes.BizErrorPart1)
                {
                    runner.Errors.Single().ErrorMessage.ShouldEqual("Failed in Part1");
                }
                if (mode == MockBizActionTransact2Modes.BizErrorPart2)
                {
                    runner.Errors.Single().ErrorMessage.ShouldEqual("Failed in Part2");
                }
            }
        }
Esempio n. 13
0
        public void TestConnectedUpdateExistingRelationship()
        {
            //SETUP
            var inMemDb = new SqliteInMemory();

            using (var context = inMemDb.GetContextWithSetup())
            {
                context.SeedDatabaseFourBooks();

                var book = context.Books
                           .Include(p => p.Reviews)
                           .First(p => p.Reviews.Any());

                var orgReviews = book.Reviews.Count;

                //ATTEMPT
                book.Reviews.Add(new Review
                {
                    VoterName = "Unit Test",
                    NumStars  = 5,
                });
                context.SaveChanges();

                //VERIFY
                var bookAgain = context.Books
                                .Include(p => p.Reviews)
                                .Single(p => p.BookId == book.BookId);
                bookAgain.Reviews.ShouldNotBeNull();
                bookAgain.Reviews.Count.ShouldEqual(orgReviews + 1);
            }
        }
Esempio n. 14
0
        public async Task TestMapBookToDtoAsyncOk()
        {
            //SETUP
            var inMemDb = new SqliteInMemory();

            //ATTEMPT
            using (var context = inMemDb.GetContextWithSetup())
            {
                context.Books.AddRange(EfTestData.CreateFourBooks());
                await context.SaveChangesAsync();

                //ATTEMPT
                var result = await context.Books.Select(p =>
                                                        new BookListDto
                {
                    ActualPrice = p.Promotion == null
                            ? p.Price
                            : p.Promotion.NewPrice,
                    ReviewsCount = p.Reviews.Count,
                }).ToListAsync();

                //VERIFY
                result.Count.ShouldEqual(4);
            }
        }
Esempio n. 15
0
        public async Task TwoTasksSameDbContextBad()
        {
            //SETUP
            var inMemDb = new SqliteInMemory();

            using (var context = inMemDb.GetContextWithSetup())
            {
                context.SeedDatabaseFourBooks();

                //ATTEMPT
                var task1 = MyTask(context);
                var task2 = MyTask(context);

                var exceptionRaised = false;
                try
                {
                    await Task.WhenAll(task1, task2);
                }
                catch (Exception e)
                {
                    e.ShouldBeType <InvalidOperationException>();
                    e.Message.ShouldEqual("A second operation started on this context before a previous operation completed. Any instance members are not guaranteed to be thread safe.");
                    exceptionRaised = true;
                }

                //VERIFY
                exceptionRaised.ShouldBeTrue();
            }
        }
Esempio n. 16
0
        public void TestCheckoutListTwoBooksSqLite()
        {
            //SETUP
            var inMemDb = new SqliteInMemory();


            using (var context = inMemDb.GetContextWithSetup())
            {
                context.SeedDatabaseDummyBooks(10);

                //two line items: BookId:1 NumBooks:2, BookId:2 NumBooks:3
                var mockCookieRequests = new MockHttpCookieAccess(CheckoutCookie.CheckoutCookieName, $"{Guid.NewGuid()},1,2,2,3");

                //ATTEMPT

                var service = new CheckoutListService(context, mockCookieRequests.CookiesIn);
                var list    = service.GetCheckoutList();

                //VERIFY
                for (int i = 0; i < list.Count(); i++)
                {
                    list[i].BookId.ShouldEqual(i + 1);
                    list[i].NumBooks.ShouldEqual((short)(i + 2));
                    list[i].BookPrice.ShouldEqual((i + 1));
                }
            }
        }
Esempio n. 17
0
        public void TestDeleteBookInLineItemFails()
        {
            //SETUP
            var inMemDb = new SqliteInMemory();

            using (var context = inMemDb.GetContextWithSetup())
            {
                context.SeedDatabaseFourBooks();
                var userId = Guid.NewGuid();

                var order = new Order
                {
                    CustomerName = userId,
                    LineItems    = new List <LineItem>
                    {
                        new LineItem
                        {
                            ChosenBook = context.Books.First(),
                            LineNum    = 0,
                            BookPrice  = 123,
                            NumBooks   = 1
                        }
                    }
                };
                context.Orders.Add(order);
                context.SaveChanges();

                //ATTEMPT
                context.Books.Remove(context.Books.First());
                var ex = Assert.Throws <DbUpdateException> (() => context.SaveChanges());

                //VERIFY
                ex.InnerException.Message.ShouldEqual("SQLite Error 19: 'FOREIGN KEY constraint failed'.");
            }
        }
Esempio n. 18
0
        public async Task TestGetNumBooksAsync()
        {
            //SETUP
            var inMemDb = new SqliteInMemory();

            using (var context = inMemDb.GetContextWithSetup())
            {
                context.SeedDatabaseFourBooks();

                //ATTEMPT
                var numBooks = await GetNumBooksAsync(context);

                //VERIFY
                numBooks.ShouldEqual(4);
            }
        }
Esempio n. 19
0
        public void SoftDeleteOneBookNotSaved()
        {
            //SETUP
            var inMemDb = new SqliteInMemory();

            using (var context = inMemDb.GetContextWithSetup())
            {
                context.SeedDatabaseFourBooks();

                //ATTEMPT
                context.Books.First().SoftDeleted = true;

                //VERIFY
                context.Books.Count().ShouldEqual(4);
            }
        }
Esempio n. 20
0
        public void TestGetOrderDetailNotFound()
        {
            //SETUP
            var inMemDb = new SqliteInMemory();

            using (var context = inMemDb.GetContextWithSetup())
            {
                var service = new DisplayOrdersService(context);

                //ATTEMPT
                var ex = Assert.Throws <NullReferenceException>(() => service.GetOrderDetail(1));

                //VERIFY
                ex.Message.ShouldEqual("Could not find the order with id of 1.");
            }
        }
Esempio n. 21
0
        public async Task RunClientServerSimpleAsync()
        {
            //SETUP
            var inMemDb = new SqliteInMemory();

            using (var context = inMemDb.GetContextWithSetup())
            {
                context.SeedDatabaseFourBooks();

                //ATTEMPT
                var dtos = await context.Books
                           .Select(p => p.BookId.ToString() + "Hello").ToListAsync();

                //VERIFY
                dtos.Count.ShouldEqual(4);
            }
        }
Esempio n. 22
0
        public void TestDeleteBookNoOrder()
        {
            //SETUP
            var inMemDb = new SqliteInMemory();

            using (var context = inMemDb.GetContextWithSetup())
            {
                context.SeedDatabaseFourBooks();
                //ATTEMPT

                context.Books.Remove(context.Books.First());
                context.SaveChanges();

                //VERIFY
                context.Books.Count().ShouldEqual(3);
            }
        }
Esempio n. 23
0
        public async Task RunBookListAsync()
        {
            //SETUP
            var inMemDb = new SqliteInMemory();

            using (var context = inMemDb.GetContextWithSetup())
            {
                context.SeedDatabaseFourBooks();
                var service = new ListBooksService(context);

                //ATTEMPT
                var books = await service.SortFilterPage(new SortFilterPageOptions()).ToListAsync();

                //VERIFY
                books.Count.ShouldEqual(4);
            }
        }
Esempio n. 24
0
        public void TestSqliteInMemoryBasicOk()
        {
            //SETUP
            var inMemDb = new SqliteInMemory();

            //ATTEMPT
            using (var context = inMemDb.GetContextWithSetup())
            {
                var books = EfTestData.CreateFourBooks();
                context.Books.AddRange(books);
                context.SaveChanges();

                //VERIFY
                context.Books.Count().ShouldEqual(4);
                context.Books.Count(p => p.Title.StartsWith("Quantum")).ShouldEqual(1);
            }
        }
Esempio n. 25
0
        public void TestChangeAuthorsNewListOk()
        {
            //SETUP
            var inMemDb = new SqliteInMemory();

            using (var context = inMemDb.GetContextWithSetup())
            {
                context.SeedDatabaseFourBooks();

                //ATTEMPT
                var book = context.Books                                  //#A
                           .Include(p => p.AuthorsLink)                   //#A
                           .Single(p => p.Title == "Quantum Networking"); //#A

                var newAuthor = context.Authors                           //#B
                                .Single(p => p.Name == "Martin Fowler");  //#B

                book.AuthorsLink = new List <BookAuthor>                  //#C
                {                                                         //#C
                    new BookAuthor                                        //#C
                    {                                                     //#C
                        Book   = book,                                    //#C
                        Author = newAuthor,                               //#C
                        Order  = 0                                        //#C
                    }                                                     //#C
                };                                                        //#C

                context.SaveChanges();                                    //#D

                /**********************************************************
                 #A This finds the book with title "Quantum Networking", whose current author is "Future Person"
                 #B I then find an existing author, in this case "Martin Fowler"
                 #C Then I completely replace the list of authors, so that the "Quantum Networking" book's author is "Martin Fowler"
                 #C The SaveChanges method calls DetectChanges, which finds that the AuthorsLink has changes so deletes the old ones and replaces it with the new link
                 * *******************************************************/

                //VERIFY
                var bookAgain = context.Books
                                .Include(p => p.AuthorsLink)
                                .Single(p => p.BookId == book.BookId);
                bookAgain.AuthorsLink.ShouldNotBeNull();
                bookAgain.AuthorsLink.Count.ShouldEqual(1);
                bookAgain.AuthorsLink.First().Author.Name.ShouldEqual("Martin Fowler");
                context.Authors.Count(p => p.Name == "Future Person").ShouldEqual(1);
            }
        }
Esempio n. 26
0
        public void RunActionThrowException()
        {
            //SETUP
            var inMemDb = new SqliteInMemory();

            using (var context = inMemDb.GetContextWithSetup())
            {
                var action1 = new MockBizActionPart1(context);
                var action2 = new MockBizActionPart2(context);
                var runner  = new RunnerTransact2WriteDb <TransactBizActionDto, TransactBizActionDto, TransactBizActionDto>(context, action1, action2);

                //ATTEMPT
                Assert.Throws <InvalidOperationException>(() => runner.RunAction(new TransactBizActionDto(MockBizActionTransact2Modes.ThrowExceptionPart2)));

                //VERIFY
                context.Authors.Count().ShouldEqual(0);
            }
        }
Esempio n. 27
0
        public void SoftDeleteOneBookFind()
        {
            //SETUP
            var inMemDb = new SqliteInMemory();

            using (var context = inMemDb.GetContextWithSetup())
            {
                context.SeedDatabaseFourBooks();
                var firstBook = context.Books.First();
                firstBook.SoftDeleted = true;
                context.SaveChanges();

                //ATTEMPT
                var softBook = context.Find <Book>(firstBook.BookId);

                //VERIFY
                softBook.ShouldNotBeNull();
            }
        }
Esempio n. 28
0
        public async Task TestReadSqliteAsyncOk()
        {
            //SETUP
            var inMemDb = new SqliteInMemory();

            //ATTEMPT
            using (var context = inMemDb.GetContextWithSetup())
            {
                context.Books.AddRange(EfTestData.CreateFourBooks());
                await context.SaveChangesAsync();

                //ATTEMPT
                var books = await context.Books.ToListAsync();

                //VERIFY
                books.Count.ShouldEqual(4);
                books.Count(p => p.Title.StartsWith("Quantum")).ShouldEqual(1);
            }
        }
Esempio n. 29
0
        public void TestCreateBookAddTwice()
        {
            //SETUP
            var inMemDb = new SqliteInMemory();

            using (var context = inMemDb.GetContextWithSetup())
            {
                var oneBook =
                    EfTestData.CreateDummyBookOneAuthor();

                //ATTEMPT
                context.Add(oneBook);
                context.Add(oneBook);
                context.SaveChanges();

                //VERIFY
                context.Books.Count().ShouldEqual(1);
            }
        }
Esempio n. 30
0
        public void TestCreateBookWithExistingAuthorSavedToDatabase()
        {
            //SETUP
            var inMemDb = new SqliteInMemory();

            using (var context = inMemDb.GetContextWithSetup())
            {
                var oneBook =
                    EfTestData.CreateDummyBookOneAuthor(); //#A
                context.Add(oneBook);                      //#A
                context.SaveChanges();                     //#A

                var book = new Book                        //#B
                {                                          //#B
                    Title       = "Test Book",             //#B
                    PublishedOn = DateTime.Today           //#B
                };                                         //#B
                book.AuthorsLink = new List <BookAuthor>   //#C
                {                                          //#C
                    new BookAuthor                         //#C
                    {                                      //#C
                        Book   = book,                     //#C
                        Author = oneBook.AuthorsLink       //#C
                                 .First().Author           //#C
                    }                                      //#C
                };                                         //#C

                //ATTEMPT
                context.Add(book);                //#D
                context.SaveChanges();            //#D

                /************************************************************
                 #A This method creates dummy books for testing. I create one dummy book with one Author and add it to the empty database
                 #B This creates a book in the same way as the previous example, but sets up its Author
                 #C This adds a AuthorBook linking entry, but it reads in an existing the Author from the first book
                 #D This is the same process: add the new book to the DbContext Books property and call SaveChanges
                 * *********************************************************/

                //VERIFY
                context.Books.Count().ShouldEqual(2);   //#E
                context.Authors.Count().ShouldEqual(1); //#F
            }
        }