Esempio n. 1
0
        public async Task Exception_while_applying_migrations()
        {
            using (var database = SqlTestStore.CreateScratch())
            {
                using var host = new HostBuilder()
                                 .ConfigureWebHost(webHostBuilder =>
                {
                    webHostBuilder
                    .UseTestServer()
                    .Configure(app => app.UseMigrationsEndPoint())
                    .ConfigureServices(services =>
                    {
                        services.AddDbContext <BloggingContextWithSnapshotThatThrows>(optionsBuilder =>
                        {
                            optionsBuilder.UseSqlite(database.ConnectionString);
                        });
                    });
                }).Build();

                await host.StartAsync();

                var server = host.GetTestServer();

                var formData = new FormUrlEncodedContent(new List <KeyValuePair <string, string> >
                {
                    new KeyValuePair <string, string>("context", typeof(BloggingContextWithSnapshotThatThrows).AssemblyQualifiedName)
                });

                var ex = await Assert.ThrowsAsync <InvalidOperationException>(async() =>
                                                                              await server.CreateClient().PostAsync("http://localhost" + MigrationsEndPointOptions.DefaultPath, formData));

                Assert.StartsWith(StringsHelpers.GetResourceString("FormatMigrationsEndPointMiddleware_Exception", typeof(BloggingContextWithSnapshotThatThrows)), ex.Message);
                Assert.Equal("Welcome to the invalid migration!", ex.InnerException.Message);
            }
        }
Esempio n. 2
0
        public async Task Pass_thru_when_exception_in_logic()
        {
            using (var database = SqlTestStore.CreateScratch())
            {
                var logProvider = new TestLoggerProvider();

                using var host = await SetupServer <BloggingContextWithSnapshotThatThrows, ExceptionInLogicMiddleware>(database, logProvider);

                using var server = host.GetTestServer();

                try
                {
                    await server.CreateClient().GetAsync("http://localhost/");
                }
                catch (Exception exception)
                {
                    Assert.True(
                        exception.GetType().Name == "SqliteException" ||
                        exception.InnerException?.GetType().Name == "SqliteException");
                }

                Assert.Contains(logProvider.Logger.Messages.ToList(), m =>
                                m.StartsWith(StringsHelpers.GetResourceString("DatabaseErrorPageMiddleware_Exception")));
            }
        }
Esempio n. 3
0
        public async Task Customize_migrations_end_point()
        {
            var migrationsEndpoint = "/MyCustomEndPoints/ApplyMyMigrationsHere";

            using (var database = SqlTestStore.CreateScratch())
            {
                var builder = new WebHostBuilder()
                              .Configure(app =>
                {
                    app.UseDatabaseErrorPage(new DatabaseErrorPageOptions
                    {
                        MigrationsEndPointPath = new PathString(migrationsEndpoint)
                    });

                    app.UseMiddleware <PendingMigrationsMiddleware>();
                })
                              .ConfigureServices(services =>
                {
                    services.AddDbContext <BloggingContextWithMigrations>(
                        optionsBuilder => optionsBuilder.UseSqlite(database.ConnectionString));
                });
                var server = new TestServer(builder);

                HttpResponseMessage response = await server.CreateClient().GetAsync("http://localhost/");

                Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);

                var content = await response.Content.ReadAsStringAsync();

                Assert.Contains("req.open(\"POST\", \"" + JavaScriptEncode(migrationsEndpoint) + "\", true);", content);
            }
        }
Esempio n. 4
0
        private async Task Migration_request(bool useCustomPath)
        {
            using (var database = SqlTestStore.CreateScratch())
            {
                var optionsBuilder = new DbContextOptionsBuilder();
                optionsBuilder.UseSqlite(database.ConnectionString);

                var path = useCustomPath ? new PathString("/EndPoints/ApplyMyMigrations") : MigrationsEndPointOptions.DefaultPath;

                var builder = new WebHostBuilder()
                              .Configure(app =>
                {
                    if (useCustomPath)
                    {
                        app.UseMigrationsEndPoint(new MigrationsEndPointOptions
                        {
                            Path = path
                        });
                    }
                    else
                    {
                        app.UseMigrationsEndPoint();
                    }
                })
                              .ConfigureServices(services =>
                {
                    services.AddDbContext <BloggingContextWithMigrations>(options =>
                    {
                        options.UseSqlite(database.ConnectionString);
                    });
                });
                var server = new TestServer(builder);

                using (var db = BloggingContextWithMigrations.CreateWithoutExternalServiceProvider(optionsBuilder.Options))
                {
                    var databaseCreator = db.GetService <IRelationalDatabaseCreator>();
                    Assert.False(databaseCreator.Exists());

                    var formData = new FormUrlEncodedContent(new List <KeyValuePair <string, string> >
                    {
                        new KeyValuePair <string, string>("context", typeof(BloggingContextWithMigrations).AssemblyQualifiedName)
                    });

                    HttpResponseMessage response = await server.CreateClient()
                                                   .PostAsync("http://localhost" + path, formData);

                    Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);

                    Assert.True(databaseCreator.Exists());

                    var historyRepository = db.GetService <IHistoryRepository>();
                    var appliedMigrations = historyRepository.GetAppliedMigrations();
                    Assert.Equal(2, appliedMigrations.Count);
                    Assert.Equal("111111111111111_MigrationOne", appliedMigrations.ElementAt(0).MigrationId);
                    Assert.Equal("222222222222222_MigrationTwo", appliedMigrations.ElementAt(1).MigrationId);
                }
            }
        }
Esempio n. 5
0
        public async Task Existing_database_not_using_migrations_exception_passes_thru()
        {
            using (var database = SqlTestStore.CreateScratch())
            {
                TestServer server = SetupTestServer <BloggingContext, DatabaseErrorButNoMigrationsMiddleware>(database);
                var        ex     = await Assert.ThrowsAsync <DbUpdateException>(async() =>
                                                                                 await server.CreateClient().GetAsync("http://localhost/"));

                Assert.Equal("SQLite Error 1: 'no such table: Blogs'.", ex.InnerException.Message);
            }
        }
Esempio n. 6
0
            public virtual Task Invoke(HttpContext context)
            {
                using (var database = SqlTestStore.CreateScratch())
                {
                    var optionsBuilder = new DbContextOptionsBuilder()
                                         .UseLoggerFactory(context.RequestServices.GetService <ILoggerFactory>())
                                         .UseSqlite(database.ConnectionString);

                    var db = new BloggingContext(optionsBuilder.Options);
                    db.Blogs.Add(new Blog());
                    db.SaveChanges();
                    throw new Exception("SaveChanges should have thrown");
                }
            }
Esempio n. 7
0
        public async Task Error_page_displayed_when_exception_wrapped()
        {
            using (var database = SqlTestStore.CreateScratch())
            {
                TestServer          server   = SetupTestServer <BloggingContext, WrappedExceptionMiddleware>(database);
                HttpResponseMessage response = await server.CreateClient().GetAsync("http://localhost/");

                Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
                var content = await response.Content.ReadAsStringAsync();

                Assert.Contains("I wrapped your exception", content);
                Assert.Contains(StringsHelpers.GetResourceString("FormatDatabaseErrorPage_NoDbOrMigrationsTitle", typeof(BloggingContext).Name), content);
            }
        }
Esempio n. 8
0
        public async Task Error_page_displayed_no_migrations()
        {
            using (var database = SqlTestStore.CreateScratch())
            {
                TestServer          server   = SetupTestServer <BloggingContext, NoMigrationsMiddleware>(database);
                HttpResponseMessage response = await server.CreateClient().GetAsync("http://localhost/");

                Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
                var content = await response.Content.ReadAsStringAsync();

                Assert.Contains(StringsHelpers.GetResourceString("FormatDatabaseErrorPage_NoDbOrMigrationsTitle", typeof(BloggingContext).Name), content);
                Assert.Contains(StringsHelpers.GetResourceString("DatabaseErrorPage_AddMigrationCommandPMC").Replace(">", "&gt;"), content);
                Assert.Contains(StringsHelpers.GetResourceString("DatabaseErrorPage_ApplyMigrationsCommandPMC").Replace(">", "&gt;"), content);
            }
        }
Esempio n. 9
0
        public async Task Error_page_then_apply_migrations()
        {
            using (var database = SqlTestStore.CreateScratch())
            {
                using var host = await SetupServer <BloggingContextWithMigrations, ApplyMigrationsMiddleware>(database);

                using var server = host.GetTestServer();
                var client = server.CreateClient();

                var expectedMigrationsEndpoint = "/ApplyDatabaseMigrations";
                var expectedContextType        = typeof(BloggingContextWithMigrations).AssemblyQualifiedName;

                // Step One: Initial request with database failure
                HttpResponseMessage response = await client.GetAsync("http://localhost/");

                Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
                var content = await response.Content.ReadAsStringAsync();

                // Ensure the url we're going to test is what the page is using in it's JavaScript
                var javaScriptEncoder = JavaScriptEncoder.Default;
                Assert.Contains("req.open(\"POST\", \"" + JavaScriptEncode(expectedMigrationsEndpoint) + "\", true);", content);
                Assert.Contains("data-assemblyname=\"" + JavaScriptEncode(expectedContextType) + "\"", content);

                // Step Two: Request to migrations endpoint
                var formData = new FormUrlEncodedContent(new List <KeyValuePair <string, string> >
                {
                    new KeyValuePair <string, string>("context", expectedContextType)
                });

                response = await client.PostAsync("http://localhost" + expectedMigrationsEndpoint, formData);

                content = await response.Content.ReadAsStringAsync();

                Console.WriteLine(content);
                Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);

                // Step Three: Successful request after migrations applied
                response = await client.GetAsync("http://localhost/");

                content = await response.Content.ReadAsStringAsync();

                Assert.Equal("Saved a Blog", content);
            }
        }
Esempio n. 10
0
        public async Task Error_page_displayed_pending_model_changes()
        {
            using (var database = SqlTestStore.CreateScratch())
            {
                using var host = await SetupServer <BloggingContextWithPendingModelChanges, PendingModelChangesMiddleware>(database);

                using var server = host.GetTestServer();
                HttpResponseMessage response = await server.CreateClient().GetAsync("http://localhost/");

                Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);

                var content = await response.Content.ReadAsStringAsync();

                Assert.Contains(StringsHelpers.GetResourceString("FormatDatabaseErrorPage_PendingChangesTitle", typeof(BloggingContextWithPendingModelChanges).Name), content);
                Assert.Contains(StringsHelpers.GetResourceString("DatabaseErrorPage_AddMigrationCommandCLI").Replace(">", "&gt;"), content);
                Assert.Contains(StringsHelpers.GetResourceString("DatabaseErrorPage_AddMigrationCommandPMC").Replace(">", "&gt;"), content);
                Assert.Contains(StringsHelpers.GetResourceString("DatabaseErrorPage_ApplyMigrationsCommandCLI").Replace(">", "&gt;"), content);
                Assert.Contains(StringsHelpers.GetResourceString("DatabaseErrorPage_ApplyMigrationsCommandPMC").Replace(">", "&gt;"), content);
            }
        }
Esempio n. 11
0
        public async Task No_exception_on_diagnostic_event_received_when_null_state()
        {
            using (var database = SqlTestStore.CreateScratch())
            {
                using (var server = await SetupServer <BloggingContext, NoMigrationsMiddleware>(database))
                {
                    using (var db = server.Services.GetService <BloggingContext>())
                    {
                        db.Blogs.Add(new Blog());

                        try
                        {
                            db.SaveChanges();
                        }
                        catch (Exception e)
                        {
                            Assert.Equal("DbUpdateException", e.GetType().Name);
                        }
                    }
                }
            }
        }
Esempio n. 12
0
        public async Task Error_page_displayed_pending_migrations()
        {
            using (var database = SqlTestStore.CreateScratch())
            {
                using var host = await SetupServer <BloggingContextWithMigrations, PendingMigrationsMiddleware>(database);

                using var server = host.GetTestServer();
                HttpResponseMessage response = await server.CreateClient().GetAsync("http://localhost/");

                Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);

                var content = await response.Content.ReadAsStringAsync();

                Assert.Contains(StringsHelpers.GetResourceString("DatabaseErrorPage_PendingMigrationsTitle"), content);
                Assert.Contains(StringsHelpers.GetResourceString("DatabaseErrorPage_PendingMigrationsInfo"), content);
                Assert.Contains(typeof(BloggingContextWithMigrations).Name, content);
                Assert.Contains(StringsHelpers.GetResourceString("DatabaseErrorPage_ApplyMigrationsCommandPMC").Replace(">", "&gt;"), content);
                Assert.Contains("<li>111111111111111_MigrationOne</li>", content);
                Assert.Contains("<li>222222222222222_MigrationTwo</li>", content);

                Assert.DoesNotContain(StringsHelpers.GetResourceString("DatabaseErrorPage_AddMigrationCommandPMC").Replace(">", "&gt;"), content);
            }
        }