Ejemplo n.º 1
0
 public void GivenDb_WhenOnPrepareIsConfigured__AndExecuteIsCalled_CommandIsPrepared()
 {
     var fakeConnection = new FakeConnection();
     var db = new Db(fakeConnection, new DbConfig(c => ((FakeCommand)c).Comment = "PREPARED", MappingConvention.OracleStyle, string.Empty));
     db.Execute("");
     Assert.AreEqual("PREPARED", fakeConnection.Commands.Single().Comment);
 }
Ejemplo n.º 2
0
        public void TestInitialConnectionPromptsAfterEachWrite()
        {
            string endl = Environment.NewLine;
            var connection = new FakeConnection();
            var session = new Session(connection);

            // Send a prompt through the connection. (This should be asking which character to login, or to create a new one.)
            var prompt = session.State.BuildPrompt();
            Verify.IsTrue(prompt.Length > 0);
            Verify.AreEqual(1, connection.FakeMessagesSent.Count);

            connection.Reset();

            session.Write("test 1", true);
            Verify.AreEqual(1, connection.FakeMessagesSent.Count);
            Verify.AreEqual("test 1" + endl + prompt, connection.FakeMessagesSent[0]);

            connection.Reset();

            session.Write("test 2", false);
            Verify.AreEqual(1, connection.FakeMessagesSent.Count);
            Verify.AreEqual(endl + "test 2", connection.FakeMessagesSent[0]);

            connection.Reset();

            session.Write("test 3a");
            session.Write("test 3b");
            Verify.AreEqual(2, connection.FakeMessagesSent.Count);
            Verify.AreEqual("test 3a" + endl + prompt, connection.FakeMessagesSent[0]);
            Verify.AreEqual(endl + "test 3b" + endl + prompt, connection.FakeMessagesSent[1]);
        }
Ejemplo n.º 3
0
        static void Main(string[] args)
        {
            ConsoleColor old = Console.ForegroundColor;
            try{
                var props = new ConnectionProperties();
                using (var frm = new ConnectionDialog(props, true, Assembly.LoadFrom))
                {
                    var result = frm.ShowDialog();
                    if (result != System.Windows.Forms.DialogResult.OK)
                        return;
                }

                var cxi = new FakeConnection();
                new ConnectionPropertiesSerializer().Serialize(cxi.DriverData, props);

                var driver = new MongoDynamicDataContextDriver();

                List<Assembly> assemblies = props.AssemblyLocations.Select(Assembly.LoadFrom).ToList();
                var code = driver.GetStaticCodeFiles()
                    .Concat(new string[] {driver.GenerateDynamicCode(props, assemblies, "", "driver")});
                if(props.InitializationQuery != null)
                    code = code.Concat(new string[]{driver.GenerateCustomInitQuery(props.InitializationQuery, "driver")});

                Console.ForegroundColor = ConsoleColor.DarkCyan;
                Console.WriteLine("------------------------------------------------");
                foreach (string s in code)
                {
                    Console.WriteLine(s);
                    Console.WriteLine("------------------------------------------------");
                }
                Console.ForegroundColor = old;

                using (var frm = new SaveFileDialog())
                {
                    var result = frm.ShowDialog();
                    if (result == DialogResult.OK)
                    {
                        using (StreamWriter writer = new StreamWriter(frm.OpenFile()))
                        {
                            foreach (string s in code)
                            {
                                writer.WriteLine(s);
                                writer.WriteLine("---------------------------------------------------");
                            }

                            writer.Flush();
                        }

                    }
                }

            }catch(Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(ex);
            }
            finally{
                Console.ForegroundColor = old;
            }
        }
        public async Task StartCreatesAndOpensWebSocket()
        {
            var fakeWebSocketTransport = new FakeWebSocketTransport();

            fakeWebSocketTransport.Setup("OpenWebSocket", () =>
            {
                var tcs = new TaskCompletionSource<object>();
                tcs.TrySetResult(null);
                return tcs.Task;
            });

            var fakeConnection = new FakeConnection
            {
                TransportConnectTimeout = new TimeSpan(0, 0, 0, 0, 100),
                TotalTransportConnectTimeout = new TimeSpan(0, 0, 0, 0, 100),
                Url = "http://fake.url",
                Protocol = new Version(1, 42),
                ConnectionToken = "MyConnToken",
                MessageId = "MsgId"
            };

            // connect timeout unblocks this call hence the expected exception
            await Assert.ThrowsAsync<TimeoutException>(
                async () => await fakeWebSocketTransport.Start(fakeConnection, "test", CancellationToken.None));

            Assert.Equal(1, fakeConnection.GetInvocations("Trace").Count());
            Assert.Equal(1, fakeConnection.GetInvocations("PrepareRequest").Count());

            var openWebSocketInvocations = fakeWebSocketTransport.GetInvocations("OpenWebSocket").ToArray();
            Assert.Equal(1, openWebSocketInvocations.Length);
            Assert.StartsWith(
                "ws://fake.urlconnect/?clientProtocol=1.42&transport=webSockets&connectionData=test&connectionToken=MyConnToken&messageId=MsgId",
                ((Uri)openWebSocketInvocations[0][1]).AbsoluteUri);
        }
Ejemplo n.º 5
0
 public MigrationTaskRunnerTests()
 {
     _db = new FakeConnection();
     //_db.Setup(d => d.BeginTransaction()).Returns(new FakeTransaction());
     LogHelper.Register(new ConsoleLogger(), "Default");
     _sb = new StringBuilder();
    _runner = new MigrationTaskRunner(_db, LogHelper.DefaultLogger);
 }
Ejemplo n.º 6
0
        public void TestInitialConnectionStateIsNotDefaultState()
        {
            string endl = Environment.NewLine;
            var connection = new FakeConnection();
            var session = new Session(connection);

            Verify.IsTrue(session.State is SessionState);
            Verify.IsTrue(!(session.State is DefaultState), "The default session state should have been ConnectedState.");
        }
        public async Task When_Add_Succeeds_InsertAsync_Returns_Success()
        {
            var connection = new FakeConnection();
            connection.SetResponse(ResponsePackets.ADD_SUCCESS);
            _connectionPool.AddConnection(connection);

            var bucket = GetBucketForKey("key1");
            var result = await bucket.InsertAsync("key1", "NA");

            Assert.IsTrue(result.Success);
            Assert.AreEqual(ResponseStatus.Success, result.Status);
        }
        public async void When_Key_Is_Found_GetAsync_Returns_True()
        {
            var connection = new FakeConnection();
            connection.SetResponse(ResponsePackets.GET_OPAQUE_5_SUCCESS);
            _connectionPool.AddConnection(connection);

            var bucket = GetBucketForKey("key1");
            var result = await bucket.GetAsync<int>("key1");

            Assert.IsTrue(result.Success);
            Assert.AreEqual(ResponseStatus.Success, result.Status);
        }
        public void SpecificCommand()
        {
            var connection = new FakeConnection();
            var cmdToReturn = new FakeCommand(new ScalarCommandResult("SELECT count(*) FROM users", null){Result = 201});
            connection.Setup(cmdToReturn);

            var cmd = connection.CreateCommand();
            cmd.CommandText = "SELECT count(*) FROM users";
            var result = cmd.ExecuteScalar();

           Assert.Equal(201, result);
        }
        public void CreateModel_CreatesANewModel()
        {
            // Arrange
            var connection = new FakeConnection(new RabbitServer());

            // Act
            var result = connection.CreateModel();

            // Assert
            Assert.That(connection.Models,Has.Count.EqualTo(1));
            Assert.That(connection.Models,Is.EquivalentTo(new[]{result}));
        }
        public void Close_TimeoutArguments_ClosesTheConnection()
        {
            // Arrange
            var connection = new FakeConnection(new RabbitServer());

            // Act
            connection.Close(timeout:2);

            // Assert
            Assert.That(connection.IsOpen, Is.False);
            Assert.That(connection.CloseReason, Is.Not.Null);
        }
        public void Can_create_new_connection_lazily_using_given_connection_string()
        {
            using (var connection = new FakeConnection(
                CreateConfiguration(e => e.ConnectionString = "Database=FrodoLives"), new ConnectionStringResolver(null)))
            {
                Assert.Equal(0, connection.CreateCount);

                var dbConnection = connection.DbConnection;

                Assert.Equal(1, connection.CreateCount);
                Assert.Equal("Database=FrodoLives", dbConnection.ConnectionString);
            }
        }
        public void Close_AllArguments_ClosesTheConnection()
        {
            // Arrange
            var connection = new FakeConnection(new RabbitServer());

            // Act
            connection.Close(reasonCode: 3, reasonText: "foo",timeout:4);

            // Assert
            Assert.That(connection.IsOpen, Is.False);
            Assert.That(connection.CloseReason.ReplyCode, Is.EqualTo(3));
            Assert.That(connection.CloseReason.ReplyText, Is.EqualTo("foo"));
        }
        public void WithConnection_WhenSet_SetsTheUnderlyingConnection()
        {
            // Arrange
            var factory = new FakeConnectionFactory();

            var connection = new FakeConnection(new RabbitServer());

            // Act
            factory.WithConnection(connection);

            // Assert
            Assert.That(factory.Connection,Is.SameAs(connection));
        }
        public void CreateModel_MultipleTimes_CreatesManyModels()
        {
            // Arrange
            var connection = new FakeConnection(new RabbitServer());

            // Act
            var result1 = connection.CreateModel();
            var result2 = connection.CreateModel();

            // Assert
            Assert.That(connection.Models, Has.Count.EqualTo(2));
            Assert.That(connection.Models, Is.EquivalentTo(new[] { result1, result2 }));
        }
        public void UnderlyingConnection_WithConnection_ReturnsConnection()
        {
            // Arrange
            var factory = new FakeConnectionFactory();
            var connection = new FakeConnection(new RabbitServer());
            factory.WithConnection(connection);

            // Act
            var result = factory.UnderlyingConnection;

            // Assert
            Assert.That(result, Is.SameAs(connection));
        }
        public void Can_create_new_connection_lazily_using_given_connection_string()
        {
            using (var connection = new FakeConnection(
                CreateOptions(new FakeOptionsExtension1 { ConnectionString = "Database=FrodoLives" })))
            {
                Assert.Equal(0, connection.CreateCount);

                var dbConnection = connection.DbConnection;

                Assert.Equal(1, connection.CreateCount);
                Assert.Equal("Database=FrodoLives", dbConnection.ConnectionString);
            }
        }
        public async void When_Lock_Acquired_GetWithLockReturns_Success()
        {
            var connection = new FakeConnection();

            connection.SetResponse(ResponsePackets.GET_WITH_LOCK_SUCCESS);
            _connectionPool.AddConnection(connection);

            var bucket = GetBucketForKey("key1");
            var result = await bucket.GetWithLockAsync <string>("key1", new TimeSpan(0, 0, 0, 2));

            Console.WriteLine(result.Message);
            Assert.IsTrue(result.Success);
            Assert.AreEqual(ResponseStatus.Success, result.Status);
        }
        public async void When_Key_Found_InsertAsync_Returns_KeyExists()
        {
            var connection = new FakeConnection();

            connection.SetResponse(ResponsePackets.INSERT_KEYEXISTS);
            _connectionPool.AddConnection(connection);

            var key    = "When_Key_Found_InsertAsync_Returns_KeyExists";
            var bucket = GetBucketForKey(key);
            var result = await bucket.InsertAsync(key, "NA");

            Assert.IsFalse(result.Success);
            Assert.AreEqual(ResponseStatus.KeyExists, result.Status);
        }
        public async void Test_AppendAsync()
        {
            var connection = new FakeConnection();

            connection.SetResponse(ResponsePackets.INSERT_SUCCESS);
            _connectionPool.AddConnection(connection);

            var key    = "Test_Append_Async";
            var bucket = GetBucketForKey(key);
            var result = await bucket.AppendAsync(key, "AB");

            Assert.IsTrue(result.Success);
            Assert.AreEqual(ResponseStatus.Success, result.Status);
        }
        public async Task When_Key_Does_Not_Exist_RemoveAsync_Returns_KeyNotFound()
        {
            var connection = new FakeConnection();

            connection.SetResponse(ResponsePackets.REMOVE_KEYNOTFOUND);
            _connectionPool.AddConnection(connection);

            var key    = "When_Key_Does_Not_Exist_RemoveAsync_Returns_KeyNotFound";
            var bucket = GetBucketForKey(key);
            var result = await bucket.RemoveAsync(key);

            Assert.IsFalse(result.Success);
            Assert.AreEqual(ResponseStatus.KeyNotFound, result.Status);
        }
        public async void When_Key_Found_RemoveAsync_Returns_Success()
        {
            var connection = new FakeConnection();

            connection.SetResponse(ResponsePackets.REMOVE_SUCCESS);
            _connectionPool.AddConnection(connection);

            var key    = "When_Key_Found_RemoveAsync_Returns_Success";
            var bucket = GetBucketForKey(key);
            var result = await bucket.RemoveAsync(key);

            Assert.IsTrue(result.Success);
            Assert.AreEqual(ResponseStatus.Success, result.Status);
        }
        public async void When_Key_Does_Not_Exist_InsertAsync_Succeeds()
        {
            var connection = new FakeConnection();

            connection.SetResponse(ResponsePackets.INSERT_SUCCESS);
            _connectionPool.AddConnection(connection);

            var key    = "When_Key_Does_Not_Exist_InsertAsync_Succeeds";
            var bucket = GetBucketForKey(key);
            var result = await bucket.InsertAsync(key, "NA");

            Assert.IsTrue(result.Success);
            Assert.AreEqual(ResponseStatus.Success, result.Status);
        }
        public async Task When_NMV_Found_GetAsync_Will_Retry_Until_Timeout()
        {
            var connection = new FakeConnection();

            connection.SetResponse(ResponsePackets.GET_WITH_NMV);
            _connectionPool.AddConnection(connection);

            var bucket = GetBucketForKey("key1");
            var result = await bucket.GetAsync <int>("key1");

            Console.WriteLine(result.Message);
            Assert.IsFalse(result.Success);
            Assert.AreEqual(ResponseStatus.OperationTimeout, result.Status);
        }
Ejemplo n.º 25
0
        public void Can_create_new_connection_lazily_using_given_connection_string()
        {
            using (var connection = new FakeConnection(
                       CreateOptions(new FakeOptionsExtension1 {
                ConnectionString = "Database=FrodoLives"
            })))
            {
                Assert.Equal(0, connection.CreateCount);

                var dbConnection = connection.DbConnection;

                Assert.Equal(1, connection.CreateCount);
                Assert.Equal("Database=FrodoLives", dbConnection.ConnectionString);
            }
        }
Ejemplo n.º 26
0
                public async Task The_player_should_move_one_block_in_the_given_direction(
                    Direction towards,
                    string axis,
                    int expectedPosition)
                {
                    var connection = new FakeConnection();
                    var player     = new JavaPlayer(connection);
                    await player.SetPositionAsync(new Vector3(0, 0, 0));

                    await player.MoveAsync(towards);

                    var setPosition = connection.LastPosition.ParseCoordinates();

                    (axis == "X" ? setPosition.X : setPosition.Z).Should().Be(expectedPosition,
                                                                              $"moving {towards} means decrementing along the {axis}-axes");
                }
Ejemplo n.º 27
0
        public void Can_create_new_connection_from_exsting_DbConnection()
        {
            var dbConnection = CreateDbConnectionMock("Database=FrodoLives").Object;

            using (var connection = new FakeConnection(
                       CreateOptions(new FakeOptionsExtension1 {
                Connection = dbConnection
            })))
            {
                Assert.Equal(0, connection.CreateCount);

                Assert.Same(dbConnection, connection.DbConnection);

                Assert.Equal(0, connection.CreateCount);
            }
        }
        public void Uses_connection_string_resolver()
        {
            var configuration = new Configuration
            {
                new MemoryConfigurationSource(
                    new Dictionary <string, string>
                {
                    { "Data:Lobsang:ConnectionString", "Database=DatumEarth" }
                })
            };

            using (var connection = new FakeConnection(
                       CreateConfiguration(e => e.ConnectionString = "Lobsang"), new ConnectionStringResolver(configuration)))
            {
                Assert.Equal("Database=DatumEarth", connection.ConnectionString);
            }
        }
Ejemplo n.º 29
0
        public async Task ReconnectRetriesReconnectingIfStartingWebSocketThrows()
        {
            var fakeConnection = new FakeConnection
            {
                LastActiveAt    = DateTime.UtcNow,
                ReconnectWindow = new TimeSpan(0, 0, 15),
                Url             = "http://fakeserver/"
            };

            fakeConnection.Setup("ChangeState",
                                 () =>
            {
                fakeConnection.State = ConnectionState.Reconnecting;
                return(true);
            });

            var fakeWebSocketTransport = new FakeWebSocketTransport
            {
                ReconnectDelay = new TimeSpan(0, 0, 0, 1)
            };

            var openWebSocketInvoked = false;
            var exception            = new Exception();

            fakeWebSocketTransport.Setup <Task>("OpenWebSocket", () =>
            {
                if (!openWebSocketInvoked)
                {
                    openWebSocketInvoked = true;
                    throw exception;
                }

                var tcs = new TaskCompletionSource <object>();
                tcs.TrySetResult(null);
                return(tcs.Task);
            });

            await fakeWebSocketTransport.Reconnect(fakeConnection, null);

            Assert.Equal(2, fakeWebSocketTransport.GetInvocations("OpenWebSocket").Count());
            var onErrorInvocations = fakeConnection.GetInvocations("OnError").ToArray();

            Assert.Equal(1, onErrorInvocations.Length);
            Assert.Same(exception, onErrorInvocations[0][0]);
            Assert.Equal(1, fakeConnection.GetInvocations("OnReconnected").Count());
        }
Ejemplo n.º 30
0
        public async Task InCaseOfExceptionStartInvokesOnFailureAndThrowsOriginalException()
        {
            var fakeConnection = new FakeConnection { TotalTransportConnectTimeout = new TimeSpan(0, 0, 10)};
            var fakeWebSocketTransport = new FakeWebSocketTransport();  

            var expectedException = new Exception("OpenWebSocket failed.");
            fakeWebSocketTransport.Setup<Task>("OpenWebSocket", () =>
            {
                throw expectedException;
            });

            Assert.Same(expectedException,
                await Assert.ThrowsAsync<Exception>(
                    async () => await fakeWebSocketTransport.Start(fakeConnection, null, CancellationToken.None)));

            Assert.Equal(1, fakeWebSocketTransport.GetInvocations("OnStartFailed").Count());
        }
Ejemplo n.º 31
0
        public void SpecificCommand()
        {
            var connection  = new FakeConnection();
            var cmdToReturn = new FakeCommand(new ScalarCommandResult("SELECT count(*) FROM users", null)
            {
                Result = 201
            });

            connection.Setup(cmdToReturn);

            var cmd = connection.CreateCommand();

            cmd.CommandText = "SELECT count(*) FROM users";
            var result = cmd.ExecuteScalar();

            Assert.Equal(201, result);
        }
Ejemplo n.º 32
0
        public void Existing_connection_can_start_in_opened_state()
        {
            var connectionMock = CreateDbConnectionMock("Database=FrodoLives");

            connectionMock.Setup(m => m.State).Returns(ConnectionState.Open);

            using (var connection = new FakeConnection(
                       CreateOptions(new FakeOptionsExtension1 {
                Connection = connectionMock.Object
            })))
            {
                Assert.Equal(0, connection.CreateCount);

                connection.Open();

                Assert.Equal(0, connection.CreateCount);

                connectionMock.Verify(m => m.Open(), Times.Never);

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

                connectionMock.Verify(m => m.Open(), Times.Never);

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

                connectionMock.Verify(m => m.Open(), Times.Never);
                connectionMock.Verify(m => m.Close(), Times.Never);

                connection.Close();

                connectionMock.Verify(m => m.Open(), Times.Never);
                connectionMock.Verify(m => m.Close(), Times.Never);

                connection.Open();

                connectionMock.Verify(m => m.Open(), Times.Never);

                connection.Close();

                connectionMock.Verify(m => m.Open(), Times.Never);
                connectionMock.Verify(m => m.Close(), Times.Never);
            }
        }
Ejemplo n.º 33
0
        public void Existing_connection_is_opened_and_closed_when_necessary()
        {
            var connectionMock = CreateDbConnectionMock("Database=FrodoLives");

            connectionMock.Setup(m => m.State).Returns(ConnectionState.Closed);

            using (var connection = new FakeConnection(
                       CreateOptions(new FakeOptionsExtension1 {
                Connection = connectionMock.Object
            })))
            {
                Assert.Equal(0, connection.CreateCount);

                connection.Open();

                Assert.Equal(0, connection.CreateCount);

                connectionMock.Verify(m => m.Open(), Times.Once);

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

                connectionMock.Verify(m => m.Open(), Times.Once);

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

                connectionMock.Verify(m => m.Open(), Times.Once);
                connectionMock.Verify(m => m.Close(), Times.Never);

                connection.Close();

                connectionMock.Verify(m => m.Open(), Times.Once);
                connectionMock.Verify(m => m.Close(), Times.Once);

                connection.Open();

                connectionMock.Verify(m => m.Open(), Times.Exactly(2));

                connection.Close();

                connectionMock.Verify(m => m.Open(), Times.Exactly(2));
                connectionMock.Verify(m => m.Close(), Times.Exactly(2));
            }
        }
        public void ToList_should_fill_the_list()
        {
            var connection = new FakeConnection()
            {
                CurrentState = ConnectionState.Open
            };
            var table  = new FakeTable(new String[] { "Id" }, new object[][] { new object[] { 1 }, });
            var result = new CommandResult[] { new ReaderCommandResult {
                                                   Result = new FakeDataReader(table)
                                               } };
            var cmd = new FakeCommand(connection, result);

            cmd.CommandText = "Hello";

            var actual = cmd.ToList <Tentity>(new TentityMapper());

            actual[0].Id.Should().Be("1");
        }
        public CommandResult EmulateUsingLog()
        {
            OpenFileDialog dlg = new OpenFileDialog();

            dlg.Title       = "Emulation Using Log";
            dlg.Multiselect = false;
            if (GCUtil.ShowModalDialog(_frame, dlg) == DialogResult.OK)
            {
                //エミュレートによるテスト
                FakeConnection fc = new FakeConnection(TCPTerminalParam.Fake);
                //!!new ConnectionTag()はpublicにしたくない
                AddNewTerminal(new ConnectionTag(fc));
                TestUtil.EmulateWithLog(dlg.FileName, GEnv.Connections.FindTag(fc));
                return(CommandResult.Success);
            }

            return(CommandResult.Cancelled);
        }
        public void AutomaticResult()
        {
            var table = new FakeTable(new[]
                {
                    new object[] {1, "jonas"},
                    new object[] {2, "arne"},
                });
            var connection = new FakeConnection();
            connection.Setup(new FakeCommand(table));

            var cmd = connection.CreateCommand();
            cmd.CommandText = "SELECT Id, UserName FROM users";
            var result = cmd.ExecuteReader();
            
            Assert.True(result.Read());
            Assert.Equal(1, (int)result[0]);
            Assert.Equal("jonas", result[1]);
        }
Ejemplo n.º 37
0
        public async Task Lazy_connection_is_async_opened_and_closed_when_necessary()
        {
            using (var connection = new FakeConnection(
                       CreateOptions(new FakeOptionsExtension1 {
                ConnectionString = "Database=FrodoLives"
            })))
            {
                Assert.Equal(0, connection.CreateCount);

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

                Assert.Equal(1, connection.CreateCount);

                var connectionMock = Mock.Get(connection.DbConnection);
                connectionMock.Verify(m => m.OpenAsync(cancellationToken), Times.Once);

                await connection.OpenAsync(cancellationToken);

                await connection.OpenAsync(cancellationToken);

                connectionMock.Verify(m => m.OpenAsync(It.IsAny <CancellationToken>()), Times.Once);

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

                connectionMock.Verify(m => m.OpenAsync(It.IsAny <CancellationToken>()), Times.Once);
                connectionMock.Verify(m => m.Close(), Times.Never);

                connection.Close();

                connectionMock.Verify(m => m.OpenAsync(It.IsAny <CancellationToken>()), Times.Once);
                connectionMock.Verify(m => m.Close(), Times.Once);

                await connection.OpenAsync(cancellationToken);

                connectionMock.Verify(m => m.OpenAsync(cancellationToken), Times.Exactly(2));

                connection.Close();

                connectionMock.Verify(m => m.OpenAsync(cancellationToken), Times.Exactly(2));
                connectionMock.Verify(m => m.Close(), Times.Exactly(2));
            }
        }
        public void Existing_connection_can_start_in_opened_state()
        {
            var connectionMock = CreateDbConnectionMock("Database=FrodoLives");

            connectionMock.Setup(m => m.State).Returns(ConnectionState.Open);

            using (var connection = new FakeConnection(
                       CreateConfiguration(e => e.Connection = connectionMock.Object), new ConnectionStringResolver(null)))
            {
                Assert.Equal(0, connection.CreateCount);

                connection.Open();

                Assert.Equal(0, connection.CreateCount);

                connectionMock.Verify(m => m.Open(), Times.Never);

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

                connectionMock.Verify(m => m.Open(), Times.Never);

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

                connectionMock.Verify(m => m.Open(), Times.Never);
                connectionMock.Verify(m => m.Close(), Times.Never);

                connection.Close();

                connectionMock.Verify(m => m.Open(), Times.Never);
                connectionMock.Verify(m => m.Close(), Times.Never);

                connection.Open();

                connectionMock.Verify(m => m.Open(), Times.Never);

                connection.Close();

                connectionMock.Verify(m => m.Open(), Times.Never);
                connectionMock.Verify(m => m.Close(), Times.Never);
            }
        }
        public void Lazy_connection_is_opened_and_closed_when_necessary()
        {
            using (var connection = new FakeConnection(
                       CreateConfiguration(
                           e => e.ConnectionString = "Database=FrodoLives"),
                       new ConnectionStringResolver(null)))
            {
                Assert.Equal(0, connection.CreateCount);

                connection.Open();

                Assert.Equal(1, connection.CreateCount);

                var connectionMock = Mock.Get(connection.DbConnection);
                connectionMock.Verify(m => m.Open(), Times.Once);

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

                connectionMock.Verify(m => m.Open(), Times.Once);

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

                connectionMock.Verify(m => m.Open(), Times.Once);
                connectionMock.Verify(m => m.Close(), Times.Never);

                connection.Close();

                connectionMock.Verify(m => m.Open(), Times.Once);
                connectionMock.Verify(m => m.Close(), Times.Once);

                connection.Open();

                connectionMock.Verify(m => m.Open(), Times.Exactly(2));

                connection.Close();

                connectionMock.Verify(m => m.Open(), Times.Exactly(2));
                connectionMock.Verify(m => m.Close(), Times.Exactly(2));
            }
        }
        public async Task Lazy_connection_is_async_opened_and_closed_when_necessary()
        {
            using (var connection = new FakeConnection(
                CreateConfiguration(e => e.ConnectionString = "Database=FrodoLives"), new ConnectionStringResolver(null)))

            {
                Assert.Equal(0, connection.CreateCount);

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

                Assert.Equal(1, connection.CreateCount);

                var connectionMock = Mock.Get(connection.DbConnection);
                connectionMock.Verify(m => m.OpenAsync(cancellationToken), Times.Once);

                await connection.OpenAsync(cancellationToken);
                await connection.OpenAsync(cancellationToken);

                connectionMock.Verify(m => m.OpenAsync(It.IsAny<CancellationToken>()), Times.Once);

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

                connectionMock.Verify(m => m.OpenAsync(It.IsAny<CancellationToken>()), Times.Once);
                connectionMock.Verify(m => m.Close(), Times.Never);

                connection.Close();

                connectionMock.Verify(m => m.OpenAsync(It.IsAny<CancellationToken>()), Times.Once);
                connectionMock.Verify(m => m.Close(), Times.Once);

                await connection.OpenAsync(cancellationToken);

                connectionMock.Verify(m => m.OpenAsync(cancellationToken), Times.Exactly(2));

                connection.Close();

                connectionMock.Verify(m => m.OpenAsync(cancellationToken), Times.Exactly(2));
                connectionMock.Verify(m => m.Close(), Times.Exactly(2));
            }
        }
        public void Lazy_connection_is_opened_and_closed_when_necessary()
        {
            using (var connection = new FakeConnection(
                CreateConfiguration(
                    e => e.ConnectionString = "Database=FrodoLives"),
                new ConnectionStringResolver(null)))
            {
                Assert.Equal(0, connection.CreateCount);

                connection.Open();

                Assert.Equal(1, connection.CreateCount);

                var connectionMock = Mock.Get(connection.DbConnection);
                connectionMock.Verify(m => m.Open(), Times.Once);

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

                connectionMock.Verify(m => m.Open(), Times.Once);

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

                connectionMock.Verify(m => m.Open(), Times.Once);
                connectionMock.Verify(m => m.Close(), Times.Never);

                connection.Close();

                connectionMock.Verify(m => m.Open(), Times.Once);
                connectionMock.Verify(m => m.Close(), Times.Once);

                connection.Open();

                connectionMock.Verify(m => m.Open(), Times.Exactly(2));

                connection.Close();

                connectionMock.Verify(m => m.Open(), Times.Exactly(2));
                connectionMock.Verify(m => m.Close(), Times.Exactly(2));
            }
        }
Ejemplo n.º 42
0
        public void Lazy_connection_is_opened_and_closed_when_necessary()
        {
            using (var connection = new FakeConnection(
                       CreateOptions(new FakeOptionsExtension1 {
                ConnectionString = "Database=FrodoLives"
            })))
            {
                Assert.Equal(0, connection.CreateCount);

                connection.Open();

                Assert.Equal(1, connection.CreateCount);

                var connectionMock = Mock.Get(connection.DbConnection);
                connectionMock.Verify(m => m.Open(), Times.Once);

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

                connectionMock.Verify(m => m.Open(), Times.Once);

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

                connectionMock.Verify(m => m.Open(), Times.Once);
                connectionMock.Verify(m => m.Close(), Times.Never);

                connection.Close();

                connectionMock.Verify(m => m.Open(), Times.Once);
                connectionMock.Verify(m => m.Close(), Times.Once);

                connection.Open();

                connectionMock.Verify(m => m.Open(), Times.Exactly(2));

                connection.Close();

                connectionMock.Verify(m => m.Open(), Times.Exactly(2));
                connectionMock.Verify(m => m.Close(), Times.Exactly(2));
            }
        }
Ejemplo n.º 43
0
        public async Task ReconnectDoesNotStartNewWebSocketIfDisconnectTokenTripped()
        {
            var fakeConnection = new FakeConnection
            {
                LastActiveAt    = DateTime.UtcNow,
                ReconnectWindow = new TimeSpan(0, 0, 15),
                Url             = "http://fakeserver/",
                State           = ConnectionState.Reconnecting
            };

            var fakeWebSocketTransport = new FakeWebSocketTransport();

            // this is called just to initialize the disconnect token
            var _ = fakeWebSocketTransport.Start(new FakeConnection(), string.Empty, new CancellationToken(true));

            await fakeWebSocketTransport.Reconnect(fakeConnection, null);

            Assert.Equal(0, fakeWebSocketTransport.GetInvocations("OpenWebSocket").Count());
            Assert.Equal(0, fakeConnection.GetInvocations("Stop").Count());
        }
Ejemplo n.º 44
0
        public async Task InCaseOfExceptionStartInvokesOnFailureAndThrowsOriginalException()
        {
            var fakeConnection = new FakeConnection {
                TotalTransportConnectTimeout = new TimeSpan(0, 0, 10)
            };
            var fakeWebSocketTransport = new FakeWebSocketTransport();

            var expectedException = new Exception("OpenWebSocket failed.");

            fakeWebSocketTransport.Setup <Task>("OpenWebSocket", () =>
            {
                throw expectedException;
            });

            Assert.Same(expectedException,
                        await Assert.ThrowsAsync <Exception>(
                            async() => await fakeWebSocketTransport.Start(fakeConnection, null, CancellationToken.None)));

            Assert.Equal(1, fakeWebSocketTransport.GetInvocations("OnStartFailed").Count());
        }
Ejemplo n.º 45
0
        public void AutomaticResult()
        {
            var table = new FakeTable(new[]
            {
                new object[] { 1, "jonas" },
                new object[] { 2, "arne" },
            });
            var connection = new FakeConnection();

            connection.Setup(new FakeCommand(table));

            var cmd = connection.CreateCommand();

            cmd.CommandText = "SELECT Id, UserName FROM users";
            var result = cmd.ExecuteReader();

            Assert.True(result.Read());
            Assert.Equal(1, (int)result[0]);
            Assert.Equal("jonas", result[1]);
        }
Ejemplo n.º 46
0
        public async Task StartInvokesOnFailureAndThrowsIfOpenWebSocketCancelled()
        {
            var fakeConnection = new FakeConnection {
                TotalTransportConnectTimeout = new TimeSpan(0, 0, 10)
            };
            var fakeWebSocketTransport = new FakeWebSocketTransport();

            fakeWebSocketTransport.Setup <Task>("OpenWebSocket", () =>
            {
                var tcs = new TaskCompletionSource <object>();
                tcs.SetCanceled();
                return(tcs.Task);
            });

            Assert.Equal(
                ResourceUtil.GetResource("Error_TransportFailedToConnect"),
                (await Assert.ThrowsAsync <InvalidOperationException>(
                     async() => await fakeWebSocketTransport.Start(fakeConnection, null, CancellationToken.None))).Message);

            Assert.Equal(1, fakeWebSocketTransport.GetInvocations("OnStartFailed").Count());
        }
Ejemplo n.º 47
0
        static void Main(string[] args)
        {
            var connection = new FakeConnection(new Uri("http://localhost:9200"));

            IEnumerable <int> r = new[] { 1, 2, 3 };
            int v = 2;

            var context = new ElasticContext(connection);

            var queryable = context
                            .Query <tata>("toto", "tata")
                            .Query(x => x
                                   .Where(y => y.Int == 2)
                                   .Query(y => y
                                          .Where(z => z.String == "tutu")
                                          )
                                   )
                            .Where(y => true && y.Int == 2 || false)
                            .Where(y => y.Int == 2)
                            .Where(z => z.String == "tutu")
                            .Where(z => z.Array.Contains(1) || r.Contains(z.Int))
                            //.Where(z => z.Array.ContainsAll(r))
                            .Where(z => z.Array.ContainsAll(1, 2, 3))
                            .OrderBy(x => x.Int)
                            .Where(x => x.Int > 4 && x.Int > 3)
                            .Where(x => x.Int.Exists())
                            .Where(x => x.String.Missing())
                            .Where(x => x.Tutu.Double.Equals(42))
                            .Where(x => x.Tutu.Double > 2 + Settings.A + 4)
                            .Where(x => (x.Int < 2 || x.String == "tutu") == false)
                            .Where(x => x.Int.Exists() == true)
                            //.Where(x => bbb() == bbb())
                            //.Where(x => !bbb())
                            //.Where(x => true)
                            .Where(x => x.Int.Missing() == false)
                            .Where(x => !!!x.String.Missing())
                            .Skip(0)
                            .Take(10)
                            .ToList();
        }
        public void Lazy_connection_is_opened_and_closed_when_necessary()
        {
            using (var connection = new FakeConnection(
                CreateOptions(new FakeOptionsExtension1 { ConnectionString = "Database=FrodoLives" })))
            {
                Assert.Equal(0, connection.CreateCount);

                connection.Open();

                Assert.Equal(1, connection.CreateCount);

                var connectionMock = Mock.Get(connection.DbConnection);
                connectionMock.Verify(m => m.Open(), Times.Once);

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

                connectionMock.Verify(m => m.Open(), Times.Once);

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

                connectionMock.Verify(m => m.Open(), Times.Once);
                connectionMock.Verify(m => m.Close(), Times.Never);

                connection.Close();

                connectionMock.Verify(m => m.Open(), Times.Once);
                connectionMock.Verify(m => m.Close(), Times.Once);

                connection.Open();

                connectionMock.Verify(m => m.Open(), Times.Exactly(2));

                connection.Close();

                connectionMock.Verify(m => m.Open(), Times.Exactly(2));
                connectionMock.Verify(m => m.Close(), Times.Exactly(2));
            }
        }
Ejemplo n.º 49
0
        public async Task ReconnectDoesNotStartNewWebSocketIfClientWasNotInConnectState()
        {
            var fakeConnection = new FakeConnection
            {
                LastActiveAt    = DateTime.UtcNow,
                ReconnectWindow = new TimeSpan(0, 0, 15),
                Url             = "http://fakeserver/"
            };

            fakeConnection.Setup("ChangeState",
                                 () =>
            {
                fakeConnection.State = ConnectionState.Disconnected;
                return(false);
            });

            var fakeWebSocketTransport = new FakeWebSocketTransport();

            await fakeWebSocketTransport.Reconnect(fakeConnection, null);

            Assert.Equal(0, fakeWebSocketTransport.GetInvocations("OpenWebSocket").Count());
            Assert.Equal(0, fakeConnection.GetInvocations("Stop").Count());
        }
        public void ToEnumerable_without_arguments_generates_an_enumerable_without_connection_ownership()
        {
            var provider = Substitute.For <IMappingProvider>();

            provider.Get <Tentity>().Returns(new TentityMapper());
            EntityMappingProvider.Provider = provider;
            var connection = new FakeConnection()
            {
                CurrentState = ConnectionState.Open
            };
            var cmd = new FakeCommand(connection, new CommandResult[] { new ReaderCommandResult()
                                                                        {
                                                                            Result = new FakeDataReader(new DataTable())
                                                                        }, });

            cmd.CommandText = "Hello";

            var actual = cmd.ToEnumerable <Tentity>();

            actual.GetEnumerator().Dispose();

            connection.State.Should().Be(ConnectionState.Open);
        }
Ejemplo n.º 51
0
 public DbCommandTests()
 {
     _fakeConnection = new FakeConnection();
     _db             = new Db(_fakeConnection, DbConfig.Default);
 }
Ejemplo n.º 52
0
 public QueryTypedObjectTests()
 {
     Connection = new FakeConnection();
     Connection.Open();
 }
        public async Task When_NMV_Found_GetAsync_Will_Retry_Until_Timeout()
        {
            var connection = new FakeConnection();
            connection.SetResponse(ResponsePackets.GET_WITH_NMV);
            _connectionPool.AddConnection(connection);

            var bucket = GetBucketForKey("key1");
            var result = await bucket.GetAsync<int>("key1");

            Console.WriteLine(result.Message);
            Assert.IsFalse(result.Success);
            Assert.AreEqual(ResponseStatus.OperationTimeout, result.Status);
        }
        public async Task When_Key_Does_Not_Exist_ReplaceAsync_Returns_KeyNotFound()
        {
            var connection = new FakeConnection();
            connection.SetResponse(ResponsePackets.REPLACE_KEYNOTFOUND);
            _connectionPool.AddConnection(connection);

            var key = "When_Key_Does_Not_Exist_ReplaceAsync_Returns_KeyNotFound";
            var bucket = GetBucketForKey(key);
            var result = await bucket.ReplaceAsync(key, "NA");

            Assert.IsFalse(result.Success);
            Assert.AreEqual(ResponseStatus.KeyNotFound, result.Status);
        }
        public async Task When_Key_Found_ReplaceAsync_Returns_Success()
        {
            var connection = new FakeConnection();
            connection.SetResponse(ResponsePackets.REPLACE_SUCCESS);
            _connectionPool.AddConnection(connection);

            var key = "When_Key_Found_ReplaceAsync_Returns_Success";
            var bucket = GetBucketForKey(key);
            var result = await bucket.ReplaceAsync(key, "NA");

            Assert.IsTrue(result.Success);
        }
        public async Task When_Key_Found_InsertAsync_Returns_KeyExists()
        {
            var connection = new FakeConnection();
            connection.SetResponse(ResponsePackets.INSERT_KEYEXISTS);
            _connectionPool.AddConnection(connection);

            var key = "When_Key_Found_InsertAsync_Returns_KeyExists";
            var bucket = GetBucketForKey(key);
            var result = await bucket.InsertAsync(key, "NA");

            Assert.IsFalse(result.Success);
            Assert.AreEqual(ResponseStatus.KeyExists, result.Status);
        }
        public async Task When_Key_Does_Not_Exist_InsertAsync_Succeeds()
        {
            var connection = new FakeConnection();
            connection.SetResponse(ResponsePackets.INSERT_SUCCESS);
            _connectionPool.AddConnection(connection);

            var key = "When_Key_Does_Not_Exist_InsertAsync_Succeeds";
            var bucket = GetBucketForKey(key);
            var result = await bucket.InsertAsync(key, "NA");

            Assert.IsTrue(result.Success);
            Assert.AreEqual(ResponseStatus.Success, result.Status);
        }
        public async Task When_Key_Found_ExistAsync_Returns_True()
        {
            var connection = new FakeConnection();
            connection.SetResponse(ResponsePackets.OBSERVE_KEY_DNE);
            _connectionPool.AddConnection(connection);

            var key = "When_Key_Found_ExistAsync_Returns_True";
            var bucket = GetBucketForKey(key);
            var result = await bucket.ExistsAsync(key);

            Assert.IsTrue(result);
        }
        public async Task Test_AppendAsync()
        {
            var connection = new FakeConnection();
            connection.SetResponse(ResponsePackets.INSERT_SUCCESS);
            _connectionPool.AddConnection(connection);

            var key = "Test_Append_Async";
            var bucket = GetBucketForKey(key);
            var result = await bucket.AppendAsync(key, "AB");

            Assert.IsTrue(result.Success);
            Assert.AreEqual(ResponseStatus.Success, result.Status);
        }
        public async Task When_Add_Fails_InsertAsync_Returns_KEY_EXISTS()
        {
            var connection = new FakeConnection();
            connection.SetResponse(ResponsePackets.Add_FAILED_KEY_EXISTS);
            _connectionPool.AddConnection(connection);

            var bucket = GetBucketForKey("key1");
            var result = await bucket.InsertAsync("key1", "NA");

            Assert.IsFalse(result.Success);
            Assert.AreEqual(ResponseStatus.KeyExists, result.Status);
        }