コード例 #1
0
        public async Task Reports_command_diagnostic(
            Delegate commandDelegate,
            DbCommandMethod diagnosticName,
            bool async)
        {
            var options = CreateOptions();

            var fakeConnection = new FakeRelationalConnection(options);

            var diagnostic = new List <Tuple <string, object> >();

            var relationalCommand = CreateRelationalCommand(
                new DiagnosticsLogger <DbLoggerCategory.Database.Command>(
                    new ListLoggerFactory(new List <(LogLevel, EventId, string)>()),
                    new FakeLoggingOptions(false),
                    new ListDiagnosticSource(diagnostic)),
                parameters: new[]
            {
                new TypeMappedRelationalParameter("FirstInvariant", "FirstParameter", new IntTypeMapping("int", DbType.Int32), false)
            });

            var parameterValues = new Dictionary <string, object>
            {
                { "FirstInvariant", 17 }
            };

            if (async)
            {
                await((CommandFunc)commandDelegate)(fakeConnection, relationalCommand, parameterValues);
            }
            else
            {
                ((CommandAction)commandDelegate)(fakeConnection, relationalCommand, parameterValues);
            }

            Assert.Equal(2, diagnostic.Count);
            Assert.Equal(RelationalEventId.CommandExecuting.Name, diagnostic[0].Item1);
            Assert.Equal(RelationalEventId.CommandExecuted.Name, diagnostic[1].Item1);

            var beforeData = (CommandEventData)diagnostic[0].Item2;
            var afterData  = (CommandExecutedEventData)diagnostic[1].Item2;

            Assert.Equal(fakeConnection.DbConnections[0].DbCommands[0], beforeData.Command);
            Assert.Equal(fakeConnection.DbConnections[0].DbCommands[0], afterData.Command);

            Assert.Equal(diagnosticName, beforeData.ExecuteMethod);
            Assert.Equal(diagnosticName, afterData.ExecuteMethod);

            Assert.Equal(async, beforeData.IsAsync);
            Assert.Equal(async, afterData.IsAsync);
        }
コード例 #2
0
        public async Task Logs_commands_parameter_values(
            Delegate commandDelegate,
            string diagnosticName,
            bool async)
        {
            var optionsExtension = new FakeRelationalOptionsExtension().WithConnectionString(ConnectionString);

            var options = CreateOptions(optionsExtension);

            var logFactory = new ListLoggerFactory();

            var fakeConnection = new FakeRelationalConnection(options);

            var relationalCommand = CreateRelationalCommand(
                new DiagnosticsLogger <DbLoggerCategory.Database.Command>(
                    logFactory,
                    new FakeLoggingOptions(true),
                    new DiagnosticListener("Fake")),
                commandText: "Logged Command",
                parameters: new[]
                { new TypeMappedRelationalParameter("FirstInvariant", "FirstParameter", new IntTypeMapping("int", DbType.Int32), false) });

            var parameterValues = new Dictionary <string, object>
            {
                { "FirstInvariant", 17 }
            };

            if (async)
            {
                await((CommandFunc)commandDelegate)(fakeConnection, relationalCommand, parameterValues);
            }
            else
            {
                ((CommandAction)commandDelegate)(fakeConnection, relationalCommand, parameterValues);
            }

            Assert.Equal(3, logFactory.Log.Count);
            Assert.Equal(LogLevel.Warning, logFactory.Log[0].Level);
            Assert.Equal(CoreStrings.LogSensitiveDataLoggingEnabled.GenerateMessage(), logFactory.Log[0].Message);

            Assert.Equal(LogLevel.Debug, logFactory.Log[1].Level);
            Assert.Equal(LogLevel.Information, logFactory.Log[2].Level);

            foreach (var(_, _, message, _, _) in logFactory.Log.Skip(1))
            {
                Assert.EndsWith(
                    "[Parameters=[FirstParameter='17'], CommandType='0', CommandTimeout='30']" + _eol +
                    "Logged Command",
                    message);
            }
        }
コード例 #3
0
        public async Task Logs_commands_without_parameter_values(
            Delegate commandDelegate,
            string diagnosticName,
            bool async)
        {
            var options = CreateOptions();

            var logFactory = new ListLoggerFactory();

            var fakeConnection = new FakeRelationalConnection(options);

            var logger = new DiagnosticsLogger <DbLoggerCategory.Database.Command>(
                logFactory,
                new FakeLoggingOptions(false),
                new DiagnosticListener("Fake"),
                new RelationalLoggingDefinitions());

            var relationalCommand = CreateRelationalCommand(
                commandText: "Logged Command",
                parameters: new[]
            {
                new TypeMappedRelationalParameter("FirstInvariant", "FirstParameter", new IntTypeMapping("int", DbType.Int32), false)
            });

            var parameterValues = new Dictionary <string, object>
            {
                { "FirstInvariant", 17 }
            };

            if (async)
            {
                await((CommandFunc)commandDelegate)(fakeConnection, relationalCommand, parameterValues, logger);
            }
            else
            {
                ((CommandAction)commandDelegate)(fakeConnection, relationalCommand, parameterValues, logger);
            }

            Assert.Equal(2, logFactory.Log.Count);

            Assert.Equal(LogLevel.Debug, logFactory.Log[0].Level);
            Assert.Equal(LogLevel.Debug, logFactory.Log[1].Level);

            foreach (var(_, _, message, _, _) in logFactory.Log)
            {
                Assert.EndsWith(
                    "[Parameters=[FirstParameter='?' (DbType = Int32)], CommandType='0', CommandTimeout='30']" + _eol +
                    "Logged Command",
                    message);
            }
        }
コード例 #4
0
        public void Can_create_new_connection_from_exsting_DbConnection()
        {
            var dbConnection = new FakeDbConnection("Database=FrodoLives");

            using (var connection = new FakeRelationalConnection(
                       CreateOptions(new FakeRelationalOptionsExtension().WithConnection(dbConnection))))
            {
                Assert.Equal(0, connection.DbConnections.Count);

                Assert.Same(dbConnection, connection.DbConnection);

                Assert.Equal(0, connection.DbConnections.Count);
            }
        }
コード例 #5
0
        public async Task Logs_commands_parameter_values(
            Delegate commandDelegate,
            string diagnosticName,
            bool async)
        {
            var optionsExtension = new FakeRelationalOptionsExtension {
                ConnectionString = ConnectionString
            };

            var options = CreateOptions(optionsExtension, logParameters: true);

            var log = new List <Tuple <LogLevel, string> >();

            var fakeConnection = new FakeRelationalConnection(options);

            var relationalCommand = CreateRelationalCommand(
                logger: new SensitiveDataLogger <RelationalCommand>(
                    new SensitiveDataLoggerDependencies <RelationalCommand>(
                        new ListLogger <RelationalCommand>(log),
                        options)),
                commandText: "Logged Command",
                parameters: new[]
            {
                new TypeMappedRelationalParameter("FirstInvariant", "FirstParameter", new RelationalTypeMapping("int", typeof(int), DbType.Int32), false)
            });

            var parameterValues = new Dictionary <string, object>
            {
                { "FirstInvariant", 17 }
            };

            if (async)
            {
                await((CommandFunc)commandDelegate)(fakeConnection, relationalCommand, parameterValues);
            }
            else
            {
                ((CommandAction)commandDelegate)(fakeConnection, relationalCommand, parameterValues);
            }

            Assert.Equal(2, log.Count);
            Assert.Equal(LogLevel.Warning, log[0].Item1);
            Assert.Equal(CoreStrings.SensitiveDataLoggingEnabled, log[0].Item2);

            Assert.Equal(LogLevel.Information, log[1].Item1);
            Assert.EndsWith(
                @"ms) [Parameters=[FirstParameter='17'], CommandType='0', CommandTimeout='30']
Logged Command",
                log[1].Item2.Replace(Environment.NewLine, FileLineEnding));
        }
コード例 #6
0
        public async Task Does_not_close_unmanaged_connections_on_exception(
            Delegate commandDelegate,
            string telemetryName,
            bool async)
        {
            var exception = new InvalidOperationException();

            var fakeDbConnection = new FakeDbConnection(
                ConnectionString,
                new FakeCommandExecutor(
                    c => { throw exception; },
                    c => { throw exception; },
                    (c, cb) => { throw exception; },
                    (c, ct) => { throw exception; },
                    (c, ct) => { throw exception; },
                    (c, cb, ct) => { throw exception; }));

            var optionsExtension = new FakeRelationalOptionsExtension {
                Connection = fakeDbConnection
            };

            var options = CreateOptions(optionsExtension);

            var fakeConnection = new FakeRelationalConnection(options);

            var relationalCommand = new RelationalCommand(
                new FakeSensitiveDataLogger <RelationalCommand>(),
                new DiagnosticListener("Fake"),
                "ExecuteReader Command",
                new RelationalParameter[0]);

            if (async)
            {
                await Assert.ThrowsAsync <InvalidOperationException>(
                    async()
                    => await((Func <RelationalCommand, bool, IRelationalConnection, Task>)commandDelegate)(relationalCommand, false, fakeConnection));

                Assert.Equal(0, fakeDbConnection.OpenAsyncCount);
            }
            else
            {
                Assert.Throws <InvalidOperationException>(()
                                                          => ((Action <RelationalCommand, bool, IRelationalConnection>)commandDelegate)(relationalCommand, false, fakeConnection));

                Assert.Equal(0, fakeDbConnection.OpenCount);
            }

            Assert.Equal(0, fakeDbConnection.CloseCount);
        }
コード例 #7
0
        public void Existing_connection_can_be_opened_and_closed_externally()
        {
            var dbConnection = new FakeDbConnection(
                "Database=FrodoLives",
                state: ConnectionState.Closed);

            using (var connection = new FakeRelationalConnection(
                       CreateOptions(new FakeRelationalOptionsExtension {
                Connection = dbConnection
            })))
            {
                Assert.Equal(0, connection.DbConnections.Count);

                connection.Open();

                Assert.Equal(0, connection.DbConnections.Count);

                Assert.Equal(1, dbConnection.OpenCount);

                connection.Close();

                Assert.Equal(1, dbConnection.OpenCount);
                Assert.Equal(1, dbConnection.CloseCount);

                dbConnection.SetState(ConnectionState.Open);

                connection.Open();

                Assert.Equal(1, dbConnection.OpenCount);
                Assert.Equal(1, dbConnection.CloseCount);

                connection.Close();

                Assert.Equal(1, dbConnection.OpenCount);
                Assert.Equal(1, dbConnection.CloseCount);

                dbConnection.SetState(ConnectionState.Closed);

                connection.Open();

                Assert.Equal(2, dbConnection.OpenCount);
                Assert.Equal(1, dbConnection.CloseCount);

                connection.Close();

                Assert.Equal(2, dbConnection.OpenCount);
                Assert.Equal(2, dbConnection.CloseCount);
            }
        }
コード例 #8
0
        public async Task Logs_commands_without_parameter_values(
            Delegate commandDelegate,
            string diagnosticName,
            bool async)
        {
            var options = CreateOptions();

            var log = new List <Tuple <LogLevel, EventId, string> >();

            var fakeConnection = new FakeRelationalConnection(options);

            var relationalCommand = CreateRelationalCommand(
                new DiagnosticsLogger <DbLoggerCategory.Database.Command>(
                    new ListLoggerFactory(log),
                    new FakeLoggingOptions(false),
                    new DiagnosticListener("Fake")),
                commandText: "Logged Command",
                parameters: new[]
            {
                new TypeMappedRelationalParameter("FirstInvariant", "FirstParameter", new IntTypeMapping("int", DbType.Int32), false)
            });

            var parameterValues = new Dictionary <string, object>
            {
                { "FirstInvariant", 17 }
            };

            if (async)
            {
                await((CommandFunc)commandDelegate)(fakeConnection, relationalCommand, parameterValues);
            }
            else
            {
                ((CommandAction)commandDelegate)(fakeConnection, relationalCommand, parameterValues);
            }

            Assert.Equal(2, log.Count);

            Assert.Equal(LogLevel.Debug, log[0].Item1);
            Assert.Equal(LogLevel.Information, log[1].Item1);

            foreach (var item in log)
            {
                Assert.EndsWith(
                    @"[Parameters=[FirstParameter='?'], CommandType='0', CommandTimeout='30']
Logged Command",
                    item.Item3.Replace(Environment.NewLine, FileLineEnding));
            }
        }
コード例 #9
0
        public void Can_create_new_connection_lazily_using_given_connection_string()
        {
            using (var connection = new FakeRelationalConnection(
                       CreateOptions(new FakeRelationalOptionsExtension {
                ConnectionString = "Database=FrodoLives"
            })))
            {
                Assert.Equal(0, connection.DbConnections.Count);

                var dbConnection = connection.DbConnection;

                Assert.Equal(1, connection.DbConnections.Count);
                Assert.Equal("Database=FrodoLives", dbConnection.ConnectionString);
            }
        }
コード例 #10
0
        public void Throws_when_rollback_is_called_without_active_transaction()
        {
            using (var connection = new FakeRelationalConnection(
                       CreateOptions(new FakeRelationalOptionsExtension {
                ConnectionString = "Database=FrodoLives"
            })))
            {
                Assert.Equal(0, connection.DbConnections.Count);

                Assert.Equal(
                    RelationalStrings.NoActiveTransaction,
                    Assert.Throws <InvalidOperationException>(
                        () => connection.RollbackTransaction()).Message);
            }
        }
コード例 #11
0
        public async Task Reports_command_diagnostic(
            Delegate commandDelegate,
            string diagnosticName,
            bool async)
        {
            var options = CreateOptions();

            var fakeConnection = new FakeRelationalConnection(options);

            var diagnostic = new List <Tuple <string, object> >();

            var relationalCommand = CreateRelationalCommand(
                diagnosticSource: new ListDiagnosticSource(diagnostic),
                parameters: new[]
            {
                new TypeMappedRelationalParameter("FirstInvariant", "FirstParameter", new RelationalTypeMapping("int", typeof(int), DbType.Int32), false)
            });

            var parameterValues = new Dictionary <string, object>
            {
                { "FirstInvariant", 17 }
            };

            if (async)
            {
                await((CommandFunc)commandDelegate)(fakeConnection, relationalCommand, parameterValues);
            }
            else
            {
                ((CommandAction)commandDelegate)(fakeConnection, relationalCommand, parameterValues);
            }

            Assert.Equal(2, diagnostic.Count);
            Assert.Equal(RelationalDiagnostics.BeforeExecuteCommand, diagnostic[0].Item1);
            Assert.Equal(RelationalDiagnostics.AfterExecuteCommand, diagnostic[1].Item1);

            var beforeData = (RelationalDiagnosticSourceBeforeMessage)diagnostic[0].Item2;
            var afterData  = (RelationalDiagnosticSourceAfterMessage)diagnostic[1].Item2;

            Assert.Equal(fakeConnection.DbConnections[0].DbCommands[0], beforeData.Command);
            Assert.Equal(fakeConnection.DbConnections[0].DbCommands[0], afterData.Command);

            Assert.Equal(diagnosticName, beforeData.ExecuteMethod);
            Assert.Equal(diagnosticName, afterData.ExecuteMethod);

            Assert.Equal(async, beforeData.IsAsync);
            Assert.Equal(async, afterData.IsAsync);
        }
コード例 #12
0
        public async Task Logs_commands_parameter_values_and_warnings(
            Delegate commandDelegate,
            string diagnosticName,
            bool async)
        {
            var optionsExtension = new FakeRelationalOptionsExtension
            {
                ConnectionString = ConnectionString
            };

            var options = CreateOptions(optionsExtension, logParameters: true);

            var fakeConnection = new FakeRelationalConnection(options);

            var log = new List <Tuple <LogLevel, string> >();

            var relationalCommand = new RelationalCommand(
                new SensitiveDataLogger <RelationalCommand>(
                    new ListLogger <RelationalCommand>(log),
                    options),
                new DiagnosticListener("Fake"),
                "Command Text",
                new[]
            {
                new RelationalParameter("FirstParameter", 17, new RelationalTypeMapping("int", typeof(int), DbType.Int32), false)
            });

            if (async)
            {
                await((Func <RelationalCommand, bool, IRelationalConnection, Task>)commandDelegate)(relationalCommand, true, fakeConnection);
            }
            else
            {
                ((Action <RelationalCommand, bool, IRelationalConnection>)commandDelegate)(relationalCommand, true, fakeConnection);
            }

            Assert.Equal(2, log.Count);
            Assert.Equal(LogLevel.Warning, log[0].Item1);
            Assert.Equal(
                @"SQL parameter value logging is enabled. As SQL parameter values may include sensitive application data, this mode should only be enabled during development.",
                log[0].Item2);

            Assert.Equal(LogLevel.Information, log[1].Item1);
            Assert.EndsWith(
                @"[Parameters=[FirstParameter='17'], CommandType='0', CommandTimeout='30']
Command Text",
                log[1].Item2);
        }
コード例 #13
0
        public async Task Reports_command_diagnostic(
            Delegate commandDelegate,
            string diagnosticName,
            bool async)
        {
            var options = CreateOptions();

            var fakeConnection = new FakeRelationalConnection(options);

            var diagnostic = new List <Tuple <string, object> >();

            var relationalCommand = new RelationalCommand(
                new SensitiveDataLogger <RelationalCommand>(
                    new FakeSensitiveDataLogger <RelationalCommand>(),
                    options),
                new ListDiagnosticSource(diagnostic),
                "Command Text",
                new[]
            {
                new RelationalParameter("FirstParameter", 17, new RelationalTypeMapping("int", typeof(int), DbType.Int32), false, null)
            });

            if (async)
            {
                await((Func <RelationalCommand, bool, IRelationalConnection, Task>)commandDelegate)(relationalCommand, true, fakeConnection);
            }
            else
            {
                ((Action <RelationalCommand, bool, IRelationalConnection>)commandDelegate)(relationalCommand, true, fakeConnection);
            }

            Assert.Equal(2, diagnostic.Count);
            Assert.Equal(RelationalDiagnostics.BeforeExecuteCommand, diagnostic[0].Item1);
            Assert.Equal(RelationalDiagnostics.AfterExecuteCommand, diagnostic[1].Item1);

            var beforeData = (RelationalDiagnosticSourceMessage)diagnostic[0].Item2;
            var afterData  = (RelationalDiagnosticSourceMessage)diagnostic[1].Item2;

            Assert.Equal(fakeConnection.DbConnections[0].DbCommands[0], beforeData.Command);
            Assert.Equal(fakeConnection.DbConnections[0].DbCommands[0], afterData.Command);

            Assert.Equal(diagnosticName, beforeData.ExecuteMethod);
            Assert.Equal(diagnosticName, afterData.ExecuteMethod);

            Assert.Equal(async, beforeData.IsAsync);
            Assert.Equal(async, afterData.IsAsync);
        }
コード例 #14
0
        public void GetDbTransaction_returns_the_DbTransaction()
        {
            var dbConnection  = new FakeDbConnection(ConnectionString);
            var dbTransaction = new FakeDbTransaction(dbConnection);

            var connection = new FakeRelationalConnection(
                CreateOptions((FakeRelationalOptionsExtension) new FakeRelationalOptionsExtension().WithConnection(dbConnection)));

            var transaction = new RelationalTransaction(
                connection,
                dbTransaction,
                new InterceptingLogger <LoggerCategory.Database.Transaction>(new ListLoggerFactory(new List <Tuple <LogLevel, string> >()), new LoggingOptions()),
                new DiagnosticListener("Fake"),
                false);

            Assert.Equal(dbTransaction, transaction.GetDbTransaction());
        }
コード例 #15
0
        public void Can_use_existing_transaction()
        {
            var dbConnection = new FakeDbConnection("Database=FrodoLives");

            var dbTransaction = dbConnection.BeginTransaction(IsolationLevel.Unspecified);

            using (var connection = new FakeRelationalConnection(
                       CreateOptions(new FakeRelationalOptionsExtension {
                Connection = dbConnection
            })))
            {
                using (connection.UseTransaction(dbTransaction))
                {
                    Assert.Equal(dbTransaction, connection.CurrentTransaction.GetDbTransaction());
                }
            }
        }
コード例 #16
0
        public void Can_ExecuteNonQuery(bool manageConnection)
        {
            var executeNonQueryCount = 0;
            var disposeCount         = -1;

            var fakeDbConnection = new FakeDbConnection(
                ConnectionString,
                new FakeCommandExecutor(
                    executeNonQuery: c =>
            {
                executeNonQueryCount++;
                disposeCount = c.DisposeCount;
                return(1);
            }));

            var optionsExtension = new FakeRelationalOptionsExtension {
                Connection = fakeDbConnection
            };

            var options = CreateOptions(optionsExtension);

            var fakeConnection = new FakeRelationalConnection(options);

            var relationalCommand = new RelationalCommand(
                new FakeSensitiveDataLogger <RelationalCommand>(),
                new DiagnosticListener("Fake"),
                "ExecuteNonQuery Command",
                new RelationalParameter[0]);

            var result = relationalCommand.ExecuteNonQuery(fakeConnection, manageConnection: manageConnection);

            Assert.Equal(1, result);

            var expectedCount = manageConnection ? 1 : 0;

            Assert.Equal(expectedCount, fakeDbConnection.OpenCount);
            Assert.Equal(expectedCount, fakeDbConnection.CloseCount);

            // Durring command execution
            Assert.Equal(1, executeNonQueryCount);
            Assert.Equal(0, disposeCount);

            // After command execution
            Assert.Equal(1, fakeDbConnection.DbCommands[0].DisposeCount);
        }
コード例 #17
0
        public void Existing_connection_can_start_in_opened_state()
        {
            var dbConnection = new FakeDbConnection(
                "Database=FrodoLives",
                state: ConnectionState.Open);

            using (var connection = new FakeRelationalConnection(
                       CreateOptions(new FakeRelationalOptionsExtension {
                Connection = dbConnection
            })))
            {
                Assert.Equal(0, connection.DbConnections.Count);

                connection.Open();

                Assert.Equal(0, connection.DbConnections.Count);

                Assert.Equal(0, dbConnection.OpenCount);

                connection.Open();
                connection.Open();

                Assert.Equal(0, dbConnection.OpenCount);

                connection.Close();
                connection.Close();

                Assert.Equal(0, dbConnection.OpenCount);
                Assert.Equal(0, dbConnection.CloseCount);

                connection.Close();

                Assert.Equal(0, dbConnection.OpenCount);
                Assert.Equal(0, dbConnection.CloseCount);

                connection.Open();

                Assert.Equal(0, dbConnection.OpenCount);

                connection.Close();

                Assert.Equal(0, dbConnection.OpenCount);
                Assert.Equal(0, dbConnection.CloseCount);
            }
        }
コード例 #18
0
        public async Task Can_ExecuteScalarAsync(bool manageConnection)
        {
            var executeScalarCount = 0;
            var disposeCount       = -1;

            var fakeDbConnection = new FakeDbConnection(
                ConnectionString,
                new FakeCommandExecutor(
                    executeScalarAsync: (c, ct) =>
            {
                executeScalarCount++;
                disposeCount = c.DisposeCount;
                return(Task.FromResult <object>("ExecuteScalar Result"));
            }));

            var optionsExtension = new FakeRelationalOptionsExtension {
                Connection = fakeDbConnection
            };

            var options = CreateOptions(optionsExtension);

            var fakeConnection = new FakeRelationalConnection(options);

            var relationalCommand = new RelationalCommand(
                new FakeSensitiveDataLogger <RelationalCommand>(),
                new DiagnosticListener("Fake"),
                "ExecuteScalar Command",
                new RelationalParameter[0]);

            var result = (string)await relationalCommand.ExecuteScalarAsync(fakeConnection, manageConnection : manageConnection);

            Assert.Equal("ExecuteScalar Result", result);

            var expectedCount = manageConnection ? 1 : 0;

            Assert.Equal(expectedCount, fakeDbConnection.OpenCount);
            Assert.Equal(expectedCount, fakeDbConnection.CloseCount);

            // Durring command execution
            Assert.Equal(1, executeScalarCount);
            Assert.Equal(0, disposeCount);

            // After command execution
            Assert.Equal(1, fakeDbConnection.DbCommands[0].DisposeCount);
        }
コード例 #19
0
        public async Task Does_not_close_unmanaged_connections_on_exception(
            Delegate commandDelegate,
            string telemetryName,
            bool async)
        {
            var exception = new InvalidOperationException();

            var fakeDbConnection = new FakeDbConnection(
                ConnectionString,
                new FakeCommandExecutor(
                    c => { throw exception; },
                    c => { throw exception; },
                    (c, cb) => { throw exception; },
                    (c, ct) => { throw exception; },
                    (c, ct) => { throw exception; },
                    (c, cb, ct) => { throw exception; }));

            var optionsExtension = new FakeRelationalOptionsExtension {
                Connection = fakeDbConnection
            };

            var options = CreateOptions(optionsExtension);

            var fakeConnection = new FakeRelationalConnection(options);

            var relationalCommand = CreateRelationalCommand();

            if (async)
            {
                await Assert.ThrowsAsync <InvalidOperationException>(
                    async()
                    => await((CommandFunc)commandDelegate)(fakeConnection, relationalCommand, null));

                Assert.Equal(1, fakeDbConnection.OpenAsyncCount);
            }
            else
            {
                Assert.Throws <InvalidOperationException>(()
                                                          => ((CommandAction)commandDelegate)(fakeConnection, relationalCommand, null));

                Assert.Equal(1, fakeDbConnection.OpenCount);
            }

            Assert.Equal(1, fakeDbConnection.CloseCount);
        }
コード例 #20
0
        public void GetDbTransaction_returns_the_DbTransaction()
        {
            var dbConnection  = new FakeDbConnection(ConnectionString);
            var dbTransaction = new FakeDbTransaction(dbConnection);

            var connection = new FakeRelationalConnection(
                CreateOptions(new FakeRelationalOptionsExtension {
                Connection = dbConnection
            }));

            var transaction = new RelationalTransaction(
                connection,
                dbTransaction,
                new ListLogger(new List <Tuple <LogLevel, string> >()),
                false);

            Assert.Equal(dbTransaction, transaction.GetDbTransaction());
        }
コード例 #21
0
        public async Task Lazy_connection_is_async_opened_and_closed_when_necessary()
        {
            using (var connection = new FakeRelationalConnection(
                       CreateOptions(new FakeRelationalOptionsExtension {
                ConnectionString = "Database=FrodoLives"
            })))
            {
                Assert.Equal(0, connection.DbConnections.Count);

                var cancellationToken = new CancellationTokenSource().Token;
                await connection.OpenAsync(cancellationToken);

                Assert.Equal(1, connection.DbConnections.Count);

                var dbConnection = connection.DbConnections[0];
                Assert.Equal(1, dbConnection.OpenAsyncCount);

                await connection.OpenAsync(cancellationToken);

                await connection.OpenAsync(cancellationToken);

                Assert.Equal(1, dbConnection.OpenAsyncCount);

                connection.Close();
                connection.Close();

                Assert.Equal(1, dbConnection.OpenAsyncCount);
                Assert.Equal(0, dbConnection.CloseCount);

                connection.Close();

                Assert.Equal(1, dbConnection.OpenAsyncCount);
                Assert.Equal(1, dbConnection.CloseCount);

                await connection.OpenAsync(cancellationToken);

                Assert.Equal(2, dbConnection.OpenAsyncCount);

                connection.Close();

                Assert.Equal(2, dbConnection.OpenAsyncCount);
                Assert.Equal(2, dbConnection.CloseCount);
            }
        }
コード例 #22
0
        public void Existing_connection_is_opened_and_closed_when_necessary()
        {
            var dbConnection = new FakeDbConnection("Database=FrodoLives");

            using (var connection = new FakeRelationalConnection(
                       CreateOptions(new FakeRelationalOptionsExtension {
                Connection = dbConnection
            })))
            {
                Assert.Equal(0, connection.DbConnections.Count);

                connection.Open();

                Assert.Equal(0, connection.DbConnections.Count);

                Assert.Equal(1, dbConnection.OpenCount);

                connection.Open();
                connection.Open();

                Assert.Equal(1, dbConnection.OpenCount);

                connection.Close();
                connection.Close();

                Assert.Equal(1, dbConnection.OpenCount);
                Assert.Equal(0, dbConnection.CloseCount);

                connection.Close();

                Assert.Equal(1, dbConnection.OpenCount);
                Assert.Equal(1, dbConnection.CloseCount);

                connection.Open();

                Assert.Equal(2, dbConnection.OpenCount);

                connection.Close();

                Assert.Equal(2, dbConnection.OpenCount);
                Assert.Equal(2, dbConnection.CloseCount);
            }
        }
コード例 #23
0
        public async Task Logs_commands_without_parameter_values(
            Delegate commandDelegate,
            string diagnosticName,
            bool async)
        {
            var options = CreateOptions();

            var log = new List <Tuple <LogLevel, string> >();

            var fakeConnection = new FakeRelationalConnection(options);

            var relationalCommand = CreateRelationalCommand(
                logger: new SensitiveDataLogger <RelationalCommand>(
                    new ListLogger <RelationalCommand>(log),
                    options),
                commandText: "Logged Command",
                parameters: new[]
            {
                new TypeMappedRelationalParameter("FirstInvariant", "FirstParameter", new RelationalTypeMapping("int", typeof(int), DbType.Int32), false)
            });

            var parameterValues = new Dictionary <string, object>
            {
                { "FirstInvariant", 17 }
            };

            if (async)
            {
                await((CommandFunc)commandDelegate)(fakeConnection, relationalCommand, parameterValues, true);
            }
            else
            {
                ((CommandAction)commandDelegate)(fakeConnection, relationalCommand, parameterValues, true);
            }

            Assert.Equal(1, log.Count);
            Assert.Equal(LogLevel.Information, log[0].Item1);
            Assert.EndsWith(
                @"[Parameters=[FirstParameter='?'], CommandType='0', CommandTimeout='30']
Logged Command",
                log[0].Item2);
        }
コード例 #24
0
        public void Lazy_connection_is_opened_and_closed_when_necessary()
        {
            using (var connection = new FakeRelationalConnection(
                       CreateOptions(new FakeRelationalOptionsExtension {
                ConnectionString = "Database=FrodoLives"
            })))
            {
                Assert.Equal(0, connection.DbConnections.Count);

                connection.Open();

                Assert.Equal(1, connection.DbConnections.Count);

                var dbConnection = connection.DbConnections[0];
                Assert.Equal(1, dbConnection.OpenCount);

                connection.Open();
                connection.Open();

                Assert.Equal(1, dbConnection.OpenCount);

                connection.Close();
                connection.Close();

                Assert.Equal(1, dbConnection.OpenCount);
                Assert.Equal(0, dbConnection.CloseCount);

                connection.Close();

                Assert.Equal(1, dbConnection.OpenCount);
                Assert.Equal(1, dbConnection.CloseCount);

                connection.Open();

                Assert.Equal(2, dbConnection.OpenCount);

                connection.Close();

                Assert.Equal(2, dbConnection.OpenCount);
                Assert.Equal(2, dbConnection.CloseCount);
            }
        }
コード例 #25
0
        public void Lazy_connection_is_recreated_if_used_again_after_being_disposed()
        {
            var connection = new FakeRelationalConnection(
                CreateOptions(new FakeRelationalOptionsExtension {
                ConnectionString = "Database=FrodoLives"
            }));

            Assert.Equal(0, connection.DbConnections.Count);
            var dbConnection = (FakeDbConnection)connection.DbConnection;

            Assert.Equal(1, connection.DbConnections.Count);

            connection.Open();

#if DNX451
            // On CoreCLR, DbConnection.Dispose() calls DbConnection.Close()
            connection.Close();
#endif

            connection.Dispose();

            Assert.Equal(1, dbConnection.OpenCount);
            Assert.Equal(1, dbConnection.CloseCount);
            Assert.Equal(1, dbConnection.DisposeCount);

            Assert.Equal(1, connection.DbConnections.Count);
            dbConnection = (FakeDbConnection)connection.DbConnection;
            Assert.Equal(2, connection.DbConnections.Count);

            connection.Open();

#if DNX451
            connection.Close();
#endif

            connection.Dispose();

            Assert.Equal(1, dbConnection.OpenCount);
            Assert.Equal(1, dbConnection.CloseCount);
            Assert.Equal(1, dbConnection.DisposeCount);
        }
コード例 #26
0
        public async Task Transaction_can_begin_with_isolation_level_async()
        {
            using (var connection = new FakeRelationalConnection(
                       CreateOptions(new FakeRelationalOptionsExtension {
                ConnectionString = "Database=FrodoLives"
            })))
            {
                Assert.Equal(0, connection.DbConnections.Count);

                using (var transaction = await connection.BeginTransactionAsync(IsolationLevel.Chaos))
                {
                    Assert.Equal(1, connection.DbConnections.Count);
                    var dbConnection = connection.DbConnections[0];

                    Assert.Equal(1, dbConnection.DbTransactions.Count);
                    var dbTransaction = dbConnection.DbTransactions[0];

                    Assert.Equal(IsolationLevel.Chaos, dbTransaction.IsolationLevel);
                }
            }
        }
コード例 #27
0
        public async Task Disposes_command_on_exception(
            Delegate commandDelegate,
            string telemetryName,
            bool async)
        {
            var exception = new InvalidOperationException();

            var fakeDbConnection = new FakeDbConnection(
                ConnectionString,
                new FakeCommandExecutor(
                    c => throw exception,
                    c => throw exception,
                    (c, cb) => throw exception,
                    (c, ct) => throw exception,
                    (c, ct) => throw exception,
                    (c, cb, ct) => throw exception));

            var optionsExtension = new FakeRelationalOptionsExtension().WithConnection(fakeDbConnection);

            var options = CreateOptions(optionsExtension);

            var fakeConnection = new FakeRelationalConnection(options);

            var relationalCommand = CreateRelationalCommand();

            if (async)
            {
                await Assert.ThrowsAsync <InvalidOperationException>(
                    async()
                    => await((CommandFunc)commandDelegate)(fakeConnection, relationalCommand, null));
            }
            else
            {
                Assert.Throws <InvalidOperationException>(
                    ()
                    => ((CommandAction)commandDelegate)(fakeConnection, relationalCommand, null));
            }

            Assert.Equal(1, fakeDbConnection.DbCommands[0].DisposeCount);
        }
コード例 #28
0
        public void GetDbTransaction_returns_the_DbTransaction()
        {
            var dbConnection  = new FakeDbConnection(ConnectionString);
            var dbTransaction = new FakeDbTransaction(dbConnection);

            var connection = new FakeRelationalConnection(
                CreateOptions((FakeRelationalOptionsExtension) new FakeRelationalOptionsExtension().WithConnection(dbConnection)));

            var loggerFactory = new ListLoggerFactory();

            var transaction = new RelationalTransaction(
                connection,
                dbTransaction,
                new DiagnosticsLogger <DbLoggerCategory.Database.Transaction>(
                    loggerFactory,
                    new LoggingOptions(),
                    new DiagnosticListener("Fake"),
                    new TestRelationalLoggingDefinitions()),
                false);

            Assert.Equal(dbTransaction, transaction.GetDbTransaction());
        }
コード例 #29
0
        public async Task Logs_commands_without_parameter_values(
            Delegate commandDelegate,
            string diagnosticName,
            bool async)
        {
            var options = CreateOptions();

            var fakeConnection = new FakeRelationalConnection(options);

            var log = new List <Tuple <LogLevel, string> >();

            var relationalCommand = new RelationalCommand(
                new SensitiveDataLogger <RelationalCommand>(
                    new ListLogger <RelationalCommand>(log),
                    options),
                new DiagnosticListener("Fake"),
                "Command Text",
                new[]
            {
                new RelationalParameter("FirstParameter", 17, new RelationalTypeMapping("int", typeof(int), DbType.Int32), false, null)
            });

            if (async)
            {
                await((Func <RelationalCommand, bool, IRelationalConnection, Task>)commandDelegate)(relationalCommand, true, fakeConnection);
            }
            else
            {
                ((Action <RelationalCommand, bool, IRelationalConnection>)commandDelegate)(relationalCommand, true, fakeConnection);
            }

            Assert.Equal(1, log.Count);
            Assert.Equal(LogLevel.Information, log[0].Item1);
            Assert.EndsWith(
                @"[Parameters=[FirstParameter='?'], CommandType='0', CommandTimeout='30']
Command Text",
                log[0].Item2);
        }
コード例 #30
0
        public void Rollback_calls_rollback_on_DbTransaction()
        {
            using (var connection = new FakeRelationalConnection(
                       CreateOptions(new FakeRelationalOptionsExtension {
                ConnectionString = "Database=FrodoLives"
            })))
            {
                Assert.Equal(0, connection.DbConnections.Count);

                using (var transaction = connection.BeginTransaction())
                {
                    Assert.Equal(1, connection.DbConnections.Count);
                    var dbConnection = connection.DbConnections[0];

                    Assert.Equal(1, dbConnection.DbTransactions.Count);
                    var dbTransaction = dbConnection.DbTransactions[0];

                    connection.RollbackTransaction();

                    Assert.Equal(1, dbTransaction.RollbackCount);
                }
            }
        }