public void Should_throw_when_task_is_cancelled()
        {
            // Arrange
            const string name = "custom with cancellation token";

            // Act
            var builder = new HealthBuilder().HealthChecks.AddCheck(
                name,
                async token =>
            {
                await Task.Delay(2000, token);
                return(HealthCheckResult.Healthy());
            });

            var tokenSource = new CancellationTokenSource();

            tokenSource.CancelAfter(200);

            var check = builder.Build().Checks.Single();

            // Assert
            Action action = () =>
            {
                var result = check.ExecuteAsync(tokenSource.Token).GetAwaiter().GetResult();

                result.Check.Status.Should().Be(HealthCheckStatus.Unhealthy);
            };

            action.ShouldThrow <OperationCanceledException>();
        }
Ejemplo n.º 2
0
        private IHealthRoot ConfigureHealth()
        {
            var healthBuilder = new HealthBuilder();

            healthBuilder.HealthChecks.AddCheck(new SampleHealthCheck());
            return(healthBuilder.Build());
        }
Ejemplo n.º 3
0
        public void Options_should_not_be_null_when_configuration_not_used()
        {
            // Arrange
            var builder = new HealthBuilder();

            // Act
            var health = builder.Build();

            // Assert
            health.Options.Should().NotBeNull();
        }
Ejemplo n.º 4
0
        public void Can_use_reporter_of_type()
        {
            // Arrange
            var builder = new HealthBuilder().Report.Using <TestReporter>();

            // Act
            var metrics = builder.Build();

            // Assert
            metrics.Reporters.Should().Contain(reportMetrics => reportMetrics is TestReporter);
        }
        public void At_least_one_formatter_is_required()
        {
            // Arrange
            var builder = new HealthBuilder();

            // Act
            var health = builder.Build();

            // Assert
            health.OutputHealthFormatters.Count.Should().Be(1);
            health.DefaultOutputHealthFormatter.Should().NotBeNull();
        }
Ejemplo n.º 6
0
        public void Default_formatter_should_default_to_text_if_not_configured()
        {
            // Arrange
            var builder = new HealthBuilder();

            // Act
            var health = builder.Build();

            // Assert
            health.DefaultOutputHealthFormatter.Should().NotBeNull();
            health.DefaultOutputHealthFormatter.Should().BeOfType <HealthStatusTextOutputFormatter>();
        }
Ejemplo n.º 7
0
        public void Can_use_reporter_of_type_and_override_flushinterval()
        {
            // Arrange
            var builder = new HealthBuilder().Report.Using <TestReporter>(reportInterval: TimeSpan.FromDays(1));

            // Act
            var metrics  = builder.Build();
            var reporter = (metrics.Reporters as HealthReporterCollection)?.GetType <TestReporter>();

            // Assert
            reporter?.ReportInterval.Should().Be(TimeSpan.FromDays(1));
        }
Ejemplo n.º 8
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <EndpointsConfig>(Configuration.GetSection("Endpoints"));

            services.AddSingleton <IBusDataStore, RedisBusDataStore>();

            services.AddSingleton <IRabbitMQPersistentConnection>(sp =>
            {
                var factory = new ConnectionFactory()
                {
                    HostName = Configuration.GetValue <string>("Endpoints:RabbitMq")
                };

                if (!string.IsNullOrEmpty(Configuration["EventBusUserName"]))
                {
                    factory.UserName = Configuration["EventBusUserName"];
                }

                if (!string.IsNullOrEmpty(Configuration["EventBusPassword"]))
                {
                    factory.Password = Configuration["EventBusPassword"];
                }

                var retryCount = 5;
                if (!string.IsNullOrEmpty(Configuration["EventBusRetryCount"]))
                {
                    retryCount = int.Parse(Configuration["EventBusRetryCount"]);
                }

                return(new DefaultRabbitMQPersistentConnection(factory, retryCount));
            });

            RegisterEventBus(services);
            var identityServerEndpoint = Configuration.GetValue <string>("Endpoints:IdentityServer");

            // Add health checks
            var healthBuilder = new HealthBuilder()
                                .HealthChecks.AddHttpGetCheck("IdentityServer", new Uri(new Uri(identityServerEndpoint), "/_system/health"), 3, TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(2));

            services.AddHealth(healthBuilder.Build());
            services.TryAddEnumerable(ServiceDescriptor.Singleton <IConfigureOptions <HealthEndpointsHostingOptions>, HealthCheckOptions>());

            services.AddMvc();

            services.AddAuthentication("Bearer")
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority            = identityServerEndpoint;
                options.RequireHttpsMetadata = false;
                options.ApiName = "resources";
            });
        }
        public void Should_set_health_output_formatters_when_selected_via_type()
        {
            // Arrange
            var builder = new HealthBuilder()
                          .OutputHealth.Using <HealthStatusTextOutputFormatter>()
                          .OutputHealth.Using <HealthStatusJsonOutputFormatter>();

            // Act
            var health = builder.Build();

            // Assert
            health.OutputHealthFormatters.Count.Should().Be(2);
        }
        public void Default_health_output_formatter_should_be_first_formatter_selected_via_type()
        {
            // Arrange
            var builder = new HealthBuilder()
                          .OutputHealth.Using <HealthStatusJsonOutputFormatter>()
                          .OutputHealth.Using <HealthStatusTextOutputFormatter>();

            // Act
            var health = builder.Build();

            // Assert
            health.DefaultOutputHealthFormatter.Should().BeOfType <HealthStatusJsonOutputFormatter>();
        }
Ejemplo n.º 11
0
        public void Can_bind_metrics_options_from_configuration()
        {
            // Arrange
            var builder       = new HealthBuilder();
            var configuration = new ConfigurationBuilder().AddJsonFile("JsonFIles/HealthOptions.json").Build();

            // Act
            builder.Configuration.ReadFrom(configuration);
            var health = builder.Build();

            // Assert
            health.Options.Enabled.Should().BeFalse();
        }
        public void Should_only_add_a_single_formatter_of_the_same_type()
        {
            // Arrange
            var builder = new HealthBuilder()
                          .OutputHealth.Using <HealthStatusTextOutputFormatter>()
                          .OutputHealth.Using <HealthStatusTextOutputFormatter>();

            // Act
            var health = builder.Build();

            // Assert
            health.OutputHealthFormatters.Count.Should().Be(1);
            health.DefaultOutputHealthFormatter.Should().NotBeNull();
        }
Ejemplo n.º 13
0
        public void Throws_on_duplicate_registration()
        {
            // Arrange
            var builder = new HealthBuilder().HealthChecks.AddCheck("test", () => HealthyResult);

            Action action = () =>
            {
                // Act
                builder.HealthChecks.AddCheck("test", () => HealthyResult);
                var unused = builder.Build();
            };

            // Assert
            action.Should().Throw <ArgumentException>();
        }
        public async Task Can_execute_process_virtual_memory_check(HealthCheckStatus expectedResult, long thresholdBytes, bool degradedOnError = false)
        {
            // Arrange
            const string name    = "virtual memory";
            var          builder = new HealthBuilder()
                                   .HealthChecks.AddProcessVirtualMemorySizeCheck(name, thresholdBytes, degradedOnError: degradedOnError);
            var health = builder.Build();

            var check = health.Checks.First();

            // Act
            var result = await check.ExecuteAsync();

            // Assert
            result.Check.Status.Should().Be(expectedResult);
        }
        public void Should_not_replace_formatter_if_types_are_different_and_asked_not_to_replace()
        {
            // Arrange
            var formatter = new HealthStatusTextOutputFormatter(new HealthTextOptions {
                Encoding = Encoding.BigEndianUnicode
            });
            var builder = new HealthBuilder()
                          .OutputHealth.Using(formatter)
                          .OutputHealth.Using <HealthStatusJsonOutputFormatter>(false);

            // Act
            var health = builder.Build();

            // Assert
            health.OutputHealthFormatters.Count.Should().Be(2);
        }
        public void Can_keep_existing_formatter_if_registered_more_than_once()
        {
            // Arrange
            var formatter = new HealthStatusTextOutputFormatter(new HealthTextOptions {
                Encoding = Encoding.BigEndianUnicode
            });
            var builder = new HealthBuilder()
                          .OutputHealth.Using(formatter)
                          .OutputHealth.Using <HealthStatusTextOutputFormatter>(false);

            // Act
            var health = builder.Build();

            // Assert
            health.OutputHealthFormatters.Count.Should().Be(1);
            health.OutputHealthFormatters.First().Should().BeSameAs(formatter);
        }
Ejemplo n.º 17
0
        public void Can_bind_metrics_options_from_configuration()
        {
            // Arrange
            var builder       = new HealthBuilder();
            var keyValuePairs = new Dictionary <string, string>
            {
                { "HealthOptions:Enabled", "false" }
            };
            var configuration = new ConfigurationBuilder().AddInMemoryCollection(keyValuePairs).Build();

            // Act
            builder.Configuration.ReadFrom(configuration);
            var health = builder.Build();

            // Assert
            health.Options.Enabled.Should().BeFalse();
        }
        public void Can_register_process_physical_memory_check()
        {
            // Arrange
            const string name = "physical memory";

            // Act
            var builder = new HealthBuilder()
                          .HealthChecks.AddProcessPhysicalMemoryCheck(name, 100);
            var health = builder.Build();
            var checks = health.Checks;

            // Assert
            // ReSharper disable PossibleMultipleEnumeration
            checks.Should().NotBeNull();
            checks.Should().NotBeEmpty();
            checks.Single().Name.Should().Be(name);
            // ReSharper restore PossibleMultipleEnumeration
        }