Skip to content

Commit

Permalink
Add CancellationToken into all Controller methods calling Contentful
Browse files Browse the repository at this point in the history
  • Loading branch information
killij committed Oct 3, 2023
1 parent 7b5e56c commit c0512f7
Show file tree
Hide file tree
Showing 9 changed files with 61 additions and 51 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

namespace Childrens_Social_Care_CPD_Tests.Controllers;
Expand Down Expand Up @@ -36,7 +37,7 @@ public async Task Content_Will_Contain_Warning_If_Data_Is_Self_Referential()
var content = new Content();
content.Items = new List<IContent> { content };
var contentCollection = new ContentfulCollection<Content>() { Items = new List<Content>() { content } };
_application.CpdContentfulClient.GetEntries(Arg.Any<QueryBuilder<Content>>(), default).Returns(contentCollection);
_application.CpdContentfulClient.GetEntries(Arg.Any<QueryBuilder<Content>>(), Arg.Any<CancellationToken>()).Returns(contentCollection);

// act
var response = await _httpClient.GetAsync(ContentUrl);
Expand All @@ -54,7 +55,7 @@ public async Task Content_Will_Contain_Warning_If_Data_Has_An_Unknown_Content_Ty
var content = new Content();
content.Items = new List<IContent> { new TestingContentItem() };
var contentCollection = new ContentfulCollection<Content>() { Items = new List<Content>() { content } };
_application.CpdContentfulClient.GetEntries(Arg.Any<QueryBuilder<Content>>(), default).Returns(contentCollection);
_application.CpdContentfulClient.GetEntries(Arg.Any<QueryBuilder<Content>>(), Arg.Any<CancellationToken>()).Returns(contentCollection);

// act
var response = await _httpClient.GetAsync(ContentUrl);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
using NSubstitute;
using NUnit.Framework;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace Childrens_Social_Care_CPD_Tests.Controllers;
Expand All @@ -22,6 +23,7 @@ public class ContentControllerTests
private HttpContext _httpContext;
private HttpRequest _httpRequest;
private ICpdContentfulClient _contentfulClient;
private CancellationTokenSource _cancellationTokenSource;

private void SetContent(Content content)
{
Expand All @@ -32,8 +34,10 @@ private void SetContent(Content content)
: contentCollection.Items = new List<Content> { content };

_contentfulClient
.GetEntries(Arg.Any<QueryBuilder<Content>>(), default)
.GetEntries(Arg.Any<QueryBuilder<Content>>(), Arg.Any<CancellationToken>())
.Returns(contentCollection);

_cancellationTokenSource = new CancellationTokenSource();
}

[SetUp]
Expand Down Expand Up @@ -62,7 +66,7 @@ public async Task Index_Returns_404_When_No_Content_Found()
SetContent(null);

// act
var actual = await _contentController.Index("home");
var actual = await _contentController.Index(_cancellationTokenSource.Token, "home");

// assert
actual.Should().BeOfType<NotFoundResult>();
Expand All @@ -75,7 +79,7 @@ public async Task Index_Returns_View()
SetContent(new Content());

// act
var actual = await _contentController.Index("home");
var actual = await _contentController.Index(_cancellationTokenSource.Token, "home");

// assert
actual.Should().BeOfType<ViewResult>();
Expand All @@ -94,7 +98,7 @@ public async Task Index_Sets_The_ViewState_ContextModel()
SetContent(rootContent);

// act
await _contentController.Index("home");
await _contentController.Index(_cancellationTokenSource.Token, "home");
var actual = _contentController.ViewData["ContextModel"] as ContextModel;

// assert
Expand All @@ -112,7 +116,7 @@ public async Task Index_Sets_The_ContextModel_Preferences_Set_Value_Correctly(bo
SetContent(new Content());

// act
await _contentController.Index("home", preferenceSet);
await _contentController.Index(_cancellationTokenSource.Token, "home", preferenceSet);
var actual = _contentController.ViewData["ContextModel"] as ContextModel;

// assert
Expand All @@ -138,7 +142,7 @@ public async Task Index_Sets_The_ContextModel_UseContainers_From_SideMenu_Value_
SetContent(rootContent);

// act
await _contentController.Index("home");
await _contentController.Index(_cancellationTokenSource.Token, "home");
var actual = _contentController.ViewData["ContextModel"] as ContextModel;

// assert
Expand All @@ -152,10 +156,10 @@ public async Task Index_Trims_Trailing_Slashes()
// arrange
SetContent(new Content());
var query = "";
await _contentfulClient.GetEntries(Arg.Do<QueryBuilder<Content>>(value => query = value.Build()));
await _contentfulClient.GetEntries(Arg.Do<QueryBuilder<Content>>(value => query = value.Build()), Arg.Any<CancellationToken>());

// act
var actual = await _contentController.Index("home/");
var actual = await _contentController.Index(_cancellationTokenSource.Token, "home/");

// assert
query.Should().Contain("fields.id=home&");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
using System;
using Childrens_Social_Care_CPD;
using Childrens_Social_Care_CPD.Configuration;
using System.Threading;

namespace Childrens_Social_Care_CPD_Tests.Controllers;

Expand All @@ -26,6 +27,7 @@ public partial class CookieControllerTests
private HttpContext _httpContext;
private HttpRequest _httpRequest;
private ICpdContentfulClient _contentfulClient;
private CancellationTokenSource _cancellationTokenSource;

private void SetContent(Content content)
{
Expand All @@ -36,8 +38,10 @@ private void SetContent(Content content)
: contentCollection.Items = new List<Content> { content };

_contentfulClient
.GetEntries(Arg.Any<QueryBuilder<Content>>(), default)
.GetEntries(Arg.Any<QueryBuilder<Content>>(), Arg.Any<CancellationToken>())
.Returns(contentCollection);

_cancellationTokenSource = new CancellationTokenSource();
}

[SetUp]
Expand Down Expand Up @@ -71,7 +75,7 @@ public async Task Cookies_Returns_404_When_No_Content_Found()
SetContent(null);

// act
var actual = await _cookieController.Cookies();
var actual = await _cookieController.Cookies(_cancellationTokenSource.Token);

// assert
actual.Should().BeOfType<NotFoundResult>();
Expand All @@ -90,7 +94,7 @@ public async Task Cookies_Sets_The_ViewState_ContextModel()
SetContent(rootContent);

// act
await _cookieController.Cookies();
await _cookieController.Cookies(_cancellationTokenSource.Token);
var actual = _cookieController.ViewData["ContextModel"] as ContextModel;

// assert
Expand All @@ -108,7 +112,7 @@ public async Task Cookies_Sets_The_ContextModel_Preferences_Set_Value_Correctly(
SetContent(new Content());

// act
await _cookieController.Cookies(preferenceSet: preferenceSet);
await _cookieController.Cookies(_cancellationTokenSource.Token, preferenceSet: preferenceSet);
var actual = _cookieController.ViewData["ContextModel"] as ContextModel;

// assert
Expand All @@ -133,7 +137,7 @@ public async Task Cookies_Sets_The_ContextModel_UseContainers_Ignoring_The_SideM
SetContent(rootContent);

// act
await _cookieController.Cookies();
await _cookieController.Cookies(_cancellationTokenSource.Token);
var actual = _cookieController.ViewData["ContextModel"] as ContextModel;

// assert
Expand All @@ -148,7 +152,7 @@ public async Task Cookies_Action_Should_Not_Show_Consent_Panel()
SetContent(new Content());

// act
await _cookieController.Cookies();
await _cookieController.Cookies(_cancellationTokenSource.Token);
var actual = _cookieController.ViewData["ContextModel"] as ContextModel;

// assert
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

namespace Childrens_Social_Care_CPD_Tests.Controllers;
Expand All @@ -37,7 +38,7 @@ public async Task Non_Existant_Page_Will_Return_404()
{
// arrange
var contentCollection = new ContentfulCollection<Content>() { Items = new List<Content>() };
_application.CpdContentfulClient.GetEntries(Arg.Any<QueryBuilder<Content>>(), default).Returns(contentCollection);
_application.CpdContentfulClient.GetEntries(Arg.Any<QueryBuilder<Content>>(), Arg.Any<CancellationToken>()).Returns(contentCollection);
var url = "/does_not_exist";

// act
Expand All @@ -52,7 +53,7 @@ public async Task Non_Existant_Page_Will_Return_404()
public async Task Exception_Will_Return_500()
{
// arrange
_application.CpdContentfulClient.GetEntries(Arg.Any<QueryBuilder<Content>>(), default).Throws(new Exception("Test exception"));
_application.CpdContentfulClient.GetEntries(Arg.Any<QueryBuilder<Content>>(), Arg.Any<CancellationToken>()).Throws(new Exception("Test exception"));
var url = "/something";

// act
Expand All @@ -72,7 +73,7 @@ public async Task Exception_Will_Be_Logged()
var exception = new TestException();
var logger = Substitute.For<ILogger<ErrorController>>();
_application.LoggerFactory.CreateLogger<ErrorController>().Returns(logger);
_application.CpdContentfulClient.GetEntries(Arg.Any<QueryBuilder<Content>>(), default).Throws(exception);
_application.CpdContentfulClient.GetEntries(Arg.Any<QueryBuilder<Content>>(), Arg.Any<CancellationToken>()).Throws(exception);
var url = "/something";

// act
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,10 @@
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.Extensions.Logging;
using NSubstitute;
using NSubstitute.ExceptionExtensions;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;

namespace Childrens_Social_Care_CPD_Tests.Controllers;
Expand All @@ -28,13 +27,14 @@ public class ResourcesControllerTests
private HttpRequest _httpRequest;
private ICpdContentfulClient _contentfulClient;
private ILogger<ResourcesController> _logger;
private CancellationTokenSource _cancellationTokenSource;

private void SetContent(Content content, ContentfulCollection<Resource> resourceCollection)
{
resourceCollection ??= new ();

_contentfulClient
.GetEntries(Arg.Any<QueryBuilder<Resource>>(), default)
.GetEntries(Arg.Any<QueryBuilder<Resource>>(), Arg.Any<CancellationToken>())
.Returns(resourceCollection);

var contentCollection = new ContentfulCollection<Content>();
Expand All @@ -44,8 +44,10 @@ private void SetContent(Content content, ContentfulCollection<Resource> resource
: contentCollection.Items = new List<Content> { content };

_contentfulClient
.GetEntries(Arg.Any<QueryBuilder<Content>>(), default)
.GetEntries(Arg.Any<QueryBuilder<Content>>(), Arg.Any<CancellationToken>())
.Returns(contentCollection);

_cancellationTokenSource = new CancellationTokenSource();
}

[SetUp]
Expand Down Expand Up @@ -77,7 +79,7 @@ public async Task Search_With_Empty_Query_Returns_View()
SetContent(null, null);

// act
var actual = await _resourcesController.Search(query: null) as ViewResult;
var actual = await _resourcesController.Search(_cancellationTokenSource.Token, query: null) as ViewResult;

// assert
actual.Should().BeOfType<ViewResult>();
Expand All @@ -97,7 +99,7 @@ public async Task Search_Page_Resource_Is_Passed_To_View()
};

// act
var actual = (await _resourcesController.Search(query: null) as ViewResult)?.Model as ResourcesListViewModel;
var actual = (await _resourcesController.Search(_cancellationTokenSource.Token, query: null) as ViewResult)?.Model as ResourcesListViewModel;

// assert
actual.Content.Should().Be(content);
Expand All @@ -110,7 +112,7 @@ public async Task Search_Sets_The_ViewState_ContextModel()
SetContent(null, null);

// act
await _resourcesController.Search(null);
await _resourcesController.Search(_cancellationTokenSource.Token, null);
var actual = _resourcesController.ViewData["ContextModel"] as ContextModel;

// assert
Expand All @@ -132,7 +134,7 @@ public async Task Search_Selected_Tags_Are_Passed_Into_View()
};

// act
var actual = (await _resourcesController.Search(query) as ViewResult)?.Model as ResourcesListViewModel;
var actual = (await _resourcesController.Search(_cancellationTokenSource.Token, query) as ViewResult)?.Model as ResourcesListViewModel;

// assert
actual.SelectedTags.Should().Equal(query.Tags);
Expand All @@ -157,7 +159,7 @@ public async Task Search_Page_Set_To_Be_In_Bounds()
};

// act
var actual = (await _resourcesController.Search(query) as ViewResult)?.Model as ResourcesListViewModel;
var actual = (await _resourcesController.Search(_cancellationTokenSource.Token, query) as ViewResult)?.Model as ResourcesListViewModel;

// assert
actual.CurrentPage.Should().Be(1);
Expand All @@ -176,7 +178,7 @@ public async Task Search_Invalid_Tags_Logs_Warning()
};

// act
await _resourcesController.Search(query);
await _resourcesController.Search(_cancellationTokenSource.Token, query);

//assert
_logger.ReceivedWithAnyArgs(1).LogWarning(default, args: default);
Expand Down
2 changes: 2 additions & 0 deletions Childrens-Social-Care-CPD-Tests/CpdTestServerApplication.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NSubstitute;
using System.Threading;

namespace Childrens_Social_Care_CPD_Tests;

Expand All @@ -24,6 +25,7 @@ protected override IHost CreateHost(IHostBuilder builder)
{
services.AddTransient((_) => _cpdContentfulClient);
services.AddSingleton(_loggerFactory);
services.AddScoped(typeof(CancellationToken), s => new CancellationTokenSource().Token);
});
return base.CreateHost(builder);
}
Expand Down
18 changes: 7 additions & 11 deletions Childrens-Social-Care-CPD/Controllers/ContentController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,24 +9,20 @@ namespace Childrens_Social_Care_CPD.Controllers;
public class ContentController : Controller
{
private readonly ICpdContentfulClient _cpdClient;
private readonly static int ContentFetchDepth = 10;
private readonly static string ContentTypeId = "content";
private readonly static string DefaultHomePageName = "home";

public ContentController(ICpdContentfulClient cpdClient)
{
_cpdClient = cpdClient;
}

private async Task<Content> FetchPageContentAsync(string contentId)
private async Task<Content> FetchPageContentAsync(string contentId, CancellationToken cancellationToken)
{
var queryBuilder = QueryBuilder<Content>.New
.ContentTypeIs(ContentTypeId)
.FieldEquals("fields.id", contentId ?? DefaultHomePageName)
//.FieldEquals("fields.items.id", "foo9")
.Include(ContentFetchDepth);
.ContentTypeIs("content")
.FieldEquals("fields.id", contentId)
.Include(10);

var result = await _cpdClient.GetEntries(queryBuilder);
var result = await _cpdClient.GetEntries(queryBuilder, cancellationToken);

return result?.FirstOrDefault();
}
Expand All @@ -46,10 +42,10 @@ private async Task<Content> FetchPageContentAsync(string contentId)
Etc.
*/
[Route("/{*pagename:regex(^[[0-9a-z]](\\/?[[0-9a-z\\-]])*\\/?$)}")]
public async Task<IActionResult> Index(string pageName, bool preferenceSet = false)
public async Task<IActionResult> Index(CancellationToken cancellationToken, string pageName = "home", bool preferenceSet = false)
{
pageName = pageName?.TrimEnd('/');
var pageContent = await FetchPageContentAsync(pageName);
var pageContent = await FetchPageContentAsync(pageName, cancellationToken);
if (pageContent == null)
{
return NotFound();
Expand Down
4 changes: 2 additions & 2 deletions Childrens-Social-Care-CPD/Controllers/CookieController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public IActionResult SetPreferences(string consentValue, string sourcePage = nul

[HttpGet]
[Route("/cookies")]
public async Task<IActionResult> Cookies(string sourcePage = null, bool preferenceSet = false)
public async Task<IActionResult> Cookies(CancellationToken cancellationToken, string sourcePage = null, bool preferenceSet = false)
{
sourcePage = sourcePage ?? string.Empty;

Expand All @@ -46,7 +46,7 @@ public async Task<IActionResult> Cookies(string sourcePage = null, bool preferen
.FieldEquals("fields.id", PageName)
.Include(10);

var result = await _cpdClient.GetEntries(queryBuilder);
var result = await _cpdClient.GetEntries(queryBuilder, cancellationToken);
var pageContent = result.FirstOrDefault();

if (pageContent == null)
Expand Down
Loading

0 comments on commit c0512f7

Please sign in to comment.