Esempio n. 1
0
        public void TestSqliteSingleInstanceOk()
        {
            //SETUP
            var options = SqliteInMemory
                          .CreateOptions <BookContext>(false);

            using (var context = new BookContext(options))
            {
                context.Database.EnsureCreated();  //#A
                context.SeedDatabaseFourBooks();   //#A

                //ATTEMPT
                var book = context.Books.Last();            //#B
                book.Reviews.Add(new Review {
                    NumStars = 5
                });                      //#C
                context.SaveChanges();   //#D

                //VERIFY
                context.Books.Last().Reviews
                .Count.ShouldEqual(3);     //#E
            }
        }
Esempio n. 2
0
        public async Task TestNoBeforeSaveChangesMethodProvided()
        {
            //SETUP
            var options = SqliteInMemory.CreateOptions <TestDbContext>();

            using (var context = new TestDbContext(options))
            {
                context.Database.EnsureCreated();

                var utData  = context.SetupSingleDtoAndEntities <UniqueWithConfigDto>();
                var service = new CrudServicesAsync(context, utData.ConfigAndMapper);

                //ATTEMPT
                await service.CreateAndSaveAsync(new NormalEntity { MyString = "bad word" });

                //VERIFY
                service.IsValid.ShouldBeTrue(service.GetAllErrors());
            }
            using (var context = new TestDbContext(options))
            {
                context.NormalEntities.Count().ShouldEqual(1);
            }
        }
Esempio n. 3
0
        public async Task TestWriteBooksAsyncAskNumberOk(int totalBooks)
        {
            //SETUP
            var fileDir = Path.Combine(TestData.GetTestDataDir());
            var options = SqliteInMemory.CreateOptions <BookDbContext>();

            options.TurnOffDispose();
            using var context = new BookDbContext(options);
            context.Database.EnsureCreated();
            await context.SeedDatabaseWithBooksAsync(fileDir);

            context.ChangeTracker.Clear();

            //ATTEMPT
            var serviceProvider = BuildServiceProvider(options);
            var generator       = new BookGenerator(serviceProvider);

            await generator.WriteBooksAsync(fileDir, false, totalBooks, true, default);

            //VERIFY
            context.Books.Count().ShouldEqual(totalBooks);
            options.ManualDispose();
        }
        public void TestExample()
        {
            //SETUP
            var options = SqliteInMemory
                          .CreateOptions <BookDbContext>();

            using var context = new BookDbContext(options);

            context.Database.EnsureCreated();

            context.SeedDatabaseFourBooks();

            //ATTEMPT
            var testDate = new DateTime(2020, 1, 1);
            var query    = context.Books
                           .Where(x => x.PublishedOn < testDate);

            var books = query.ToList();

            //VERIFY
            _output.WriteLine(query.ToQueryString());
            books.Count.ShouldEqual(3);
        }
        public void TestBookCountAuthorsOk()
        {
            //SETUP
            var options = SqliteInMemory.CreateOptions <EfCoreContext>();

            using (var context = new EfCoreContext(options))
            {
                context.Database.EnsureCreated();
                context.SeedDatabaseFourBooks();
            }
            using (var context = new EfCoreContext(options))
            {
                //ATTEMPT
                var books = context.Books
                            .Include(r => r.AuthorsLink)
                            .ThenInclude(r => r.Author)
                            .ToList();

                //VERIFY
                books.Count.ShouldEqual(4);
                books.SelectMany(x => x.AuthorsLink.Select(y => y.Author)).Distinct().Count().ShouldEqual(3);
            }
        }
        public void ExampleIdentityResolutionBad()
        {
            //SETUP
            var options = SqliteInMemory
                          .CreateOptions <EfCoreContext>();

            using var context = new EfCoreContext(options);

            context.Database.EnsureCreated();
            context.SeedDatabaseFourBooks();

            //ATTEMPT
            var book = context.Books.First();

            book.Price = 123;
            // Should call context.SaveChanges()

            //VERIFY
            var verifyBook = context.Books.First();

            //!!! THIS IS WRONG !!! THIS IS WRONG
            verifyBook.Price.ShouldEqual(123);
        }
        public async Task TestCheckFixCacheValuesServiceFindFixReviewsOk()
        {
            //SETUP
            var options = SqliteInMemory.CreateOptions<BookDbContext>();
            using var context = new BookDbContext(options);
            context.Database.EnsureCreated();

            var books = context.SeedDatabaseFourBooks(); //The Review cache values will be incorrect, and createUpdate not set
            SetAllBooksAsUpdatedNow(books);
            books[3].UpdateReviewCachedValues(2, books[3].Reviews.Average(x => x.NumStars));
            await context.SaveChangesAsync();

            var logs = new List<LogOutput>();
            var logger = new Logger<CheckFixCacheValuesService>(new LoggerFactory(new[] { new MyLoggerProviderActionOut(logs.Add) }));
            var service = new CheckFixCacheValuesService(context, logger);

            //ATTEMPT
            var notes = await service.RunCheckAsync(new DateTime(2000, 1, 1), true, default);

            //VERIFY
            logs.Count.ShouldEqual(0);
            notes.First().ShouldEqual("Looked at 4 SQL books and found no errors");
        }
        public void TestReadBookWithInclude()
        {
            //SETUP
            int bookId;
            var options = SqliteInMemory.CreateOptions <EfCoreContext>();

            using (var context = new EfCoreContext(options))
            {
                context.Database.EnsureCreated();
                context.SeedDatabaseFourBooks();
                bookId = context.Books.Single(x => x.Reviews.Any()).BookId;
            }
            using (var context = new EfCoreContext(options))
            {
                //ATTEMPT
                var bookWithReviews = context.Books
                                      .Include(x => x.Reviews)
                                      .Single(x => x.BookId == bookId);

                //VERIFY
                bookWithReviews.Reviews.Count.ShouldEqual(2);
            }
        }
        public async Task TestUpdatePublishedOnViaRepositoryOk()
        {
            //SETUP
            var options = SqliteInMemory.CreateOptions <DddContext>();

            using var context = new DddContext(options);
            context.Database.EnsureCreated();
            AddBookWithNewAuthor(context);

            var repository = new BookRepository(context);

            //ATTEMPT
            var book = await repository.FindEntityAsync(1);

            book.UpdatePublishedOn(new DateTime(2020, 1, 1));
            await repository.PersistDataAsync();

            //VERIFY
            context.ChangeTracker.Clear();
            var readBook = context.Books.Single();

            readBook.PublishedOn.ShouldEqual(new DateTime(2020, 1, 1));
        }
        public void TestReadJustBookTableOk()
        {
            //SETUP
            var options = SqliteInMemory.CreateOptions <EfCoreContext>();

            using (var context = new EfCoreContext(options))
            {
                context.Database.EnsureCreated();
                context.SeedDatabaseFourBooks();
            }

            using (var context = new EfCoreContext(options)
                   ) //dispose first DbContext and create new one. That way the read isn't effected by the setup code
            {
                //ATTEMPT
                var book = context.Books.First();

                //VERIFY
                book.AuthorsLink.ShouldBeNull();
                book.Reviews.ShouldBeNull();
                book.Promotion.ShouldBeNull();
            }
        }
Esempio n. 11
0
        public void PageBooks(int pageSize)
        {
            //SETUP
            var numBooks = 12;
            var options  = SqliteInMemory.CreateOptions <EfCoreContext>();

            using (var context = new EfCoreContext(options))
            {
                context.Database.EnsureCreated();
                context.SeedDatabaseDummyBooks(numBooks);

                //ATTEMPT
                var service     = new ListBooksService(context);
                var listOptions = new SortFilterPageOptions()
                {
                    PageSize = pageSize
                };
                var dtos = service.SortFilterPage(listOptions).ToList();

                //VERIFY
                dtos.Count.ShouldEqual(pageSize);
            }
        }
Esempio n. 12
0
        public void TestIncludeThenTwoLevelManuallyLoad()
        {
            //SETUP
            var options = SqliteInMemory.CreateOptions <EfCoreContext>();

            using (var context = new EfCoreContext(options))
            {
                context.Database.EnsureCreated();
                context.SeedDatabaseFourBooks();

                var includeStrings = typeof(AddNewAuthorToBookUsingIncludesDto)
                                     .GetCustomAttributes(typeof(IncludeThenAttribute), true).Cast <IncludeThenAttribute>()
                                     .Select(x => x.IncludeNames).ToList();

                //ATTEMPT
                var query = ApplyAnyIncludeStringsAtDbSetLevel <AddReviewWithIncludeDto>(context.Books);
                var books = query.ToList();

                //VERIFY
                var names = books.SelectMany(x => x.AuthorsLink.Select(y => y.Author.Name)).ToArray();
                names.ShouldEqual(new string[] { "Martin Fowler", "Martin Fowler", "Eric Evans", "Future Person" });
            }
        }
        public void UpdateAuthorBadId()
        {
            //SETUP
            var options = SqliteInMemory.CreateOptions <EfCoreContext>();

            using (var context = new EfCoreContext(options))
            {
                context.Database.EnsureCreated();
                context.SeedDatabaseFourBooks();

                //ATTEMPT
                var author = new Author
                {
                    AuthorId = 999999,
                    Name     = "Future Person 2"
                };
                context.Authors.Update(author);
                var ex = Assert.Throws <DbUpdateConcurrencyException>(() => context.SaveChanges());

                //VERIFY
                ex.Message.StartsWith("Database operation expected to affect 1 row(s) but actually affected 0 row(s).").ShouldBeTrue();
            }
        }
Esempio n. 14
0
        public void AuthorDecodedEntityClass()
        {
            //SETUP
            var options = SqliteInMemory.CreateOptions <EfCoreContext>();

            using (var context = new EfCoreContext(options))
            {
                //ATTEMPT
                var decoded = new DecodedEntityClass(typeof(Author), context);

                //VERIFY
                decoded.EntityStyle.ShouldEqual(EntityStyles.Standard);
                decoded.PrimaryKeyProperties.Single().Name.ShouldEqual(nameof(Author.AuthorId));
                decoded.CanBeUpdatedViaMethods.ShouldBeFalse();
                decoded.CanBeUpdatedViaProperties.ShouldBeTrue();
                decoded.CanBeCreatedByCtorOrStaticMethod.ShouldBeFalse();
                decoded.PublicCtors.Length.ShouldEqual(1);
                decoded.PublicStaticCreatorMethods.Length.ShouldEqual(0);
                decoded.PublicSetterMethods.Length.ShouldEqual(0);
                decoded.PropertiesWithPublicSetter.Select(x => x.Name)
                .ShouldEqual(new [] { nameof(Author.AuthorId), nameof(Author.Name), nameof(Author.Email), nameof(Author.BooksLink) });
            }
        }
        public void TestLoadManager()
        {
            //SETUP
            var options = SqliteInMemory.CreateOptions <Chapter06Context>();

            using (var context = new Chapter06Context(options))
            {
                context.Database.EnsureCreated();
                context.AddTestEmployeesToDb();
            }
            using (var context = new Chapter06Context(options))
            {
                //ATTEMPT
                var all = context.Employees.Include(x => x.Manager)
                          .ToList();

                //VERIFY
                all.Count.ShouldEqual(11);
                all.Count(x => x.Manager != null).ShouldEqual(10);
                all.Count(x => x.WorksForMe != null).ShouldEqual(5);
                all.Count(x => x.WorksForMe == null).ShouldEqual(6);
            }
        }
        public async Task TestAddReviewViaRepositoryOk()
        {
            //SETUP
            var options = SqliteInMemory.CreateOptions <DddContext>();

            using var context = new DddContext(options);
            context.Database.EnsureCreated();
            AddBookWithNewAuthor(context);

            var repository = new BookRepository(context);

            //ATTEMPT
            var book = await repository.LoadBookWithReviewsAsync(1);

            book.AddReview(5, "great", "me");
            await repository.PersistDataAsync();

            //VERIFY
            context.ChangeTracker.Clear();
            var readBook = context.Books.Include(b => b.Reviews).Single();

            readBook.Reviews.Count.ShouldEqual(1);
        }
        public void TestExtractCompanyId()
        {
            //SETUP
            var options = SqliteInMemory.CreateOptions <CompanyDbContext>();

            using (var context = new CompanyDbContext(options, new FakeGetClaimsProvider("123*")))
            {
                context.Database.EnsureCreated();
                var rootCompanies = context.AddCompanyAndChildrenInDatabase();

                //ATTEMPT
                //                   -- West Coast --|--- San Fran ---
                var sfDress4U = rootCompanies.First().Children.Single().Children.First().Children.First();
                //                  -- West Coast --|------ LA ------
                var la = rootCompanies.First().Children.Single().Children.Last();


                //VERIFY
                rootCompanies.First().ExtractCompanyId().ShouldEqual(1);
                sfDress4U.ExtractCompanyId().ShouldEqual(1);
                la.ExtractCompanyId().ShouldEqual(1);
            }
        }
Esempio n. 18
0
        public void TestReadEachSeparately()
        {
            //SETUP
            int bookId;
            var options = SqliteInMemory.CreateOptions <EfCoreContext>();

            using var context = new EfCoreContext(options);
            context.Database.EnsureCreated();
            context.SeedDatabaseFourBooks();
            bookId = context.Books.Single(x => x.Reviews.Any()).BookId;

            context.ChangeTracker.Clear();

            //ATTEMPT
            var book         = context.Books.ToList();
            var reviews      = context.Set <Review>().ToList();
            var authorsLinks = context.Set <BookAuthor>().ToList();
            var authors      = context.Authors.ToList();

            //VERIFY
            book.Last().Reviews.Count.ShouldEqual(2);
            book.Last().AuthorsLink.Single().Author.ShouldNotBeNull();
        }
        public void TestLogQueryClientEvaluationWarning()
        {
            //SETUP
            var logs    = new List <LogOutput>();
            var options = SqliteInMemory.CreateOptionsWithLogging <BookContext>(log => logs.Add(log), LogLevel.Warning, false);

            using (var context = new BookContext(options))
            {
                context.Database.EnsureCreated();


                //ATTEMPT
                var books = context.Books.Select(x => new ClientSeverTestDto
                {
                    ClientSideProp = x.Price.ToString("C")
                }).OrderBy(x => x.ClientSideProp)
                            .ToList();

                //VERIFY
                logs.ToList().Any(x => x.EventId.Name == RelationalEventId.QueryClientEvaluationWarning.Name).ShouldBeTrue();
                logs.All(x => x.LogLevel >= LogLevel.Warning).ShouldBeTrue();
            }
        }
Esempio n. 20
0
        public void TestBookListReviewSaveChangesTimeOk(int numReviews)
        {
            //SETUP
            var options = SqliteInMemory.CreateOptions <EfCoreContext>();

            using (var context = new EfCoreContext(options))
            {
                context.Database.EnsureCreated();
                var book = CreateBookWithListReviews(numReviews);
                using (new TimeThings(_output, $"ADD BookListReview: {numReviews} entries"))
                    context.Add(book);
                context.SaveChanges();

                using (new TimeThings(_output, $"1: BookListReview: {numReviews} entries"))
                {
                    context.SaveChanges();
                }
                using (new TimeThings(_output, $"2: BookListReview: {numReviews} entries"))
                {
                    context.SaveChanges();
                }
            }
        }
Esempio n. 21
0
        public async Task TestStopOnFirstBeforeHandlerThatHasAnError(bool stopOnFirst)
        {
            //SETUP
            var options = SqliteInMemory.CreateOptions <ExampleDbContext>();
            var config  = new GenericEventRunnerConfig
            {
                StopOnFirstBeforeHandlerThatHasAnError = stopOnFirst
            };
            var context = options.CreateAndSeedDbWithDiForHandlers <OrderCreatedHandler>(config: config);
            {
                var tax = new TaxRate(DateTime.Now, 6);
                context.Add(tax);

                //ATTEMPT
                tax.AddEvent(new EventTestBeforeReturnError());
                tax.AddEvent(new EventTestBeforeReturnError());
                var ex = await Assert.ThrowsAsync <GenericEventRunnerStatusException>(async() => await context.SaveChangesAsync());

                //VERIFY
                context.StatusFromLastSaveChanges.IsValid.ShouldBeFalse();
                context.StatusFromLastSaveChanges.Errors.Count.ShouldEqual(stopOnFirst ? 1 : 2);
            }
        }
Esempio n. 22
0
        public void TestIQueryableSelectBookListDtoOk()
        {
            //SETUP
            var options = SqliteInMemory.CreateOptions <BookDbContext>();

            using (var context = new BookDbContext(options))
            {
                context.Database.EnsureCreated();
                var books = context.SeedDatabaseFourBooks();

                //ATTEMPT
                var dtos = context.Books.MapBookToDto().OrderByDescending(x => x.BookId).ToList();

                //VERIFY
                dtos.First().BookId.ShouldNotEqual(0);
                dtos.First().Title.ShouldNotBeNull();
                dtos.First().OrgPrice.ShouldNotEqual(0);
                dtos.First().ActualPrice.ShouldNotEqual(dtos.Last().OrgPrice);
                dtos.First().AuthorsOrdered.Length.ShouldBeInRange(1, 100);
                dtos.First().ReviewsCount.ShouldEqual(2);
                dtos.First().ReviewsAverageVotes.ShouldEqual(4);
            }
        }
Esempio n. 23
0
        public void TestUpdateViaStatedMethodBad()
        {
            //SETUP
            var options = SqliteInMemory.CreateOptions <EfCoreContext>();

            using (var context = new EfCoreContext(options))
            {
                context.Database.EnsureCreated();
                context.SeedDatabaseFourBooks();

                var utData  = context.SetupSingleDtoAndEntities <Tests.Dtos.ChangePubDateDto>();
                var service = new CrudServices(context, utData.ConfigAndMapper, new CreateNewDBContextHelper(() => new EfCoreContext(options)));

                //ATTEMPT
                var dto = new Tests.Dtos.ChangePubDateDto {
                    BookId = 4, PublishedOn = new DateTime(2000, 1, 1)
                };
                var ex = Assert.Throws <InvalidOperationException>(() => service.UpdateAndSave(dto, nameof(Book.AddReview)));

                //VERIFY
                ex.Message.ShouldStartWith("Could not find a method of name AddReview. The method that fit the properties in the DTO/VM are:");
            }
        }
Esempio n. 24
0
        public void TestAverageDirectOk()
        {
            //SETUP
            var options = SqliteInMemory.CreateOptions <BookDbContext>();

            using var context = new BookDbContext(options);
            context.Database.EnsureCreated();
            context.SeedDatabaseFourBooks();
            context.ChangeTracker.Clear();

            //ATTEMPT
            var query = context.Books.Select(p =>
                                             !p.Reviews.Any()
                    ? null
                    : (decimal?)p.Reviews.Select(q => q.NumStars).Average());

            _output.WriteLine(query.ToQueryString());
            var averages = query.ToList();

            //VERIFY
            averages.Count(x => x == null).ShouldEqual(3);
            averages.Count(x => x != null).ShouldEqual(1);
        }
        public void TestAddRoleNotTrigger()
        {
            //SETUP
            var fakeAuthChanges = new FakeAuthChanges();
            var options         = SqliteInMemory.CreateOptions <ExtraAuthorizeDbContext>();

            using (var context = new ExtraAuthorizeDbContext(options, fakeAuthChanges))
            {
                context.Database.EnsureCreated();

                //ATTEMPT
                var rolToPer = RoleToPermissions.CreateRoleWithPermissions
                                   ("test", "test", new List <Permissions> {
                    Permissions.AccessAll
                }, context).Result;
                context.Add(rolToPer);
                context.SaveChanges();

                //VERIFY
                fakeAuthChanges.CacheValueSet.ShouldBeFalse();
                context.RolesToPermissions.Count().ShouldEqual(1);
            }
        }
Esempio n. 26
0
        public void TestSoftDeleteServiceSetSoftDeleteViaKeysNotFoundReturnsZero()
        {
            //SETUP
            var options = SqliteInMemory.CreateOptions <SingleSoftDelDbContext>();

            using (var context = new SingleSoftDelDbContext(options))
            {
                context.Database.EnsureCreated();

                var config = new ConfigSoftDeleteWithUserId(context)
                {
                    NotFoundIsNotAnError = true
                };
                var service = new SingleSoftDeleteService <ISingleSoftDelete>(context, config);

                //ATTEMPT
                var status = service.SetSoftDeleteViaKeys <Book>(123);

                //VERIFY
                status.IsValid.ShouldBeTrue(status.GetAllErrors());
                status.Result.ShouldEqual(0);
            }
        }
        public void TestPlaceOrderOk()
        {
            //SETUP
            var inMemDb = new SqliteInMemory();

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

                var mockCookieRequests = new MockHttpCookieAccess(CheckoutCookie.CheckoutCookieName, $"{Guid.NewGuid()},1,2");
                var service            = new PlaceOrderServiceTransact(mockCookieRequests.CookiesIn, mockCookieRequests.CookiesOut, context);

                //ATTEMPT
                var orderId = service.PlaceOrder(true);
                context.SaveChanges();

                //VERIFY
                orderId.ShouldNotEqual(0);
                service.Errors.Count.ShouldEqual(0);
                context.Orders.Count().ShouldEqual(1);
                context.Orders.First().OrderId.ShouldEqual(orderId);
            }
        }
        public void ShouldRenameASurvey()
        {
            var options = SqliteInMemory.CreateOptions <SurveyDbContext>();

            using (var context = new SurveyDbContext(options))
            {
                context.Database.EnsureCreated();
                context.SeedDataBaseWithSurveys();

                var surveyDto = new SurveyDto
                {
                    Id      = 1,
                    NewName = "Test New Name"
                };

                var service = new RenameSurveyService(context);

                var result = service.RenameSurvey(surveyDto);
                result.ShouldBeNull();
                context.SaveChanges();
                context.Surveys.First(m => m.SurveyId == surveyDto.Id).Name.ShouldEqual(surveyDto.NewName);
            }
        }
Esempio n. 29
0
        public void TestDetachViaCreatingNewDbContext(int numCollection)
        {
            //SETUP
            ManyTop entityToDetach;
            var     options = SqliteInMemory.CreateOptions <Chapter06Context>();

            options.StopNextDispose();
            using (var context = new Chapter06Context(options))
            {
                context.Database.EnsureCreated();
                entityToDetach = context.AddManyTopWithRelationsToDb(numCollection);
            }
            //ATTEMPT
            using (new TimeThings(_output, $"detach by creating new DbContext - {numCollection * 3:n0} tracked entities."))
            {
                using (var context = new Chapter06Context(options))
                {
                    context.Database.EnsureCreated();
                }
            }

            //VERIFY
        }
Esempio n. 30
0
        public void OrderBooksBy(OrderByOptions orderByOptions)
        {
            //SETUP
            var inMemDb = new SqliteInMemory();

            const int numBooks = 5;

            using (var db = inMemDb.GetContextWithSetup())
            {
                db.SeedDatabaseDummyBooks(numBooks);

                //ATTEMPT
                var service     = new ListBooksService(db);
                var listOptions = new SortFilterPageOptions()
                {
                    OrderByOptions = orderByOptions
                };
                var dtos = service.SortFilterPage(listOptions).ToList();

                //VERIFY
                dtos.Count.ShouldEqual(numBooks);
            }
        }