test: 增加健康检查单元测试

This commit is contained in:
Argo Zhang 2019-08-14 11:05:59 +08:00
parent 04b146369f
commit f7c9a638ed
No known key found for this signature in database
GPG Key ID: 152E398953DDF19F
2 changed files with 43 additions and 10 deletions

View File

@ -3,6 +3,7 @@ using Microsoft.Extensions.Diagnostics.HealthChecks;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
@ -23,7 +24,7 @@ namespace Bootstrap.Admin.HealthChecks
public GiteeHttpHealthCheck(IHttpClientFactory factory, IHttpContextAccessor accessor)
{
_client = factory.CreateClient();
_client.BaseAddress = new Uri($"{accessor.HttpContext.Request.Scheme}://{accessor.HttpContext.Request.Host}/{accessor.HttpContext.Request.PathBase}");
_client.BaseAddress = new Uri($"{accessor.HttpContext.Request.Scheme}://{accessor.HttpContext.Request.Host}{accessor.HttpContext.Request.PathBase}");
}
/// <summary>
@ -32,21 +33,30 @@ namespace Bootstrap.Admin.HealthChecks
/// <param name="context"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
{
var urls = new string[] { "Issues", "Pulls", "Releases", "Builds" };
var data = new Dictionary<string, object>();
var sw = Stopwatch.StartNew();
foreach (var url in urls)
urls.ToList().ForEach(url =>
{
var sw = Stopwatch.StartNew();
try
{
var task = _client.GetStringAsync($"/api/Gitee/{url}");
task.Wait(cancellationToken);
}
catch (Exception)
{
}
finally
{
sw.Restart();
await _client.GetStringAsync($"api/Gitee/{url}").ConfigureAwait(false);
sw.Stop();
data.Add(url, sw.Elapsed);
}
return HealthCheckResult.Healthy("Ok", data);
});
return Task.FromResult(HealthCheckResult.Healthy("Ok", data));
}
}
}

View File

@ -0,0 +1,23 @@
using Xunit;
namespace Bootstrap.Admin.Api
{
public class HealthCheckTest : ControllerTest
{
public HealthCheckTest(BAWebHost factory) : base(factory, "") { }
[Fact]
public async void Get_Ok()
{
var cates = await Client.GetAsJsonAsync<object>("/Healths");
Assert.NotNull(cates);
}
[Fact]
public async void UI_Ok()
{
var cates = await Client.GetStringAsync("/Healths-ui");
Assert.Contains("健康检查", cates);
}
}
}