diff --git a/Kiss.Bff.Test/AuthorizationCheckTests.cs b/Kiss.Bff.Test/AuthorizationCheckTests.cs index f306a5e49..5e1646b12 100644 --- a/Kiss.Bff.Test/AuthorizationCheckTests.cs +++ b/Kiss.Bff.Test/AuthorizationCheckTests.cs @@ -1,5 +1,19 @@ -using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using System.Reflection; +using Microsoft.AspNetCore.Mvc.Testing; using static System.Net.HttpStatusCode; +using Microsoft.AspNetCore.Mvc.Routing; +using System.Net; +using Kiss.Bff.ZaakGerichtWerken.Contactmomenten; +using Kiss.Bff.Beheer.Faq; +using Kiss.Bff.Beheer.Data; +using Microsoft.EntityFrameworkCore; +using Kiss.Bff.Beheer.Gespreksresultaten.Controllers; +using Kiss.Bff.Beheer.Links.Controllers; +using static Kiss.Bff.Beheer.Links.Controllers.LinksController; +using Kiss.Bff.NieuwsEnWerkinstructies.Controllers; +using Kiss.Bff.Beheer.Verwerking; namespace Kiss.Bff.Test { @@ -23,15 +37,70 @@ public static void ClassCleanup() s_factory?.Dispose(); } + public static IEnumerable GetControllersWithAuthorizeAttributeAndMethods() + { + // Define the controllers and methods to test here + var controllersWithMethodsToTest = new List<(Type controllerType, string methodName, Type[] parameterTypes)> + { + (typeof(ReadContactmomentenDetails), "Get", new Type[0]), + (typeof(GespreksresultatenController), "PutGespreksresultaat", new[] { typeof(Guid), typeof(GespreksresultaatModel), typeof(CancellationToken) }), + (typeof(GespreksresultatenController), "PostGespreksresultaat", new[] { typeof(GespreksresultaatModel), typeof(CancellationToken)}), + (typeof(GespreksresultatenController), "DeleteGespreksresultaat", new[] { typeof(Guid), typeof(CancellationToken)}), + (typeof(LinksController), "PutLink", new[] { typeof(int), typeof(LinkPutModel),typeof(CancellationToken)}), + (typeof(LinksController), "PostLink", new[] { typeof(LinkPostModel) }), + (typeof(LinksController), "DeleteLink", new[] { typeof(int) }), + (typeof(SkillsController), "PutSkill", new[] { typeof(int), typeof(SkillPutModel), typeof(CancellationToken) }), + (typeof(SkillsController), "PostSkill", new[] { typeof(SkillPostModel), typeof(CancellationToken) }), + (typeof(GetVerwerkingsLogs), "Get", new Type[0]), + // Add more controller, method, and parameter combinations as needed + }; + + foreach (var (controllerType, methodName, parameterTypes) in controllersWithMethodsToTest) + { + yield return new object[] { controllerType, methodName, parameterTypes }; + } + } + [DataTestMethod] [DataRow("/api/postcontactmomenten", "post")] [DataRow("/api/internetaak/api/version/objects", "post")] [DataRow("/api/faq")] + [DataRow("/api/contactmomentendetails?id=1")] public async Task Test(string url, string method = "get") { using var request = new HttpRequestMessage(new(method), url); using var response = await s_client.SendAsync(request); Assert.AreEqual(Unauthorized, response.StatusCode); } + + [DataTestMethod] + [DynamicData(nameof(GetControllersWithAuthorizeAttributeAndMethods), DynamicDataSourceType.Method)] + public async Task TestAuthorizeAttribute(Type controllerType, string methodName, Type[] parameterTypes) + { + // Manually create an instance of the controller + var dbContextOptions = new DbContextOptionsBuilder() + .UseInMemoryDatabase(databaseName: "TestDatabase") + .Options; + var dbContext = new BeheerDbContext(dbContextOptions); + var controller = Activator.CreateInstance(controllerType, dbContext) as ControllerBase; + + // Assert that the controller instance is not null + Assert.IsNotNull(controller); + + // Retrieve the method to test + var method = controllerType.GetMethod(methodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly, null, parameterTypes, null); + + // Assert that the method exists + Assert.IsNotNull(method); + + // Retrieve the Authorize attribute + var authorizeAttribute = method.GetCustomAttributes(typeof(AuthorizeAttribute), true) + .FirstOrDefault() as AuthorizeAttribute; + + // Assert that the Authorize attribute exists and has the expected policy + Assert.IsNotNull(authorizeAttribute); + Assert.AreEqual(Policies.RedactiePolicy, authorizeAttribute.Policy); + } } } + diff --git a/Kiss.Bff.Test/CategorienControllerTests.cs b/Kiss.Bff.Test/CategorienControllerTests.cs index ded6bc9b4..037177b24 100644 --- a/Kiss.Bff.Test/CategorienControllerTests.cs +++ b/Kiss.Bff.Test/CategorienControllerTests.cs @@ -1,13 +1,7 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Kiss.Bff.Beheer.Data; +using Kiss.Bff.Beheer.Data; using Kiss.Bff.Beheer.Links.Controllers; using Kiss.Bff.Beheer.Links.Data.Entities; using Microsoft.AspNetCore.Mvc; -using Microsoft.EntityFrameworkCore; namespace Kiss.Bff.Test { diff --git a/Kiss.Bff.Test/GetFaqTests.cs b/Kiss.Bff.Test/GetFaqTests.cs new file mode 100644 index 000000000..984fee7fc --- /dev/null +++ b/Kiss.Bff.Test/GetFaqTests.cs @@ -0,0 +1,74 @@ +using Kiss.Bff.Beheer.Data; +using Kiss.Bff.Beheer.Faq; +using Kiss.Bff.ZaakGerichtWerken.Contactmomenten; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; + +namespace Kiss.Bff.Test +{ + [TestClass] + public class GetFaqTests : TestHelper + { + [TestInitialize] + public void Initialize() + { + InitializeDatabase(); + } + + [TestCleanup] + public void Cleanup() + { + using var dbContext = new BeheerDbContext(_dbContextOptions); + dbContext.Database.EnsureDeleted(); + dbContext.Dispose(); + } + + [TestMethod] + public async Task Get_ReturnsTopQuestions() + { + using var dbContext = new BeheerDbContext(_dbContextOptions); + // Arrange + var controller = new GetFaq(dbContext); + + var testData = new List(); + var topQuestionsCount = 10; + + // Add 500 questions + for (int i = 1; i <= 500; i++) + { + testData.Add(new ContactmomentDetails + { + Id = i.ToString(), + Vraag = $"Question {i}", + Einddatum = DateTime.UtcNow + }); + } + + dbContext.ContactMomentDetails.AddRange(testData); + dbContext.SaveChanges(); + + // Act + var result = controller.Get() as OkObjectResult; + + // Assert + Assert.IsNotNull(result); + Assert.AreEqual(200, result.StatusCode); + + var resultList = result.Value as IEnumerable; + Assert.IsNotNull(resultList); + + // Ensure that the result contains the top questions + var expectedQuestions = testData + .OrderByDescending(x => x.Einddatum) + .Where(x => !string.IsNullOrWhiteSpace(x.Vraag)) + .GroupBy(x => x.Vraag) + .OrderByDescending(x => x.Count()) + .Take(topQuestionsCount) + .Select(x => x.Key); + + CollectionAssert.AreEqual(expectedQuestions.ToList(), resultList.ToList()); + } + + } +} diff --git a/Kiss.Bff.Test/GetFeaturedCountControllerTests.cs b/Kiss.Bff.Test/GetFeaturedCountControllerTests.cs index 41b0d918c..d7e47b9d8 100644 --- a/Kiss.Bff.Test/GetFeaturedCountControllerTests.cs +++ b/Kiss.Bff.Test/GetFeaturedCountControllerTests.cs @@ -1,17 +1,7 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Security.Claims; -using System.Text; -using System.Threading.Tasks; -using Kiss.Bff.Beheer.Data; +using Kiss.Bff.Beheer.Data; using Kiss.Bff.NieuwsEnWerkinstructies.Controllers; using Kiss.Bff.NieuwsEnWerkinstructies.Data.Entities; -using Kiss.Bff.NieuwsEnWerkinstructies.Migrations; -using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; namespace Kiss.Bff.Test { diff --git a/Kiss.Bff.Test/LinksControllerUnitTests.cs b/Kiss.Bff.Test/LinksControllerUnitTests.cs index da26ad5dd..c0c9025f6 100644 --- a/Kiss.Bff.Test/LinksControllerUnitTests.cs +++ b/Kiss.Bff.Test/LinksControllerUnitTests.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Kiss.Bff.Beheer.Data; +using Kiss.Bff.Beheer.Data; using Kiss.Bff.Beheer.Links.Controllers; using Kiss.Bff.Beheer.Links.Data.Entities; using Microsoft.AspNetCore.Mvc; diff --git a/Kiss.Bff.Test/MarkeerGelezenControllerTests.cs b/Kiss.Bff.Test/MarkeerGelezenControllerTests.cs index e52a1c537..b2b31c241 100644 --- a/Kiss.Bff.Test/MarkeerGelezenControllerTests.cs +++ b/Kiss.Bff.Test/MarkeerGelezenControllerTests.cs @@ -1,17 +1,9 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Security.Claims; -using System.Text; -using System.Threading.Tasks; -using IdentityModel; +using System.Security.Claims; using Kiss.Bff.Beheer.Data; using Kiss.Bff.NieuwsEnWerkinstructies.Controllers; using Kiss.Bff.NieuwsEnWerkinstructies.Data.Entities; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; namespace Kiss.Bff.Test { diff --git a/Kiss.Bff.Test/ReadContactmomentenDetailsTests.cs b/Kiss.Bff.Test/ReadContactmomentenDetailsTests.cs new file mode 100644 index 000000000..a37a97150 --- /dev/null +++ b/Kiss.Bff.Test/ReadContactmomentenDetailsTests.cs @@ -0,0 +1,104 @@ +using System; +using System.Linq.Expressions; +using System.Security.Claims; +using Kiss.Bff.Beheer.Data; +using Kiss.Bff.ZaakGerichtWerken.Contactmomenten; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; + +namespace Kiss.Bff.Test +{ + [TestClass] + public class ReadContactmomentenDetailsTests : TestHelper + { + private IServiceProvider? _serviceProvider; + + [TestInitialize] + public void Initialize() + { + InitializeDatabase(); + SeedTestData(); + + var services = new ServiceCollection(); + var user = new ClaimsPrincipal(new ClaimsIdentity(new[] + { + new Claim(ClaimTypes.NameIdentifier, "testuser"), + new Claim(ClaimTypes.Role, Policies.RedactiePolicy) + })); + services.AddSingleton(_ => new HttpContextAccessor { HttpContext = new DefaultHttpContext { User = user } }); + _serviceProvider = services.BuildServiceProvider(); + } + + [TestCleanup] + public void Cleanup() + { + using var dbContext = new BeheerDbContext(_dbContextOptions); + dbContext.Database.EnsureDeleted(); + dbContext.Dispose(); + } + + private void SeedTestData() + { + using var dbContext = new BeheerDbContext(_dbContextOptions); + var contactmoment1 = new ContactmomentDetails + { + Id = "1", + Startdatum = DateTime.Now, + Einddatum = DateTime.Now.AddHours(1), + Gespreksresultaat = "Result 1", + Vraag = "Question 1" + }; + + var contactmoment2 = new ContactmomentDetails + { + Id = "2", + Startdatum = DateTime.Now, + Einddatum = DateTime.Now.AddHours(1), + Gespreksresultaat = "Result 2", + Vraag = "Question 2" + }; + + dbContext.ContactMomentDetails.AddRange(contactmoment1, contactmoment2); + dbContext.SaveChanges(); + } + + [TestMethod] + public async Task Get_ValidId_ReturnsOk() + { + using var dbContext = new BeheerDbContext(_dbContextOptions); + // Arrange + var controller = new ReadContactmomentenDetails(dbContext); + var validId = "1"; + + // Act + var result = await controller.Get(validId, CancellationToken.None) as OkObjectResult; + + // Assert + Assert.IsNotNull(result); + Assert.AreEqual(200, result.StatusCode); + + var contactmoment = result.Value as ContactmomentDetails; + Assert.IsNotNull(contactmoment); + Assert.AreEqual(validId, contactmoment.Id); + } + + [TestMethod] + public async Task Get_InvalidId_ReturnsNotFound() + { + using var dbContext = new BeheerDbContext(_dbContextOptions); + // Arrange + var controller = new ReadContactmomentenDetails(dbContext); + var invalidId = "nonexistent"; + + // Act + var result = await controller.Get(invalidId, CancellationToken.None) as NotFoundResult; + + // Assert + Assert.IsNotNull(result); + Assert.AreEqual(404, result.StatusCode); + } + } +} diff --git a/Kiss.Bff.Test/ReadContactverzoekenVragensetsTests.cs b/Kiss.Bff.Test/ReadContactverzoekenVragensetsTests.cs new file mode 100644 index 000000000..ce6950314 --- /dev/null +++ b/Kiss.Bff.Test/ReadContactverzoekenVragensetsTests.cs @@ -0,0 +1,86 @@ +using Kiss.Bff.Beheer.Data; +using Kiss.Bff.ZaakGerichtWerken.Contactverzoeken; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.Extensions.DependencyInjection; + +namespace Kiss.Bff.Test +{ + [TestClass] + public class ReadContactverzoekenVragenSetsTests : TestHelper + { + [TestInitialize] + public void Initialize() + { + InitializeDatabase(); + } + + [TestCleanup] + public void Cleanup() + { + using var dbContext = new BeheerDbContext(_dbContextOptions); + dbContext.Database.EnsureDeleted(); + dbContext.Dispose(); + } + + [TestMethod] + public async Task Get_ContactVerzoekVragenSetsExist_ReturnsOkWithList() + { + using var dbContext = new BeheerDbContext(_dbContextOptions); + // Arrange + var controller = new ReadContactverzoekenVragenSets(dbContext); + + var vragenSets = new List + { + new ContactVerzoekVragenSet + { + Id = 1, + Titel = "VragenSet 1", + JsonVragen = "{ \"Question1\": \"Answer1\" }", + AfdelingId = "Dept1" + }, + new ContactVerzoekVragenSet + { + Id = 2, + Titel = "VragenSet 2", + JsonVragen = "{ \"Question2\": \"Answer2\" }", + AfdelingId = "Dept2" + } + }; + + await dbContext.ContactVerzoekVragenSets.AddRangeAsync(vragenSets); + await dbContext.SaveChangesAsync(); + + // Act + var result = await controller.Get(CancellationToken.None) as OkObjectResult; + + // Assert + Assert.IsNotNull(result); + Assert.AreEqual(200, result.StatusCode); + + var resultList = result.Value as List; + Assert.IsNotNull(resultList); + Assert.AreEqual(2, resultList.Count); + } + + [TestMethod] + public async Task Get_NoContactVerzoekVragenSets_ReturnsOkWithEmptyList() + { + using var dbContext = new BeheerDbContext(_dbContextOptions); + // Arrange + var controller = new ReadContactverzoekenVragenSets(dbContext); + + // Act + var result = await controller.Get(CancellationToken.None) as OkObjectResult; + + // Assert + Assert.IsNotNull(result); + Assert.AreEqual(200, result.StatusCode); + + var resultList = result.Value as List; + Assert.IsNotNull(resultList); + Assert.AreEqual(0, resultList.Count); + } + } +} diff --git a/Kiss.Bff.Test/SearchBerichtenControllerTests.cs b/Kiss.Bff.Test/SearchBerichtenControllerTests.cs index 0e317a7e1..e63d9e9d4 100644 --- a/Kiss.Bff.Test/SearchBerichtenControllerTests.cs +++ b/Kiss.Bff.Test/SearchBerichtenControllerTests.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Security.Claims; -using System.Text; -using System.Threading.Tasks; +using System.Security.Claims; using Kiss.Bff.Beheer.Data; using Kiss.Bff.NieuwsEnWerkinstructies.Controllers; using Kiss.Bff.NieuwsEnWerkinstructies.Data.Entities; diff --git a/Kiss.Bff.Test/SkillsUnitTests.cs b/Kiss.Bff.Test/SkillsUnitTests.cs index 07bc8b091..bef813502 100644 --- a/Kiss.Bff.Test/SkillsUnitTests.cs +++ b/Kiss.Bff.Test/SkillsUnitTests.cs @@ -1,27 +1,18 @@ -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using Microsoft.AspNetCore.Mvc; using Kiss.Bff.Beheer.Data; using Kiss.Bff.NieuwsEnWerkinstructies.Controllers; using Kiss.Bff.NieuwsEnWerkinstructies.Data.Entities; -using Kiss.Bff.Test; +using Microsoft.EntityFrameworkCore; namespace Kiss.Bff.Test { [TestClass] public class SkillsControllerUnitTests : TestHelper { - private SkillsController _controller; - [TestInitialize] public void Initialize() { InitializeDatabase(); - var dbContext = new BeheerDbContext(_dbContextOptions); - _controller = new SkillsController(dbContext); } [TestMethod] @@ -36,14 +27,17 @@ public async Task GetSkills_ReturnsOkResult_WithSkills() }); dbContext.SaveChanges(); + var controller = new SkillsController(dbContext); + // Act - var actionResult = _controller.GetSkills(); + var actionResult = controller.GetSkills(); var okResult = actionResult?.Result as OkObjectResult; var resultSkills = okResult?.Value as IAsyncEnumerable; // Assert var skillsList = new List(); - var enumerator = resultSkills.GetAsyncEnumerator(); + var enumerator = resultSkills?.GetAsyncEnumerator(); + if (enumerator != null) while (await enumerator.MoveNextAsync()) { skillsList.Add(enumerator.Current); @@ -78,7 +72,9 @@ public async Task GetSkill_ReturnsOkResult_WithValidId() public async Task GetSkill_ReturnsNotFoundResult_WithInvalidId() { // Act - var actionResult = await _controller.GetSkill(1, CancellationToken.None); + using var dbContext = new BeheerDbContext(_dbContextOptions); + var controller = new SkillsController(dbContext); + var actionResult = await controller.GetSkill(1, CancellationToken.None); var notFoundResult = actionResult.Result as NotFoundResult; // Assert @@ -111,9 +107,11 @@ public async Task PutSkill_ReturnsNotFoundResult_WithInvalidId() { // Arrange var updatedSkill = new SkillPutModel { Naam = "Updated Skill" }; + var dbContext = new BeheerDbContext(_dbContextOptions); + var controller = new SkillsController(dbContext); // Act - var actionResult = await _controller.PutSkill(1, updatedSkill, CancellationToken.None); + var actionResult = await controller.PutSkill(1, updatedSkill, CancellationToken.None); var notFoundResult = actionResult as NotFoundResult; // Assert @@ -126,9 +124,10 @@ public async Task PostSkill_ReturnsCreatedAtActionResult_WithValidModel() // Arrange var dbContext = new BeheerDbContext(_dbContextOptions); var newSkill = new SkillPostModel { Naam = "New Skill" }; + var controller = new SkillsController(dbContext); // Act - var actionResult = await _controller.PostSkill(newSkill, CancellationToken.None); + var actionResult = await controller.PostSkill(newSkill, CancellationToken.None); var createdAtActionResult = actionResult.Result as CreatedAtActionResult; var resultSkill = createdAtActionResult?.Value as Skill; @@ -165,7 +164,9 @@ public async Task DeleteSkill_ReturnsNoContentResult_WithValidId() public async Task DeleteSkill_ReturnsNotFoundResult_WithInvalidId() { // Act - var actionResult = await _controller.DeleteSkill(1, CancellationToken.None); + var dbContext = new BeheerDbContext(_dbContextOptions); + var controller = new SkillsController(dbContext); + var actionResult = await controller.DeleteSkill(1, CancellationToken.None); var notFoundResult = actionResult as NotFoundResult; // Assert diff --git a/Kiss.Bff.Test/TestHelper.cs b/Kiss.Bff.Test/TestHelper.cs index 3ccdbb38e..2af7683b8 100644 --- a/Kiss.Bff.Test/TestHelper.cs +++ b/Kiss.Bff.Test/TestHelper.cs @@ -1,8 +1,16 @@ global using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Security.Claims; using Kiss.Bff.Beheer.Data; +using Microsoft.AspNetCore.Authorization.Infrastructure; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using Moq; namespace Kiss.Bff.Test { @@ -20,6 +28,29 @@ public void InitializeDatabase() .ConfigureWarnings(x => x.Ignore(InMemoryEventId.TransactionIgnoredWarning)) .Options; } + + public static bool IsUserAuthorized(string policyName, ClaimsPrincipal user) + { + var serviceProvider = new ServiceCollection() + .AddAuthorization(options => + { + options.AddPolicy(policyName, policy => policy.RequireAssertion(context => + { + return context.User.HasClaim(c => c.Type == ClaimTypes.Name) && context.User.HasClaim(c => c.Type == ClaimTypes.Email); + })); + }) + .BuildServiceProvider(); + + var httpContext = new DefaultHttpContext + { + User = user + }; + + var authorizationService = serviceProvider.GetRequiredService(); + var authorizationResult = authorizationService.AuthorizeAsync(httpContext.User, null, policyName).GetAwaiter().GetResult(); + + return authorizationResult.Succeeded; + } } } diff --git a/Kiss.Bff.Test/UserExtentionsTests.cs b/Kiss.Bff.Test/UserExtentionsTests.cs new file mode 100644 index 000000000..07595692f --- /dev/null +++ b/Kiss.Bff.Test/UserExtentionsTests.cs @@ -0,0 +1,158 @@ +using IdentityModel; +using System.Security.Claims; + +namespace Kiss.Bff.Test +{ + [TestClass] + public class UserExtensionsTests + { + [TestMethod] + public void GetId_UserHasObjectIdentifier_ReturnsObjectIdentifier() + { + // Arrange + var user = new ClaimsPrincipal(new ClaimsIdentity(new[] + { + new Claim("http://schemas.microsoft.com/identity/claims/objectidentifier", "12345"), + })); + + // Act + var id = user.GetId(); + + // Assert + Assert.AreEqual("12345", id); + } + + [TestMethod] + public void GetId_UserHasNameIdentifier_ReturnsNameIdentifier() + { + // Arrange + var user = new ClaimsPrincipal(new ClaimsIdentity(new[] + { + new Claim(ClaimTypes.NameIdentifier, "67890"), + })); + + // Act + var id = user.GetId(); + + // Assert + Assert.AreEqual("67890", id); + } + + [TestMethod] + public void GetEmail_UserHasJwtEmailClaim_ReturnsJwtEmailClaim() + { + // Arrange + var user = new ClaimsPrincipal(new ClaimsIdentity(new[] + { + new Claim(JwtClaimTypes.Email, "test@example.com"), + })); + + // Act + var email = user.GetEmail(); + + // Assert + Assert.AreEqual("test@example.com", email); + } + + [TestMethod] + public void GetEmail_UserHasPreferredUserNameClaim_ReturnsPreferredUserNameClaim() + { + // Arrange + var user = new ClaimsPrincipal(new ClaimsIdentity(new[] + { + new Claim(JwtClaimTypes.PreferredUserName, "user123"), + })); + + // Act + var email = user.GetEmail(); + + // Assert + Assert.AreEqual("user123", email); + } + + [TestMethod] + public void GetLastName_UserHasJwtFamilyNameClaim_ReturnsJwtFamilyNameClaim() + { + // Arrange + var user = new ClaimsPrincipal(new ClaimsIdentity(new[] + { + new Claim(JwtClaimTypes.FamilyName, "Doe"), + })); + + // Act + var lastName = user.GetLastName(); + + // Assert + Assert.AreEqual("Doe", lastName); + } + + [TestMethod] + public void GetLastName_UserHasJwtNameClaim_ReturnsJwtNameClaim() + { + // Arrange + var user = new ClaimsPrincipal(new ClaimsIdentity(new[] + { + new Claim(JwtClaimTypes.Name, "John Doe"), + })); + + // Act + var lastName = user.GetLastName(); + + // Assert + Assert.AreEqual("John Doe", lastName); + } + + [TestMethod] + public void GetLastName_UserHasIdentityName_ReturnsIdentityName() + { + // Arrange + var user = new ClaimsPrincipal(new ClaimsIdentity(new[] + { + new Claim(ClaimTypes.Name, "User1"), + })); + + // Act + var lastName = user.GetLastName(); + + // Assert + Assert.AreEqual("User1", lastName); + } + + [TestMethod] + public void GetFirstName_UserHasJwtGivenNameClaim_ReturnsJwtGivenNameClaim() + { + // Arrange + var user = new ClaimsPrincipal(new ClaimsIdentity(new[] + { + new Claim(JwtClaimTypes.GivenName, "John"), + })); + + // Act + var firstName = user.GetFirstName(); + + // Assert + Assert.AreEqual("John", firstName); + } + + [TestMethod] + public void GetMedewerkerIdentificatie_ReturnsJsonObjectWithTruncatedValues() + { + // Arrange + var user = new ClaimsPrincipal(new ClaimsIdentity(new[] + { + new Claim(JwtClaimTypes.Email, "test@example.com"), + new Claim(JwtClaimTypes.FamilyName, "DoeLastName"), + new Claim(JwtClaimTypes.GivenName, "JohnFirstName"), + })); + + // Act + var medewerkerIdentificatie = user.GetMedewerkerIdentificatie(); + + // Assert + Assert.AreEqual("DoeLastName", medewerkerIdentificatie["achternaam"]?.GetValue()); + Assert.AreEqual("test@example.com", medewerkerIdentificatie["identificatie"]?.GetValue()); + Assert.AreEqual("JohnFirstName", medewerkerIdentificatie["voorletters"]?.GetValue()); + Assert.AreEqual("", medewerkerIdentificatie["voorvoegselAchternaam"]?.GetValue()); + } + } +} diff --git a/Kiss.Bff.Test/WriteContactmomentDetailsTests.cs b/Kiss.Bff.Test/WriteContactmomentDetailsTests.cs new file mode 100644 index 000000000..19f414db8 --- /dev/null +++ b/Kiss.Bff.Test/WriteContactmomentDetailsTests.cs @@ -0,0 +1,100 @@ +using Kiss.Bff.Beheer.Data; +using Kiss.Bff.ZaakGerichtWerken.Contactmomenten; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; + +namespace Kiss.Bff.Test +{ + [TestClass] + public class WriteContactmomentDetailsTests : TestHelper + { + [TestInitialize] + public void Initialize() + { + InitializeDatabase(); + } + + [TestCleanup] + public void Cleanup() + { + using var dbContext = new BeheerDbContext(_dbContextOptions); + dbContext.Database.EnsureDeleted(); + dbContext.Dispose(); + } + + [TestMethod] + public async Task Post_ValidModel_ReturnsOk() + { + using var dbContext = new BeheerDbContext(_dbContextOptions); + // Arrange + var controller = new WriteContactmomentenDetails(dbContext); + var validModel = new ContactmomentDetails + { + Id = "1", + Startdatum = DateTime.Now, + Einddatum = DateTime.Now.AddHours(1), + Gespreksresultaat = "Result 1", + Vraag = "Question 1", + EmailadresKcm = "test@example.com" // User.GetEmail() + }; + + // Act + var result = await controller.Post(validModel, CancellationToken.None); + + // Assert + Assert.IsNotNull(result); + //Assert.AreEqual(200, result.StatusCode); + + // Check if the model is added to the database + var addedModel = await dbContext.ContactMomentDetails.FirstOrDefaultAsync(); + Assert.IsNotNull(addedModel); + Assert.AreEqual(validModel.Id, addedModel.Id); + } + + + [TestMethod] + public async Task Post_ModelWithExistingId_UpdatesExistingEntity() + { + // Arrange + using var dbContext = new BeheerDbContext(_dbContextOptions); + var existingEntity = new ContactmomentDetails + { + Id = "1", + Startdatum = DateTime.Now, + Einddatum = DateTime.Now.AddHours(1), + Gespreksresultaat = "Result 1", + Vraag = "Question 1", + EmailadresKcm = "test@example.com" + }; + dbContext.ContactMomentDetails.Add(existingEntity); + dbContext.SaveChanges(); + + var controller = new WriteContactmomentenDetails(dbContext); + var model = new ContactmomentDetails + { + Id = "1", + Startdatum = DateTime.Now, + Einddatum = DateTime.Now.AddHours(1), + Gespreksresultaat = "Result 2", + Vraag = "Question 2", + EmailadresKcm = "test@example.com" + }; + + // Act + var result = await controller.Post(model, CancellationToken.None) as OkResult; + + // Assert + Assert.IsNotNull(result); + Assert.AreEqual(200, result.StatusCode); + + // Check if the entity was updated in the database + var updatedEntity = await dbContext.ContactMomentDetails.FindAsync(model.Id); + Assert.IsNotNull(updatedEntity); + Assert.AreEqual(model.Gespreksresultaat, updatedEntity.Gespreksresultaat); + } + } +} + + + diff --git a/Kiss.Bff.Test/ZaakGerichtWerkenUnitTests.cs b/Kiss.Bff.Test/ZaakGerichtWerkenUnitTests.cs index ccade21e3..e10d1e4bd 100644 --- a/Kiss.Bff.Test/ZaakGerichtWerkenUnitTests.cs +++ b/Kiss.Bff.Test/ZaakGerichtWerkenUnitTests.cs @@ -1,13 +1,11 @@ using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text; -using System.Text.Json.Nodes; using Kiss.Bff.Beheer.Data; using Kiss.Bff.ZaakGerichtWerken; using Kiss.Bff.ZaakGerichtWerken.Contactmomenten; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.Configuration; using Microsoft.IdentityModel.Tokens; using Moq; diff --git a/Kiss.Bff/ZaakGerichtWerken/Contactmomenten/WriteContactmomentenDetails.cs b/Kiss.Bff/ZaakGerichtWerken/Contactmomenten/WriteContactmomentenDetails.cs index 566412f6f..44696963e 100644 --- a/Kiss.Bff/ZaakGerichtWerken/Contactmomenten/WriteContactmomentenDetails.cs +++ b/Kiss.Bff/ZaakGerichtWerken/Contactmomenten/WriteContactmomentenDetails.cs @@ -18,16 +18,19 @@ public WriteContactmomentenDetails(BeheerDbContext db) public async Task Post(ContactmomentDetails model, CancellationToken cancellationToken) { model.EmailadresKcm = User.GetEmail(); - await _db.AddAsync(model, cancellationToken); - try + var existingModel = await _db.ContactMomentDetails.FindAsync(model.Id); + + if (existingModel == null) { - await _db.SaveChangesAsync(cancellationToken); + await _db.AddAsync(model, cancellationToken); } - catch (DbUpdateException) + else { - _db.Entry(model).State = EntityState.Modified; - await _db.SaveChangesAsync(cancellationToken); + _db.Entry(existingModel).CurrentValues.SetValues(model); } + + await _db.SaveChangesAsync(cancellationToken); + return Ok(); } }