Skip to content

Commit

Permalink
Merge pull request #1426 from DFE-Digital/dependabot/nuget/xunit-2.8.1
Browse files Browse the repository at this point in the history
Bump xunit from 2.7.1 to 2.8.1
  • Loading branch information
martyn-w authored Jun 19, 2024
2 parents 3deb070 + 53f6e82 commit 5399ce8
Show file tree
Hide file tree
Showing 17 changed files with 293 additions and 281 deletions.
59 changes: 30 additions & 29 deletions GetIntoTeachingApiTests/Auth/ApiClientHandlerTests.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System.Security.Claims;
using System.Security.Claims;
using System.Text.Encodings.Web;
using FluentAssertions;
using GetIntoTeachingApi.Auth;
Expand All @@ -9,6 +9,7 @@
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Moq;
using System.Threading.Tasks;
using Xunit;

namespace GetIntoTeachingApiTests.Auth
Expand Down Expand Up @@ -44,7 +45,7 @@ public ApiClientHandlerTests()
[InlineData("", false)]
[InlineData(" ", false)]
[InlineData(null, false)]
public async void InitializeAsync_WithApiClient_AuthenticatesCorrectly(string authHeaderValue, bool expected)
public async Task InitializeAsync_WithApiClient_AuthenticatesCorrectly(string authHeaderValue, bool expected)
{
var client = new Client() { Name = "Admin", Description = "Admin account", Role = "Service", ApiKey = "api_key", ApiKeyPrefix = "ADMIN" };
_mockClientManager.Setup(m => m.GetClient(client.ApiKey)).Returns(client);
Expand All @@ -65,37 +66,37 @@ public async void InitializeAsync_WithApiClient_AuthenticatesCorrectly(string au
}
}

[Theory]
[InlineData("Bearer ", "")]
[InlineData("Bearer ", null)]
[InlineData("Bearer ", " ")]
[InlineData("Bearer ", " ")]
[InlineData("Bearer", "")]
[InlineData("Bearer", null)]
[InlineData("Bearer", " ")]
[InlineData("", "")]
[InlineData("", null)]
[InlineData(" ", " ")]
[InlineData(" ", "")]
[InlineData(" ", null)]
public async void InitializeAsync_EmptyOrNullHeaderAndApiKey_ReturnsUnauthorized(string authHeaderValue, string apiKey)
{
[Theory]
[InlineData("Bearer ", "")]
[InlineData("Bearer ", null)]
[InlineData("Bearer ", " ")]
[InlineData("Bearer ", " ")]
[InlineData("Bearer", "")]
[InlineData("Bearer", null)]
[InlineData("Bearer", " ")]
[InlineData("", "")]
[InlineData("", null)]
[InlineData(" ", " ")]
[InlineData(" ", "")]
[InlineData(" ", null)]
public async Task InitializeAsync_EmptyOrNullHeaderAndApiKey_ReturnsUnauthorized(string authHeaderValue, string apiKey)
{
var client = new Client() { Name = "Admin", Description = "Admin account", Role = "Admin", ApiKey = apiKey, ApiKeyPrefix = "ADMIN" };
_mockClientManager.Setup(m => m.GetClient(client.ApiKey)).Returns(client);

var context = new DefaultHttpContext();
context.Request.Headers.Add("Authorization", authHeaderValue);
var scheme = new AuthenticationScheme("ApiClientHandler", null, typeof(ApiClientHandler));
await _handler.InitializeAsync(scheme, context);

var result = await _handler.AuthenticateAsync();

result.Succeeded.Should().BeFalse();
result.Failure.Message.Should().Be("API key is not valid");
_mockClientManager.Setup(m => m.GetClient(client.ApiKey)).Returns(client);

var context = new DefaultHttpContext();
context.Request.Headers.Add("Authorization", authHeaderValue);
var scheme = new AuthenticationScheme("ApiClientHandler", null, typeof(ApiClientHandler));
await _handler.InitializeAsync(scheme, context);

var result = await _handler.AuthenticateAsync();

result.Succeeded.Should().BeFalse();
result.Failure.Message.Should().Be("API key is not valid");
}

[Fact]
public async void InitializeAsync_NoAuthorizationHeader_ReturnsUnauthorized()
public async Task InitializeAsync_NoAuthorizationHeader_ReturnsUnauthorized()
{
var context = new DefaultHttpContext();
var scheme = new AuthenticationScheme("ApiClientHandler", null, typeof(ApiClientHandler));
Expand Down
3 changes: 2 additions & 1 deletion GetIntoTeachingApiTests/Contracts/ApplyCandidateApiTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using GetIntoTeachingApiTests.Helpers;
using Hangfire;
using Newtonsoft.Json;
using System.Threading.Tasks;
using Xunit;

namespace GetIntoTeachingApiTests.Contracts
Expand All @@ -17,7 +18,7 @@ public ApplyCandidateApiTests(DatabaseFixture databaseFixture) : base(databaseFi

[Theory]
[ContractTestInputs("./Contracts/Input/ApplyCandidateApi")]
public async void Contract(string scenario)
public async Task Contract(string scenario)
{
await Setup();

Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
using System;
using System;
using System.Net;
using System.Net.Http;
using System.Text;
using FluentAssertions;
using FluentAssertions.Json;
using FluentAssertions.Json;
using GetIntoTeachingApiTests.Helpers;
using System.Threading.Tasks;
using Xunit;

namespace GetIntoTeachingApiTests.Contracts
Expand All @@ -19,7 +20,7 @@ public TeacherTrainingAdviserTests(DatabaseFixture databaseFixture)

[Theory]
[ContractTestInputs("./Contracts/Input/TeacherTrainingAdviser")]
public async void Contract(string scenario)
public async Task Contract(string scenario)
{
await Setup();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ public void Search_SearchRequestIsDecoratedWithCommaSeparatedAttributeForArrayPr
}

[Fact]
public async void Search_InvalidRequest_RespondsWithValidationErrors()
public async Task Search_InvalidRequest_RespondsWithValidationErrors()
{
var request = new TeachingEventSearchRequest() { Postcode = null };
_controller.ModelState.AddModelError("Postcode", "Postcode must be specified.");
Expand All @@ -126,7 +126,7 @@ public async void Search_InvalidRequest_RespondsWithValidationErrors()
}

[Fact]
public async void Search_ValidRequest_ReturnsTeachingEvents()
public async Task Search_ValidRequest_ReturnsTeachingEvents()
{
var request = new TeachingEventSearchRequest() { Postcode = "KY12 8FG" };
var metricCountBefore = _metrics.TeachingEventSearchResults.WithLabels(new[] { string.Empty, request.Radius.ToString() }).Count;
Expand All @@ -146,7 +146,7 @@ public async void Search_ValidRequest_ReturnsTeachingEvents()
}

[Fact]
public async void Get_ReturnsTeachingEvent()
public async Task Get_ReturnsTeachingEvent()
{
var teachingEvent = new TeachingEvent() { ReadableId = "123" };
_mockStore.Setup(mock => mock.GetTeachingEventAsync(teachingEvent.ReadableId)).ReturnsAsync(teachingEvent);
Expand All @@ -158,7 +158,7 @@ public async void Get_ReturnsTeachingEvent()
}

[Fact]
public async void Get_WithMissingEvent_ReturnsNotFound()
public async Task Get_WithMissingEvent_ReturnsNotFound()
{
_mockStore.Setup(mock => mock.GetTeachingEventAsync(It.IsAny<Guid>())).ReturnsAsync(null as TeachingEvent);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
using GetIntoTeachingApi.Attributes;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace GetIntoTeachingApiTests.Controllers
{
Expand Down Expand Up @@ -38,7 +39,7 @@ public void PrivateShortTermResponseCache_IsPresent()
}

[Fact]
public async void GetCountries_ReturnsAllCountriesSortedByCountryName()
public async Task GetCountries_ReturnsAllCountriesSortedByCountryName()
{
var mockCountries = MockCountries();
_mockStore.Setup(mock => mock.GetCountries()).Returns(mockCountries.AsAsyncQueryable());
Expand All @@ -51,7 +52,7 @@ public async void GetCountries_ReturnsAllCountriesSortedByCountryName()
}

[Fact]
public async void GetTeachingSubjects_ReturnsAllSubjectsSortedBySubjectName()
public async Task GetTeachingSubjects_ReturnsAllSubjectsSortedBySubjectName()
{
var mockSubjects = MockTeachingSubjects();
_mockStore.Setup(mock => mock.GetTeachingSubjects()).Returns(mockSubjects.AsAsyncQueryable());
Expand Down
93 changes: 47 additions & 46 deletions GetIntoTeachingApiTests/Controllers/OperationsControllerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,14 @@
using GetIntoTeachingApi.Utils;
using Moq;
using Xunit;
using System;
using Microsoft.AspNetCore.Authorization;
using Hangfire;
using Hangfire.Common;
using GetIntoTeachingApi.Jobs;
using Hangfire.States;

using System;
using Microsoft.AspNetCore.Authorization;
using Hangfire;
using Hangfire.Common;
using GetIntoTeachingApi.Jobs;
using Hangfire.States;
using System.Threading.Tasks;

namespace GetIntoTeachingApiTests.Controllers
{
public class OperationsControllerTests
Expand Down Expand Up @@ -62,8 +63,8 @@ public void GenerateMappingInfo_RespondsWithMappingInfo()
mappings.Any(m => m.LogicalName == "contact" &&
m.Class == "GetIntoTeachingApi.Models.Crm.Candidate"
).Should().BeTrue();
}

}

[Fact]
public void PauseCrmIntegration_Authorize_IsPresent()
{
Expand All @@ -73,13 +74,13 @@ public void PauseCrmIntegration_Authorize_IsPresent()

[Fact]
public void PauseCrmIntegration_PausesFor6HoursAndRespondsWithNoContent()
{
var sixHoursFromNow = DateTime.UtcNow.AddHours(6);
{
var sixHoursFromNow = DateTime.UtcNow.AddHours(6);

var response = _controller.PauseCrmIntegration();

response.Should().BeOfType<NoContentResult>();

response.Should().BeOfType<NoContentResult>();

_mockAppSettings.VerifySet(m => m.CrmIntegrationPausedUntil =
It.Is<DateTime>(d => VerifyDateIsCloseTo(d, sixHoursFromNow)), Times.Once());
}
Expand All @@ -96,11 +97,11 @@ public void ResumeCrmIntegration_ResumesAndRespondsWithNoContent()
{
var response = _controller.ResumeCrmIntegration();

response.Should().BeOfType<NoContentResult>();

response.Should().BeOfType<NoContentResult>();

_mockAppSettings.VerifySet(m => m.CrmIntegrationPausedUntil = null, Times.Once());
}

}

[Fact]
public void BackfillApplyCandidates_Authorize_IsPresent()
{
Expand All @@ -109,47 +110,47 @@ public void BackfillApplyCandidates_Authorize_IsPresent()
}

[Fact]
public void BackfillApplyCandidates_WhenNotAlreadyRunning_EnqueuesJob()
{
var updatedSince = DateTime.MinValue;
_mockAppSettings.Setup(m => m.IsApplyBackfillInProgress).Returns(false);

public void BackfillApplyCandidates_WhenNotAlreadyRunning_EnqueuesJob()
{
var updatedSince = DateTime.MinValue;
_mockAppSettings.Setup(m => m.IsApplyBackfillInProgress).Returns(false);

var response = _controller.BackfillApplyCandidates(updatedSince);

response.Should().BeOfType<NoContentResult>();

_mockJobClient.Verify(x => x.Create(
It.Is<Job>(job => job.Type == typeof(ApplyBackfillJob) && job.Method.Name == "RunAsync" && (DateTime)job.Args[0] == updatedSince),
It.IsAny<EnqueuedState>()), Times.Once);
response.Should().BeOfType<NoContentResult>();

_mockJobClient.Verify(x => x.Create(
It.Is<Job>(job => job.Type == typeof(ApplyBackfillJob) && job.Method.Name == "RunAsync" && (DateTime)job.Args[0] == updatedSince),
It.IsAny<EnqueuedState>()), Times.Once);
}

[Fact]
public void BackfillApplyCandidates_WhenAlreadyRunning_ReturnsBadRequest()
{
var updatedSince = DateTime.MinValue;
_mockAppSettings.Setup(m => m.IsApplyBackfillInProgress).Returns(true);

public void BackfillApplyCandidates_WhenAlreadyRunning_ReturnsBadRequest()
{
var updatedSince = DateTime.MinValue;
_mockAppSettings.Setup(m => m.IsApplyBackfillInProgress).Returns(true);

var response = _controller.BackfillApplyCandidates(updatedSince);

response.Should().BeOfType<BadRequestObjectResult>();

_mockJobClient.Verify(x => x.Create(
It.Is<Job>(job => job.Type == typeof(ApplyBackfillJob) && job.Method.Name == "RunAsync" && (DateTime)job.Args[0] == updatedSince),
It.IsAny<EnqueuedState>()),Times.Never);
response.Should().BeOfType<BadRequestObjectResult>();

_mockJobClient.Verify(x => x.Create(
It.Is<Job>(job => job.Type == typeof(ApplyBackfillJob) && job.Method.Name == "RunAsync" && (DateTime)job.Args[0] == updatedSince),
It.IsAny<EnqueuedState>()),Times.Never);
}

[Theory]
[InlineData(true, true, true, true, true, "healthy")]
[InlineData(true, true, true, false, true, "degraded")]
[InlineData(true, true, true, false, false, "degraded")]
[InlineData(true, true, true, true, false, "degraded")]
[InlineData(true, true, true, true, false, "degraded")]
[InlineData(true, true, false, true, true, "degraded")]
[InlineData(false, true, true, true, true, "unhealthy")]
[InlineData(true, false, true, true, true, "unhealthy")]
[InlineData(false, false, false, true, true, "unhealthy")]
[InlineData(true, false, false, false, true, "unhealthy")]
[InlineData(false, false, false, false, false, "unhealthy")]
public async void HealthCheck_ReturnsCorrectly(bool database, bool hangfire, bool redis, bool crm, bool notify, string expectedStatus)
public async Task HealthCheck_ReturnsCorrectly(bool database, bool hangfire, bool redis, bool crm, bool notify, string expectedStatus)
{
const string sha = "3c42c1051f6eb535c2017eafb660d1a884a39722";
const string environmentName = "Test";
Expand Down Expand Up @@ -181,13 +182,13 @@ public async void HealthCheck_ReturnsCorrectly(bool database, bool hangfire, boo
health.Redis.Should().Be(redisStatus);
health.Hangfire.Should().Be(hangfireStatus);
health.Status.Should().Be(expectedStatus);
}

private static bool VerifyDateIsCloseTo(DateTime date, DateTime closeToDate)
{
date.Should().BeCloseTo(closeToDate, TimeSpan.FromSeconds(30));

return true;
}

private static bool VerifyDateIsCloseTo(DateTime date, DateTime closeToDate)
{
date.Should().BeCloseTo(closeToDate, TimeSpan.FromSeconds(30));

return true;
}
}
}
Loading

0 comments on commit 5399ce8

Please sign in to comment.