public async Task Can_open_the_underlying_connection(bool async)
    {
        var dbConnection = new FakeDbConnection("A=B");
        var context      = RelationalTestHelpers.Instance.CreateContext();

        ((FakeRelationalConnection)context.GetService <IRelationalConnection>()).UseConnection(dbConnection);

        if (async)
        {
            await context.Database.OpenConnectionAsync();

            Assert.Equal(1, dbConnection.OpenAsyncCount);
        }
        else
        {
            context.Database.OpenConnection();
            Assert.Equal(1, dbConnection.OpenCount);
        }
    }
Example #2
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().WithConnection(dbConnection))))
            {
                Assert.Null(connection.CurrentTransaction);

                using (connection.UseTransaction(dbTransaction))
                {
                    Assert.Equal(dbTransaction, connection.CurrentTransaction.GetDbTransaction());
                }

                Assert.Null(connection.CurrentTransaction);
            }
        }
Example #3
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> >()),
                new DiagnosticListener("Fake"),
                false);

            Assert.Equal(dbTransaction, transaction.GetDbTransaction());
        }
Example #4
0
            public void ShouldThrowExceptionWhenCreateTableCommandDoesNotReturnZero()
            {
                // Given
                var connection = new FakeDbConnection(openConnection: true);
                var language   = new FakeDbLanguage();
                var database   = new Database <FakeDbConnection, FakeDbLanguage>(connection, language);
                var table      = new TableMetaData <TestEntity>();

                connection.CreateCommandFactory = () => new FakeDbCommand()
                {
                    ReturnValueForExecuteNonQuery = 1
                };

                // When
                Action action = () => database.CreateTable(table);

                // Then
                action.ShouldThrow <Exception>().WithMessage("CREATE TABLE returned 1. Expected value to be 0.");
            }
        public virtual async Task Can_ExecuteNonQueryAsync(bool manageConnection)
        {
            var executeNonQueryCount = 0;
            var disposeCount         = -1;

            var fakeDbConnection = new FakeDbConnection(
                ConnectionString,
                new FakeCommandExecutor(
                    executeNonQueryAsync: (c, ct) =>
            {
                executeNonQueryCount++;
                disposeCount = c.DisposeCount;
                return(Task.FromResult(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]);

            await relationalCommand.ExecuteNonQueryAsync(fakeConnection, manageConnection : manageConnection);

            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);
        }
Example #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().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));

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

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

            Assert.Equal(1, fakeDbConnection.CloseCount);
        }
Example #7
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);
            }
        }
Example #8
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().WithConnection(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);
            }
        }
Example #9
0
        public async Task Disposes_transaction_on_exception(bool async)
        {
            var fakeDbConnection =
                new FakeDbConnection(
                    ConnectionString,
                    new FakeCommandExecutor(
                        executeNonQuery: c => { throw new InvalidOperationException(); },
                        executeNonQueryAsync: (c, ct) => { throw new InvalidOperationException(); }));

            var fakeConnection =
                CreateConnection(
                    CreateOptions(
                        new FakeRelationalOptionsExtension().WithConnection(fakeDbConnection)));

            var commandList = new List <MigrationCommand>
            {
                new MigrationCommand(CreateRelationalCommand())
            };

            var migrationCommandExecutor = new MigrationCommandExecutor();

            if (async)
            {
                await Assert.ThrowsAsync <InvalidOperationException>(
                    async()
                    => await migrationCommandExecutor.ExecuteNonQueryAsync(commandList, fakeConnection));
            }
            else
            {
                Assert.Throws <InvalidOperationException>(
                    ()
                    => migrationCommandExecutor.ExecuteNonQuery(commandList, fakeConnection));
            }

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

            Assert.Equal(1, fakeDbConnection.DbTransactions.Count);
            Assert.Equal(1, fakeDbConnection.DbTransactions[0].DisposeCount);
            Assert.Equal(0, fakeDbConnection.DbTransactions[0].CommitCount);
            Assert.Equal(0, fakeDbConnection.DbTransactions[0].RollbackCount);
        }
Example #10
0
            public void ShouldThrowExceptionWhenInsertTableCommandDoesNotReturnOne()
            {
                // Given
                var connection = new FakeDbConnection()
                {
                    CreateCommandFactory = () => new FakeDbCommand()
                    {
                        ReturnValueForExecuteNonQuery = 0
                    }
                };
                var language = new FakeDbLanguage();
                var database = new Database <FakeDbConnection, FakeDbLanguage>(connection, language);
                var row      = new TestEntity();

                // When
                Action action = () => database.Insert(row);

                // Then
                action.ShouldThrow <Exception>().WithMessage("INSERT returned 0. Expected value to be 1.");
            }
Example #11
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 {
                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, true));
            }
            else
            {
                Assert.Throws <InvalidOperationException>(()
                                                          => ((CommandAction)commandDelegate)(fakeConnection, relationalCommand, null, true));
            }

            Assert.Equal(1, fakeDbConnection.DbCommands[0].DisposeCount);
        }
Example #12
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 relationalCommand = CreateRelationalCommand();

            var result = (string)await relationalCommand.ExecuteScalarAsync(
                new FakeRelationalConnection(options),
                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);
        }
Example #13
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 relationalCommand = CreateRelationalCommand();

            var result = relationalCommand.ExecuteNonQuery(
                new FakeRelationalConnection(options),
                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);
        }
        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")),
                false);

            Assert.Equal(dbTransaction, transaction.GetDbTransaction());
        }
Example #15
0
            public void ShouldInsertRow()
            {
                // Given
                var connection = new FakeDbConnection()
                {
                    CreateCommandFactory = () => new FakeDbCommand()
                    {
                        ReturnValueForExecuteNonQuery = 1
                    }
                };
                var language = new FakeDbLanguage();
                var database = new Database <FakeDbConnection, FakeDbLanguage>(connection, language);
                var row      = new TestEntity();

                // When
                database.Insert(row);

                // Then
                var command = connection.Commands.Single();

                command.CommandText.Should().Be(FormatCommandText(
                                                    @"INSERT INTO *TestEntities* (
                        *RequiredInt*, 
                        *NullableInt*, 
                        *RequiredString*, 
                        *NullableString*
                    ) 
                    VALUES (
                        #RequiredInt, 
                        #NullableInt, 
                        #RequiredString, 
                        #NullableString
                    );"
                                                    ));

                var parameterNames = from p in command.Parameters.Cast <IDbDataParameter>()
                                     select p.ParameterName;

                parameterNames.ShouldBeEquivalentTo(new string[] { "#RequiredInt", "#NullableInt", "#RequiredString", "#NullableString" });
            }
        public virtual async Task Can_ExecuteNonQueryAsync()
        {
            var executeNonQueryCount = 0;
            var disposeCount         = -1;

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

            var optionsExtension = new FakeRelationalOptionsExtension {
                Connection = fakeDbConnection
            };

            var options = CreateOptions(optionsExtension);

            var relationalCommand = CreateRelationalCommand();

            var result = await relationalCommand.ExecuteNonQueryAsync(
                new FakeRelationalConnection(options));

            Assert.Equal(1, result);

            var expectedCount = 1;

            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);
        }
        public void Can_ExecuteScalar()
        {
            var executeScalarCount = 0;
            var disposeCount       = -1;

            var fakeDbConnection = new FakeDbConnection(
                ConnectionString,
                new FakeCommandExecutor(
                    executeScalar: c =>
            {
                executeScalarCount++;
                disposeCount = c.DisposeCount;
                return("ExecuteScalar Result");
            }));

            var optionsExtension = new FakeRelationalOptionsExtension {
                Connection = fakeDbConnection
            };

            var options = CreateOptions(optionsExtension);

            var relationalCommand = CreateRelationalCommand();

            var result = (string)relationalCommand.ExecuteScalar(
                new FakeRelationalConnection(options));

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

            var expectedCount = 1;

            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);
        }
        public void SimpleExample()
        {
            // This is the result we want to return when execute reader is executed
            var fakeDataReader = new FakeDataReader(0,"UserId","Name");
            fakeDataReader.AddRow(1, "Smith");
            fakeDataReader.AddRow(2, "John");

            var result = new List<User>();
            using (var connection = new FakeDbConnection("ConnectionString", dbCommand => fakeDataReader))
            {
                connection.Open();
                using (IDbCommand command = connection.CreateCommand())
                {
                    command.CommandText = "SELECT * FROM Users";

                    IDbDataParameter dbDataParameter = command.CreateParameter();
                    dbDataParameter.ParameterName = "ParameterName";
                    dbDataParameter.DbType = DbType.Int32;
                    dbDataParameter.Value = 0;

                    command.Parameters.Add(dbDataParameter);
                    using (IDataReader reader = command.ExecuteReader())
                    {

                        while (reader.Read())
                        {
                            result.Add(new User { UserId = reader.GetInt32(0), Name = reader.GetString(1)});
                        }
                    }
                }
            }

            Assert.That(result.Count, Is.EqualTo(2));

            Assert.That(result.ElementAt(0).UserId, Is.EqualTo(1));
            Assert.That(result.ElementAt(0).Name, Is.EqualTo("Smith"));

            Assert.That(result.ElementAt(1).UserId, Is.EqualTo(2));
            Assert.That(result.ElementAt(1).Name, Is.EqualTo("John"));
        }
        public void Can_ExecuteNonQuery()
        {
            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().WithConnection(fakeDbConnection);

            var options = CreateOptions(optionsExtension);

            var relationalCommand = CreateRelationalCommand();

            var result = relationalCommand.ExecuteNonQuery(
                new RelationalCommandParameterObject(
                    new FakeRelationalConnection(options), null, null, null));

            Assert.Equal(1, result);

            var expectedCount = 1;

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

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

            // After command execution
            Assert.Equal(1, fakeDbConnection.DbCommands[0].DisposeCount);
        }
Example #20
0
            public void ShouldIdAfterPreviousInsert()
            {
                // Given
                var expectedLastId = 123;
                var connection     = new FakeDbConnection()
                {
                    CreateCommandFactory = () => new FakeDbCommand()
                    {
                        ReturnValueForExecuteScalar = expectedLastId
                    }
                };
                var language = new FakeDbLanguage();
                var database = new Database <FakeDbConnection, FakeDbLanguage>(connection, language);

                // When
                var lastId = database.GetLastId <TestEntity>();

                // Then
                var command = connection.Commands.Single();

                lastId.Should().Be(expectedLastId);
                command.CommandText.Should().Be("SELECT #GetLastId;");
            }
Example #21
0
    public void Existing_connection_can_be_changed_and_reset()
    {
        var dbConnection = new FakeDbConnection("Database=FrodoLives");

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

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

        connection.DbConnection = null;
        Assert.Null(connection.ConnectionString);

        dbConnection            = new FakeDbConnection("Database=SamLives");
        connection.DbConnection = dbConnection;

        Assert.Equal("Database=SamLives", connection.ConnectionString);

        Assert.Equal(0, connection.DbConnections.Count);
        Assert.Same(dbConnection, connection.DbConnection);
        Assert.Equal(0, connection.DbConnections.Count);
        Assert.Equal("Database=SamLives", connection.ConnectionString);

        connection.DbConnection = null;

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

        connection.ConnectionString = "Database=MerryLives";

        dbConnection            = new FakeDbConnection("Database=MerryLives");
        connection.DbConnection = dbConnection;

        Assert.Equal(0, connection.DbConnections.Count);
        Assert.Same(dbConnection, connection.DbConnection);
        Assert.Equal(0, connection.DbConnections.Count);
        Assert.Equal("Database=MerryLives", connection.ConnectionString);
    }
Example #22
0
            public void ShouldCreateTable()
            {
                // Given
                var connection = new FakeDbConnection(openConnection: true);
                var language   = new FakeDbLanguage();
                var database   = new Database <FakeDbConnection, FakeDbLanguage>(connection, language);
                var table      = new TableMetaData <TestEntity>();

                // When
                database.CreateTable(table);

                // Then
                var command = connection.Commands.Single();

                command.CommandText.Should().Be(FormatCommandText(
                                                    @"CREATE TABLE *TestEntities* (
                        *Id* Int32 NOT NULL PRIMARY KEY, 
                        *RequiredInt* Int32 NOT NULL, 
                        *NullableInt* Nullable`1[[Int32]], 
                        *RequiredString* String NOT NULL, 
                        *NullableString* String
                    );"
                                                    ));
            }
Example #23
0
    public void Existing_connection_can_be_opened_and_closed_externally()
    {
        var dbConnection = new FakeDbConnection(
            "Database=FrodoLives");

        using var connection = new FakeRelationalConnection(
                  CreateOptions(new FakeRelationalOptionsExtension().WithConnection(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);

        dbConnection.SetState(ConnectionState.Open);

        connection.Open();

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

        dbConnection.SetState(ConnectionState.Closed);

        connection.Close();

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

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

        Assert.Equal(3, dbConnection.OpenCount);

        dbConnection.SetState(ConnectionState.Closed);

        connection.Open();

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

        dbConnection.SetState(ConnectionState.Closed);

        connection.Close();

        Assert.Equal(4, dbConnection.OpenCount);
        Assert.Equal(2, dbConnection.CloseCount);
    }
 public static FakeDbConnectionAssertions Should(this FakeDbConnection instance)
 {
     return(new FakeDbConnectionAssertions(instance));
 }
        public async Task Existing_connection_can_be_opened_and_closed_externally_async()
        {
            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);

                await connection.OpenAsync();

                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);

                await connection.OpenAsync();

                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);

                await connection.OpenAsync();

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

                connection.Close();

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

                dbConnection.SetState(ConnectionState.Open);

                await connection.OpenAsync();

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

                dbConnection.SetState(ConnectionState.Closed);

                connection.Close();

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

                await connection.OpenAsync();

                await connection.OpenAsync();

                Assert.Equal(3, dbConnection.OpenCount);

                dbConnection.SetState(ConnectionState.Closed);

                await connection.OpenAsync();

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

                dbConnection.SetState(ConnectionState.Closed);

                connection.Close();

                Assert.Equal(4, dbConnection.OpenCount);
                Assert.Equal(2, dbConnection.CloseCount);
            }
        }
        public async Task Reports_command_diagnostic_on_exception(
            Delegate commandDelegate,
            string diagnosticName,
            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 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 Assert.ThrowsAsync <InvalidOperationException>(
                    async()
                    => await((Func <RelationalCommand, bool, IRelationalConnection, Task>)commandDelegate)(relationalCommand, true, fakeConnection));
            }
            else
            {
                Assert.Throws <InvalidOperationException>(()
                                                          => ((Action <RelationalCommand, bool, IRelationalConnection>)commandDelegate)(relationalCommand, true, fakeConnection));
            }

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

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

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

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

            Assert.Equal(async, beforeData.IsAsync);
            Assert.Equal(async, afterData.IsAsync);

            Assert.Equal(exception, afterData.Exception);
        }
        public async Task Reports_command_diagnostic_on_exception(
            Delegate commandDelegate,
            string diagnosticName,
            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 diagnostic = new List <Tuple <string, object> >();

            var fakeConnection = new FakeRelationalConnection(options);

            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 Assert.ThrowsAsync <InvalidOperationException>(
                    async()
                    => await((CommandFunc)commandDelegate)(fakeConnection, relationalCommand, parameterValues));
            }
            else
            {
                Assert.Throws <InvalidOperationException>(()
                                                          => ((CommandAction)commandDelegate)(fakeConnection, relationalCommand, parameterValues));
            }

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

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

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

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

            Assert.Equal(async, beforeData.IsAsync);
            Assert.Equal(async, afterData.IsAsync);

            Assert.Equal(exception, afterData.Exception);
        }
Example #28
0
        public async Task Proxy_UpdateAsync_should_work_identically_to_Update()
        {
            List <TestTable> randomDataSource = RandomDataGenerator.CreateRandomTables(seed: 1234, tableCount: 5, /*allowZeroRowsInTablesByIdx: */ 1, 3);

            // Part 1: Use proxy
            DataSet dataSetFromProxy;
            {
                using (FakeDbConnection connection = new FakeDbConnection(asyncMode: AsyncMode.AwaitAsync))
                    using (FakeDbCommand selectCommand = connection.CreateCommand(testTables: randomDataSource))
                    {
                        await connection.OpenAsync();

                        using (BatchingFakeProxiedDbDataAdapter adapter = new BatchingFakeProxiedDbDataAdapter(selectCommand))
                            using (DbCommandBuilder cmdBuilder = await adapter.CreateCommandBuilderAsync().ConfigureAwait(false))
                            {
                                dataSetFromProxy = new DataSet();

                                // `.Fill` returns the number of rows in the first table, not any subsequent tables. Yes, that's silly.
                                Int32 rowsInFirstTable = await adapter.FillAsync(dataSetFromProxy);

                                rowsInFirstTable.ShouldBe(40);

                                //

                                Dictionary <String, Int32> rowsModified = DataTableMethods.MutateDataSet(dataSetFromProxy);

                                //

                                adapter.UpdateCommand = (FakeDbCommand)cmdBuilder.GetUpdateCommand();
                                adapter.UpdateCommand.NonQueryResultRowCountValue = (cmd) => 1; // HACK /* DataTableMethods.GetNonQueryResultRowCountValue( dataSetFromProxy, cmd, rowsModified ); */;

                                //

                                Int32 updatedRows = await adapter.UpdateAsync(dataSetFromProxy); // updatedRows... in first table only?

//                      updatedRows.ShouldBe( rowsModified );
                            }
                    }
            }

            // Part 2: Use real
            DataSet dataSetFromReal;

            {
                using (FakeDbConnection connection = new FakeDbConnection(asyncMode: AsyncMode.AllowSync))
                    using (FakeDbCommand selectCommand = connection.CreateCommand(testTables: randomDataSource))
                    {
                        connection.Open();

                        using (FakeDbDataAdapter adapter = new FakeDbDataAdapter(selectCommand))
                            using (FakeDbCommandBuilder cmdBuilder = adapter.CreateCommandBuilder())
                            {
                                dataSetFromReal = new DataSet();

                                // `.Fill` returns the number of rows in the first table, not any subsequent tables. Yes, that's silly.
                                Int32 rowsInFirstTable = adapter.Fill(dataSetFromReal);
                                rowsInFirstTable.ShouldBe(40);

                                //

                                Dictionary <String, Int32> rowsModified = DataTableMethods.MutateDataSet(dataSetFromReal);

                                //

                                adapter.UpdateCommand = cmdBuilder.GetUpdateCommand();
                                adapter.UpdateCommand.NonQueryResultRowCountValue = (cmd) => 1; // HACK /* DataTableMethods.GetNonQueryResultRowCountValue( dataSetFromProxy, cmd, rowsModified ); */;

                                //

                                Int32 updatedRows = adapter.Update(dataSetFromReal); // updatedRows... in first table only?
//                      updatedRows.ShouldBe( rowsModified );
                            }
                    }
            }

            // Assert equality:
            DataTableMethods.DataSetEquals(dataSetFromProxy, dataSetFromReal, out String diffs).ShouldBeTrue(customMessage: diffs);
        }
Example #29
0
        public void Proxy_Update_should_work_identically_to_Update()
        {
            List <TestTable> randomDataSource = RandomDataGenerator.CreateRandomTables(seed: 1234, tableCount: 5, /*allowZeroRowsInTablesByIdx: */ 1, 3);

            // TODO: Multiple table UPDATE support is... complicated: https://stackoverflow.com/questions/16218856/how-to-update-two-tables-with-one-dataset

            // Part 1: Use proxy
            DataSet dataSetFromProxy;
            {
                using (FakeDbConnection connection = new FakeDbConnection(asyncMode: AsyncMode.AllowSync))
                    using (FakeDbCommand selectCommand = connection.CreateCommand(testTables: randomDataSource))
                    {
                        connection.Open();

                        using (BatchingFakeProxiedDbDataAdapter adapter = new BatchingFakeProxiedDbDataAdapter(selectCommand))
                            using (FakeDbCommandBuilder cmdBuilder = new FakeDbCommandBuilder(adapter))
                            {
                                dataSetFromProxy = new DataSet();

                                // `.Fill` returns the number of rows in the first table, not any subsequent tables. Yes, that's silly.
                                Int32 rowsInFirstTable = adapter.Fill(dataSetFromProxy);
                                rowsInFirstTable.ShouldBe(40);

                                //

                                Dictionary <String, Int32> rowsModified = DataTableMethods.MutateDataSet(dataSetFromProxy);

                                //
                                adapter.UpdateCommand = cmdBuilder.GetUpdateCommand();
                                adapter.UpdateCommand.NonQueryResultRowCountValue = (cmd) => DataTableMethods.GetUpdateStatementNonQueryResultRowCountValue(expectedTableName: "TODO", adapter, dataSetFromProxy, cmd, rowsModified);

                                Int32 updatedRows = adapter.Update(dataSetFromProxy); // updatedRows... in first table only?
//                      updatedRows.ShouldBe( rowsModified );
                            }
                    }
            }

            // Part 2: Use real
            DataSet dataSetFromReal;

            {
                using (FakeDbConnection connection = new FakeDbConnection(asyncMode: AsyncMode.AllowSync))
                    using (FakeDbCommand selectCommand = connection.CreateCommand(testTables: randomDataSource))
                    {
                        connection.Open();

                        using (FakeDbDataAdapter adapter = new FakeDbDataAdapter(selectCommand))
                            using (FakeDbCommandBuilder cmdBuilder = adapter.CreateCommandBuilder())
                            {
                                dataSetFromReal = new DataSet();

                                // `.Fill` returns the number of rows in the first table, not any subsequent tables. Yes, that's silly.
                                Int32 rowsInFirstTable = adapter.Fill(dataSetFromReal);
                                rowsInFirstTable.ShouldBe(40);

                                //

                                Dictionary <String, Int32> rowsModified = DataTableMethods.MutateDataSet(dataSetFromReal);

                                //
                                adapter.UpdateCommand = cmdBuilder.GetUpdateCommand();
                                adapter.UpdateCommand.NonQueryResultRowCountValue = (cmd) => DataTableMethods.GetUpdateStatementNonQueryResultRowCountValue(expectedTableName: "TODO", adapter, dataSetFromReal, cmd, rowsModified);

                                Int32 updatedRows = adapter.Update(dataSetFromReal); // updatedRows... in first table only?
//                      updatedRows.ShouldBe( rowsModified );
                            }
                    }
            }

            // Assert equality:
            DataTableMethods.DataSetEquals(dataSetFromProxy, dataSetFromReal, out String diffs).ShouldBeTrue(customMessage: diffs);
        }
Example #30
0
 public FakeDbTransaction(FakeDbConnection connection, IsolationLevel isolationLevel = IsolationLevel.Unspecified)
 {
     DbConnection   = connection;
     IsolationLevel = isolationLevel;
 }