Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ensure warnings configured to throw really do throw with the SQL Server provider #29086

Merged
merged 1 commit into from
Sep 14, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -192,10 +192,11 @@ var coreOptionsExtension
= optionsBuilder.Options.FindExtension<CoreOptionsExtension>()
?? new CoreOptionsExtension();

coreOptionsExtension = RelationalOptionsExtension.WithDefaultWarningConfiguration(coreOptionsExtension)
.WithWarningsConfiguration(
coreOptionsExtension.WarningsConfiguration.TryWithExplicit(
SqlServerEventId.ConflictingValueGenerationStrategiesWarning, WarningBehavior.Throw));
coreOptionsExtension = RelationalOptionsExtension.WithDefaultWarningConfiguration(coreOptionsExtension);

coreOptionsExtension = coreOptionsExtension.WithWarningsConfiguration(
coreOptionsExtension.WarningsConfiguration.TryWithExplicit(
SqlServerEventId.ConflictingValueGenerationStrategiesWarning, WarningBehavior.Throw));

((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(coreOptionsExtension);
}
Expand Down
4 changes: 4 additions & 0 deletions test/EFCore.InMemory.FunctionalTests/LoggingInMemoryTest.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.EntityFrameworkCore.InMemory.Diagnostics.Internal;
using Microsoft.EntityFrameworkCore.InMemory.Infrastructure.Internal;

namespace Microsoft.EntityFrameworkCore;
Expand All @@ -12,6 +13,9 @@ protected override DbContextOptionsBuilder CreateOptionsBuilder(IServiceCollecti
.UseInMemoryDatabase("LoggingInMemoryTest")
.UseInternalServiceProvider(services.AddEntityFrameworkInMemoryDatabase().BuildServiceProvider(validateScopes: true));

protected override TestLogger CreateTestLogger()
=> new TestLogger<InMemoryLoggingDefinitions>();

protected override string ProviderName
=> "Microsoft.EntityFrameworkCore.InMemory";

Expand Down
5 changes: 2 additions & 3 deletions test/EFCore.InMemory.FunctionalTests/Query/WarningsTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,8 @@
// ReSharper disable UnusedMember.Local
// ReSharper disable InconsistentNaming
namespace Microsoft.EntityFrameworkCore.Query;
#pragma warning disable xUnit1000 // Test classes must be public
internal class WarningsTest
#pragma warning restore xUnit1000 // Test classes must be public

public class WarningsTest
{
[ConditionalFact]
public void Should_throw_by_default_when_transaction()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

// ReSharper disable InconsistentNaming

using Microsoft.EntityFrameworkCore.Diagnostics.Internal;

namespace Microsoft.EntityFrameworkCore;

public abstract class LoggingRelationalTestBase<TBuilder, TExtension> : LoggingTestBase
Expand Down Expand Up @@ -45,6 +47,106 @@ public void Logs_context_initialization_migrations_history_table_schema()
ExpectedMessage("MigrationsHistoryTable=mySchema.MyHistory " + DefaultOptions),
ActualMessage(s => CreateOptionsBuilder(s, b => b.MigrationsHistoryTable("MyHistory", "mySchema"))));

[ConditionalFact]
public virtual void IndexPropertiesBothMappedAndNotMappedToTable_throws_by_default()
{
using var context = new IndexPropertiesBothMappedAndNotMappedToTableContext(CreateOptionsBuilder(new ServiceCollection()));

Assert.Equal(
CoreStrings.WarningAsErrorTemplate(
RelationalEventId.IndexPropertiesBothMappedAndNotMappedToTable.ToString(),
RelationalResources.LogUnnamedIndexPropertiesBothMappedAndNotMappedToTable(CreateTestLogger())
.GenerateMessage(nameof(Cat), "{'Name', 'Identity'}", nameof(Cat.Identity)),
"RelationalEventId.IndexPropertiesBothMappedAndNotMappedToTable"),
Assert.Throws<InvalidOperationException>(
() => context.Model).Message);
}

protected class IndexPropertiesBothMappedAndNotMappedToTableContext : DbContext
{
public IndexPropertiesBothMappedAndNotMappedToTableContext(DbContextOptionsBuilder optionsBuilder)
: base(optionsBuilder.Options)
{
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Animal>();
modelBuilder.Entity<Cat>().ToTable((string)null).HasIndex(nameof(Animal.Name), nameof(Cat.Identity));
}
}

[ConditionalFact]
public virtual void UnnamedIndexPropertiesMappedToNonOverlappingTables_throws_by_default()
{
using var context = new UnnamedIndexPropertiesMappedToNonOverlappingTablesContext(CreateOptionsBuilder(new ServiceCollection()));

Assert.Equal(
CoreStrings.WarningAsErrorTemplate(
RelationalEventId.IndexPropertiesMappedToNonOverlappingTables.ToString(),
RelationalResources.LogUnnamedIndexPropertiesMappedToNonOverlappingTables(CreateTestLogger())
.GenerateMessage(
nameof(Cat), "{'Name', 'Identity'}", nameof(Animal.Name), "{'Animals'}", nameof(Cat.Identity), "{'Cats'}"),
"RelationalEventId.IndexPropertiesMappedToNonOverlappingTables"),
Assert.Throws<InvalidOperationException>(
() => context.Model).Message);
}

protected class UnnamedIndexPropertiesMappedToNonOverlappingTablesContext : DbContext
{
public UnnamedIndexPropertiesMappedToNonOverlappingTablesContext(DbContextOptionsBuilder optionsBuilder)
: base(optionsBuilder.Options)
{
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Animal>().ToTable("Animals");
modelBuilder.Entity<Cat>().ToTable("Cats");
modelBuilder.Entity<Cat>().HasIndex(nameof(Animal.Name), nameof(Cat.Identity));
}
}

[ConditionalFact]
public virtual void ForeignKeyPropertiesMappedToUnrelatedTables_throws_by_default()
{
using var context = new ForeignKeyPropertiesMappedToUnrelatedTablesContext(CreateOptionsBuilder(new ServiceCollection()));

var definition = RelationalResources.LogForeignKeyPropertiesMappedToUnrelatedTables(CreateTestLogger());
Assert.Equal(
CoreStrings.WarningAsErrorTemplate(
RelationalEventId.ForeignKeyPropertiesMappedToUnrelatedTables.ToString(),
definition
.GenerateMessage(
l => l.Log(
definition.Level,
definition.EventId,
definition.MessageFormat,
"{'FavoritePersonId'}", nameof(Cat), nameof(Person), "{'FavoritePersonId'}", nameof(Cat), "{'Id'}",
nameof(Person))),
"RelationalEventId.ForeignKeyPropertiesMappedToUnrelatedTables"),
Assert.Throws<InvalidOperationException>(
() => context.Model).Message);
}

protected class ForeignKeyPropertiesMappedToUnrelatedTablesContext : DbContext
{
public ForeignKeyPropertiesMappedToUnrelatedTablesContext(DbContextOptionsBuilder optionsBuilder)
: base(optionsBuilder.Options)
{
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Animal>()
.Ignore(a => a.FavoritePerson)
.Property<int>("FavoritePersonId");
modelBuilder.Entity<Cat>().ToTable("Cat")
.HasOne<Person>().WithMany()
.HasForeignKey("FavoritePersonId");
}
}

protected abstract DbContextOptionsBuilder CreateOptionsBuilder(
IServiceCollection services,
Action<RelationalDbContextOptionsBuilder<TBuilder, TExtension>> relationalAction);
Expand Down
49 changes: 49 additions & 0 deletions test/EFCore.Specification.Tests/LoggingTestBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,55 @@ protected virtual string ExpectedMessage(string optionsFragment)
ProviderVersion,
optionsFragment ?? "None").Trim();

[ConditionalFact]
public virtual void InvalidIncludePathError_throws_by_default()
{
using var context = new InvalidIncludePathErrorContext(CreateOptionsBuilder(new ServiceCollection()));

Assert.Equal(
CoreStrings.WarningAsErrorTemplate(
CoreEventId.InvalidIncludePathError.ToString(),
CoreResources.LogInvalidIncludePath(CreateTestLogger())
.GenerateMessage("Wheels", "Wheels"),
"CoreEventId.InvalidIncludePathError"),
Assert.Throws<InvalidOperationException>(
() => context.Set<Animal>().Include("Wheels").Load()).Message);
}

protected class InvalidIncludePathErrorContext : DbContext
{
public InvalidIncludePathErrorContext(DbContextOptionsBuilder optionsBuilder)
: base(optionsBuilder.Options)
{
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
=> modelBuilder.Entity<Animal>();
}

protected class Animal
{
public int Id { get; set; }
public string Name { get; set; }
public Person FavoritePerson { get; set; }
}

protected class Cat : Animal
{
public string Breed { get; set; }
public string Type { get; set; }
public int Identity { get; set; }
}

protected class Person
{
public int Id { get; set; }
public string Name { get; set; }
public string FavoriteBreed { get; set; }
}

protected abstract TestLogger CreateTestLogger();

protected abstract DbContextOptionsBuilder CreateOptionsBuilder(IServiceCollection services);

protected abstract string ProviderName { get; }
Expand Down
4 changes: 4 additions & 0 deletions test/EFCore.SqlServer.FunctionalTests/LoggingSqlServerTest.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.EntityFrameworkCore.SqlServer.Diagnostics.Internal;
using Microsoft.EntityFrameworkCore.SqlServer.Infrastructure.Internal;

// ReSharper disable InconsistentNaming
Expand All @@ -15,6 +16,9 @@ protected override DbContextOptionsBuilder CreateOptionsBuilder(
.UseInternalServiceProvider(services.AddEntityFrameworkSqlServer().BuildServiceProvider(validateScopes: true))
.UseSqlServer("Data Source=LoggingSqlServerTest.db", relationalAction);

protected override TestLogger CreateTestLogger()
=> new TestLogger<SqlServerLoggingDefinitions>();

protected override string ProviderName
=> "Microsoft.EntityFrameworkCore.SqlServer";

Expand Down
35 changes: 35 additions & 0 deletions test/EFCore.Sqlite.FunctionalTests/LoggingSqliteTest.cs
Original file line number Diff line number Diff line change
@@ -1,20 +1,55 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Transactions;
using Microsoft.EntityFrameworkCore.Diagnostics.Internal;
using Microsoft.EntityFrameworkCore.Sqlite.Diagnostics.Internal;
using Microsoft.EntityFrameworkCore.Sqlite.Infrastructure.Internal;

// ReSharper disable InconsistentNaming
namespace Microsoft.EntityFrameworkCore;

public class LoggingSqliteTest : LoggingRelationalTestBase<SqliteDbContextOptionsBuilder, SqliteOptionsExtension>
{
[ConditionalFact]
public void AmbientTransactionWarning_throws_by_default()
{
using var context = new AmbientTransactionWarningContext(CreateOptionsBuilder(new ServiceCollection()));

context.Add(new Animal());

using var transactionScope = new TransactionScope();

Assert.Equal(
CoreStrings.WarningAsErrorTemplate(
RelationalEventId.AmbientTransactionWarning.ToString(),
RelationalResources.LogAmbientTransaction(CreateTestLogger()).GenerateMessage(),
"RelationalEventId.AmbientTransactionWarning"),
Assert.Throws<InvalidOperationException>(
() => context.SaveChanges()).Message);
}

protected class AmbientTransactionWarningContext : DbContext
{
public AmbientTransactionWarningContext(DbContextOptionsBuilder optionsBuilder)
: base(optionsBuilder.Options)
{
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
=> modelBuilder.Entity<Animal>();
}

protected override DbContextOptionsBuilder CreateOptionsBuilder(
IServiceCollection services,
Action<RelationalDbContextOptionsBuilder<SqliteDbContextOptionsBuilder, SqliteOptionsExtension>> relationalAction)
=> new DbContextOptionsBuilder()
.UseInternalServiceProvider(services.AddEntityFrameworkSqlite().BuildServiceProvider(validateScopes: true))
.UseSqlite("Data Source=LoggingSqliteTest.db", relationalAction);

protected override TestLogger CreateTestLogger()
=> new TestLogger<SqliteLoggingDefinitions>();

protected override string ProviderName
=> "Microsoft.EntityFrameworkCore.Sqlite";

Expand Down