Creado apartir del commit b888de6c92056de294456f581a56e25e734d4ab7 de develop

This commit is contained in:
jrojas
2026-06-26 09:52:35 +02:00
commit 319fd3dfb0
746 changed files with 106610 additions and 0 deletions
@@ -0,0 +1,574 @@
using System.Security.Claims;
using adas_core.Application.Exceptions;
using adas_core.Application.Repositories.Interfaces;
using adas_core.Application.Services;
using adas_core.Application.Services.Interfaces;
using adas_core.Domain.Enums;
using adas_core.Domain.Models;
using adas_core.Domain.Models.Masters;
using adas_core.Domain.Models.MongoModels;
using adas_core.Test.Utilities;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using MongoDB.Bson;
using Moq;
namespace adas_core.Test.Services;
public class AdmissionServiceTest
{
private Mock<IAdmissionRepository> _admissionRepositoryMock;
private AdmissionService _admissionService;
private Mock<ILocalAuditService> _auditServiceMock;
private Mock<IClientMessageService> _clientMessageServiceMock;
private Mock<IDischargeService> _dischargeServiceMock;
private Mock<IDisplayService> _displayServiceMock;
//Logs de auditoria
private Mock<IHttpContextAccessor> _httpContextAccessorMock;
private Mock<ILogger<AdmissionService>> _loggerMock;
private Mock<IMasterListServiceFactory> _masterListServiceFactoryMock;
private Mock<IPatientArchiveRepository> _patientArchiveRepoMock;
private Mock<IPatientService> _patientServiceMock;
private Mock<IPointOfCareService> _pointOfCareServiceMock;
private Mock<ISubscribersService> _subscribersServiceMock;
private Mock<IUnitService> _unitServiceMock;
[SetUp]
public void Setup()
{
_loggerMock = new Mock<ILogger<AdmissionService>>();
_subscribersServiceMock = new Mock<ISubscribersService>();
_admissionRepositoryMock = new Mock<IAdmissionRepository>();
_pointOfCareServiceMock = new Mock<IPointOfCareService>();
_clientMessageServiceMock = new Mock<IClientMessageService>();
_unitServiceMock = new Mock<IUnitService>();
_patientServiceMock = new Mock<IPatientService>();
_displayServiceMock = new Mock<IDisplayService>();
_dischargeServiceMock = new Mock<IDischargeService>();
_patientArchiveRepoMock = new Mock<IPatientArchiveRepository>();
_auditServiceMock = new Mock<ILocalAuditService>();
_httpContextAccessorMock = new Mock<IHttpContextAccessor>();
_masterListServiceFactoryMock = new Mock<IMasterListServiceFactory>();
// Simulación de contexto HTTP y usuario autenticado
var userClaims = new ClaimsPrincipal(new ClaimsIdentity([
new Claim(ClaimTypes.Name, "TestUser")
], "mock"));
var httpContextMock = new DefaultHttpContext
{
User = userClaims
};
_httpContextAccessorMock.Setup(accessor => accessor.HttpContext)
.Returns(httpContextMock);
_admissionService = new AdmissionService(_loggerMock.Object,
_subscribersServiceMock.Object,
_admissionRepositoryMock.Object,
_clientMessageServiceMock.Object,
_unitServiceMock.Object,
_patientServiceMock.Object,
_pointOfCareServiceMock.Object,
_displayServiceMock.Object,
_dischargeServiceMock.Object,
_patientArchiveRepoMock.Object,
_httpContextAccessorMock.Object,
_auditServiceMock.Object,
_masterListServiceFactoryMock.Object);
}
[Test]
public async Task DeleteAdmissionAsync_ValidAdmission_DeletesSuccessfully()
{
// Arrange
var admissionId = ObjectId.GenerateNewId();
var admission = new Admission { Id = admissionId };
_admissionRepositoryMock.Setup(repo => repo.FindById(admissionId))
.ReturnsAsync(admission);
// Act
await _admissionService.DeleteAdmissionAsync(admission);
// Assert
_admissionRepositoryMock.Verify(repo => repo.Delete(admissionId), Times.Once);
}
[Test]
public async Task DeleteAdmissionByIdAsync_AdmissionExists_DeletesSuccessfully()
{
// Arrange
var admissionId = ObjectId.GenerateNewId();
var admission = new Admission { Id = admissionId, PointOfCareId = ObjectId.GenerateNewId() };
_admissionRepositoryMock.Setup(repo => repo.FindById(admissionId))
.ReturnsAsync(admission);
// Act
await _admissionService.DeleteAdmissionByIdAsync(admissionId);
// Assert
_admissionRepositoryMock.Verify(repo => repo.Delete(admissionId), Times.Once);
}
[Test]
public async Task GetAdmissionByIdAsync_AdmissionExists_ReturnsAdmissionWithPatientLocation()
{
// Arrange
var admissionId = ObjectId.GenerateNewId();
var pointOfCareId = ObjectId.GenerateNewId();
var admission = new Admission { Id = admissionId, PointOfCareId = pointOfCareId };
var poc = new PointOfCare { Id = pointOfCareId, UnitName = "TestUnit", Bed = "TestBed", Room = "TestRoom" };
_admissionRepositoryMock.Setup(repo => repo.FindById(admissionId))
.ReturnsAsync(admission);
_pointOfCareServiceMock.Setup(repo => repo.GetInfo(pointOfCareId, null, false, It.IsAny<CancellationToken>()))
.ReturnsAsync(poc);
// Act
var result = await _admissionService.GetAdmissionByIdAsync(admissionId);
// Assert
Assert.That(result, Is.Not.Null);
Assert.That(result?.PatientLocation, Is.Not.Null);
Assert.That(result?.PatientLocation?.UnitName, Is.EqualTo("TestUnit"));
Assert.That(result?.PatientLocation?.Bed, Is.EqualTo("TestBed"));
Assert.That(result?.PatientLocation?.Room, Is.EqualTo("TestRoom"));
}
[Test]
public async Task GetAdmissionsAsync_ReturnsAdmissionsWithPatientLocations()
{
// Arrange
var admission1Id = ObjectId.GenerateNewId();
var admission2Id = ObjectId.GenerateNewId();
var poc1Id = ObjectId.GenerateNewId();
var poc2Id = ObjectId.GenerateNewId();
var admission1 = new Admission { Id = admission1Id, PointOfCareId = poc1Id };
var admission2 = new Admission { Id = admission2Id, PointOfCareId = poc2Id };
var admissionsList = new List<Admission> { admission1, admission2 };
_admissionRepositoryMock.Setup(repo => repo.FindAll())
.ReturnsAsync(admissionsList);
_pointOfCareServiceMock.Setup(repo => repo.GetInfo(poc1Id, null, false, It.IsAny<CancellationToken>()))
.ReturnsAsync(TestUtilities.CreateValidPointOfCare());
_pointOfCareServiceMock.Setup(repo => repo.GetInfo(poc2Id, null, false, It.IsAny<CancellationToken>()))
.ReturnsAsync(TestUtilities.CreateValidPointOfCare());
// Act
var result = await _admissionService.GetAdmissionsAsync();
// Assert
var admissions = result.ToList();
Assert.That(admissions, Is.Not.Null);
Assert.That(admissions.Count(), Is.EqualTo(2));
var admissionArray = admissions.ToArray();
Assert.That(admissionArray.First().PatientLocation, Is.Not.Null);
Assert.That(admissionArray.First().PatientLocation?.UnitName, Is.EqualTo("Test Unit"));
Assert.That(admissionArray.First().PatientLocation?.Bed, Is.EqualTo("Test Bed"));
Assert.That(admissionArray.First().PatientLocation?.Room, Is.EqualTo("Test Room"));
}
// [Test]
// public async Task InsertAdmission_WhenPointOfCareExists_InsertsAdmission()
// {
// // Arrange
// var admission = new Admission
// {
// Id = ObjectId.GenerateNewId(),
// AdmissionDate = DateTime.UtcNow,
// Nhc = "TestNhc",
// PointOfCareId = ObjectId.GenerateNewId(),
// Person = new Person(),
// Origin = TestUtilities.CreateValidOptionList(),
// Diagnosis = TestUtilities.CreateValidOptionList(),
// Allergies = new List<OptionList> { TestUtilities.CreateValidOptionList() },
// Insulation = TestUtilities.CreateValidOptionList(),
// LanguageBarrier = TestUtilities.CreateValidOptionList()
// };
//
// var pointOfCare = TestUtilities.CreateValidPointOfCare();
//
// // Setup the pointOfCareServiceMock to return a valid point of care
// pointOfCareServiceMock
// .Setup(repo => repo.GetInfo(It.IsAny<ObjectId>()))
// .ReturnsAsync(pointOfCare);
//
// // Act
// var result = await admissionService.InsertAdmission(admission);
//
// // Assert
// Assert.That(result, Is.Not.Null);
// Assert.That(result, Is.EqualTo(admission));
// admissionRepositoryMock.Verify(repo => repo.InsertOneAsyncAndReturn(It.IsAny<Admission>()), Times.Once);
// pointOfCareServiceMock.Verify(repo => repo.Update(It.IsAny<PointOfCare>()), Times.Once);
// }
[Test]
public async Task UpdateAdmissionAsync_WhenAdmissionExists_UpdatesAdmission()
{
// Arrange
var admissionId = ObjectId.GenerateNewId();
var admission = new Admission
{
Id = admissionId,
AdmissionDate = DateTime.UtcNow,
Nhc = "TestNhc",
PointOfCareId = ObjectId.GenerateNewId(),
Person = new Person(),
Origin = TestUtilities.CreateValidOptionList(),
Diagnosis = TestUtilities.CreateValidOptionList(),
Allergies = [TestUtilities.CreateValidOptionList()],
Insulation = TestUtilities.CreateValidOptionList(),
LanguageBarrier = [TestUtilities.CreateValidOptionList()]
};
var oldAdmission = new Admission
{
Id = admissionId,
AdmissionDate = DateTime.UtcNow.AddDays(-1), // Update admission date
Nhc = "OldNhc",
PointOfCareId = ObjectId.GenerateNewId(), // Change PointOfCareId
Person = new Person(),
Origin = TestUtilities.CreateValidOptionList(),
Diagnosis = TestUtilities.CreateValidOptionList(),
Allergies = [TestUtilities.CreateValidOptionList()],
Insulation = TestUtilities.CreateValidOptionList(),
LanguageBarrier = [TestUtilities.CreateValidOptionList()]
};
_admissionRepositoryMock
.Setup(repo => repo.FindById(admissionId))
.ReturnsAsync(oldAdmission);
var updatedPointOfCare = TestUtilities.CreateValidPointOfCare();
_pointOfCareServiceMock
.Setup(repo => repo.GetInfo(admission.PointOfCareId.Value, null, false, It.IsAny<CancellationToken>()))
.ReturnsAsync(updatedPointOfCare);
// Act
await _admissionService.UpdateAdmissionAsync(admission);
// Assert
_admissionRepositoryMock.Verify(repo => repo.Update(admission), Times.Once);
_pointOfCareServiceMock.Verify(repo => repo.GetInfo(admission.PointOfCareId.Value, null, false, It.IsAny<CancellationToken>()), Times.Once);
_pointOfCareServiceMock.Verify(repo => repo.GetInfo(oldAdmission.PointOfCareId.Value, null, false, It.IsAny<CancellationToken>()), Times.Once);
}
[Test]
public async Task AdmitPatient_WithValidAdmission_CreatesPatientAndDeletesAdmission()
{
// Arrange
var admission = TestUtilities.CreateValidAdmission();
var unit = TestUtilities.CreateValidUnit();
var pointOfCare = TestUtilities.CreateValidPointOfCare();
_unitServiceMock
.Setup(repo => repo.FindById(admission.UnitId))
.ReturnsAsync(unit);
_pointOfCareServiceMock
.Setup(repo => repo.FindById(It.IsAny<ObjectId>()))
.ReturnsAsync((ObjectId id) => id == admission.PointOfCareId ? pointOfCare : null);
// Act
await _admissionService.AdmitPatient(admission);
// Assert
_patientServiceMock.Verify(repo => repo.Insert(It.IsAny<Patient>()), Times.Once);
}
[Test]
public async Task GetAdmissionByLocation_LocationExists_ReturnsAdmissions()
{
// Arrange
var location = new PatientLocation
{
UnitName = "Test Unit",
Bed = "Test Bed",
Room = "Test Room"
};
var expectedAdmissions = new List<Admission>
{
new() { Id = ObjectId.GenerateNewId() },
new() { Id = ObjectId.GenerateNewId() }
};
_admissionRepositoryMock.Setup(repo => repo.FindByLocation(location))
.ReturnsAsync(expectedAdmissions);
// Act
var result = await _admissionService.GetAdmissionByLocation(location);
// Assert
Assert.That(result, Is.Not.Null);
Assert.That(result, Is.EqualTo(expectedAdmissions));
}
[Test]
public async Task GetAdmissionByLocation_LocationNotFound_ReturnsNull()
{
// Arrange
var location = new PatientLocation
{
UnitName = "Nonexistent Unit",
Bed = "Nonexistent Bed",
Room = "Nonexistent Room"
};
_admissionRepositoryMock.Setup(repo => repo.FindByLocation(location))
.ThrowsAsync(new Exception());
// Act
var result = await _admissionService.GetAdmissionByLocation(location);
// Assert
Assert.That(result, Is.Empty);
}
[Test]
public async Task GetAdmissionByPointOfCareId_POCExists_ReturnsAdmissionsWithLocation()
{
// Arrange
var pocId = ObjectId.GenerateNewId();
var expectedAdmissions = new List<Admission>
{
new() { Id = ObjectId.GenerateNewId() },
new() { Id = ObjectId.GenerateNewId() }
};
var poc = new PointOfCare
{
Id = pocId,
UnitName = "Test Unit",
Bed = "Test Bed",
Room = "Test Room"
};
_admissionRepositoryMock.Setup(repo => repo.FindByPointOfCareId(pocId))
.ReturnsAsync(expectedAdmissions);
_pointOfCareServiceMock.Setup(repo => repo.GetInfo(pocId, null, false, It.IsAny<CancellationToken>()))
.ReturnsAsync(poc);
// Act
var result = await _admissionService.GetAdmissionByPointOfCareId(pocId);
// Assert
Assert.That(result, Is.Not.Null);
Assert.That(result.Count, Is.EqualTo(expectedAdmissions.Count));
foreach (var admission in result)
{
Assert.That(admission.PatientLocation, Is.Not.Null);
Assert.That(admission.PatientLocation?.UnitName, Is.EqualTo(poc.UnitName));
Assert.That(admission.PatientLocation?.Bed, Is.EqualTo(poc.Bed));
Assert.That(admission.PatientLocation?.Room, Is.EqualTo(poc.Room));
}
}
[Test]
public async Task GetAdmissionByPointOfCareId_POCNotFound_ReturnsNull()
{
// Arrange
var pocId = ObjectId.GenerateNewId();
_admissionRepositoryMock.Setup(repo => repo.FindByPointOfCareId(pocId))
.ThrowsAsync(new Exception("Repository error"));
// Act
var result = await _admissionService.GetAdmissionByPointOfCareId(pocId);
// Assert
Assert.That(result, Is.Empty);
}
[Test]
public async Task GetAdmissionByUnitIdWithOutPoC_UnitIdExists_ReturnsAdmissions()
{
// Arrange
var unitId = ObjectId.GenerateNewId();
var expectedAdmissions = new List<Admission>
{
new() { Id = ObjectId.GenerateNewId() },
new() { Id = ObjectId.GenerateNewId() }
};
_admissionRepositoryMock.Setup(repo => repo.GetAdmissionByUnitIdWithOutPoC(unitId))
.ReturnsAsync(expectedAdmissions);
// Act
var result = await _admissionService.GetAdmissionByUnitIdWithOutPoC(unitId);
// Assert
Assert.That(result, Is.Not.Null);
Assert.That(result.Count, Is.EqualTo(expectedAdmissions.Count));
Assert.That(result, Is.EqualTo(expectedAdmissions));
}
[Test]
public async Task GetAdmissionByUnitIdWithOutPoC_UnitIdNotFound_ReturnsNull()
{
// Arrange
var unitId = ObjectId.GenerateNewId();
_admissionRepositoryMock.Setup(repo => repo.GetAdmissionByUnitIdWithOutPoC(unitId))
.ThrowsAsync(new Exception("Repository error"));
// Act
var result = await _admissionService.GetAdmissionByUnitIdWithOutPoC(unitId);
// Assert
Assert.That(result, Is.Empty);
}
// [Test]
// public async Task SaveRequest_NewAdmission_ValidRequest_InsertsAdmission()
// {
// // Arrange
// var apiRequest = new ApiRequest
// {
// Type = "NewAdmission",
// Admission = new Admission
// {
// Id = ObjectId.GenerateNewId(),
// Nhc = "TestNhc",
// Origin = new OptionList(),
// Diagnosis = new OptionList()
// }
// };
//
// admissionServiceMock.Setup(service => service.InsertAdmission(apiRequest.Admission))
// .Verifiable();
//
// // Act
// await admissionService.SaveRequest(apiRequest);
//
// // Assert
// admissionServiceMock.Verify(service => service.InsertAdmission(apiRequest.Admission), Times.Once);
// }
// [Test]
// public async Task SaveRequest_UpdateAdmission_ValidRequest_UpdatesAdmission()
// {
// // Arrange
// var apiRequest = new ApiRequest
// {
// Type = "UpdateAdmission",
// Admission = new Admission
// {
// Id = ObjectId.GenerateNewId(),
// Nhc = "TestNhc",
// Origin = new OptionList(),
// Diagnosis = new OptionList()
// }
// };
//
// admissionServiceMock.Setup(service => service.UpdateAdmissionAsync(apiRequest.Admission))
// .Verifiable();
//
// // Act
// await admissionService.SaveRequest(apiRequest);
//
// // Assert
// admissionServiceMock.Verify(service => service.UpdateAdmissionAsync(apiRequest.Admission), Times.Once);
// }
// [Test]
// public async Task SaveRequest_DeleteAdmission_ValidRequest_DeletesAdmission()
// {
// // Arrange
// var apiRequest = new ApiRequest
// {
// Type = "DeleteAdmission",
// Admission = new Admission { Id = ObjectId.GenerateNewId() }
// };
//
// admissionServiceMock.Setup(service => service.DeleteAdmissionAsync(apiRequest.Admission))
// .Verifiable();
//
// // Act
// await admissionService.SaveRequest(apiRequest);
//
// // Assert
// admissionServiceMock.Verify(service => service.DeleteAdmissionAsync(apiRequest.Admission), Times.Once);
// }
// [Test]
// public async Task SaveRequestAsync_Calls_SaveRequest_Method()
// {
// // Arrange
// var apiRequest = new ApiRequest
// {
// Type = "NewAdmission",
// Admission = new Admission
// {
// Id = ObjectId.GenerateNewId(),
// Nhc = "TestNhc",
// Origin = new OptionList(),
// Diagnosis = new OptionList()
// }
// };
//
// admissionServiceMock.Setup(service => service.SaveRequest(apiRequest))
// .Returns(Task.CompletedTask) // Since SaveRequest is async, returning completed task for simplicity
// .Verifiable();
//
// // Act
// await admissionService.SaveRequestAsync(apiRequest);
//
// // Assert
// admissionServiceMock.Verify(service => service.SaveRequest(apiRequest), Times.Once);
// }
[Test]
public async Task InsertAdmission_ValidAdmission_InsertsSuccessfullyWithUser()
{
// Arrange
var admission = new Admission
{
Id = ObjectId.GenerateNewId(),
AdmissionDate = DateTime.UtcNow,
Nhc = "TestNhc",
PointOfCareId = ObjectId.GenerateNewId(),
Person = new Person(),
Origin = new OptionList(),
Diagnosis = new OptionList(),
Allergies = [new OptionList()],
Insulation = new OptionList(),
LanguageBarrier = [new OptionList()]
};
var pointOfCare = TestUtilities.CreateValidPointOfCare();
_admissionRepositoryMock
.Setup(repo => repo.FindByNhc(admission.Nhc))
.ReturnsAsync((Admission?)null);
_pointOfCareServiceMock
.Setup(repo => repo.GetInfo(admission.PointOfCareId.Value, null, false, It.IsAny<CancellationToken>()))
.ReturnsAsync(pointOfCare);
_admissionRepositoryMock
.Setup(repo => repo.InsertOneAsyncAndReturn(admission))
.ReturnsAsync(admission);
Func<Task> act = () => _admissionService.InsertAdmission(admission);
var ex = Assert.ThrowsAsync<NotFoundException>(act);
Assert.That(ex!.Message,
Is.EqualTo(((int)HttpEnum.ErrorMessage.NotFoundResourceMissing).ToString()));
// Verify no insert
_admissionRepositoryMock
.Verify(repo => repo.InsertOneAsyncAndReturn(It.IsAny<Admission>()), Times.Never);
// Verify no update
_pointOfCareServiceMock
.Verify(service => service.Update(It.IsAny<PointOfCare>()), Times.Never);
}
}
+247
View File
@@ -0,0 +1,247 @@
using System.Security.Claims;
using adas_core.Application.Repositories.Interfaces;
using adas_core.Application.Services;
using adas_core.Application.Services.Interfaces;
using adas_core.Domain.Enums;
using adas_core.Domain.Models;
using adas_core.Domain.Models.AppSettings;
using adas_core.Domain.Models.MongoModels;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using MongoDB.Bson;
using Moq;
using Options = Microsoft.Extensions.Options.Options;
namespace adas_core.Test.Services;
public class AlarmServiceTest
{
private readonly Mock<IAlarmRepository> _alarmRepositoryMock;
private readonly AlarmService _alarmService;
private readonly ApiSettings _apiSettings = new()
{
ConfigObservation = new ConfigObservationSettings
{
IgnoreUnknownObservation = false
},
IntravenousLinesCode = ["10546003"],
AllergiesCode = ["473011001"],
DrainageCode = ["56868008"],
IsolationCode = ["302147001"],
PositionCode = ["386053000"]
};
private readonly Mock<ICalculatedObservationsService> _calculatedObservationsServiceMock;
private readonly Mock<IConfigObservationService> _configObservationServiceMock;
private readonly Mock<IObservationService> _observationServiceMock;
private readonly Mock<IPatientService> _patientServiceMock;
private readonly RecordingSettings _recordingSettings = new();
private readonly Mock<IUnitService> _unitServiceMock;
public AlarmServiceTest()
{
var optionsApiSettings = Options.Create(_apiSettings);
Options.Create(_recordingSettings);
_observationServiceMock = new Mock<IObservationService>();
var observationServiceMockLazy = new Lazy<IObservationService>(() => _observationServiceMock.Object);
_patientServiceMock = new Mock<IPatientService>();
_configObservationServiceMock = new Mock<IConfigObservationService>();
_unitServiceMock = new Mock<IUnitService>();
var pocServiceMock = new Mock<IPointOfCareService>();
var beaconServiceMock = new Mock<ILightBeaconService>();
var beaconServiceMockLazy = new Lazy<ILightBeaconService>(() => beaconServiceMock.Object);
var relayServiceMock = new Mock<IRelayService>();
var relayServiceMockLazy = new Lazy<IRelayService>(() => relayServiceMock.Object);
var recordingServiceMock = new Mock<IRecordingService>();
var recordingServiceMockLazy = new Lazy<IRecordingService>(() => recordingServiceMock.Object);
var clientMessageServiceMock = new Mock<IClientMessageService>();
var subscribersServiceMock = new Mock<ISubscribersService>();
var httpContextAccessorMock = new Mock<IHttpContextAccessor>();
var auditServiceMock = new Mock<ILocalAuditService>();
_calculatedObservationsServiceMock = new Mock<ICalculatedObservationsService>();
var calculatedObservationsServiceLazy =
new Lazy<ICalculatedObservationsService>(() => _calculatedObservationsServiceMock.Object);
var logger = new Mock<ILogger<AlarmService>>();
_alarmRepositoryMock = new Mock<IAlarmRepository>();
var userClaims = new ClaimsPrincipal(new ClaimsIdentity([
new Claim(ClaimTypes.Name, "TestUser")
], "mock"));
var httpContextMock = new DefaultHttpContext
{
User = userClaims
};
httpContextAccessorMock.Setup(accessor => accessor.HttpContext)
.Returns(httpContextMock);
_alarmService = new AlarmService(
_alarmRepositoryMock.Object,
logger.Object,
_patientServiceMock.Object,
_configObservationServiceMock.Object,
observationServiceMockLazy,
clientMessageServiceMock.Object,
subscribersServiceMock.Object,
calculatedObservationsServiceLazy,
beaconServiceMockLazy,
recordingServiceMockLazy,
relayServiceMockLazy,
optionsApiSettings,
_unitServiceMock.Object,
pocServiceMock.Object,
httpContextAccessorMock.Object,
auditServiceMock.Object,
false // Disable the timer for testing
);
}
[Test]
public async Task SaveRequest_Oru_R40_Type_Without_Alarms_Dont_Insert()
{
// Arrange
var apiRequest = new ApiRequest
{
Type = "ORU_R40",
PatientNumber = "12345",
Observation = new PatientObservation { Value = "Test" },
Alarms = [],
Location = new PatientLocation { Bed = "Bed1", Room = "Bed1", UnitName = "Unit1" }
};
var unit = new Unit { Configuration = new UnitConfiguration { AutoAdt = true } };
var patient = new Patient { Id = ObjectId.GenerateNewId(), Bed = "Bed1" };
_unitServiceMock.Setup(u => u.FindByUnitNameOrPocName(It.IsAny<string>(), It.IsAny<string>()))
.ReturnsAsync(unit);
_patientServiceMock.Setup(p => p.FindPatientByApiRequest(apiRequest)).ReturnsAsync(patient);
_observationServiceMock.Setup(o => o.SaveRequestAsync(It.IsAny<ApiRequest>())).Returns(Task.CompletedTask);
// Act
await _alarmService.SaveRequest(apiRequest);
// Assert
_patientServiceMock.Verify(p => p.FindPatientByApiRequest(apiRequest), Times.Once);
_observationServiceMock.Verify(o => o.SaveRequestAsync(It.IsAny<ApiRequest>()), Times.Never);
}
[Test]
public async Task ProcessAlarmObservations_Should_Insert_Alarm_Observations()
{
// Arrange
var patient = new Patient { Id = ObjectId.GenerateNewId(), Bed = "Bed1" };
var alarmObservations = new List<PatientObservationAlarm>
{
new() { Value = "Alarm1", Time = DateTime.UtcNow}
};
var observations = new List<PatientObservation>
{
new() { Value = "Alarm1", Time = DateTime.MinValue}
};
_configObservationServiceMock.Setup(o => o.Map(It.IsAny<PatientObservationAlarm>(), It.IsAny<bool>()))
.ReturnsAsync((PatientObservationAlarm obs, bool _) => obs); // Correct setup
_calculatedObservationsServiceMock.Setup(o => o.Map(It.IsAny<PatientObservationAlarm>(), It.IsAny<bool>()))
.ReturnsAsync((PatientObservationAlarm obs, bool _) => obs); // Correct setup
// Act
await _alarmService.ProcessAlarmObservations(alarmObservations, observations, patient, DateTime.UtcNow);
// Assert
_alarmRepositoryMock.Verify(a => a.InsertOneAsync(It.IsAny<PatientObservationAlarm>()), Times.Once);
}
[Test]
public async Task CheckObservationAlarm_Alarm_EventPEEP_PEEP_bajo_create_Event()
{
var obs = new PatientObservation();
var configs = new ConfigObservation
{
Id = ObjectId.GenerateNewId(),
Name = "Event_PEEP_Low",
CodingSystem = "ADAS_EVENT",
Description = "EVT_LO and EVT_EXTR_LO"
};
_configObservationServiceMock.Setup(c => c.Get(It.IsAny<PatientObservation>(), false))
.ReturnsAsync(configs);
await _alarmService.CheckObservationAlarm(obs);
_observationServiceMock.Verify(o => o.InsertObservation(obs, true, true), Times.Never);
}
[Test]
public async Task CheckObservationAlarm_Should_Launch_Red_Alarm_And_Set_BeaconColor_Red()
{
var alarmConfig = new AlarmConfig
{
Enabled = true,
Priority = 10,
Beacon = new AlarmItem
{
Enabled = true,
BeaconColor = AlarmEnum.BeaconColor.Red, // Using the enum value
EndAfter = 60 // Assuming the alarm should end after 60 seconds
}
};
var configs = new ConfigObservation
{
Id = ObjectId.GenerateNewId(),
Name = "Event_PEEP_Low",
CodingSystem = "ADAS_EVENT",
Description = "logs an event. No generate an alarm.",
Alarm = alarmConfig,
RequiredValue = "PEEP"
};
var obsConfig = new ConfigObservation
{
Id = ObjectId.GenerateNewId(),
Name = "EVT_LO",
CheckObservations = true,
CreateObservation = [configs]
};
var patId = ObjectId.GenerateNewId();
// Arrange
var obs = new PatientObservation
{
Id = ObjectId.GenerateNewId(),
Name = "EVT_LO",
PatientId = patId,
Value = "PEEP High",
Time = DateTime.UtcNow,
CheckObservations = true,
CreateObservation = [configs]
};
_configObservationServiceMock.Setup(c => c.Get(It.IsAny<PatientObservation>(), false))
.ReturnsAsync(obsConfig);
// Act
await _alarmService.CheckObservationAlarm(obs);
_observationServiceMock.Verify(
o => o.InsertObservation(
It.Is<PatientObservation>(ob => ob.Value.ToString() == "PEEP High"), true, true),
Times.Once);
}
}
@@ -0,0 +1,256 @@
using adas_core.Application.Services.Caching;
using adas_core.Application.Services.Interfaces;
using adas_core.Domain.Enums;
using adas_core.Domain.Models.AppSettings;
using adas_core.Domain.Models.GroupedObservations;
using adas_core.Domain.Utils;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MongoDB.Bson;
using Moq;
namespace adas_core.Test.Services;
public class FakeLockProvider : ILockProvider
{
public Task<bool> AcquireAsync(string key, TimeSpan timeout) => Task.FromResult(true);
public Task ReleaseAsync(string key) => Task.CompletedTask;
}
public class FakeLockManagerService : LockManagerService
{
public FakeLockManagerService() : base(
Mock.Of<ILogger<LockManagerService>>(),
new FakeLockProvider())
{
}
}
public class FakeRedisService : RedisService, ICacheService
{
public bool WasCalled { get; private set; }
public string? LastKey { get; private set; }
public FakeRedisService() : base(
Options.Create(new CacheSettings()),
Mock.Of<ILogger<RedisService>>(),
new FakeLockManagerService())
{
}
Task<T> ICacheService.GetOrSetObjectAsync<T>(
string key,
Func<Task<T>> factory,
TimeSpan? ttl,
CancellationToken cancellationToken)
{
WasCalled = true;
LastKey = key;
return factory();
}
Task<T> ICacheService.GetOrSetObjectAsync<T>(
GroupedField groupedField,
ObjectId patientId,
Func<Task<T>> factory,
TimeSpan? ttl,
CancellationToken cancellationToken)
{
WasCalled = true;
return factory();
}
}
public class FakeCacheService : CacheService, ICacheService
{
public bool WasCalled { get; private set; }
public string? LastKey { get; private set; }
public FakeCacheService() : base(new FakeLockManagerService())
{
}
Task<T> ICacheService.GetOrSetObjectAsync<T>(
string key,
Func<Task<T>> factory,
TimeSpan? ttl,
CancellationToken cancellationToken)
{
WasCalled = true;
LastKey = key;
return factory();
}
Task<T> ICacheService.GetOrSetObjectAsync<T>(
GroupedField groupedField,
ObjectId patientId,
Func<Task<T>> factory,
TimeSpan? ttl,
CancellationToken cancellationToken)
{
WasCalled = true;
return factory();
}
}
public class FakeNoCacheService : NoCacheService, ICacheService
{
public bool WasCalled { get; private set; }
public string? LastKey { get; private set; }
Task<T> ICacheService.GetOrSetObjectAsync<T>(
string key,
Func<Task<T>> factory,
TimeSpan? ttl,
CancellationToken cancellationToken)
{
WasCalled = true;
LastKey = key;
return factory();
}
Task<T> ICacheService.GetOrSetObjectAsync<T>(
GroupedField groupedField,
ObjectId patientId,
Func<Task<T>> factory,
TimeSpan? ttl,
CancellationToken cancellationToken)
{
WasCalled = true;
return factory();
}
}
[TestFixture]
public class CacheDispatcherTest
{
private FakeRedisService _redisServiceFake = null!;
private FakeCacheService _memoryServiceFake = null!;
private FakeNoCacheService _noopServiceFake = null!;
private CacheSettings _cacheSettings = null!;
private CacheDispatcher _cacheDispatcher = null!;
[SetUp]
public void SetUp()
{
_redisServiceFake = new FakeRedisService();
_memoryServiceFake = new FakeCacheService();
_noopServiceFake = new FakeNoCacheService();
_cacheSettings = new CacheSettings();
_cacheDispatcher = new CacheDispatcher(
_redisServiceFake,
_memoryServiceFake,
_noopServiceFake,
_cacheSettings);
}
#region TC-23
[Test]
public async Task GetOrSetObjectAsync_UsesRedisService_WhenPatientsModeIsRedis()
{
// Arrange
var key = "patients:latestObs:abc";
var expectedResult = new { Name = "TestPatient" };
Func<Task<object>> factory = () => Task.FromResult<object>(expectedResult);
_cacheSettings.Patients = CacheEnum.Mode.Redis;
// Act
var result = await _cacheDispatcher.GetOrSetObjectAsync<object>(key, factory);
// Assert
Assert.That(_redisServiceFake.WasCalled, Is.True, "RedisService debería haber sido invocado");
Assert.That(_redisServiceFake.LastKey, Is.EqualTo(key));
Assert.That(_memoryServiceFake.WasCalled, Is.False, "CacheService NO debería haber sido invocado");
Assert.That(_noopServiceFake.WasCalled, Is.False, "NoCacheService NO debería haber sido invocado");
}
#endregion
#region TC-24
[Test]
public async Task GetOrSetObjectAsync_UsesCacheService_WhenAppointmentsModeIsCache()
{
// Arrange
var key = "appointments:patient:id:20260224";
var expectedResult = new { Name = "TestAppointment" };
Func<Task<object>> factory = () => Task.FromResult<object>(expectedResult);
_cacheSettings.Appointments = CacheEnum.Mode.Cache;
// Act
var result = await _cacheDispatcher.GetOrSetObjectAsync<object>(key, factory);
// Assert
Assert.That(_memoryServiceFake.WasCalled, Is.True, "CacheService debería haber sido invocado");
Assert.That(_memoryServiceFake.LastKey, Is.EqualTo(key));
Assert.That(_redisServiceFake.WasCalled, Is.False, "RedisService NO debería haber sido invocado");
Assert.That(_noopServiceFake.WasCalled, Is.False, "NoCacheService NO debería haber sido invocado");
}
#endregion
#region TC-25
[Test]
public async Task GetOrSetObjectAsync_UsesNoCacheService_WhenPumpObservationsModeIsNone()
{
// Arrange
var key = "pumpObs:latest:abc:10";
var expectedResult = new { Name = "TestPump" };
Func<Task<object>> factory = () => Task.FromResult<object>(expectedResult);
_cacheSettings.PumpObservations = CacheEnum.Mode.None;
// Act
var result = await _cacheDispatcher.GetOrSetObjectAsync<object>(key, factory);
// Assert
Assert.That(_noopServiceFake.WasCalled, Is.True, "NoCacheService debería haber sido invocado");
Assert.That(_noopServiceFake.LastKey, Is.EqualTo(key));
Assert.That(_redisServiceFake.WasCalled, Is.False, "RedisService NO debería haber sido invocado");
Assert.That(_memoryServiceFake.WasCalled, Is.False, "CacheService NO debería haber sido invocado");
}
#endregion
#region TC-26
[Test]
public async Task GetOrSetObjectAsync_UsesCacheService_WhenKeyIsUnrecognized()
{
// Arrange
var key = "unknown:prefix:key";
var expectedResult = new { Name = "TestUnknown" };
Func<Task<object>> factory = () => Task.FromResult<object>(expectedResult);
// Act
var result = await _cacheDispatcher.GetOrSetObjectAsync<object>(key, factory);
// Assert - Unknown keys fallback to InMemory (Cache)
Assert.That(_memoryServiceFake.WasCalled, Is.True, "CacheService debería haber sido invocado como fallback");
Assert.That(_memoryServiceFake.LastKey, Is.EqualTo(key));
Assert.That(_redisServiceFake.WasCalled, Is.False, "RedisService NO debería haber sido invocado");
Assert.That(_noopServiceFake.WasCalled, Is.False, "NoCacheService NO debería haber sido invocado");
}
[Test]
public void Classify_ReturnsUnknown_ForUnrecognizedPrefix()
{
// Arrange
var key = "unknown:prefix:key";
// Act
var result = CacheKeyClassifier.Classify(key);
// Assert
Assert.That(result, Is.EqualTo(CacheEnum.EntityType.Unknown));
}
#endregion
}
+208
View File
@@ -0,0 +1,208 @@
namespace adas_core.Test.Services;
using adas_core.Application.Services.Caching;
using Microsoft.Extensions.Logging;
using Moq;
[TestFixture]
public class CacheServiceTest
{
private CacheService _svc = null!;
[SetUp]
public void SetUp()
{
var lockMgr = new LockManagerService(
new Mock<ILogger<LockManagerService>>().Object,
new InMemoryLockProvider());
_svc = new CacheService(lockMgr);
}
#region TC-31
[Test]
public async Task GetOrSetObjectAsync_ReturnsCachedValue_AndDoesNotInvokeFactory_WhenKeyAlreadyExists()
{
const string key = "patients:latestObs:abc";
const string expected = "cached-value";
await _svc.SetObjectAsync(key, expected);
var factoryCallCount = 0;
var result = await _svc.GetOrSetObjectAsync(key, () =>
{
factoryCallCount++;
return Task.FromResult("factory-value");
});
Assert.That(factoryCallCount, Is.EqualTo(0));// por qué como la clave esta, no se ejecutó el factory
Assert.That(result, Is.EqualTo(expected));
}
#endregion
#region TC-32
[Test]
public async Task GetOrSetObjectAsync_InvokesFactory_StoresResult_AndDoesNotInvokeAgainOnSecondCall()
{
const string key = "patients:latestObs:new";
const string factoryValue = "factory-result";
var factoryCallCount = 0;
var firstResult = await _svc.GetOrSetObjectAsync(key, () =>
{
factoryCallCount++;
return Task.FromResult(factoryValue);
});
Assert.That(factoryCallCount, Is.EqualTo(1));
Assert.That(firstResult, Is.EqualTo(factoryValue));
var cached = await _svc.GetObjectAsync<string>(key);
Assert.That(cached, Is.EqualTo(factoryValue));
var secondResult = await _svc.GetOrSetObjectAsync(key, () =>
{
factoryCallCount++;
return Task.FromResult("second-call-value");
});
Assert.That(factoryCallCount, Is.EqualTo(1));
Assert.That(secondResult, Is.EqualTo(factoryValue));
}
#endregion
#region TC-33
[Test]
public async Task GetOrSetObjectAsync_DoesNotCacheNullResult_AndInvokesFactoryOnSubsequentCalls()
{
const string key = "patients:latestObs:null";
var factoryCallCount = 0;
await _svc.GetOrSetObjectAsync(key, () =>
{
factoryCallCount++;
return Task.FromResult<string?>(null);
});
Assert.That(factoryCallCount, Is.EqualTo(1));
await _svc.GetOrSetObjectAsync(key, () =>
{
factoryCallCount++;
return Task.FromResult<string?>(null);
});
Assert.That(factoryCallCount, Is.EqualTo(2));
}
#endregion
#region TC-34
[Test]
public async Task GetOrSetObjectAsync_SecondCheckInLock_PreventsFactoryExecution_WhenValueAlreadyInsertedByFirstThread()
{
const string key = "patients:concurrent:abc";
var factoryCallCount = 0;
var task1InFactory = new SemaphoreSlim(0, 1);
var task1CanFinish = new SemaphoreSlim(0, 1);
async Task<string> ControlledFactory()
{
Interlocked.Increment(ref factoryCallCount);
task1InFactory.Release();
await task1CanFinish.WaitAsync();
return "first-result";
}
var t1 = _svc.GetOrSetObjectAsync(key, ControlledFactory);
await task1InFactory.WaitAsync();
var t2 = _svc.GetOrSetObjectAsync(key, () =>
{
Interlocked.Increment(ref factoryCallCount);
return Task.FromResult("second-result");
});
await Task.Delay(20);
task1CanFinish.Release();
var r1 = await t1;
var r2 = await t2;
Assert.That(factoryCallCount, Is.EqualTo(1));
Assert.That(r1, Is.EqualTo("first-result"));
Assert.That(r2, Is.EqualTo("first-result"));
}
#endregion
#region TC-35
[Test]
public async Task DeleteObjectAsync_RemovesKey_AndFactoryIsInvokedOnNextCall()
{
const string key = "patients:latestObs:delete";
await _svc.SetObjectAsync(key, "stored-value");
await _svc.DeleteObjectAsync(key);
var valueAfterDelete = await _svc.GetObjectAsync<string>(key);
Assert.That(valueAfterDelete, Is.Null);
var factoryCallCount = 0;
var result = await _svc.GetOrSetObjectAsync(key, () =>
{
factoryCallCount++;
return Task.FromResult("after-delete");
});
Assert.That(factoryCallCount, Is.EqualTo(1));
Assert.That(result, Is.EqualTo("after-delete"));
}
#endregion
#region TC-36
[Test]
public async Task DeleteByPatternAsync_RemovesMatchingKeys_AndKeepsNonMatchingKeys()
{
await _svc.SetObjectAsync("patients:abc", "val1");
await _svc.SetObjectAsync("patients:def", "val2");
await _svc.SetObjectAsync("appointments:xyz", "val3");
var deleted = await _svc.DeleteByPatternAsync("patients:");
Assert.That(deleted, Is.EqualTo(2));
var p1 = await _svc.GetObjectAsync<string>("patients:abc");
var p2 = await _svc.GetObjectAsync<string>("patients:def");
var a1 = await _svc.GetObjectAsync<string>("appointments:xyz");
Assert.That(p1, Is.Null);
Assert.That(p2, Is.Null);
Assert.That(a1, Is.EqualTo("val3"));
}
#endregion
#region TC-37
[Test]
public async Task CleanCache_RemovesAllKeys_AndFactoryIsInvokedAfterClean()
{
await _svc.SetObjectAsync("patients:1", "v1");
await _svc.SetObjectAsync("patients:2", "v2");
await _svc.SetObjectAsync("appointments:1", "v3");
await _svc.SetObjectAsync("configDisplays:1", "v4");
await _svc.SetObjectAsync("pumpObs:1", "v5");
_svc.CleanCache();
Assert.That(await _svc.GetObjectAsync<string>("patients:1"), Is.Null);
Assert.That(await _svc.GetObjectAsync<string>("patients:2"), Is.Null);
Assert.That(await _svc.GetObjectAsync<string>("appointments:1"), Is.Null);
Assert.That(await _svc.GetObjectAsync<string>("configDisplays:1"), Is.Null);
Assert.That(await _svc.GetObjectAsync<string>("pumpObs:1"), Is.Null);
var factoryCallCount = 0;
await _svc.GetOrSetObjectAsync("patients:1", () =>
{
factoryCallCount++;
return Task.FromResult("after-clean");
});
Assert.That(factoryCallCount, Is.EqualTo(1));
}
#endregion
}
@@ -0,0 +1,59 @@
namespace adas_core.Test.Services;
[TestFixture]
internal class CameraServiceTest
{
//CameraService cameraService;
//Mock<CameraService> cameraServiceMock;
//Mock<ILogger<CameraService>> logger;
//Dictionary<string, object> cameraSettings;
[SetUp]
public void Setup()
{
//cameraSettings = new Dictionary<string, object>()
//{
// { "camHost", "http://localhost:8080" },
// { "camUser", "username" },
// { "camPassword", "password" }
//};
//cameraServiceMock = new Mock<CameraService>();
//logger = new Mock<ILogger<CameraService>>();
//cameraService = new CameraService(
// logger.Object
// );
// Create a mock of the singleton class subscribers
//var mockSingleton = new Mock<ISubscribersService>();
//var subscribers = new List<WsSubscriber>();
// Set up the mock object to return a specific value when a method is called
//mockSingleton.Setup(x => x.GetSubscribers()).Returns(subscribers);
}
//TODO HttpWebResponse test
//[Test]
public void MaskStream_Return_Ok()
{
//bool activate = true;
//string coordinates = "100,100";
//var expectedResponse = new HttpResponseMessage();
////cameraServiceMock.Setup(c => c.GrabResponse(It.IsAny<string>(), It.IsAny<string>())).Returns(((string)null));
//// Act
//var response = cameraService.MaskStream(activate, coordinates, cameraSettings);
//// Assert
//Assert.IsNotNull(response);
//Assert.AreEqual(expectedResponse.StatusCode, response.StatusCode);
//Assert.AreEqual(expectedResponse.Content, response.Content);
}
}
@@ -0,0 +1,381 @@
using System.Security.Claims;
using adas_core.Application.Exceptions;
using adas_core.Application.Repositories.Interfaces;
using adas_core.Application.Services;
using adas_core.Application.Services.Interfaces;
using adas_core.Domain.Enums;
using adas_core.Domain.Models;
using adas_core.Domain.Models.AppSettings;
using adas_core.Domain.Models.MongoModels;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MongoDB.Bson;
using Moq;
using Options = Microsoft.Extensions.Options.Options;
namespace adas_core.Test.Services;
[TestFixture]
public class ConfigObservationServiceTest
{
private ConfigObservationService _service = null!;
private Mock<IConfigObservationRepository> _repo = null!;
private Mock<IUnitService> _unitSvc = null!;
private Mock<ILocalAuditService> _auditSvc = null!;
private Mock<IHttpContextAccessor> _http = null!;
private Mock<ICacheService> _cache = null!;
private Mock<ILogger<ConfigObservationService>> _logger = null!;
private IOptions<ApiSettings> _settings = null!;
private IOptions<CacheSettings> _cacheSettings = null!;
private static readonly ObjectId Id = ObjectId.GenerateNewId();
private static readonly ConfigObservation ConfigList = new()
{
Id = Id,
Name = "FC",
Code = "147842",
CodingSystem = "MDC",
ParentCode = "69965",
ParentName = "MDC_DEV_MON_PHYSIO_MULTI_PARAM_MDS",
MinAlert = 60,
MaxAlert = 100,
ForceAlert = true
};
private readonly List<ConfigObservation> _allConfigList =
[
new() { Id = ObjectId.GenerateNewId(), Name = "Hemoglobina", Code = "12345", CodingSystem = "SNM" },
new() { Id = ObjectId.GenerateNewId(), Name = "Glucemia", Code = "54321", CodingSystem = "SNM", OriginalName = "GLU" },
new() { Id = ObjectId.GenerateNewId(), Name = "Sodio", OriginalName = "Sodio" },
new()
{
Id = ObjectId.GenerateNewId(),
Name = "ph",
Code = "555",
CodingSystem = "MG4",
ParentCode = "3333",
ParentCodingSystem = "SNM"
},
new()
{
Id = ObjectId.GenerateNewId(),
Name = "SOFA",
Code = "278061009",
OriginalName = "SOFA",
CodingSystem = "SNM",
MinAlert = 10,
MinWarn = 14
},
ConfigList,
new() { Id = ObjectId.GenerateNewId(), Name = "Alarm_BlueCode", CodingSystem = "ADAS_EVENT" }
];
[SetUp]
public void Setup()
{
_repo = new Mock<IConfigObservationRepository>();
_unitSvc = new Mock<IUnitService>();
_auditSvc = new Mock<ILocalAuditService>();
_http = new Mock<IHttpContextAccessor>();
_cache = new Mock<ICacheService>();
_logger = new Mock<ILogger<ConfigObservationService>>();
var user = new ClaimsPrincipal(
new ClaimsIdentity([new Claim(ClaimTypes.Name, "TestUser")], "mock"));
_http.Setup(x => x.HttpContext).Returns(new DefaultHttpContext { User = user });
_settings = Options.Create(new ApiSettings
{
ConfigObservation = new ConfigObservationSettings
{
IgnoreUnknownObservation = false,
Refresh = null
},
});
_cacheSettings = Options.Create(new CacheSettings());
// KEY: mock cache to execute repository calls
_cache.Setup(c => c.GetOrSetObjectAsync(
It.IsAny<string>(),
It.IsAny<Func<Task<ICollection<ConfigObservation>>>>(),
It.IsAny<TimeSpan?>(),
It.IsAny<CancellationToken>()))
.Returns((string _, Func<Task<ICollection<ConfigObservation>>> f, TimeSpan? __, CancellationToken ___) => f());
_cache.Setup(c => c.GetOrSetObjectAsync(
It.IsAny<string>(),
It.IsAny<Func<Task<ConfigObservation>>>(),
It.IsAny<TimeSpan?>(),
It.IsAny<CancellationToken>()))
.Returns((string _, Func<Task<ConfigObservation>> f, TimeSpan? __, CancellationToken ___) => f());
_service = new ConfigObservationService(
_repo.Object,
_settings,
_cacheSettings,
_logger.Object,
_unitSvc.Object,
_http.Object,
_auditSvc.Object,
_cache.Object);
_repo.Setup(x => x.FindAll()).ReturnsAsync([ConfigList]);
}
// ---------------------------------------------------------
// TESTS
// ---------------------------------------------------------
[Test]
public async Task Get_config_observation_item_by_codingSystem_only_return_null()
{
var obs = new PatientObservation
{
CodingSystem = "ADAS_EVENT",
Code = "Pump_X",
Name = "Alarm_Pump_X"
};
var result = await _service.Get(obs);
Assert.That(result, Is.Null);
}
[Test]
public async Task Get_config_observation_item_by_code_and_codingSystem()
{
_repo.Setup(x => x.FindAll()).ReturnsAsync(_allConfigList);
var obs = new BasePatientObservation
{
Name = "Hemo^GBr",
Code = "12345",
CodingSystem = "SNM"
};
var result = await _service.Get(obs);
Assert.That(result, Is.Not.Null);
Assert.That(result!.Name, Is.EqualTo("Hemoglobina"));
}
[Test]
public async Task Get_config_observation_item_by_name()
{
_repo.Setup(x => x.FindAll()).ReturnsAsync(_allConfigList);
var obs = new BasePatientObservation { Name = "Hemoglobina" };
var result = await _service.Get(obs);
Assert.That(result!.Name, Is.EqualTo("Hemoglobina"));
}
[Test]
public async Task Get_config_observation_item_by_name_not_exist_returns_null()
{
_repo.Setup(x => x.FindAll()).ReturnsAsync(_allConfigList);
var obs = new BasePatientObservation { Name = "XXX" };
var result = await _service.Get(obs);
Assert.That(result, Is.Null);
}
[Test]
public async Task Get_config_by_code_and_parent()
{
_repo.Setup(x => x.FindAll()).ReturnsAsync(_allConfigList);
var obs = new BasePatientObservation
{
Code = "555",
CodingSystem = "MG4",
ParentData = new ParentDataClass
{
Code = "3333",
CodingSystem = "SNM"
}
};
var result = await _service.Get(obs);
Assert.That(result!.Name, Is.EqualTo("ph"));
}
[Test]
public async Task Map_unknown_ignore_true_returns_null()
{
_settings.Value.ConfigObservation!.IgnoreUnknownObservation = true;
_repo.Setup(x => x.FindAll()).ReturnsAsync([]);
var result = await _service.Map(new BasePatientObservation { Name = "XX" });
Assert.That(result, Is.Null);
}
[Test]
public async Task Map_unknown_ignore_false_returns_obs()
{
_settings.Value.ConfigObservation!.IgnoreUnknownObservation = false;
_repo.Setup(x => x.FindAll()).ReturnsAsync([]);
var obs = new BasePatientObservation { Name = "XX" };
var result = await _service.Map(obs);
Assert.That(result, Is.EqualTo(obs));
}
[Test]
public async Task Map_threshold_Ok()
{
_repo.Setup(x => x.FindAll()).ReturnsAsync(_allConfigList);
var obs = new PatientObservation
{
Name = "SOFA",
CodingSystem = "SNM",
Value = 14
};
var result = await _service.Map(obs);
Assert.That(result!.Status, Is.EqualTo(StatusEnum.Type.Ok));
}
[Test]
public async Task Map_threshold_Warning()
{
_repo.Setup(x => x.FindAll()).ReturnsAsync(_allConfigList);
var obs = new PatientObservation
{
Name = "SOFA",
CodingSystem = "SNM",
Value = 13
};
var result = await _service.Map(obs);
Assert.That(result!.Status, Is.EqualTo(StatusEnum.Type.Warning));
}
[Test]
public async Task Map_threshold_Alert()
{
_repo.Setup(x => x.FindAll()).ReturnsAsync(_allConfigList);
var obs = new PatientObservation
{
Name = "SOFA",
CodingSystem = "SNM",
Value = 9
};
var result = await _service.Map(obs);
Assert.That(result!.Status, Is.EqualTo(StatusEnum.Type.Alert));
}
[Test]
public async Task Map_parent_ok()
{
_repo.Setup(x => x.FindById(Id)).ReturnsAsync(ConfigList);
var fc = new PatientObservation
{
Id = Id,
Name = "FC",
Value = 70
};
var result = await _service.Map(fc);
Assert.That(result!.Status, Is.EqualTo(StatusEnum.Type.Ok));
}
[Test]
public async Task UpdateConfig_ok()
{
var newCfg = new ConfigObservation
{
Id = Id,
Name = "New",
Code = "X",
CodingSystem = "S"
};
_repo.Setup(r => r.FindById(Id)).ReturnsAsync(ConfigList);
_repo.Setup(r => r.Update(It.IsAny<ConfigObservation>())).ReturnsAsync(newCfg);
var result = await _service.UpdateConfig(newCfg);
Assert.That(result!.Name, Is.EqualTo("New"));
}
[Test]
public async Task UpdateConfig_notfound()
{
_repo
.Setup(r => r.FindById(Id))
.ReturnsAsync((ConfigObservation?)null);
Func<Task> act = () => _service.UpdateConfig(new ConfigObservation { Id = Id });
Assert.ThrowsAsync<NotFoundException>(act);
}
[Test]
public async Task CreateConfig_ok()
{
_repo.Setup(r => r.InsertOneAsyncAndReturn(ConfigList)).Returns(Task.FromResult(ConfigList));
var result = await _service.CreateConfig(ConfigList);
Assert.That(result, Is.EqualTo(ConfigList));
}
[Test]
public void CreateConfig_duplicate_throws()
{
_repo.Setup(r => r.FindById(It.IsAny<ObjectId>())).ReturnsAsync(ConfigList);
Func<Task> act = () => _service.CreateConfig(ConfigList);
Assert.ThrowsAsync<BadRequestException>(act);
}
[Test]
public async Task RemoveConfigItem_ok()
{
var deleted = new ConfigObservation { Id = ObjectId.GenerateNewId(), Name = "X" };
_repo.Setup(r => r.FindById(It.IsAny<ObjectId>())).ReturnsAsync(ConfigList);
_repo.Setup(r => r.Delete(It.IsAny<ObjectId>())).ReturnsAsync(deleted);
var result = await _service.RemoveConfigItem(ObjectId.GenerateNewId());
Assert.That(result, Is.EqualTo(deleted));
}
[Test]
public async Task RemoveConfigItem_null()
{
_repo.Setup(r => r.FindById(Id)).ReturnsAsync(ConfigList);
_repo.Setup(r => r.Delete(Id)).ReturnsAsync((ConfigObservation?)null);
var result = await _service.RemoveConfigItem(Id);
Assert.That(result, Is.Null);
}
}
@@ -0,0 +1,170 @@
using adas_core.Application.Repositories.Interfaces;
using adas_core.Application.Services;
using adas_core.Application.Services.Interfaces;
using adas_core.Domain.Enums;
using adas_core.Domain.Models;
using adas_core.Domain.Models.AppSettings;
using adas_core.Domain.Models.MongoModels;
using adas_core.Domain.Models.Pumps;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Moq;
using Options = Microsoft.Extensions.Options.Options;
namespace adas_core.Test.Services;
[TestFixture]
public class ConfigPumpsServiceTest
{
[SetUp]
public void Setup()
{
//configPumpsServiceMock = new Mock<IConfigPumpsService>();
_configPumpsRepositoryMock = new Mock<IConfigPumpsRepository>();
_optionsApiSettings = Options.Create(_apiSettings);
_logger = new Mock<ILogger<ConfigPumpsService>>();
_configPumpsService = new ConfigPumpsService(
_configPumpsRepositoryMock.Object,
_optionsApiSettings,
_logger.Object,
_httpContextAccessor.Object,
_auditService.Object);
}
private ConfigPumpsService _configPumpsService;
//Mock<IConfigPumpsService> configPumpsServiceMock;
private Mock<IConfigPumpsRepository> _configPumpsRepositoryMock;
private readonly ApiSettings _apiSettings = new()
{
ConfigPumpsRequired = true,
ConfigPumpsKey = "PV1",
ConfigObservation = new ConfigObservationSettings
{
Refresh = null
}
};
private IOptions<ApiSettings> _optionsApiSettings;
private Mock<ILogger<ConfigPumpsService>> _logger;
private readonly Mock<IHttpContextAccessor> _httpContextAccessor = new();
private readonly Mock<ILocalAuditService> _auditService = new();
private static readonly DateTime Now = DateTime.Now;
[Test]
public async Task Map_configPumpsRequired_false_Return_same_pump()
{
_optionsApiSettings.Value.ConfigPumpsRequired = false;
var pump = new PumpObservation
{
Code = "code",
Name = "name",
Time = Now
};
var configPumpsService = new ConfigPumpsService(
_configPumpsRepositoryMock.Object,
_optionsApiSettings,
_logger.Object,
_httpContextAccessor.Object,
_auditService.Object);
var result = await configPumpsService.Map(pump);
Assert.That(pump, Is.EqualTo(result));
}
[Test]
public async Task Map_not_alarmType_Return_same_pump()
{
_optionsApiSettings.Value.ConfigPumpsRequired = true;
var pump = new PumpObservation
{
Code = "code",
Name = "name",
Time = Now
};
var result = await _configPumpsService.Map(pump);
Assert.That(pump, Is.EqualTo(result));
}
[Test]
public async Task Map_Not_uiConfiguration_Return_same_pump()
{
_optionsApiSettings.Value.ConfigPumpsRequired = true;
var pump = new PumpObservation
{
Code = "code",
Name = "name",
Time = Now,
AlarmType = PumpEnum.AlarmType.Attention
};
var configPumpItem = new ConfigPumpItem();
var configPumps = new ConfigPumps
{
Id = "PV1",
Items = [configPumpItem]
};
_configPumpsRepositoryMock.Setup(c => c.FindById(It.IsAny<string>())).ReturnsAsync(configPumps);
var result = await _configPumpsService.Map(pump);
using (Assert.EnterMultipleScope())
{
Assert.That(pump, Is.EqualTo(result));
Assert.That(result.UiConfiguration, Is.Null);
}
}
[Test]
public async Task Map_uiConfiguration_Return_pump_uiConfiguration()
{
_optionsApiSettings.Value.ConfigPumpsRequired = true;
var pump = new PumpObservation
{
Code = "code",
Name = "name",
Time = Now,
AlarmType = PumpEnum.AlarmType.AirInLine
};
var configPumpItem = new ConfigPumpItem
{
AlarmType = PumpEnum.AlarmType.AirInLine,
UiConfiguration = new Dictionary<string, object> { { "screenAlarmLabel", PumpEnum.AlarmType.AirInLine } }
};
var configPumps = new ConfigPumps
{
Id = "PV1",
Items = [configPumpItem]
};
_configPumpsRepositoryMock.Setup(c => c.FindById(It.IsAny<string>())).ReturnsAsync(configPumps);
var result = await _configPumpsService.Map(pump);
Assert.That(result.UiConfiguration, Is.Not.Null);
using (Assert.EnterMultipleScope())
{
Assert.That(result.UiConfiguration, Has.Count.EqualTo(1));
Assert.That(result.UiConfiguration!["screenAlarmLabel"], Is.EqualTo(PumpEnum.AlarmType.AirInLine));
};
}
}
@@ -0,0 +1,157 @@
using adas_core.Application.Repositories.Interfaces;
using adas_core.Application.Services;
using adas_core.Domain.Models;
using adas_core.Domain.Models.AppSettings;
using adas_core.Domain.Models.MongoModels;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Moq;
using Options = Microsoft.Extensions.Options.Options;
namespace adas_core.Test.Services;
[TestFixture]
public class ConfigUnitsServiceTest
{
[SetUp]
public void Setup()
{
//configUnitsServiceMock = new Mock<IConfigUnitsService>();
_configUnitsRepositoryMock = new Mock<IConfigUnitsRepository>();
_optionsApiSettings = Options.Create(_apiSettings);
_logger = new Mock<ILogger<ConfigUnitsService>>();
_configUnitsService = new ConfigUnitsService(
_configUnitsRepositoryMock.Object,
_optionsApiSettings,
_logger.Object);
}
private ConfigUnitsService _configUnitsService;
//Mock<IConfigUnitsService> configUnitsServiceMock;
private Mock<IConfigUnitsRepository> _configUnitsRepositoryMock;
private readonly ApiSettings _apiSettings = new()
{
ConfigObservation = new ConfigObservationSettings
{
Refresh = null
}
};
private IOptions<ApiSettings> _optionsApiSettings;
private Mock<ILogger<ConfigUnitsService>> _logger;
private static readonly DateTime Now = DateTime.Now;
[Test]
public async Task Map_configUnitsRequired_false_Return_same_obs()
{
_optionsApiSettings.Value.ConfigUnitsRequired = false;
var obs = new PatientObservation
{
Code = "code",
CodingSystem = "SNM",
Name = "name",
Time = Now
};
var configUnitsService = new ConfigUnitsService(
_configUnitsRepositoryMock.Object,
_optionsApiSettings,
_logger.Object);
var result = await configUnitsService.Map(obs);
Assert.That(obs, Is.EqualTo(result));
}
[Test]
public async Task Map_not_units_Return_same_obs()
{
_optionsApiSettings.Value.ConfigUnitsRequired = true;
var obs = new PatientObservation
{
Code = "code",
CodingSystem = "SNM",
Name = "name",
Time = Now
};
var result = await _configUnitsService.Map(obs);
Assert.That(obs, Is.EqualTo(result));
}
[Test]
public async Task Map_Not_Find_Config_Return_same_obs()
{
_optionsApiSettings.Value.ConfigUnitsRequired = true;
var obs = new PatientObservation
{
Code = "code",
CodingSystem = "SNM",
Name = "name",
Time = Now
};
var configUnitItem = new ConfigUnitItem();
var configUnits = new ConfigUnits
{
Id = "PV1",
Items = [configUnitItem]
};
_configUnitsRepositoryMock.Setup(c => c.FindById(It.IsAny<string>())).ReturnsAsync(configUnits);
var result = await _configUnitsService.Map(obs);
using (Assert.EnterMultipleScope())
{
Assert.That(obs, Is.EqualTo(result));
Assert.That(result.Units, Is.Null);
};
}
[Test]
public async Task Map_configUnits_Return_obs_ConfigUnit()
{
_optionsApiSettings.Value.ConfigUnitsRequired = true;
var obs = new PatientObservation
{
Code = "code",
CodingSystem = "SNM",
Name = "name",
Time = Now,
Units = "MDC_DIM_X_G_PER_KG"
};
var configUnitItem = new ConfigUnitItem
{
Code = "MDC_DIM_X_G_PER_KG",
Value = "g/kg"
};
var configUnits = new ConfigUnits
{
Id = "PV1",
Items = [configUnitItem]
};
_configUnitsRepositoryMock.Setup(c => c.FindById(It.IsAny<string>())).ReturnsAsync(configUnits);
var result = await _configUnitsService.Map(obs);
Assert.That(result.Units, Is.Not.Null);
Assert.That(result.Units, Is.EqualTo("g/kg"));
}
}
@@ -0,0 +1,541 @@
using adas_core.Application.Repositories.Interfaces;
using adas_core.Application.Services;
using adas_core.Application.Services.Interfaces;
using adas_core.Domain.Enums;
using adas_core.Domain.Models;
using adas_core.Domain.Models.AppSettings;
using adas_core.Domain.Models.MongoModels;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MongoDB.Bson;
using Moq;
using Options = Microsoft.Extensions.Options.Options;
namespace adas_core.Test.Services;
[TestFixture]
public class DiagnosisServiceTest
{
[SetUp]
public void Setup()
{
_patientServiceMock = new Mock<IPatientService>();
_patientServiceLazy = new Lazy<IPatientService>(() => _patientServiceMock.Object);
//var sectionServiceMock = new Mock<ISectionService>();
//sectionServiceLazy = new Lazy<ISectionService>(() => sectionServiceMock.Object);
_diagnosisRepositoryMock = new Mock<IDiagnosisRepository>();
_diagnosisArchiveRepositoryMock = new Mock<IDiagnosisArchiveRepository>();
_clientMessageServiceMock = new Mock<IClientMessageService>();
_subscribersServiceMock = new Mock<ISubscribersService>();
_unitServiceMock = new Mock<IUnitService>();
_httpContextAccessor = new Mock<IHttpContextAccessor>();
_auditService = new Mock<ILocalAuditService>();
_calculatedObservationsServiceMock = new Mock<ICalculatedObservationsService>();
_calculatedObservationsServiceLazy =
new Lazy<ICalculatedObservationsService>(() => _calculatedObservationsServiceMock.Object);
_calculatedObservationsServiceMock.Setup(x => x.Map(It.IsAny<PatientDiagnosis>()))
.ReturnsAsync((PatientDiagnosis? value) => value);
_optionsApiSettings = Options.Create(_apiSettings);
_logger = new Mock<ILogger<DiagnosisService>>();
_diagnosisService = new DiagnosisService(
_patientServiceLazy,
//sectionServiceLazy,
_optionsApiSettings,
_diagnosisRepositoryMock.Object,
_diagnosisArchiveRepositoryMock.Object,
_logger.Object,
_clientMessageServiceMock.Object,
_subscribersServiceMock.Object,
_calculatedObservationsServiceLazy,
_httpContextAccessor.Object,
_auditService.Object,
_unitServiceMock.Object
);
// Create a mock of the singleton class subscribers
var mockSingleton = new Mock<ICalculatedObservationsService>();
// Set up the mock object to return a specific value when a method is called
mockSingleton.Setup(x => x.Map(It.IsAny<PatientDiagnosis>())).ReturnsAsync((PatientDiagnosis? value) => value);
}
private DiagnosisService _diagnosisService;
private Lazy<IPatientService> _patientServiceLazy;
private Mock<IPatientService> _patientServiceMock;
private Mock<IDiagnosisRepository> _diagnosisRepositoryMock;
private Mock<IDiagnosisArchiveRepository> _diagnosisArchiveRepositoryMock;
private Mock<IClientMessageService> _clientMessageServiceMock;
private Mock<ISubscribersService> _subscribersServiceMock;
private Mock<IUnitService> _unitServiceMock;
private Lazy<ICalculatedObservationsService> _calculatedObservationsServiceLazy;
private Mock<ICalculatedObservationsService> _calculatedObservationsServiceMock;
private Mock<IHttpContextAccessor> _httpContextAccessor = new();
private Mock<ILocalAuditService> _auditService = new();
private readonly ApiSettings _apiSettings = new()
{
DiagnosisSystem = "Snomed-CT",
DiagnosisCode = { "55607006" }
};
private IOptions<ApiSettings> _optionsApiSettings;
private Mock<ILogger<DiagnosisService>> _logger;
private static readonly DateTime Now = DateTime.Now;
private static readonly ObjectId PatientId = ObjectId.GenerateNewId();
// [Test]
// public void SaveRequest_patientNumber_and_pointOfCare_null_Return_not_insert()
// {
// var apiRequest = new ApiRequest();
//
// Assert.ThrowsAsync<Exception>(async () => await _diagnosisService.SaveRequest(apiRequest, null));
// }
// [Test]
// public void SaveRequest_Not_ORU_R01_Return_not_insert()
// {
// var patientObs = new Person
// {
// FirstName = "Miguel",
// LastName = "Villanueva",
// Ids = new Dictionary<string, string> { { "MR", "437537" } }
// };
//
// var patient = new Patient
// {
// Id = ObjectId.GenerateNewId(),
// UnitString = "UCI5C",
// Bed = "Box4",
// PatientNumber = "437537",
// Person = patientObs
//
// };
//
// var apiRequest = new ApiRequest
// {
// Location = new PatientLocation("UCI5C", "Box4"),
// Patient = patientObs,
// PatientNumber = "437537",
// Type = "ORU_R11",
// PatientId = PatientId.ToString(),
// MessageTime = Now
// };
//
// _patientServiceMock.Setup(cm => cm.FindPatientByApiRequest(apiRequest)).ReturnsAsync(patient);
//
// Assert.ThrowsAsync<Exception>(async () => await _diagnosisService.SaveRequest(apiRequest, null));
// }
[Test]
public async Task SaveRequest_Not_FindPatient_Return_not_insert()
{
var apiRequest = new ApiRequest
{
Location = new PatientLocation("UCI5C", "Box4"),
PatientNumber = "437537",
Type = "ORU_R01",
PatientId = PatientId.ToString(),
MessageTime = Now
};
_patientServiceMock.Setup(cm => cm.FindPatientByApiRequest(apiRequest)).ReturnsAsync((Patient?)null);
await _diagnosisService.SaveRequest(apiRequest, null);
_diagnosisRepositoryMock.Verify(d => d.InsertOneAsync(It.IsAny<PatientDiagnosis>()), Times.Never);
}
[Test]
public async Task SaveRequest_Not_Observations_Return_not_insert()
{
var patientObs = new Person
{
FirstName = "Miguel",
LastName = "Villanueva",
Ids = new Dictionary<string, string> { { "MR", "437537" } }
};
var patient = new Patient
{
Id = ObjectId.GenerateNewId(),
UnitString = "UCI5C",
Bed = "Box4",
PatientNumber = "437537",
Person = patientObs
};
var apiRequest = new ApiRequest
{
Location = new PatientLocation("UCI5C", "Box4"),
ObservationData = new ObservationData
{
Code = "302147001",
CodingSystem = "SNM",
Value = "Aire; Contacto; Preventivo",
Text = "Aislamiento",
Time = Now
},
Patient = patientObs,
PatientNumber = "437537",
Type = "ORU_R01",
PatientId = PatientId.ToString(),
MessageTime = Now
};
_patientServiceMock.Setup(cm => cm.FindPatientByApiRequest(apiRequest)).ReturnsAsync(patient);
await _diagnosisService.SaveRequest(apiRequest, null);
_diagnosisRepositoryMock.Verify(d => d.InsertOneAsync(It.IsAny<PatientDiagnosis>()), Times.Never);
}
[Test]
public async Task SaveRequest_Not_DiagnosisCodeSettings_Return_not_insert()
{
var patientObs = new Person
{
FirstName = "Miguel",
LastName = "Villanueva",
Ids = new Dictionary<string, string> { { "MR", "437537" } }
};
var patient = new Patient
{
Id = ObjectId.GenerateNewId(),
UnitString = "UCI5C",
Bed = "Box4",
PatientNumber = "437537",
Person = patientObs
};
var apiRequest = new ApiRequest
{
Location = new PatientLocation("UCI5C", "Box4"),
ObservationData = new ObservationData
{
Code = "302147001",
CodingSystem = "SNM",
Value = "Aire; Contacto; Preventivo",
Text = "Aislamiento",
Time = Now
},
Observations =
[
new PatientObservation
{
Code = "263490005",
CodingSystem = "SNM",
Name = "Estado",
Status = StatusEnum.Type.Ok,
Time = Now,
Value = "Sin alergias conocidas"
},
new PatientObservation
{
Code = "300916003",
CodingSystem = "SNM",
Name = "¿Alergia al látex?",
Status = StatusEnum.Type.Ok,
Time = Now,
Value = "No"
}
],
Patient = patientObs,
PatientNumber = "437537",
Type = "ORU_R01",
PatientId = PatientId.ToString(),
MessageTime = Now
};
Options.Create(new ApiSettings());
var diagnosisService = new DiagnosisService(
_patientServiceLazy,
//sectionServiceLazy,
_optionsApiSettings,
_diagnosisRepositoryMock.Object,
_diagnosisArchiveRepositoryMock.Object,
_logger.Object,
_clientMessageServiceMock.Object,
_subscribersServiceMock.Object,
_calculatedObservationsServiceLazy,
_httpContextAccessor.Object,
_auditService.Object,
_unitServiceMock.Object);
_patientServiceMock.Setup(cm => cm.FindPatientByApiRequest(apiRequest)).ReturnsAsync(patient);
await diagnosisService.SaveRequest(apiRequest, null);
_diagnosisRepositoryMock.Verify(d => d.InsertOneAsync(It.IsAny<PatientDiagnosis>()), Times.Never);
}
// [Test]
// public async Task SaveRequest_DiagnosisCodeSettings_Return_insert()
// {
// var patientObs = new Person
// {
// FirstName = "Miguel",
// LastName = "Villanueva",
// Ids = new Dictionary<string, string> { { "MR", "437537" } }
// };
//
// var patient = new Patient
// {
// Id = ObjectId.GenerateNewId(),
// UnitString = "UCI5C",
// Bed = "Box4",
// PatientNumber = "437537",
// Person = patientObs
// };
//
// var apiRequest = new ApiRequest
// {
// Location = new PatientLocation("UCI5C", "Box4"),
// ObservationData= new ObservationData
// {
// Code = "55607006",
// CodingSystem = "SNM",
// Value = "Diagnosis",
// Time = Now
//
// },
// Observations = new List<PatientObservation>
// {
// new()
// {
// Code = "272099008",
// CodingSystem = "SNM",
// Name = "description",
// Status = ObservationStatus.Ok,
// Time = Now,
// Value = "Daño axonal difuso"
// },
// new()
// {
// Code = "1000000013",
// CodingSystem = "SNM",
// Name = "label",
// Status = ObservationStatus.Ok,
// Time = Now,
// Value = "Daño axonal difuso"
// },
// new()
// {
// Code = "1000000014",
// CodingSystem = "SNM",
// Name = "code",
// Status = ObservationStatus.Ok,
// Time = Now,
// Value = "262693007"
// },
// new()
// {
// Code = "394731006",
// CodingSystem = "SNM",
// Name = "state",
// Status = ObservationStatus.Ok,
// Time = Now,
// Value = "state"
// },
// new()
// {
// Code = "272125009",
// CodingSystem = "SNM",
// Name = "category",
// Status = ObservationStatus.Ok,
// Time = Now,
// Value = "category"
// },
// new()
// {
// Code = "398201009",
// CodingSystem = "SNM",
// Name = "starTime",
// Status = ObservationStatus.Ok,
// Time = Now,
// Value = Now.AddHours(1)
// },
// new()
// {
// Code = "397898000",
// CodingSystem = "SNM",
// Name = "endTime",
// Status = ObservationStatus.Ok,
// Time = Now,
// Value = Now.AddHours(2)
// }
//
// },
// Patient = patientObs,
// PatientNumber = "437537",
// Type = "ORU_R01",
// PatientId = PatientId.ToString(),
// MessageTime = Now
// };
//
// _diagnosisService = new DiagnosisService(
// _patientServiceLazy,
// //sectionServiceLazy,
// _optionsApiSettings,
// _diagnosisRepositoryMock.Object,
// _diagnosisArchiveRepositoryMock.Object,
// _logger.Object,
// _clientMessageServiceMock.Object,
// _subscribersServiceMock.Object,
// _calculatedObservationsServiceLazy,
// _unitServiceMock.Object);
//
// _patientServiceMock.Setup(cm => cm.FindPatientByApiRequest(apiRequest)).ReturnsAsync(patient);
//
// await _diagnosisService.SaveRequest(apiRequest, null);
//
// _diagnosisRepositoryMock.Verify(d => d.InsertOneAsync(It.IsAny<PatientDiagnosis>()), Times.Once);
// _diagnosisRepositoryMock.Verify(d => d.UpdateOneAsync(It.IsAny<ObjectId>(),It.IsAny<PatientDiagnosis>()), Times.Never);
// }
// [Test]
// public async Task SaveRequest_DiagnosisCodeSettings_Return_Update()
// {
// var patientObs = new Person
// {
// FirstName = "Miguel",
// LastName = "Villanueva",
// Ids = new Dictionary<string, string> { { "MR", "437537" } }
// };
//
// var patient = new Patient
// {
// Id = ObjectId.GenerateNewId(),
// UnitString = "UCI5C",
// Bed = "Box4",
// PatientNumber = "437537",
// Person = patientObs
// };
//
// var apiRequest = new ApiRequest
// {
// Location = new PatientLocation("UCI5C", "Box4"),
// ObservationData= new ObservationData
// {
// Code = "55607006",
// CodingSystem = "SNM",
// Value = "Diagnosis",
// Time = Now
//
// },
// Observations = new List<PatientObservation>
// {
// new()
// {
// Code = "272099008",
// CodingSystem = "SNM",
// Name = "description",
// Status = ObservationStatus.Ok,
// Time = Now,
// Value = "Daño axonal difuso"
// },
// new()
// {
// Code = "1000000013",
// CodingSystem = "SNM",
// Name = "label",
// Status = ObservationStatus.Ok,
// Time = Now,
// Value = "Daño axonal difuso"
// },
// new()
// {
// Code = "1000000014",
// CodingSystem = "SNM",
// Name = "code",
// Status = ObservationStatus.Ok,
// Time = Now,
// Value = "262693007"
// },
// new()
// {
// Code = "394731006",
// CodingSystem = "SNM",
// Name = "state",
// Status = ObservationStatus.Ok,
// Time = Now,
// Value = "state"
// },
// new()
// {
// Code = "272125009",
// CodingSystem = "SNM",
// Name = "category",
// Status = ObservationStatus.Ok,
// Time = Now,
// Value = "category"
// },
// new()
// {
// Code = "398201009",
// CodingSystem = "SNM",
// Name = "starTime",
// Status = ObservationStatus.Ok,
// Time = Now,
// Value = Now.AddHours(1)
// },
// new()
// {
// Code = "397898000",
// CodingSystem = "SNM",
// Name = "endTime",
// Status = ObservationStatus.Ok,
// Time = Now,
// Value = Now.AddHours(2)
// }
//
// },
// Patient = patientObs,
// PatientNumber = "437537",
// Type = "ORU_R01",
// PatientId = patient.Id.ToString(),
// MessageTime = Now
// };
//
// var patientDiagnosis = new PatientDiagnosis
// {
// Id = ObjectId.GenerateNewId(),
// Time = Now
// };
//
// _diagnosisService = new DiagnosisService(
// _patientServiceLazy,
// //sectionServiceLazy,
// _optionsApiSettings,
// _diagnosisRepositoryMock.Object,
// _diagnosisArchiveRepositoryMock.Object,
// _logger.Object,
// _clientMessageServiceMock.Object,
// _subscribersServiceMock.Object,
// _calculatedObservationsServiceLazy,
// _unitServiceMock.Object);
//
// _patientServiceMock.Setup(cm => cm.FindPatientByApiRequest(apiRequest)).ReturnsAsync(patient);
// _diagnosisRepositoryMock.Setup(d => d.FindByPatientIdAndCode(patient.Id, "262693007", "Snomed-CT")).ReturnsAsync(patientDiagnosis);
//
// await _diagnosisService.SaveRequest(apiRequest, null);
//
// //_diagnosisRepositoryMock.Verify(d => d.InsertOneAsync(It.IsAny<PatientDiagnosis>()), Times.Never);
// _diagnosisRepositoryMock.Verify(d => d.UpdateOneAsync(It.IsAny<ObjectId>(), It.IsAny<PatientDiagnosis>()), Times.Once);
// }
}
@@ -0,0 +1,218 @@
using System.Security.Claims;
using adas_core.Application.Exceptions;
using adas_core.Application.Repositories.Interfaces;
using adas_core.Application.Services;
using adas_core.Application.Services.Interfaces;
using adas_core.Domain.Models;
using adas_core.Domain.Models.MongoModels;
using adas_core.Test.Utilities;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using MongoDB.Bson;
using Moq;
namespace adas_core.Test.Services;
public class DischargeServiceTest
{
private readonly Mock<ILocalAuditService> _auditServiceMock = new();
private readonly Mock<IClientMessageService> _clientMessageServiceMock = new();
private readonly Mock<IDischargeRepository> _dischargeRepositoryMock = new();
private readonly Mock<IHttpContextAccessor> _httpContextAccessorMock = new();
private readonly Mock<ILogger<DischargeService>> _loggerMock = new();
private readonly Mock<IMasterListServiceFactory> _masterMock = new();
private readonly Mock<Lazy<IPatientService>> _patientServiceLazyMock = new();
private readonly Mock<IPointOfCareService> _pointOfCareServiceMock = new();
private readonly Mock<ISubscribersService> _subscribersServiceMock = new();
private readonly Mock<IUnitService> _unitServiceMock = new();
private DischargeService _dischargeService = null!;
[SetUp]
public void Setup()
{
var userClaims = new ClaimsPrincipal(new ClaimsIdentity([
new Claim(ClaimTypes.Name, "TestUser")
], "mock"));
var httpContextMock = new DefaultHttpContext
{
User = userClaims
};
_httpContextAccessorMock.Setup(accessor => accessor.HttpContext)
.Returns(httpContextMock);
_dischargeService = new DischargeService(
_loggerMock.Object,
_subscribersServiceMock.Object,
_dischargeRepositoryMock.Object,
_patientServiceLazyMock.Object,
_clientMessageServiceMock.Object,
_pointOfCareServiceMock.Object,
_httpContextAccessorMock.Object,
_auditServiceMock.Object,
_unitServiceMock.Object,
_masterMock.Object);
}
[Test]
public async Task DeleteDischargeAsync_WhenDischargeExists_DeletesDischarge()
{
// Arrange
var dischargeId = ObjectId.GenerateNewId();
var discharge = new Discharge { Id = dischargeId };
_dischargeRepositoryMock.Setup(repo => repo.FindById(dischargeId)).ReturnsAsync(discharge);
// Act
await _dischargeService.DeleteDischargeAsync(discharge);
// Assert
_dischargeRepositoryMock.Verify(repo => repo.Delete(dischargeId), Times.Once);
}
//necesita el pocservice
// [Test]
// public async Task GetDischargeByIdAsync_WhenDischargeExists_ReturnsDischarge()
// {
// // Arrange
// var dischargeId = ObjectId.GenerateNewId();
// var discharge = new Discharge { Id = dischargeId };
// _dischargeRepositoryMock.Setup(repo => repo.FindById(dischargeId)).ReturnsAsync(discharge);
//
// // Act
// var result = await _dischargeService.GetDischargeByIdAsync(dischargeId);
//
// // Assert
// Assert.That(result, Is.EqualTo(discharge));
// }
[Test]
public void GetDischargeByIdAsync_WhenExceptionOccurs_ReturnsNullAndLogsError()
{
// Arrange
var dischargeId = ObjectId.GenerateNewId();
// Act and assert
Func<Task> act = async () => await _dischargeService.GetDischargeByIdAsync(dischargeId);
Assert.ThrowsAsync<NotFoundException>(act);
}
[Test]
public async Task GetDischargesAsync_WhenNoException_ReturnsDischarges()
{
// Arrange
var discharge = TestUtilities.CreateValidDischarge();
var discharges = new List<Discharge> { discharge };
_dischargeRepositoryMock.Setup(repo => repo.FindAll()).ReturnsAsync(discharges);
// Act
var result = await _dischargeService.GetDischargesAsync();
var resultList = result.ToList();
// Assert
Assert.That(resultList.First().Id, Is.EqualTo(discharges.First().Id));
}
//necesita el pocservice
// [Test]
// public async Task GetDischargeByPatientId_WhenDischargeExists_ReturnsDischarge()
// {
// // Arrange
// var discharge = TestUtilities.CreateValidDischarge();
// _dischargeRepositoryMock.Setup(repo => repo.GetByPatientId(discharge.PatientId)).ReturnsAsync(discharge);
//
// // Act
// var result = await _dischargeService.GetDischargeByPatientId(discharge.PatientId);
//
// // Assert
// Assert.That(result?.Id, Is.EqualTo(discharge.Id));
// }
[Test]
public async Task InsertDischarge_WhenInsertionSuccessful_ReturnsInsertedDischarge()
{
// Arrange
var dischargeId = ObjectId.GenerateNewId();
var discharge = new Discharge { Id = dischargeId };
_dischargeRepositoryMock.Setup(repo => repo.InsertOneAsync(discharge)).Returns(Task.CompletedTask);
_dischargeRepositoryMock.Setup(repo => repo.FindById(dischargeId)).ReturnsAsync(discharge);
// Act
var result = await _dischargeService.InsertDischarge(discharge);
// Assert
Assert.That(result, Is.EqualTo(discharge));
}
[Test]
public void InsertDischarge_WhenInsertionFails_ReturnsNullAndLogsError()
{
// Arrange
var discharge = new Discharge { Id = ObjectId.GenerateNewId() };
var exception = new Exception("Failed to insert discharge");
_dischargeRepositoryMock.Setup(repo => repo.InsertOneAsync(discharge)).ThrowsAsync(exception);
// Assert
Func<Task> act = async () => await _dischargeService.InsertDischarge(discharge);
Assert.ThrowsAsync<Exception>(act);
}
[Test]
public async Task GetDischargeByLocation_WhenDischargeExists_ReturnsDischarge()
{
// Arrange
var location = new PatientLocation("UnitName", "Bed", "Room");
var discharge = new Discharge();
_dischargeRepositoryMock.Setup(repo => repo.GetDischargeByLocation(location)).ReturnsAsync(discharge);
// Act
var result = await _dischargeService.GetDischargeByLocation(location);
// Assert
Assert.That(result, Is.EqualTo(discharge));
}
[Test]
public async Task GetDischargeByLocation_WhenExceptionOccurs_ReturnsNullAndLogsError()
{
// Arrange
var location = new PatientLocation("UnitName", "Bed", "Room");
var exception = new Exception("Failed to retrieve discharge by location");
_dischargeRepositoryMock.Setup(repo => repo.GetDischargeByLocation(location)).ThrowsAsync(exception);
// Act
var result = await _dischargeService.GetDischargeByLocation(location);
// Assert
Assert.That(result, Is.Null);
}
// [Test]
// public async Task GetDischargeByPointOfCareId_WhenDischargeExists_ReturnsDischarge()
// {
// // Arrange
// var discharge = TestUtilities.CreateValidDischarge();
// _dischargeRepositoryMock.Setup(repo => repo.GetDischargeByPointOfCareId(discharge.PointOfCareId)).ReturnsAsync(discharge);
//
// // Act
// var result = await _dischargeService.GetDischargeByPointOfCareId(discharge.PointOfCareId);
//
// // Assert
// Assert.That(result, Is.EqualTo(discharge));
// }
[Test]
public async Task GetDischargeByPointOfCareId_WhenExceptionOccurs_ReturnsNullAndLogsError()
{
// Arrange
var poc = ObjectId.GenerateNewId();
var exception = new Exception("Failed to retrieve discharge by PointOfCareId");
_dischargeRepositoryMock.Setup(repo => repo.GetDischargeByPointOfCareId(poc)).ThrowsAsync(exception);
// Act
var result = await _dischargeService.GetDischargeByPointOfCareId(poc);
// Assert
Assert.That(result, Is.Null);
}
}
@@ -0,0 +1,375 @@
using System.Security.Claims;
using adas_core.Application.Exceptions;
using adas_core.Application.Repositories.Interfaces;
using adas_core.Application.Services;
using adas_core.Application.Services.Interfaces;
using adas_core.Domain.Enums;
using adas_core.Domain.Models.AppSettings;
using adas_core.Domain.Models.MongoModels;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using MongoDB.Bson;
using Moq;
using static NUnit.Framework.Assert;
using Options = Microsoft.Extensions.Options.Options;
namespace adas_core.Test.Services;
[TestFixture]
public class DisplayServiceTest
{
private Mock<ICacheService> _mockCacheService = null!;
private Mock<IDisplayRepository> _mockDisplayRepository = null!;
private Mock<IPointOfCareService> _mockPointOfCareService = null!;
private Mock<IDisplayConfigService> _mockDisplayConfigService = null!;
private Mock<IUserRepository> _mockUserRepository = null!;
private Mock<IAuthService> _authServiceMock = null!;
private Mock<ISubscribersService> _mockSubscribersService = null!;
private Mock<IClientMessageService> _mockClientMessageService = null!;
private Mock<Lazy<IUnitService>> _mockUnitService = null!;
private Mock<IPermissionService> _mockPermissionService = null!;
private Lazy<IPermissionService> _lazyMockPermission = null!;
private Mock<ILogger<DisplayService>> _mockLogger = null!;
private readonly Mock<IHttpContextAccessor> _httpContextAccessorMock = new();
private readonly Mock<ILocalAuditService> _auditServiceMock = new();
private DisplayService _displayService = null!;
[SetUp]
public void SetUp()
{
_mockCacheService = new Mock<ICacheService>();
_mockDisplayRepository = new Mock<IDisplayRepository>();
_mockPointOfCareService = new Mock<IPointOfCareService>();
_mockDisplayConfigService = new Mock<IDisplayConfigService>();
_mockUserRepository = new Mock<IUserRepository>();
_authServiceMock = new Mock<IAuthService>();
_mockSubscribersService = new Mock<ISubscribersService>();
_mockClientMessageService = new Mock<IClientMessageService>();
_mockUnitService = new Mock<Lazy<IUnitService>>();
_mockPermissionService = new Mock<IPermissionService>();
_lazyMockPermission = new Lazy<IPermissionService>(() => _mockPermissionService.Object);
_mockLogger = new Mock<ILogger<DisplayService>>();
var claims = new ClaimsPrincipal(
new ClaimsIdentity([new Claim(ClaimTypes.Name, "TestUser")], "mock"));
_httpContextAccessorMock.Setup(a => a.HttpContext).Returns(new DefaultHttpContext { User = claims });
var cacheSettings = Options.Create(new CacheSettings());
_displayService = new DisplayService(
_mockDisplayRepository.Object,
_mockPointOfCareService.Object,
_mockUnitService.Object,
_mockDisplayConfigService.Object,
_mockSubscribersService.Object,
_mockClientMessageService.Object,
_mockUserRepository.Object,
_authServiceMock.Object,
_mockLogger.Object,
_httpContextAccessorMock.Object,
_auditServiceMock.Object,
_lazyMockPermission,
_mockCacheService.Object,
cacheSettings
);
}
// -----------------------------------------------------------
// InsertOne
// -----------------------------------------------------------
[Test]
public async Task InsertOne_ShouldInsertDisplay()
{
var display = new Display
{
Name = "Test Display",
Type = DisplayConfigEnums.DisplayType.DisplayNurse
};
var defaultCfg = new DisplayConfig { Id = ObjectId.GenerateNewId(), Type = display.Type };
_mockDisplayConfigService.Setup(s => s.GetDefaultConfig(display.Type)).ReturnsAsync(defaultCfg);
_mockDisplayRepository.Setup(r => r.InsertOneAsync(display))
.Returns(Task.CompletedTask);
var result = await _displayService.InsertOne(display);
That(result, Is.EqualTo(display));
_mockDisplayRepository.Verify(r => r.InsertOneAsync(display), Times.Once);
}
// -----------------------------------------------------------
// GetById
// -----------------------------------------------------------
[Test]
public async Task GetById_ShouldReturnDisplay()
{
var id = ObjectId.GenerateNewId();
var d = new Display { Id = id, Name = "D1" };
_mockDisplayRepository.Setup(r => r.GetById(id)).ReturnsAsync(d);
var result = await _displayService.GetById(id);
That(result, Is.EqualTo(d));
}
// -----------------------------------------------------------
// GetAllByUser - userName null
// -----------------------------------------------------------
[Test]
public async Task GetAllByUser_ShouldReturnEmpty_WhenUserNameNull()
{
var result = await _displayService.GetAllByUser(null);
That(result, Is.Empty);
}
// -----------------------------------------------------------
// GetAllByUser - Admin case
// -----------------------------------------------------------
[Test]
public async Task GetAllByUser_ShouldReturnDisplays_WhenAdmin()
{
// Arrange
const string userName = "admin";
var adminId = ObjectId.GenerateNewId();
var unitId = ObjectId.GenerateNewId();
var user = new User
{
Id = adminId,
UserName = userName,
Authorization =
[
new Authorization { UnitId = unitId.ToString(), Rol = nameof(PermissionEnum.RolesType.AuthAdmin) }
]
};
// 1) Usuario + authorities
_mockUserRepository.Setup(r => r.GetByUserAndAuthoritesName(userName))
.ReturnsAsync(user);
_authServiceMock.Setup(a => a.GetUserAuthorities(adminId))
.ReturnsAsync(user.Authorization);
// 2) Displays por UnitId
var d1 = new Display { Id = ObjectId.GenerateNewId(), Name = "D1", UnitId = unitId };
var d2 = new Display { Id = ObjectId.GenerateNewId(), Name = "D2", UnitId = unitId };
var displays = new List<Display> { d1, d2 };
_mockDisplayRepository.Setup(r => r.GetByUnitId(unitId))
.ReturnsAsync(displays);
// 3) GetInfo (rama base) → caché debe devolver el display haciendo el factory
_mockDisplayRepository.Setup(r => r.GetById(d1.Id)).ReturnsAsync(d1);
_mockDisplayRepository.Setup(r => r.GetById(d2.Id)).ReturnsAsync(d2);
_mockCacheService
.Setup(c => c.GetOrSetObjectAsync(
It.IsAny<string>(),
It.IsAny<Func<Task<Display?>>>(),
It.IsAny<TimeSpan?>(),
It.IsAny<CancellationToken>()))
.Returns((string _, Func<Task<Display?>> factory, TimeSpan? _, CancellationToken _) => factory());
// 4) Permisos (si es null, el servicio NO añade el display)
_mockPermissionService
.Setup(p => p.GetPermissionsForUnit(unitId.ToString(), user))
.ReturnsAsync(new DisplayPermissionTypes(
new UserActions(true,true,true,true,true),
new UserActions(true,true,true,true,true),
new UserActions(true,true,true,true,true),
new UserActions(true,true,true,true,true),
new UserActions(true,true,true,true,true),
new UserActions(true,true,true,true,true),
new UserActions(true,true,true,true,true),
true
));
// Act
var result = await _displayService.GetAllByUser(userName);
// Assert
That(result, Has.Count.EqualTo(2));
using (Assert.EnterMultipleScope())
{
That(result.Any(r => r.Display != null && r.Display.Id == d1.Id), Is.True);
That(result.Any(r => r.Display != null && r.Display.Id == d2.Id), Is.True);
}
}
// -----------------------------------------------------------
// GetByType
// -----------------------------------------------------------
[Test]
public async Task GetByType_ShouldReturnDisplays()
{
var cfgId = ObjectId.GenerateNewId();
var cfg = new DisplayConfig { Id = cfgId, Type = DisplayConfigEnums.DisplayType.DisplayNurse };
var display = new Display { Id = ObjectId.GenerateNewId(), DisplayConfigId = cfgId, Name = "D" };
_mockDisplayConfigService.Setup(s => s.GetByType(cfg.Type))
.ReturnsAsync([cfg]);
_mockDisplayRepository.Setup(r => r.GetByConfigId(cfgId))
.ReturnsAsync([display]);
var result = await _displayService.GetByType(cfg.Type);
That(result.Count, Is.EqualTo(1));
That(result[0], Is.EqualTo(display));
}
[Test]
public async Task GetByType_ShouldReturnEmpty_WhenNoConfigsFound()
{
_mockDisplayConfigService.Setup(s => s.GetByType(It.IsAny<DisplayConfigEnums.DisplayType>()))
.ReturnsAsync([]);
var result = await _displayService.GetByType(DisplayConfigEnums.DisplayType.DisplayNurse);
That(result, Is.Empty);
}
// -----------------------------------------------------------
// GetByPointOfCare
// -----------------------------------------------------------
[Test]
public async Task GetByPointOfCare_ShouldReturnDisplays()
{
var poc = new PointOfCare { Id = ObjectId.GenerateNewId() };
var d = new Display { Id = ObjectId.GenerateNewId(), Name = "Display" };
_mockDisplayRepository.Setup(r => r.GetByPointOfCare(poc))
.ReturnsAsync([d]);
var result = await _displayService.GetByPointOfCare(poc);
That(result, Has.Count.EqualTo(1));
}
// -----------------------------------------------------------
// GetByConfigId
// -----------------------------------------------------------
[Test]
public async Task GetByConfigId_ShouldReturnDisplays()
{
var cfgId = ObjectId.GenerateNewId();
var d = new Display { Id = ObjectId.GenerateNewId(), DisplayConfigId = cfgId, Name = "display1"};
_mockDisplayRepository.Setup(r => r.GetByConfigId(cfgId))
.ReturnsAsync([d]);
var result = await _displayService.GetByConfigId(cfgId);
That(result, Has.Count.EqualTo(1));
}
// -----------------------------------------------------------
// GetByName
// -----------------------------------------------------------
[Test]
public void GetByName_ShouldThrow_WhenNotFound()
{
_mockDisplayRepository.Setup(r => r.GetByName("X"))
.ReturnsAsync((Display?)null);
Func<Task> act = () => _displayService.GetByName("X");
Assert.ThrowsAsync<NotFoundException>(act);
}
// -----------------------------------------------------------
// GetInfo
// -----------------------------------------------------------
[Test]
public async Task GetInfo_ShouldReturnDisplayWithPoc()
{
var id = ObjectId.GenerateNewId();
var cfgId = ObjectId.GenerateNewId();
var pocId = ObjectId.GenerateNewId();
var display = new Display
{
Id = id,
Name = "Display",
DisplayConfigId = cfgId,
PointOfCareIdList = [pocId]
};
_mockCacheService
.Setup(c => c.GetOrSetObjectAsync(
It.IsAny<string>(),
It.IsAny<Func<Task<Display?>>>(),
It.IsAny<TimeSpan?>(),
It.IsAny<CancellationToken>()))
.Returns((string _, Func<Task<Display?>> factory, TimeSpan? _, CancellationToken _) => factory());
_mockDisplayRepository.Setup(r => r.GetById(id)).ReturnsAsync(display);
_mockDisplayConfigService.Setup(s => s.GetById(cfgId))
.ReturnsAsync(new DisplayConfig { Id = cfgId });
var poc = new PointOfCare { Id = pocId };
_mockPointOfCareService.Setup(s => s.GetInfo(pocId, null, true, It.IsAny<CancellationToken>()))
.ReturnsAsync(poc);
var result = await _displayService.GetInfo(id, "user", [], null, true, true, false);
That(result, Is.Not.Null);
That(result!.PointOfCares.First(), Is.EqualTo(poc));
}
// -----------------------------------------------------------
// GetByUnitId
// -----------------------------------------------------------
[Test]
public async Task GetByUnitId_ShouldReturnDisplays()
{
var id = ObjectId.GenerateNewId();
var d = new Display { Id = ObjectId.GenerateNewId(), UnitId = id , Name = "display1"};
_mockDisplayRepository.Setup(r => r.GetByUnitId(id))
.ReturnsAsync([d]);
var result = await _displayService.GetByUnitId(id);
That(result, Has.Count.EqualTo(1));
}
// -----------------------------------------------------------
// UpdatePointOfCareList
// -----------------------------------------------------------
[Test]
public void UpdatePointOfCareList_ShouldThrow_WhenDisplayNotFound()
{
var id = ObjectId.GenerateNewId();
_mockDisplayRepository.Setup(r => r.GetById(id))
.ReturnsAsync((Display?)null);
Func<Task> act = () => _displayService.UpdatePointOfCareList(id, []);
Assert.ThrowsAsync<NotFoundException>(act);
}
// -----------------------------------------------------------
// UpdateConfigPreset
// -----------------------------------------------------------
[Test]
public void UpdateConfigPreset_ShouldThrow_WhenUpdateFails()
{
var id = ObjectId.GenerateNewId();
var cfgId = ObjectId.GenerateNewId();
_mockDisplayRepository.Setup(r => r.UpdateConfigPreset(id, cfgId))
.ReturnsAsync((Display?)null);
Func<Task> act = () => _displayService.UpdateConfigPreset(id, cfgId);
Assert.ThrowsAsync<NotFoundException>(act);
}
}
@@ -0,0 +1,487 @@
using adas_core.Application.Repositories.Interfaces;
using adas_core.Application.Services;
using adas_core.Application.Services.Interfaces;
using adas_core.Domain.Models.AppSettings;
using adas_core.Domain.Models.GroupedObservations;
using adas_core.Domain.Utils;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MongoDB.Bson;
using Moq;
using static adas_core.Domain.Enums.GroupedObservationEnum;
namespace adas_core.Test.Services;
[TestFixture]
public class GroupedObservationServiceTest
{
[SetUp]
public void Setup()
{
var configObservationService = new Mock<IConfigObservationService>();
var observationRepository = new Mock<IObservationRepository>();
_logger = new Mock<ILogger<GroupedObservationService>>();
_groupedObservationService = new GroupedObservationService(
observationRepository.Object, configObservationService.Object,
_logger.Object, Mock.Of<ICacheService>(), Options.Create(new ApiSettings()), Options.Create(new CacheSettings()));
}
private GroupedObservationService _groupedObservationService;
private Mock<ILogger<GroupedObservationService>> _logger;
[Test]
public void Generate_Shift_Observations()
{
var dateTime = DateTime.Now;
if (dateTime.Day <= 2) dateTime = dateTime.AddDays(2);
var result = new List<BsonDocument>
{
GenerateBsonDocument(dateTime.Year, dateTime.Month, dateTime.Day, 12, 30, "FC", 100, Result.Last, null),
GenerateBsonDocument(dateTime.Year, dateTime.Month, dateTime.Day, 10, 30, "FC", 108, Result.Last, null),
GenerateBsonDocument(dateTime.Year, dateTime.Month, dateTime.Day, 9, 30, "FC", 106, Result.Last, null),
GenerateBsonDocument(dateTime.Year, dateTime.Month, dateTime.Day, 5, 30, "FC", 112, Result.Last, null),
GenerateBsonDocument(dateTime.Year, dateTime.Month, dateTime.Day, 4, 30, "FC", 105, Result.Last, null),
GenerateBsonDocument(dateTime.Year, dateTime.Month, dateTime.Day - 1, 23, 30, "FC", 190, Result.Last, null),
GenerateBsonDocument(dateTime.Year, dateTime.Month, dateTime.Day - 1, 19, 30, "FC", 120, Result.Last, null),
GenerateBsonDocument(dateTime.Year, dateTime.Month, dateTime.Day - 1, 15, 30, "FC", 130, Result.Last, null),
GenerateBsonDocument(dateTime.Year, dateTime.Month, dateTime.Day - 1, 12, 30, "FC", 140, Result.Last, null),
GenerateBsonDocument(dateTime.Year, dateTime.Month, dateTime.Day - 1, 09, 30, "FC", 150, Result.Last, null),
GenerateBsonDocument(dateTime.Year, dateTime.Month, dateTime.Day - 2, 15, 30, "FC", 150, Result.Last, null)
};
var groupedField = new GroupedField
{
StartTimeShift = ["08:00", "15:00", "22:00"],
Max = 36,
Result = [Result.Last]
};
var shiftObservations = _groupedObservationService.GenerateShiftObservations(result, groupedField);
var shift1ObsToday = shiftObservations.Count(s => s.Get("shift") == 0 && s.Get("day") == dateTime.Day);
var shift1ObsYesterday = shiftObservations.Count(s => s.Get("shift") == 0 && s.Get("day") == dateTime.Day - 1);
var shift2ObsYesterday = shiftObservations.Count(s => s.Get("shift") == 1 && s.Get("day") == dateTime.Day - 1);
var shif3ObsYesterday = shiftObservations.Count(s => s.Get("shift") == 2 && s.Get("day") == dateTime.Day - 1);
var shiftTwoDaysAgo = shiftObservations.Count(s => s.Get("shift") == 1 && s.Get("day") == dateTime.Day - 2);
using (Assert.EnterMultipleScope())
{
Assert.That(shift1ObsToday, Is.EqualTo(3));
Assert.That(shif3ObsYesterday, Is.EqualTo(3));
Assert.That(shift2ObsYesterday, Is.EqualTo(2));
Assert.That(shift1ObsYesterday, Is.EqualTo(2));
Assert.That(shiftTwoDaysAgo, Is.EqualTo(1));
};
}
[Test]
public void Calculate_Shift_Observations()
{
var dateTime = DateTime.Now;
if (dateTime.Day <= 2) dateTime = dateTime.AddDays(2);
var groupedField = new GroupedField
{
StartTimeShift = ["08:00", "15:00", "22:00"],
Max = 36,
Result = [Result.Sum]
};
var result = new List<BsonDocument>
{
GenerateBsonDocument(dateTime.Year, dateTime.Month, dateTime.Day, 12, 30, "FC", 100, Result.Sum, null),
GenerateBsonDocument(dateTime.Year, dateTime.Month, dateTime.Day, 10, 30, "FC", 108, Result.Sum, null),
GenerateBsonDocument(dateTime.Year, dateTime.Month, dateTime.Day, 9, 30, "FC", 106, Result.Sum, null),
GenerateBsonDocument(dateTime.Year, dateTime.Month, dateTime.Day, 5, 30, "FC", 112, Result.Sum, null),
GenerateBsonDocument(dateTime.Year, dateTime.Month, dateTime.Day, 4, 30, "FC", 105, Result.Sum, null),
GenerateBsonDocument(dateTime.Year, dateTime.Month, dateTime.Day - 1, 23, 30, "FC", 190, Result.Sum, null),
GenerateBsonDocument(dateTime.Year, dateTime.Month, dateTime.Day - 1, 19, 30, "FC", 120, Result.Sum, null),
GenerateBsonDocument(dateTime.Year, dateTime.Month, dateTime.Day - 1, 15, 30, "FC", 130, Result.Sum, null),
GenerateBsonDocument(dateTime.Year, dateTime.Month, dateTime.Day - 1, 12, 30, "FC", 140, Result.Sum, null),
GenerateBsonDocument(dateTime.Year, dateTime.Month, dateTime.Day - 1, 09, 30, "FC", 150, Result.Sum, null),
GenerateBsonDocument(dateTime.Year, dateTime.Month, dateTime.Day - 2, 15, 30, "FC", 150, Result.Sum, null)
};
var shiftObservations = _groupedObservationService.GenerateShiftObservations(result, groupedField);
_groupedObservationService.CalculateShiftObservations(shiftObservations, groupedField);
var shift1ObsToday = shiftObservations.First(s => s.Get("shift") == 0 && s.Get("day") == dateTime.Day);
var shift1ObsYesterday = shiftObservations.First(s => s.Get("shift") == 0 && s.Get("day") == dateTime.Day - 1);
var shift2ObsYesterday = shiftObservations.First(s => s.Get("shift") == 1 && s.Get("day") == dateTime.Day - 1);
var shif3ObsYesterday = shiftObservations.First(s => s.Get("shift") == 2 && s.Get("day") == dateTime.Day - 1);
var shiftTwoDaysAgo = shiftObservations.First(s => s.Get("shift") == 1 && s.Get("day") == dateTime.Day - 2);
using (Assert.EnterMultipleScope())
{
Assert.That(shift1ObsToday.Get("sum")?.ToInt32(), Is.EqualTo(314));
Assert.That(shif3ObsYesterday.Get("sum")?.ToInt32(), Is.EqualTo(407));
Assert.That(shift2ObsYesterday.Get("sum")?.ToInt32(), Is.EqualTo(250));
Assert.That(shift1ObsYesterday.Get("sum")?.ToInt32(), Is.EqualTo(290));
Assert.That(shiftTwoDaysAgo.Get("sum")?.ToInt32(), Is.EqualTo(150));
};
}
// [Test]
// public void Calculate_Half_Time_Observations()
// {
// /*
// 09:18 - Toma 1: 50/100/75
// 09:38 - Toma 2: 52/102/76
// 10:07 - Toma 3: 54/101/72
// 10:18 - Toma 4: 51/102/73
// 10:58 - Toma 5: 52/107/79
// 12:04 - Toma 6: 60/120/90
//
// El api convierte a
//
// 09h - Toma 2: 52/102/76
// 10h - Toma 4: 51/102/73
// 11h - Toma 5: 52/107/79
// 12h- Toma 6: 60/120/90
// */
//
//
// var dateTime = DateTime.Now;
//
// var values9 = new BsonArray {
// new BsonDocument
// {
// { "value", 50},
// { "time", new BsonDateTime(new DateTime(2021,3,10,9,18,0))},
//
// },
// new BsonDocument
// {
// { "value", 100},
// { "time", new BsonDateTime(new DateTime(2021,3,10,9,38,0))}
// }
// };
//
// var values10 = new BsonArray {
// new BsonDocument
// {
// { "value", 50},
// { "time", new BsonDateTime(new DateTime(2021,3,10,10,7,0))}
// },
// new BsonDocument
// {
// { "value", 60},
// { "time", new BsonDateTime(new DateTime(2021,3,10,10,18,0))}
// },
// new BsonDocument
// {
// { "value", 70},
// { "time", new BsonDateTime(new DateTime(2021,3,10,10,58,0))}
// }
// };
//
// var values11 = new BsonArray
// {
//
// };
//
// var values12 = new BsonArray
// {
// new BsonDocument
// {
// { "value", 50},
// { "time", new BsonDateTime(new DateTime(2021,3,10,12,04,0))}
// }
// };
//
//
// var result = new List<BsonDocument>()
// {
// GenerateBsonDocument(dateTime.Year,dateTime.Month,dateTime.Day,9,0,"TAM", 100, Result.HalfHour,values9),
// GenerateBsonDocument(dateTime.Year,dateTime.Month,dateTime.Day,10,0,"TAM", 100, Result.HalfHour,values10),
// GenerateBsonDocument(dateTime.Year,dateTime.Month,dateTime.Day,11,0,"TAM", 100, Result.HalfHour,values11),
// GenerateBsonDocument(dateTime.Year,dateTime.Month,dateTime.Day,12,0,"TAM", 100, Result.HalfHour,values12)
// };
//
// var halfObservations = _groupedObservationService.CalculateHalfHourObservations(result);
//
// Assert.That(halfObservations, Has.Count.EqualTo(4));
// Assert.Multiple(() =>
// {
// Assert.That(halfObservations[0].GetByCodeSysAndCode("halfhour")?.AsBsonDocument.GetByCodeSysAndCode("value")?.AsInt32, Is.EqualTo(100));
// Assert.That(halfObservations[1].GetByCodeSysAndCode("halfhour")?.AsBsonDocument.GetByCodeSysAndCode("value")?.AsInt32, Is.EqualTo(60));
// Assert.That(halfObservations[2].GetByCodeSysAndCode("halfhour")?.AsBsonDocument.GetByCodeSysAndCode("value")?.AsInt32, Is.EqualTo(70));
// Assert.That(halfObservations[3].GetByCodeSysAndCode("halfhour")?.AsBsonDocument.GetByCodeSysAndCode("value")?.AsInt32, Is.EqualTo(50));
// });
// }
[Test]
public async Task Calculate_Last_Filled_Observations_should_add_Minus_4_hour_to_complete_last_five_hours()
{
var dateTime = DateTime.Now;
//Falta el -4 tiene que crearlo el calculate last filled observation
var result = new List<BsonDocument>
{
GenerateBsonDocument(dateTime.AddHours(-5).Year, dateTime.AddHours(-5).Month, dateTime.AddHours(-5).Day,
dateTime.AddHours(-5).Hour, 0, "TAM", 100, Result.LastFilled, null),
GenerateBsonDocument(dateTime.AddHours(-3).Year, dateTime.AddHours(-3).Month, dateTime.AddHours(-3).Day,
dateTime.AddHours(-3).Hour, 0, "TAM", 100, Result.LastFilled, null),
GenerateBsonDocument(dateTime.AddHours(-2).Year, dateTime.AddHours(-2).Month, dateTime.AddHours(-2).Day,
dateTime.AddHours(-2).Hour, 0, "TAM", 100, Result.LastFilled, null),
GenerateBsonDocument(dateTime.AddHours(-1).Year, dateTime.AddHours(-1).Month, dateTime.AddHours(-1).Day,
dateTime.AddHours(-1).Hour, 0, "TAM", 100, Result.LastFilled, null)
};
var groupedField = new GroupedField
{
Max = 5,
Name = "TAM",
Regularity = Regularity.Hour
};
var patientId = ObjectId.GenerateNewId();
var lastFilledObservations =
await _groupedObservationService.CalculateLastFilledObservations(result, groupedField, patientId);
using (Assert.EnterMultipleScope())
{
Assert.That(lastFilledObservations, Has.Count.EqualTo(5));
Assert.That(
lastFilledObservations.Exists(i => i.Get("time")?.ToLocalTime().Hour == dateTime.AddHours(-5).Hour),
Is.True);
Assert.That(
lastFilledObservations.Exists(i => i.Get("time")?.ToLocalTime().Hour == dateTime.AddHours(-4).Hour),
Is.True);
Assert.That(
lastFilledObservations.Exists(i => i.Get("time")?.ToLocalTime().Hour == dateTime.AddHours(-3).Hour),
Is.True);
Assert.That(
lastFilledObservations.Exists(i => i.Get("time")?.ToLocalTime().Hour == dateTime.AddHours(-2).Hour),
Is.True);
Assert.That(
lastFilledObservations.Exists(i => i.Get("time")?.ToLocalTime().Hour == dateTime.AddHours(-1).Hour),
Is.True);
};
}
[Test]
public async Task Calculate_Last_Filled_Observations_should_add_Minus_1_hour_to_complete_last_five_hours()
{
var dateTime = DateTime.Now;
//Falta el -4 tiene que crearlo el calculate last filled observation
var result = new List<BsonDocument>
{
GenerateBsonDocument(dateTime.AddHours(-5).Year, dateTime.AddHours(-5).Month, dateTime.AddHours(-5).Day,
dateTime.AddHours(-5).Hour, 0, "TAM", 100, Result.LastFilled, null),
GenerateBsonDocument(dateTime.AddHours(-4).Year, dateTime.AddHours(-4).Month, dateTime.AddHours(-4).Day,
dateTime.AddHours(-4).Hour, 0, "TAM", 100, Result.LastFilled, null),
GenerateBsonDocument(dateTime.AddHours(-3).Year, dateTime.AddHours(-3).Month, dateTime.AddHours(-3).Day,
dateTime.AddHours(-3).Hour, 0, "TAM", 100, Result.LastFilled, null),
GenerateBsonDocument(dateTime.AddHours(-2).Year, dateTime.AddHours(-2).Month, dateTime.AddHours(-2).Day,
dateTime.AddHours(-2).Hour, 0, "TAM", 100, Result.LastFilled, null)
};
var groupedField = new GroupedField
{
Max = 5,
Name = "TAM",
Regularity = Regularity.Hour
};
var patientId = ObjectId.GenerateNewId();
var lastFilledObservations =
await _groupedObservationService.CalculateLastFilledObservations(result, groupedField, patientId);
using (Assert.EnterMultipleScope())
{
Assert.That(lastFilledObservations, Has.Count.EqualTo(5));
Assert.That(
lastFilledObservations.Exists(i => i.Get("time")?.ToLocalTime().Hour == dateTime.AddHours(-5).Hour),
Is.True);
Assert.That(
lastFilledObservations.Exists(i => i.Get("time")?.ToLocalTime().Hour == dateTime.AddHours(-4).Hour),
Is.True);
Assert.That(
lastFilledObservations.Exists(i => i.Get("time")?.ToLocalTime().Hour == dateTime.AddHours(-3).Hour),
Is.True);
Assert.That(
lastFilledObservations.Exists(i => i.Get("time")?.ToLocalTime().Hour == dateTime.AddHours(-2).Hour),
Is.True);
Assert.That(
lastFilledObservations.Exists(i => i.Get("time")?.ToLocalTime().Hour == dateTime.AddHours(-1).Hour),
Is.True);
};
}
[Test]
public void FillHoursObservations()
{
/*
09:18 - Toma 1: 50/100/75
09:38 - Toma 2: 52/102/76
10:07 - Toma 3: 54/101/72
10:18 - Toma 4: 51/102/73
10:58 - Toma 5: 52/107/79
12:04 - Toma 6: 60/120/90
El api convierte a
09h - Toma 2: 52/102/76
10h - Toma 4: 51/102/73
11h - Toma 5: 52/107/79
12h- Toma 6: 60/120/90
*/
var groupedField = new GroupedField
{
Max = 5,
Name = "TAM",
Regularity = Regularity.Hour
};
var dateTime =
new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 12, 30, 0).ToUniversalTime();
var values9 = new BsonArray
{
new BsonDocument
{
{ "value", 50 },
{
"time",
new BsonDateTime(
new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, 9, 18, 0).ToUniversalTime())
}
},
new BsonDocument
{
{ "value", 100 },
{
"time",
new BsonDateTime(
new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, 9, 38, 0).ToUniversalTime())
}
}
};
var values10 = new BsonArray
{
new BsonDocument
{
{ "value", 50 },
{
"time",
new BsonDateTime(
new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, 10, 7, 0).ToUniversalTime())
}
},
new BsonDocument
{
{ "value", 60 },
{
"time",
new BsonDateTime(new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, 10, 18, 0)
.ToUniversalTime())
}
},
new BsonDocument
{
{ "value", 70 },
{
"time",
new BsonDateTime(new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, 10, 58, 0)
.ToUniversalTime())
}
}
};
var values12 = new BsonArray
{
new BsonDocument
{
{ "value", 50 },
{
"time",
new BsonDateTime(new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, 12, 04, 0)
.ToUniversalTime())
}
}
};
var result = new List<BsonDocument>
{
GenerateBsonDocument(dateTime.Year, dateTime.Month, dateTime.Day, 9, 0, "TAM", 100, Result.HalfHour,
values9),
GenerateBsonDocument(dateTime.Year, dateTime.Month, dateTime.Day, 10, 0, "TAM", 100, Result.HalfHour,
values10),
GenerateBsonDocument(dateTime.Year, dateTime.Month, dateTime.Day, 12, 0, "TAM", 100, Result.HalfHour,
values12)
};
var halfObservations = _groupedObservationService.CalculateHalfHourObservations(result);
var fillHoursObservations = _groupedObservationService.FillHours(halfObservations, groupedField);
Assert.That(fillHoursObservations, Is.Not.Empty);
}
private static BsonDocument GenerateBsonDocument(int? year, int? month, int? day, int? hour, int? minute,
string name, object value, Result resultType, BsonArray? all)
{
var result = new BsonDocument
{
{
"_id", new BsonDocument
{
{ "year", year ?? new DateTime().Year },
{ "month", month ?? new DateTime().Month },
{ "day", day ?? new DateTime().Day },
{ "hour", hour ?? new DateTime().Hour },
{ "minute", minute ?? new DateTime().Minute },
{ "name", name }
}
},
{ "time", new BsonDateTime(new DateTime((int)year!, (int)month!, (int)day!, (int)hour!, (int)minute!, 0)) }
};
/*
{resultType.ToString().ToLower(), new BsonDocument{
{"time", new BsonDateTime(new System.DateTime((int)year, (int)month, (int)day, (int)hour, (int)minute,0)) },
{"value", value.ToString() }
}},
{ "time", new BsonDateTime(new System.DateTime((int)year, (int)month, (int)day, (int)hour, (int)minute,0)) },
};
*/
if (resultType != Result.HalfHour && resultType != Result.Sum && resultType != Result.Count
&& resultType != Result.Min && resultType != Result.Average && resultType != Result.Max)
result.Add(resultType.ToString().ToLower(), new BsonDocument
{
{ "time", new BsonDateTime(new DateTime((int)year, (int)month, (int)day, (int)hour, (int)minute, 0)) },
{ "value", value.ToString() }
});
else
result.AddRange(new Dictionary<string, object> { { resultType.ToString().ToLower(), value } });
if (all != null) result.Add("all", all);
return result;
}
}
@@ -0,0 +1,136 @@
using adas_core.Application.Repositories.Interfaces;
using adas_core.Application.Services;
using adas_core.Application.Services.Interfaces;
using adas_core.Domain.Enums;
using adas_core.Domain.Models.MongoModels;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Moq;
namespace adas_core.Test.Services;
[TestFixture]
[NonParallelizable]
internal class HistoricalConfigChangesServiceTest
{
[SetUp]
public void Setup()
{
_mockRepo = new Mock<IHistoricalConfigChangesRepository>();
_mockLogger = new Mock<ILogger<HistoricalConfigChangesService>>();
_service = new HistoricalConfigChangesService(_mockRepo.Object, _mockLogger.Object, _httpContextAccessor.Object,
_auditService.Object);
}
private HistoricalConfigChangesService _service;
private Mock<IHistoricalConfigChangesRepository> _mockRepo;
private Mock<ILogger<HistoricalConfigChangesService>> _mockLogger;
private readonly Mock<IHttpContextAccessor> _httpContextAccessor = new();
private readonly Mock<ILocalAuditService> _auditService = new();
[Test]
public async Task FindLastConfigChanges_ReturnsLastConfigChange()
{
// Arrange
var configType = DisplayConfigEnums.ConfigTypes.ObservationCfg;
var mockResult = new List<HistoricalConfigChanges>
{
new() // Mock object with desired properties
};
_mockRepo.Setup(r => r.FindLastHistoricalConfigChangesByType(configType, 10)).ReturnsAsync(mockResult);
// Act
var result = await _service.FindLastConfigChanges(configType);
// Assert
Assert.That(result, Is.Not.Null);
// Further assertions based on the expected result
}
[Test]
public async Task InsertOne_WhenExceptionOccurs_ReturnsNull()
{
// Arrange
var mockChange = new HistoricalConfigChanges();
_mockRepo.Setup(r => r.InsertOneAsync(mockChange)).Throws(new Exception());
// Act
var result = await _service.InsertOne(mockChange);
// Assert
Assert.That(result, Is.Null);
}
[Test]
public async Task GetAll_ReturnsAllConfigChanges()
{
// Arrange
var mockResult = new List<HistoricalConfigChanges>
{
new(),
new()
};
_mockRepo.Setup(r => r.FindAll()).ReturnsAsync(mockResult);
// Act
var result = await _service.GetAll();
// Assert
Assert.That(result, Has.Count.EqualTo(2));
}
[Test]
public async Task GetByType_ReturnsCorrectAmountOfConfigs()
{
// Arrange
var configType = DisplayConfigEnums.ConfigTypes.ObservationCfg;
var mockResult = new List<HistoricalConfigChanges>
{
new(),
new(),
new()
};
_mockRepo.Setup(r => r.FindLastHistoricalConfigChangesByType(configType, 3)).ReturnsAsync(mockResult);
// Act
var result = await _service.GetByType(configType, 3);
// Assert
Assert.That(result, Has.Count.EqualTo(3));
}
[Test]
public async Task GetByUser_ReturnsCorrectConfigs()
{
// Arrange
var user = "TestUser";
var mockResult = new List<HistoricalConfigChanges>
{
new(),
new()
};
_mockRepo.Setup(r => r.FindLastHistoricalConfigChangesByUser(user, null, 2)).ReturnsAsync(mockResult);
// Act
var result = await _service.GetByUser(user, null, 2);
// Assert
Assert.That(result, Has.Count.EqualTo(2));
}
[Test]
public async Task UpdateHistoricalConfigChange_WhenExceptionOccurs_ReturnsNull()
{
// Arrange
var mockChange = new HistoricalConfigChanges();
_mockRepo.Setup(r => r.Update(mockChange)).Throws(new Exception());
// Act
var result = await _service.UpdateHistoricalConfigChange(mockChange);
// Assert
Assert.That(result, Is.Null);
}
}
@@ -0,0 +1,121 @@
using System.Collections.Concurrent;
using System.Reflection;
using adas_core.Application.Services.Caching;
namespace adas_core.Test.Services;
[TestFixture]
public class InMemoryLockProviderTest
{
private InMemoryLockProvider _provider = null!;
[SetUp]
public void SetUp()
{
_provider = new InMemoryLockProvider();
}
private ConcurrentDictionary<string, SemaphoreSlim> GetLocks()
{
var field = typeof(InMemoryLockProvider)
.GetField("_locks", BindingFlags.NonPublic | BindingFlags.Instance);
return (ConcurrentDictionary<string, SemaphoreSlim>)field!.GetValue(_provider)!;
}
#region TC-50
[Test]
public async Task AcquireAsync_ReturnsTrue_AndCreatesEntryInLocksDictionary()
{
var result = await _provider.AcquireAsync("key", TimeSpan.FromSeconds(1));
Assert.That(result, Is.True);
var locks = GetLocks();
Assert.That(locks.ContainsKey("key"), Is.True);
}
#endregion
#region TC-51
[Test]
public async Task AcquireAsync_ReturnsFalse_WhenSemaphoreOccupiedAndTimeoutExpires()
{
await _provider.AcquireAsync("key", TimeSpan.FromSeconds(5));
var result = await _provider.AcquireAsync("key", TimeSpan.FromMilliseconds(100));
Assert.That(result, Is.False);
await _provider.ReleaseAsync("key");
var locks = GetLocks();
Assert.That(locks["key"].CurrentCount, Is.EqualTo(1));
}
#endregion
#region TC-52
[Test]
public async Task ReleaseAsync_MakesSemaphoreAvailableForNextAcquire()
{
await _provider.AcquireAsync("key", TimeSpan.FromSeconds(1));
await _provider.ReleaseAsync("key");
var result = await _provider.AcquireAsync("key", TimeSpan.FromSeconds(1));
Assert.That(result, Is.True);
var locks = GetLocks();
Assert.That(locks["key"].CurrentCount, Is.EqualTo(0));
await _provider.ReleaseAsync("key");
Assert.That(locks["key"].CurrentCount, Is.EqualTo(1));
}
#endregion
#region TC-53
[Test]
public async Task ReleaseAsync_DoesNotThrow_WhenCalledWithoutPriorAcquire()
{
await _provider.ReleaseAsync("nonexistent-key");
await _provider.AcquireAsync("key", TimeSpan.FromSeconds(1));
await _provider.ReleaseAsync("key");
await _provider.ReleaseAsync("key");
}
#endregion
#region TC-54
[Test]
public async Task AcquireAsync_IsThreadSafe_OnlyOneHolderAtATime_SingleSemaphorePerKey()
{
const string key = "same-key";
const int threadCount = 10;
var acquiredCount = 0;
var currentHolders = 0;
var tasks = Enumerable.Range(0, threadCount).Select(_ => Task.Run(async () =>
{
var acquired = await _provider.AcquireAsync(key, TimeSpan.FromSeconds(10));
Assert.That(acquired, Is.True);
var current = Interlocked.Increment(ref currentHolders);
Assert.That(current, Is.EqualTo(1));
Interlocked.Increment(ref acquiredCount);
await Task.Delay(5);
Interlocked.Decrement(ref currentHolders);
await _provider.ReleaseAsync(key);
})).ToArray();
await Task.WhenAll(tasks);
Assert.That(acquiredCount, Is.EqualTo(threadCount));
var locks = GetLocks();
Assert.That(locks.ContainsKey(key), Is.True);
Assert.That(locks.Keys.Count(k => k == key), Is.EqualTo(1));
}
#endregion
}
@@ -0,0 +1,70 @@
using adas_core.Application.Repositories.Interfaces;
using adas_core.Application.Services.Interfaces;
using adas_core.Domain.Enums;
using adas_core.Domain.Models.AppSettings;
using adas_core.Domain.Models.MongoModels;
using adas_core.module.LightBeacons.Services;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MongoDB.Bson;
using Moq;
using Options = Microsoft.Extensions.Options.Options;
namespace adas_core.Test.Services;
[TestFixture]
public class LightBeaconServiceTest
{
[SetUp]
public void Setup()
{
_optionsApiSettings = Options.Create(_apiSettings);
_pocService = new Mock<IPointOfCareService>();
_clientMessageService = new Mock<IClientMessageService>();
_subscribersService = new Mock<ISubscribersService>();
_logger = new Mock<ILogger<LightBeaconService>>();
_lightBeaconRepository = new Mock<ILightBeaconRepository>();
_lightBeaconService = new LightBeaconService(
_optionsApiSettings,
_logger.Object,
_clientMessageService.Object,
_subscribersService.Object,
_pocService.Object,
_lightBeaconRepository.Object
);
}
private LightBeaconService _lightBeaconService = null!;
private readonly ApiSettings _apiSettings = new()
{
BalizaUrl = "http://localhost/info.html",
BalizaPassword = "password"
};
private IOptions<ApiSettings> _optionsApiSettings = null!;
private Mock<ILogger<LightBeaconService>> _logger = null!;
private Mock<IPointOfCareService> _pocService = null!;
private Mock<IClientMessageService> _clientMessageService = null!;
private Mock<ISubscribersService> _subscribersService = null!;
private Mock<ILightBeaconRepository> _lightBeaconRepository = null!;
[Ignore("Integration test")]
[Test]
public async Task GetBeaconColor()
{
var patient = new Patient
{
UnitId = ObjectId.GenerateNewId(),
PointOfCareId = ObjectId.GenerateNewId()
};
var color = await _lightBeaconService.GetColor(patient.PointOfCareId.Value);
Assert.That(color, Is.EqualTo(
LightBeaconColor.Off));
}
}
@@ -0,0 +1,185 @@
using System.Security.Claims;
using adas_core.Application.Repositories.Interfaces;
using adas_core.Application.Services;
using adas_core.Application.Services.Interfaces;
using adas_core.Domain.Enums;
using adas_core.Domain.Models.AppSettings;
using adas_core.Domain.Models.Masters;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MongoDB.Bson;
using Moq;
namespace adas_core.Test.Services;
[TestFixture]
public class MasterListServiceTest
{
[SetUp]
public void Setup()
{
_loggerMock = new Mock<ILogger<MasterListService<MasterList>>>();
_serviceProviderMock = new Mock<IServiceProvider>();
_clientMessageServiceMock = new Mock<IClientMessageService>();
_subscribersServiceMock = new Mock<ISubscribersService>();
_unitServiceMock = new Mock<IUnitService>();
_displayServiceMock = new Mock<IDisplayService>();
_repositoryMock = new Mock<IMasterListRepository<MasterList>>();
_patientServiceMock = new Mock<IPatientService>();
_dischargeServiceMock = new Mock<IDischargeService>();
_admissionServiceMock = new Mock<IAdmissionService>();
_apiSettingsMock = new Mock<IOptions<ApiSettings>>();
var userClaims = new ClaimsPrincipal(new ClaimsIdentity([
new Claim(ClaimTypes.Name, "TestUser")
], "mock"));
var httpContextMock = new DefaultHttpContext
{
User = userClaims
};
_httpContextAccessorMock.Setup(accessor => accessor.HttpContext)
.Returns(httpContextMock);
var apiSettings = new ApiSettings
{
PathToDisplayAssets = ["path/to/assets"]
};
_apiSettingsMock.Setup(ap => ap.Value).Returns(apiSettings);
_serviceProviderMock.Setup(sp => sp.GetService(typeof(IMasterListRepository<MasterList>)))
.Returns(_repositoryMock.Object);
_service = new MasterListService<MasterList>(
_loggerMock.Object,
_serviceProviderMock.Object,
new Lazy<IClientMessageService>(() => _clientMessageServiceMock.Object),
_subscribersServiceMock.Object,
new Lazy<IUnitService>(() => _unitServiceMock.Object),
new Lazy<IDisplayService>(() => _displayServiceMock.Object),
new Lazy<IPatientService>(() => _patientServiceMock.Object),
new Lazy<IDischargeService>(() => _dischargeServiceMock.Object),
new Lazy<IAdmissionService>(() => _admissionServiceMock.Object),
_apiSettingsMock.Object,
_httpContextAccessorMock.Object,
_auditServiceMock.Object
);
}
private Mock<ILogger<MasterListService<MasterList>>> _loggerMock = null!;
private Mock<IServiceProvider> _serviceProviderMock = null!;
private Mock<IClientMessageService> _clientMessageServiceMock = null!;
private Mock<ISubscribersService> _subscribersServiceMock = null!;
private Mock<IUnitService> _unitServiceMock = null!;
private Mock<IDisplayService> _displayServiceMock = null!;
private Mock<IPatientService> _patientServiceMock = null!;
private Mock<IDischargeService> _dischargeServiceMock = null!;
private Mock<IAdmissionService> _admissionServiceMock = null!;
private Mock<IMasterListRepository<MasterList>> _repositoryMock = null!;
private Mock<IOptions<ApiSettings>> _apiSettingsMock = null!;
private readonly Mock<IHttpContextAccessor> _httpContextAccessorMock = new();
private readonly Mock<ILocalAuditService> _auditServiceMock = new();
private MasterListService<MasterList> _service = null!;
[Test]
public async Task DeleteMasterListById_ShouldCallRepositoryDelete_WhenMasterListFound()
{
// Arrange
var id = ObjectId.GenerateNewId();
var masterList = new MasterList { Id = id };
_repositoryMock.Setup(repo => repo.FindById(It.IsAny<ObjectId>(), It.IsAny<LocaleEnum>()))
.ReturnsAsync(masterList);
_repositoryMock.Setup(repo => repo.Delete(It.IsAny<ObjectId>()))
.Returns(Task.CompletedTask);
_unitServiceMock.Setup(c => c.CountUnitsByMasterListId(It.IsAny<ObjectId>(), It.IsAny<MasterListType>()))
.ReturnsAsync(0);
// Act
await _service.DeleteMasterListById(id);
// Assert
_repositoryMock.Verify(repo => repo.Delete(id), Times.Once);
}
// [Test]
// public async Task GetAllMasterList_ShouldReturnAllMasterLists()
// {
// // Arrange
// var masterLists = new List<MasterList> { new MasterList(), new MasterList() };
// _repositoryMock.Setup(repo => repo.GetAll())
// .ReturnsAsync(masterLists);
//
// // Act
// var result = await _service.GetAllMasterList();
//
// // Assert
// Assert.That(masterLists, Is.EqualTo(result));
// }
[Test]
public async Task GetMasterListById_ShouldReturnMasterList_WhenFound()
{
// Arrange
var id = ObjectId.GenerateNewId();
var masterList = new MasterList { Id = id };
_repositoryMock.Setup(repo => repo.FindById(It.IsAny<ObjectId>(), It.IsAny<LocaleEnum>()))
.ReturnsAsync(masterList);
// Act
var result = await _service.GetMasterListById(id, LocaleEnum.Default);
// Assert
Assert.That(masterList, Is.EqualTo(result));
}
[Test]
public async Task GetMasterListByName_ShouldReturnMasterList_WhenFound()
{
// Arrange
var name = "TestName";
var masterList = new MasterList { Id = ObjectId.GenerateNewId(), Name = name };
_repositoryMock.Setup(repo => repo.FindByName(It.IsAny<string>()))
.ReturnsAsync(masterList);
// Act
var result = await _service.GetMasterListByName(name);
// Assert
Assert.That(masterList, Is.EqualTo(result));
}
[Test]
public async Task InsertMasterList_ShouldReturnInsertedMasterList()
{
// Arrange
var masterList = new MasterList { Id = ObjectId.GenerateNewId() };
_repositoryMock.Setup(repo => repo.InsertOneAsync(It.IsAny<MasterList>()))
.Returns(Task.CompletedTask);
_repositoryMock.Setup(repo => repo.FindById(It.IsAny<ObjectId>()))
.ReturnsAsync(masterList);
// Act
var result = await _service.InsertMasterList(masterList);
// Assert
Assert.That(masterList, Is.EqualTo(result));
}
[Test]
public async Task UpdateMasterList_ShouldReturnUpdatedMasterList()
{
// Arrange
var masterList = new MasterList { Id = ObjectId.GenerateNewId() };
_repositoryMock.Setup(repo => repo.Update(It.IsAny<MasterList>()))
.Returns(Task.CompletedTask);
_repositoryMock.Setup(repo => repo.FindById(It.IsAny<ObjectId>(), It.IsAny<LocaleEnum>()))
.ReturnsAsync(masterList);
// Act
var result = await _service.UpdateMasterList(masterList);
// Assert
Assert.That(masterList, Is.EqualTo(result));
}
}
@@ -0,0 +1,270 @@
using adas_core.Application.Repositories.Interfaces;
using adas_core.Application.Services;
using adas_core.Application.Services.Interfaces;
using adas_core.Domain.Enums;
using adas_core.Domain.Models;
using adas_core.Domain.Models.AppSettings;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MongoDB.Bson;
using Moq;
using static NUnit.Framework.Is;
using Options = Microsoft.Extensions.Options.Options;
namespace adas_core.Test.Services;
[TestFixture]
public class MedicineServiceTest
{
[SetUp]
public void Setup()
{
_medicineRepositoryMock = new Mock<IMedicineRepository>();
_treatmentServiceMock = new Mock<ITreatmentService>();
_optionsApiSettings = Options.Create(_apiSettings);
_logger = new Mock<ILogger<MedicineService>>();
_medicineService = new MedicineService(
_medicineRepositoryMock.Object,
_treatmentServiceMock.Object,
_optionsApiSettings,
_logger.Object,
_httpContextAccessor.Object,
_auditService.Object);
}
private MedicineService _medicineService;
private Mock<IMedicineRepository> _medicineRepositoryMock;
private Mock<ITreatmentService> _treatmentServiceMock;
private readonly Mock<IHttpContextAccessor> _httpContextAccessor = new();
private readonly Mock<ILocalAuditService> _auditService = new();
private readonly ApiSettings _apiSettings = new()
{
NotesIndicatingMedication = ["NoteMedication"]
};
private IOptions<ApiSettings> _optionsApiSettings;
private Mock<ILogger<MedicineService>> _logger;
//private static readonly DateTime now = DateTime.Now;
private static readonly ObjectId PatientId = ObjectId.GenerateNewId();
[Test]
public async Task GetMedicinesOfTreatments_Null_Medicine_Return_0()
{
var medicineList = new List<Medicine>();
List<PatientTreatment> patientTreatment = [];
if (patientTreatment == null) throw new ArgumentNullException(nameof(patientTreatment));
_medicineRepositoryMock.Setup(m => m.GetMedicineByCodeOrNote(It.IsAny<List<string>>()))
.ReturnsAsync(medicineList);
var result = await _medicineService.GetMedicinesOfTreatments(patientTreatment);
Assert.That(result.Count(), EqualTo(0));
}
[Test]
public async Task GetMedicinesOfTreatments_Medicines_Return_Medicines()
{
var treatment =
new PatientTreatment
{
Id = ObjectId.GenerateNewId(),
PatientId = PatientId,
OrderControl = OrderControlType.Nw,
PlacerOrder = new Entity { EntityIdentifier = "100", NamespaceId = "CareVue" },
FillerOrder = new Entity { EntityIdentifier = "100", NamespaceId = "CareVue" },
RequestedGiveCodes = [new Code { Identifier = "12345" }],
OrderStatus = "A",
OrderTime = DateTime.Now,
Notes = [],
Routes = []
};
var treatmentList = new List<PatientTreatment>
{
treatment
};
var medicine =
new Medicine
{
Codes = ["12345"],
Group = [MedicineEnum.Group.DoubleSignature.ToString()],
Type = [MedicineEnum.Types.MuscleRelaxant.ToString()],
Name = "cisataracurio"
};
var medicineList = new List<Medicine>
{
medicine
};
_medicineRepositoryMock.Setup(m => m.GetMedicineByCodeOrNote(It.IsAny<List<string>>()))
.ReturnsAsync(medicineList);
var result = await _medicineService.GetMedicinesOfTreatments(treatmentList);
Assert.That(result.Count(), GreaterThan(0));
}
[Test]
public async Task GetMedicinesOfTreatments_Not_Get_Medicines_Return_Note_Medicines()
{
var treatment =
new PatientTreatment
{
Id = ObjectId.GenerateNewId(),
PatientId = PatientId,
OrderControl = OrderControlType.Nw,
PlacerOrder = new Entity { EntityIdentifier = "100", NamespaceId = "CareVue" },
FillerOrder = new Entity { EntityIdentifier = "100", NamespaceId = "CareVue" },
RequestedGiveCodes = [new Code { Identifier = "12345", Text = "CodeText" }],
OrderStatus = "A",
OrderTime = DateTime.Now,
Notes = [new Note { Comment = "NoteMedication" }],
Routes = []
};
var treatmentList = new List<PatientTreatment>
{
treatment
};
_medicineRepositoryMock.Setup(m => m.GetMedicineByCodeOrNote(It.IsAny<List<string>>())).ReturnsAsync([]);
var result = await _medicineService.GetMedicinesOfTreatments(treatmentList);
using (Assert.EnterMultipleScope())
{
var medicines = result as Medicine[] ?? result.ToArray();
Assert.That(medicines.Count(), GreaterThan(0));
Assert.That(medicines.FirstOrDefault()?.Codes.FirstOrDefault(), EqualTo("12345"));
Assert.That(medicines.FirstOrDefault()?.Name, EqualTo("CodeText"));
};
}
[Test]
public async Task GetMedicinesOfTreatments_Not_Get_Medicines_Not_Code_identifier_Return_Note_Medicines()
{
var treatment =
new PatientTreatment
{
Id = ObjectId.GenerateNewId(),
PatientId = PatientId,
OrderControl = OrderControlType.Nw,
PlacerOrder = new Entity { EntityIdentifier = "100", NamespaceId = "CareVue" },
FillerOrder = new Entity { EntityIdentifier = "100", NamespaceId = "CareVue" },
RequestedGiveCodes = [new Code { Text = "CodeText" }],
OrderStatus = "A",
OrderTime = DateTime.Now,
Notes = [new Note { Comment = "NoteMedication" }],
Routes = []
};
var treatmentList = new List<PatientTreatment>
{
treatment
};
_medicineRepositoryMock.Setup(m => m.GetMedicineByCodeOrNote(It.IsAny<List<string>>())).ReturnsAsync([]);
var result = await _medicineService.GetMedicinesOfTreatments(treatmentList);
using (Assert.EnterMultipleScope())
{
var medicines = result as Medicine[] ?? result.ToArray();
Assert.That(medicines.Count(), GreaterThan(0));
Assert.That(medicines.FirstOrDefault()?.Codes.FirstOrDefault(), EqualTo(string.Empty));
Assert.That(medicines.FirstOrDefault()?.Name, EqualTo("CodeText"));
};
}
[Test]
public async Task CalculateParentalNutritionMedicine_Notes_NPT_Return_NPT_Medicine()
{
var treatment =
new PatientTreatment
{
Id = ObjectId.GenerateNewId(),
PatientId = PatientId,
OrderControl = OrderControlType.Nw,
PlacerOrder = new Entity { EntityIdentifier = "100", NamespaceId = "CareVue" },
FillerOrder = new Entity { EntityIdentifier = "100", NamespaceId = "CareVue" },
RequestedGiveCodes = [new Code { Text = "CodeText" }],
OrderStatus = "A",
OrderTime = DateTime.Now,
Notes = [new Note { Comment = "NPT", CommentType = "formularybaseformulation" }],
Routes = []
};
var treatmentList = new List<PatientTreatment>
{
treatment
};
_medicineRepositoryMock.Setup(m => m.GetMedicineByCodeOrNote(It.IsAny<List<string>>())).ReturnsAsync([]);
var result = await _medicineService.GetMedicinesOfTreatments(treatmentList);
using (Assert.EnterMultipleScope())
{
var medicines = result as Medicine[] ?? result.ToArray();
Assert.That(medicines.Count(), GreaterThan(0));
Assert.That(medicines.FirstOrDefault()?.Codes.FirstOrDefault(), EqualTo(null));
Assert.That(medicines.FirstOrDefault()?.Name, EqualTo("NPT"));
Assert.That(MedicineEnum.Types.ParenteralNutrition.ToString(),
EqualTo(medicines.FirstOrDefault()?.Type.FirstOrDefault()));
};
}
[Test]
public async Task CalculateParentalNutritionMedicine_Notes_NPTL_Return_NPTL_Medicine()
{
var treatment =
new PatientTreatment
{
Id = ObjectId.GenerateNewId(),
PatientId = PatientId,
OrderControl = OrderControlType.Nw,
PlacerOrder = new Entity { EntityIdentifier = "100", NamespaceId = "CareVue" },
FillerOrder = new Entity { EntityIdentifier = "100", NamespaceId = "CareVue" },
RequestedGiveCodes = [new Code { Text = "CodeText" }],
OrderStatus = "A",
OrderTime = DateTime.Now,
Notes =
[
new Note { Comment = "NPT", CommentType = "formularybaseformulation" },
new Note { Comment = "LÍPIDOS NEONATALES AL 20%" }
],
Routes = []
};
var treatmentList = new List<PatientTreatment>
{
treatment
};
_medicineRepositoryMock.Setup(m => m.GetMedicineByCodeOrNote(It.IsAny<List<string>>())).ReturnsAsync([]);
var result = await _medicineService.GetMedicinesOfTreatments(treatmentList);
using (Assert.EnterMultipleScope())
{
var medicines = result as Medicine[] ?? result.ToArray();
Assert.That(medicines.Count(), GreaterThan(0));
Assert.That(medicines.FirstOrDefault()?.Codes.FirstOrDefault(), EqualTo(null));
Assert.That(medicines.FirstOrDefault()?.Name, EqualTo("NPT"));
Assert.That(MedicineEnum.Types.ParenteralNutritionLipids.ToString(),
EqualTo(medicines.FirstOrDefault()?.Type.FirstOrDefault()));
};
}
}
@@ -0,0 +1,141 @@
using adas_core.Application.Services.Caching;
namespace adas_core.Test.Services;
[TestFixture]
public class NoCacheServiceTest
{
private NoCacheService _noCacheService = null!;
[SetUp]
public void SetUp()
{
_noCacheService = new NoCacheService();
}
#region TC-27
[Test]
public async Task GetOrSetObjectAsync_AlwaysCallsFactory_NeverUsesCache()
{
// Arrange
var callCount = 0;
var expectedResult = new { Name = "TestPatient", Id = "123" };
Func<Task<object>> factory = () =>
{
callCount++;
return Task.FromResult<object>(expectedResult);
};
var key = "patients:abc123";
var ttl = TimeSpan.FromMinutes(5);
// Act
var result1 = await _noCacheService.GetOrSetObjectAsync(key, factory, ttl);
var result2 = await _noCacheService.GetOrSetObjectAsync(key, factory, ttl);
// Assert
Assert.That(callCount, Is.EqualTo(2), "La factory debería llamarse siempre (no hay caché)");
Assert.That(result1, Is.EqualTo(expectedResult));
Assert.That(result2, Is.EqualTo(expectedResult));
}
[Test]
public async Task GetOrSetObjectAsync_CallsFactory_ForEachUniqueKey()
{
// Arrange
var callCount = 0;
Func<Task<string>> factory = () =>
{
callCount++;
return Task.FromResult($"result-{callCount}");
};
// Act
await _noCacheService.GetOrSetValueAsync("key1", factory);
await _noCacheService.GetOrSetValueAsync("key2", factory);
await _noCacheService.GetOrSetValueAsync("key3", factory);
// Assert
Assert.That(callCount, Is.EqualTo(3),
"La factory debería haber sido invocada 3 veces, una por cada clave única");
}
#endregion
#region TC-28
[Test]
public async Task GetOrSetObjectAsync_DoesNotStoreData_InAnyBackend()
{
var key = "patients:abc123";
var expectedResult = new { Name = "TestPatient" };
Func<Task<object>> factory = () => Task.FromResult<object>(expectedResult);
await _noCacheService.GetOrSetObjectAsync(key, factory);
var retrieved = await _noCacheService.GetObjectAsync<object>(key);
Assert.That(retrieved, Is.Null);
Func<Task> act = async () => await _noCacheService.DeleteObjectAsync(key);
Assert.That(act, Throws.Nothing);
}
#endregion
#region TC-29
[Test]
public async Task DeleteByPatternAsync_ReturnsZero_DoesNotThrow()
{
// Act
var result = await _noCacheService.DeleteByPatternAsync("patients:*");
var result2 = await _noCacheService.DeleteByPatternAsync("any:pattern:*");
// Assert
Assert.That(result, Is.EqualTo(0));
Assert.That(result2, Is.EqualTo(0));
}
#endregion
#region TC-30
[Test]
public void CleanCache_IsNoOp_DoesNotThrow()
{
Action act = () => _noCacheService.CleanCache();
Assert.That(act, Throws.Nothing);
var result = _noCacheService.GetValue("any-key");
Assert.That(result, Is.Null);
}
[Test]
public void SetValue_IsNoOp_DoesNotThrow()
{
Action act = () => _noCacheService.SetValue("key", "value");
Assert.That(act, Throws.Nothing);
}
[Test]
public void GetValue_IsNoOp_ReturnsNull()
{
var result = _noCacheService.GetValue("any-key");
Assert.That(result, Is.Null);
}
#endregion
}
@@ -0,0 +1,927 @@
using adas_core.Application.Repositories.Interfaces;
using adas_core.Application.Services;
using adas_core.Application.Services.Interfaces;
using adas_core.Domain.Enums;
using adas_core.Domain.Models;
using adas_core.Domain.Models.AppSettings;
using adas_core.Domain.Models.MongoModels;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MongoDB.Bson;
using Moq;
using Options = Microsoft.Extensions.Options.Options;
/*
* Tests shift observations
*/
namespace adas_core.Test.Services;
[TestFixture]
public class ObservationServiceTest
{
[SetUp]
public void Setup()
{
//_observationServiceMock = new Mock<IObservationService>();
//var medicineServiceMock = new Mock<IMedicineService>();1
var groupedObservationServiceMock = new Mock<IGroupedObservationService>();
var alarmServiceMock = new Mock<IAlarmService>();
var clientMessageServiceMock = new Mock<IClientMessageService>();
var subscribersServiceMock = new Mock<ISubscribersService>();
var subscriberGroupedServiceMock = new Mock<ISubscriberGroupedService>();
_patientServiceMock = new Mock<IPatientService>();
_configObservationService = new Mock<IConfigObservationService>();
_observationRepository = new Mock<IObservationRepository>();
var observationArchiveRepository = new Mock<IObservationArchiveRepository>();
var calculatedObservationsServiceMock = new Mock<ICalculatedObservationsService>();
var calculatedObservationsServiceLazy =
new Lazy<ICalculatedObservationsService>(() => calculatedObservationsServiceMock.Object);
calculatedObservationsServiceMock.Setup(o => o.Map(It.IsAny<PatientObservation>(), It.IsAny<bool>()))
.ReturnsAsync((PatientObservation obs, bool _) => obs);
_configUnitsService = new Mock<IConfigUnitsService>();
_unitServiceMock = new Mock<IUnitService>();
var diagnosisServiceMock = new Mock<IDiagnosisService>();
_optionsApiSettings = Options.Create(_apiSettings);
Options.Create(_recordingSettings);
_optionsCacheSettings = Options.Create(_cacheSettings);
var balizaService = new Mock<ILightBeaconService>();
var pocService = new Mock<IPointOfCareService>();
var relayService = new Mock<IRelayService>();
var recordingService = new Mock<IRecordingService>();
_logger = new Mock<ILogger<ObservationService>>();
_observationService = new ObservationService(
_patientServiceMock.Object,
//Ipoc.Object,
_configObservationService.Object,
_observationRepository.Object,
observationArchiveRepository.Object,
_configUnitsService.Object,
diagnosisServiceMock.Object,
_optionsApiSettings,
_optionsCacheSettings,
balizaService.Object,
relayService.Object,
recordingService.Object,
_logger.Object,
groupedObservationServiceMock.Object,
alarmServiceMock.Object,
clientMessageServiceMock.Object,
subscribersServiceMock.Object,
subscriberGroupedServiceMock.Object,
calculatedObservationsServiceLazy,
_httpContextAccessor.Object,
_auditService.Object,
pocService.Object,
Mock.Of<ICacheService>()
);
// Create a mock of the singleton class subscribers
var mockSingleton = new Mock<ICalculatedObservationsService>();
// Set up the mock object to return a specific value when a method is called
mockSingleton.Setup(x => x.Map(It.IsAny<PatientObservation>(), It.IsAny<bool>()))
.ReturnsAsync((PatientObservation? value, bool _) => value);
var unitId = ObjectId.GenerateNewId();
var unit = new Unit
{
Id = unitId,
Name = "UCI5C",
Title = "CONTROLC",
Configuration = new UnitConfiguration
{
AutoAdt = true
}
};
_unitServiceMock.Setup(u => u.FindByName(unit.Name)).ReturnsAsync(unit);
_unitServiceMock.Setup(u => u.FindById(unit.Id)).ReturnsAsync(unit);
}
private ObservationService _observationService;
//Mock<IObservationService> _observationServiceMock ;
private Mock<IPatientService> _patientServiceMock;
private Mock<IConfigObservationService> _configObservationService;
private Mock<IConfigUnitsService> _configUnitsService;
private Mock<IObservationRepository> _observationRepository;
private Mock<IUnitService> _unitServiceMock;
private readonly Mock<IHttpContextAccessor> _httpContextAccessor = new();
private readonly Mock<ILocalAuditService> _auditService = new();
private readonly ApiSettings _apiSettings = new()
{
ConfigObservation = new ConfigObservationSettings
{
IgnoreUnknownObservation = false
},
Customize = "H12O",
IntravenousLinesCode = ["10546003"],
AllergiesCode = ["473011001"],
DrainageCode = ["56868008"],
IsolationCode = ["302147001"],
PositionCode = ["386053000"]
};
private readonly CacheSettings _cacheSettings = new();
private IOptions<ApiSettings> _optionsApiSettings;
private IOptions<CacheSettings> _optionsCacheSettings;
private readonly RecordingSettings _recordingSettings = new();
private Mock<ILogger<ObservationService>> _logger;
private static readonly DateTime Now = DateTime.Now;
private static readonly ObjectId PatientId = ObjectId.GenerateNewId();
[Test]
public async Task ProcessAllergiesObservation__apiRequest_No_Allergies_Return_Nothing()
{
var patientObs = new Person
{
FirstName = "Miguel",
LastName = "Villanueva",
Ids = new Dictionary<string, string> { { "MR", "437537" } }
};
var patient = new Patient
{
Id = ObjectId.GenerateNewId(),
UnitString = "UCI5C",
Bed = "Box4",
PatientNumber = "437537",
Person = patientObs
};
var apiRequest = new ApiRequest
{
Location = new PatientLocation("UCI5C", "Box4"),
ObservationData = new ObservationData
{
Code = "473011001",
CodingSystem = "SNM",
Text = "Alergias",
Time = Now,
Value = ""
},
Observations =
[
new PatientObservation
{
Code = "263490005",
CodingSystem = "SNM",
Name = "Estado",
Status = StatusEnum.Type.Ok,
Time = Now,
Value = "Sin alergias conocidas"
},
new PatientObservation
{
Code = "300916003",
CodingSystem = "SNM",
Name = "Alergia al ltex?",
Status = StatusEnum.Type.Ok,
Time = Now,
Value = "No"
}
],
Patient = patientObs,
PatientNumber = "437537",
Type = "ORU_R01",
PatientId = PatientId.ToString()
};
//PatientObservation expectedObs = new();
_patientServiceMock.Setup(cm => cm.FindPatientByApiRequest(apiRequest)).ReturnsAsync(patient);
await _observationService.SaveRequest(apiRequest);
_observationRepository.Verify(o => o.InsertOneAsync(It.Is<PatientObservation>(arg =>
arg.Name == "AllergiesObs" &&
arg.PatientId == PatientId
)), Times.Never);
}
[Test]
public async Task ProcessAllergiesObservation_apiRequest_Allergies_Latex_Return_AllergiesObs_Latex()
{
//Falla CalculatedObservationService.Instance = null
var patientObs = new Person
{
FirstName = "Miguel",
LastName = "Villanueva",
Ids = new Dictionary<string, string> { { "MR", "437537" } }
};
var patient = new Patient
{
Id = ObjectId.GenerateNewId(),
UnitString = "UCI5C",
Bed = "Box4",
PatientNumber = "437537",
Person = patientObs,
UnitId = ObjectId.GenerateNewId(),
PointOfCareId = ObjectId.GenerateNewId()
};
var apiRequest = new ApiRequest
{
Location = new PatientLocation("UCI5C", "Box4"),
ObservationData = new ObservationData
{
Code = "473011001",
CodingSystem = "SNM",
Text = "Alergias",
Time = Now
},
Observations =
[
new PatientObservation
{
Code = "263490005",
CodingSystem = "SNM",
Name = "Estado",
Status = StatusEnum.Type.Ok,
Time = Now,
Value = "Alergias"
},
new PatientObservation
{
Code = "300916003",
CodingSystem = "SNM",
Name = "Alergia al ltex?",
Status = StatusEnum.Type.Ok,
Time = Now,
Value = "Si"
}
],
Patient = patientObs,
PatientNumber = "437537",
Type = "ORU_R01",
PatientId = PatientId.ToString()
};
List<PatientAllergiesValue> expectePatientAllergiesValues =
[
new()
{
Type = "Latex",
Value = "Si"
}
];
PatientObservation expectedObs = new()
{
Time = apiRequest.ObservationData.Time.Value,
Code = apiRequest.ObservationData.Code,
CodingSystem = apiRequest.ObservationData.CodingSystem,
PatientId = patient.Id,
ParentData = new ParentDataClass
{
Code = apiRequest.ObservationData.Code,
CodingSystem = apiRequest.ObservationData.CodingSystem,
Name = apiRequest.ObservationData.Text
},
Value = expectePatientAllergiesValues
};
_patientServiceMock.Setup(cm => cm.FindPatientByApiRequest(apiRequest)).ReturnsAsync(patient);
_configObservationService.Setup(o => o.Map(It.IsAny<PatientObservation>(), false)).ReturnsAsync(expectedObs);
_configUnitsService.Setup(o => o.Map(It.IsAny<PatientObservation>())).ReturnsAsync(expectedObs);
_configObservationService.Setup(o => o.RetentionActions(It.IsAny<PatientObservation>()))
.ReturnsAsync(new ObservatitonRetentionResult());
_unitServiceMock.Setup(o => o.FindById(It.IsAny<ObjectId>())).ReturnsAsync(new Unit
{ Configuration = new UnitConfiguration { AutoAdt = true } });
await _observationService.SaveRequest(apiRequest);
_observationRepository.Verify(o => o.InsertOneAsync(expectedObs));
}
[Test]
public async Task ProcessAllergiesObservation_apiRequest_Allergies_Return_AllergiesObs()
{
//Falla CalculatedObservationService.Instance = null
var patientObs = new Person
{
FirstName = "Miguel",
LastName = "Villanueva",
Ids = new Dictionary<string, string> { { "MR", "437537" } }
};
var patient = new Patient
{
Id = ObjectId.GenerateNewId(),
UnitId = ObjectId.GenerateNewId(),
UnitString = "UCI5C",
Bed = "Box4",
PatientNumber = "437537",
Person = patientObs
};
var apiRequest = new ApiRequest
{
Location = new PatientLocation("UCI5C", "Box4"),
ObservationData = new ObservationData
{
Code = "473011001",
CodingSystem = "SNM",
Text = "Alergias",
Time = Now
},
Observations =
[
new PatientObservation
{
Code = "263490005",
CodingSystem = "SNM",
Name = "Estado",
Status = StatusEnum.Type.Ok,
Time = Now,
Value = "Alergias"
},
new PatientObservation
{
Code = "419199007",
CodingSystem = "SNM",
Name = "Tipo",
Status = StatusEnum.Type.Ok,
Time = Now,
Value = "Alergia ambienta"
},
new PatientObservation
{
Code = "277054007",
CodingSystem = "SNM",
Name = "Alergeno",
Status = StatusEnum.Type.Ok,
Time = Now,
Value = "Estacional"
},
new PatientObservation
{
Code = "281296001",
CodingSystem = "SNM",
Name = "Comentarios",
Status = StatusEnum.Type.Ok,
Time = Now,
Value = "epitelio de perro, mezcla de gramneas salvajes,"
},
new PatientObservation
{
Code = "419199007",
CodingSystem = "SNM",
Name = "Tipo",
Status = StatusEnum.Type.Ok,
Time = Now,
Value = "Alergia a frmacos"
},
new PatientObservation
{
Code = "416098002",
CodingSystem = "SNM",
Name = "Frmacos alrgenos",
Status = StatusEnum.Type.Ok,
Time = Now,
Value = "METILPREDNISOLONA"
},
new PatientObservation
{
Code = "281296001",
CodingSystem = "SNM",
Name = "Comentarios",
Status = StatusEnum.Type.Ok,
Time = Now,
Value = "Tolera dexametasona y actocortina"
},
new PatientObservation
{
Code = "419199007",
CodingSystem = "SNM",
Name = "Tipo",
Status = StatusEnum.Type.Ok,
Time = Now,
Value = "Alergia a frmacos"
},
new PatientObservation
{
Code = "277054007",
CodingSystem = "SNM",
Name = "Alergeno",
Status = StatusEnum.Type.Ok,
Time = Now,
Value = "Penicilina/cefalosporinas"
}
],
Patient = patientObs,
PatientNumber = "437537",
Type = "ORU_R01",
PatientId = PatientId.ToString()
};
List<PatientAllergiesValue> expectePatientAllergiesValues =
[
new()
{
Type = "Alergia ambienta",
Value = "Estacional",
Notes = "epitelio de perro, mezcla de gramneas salvajes,"
},
new()
{
Type = "Alergia a frmacos",
Value = "METILPREDNISOLONA",
Notes = "Tolera dexametasona y actocortina"
},
new()
{
Type = "Alergia a frmacos",
Value = "Penicilina/cefalosporinas"
}
];
PatientObservation expectedObs = new()
{
Time = apiRequest.ObservationData.Time.Value,
Code = apiRequest.ObservationData?.Code,
CodingSystem = apiRequest.ObservationData?.CodingSystem,
PatientId = patient.Id,
ParentData = new ParentDataClass
{
Code = apiRequest.ObservationData?.Code,
CodingSystem = apiRequest.ObservationData?.CodingSystem,
Name = apiRequest.ObservationData?.Text
},
Value = expectePatientAllergiesValues
};
_patientServiceMock.Setup(cm => cm.FindPatientByApiRequest(apiRequest)).ReturnsAsync(patient);
_configObservationService.Setup(o => o.Map(It.IsAny<PatientObservation>(), false)).ReturnsAsync(expectedObs);
_configUnitsService.Setup(o => o.Map(It.IsAny<PatientObservation>())).ReturnsAsync(expectedObs);
_unitServiceMock.Setup(o => o.FindById(It.IsAny<ObjectId>())).ReturnsAsync(new Unit
{ Configuration = new UnitConfiguration { AutoAdt = true } });
// sectionServiceMock.Setup(s => s.FindByPatient(It.Is<ObjectId>(arg => arg == patient.id))).Returns(Task.FromResult<Section>(null));
_configObservationService.Setup(o => o.RetentionActions(It.IsAny<PatientObservation>()))
.ReturnsAsync(new ObservatitonRetentionResult());
await _observationService.SaveRequest(apiRequest);
_observationRepository.Verify(o => o.InsertOneAsync(expectedObs));
}
[Test]
public async Task ProcessDrainagesObservation_apiRequest_Drainages_Return_DrainagesObs()
{
//Falla CalculatedObservationService.Instance = null
var patientObs = new Person
{
FirstName = "Miguel",
LastName = "Villanueva",
Ids = new Dictionary<string, string> { { "MR", "437537" } }
};
var patient = new Patient
{
Id = ObjectId.GenerateNewId(),
UnitId = ObjectId.GenerateNewId(),
UnitString = "UCI5C",
Bed = "Box4",
PatientNumber = "437537",
Person = patientObs
};
var apiRequest = new ApiRequest
{
Location = new PatientLocation("UCI5C", "Box4"),
ObservationData = new ObservationData
{
Code = "56868008",
CodingSystem = "SNM",
Text = "Drenaje: Cabeza",
Time = Now
},
Observations =
[
new PatientObservation
{
Code = "56868008",
CodingSystem = "SNM",
Name = "Volumen",
Status = StatusEnum.Type.Ok,
Time = Now,
Value = 100
},
new PatientObservation
{
Code = "10546003",
CodingSystem = "SNM",
Name = "Localizacin",
Status = StatusEnum.Type.Ok,
Time = Now,
Value = "Cabeza"
},
new PatientObservation
{
Code = "138875005",
CodingSystem = "SNM",
Name = "Tipo de drenaje",
Status = StatusEnum.Type.Ok,
Time = Now,
Value = "Drenaje ventricular"
},
new PatientObservation
{
Code = "138875005",
CodingSystem = "SNM",
Name = "Altura columna(cmH2O)",
Status = StatusEnum.Type.Ok,
Time = Now,
Value = 88
}
],
Patient = patientObs,
PatientNumber = "437537",
Type = "ORU_R01",
PatientId = PatientId.ToString()
};
List<PatientDrainagesValue> expectePatientDraingesValues =
[
new()
{
Type = "Drenaje ventricular",
Location = "Cabeza",
Volume = 1001,
Height = 8
}
];
PatientObservation expectedObs = new()
{
Time = apiRequest.ObservationData.Time.Value,
Code = apiRequest.ObservationData.Code,
CodingSystem = apiRequest.ObservationData.CodingSystem,
PatientId = patient.Id,
ParentData = new ParentDataClass
{
Code = apiRequest.ObservationData.Code,
CodingSystem = apiRequest.ObservationData.CodingSystem,
Name = apiRequest.ObservationData.Text
},
Value = expectePatientDraingesValues
};
_patientServiceMock.Setup(cm => cm.FindPatientByApiRequest(apiRequest)).ReturnsAsync(patient);
_configObservationService
.Setup(o => o.Map(It.Is<PatientObservation>(arg => arg.PatientId == patient.Id), false))
.ReturnsAsync(expectedObs);
_configUnitsService.Setup(o => o.Map(It.Is<PatientObservation>(arg => arg.PatientId == patient.Id)))
.ReturnsAsync(expectedObs);
_configObservationService.Setup(o => o.RetentionActions(It.IsAny<PatientObservation>()))
.ReturnsAsync(new ObservatitonRetentionResult());
_unitServiceMock.Setup(o => o.FindById(It.IsAny<ObjectId>())).ReturnsAsync(new Unit
{ Configuration = new UnitConfiguration { AutoAdt = true } });
await _observationService.SaveRequest(apiRequest);
_observationRepository.Verify(o => o.InsertOneAsync(It.Is<PatientObservation>(arg =>
arg.Value == expectedObs.Value &&
arg.PatientId == expectedObs.PatientId &&
arg.ParentData == expectedObs.ParentData &&
arg.Time == expectedObs.Time &&
arg.Code == expectedObs.Code &&
arg.CodingSystem == expectedObs.CodingSystem
)));
}
[Test]
public async Task ProcessIsolationObservation_Return_IsolationObs()
{
var patientObs = new Person
{
FirstName = "Miguel",
LastName = "Villanueva",
Ids = new Dictionary<string, string> { { "MR", "437537" } }
};
var patient = new Patient
{
Id = ObjectId.GenerateNewId(),
UnitId = ObjectId.GenerateNewId(),
UnitString = "UCI5C",
Bed = "Box4",
PatientNumber = "437537",
Person = patientObs
};
var apiRequest = new ApiRequest
{
Location = new PatientLocation("UCI5C", "Box4"),
ObservationData = new ObservationData
{
Code = "302147001",
CodingSystem = "SNM",
Value = "Aire; Contacto; Preventivo",
Text = "Aislamiento",
Time = Now
},
Observations =
[
new PatientObservation
{
Code = "code",
CodingSystem = "SNM",
Name = "name",
Status = StatusEnum.Type.Ok,
Time = Now,
Value = "value"
}
],
Patient = patientObs,
PatientNumber = "437537",
Type = "ORU_R01",
PatientId = PatientId.ToString(),
MessageTime = Now
};
var newObs = new PatientObservation
{
Value = "Aire, Contacto, Preventivo",
Name = "Isolation",
CodingSystem = "ADAS",
PatientId = patient.Id,
MessageTime = Now,
Time = Now
};
_patientServiceMock.Setup(cm => cm.FindPatientByApiRequest(apiRequest)).ReturnsAsync(patient);
_configObservationService
.Setup(o => o.Map(It.Is<PatientObservation>(arg => arg.PatientId == patient.Id), false))
.ReturnsAsync(newObs);
_configUnitsService.Setup(o => o.Map(It.Is<PatientObservation>(arg => arg.PatientId == patient.Id)))
.ReturnsAsync(newObs);
_configObservationService.Setup(o => o.RetentionActions(It.IsAny<PatientObservation>()))
.ReturnsAsync(new ObservatitonRetentionResult());
_unitServiceMock.Setup(o => o.FindById(It.IsAny<ObjectId>())).ReturnsAsync(new Unit
{ Configuration = new UnitConfiguration { AutoAdt = true } });
await _observationService.SaveRequest(apiRequest);
_observationRepository.Verify(o => o.InsertOneAsync(It.Is<PatientObservation>(arg =>
arg.Value == newObs.Value &&
arg.PatientId == newObs.PatientId &&
arg.Name == newObs.Name &&
arg.Time == newObs.Time &&
arg.MessageTime == newObs.MessageTime &&
arg.CodingSystem == newObs.CodingSystem
)));
}
[Test]
public async Task ProcessPositionObservation_Return_PositionObs()
{
var patientObs = new Person
{
FirstName = "Miguel",
LastName = "Villanueva",
Ids = new Dictionary<string, string> { { "MR", "437537" } }
};
var patient = new Patient
{
Id = ObjectId.GenerateNewId(),
UnitId = ObjectId.GenerateNewId(),
UnitString = "UCI5C",
Bed = "Box4",
PatientNumber = "437537",
Person = patientObs
};
var apiRequest = new ApiRequest
{
Location = new PatientLocation("UCI5C", "Box4"),
ObservationData = new ObservationData
{
Code = "386053000",
CodingSystem = "SNM",
Text = "CAMBIOS POSTURALES",
Value = "Cama Hill-rom",
Time = Now
},
Observations =
[
new PatientObservation
{
Code = "code",
CodingSystem = "SNM",
Name = "name",
Status = StatusEnum.Type.Ok,
Time = Now,
Value = "Cama Hill-rom"
}
],
Patient = patientObs,
PatientNumber = "437537",
Type = "ORU_R01",
PatientId = PatientId.ToString(),
MessageTime = Now
};
var newObs = new PatientObservation
{
Value = "Cama Hill-rom",
Name = "Patient_Position",
CodingSystem = "ADAS",
PatientId = patient.Id,
MessageTime = Now,
Time = Now
};
_patientServiceMock.Setup(cm => cm.FindPatientByApiRequest(apiRequest)).ReturnsAsync(patient);
_configObservationService
.Setup(o => o.Map(It.Is<PatientObservation>(arg => arg.PatientId == patient.Id), false))
.ReturnsAsync(newObs);
_configUnitsService.Setup(o => o.Map(It.Is<PatientObservation>(arg => arg.PatientId == patient.Id)))
.ReturnsAsync(newObs);
_configObservationService.Setup(o => o.RetentionActions(It.IsAny<PatientObservation>()))
.ReturnsAsync(new ObservatitonRetentionResult());
_unitServiceMock.Setup(o => o.FindById(It.IsAny<ObjectId>())).ReturnsAsync(new Unit
{ Configuration = new UnitConfiguration { AutoAdt = true } });
await _observationService.SaveRequest(apiRequest);
_observationRepository.Verify(o => o.InsertOneAsync(It.Is<PatientObservation>(arg =>
arg.Value == newObs.Value &&
arg.PatientId == newObs.PatientId &&
arg.Name == newObs.Name &&
arg.Time == newObs.Time &&
arg.MessageTime == newObs.MessageTime &&
arg.CodingSystem == newObs.CodingSystem
)));
}
[Test]
public async Task ProcessIntravenousLinesObservation_Return_PositionObs()
{
var patientObs = new Person
{
FirstName = "Miguel",
LastName = "Villanueva",
Ids = new Dictionary<string, string> { { "MR", "437537" } }
};
var patient = new Patient
{
Id = ObjectId.GenerateNewId(),
UnitId = ObjectId.GenerateNewId(),
UnitString = "UCI5C",
Bed = "Box4",
PatientNumber = "437537",
Person = patientObs
};
var apiRequest = new ApiRequest
{
Location = new PatientLocation("UCI5C", "Box4"),
ObservationData = new ObservationData
{
Code = "10546003",
CodingSystem = "SNM",
Text = "Catter EPICUTNEO PERIFRICO: Zona temporal derecha",
Time = Now
},
Observations =
[
new PatientObservation
{
Code = "439272007",
CodingSystem = "SNM",
Name = "Fecha insercin",
Status = StatusEnum.Type.Ok,
Time = Now,
Value = Now
},
new PatientObservation
{
Code = "228864003",
CodingSystem = "SNM",
Name = "Duracin (das)",
Status = StatusEnum.Type.Ok,
Time = Now,
Value = 7
},
new PatientObservation
{
Code = "273248003",
CodingSystem = "SNM",
Name = "Actuacin",
Status = StatusEnum.Type.Ok,
Time = Now,
Value = "Insertado"
},
new PatientObservation
{
Code = "10546003",
CodingSystem = "SNM",
Name = "Localizacin",
Status = StatusEnum.Type.Ok,
Time = Now,
Value = "Zona temporal derecha"
}
],
Patient = patientObs,
PatientNumber = "437537",
Type = "ORU_R01",
PatientId = PatientId.ToString(),
MessageTime = Now
};
var obsIntravenousLines = new PatientIntravenousLinesValue
{
Type = "Catter EPICUTNEO PERIFRICO",
Location = "Zona temporal derecha",
Action = "Insertado",
InsertTime = Now,
Duration = "7"
};
var newObs = new PatientObservation
{
Value = obsIntravenousLines,
Code = "10546003",
CodingSystem = "SNM",
PatientId = patient.Id,
MessageTime = Now,
Time = Now
};
_patientServiceMock.Setup(cm => cm.FindPatientByApiRequest(apiRequest)).ReturnsAsync(patient);
_configObservationService
.Setup(o => o.Map(It.Is<PatientObservation>(arg => arg.PatientId == patient.Id), false))
.ReturnsAsync(newObs);
_configUnitsService.Setup(o => o.Map(It.Is<PatientObservation>(arg => arg.PatientId == patient.Id)))
.ReturnsAsync(newObs);
_configObservationService.Setup(o => o.RetentionActions(It.IsAny<PatientObservation>()))
.ReturnsAsync(new ObservatitonRetentionResult());
_unitServiceMock.Setup(o => o.FindById(It.IsAny<ObjectId>())).ReturnsAsync(new Unit
{ Configuration = new UnitConfiguration { AutoAdt = true } });
await _observationService.SaveRequest(apiRequest);
_observationRepository.Verify(o => o.InsertOneAsync(It.Is<PatientObservation>(arg =>
arg.Value == newObs.Value &&
arg.PatientId == newObs.PatientId &&
arg.Code == newObs.Code &&
arg.Time == newObs.Time &&
arg.MessageTime == newObs.MessageTime &&
arg.CodingSystem == newObs.CodingSystem
)));
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,291 @@
using System.Security.Claims;
using adas_core.Application.Exceptions;
using adas_core.Application.Repositories.Interfaces;
using adas_core.Application.Services;
using adas_core.Application.Services.Interfaces;
using adas_core.Domain.Enums;
using adas_core.Domain.Models.AppSettings;
using adas_core.Domain.Models.MongoModels;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using MongoDB.Bson;
using Moq;
using Options = Microsoft.Extensions.Options.Options;
namespace adas_core.Test.Services;
[TestFixture]
public class PointOfCareServiceTests
{
[SetUp]
public void SetUp()
{
_pointOfCareRepositoryMock = new Mock<IPointOfCareRepository>();
_unitServiceMock = new Mock<IUnitService>();
_admissionServiceMock = new Mock<IAdmissionService>();
_cacheServiceMock = new Mock<ICacheService>();
_cacheServiceMock
.Setup(c => c.GetOrSetObjectAsync(
It.IsAny<string>(),
It.IsAny<Func<Task<PointOfCare?>>>(),
It.IsAny<TimeSpan?>(),
It.IsAny<CancellationToken>()))
.Returns((string _, Func<Task<PointOfCare?>> factory, TimeSpan? _, CancellationToken _) => factory());
var loggerMock = new Mock<ILogger<PointOfCareService>>();
var userClaims = new ClaimsPrincipal(new ClaimsIdentity([
new Claim(ClaimTypes.Name, "TestUser")
], "mock"));
var httpContextMock = new DefaultHttpContext
{
User = userClaims
};
_httpContextAccessorMock.Setup(accessor => accessor.HttpContext)
.Returns(httpContextMock);
_pointOfCareService = new PointOfCareService(
loggerMock.Object,
_pointOfCareRepositoryMock.Object,
new Lazy<IPatientService>(Mock.Of<IPatientService>),
new Lazy<IUnitService>(() => _unitServiceMock.Object),
Mock.Of<ISubscribersService>(),
Mock.Of<Lazy<IClientMessageService>>(),
new Lazy<IAdmissionService>(() => _admissionServiceMock.Object),
_httpContextAccessorMock.Object,
_auditServiceMock.Object,
_cacheServiceMock.Object,
Options.Create(new CacheSettings())
);
}
private PointOfCareService _pointOfCareService = null!;
private Mock<IPointOfCareRepository> _pointOfCareRepositoryMock = null!;
private Mock<IUnitService> _unitServiceMock = null!;
private Mock<ICacheService> _cacheServiceMock = null!;
private Mock<IAdmissionService> _admissionServiceMock = null!;
private readonly Mock<IHttpContextAccessor> _httpContextAccessorMock = new();
private readonly Mock<ILocalAuditService> _auditServiceMock = new();
[Test]
public async Task Delete_ValidObjectId_DeletesPointOfCare()
{
// Arrange
var id = ObjectId.GenerateNewId();
_pointOfCareRepositoryMock.Setup(m => m.FindByIdAllConfig(id))
.ReturnsAsync(new PointOfCare { Id = id, AdmissionId = null });
_pointOfCareRepositoryMock.Setup(m => m.Delete(id)).Verifiable();
// Act
await _pointOfCareService.Delete(id);
// Assert
_pointOfCareRepositoryMock.Verify();
}
[Test]
public async Task Update_ValidPointOfCare_UpdatesPointOfCare()
{
// Arrange
var pointOfCare = new PointOfCare { Id = ObjectId.GenerateNewId(), UnitName = "TestUnit" };
_pointOfCareRepositoryMock.Setup(m => m.Update(pointOfCare)).Verifiable();
// Act
await _pointOfCareService.Update(pointOfCare);
// Assert
_pointOfCareRepositoryMock.Verify();
}
[Test]
public async Task GetAll_NoArguments_ReturnsListOfPointOfCare()
{
// Arrange
var pointOfCareList = new List<PointOfCare> { new(), new() };
_pointOfCareRepositoryMock.Setup(m => m.GetAll()).ReturnsAsync(pointOfCareList);
// Act
var result = await _pointOfCareService.GetAll();
// Assert
Assert.That(result, Is.EqualTo(pointOfCareList));
}
[Test]
public void UpdateConfiguration_ValidIdAndConfiguration_InvokesRepositoryUpdateConfiguration()
{
// Arrange
var id = ObjectId.GenerateNewId();
var configuration = new PointOfCareConfiguration();
// Act & Assert
Assert.That(_pointOfCareService, Is.Not.Null);
Assert.That(_pointOfCareRepositoryMock, Is.Not.Null);
Func<Task> act = async () => await _pointOfCareService.UpdateConfiguration(id, configuration);
Assert.ThrowsAsync<ConflictException>(act);
}
[Test]
public async Task FindById_ValidId_ReturnsPointOfCare()
{
// Arrange
var id = ObjectId.GenerateNewId();
var expectedPointOfCare = new PointOfCare { Id = id };
_pointOfCareRepositoryMock.Setup(m => m.FindByIdAllConfig(id)).ReturnsAsync(expectedPointOfCare);
// Act
var result = await _pointOfCareService.FindById(id);
// Assert
Assert.That(result, Is.EqualTo(expectedPointOfCare));
}
// [Test]
// public async Task FindByUnit_ValidUnit_ReturnsListOfPointOfCare()
// {
// // Arrange
// var id = ObjectId.GenerateNewId();
// var pointOfCare = new PointOfCare { Id = id, UnitId = ObjectId.GenerateNewId() };
// var unit = new Unit { Id = pointOfCare.UnitId, Name = "TestUnit" };
// var expectedPointOfCareList = new List<PointOfCare>
// {
// new PointOfCare { Unit = unit },
// new PointOfCare { Unit = unit },
// };
// _pointOfCareRepositoryMock.Setup(m => m.FindByUnit(unit)).ReturnsAsync(expectedPointOfCareList);
//
// // Act
// var result = await _pointOfCareService.FindByUnit(unit);
//
// // Assert
// Assert.That(result, Is.EqualTo(expectedPointOfCareList));
// }
[Test]
public async Task FindByUnitAndStatus_ValidUnitIdAndStatus_ReturnsListOfPointOfCare()
{
// Arrange
var unitId = ObjectId.GenerateNewId();
var pocStatus = StatusEnum.PointOfCare.Available;
var expectedPointOfCareList = new List<PointOfCare>
{
new(),
new()
};
_pointOfCareRepositoryMock.Setup(m => m.FindByUnitAndStatus(unitId, pocStatus, false))
.ReturnsAsync(expectedPointOfCareList);
// Act
var result = await _pointOfCareService.FindByUnitAndStatus(unitId, pocStatus);
// Assert
Assert.That(result, Is.EqualTo(expectedPointOfCareList));
}
[Test]
public void CheckNextAdmission_ValidPatientLocation_UpdatesPoCStatus_AndCallsUpdate()
{
// Arrange
var patientLocationId = ObjectId.GenerateNewId();
var pocToCheck = new PointOfCare
{
Id = patientLocationId,
AdmissionId = null, // Forzamos la rama que busca la siguiente admisión
Status = StatusEnum.PointOfCare.Locked // Locked → no debe actualizar. Cambia para probar actualización:
// Usa Available o Reserved para que se ejecute el update.
};
// Para que ejecute la lógica de actualización, cambiamos el estado inicial:
pocToCheck.Status = StatusEnum.PointOfCare.Available;
var nextAdmission = new Admission { Id = ObjectId.GenerateNewId() };
// 1) Cache: debe ejecutar el factory y devolver el PoC
_cacheServiceMock
.Setup(c => c.GetOrSetObjectAsync(
It.IsAny<string>(),
It.IsAny<Func<Task<PointOfCare?>>>(),
It.IsAny<TimeSpan?>(),
It.IsAny<CancellationToken>()))
.Returns((string _, Func<Task<PointOfCare?>> factory, TimeSpan? _, CancellationToken _) => factory());
// 2) Repo: FindById (usado por el factory del caché)
_pointOfCareRepositoryMock
.Setup(m => m.FindById(patientLocationId))
.ReturnsAsync(pocToCheck);
// 3) AdmissionService (ruta AdmissionId == null → buscar siguiente)
_admissionServiceMock
.Setup(m => m.GetAdmissionByPointOfCareId(pocToCheck.Id))
.ReturnsAsync([nextAdmission]);
// 4) Update(poc) → queremos esperar a que se invoque
var updatedSignal = new ManualResetEventSlim(false);
_pointOfCareRepositoryMock
.Setup(m => m.Update(It.IsAny<PointOfCare>()))
.Callback<PointOfCare>(_ => updatedSignal.Set())
.Returns(Task.CompletedTask);
// Update llama internamente a FindById otra vez (en Update)
_pointOfCareRepositoryMock
.Setup(m => m.FindById(pocToCheck.Id))
.ReturnsAsync(pocToCheck);
// 5) Ejecutar (async void) y esperar a que se dispare el update
_pointOfCareService.CheckNextAdmission(patientLocationId);
// Espera razonable a que termine la operación asíncrona interna
var completed = updatedSignal.Wait(TimeSpan.FromSeconds(1));
Assert.That(completed, Is.True, "CheckNextAdmission no disparó Update a tiempo.");
// Assert
// a) Se llamó a FindById (vía caché)
_pointOfCareRepositoryMock.Verify(m => m.FindById(patientLocationId), Times.AtLeastOnce);
// b) Se llamó a Update con el PoC actualizado: Status Reserved + Admission asignada
_pointOfCareRepositoryMock.Verify(m => m.Update(
It.Is<PointOfCare>(p =>
p.Id == pocToCheck.Id &&
p.Status == StatusEnum.PointOfCare.Reserved &&
p.AdmissionId == nextAdmission.Id &&
p.Admission == nextAdmission)
), Times.Once);
// c) NO verifiques FindByIdAllConfig: en CheckNextAdmission no se usa esa ruta
}
[Test]
public async Task FindByRoom_ValidRoom_CallsRepositoryFindByRoom()
{
// Arrange
const string room = "TestRoom";
var expectedPointOfCares = new List<PointOfCare>();
_pointOfCareRepositoryMock.Setup(m => m.FindByRoom(room)).ReturnsAsync(expectedPointOfCares);
// Act
var result = await _pointOfCareService.FindByRoom(room);
// Assert
Assert.That(result, Is.EqualTo(expectedPointOfCares));
_pointOfCareRepositoryMock.Verify(m => m.FindByRoom(room), Times.Once);
}
[Test]
public async Task FindByBed_ValidBed_CallsRepositoryFindByBed()
{
// Arrange
const string bed = "TestBed";
var expectedPointOfCares = new List<PointOfCare>();
_pointOfCareRepositoryMock.Setup(m => m.FindByBed(bed)).ReturnsAsync(expectedPointOfCares);
// Act
var result = await _pointOfCareService.FindByBed(bed);
// Assert
Assert.That(result, Is.EqualTo(expectedPointOfCares));
_pointOfCareRepositoryMock.Verify(m => m.FindByBed(bed), Times.Once);
}
}
@@ -0,0 +1,62 @@
using adas_core.Domain.Models.AppSettings;
using adas_core.Infrastructure.Services;
using EasyNetQ;
using EasyNetQ.SystemMessages;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Moq;
namespace adas_core.Test.Services;
[TestFixture]
public class PublisherServiceTest
{
//private static readonly DateTime now = DateTime.Now;
//private static readonly ObjectId patientId = ObjectId.GenerateNewId();
[SetUp]
public void Setup()
{
//advancedBusMock = new Mock<IAdvancedBus>();
_optionsRabbitMqSettings = Options.Create(_rabbitMqSettings);
_logger = new Mock<ILogger<PublisherService>>();
_publisherService = new PublisherService(
_optionsRabbitMqSettings,
_logger.Object);
}
private PublisherService _publisherService = null!;
//private Mock<IAdvancedBus> advancedBusMock;
private readonly RabbitMqSettings _rabbitMqSettings = new()
{
ObservationsQueue = "Observations"
};
private IOptions<RabbitMqSettings> _optionsRabbitMqSettings = null!;
private Mock<ILogger<PublisherService>> _logger = null!;
[Test]
public void SendMessage_Return_true()
{
var newMessage = new Message<string>();
var result = _publisherService.SendMessage(newMessage, _rabbitMqSettings.ObservationsQueue);
Assert.That(result, Is.Not.Null);
}
[Test]
public void SendMessage_Error_Return_true()
{
var newMessage = new Message<Error>();
var result = _publisherService.SendMessageError(newMessage, _rabbitMqSettings.ObservationsQueue);
Assert.That(result, Is.Not.Null);
}
}
+461
View File
@@ -0,0 +1,461 @@
using System.Security.Claims;
using adas_core.Application.Repositories.Interfaces;
using adas_core.Application.Services;
using adas_core.Application.Services.Interfaces;
using adas_core.Application.Subscriptions;
using adas_core.Domain.Enums;
using adas_core.Domain.Models;
using adas_core.Domain.Models.AppSettings;
using adas_core.Domain.Models.Filter;
using adas_core.Domain.Models.MongoModels;
using adas_core.Domain.Models.Pumps;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using MongoDB.Bson;
using Moq;
using Options = Microsoft.Extensions.Options.Options;
namespace adas_core.Test.Services;
[TestFixture]
public class PumpServiceTest
{
private PumpService _service = null!;
private Mock<IPumpObservationRepository> _obsRepo = null!;
private Mock<IPumpStateRepository> _stateRepo = null!;
private Mock<IPumpAlarmEventRepository> _alarmEventRepo = null!;
private Mock<IPumpAlarmStateRepository> _alarmStateRepo = null!;
private Mock<IPumpArchiveRepository> _archiveRepo = null!;
private Mock<IPatientService> _patientSvc = null!;
private Mock<IConfigPumpsService> _configPumps = null!;
private Mock<ISubscribersService> _subs = null!;
private Mock<IClientMessageService> _clientMsg = null!;
private Mock<IConfigUnitsService> _configUnits = null!;
private Mock<ICalculatedObservationsService> _calcObs = null!;
private Lazy<ICalculatedObservationsService> _lazyCalc = null!;
private Mock<IHttpContextAccessor> _http = null!;
private Mock<ILocalAuditService> _audit = null!;
private Mock<ILogger<PumpService>> _logger = null!;
private static readonly ObjectId PatientId = ObjectId.GenerateNewId();
private static readonly DateTime Now = DateTime.UtcNow;
[SetUp]
public void Setup()
{
_obsRepo = new Mock<IPumpObservationRepository>();
_stateRepo = new Mock<IPumpStateRepository>();
_alarmEventRepo = new Mock<IPumpAlarmEventRepository>();
_alarmStateRepo = new Mock<IPumpAlarmStateRepository>();
_archiveRepo = new Mock<IPumpArchiveRepository>();
_patientSvc = new Mock<IPatientService>();
_configPumps = new Mock<IConfigPumpsService>();
_subs = new Mock<ISubscribersService>();
_clientMsg = new Mock<IClientMessageService>();
_calcObs = new Mock<ICalculatedObservationsService>();
_lazyCalc = new Lazy<ICalculatedObservationsService>(() => _calcObs.Object);
_http = new Mock<IHttpContextAccessor>();
_audit = new Mock<ILocalAuditService>();
_logger = new Mock<ILogger<PumpService>>();
_configUnits = new Mock<IConfigUnitsService>();
var principal = new ClaimsPrincipal(
new ClaimsIdentity([new Claim(ClaimTypes.Name, "test")], "mock"));
_http.Setup(x => x.HttpContext)
.Returns(new DefaultHttpContext { User = principal });
_calcObs.Setup(x => x.Map(It.IsAny<PumpObservation>()))
.ReturnsAsync((PumpObservation o) => o);
var api = Options.Create(new ApiSettings
{
PumpExpiresSeconds = 5,
SendPumpsZero = false
});
_service = new PumpService(
_obsRepo.Object,
_stateRepo.Object,
_alarmEventRepo.Object,
_alarmStateRepo.Object,
_archiveRepo.Object,
_patientSvc.Object,
_configPumps.Object,
api,
_logger.Object,
_subs.Object,
_clientMsg.Object,
_lazyCalc,
_http.Object,
_audit.Object,
_configUnits.Object
);
_configPumps.Setup(x => x.Map(It.IsAny<PumpObservation>()))
.ReturnsAsync((PumpObservation o) => o);
_configUnits.Setup(x => x.Map(It.IsAny<PumpObservation>()))
.ReturnsAsync((PumpObservation o) => o);
}
// --------------------------------------------------------------
// SAVE REQUEST — casos básicos
// --------------------------------------------------------------
[Test]
public async Task SaveRequest_Returns_When_No_Observations()
{
var req = new ApiRequest { Type = "ORU_R01" };
await _service.SaveRequest(req);
_obsRepo.Verify(r => r.InsertAsync(It.IsAny<PumpObservation>()), Times.Never);
}
[Test]
public async Task SaveRequest_UnknownType_DoesNotInsert()
{
var req = new ApiRequest
{
Type = "UNKNOWN",
PumpObservation = new PumpObservation { Time = Now }
};
await _service.SaveRequest(req);
_obsRepo.Verify(r => r.InsertAsync(It.IsAny<PumpObservation>()), Times.Never);
}
[Test]
public async Task SaveRequest_Converts_SingleObservation_ToList()
{
var obs = new PumpObservation { Time = Now };
var req = new ApiRequest
{
Type = "ORU_R01",
PumpObservation = obs,
PatientNumber = "123"
};
_patientSvc.Setup(p => p.FindPatientByApiRequest(req))
.ReturnsAsync(new Patient { Id = PatientId });
await _service.SaveRequest(req);
Assert.That(req.PumpObservations, Has.Count.EqualTo(1));
}
[Test]
public async Task SaveRequest_SetsExpires_BeforeInsert()
{
var obs = new PumpObservation
{
Time = Now,
DeviceId = "D1"
};
var req = new ApiRequest
{
Type = "ORU_R01",
PumpObservation = obs,
PatientNumber = "1"
};
_patientSvc.Setup(x => x.FindPatientByApiRequest(req))
.ReturnsAsync(new Patient { Id = PatientId });
await _service.SaveRequest(req);
_obsRepo.Verify(r => r.InsertAsync(
It.Is<PumpObservation>(o => o.Expires == 5)), Times.Once);
}
// --------------------------------------------------------------
// PROCESS ALARM
// --------------------------------------------------------------
[Test]
public async Task SaveRequest_ORU_R40_CreatesAlarmEvent()
{
var obs = new PumpObservation
{
Time = Now,
DeviceId = "D1",
AlarmType = PumpEnum.AlarmType.Occlusion,
EventPhase = PumpEnum.EventPhase.Start
};
var req = new ApiRequest { Type = "ORU_R40", PumpObservation = obs };
_patientSvc.Setup(x => x.FindPatientByApiRequest(req))
.ReturnsAsync(new Patient { Id = PatientId });
await _service.SaveRequest(req);
_alarmEventRepo.Verify(r => r.InsertAsync(It.IsAny<PumpAlarmEvent>()), Times.Once);
_obsRepo.Verify(r => r.InsertAsync(It.IsAny<PumpObservation>()), Times.Never);
}
[Test]
public async Task ProcessAlarm_End_RemovesAlarmState()
{
var obs = new PumpObservation
{
Time = Now,
DeviceId = "DX",
AlarmType = PumpEnum.AlarmType.Occlusion,
AlarmTypeMdc = "H1",
EventPhase = PumpEnum.EventPhase.End
};
var req = new ApiRequest { Type = "ORU_R40", PumpObservation = obs };
_patientSvc.Setup(x => x.FindPatientByApiRequest(req))
.ReturnsAsync(new Patient { Id = PatientId });
await _service.SaveRequest(req);
_alarmStateRepo.Verify(r => r.RemoveAsync("DX", PumpEnum.AlarmType.Occlusion, "H1"), Times.Once);
}
// --------------------------------------------------------------
// SNAPSHOT DE BOMBA
// --------------------------------------------------------------
[Test]
public async Task SaveRequest_CreatesPumpState_IfNotExists()
{
var obs = new PumpObservation { Time = Now, DeviceId = "P1" };
var req = new ApiRequest { Type = "ORU_R01", PumpObservation = obs, PatientNumber = "1" };
_patientSvc.Setup(x => x.FindPatientByApiRequest(req))
.ReturnsAsync(new Patient { Id = PatientId });
_stateRepo.Setup(r => r.FindByDeviceIdAsync("P1"))
.ReturnsAsync((PumpState?)null);
await _service.SaveRequest(req);
_stateRepo.Verify(r => r.UpsertAsync(It.Is<PumpState>(s => s.DeviceId == "P1")), Times.Once);
}
// --------------------------------------------------------------
// BROADCAST
// --------------------------------------------------------------
[Test]
public async Task SaveRequest_NoSubscribers_NoBroadcast()
{
var obs = new PumpObservation { Time = Now, DeviceId = "BR1", PatientId = PatientId };
var patient = new Patient
{
Id = PatientId,
Location = new PatientLocation("U1", "B1")
};
var req = new ApiRequest
{
Type = "ORU_R01",
PumpObservation = obs,
PatientNumber = "1"
};
_subs.Setup(x => x.GetSubscribers()).Returns([]);
_patientSvc.Setup(x => x.FindPatientByApiRequest(req))
.ReturnsAsync(patient);
await _service.SaveRequest(req);
_clientMsg.Verify(r => r.SendAsync(It.IsAny<string>(), It.IsAny<OperationType>(), It.IsAny<object>()),
Times.Never);
}
[Test]
public async Task SaveRequest_WithSubscribers_UsesReqLocation_AndSendsBroadcast()
{
// Arrange
var obs = new PumpObservation
{
Time = Now,
DeviceId = "D22",
PatientId = null // <- clave para que se use req.Location
};
var req = new ApiRequest
{
Type = "ORU_R01",
PumpObservation = obs,
Location = new PatientLocation("UCI5C", "Box4", "Room1"),
PatientNumber = "437537"
};
var subscriber = new WsSubscriber("sub1")
{
Locations = [ new PatientLocation("UCI5C", "Box4", "Room1") ]
};
// 1) NO devolver paciente en FindPatientByApiRequest -> fuerza uso de req. Location
_patientSvc.Setup(p => p.FindPatientByApiRequest(req))
.ReturnsAsync((Patient?)null);
// 2) Suscriptores con la misma ubicación que req.Location
_subs.Setup(x => x.GetSubscribers())
.Returns([subscriber]);
// 3) Evitar null en alarmas activas al enumerar (foreach)
_alarmStateRepo.Setup(r => r.FindAllActiveByDeviceAsync("D22"))
.ReturnsAsync(Enumerable.Empty<PumpAlarmState>());
// 4) Snapshot: por claridad, fuerza que se cree uno nuevo
_stateRepo.Setup(r => r.FindByDeviceIdAsync("D22"))
.ReturnsAsync((PumpState?)null);
// Map mínimo para que avance el flujo
_configPumps.Setup(m => m.Map(It.IsAny<PumpObservation>()))
.ReturnsAsync((PumpObservation o) => o);
_configUnits.Setup(m => m.Map(It.IsAny<PumpObservation>()))
.ReturnsAsync((PumpObservation o) => o);
// Act
await _service.SaveRequest(req);
// Assert
_clientMsg.Verify(x =>
x.SendAsync("sub1", OperationType.Pump, It.IsAny<PumpState>()),
Times.Once);
// No se envían PumpAlarm si no hay activas
_clientMsg.Verify(x =>
x.SendAsync("sub1", OperationType.PumpAlarm, It.IsAny<object>()),
Times.Never);
}
// --------------------------------------------------------------
// RETENCIÓN — DeleteOlderDays
// --------------------------------------------------------------
[Test]
public async Task SaveRequest_Retention_DeleteOlderDays_CallsRepo()
{
var obs = new PumpObservation { Time = Now, DeviceId = "R1", PatientId = PatientId };
var req = new ApiRequest { Type = "ORU_R01", PumpObservation = obs, PatientNumber = "1" };
_patientSvc.Setup(x => x.FindPatientByApiRequest(req))
.ReturnsAsync(new Patient { Id = PatientId });
_configPumps.Setup(x => x.RetentionActions(It.IsAny<PumpObservation>()))
.ReturnsAsync(new ObservatitonRetentionResult
{
RetentionPolicy = RetentionPolicy.DeleteOlderDays,
RetentionPolicyValue = 7
});
await _service.SaveRequest(req);
_obsRepo.Verify(r => r.DeleteOlderThanDaysAsync(7, null), Times.Once);
}
// --------------------------------------------------------------
// PAGINACIÓN
// --------------------------------------------------------------
[Test]
public async Task GetPaginatedPump_ByPatient_Works()
{
var obs = new List<PumpObservation>
{
new() { Time = Now.AddMinutes(-1), PatientId = PatientId },
new() { Time = Now.AddMinutes(-5), PatientId = PatientId }
};
_obsRepo.Setup(r => r.FindByPatientId(PatientId))
.ReturnsAsync(obs);
var fileredRequest = new FilteredRequest
{
PatientId = PatientId.ToString()
};
var filter = new PaginationFilter(1, 1, fileredRequest);
var result = await _service.GetPaginatedPump(filter);
using (Assert.EnterMultipleScope())
{
Assert.That(result!.Data, Has.Count.EqualTo(1));
Assert.That(result.Data[0].Time, Is.EqualTo(Now.AddMinutes(-1)).Within(TimeSpan.FromMilliseconds(2)));
}
}
// --------------------------------------------------------------
// ARCHIVO
// --------------------------------------------------------------
[Test]
public async Task ArchiveByPatientId_InsertsArchive_ThenDeletes()
{
var list = new List<PumpObservation>
{
new() { Id = ObjectId.GenerateNewId(), PatientId = PatientId }
};
_obsRepo.Setup(r => r.FindByPatientId(PatientId)).ReturnsAsync(list);
await _service.ArchiveByPatientId(PatientId);
_archiveRepo.Verify(r => r.InsertManyAsync(list), Times.Once);
_obsRepo.Verify(r => r.DeleteByPatientId(PatientId), Times.Once);
_alarmEventRepo.Verify(r => r.DeleteByPatientId(PatientId), Times.Once);
_alarmStateRepo.Verify(r => r.DeleteByPatientId(PatientId), Times.Once);
}
// --------------------------------------------------------------
// UPDATE MANY
// --------------------------------------------------------------
[Test]
public async Task UpdateManyObjectId_UpdatesObs_Alarms_States()
{
var oldId = ObjectId.GenerateNewId();
var newId = ObjectId.GenerateNewId();
_obsRepo.Setup(r => r.UpdateManyObjectIdByFieldAsync("patientId", newId, oldId))
.ReturnsAsync(3);
_alarmEventRepo.Setup(r => r.UpdateManyObjectIdByFiledNameAsync("patientId", newId, oldId))
.ReturnsAsync(1);
_alarmStateRepo.Setup(r => r.UpdateManyObjectIdByFieldNameAsync("patientId", newId, oldId))
.ReturnsAsync(2);
await _service.UpdateManyObjectId("patientId", newId, oldId);
}
// --------------------------------------------------------------
// FIND LAST OBSERVATIONS
// --------------------------------------------------------------
[Test]
public async Task FindLastPumpObservations_ReturnsOrdered()
{
var items = new List<PumpObservation>
{
new() { Time = Now.AddMinutes(-10) },
new() { Time = Now.AddMinutes(-1) }
};
_obsRepo.Setup(r => r.FindByPatientId(PatientId))
.ReturnsAsync(items);
var result = await _service.FindLastPumpObservations(PatientId, 1);
Assert.That(result, Has.Count.EqualTo(1));
Assert.That(result[0].Time, Is.EqualTo(items[1].Time));
}
// --------------------------------------------------------------
// INSERT MANUAL
// --------------------------------------------------------------
[Test]
public async Task InsertPumpObservation_Inserts_AndBroadcasts()
{
var obs = new PumpObservation
{
DeviceId = "D11",
PatientId = PatientId,
Time = Now
};
_stateRepo.Setup(r => r.FindByDeviceIdAsync("D11"))
.ReturnsAsync((PumpState?)null);
_subs.Setup(x => x.GetSubscribers()).Returns([]);
await _service.InsertPumpObservation(obs);
_obsRepo.Verify(r => r.InsertAsync(It.IsAny<PumpObservation>()), Times.Once);
_stateRepo.Verify(r => r.UpsertAsync(It.IsAny<PumpState>()), Times.Once);
}
}
@@ -0,0 +1,173 @@
using System.Security.Claims;
using adas_core.Application.Repositories.Interfaces;
using adas_core.Application.Services;
using adas_core.Application.Services.Interfaces;
using adas_core.Domain.Models;
using adas_core.Domain.Models.MongoModels;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using MongoDB.Bson;
using Moq;
namespace adas_core.Test.Services;
[TestFixture]
public class RecordingAlertServiceTest
{
[SetUp]
public void Setup()
{
_patientServiceMock = new Mock<IPatientService>();
_patientServiceLazy = new Lazy<IPatientService>(() => _patientServiceMock.Object);
_configObservationServiceMock = new Mock<IConfigObservationService>();
_recordingAlertRepositoryMock = new Mock<IRecordingAlertRepository>();
_recordingAlertArchiveRepositoryMock = new Mock<IRecordingAlertArchiveRepository>();
_clientMessageServiceMock = new Mock<IClientMessageService>();
_subscribersServiceMock = new Mock<ISubscribersService>();
var userClaims = new ClaimsPrincipal(new ClaimsIdentity([
new Claim(ClaimTypes.Name, "TestUser")
], "mock"));
var httpContextMock = new DefaultHttpContext
{
User = userClaims
};
_httpContextAccessorMock.Setup(accessor => accessor.HttpContext)
.Returns(httpContextMock);
//optionsApiSettings = Microsoft.Extensions.Options.Options.Create<ApiSettings>(apiSettings);
_logger = new Mock<ILogger<RecordingAlertService>>();
_recordingAlertService = new RecordingAlertService(
_patientServiceLazy,
_configObservationServiceMock.Object,
_recordingAlertRepositoryMock.Object,
_recordingAlertArchiveRepositoryMock.Object,
//optionsApiSettings,
_logger.Object,
_clientMessageServiceMock.Object,
_subscribersServiceMock.Object,
_httpContextAccessorMock.Object,
_auditServiceMock.Object
);
}
private RecordingAlertService _recordingAlertService = null!;
private Mock<IPatientService> _patientServiceMock = null!;
private Lazy<IPatientService> _patientServiceLazy = null!;
private Mock<IConfigObservationService> _configObservationServiceMock = null!;
private Mock<IRecordingAlertRepository> _recordingAlertRepositoryMock = null!;
private Mock<IRecordingAlertArchiveRepository> _recordingAlertArchiveRepositoryMock = null!;
private Mock<IClientMessageService> _clientMessageServiceMock = null!;
private Mock<ISubscribersService> _subscribersServiceMock = null!;
private readonly Mock<IHttpContextAccessor> _httpContextAccessorMock = new();
private readonly Mock<ILocalAuditService> _auditServiceMock = new();
//private readonly ApiSettings apiSettings = new ()
//{
//};
//IOptions<ApiSettings> optionsApiSettings;
private Mock<ILogger<RecordingAlertService>> _logger = null!;
private static readonly DateTime Now = DateTime.Now;
private static readonly ObjectId PatientId = ObjectId.GenerateNewId();
[Test]
public async Task SaveRequest_Not_RecordingAlert_Not_ORU_R01_Return_not_insert()
{
var apiRequest = new ApiRequest();
await _recordingAlertService.SaveRequest(apiRequest);
_recordingAlertRepositoryMock.Verify(d => d.InsertOneAsync(It.IsAny<PatientRecordingAlert>()), Times.Never);
}
[Test]
public async Task SaveRequest_patientNumber_and_pointOfCare_null_Return_not_insert()
{
var apiRequest = new ApiRequest
{
Type = "ORU_R11",
MessageTime = Now
};
await _recordingAlertService.SaveRequest(apiRequest);
_recordingAlertRepositoryMock.Verify(d => d.InsertOneAsync(It.IsAny<PatientRecordingAlert>()), Times.Never);
}
[Test]
public async Task SaveRequest_Not_Find_Patient_Return_not_insert()
{
var person = new Person
{
FirstName = "Miguel",
LastName = "Villanueva",
Ids = new Dictionary<string, string> { { "MR", "437537" } }
};
var apiRequest = new ApiRequest
{
Location = new PatientLocation("UCI5C", "Box4"),
Patient = person,
PatientNumber = "437537",
Type = "ORU_R01",
PatientId = PatientId.ToString(),
MessageTime = Now
};
await _recordingAlertService.SaveRequest(apiRequest);
_recordingAlertRepositoryMock.Verify(d => d.InsertOneAsync(It.IsAny<PatientRecordingAlert>()), Times.Never);
}
[Test]
public async Task SaveRequest_Alert_Return_insert()
{
var person = new Person
{
FirstName = "Miguel",
LastName = "Villanueva",
Ids = new Dictionary<string, string> { { "MR", "437537" } }
};
var patient = new Patient
{
Id = ObjectId.GenerateNewId(),
UnitString = "UCI5C",
Bed = "Box4",
PatientNumber = "437537",
Person = person
};
var recordingAlert = new PatientRecordingAlert
{
IsRecording = true
};
var apiRequest = new ApiRequest
{
Location = new PatientLocation("UCI5C", "Box4"),
Patient = person,
PatientNumber = "437537",
Type = "ORU_R01",
PatientId = PatientId.ToString(),
MessageTime = Now,
RecordingAlert = recordingAlert
};
_patientServiceMock.Setup(p => p.FindPatientByApiRequest(apiRequest)).ReturnsAsync(patient);
_configObservationServiceMock.Setup(c => c.RetentionActions(It.IsAny<PatientRecordingAlert>()))
.ReturnsAsync((ObservatitonRetentionResult?)null);
await _recordingAlertService.SaveRequest(apiRequest);
_recordingAlertRepositoryMock.Verify(d => d.InsertOneAsync(It.IsAny<PatientRecordingAlert>()), Times.Once);
}
}
@@ -0,0 +1,187 @@
using System.Net;
using System.Text;
using adas_core.Application.Services;
using adas_core.Application.Services.Interfaces;
using adas_core.Domain.Models;
using adas_core.Domain.Models.AppSettings;
using adas_core.Domain.Models.Recording;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Moq;
using Moq.Protected;
using Newtonsoft.Json;
using Error = EasyNetQ.SystemMessages.Error;
using Options = Microsoft.Extensions.Options.Options;
namespace adas_core.Test.Services;
[TestFixture]
public class RecordingServiceTest
{
[SetUp]
public void Setup()
{
_optionsApiSettings = Options.Create(_apiSettings);
_optionsRabbitMqSettings = Options.Create(_rabbitMqSettings);
_optionsRecordingSettings = Options.Create(_recordingSettings);
_publisherServiceMock = new Mock<IPublisherService>();
_logger = new Mock<ILogger<RecordingService>>();
_authServiceMock = new Mock<IAuthService>();
_httpClientFactoryMock = new Mock<IHttpClientFactory>();
_httpMessageHandlerMock = new Mock<HttpMessageHandler>();
_clientMessageServiceMock = new Mock<IClientMessageService>();
_subscribersServiceMock = new Mock<ISubscribersService>();
_patientServiceMock = new Mock<Lazy<IPatientService>>();
var client = new HttpClient(_httpMessageHandlerMock.Object);
_httpClientFactoryMock.Setup(c => c.CreateClient(It.IsAny<string>())).Returns(client);
_recordingService = new RecordingService(
_optionsRabbitMqSettings,
_optionsRecordingSettings,
_logger.Object,
_httpClientFactoryMock.Object,
_publisherServiceMock.Object,
_authServiceMock.Object,
_optionsApiSettings,
_clientMessageServiceMock.Object,
_subscribersServiceMock.Object,
_patientServiceMock.Object
);
// Set up the mock object to return a specific value when a method is called
_publisherServiceMock.Setup(x => x.SendMessage(It.IsAny<object>(), It.IsAny<string>())).ReturnsAsync(true);
_publisherServiceMock.Setup(x => x.SendMessageError(It.IsAny<Error>(), It.IsAny<string>())).ReturnsAsync(true);
}
private RecordingService _recordingService = null!;
//Mock<PublisherService> mockSingleton = null!;
private Mock<IHttpClientFactory> _httpClientFactoryMock = null!;
private Mock<HttpMessageHandler> _httpMessageHandlerMock = null!;
private Mock<IPublisherService> _publisherServiceMock = null!;
private Mock<IAuthService> _authServiceMock = null!;
private Mock<Lazy<IPatientService>> _patientServiceMock = null!;
private readonly RabbitMqSettings _rabbitMqSettings = new()
{
RecordingQueue = "recordings"
};
private IOptions<RabbitMqSettings> _optionsRabbitMqSettings = null!;
private readonly RecordingSettings _recordingSettings = new()
{
RecordingApiUrl = "http://localhost:8082"
};
private IOptions<RecordingSettings> _optionsRecordingSettings = null!;
private readonly ApiSettings _apiSettings = new()
{
StartRecordingWithoutPatientNumber = false
};
private IOptions<ApiSettings> _optionsApiSettings = null!;
private Mock<ILogger<RecordingService>> _logger = null!;
private Mock<IClientMessageService> _clientMessageServiceMock = null!;
private Mock<ISubscribersService> _subscribersServiceMock = null!;
[Test]
public async Task GetRecordings_Return_Empty()
{
var httpResponseMessage = new HttpResponseMessage
{
StatusCode = HttpStatusCode.Unauthorized,
Content = new StringContent("Content text.")
};
var recordingData = new List<RecordingData>();
_authServiceMock.Setup(s => s.GetToken()).ReturnsAsync("abc");
_httpMessageHandlerMock.Protected()
.Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(),
ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(httpResponseMessage);
var result = await _recordingService.GetRecordings(4);
Assert.That(result, Is.Not.Null);
//Assert.AreEqual(result, recordingData);
Assert.That(result, Is.EqualTo(recordingData));
}
[Test]
public async Task GetRecordings_Return_RecordingData()
{
var patient = new Patient
{
Id = "id",
FirstName = "firstName",
LastName = "lastName"
};
var recordingData = new List<RecordingData>
{
new()
{
Patient = patient,
RoomId = 4,
Status = "INITIALIZED"
}
};
var httpResponseMessage = new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent(JsonConvert.SerializeObject(recordingData), Encoding.UTF8, "application/json")
};
_httpMessageHandlerMock.Protected()
.Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(),
ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(httpResponseMessage);
_authServiceMock.Setup(s => s.GetToken()).ReturnsAsync("abc");
var result = await _recordingService.GetRecordings(4);
Assert.That(result, Is.Not.Null);
using (Assert.EnterMultipleScope())
{
Assert.That(recordingData[0].Status, Is.EqualTo(result![0].Status));
Assert.That(recordingData[0].Patient?.Id, Is.EqualTo(result[0].Patient?.Id));
Assert.That(recordingData[0].Patient?.LastName, Is.EqualTo(result[0].Patient?.LastName));
Assert.That(recordingData[0].Patient?.FirstName, Is.EqualTo(result[0].Patient?.FirstName));
Assert.That(recordingData[0].RoomId, Is.EqualTo(result[0].RoomId));
}
}
[Test]
public Task SaveRequest()
{
ApiRequest apiRequest = new();
var httpResponseMessage = new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent("Content text.")
};
_httpMessageHandlerMock.Protected()
.Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(),
ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(httpResponseMessage);
Func<Task> act = async () => await _recordingService.SaveRequest(apiRequest);
Assert.ThrowsAsync<NotImplementedException>(act);
return Task.CompletedTask;
}
}
@@ -0,0 +1,175 @@
using System.Diagnostics;
using adas_core.Application.Services.Caching;
using Moq;
using StackExchange.Redis;
namespace adas_core.Test.Services;
[TestFixture]
public class RedisLockProviderTest
{
private Mock<IDatabase> _mockDb = null!;
private RedisLockProvider _provider = null!;
[SetUp]
public void SetUp()
{
_mockDb = new Mock<IDatabase>();
_provider = new RedisLockProvider(() => _mockDb.Object);
}
#region TC-45
[Test]
public async Task AcquireAsync_ReturnsTrue_AndStoresToken_WhenRedisAcceptsNxSet()
{
_mockDb
.Setup(db => db.StringSetAsync(
It.IsAny<RedisKey>(),
It.IsAny<RedisValue>(),
It.IsAny<TimeSpan?>(),
It.IsAny<When>()))
.ReturnsAsync(true);
_mockDb
.Setup(db => db.ScriptEvaluateAsync(
It.IsAny<string>(),
It.IsAny<RedisKey[]?>(),
It.IsAny<RedisValue[]?>(),
It.IsAny<CommandFlags>()))
.Returns(Task.FromResult<RedisResult>(null!));
var result = await _provider.AcquireAsync("key", TimeSpan.FromSeconds(5));
Assert.That(result, Is.True);
_mockDb.Verify(db => db.StringSetAsync(
It.Is<RedisKey>(k => k == (RedisKey)"lock:key"),
It.IsAny<RedisValue>(),
(TimeSpan?)TimeSpan.FromSeconds(5),
When.NotExists), Times.Once());
await _provider.ReleaseAsync("key");
_mockDb.Verify(db => db.ScriptEvaluateAsync(
It.IsAny<string>(),
It.IsAny<RedisKey[]?>(),
It.IsAny<RedisValue[]?>(),
It.IsAny<CommandFlags>()), Times.Once());
}
#endregion
#region TC-46
[Test]
public async Task AcquireAsync_RetriesWithDelays_UntilNxSucceeds()
{
_mockDb
.SetupSequence(db => db.StringSetAsync(
It.IsAny<RedisKey>(),
It.IsAny<RedisValue>(),
It.IsAny<TimeSpan?>(),
It.IsAny<When>()))
.ReturnsAsync(false)
.ReturnsAsync(false)
.ReturnsAsync(false)
.ReturnsAsync(true);
var sw = Stopwatch.StartNew();
var result = await _provider.AcquireAsync("key", TimeSpan.FromSeconds(1));
sw.Stop();
Assert.That(result, Is.True);
_mockDb.Verify(db => db.StringSetAsync(
It.IsAny<RedisKey>(),
It.IsAny<RedisValue>(),
It.IsAny<TimeSpan?>(),
It.IsAny<When>()), Times.Exactly(4));
Assert.That(sw.ElapsedMilliseconds, Is.GreaterThan(100));
}
#endregion
#region TC-47
[Test]
public async Task AcquireAsync_ReturnsFalse_AfterTimeoutWithMultipleRetries()
{
_mockDb
.Setup(db => db.StringSetAsync(
It.IsAny<RedisKey>(),
It.IsAny<RedisValue>(),
It.IsAny<TimeSpan?>(),
It.IsAny<When>()))
.ReturnsAsync(false);
var sw = Stopwatch.StartNew();
var result = await _provider.AcquireAsync("key", TimeSpan.FromMilliseconds(200));
sw.Stop();
Assert.That(result, Is.False);
Assert.That(sw.ElapsedMilliseconds, Is.GreaterThan(100));
_mockDb.Verify(db => db.StringSetAsync(
It.IsAny<RedisKey>(),
It.IsAny<RedisValue>(),
It.IsAny<TimeSpan?>(),
It.IsAny<When>()), Times.AtLeast(2));
}
#endregion
#region TC-48
[Test]
public async Task ReleaseAsync_CallsScriptEvaluateWithCorrectKeyAndToken()
{
RedisValue capturedToken = default;
_mockDb
.Setup(db => db.StringSetAsync(
It.IsAny<RedisKey>(),
It.IsAny<RedisValue>(),
It.IsAny<TimeSpan?>(),
It.IsAny<When>()))
.Callback<RedisKey, RedisValue, TimeSpan?, When>(
(_, v, _, _) => capturedToken = v)
.ReturnsAsync(true);
_mockDb
.Setup(db => db.ScriptEvaluateAsync(
It.IsAny<string>(),
It.IsAny<RedisKey[]?>(),
It.IsAny<RedisValue[]?>(),
It.IsAny<CommandFlags>()))
.Returns(Task.FromResult<RedisResult>(null!));
await _provider.AcquireAsync("key", TimeSpan.FromSeconds(5));
await _provider.ReleaseAsync("key");
_mockDb.Verify(db => db.ScriptEvaluateAsync(
It.IsAny<string>(),
It.Is<RedisKey[]?>(keys => keys != null && keys[0] == (RedisKey)"lock:key"),
It.Is<RedisValue[]?>(vals => vals != null && vals[0] == capturedToken),
It.IsAny<CommandFlags>()), Times.Once());
}
#endregion
#region TC-49
[Test]
public async Task ReleaseAsync_IsIdempotent_WhenCalledWithoutPriorAcquire()
{
_mockDb
.Setup(db => db.ScriptEvaluateAsync(
It.IsAny<string>(),
It.IsAny<RedisKey[]?>(),
It.IsAny<RedisValue[]?>(),
It.IsAny<CommandFlags>()))
.Returns(Task.FromResult<RedisResult>(null!));
await _provider.ReleaseAsync("key");
_mockDb.Verify(db => db.ScriptEvaluateAsync(
It.IsAny<string>(),
It.IsAny<RedisKey[]?>(),
It.IsAny<RedisValue[]?>(),
It.IsAny<CommandFlags>()), Times.Never());
}
#endregion
}
+251
View File
@@ -0,0 +1,251 @@
using System.Reflection;
using adas_core.Application.Services.Caching;
using adas_core.Domain.Models.AppSettings;
using Microsoft.Extensions.Logging;
using Moq;
using Newtonsoft.Json;
using StackExchange.Redis;
using Options = Microsoft.Extensions.Options.Options;
namespace adas_core.Test.Services;
[TestFixture]
public class RedisServiceTest
{
private record TestModel(string Name);
private Mock<IDatabase> _mockDb = null!;
private LockManagerService _lockMgr = null!;
[SetUp]
public void SetUp()
{
_mockDb = new Mock<IDatabase>();
_lockMgr = new LockManagerService(
new Mock<ILogger<LockManagerService>>().Object,
new InMemoryLockProvider());
}
private RedisService CreateSut(CacheSettings? settings = null, bool redisAvailable = true)
{
var sut = new RedisService(
Options.Create(settings ?? new CacheSettings()),
new Mock<ILogger<RedisService>>().Object,
_lockMgr);
SetField(sut, "_database", _mockDb.Object);
SetField(sut, "_isRedisAvailable", redisAvailable);
return sut;
}
private static void SetField(object target, string name, object? value)
=> typeof(RedisService)
.GetField(name, BindingFlags.NonPublic | BindingFlags.Instance)!
.SetValue(target, value);
private void SetupStringSetAsync()
=> _mockDb
.Setup(db => db.StringSetAsync(
It.IsAny<RedisKey>(), It.IsAny<RedisValue>(), It.IsAny<TimeSpan?>(),
It.IsAny<bool>(), It.IsAny<When>(), It.IsAny<CommandFlags>()))
.ReturnsAsync(true);
private void SetupKeyExpire()
=> _mockDb
.Setup(db => db.KeyExpire(
It.IsAny<RedisKey>(), It.IsAny<TimeSpan?>(),
It.IsAny<ExpireWhen>(), It.IsAny<CommandFlags>()))
.Returns(true);
#region TC-38
[Test]
public async Task GetOrSetObjectAsync_ExecutesFactory_WhenRedisUnavailable()
{
var sut = CreateSut(redisAvailable: false);
var factoryInvoked = false;
var result = await sut.GetOrSetObjectAsync<string>(
"patients:latestObs:abc",
() => { factoryInvoked = true; return Task.FromResult("result"); });
Assert.That(factoryInvoked, Is.True);
Assert.That(result, Is.EqualTo("result"));
_mockDb.Verify(db => db.StringGetAsync(It.IsAny<RedisKey>(), It.IsAny<CommandFlags>()), Times.Never);
_mockDb.Verify(db => db.StringSetAsync(It.IsAny<RedisKey>(), It.IsAny<RedisValue>(), It.IsAny<TimeSpan?>(), It.IsAny<bool>(), It.IsAny<When>(), It.IsAny<CommandFlags>()), Times.Never);
}
#endregion
#region TC-39
[Test]
public async Task GetOrSetObjectAsync_ReturnsCachedObject_WhenRedisHit()
{
var cached = new TestModel("cached");
_mockDb.Setup(db => db.StringGetAsync(It.IsAny<RedisKey>(), It.IsAny<CommandFlags>()))
.ReturnsAsync((RedisValue)JsonConvert.SerializeObject(cached));
SetupKeyExpire();
var sut = CreateSut();
var factoryInvoked = false;
var result = await sut.GetOrSetObjectAsync<TestModel>(
"patients:latestObs:abc",
() => { factoryInvoked = true; return Task.FromResult(new TestModel("fresh")); });
Assert.That(factoryInvoked, Is.False);
Assert.That(result?.Name, Is.EqualTo("cached"));
_mockDb.Verify(db => db.StringSetAsync(It.IsAny<RedisKey>(), It.IsAny<RedisValue>(), It.IsAny<TimeSpan?>(), It.IsAny<bool>(), It.IsAny<When>(), It.IsAny<CommandFlags>()), Times.Never);
}
#endregion
#region TC-40
[Test]
public async Task GetObjectAsync_CallsKeyExpire_WhenUpdateExpirationIsTrue()
{
var settings = new CacheSettings
{
Redis = new RedisSettings { Ttl = new TtlSettings { PatientsSeconds = 300 } }
};
_mockDb.Setup(db => db.StringGetAsync(It.IsAny<RedisKey>(), It.IsAny<CommandFlags>()))
.ReturnsAsync((RedisValue)JsonConvert.SerializeObject(new TestModel("hit")));
SetupKeyExpire();
var sut = CreateSut(settings);
await sut.GetObjectAsync<TestModel>("patients:latestObs:abc", updateExpiration: true);
_mockDb.Verify(
db => db.KeyExpire(
It.IsAny<RedisKey>(),
It.Is<TimeSpan?>(t => t == TimeSpan.FromSeconds(300)),
It.IsAny<ExpireWhen>(),
It.IsAny<CommandFlags>()),
Times.Once);
}
[Test]
public async Task GetObjectAsync_DoesNotCallKeyExpire_WhenUpdateExpirationIsFalse()
{
_mockDb.Setup(db => db.StringGetAsync(It.IsAny<RedisKey>(), It.IsAny<CommandFlags>()))
.ReturnsAsync((RedisValue)JsonConvert.SerializeObject(new TestModel("hit")));
var sut = CreateSut();
await sut.GetObjectAsync<TestModel>("patients:latestObs:abc", updateExpiration: false);
_mockDb.Verify(
db => db.KeyExpire(It.IsAny<RedisKey>(), It.IsAny<TimeSpan?>(), It.IsAny<ExpireWhen>(), It.IsAny<CommandFlags>()),
Times.Never);
}
#endregion
#region TC-41
[Test]
public async Task GetOrSetObjectAsync_InvokesFactoryAndPersists_WhenCacheMiss()
{
var settings = new CacheSettings
{
Redis = new RedisSettings { Ttl = new TtlSettings { PatientsSeconds = 300, PatientObservationsSeconds = 300} }
};
_mockDb.Setup(db => db.StringGetAsync(It.IsAny<RedisKey>(), It.IsAny<CommandFlags>()))
.ReturnsAsync(RedisValue.Null);
SetupStringSetAsync();
var sut = CreateSut(settings);
var expected = new TestModel("fresh");
var factoryInvoked = false;
var result = await sut.GetOrSetObjectAsync<TestModel>(
"patients:latestObs:abc",
() => { factoryInvoked = true; return Task.FromResult(expected); });
var expectedJson = JsonConvert.SerializeObject(expected);
Assert.That(factoryInvoked, Is.True);
Assert.That(result?.Name, Is.EqualTo("fresh"));
_mockDb.Verify(
db => db.StringSetAsync(
It.IsAny<RedisKey>(),
It.IsAny<RedisValue>(),
It.Is<TimeSpan?>(t => t == TimeSpan.FromSeconds(300)),
It.IsAny<bool>(),
It.IsAny<When>(),
It.IsAny<CommandFlags>()),
Times.Once);
It.Is<RedisValue>(v => v.Equals(expectedJson));
}
#endregion
#region TC-42
[Test]
public async Task GetOrSetObjectAsync_DoesNotPersist_WhenFactoryReturnsNull()
{
_mockDb.Setup(db => db.StringGetAsync(It.IsAny<RedisKey>(), It.IsAny<CommandFlags>()))
.ReturnsAsync(RedisValue.Null);
var sut = CreateSut();
var result = await sut.GetOrSetObjectAsync<TestModel?>(
"patients:latestObs:abc",
() => Task.FromResult<TestModel?>(null));
Assert.That(result, Is.Null);
_mockDb.Verify(
db => db.StringSetAsync(It.IsAny<RedisKey>(), It.IsAny<RedisValue>(), It.IsAny<TimeSpan?>(), It.IsAny<bool>(), It.IsAny<When>(), It.IsAny<CommandFlags>()),
Times.Never);
}
#endregion
#region TC-43
[Test]
public async Task GetObjectAsync_ReturnsObject_AndSkipsKeyExpire_WhenUpdateExpirationFalse()
{
var expected = new TestModel("data");
_mockDb.Setup(db => db.StringGetAsync(It.IsAny<RedisKey>(), It.IsAny<CommandFlags>()))
.ReturnsAsync((RedisValue)JsonConvert.SerializeObject(expected));
var sut = CreateSut();
var result = await sut.GetObjectAsync<TestModel>("patients:latestObs:abc", updateExpiration: false);
Assert.That(result?.Name, Is.EqualTo("data"));
_mockDb.Verify(
db => db.KeyExpire(It.IsAny<RedisKey>(), It.IsAny<TimeSpan?>(), It.IsAny<ExpireWhen>(), It.IsAny<CommandFlags>()),
Times.Never);
}
#endregion
#region TC-44
[Test]
public async Task SetObjectAsync_SerializesToJson_AndPersistsWithEntityTtl()
{
var settings = new CacheSettings
{
Redis = new RedisSettings { Ttl = new TtlSettings { PatientsSeconds = 600 } }
};
SetupStringSetAsync();
var sut = CreateSut(settings);
var obj = new TestModel("save-me");
var expectedJson = JsonConvert.SerializeObject(obj);
await sut.SetObjectAsync("patients:latestObs:abc", obj, null, true);
_mockDb.Verify(
db => db.StringSetAsync(
It.IsAny<RedisKey>(),
It.IsAny<RedisValue>(),
It.Is<TimeSpan?>(t => t == TimeSpan.FromSeconds(600)),
It.IsAny<bool>(),
It.IsAny<When>(),
It.IsAny<CommandFlags>()),
Times.Once);
It.Is<RedisValue>(v => v.Equals(expectedJson));
}
#endregion
}
+241
View File
@@ -0,0 +1,241 @@
using System.Net;
using adas_core.Application.Repositories.Interfaces;
using adas_core.Application.Services.Interfaces;
using adas_core.Domain.Enums;
using adas_core.Domain.Models.MongoModels;
using adas_core.Infrastructure.Services;
using adas_core.module.Relays.Models;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Moq;
using Moq.Protected;
using Options = Microsoft.Extensions.Options.Options;
namespace adas_core.Test.Services;
[TestFixture]
public class RelayServiceTest
{
[SetUp]
public void Setup()
{
_logger = new Mock<ILogger<RelayService>>();
_httpClientFactoryMock = new Mock<IHttpClientFactory>();
_httpMessageHandlerMock = new Mock<HttpMessageHandler>();
_relaySettings.RecordingOrApiUrl = "http://localhost:8080";
_relaySettings.Cache = true;
_optionsRelaySettings = Options.Create(_relaySettings);
_pocServiceMock = new Mock<IPointOfCareService>();
_relayRepositoryMock = new Mock<IRelayRepository>();
_relayService = new RelayService(
//optionsApiSettings,
_logger.Object,
_httpClientFactoryMock.Object,
_optionsRelaySettings,
_pocServiceMock.Object,
_relayRepositoryMock.Object);
}
private RelayService _relayService = null!;
private Mock<IHttpClientFactory> _httpClientFactoryMock = null!;
private Mock<HttpMessageHandler> _httpMessageHandlerMock = null!;
private readonly RelaySettings _relaySettings = new();
private IOptions<RelaySettings> _optionsRelaySettings = null!;
private Mock<IPointOfCareService> _pocServiceMock = null!;
private Mock<IRelayRepository> _relayRepositoryMock = null!;
//readonly ApiSettings apiSettings = new ()
//{
//};
//IOptions<ApiSettings> optionsApiSettings;
private Mock<ILogger<RelayService>> _logger = null!;
[Test]
public async Task PowerOffAsync()
{
var relay = new Relay
{
Driver = "KMTronicV2",
Ip = "10.133.10.169",
Port = 80,
RelayNumber = 1,
RelayName = "Relay1",
Total = 8,
Username = "adas",
Password = "!HULPM22"
};
var httpResponseMessage = new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent("Test content")
};
_httpMessageHandlerMock.Protected()
.Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(),
ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(httpResponseMessage);
var client = new HttpClient(_httpMessageHandlerMock.Object);
_httpClientFactoryMock.Setup(c => c.CreateClient(It.IsAny<string>())).Returns(client);
await _relayService.PowerOff(relay);
}
[Test]
public async Task PowerOnAsync()
{
var relay = new Relay
{
Driver = "KMTronicV2",
Ip = "10.133.10.169",
Port = 80,
RelayNumber = 1,
RelayName = "Relay1",
Total = 8,
Username = "adas",
Password = "!HULPM22"
};
var httpResponseMessage = new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent("Test content")
};
_httpMessageHandlerMock.Protected()
.Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(),
ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(httpResponseMessage);
var client = new HttpClient(_httpMessageHandlerMock.Object);
_httpClientFactoryMock.Setup(c => c.CreateClient(It.IsAny<string>())).Returns(client);
await _relayService.PowerOn(relay);
}
[Test]
public async Task CheckRelayStatus_Return_On()
{
var relay = new Relay
{
Driver = "KMTronicV2",
Ip = "10.133.10.169",
Port = 80,
RelayNumber = 1,
RelayName = "Relay1",
Total = 8,
Username = "adas",
Password = "!HULPM22"
};
var httpResponseMessage = new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent("\"On")
};
_httpMessageHandlerMock.Protected()
.Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(),
ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(httpResponseMessage);
//httpMessageHandlerMock.Protected()
// .Setup<Task<string>>("ReadAsStringAsync", ItExpr.IsAny<string>(), ItExpr.IsAny<CancellationToken>())
// .ReturnsAsync("\\On");
var client = new HttpClient(_httpMessageHandlerMock.Object);
_httpClientFactoryMock.Setup(c => c.CreateClient(It.IsAny<string>())).Returns(client);
await _relayService.PowerOn(relay);
var result = await _relayService.CheckRelayStatus(relay);
//Assert.That(result, Is.Not.Null);
Assert.That(result, Is.EqualTo(RelayEnum.Status.On));
}
[Test]
public async Task CheckRelayStatus_Return_Off()
{
var relay = new Relay
{
Driver = "KMTronicV2",
Ip = "10.133.10.169",
Port = 80,
RelayNumber = 1,
RelayName = "Relay1",
Total = 8,
Username = "adas",
Password = "!HULPM22"
};
var httpResponseMessage = new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent("\"Off")
};
_httpMessageHandlerMock.Protected()
.Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(),
ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(httpResponseMessage);
var client = new HttpClient(_httpMessageHandlerMock.Object);
_httpClientFactoryMock.Setup(c => c.CreateClient(It.IsAny<string>())).Returns(client);
await _relayService.PowerOff(relay);
var result = await _relayService.CheckRelayStatus(relay);
//Assert.That(result, Is.Not.Null); //result nunca es null aquí
Assert.That(result, Is.EqualTo(RelayEnum.Status.Off));
}
[Test]
public async Task CheckRelayStatus_Return_Unknown()
{
var relay = new Relay
{
Driver = "KMTronicV2",
Ip = "10.133.10.169",
Port = 80,
RelayNumber = 1,
RelayName = "Relay1",
Total = 8,
Username = "adas",
Password = "!HULPM22"
};
var httpResponseMessage = new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent("\\Off")
};
_httpMessageHandlerMock.Protected()
.Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(),
ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(httpResponseMessage);
var client = new HttpClient(_httpMessageHandlerMock.Object);
_httpClientFactoryMock.Setup(c => c.CreateClient(It.IsAny<string>())).Returns(client);
var result = await _relayService.CheckRelayStatus(relay);
//Assert.That(result, Is.Not.Null);
Assert.That(result, Is.EqualTo(RelayEnum.Status.Unknown));
}
}
@@ -0,0 +1,590 @@
using System.Collections.Specialized;
using adas_core.Application.Services;
using adas_core.Application.Services.Interfaces;
using adas_core.Domain.Enums;
using adas_core.Domain.Models;
using adas_core.Domain.Models.AppSettings;
using adas_core.Domain.Models.MongoModels;
using adas_core.Domain.Models.Providers;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MongoDB.Bson;
using Moq;
using Quartz;
using Quartz.Impl;
using Options = Microsoft.Extensions.Options.Options;
namespace adas_core.Test.Services;
[TestFixture]
public class SchedulerServiceTest
{
[OneTimeSetUp]
public async Task SetUp()
{
#region [Services Mock seUp]
_treatmentServiceMock = new Mock<ITreatmentService>();
_treatmentServiceLazy = new Lazy<ITreatmentService>(() => _treatmentServiceMock.Object);
_patientServiceMock = new Mock<IPatientService>();
_patientServiceLazy = new Lazy<IPatientService>(() => _patientServiceMock.Object);
_medicineServiceMock = new Mock<IMedicineService>();
_medicineServiceLazy = new Lazy<IMedicineService>(() => _medicineServiceMock.Object);
_observationServiceMock = new Mock<IObservationService>();
_observationServiceLazy = new Lazy<IObservationService>(() => _observationServiceMock.Object);
_configObservationServiceMock = new Mock<IConfigObservationService>();
var configObservationServiceLazy =
new Lazy<IConfigObservationService>(() => _configObservationServiceMock.Object);
_logger = new Mock<ILogger<SchedulerService>>();
_httpClientFactoryMock = new Mock<IHttpClientFactory>();
_httpMessageHandlerMock = new Mock<HttpMessageHandler>();
_calculatedObservationsServiceMock = new Mock<ICalculatedObservationsService>();
_calculatedObservationsServiceLazy =
new Lazy<ICalculatedObservationsService>(() => _calculatedObservationsServiceMock.Object);
_appointmentServiceServiceMock = new Mock<IAppointmentService>();
_appointmentServiceServiceLazy =
new Lazy<IAppointmentService>(() => _appointmentServiceServiceMock.Object);
_diagnosisServiceMock = new Mock<IDiagnosisService>();
_diagnosisServiceLazy =
new Lazy<IDiagnosisService>(() => _diagnosisServiceMock.Object);
var client = new HttpClient(_httpMessageHandlerMock.Object);
_httpClientFactoryMock.Setup(c => c.CreateClient(It.IsAny<string>())).Returns(client);
_optionsApiSettings = Options.Create(_apiSettings);
_optionsProvidersSettings = Options.Create(_providersSettings);
#endregion
var unused = new SchedulerService(
_optionsApiSettings,
_optionsProvidersSettings,
_patientServiceLazy,
_treatmentServiceLazy,
_appointmentServiceServiceLazy,
_diagnosisServiceLazy,
_medicineServiceLazy,
_observationServiceLazy,
configObservationServiceLazy,
_logger.Object,
_httpClientFactoryMock.Object,
_calculatedObservationsServiceLazy,
_patientCarePlanLazy
);
#region [Service item fill]
_sinceDate = Now.AddHours(-24);
_sinceDischargeTimeToArchive = 48;
_archivePatientsWithoutObservationsSinceHours = 28;
_jobDataMap = new JobDataMap
{
{ "sinceDate", _sinceDate },
{ "sinceDischargeTime", _sinceDischargeTimeToArchive },
{ "archivePatientsWithoutObservationsSinceHours", _archivePatientsWithoutObservationsSinceHours },
{ "checkNewsJobIntervalMinutes", 15 }
};
// Grab the Scheduler instance from the Factory
var properties = new NameValueCollection
{
{ "quartz.scheduler.instanceName", "MyUniqueSchedulerName" }
};
_factory = new StdSchedulerFactory(properties);
if (_scheduler == null)
{
var getFactory = await _factory.GetScheduler();
_scheduler = getFactory;
}
// Set up observation list
var itemList = new List<ConfigObservation>
{
new()
{
Name = "Resp_Rate_Calculated",
CodingSystem = "ADAS",
MinAlert = 14,
MaxAlert = 25,
Expires = 10,
ShowOnExpired = false
},
new()
{
Name = "SpO2",
Code = "150456",
OriginalName = "MDC_PULS_OXIM_SAT_O2",
CodingSystem = "MDC",
ParentCode = "69965",
ParentName = "MDC_DEV_MON_PHYSIO_MULTI_PARAM_MDS",
MinAlert = 94,
MaxAlert = 100,
ParentCodingSystem = "MDC",
Expires = 10,
ShowOnExpired = false
},
new()
{
Name = "Temperature",
Code = "386053000",
OriginalName = "Temperatura",
CodingSystem = "SNM",
ParentCode = "386053000",
ParentName = "Temperatura(ºC)",
MinAlert = 34.5,
MinWarn = 35.5,
MaxWarn = 37.4,
MaxAlert = 38,
ParentCodingSystem = "SNM",
Expires = 60
},
new()
{
CodingSystem = "MDC",
Code = "150033",
OriginalName = "MDC_PRESS_BLD_ART_SYS",
Name = "TAs",
Expires = 10
},
new()
{
Name = "FC",
Code = "149514",
OriginalName = "MDC_PULS_RATE",
CodingSystem = "MDC",
MinAlert = 60,
MaxAlert = 100,
Expires = 10,
ShowOnExpired = false
}
};
var observations = new List<PatientObservation>
{
new()
{
Name = "Resp_Rate_Calculated", Value = 18, Time = DateTime.UtcNow.AddMinutes(-60), PatientId = PatientId
},
new() { Name = "SpO2", Value = 93, Time = DateTime.UtcNow.AddMinutes(-60), PatientId = PatientId },
new() { Name = "Temperature", Value = 36.5, Time = DateTime.UtcNow, PatientId = PatientId },
new() { Name = "TAs", Value = 103, Time = DateTime.UtcNow, PatientId = PatientId },
new() { Name = "FC", Value = 80, Time = DateTime.UtcNow.AddMinutes(-60), PatientId = PatientId },
new()
{
Name = "Resp_Rate_Calculated", Value = 18, Time = DateTime.UtcNow.AddMinutes(-60),
PatientId = PatientId2
},
new() { Name = "SpO2", Value = 93, Time = DateTime.UtcNow.AddMinutes(-60), PatientId = PatientId2 },
new()
{
Name = "Temperature", Value = 36.5, Time = DateTime.UtcNow.AddMinutes(-60), PatientId = PatientId2
},
new() { Name = "TAs", Value = 103, Time = DateTime.UtcNow, PatientId = PatientId2 },
new() { Name = "FC", Value = 40, Time = DateTime.UtcNow, PatientId = PatientId2 }
};
// Set Up patientList
var patientList = new List<Patient>
{
new()
{
Id = PatientId,
UnitId = ObjectId.GenerateNewId(),
PointOfCareId = ObjectId.GenerateNewId(),
PatientNumber = "patientNumber1",
Person = new Person
{
FirstName = "firstName1",
LastName = "lastName1",
BirthDate = new DateTime(),
Gender = PatientEnum.Gender.Male
}
},
new()
{
Id = PatientId2,
UnitId = ObjectId.GenerateNewId(),
PointOfCareId = ObjectId.GenerateNewId(),
PatientNumber = "patientNumber2",
Person = new Person
{
FirstName = "firstName2",
LastName = "lastName2",
BirthDate = new DateTime(),
Gender = PatientEnum.Gender.Male
}
}
};
#endregion
#region [Service behavior]
// Set up configObservationServiceMock to return desire item
_configObservationServiceMock
.Setup(service => service.Get(It.IsAny<BasePatientObservation>(), It.IsAny<bool>()))
.ReturnsAsync((BasePatientObservation obs, bool _) =>
{
return itemList.FirstOrDefault(obsConfig => obsConfig.Name == obs.Name);
});
// Set up observationService behavior
_observationServiceMock
.Setup(service => service.FindLastObservations(It.IsAny<ObjectId>(), 1, It.IsAny<List<string>>()))
.ReturnsAsync((ObjectId patientId, int _, List<string>? filterObservations) =>
{
var filteredObservations = observations
.Where(obs =>
filterObservations != null && obs.Name != null && filterObservations.Contains(obs.Name) &&
obs.PatientId == patientId)
.ToList();
return filteredObservations;
});
// Set up patientServiceMock to return patientList for FindInActivePoC
_patientServiceMock.Setup(service => service.FindInActivePoC()).ReturnsAsync(patientList);
#endregion
// Asignación de dependencias estáticas para el job
CalculateNewsJob.PatientService = _patientServiceMock.Object;
CalculateNewsJob.ObservationService = _observationServiceMock.Object;
CheckExpiredAlertsJob.ObservationService = _observationServiceMock.Object;
CheckExpiredObservationsJob.ObservationService = _observationServiceMock.Object;
CalculateNewsJob.ConfigObservationService = _configObservationServiceMock.Object;
// and start it off
_scheduler?.Start();
}
//[TearDown]
[OneTimeTearDown]
public void TearDown()
{
// Detener el motor de Quartz.NET después de las pruebas
//scheduler.Shutdown().Wait();
_scheduler?.Shutdown();
}
private Mock<ITreatmentService>? _treatmentServiceMock;
private Mock<IPatientService>? _patientServiceMock;
private Mock<IMedicineService>? _medicineServiceMock;
private Mock<IObservationService>? _observationServiceMock;
private Mock<IConfigObservationService>? _configObservationServiceMock;
private Mock<IHttpClientFactory>? _httpClientFactoryMock;
private Mock<HttpMessageHandler>? _httpMessageHandlerMock;
private Mock<ICalculatedObservationsService>? _calculatedObservationsServiceMock;
private Mock<IAppointmentService>? _appointmentServiceServiceMock;
private Mock<IDiagnosisService>? _diagnosisServiceMock;
private Lazy<ITreatmentService>? _treatmentServiceLazy;
private Lazy<IPatientService>? _patientServiceLazy;
private Lazy<IMedicineService>? _medicineServiceLazy;
private Lazy<IObservationService>? _observationServiceLazy;
private Lazy<ICalculatedObservationsService> _calculatedObservationsServiceLazy;
private Lazy<IAppointmentService> _appointmentServiceServiceLazy;
private Lazy<IDiagnosisService> _diagnosisServiceLazy;
private readonly Lazy<IPatientCarePlanService> _patientCarePlanLazy = new();
private readonly ApiSettings _apiSettings = new();
private IOptions<ApiSettings>? _optionsApiSettings;
private readonly List<ProvidersSettings> _providersSettings =
[
new()
{
Name = "Adas",
Url = "http://localhost/info.html"
}
];
private IOptions<List<ProvidersSettings>>? _optionsProvidersSettings;
private Mock<ILogger<SchedulerService>>? _logger;
private JobDataMap _jobDataMap = new();
private DateTime _sinceDate;
private int _sinceDischargeTimeToArchive;
private int _archivePatientsWithoutObservationsSinceHours;
private StdSchedulerFactory? _factory;
private IScheduler? _scheduler;
private static readonly DateTime Now = DateTime.Now;
private static readonly ObjectId PatientId = ObjectId.GenerateNewId();
private static readonly ObjectId PatientId2 = ObjectId.GenerateNewId();
[Test]
public void CheckInactivePatientsJob_ShouldExecuteOnTrigger()
{
var checkInactivePatientSchedulerIntervalHours = 12;
// Arrange
var checkInactivePatientsJob = JobBuilder.Create<CheckInactivePatientsJob>()
.UsingJobData(_jobDataMap)
.Build();
// Crear un disparador personalizado que incremente el contador
var checkInactivePatientsTrigger = TriggerBuilder.Create()
.StartNow()
.WithSimpleSchedule(x => x
.WithIntervalInHours(checkInactivePatientSchedulerIntervalHours)
.RepeatForever())
.Build();
_patientServiceMock?.Setup(p => p.DischargeInactivePatients(_sinceDate, _sinceDischargeTimeToArchive));
// Asociar el trabajo y el desencadenador en el motor de Quartz.NET
_scheduler?.ScheduleJob(checkInactivePatientsJob, checkInactivePatientsTrigger).Wait();
// Act
// Esperar un tiempo suficiente para que el trabajo se ejecute varias veces
Thread.Sleep(TimeSpan.FromSeconds(1));
_patientServiceMock?.Verify(p => p.DischargeInactivePatients(It.IsAny<DateTime>(), It.IsAny<int>()),
Times.AtLeastOnce());
}
[Test]
public void CheckActiveTreatmentsJob_ShouldExecuteOnTrigger()
{
var patient = new Patient
{
PatientId = PatientId.ToString(),
UnitString = "NEONATAL",
Bed = "CINA02",
PatientNumber = "123456",
Person = new Person
{
FirstName = "Jose",
LastName = "Luis",
BirthDate = new DateTime(),
Gender = PatientEnum.Gender.Male
}
};
const int checkActiveTreatmentsSchedulerIntervalMinutes = 10;
var treatmentsJob = JobBuilder.Create<CheckActiveTreatmentsJob>()
.Build();
// Trigger the job to run now, and then repeat every 10 seconds
var treatmentsTrigger = TriggerBuilder.Create()
.StartNow()
.WithSimpleSchedule(x => x
.WithIntervalInMinutes(checkActiveTreatmentsSchedulerIntervalMinutes)
.RepeatForever())
.Build();
_patientServiceMock?.Setup(p => p.FindAll(It.IsAny<bool>())).ReturnsAsync([patient]);
// Create a mock of the singleton class subscribers
var mockSingleton = new Mock<ICalculatedObservationsService>();
// Set up the mock object to return a specific value when a method is called
var patientTreatmentList = new List<PatientTreatment?>
{
new()
{
Id = ObjectId.GenerateNewId(),
PatientId = PatientId,
OrderControl = OrderControlType.Nw,
PlacerOrder = new Entity { EntityIdentifier = "3690", NamespaceId = "CareVue" },
FillerOrder = new Entity { EntityIdentifier = "3690", NamespaceId = "CareVue" },
OrderStatus = "A",
OrderTime = Now,
Notes = [],
Routes = []
}
};
mockSingleton.Setup(x => x.GetActiveTreatmentsByPatient(PatientId)).ReturnsAsync(patientTreatmentList);
_medicineServiceMock?.Setup(m => m.GetMedicinesOfTreatments(It.IsAny<List<PatientTreatment>>()))
.ReturnsAsync(new List<Medicine>());
// Asociar el trabajo y el desencadenador en el motor de Quartz.NET
_scheduler?.ScheduleJob(treatmentsJob, treatmentsTrigger).Wait();
// Act
// Esperar un tiempo suficiente para que el trabajo se ejecute varias veces
Thread.Sleep(TimeSpan.FromSeconds(10));
_medicineServiceMock?.Verify(x => x.GetMedicinesOfTreatments(It.IsAny<IEnumerable<PatientTreatment>>()),
Times.Once());
}
[Test]
public void CheckExpiredObservationsJob_ShouldExecuteOnTrigger()
{
var checkExpiredObservationsIntervalMinutes = 3;
// Arrange
var checkExpiredObservationsJob = JobBuilder.Create<CheckExpiredObservationsJob>()
.UsingJobData(_jobDataMap)
.Build();
// Crear un disparador personalizado que incremente el contador
var checkExpiredObservationsTrigger = TriggerBuilder.Create()
.StartNow()
.WithSimpleSchedule(x => x
.WithIntervalInHours(checkExpiredObservationsIntervalMinutes)
.RepeatForever())
.Build();
// Asociar el trabajo y el desencadenador en el motor de Quartz.NET
_scheduler?.ScheduleJob(checkExpiredObservationsJob, checkExpiredObservationsTrigger).Wait();
// Act
// Esperar un tiempo suficiente para que el trabajo se ejecute varias veces
Thread.Sleep(TimeSpan.FromSeconds(1));
_observationServiceMock?.Verify(p => p.ExpireObservationsAndRecalculateAsync(), Times.AtLeastOnce());
}
[Test]
public void CheckExpiredAlertsJob_ShouldExecuteOnTrigger()
{
var checkExpiredAlertsIntervalMinutes = 3;
// Arrange
var checkExpiredAlertsJob = JobBuilder.Create<CheckExpiredAlertsJob>()
.UsingJobData(_jobDataMap)
.Build();
// Crear un disparador personalizado que incremente el contador
var checkExpiredAlertsTrigger = TriggerBuilder.Create()
.StartNow()
.WithSimpleSchedule(x => x
.WithIntervalInHours(checkExpiredAlertsIntervalMinutes)
.RepeatForever())
.Build();
// Asociar el trabajo y el desencadenador en el motor de Quartz.NET
_scheduler?.ScheduleJob(checkExpiredAlertsJob, checkExpiredAlertsTrigger).Wait();
// Act
// Esperar un tiempo suficiente para que el trabajo se ejecute varias veces
Thread.Sleep(TimeSpan.FromSeconds(1));
_observationServiceMock?.Verify(p => p.ExpireAlertsAndPowerOffAsync(), Times.AtLeastOnce());
}
[Test]
public void GetProvidersObservationsJob_ShouldExecuteOnTrigger_Result_GetType_null()
{
var getProviderObservationsIntervalMinutes = 5;
var patient = new Patient
{
PatientId = PatientId.ToString(),
UnitString = "NEONATAL",
Bed = "CINA02",
PatientNumber = "123456",
Person = new Person
{
FirstName = "Jose",
LastName = "Luis",
BirthDate = new DateTime(),
Gender = PatientEnum.Gender.Male
}
};
// Arrange
var getProvidersObservationsJob = JobBuilder.Create<GetProvidersObservationsJob>()
.UsingJobData(_jobDataMap)
.Build();
// Crear un disparador personalizado que incremente el contador
var getProvidersObservationsTrigger = TriggerBuilder.Create()
.StartNow()
.WithSimpleSchedule(x => x
.WithIntervalInHours(getProviderObservationsIntervalMinutes)
.RepeatForever())
.Build();
_patientServiceMock?.Setup(p => p.FindAll(It.IsAny<bool>())).ReturnsAsync([patient]);
// Asociar el trabajo y el desencadenador en el motor de Quartz.NET
_scheduler?.ScheduleJob(getProvidersObservationsJob, getProvidersObservationsTrigger).Wait();
// Act
// Esperar un tiempo suficiente para que el trabajo se ejecute varias veces
Thread.Sleep(TimeSpan.FromSeconds(1));
//observationServiceMock.Verify(p => p.InsertObservation(It.IsAny<PatientObservation>(),true,true), Times.AtLeastOnce());
_observationServiceMock?.Verify(p => p.InsertObservation(
It.Is<PatientObservation>(obs => obs.Name != "NEWS"), true, true), Times.Never());
}
[Test]
public void CheckCalculateNewsJob_ShouldExecuteOnTrigger()
{
var checkExpiredAlertsIntervalMinutes = 3;
// Arrange
var calculateNewsJob = JobBuilder.Create<CalculateNewsJob>()
.UsingJobData(_jobDataMap)
.Build();
// Crear un disparador personalizado que incremente el contador
var checkExpiredAlertsTrigger = TriggerBuilder.Create()
.StartNow()
.WithSimpleSchedule(x => x
.WithIntervalInHours(checkExpiredAlertsIntervalMinutes)
.RepeatForever())
.Build();
// Asociar el trabajo y el desencadenador en el motor de Quartz.NET
_scheduler?.ScheduleJob(calculateNewsJob, checkExpiredAlertsTrigger).Wait();
// Act
// Esperar un tiempo suficiente para que el trabajo se ejecute varias veces
Thread.Sleep(TimeSpan.FromSeconds(6));
_observationServiceMock?.Verify(p => p.InsertObservation(It.IsAny<PatientObservation>(), true, true),
Times.AtLeastOnce());
}
[Test]
public async Task CalculateNewsJob_Insert_ObsFull_MultiplePatient_With_Correct_Value()
{
var job = new CalculateNewsJob();
// Act
await job.Execute(Mock.Of<IJobExecutionContext>());
// Assert
_observationServiceMock?.Verify(
service => service.InsertObservation(
It.Is<PatientObservation>(obs =>
obs.Name == "NEWS" && (int)obs.Value == 1 && obs.PatientId == PatientId),
true, true),
Times.Once);
_observationServiceMock?.Verify(
service => service.InsertObservation(
It.Is<PatientObservation>(obs =>
obs.Name == "NEWS" && (int)obs.Value == 4 && obs.PatientId == PatientId2),
true, true),
Times.Once);
}
//Se deshabilita el mensaje de warning porque lo detecta como no usado y sugiere suprimirlo siendo necesario
}
@@ -0,0 +1,115 @@
using adas_core.Domain.Models.AppSettings;
using adas_core.Domain.Models.SystemAlerts;
using adas_core.Infrastructure.Services;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Moq;
namespace adas_core.Test.Services;
[TestFixture]
public class SendAlertServiceTest
{
[SetUp]
public void Setup()
{
_optionsRabbitMqSettings = Options.Create(_rabbitMqSettings);
_logger = new Mock<ILogger<SendAlertService>>();
_sendAlertService = new SendAlertService(
_optionsRabbitMqSettings,
_logger.Object
);
_windowsPlatforms =
[
PlatformID.Win32NT,
PlatformID.Win32S,
PlatformID.Win32Windows,
PlatformID.WinCE
];
}
private SendAlertService _sendAlertService = null!;
private readonly RabbitMqSettings _rabbitMqSettings = new();
private IOptions<RabbitMqSettings> _optionsRabbitMqSettings = null!;
private Mock<ILogger<SendAlertService>> _logger = null!;
private PlatformID[] _windowsPlatforms = null!;
[Ignore("Integration test to pull request")]
[Test]
public void GetConsumedCpu_Return_PerformanceCpu_data()
{
if (_windowsPlatforms.Contains(Environment.OSVersion.Platform))
{
var result = _sendAlertService.GetConsumedCpu();
//result = await sendAlertService.GetConsumedCpu();
Assert.That(result, Is.Not.Null);
Assert.That(result.ValueTotal, Is.GreaterThan(0));
}
else
{
Assert.Ignore("This test can only be run on Windows.");
}
}
[Ignore("Integration test to pull request")]
[Test]
public void GetConsumedRAM_Return_PerformanceRAM_data()
{
if (_windowsPlatforms.Contains(Environment.OSVersion.Platform))
{
var result = _sendAlertService.GetConsumedRam();
//result = await sendAlertService.GetConsumedRAM();
Assert.That(result, Is.Not.Null);
using (Assert.EnterMultipleScope())
{
Assert.That(result.PercentageConsumed, Is.GreaterThan(0));
Assert.That(result.ValueConsumed, Is.GreaterThan(0));
Assert.That(result.ValueTotal, Is.GreaterThan(0));
}
}
else
{
Assert.Ignore("This test can only be run on Windows.");
}
}
[Ignore("Integration test to pull request")]
[Test]
public void GetConsumedStorage_Return_PerformanceStorage_data()
{
if (_windowsPlatforms.Contains(Environment.OSVersion.Platform))
{
List<Performance> performanceList = [];
foreach (var drive in DriveInfo.GetDrives())
if (drive.IsReady)
{
var performance = _sendAlertService.GetConsumedStorage(drive);
performanceList.Add(performance);
}
Assert.That(performanceList, Is.Not.Null);
using (Assert.EnterMultipleScope())
{
Assert.That(performanceList, Is.Not.Empty);
Assert.That(performanceList[0].PercentageConsumed, Is.GreaterThan(0));
Assert.That(performanceList[0].ValueConsumed, Is.GreaterThan(0));
Assert.That(performanceList[0].ValueTotal, Is.GreaterThan(0));
}
}
else
{
Assert.Ignore("This test can only be run on Windows.");
}
}
}
@@ -0,0 +1,63 @@
using adas_core.Application.Repositories.Interfaces;
using adas_core.Domain.Models.MongoModels;
using Microsoft.Extensions.Logging;
using MongoDB.Bson;
using Moq;
using ServiceConfigService = adas_core.Application.Services.ServiceConfigService;
namespace adas_core.Test.Services;
[TestFixture]
public class ServiceConfigServiceTest
{
[SetUp]
public void Setup()
{
_serviceConfigRepositoryMock = new Mock<IServiceConfigRepository>();
_logger = new Mock<ILogger<ServiceConfigService>>();
_serviceConfigService = new ServiceConfigService(
_serviceConfigRepositoryMock.Object,
_logger.Object
);
}
private ServiceConfigService _serviceConfigService;
private Mock<IServiceConfigRepository> _serviceConfigRepositoryMock;
private Mock<ILogger<ServiceConfigService>> _logger;
private static ObjectId _id = ObjectId.GenerateNewId();
[Test]
public async Task Get_Find_Id_Return_ServiceConfig()
{
var serviceConfig = new ServiceConfig
{
StrId = _id.ToString()
};
_serviceConfigRepositoryMock.Setup(s => s.FindById(_id.ToString())).ReturnsAsync(serviceConfig);
var result = await _serviceConfigService.Get(serviceConfig.StrId);
Assert.That(result, Is.Not.Null);
}
[Test]
public async Task Get_Not_Find_Id_Return_ServiceConfig()
{
var serviceConfig = new ServiceConfig
{
StrId = _id.ToString()
};
_serviceConfigRepositoryMock.Setup(s => s.FindById(_id)).ReturnsAsync((ServiceConfig?)null);
_serviceConfigRepositoryMock.Setup(s => s.FindById(It.IsAny<ObjectId>())).ReturnsAsync(serviceConfig);
var result = await _serviceConfigService.Get(_id.ToString());
Assert.That(result, Is.Not.Null);
}
}
@@ -0,0 +1,277 @@
using adas_core.Application.Exceptions;
using adas_core.Application.Repositories.Interfaces;
using adas_core.Application.Services;
using adas_core.Application.Services.Interfaces;
using adas_core.Domain.Enums;
using adas_core.Domain.Models;
using adas_core.Domain.Models.MongoModels;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using MongoDB.Bson;
using Moq;
using static NUnit.Framework.Assert;
namespace adas_core.Test.Services;
[TestFixture]
public class TreatmentServiceTest
{
[SetUp]
public void Setup()
{
_treatmentRepositoryMock = new Mock<ITreatmentRepository>();
_treatmentArchiveRepositoryMock = new Mock<ITreatmentArchiveRepository>();
//pocMappingServiceMock = new Mock<IPoCMappingService>();
_patientServiceMock = new Mock<IPatientService>();
//calculatedObservationsServiceMock = new Mock<ICalculatedObservationsService>();
_configObservationServiceMock = new Mock<IConfigObservationService>();
_clientMessageServiceMock = new Mock<IClientMessageService>();
_subscribersServiceMock = new Mock<ISubscribersService>();
_calculatedObservationsServiceMock = new Mock<ICalculatedObservationsService>();
_unitServiceMock = new Mock<IUnitService>();
_calculatedObservationsServiceLazy =
new Lazy<ICalculatedObservationsService>(() => _calculatedObservationsServiceMock.Object);
//optionsApiSettings = Microsoft.Extensions.Options.Options.Create<ApiSettings>(apiSettings);
_logger = new Mock<ILogger<TreatmentService>>();
_treatmentService = new TreatmentService(
_treatmentRepositoryMock.Object,
_treatmentArchiveRepositoryMock.Object,
_patientServiceMock.Object,
_configObservationServiceMock.Object,
//optionsApiSettings,
_logger.Object,
_clientMessageServiceMock.Object,
_subscribersServiceMock.Object,
_calculatedObservationsServiceLazy,
_unitServiceMock.Object,
_httpContextAccessor.Object,
_auditService.Object
);
}
private TreatmentService _treatmentService = null!;
private Mock<ITreatmentRepository> _treatmentRepositoryMock = null!;
private Mock<ITreatmentArchiveRepository> _treatmentArchiveRepositoryMock = null!;
//Mock<IPoCMappingService> pocMappingServiceMock = null!;
private Mock<IPatientService> _patientServiceMock = null!;
//Mock<ICalculatedObservationsService> calculatedObservationsServiceMock = null!;
private Mock<IConfigObservationService> _configObservationServiceMock = null!;
private Mock<IClientMessageService> _clientMessageServiceMock = null!;
private Mock<ISubscribersService> _subscribersServiceMock = null!;
private Lazy<ICalculatedObservationsService> _calculatedObservationsServiceLazy = null!;
private Mock<ICalculatedObservationsService> _calculatedObservationsServiceMock = null!;
private Mock<IUnitService> _unitServiceMock = null!;
private readonly Mock<IHttpContextAccessor> _httpContextAccessor = new();
private readonly Mock<ILocalAuditService> _auditService = new();
//readonly ApiSettings apiSettings = new ()
//{
// ConfigObservation = new ConfigObservationSettings
// {
// IgnoreUnknownObservation = false
// }
//};
//IOptions<ApiSettings> optionsApiSettings;
private Mock<ILogger<TreatmentService>> _logger = null!;
private static readonly DateTime Now = DateTime.Now;
private static readonly ObjectId PatientId = ObjectId.GenerateNewId();
//3 Nuevos tratamiento3,5,6
private readonly List<PatientTreatment> _patientTreatments =
[
new()
{
Id = ObjectId.GenerateNewId(),
PatientId = PatientId,
OrderControl = OrderControlType.Nw,
PlacerOrder = new Entity { EntityIdentifier = "3690", NamespaceId = "CareVue" },
FillerOrder = new Entity { EntityIdentifier = "3690", NamespaceId = "CareVue" },
OrderStatus = "A",
OrderTime = DateTime.Now,
Notes = [],
Routes = []
},
new()
{
Id = ObjectId.GenerateNewId(),
PatientId = PatientId,
OrderControl = OrderControlType.Dc,
PlacerOrder = new Entity { EntityIdentifier = "3690", NamespaceId = "CareVue" },
FillerOrder = new Entity { EntityIdentifier = "3690", NamespaceId = "CareVue" },
OrderStatus = "A",
OrderTime = DateTime.Now,
Notes = [],
Routes = []
},
new()
{
Id = ObjectId.GenerateNewId(),
PatientId = PatientId,
OrderControl = OrderControlType.Nw,
PlacerOrder = new Entity { EntityIdentifier = "4590", NamespaceId = "CareVue" },
FillerOrder = new Entity { EntityIdentifier = "4590", NamespaceId = "CareVue" },
OrderStatus = "A",
OrderTime = DateTime.Now,
Notes = [],
Routes = []
},
new()
{
Id = ObjectId.GenerateNewId(),
PatientId = PatientId,
OrderControl = OrderControlType.Xo,
PlacerOrder = new Entity { EntityIdentifier = "4590", NamespaceId = "CareVue" },
FillerOrder = new Entity { EntityIdentifier = "4590", NamespaceId = "CareVue" },
OrderStatus = "A",
OrderTime = DateTime.Now,
Notes = [],
Routes = []
},
new()
{
Id = ObjectId.GenerateNewId(),
PatientId = PatientId,
OrderControl = OrderControlType.Nw,
PlacerOrder = new Entity { EntityIdentifier = "2100", NamespaceId = "CareVue" },
FillerOrder = new Entity { EntityIdentifier = "2100", NamespaceId = "CareVue" },
OrderStatus = "A",
OrderTime = DateTime.Now,
Notes = [],
Routes = []
},
new()
{
Id = ObjectId.GenerateNewId(),
PatientId = PatientId,
OrderControl = OrderControlType.Nw,
PlacerOrder = new Entity { EntityIdentifier = "100", NamespaceId = "CareVue" },
FillerOrder = new Entity { EntityIdentifier = "100", NamespaceId = "CareVue" },
OrderStatus = "A",
OrderTime = DateTime.Now,
Notes = [],
Routes = []
}
];
[Test]
public void SaveRequest_Not_Case_option_Return_not_insert()
{
var apiRequest = new ApiRequest();
Func<Task> act = async () => await _treatmentService.SaveRequest(apiRequest);
Assert.ThrowsAsync<ApiRequestException>(act);
}
[Test]
public void SaveRequest_patientNumber_and_pointOfCare_null_Return_not_insert()
{
var apiRequest = new ApiRequest
{
Type = "ORU_R01",
MessageTime = Now
};
Func<Task> act = async () => await _treatmentService.SaveRequest(apiRequest);
Assert.ThrowsAsync<ApiRequestException>(act);
}
[Test]
public async Task SaveRequest_Not_Find_Patient_Return_not_insert()
{
var person = new Person
{
FirstName = "Miguel",
LastName = "Villanueva",
Ids = new Dictionary<string, string> { { "MR", "437537" } }
};
var apiRequest = new ApiRequest
{
Location = new PatientLocation("UCI5C", "Box4"),
Patient = person,
PatientNumber = "437537",
Type = "OMP_O09",
PatientId = PatientId.ToString(),
MessageTime = Now
};
await _treatmentService.SaveRequest(apiRequest);
_treatmentArchiveRepositoryMock.Verify(d => d.InsertOneAsync(It.IsAny<PatientTreatment>()), Times.Never);
}
[Test]
public async Task SaveRequest_Find_Patient_Return_insert()
{
var person = new Person
{
FirstName = "Miguel",
LastName = "Villanueva",
Ids = new Dictionary<string, string> { { "MR", "437537" } }
};
var patient = new Patient
{
Id = ObjectId.GenerateNewId(),
UnitString = "UCI5C",
Bed = "Box4",
PatientNumber = "437537",
Person = person
};
var apiRequest = new ApiRequest
{
Location = new PatientLocation("UCI5C", "Box4"),
Patient = person,
PatientNumber = "437537",
Type = "OMP_O09",
PatientId = PatientId.ToString(),
MessageTime = Now
};
_patientServiceMock.Setup(p => p.FindByPatientNumber(apiRequest.PatientNumber, false)).ReturnsAsync(patient);
await _treatmentService.SaveRequest(apiRequest);
_treatmentArchiveRepositoryMock.Verify(d => d.InsertOneAsync(It.IsAny<PatientTreatment>()), Times.Never);
}
[Test]
public async Task GetActiveTreatmentsByPatient()
{
_treatmentRepositoryMock.Setup(t => t.GetByPatientId(PatientId))
.ReturnsAsync(_patientTreatments.AsEnumerable());
var treatments = await _treatmentService.GetActiveTreatmentsByPatient(PatientId);
var result = treatments.ToList();
using (Assert.EnterMultipleScope())
{
That(result, Is.Not.Empty);
That(result, Has.Count.EqualTo(4));
That(result.Find(t => t?.PlacerOrder?.EntityIdentifier == "100"), Is.Not.Null);
That(result.Find(t => t?.PlacerOrder?.EntityIdentifier == "2100"), Is.Not.Null);
That(result.Find(t => t?.PlacerOrder?.EntityIdentifier == "4590"), Is.Not.Null);
That(result.Find(t => t?.PlacerOrder?.EntityIdentifier == "3690"), Is.Not.Null);
};
}
}
+317
View File
@@ -0,0 +1,317 @@
using System.Security.Claims;
using adas_core.Application.Repositories.Interfaces;
using adas_core.Application.Services;
using adas_core.Application.Services.Interfaces;
using adas_core.Domain.Enums;
using adas_core.Domain.Models;
using adas_core.Domain.Models.MongoModels;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using MongoDB.Bson;
using Moq;
namespace adas_core.Test.Services;
public class UnitServiceTest
{
private readonly Mock<ILocalAuditService> _auditServiceMock = new();
private readonly Mock<IHttpContextAccessor> _httpContextAccessorMock = new();
private Mock<IClientMessageService> _clientMessageServiceMock = null!;
private Mock<ILogger<UnitService>> _loggerMock = null!;
private Mock<IMasterListServiceFactory> _masterListServiceFactoryMock = null!;
private Mock<IPatientService> _patientServiceMock = null!;
private Mock<IPointOfCareService> _pointOfCareServiceMock = null!;
private Mock<ISubscribersService> _subscribersServiceMock = null!;
private Mock<IUnitRepository> _unitRepositoryMock = null!;
private UnitService _unitService = null!;
[SetUp]
public void SetUp()
{
_unitRepositoryMock = new Mock<IUnitRepository>();
_patientServiceMock = new Mock<IPatientService>();
_loggerMock = new Mock<ILogger<UnitService>>();
_clientMessageServiceMock = new Mock<IClientMessageService>();
_subscribersServiceMock = new Mock<ISubscribersService>();
_masterListServiceFactoryMock = new Mock<IMasterListServiceFactory>();
_pointOfCareServiceMock = new Mock<IPointOfCareService>();
var userClaims = new ClaimsPrincipal(new ClaimsIdentity([
new Claim(ClaimTypes.Name, "TestUser")
], "mock"));
var httpContextMock = new DefaultHttpContext
{
User = userClaims
};
_httpContextAccessorMock.Setup(accessor => accessor.HttpContext)
.Returns(httpContextMock);
_unitService = new UnitService(
_unitRepositoryMock.Object,
new Lazy<IPatientService>(() => _patientServiceMock.Object),
_loggerMock.Object,
_masterListServiceFactoryMock.Object,
_subscribersServiceMock.Object,
new Lazy<IClientMessageService>(() => _clientMessageServiceMock.Object),
_pointOfCareServiceMock.Object,
_httpContextAccessorMock.Object,
_auditServiceMock.Object
);
}
[Test]
public async Task GetAll_ShouldReturnAllUnits()
{
// Arrange
var units = new List<Unit> { new() { Id = ObjectId.GenerateNewId() } };
_unitRepositoryMock.Setup(repo => repo.GetAll()).ReturnsAsync(units);
// Act
var result = await _unitService.GetAll();
// Assert
Assert.That(result, Is.Not.Null);
Assert.That(result.Count, Is.EqualTo(1));
Assert.That(result, Is.EqualTo(units));
}
[Test]
public async Task Get_ShouldReturnUnitById()
{
// Arrange
var unitId = ObjectId.GenerateNewId();
var unit = new Unit { Id = unitId };
_unitRepositoryMock.Setup(repo => repo.FindById(unitId)).ReturnsAsync(unit);
// Act
var result = await _unitService.Get(unitId.ToString());
// Assert
Assert.That(result, Is.Not.Null);
Assert.That(result, Is.EqualTo(unit));
}
[Test]
public async Task Get_ShouldReturnUnitByName_WhenIdIsNotObjectId()
{
// Arrange
var unitName = "TestUnit";
var units = new List<Unit>
{
new() { Title = unitName },
new() { Name = unitName }
};
_unitRepositoryMock.Setup(repo => repo.GetAll()).ReturnsAsync(units);
// Act
var result = await _unitService.Get(unitName);
// Assert
Assert.That(result, Is.Not.Null);
Assert.That(result?.Title ?? result?.Name, Is.EqualTo(unitName));
}
[Test]
public async Task GetAllUnits_ShouldReturnAllUnits()
{
// Arrange
var units = new List<Unit>
{
new() { Id = ObjectId.GenerateNewId(), Name = "Unit1" },
new() { Id = ObjectId.GenerateNewId(), Name = "Unit2" }
};
_unitRepositoryMock.Setup(repo => repo.GetAll()).ReturnsAsync(units);
// Act
var result = await _unitService.GetAll();
// Assert
Assert.That(result, Is.Not.Null);
Assert.That(result.Count(), Is.EqualTo(units.Count));
Assert.That(result, Is.EquivalentTo(units));
}
[Test]
public async Task GetUnitById_ShouldReturnUnit_WhenFound()
{
// Arrange
var unitId = ObjectId.GenerateNewId();
var unit = new Unit { Id = unitId, Name = "Unit1" };
_unitRepositoryMock.Setup(repo => repo.FindById(unitId)).ReturnsAsync(unit);
// Act
var result = await _unitService.FindById(unitId);
// Assert
Assert.That(result, Is.Not.Null);
Assert.That(result, Is.EqualTo(unit));
}
[Test]
public async Task GetUnitByName_ShouldReturnUnit_WhenFound()
{
// Arrange
var unitName = "TestUnit";
var expectedUnit = new Unit { Id = ObjectId.GenerateNewId(), Name = unitName };
_unitRepositoryMock.Setup(repo => repo.FindByName(unitName)).ReturnsAsync(expectedUnit);
// Act
var result = await _unitService.GetByName(unitName);
// Assert
Assert.That(result, Is.Not.Null);
Assert.That(result, Is.EqualTo(expectedUnit));
}
[Test]
public async Task FindUnitByPatientId_ShouldReturnUnit_WhenPatientFoundInActivePoC()
{
// Arrange
var patientId = ObjectId.GenerateNewId();
var unitId = ObjectId.GenerateNewId();
var pocId = ObjectId.GenerateNewId();
var patient = new Patient { Id = patientId, PointOfCareId = pocId, UnitId = unitId };
var unit = new Unit
{
Id = unitId,
PointOfCares = [new PointOfCare { Id = pocId, UnitId = unitId, Status = StatusEnum.PointOfCare.InUse }]
};
_unitRepositoryMock.Setup(repo => repo.FindById(unitId)).ReturnsAsync(unit);
_patientServiceMock.Setup(service => service.FindById(patientId, false)).ReturnsAsync(patient);
// Act
var result = await _unitService.FindByPatientId(patientId);
// Assert
Assert.That(result, Is.Not.Null);
Assert.That(result?.PointOfCares?.Any(c => c.Id == patient.PointOfCareId && c.UnitId == patient.UnitId),
Is.True);
}
[Test]
public async Task FindUnitsByMasterListId_ShouldReturnUnits_WhenUnitsFound()
{
// Arrange
var masterListId = ObjectId.GenerateNewId();
var masterListType = MasterListType.AltableOptionList;
var units = new List<Unit> { new(), new() };
_unitRepositoryMock.Setup(repo => repo.FindByMasterListId(masterListId, masterListType)).ReturnsAsync(units);
// Act
var result = await _unitService.FindUnitsByMasterListId(masterListId, masterListType);
// Assert
if (result != null)
{
var actual = result.ToList();
Assert.That(actual, Is.Not.Null);
Assert.That(actual, Is.EqualTo(units));
}
}
[Test]
public async Task FindByLocation_ShouldReturnUnits_WhenUnitsFound()
{
// Arrange
var location = new PatientLocation("TestUnit", "TestBed", "TestRoom");
var units = new List<Unit>
{
new()
{
PointOfCares = [new PointOfCare { UnitName = "TestUnit", Bed = "TestBed" }]
}
};
_unitRepositoryMock.Setup(repo => repo.GetAll()).ReturnsAsync(units);
// Act
var result = await _unitService.FindByLocation(location);
// Assert
Assert.That(result, Is.Not.Null);
Assert.That(result?.Count, Is.EqualTo(1));
Assert.That(result?.First().PointOfCares?.First().UnitName, Is.EqualTo("TestUnit"));
Assert.That(result?.First().PointOfCares?.First().Bed, Is.EqualTo("TestBed"));
}
[Test]
public async Task FindByLocation_ShouldReturnEmptyList_WhenNoUnitsFound()
{
// Arrange
var location = new PatientLocation("NonExistentUnit", "NonExistentBed", "NonExistentRoom");
_unitRepositoryMock.Setup(repo => repo.GetAll()).ReturnsAsync([]);
// Act
var result = await _unitService.FindByLocation(location);
// Assert
Assert.That(result, Is.Not.Null);
Assert.That(result?.Count, Is.EqualTo(0));
}
[Test]
public async Task FindById_ShouldReturnUnit_WhenValidIdProvided()
{
// Arrange
var unitId = ObjectId.GenerateNewId();
var expectedUnit = new Unit { Id = unitId };
_unitRepositoryMock.Setup(repo => repo.FindById(unitId)).ReturnsAsync(expectedUnit);
// Act
var result = await _unitService.FindById(unitId);
// Assert
Assert.That(result, Is.Not.Null);
Assert.That(result, Is.EqualTo(expectedUnit));
}
[Test]
public async Task FindById_ShouldReturnNull_WhenNullIdProvided()
{
// Arrange
// Act
var result = await _unitService.FindById(null);
// Assert
Assert.That(result, Is.Null);
}
[Test]
public async Task FindByName_ShouldReturnUnit_WhenValidNameProvided()
{
// Arrange
var unitName = "Unit1";
var expectedUnit = new Unit { Name = unitName };
_unitRepositoryMock.Setup(repo => repo.FindByName(unitName)).ReturnsAsync(expectedUnit);
// Act
var result = await _unitService.FindByName(unitName);
// Assert
Assert.That(result, Is.Not.Null);
Assert.That(result, Is.EqualTo(expectedUnit));
}
[Test]
public async Task InsertOne_ShouldReturnInsertedUnit()
{
// Arrange
var unit = new Unit { Id = ObjectId.GenerateNewId(), Name = "TestUnit" };
_unitRepositoryMock.Setup(repo => repo.InsertOneUnit(unit)).ReturnsAsync(unit);
// Act
var result = await _unitService.InsertOne(unit);
// Assert
Assert.That(result, Is.Not.Null);
Assert.That(result, Is.EqualTo(unit));
}
}