add girIgnore

This commit is contained in:
jrojas
2026-06-23 19:03:17 +02:00
parent 52335cc5fa
commit 95c9039c78
321 changed files with 84 additions and 12748 deletions
+78
View File
@@ -0,0 +1,78 @@
using audit_logs.Repositories;
using audit.Model;
namespace audit_test.Repository;
public class AuditRecordRepositoryTests
{
private AuditRecordRepository _repository = null!;
[SetUp]
public void Setup()
{
_repository = new AuditRecordRepository (IntegrationDb.Database);
}
[Test]
public async Task InsertRecord_RecordIsInsertedAndCanBeRetrieved()
{
var record = new AuditRecord
{
EntityType = "User",
RecordId = "1",
UserId = "123",
ActionType = "Create",
ActionTime = DateTime.UtcNow,
Changes = new List<AuditRecord.Change>
{
new AuditRecord.Change { Field = "Username", OldValue = "oldUser", NewValue = "newUser", ValueType = "String" }
},
Reason = "Ingreso de paciente"
};
await _repository.InsertOneAsync(record);
var retrievedRecord = await _repository.FindRecordByIdAsync(record.Id);
Assert.IsNotNull(retrievedRecord);
Assert.AreEqual(record.ActionType, retrievedRecord.ActionType);
//Assert.AreEqual(record.Details, retrievedRecord.Details);
}
[Test]
public async Task GetAllAuditRecords_ReturnsAllRecords()
{
// Prepare data
var records = new List<AuditRecord>
{
new AuditRecord { EntityType = "User", RecordId = "1", UserId = "123", ActionType = "Create", ActionTime = DateTime.UtcNow, Reason = "Test Reason 1" },
new AuditRecord { EntityType = "Admin", RecordId = "2", UserId = "456", ActionType = "Delete", ActionTime = DateTime.UtcNow, Reason = "Test Reason 2" }
};
foreach (var rec in records)
{
await _repository.InsertOneAsync(rec);
}
// Test GetAllAuditRecordsAsync method
var allRecords = await _repository.GetAllAuditRecordsAsync();
// Assert that all records are retrieved
Assert.IsNotNull(allRecords);
Assert.AreEqual(2, allRecords.Count); // This assumes the database is empty before test starts
Assert.IsTrue(allRecords.Exists(r => r.RecordId == "1" && r.EntityType == "User"));
Assert.IsTrue(allRecords.Exists(r => r.RecordId == "2" && r.EntityType == "Admin"));
}
[TearDown]
public async Task Cleanup()
{
await IntegrationDb.Database.DropCollectionAsync("audit_records");
}
}
+520
View File
@@ -0,0 +1,520 @@
using audit_logs.Models.DTO;
using audit.Model;
using Newtonsoft.Json;
namespace audit_test.Repository;
using audit_logs.Models;
using audit_logs.Services;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
public class AuditServiceFilterTests
{
private AuditService _service;
[SetUp]
public void Setup()
{
// Limpia la base de datos antes de cada prueba
IntegrationDb.Database.DropCollectionAsync("audit_records").Wait();
_service = new AuditService(IntegrationDb.Database);
}
[Test]
public async Task GetAuditLogsAsync_FilterByUserId_ReturnsMatchingRecords()
{
// Arrange
var records = new List<AuditRecord>
{
new AuditRecord
{
EntityType = "User",
RecordId = "1",
UserId = "User123",
ActionType = "Create",
ActionTime = DateTime.UtcNow.AddMinutes(-10),
Reason = "Testing filter",
Changes = new List<AuditRecord.Change>()
},
new AuditRecord
{
EntityType = "Admin",
RecordId = "2",
UserId = "User456",
ActionType = "Delete",
ActionTime = DateTime.UtcNow,
Reason = "Testing filter",
Changes = new List<AuditRecord.Change>()
}
};
foreach (var record in records)
{
await _service.AuditLogRepository.InsertOneAsync(record);
}
SpecificAuditLogFilterDto auditLogParametersDto = new SpecificAuditLogFilterDto();
auditLogParametersDto.pageNumber=1;
auditLogParametersDto.pageSize = 10;
auditLogParametersDto.userId="User123";
// Act
var paginatedResult = await _service.GetAuditLogsBySpecificFilterAsync(auditLogParametersDto);
// Assert
// Assert
Assert.That(paginatedResult.Records.Count(), Is.EqualTo(1), "Should return only records matching the UserId.");
var result = paginatedResult.Records.First();
Assert.That(result.UserId, Is.EqualTo("User123"), "The UserId should match the filter.");
}
[Test]
public async Task GetAuditLogsAsync_FilterByRecordId_ReturnsMatchingRecords()
{
// Arrange
var records = new List<AuditRecord>
{
new AuditRecord
{
EntityType = "User",
RecordId = "Record123",
UserId = "User123",
ActionType = "Create",
ActionTime = DateTime.UtcNow.AddMinutes(-10),
Reason = "Testing filter",
Changes = new List<AuditRecord.Change>()
},
new AuditRecord
{
EntityType = "Admin",
RecordId = "Record456",
UserId = "User456",
ActionType = "Delete",
ActionTime = DateTime.UtcNow,
Reason = "Testing filter",
Changes = new List<AuditRecord.Change>()
}
};
foreach (var record in records)
{
await _service.AuditLogRepository.InsertOneAsync(record);
}
SpecificAuditLogFilterDto auditLogParametersDto = new SpecificAuditLogFilterDto();
auditLogParametersDto.pageNumber=1;
auditLogParametersDto.pageSize = 10;
auditLogParametersDto.userId="User123";
// Act
var paginatedResult = await _service.GetAuditLogsBySpecificFilterAsync(auditLogParametersDto);
// Assert
// Assert
Assert.That(paginatedResult.Records.Count(), Is.EqualTo(1), "Should return only records matching the RecordId.");
var result = paginatedResult.Records.First();
Assert.That(result.RecordId, Is.EqualTo("Record123"), "The RecordId should match the filter.");
}
[Test]
public async Task GetAuditLogsAsync_FilterByDateRange_ReturnsMatchingRecords()
{
// Arrange
var now = DateTime.UtcNow;
var records = new List<AuditRecord>
{
new AuditRecord
{
EntityType = "User",
RecordId = "1",
UserId = "User1",
ActionType = "Create",
ActionTime = now.AddDays(-2),
Reason = "Old record",
Changes = new List<AuditRecord.Change>()
},
new AuditRecord
{
EntityType = "Admin",
RecordId = "2",
UserId = "User2",
ActionType = "Update",
ActionTime = now,
Reason = "Current record",
Changes = new List<AuditRecord.Change>()
}
};
foreach (var record in records)
{
await _service.AuditLogRepository.InsertOneAsync(record);
}
SpecificAuditLogFilterDto auditLogParametersDto = new SpecificAuditLogFilterDto();
auditLogParametersDto.pageNumber=1;
auditLogParametersDto.pageSize = 10;
auditLogParametersDto.startDate=now.AddDays(-1);
auditLogParametersDto.endDate=now;
// Act
var paginatedResult = await _service.GetAuditLogsBySpecificFilterAsync(auditLogParametersDto);
// Assert
// Assert
Assert.That(paginatedResult.Records.Count(), Is.EqualTo(1), "Should return only records within the date range.");
var result = paginatedResult.Records.First();
Assert.That(result.RecordId, Is.EqualTo("2"), "Only the record within the date range should be returned.");
}
[Test]
public async Task GetAuditLogsAsync_CombinationOfFilters_ReturnsMatchingRecords()
{
// Arrange
var now = DateTime.UtcNow;
var records = new List<AuditRecord>
{
new AuditRecord
{
EntityType = "User",
RecordId = "123",
UserId = "User123",
ActionType = "Create",
ActionTime = now.AddDays(-1),
Reason = "Testing combinatoin filter",
Changes = new List<AuditRecord.Change>()
},
new AuditRecord
{
EntityType = "Admin",
RecordId = "456",
UserId = "User456",
ActionType = "Delete",
ActionTime = now,
Reason = "Testng combination filter",
Changes = new List<AuditRecord.Change>()
}
};
foreach (var record in records)
{
await _service.AuditLogRepository.InsertOneAsync(record);
}
SpecificAuditLogFilterDto auditLogParametersDto = new SpecificAuditLogFilterDto();
auditLogParametersDto.pageNumber=1;
auditLogParametersDto.pageSize = 10;
auditLogParametersDto.userId="User123";
auditLogParametersDto.startDate=now.AddDays(-2);
auditLogParametersDto.endDate=now;
// Act
var paginatedResult = await _service.GetAuditLogsBySpecificFilterAsync(auditLogParametersDto);
// Assert
// Assert
Assert.That(paginatedResult.Records.Count(), Is.EqualTo(1), "Should return only records matching all filters.");
var result = paginatedResult.Records.First();
Assert.That(result.RecordId, Is.EqualTo("123"), "The record should match all filters.");
Assert.That(result.UserId, Is.EqualTo("User123"), "The UserId should match the filter.");
}
[Test]
public async Task GetAuditLogsAsync_FilterByEntityType_ReturnsMatchingRecords()
{
// Arrange
var records = new List<AuditRecord>
{
new AuditRecord
{
EntityType = "User",
RecordId = "1",
UserId = "User123",
ActionType = "Create",
ActionTime = DateTime.UtcNow.AddMinutes(-10),
Reason = "Testing filter by EntityType",
Changes = new List<AuditRecord.Change>()
},
new AuditRecord
{
EntityType = "Admin",
RecordId = "2",
UserId = "User456",
ActionType = "Delete",
ActionTime = DateTime.UtcNow,
Reason = "Testing filter by EntityType",
Changes = new List<AuditRecord.Change>()
}
};
SpecificAuditLogFilterDto auditLogParametersDto = new SpecificAuditLogFilterDto();
auditLogParametersDto.pageNumber=1;
auditLogParametersDto.pageSize = 10;
auditLogParametersDto.entityType = "User";
foreach (var record in records)
{
await _service.AuditLogRepository.InsertOneAsync(record);
}
// Act
var paginatedResult = await _service.GetAuditLogsBySpecificFilterAsync(auditLogParametersDto);
// Assert
Assert.That(paginatedResult.Records.Count(), Is.EqualTo(1), "Should return only records matching the EntityType filter.");
var result = paginatedResult.Records.First();
Assert.That(result.EntityType, Is.EqualTo("User"), "The EntityType should match the filter.");
}
[Test]
public async Task GetAuditLogsMatchingTextAsync_WithSearchText_ReturnsMatchingRecords()
{
// Arrange
var records = new List<AuditRecord>
{
new AuditRecord
{
EntityType = "User",
RecordId = "nhc1",
UserId = "User123",
ActionType = "Create",
ActionTime = DateTime.UtcNow,
Reason = "Include this record",
UserIpAddress = "192.168.1.1"
},
new AuditRecord
{
EntityType = "Admin",
RecordId = "nhc2",
UserId = "User456",
ActionType = "Delete",
ActionTime = DateTime.UtcNow,
Reason = "Do not include this record",
UserIpAddress = "192.168.1.2"
}
};
foreach (var record in records)
{
await _service.AuditLogRepository.InsertOneAsync(record);
}
AuditLogTextOrDateSearchDTO orDateSearchTextOrDateDto = new AuditLogTextOrDateSearchDTO
{
pageNumber = 1,
pageSize = 10,
searchText = "nhc2"
};
// Act
var result = await _service.GetAuditLogsMatchingTextOrDateAsync(orDateSearchTextOrDateDto);
// Assert
Assert.That(result.Records.Count, Is.EqualTo(1), "Should return only records matching the search text.");
Assert.That(result.Records.First().UserId, Is.EqualTo("User456"), "The UserId should match the record with the included search text.");
}
[Test]
public async Task GetAuditLogsMatchingTextAsync_WithoutSearchText_ReturnsAllRecords()
{
// Arrange
var records = new List<AuditRecord>
{
new AuditRecord
{
EntityType = "User",
RecordId = "1",
UserId = "User123",
ActionType = "Create",
ActionTime = DateTime.UtcNow,
Reason = "First record",
UserIpAddress = "192.168.1.1"
},
new AuditRecord
{
EntityType = "Admin",
RecordId = "2",
UserId = "User456",
ActionType = "Delete",
ActionTime = DateTime.UtcNow,
Reason = "Second record",
UserIpAddress = "192.168.1.2"
}
};
foreach (var record in records)
{
await _service.AuditLogRepository.InsertOneAsync(record);
}
AuditLogTextOrDateSearchDTO orDateSearchTextOrDateDto = new AuditLogTextOrDateSearchDTO
{
pageNumber = 1,
pageSize = 10
};
// Act
var result = await _service.GetAuditLogsMatchingTextOrDateAsync(orDateSearchTextOrDateDto);
// Assert
Assert.That(result.Records.Count, Is.EqualTo(2), "Should return all records when no search text is provided.");
}
[Test]
public async Task GetAuditLogsMatchingTextAsync_WithDateRange_ReturnsMatchingRecords()
{
// Arrange
var now = DateTime.UtcNow;
var earlier = now.AddDays(-1);
var records = new List<AuditRecord>
{
new AuditRecord
{
EntityType = "User",
RecordId = "123",
UserId = "User123",
ActionType = "Create",
ActionTime = earlier,
Reason = "Old record",
UserIpAddress = "192.168.1.1"
},
new AuditRecord
{
EntityType = "Admin",
RecordId = "456",
UserId = "User456",
ActionType = "Delete",
ActionTime = now,
Reason = "Recent record",
UserIpAddress = "192.168.1.2"
}
};
foreach (var record in records)
{
await _service.AuditLogRepository.InsertOneAsync(record);
}
AuditLogTextOrDateSearchDTO searchDto = new AuditLogTextOrDateSearchDTO
{
pageNumber = 1,
pageSize = 10,
searchText = "",
startDate = earlier,
endDate = now
};
// Act
var result = await _service.GetAuditLogsMatchingTextOrDateAsync(searchDto);
// Assert
Assert.That(result.Records.Count(),Is.EqualTo(2),"Should return records within the date range.");
}
[Test]
public async Task GetAuditLogsMatchingTextAsync_WithTextAndDateFilters_ReturnsCorrectlyFilteredRecords()
{
// Arrange
var now = DateTime.UtcNow;
var earlier = now.AddDays(-2);
var records = new List<AuditRecord>
{
new AuditRecord
{
EntityType = "User",
RecordId = "123",
UserId = "User123",
ActionType = "Create",
ActionTime = now.AddDays(-1),
Reason = "Old record",
UserIpAddress = "192.168.1.1"
},
new AuditRecord
{
EntityType = "Admin",
RecordId = "456",
UserId = "User456",
ActionType = "Delete",
ActionTime = now,
Reason = "Recent record",
UserIpAddress = "192.168.1.2"
}
};
foreach (var record in records)
{
await _service.AuditLogRepository.InsertOneAsync(record);
}
AuditLogTextOrDateSearchDTO searchDto = new AuditLogTextOrDateSearchDTO
{
pageNumber = 1,
pageSize = 10,
searchText = "123",
startDate = earlier,
endDate = now//now.AddDays(-0.5) // This will exclude the recent record
};
// Act
var result = await _service.GetAuditLogsMatchingTextOrDateAsync(searchDto);
// Assert
Assert.That(result.Records.Count, Is.EqualTo(1), "Should return only records matching both text and date range filters.");
Assert.That(result.Records.First().Reason, Is.EqualTo("Old record"), "The Reason should match the filter.");
}
[Test]
public async Task GetAuditLogsMatchingTextAsync_NoMatchingCriteria_ReturnsNoRecords()
{
// Arrange
var now = DateTime.UtcNow;
var records = new List<AuditRecord>
{
new AuditRecord
{
EntityType = "User",
RecordId = "123",
UserId = "User123",
ActionType = "Create",
ActionTime = now.AddDays(-2),
Reason = "Old record",
UserIpAddress = "192.168.1.1"
}
};
foreach (var record in records)
{
await _service.AuditLogRepository.InsertOneAsync(record);
}
AuditLogTextOrDateSearchDTO searchDto = new AuditLogTextOrDateSearchDTO
{
pageNumber = 1,
pageSize = 10,
searchText = "No match",
startDate = DateTime.UtcNow.AddDays(-5),
endDate = DateTime.UtcNow.AddDays(-3)
};
// Act
var result = await _service.GetAuditLogsMatchingTextOrDateAsync(searchDto);
// Assert
Assert.That(result.Records.Count(),Is.EqualTo(0));
}
}
@@ -0,0 +1,77 @@
namespace audit_test.Repository;
using audit_logs.Models.DTO;
using audit.Model;
using audit_logs.Services;
using NUnit.Framework;
using System;
using System.Linq;
using System.Threading.Tasks;
[TestFixture]
[Category("Integration")]
public class AuditServiceFilterbyTextAndDateTests
{
private AuditService _service;
[SetUp]
public void Setup()
{
// Crear la instancia del servicio utilizando la base de datos real
_service = new AuditService(IntegrationDbReal.Database);
}
[Test]
public async Task VerifyAllRecordsLoaded_ReturnsCorrectCount()
{
// Act
var allRecords = await _service.AuditLogRepository.GetAllAuditRecordsAsync();
// Assert
Assert.That(allRecords.Count(), Is.EqualTo(3), "All records from the JSON file should be loaded.");
}
[Test]
public async Task GetAuditLogsAsync_FilterByDateRange_ReturnsCorrectRecords()
{
// Arrange
var startDate = DateTime.ParseExact("2024-11-21T23:29:40.267Z", "yyyy-MM-ddTHH:mm:ss.fffZ", System.Globalization.CultureInfo.InvariantCulture).ToUniversalTime();
var endDate = DateTime.ParseExact("2024-11-22T08:48:51.194Z", "yyyy-MM-ddTHH:mm:ss.fffZ", System.Globalization.CultureInfo.InvariantCulture).ToUniversalTime();
var auditLogParametersDto = new AuditLogTextOrDateSearchDTO
{
pageNumber = 1,
pageSize = 10,
startDate = startDate,
endDate = endDate
};
// Act
var paginatedResult = await _service.GetAuditLogsMatchingTextOrDateAsync(auditLogParametersDto);
// Assert
Assert.That(paginatedResult.Records.Count, Is.EqualTo(0), "Should return only records within the specified date range.");
}
[Test]
public async Task GetAuditLogsAsync_FilterByTextAndDateRange_ReturnsCorrectRecords()
{
// Arrange
var startDate = DateTime.Parse("2024-11-21T23:29:40.267Z");
var endDate = DateTime.Parse("2024-11-22T08:48:51.194Z");
var auditLogParametersDto = new AuditLogTextOrDateSearchDTO
{
pageNumber = 1,
pageSize = 10,
startDate = startDate,
endDate = endDate,
searchText = "673fc258d26d3f5086c49598"
};
// Act
var paginatedResult = await _service.GetAuditLogsMatchingTextOrDateAsync(auditLogParametersDto);
// Assert
Assert.That(paginatedResult.Records.Count, Is.EqualTo(0), "Should return only records matching the text and date range.");
}
}
+372
View File
@@ -0,0 +1,372 @@
using System.Security.Claims;
using audit_logs.Models;
using audit_logs.Models.DTO;
using audit_logs.Utils;
using MongoDB.Bson;
namespace audit_test.Repository;
using audit_logs.Repositories;
using audit.Model;
using audit_logs.Services;
public class AuditServiceIntegrationTests
{
private AuditService _service;
// private AuditRecordRepository _repository;
[Order(1)]
[SetUp]
public void Setup()
{
IntegrationDb.Database.DropCollectionAsync("audit_records");
//_repository = new AuditRecordRepository(IntegrationDb.Database);
//_service = new AuditService(IntegrationDb.Database);
_service = new AuditService(IntegrationDbReal.Database);
}
[Test]
public async Task RecordAuditAsync_CreatesAndRetrievesAuditRecord()
{
// Arrange
var changes = new List<AuditRecord.Change>
{
new AuditRecord.Change
{ Field = "Username", OldValue = "oldUser", NewValue = "newUser", ValueType = "String" }
};
AuditRecord auditLogData = new();
auditLogData.EntityType = "User";
auditLogData.RecordId = "1";
auditLogData.UserId = "123";
auditLogData.ActionType = "Update";
auditLogData.ActionTime = DateTime.UtcNow;
auditLogData.Reason = "Testing change detection";
auditLogData.UserIpAddress = "127.0.0.1";
auditLogData.Changes = changes;
// Act
await _service.RecordAuditAsync(auditLogData);
// Retrieve all records to validate insertion
var allRecords = await _service.AuditLogRepository.GetAllAuditRecordsAsync();
// Assert
Assert.AreEqual(1, allRecords.Count, "There should be exactly three audit record in the database.");
var storedRecord = allRecords[0];
Assert.AreEqual(auditLogData.EntityType, storedRecord.EntityType);
Assert.AreEqual(auditLogData.RecordId, storedRecord.RecordId);
Assert.AreEqual(auditLogData.UserId, storedRecord.UserId);
Assert.AreEqual(auditLogData.ActionType, storedRecord.ActionType);
Assert.AreEqual(auditLogData.Reason, storedRecord.Reason);
// Assert.That(storedRecord.Changes, Is.EquivalentTo(changes).Using(new ChangeComparer()), "Changes should match the input changes.");
}
[Test]
public async Task GetAllAuditRecords_ReturnsAllRecords()
{
// Prepare multiple records
var records = new List<AuditRecord>
{
new AuditRecord
{
EntityType = "User", RecordId = "1", UserId = "123", ActionType = "Create",
ActionTime = DateTime.UtcNow, Reason = "Test Reason 1"
},
new AuditRecord
{
EntityType = "Admin", RecordId = "2", UserId = "456", ActionType = "Delete",
ActionTime = DateTime.UtcNow, Reason = "Test Reason 2"
}
};
foreach (var rec in records)
{
await _service.AuditLogRepository.InsertOneAsync(rec);
}
// Test retrieval method
var allRecords = await _service.AuditLogRepository.GetAllAuditRecordsAsync();
// Assert
Assert.AreEqual(2, allRecords.Count, "All records should be retrieved.");
Assert.IsTrue(allRecords.Exists(r => r.RecordId == "1" && r.EntityType == "User"));
Assert.IsTrue(allRecords.Exists(r => r.RecordId == "2" && r.EntityType == "Admin"));
}
[Test]
public async Task DetectChangesAsync_DetectsAndRecordsChanges() //este es el que da problemas
{
// Arrange
// Arrange
var user = new ClaimsPrincipal(new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, "testUser"),
new Claim("IpAddress", "127.0.0.1")
}));
// Variables de auditoría
AuditLogData auditLogData = new();
auditLogData.OriginalJson = "{\"nhc\":\"C469\",\"person\":{\"admTime\":\"2024-11-26T12:03:36.276Z\",\"birthDate\":\"2024-11-02\",\"firstName\":\"Carlos Vi\",\"secondName\":\"Rey\",\"gender\":\"Male\",\"allergies\":\"\",\"ids\":{\"MR\":\"C469\"},\"historicalIds\":{}},\"unitId\":\"662760a96bdc7150b49fe29d\",\"admissionDate\":\"2024-11-26T12:03:36.276Z\",\"allergies\":\"\",\"diagnosis\":{\"optionType\":null,\"name\":\"Absceso amebiano del cerebro\",\"iconDefault\":null,\"iconLight\":null,\"iconDark\":null,\"color\":null,\"bgColor\":null,\"description\":\"A06.6\",\"initDate\":null,\"endDate\":null},\"origin\":{\"optionType\":null,\"name\":\"3A ucip\",\"iconDefault\":null,\"iconLight\":null,\"iconDark\":null,\"color\":null,\"bgColor\":null,\"description\":null,\"initDate\":null,\"endDate\":null},\"pointOfCareId\":null,\"languageBarrier\":\"\",\"originAux\":\"\",\"diagnosisAux\":\"Absceso amebiano del cerebro\"}";
// auditLogData.ModifiedJson = "{\"nhc\":\"H987541\",\"patientLocation\":{\"unitName\":\"SMACST\",\"bed\":\"SMT 2\",\"room\":\"SMT 2\"},\"person\":{\"admTime\":\"2024-11-26T10:31:37.018Z\",\"birthDate\":\"2024-11-01\",\"firstName\":\"Carlos\",\"secondName\":\"Borja\",\"gender\":\"Male\",\"allergies\":[{\"optionType\":null,\"name\":\"Sí\",\"iconDefault\":\"icCheck\",\"iconLight\":null,\"iconDark\":null,\"color\":null,\"bgColor\":null,\"description\":null,\"initDate\":null,\"endDate\":null}],\"ids\":{\"MR\":\"H987541\"},\"historicalIds\":{}},\"unitId\":\"662760a96bdc7150b49fe29d\",\"admissionDate\":\"2024-11-26T10:31:37.018Z\",\"allergies\":[{\"optionType\":null,\"name\":\"Sí\",\"iconDefault\":\"icCheck\",\"iconLight\":null,\"iconDark\":null,\"color\":null,\"bgColor\":null,\"description\":null,\"initDate\":null,\"endDate\":null}],\"diagnosis\":{\"optionType\":null,\"name\":\"Absceso amebiano del cerebro\",\"iconDefault\":null,\"iconLight\":null,\"iconDark\":null,\"color\":null,\"bgColor\":null,\"description\":\"A06.6\",\"initDate\":null,\"endDate\":null},\"origin\":{\"optionType\":null,\"name\":\"3A ucip\",\"iconDefault\":null,\"iconLight\":null,\"iconDark\":null,\"color\":null,\"bgColor\":null,\"description\":null,\"initDate\":null,\"endDate\":null},\"pointOfCareId\":\"662761fc6bdc7150b49fe29f\",\"languageBarrier\":\"\",\"originAux\":\"\",\"diagnosisAux\":\"Absceso amebiano del cerebro\"}";
auditLogData.ModifiedJson = null;//"{\"nhc\":\"C469\",\"person\":{\"admTime\":\"2024-11-26T12:03:36.276Z\",\"birthDate\":\"2024-11-01\",\"firstName\":\"Carlos V\",\"secondName\":\"Rey\",\"gender\":\"Male\",\"allergies\":\"\",\"ids\":{\"MR\":\"C469\"},\"historicalIds\":{}},\"unitId\":\"662760a96bdc7150b49fe29d\",\"admissionDate\":\"2024-11-26T12:03:36.276Z\",\"allergies\":\"\",\"diagnosis\":{\"optionType\":null,\"name\":\"Absceso amebiano del cerebro\",\"iconDefault\":null,\"iconLight\":null,\"iconDark\":null,\"color\":null,\"bgColor\":null,\"description\":\"A06.6\",\"initDate\":null,\"endDate\":null},\"origin\":{\"optionType\":null,\"name\":\"3A ucip\",\"iconDefault\":null,\"iconLight\":null,\"iconDark\":null,\"color\":null,\"bgColor\":null,\"description\":null,\"initDate\":null,\"endDate\":null},\"pointOfCareId\":null,\"languageBarrier\":\"\",\"originAux\":\"\",\"diagnosisAux\":\"Absceso amebiano del cerebro\"}";
auditLogData.EntityType = "User";
auditLogData.RecordId = "1";
auditLogData.UserId = "123";
auditLogData.ActionType = "Update";
auditLogData.ActionTime = DateTime.UtcNow;
auditLogData.Reason = "Testing change detection";
auditLogData.UserIpAddress = "127.0.0.1";
// Act - Llamar a DetectChangesAsync para que identifique cambios
//await _service.CreateAuditLogAsync(auditLogData);
await _service.CreateAuditLogAsync(auditLogData);
// Retrieve all records to validate insertion
var allRecords = await _service.AuditLogRepository.GetAllAuditRecordsAsync();
// Assert
Assert.AreEqual(1, allRecords.Count, "Debe haber exactamente un registro de auditoría en la base de datos.");
var storedRecord = allRecords[0];
Assert.AreEqual(auditLogData.EntityType, storedRecord.EntityType);
Assert.AreEqual(auditLogData.RecordId, storedRecord.RecordId);
Assert.AreEqual(auditLogData.UserId, storedRecord.UserId);
Assert.AreEqual(auditLogData.ActionType, storedRecord.ActionType);
Assert.AreEqual(auditLogData.Reason, storedRecord.Reason);
// Verificar que los cambios detectados sean correctos
Assert.That(storedRecord.Changes.Count, Is.EqualTo(10), "Debería detectar tres cambios.");
}
[Test]
public async Task GetAuditLogsAsync_ReturnsPaginatedRecords()
{
// Arrange - Insert multiple audit records to test pagination
var records = new List<AuditRecord>();
for (int i = 1; i <= 20; i++)
{
records.Add(new AuditRecord
{
EntityType = "TestEntity",
RecordId = i.ToString(),
UserId = "User" + i,
ActionType = "Create",
ActionTime = DateTime.UtcNow,
Reason = "Test Reason " + i,
Changes = new List<AuditRecord.Change>
{
new AuditRecord.Change
{
Field = "Field" + i,
OldValue = "OldValue" + i,
NewValue = "NewValue" + i,
ValueType = "String"
}
}
});
}
foreach (var record in records)
{
await _service.AuditLogRepository.InsertOneAsync(record);
}
// Act - Retrieve the first page with a page size of 5
int pageNumber = 1;
int pageSize = 5;
SpecificAuditLogFilterDto auditLogParametersDto = new SpecificAuditLogFilterDto();
auditLogParametersDto.pageNumber=1;
auditLogParametersDto.pageSize = 5;
var paginatedResult = await _service.GetAuditLogsBySpecificFilterAsync(auditLogParametersDto);
// Assert - Check that the pagination returns the correct number of records and page information
Assert.AreEqual(pageSize, paginatedResult.Records.Count(), "The number of records should match the page size.");
Assert.AreEqual(20, paginatedResult.TotalRecords,"The total number of records should match the inserted records.");
Assert.AreEqual(4, paginatedResult.TotalPages, "The total pages should be calculated correctly.");
Assert.AreEqual(pageNumber, paginatedResult.CurrentPage, "The current page should be correct.");
// Further assertions to check that the records and changes are the expected ones
var firstRecord = paginatedResult.Records.First();
Assert.AreEqual("TestEntity", firstRecord.EntityType);
Assert.AreEqual("1", firstRecord.RecordId);
Assert.AreEqual("User1", firstRecord.UserId);
Assert.AreEqual("Create", firstRecord.ActionType);
// Verify the changes for the first record
Assert.IsNotNull(firstRecord.Changes);
Assert.AreEqual(1, firstRecord.Changes.Count, "There should be exactly one change in the first record.");
var firstChange = firstRecord.Changes.First();
Assert.AreEqual("Field1", firstChange.Field);
Assert.AreEqual("OldValue1", firstChange.OldValue);
Assert.AreEqual("NewValue1", firstChange.NewValue);
Assert.AreEqual("String", firstChange.ValueType);
}
[Test]
public async Task CreateAuditLogAsync_CreatesCorrectAuditLog()
{
// Arrange
var user = new ClaimsPrincipal(new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, "testUser"),
new Claim("IpAddress", "127.0.0.1")
}));
var dataOriginal = new
{
Id = ObjectId.GenerateNewId(),
Name = "OldName",
Email = "old@example.com"
};
var dataModified = new
{
Id = dataOriginal.Id,
Name = "NewName",
Email = "new@example.com"
};
string reason = "Updating user details";
// Act
await _service.CreateAuditLogAsync(user, dataOriginal, dataModified, reason);
// Assert - Retrieve audit logs to validate
var allRecords = await _service.AuditLogRepository.GetAllAuditRecordsAsync();
Assert.AreEqual(1, allRecords.Count, "There should be exactly one audit log entry.");
var storedRecord = allRecords[0];
// Validate stored record
Assert.AreEqual("AnonymousType", storedRecord.EntityType);
Assert.AreEqual(dataOriginal.Id.ToString(), storedRecord.RecordId);
Assert.AreEqual("testUser", storedRecord.UserId);
Assert.AreEqual("update", storedRecord.ActionType);
Assert.AreEqual(reason, storedRecord.Reason);
Assert.AreEqual("127.0.0.1", storedRecord.UserIpAddress);
// Validate changes
Assert.AreEqual(2, storedRecord.Changes.Count, "There should be exactly two detected changes.");
var nameChange = storedRecord.Changes.Find(c => c.Field == "Name");
Assert.NotNull(nameChange, "There should be a change in the 'Name' field.");
Assert.AreEqual("OldName", nameChange.OldValue.AsString);
Assert.AreEqual("NewName", nameChange.NewValue.AsString);
Assert.AreEqual("string", nameChange.ValueType);
var emailChange = storedRecord.Changes.Find(c => c.Field == "Email");
Assert.NotNull(emailChange, "There should be a change in the 'Email' field.");
Assert.AreEqual("old@example.com", emailChange.OldValue.AsString);
Assert.AreEqual("new@example.com", emailChange.NewValue.AsString);
Assert.AreEqual("string", emailChange.ValueType);
}
[Test]
public async Task CreateAuditLogAsync_WithNullIpAndDataOriginal_CreatesCorrectAuditLog()
{
// Arrange
var user = new ClaimsPrincipal(new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, "testUser"),
// IP Address claim is not included to simulate a null IP scenario
}));
// Set dataOriginal to null to simulate scenario
object dataOriginal = null;
var dataModified = new
{
Id = ObjectId.GenerateNewId(),
Name = "NewName",
Email = "new@example.com"
};
string reason = "Creating new user";
// Act
await _service.CreateAuditLogAsync(user, dataOriginal, dataModified, reason);
// Assert - Retrieve audit logs to validate
var allRecords = await _service.AuditLogRepository.GetAllAuditRecordsAsync();
Assert.AreEqual(1, allRecords.Count, "There should be exactly one audit log entry.");
var storedRecord = allRecords[0];
// Validate stored record
Assert.AreEqual("AnonymousType", storedRecord.EntityType);
Assert.AreEqual(dataModified.Id.ToString(), storedRecord.RecordId);
Assert.AreEqual("testUser", storedRecord.UserId);
Assert.AreEqual("create", storedRecord.ActionType); // Action type should be 'create' as original data is null
Assert.AreEqual(reason, storedRecord.Reason);
// Validate changes - expecting changes in name and email as it's a creation
Assert.AreEqual(3, storedRecord.Changes.Count, "There should be exactly two detected changes.");
var nameChange = storedRecord.Changes.Find(c => c.Field == "Name");
Assert.NotNull(nameChange, "There should be a change in the 'Name' field.");
Assert.IsTrue(nameChange.OldValue.IsBsonNull, "Old value should be null for new creations.");
Assert.AreEqual("NewName", nameChange.NewValue.AsString);
Assert.AreEqual("string", nameChange.ValueType);
var emailChange = storedRecord.Changes.Find(c => c.Field == "Email");
Assert.NotNull(emailChange, "There should be a change in the 'Email' field.");
Assert.IsTrue(emailChange.OldValue.IsBsonNull, "Old value should be null for new creations.");
Assert.AreEqual("new@example.com", emailChange.NewValue.AsString);
Assert.AreEqual("string", emailChange.ValueType);
}
[Test]
public async Task CreateAuditLogAsync_WithNullIpAndDataModified_CreatesCorrectAuditLog()
{
// Arrange
var user = new ClaimsPrincipal(new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, "testUser"),
// IP Address claim is not included to simulate a null IP scenario
}));
// Set dataModified to null to simulate the scenario
object? dataModified = null;
var dataOriginal = new
{
Id = ObjectId.GenerateNewId(),
Name = "OldName",
Email = "old@example.com"
};
string reason = "Deleting user";
// Act
await _service.CreateAuditLogAsync(user, dataOriginal, dataModified, reason);
// Assert - Retrieve audit logs to validate
var allRecords = await _service.AuditLogRepository.GetAllAuditRecordsAsync();
Assert.AreEqual(1, allRecords.Count, "There should be exactly one audit log entry.");
var storedRecord = allRecords[0];
// Validate stored record
Assert.AreEqual("AnonymousType", storedRecord.EntityType);
Assert.AreEqual(dataOriginal.Id.ToString(), storedRecord.RecordId);
Assert.AreEqual("testUser", storedRecord.UserId);
Assert.AreEqual("delete", storedRecord.ActionType); // Action type should be 'delete' as modified data is null
Assert.AreEqual(reason, storedRecord.Reason);
// Validate changes - expecting no changes as it's a deletion
Assert.AreEqual(3, storedRecord.Changes.Count, "There should be exactly two detected changes.");
var nameChange = storedRecord.Changes.Find(c => c.Field == "Name");
Assert.NotNull(nameChange, "There should be a change in the 'Name' field.");
Assert.AreEqual("OldName", nameChange.OldValue.AsString, "Old value should be 'OldName'.");
Assert.IsTrue(nameChange.NewValue.IsBsonNull, "New value should be null for deletions.");
Assert.AreEqual("string", nameChange.ValueType);
var emailChange = storedRecord.Changes.Find(c => c.Field == "Email");
Assert.NotNull(emailChange, "There should be a change in the 'Email' field.");
Assert.AreEqual("old@example.com", emailChange.OldValue.AsString, "Old value should be 'old@example.com'.");
Assert.IsTrue(emailChange.NewValue.IsBsonNull, "New value should be null for deletions.");
Assert.AreEqual("string", emailChange.ValueType);
}
}
+69
View File
@@ -0,0 +1,69 @@
using audit_logs.Utils;
namespace audit_test.Repository;
using Mongo2Go;
using MongoDB.Bson;
using MongoDB.Driver;
[SetUpFixture]
[Category("Integration")]
public class IntegrationDb
{
public static MongoDbRunner Runner { get { return _runner; } }
public static MongoClient Client { get { return _client; } }
public static IMongoDatabase Database { get; private set; } = null!;
private static MongoDbRunner _runner = null!;
private static MongoClient _client = null!;
private const int TimeoutInSeconds = 60; // Set the desired timeout in seconds.
public static string DatabaseName { get; private set; } = "IntegrationTestDb";
[OneTimeSetUp]
public void InitIntegrationTests()
{
StartMongoDbRunner().Wait();
MongoDbHostBuilderExtension.ConfigureMongoDbConventions();
//MongoDbHostBuilderExtension.ConfigureRegisterMapClass();
_client = new MongoClient(_runner.ConnectionString);
Database = _client.GetDatabase(DatabaseName);
}
private static async Task StartMongoDbRunner()
{
_runner = MongoDbRunner.Start();
// Wait for the MongoDB server to become available or timeout.
var startTime = DateTime.UtcNow;
while (DateTime.UtcNow - startTime < TimeSpan.FromSeconds(TimeoutInSeconds))
{
try
{
var testClient = new MongoClient(_runner.ConnectionString);
var adminDb = testClient.GetDatabase("admin");
await adminDb.RunCommandAsync((Command<BsonDocument>)"{ping:1}");
return; // MongoDB server is available, continue.
}
catch
{
// Retry after a short delay.
await Task.Delay(500);
}
}
// Timeout reached, dispose the runner and throw an exception.
_runner?.Dispose();
throw new TimeoutException("Timeout while starting MongoDB server.");
}
[OneTimeTearDown]
public void TeardownIntegrationTests()
{
_runner?.Dispose();
_runner = null;
_client = null;
Database = null;
}
}
+31
View File
@@ -0,0 +1,31 @@
namespace audit_test.Repository;
using MongoDB.Bson;
using MongoDB.Driver;
using NUnit.Framework;
[SetUpFixture]
[Category("Integration")]
public class IntegrationDbReal
{
public static IMongoClient Client { get; private set; } = null!;
public static IMongoDatabase Database { get; private set; } = null!;
private const string ConnectionString = "mongodb://smacsuci:2(R*aQpu2r@julianrojas.xyz:27017/?authSource=admin";
private const string DatabaseName = "AuditMeddisPlanUciPanel";
[OneTimeSetUp]
public void InitIntegrationTests()
{
// Configurar cliente y base de datos
Client = new MongoClient(ConnectionString);
Database = Client.GetDatabase(DatabaseName);
}
[OneTimeTearDown]
public void TeardownIntegrationTests()
{
Client = null;
Database = null;
}
}