public void TestDecodeMessageNoParams() { //SETUP var logs = new List <LogOutput>(); #pragma warning disable 618 var options = SqliteInMemory.CreateOptionsWithLogging <BookContext>(log => logs.Add(log)); #pragma warning restore 618 //var options = this.CreateUniqueClassOptionsWithLogging<BookContext>(log => logs.Add(log)); using (var context = new BookContext(options)) { context.Database.EnsureCreated(); context.SeedDatabaseFourBooks(); //ATTEMPT context.Books.Count(); var decoded = logs.Last().DecodeMessage(); //VERIFY var sqlCommand = decoded.Split('\n').Skip(1).Select(x => x.Trim()).ToArray(); sqlCommand[0].ShouldEqual("SELECT COUNT(*)"); sqlCommand[1].ShouldEqual("FROM \"Books\" AS \"b\""); sqlCommand[2].ShouldEqual("WHERE NOT (\"b\".\"SoftDeleted\")"); } }
public void TestAddExtraOption() { //SETUP var options1 = SqliteInMemory.CreateOptions <BookContext>(); options1.StopNextDispose(); DbConnection connection; using (var context = new BookContext(options1)) { context.Database.EnsureCreated(); context.SeedDatabaseFourBooks(); connection = context.Database.GetDbConnection(); var book = context.Books.First(); context.Entry(book).State.ShouldEqual(EntityState.Unchanged); } //ATTEMPT var options2 = SqliteInMemory.CreateOptions <BookContext>(builder => { builder.UseSqlite(connection); builder.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking); }); using (var context = new BookContext(options2)) { //VERIFY var book = context.Books.First(); context.Entry(book).State.ShouldEqual(EntityState.Detached); } }
public void TestResetKeysSingleEntityWithRelationshipsCheckStateIsAdded() { //SETUP var options = SqliteInMemory.CreateOptions <BookContext>(); Book entity; using (var context = new BookContext(options)) { context.Database.EnsureCreated(); context.SeedDatabaseFourBooks(); entity = context.Books .Include(x => x.Reviews) .Include(x => x.Promotion) .Include(x => x.AuthorsLink) .ThenInclude(x => x.Author) .First(x => x.Reviews.Any()); var resetter = new DataResetter(context); resetter.ResetKeysEntityAndRelationships(entity); } using (var context = new BookContext(options)) { //ATTEMPT context.Add(entity); var states = context.ChangeTracker.Entries().Select(x => x.State).ToList(); //VERIFY states.Count.ShouldEqual(1 + 2 + 1 + 1 + 1); // Book + 2 reviews + promotion + BookAuthor + author states.All(x => x == EntityState.Added).ShouldBeTrue(); } }
public void TestResetKeysSingleEntityWithRelationships() { //SETUP var options = SqliteInMemory.CreateOptions <BookContext>(); using (var context = new BookContext(options)) { context.Database.EnsureCreated(); context.SeedDatabaseFourBooks(); var entity = context.Books .Include(x => x.Reviews) .Include(x => x.Promotion) .Include(x => x.AuthorsLink) .ThenInclude(x => x.Author) .First(x => x.Reviews.Any()); //ATTEMPT var resetter = new DataResetter(context); resetter.ResetKeysEntityAndRelationships(entity); //VERIFY entity.BookId.ShouldEqual(0); entity.Reviews.All(x => x.ReviewId == 0).ShouldBeTrue(); entity.Reviews.All(x => x.BookId == 0).ShouldBeTrue(); entity.Promotion.BookId.ShouldEqual(0); entity.Promotion.PriceOfferId.ShouldEqual(0); entity.AuthorsLink.All(x => x.AuthorId == 0).ShouldBeTrue(); entity.AuthorsLink.All(x => x.BookId == 0).ShouldBeTrue(); entity.AuthorsLink.Select(x => x.Author).All(x => x.AuthorId == 0).ShouldBeTrue(); } }
public void TestEfCoreLoggingViaBuilder() { //SETUP var connection = new SqliteConnection("DataSource=:memory:"); connection.Open(); var logs = new List <LogOutput>(); var options = new DbContextOptionsBuilder <BookContext>() .UseLoggerFactory(new LoggerFactory(new[] { new MyLoggerProviderActionOut(log => logs.Add(log)) })) .UseSqlite(connection) .Options; using (var context = new BookContext(options)) { context.Database.EnsureCreated(); context.SeedDatabaseFourBooks(); //ATTEMPT logs.Clear(); var books = context.Books.ToList(); //VERIFY #if NETCOREAPP2_1 logs.Single().ToString().ShouldStartWith("Information,CommandExecuted: Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']"); logs.Single().Message.ShouldStartWith("Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']"); #elif NETCOREAPP3_0 logs.Single().ToString().ShouldStartWith("Information,CommandExecuting: Executing DbCommand [Parameters=[], CommandType='Text', CommandTimeout='30']"); logs.Single().Message.ShouldStartWith("Executing DbCommand [Parameters=[], CommandType='Text', CommandTimeout='30']"); #endif } }
public void TestSqliteTwoInstancesOk() { //SETUP var options = SqliteInMemory //#A .CreateOptions <BookContext>(false); //#A using (var context = new BookContext(options)) //#B { context.Database.EnsureCreated(); context.SeedDatabaseFourBooks(); //#C } using (var context = new BookContext(options)) //#D { //ATTEMPT var book = context.Books.Last(); //#E var ex = Assert.Throws <NullReferenceException>( //#F () => book.Reviews.Add( //#F new Review { NumStars = 5 })); //#F //VERIFY ex.Message.ShouldStartWith("Object reference not set to an instance of an object."); } }
public void TestSqliteThreeInstancesOk() { //SETUP var options = SqliteInMemory.CreateOptions <BookContext>(); options.TurnOffDispose(); using (var context = new BookContext(options)) { context.Database.EnsureCreated(); context.SeedDatabaseFourBooks(); } using (var context = new BookContext(options)) { //ATTEMPT var books = context.Books.ToList(); //VERIFY books.Last().Reviews.ShouldBeNull(); } using (var context = new BookContext(options)) { //ATTEMPT var books = context.Books.ToList(); //VERIFY books.Last().Reviews.ShouldBeNull(); } options.ManualDispose(); }
public void TestDecodeMessageOneParams() { //SETUP var logs = new List <LogOutput>(); //var options = SqliteInMemory.CreateOptionsWithLogging<BookContext>(log => logs.Add(log)); #pragma warning disable 618 var options = this.CreateUniqueClassOptionsWithLogging <BookContext>(log => logs.Add(log)); #pragma warning restore 618 using (var context = new BookContext(options)) { context.Database.EnsureCreated(); context.SeedDatabaseFourBooks(); //ATTEMPT var id = context.Books.First().BookId; var book = context.Books.Single(x => x.BookId == id); var decoded = logs.Last().DecodeMessage(); //VERIFY var sqlCommand = decoded.Split('\n').Skip(1).Select(x => x.Trim()).ToArray(); sqlCommand[0].ShouldEqual( "SELECT TOP(2) [b].[BookId], [b].[Description], [b].[ImageUrl], [b].[Price], [b].[PublishedOn], [b].[Publisher], [b].[SoftDeleted], [b].[Title]"); sqlCommand[1].ShouldEqual("FROM [Books] AS [b]"); sqlCommand[2].ShouldEqual("WHERE ([b].[SoftDeleted] <> CAST(1 AS bit)) AND ([b].[BookId] = '1')"); } }
public void TestDecodeMessageNotSensitiveLogging() { //SETUP var connection = new SqliteConnection("DataSource=:memory:"); connection.Open(); var logs = new List <LogOutput>(); var options = new DbContextOptionsBuilder <BookContext>() .UseLoggerFactory(new LoggerFactory(new[] { new MyLoggerProviderActionOut(l => logs.Add(l)) })) .UseSqlite(connection) .EnableSensitiveDataLogging() .Options; using (var context = new BookContext(options)) { context.Database.EnsureCreated(); context.SeedDatabaseFourBooks(); //ATTEMPT var id = context.Books.First().BookId; var book = context.Books.Single(x => x.BookId == id); var decoded = logs.Last().DecodeMessage(); //VERIFY var sqlCommand = decoded.Split('\n').Skip(1).Select(x => x.Trim()).ToArray(); sqlCommand[0].ShouldEqual( "SELECT \"b\".\"BookId\", \"b\".\"Description\", \"b\".\"ImageUrl\", \"b\".\"Price\", \"b\".\"PublishedOn\", \"b\".\"Publisher\", \"b\".\"SoftDeleted\", \"b\".\"Title\""); sqlCommand[1].ShouldEqual("FROM \"Books\" AS \"b\""); sqlCommand[2].ShouldEqual("WHERE NOT (\"b\".\"SoftDeleted\") AND (\"b\".\"BookId\" = '1')"); } }
public void TestEfCoreLoggingCheckFilterFunction() { bool MyFilterFunction(EventId eventId, LogLevel logLevel) { return(eventId.Name == RelationalEventId.CommandExecuted.Name && logLevel == LogLevel.Information); } //SETUP var logs = new List <string>(); var logToOptions = new LogToOptions { FilterFunction = MyFilterFunction }; var options = SqliteInMemory.CreateOptionsWithLogTo <BookContext>(log => logs.Add(log), logToOptions); using var context = new BookContext(options); context.Database.EnsureCreated(); context.SeedDatabaseFourBooks(); //ATTEMPT var books = context.Books.Select(x => x.BookId).ToList(); //VERIFY logs.All(l => l.StartsWith("Executed DbCommand ")).ShouldBeTrue(); }
public void ExampleSetup() { //This simulates the production database //Typically you would get the options for a database using the SqlProductionSetup class. var options = SqliteInMemory.CreateOptions <BookContext>(); using (var context = new BookContext(options)) { context.Database.EnsureCreated(); context.SeedDatabaseFourBooks(); //1a. Read in the data to want to seed the database with var entities = context.Books .Include(x => x.Reviews) .Include(x => x.Promotion) .Include(x => x.AuthorsLink) .ThenInclude(x => x.Author) .ToList(); //1b. Reset primary and foreign keys (see next version for anonymise) var resetter = new DataResetter(context); resetter.ResetKeysEntityAndRelationships(entities); //1c. Convert to JSON string var jsonString = entities.DefaultSerializeToJson(); //1d. Save to JSON local file in TestData directory "ExampleDatabase".WriteJsonToJsonFile(jsonString); } }
public void TestWhatHappensIfDoNotResetPkFk() { //SETUP var options = SqliteInMemory.CreateOptions <BookContext>(); Book entity; using (var context = new BookContext(options)) { context.Database.EnsureCreated(); context.SeedDatabaseFourBooks(); entity = context.Books .Include(x => x.AuthorsLink) .ThenInclude(x => x.Author) .First(); } using (var context = new BookContext(options)) { //ATTEMPT context.Add(entity); var ex = Assert.Throws <DbUpdateException>(() => context.SaveChanges()); //VERIFY ex.InnerException.Message.ShouldEqual("SQLite Error 19: 'UNIQUE constraint failed: Authors.AuthorId'."); } }
public void TestEfCoreLoggingCheckSqlOutputShowLog() { //SETUP var logs = new List <string>(); var logToOptions = new LogToOptions { ShowLog = false }; var options = SqliteInMemory.CreateOptionsWithLogTo <BookContext>(log => logs.Add(log), logToOptions); using var context = new BookContext(options); context.Database.EnsureCreated(); context.SeedDatabaseFourBooks(); //ATTEMPT logToOptions.ShowLog = true; var book = context.Books.Single(x => x.Reviews.Count() > 1); //VERIFY logs.Count.ShouldEqual(1); logs.Single().ShouldEqual("Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']\r\n" + "SELECT \"b\".\"BookId\", \"b\".\"Description\", \"b\".\"ImageUrl\", \"b\".\"Price\"," + " \"b\".\"PublishedOn\", \"b\".\"Publisher\", \"b\".\"SoftDeleted\", \"b\".\"Title\"\r\n" + "FROM \"Books\" AS \"b\"\r\nWHERE NOT (\"b\".\"SoftDeleted\") AND ((\r\n" + " SELECT COUNT(*)\r\n FROM \"Review\" AS \"r\"\r\n WHERE \"b\".\"BookId\" = \"r\".\"BookId\") > 1)\r\nLIMIT 2"); }
public void TestSqliteLogToOk() { //SETUP using var options = SqliteInMemory.CreateOptions <BookContext>(); using var context = new BookContext(options); context.Database.EnsureCreated(); //ATTEMPT context.SeedDatabaseFourBooks(); //VERIFY context.Books.Count().ShouldEqual(4); }
public void TestEfCoreLoggingExampleOfOutputToConsole() { //SETUP var options = SqliteInMemory.CreateOptionsWithLogTo <BookContext>(_output.WriteLine); using var context = new BookContext(options); context.Database.EnsureCreated(); context.SeedDatabaseFourBooks(); //ATTEMPT var books = context.Books.ToList(); //VERIFY }
public void TestSqlDatabaseEnsureCleanOk() { //SETUP var options = this.CreateUniqueClassOptions <BookContext>(); using var context = new BookContext(options); context.Database.EnsureClean(); //ATTEMPT context.SeedDatabaseFourBooks(); //VERIFY context.Books.Count().ShouldEqual(4); }
public void TestSeedContextOk() { //SETUP var options = SqliteInMemory.CreateOptions <BookContext>(); using var context = new BookContext(options); context.Database.EnsureCreated(); //ATTEMPT context.SeedDatabaseFourBooks(); //VERIFY context.Books.Count().ShouldEqual(4); context.Tags.Count().ShouldEqual(4); context.Model.GetDefaultSchema().ShouldEqual(null); }
public void TestInMemoryOk() { //SETUP var options = EfInMemory.CreateOptions <BookContext>(); using (var context = new BookContext(options)) { context.Database.EnsureCreated(); //ATTEMPT context.SeedDatabaseFourBooks(); //VERIFY context.Books.Count().ShouldEqual(4); } }
public void TestSqliteOneInstanceWithChangeTrackerClearOk() { //SETUP var options = SqliteInMemory.CreateOptions <BookContext>(); using var context = new BookContext(options); context.Database.EnsureCreated(); context.SeedDatabaseFourBooks(); context.ChangeTracker.Clear(); //ATTEMPT var books = context.Books.ToList(); //VERIFY books.Last().Reviews.ShouldBeNull(); }
public void ExampleSetupWithAnonymiseLinkToLibrary() { //SETUP //This simulates the production database //Typically you would open a database var options = SqliteInMemory.CreateOptions <BookContext>(); using (var context = new BookContext(options)) { context.Database.EnsureCreated(); context.SeedDatabaseFourBooks(); //1a. Read in the data to want to seed the database with var entities = context.Books .Include(x => x.Reviews) .Include(x => x.Promotion) .Include(x => x.AuthorsLink) .ThenInclude(x => x.Author) .ToList(); //1b-ii. Set up resetter config to use own method var myAnonymiser = new MyAnonymiser(42); var config = new DataResetterConfig { AnonymiserFunc = myAnonymiser.AnonymiseThis }; //1b-ii. Add all class/properties that you want to anonymise config.AddToAnonymiseList <Author>(x => x.Name, "FullName"); config.AddToAnonymiseList <Review>(x => x.VoterName, "FirstName"); //1b. Reset primary and foreign keys and anonymise author's name and Review's VoterName var resetter = new DataResetter(context, config); resetter.ResetKeysEntityAndRelationships(entities); //Show author's myAnonymiser foreach (var author in entities.SelectMany(x => x.AuthorsLink.Select(y => y.Author)).Distinct()) { _output.WriteLine($"Author name = {author.Name}"); } //1c. Convert to JSON string var jsonString = entities.DefaultSerializeToJson(); //1d. Save to JSON local file in TestData directory "ExampleDatabaseAnonymised".WriteJsonToJsonFile(jsonString); } }
public void TestSqliteOk() { //SETUP var options = SqliteInMemory //#A .CreateOptions <BookContext>(); //#A using (var context = new BookContext(options)) //#B { context.Database.EnsureCreated(); //#C //ATTEMPT context.SeedDatabaseFourBooks(); //#D //VERIFY context.Books.Count().ShouldEqual(4); //#E } }
public void TestEfCoreLoggingExampleOfOutputToConsole() { //SETUP #pragma warning disable 618 var options = SqliteInMemory.CreateOptionsWithLogging <BookContext>(l => _output.WriteLine(l.Message)); #pragma warning restore 618 using (var context = new BookContext(options)) { context.Database.EnsureCreated(); context.SeedDatabaseFourBooks(); //ATTEMPT var books = context.Books.ToList(); //VERIFY } }
public void TestExampleSqlDatabaseOk() { //SETUP var options = this .CreateUniqueClassOptions <BookContext>(); using (var context = new BookContext(options)) { context.CreateEmptyViaWipe(); //ATTEMPT context.SeedDatabaseFourBooks(); //VERIFY context.Books.Count().ShouldEqual(4); } }
public void TestWipeDbViaSqlNotAuthorsOk() { //SETUP var options = SqliteInMemory.CreateOptions <BookContext>(); using (var context = new BookContext(options)) { context.Database.EnsureCreated(); context.SeedDatabaseFourBooks(); //ATTEMPT context.WipeAllDataFromDatabase(false, 10, typeof(Author)); //VERIFY context.Books.Count().ShouldEqual(0); context.Authors.Count().ShouldNotEqual(0); } }
public void TestSqliteSingleInstanceOk() { //SETUP var options = SqliteInMemory .CreateOptions <BookContext>(); using (var context = new BookContext(options)) { context.Database.EnsureCreated(); context.SeedDatabaseFourBooks(); //ATTEMPT var books = context.Books.ToList(); //VERIFY books.Last().Reviews.ShouldNotBeNull(); } }
public void TestResetKeysSingleEntityPkOnly() { //SETUP var options = SqliteInMemory.CreateOptions <BookContext>(); using (var context = new BookContext(options)) { context.Database.EnsureCreated(); context.SeedDatabaseFourBooks(); var entity = context.Books.First(); //ATTEMPT var resetter = new DataResetter(context); resetter.ResetKeysSingleEntity(entity); //VERIFY entity.BookId.ShouldEqual(0); } }
public void TestSqliteTwoInstancesOk() { //SETUP var options = SqliteInMemory.CreateOptions <BookContext>(); //#A options.StopNextDispose(); using (var context = new BookContext(options)) //#B { context.Database.EnsureCreated(); //#C context.SeedDatabaseFourBooks(); //#C } using (var context = new BookContext(options)) //#D { //ATTEMPT var books = context.Books.ToList(); //#E //VERIFY books.Last().Reviews.ShouldBeNull(); //#F } }
public void TestEfCoreLoggingCheckLoggerOptionsDefaultWithUtcTime() { //SETUP var logs = new List <string>(); var logToOptions = new LogToOptions { LoggerOptions = DbContextLoggerOptions.DefaultWithUtcTime }; var options = SqliteInMemory.CreateOptionsWithLogTo <BookContext>(log => logs.Add(log), logToOptions); using var context = new BookContext(options); context.Database.EnsureCreated(); context.SeedDatabaseFourBooks(); //ATTEMPT var books = context.Books.Select(x => x.BookId).ToList(); //VERIFY logs.All(x => x.StartsWith("warn:") || x.StartsWith("info:")).ShouldBeTrue(); }
public void TestEfCoreLoggingCheckLoggerOptionsSingleLine() { //SETUP var logs = new List <string>(); var logToOptions = new LogToOptions { LoggerOptions = DbContextLoggerOptions.Id }; var options = SqliteInMemory.CreateOptionsWithLogTo <BookContext>(log => logs.Add(log), logToOptions); using var context = new BookContext(options); context.Database.EnsureCreated(); context.SeedDatabaseFourBooks(); //ATTEMPT var books = context.Books.Select(x => x.BookId).ToList(); //VERIFY logs.All(x => x.StartsWith("RelationalEventId.CommandExecuted") || x.StartsWith("CoreEventId.")).ShouldBeTrue(); }
public void TestEfCoreLoggingCheckOnlyShowTheseCategories() { //SETUP var logs = new List <string>(); var logToOptions = new LogToOptions { OnlyShowTheseCategories = new[] { DbLoggerCategory.Database.Command.Name } }; var options = SqliteInMemory.CreateOptionsWithLogTo <BookContext>(log => logs.Add(log), logToOptions); using var context = new BookContext(options); context.Database.EnsureCreated(); context.SeedDatabaseFourBooks(); //ATTEMPT var books = context.Books.Select(x => x.BookId).ToList(); //VERIFY logs.All(x => x.StartsWith("Executed DbCommand")).ShouldBeTrue(); }