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 5 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
2 changes: 1 addition & 1 deletion .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ jobs:
command: dotnet tool install dotnet-format --tool-path ./dotnet-format-local/
- run:
name: Run formatter check
command: ./dotnet-format-local/dotnet-format --dry-run --check
command: ./dotnet-format-local/dotnet-format --check
build-and-test:
executor: docker-python
steps:
Expand Down
1 change: 0 additions & 1 deletion BaseApi.Tests/MockWebApplicationFactory.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System.Data.Common;
using BaseApi;
using BaseApi.V1.Infrastructure;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
Expand Down
27 changes: 27 additions & 0 deletions BaseApi.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:52488/",
"sslPort": 44338
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"BaseApi.Tests": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "https://localhost:5001;http://localhost:5000"
}
}
}
52 changes: 52 additions & 0 deletions BaseApi.Tests/V1/Controllers/BaseControllerTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
using System.Collections.Generic;
using BaseApi.V1.Controllers;
using BaseApi.V1.Infrastructure;
using FluentAssertions;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Routing;
using NUnit.Framework;

namespace BaseApi.Tests.V1.Controllers
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The folder names need to be changed (both BaseAPI and BaseAPI.Tests)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Happy to do so, but if possible we should merge the initial renaming PR. And then I can merge master from there to this branch which should resolve it.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I forgot the renaming PR hasn't been merged, ignore this comment please

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No worries at all :) With 2 approvals, I took the liberty of merging the renaming PR to master and then into this branch. Renaming issues should be resolved by now.

{
[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");
}
}
}
1 change: 1 addition & 0 deletions BaseApi.Tests/V1/Gateways/ExampleGatewayTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ namespace BaseApi.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("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 BaseApi.Tests/V1/Infrastructure/CorrelationMiddlewareTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
using System.Threading.Tasks;
using BaseApi.V1.Infrastructure;
using FluentAssertions;
using Microsoft.AspNetCore.Http;
using NUnit.Framework;

namespace BaseApi.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 BaseApi.Tests/V1/Infrastructure/ExampleContextTests.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
using System.Linq;
using BaseApi.Tests.V1.Helper;
using BaseApi.V1.Infrastructure;
using NUnit.Framework;

namespace BaseApi.Tests.V1.Infrastructure
{
[TestFixture]
[Ignore("Not needed until we decide on DB")]
public class DatabaseContextTest : DatabaseTests
{
[Test]
Expand Down
1 change: 0 additions & 1 deletion BaseApi/Program.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
using System;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;

Expand Down
2 changes: 2 additions & 0 deletions BaseApi/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 BaseApi/V1/Controllers/BaseController.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
using System.Collections.Generic;
using BaseApi.V1.Infrastructure;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
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
12 changes: 12 additions & 0 deletions BaseApi/V1/Infrastructure/Constants.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BaseApi.V1.Infrastructure
{
public static class Constants
{
public const string CorrelationId = "x-correlation-id";
}
}
37 changes: 37 additions & 0 deletions BaseApi/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 BaseApi.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>();
}
}
}
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"
}
}
}