Se hicieron cambios en los filtros, se limpian los json para evtiar subir nulos y se arreglo el error que tenia con admision

This commit is contained in:
jrojas
2024-11-26 15:54:28 +01:00
parent 8c3be106f9
commit 7c08e6e218
122 changed files with 3745 additions and 1905 deletions
@@ -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("AuditRecords").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(5), "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(3), "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(1), "Should return only records matching the text and date range.");
}
}
@@ -1,5 +1,8 @@
using System.Security.Claims;
using audit_logs.Models;
using audit_logs.Models.DTO;
using audit_logs.Utils;
using MongoDB.Bson;
namespace audit_test.Repository;
@@ -10,7 +13,7 @@ using audit_logs.Services;
public class AuditServiceIntegrationTests
{
private AuditService _service;
// private AuditRecordRepository _repository;
// private AuditRecordRepository _repository;
[Order(1)]
[SetUp]
@@ -78,11 +81,11 @@ public class AuditServiceIntegrationTests
foreach (var rec in records)
{
await _service.AuditLogRepository.InsertOneAsync(rec);
await _service.AuditLogRepository.InsertOneAsync(rec);
}
// Test retrieval method
var allRecords = await _service.AuditLogRepository.GetAllAuditRecordsAsync();
var allRecords = await _service.AuditLogRepository.GetAllAuditRecordsAsync();
// Assert
Assert.AreEqual(2, allRecords.Count, "All records should be retrieved.");
@@ -91,15 +94,21 @@ public class AuditServiceIntegrationTests
}
[Test]
public async Task DetectChangesAsync_DetectsAndRecordsChanges()
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 = "{ \"Username\": \"oldUser\", \"Email\": \"old@example.com\", \"address\": 15 }";
auditLogData.ModifiedJson =
"{ \"Username\": \"newUser\", \"Email\": \"old@example.com\", \"PhoneNumber\": \"123456789\" }";
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";
@@ -111,12 +120,9 @@ public class AuditServiceIntegrationTests
// Act - Llamar a DetectChangesAsync para que identifique cambios
await _service.CreateAuditLogAsync(auditLogData);
// Act - Registrar la auditoría usando los cambios detectados
// List<AuditRecord.Change> changes = new JsonComparer().GetDifferences(originalJson, modifiedJson);
//await _service.RecordAuditAsync(entityType, recordId, userId, actionType, reason,actionTime, changes, );
// Retrieve all records to validate insertion
var allRecords = await _service.AuditLogRepository.GetAllAuditRecordsAsync();
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.");
@@ -128,80 +134,237 @@ public class AuditServiceIntegrationTests
Assert.AreEqual(auditLogData.Reason, storedRecord.Reason);
// Verificar que los cambios detectados sean correctos
Assert.That(storedRecord.Changes.Count, Is.EqualTo(3), "Debería detectar tres cambios.");
Assert.That(storedRecord.Changes.Count, Is.EqualTo(10), "Debería detectar tres cambios.");
var changeUsername = storedRecord.Changes.Find(c => c.Field == "Username");
Assert.NotNull(changeUsername, "Debe existir un cambio en el campo 'Username'.");
Assert.AreEqual("oldUser", changeUsername.OldValue.AsString);
Assert.AreEqual("newUser", changeUsername.NewValue.AsString);
Assert.AreEqual("string", changeUsername.ValueType);
var changePhoneNumber = storedRecord.Changes.Find(c => c.Field == "PhoneNumber");
Assert.NotNull(changePhoneNumber, "Debe existir un cambio en el campo 'PhoneNumber'.");
Assert.IsTrue(changePhoneNumber.OldValue.IsBsonNull, "El valor anterior de 'PhoneNumber' debe ser nulo.");
Assert.AreEqual("123456789", changePhoneNumber.NewValue.AsString);
Assert.AreEqual("string", changePhoneNumber.ValueType);
}
[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++)
public async Task GetAuditLogsAsync_ReturnsPaginatedRecords()
{
records.Add(new AuditRecord
// Arrange - Insert multiple audit records to test pagination
var records = new List<AuditRecord>();
for (int i = 1; i <= 20; i++)
{
EntityType = "TestEntity",
RecordId = i.ToString(),
UserId = "User" + i,
ActionType = "Create",
ActionTime = DateTime.UtcNow,
Reason = "Test Reason " + i,
Changes = new List<AuditRecord.Change>
records.Add(new AuditRecord
{
new AuditRecord.Change
EntityType = "TestEntity",
RecordId = i.ToString(),
UserId = "User" + i,
ActionType = "Create",
ActionTime = DateTime.UtcNow,
Reason = "Test Reason " + i,
Changes = new List<AuditRecord.Change>
{
Field = "Field" + i,
OldValue = "OldValue" + i,
NewValue = "NewValue" + i,
ValueType = "String"
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);
}
foreach (var record in records)
[Test]
public async Task CreateAuditLogAsync_CreatesCorrectAuditLog()
{
await _service.AuditLogRepository.InsertOneAsync(record);
// 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);
}
// Act - Retrieve the first page with a page size of 5
int pageNumber = 1;
int pageSize = 5;
var paginatedResult = await _service.GetAuditLogsAsync(pageNumber, pageSize);
[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
}));
// 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.");
// Set dataOriginal to null to simulate scenario
object dataOriginal = null;
// 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);
var dataModified = new
{
Id = ObjectId.GenerateNewId(),
Name = "NewName",
Email = "new@example.com"
};
// 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.AsString);
Assert.AreEqual("NewValue1", firstChange.NewValue.AsString);
Assert.AreEqual("String", firstChange.ValueType);
}
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);
}
}
@@ -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;
}
}