Beispiel #1
0
        public void GlobalSetup()
        {
            var writer = MemoryBufferWriter.Get();

            try
            {
                HandshakeProtocol.WriteResponseMessage(HandshakeResponseMessage.Empty, writer);
                _handshakeResponseResult = new ReadResult(new ReadOnlySequence <byte>(writer.ToArray()), false, false);
            }
            finally
            {
                MemoryBufferWriter.Return(writer);
            }

            _pipe = new TestDuplexPipe();

            var hubConnectionBuilder      = new HubConnectionBuilder();
            var delegateConnectionFactory = new DelegateConnectionFactory(endPoint =>
            {
                var connection = new DefaultConnectionContext();
                // prevents keep alive time being activated
                connection.Features.Set <IConnectionInherentKeepAliveFeature>(new TestConnectionInherentKeepAliveFeature());
                connection.Transport = _pipe;
                return(new ValueTask <ConnectionContext>(connection));
            });

            hubConnectionBuilder.Services.AddSingleton <IConnectionFactory>(delegateConnectionFactory);

            _hubConnection = hubConnectionBuilder.Build();
        }
Beispiel #2
0
        public RunGroupOrderScenarios()
        {
            upgradeResult = null;
            scripts       = new List <SqlScript>
            {
                new SqlScript("ZZZScript1.sql", "create table Foo (Id int identity)", new SqlScriptOptions {
                    ScriptType = ScriptType.RunOnce, RunGroupOrder = DbUpDefaults.DefaultRunGroupOrder
                }),
                new SqlScript("ZZZScript2.sql", "alter table Foo add column Name varchar(255)", new SqlScriptOptions {
                    ScriptType = ScriptType.RunOnce, RunGroupOrder = DbUpDefaults.DefaultRunGroupOrder
                }),
                new SqlScript("AAAScript3.sql", "insert into Foo (Name) values ('test')", new SqlScriptOptions {
                    ScriptType = ScriptType.RunOnce, RunGroupOrder = DbUpDefaults.DefaultRunGroupOrder + 1
                })
            };

            logger = new CaptureLogsLogger();
            recordingConnection   = new RecordingDbConnection(logger, "SchemaVersions");
            testConnectionFactory = new DelegateConnectionFactory(_ => recordingConnection);

            upgradeEngineBuilder = DeployChanges.To
                                   .SqlDatabase("testconn")
                                   .WithScripts(new TestScriptProvider(scripts))
                                   .OverrideConnectionFactory(testConnectionFactory)
                                   .LogTo(logger);
        }
Beispiel #3
0
        public void GlobalSetup()
        {
            var arguments = new object[ArgumentCount];

            for (var i = 0; i < arguments.Length; i++)
            {
                arguments[i] = "Hello world!";
            }

            var writer = MemoryBufferWriter.Get();

            try
            {
                HandshakeProtocol.WriteResponseMessage(HandshakeResponseMessage.Empty, writer);
                var handshakeResponseResult = new ReadResult(new ReadOnlySequence <byte>(writer.ToArray()), false, false);

                _pipe = new TestDuplexPipe();
                _pipe.AddReadResult(new ValueTask <ReadResult>(handshakeResponseResult));
            }
            finally
            {
                MemoryBufferWriter.Return(writer);
            }

            _nextReadTcs = new TaskCompletionSource <ReadResult>();
            _pipe.AddReadResult(new ValueTask <ReadResult>(_nextReadTcs.Task));

            IHubProtocol hubProtocol;

            var hubConnectionBuilder = new HubConnectionBuilder();

            if (Protocol == "json")
            {
                hubProtocol = new NewtonsoftJsonHubProtocol();
            }
            else
            {
                hubProtocol = new MessagePackHubProtocol();
            }

            hubConnectionBuilder.Services.TryAddEnumerable(ServiceDescriptor.Singleton(typeof(IHubProtocol), hubProtocol));
            hubConnectionBuilder.WithUrl("http://doesntmatter");

            _invocationMessageBytes = hubProtocol.GetMessageBytes(new InvocationMessage(MethodName, arguments));

            var delegateConnectionFactory = new DelegateConnectionFactory(endPoint =>
            {
                var connection = new DefaultConnectionContext();
                // prevents keep alive time being activated
                connection.Features.Set <IConnectionInherentKeepAliveFeature>(new TestConnectionInherentKeepAliveFeature());
                connection.Transport = _pipe;
                return(new ValueTask <ConnectionContext>(connection));
            });

            hubConnectionBuilder.Services.AddSingleton <IConnectionFactory>(delegateConnectionFactory);

            _hubConnection = hubConnectionBuilder.Build();
            _hubConnection.On(MethodName, arguments.Select(v => v.GetType()).ToArray(), OnInvoke);
            _hubConnection.StartAsync().GetAwaiter().GetResult();
        }
            public async Task StartingAfterStopCreatesANewConnection()
            {
                // Set up StartAsync to wait on the syncPoint when starting
                var createCount = 0;

                ValueTask <ConnectionContext> ConnectionFactory(EndPoint endPoint)
                {
                    createCount += 1;
                    return(new TestConnection().StartAsync());
                }

                var builder = new HubConnectionBuilder().WithUrl("http://example.com");
                var delegateConnectionFactory = new DelegateConnectionFactory(ConnectionFactory);

                builder.Services.AddSingleton <IConnectionFactory>(delegateConnectionFactory);

                await AsyncUsing(builder.Build(), async connection =>
                {
                    Assert.Equal(HubConnectionState.Disconnected, connection.State);

                    await connection.StartAsync().DefaultTimeout();
                    Assert.Equal(1, createCount);
                    Assert.Equal(HubConnectionState.Connected, connection.State);

                    await connection.StopAsync().DefaultTimeout();
                    Assert.Equal(HubConnectionState.Disconnected, connection.State);

                    await connection.StartAsync().DefaultTimeout();
                    Assert.Equal(2, createCount);
                    Assert.Equal(HubConnectionState.Connected, connection.State);
                });
            }
Beispiel #5
0
            public async Task HubConnectionClosesWithErrorIfTerminatedWithPartialMessage()
            {
                var builder         = new HubConnectionBuilder();
                var innerConnection = new TestConnection();

                var delegateConnectionFactory = new DelegateConnectionFactory(
                    format => innerConnection.StartAsync(format),
                    connection => ((TestConnection)connection).DisposeAsync());

                builder.Services.AddSingleton <IConnectionFactory>(delegateConnectionFactory);

                var hubConnection  = builder.Build();
                var closedEventTcs = new TaskCompletionSource <Exception>();

                hubConnection.Closed += e =>
                {
                    closedEventTcs.SetResult(e);
                    return(Task.CompletedTask);
                };

                await hubConnection.StartAsync().OrTimeout();

                await innerConnection.Application.Output.WriteAsync(Encoding.UTF8.GetBytes(new[] { '{' })).OrTimeout();

                innerConnection.Application.Output.Complete();

                var exception = await closedEventTcs.Task.OrTimeout();

                Assert.Equal("Connection terminated while reading a message.", exception.Message);
            }
        public UpgradeDatabaseScenarios()
        {
            upgradeResult = null;
            scripts       = new List <SqlScript>
            {
                new SqlScript("Script1.sql", "create table Foo (Id int identity)"),
                new SqlScript("Script2.sql", "alter table Foo add column Name varchar(255)"),
                new SqlScript("Script3.sql", "insert into Foo (Name) values ('test')")
            };

            executedScripts = new List <ExecutedSqlScript>
            {
                new ExecutedSqlScript {
                    Name = "Script1.sql", Hash = "a"
                },
                new ExecutedSqlScript {
                    Name = "Script2.sql", Hash = "b"
                },
                new ExecutedSqlScript {
                    Name = "Script3.sql", Hash = "c"
                }
            };

            logger = new CaptureLogsLogger();
            recordingConnection   = new RecordingDbConnection(logger, "SchemaVersions");
            testConnectionFactory = new DelegateConnectionFactory(_ => recordingConnection);

            upgradeEngineBuilder = DeployChanges.To
                                   .SqlDatabase("testconn")
                                   .WithScripts(new TestScriptProvider(scripts))
                                   .OverrideConnectionFactory(testConnectionFactory)
                                   .LogTo(logger);
        }
Beispiel #7
0
        private static HubConnection CreateHubConnection(TestConnection connection, IHubProtocol protocol = null, ILoggerFactory loggerFactory = null, IRetryPolicy reconnectPolicy = null)
        {
            var builder = new HubConnectionBuilder();

            var delegateConnectionFactory = new DelegateConnectionFactory(
                connection.StartAsync,
                c => ((TestConnection)c).DisposeAsync());

            builder.Services.AddSingleton <IConnectionFactory>(delegateConnectionFactory);

            if (loggerFactory != null)
            {
                builder.WithLoggerFactory(loggerFactory);
            }

            if (protocol != null)
            {
                builder.Services.AddSingleton(protocol);
            }

            if (reconnectPolicy != null)
            {
                builder.WithAutomaticReconnect(reconnectPolicy);
            }

            return(builder.Build());
        }
        public async Task ClosedEventRaisedWhenTheClientIsStopped()
        {
            var builder = new HubConnectionBuilder();

            var delegateConnectionFactory = new DelegateConnectionFactory(
                format => new TestConnection().StartAsync(format),
                connection => ((TestConnection)connection).DisposeAsync());

            builder.Services.AddSingleton <IConnectionFactory>(delegateConnectionFactory);

            var hubConnection  = builder.Build();
            var closedEventTcs = new TaskCompletionSource <Exception>();

            hubConnection.Closed += e =>
            {
                closedEventTcs.SetResult(e);
                return(Task.CompletedTask);
            };

            await hubConnection.StartAsync().OrTimeout();

            await hubConnection.StopAsync().OrTimeout();

            Assert.Null(await closedEventTcs.Task);
        }
Beispiel #9
0
        public void GlobalSetup()
        {
            var writer = MemoryBufferWriter.Get();

            try
            {
                HandshakeProtocol.WriteResponseMessage(HandshakeResponseMessage.Empty, writer);
                var handshakeResponseResult = new ReadResult(new ReadOnlySequence <byte>(writer.ToArray()), false, false);

                _pipe = new TestDuplexPipe();
                _pipe.AddReadResult(new ValueTask <ReadResult>(handshakeResponseResult));
            }
            finally
            {
                MemoryBufferWriter.Return(writer);
            }

            _tcs = new TaskCompletionSource <ReadResult>();
            _pipe.AddReadResult(new ValueTask <ReadResult>(_tcs.Task));

            var hubConnectionBuilder = new HubConnectionBuilder();

            if (Protocol == "json")
            {
                // JSON protocol added by default
            }
            else
            {
                hubConnectionBuilder.AddMessagePackProtocol();
            }

            var delegateConnectionFactory = new DelegateConnectionFactory(format =>
            {
                var connection = new DefaultConnectionContext();
                // prevents keep alive time being activated
                connection.Features.Set <IConnectionInherentKeepAliveFeature>(new TestConnectionInherentKeepAliveFeature());
                connection.Transport = _pipe;
                return(Task.FromResult <ConnectionContext>(connection));
            },
                                                                          connection =>
            {
                connection.Transport.Output.Complete();
                connection.Transport.Input.Complete();
                return(Task.CompletedTask);
            });

            hubConnectionBuilder.Services.AddSingleton <IConnectionFactory>(delegateConnectionFactory);

            _hubConnection = hubConnectionBuilder.Build();
            _hubConnection.StartAsync().GetAwaiter().GetResult();

            _arguments = new object[ArgumentCount];
            for (var i = 0; i < _arguments.Length; i++)
            {
                _arguments[i] = "Hello world!";
            }
        }
Beispiel #10
0
            private HubConnection CreateHubConnection(Func <TransferFormat, Task <ConnectionContext> > connectDelegate, Func <ConnectionContext, Task> disposeDelegate)
            {
                var builder = new HubConnectionBuilder();

                var delegateConnectionFactory = new DelegateConnectionFactory(connectDelegate, disposeDelegate);

                builder.Services.AddSingleton <IConnectionFactory>(delegateConnectionFactory);

                return(builder.Build());
            }
Beispiel #11
0
            private HubConnection CreateHubConnection(TestConnection testConnection)
            {
                var builder = new HubConnectionBuilder();

                var delegateConnectionFactory = new DelegateConnectionFactory(
                    testConnection.StartAsync,
                    connection => ((TestConnection)connection).DisposeAsync());

                builder.Services.AddSingleton <IConnectionFactory>(delegateConnectionFactory);

                return(builder.Build());
            }
        public ConfigurationHelperTests()
        {
            scripts = new List <SqlScript>
            {
                new SqlScript("Script1.sql", "create table Foo (Id int identity)")
                //new SqlScript("Script2.sql", "alter table Foo add column Name varchar(255)"),
                //new SqlScript("Script3.sql", "insert into Foo (Name) values ('test')")
            };

            logger = new CaptureLogsLogger();
            recordingConnection   = new RecordingDbConnection(logger, "SchemaVersions");
            testConnectionFactory = new DelegateConnectionFactory(_ => recordingConnection);

            upgradeEngineBuilder = DeployChanges.To
                                   .SqlDatabase("testconn")
                                   .WithScripts(new TestScriptProvider(scripts))
                                   .OverrideConnectionFactory(testConnectionFactory)
                                   .LogTo(logger);
        }
Beispiel #13
0
        private HubConnection CreateHubConnection(
            string path = null,
            HttpTransportType?transportType = null,
            IHubProtocol protocol           = null,
            ILoggerFactory loggerFactory    = null)
        {
            var hubConnectionBuilder = new HubConnectionBuilder();

            hubConnectionBuilder.Services.AddSingleton(protocol);
            hubConnectionBuilder.WithLoggerFactory(loggerFactory);

            var delegateConnectionFactory = new DelegateConnectionFactory(
                GetHttpConnectionFactory(loggerFactory, path, transportType ?? HttpTransportType.LongPolling | HttpTransportType.WebSockets | HttpTransportType.ServerSentEvents),
                connection => ((HttpConnection)connection).DisposeAsync());

            hubConnectionBuilder.Services.AddSingleton <IConnectionFactory>(delegateConnectionFactory);

            return(hubConnectionBuilder.Build());
        }
Beispiel #14
0
            public async Task StartingDuringStopCreatesANewConnection()
            {
                // Set up StartAsync to wait on the syncPoint when starting
                var createCount = 0;
                var onDisposeForFirstConnection = SyncPoint.Create(out var syncPoint);

                Task <ConnectionContext> ConnectionFactory(TransferFormat format)
                {
                    createCount += 1;
                    return(new TestConnection(onDispose: createCount == 1 ? onDisposeForFirstConnection : null).StartAsync(format));
                }

                Task DisposeAsync(ConnectionContext connection) => ((TestConnection)connection).DisposeAsync();

                var builder = new HubConnectionBuilder();
                var delegateConnectionFactory = new DelegateConnectionFactory(ConnectionFactory, DisposeAsync);

                builder.Services.AddSingleton <IConnectionFactory>(delegateConnectionFactory);

                await AsyncUsing(builder.Build(), async connection =>
                {
                    await connection.StartAsync().OrTimeout();
                    Assert.Equal(1, createCount);

                    var stopTask = connection.StopAsync();

                    // Wait to hit DisposeAsync on TestConnection (which should be after StopAsync has cleared the connection state)
                    await syncPoint.WaitForSyncPoint().OrTimeout();

                    // We should not yet be able to start now because StopAsync hasn't completed
                    Assert.False(stopTask.IsCompleted);
                    var startTask = connection.StartAsync();
                    Assert.False(stopTask.IsCompleted);

                    // When we release the sync point, the StopAsync task will finish
                    syncPoint.Continue();
                    await stopTask.OrTimeout();

                    // Which will then allow StartAsync to finish.
                    await startTask.OrTimeout();
                });
            }
Beispiel #15
0
    private static HubConnection CreateHubConnection(TestConnection connection, IHubProtocol protocol = null, ILoggerFactory loggerFactory = null)
    {
        var builder = new HubConnectionBuilder().WithUrl("http://example.com");

        var delegateConnectionFactory = new DelegateConnectionFactory(
            endPoint => connection.StartAsync());

        builder.Services.AddSingleton <IConnectionFactory>(delegateConnectionFactory);

        if (loggerFactory != null)
        {
            builder.WithLoggerFactory(loggerFactory);
        }

        if (protocol != null)
        {
            builder.Services.AddSingleton(protocol);
        }

        return(builder.Build());
    }
Beispiel #16
0
            public async Task StartingAfterStopCreatesANewConnection()
            {
                // Set up StartAsync to wait on the syncPoint when starting
                var createCount = 0;

                Task <ConnectionContext> ConnectionFactory(TransferFormat format)
                {
                    createCount += 1;
                    return(new TestConnection().StartAsync(format));
                }

                Task DisposeAsync(ConnectionContext connection)
                {
                    return(((TestConnection)connection).DisposeAsync());
                }

                var builder = new HubConnectionBuilder();
                var delegateConnectionFactory = new DelegateConnectionFactory(ConnectionFactory, DisposeAsync);

                builder.Services.AddSingleton <IConnectionFactory>(delegateConnectionFactory);

                await AsyncUsing(builder.Build(), async connection =>
                {
                    Assert.Equal(HubConnectionState.Disconnected, connection.State);

                    await connection.StartAsync().OrTimeout();
                    Assert.Equal(1, createCount);
                    Assert.Equal(HubConnectionState.Connected, connection.State);

                    await connection.StopAsync().OrTimeout();
                    Assert.Equal(HubConnectionState.Disconnected, connection.State);

                    await connection.StartAsync().OrTimeout();
                    Assert.Equal(2, createCount);
                    Assert.Equal(HubConnectionState.Connected, connection.State);
                });
            }
Beispiel #17
0
        public async Task ClosedEventRaisedWhenTheClientIsStopped()
        {
            var builder = new HubConnectionBuilder().WithUrl("http://example.com");

            var delegateConnectionFactory = new DelegateConnectionFactory(
                endPoint => new TestConnection().StartAsync());

            builder.Services.AddSingleton <IConnectionFactory>(delegateConnectionFactory);

            var hubConnection  = builder.Build();
            var closedEventTcs = new TaskCompletionSource <Exception>();

            hubConnection.Closed += e =>
            {
                closedEventTcs.SetResult(e);
                return(Task.CompletedTask);
            };

            await hubConnection.StartAsync().DefaultTimeout();

            await hubConnection.StopAsync().DefaultTimeout();

            Assert.Null(await closedEventTcs.Task);
        }
Beispiel #18
0
 public ConfigLoaderTests()
 {
     Logger = new CaptureLogsLogger();
     recordingConnection   = new RecordingDbConnection(Logger, "SchemaVersions");
     testConnectionFactory = new DelegateConnectionFactory(_ => recordingConnection);
 }
 public VariableSubstitutionTests()
 {
     Logger = new CaptureLogsLogger();
     recordingConnection   = new RecordingDbConnection(Logger, "SchemaVersions");
     testConnectionFactory = new DelegateConnectionFactory(_ => recordingConnection);
 }