Ejemplo n.º 1
0
        public async Task CreateTransactionAsync_WhenResponseIsSuccess_ShouldReturnDeserializedContent()
        {
            //Arrange
            var createBankTransactionRequest = GetCreateBankTransactionRequestObject();
            var expectedTransactionResult    = GetTransactionResultObject();
            var httpResponseMessage          = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content        = new StringContent(JsonConvert.SerializeObject(expectedTransactionResult)),
                RequestMessage = Mock.Of <HttpRequestMessage>()
            };

            var mockedHandler = new DummyHandler(() => Task.CompletedTask, httpResponseMessage);

            var dummyClient = new HttpClient(mockedHandler)
            {
                BaseAddress = new Uri(_BankClientOptions.Url)
            };

            var sut = new BankHttpClient(dummyClient, _loggerMock.Object, _jsonSerializer, _BankClientOptions);

            //Act
            var result = await sut.CreateTransactionAsync(createBankTransactionRequest);

            //Assert
            result.Should().BeEquivalentTo(expectedTransactionResult);
        }
Ejemplo n.º 2
0
        public void OnHandlingErrorGetsCalledWhenBeforeHandlingThrowsException()
        {
            // arrange
            Exception actual   = null;
            var       expected = new Exception();
            var       handler  = new DummyHandler();

            activator.UseHandler(handler);
            dispatcher.BeforeHandling += (message, sagadata) =>
            {
                throw expected;
            };
            dispatcher.OnHandlingError += exception =>
            {
                actual = exception;
            };

            // act
            var task = dispatcher.Dispatch(new Object());

            Assert.Throws <AggregateException>(() => task.Wait());

            // assert
            Assert.AreEqual(expected, actual);
        }
Ejemplo n.º 3
0
        public async Task CreateTransactionAsync_WhenResponseIsUnauthorized_ShouldLogErrorMessageAndThrow()
        {
            //Arrange
            var createBankTransactionRequest    = GetCreateBankTransactionRequestObject();
            var unauthorizedHttpResponseMessage = new HttpResponseMessage(HttpStatusCode.Unauthorized)
            {
                Content        = Mock.Of <HttpContent>(),
                RequestMessage = Mock.Of <HttpRequestMessage>()
            };

            var unauthorizedHandler = new DummyHandler(() => Task.CompletedTask, unauthorizedHttpResponseMessage);

            var dummyClient = new HttpClient(unauthorizedHandler)
            {
                BaseAddress = new Uri(_BankClientOptions.Url)
            };

            var sut = new BankHttpClient(dummyClient, _loggerMock.Object, _jsonSerializer, _BankClientOptions);

            //Act
            Assert.ThrowsAsync <HttpRequestException>(async() =>
                                                      await sut.CreateTransactionAsync(createBankTransactionRequest));

            //Assert
            _loggerMock.Verify(x =>
                               x.Write(LogLevel.Error, $"{EventCodes.ErrorCallingBankApi} - {It.IsAny<string>()}"),
                               Times.Once);
        }
Ejemplo n.º 4
0
        public ServiceClient(IClientLogic logic, IPAddress hostIP, int port, int interfaceId, long ticket)
        {
            this.logic = logic;

            client = new DynamicClient(hostIP, port);
            tree   = new ProtocolTree();
            root   = new DummyHandler <DummyProtocol>();
            auth   = new LeafProtocolHandler <AuthenticationProtocol>();

            tree.Register(root);
            tree.Register(auth);
            tree.Entry(root);
            tree.ConnectToLeaf(root, auth);
            tree.Connect(root, logic.ProtocolTree);

            app = new ApplicationConnectionManager(client, tree, 3000, 6000);

            auth.NewData += data =>
            {
                switch (data.statusCode)
                {
                case AuthenticationProtocol.StatusCode.Request:
                    Logger.Log("receiving auth request", "ServiceClient");
                    auth.Send(new AuthenticationProtocol
                    {
                        interfaceId = interfaceId,
                        ticket      = ticket,
                        resumeToken = ResumeToken,
                        statusCode  = AuthenticationProtocol.StatusCode.Ack
                    });
                    break;

                case AuthenticationProtocol.StatusCode.Accept:
                    Logger.Log("auth accepted by the host", "ServiceClient");
                    ResumeToken = data.resumeToken;
                    ConnectionAccepted?.Invoke();
                    break;

                case AuthenticationProtocol.StatusCode.Reject:
                    Logger.Log($"auth rejected by the host, {data.reason}", "ServiceClient", Logger.LogType.WARNING);
                    rejected = true;
                    client.CloseConnection();
                    app.Dispose();
                    ConnectionRejected?.Invoke();
                    break;

                default:
                    Logger.Log("invalid auth msg from host", "ServiceClient", Logger.LogType.WARNING);
                    break;
                }
            };

            app.ConnectionLost += () =>
            {
                if (!rejected)
                {
                    ConnectionLost?.Invoke();
                }
            };
        }
Ejemplo n.º 5
0
 public void SetUp()
 {
     dummySession = new DummySession();
     handler      = new DummyHandler(this);
     dummySession.SetHandler(handler);
     chain      = dummySession.FilterChain;
     testResult = String.Empty;
 }
Ejemplo n.º 6
0
 public void SetUp()
 {
     dummySession = new DummySession();
     handler = new DummyHandler(this);
     dummySession.SetHandler(handler);
     chain = dummySession.FilterChain;
     testResult = String.Empty;
 }
Ejemplo n.º 7
0
        public void CanRegisterHandler()
        {
            var handler = new DummyHandler();
            Events.RegisterHandler(handler);

            Events.Publish(new FooEvent());

            Assert.NotNull(handler.HandledEvent);
        }
Ejemplo n.º 8
0
        public void CanRegisterHandlerWithoutGenerics()
        {
            var handler = new DummyHandler();
            var handlerWithoutGenerics = (object)handler;
            Events.RegisterHandler(handlerWithoutGenerics);

            Events.Publish(new FooEvent());

            Assert.NotNull(handler.HandledEvent);
        }
Ejemplo n.º 9
0
        public async Task TestWatchWithHandlers()
        {
            AsyncCountdownEvent   eventsReceived = new AsyncCountdownEvent(1);
            AsyncManualResetEvent serverShutdown = new AsyncManualResetEvent();

            using (var server = new MockKubeApiServer(testOutput, async httpContext =>
            {
                await WriteStreamLine(httpContext, MockKubeApiServer.MockPodResponse);
                await WriteStreamLine(httpContext, MockAddedEventStreamLine);

                // make server alive, cannot set to int.max as of it would block response
                await serverShutdown.WaitAsync();
                return(false);
            }))
            {
                var handler1 = new DummyHandler();
                var handler2 = new DummyHandler();

                var client = new Kubernetes(new KubernetesClientConfiguration
                {
                    Host = server.Uri.ToString()
                }, handler1, handler2);

                Assert.False(handler1.Called);
                Assert.False(handler2.Called);

                var listTask = await client.ListNamespacedPodWithHttpMessagesAsync("default", watch : true);

                var events = new HashSet <WatchEventType>();

                var watcher = listTask.Watch <V1Pod, V1PodList>(
                    (type, item) =>
                {
                    events.Add(type);
                    eventsReceived.Signal();
                }
                    );

                // wait server yields all events
                await Task.WhenAny(eventsReceived.WaitAsync(), Task.Delay(TestTimeout));

                Assert.True(
                    eventsReceived.CurrentCount == 0,
                    "Timed out waiting for all events / errors to be received."
                    );

                Assert.Contains(WatchEventType.Added, events);

                Assert.True(handler1.Called);
                Assert.True(handler2.Called);

                serverShutdown.Set();
            }
        }
Ejemplo n.º 10
0
        static void TestAsyncHandler()
        {
            using (var evt = new ManualResetEvent(false))
            {
                var handler = new DummyHandler(evt);

                using (Postal.Box.AddAsyncHandler <string>(handler, "channel", "topic"))
                {
                    Postal.Box.Publish("channel", "topic", "Hello, World!");

                    evt.WaitOne();
                }
            }
        }
Ejemplo n.º 11
0
        public void Test()
        {
            var handler = new DummyHandler();

            Assert.That(handler.TaskHandlerKey, Is.EqualTo("Dummy"));

            handler.OnHandleTask = (dp) =>
            {
                Assert.That(dp.S, Is.EqualTo("aaa"));
            };

            var bgTask = handler.ToBackgroundTask(new DummyParams {
                S = "aaa"
            });

            Assert.That(bgTask.HandlerKey, Is.EqualTo("Dummy"));

            handler.HandleTask(bgTask);
        }
Ejemplo n.º 12
0
        public void TestWatchWithHandlers()
        {
            using (var server = new MockKubeApiServer(async httpContext =>
            {
                await WriteStreamLine(httpContext, MockKubeApiServer.MockPodResponse);
                await Task.Delay(TimeSpan.FromMilliseconds(100));

                await WriteStreamLine(httpContext, MockAddedEventStreamLine);
                await Task.Delay(TimeSpan.FromMilliseconds(100));

                // make server alive, cannot set to int.max as of it would block response
                await Task.Delay(TimeSpan.FromDays(1));
                return(false);
            }))
            {
                var handler1 = new DummyHandler();
                var handler2 = new DummyHandler();

                var client = new Kubernetes(new KubernetesClientConfiguration
                {
                    Host = server.Uri.ToString()
                }, handler1, handler2);

                Assert.False(handler1.Called);
                Assert.False(handler2.Called);

                var listTask = client.ListNamespacedPodWithHttpMessagesAsync("default", watch: true).Result;

                var events = new HashSet <WatchEventType>();

                var watcher = listTask.Watch <V1Pod>(
                    (type, item) => { events.Add(type); }
                    );

                // wait server yields all events
                Thread.Sleep(TimeSpan.FromMilliseconds(500));

                Assert.Contains(WatchEventType.Added, events);

                Assert.True(handler1.Called);
                Assert.True(handler2.Called);
            }
        }
Ejemplo n.º 13
0
        public void SuspendWithNoSecondaryId()
        {
            var oldContext = new RequestContextData(RequestContext.GetContext());

            try
            {
                var mockHandler = new Mock <DummyHandler>();

                var handler = new DummyHandler();

                var bgTask = handler.ToBackgroundTask(new DummyParams()
                {
                    S = "SuspendRestore"
                });

                var primaryUa = new UserAccount()
                {
                    Name = "primaryId"
                };

                var primaryId = new IdentityInfo(primaryUa.Id, primaryUa.Name);

                var contextData = new RequestContextData(primaryId, RequestContext.GetContext().Tenant, "XYZ", null)
                {
                    TimeZone = "XYZTZ"
                };

                RequestContext.SetContext(contextData);

                using (new SecurityBypassContext())
                {
                    // Suspend
                    IEntity suspendedtask = handler.CreateSuspendedTask(bgTask);
                }
            }
            finally
            {
                RequestContext.SetContext(oldContext);
            }
        }
Ejemplo n.º 14
0
        public void Runs( )
        {
            var edcTenantId = TenantHelper.GetTenantId("EDC", true);

            //static string result = "";
            _result = "";

            using (CountdownEvent evt = new CountdownEvent(1))
            {
                Action <DummyParam> act = (p) =>
                {
                    _result += p.S;
                    // ReSharper disable once AccessToDisposedClosure
                    evt.Signal( );
                };


                var handler = new DummyHandler {
                    Action = act
                };
                var qFactory = new RedisTenantQueueFactory("BackgroundTaskManagerTests " + Guid.NewGuid( ));
                var manager  = new BackgroundTaskManager(qFactory, handlers: handler.ToEnumerable( ))
                {
                    IsActive = true
                };

                try
                {
                    manager.EnqueueTask(edcTenantId, BackgroundTask.Create("DummyHandler", new DummyParam {
                        S = "a"
                    }));
                    Assert.That(_result, Is.Empty);

                    manager.Start( );

                    evt.Wait(DefaultTimeout);
                    evt.Reset( );

                    Assert.That(_result, Is.EqualTo("a"));

                    manager.EnqueueTask(edcTenantId, BackgroundTask.Create("DummyHandler", new DummyParam {
                        S = "b"
                    }));

                    evt.Wait(DefaultTimeout);
                    evt.Reset( );

                    Assert.That(_result, Is.EqualTo("ab"));

                    manager.Stop(5000);

                    manager.EnqueueTask(edcTenantId, BackgroundTask.Create("DummyHandler", new DummyParam {
                        S = "c"
                    }));

                    Assert.That(_result, Is.EqualTo("ab"));                              // c not processed
                }
                finally
                {
                    manager.Stop( );
                    var items = manager.EmptyQueue(edcTenantId);
                    Assert.That(items.Count( ), Is.EqualTo(1));
                }
            }
        }
Ejemplo n.º 15
0
        private void ListenerTask()
        {
            while (true)
            {
                Log("trying to accept a new client ...");

                DynamicRemoteClient remoteClient = null;
                try
                {
                    remoteClient = listener.Accept();
                }
                catch
                {
                    Log("unable to accept client", LogType.ERROR);
                    Thread.Sleep(2000);
                    continue;
                }

                ProtocolTree tree = new ProtocolTree();
                DummyHandler <DummyProtocol> treeRoot = new DummyHandler <DummyProtocol>();
                LeafProtocolHandler <AuthenticationProtocol> authHandler
                    = new LeafProtocolHandler <AuthenticationProtocol>();
                tree.Register(treeRoot);
                tree.Register(authHandler);
                tree.Entry(treeRoot);
                tree.ConnectToLeaf(treeRoot, authHandler);

                ApplicationConnectionManager app =
                    new ApplicationConnectionManager(remoteClient, tree, new DummyProvider(), 3000, 6000);

                applicationConnections.Add(app, -1);

                authHandler.NewData += data =>
                {
                    if (data.statusCode != AuthenticationProtocol.StatusCode.Ack)
                    {
                        Log("invalid auth status code: ACK", LogType.ERROR);
                        return;
                    }
                    void accept()
                    {
                        long resumeToken = 0;

                        if (!resumeTokens.ContainsKey(data.interfaceId))
                        {
                            resumeToken = Rnd64();
                            resumeTokens.Add(data.interfaceId, resumeToken);
                        }
                        else
                        {
                            resumeTokens[data.interfaceId] = resumeTokens[data.interfaceId];
                        }
                        Log($"accept the client {data.interfaceId}, token = {resumeToken}");

                        authHandler.Send(new AuthenticationProtocol
                        {
                            statusCode  = AuthenticationProtocol.StatusCode.Accept,
                            resumeToken = resumeToken
                        });
                    }

                    void reject(string reason)
                    {
                        authHandler.Send(new AuthenticationProtocol
                        {
                            statusCode = AuthenticationProtocol.StatusCode.Reject,
                            reason     = reason
                        });
                    }

                    if (data.interfaceId < 0 || data.interfaceId >= logic.MaxConnection)
                    {
                        Log($"reject the client since the interface {data.interfaceId} is not valie", LogType.WARNING);
                        reject("invalid interface id");
                        return;
                    }

                    lock (interfaceLock)
                    {
                        bool IsExistingUser = connectionInterruptTimers.ContainsKey(data.interfaceId);
                        if (IsExistingUser && data.resumeToken != resumeTokens[data.interfaceId])
                        {
                            Log($"reject the client since the resume token {data.resumeToken} is not correct", LogType.WARNING);
                            reject("wrong resume token");
                            return;
                        }
                        if (!serviceBackupData.connectionInterfaces[data.interfaceId].Enabled && !IsExistingUser)
                        {
                            Log($"reject the client since the interface {data.interfaceId} is not available", LogType.WARNING);
                            reject("interface is not available");
                            return;
                        }
                        if (serviceBackupData.connectionInterfaces[data.interfaceId].Ticket != data.ticket)
                        {
                            Log($"reject the client since the ticket {data.ticket} is not correct", LogType.WARNING);
                            reject("invalid ticket");
                            return;
                        }

                        Log("auth is valid, accept the client");
                        accept();

                        tree.Connect(treeRoot, logic.GetProtocolTree(data.interfaceId));
                        applicationConnections[app] = data.interfaceId;

                        if (IsExistingUser)
                        {
                            Log($"client with id {data.interfaceId} comes back", LogType.WARNING);
                            RemoveTimer(data.interfaceId);
                            logic.OnClientResume(data.interfaceId);
                        }
                        else
                        {
                            Log($"calling logic OnClientEnter and close interface {data.interfaceId}");
                            CloseInterface(data.interfaceId);
                            logic.OnClientEnter(data.interfaceId);
                        }
                    }
                };

                app.ConnectionLost += () =>
                {
                    app.Dispose();
                    int id = applicationConnections[app];
                    applicationConnections.Remove(app);

                    Log($"client {id} is leaving", LogType.WARNING);

                    if (id >= 0)
                    {
                        logic.GetProtocolTree(id).Detach();

                        if (logic.CanResume(id))
                        {
                            System.Timers.Timer timer = new System.Timers.Timer(20000)
                            {
                                AutoReset = false
                            };
                            timer.Elapsed += (s, e) =>
                            {
                                lock (interfaceLock)
                                {
                                    Log($"client {id} leave permanently", LogType.WARNING);
                                    timer.Dispose();
                                    connectionInterruptTimers.Remove(id);
                                    resumeTokens.Remove(id);
                                    logic.OnClientLeave(id);
                                }
                            };
                            timer.Start();
                            connectionInterruptTimers.Add(id, timer);
                            logic.OnClientDisconnect(id);
                            Log($"start timer to wait for client {id} to come back", LogType.WARNING);
                        }
                        else
                        {
                            logic.OnClientLeave(id);
                            Log($"client {id} leave permanently since logic cannot resume now", LogType.WARNING);
                        }
                    }
                };

                remoteClient.Activate();

                Logger.Log("sending auth data ...", "ServiceHost");
                authHandler.Send(new AuthenticationProtocol {
                    statusCode = AuthenticationProtocol.StatusCode.Request
                });
            }
        }
Ejemplo n.º 16
0
        public void SuspendRestore()
        {
            var mockHandler = new Mock <DummyHandler>();

            var handler = new DummyHandler();

            var primaryUa = new UserAccount()
            {
                Name = Guid.NewGuid().ToString()
            };

            primaryUa.Save();
            var secondaryUa = new UserAccount()
            {
                Name = Guid.NewGuid().ToString()
            };

            secondaryUa.Save();

            var primaryId   = new IdentityInfo(primaryUa.Id, primaryUa.Name);
            var secondaryId = new IdentityInfo(secondaryUa.Id, secondaryUa.Name);

            var contextData = new RequestContextData(primaryId, RequestContext.GetContext().Tenant, "XYZ", secondaryId)
            {
                TimeZone = "XYZTZ"
            };

            var oldContext = new RequestContextData(RequestContext.GetContext());

            try
            {
                RequestContext.SetContext(contextData);


                using (new SecurityBypassContext())
                {
                    // Suspend
                    IEntity        suspendedtask;
                    BackgroundTask bgTask;


                    bgTask = handler.ToBackgroundTask(new DummyParams()
                    {
                        S = "SuspendRestore"
                    });

                    suspendedtask = handler.CreateSuspendedTask(bgTask);
                    suspendedtask.Save();

                    Assert.That(handler.annotateSuspendedTask_calls, Is.EqualTo(1));

                    var castTask = suspendedtask.As <SuspendedTask>();
                    Assert.That(castTask.StCulture, Is.EqualTo("XYZ"));
                    Assert.That(castTask.StTimezone, Is.EqualTo("XYZTZ"));
                    Assert.That(castTask.StIdentity.Id, Is.EqualTo(primaryUa.Id));
                    Assert.That(castTask.StSecondaryIdentity.Id, Is.EqualTo(secondaryUa.Id));

                    IEnumerable <BackgroundTask> restoredTasks;

                    //Restore
                    restoredTasks = handler.RestoreSuspendedTasks();

                    Assert.That(handler.restoreTaskData_Calls, Is.EqualTo(1));
                    Assert.That(restoredTasks.Count(), Is.EqualTo(1));

                    var context = restoredTasks.First().Context;

                    Assert.That(context.Culture, Is.EqualTo("XYZ"));
                    Assert.That(context.TimeZone, Is.EqualTo("XYZTZ"));
                    Assert.That(context.Identity.Id, Is.EqualTo(primaryId.Id));
                    Assert.That(context.SecondaryIdentity.Id, Is.EqualTo(secondaryId.Id));

                    var parameter = restoredTasks.First().GetData <DummyParams>();
                    Assert.That(parameter.S, Is.EqualTo("restored"));
                }
            }
            finally
            {
                RequestContext.SetContext(oldContext);
            }
        }
 public HttpHandlerBaseTests()
 {
     _httpHandler = new DummyHandler();
 }
Ejemplo n.º 18
0
		public void SetUp()
		{
			_handler = new DummyHandler();
		}
Ejemplo n.º 19
0
		public void SetUp()
		{
			_handler = new DummyHandler();
			_hotKeysLL = new NuGenHotKeysLL();
		}
Ejemplo n.º 20
0
 public void SetUp()
 {
     _handler = new DummyHandler();
 }
Ejemplo n.º 21
0
 public void SetUp()
 {
     _handler   = new DummyHandler();
     _hotKeysLL = new NuGenHotKeysLL();
 }
Ejemplo n.º 22
0
 public HttpHandlerBaseTests()
 {
     _httpHandler = new DummyHandler();
 }
Ejemplo n.º 23
0
        public void ShouldGetEventsToHandlerAfterUnsubscribeAction()
        {
            var handler = new DummyHandler();
            Events.RegisterHandler(handler);
            Events.Unsubscribe<FooEvent>();

            Events.Publish(new FooEvent());

            Assert.NotNull(handler.HandledEvent);
        }