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

test: add CreateException unit tests #578

Merged
merged 4 commits into from
Jan 16, 2025
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
Expand Up @@ -14,7 +14,6 @@ public class CreateException
{
private readonly ILogger<CreateException> _logger;
private readonly IValidationExceptionData _validationData;

private readonly ICreateResponse _createResponse;
public CreateException(ILogger<CreateException> logger, IValidationExceptionData validationExceptionData, ICreateResponse createResponse)
{
Expand All @@ -26,32 +25,29 @@ public CreateException(ILogger<CreateException> logger, IValidationExceptionData
[Function("CreateException")]
public async Task<HttpResponseData> RunAsync([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequestData req)
{
ValidationException exception;

try
{
ValidationException exception;
var requestBody = "";

using (var reader = new StreamReader(req.Body, Encoding.UTF8))
{
requestBody = await reader.ReadToEndAsync();
var requestBody = await reader.ReadToEndAsync();
exception = JsonSerializer.Deserialize<ValidationException>(requestBody);
}
if (!string.IsNullOrEmpty(requestBody))
{
if (_validationData.Create(exception))
{
return _createResponse.CreateHttpResponse(HttpStatusCode.OK, req);
}
}
return req.CreateResponse(HttpStatusCode.BadRequest);

}
catch (Exception ex)
{
_logger.LogError(ex, "there has been an error while creating an exception record: {Message}", ex.Message);
return req.CreateResponse(HttpStatusCode.InternalServerError);
_logger.LogError(ex, ex.Message);
return _createResponse.CreateHttpResponse(HttpStatusCode.BadRequest, req);
}

if (_validationData.Create(exception))
{
_logger.LogInformation("The exception record has been created successfully");
return _createResponse.CreateHttpResponse(HttpStatusCode.Created, req);
}

_logger.LogError("The exception record was not inserted into the database: {Exception}", exception);
return _createResponse.CreateHttpResponse(HttpStatusCode.InternalServerError, req);
}
}

6 changes: 6 additions & 0 deletions application/CohortManager/src/Functions/Functions.sln
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ValidateDatesTests", "..\..
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DataServiceTests", "..\..\..\..\tests\UnitTests\DataServiceTests\DataServiceTests.csproj", "{E26B2D73-BD60-4AD8-B403-939ACEDE9429}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CreateExceptionTests", "..\..\..\..\tests\UnitTests\ExceptionHandlingTests\CreateExceptionTests\CreateExceptionTests.csproj", "{190F304E-D716-4A65-985D-042BF7B22460}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -440,6 +442,10 @@ Global
{E26B2D73-BD60-4AD8-B403-939ACEDE9429}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E26B2D73-BD60-4AD8-B403-939ACEDE9429}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E26B2D73-BD60-4AD8-B403-939ACEDE9429}.Release|Any CPU.Build.0 = Release|Any CPU
{190F304E-D716-4A65-985D-042BF7B22460}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{190F304E-D716-4A65-985D-042BF7B22460}.Debug|Any CPU.Build.0 = Debug|Any CPU
{190F304E-D716-4A65-985D-042BF7B22460}.Release|Any CPU.ActiveCfg = Release|Any CPU
{190F304E-D716-4A65-985D-042BF7B22460}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
namespace NHS.CohortManager.Tests.UnitTests.CreateExceptionTests;

using System.Net;
using Microsoft.Extensions.Logging;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Moq;
using Model;
using Common;
using Data.Database;
using NHS.CohortManager.ExceptionService;
using System.Text.Json;
using System.Text;

[TestClass]
public class CreateExceptionTests
{
private readonly Mock<ILogger<CreateException>> _logger = new();
private readonly Mock<FunctionContext> _context = new();
private readonly Mock<HttpRequestData> _request;
private readonly ValidationException _requestBody;
private readonly CreateException _function;
private readonly Mock<ICreateResponse> _createResponse = new();
private readonly Mock<IValidationExceptionData> _validationExceptionData = new();

public CreateExceptionTests()
{
_request = new Mock<HttpRequestData>(_context.Object);

_requestBody = new ValidationException() { ExceptionId = 1 };

_function = new CreateException(_logger.Object, _validationExceptionData.Object, _createResponse.Object);

_request.Setup(r => r.CreateResponse()).Returns(() =>
{
var response = new Mock<HttpResponseData>(_context.Object);
response.SetupProperty(r => r.Headers, new HttpHeadersCollection());
response.SetupProperty(r => r.StatusCode);
response.SetupProperty(r => r.Body, new MemoryStream());
return response.Object;
});

_createResponse.Setup(x => x.CreateHttpResponse(It.IsAny<HttpStatusCode>(), It.IsAny<HttpRequestData>(), It.IsAny<string>()))
.Returns((HttpStatusCode statusCode, HttpRequestData req, string ResponseBody) =>
{
var response = req.CreateResponse(statusCode);
response.Headers.Add("Content-Type", "application/json; charset=utf-8");
response.WriteString(ResponseBody);
return response;
});

var json = JsonSerializer.Serialize(_requestBody);
SetUpRequestBody(json);
}

[TestMethod]
public async Task Run_EmptyRequest_ReturnBadRequest()
{
// Arrange
SetUpRequestBody(string.Empty);

// Act
var result = await _function.RunAsync(_request.Object);

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

[TestMethod]
public async Task Run_ExceptionRecordCreated_ReturnsCreated()
{
// Arrange
_validationExceptionData.Setup(s => s.Create(It.IsAny<ValidationException>())).Returns(true);

// Act
var result = await _function.RunAsync(_request.Object);

// Assert
Assert.IsNotNull(result);
_validationExceptionData.Verify(v => v.Create(It.IsAny<ValidationException>()), Times.Once);
Assert.AreEqual(HttpStatusCode.Created, result.StatusCode);
}

[TestMethod]
public async Task Run_ExceptionRecordFailedToCreate_ReturnsInternalServerError()
{
// Arrange
_validationExceptionData.Setup(s => s.Create(It.IsAny<ValidationException>())).Returns(false);

// Act
var result = await _function.RunAsync(_request.Object);

// Assert
Assert.IsNotNull(result);
_validationExceptionData.Verify(v => v.Create(It.IsAny<ValidationException>()), Times.Once);
Assert.AreEqual(HttpStatusCode.InternalServerError, result.StatusCode);
}

private void SetUpRequestBody(string json)
{
var byteArray = Encoding.ASCII.GetBytes(json);
var bodyStream = new MemoryStream(byteArray);

_request.Setup(r => r.Body).Returns(bodyStream);
}
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="Moq" Version="4.20.70" />
<PackageReference Include="MSTest.TestAdapter" Version="3.1.1" />
<PackageReference Include="MSTest.TestFramework" Version="3.1.1" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="../../../../application/CohortManager/src/Functions/ExceptionHandling/CreateException/CreateException.csproj" />
<ProjectReference Include="../../../../application/CohortManager/src/Functions/Shared/Data/Data.csproj" />
<ProjectReference Include="../../../../application/CohortManager/src/Functions/Shared/Model/Model.csproj" />
</ItemGroup>

<ItemGroup>
<Using Include="Microsoft.VisualStudio.TestTools.UnitTesting" />
</ItemGroup>

</Project>
Loading