public static async Task ShouldCallElasticSearchClient()
        {
            var spyLog = new SpyLog();

            var mockConnection = Substitute.For <IElasticConnection>();

            mockConnection.Index.Returns("SearchIndex");
            mockConnection.Options.Returns(new ElasticConnectionOptions());
            mockConnection.Timeout.Returns(TimeSpan.FromSeconds(10));

            var request = new SearchRequest {
                IndexType = "abc123", Size = 2112
            };
            var token = new CancellationToken();

            var processor = new ElasticRequestProcessor(mockConnection, mapping, spyLog, retryPolicy);

            await processor.SearchAsync(request, token);

#pragma warning disable 4014 // Remove this and await the SearchAsync below once NSubstitute 1.8.3 available
            mockConnection.Received(1).SearchAsync(
#pragma warning restore 4014
                @"{""size"":2112,""timeout"":""10s""}",
                request,
                token,
                spyLog
                );
        }
        public static async Task ShouldCallElasticSearchClient()
        {
            var spyLog = new SpyLog();

            var mockConnection = Substitute.For<IElasticConnection>();

            mockConnection.Index.Returns("SearchIndex");
            mockConnection.Options.Returns(new ElasticConnectionOptions());
            mockConnection.Timeout.Returns(TimeSpan.FromSeconds(10));

            var request = new SearchRequest { DocumentType = "abc123", Size = 2112 };
            var token = new CancellationToken();

            var processor = new ElasticRequestProcessor(mockConnection, mapping, spyLog, retryPolicy);

            await processor.SearchAsync(request, token);

#pragma warning disable 4014 // Remove this and await the SearchAsync below once NSubstitute 1.8.3 available
            mockConnection.Received(1).SearchAsync(
#pragma warning restore 4014
               @"{""size"":2112,""timeout"":""10s""}",
               request,
               token,
               spyLog
               );
        }
Ejemplo n.º 3
0
        public static void InfoRecordsToLog()
        {
            var spy = new SpyLog();

            spy.Info(new Exception("InfoLog"), new Dictionary<string, object> { { "InfoInfo", new object() } }, "InfoMessage", 1, 2, 3);

            var entry = Assert.Single(spy.Entries);
            Assert.Equal(TraceEventType.Information, entry.Type);
            Assert.Contains("InfoLog", entry.Exception.Message);
            Assert.Contains("InfoInfo", entry.AdditionalInfo.Keys);
            Assert.Equal("InfoMessage", entry.Message);
        }
Ejemplo n.º 4
0
        public void DebugRecordsToLog()
        {
            var spy = new SpyLog();

            spy.Debug(new Exception("DebugLog"), new Dictionary<string, object> { { "DebugInfo", new Object() } }, "DebugMessage", 1, 2, 3);

            Assert.Equal(1, spy.Messages.Count);
            Assert.Contains("VERBOSE", spy.Messages[0]);
            Assert.Contains("DebugLog", spy.Messages[0]);
            Assert.Contains("DebugInfo", spy.Messages[0]);
            Assert.Contains("DebugMessage", spy.Messages[0]);
        }
Ejemplo n.º 5
0
        public void InfoRecordsToLog()
        {
            var spy = new SpyLog();

            spy.Info(new Exception("InfoLog"), new Dictionary<string, object> { { "InfoInfo", new Object() } }, "InfoMessage", 1, 2, 3);

            Assert.Equal(1, spy.Messages.Count);
            Assert.Contains("INFO", spy.Messages[0]);
            Assert.Contains("InfoLog", spy.Messages[0]);
            Assert.Contains("InfoInfo", spy.Messages[0]);
            Assert.Contains("InfoMessage", spy.Messages[0]);
        }
Ejemplo n.º 6
0
        public void FatalRecordsToLog()
        {
            var spy = new SpyLog();

            spy.Fatal(new Exception("FatalLog"), new Dictionary<string, object> { { "FatalInfo", new Object() } }, "FatalMessage", 1, 2, 3);

            Assert.Equal(1, spy.Messages.Count);
            Assert.Contains("CRITICAL", spy.Messages[0]);
            Assert.Contains("FatalLog", spy.Messages[0]);
            Assert.Contains("FatalInfo", spy.Messages[0]);
            Assert.Contains("FatalMessage", spy.Messages[0]);
        }
Ejemplo n.º 7
0
        public static void DebugRecordsToLog()
        {
            var spy = new SpyLog();

            spy.Debug(new Exception("DebugLog"), new Dictionary<string, object> { { "DebugInfo", new object() } }, "DebugMessage", 1, 2, 3);

            var entry = Assert.Single(spy.Entries);
            Assert.Equal(TraceEventType.Verbose, entry.Type);
            Assert.Contains("DebugLog", entry.Exception.Message);
            Assert.Contains("DebugInfo", entry.AdditionalInfo.Keys);
            Assert.Equal("DebugMessage", entry.Message);
        }
Ejemplo n.º 8
0
        public void ErrorRecordsToLog()
        {
            var spy = new SpyLog();

            spy.Error(new Exception("ErrorLog"), new Dictionary<string, object> { { "ErrorInfo", new Object() } }, "ErrorMessage", 1, 2, 3);

            Assert.Equal(1, spy.Messages.Count);
            Assert.Contains("ERROR", spy.Messages[0]);
            Assert.Contains("ErrorLog", spy.Messages[0]);
            Assert.Contains("ErrorInfo", spy.Messages[0]);
            Assert.Contains("ErrorMessage", spy.Messages[0]);
        }
Ejemplo n.º 9
0
        public void DebugRecordsToLog()
        {
            var spy = new SpyLog();

            spy.Debug(new Exception("DebugLog"), new Dictionary <string, object> {
                { "DebugInfo", new Object() }
            }, "DebugMessage", 1, 2, 3);

            Assert.Equal(1, spy.Messages.Count);
            Assert.Contains("VERBOSE", spy.Messages[0]);
            Assert.Contains("DebugLog", spy.Messages[0]);
            Assert.Contains("DebugInfo", spy.Messages[0]);
            Assert.Contains("DebugMessage", spy.Messages[0]);
        }
Ejemplo n.º 10
0
        public void InfoRecordsToLog()
        {
            var spy = new SpyLog();

            spy.Info(new Exception("InfoLog"), new Dictionary <string, object> {
                { "InfoInfo", new Object() }
            }, "InfoMessage", 1, 2, 3);

            Assert.Equal(1, spy.Messages.Count);
            Assert.Contains("INFO", spy.Messages[0]);
            Assert.Contains("InfoLog", spy.Messages[0]);
            Assert.Contains("InfoInfo", spy.Messages[0]);
            Assert.Contains("InfoMessage", spy.Messages[0]);
        }
Ejemplo n.º 11
0
        public void FatalRecordsToLog()
        {
            var spy = new SpyLog();

            spy.Fatal(new Exception("FatalLog"), new Dictionary <string, object> {
                { "FatalInfo", new Object() }
            }, "FatalMessage", 1, 2, 3);

            Assert.Equal(1, spy.Messages.Count);
            Assert.Contains("CRITICAL", spy.Messages[0]);
            Assert.Contains("FatalLog", spy.Messages[0]);
            Assert.Contains("FatalInfo", spy.Messages[0]);
            Assert.Contains("FatalMessage", spy.Messages[0]);
        }
Ejemplo n.º 12
0
        public void ErrorRecordsToLog()
        {
            var spy = new SpyLog();

            spy.Error(new Exception("ErrorLog"), new Dictionary <string, object> {
                { "ErrorInfo", new Object() }
            }, "ErrorMessage", 1, 2, 3);

            Assert.Equal(1, spy.Messages.Count);
            Assert.Contains("ERROR", spy.Messages[0]);
            Assert.Contains("ErrorLog", spy.Messages[0]);
            Assert.Contains("ErrorInfo", spy.Messages[0]);
            Assert.Contains("ErrorMessage", spy.Messages[0]);
        }
Ejemplo n.º 13
0
        public static void DebugRecordsToLog()
        {
            var spy = new SpyLog();

            spy.Debug(new Exception("DebugLog"), new Dictionary <string, object> {
                { "DebugInfo", new object() }
            }, "DebugMessage", 1, 2, 3);

            var entry = Assert.Single(spy.Entries);

            Assert.Equal(TraceEventType.Verbose, entry.Type);
            Assert.Contains("DebugLog", entry.Exception.Message);
            Assert.Contains("DebugInfo", entry.AdditionalInfo.Keys);
            Assert.Equal("DebugMessage", entry.Message);
        }
Ejemplo n.º 14
0
        public static void InfoRecordsToLog()
        {
            var spy = new SpyLog();

            spy.Info(new Exception("InfoLog"), new Dictionary <string, object> {
                { "InfoInfo", new object() }
            }, "InfoMessage", 1, 2, 3);

            var entry = Assert.Single(spy.Entries);

            Assert.Equal(TraceEventType.Information, entry.Type);
            Assert.Contains("InfoLog", entry.Exception.Message);
            Assert.Contains("InfoInfo", entry.AdditionalInfo.Keys);
            Assert.Equal("InfoMessage", entry.Message);
        }
        public static async void SearchAsyncCapturesRequestInfoOnFailure()
        {
            var spyLog = new SpyLog();
            var brokenConnection = new ElasticConnection(new Uri("http://localhost:12"), index: "MyIndex");
            var processor = new ElasticRequestProcessor(brokenConnection, mapping, spyLog, new RetryPolicy(spyLog, 100, 1));
            var searchRequest = new SearchRequest { DocumentType = "docType" };
            var formatter = new SearchRequestFormatter(brokenConnection, mapping, searchRequest);

            var ex = await Record.ExceptionAsync(() => processor.SearchAsync(searchRequest, CancellationToken.None));

            Assert.IsType<RetryFailedException>(ex);
            var retryLogEntry = Assert.Single(spyLog.Entries, s => s.AdditionalInfo.ContainsKey("category") && s.AdditionalInfo["category"].Equals("retry"));
            Assert.Equal("MyIndex", retryLogEntry.AdditionalInfo["index"]);
            Assert.Equal(brokenConnection.GetSearchUri(searchRequest), retryLogEntry.AdditionalInfo["uri"]);
            Assert.Equal(formatter.Body, retryLogEntry.AdditionalInfo["query"]);
        }
        public void ConstructorWithAllArgsSetsPropertiesFromParameters()
        {
            var expectedMapping = new ElasticMapping();
            var expectedLog = new SpyLog();
            const int expectedAttempts = 5;
            var expectedTimeout = TimeSpan.FromSeconds(21.3);

            var context = new TestableElasticContext(expectedMapping, expectedLog, expectedAttempts, expectedTimeout);

            Assert.NotNull(context.Connection);
            Assert.Equal(expectedMapping, context.Mapping);
            Assert.NotNull(context.Provider);
            Assert.NotNull(context.Requests);
            Assert.Equal(expectedLog, context.Log);
            var retryPolicy = Assert.IsType<RetryPolicy>(context.RetryPolicy);
            Assert.Equal(expectedAttempts, retryPolicy.MaxAttempts);
        }
        public void ConstructorWithAllArgsSetsPropertiesFromParameters()
        {
            var       expectedMapping  = new ElasticMapping();
            var       expectedLog      = new SpyLog();
            const int expectedAttempts = 5;
            var       expectedTimeout  = TimeSpan.FromSeconds(21.3);

            var context = new TestableElasticContext(expectedMapping, expectedLog, expectedAttempts, expectedTimeout);

            Assert.NotNull(context.Connection);
            Assert.Equal(expectedMapping, context.Mapping);
            Assert.NotNull(context.Provider);
            Assert.NotNull(context.Requests);
            Assert.Equal(expectedLog, context.Log);
            var retryPolicy = Assert.IsType <RetryPolicy>(context.RetryPolicy);

            Assert.Equal(expectedAttempts, retryPolicy.MaxAttempts);
        }
        public static async void SearchAsyncCapturesRequestInfoOnFailure()
        {
            var spyLog           = new SpyLog();
            var brokenConnection = new ElasticConnection(new Uri("http://localhost:12"), index: "MyIndex");
            var processor        = new ElasticRequestProcessor(brokenConnection, mapping, spyLog, new RetryPolicy(spyLog, 100, 1));
            var searchRequest    = new SearchRequest {
                IndexType = "docType"
            };
            var formatter = new SearchRequestFormatter(brokenConnection, mapping, searchRequest);

            var ex = await Record.ExceptionAsync(() => processor.SearchAsync(searchRequest, CancellationToken.None));

            Assert.IsType <RetryFailedException>(ex);
            var retryLogEntry = Assert.Single(spyLog.Entries, s => s.AdditionalInfo.ContainsKey("category") && s.AdditionalInfo["category"].Equals("retry"));

            Assert.Equal("MyIndex", retryLogEntry.AdditionalInfo["index"]);
            Assert.Equal(brokenConnection.GetSearchUri(searchRequest), retryLogEntry.AdditionalInfo["uri"]);
            Assert.Equal(formatter.Body, retryLogEntry.AdditionalInfo["query"]);
        }
Ejemplo n.º 19
0
        public static async void SearchAsyncThrowsTaskCancelledExceptionWithAlreadyCancelledCancellationToken()
        {
            var client = Substitute.For <IElasticsearchClient>();

            var spyLog          = new SpyLog();
            var localConnection = new ElasticNetConnection(client, "SearchIndex");
            var request         = new SearchRequest {
                DocumentType = "docType"
            };
            var formatter = new SearchRequestFormatter(localConnection, mapping, request);

            var ex = await Record.ExceptionAsync(() => localConnection.SearchAsync(
                                                     formatter.Body,
                                                     request,
                                                     new CancellationToken(true),
                                                     spyLog));

            Assert.IsType <TaskCanceledException>(ex);
        }
Ejemplo n.º 20
0
        public void Establish()
        {
            _logger    = new SpyLog();
            _myCommand = new MyCommand();

            var registry = new SubscriberRegistry();

            registry.Register <MyCommand, MyLoggedHandler>();

            var container = new TinyIoCContainer();

            container.Register <IHandleRequests <MyCommand>, MyLoggedHandler>();
            container.Register <IHandleRequests <MyCommand>, RequestLoggingHandler <MyCommand> >();

            var handlerFactory = new TinyIocHandlerFactory(container);

            _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry());

            LogProvider.SetCurrentLogProvider(new SpyLogProvider(_logger));
        }
Ejemplo n.º 21
0
        public CommandProcessorWithLoggingInPipelineAsyncTests()
        {
            _logger    = new SpyLog();
            _myCommand = new MyCommand();

            var registry = new SubscriberRegistry();

            registry.RegisterAsync <MyCommand, MyLoggedHandlerAsync>();

            var container = new TinyIoCContainer();

            container.Register <IHandleRequestsAsync <MyCommand>, MyLoggedHandlerAsync>();
            container.Register <IHandleRequestsAsync <MyCommand>, RequestLoggingHandlerAsync <MyCommand> >();

            var handlerFactory = new TinyIocHandlerFactoryAsync(container);

            _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry());

            LogProvider.SetCurrentLogProvider(new SpyLogProvider(_logger));
        }
        public static async Task LogsDebugMessagesDuringExecution()
        {
            var responseString = BuildResponseString(2, 1, 1, 0.3141, "testIndex", "testType", "testId");
            var messageHandler = new SpyMessageHandler();
            var spyLog         = new SpyLog();

            messageHandler.Response.Content = new StringContent(responseString);
            var localConnection = new ElasticConnection(messageHandler, new Uri("http://localhost"), "myUser", "myPass", "SearchIndex");
            var processor       = new ElasticRequestProcessor(localConnection, mapping, spyLog, retryPolicy);
            var request         = new SearchRequest {
                DocumentType = "abc123", Size = 2112
            };

            await processor.SearchAsync(request, CancellationToken.None);

            Assert.Equal(4, spyLog.Entries.Count);
            Assert.Equal(@"Request: POST http://localhost/SearchIndex/abc123/_search", spyLog.Entries[0].Message);
            Assert.Equal(@"Body:" + '\n' + @"{""size"":2112,""timeout"":""10s""}", spyLog.Entries[1].Message);
            Assert.True(new Regex(@"Response: 200 OK \(in \d+ms\)").Match(spyLog.Entries[2].Message).Success);
            Assert.True(new Regex(@"Deserialized \d+ bytes into 1 hits in \d+ms").Match(spyLog.Entries[3].Message).Success);
        }
Ejemplo n.º 23
0
        public static async Task LogsDebugMessagesDuringExecution()
        {
            var responseString = BuildResponseString(2, 1, 1, 0.3141, "testIndex", "testType", "testId");
            var messageHandler = new SpyMessageHandler();
            var log            = new SpyLog();

            messageHandler.Response.Content = new StringContent(responseString);
            var localConnection = new ElasticConnection(messageHandler, new Uri("http://localhost"), "myUser", "myPass", index: "SearchIndex");
            var processor       = new ElasticRequestProcessor(localConnection, mapping, log, retryPolicy);
            var request         = new ElasticSearchRequest {
                Type = "abc123", Size = 2112
            };

            await processor.SearchAsync(request);

            Assert.Equal(4, log.Messages.Count);
            Assert.Equal(@"[VERBOSE] Request: POST http://localhost/SearchIndex/abc123/_search", log.Messages[0]);
            Assert.Equal(@"[VERBOSE] Body: {""size"":2112,""timeout"":""10s""}", log.Messages[1]);
            Assert.True(new Regex(@"\[VERBOSE\] Response: 200 OK \(in \d+ms\)").Match(log.Messages[2]).Success);
            Assert.True(new Regex(@"\[VERBOSE\] De-serialized \d+ bytes into 1 hits in \d+ms").Match(log.Messages[3]).Success);
        }
Ejemplo n.º 24
0
        public EBotClient(string token, string prefix)
        {
            Console.Clear();
            Console.Title = "EBot's Logs";

            this._Token       = token;
            this._Prefix      = prefix;
            this._Log         = new BotLog();
            this._Event       = new LogEvent();
            this._Spy         = new SpyLog();
            this._Handler     = new CommandsHandler();
            this._Source      = new CommandSource(this._Handler, this._Log);
            this._Discord     = new DiscordSocketClient();
            this._DiscordREST = new DiscordRestClient();

            this._Log.Nice("Config", ConsoleColor.Yellow, "Token used => [ " + token + " ]");
            this._Log.Notify("Initializing");

            this._Handler.Client         = this._Discord;
            this._Handler._RESTClient    = this._DiscordREST;
            this._Handler.Log            = this._Log;
            this._Handler.Prefix         = this._Prefix;
            this._Handler.Source         = this._Source;
            this._Handler.EmbedReply.Log = this._Log;
            this._Handler.Initialize();

            this._Spy.Client     = this._Discord;
            this._Spy.RESTClient = this._DiscordREST;
            this._Spy.Log        = this._Log;
            this._Spy.WatchWords(new string[] { "yara", "earu" });

            this._Event.Client     = this._Discord;
            this._Event.RESTClient = this._DiscordREST;
            this._Event.Prefix     = this._Prefix;
            this._Event.Log        = this._Log;
            this._Event.InitEvents();

            CLIENT = this;
        }
Ejemplo n.º 25
0
        public static async Task LogsDebugMessagesDuringExecution()
        {
            var client = Substitute.For <IElasticsearchClient>();

            var responseString = BuildResponseString(2, 1, 1, 0.3141, "testIndex", "testType", "testId");
            var spyLog         = new SpyLog();

            client.SearchAsync <string>(
                "SearchIndex",
                "abc123",
                @"{""size"":2112,""timeout"":""10s""}",
                Arg.Any <Func <SearchRequestParameters, SearchRequestParameters> >())
            .Returns(Task.FromResult(ElasticsearchResponse <string> .Create(
                                         new ConnectionConfiguration(),
                                         200,
                                         "_search",
                                         "http://localhost/SearchIndex/abc123/_search",
                                         new byte[0],
                                         responseString)));

            var localConnection = new ElasticNetConnection(client, index: "SearchIndex");
            var request         = new SearchRequest {
                DocumentType = "abc123", Size = 2112
            };
            var formatter = new SearchRequestFormatter(localConnection, mapping, request);

            await localConnection.SearchAsync(
                formatter.Body,
                request,
                CancellationToken.None,
                spyLog);

            Assert.Equal(4, spyLog.Entries.Count);
            Assert.Equal(@"Request: POST http://localhost/SearchIndex/abc123/_search", spyLog.Entries[0].Message);
            Assert.Equal(@"Body:" + '\n' + @"{""size"":2112,""timeout"":""10s""}", spyLog.Entries[1].Message);
            Assert.True(new Regex(@"Response: 200 OK \(in \d+ms\)").Match(spyLog.Entries[2].Message).Success);
            Assert.True(new Regex(@"Deserialized \d+ characters into 1 hits in \d+ms").Match(spyLog.Entries[3].Message).Success);
        }
        public static async Task LogsDebugMessagesDuringExecution()
        {
            var responseString = BuildResponseString(2, 1, 1, 0.3141, "testIndex", "testType", "testId");
            var messageHandler = new SpyMessageHandler();
            var log = new SpyLog();
            messageHandler.Response.Content = new StringContent(responseString);
            var localConnection = new ElasticConnection(messageHandler, new Uri("http://localhost"), "myUser", "myPass", index: "SearchIndex");
            var processor = new ElasticRequestProcessor(localConnection, mapping, log, retryPolicy);
            var request = new SearchRequest { DocumentType = "abc123", Size = 2112 };

            await processor.SearchAsync(request);

            Assert.Equal(4, log.Messages.Count);
            Assert.Equal(@"[VERBOSE] Request: POST http://localhost/SearchIndex/abc123/_search", log.Messages[0]);
            Assert.Equal(@"[VERBOSE] Body:" +'\n' + @"{""size"":2112,""timeout"":""10s""}", log.Messages[1]);
            Assert.True(new Regex(@"\[VERBOSE\] Response: 200 OK \(in \d+ms\)").Match(log.Messages[2]).Success);
            Assert.True(new Regex(@"\[VERBOSE\] Deserialized \d+ bytes into 1 hits in \d+ms").Match(log.Messages[3]).Success);
        }