Добавить клиент для работы с параметрами Wits

This commit is contained in:
Roman Efremov 2024-12-11 11:29:50 +05:00
parent ba833050d3
commit 0208936a00
8 changed files with 178 additions and 59 deletions

View File

@ -1,21 +0,0 @@
using Microsoft.AspNetCore.Mvc;
using Persistence.Models;
using Refit;
namespace Persistence.Client.Clients;
public interface IWitsDataClient
{
private const string BaseRoute = "/api/witsData";
[Get($"{BaseRoute}/{{discriminatorId}}/graph")]
Task<IApiResponse<IEnumerable<WitsDataDto>>> GetValuesForGraph(int discriminatorId, [Query] DateTimeOffset dateFrom, [Query] DateTimeOffset dateTo, [Query] int approxPointsCount, CancellationToken token);
[Post($"{BaseRoute}/")]
Task<IApiResponse<int>> AddRange(IEnumerable<WitsDataDto> dtos, CancellationToken token);
[Get($"{BaseRoute}/{{discriminatorId}}/part")]
Task<IApiResponse<IEnumerable<WitsDataDto>>> GetPart(int discriminatorId, [Query] DateTimeOffset dateBegin, [Query] int take = 24 * 60 * 60, CancellationToken token = default);
[Get($"{BaseRoute}/{{discriminatorId}}/datesRange")]
Task<IApiResponse<DatesRangeDto>> GetDatesRangeAsync(int discriminatorId, CancellationToken token);
}

View File

@ -0,0 +1,47 @@
using Persistence.Models;
using Refit;
namespace Persistence.Client.Clients.Interfaces;
/// <summary>
/// Клиент для работы с параметрами Wits
/// </summary>
public interface IWitsDataClient : IDisposable
{
/// <summary>
/// Получить набор параметров (Wits) для построения графика
/// </summary>
/// <param name="discriminatorId"></param>
/// <param name="dateFrom"></param>
/// <param name="dateTo"></param>
/// <param name="approxPointsCount"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<IEnumerable<WitsDataDto>> GetValuesForGraph(int discriminatorId, [Query] DateTimeOffset dateFrom, [Query] DateTimeOffset dateTo, [Query] int approxPointsCount, CancellationToken token);
/// <summary>
/// Сохранить набор параметров (Wits)
/// </summary>
/// <param name="dtos"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<int> AddRange(IEnumerable<WitsDataDto> dtos, CancellationToken token);
/// <summary>
/// Получить порцию записей, начиная с заданной даты
/// </summary>
/// <param name="discriminatorId"></param>
/// <param name="dateBegin"></param>
/// <param name="take"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<IEnumerable<WitsDataDto>> GetPart(int discriminatorId, [Query] DateTimeOffset dateBegin, [Query] int take = 24 * 60 * 60, CancellationToken token = default);
/// <summary>
/// Получить диапазон дат, для которых есть данные в репозитории
/// </summary>
/// <param name="discriminatorId"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<DatesRangeDto> GetDatesRangeAsync(int discriminatorId, CancellationToken token);
}

View File

@ -0,0 +1,21 @@
using Microsoft.AspNetCore.Mvc;
using Persistence.Models;
using Refit;
namespace Persistence.Client.Clients.Interfaces.Refit;
public interface IRefitWitsDataClient : IDisposable
{
private const string BaseRoute = "/api/witsData";
[Get($"{BaseRoute}/{{discriminatorId}}/graph")]
Task<IApiResponse<IEnumerable<WitsDataDto>>> GetValuesForGraph(int discriminatorId, [Query] DateTimeOffset dateFrom, [Query] DateTimeOffset dateTo, [Query] int approxPointsCount, CancellationToken token);
[Post($"{BaseRoute}/")]
Task<IApiResponse<int>> AddRange(IEnumerable<WitsDataDto> dtos, CancellationToken token);
[Get($"{BaseRoute}/{{discriminatorId}}/part")]
Task<IApiResponse<IEnumerable<WitsDataDto>>> GetPart(int discriminatorId, [Query] DateTimeOffset dateBegin, [Query] int take = 24 * 60 * 60, CancellationToken token = default);
[Get($"{BaseRoute}/{{discriminatorId}}/datesRange")]
Task<IApiResponse<DatesRangeDto>> GetDatesRangeAsync(int discriminatorId, CancellationToken token);
}

View File

@ -0,0 +1,53 @@
using Microsoft.Extensions.Logging;
using Persistence.Client.Clients.Base;
using Persistence.Client.Clients.Interfaces;
using Persistence.Client.Clients.Interfaces.Refit;
using Persistence.Models;
namespace Persistence.Client.Clients;
public class WitsDataClient : BaseClient, IWitsDataClient
{
private readonly IRefitWitsDataClient refitWitsDataClient;
public WitsDataClient(IRefitWitsDataClient refitWitsDataClient, ILogger<WitsDataClient> logger) : base(logger)
{
this.refitWitsDataClient = refitWitsDataClient;
}
public async Task<int> AddRange(IEnumerable<WitsDataDto> dtos, CancellationToken token)
{
var result = await ExecutePostResponse(
async () => await refitWitsDataClient.AddRange(dtos, token), token);
return result;
}
public async Task<DatesRangeDto> GetDatesRangeAsync(int discriminatorId, CancellationToken token)
{
var result = await ExecuteGetResponse<DatesRangeDto>(
async () => await refitWitsDataClient.GetDatesRangeAsync(discriminatorId, token), token);
return result;
}
public async Task<IEnumerable<WitsDataDto>> GetPart(int discriminatorId, DateTimeOffset dateBegin, int take = 86400, CancellationToken token = default)
{
var result = await ExecuteGetResponse<IEnumerable<WitsDataDto>>(
async () => await refitWitsDataClient.GetPart(discriminatorId, dateBegin, take, token), token);
return result;
}
public async Task<IEnumerable<WitsDataDto>> GetValuesForGraph(int discriminatorId, DateTimeOffset dateFrom, DateTimeOffset dateTo, int approxPointsCount, CancellationToken token)
{
var result = await ExecuteGetResponse<IEnumerable<WitsDataDto>>(
async () => await refitWitsDataClient.GetValuesForGraph(discriminatorId, dateFrom, dateTo, approxPointsCount, token), token);
return result;
}
public void Dispose()
{
refitWitsDataClient.Dispose();
}
}

View File

@ -114,5 +114,19 @@ namespace Persistence.Client
return client;
}
/// <summary>
/// Получить клиент для работы c параметрами Wits
/// </summary>
/// <returns></returns>
public IWitsDataClient GetWitsDataClient()
{
var logger = provider.GetRequiredService<ILogger<WitsDataClient>>();
var restClient = RestService.For<IRefitWitsDataClient>(httpClient, RefitSettings);
var client = new WitsDataClient(restClient, logger);
return client;
}
}
}

View File

@ -14,6 +14,7 @@ Persistence сервисом посредством обращения к кон
- `ITimeSeriesClient` - Клиент для работы с временными данными
- `ITimestampedSetClient` - Клиент для работы с данными с отметкой времени
- `IChangeLogClient` - Клиент для работы с записями ChangeLog
- `IWitsDataClient` - Клиент для работы с параметрами Wits
## Использование
Для получения того или иного Persistence - клиента нужно
@ -31,8 +32,7 @@ Persistence сервисом посредством обращения к кон
## xunit тестирование
При написании интеграционных тестов с ипользованием Persistence - клиентов
Http - клиент не обязан быть авторизован через передачу токена в `PersistenceClientFactory`.
Для осуществления тестовой авторизации достаточно добавить в `appsettings.Tests.json`.
При этом возможна авторизация через `KeyCloak`.
Для осуществления тестовой авторизации достаточно добавить в `appsettings.Tests.json` :
```json
"NeedUseKeyCloak": false,
"AuthUser": {
@ -43,4 +43,5 @@ Http - клиент не обязан быть авторизован через
},
"KeycloakGetTokenUrl": "http://192.168.0.10:8321/realms/Persistence/protocol/openid-connect/token"
```
При этом возможна авторизация через `KeyCloak`.

View File

@ -80,7 +80,7 @@ namespace Persistence.IntegrationTests.Controllers
public async Task InsertRange_returns_BadRequest()
{
//arrange
var exceptionMessage = "Ошибка валидации, формата или маршрутизации запроса";
const string exceptionMessage = "Ошибка валидации, формата или маршрутизации запроса";
var dtos = new List<TechMessageDto>()
{
new TechMessageDto()
@ -95,11 +95,16 @@ namespace Persistence.IntegrationTests.Controllers
}
};
try
{
//act
var response = await techMessagesClient.AddRange(dtos, new CancellationToken());
}
catch (Exception ex)
{
//assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Equal(exceptionMessage, ex.Message);
}
}
[Fact]

View File

@ -1,7 +1,7 @@
using System.Net;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Persistence.Client;
using Persistence.Client.Clients;
using Persistence.Client.Clients.Interfaces;
using Persistence.Database.Entity;
using Persistence.Models;
using Xunit;
@ -17,7 +17,7 @@ public class WitsDataControllerTest : BaseIntegrationTest
var persistenceClientFactory = scope.ServiceProvider
.GetRequiredService<PersistenceClientFactory>();
witsDataClient = persistenceClientFactory.GetClient<IWitsDataClient>();
witsDataClient = persistenceClientFactory.GetWitsDataClient();
}
[Fact]
@ -32,8 +32,7 @@ public class WitsDataControllerTest : BaseIntegrationTest
var response = await witsDataClient.GetDatesRangeAsync(discriminatorId, CancellationToken.None);
//assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.NotNull(response.Content);
Assert.NotNull(response);
}
[Fact]
@ -50,9 +49,8 @@ public class WitsDataControllerTest : BaseIntegrationTest
var response = await witsDataClient.GetPart(discriminatorId, dateBegin, take, CancellationToken.None);
//assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.NotNull(response.Content);
Assert.Empty(response.Content);
Assert.NotNull(response);
Assert.Empty(response);
}
[Fact]
@ -80,9 +78,8 @@ public class WitsDataControllerTest : BaseIntegrationTest
var response = await witsDataClient.GetValuesForGraph(discriminatorId, dateFrom, dateTo, approxPointCount, CancellationToken.None);
//assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.NotNull(response.Content);
Assert.Empty(response.Content);
Assert.NotNull(response);
Assert.Empty(response);
}
[Fact]
@ -98,14 +95,13 @@ public class WitsDataControllerTest : BaseIntegrationTest
var response = await witsDataClient.GetDatesRangeAsync(discriminatorId, CancellationToken.None);
//assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.NotNull(response.Content);
Assert.NotNull(response);
var expectedDateFrom = dtos
.Select(e => e.Timestamped)
.Min()
.ToString("dd.MM.yyyy-HH:mm:ss");
var actualDateFrom = response.Content.From.DateTime
var actualDateFrom = response.From.DateTime
.ToString("dd.MM.yyyy-HH:mm:ss");
Assert.Equal(expectedDateFrom, actualDateFrom);
@ -113,7 +109,7 @@ public class WitsDataControllerTest : BaseIntegrationTest
.Select(e => e.Timestamped)
.Max()
.ToString("dd.MM.yyyy-HH:mm:ss");
var actualDateTo = response.Content.To.DateTime
var actualDateTo = response.To.DateTime
.ToString("dd.MM.yyyy-HH:mm:ss");
Assert.Equal(expectedDateTo, actualDateTo);
}
@ -133,13 +129,12 @@ public class WitsDataControllerTest : BaseIntegrationTest
var response = await witsDataClient.GetPart(discriminatorId, dateBegin, take, CancellationToken.None);
//assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.NotNull(response.Content);
Assert.NotEmpty(response.Content);
Assert.Equal(take, response.Content.Count());
Assert.NotNull(response);
Assert.NotEmpty(response);
Assert.Equal(take, response.Count());
var expectedDto = dtos.FirstOrDefault();
var actualDto = response.Content.FirstOrDefault();
var actualDto = response.FirstOrDefault();
Assert.Equal(expectedDto?.DiscriminatorId, actualDto?.DiscriminatorId);
var expectedValueDto = expectedDto?.Values.FirstOrDefault();
@ -164,15 +159,15 @@ public class WitsDataControllerTest : BaseIntegrationTest
var response = await witsDataClient.GetValuesForGraph(discriminatorId, dateFrom, dateTo, approxPointCount, CancellationToken.None);
//assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.NotNull(response.Content);
Assert.Equal(approxPointCount, response.Content.Count());
Assert.NotNull(response);
Assert.Equal(approxPointCount, response.Count());
}
[Fact]
public async Task AddRange_returns_BadRequest()
{
//arrange
const string exceptionMessage = "Ошибка валидации, формата или маршрутизации запроса";
var dtos = new List<WitsDataDto>()
{
new WitsDataDto()
@ -191,11 +186,16 @@ public class WitsDataControllerTest : BaseIntegrationTest
}
};
try
{
//act
var response = await witsDataClient.AddRange(dtos, CancellationToken.None);
}
catch (Exception ex)
{
//assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Equal(exceptionMessage, ex.Message);
}
}
private async Task<IEnumerable<WitsDataDto>> AddRange(int countToCreate = 10)
@ -226,8 +226,7 @@ public class WitsDataControllerTest : BaseIntegrationTest
//assert
var count = dtos.SelectMany(e => e.Values).Count();
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
Assert.Equal(count, response.Content);
Assert.Equal(count, response);
return dtos;
}