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

MTTL-376 Setup boiler plate code for logging the correlation ID #2

Merged
merged 7 commits into from
Mar 18, 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
27 changes: 27 additions & 0 deletions SearchApi.Tests/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:51761/",
"sslPort": 44398
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"LBH_search_api.Tests": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "https://localhost:5001;http://localhost:5000"
}
}
}
52 changes: 52 additions & 0 deletions SearchApi.Tests/V1/Controllers/BaseControllerTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
using System.Collections.Generic;
using FluentAssertions;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Routing;
using NUnit.Framework;
using SearchApi.V1.Controllers;
using SearchApi.V1.Infrastructure;

namespace SearchApi.Tests.V1.Controllers
{
[TestFixture]
public class BaseControllerTests
{
private BaseController _sut;
private ControllerContext _controllerContext;
private HttpContext _stubHttpContext;

[SetUp]
public void Init()
{
_stubHttpContext = new DefaultHttpContext();
_controllerContext = new ControllerContext(new ActionContext(_stubHttpContext, new RouteData(), new ControllerActionDescriptor()));
_sut = new BaseController();

_sut.ControllerContext = _controllerContext;
}

[Test]
public void GetCorrelationShouldThrowExceptionIfCorrelationHeaderUnavailable()
{
// Arrange + Act + Assert
_sut.Invoking(x => x.GetCorrelationId())
.Should().Throw<KeyNotFoundException>()
.WithMessage("Request is missing a correlationId");
}

[Test]
public void GetCorrelationShouldReturnCorrelationIdWhenExists()
{
// Arrange
_stubHttpContext.Request.Headers.Add(Constants.CorrelationId, "123");

// Act
var result = _sut.GetCorrelationId();

// Assert
result.Should().BeEquivalentTo("123");
}
}
}
2 changes: 1 addition & 1 deletion SearchApi.Tests/V1/Gateways/ExampleGatewayTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ namespace SearchApi.Tests.V1.Gateways
//TODO: Rename Tests to match gateway name
//For instruction on how to run tests please see the wiki: https://github.com/LBHackney-IT/lbh-base-api/wiki/Running-the-test-suite.
[TestFixture]
[Ignore("Deciding on what DB to use")]
[Ignore("Not needed until we decide on DB")]
public class ExampleGatewayTests : DatabaseTests
{
private readonly Fixture _fixture = new Fixture();
Expand Down
49 changes: 49 additions & 0 deletions SearchApi.Tests/V1/Infrastructure/CorrelationMiddlewareTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.AspNetCore.Http;
using NUnit.Framework;
using SearchApi.V1.Infrastructure;

namespace SearchApi.Tests.V1.Infrastructure
{
[TestFixture]
public class CorrelationMiddlewareTest
{
private CorrelationMiddleware _sut;

[SetUp]
public void Init()
{
_sut = new CorrelationMiddleware(null);
}

[Test]
public async Task DoesNotReplaceCorrelationIdIfOneExists()
{
// Arrange
var httpContext = new DefaultHttpContext();
var headerValue = "123";

httpContext.HttpContext.Request.Headers.Add(Constants.CorrelationId, headerValue);

// Act
await _sut.InvokeAsync(httpContext).ConfigureAwait(false);

// Assert
httpContext.HttpContext.Request.Headers[Constants.CorrelationId].Should().BeEquivalentTo(headerValue);
}

[Test]
public async Task AddsCorrelationIdIfOneDoesNotExist()
{
// Arrange
var httpContext = new DefaultHttpContext();

// Act
await _sut.InvokeAsync(httpContext).ConfigureAwait(false);

// Assert
httpContext.HttpContext.Request.Headers[Constants.CorrelationId].Should().HaveCountGreaterThan(0);
}
}
}
2 changes: 1 addition & 1 deletion SearchApi.Tests/V1/Infrastructure/ExampleContextTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
namespace SearchApi.Tests.V1.Infrastructure
{
[TestFixture]
[Ignore("Deciding on what DB to use")]
[Ignore("Not needed until we decide on DB")]
public class DatabaseContextTest : DatabaseTests
{
[Test]
Expand Down
2 changes: 2 additions & 0 deletions SearchApi/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,8 @@ private static void RegisterUseCases(IServiceCollection services)
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public static void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseCorrelation();

if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
Expand Down
10 changes: 10 additions & 0 deletions SearchApi/V1/Controllers/BaseController.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using SearchApi.V1.Infrastructure;

namespace SearchApi.V1.Controllers
{
Expand All @@ -11,6 +13,14 @@ public BaseController()
ConfigureJsonSerializer();
}

public string GetCorrelationId()
{
if (HttpContext.Request.Headers[Constants.CorrelationId].Count == 0)
throw new KeyNotFoundException("Request is missing a correlationId");

return HttpContext.Request.Headers[Constants.CorrelationId];
}

public static void ConfigureJsonSerializer()
{
JsonConvert.DefaultSettings = () =>
Expand Down
7 changes: 7 additions & 0 deletions SearchApi/V1/Infrastructure/Constants.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace SearchApi.V1.Infrastructure
{
public static class Constants
{
public const string CorrelationId = "x-correlation-id";
}
}
37 changes: 37 additions & 0 deletions SearchApi/V1/Infrastructure/CorrelationMiddleware.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;

namespace SearchApi.V1.Infrastructure
{
public class CorrelationMiddleware
{
private readonly RequestDelegate _next;

public CorrelationMiddleware(RequestDelegate next)
{
_next = next;
}

public async Task InvokeAsync(HttpContext context)
{
if (context.Request.Headers[Constants.CorrelationId].Count == 0)
{
context.Request.Headers[Constants.CorrelationId] = Guid.NewGuid().ToString();
}

if (_next != null)
await _next(context).ConfigureAwait(false);
}
}

public static class CorrelationMiddlewareExtensions
{
public static IApplicationBuilder UseCorrelation(
this IApplicationBuilder builder)
{
return builder.UseMiddleware<CorrelationMiddleware>();
}
}
}