예제 #1
0
        public InheritanceSqlServerFixture()
        {
            _serviceProvider
                = new ServiceCollection()
                  .AddEntityFramework()
                  .AddSqlServer()
                  .ServiceCollection()
                  .AddSingleton(TestSqlServerModelSource.GetFactory(OnModelCreating))
                  .AddSingleton <ILoggerFactory>(new TestSqlLoggerFactory())
                  .BuildServiceProvider();

            _testStore = SqlServerTestStore.CreateScratch();

            var optionsBuilder = new DbContextOptionsBuilder();

            optionsBuilder
            .EnableSensitiveDataLogging()
            .UseSqlServer(_testStore.Connection);

            _options = optionsBuilder.Options;
            using (var context = CreateContext())
            {
                context.Database.EnsureCreated();
                SeedData(context);
            }
        }
예제 #2
0
 public BatchingTest()
 {
     _testStore       = SqlServerTestStore.CreateScratch();
     _serviceProvider = new ServiceCollection()
                        .AddEntityFrameworkSqlServer()
                        .BuildServiceProvider();
 }
예제 #3
0
        private static async Task EnsuredDeleted_noop_when_database_doesnt_exist_test(bool async, bool file)
        {
            using (var testDatabase = SqlServerTestStore.CreateScratch(createDatabase: false, useFileName: file))
            {
                using (var context = new SqlServerDatabaseCreatorTest.BloggingContext(testDatabase))
                {
                    var creator = context.GetService <IRelationalDatabaseCreator>();

                    Assert.False(async ? await creator.ExistsAsync() : creator.Exists());

                    if (async)
                    {
                        Assert.False(await creator.EnsureDeletedAsync());
                    }
                    else
                    {
                        Assert.False(creator.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);
                }
            }
        }
예제 #4
0
 private static async Task EnsureCreated_can_create_schema_in_existing_database_test(bool async, bool file)
 {
     using (var testDatabase = SqlServerTestStore.CreateScratch(useFileName: file))
     {
         await RunDatabaseCreationTest(testDatabase, async);
     }
 }
예제 #5
0
        private static async Task Create_creates_physical_database_but_not_tables_test(bool async)
        {
            using (var testDatabase = SqlServerTestStore.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'")).Count());

                Assert.True(await testDatabase.ExecuteScalarAsync <bool>(
                                string.Concat(
                                    "SELECT is_read_committed_snapshot_on FROM sys.databases WHERE name='",
                                    testDatabase.Connection.Database,
                                    "'")));
            }
        }
예제 #6
0
        private static async Task EnsureDeleted_will_delete_database_test(bool async, bool open, bool file)
        {
            using (var testDatabase = SqlServerTestStore.CreateScratch(createDatabase: true, useFileName: file))
            {
                if (!open)
                {
                    testDatabase.Connection.Close();
                }

                using (var context = new BloggingContext(testDatabase))
                {
                    var creator = context.GetService <IRelationalDatabaseCreator>();

                    Assert.True(async ? await creator.ExistsAsync() : creator.Exists());

                    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);
                }
            }
        }
        public OneToOneQuerySqlServerFixture()
        {
            _serviceProvider
                = new ServiceCollection()
                  .AddEntityFramework()
                  .AddSqlServer()
                  .ServiceCollection()
                  .AddSingleton(TestSqlServerModelSource.GetFactory(OnModelCreating))
                  .AddSingleton <ILoggerFactory>(new TestSqlLoggerFactory())
                  .BuildServiceProvider();

            _testStore = SqlServerTestStore.CreateScratch();

            var optionsBuilder = new DbContextOptionsBuilder();

            optionsBuilder.UseSqlServer(_testStore.ConnectionString);
            _options = optionsBuilder.Options;

            using (var context = new DbContext(_serviceProvider, _options))
            {
                context.Database.EnsureCreated();

                AddTestData(context);
            }
        }
예제 #8
0
        private static async Task Exists_returns_true_when_database_exists_test(bool async)
        {
            using (var testDatabase = SqlServerTestStore.CreateScratch(createDatabase: true))
            {
                var creator = GetDatabaseCreator(testDatabase);

                Assert.True(async ? await creator.ExistsAsync() : creator.Exists());
            }
        }
예제 #9
0
        private static async Task CreateTables_creates_schema_in_existing_database_test(bool async)
        {
            using (var testDatabase = SqlServerTestStore.CreateScratch(createDatabase: true))
            {
                var serviceProvider = new ServiceCollection()
                                      .AddEntityFrameworkSqlServer()
                                      .BuildServiceProvider();

                var optionsBuilder = new DbContextOptionsBuilder()
                                     .UseInternalServiceProvider(serviceProvider)
                                     .UseSqlServer(testDatabase.ConnectionString, b => b.ApplyConfiguration());

                using (var context = new SqlServerDatabaseCreatorTest.BloggingContext(testDatabase))
                {
                    var creator = (RelationalDatabaseCreator)context.GetService <IDatabaseCreator>();

                    if (async)
                    {
                        await creator.CreateTablesAsync();
                    }
                    else
                    {
                        creator.CreateTables();
                    }

                    if (testDatabase.Connection.State != ConnectionState.Open)
                    {
                        await testDatabase.Connection.OpenAsync();
                    }

                    var tables = await testDatabase.QueryAsync <string>("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'");

                    Assert.Equal(1, tables.Count());
                    Assert.Equal("Blogs", tables.Single());

                    var columns = await testDatabase.QueryAsync <string>("SELECT TABLE_NAME + '.' + COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Blogs'");

                    Assert.Equal(15, columns.Count());
                    Assert.True(columns.Any(c => c == "Blogs.Key1"));
                    Assert.True(columns.Any(c => c == "Blogs.Key2"));
                    Assert.True(columns.Any(c => c == "Blogs.Cheese"));
                    Assert.True(columns.Any(c => c == "Blogs.ErMilan"));
                    Assert.True(columns.Any(c => c == "Blogs.George"));
                    Assert.True(columns.Any(c => c == "Blogs.TheGu"));
                    Assert.True(columns.Any(c => c == "Blogs.NotFigTime"));
                    Assert.True(columns.Any(c => c == "Blogs.ToEat"));
                    Assert.True(columns.Any(c => c == "Blogs.CupOfChar"));
                    Assert.True(columns.Any(c => c == "Blogs.OrNothing"));
                    Assert.True(columns.Any(c => c == "Blogs.Fuse"));
                    Assert.True(columns.Any(c => c == "Blogs.WayRound"));
                    Assert.True(columns.Any(c => c == "Blogs.On"));
                    Assert.True(columns.Any(c => c == "Blogs.AndChew"));
                    Assert.True(columns.Any(c => c == "Blogs.AndRow"));
                }
            }
        }
예제 #10
0
 private static Task EnsureCreated_can_create_physical_database_and_schema_test(bool async, bool file)
 {
     return(SqlServerTestStore.GetExecutionStrategy().ExecuteAsync(async state =>
     {
         using (var testDatabase = SqlServerTestStore.CreateScratch(createDatabase: false, useFileName: state.file))
         {
             await RunDatabaseCreationTest(testDatabase, state.async);
         }
     }, new { async, file }));
 }
예제 #11
0
        private static async Task HasTables_returns_false_when_database_exists_but_has_no_tables_test(bool async)
        {
            using (var testDatabase = SqlServerTestStore.CreateScratch(createDatabase: true))
            {
                var creator = GetDatabaseCreator(testDatabase);

                Assert.False(async
                    ? await((TestDatabaseCreator)creator).HasTablesAsyncBase()
                    : ((TestDatabaseCreator)creator).HasTablesBase());
            }
        }
예제 #12
0
        private static async Task HasTables_returns_true_when_database_exists_and_has_any_tables_test(bool async)
        {
            using (var testDatabase = SqlServerTestStore.CreateScratch(createDatabase: true))
            {
                await testDatabase.ExecuteNonQueryAsync("CREATE TABLE SomeTable (Id uniqueidentifier)");

                var creator = GetDatabaseCreator(testDatabase);

                Assert.True(async ? await((TestDatabaseCreator)creator).HasTablesAsyncBase() : ((TestDatabaseCreator)creator).HasTablesBase());
            }
        }
예제 #13
0
        public MigrationsSqlServerFixture()
        {
            var serviceProvider = new ServiceCollection()
                                  .AddEntityFrameworkSqlServer()
                                  .BuildServiceProvider();

            _testStore = SqlServerTestStore.CreateScratch();

            _options = new DbContextOptionsBuilder()
                       .UseInternalServiceProvider(serviceProvider)
                       .UseSqlServer(_testStore.ConnectionString, b => b.ApplyConfiguration()).Options;
        }
            public virtual SqlServerTestStore GetTestStore()
            {
                var testStore = SqlServerTestStore.CreateScratch();

                using (var context = CreateContext(testStore))
                {
                    context.Database.EnsureCreated();

                    testStore.ExecuteNonQuery(@"
CREATE TRIGGER TRG_InsertProduct
ON Products
AFTER INSERT AS
BEGIN
	if @@ROWCOUNT = 0
		return
	set nocount on;

    INSERT INTO ProductBackups
    SELECT * FROM INSERTED;
END");

                    testStore.ExecuteNonQuery(@"
CREATE TRIGGER TRG_UpdateProduct
ON Products
AFTER UPDATE AS
BEGIN
	if @@ROWCOUNT = 0
		return
	set nocount on;

    DELETE FROM ProductBackups
    WHERE Id IN(SELECT DELETED.Id FROM DELETED);

    INSERT INTO ProductBackups
    SELECT * FROM INSERTED;
END");

                    testStore.ExecuteNonQuery(@"
CREATE TRIGGER TRG_DeleteProduct
ON Products
AFTER DELETE AS
BEGIN
	if @@ROWCOUNT = 0
		return
	set nocount on;

    DELETE FROM ProductBackups
    WHERE Id IN(SELECT DELETED.Id FROM DELETED);
END");
                }

                return(testStore);
            }
        public async Task Empty_Migration_Creates_Database()
        {
            using (var testDatabase = SqlServerTestStore.CreateScratch(createDatabase: false))
            {
                using (var context = CreateContext(testDatabase))
                {
                    await context.Database.MigrateAsync();

                    Assert.True(context.GetService <IRelationalDatabaseCreator>().Exists());
                }
            }
        }
예제 #16
0
        private static async Task Exists_returns_true_when_database_exists_test(bool async, bool file)
        {
            using (var testDatabase = SqlServerTestStore.CreateScratch(createDatabase: true, useFileName: file))
            {
                using (var context = new SqlServerDatabaseCreatorTest.BloggingContext(testDatabase))
                {
                    var creator = context.GetService <IRelationalDatabaseCreator>();

                    Assert.True(async ? await creator.ExistsAsync() : creator.Exists());

                    Assert.Equal(ConnectionState.Closed, context.Database.GetDbConnection().State);
                }
            }
        }
예제 #17
0
        public async Task Empty_Migration_Creates_Database()
        {
            using (var testDatabase = SqlServerTestStore.CreateScratch(createDatabase: false))
            {
                using (var context = CreateContext(testDatabase))
                {
                    var creator = (SqlServerDatabaseCreator)context.GetService <IRelationalDatabaseCreator>();
                    creator.RetryTimeout = TimeSpan.FromMinutes(10);

                    await context.Database.MigrateAsync();

                    Assert.True(creator.Exists());
                }
            }
        }
예제 #18
0
        private static async Task Create_throws_if_database_already_exists_test(bool async)
        {
            using (var testDatabase = SqlServerTestStore.CreateScratch(createDatabase: true))
            {
                var creator = GetDatabaseCreator(testDatabase);

                var ex = async
                    ? await Assert.ThrowsAsync <SqlException>(() => creator.CreateAsync())
                    : Assert.Throws <SqlException>(() => creator.Create());

                Assert.Equal(
                    1801, // Database with given name already exists
                    ex.Number);
            }
        }
예제 #19
0
        private static async Task Delete_throws_when_database_doesnt_exist_test(bool async)
        {
            using (var testDatabase = SqlServerTestStore.CreateScratch(createDatabase: false))
            {
                var creator = GetDatabaseCreator(testDatabase);

                if (async)
                {
                    await Assert.ThrowsAsync <SqlException>(() => creator.DeleteAsync());
                }
                else
                {
                    Assert.Throws <SqlException>(() => creator.Delete());
                }
            }
        }
예제 #20
0
        public void Query_when_null_key_in_database_should_throw()
        {
            using (var testStore = SqlServerTestStore.CreateScratch())
            {
                testStore.ExecuteNonQuery(
                    @"CREATE TABLE ZeroKey (Id int);
                      INSERT ZeroKey VALUES (NULL)");

                using (var context = new NullKeyContext(testStore.ConnectionString))
                {
                    Assert.Equal(
                        CoreStrings.InvalidKeyValue("ZeroKey"),
                        Assert.Throws <InvalidOperationException>(() => context.ZeroKeys.ToList()).Message);
                }
            }
        }
예제 #21
0
        public async Task Multiple_optional_navs_should_not_deadlock_bug_5481()
        {
            using (var testStore = SqlServerTestStore.CreateScratch())
            {
                using (var context = new DeadlockContext(testStore.ConnectionString))
                {
                    context.Database.EnsureCreated();
                    context.EnsureSeeded();

                    var count
                        = await context.Persons
                          .Where(p => (p.AddressOne != null && p.AddressOne.Street.Contains("Low Street")) ||
                                 (p.AddressTwo != null && p.AddressTwo.Street.Contains("Low Street")))
                          .CountAsync();

                    Assert.Equal(0, count);
                }
            }
        }
예제 #22
0
        private static async Task CreateTables_throws_if_database_does_not_exist_test(bool async)
        {
            using (var testDatabase = SqlServerTestStore.CreateScratch(createDatabase: false))
            {
                var creator = GetDatabaseCreator(testDatabase);

                var errorNumber
                    = async
                        ? (await Assert.ThrowsAsync <SqlException>(() => creator.CreateTablesAsync())).Number
                        : Assert.Throws <SqlException>(() => creator.CreateTables()).Number;

                if (errorNumber != 233) // skip if no-process transient failure
                {
                    Assert.Equal(
                        4060, // Login failed error number
                        errorNumber);
                }
            }
        }
        public BuiltInDataTypesSqlServerFixture()
        {
            _testStore = SqlServerTestStore.CreateScratch();

            var serviceProvider = new ServiceCollection()
                                  .AddEntityFrameworkSqlServer()
                                  .AddSingleton(TestSqlServerModelSource.GetFactory(OnModelCreating))
                                  .BuildServiceProvider();

            _options = new DbContextOptionsBuilder()
                       .UseSqlServer(_testStore.Connection)
                       .UseInternalServiceProvider(serviceProvider)
                       .Options;

            using (var context = new DbContext(_options))
            {
                context.Database.EnsureCreated();
            }
        }
예제 #24
0
        private static async Task HasTables_throws_when_database_doesnt_exist_test(bool async)
        {
            using (var testDatabase = SqlServerTestStore.CreateScratch(createDatabase: false))
            {
                await((TestDatabaseCreator)GetDatabaseCreator(testDatabase)).ExecutionStrategyFactory.Create()
                .ExecuteAsync(async creator =>
                {
                    var errorNumber = async
                                ? (await Assert.ThrowsAsync <SqlException>(() => creator.HasTablesAsyncBase())).Number
                                : Assert.Throws <SqlException>(() => creator.HasTablesBase()).Number;

                    if (errorNumber != 233)         // skip if no-process transient failure
                    {
                        Assert.Equal(
                            4060,         // Login failed error number
                            errorNumber);
                    }
                }, (TestDatabaseCreator)GetDatabaseCreator(testDatabase));
            }
        }
예제 #25
0
        private static async Task EnsuredCreated_is_noop_when_database_exists_and_has_schema_test(bool async, bool file)
        {
            using (var testDatabase = SqlServerTestStore.CreateScratch(createDatabase: false, useFileName: file))
            {
                using (var context = new SqlServerDatabaseCreatorTest.BloggingContext(testDatabase))
                {
                    context.Database.EnsureCreated();

                    if (async)
                    {
                        Assert.False(await context.Database.EnsureCreatedAsync());
                    }
                    else
                    {
                        Assert.False(context.Database.EnsureCreated());
                    }

                    Assert.Equal(ConnectionState.Closed, context.Database.GetDbConnection().State);
                }
            }
        }
예제 #26
0
        private static async Task Delete_will_delete_database_test(bool async)
        {
            using (var testDatabase = SqlServerTestStore.CreateScratch(createDatabase: true))
            {
                testDatabase.Connection.Close();

                var creator = GetDatabaseCreator(testDatabase);

                Assert.True(async ? await creator.ExistsAsync() : creator.Exists());

                if (async)
                {
                    await creator.DeleteAsync();
                }
                else
                {
                    creator.Delete();
                }

                Assert.False(async ? await creator.ExistsAsync() : creator.Exists());
            }
        }
예제 #27
0
        public void It_creates_unique_query_cache_key()
        {
            using (var testStore = SqlServerTestStore.CreateScratch())
            {
                object     key1, key2;
                Expression query;
                using (var context1 = new QueryKeyCacheContext(rowNumberPaging: true, connection: testStore.Connection))
                {
                    var services = ((IInfrastructure <IServiceProvider>)context1).Instance.GetService <IDbContextServices>().DatabaseProviderServices;
                    query = context1.Set <Poco1>().Skip(4).Take(10).Expression;
                    var generator = services.CompiledQueryCacheKeyGenerator;
                    key1 = generator.GenerateCacheKey(query, false);
                }

                using (var context2 = new QueryKeyCacheContext(rowNumberPaging: false, connection: testStore.Connection))
                {
                    var services  = ((IInfrastructure <IServiceProvider>)context2).Instance.GetService <IDbContextServices>().DatabaseProviderServices;
                    var generator = services.CompiledQueryCacheKeyGenerator;
                    key2 = generator.GenerateCacheKey(query, false);
                }

                Assert.NotEqual(key1, key2);
            }
        }