Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ivanchuk/Child refactor #165

Merged
merged 5 commits into from
Jun 29, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Localization;
using Moq;
Expand All @@ -18,6 +20,10 @@ namespace OutOfSchool.WebApi.Tests.Controllers
[TestFixture]
public class ChildControllerTests
{
private const int OkStatusCode = 200;
private const int NoContentStatusCode = 204;
private const int CreateStatusCode = 201;
private const int BadRequestStatusCode = 400;
private ChildController controller;
private Mock<IChildService> service;
private Mock<IEntityRepository<Child>> repo;
Expand All @@ -32,6 +38,9 @@ public void Setup()
service = new Mock<IChildService>();
localizer = new Mock<IStringLocalizer<SharedResource>>();
controller = new ChildController(service.Object, localizer.Object);
var user = new ClaimsPrincipal(new ClaimsIdentity(
new Claim[] { new Claim("sub", "3341c870-5ef4-462b-8c86-b4e8bd4e6d41") }, "sub"));
controller.ControllerContext.HttpContext = new DefaultHttpContext { User = user };

children = FakeChildren();
child = FakeChild();
Expand All @@ -47,8 +56,8 @@ public async Task GetChildren_WhenCalled_ShouldReturnOkResultObject()
var result = await controller.Get().ConfigureAwait(false) as OkObjectResult;

// Assert
Assert.That(result, Is.Not.Null);
Assert.AreEqual(result.StatusCode, 200);
Assert.IsNotNull(result);
Assert.AreEqual(OkStatusCode, result.StatusCode);
}

[Test]
Expand All @@ -62,8 +71,8 @@ public async Task GetChildById_WhenIdIsValid_ShouldReturnOkResultObject(long id)
var result = await controller.GetById(id).ConfigureAwait(false) as OkObjectResult;

// Assert
Assert.That(result, Is.Not.Null);
Assert.AreEqual(result.StatusCode, 200);
Assert.IsNotNull(result);
Assert.AreEqual(OkStatusCode, result.StatusCode);
}

[Test]
Expand All @@ -87,11 +96,51 @@ public async Task GetChildById_WhenIdIsNotValid_ShouldReturnNull(long id)
var result = await controller.GetById(id).ConfigureAwait(false) as OkObjectResult;

// Assert
Assert.That(result, Is.Not.Null);
Assert.AreEqual(result.StatusCode, 200);
Assert.IsNotNull(result);
Assert.AreEqual(OkStatusCode, result.StatusCode);
Assert.AreEqual(result.Value, null);
}

[Test]
[TestCase(1, "3341c870-5ef4-462b-8c86-b4e8bd4e6d41")]
public async Task GetByParentId_WhenIdIsValid_ShouldReturnOkResultObject(long id, string userId)
{
// Arrange
service.Setup(x => x.GetAllByParent(id, userId)).ReturnsAsync(children.Where(p => p.ParentId == id && p.Parent.UserId == userId));

// Act
var result = await controller.GetByParentId(id).ConfigureAwait(false) as OkObjectResult;

// Assert
Assert.IsNotNull(result);
Assert.AreEqual(OkStatusCode, result.StatusCode);
}

[Test]
[TestCase(0)]
public void GetByParentId_WhenIdIsNotValid_ShouldThrowArgumentOutOfRangeException(long id)
{
// Assert
Assert.That(
async () => await controller.GetByParentId(id),
Throws.Exception.TypeOf<ArgumentOutOfRangeException>());
}

[Test]
[TestCase(10, "aab42f43-f5d6-48ed-95aa-0b4f7b77e541")]
public async Task GetByParentId_WhenIdIsNotValid_ShouldReturnNull(long id, string userId)
{
// Arrange
service.Setup(x => x.GetAllByParent(id, userId)).ReturnsAsync(children.Where(p => p.ParentId == id && p.Parent.UserId == userId));

// Act
var result = await controller.GetByParentId(id).ConfigureAwait(false) as NoContentResult;

// Assert
Assert.IsNotNull(result);
Assert.AreEqual(NoContentStatusCode, result.StatusCode);
}

[Test]
public async Task CreateChild_WhenModelIsValid_ShouldReturnCreatedAtActionResult()
{
Expand All @@ -102,8 +151,8 @@ public async Task CreateChild_WhenModelIsValid_ShouldReturnCreatedAtActionResult
var result = await controller.Create(child).ConfigureAwait(false) as CreatedAtActionResult;

// Assert
Assert.That(result, Is.Not.Null);
Assert.AreEqual(result.StatusCode, 201);
Assert.IsNotNull(result);
Assert.AreEqual(CreateStatusCode, result.StatusCode);
}

[Test]
Expand All @@ -117,7 +166,7 @@ public async Task CreateChild_WhenModelIsNotValid_ShouldReturnBadRequestObjectRe

// Assert
Assert.That(result, Is.TypeOf<BadRequestObjectResult>());
Assert.That((result as BadRequestObjectResult).StatusCode, Is.EqualTo(400));
Assert.That((result as BadRequestObjectResult).StatusCode, Is.EqualTo(BadRequestStatusCode));
}

[Test]
Expand All @@ -136,8 +185,8 @@ public async Task UpdateChild_WhenModelIsValid_ShouldReturnOkObjectResult()
var result = await controller.Update(changedChild).ConfigureAwait(false) as OkObjectResult;

// Assert
Assert.That(result, Is.Not.Null);
Assert.AreEqual(result.StatusCode, 200);
Assert.IsNotNull(result);
Assert.AreEqual(OkStatusCode, result.StatusCode);
}

[Test]
Expand All @@ -151,7 +200,7 @@ public async Task UpdateChild_WhenModelIsNotValid_ShouldReturnBadRequestObjectRe

// Assert
Assert.That(result, Is.TypeOf<BadRequestObjectResult>());
Assert.That((result as BadRequestObjectResult).StatusCode, Is.EqualTo(400));
Assert.That((result as BadRequestObjectResult).StatusCode, Is.EqualTo(BadRequestStatusCode));
}

[Test]
Expand All @@ -165,8 +214,8 @@ public async Task DeleteChild_WhenIdIsValid_ShouldReturnNoContentResult(long id)
var result = await controller.Delete(id) as NoContentResult;

// Assert
Assert.That(result, Is.Not.Null);
Assert.AreEqual(result.StatusCode, 204);
Assert.IsNotNull(result);
Assert.AreEqual(NoContentStatusCode, result.StatusCode);
}

[Test]
Expand Down Expand Up @@ -210,6 +259,9 @@ private ChildDto FakeChild()

private IEnumerable<ChildDto> FakeChildren()
{
var parent1 = new ParentDTO() { Id = 1, UserId = "3341c870-5ef4-462b-8c86-b4e8bd4e6d41" };
var parent2 = new ParentDTO() { Id = 2, UserId = "de804f35-bda8-4b8n-5eb7-70a5tyfg90a6" };

return new List<ChildDto>()
{
new ChildDto()
Expand All @@ -222,6 +274,7 @@ private IEnumerable<ChildDto> FakeChildren()
Gender = Gender.Male,
ParentId = 1,
SocialGroupId = 2,
Parent = parent1,
},
new ChildDto()
{
Expand All @@ -233,6 +286,7 @@ private IEnumerable<ChildDto> FakeChildren()
Gender = Gender.Female,
ParentId = 2,
SocialGroupId = 1,
Parent = parent2,
},
new ChildDto()
{
Expand All @@ -244,6 +298,7 @@ private IEnumerable<ChildDto> FakeChildren()
Gender = Gender.Male,
ParentId = 1,
SocialGroupId = 1,
Parent = parent1,
},
};
}
Expand Down
26 changes: 26 additions & 0 deletions OutOfSchool/OutOfSchool.WebApi/Controllers/ChildController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ public ChildController(IChildService service, IStringLocalizer<SharedResource> l
/// Get all children from the database.
/// </summary>
/// <returns>List of all children.</returns>
[Authorize(Roles = "admin")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
Expand Down Expand Up @@ -67,6 +68,31 @@ public async Task<IActionResult> GetById(long id)
return Ok(await service.GetById(id).ConfigureAwait(false));
}

/// <summary>
/// Get all children from the database by parent id.
/// </summary>
/// <param name="id">Id of Parent.</param>
/// <returns>List of all children.</returns>
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
[HttpGet("{id}")]
public async Task<IActionResult> GetByParentId(long id)
{
this.ValidateId(id, localizer);

string userId = User.FindFirst("sub")?.Value;

var children = await service.GetAllByParent(id, userId).ConfigureAwait(false);

if (!children.Any())
{
return NoContent();
}

return Ok(children);
}

/// <summary>
/// Method for creating a new child.
/// </summary>
Expand Down
2 changes: 2 additions & 0 deletions OutOfSchool/OutOfSchool.WebApi/Models/ChildDTO.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ public class ChildDto

public long? SocialGroupId { get; set; } = default;

public ParentDTO Parent { get; set; }

public BirthCertificateDto BirthCertificate { get; set; }
}
}
4 changes: 2 additions & 2 deletions OutOfSchool/OutOfSchool.WebApi/Services/ChildService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -100,11 +100,11 @@ public async Task<ChildDto> GetByIdWithDetails(long id)
}

/// <inheritdoc/>
public async Task<IEnumerable<ChildDto>> GetAllByParent(long id)
public async Task<IEnumerable<ChildDto>> GetAllByParent(long id, string userId)
{
logger.Information($"Getting Child's by Parent started. Looking ParentId = {id}.");

var children = await repository.GetByFilter(x => x.ParentId == id).ConfigureAwait(false);
var children = await repository.GetByFilter(x => x.ParentId == id && x.Parent.UserId == userId).ConfigureAwait(false);

logger.Information(!children.Any()
? $"There aren't Children for Parent with Id = {id}."
Expand Down
3 changes: 2 additions & 1 deletion OutOfSchool/OutOfSchool.WebApi/Services/IChildService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,9 @@ public interface IChildService
/// Get children with some ParentId.
/// </summary>
/// <param name="id">ParentId.</param>
/// <param name="userId">Key in the User table.</param>
/// <returns>List of children.</returns>
Task<IEnumerable<ChildDto>> GetAllByParent(long id);
Task<IEnumerable<ChildDto>> GetAllByParent(long id, string userId);

/// <summary>
/// Update entity.
Expand Down