public async Task ShouldWritePropertiesForBatchMessage()
        {
            var httpClient = HttpClientTestHelper.Create();

            httpClient.PostAsync(Arg.Any <string>(), Arg.Any <HttpContent>()).Returns(Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)));

            var entry = EventEntryTestHelper.Create();

            using (var sink = new EventHubHttpSink(httpClient, "eventHubNameNs", "eventhubName", "pubId", "token", Buffering.DefaultBufferingInterval, Buffering.DefaultBufferingCount, Buffering.DefaultMaxBufferSize, TimeSpan.Zero))
            {
                sink.OnNext(entry);
                sink.OnNext(entry);

                await sink.FlushAsync();
            }

            IList <EventEntry> entries = new List <EventEntry> {
                entry, entry
            };
            var messages    = entries.Select(c => c.ToBatchMessage());
            var sendMessage = new ServiceBusHttpMessage
            {
                Body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(messages))
            };

            var byteRepresentation = sendMessage.Body;

            await httpClient.Received().PostAsync(Arg.Any <string>(), Arg.Is <HttpContent>(c => byteRepresentation.SequenceEqual(c.ReadAsByteArrayAsync().Result)));
        }
        public void ShouldRaiseFlushFailedOnFlushAsyncWhenHttpClientFails()
        {
            var httpClient = HttpClientTestHelper.Create();

            httpClient.When(client => client.PostAsync(Arg.Any <string>(), Arg.Any <HttpContent>())).Do(action => { throw new Exception(); });

            using (var sink = new EventHubHttpSink(httpClient, "eventHubNameNs", "eventhubName", "pubId", "token", Buffering.DefaultBufferingInterval, Buffering.DefaultBufferingCount, Buffering.DefaultMaxBufferSize, TimeSpan.Zero))
                using (var collectErrorsListener = new MockEventListener())
                {
                    collectErrorsListener.EnableEvents(SemanticLoggingEventSource.Log, EventLevel.Error, Keywords.All);

                    sink.OnNext(EventEntryTestHelper.Create());

                    try
                    {
                        sink.FlushAsync().Wait();
                        Assert.Fail("AggregateException should be thrown.");
                    }
                    catch (AggregateException ex)
                    {
                        Assert.IsInstanceOfType(ex.InnerException, typeof(FlushFailedException));
                    }

                    Assert.IsTrue(collectErrorsListener.WrittenEntries.Any(x => x.EventId == 1));
                }
        }
        public void If_server_is_down_and_cache_is_empty_a_config_access_exception_should_be_thrown()
        {
            _mockConfigServiceHttpClient = HttpClientTestHelper.CreateClientSimulatingABadAddress();
            var testFactory = new ConfigProviderFactory(TestAssemblyName, _mockConfigServiceHttpClient, _mockFileSystem.Object);

            // This validator would cause an error, but the simulated connection issue above should prevent it from hitting that.
            var validators = new Dictionary <string, Func <string, bool> > {
                { "Taco", x => true }
            };
            IConfigProvider configProvider = testFactory.Create(TestComponentName, validators);

            configProvider.GetAndValidateConfiguration();
        }
        public async Task ShouldWriteEntriesOnFlushAsync()
        {
            var httpClient = HttpClientTestHelper.Create();

            httpClient.PostAsync(Arg.Any <string>(), Arg.Any <HttpContent>()).Returns(Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)));

            using (var sink = new EventHubHttpSink(httpClient, "eventHubNameNs", "eventhubName", "pubId", "token", Buffering.DefaultBufferingInterval, Buffering.DefaultBufferingCount, Buffering.DefaultMaxBufferSize, TimeSpan.Zero))
            {
                sink.OnNext(EventEntryTestHelper.Create());
                sink.OnNext(EventEntryTestHelper.Create());

                await sink.FlushAsync();
            }

            await httpClient.Received().PostAsync(Arg.Any <string>(), Arg.Any <HttpContent>());
        }
        public void Config_should_always_come_from_cache_if_server_returns_invalid_data()
        {
            ConfigRoot configFromMockCache = MockHabitatServer.GetConfigRoot(TestComponentName);

            configFromMockCache.Data.Children[0].Value = "fromcache";
            CreateMockDurableCacheEntry(configFromMockCache);

            _mockConfigServiceHttpClient = HttpClientTestHelper.CreateClientThatAlwaysReturnsGibberish();
            var testFactory = new ConfigProviderFactory(TestAssemblyName, _mockConfigServiceHttpClient, _mockFileSystem.Object);

            IConfigProvider             configProvider = testFactory.Create(TestComponentName, new Dictionary <string, Func <string, bool> >());
            ConfigRoot                  config         = configProvider.GetAndValidateConfiguration();
            Dictionary <string, string> dictionary     = config.Data.ToDictionary();

            Assert.AreEqual("fromcache", dictionary[string.Format("{0}.N1", TestComponentName)]);
        }
Example #6
0
        public void Test_provider_behavior_when_config_service_returns_invalid_data()
        {
            var provider = new ConfigServiceProvider(ResourceUrlTemplate, HttpClientTestHelper.CreateClientThatAlwaysReturnsGibberish());

            ConfigServiceResponse response = provider.GetConfig();

            Assert.IsNotNull(response);
            Assert.IsNotNull(response.Config);
            Assert.AreEqual(ResourceUrlTemplate, response.Config.ComponentName);
            Assert.AreEqual(default(DateTime), response.Config.LastModified);
            Assert.IsNull(response.Config.Data);
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
            Assert.IsNotNull(response.Exception);
            Assert.AreEqual(typeof(UnableToAccessConfigurationException), response.Exception.GetType());
            Assert.AreEqual(typeof(AggregateException), response.Exception.InnerException.GetType());
        }
Example #7
0
        public void Test_provider_behavior_when_config_service_address_does_not_resolve()
        {
            var provider = new ConfigServiceProvider(ResourceUrlTemplate, HttpClientTestHelper.CreateClientSimulatingABadAddress());

            ConfigServiceResponse response = provider.GetConfig();

            Assert.IsNotNull(response);
            Assert.IsNotNull(response.Config);
            Assert.AreEqual(ResourceUrlTemplate, response.Config.ComponentName);
            Assert.AreEqual(default(DateTime), response.Config.LastModified);
            Assert.IsNull(response.Config.Data);
            Assert.AreEqual(default(HttpStatusCode), response.StatusCode);
            Assert.IsNotNull(response.Exception);
            Assert.AreEqual(typeof(UnableToAccessConfigurationException), response.Exception.GetType());
            Assert.AreEqual(typeof(AggregateException), response.Exception.InnerException.GetType());
        }
        /// <summary>
        /// Constructs a MockRegistry instance that contains bindings for mock/fake objects
        /// </summary>
        public MockRegistry()
        {
            Mock <IDateTime> mockDateProvider = new Mock <IDateTime>(MockBehavior.Strict);

            mockDateProvider.SetupGet(x => x.Now).Returns(new DateTimeWrap(new DateTime(2011, 1, 2)));
            For <IDateTime>().Use(() => mockDateProvider.Object);
            For <HttpClient>().Use(() => HttpClientTestHelper.CreateStandardFakeClient(new MockHabitatServer()));

            Profile(NoHttpConnection, x => x.For <HttpClient>().Use(HttpClientTestHelper.CreateClientSimulatingServerWithNoHttpEndpoint));
            Profile(BadHttpAddress, x => x.For <HttpClient>().Use(HttpClientTestHelper.CreateClientSimulatingABadAddress));
            Profile(ConnectionTimeout, x => x.For <HttpClient>().Use(HttpClientTestHelper.CreateClientSimulatingRequestTimeout));
            Profile(ServerAlwaysReturns500Error, x => x.For <HttpClient>().Use(HttpClientTestHelper.CreateClientThatAlwaysThrowsServerError));
            Profile(ServerReturnsGibberish, x => x.For <HttpClient>().Use(HttpClientTestHelper.CreateClientThatAlwaysReturnsGibberish));
            Profile(ServerAlwaysReturnsJsonArray, x => x.For <HttpClient>().Use(HttpClientTestHelper.CreateClientThatAlwaysReturnsJsonArray));
            Profile(ServerAlwaysReturnsJsonObject, x => x.For <HttpClient>().Use(HttpClientTestHelper.CreateClientThatAlwaysReturnsJsonObject));
        }
        public void ShouldNotStallOrThrowWhenHttpClientFails()
        {
            var httpClient = HttpClientTestHelper.Create();

            httpClient.PostAsync(Arg.Any <string>(), Arg.Any <HttpContent>()).Returns(Task.FromResult(new HttpResponseMessage(HttpStatusCode.InternalServerError)));

            using (var sink = new EventHubHttpSink(httpClient, "eventHubNameNs", "eventhubName", "pubId", "token", Buffering.DefaultBufferingInterval, Buffering.DefaultBufferingCount, Buffering.DefaultMaxBufferSize, TimeSpan.Zero))
                using (var collectErrorsListener = new MockEventListener())
                {
                    collectErrorsListener.EnableEvents(SemanticLoggingEventSource.Log, EventLevel.Error, Keywords.All);

                    sink.OnNext(EventEntryTestHelper.Create());

                    Assert.IsTrue(Task.Run(() => sink.OnCompleted()).Wait(TimeSpan.FromSeconds(5)));
                    Assert.IsTrue(collectErrorsListener.WrittenEntries.Any(x => x.EventId == 1));
                }
        }
Example #10
0
        public void Test_provider_behavior_when_config_service_returns_404()
        {
            HttpClient mockClient = HttpClientTestHelper.CreateStandardFakeClient(new MockHabitatServer());
            var        provider   = new ConfigServiceProvider("foo2", mockClient);

            ConfigServiceResponse response = provider.GetConfig();

            Assert.IsNotNull(response);
            Assert.IsNotNull(response.Config);
            Assert.AreEqual("foo2", response.Config.ComponentName);
            Assert.AreEqual(default(DateTime), response.Config.LastModified);
            Assert.IsNull(response.Config.Data);
            Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode);
            Assert.IsNotNull(response.Exception);
            Assert.AreEqual(typeof(UnableToAccessConfigurationException), response.Exception.GetType());
            Assert.IsNull(response.Exception.InnerException);
        }
        public void Cache_should_never_be_updated_when_invalid_data_is_retrieved_from_server()
        {
            ConfigRoot originalConfigFromMockCache = MockHabitatServer.GetConfigRoot(TestComponentName);

            originalConfigFromMockCache.Data.Children[0].Value = "fromcache";
            CreateMockDurableCacheEntry(originalConfigFromMockCache);

            _mockConfigServiceHttpClient = HttpClientTestHelper.CreateClientThatAlwaysReturnsGibberish();
            var testFactory = new ConfigProviderFactory(TestAssemblyName, _mockConfigServiceHttpClient, _mockFileSystem.Object);

            IConfigProvider configProvider     = testFactory.Create(TestComponentName, new Dictionary <string, Func <string, bool> >());
            ConfigRoot      configFromProvider = configProvider.GetAndValidateConfiguration();

            ConfigRoot updatedConfigFromMockCache = ReadMockDurableCacheEntry();

            Assert.IsTrue(_objectComparer.Compare(originalConfigFromMockCache, updatedConfigFromMockCache).AreEqual);
            Assert.IsTrue(_objectComparer.Compare(configFromProvider, originalConfigFromMockCache).AreEqual);
        }
        public void Config_data_in_cache_should_always_be_validated()
        {
            ConfigRoot configFromMockCache = MockHabitatServer.GetConfigRoot(TestComponentName);

            configFromMockCache.Data.Children[0].Value = "fromcache";
            CreateMockDurableCacheEntry(configFromMockCache);

            // In this case, we have to bypass validation of the service data because the service is offline
            _mockConfigServiceHttpClient = HttpClientTestHelper.CreateClientSimulatingABadAddress();
            var testFactory = new ConfigProviderFactory(TestAssemblyName, _mockConfigServiceHttpClient, _mockFileSystem.Object);

            var validators = new Dictionary <string, Func <string, bool> > {
                { "N1.N1", x => false }, { "N1.N2", x => false }
            };
            IConfigProvider configProvider = testFactory.Create(TestComponentName, validators);

            configProvider.GetAndValidateConfiguration();
        }
        public async Task ShouldWritePropertiesForBatchMessageUsingAutoSizedBatch()
        {
            var httpClient = HttpClientTestHelper.Create();

            httpClient.PostAsync(Arg.Any <string>(), Arg.Any <HttpContent>()).Returns(Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)));

            var entry = EventEntryTestHelper.Create();

            using (var sink = new EventHubHttpSink(httpClient, "eventHubNameNs", "eventhubName", "pubId", "token", Buffering.DefaultBufferingInterval, 0, Buffering.DefaultMaxBufferSize, TimeSpan.Zero))
            {
                foreach (var i in Enumerable.Range(0, 500))
                {
                    sink.OnNext(entry);
                }
                await sink.FlushAsync();
            }

            await httpClient.Received(2).PostAsync(Arg.Any <string>(), Arg.Is <HttpContent>(c => c.Headers.ContentLength < 256 * 1024));
        }
        public async Task ShouldNotUseBatchMessagesWhenBatchCountSetToOne()
        {
            var httpClient = HttpClientTestHelper.Create();

            httpClient.PostAsync(Arg.Any <string>(), Arg.Any <HttpContent>()).Returns(Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)));

            var entry = EventEntryTestHelper.Create();

            using (var sink = new EventHubHttpSink(httpClient, "eventHubNameNs", "eventhubName", "pubId", "token", Buffering.DefaultBufferingInterval, 1, 500, TimeSpan.Zero))
            {
                sink.OnNext(entry);
                sink.OnNext(entry);

                await sink.FlushAsync();
            }

            var byteRepresentation = Encoding.Default.GetBytes(JsonConvert.SerializeObject(entry));
            await httpClient.Received(2).PostAsync(Arg.Any <string>(), Arg.Is <HttpContent>(c => byteRepresentation.SequenceEqual(c.ReadAsByteArrayAsync().Result)));
        }
Example #15
0
        public void Test_provider_behavior_when_config_service_returns_valid_data()
        {
            ConfigRoot testConfig   = MockHabitatServer.GetConfigRoot(ResourceName);
            DateTime   expectedDate = testConfig.LastModified;

            HttpClient mockClient = HttpClientTestHelper.CreateStandardFakeClient(new MockHabitatServer());
            var        provider   = new ConfigServiceProvider(ResourceName, mockClient);

            ConfigServiceResponse response = provider.GetConfig();

            Assert.IsNotNull(response);
            Assert.IsNotNull(response.Config);
            Assert.AreEqual(ResourceName, response.Config.ComponentName);
            Assert.AreEqual(expectedDate, response.Config.LastModified);
            Assert.IsNotNull(response.Config.Data);
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
            Assert.IsNull(response.Exception);
            Assert.IsNotNull(response.Config);
            Assert.IsTrue(_objectComparer.Compare(testConfig, response.Config).AreEqual);
        }
 public void SetUp()
 {
     _mockFileSystem = _mockFileSystemProvider.MockFileSystem;
     _mockFileSystem.Setup(x => x.GetTempDirectoryPath()).Returns(TestTempPath);
     _mockConfigServiceHttpClient = HttpClientTestHelper.CreateStandardFakeClient(new MockHabitatServer());
 }