Skip to content
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
8 changes: 4 additions & 4 deletions .github/workflows/codeql.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,11 @@ jobs:

steps:
- name: Checkout repository
uses: actions/checkout@v3
uses: actions/checkout@v4

# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v2
uses: github/codeql-action/init@v3
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
Expand All @@ -56,7 +56,7 @@ jobs:
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v2
uses: github/codeql-action/autobuild@v3

# ℹ️ Command-line programs to run using the OS shell.
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
Expand All @@ -69,6 +69,6 @@ jobs:
# ./location_of_script_within_repo/buildscript.sh

- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v2
uses: github/codeql-action/analyze@v3
with:
category: "/language:${{matrix.language}}"
10 changes: 5 additions & 5 deletions .github/workflows/dotnet.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,14 @@ jobs:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Setup .NET
uses: actions/setup-dotnet@v2
uses: actions/setup-dotnet@v4
with:
dotnet-version: 6.0.x
dotnet-version: 10.0.x
- name: Restore dependencies
run: dotnet restore
- name: Build
run: dotnet build --no-restore
run: dotnet build --no-restore --configuration Release
- name: Test
run: dotnet test --no-build --verbosity normal
run: dotnet test --no-build --configuration Release --verbosity normal
55 changes: 55 additions & 0 deletions DistributedCache.Tests/CacheProviderTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
using System.Text;
using System.Text.Json;
using DistributedCache.Infrastructure;
using DistributedCache.Models;
using Microsoft.Extensions.Caching.Distributed;
using Moq;

namespace DistributedCache.Tests;

public class CacheProviderTests
{
[Fact]
public async Task GetFromCacheAsync_WhenKeyExists_ReturnsDeserializedValue()
{
var users = new[] { new User { Id = 1, Email = "leanne@example.com" } };
var serializedUsers = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(users));
var cache = new Mock<IDistributedCache>();
cache.Setup(x => x.GetAsync("users", It.IsAny<CancellationToken>()))
.ReturnsAsync(serializedUsers);
var provider = new CacheProvider(cache.Object);

var result = await provider.GetFromCacheAsync<IReadOnlyList<User>>("users");

Assert.NotNull(result);
Assert.Single(result);
Assert.Equal("leanne@example.com", result[0].Email);
}

[Fact]
public async Task SetCacheAsync_SerializesAndStoresValue()
{
var cache = new Mock<IDistributedCache>();
var provider = new CacheProvider(cache.Object);
var users = new[] { new User { Id = 1, Email = "leanne@example.com" } };

await provider.SetCacheAsync("users", users, new DistributedCacheEntryOptions());

cache.Verify(x => x.SetAsync(
"users",
It.Is<byte[]>(value => Encoding.UTF8.GetString(value).Contains("leanne@example.com")),
It.IsAny<DistributedCacheEntryOptions>(),
It.IsAny<CancellationToken>()), Times.Once);
}

[Fact]
public async Task ClearCacheAsync_RemovesKey()
{
var cache = new Mock<IDistributedCache>();
var provider = new CacheProvider(cache.Object);

await provider.ClearCacheAsync("users");

cache.Verify(x => x.RemoveAsync("users", It.IsAny<CancellationToken>()), Times.Once);
}
}
48 changes: 48 additions & 0 deletions DistributedCache.Tests/CachedUserServiceTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using DistributedCache.Infrastructure;
using DistributedCache.Models;
using DistributedCache.Services;
using Microsoft.Extensions.Caching.Distributed;
using Moq;

namespace DistributedCache.Tests;

public class CachedUserServiceTests
{
private static readonly IReadOnlyList<User> Users =
[new User { Id = 1, Email = "leanne@example.com" }];

[Fact]
public async Task GetUsersAsync_WhenCacheExists_DoesNotCallUsersApi()
{
var usersApi = new Mock<IUsersApiClient>();
var cache = new Mock<ICacheProvider>();
cache.Setup(x => x.GetFromCacheAsync<IReadOnlyList<User>>(CacheKeys.Users))
.ReturnsAsync(Users);
var service = new CachedUserService(new UserService(usersApi.Object), cache.Object);

var result = await service.GetUsersAsync();

Assert.Same(Users, result);
usersApi.Verify(x => x.GetUsersAsync(), Times.Never);
}

[Fact]
public async Task GetUsersAsync_WhenCacheIsEmpty_LoadsAndCachesUsers()
{
var usersApi = new Mock<IUsersApiClient>();
usersApi.Setup(x => x.GetUsersAsync()).ReturnsAsync(Users);
var cache = new Mock<ICacheProvider>();
cache.Setup(x => x.GetFromCacheAsync<IReadOnlyList<User>>(CacheKeys.Users))
.ReturnsAsync((IReadOnlyList<User>?)null);
var service = new CachedUserService(new UserService(usersApi.Object), cache.Object);

var result = await service.GetUsersAsync();

Assert.Same(Users, result);
usersApi.Verify(x => x.GetUsersAsync(), Times.Once);
cache.Verify(x => x.SetCacheAsync(
CacheKeys.Users,
Users,
It.IsAny<DistributedCacheEntryOptions>()), Times.Once);
}
}
24 changes: 24 additions & 0 deletions DistributedCache.Tests/DistributedCache.Tests.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.9.0" />
<PackageReference Include="Moq" Version="4.20.72" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="10.0.1">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="../DistributedCache/DistributedCache.csproj" />
</ItemGroup>
</Project>
53 changes: 53 additions & 0 deletions DistributedCache.Tests/HttpClientTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
using System.Net;
using DistributedCache.Infrastructure;
using Moq;
using Moq.Protected;

namespace DistributedCache.Tests;

public class HttpClientTests
{
[Fact]
public async Task GetUsersAsync_ReturnsUsersFromApi()
{
var handler = new Mock<HttpMessageHandler>();
handler.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.IsAny<HttpRequestMessage>(),
ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent(
"""[{"id":1,"email":"leanne@example.com"}]""")
});
var factory = new Mock<IHttpClientFactory>();
factory.Setup(x => x.CreateClient(It.IsAny<string>()))
.Returns(new System.Net.Http.HttpClient(handler.Object));
var client = new UsersApiClient(factory.Object);

var result = await client.GetUsersAsync();

Assert.Single(result);
Assert.Equal("leanne@example.com", result[0].Email);
}

[Fact]
public async Task GetUsersAsync_WhenApiReturnsError_ThrowsHttpRequestException()
{
var handler = new Mock<HttpMessageHandler>();
handler.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.IsAny<HttpRequestMessage>(),
ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(new HttpResponseMessage(HttpStatusCode.InternalServerError));
var factory = new Mock<IHttpClientFactory>();
factory.Setup(x => x.CreateClient(It.IsAny<string>()))
.Returns(new System.Net.Http.HttpClient(handler.Object));
var client = new UsersApiClient(factory.Object);

await Assert.ThrowsAsync<HttpRequestException>(() => client.GetUsersAsync());
}
}
1 change: 1 addition & 0 deletions DistributedCache.Tests/Usings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
global using Xunit;
71 changes: 30 additions & 41 deletions DistributedCache/Controllers/HomeController.cs
Original file line number Diff line number Diff line change
@@ -1,41 +1,30 @@
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using DistributedCache.Services;

namespace DistributedCache.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly IUserService _userService;
private readonly ICacheUserService _cacheUserService;

public HomeController(ILogger<HomeController> logger, IUserService userService, ICacheUserService cacheUserService)
{
_logger = logger;
_userService = userService;
_cacheUserService = cacheUserService;
}

public async Task<IActionResult> Index()
{
var users = (await _cacheUserService.GetCachedUser())?.FirstOrDefault();
return View(users);
}

public async Task<IActionResult> CacheUserAsync()
{
var users = await _userService.GetUsersAsync();
var cachedEntry = users.First();
return View(nameof(Index), cachedEntry);
}

public IActionResult CacheRemoveAsync()
{
_cacheUserService.ClearCache();
return RedirectToAction(nameof(Index));
}
}
}
using Microsoft.AspNetCore.Mvc;
using DistributedCache.Services;

namespace DistributedCache.Controllers;

public class HomeController(
IUserService userService,
ICacheUserService cacheUserService) : Controller
{
private readonly IUserService _userService = userService;
private readonly ICacheUserService _cacheUserService = cacheUserService;

public async Task<IActionResult> Index()
{
var user = (await _cacheUserService.GetCachedUserAsync()).FirstOrDefault();
return View(user);
}

public async Task<IActionResult> CacheUserAsync()
{
var users = await _userService.GetUsersAsync();
return View(nameof(Index), users.FirstOrDefault());
}

public async Task<IActionResult> CacheRemoveAsync()
{
await _cacheUserService.ClearCacheAsync();
return RedirectToAction(nameof(Index));
}
}
16 changes: 9 additions & 7 deletions DistributedCache/DistributedCache.csproj
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" Version="6.0.0" />
</ItemGroup>
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" Version="10.0.11" />
</ItemGroup>

</Project>
Loading
Loading