public void Insert_with_explicit_with_default_keys() { using (var testStore = NpgsqlTestStore.Create(DatabaseName)) { using (var context = new BlogContextNoKeyGenerationNullableKey(testStore.Name)) { context.Database.EnsureCreated(); context.AddRange( new NullableKeyBlog { Id = 0, Name = "One Unicorn" }, new NullableKeyBlog { Id = 1, Name = "Two Unicorns" }); context.SaveChanges(); } using (var context = new BlogContextNoKeyGenerationNullableKey(testStore.Name)) { var blogs = context.NullableKeyBlogs.OrderBy(e => e.Id).ToList(); Assert.Equal(0, blogs[0].Id); Assert.Equal(1, blogs[1].Id); } } }
public BatchingTest() { _testStore = NpgsqlTestStore.CreateScratch(); _serviceProvider = new ServiceCollection() .AddEntityFrameworkNpgsql() .BuildServiceProvider(); }
public ArrayFixture() { _testStore = NpgsqlTestStore.CreateScratch(); using (var ctx = CreateContext()) { ctx.Database.EnsureCreated(); ctx.SomeEntities.AddRange( new SomeArrayEntity { Id = 1, SomeArray = new[] { 3, 4 }, SomeBytea = new byte[] { 3, 4 }, SomeMatrix = new[, ] { { 5, 6 }, { 7, 8 } }, SomeList = new List <int> { 3, 4 } }, new SomeArrayEntity { Id = 2, SomeArray = new[] { 5, 6, 7 }, SomeBytea = new byte[] { 5, 6, 7 }, SomeMatrix = new[, ] { { 10, 11 }, { 12, 13 } }, SomeList = new List <int> { 3, 4 } }); ctx.SaveChanges(); } }
public void Insert_with_serial_non_id() { using (var testStore = NpgsqlTestStore.Create(DatabaseName)) { int afterSave; using (var context = new BlogContextSequenceNonId(testStore.Name)) { context.Database.EnsureCreated(); var blog = context.Add(new Blog { Name = "One Unicorn" }).Entity; var beforeSave = blog.OtherId; context.SaveChanges(); afterSave = blog.OtherId; Assert.NotEqual(beforeSave, afterSave); } using (var context = new BlogContextSequenceNonId(testStore.Name)) { Assert.Equal(afterSave, context.Blogs.Single().OtherId); } } }
public void Insert_string_to_Identity_column_using_value_converter() { using var testStore = NpgsqlTestStore.CreateInitialized(DatabaseName); using (var context = new BlogContextStringToIdentityUsingValueConverter(testStore.Name)) { context.Database.EnsureCreatedResiliently(); context.AddRange( new BlogWithStringKey { Name = "One Unicorn" }, new BlogWithStringKey { Name = "Two Unicorns" }); context.SaveChanges(); } using (var context = new BlogContextStringToIdentityUsingValueConverter(testStore.Name)) { var blogs = context.StringyBlogs.OrderBy(e => e.Id).ToList(); Assert.Equal("1", blogs[0].Id); Assert.Equal("2", blogs[1].Id); } }
private static void CreateTestStore <TContext>( string databaseName, IServiceProvider serviceProvider, Func <IServiceProvider, DbContextOptions, TContext> contextCreator, Action <TContext> contextInitializer) where TContext : DbContext, IDisposable { var connectionString = NpgsqlTestStore.CreateConnectionString(databaseName); NpgsqlTestStore.GetOrCreateShared(databaseName, () => { var optionsBuilder = new DbContextOptionsBuilder(); optionsBuilder.UseNpgsql(connectionString); using (var context = contextCreator(serviceProvider, optionsBuilder.Options)) { if (context.Database.EnsureCreated()) { contextInitializer(context); } TestSqlLoggerFactory.Reset(); } }); }
public async Task Deletes_database(bool async, bool open, bool ambientTransaction) { using var testDatabase = NpgsqlTestStore.CreateInitialized("EnsureDeleteBlogging"); if (!open) { testDatabase.CloseConnection(); } using var context = new BloggingContext(testDatabase); var creator = GetDatabaseCreator(context); Assert.True(async ? await creator.ExistsAsync() : creator.Exists()); await GetExecutionStrategy(testDatabase).ExecuteAsync( async() => { using (CreateTransactionScope(ambientTransaction)) { if (async) { Assert.True(await context.Database.EnsureDeletedAsync()); } else { Assert.True(context.Database.EnsureDeleted()); } } }); Assert.Equal(ConnectionState.Closed, context.Database.GetDbConnection().State); Assert.False(async ? await creator.ExistsAsync() : creator.Exists()); Assert.Equal(ConnectionState.Closed, context.Database.GetDbConnection().State); }
private static async Task Create_creates_physical_database_but_not_tables_test(bool async) { using (var testDatabase = NpgsqlTestStore.CreateScratch(createDatabase: false)) { var creator = GetDatabaseCreator(testDatabase); Assert.False(creator.Exists()); if (async) { await creator.CreateAsync(); } else { creator.Create(); } Assert.True(creator.Exists()); if (testDatabase.Connection.State != ConnectionState.Open) { await testDatabase.Connection.OpenAsync(); } Assert.Equal(0, (await testDatabase.QueryAsync <string>("SELECT table_name FROM information_schema.tables WHERE table_type = 'BASE TABLE' AND table_schema NOT IN ('pg_catalog', 'information_schema')")).Count()); } }
public void Insert_with_server_generated_GUID_key() { using (var testStore = NpgsqlTestStore.Create(DatabaseName)) { Guid afterSave; using (var context = new BlogContextServerGuidKey(testStore.Name)) { context.Database.EnsureCreated(); var blog = context.Add(new GuidBlog { Name = "One Unicorn" }).Entity; var beforeSave = blog.Id; context.SaveChanges(); afterSave = blog.Id; Assert.NotEqual(beforeSave, afterSave); } using (var context = new BlogContextServerGuidKey(testStore.Name)) { Assert.Equal(afterSave, context.GuidBlogs.Single().Id); } } }
/// <summary> /// Initializes a <see cref="CompatibilityQueryNpgsqlFixure"/>. /// </summary> // ReSharper disable once UnusedMember.Global public CompatibilityQueryNpgsqlFixure() { TestSqlLoggerFactory = new TestSqlLoggerFactory(); _testStore = NpgsqlTestStore.CreateScratch(); using (CompatibilityContext context = CreateContext()) { context.Database.EnsureCreated(); context.CompatibilityTestEntities.AddRange( new CompatibilityTestEntity { Id = 1, DateTime = new DateTime(2018, 06, 23) }, new CompatibilityTestEntity { Id = 2, DateTime = new DateTime(2018, 06, 23) }, new CompatibilityTestEntity { Id = 3, DateTime = new DateTime(2018, 06, 23) }); context.SaveChanges(); } }
public EnumFixture() { NpgsqlConnection.GlobalTypeMapper.MapEnum <EnumType1>(); _testStore = NpgsqlTestStore.CreateScratch(); _options = new DbContextOptionsBuilder() .UseNpgsql(_testStore.ConnectionString, b => b.ApplyConfiguration()) .UseInternalServiceProvider( new ServiceCollection() .AddEntityFrameworkNpgsql() .AddSingleton <ILoggerFactory>(TestSqlLoggerFactory) .BuildServiceProvider()) .Options; using (var ctx = CreateContext()) { ctx.Database.EnsureCreated(); ctx.SomeEntities.Add(new SomeEnumEntity { Id = 1, Enum1 = EnumType1.Sad }); ctx.SaveChanges(); } }
public void Insert_with_sequence_HiLo() { using (var testStore = NpgsqlTestStore.CreateInitialized(DatabaseName)) { using (var context = new BlogContextHiLo(testStore.Name)) { context.Database.EnsureCreated(); context.AddRange(new Blog { Name = "One Unicorn" }, new Blog { Name = "Two Unicorns" }); context.SaveChanges(); } using (var context = new BlogContextHiLo(testStore.Name)) { var blogs = context.Blogs.OrderBy(e => e.Id).ToList(); Assert.Equal(1, blogs[0].Id); Assert.Equal(2, blogs[1].Id); } } }
public void Can_specify_connection_in_OnConfiguring_with_default_service_provider() { using var _ = NpgsqlTestStore.GetNorthwindStore(); using var context = new ConnectionInOnConfiguringContext(new NpgsqlConnection(NpgsqlTestStore.NorthwindConnectionString)); Assert.True(context.Customers.Any()); }
public void Insert_with_explicit_non_default_keys() { using (var testStore = NpgsqlTestStore.CreateInitialized(DatabaseName)) { using (var context = new BlogContextNoKeyGeneration(testStore.Name)) { context.Database.EnsureCreated(); context.AddRange(new Blog { Id = 66, Name = "One Unicorn" }, new Blog { Id = 67, Name = "Two Unicorns" }); context.SaveChanges(); } using (var context = new BlogContextNoKeyGeneration(testStore.Name)) { var blogs = context.Blogs.OrderBy(e => e.Id).ToList(); Assert.Equal(66, blogs[0].Id); Assert.Equal(67, blogs[1].Id); } } }
public async Task Creates_physical_database_but_not_tables(bool async, bool ambientTransaction) { using var testDatabase = NpgsqlTestStore.GetOrCreate("CreateTest"); var creator = GetDatabaseCreator(testDatabase); creator.EnsureDeleted(); await GetExecutionStrategy(testDatabase).ExecuteAsync( async() => { using (CreateTransactionScope(ambientTransaction)) { if (async) { await creator.CreateAsync(); } else { creator.Create(); } } }); Assert.True(creator.Exists()); if (testDatabase.ConnectionState != ConnectionState.Open) { await testDatabase.OpenConnectionAsync(); } Assert.Empty( await testDatabase.QueryAsync <string>( "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND NOT TABLE_NAME LIKE ANY ('{pg_%,sql_%}')")); }
public void Insert_with_default_value_from_sequence() { using (var testStore = NpgsqlTestStore.Create(DatabaseName)) { using (var context = new BlogContextDefaultValue(testStore.Name)) { context.Database.EnsureCreated(); context.AddRange(new Blog { Name = "One Unicorn" }, new Blog { Name = "Two Unicorns" }); context.SaveChanges(); } using (var context = new BlogContextDefaultValue(testStore.Name)) { var blogs = context.Blogs.OrderBy(e => e.Id).ToList(); Assert.Equal(77, blogs[0].Id); Assert.Equal(78, blogs[1].Id); } } }
private static IServiceProvider CreateContextServices(NpgsqlTestStore testStore) => ((IInfrastructure <IServiceProvider>) new BloggingContext( new DbContextOptionsBuilder() .UseNpgsql(testStore.ConnectionString, b => b.ApplyConfiguration()) .UseInternalServiceProvider(new ServiceCollection() .AddEntityFrameworkNpgsql() //.AddScoped<NpgsqlExecutionStrategyFactory, TestNpgsqlExecutionStrategyFactory>() .AddScoped <IRelationalDatabaseCreator, TestDatabaseCreator>().BuildServiceProvider()).Options)) .Instance;
private static async Task Exists_returns_true_when_database_exists_test(bool async) { using (var testDatabase = NpgsqlTestStore.CreateScratch(createDatabase: true)) { var creator = GetDatabaseCreator(testDatabase); Assert.True(async ? await creator.ExistsAsync() : creator.Exists()); } }
static async Task Can_use_an_existing_closed_connection_test(bool openConnection) { var serviceProvider = new ServiceCollection() .AddEntityFrameworkNpgsql() .BuildServiceProvider(); using (var store = NpgsqlTestStore.GetNorthwindStore()) { store.CloseConnection(); var openCount = 0; var closeCount = 0; var disposeCount = 0; using (var connection = new NpgsqlConnection(store.ConnectionString)) { if (openConnection) { await connection.OpenAsync(); } connection.StateChange += (_, a) => { if (a.CurrentState == ConnectionState.Open) { openCount++; } else if (a.CurrentState == ConnectionState.Closed) { closeCount++; } }; connection.Disposed += (_, __) => disposeCount++; using (var context = new NorthwindContext(serviceProvider, connection)) { Assert.Equal(91, await context.Customers.CountAsync()); } if (openConnection) { Assert.Equal(ConnectionState.Open, connection.State); Assert.Equal(0, openCount); Assert.Equal(0, closeCount); } else { Assert.Equal(ConnectionState.Closed, connection.State); Assert.Equal(1, openCount); Assert.Equal(1, closeCount); } Assert.Equal(0, disposeCount); } } }
public void Can_specify_connection_string_in_OnConfiguring_with_default_service_provider() { using (NpgsqlTestStore.GetNorthwindStore()) { using (var context = new StringInOnConfiguringContext()) { Assert.True(context.Customers.Any()); } } }
public void Can_depend_on_non_generic_options_when_only_one_context_with_default_service_provider() { using (NpgsqlTestStore.GetNorthwindStore()) { using (var context = new NonGenericOptionsContext(new DbContextOptions <DbContext>())) { Assert.True(context.Customers.Any()); } } }
public NotificationEntitiesNpgsqlFixture() { _options = new DbContextOptionsBuilder() .UseNpgsql(NpgsqlTestStore.CreateConnectionString(DatabaseName), b => b.ApplyConfiguration()) .UseInternalServiceProvider(new ServiceCollection() .AddEntityFrameworkNpgsql() .AddSingleton(TestModelSource.GetFactory(OnModelCreating)) .BuildServiceProvider()) .Options; }
protected override void CreateAndSeedDatabase(string databaseName, Func <MonsterContext> createContext, Action <MonsterContext> seed) { _testStore = NpgsqlTestStore.GetOrCreateShared(databaseName, () => { using (var context = createContext()) { context.Database.EnsureCreated(); seed(context); } }); }
public SystemColumnTest() { _testStore = NpgsqlTestStore.CreateScratch(); _options = new DbContextOptionsBuilder() .UseNpgsql(_testStore.ConnectionString) .Options; using (var context = CreateContext()) context.Database.EnsureCreated(); }
private static async Task HasTables_returns_true_when_database_exists_and_has_any_tables_test(bool async) { using (var testDatabase = NpgsqlTestStore.CreateScratch(createDatabase: true)) { await testDatabase.ExecuteNonQueryAsync("CREATE TABLE some_table (id SERIAL PRIMARY KEY)"); var creator = GetDatabaseCreator(testDatabase); Assert.True(async ? await((TestDatabaseCreator)creator).HasTablesAsyncBase() : ((TestDatabaseCreator)creator).HasTablesBase()); } }
public void Can_specify_connection_string_in_OnConfiguring() { var serviceProvider = new ServiceCollection() .AddDbContext <StringInOnConfiguringContext>() .BuildServiceProvider(); using var _ = NpgsqlTestStore.GetNorthwindStore(); using var context = serviceProvider.GetRequiredService <StringInOnConfiguringContext>(); Assert.True(context.Customers.Any()); }
private static async Task HasTables_returns_false_when_database_exists_but_has_no_tables_test(bool async) { using (var testDatabase = NpgsqlTestStore.CreateScratch(createDatabase: true)) { var creator = GetDatabaseCreator(testDatabase); Assert.False(async ? await((TestDatabaseCreator)creator).HasTablesAsyncBase() : ((TestDatabaseCreator)creator).HasTablesBase()); } }
public ExecutionStrategyTest(ExecutionStrategyFixture fixture) { Fixture = fixture; TestStore = NpgsqlTestStore.GetOrCreateShared(DatabaseName, () => { using (var context = CreateContext()) { context.Database.EnsureCreated(); } }); }
public async Task Throws_if_database_already_exists(bool async) { using var testDatabase = NpgsqlTestStore.GetOrCreateInitialized("ExistingBlogging"); var creator = GetDatabaseCreator(testDatabase); var ex = async ? await Assert.ThrowsAsync <PostgresException>(() => creator.CreateAsync()) : Assert.Throws <PostgresException>(() => creator.Create()); Assert.Equal(PostgresErrorCodes.DuplicateDatabase, ex.SqlState); }
public override DbContext CreateContext(NpgsqlTestStore testStore) { var optionsBuilder = new DbContextOptionsBuilder() .UseNpgsql(testStore.Connection) .UseInternalServiceProvider(_serviceProvider); var context = new GraphUpdatesContext(optionsBuilder.Options); context.Database.UseTransaction(testStore.Transaction); return(context); }
public NorthwindQueryNpgsqlFixture() { _testStore = NpgsqlNorthwindContext.GetSharedStore(); _serviceProvider = new ServiceCollection() .AddEntityFramework() .AddNpgsql() .ServiceCollection() .AddSingleton(TestNpgsqlModelSource.GetFactory(OnModelCreating)) .AddInstance<ILoggerFactory>(new TestSqlLoggerFactory()) .BuildServiceProvider(); var optionsBuilder = new DbContextOptionsBuilder(); optionsBuilder.UseNpgsql(_testStore.Connection.ConnectionString); _options = optionsBuilder.Options; _serviceProvider.GetRequiredService<ILoggerFactory>() .MinimumLevel = LogLevel.Debug; }