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

Setup unit testing project #164

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
32 changes: 32 additions & 0 deletions backend/CircleForms.Tests/CircleForms.Tests.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<Project Sdk="Microsoft.NET.Sdk">

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

<IsPackable>false</IsPackable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.11.0" />
<PackageReference Include="Moq" Version="4.18.1" />
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="3.1.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>

<ItemGroup>
<Folder Include="Integration\" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\CircleForms\CircleForms.csproj" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using CircleForms.Database.Models.Users;
using CircleForms.Database.Services;
using CircleForms.Database.Services.Extensions;
using CircleForms.Tests.Utils;
using Microsoft.Extensions.Logging.Abstractions;
using MongoDB.Bson;
using Moq;
using StackExchange.Redis;
using Xunit;
using JsonConvert = Newtonsoft.Json.JsonConvert;

namespace CircleForms.Tests.Unit.Database.Services
{
public class RedisCacheRepositoryTests
{
private readonly RedisCacheRepository _cache;
private readonly Mock<IDatabase> _redisDatabaseMock;

public RedisCacheRepositoryTests()
{
_redisDatabaseMock = new Mock<IDatabase>(MockBehavior.Strict);

var redisMock = new Mock<IConnectionMultiplexer>();
redisMock.Setup(x => x.GetDatabase(It.IsAny<int>(), It.IsAny<object>())).Returns(_redisDatabaseMock.Object);

_cache = new RedisCacheRepository(redisMock.Object, MappingHelper.CreateMapper(),
new NullLogger<RedisCacheRepository>());
}

[Fact]
public async Task IncrementAnswersUsesCorrectId()
{
const string id = "123456";

_redisDatabaseMock
.Setup(x => x.StringIncrementAsync(It.Is<RedisKey>(y => y == id.ToPostAnswersCount()), It.IsAny<long>(),
It.IsAny<CommandFlags>()))
.ReturnsAsync(1);

await _cache.IncrementAnswers(id);
}

[Fact]
public async Task PinPostAddsPostToTheSet()
{
var postId = new Guid().ToString();

_redisDatabaseMock
.Setup(x => x.KeyExists(It.Is<RedisKey>(y => y == postId.ToPostId()), It.IsAny<CommandFlags>()))
.Returns(true);

_redisDatabaseMock
.Setup(x => x.SetAddAsync(It.Is<RedisKey>(y => y == "posts:pinned"),
It.Is<RedisValue>(y => y == postId.ToPostId()), It.IsAny<CommandFlags>()))
.ReturnsAsync(true);

var result = await _cache.PinPost(postId);

Assert.True(result);
_redisDatabaseMock.Verify();
}

[Fact]
public async Task PinPostDoesntAddPostToTheSetWhenItDoesntExist()
{
var postId = new Guid().ToString();

_redisDatabaseMock
.Setup(x => x.KeyExists(It.Is<RedisKey>(y => y == postId.ToPostId()), It.IsAny<CommandFlags>()))
.Returns(false);

var result = await _cache.PinPost(postId);

Assert.False(result);
_redisDatabaseMock.Verify();
}

[Fact]
public async Task AddUserAddsCorrectData()
{
var user = new User
{
ID = "123456",
Discord = "Test#7270",
Osu = new BsonDocument(new Dictionary<string, object>
{
{ "Username", "VsevolodVolkov" },
{ "AvatarUrl", "https://a.ppy.sh/123456" }
})
};

var expectedRedisUser = JsonConvert.SerializeObject(new UserMinimalRedis
{
ID = user.ID,
Discord = user.Discord,
Username = user.Osu["Username"].ToString(),
AvatarUrl = user.Osu["AvatarUrl"].ToString()
});

_redisDatabaseMock
.Setup(x => x.SetAddAsync(It.Is<RedisKey>(y => y == "user_ids"), It.Is<RedisValue>(y => y == user.ID),
It.IsAny<CommandFlags>()))
.ReturnsAsync(true);

_redisDatabaseMock
.Setup(x => x.StringSetAsync(It.Is<RedisKey>(y => y == user.ID.ToUserId()),
It.Is<RedisValue>(y => y == expectedRedisUser),
It.IsAny<TimeSpan?>(), It.IsAny<When>(), It.IsAny<CommandFlags>()))
.ReturnsAsync(true);

await _cache.AddUser(user);

_redisDatabaseMock.Verify();
}

[Fact]
public async Task GetMinimalUserReturnsUserOnCorrectId()
{
var user = new UserMinimalRedis
{
ID = "123456",
Username = "VsevolodVolkov",
AvatarUrl = "https://a.ppy.sh/123456",
Discord = "Test#7270"
};

_redisDatabaseMock
.Setup(x => x.StringGetAsync(It.Is<RedisKey>(y => y == user.ID.ToUserId()), It.IsAny<CommandFlags>()))
.ReturnsAsync(new RedisValue(JsonConvert.SerializeObject(user)));

var result = await _cache.GetMinimalUser(user.ID);

Assert.NotNull(result);
Assert.Equal(user.ID, result.ID);
Assert.Equal(user.Username, result.Username);
Assert.Equal(user.AvatarUrl, result.AvatarUrl);
Assert.Equal(user.Discord, result.Discord);
}

[Fact]
public async Task GetMinimalUserReturnsNullOnIncorrectId()
{
var user = new UserMinimalRedis
{
ID = "123456",
Username = "VsevolodVolkov",
AvatarUrl = "https://a.ppy.sh/123456",
Discord = "Test#7270"
};

_redisDatabaseMock
.Setup(x => x.StringGetAsync(It.Is<RedisKey>(y => y == user.ID.ToUserId()), It.IsAny<CommandFlags>()))
.ReturnsAsync(new RedisValue());

var result = await _cache.GetMinimalUser(user.ID);

Assert.Null(result);
}

[Fact]
public async Task RemoveUserUsesCorrectIds()
{
const string id = "123456";

_redisDatabaseMock
.Setup(x => x.KeyDeleteAsync(It.Is<RedisKey>(y => y == id.ToUserId()), It.IsAny<CommandFlags>()))
.ReturnsAsync(true);

_redisDatabaseMock
.Setup(x => x.SetRemoveAsync(It.Is<RedisKey>(y => y == "user_ids"), It.Is<RedisValue>(y => y == id), It.IsAny<CommandFlags>()))
.ReturnsAsync(true);

await _cache.RemoveUser(id);
}
}
}
17 changes: 17 additions & 0 deletions backend/CircleForms.Tests/Utils/MappingHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using FastExpressionCompiler;
using Mapster;
using MapsterMapper;

namespace CircleForms.Tests.Utils
{
internal static class MappingHelper
{
public static IMapper CreateMapper()
{
TypeAdapterConfig.GlobalSettings.Scan(typeof(Program).Assembly);
TypeAdapterConfig.GlobalSettings.Compiler = x => x.CompileFast();

return new Mapper();
}
}
}
8 changes: 6 additions & 2 deletions backend/CircleForms/Database/Models/Users/User.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,12 @@ public class User : IEntity
{
public User()
{
this.InitOneToMany(() => PostsRelation);
this.InitOneToMany(() => Answers);
// DB inits can't be done in unit testing due to how MongoDB.Entities database initialization works
if (!UnitTestDetector.IsRunningFromXUnit)
{
this.InitOneToMany(() => PostsRelation);
this.InitOneToMany(() => Answers);
}
}

[Field("token")]
Expand Down
11 changes: 9 additions & 2 deletions backend/CircleForms/Database/Services/RedisCacheRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,16 @@ public async Task<bool> UserExists(string id)

public async Task AddUser(User user)
{
await _redis.SetAddAsync(_userIds, user.ID);
if (!await _redis.SetAddAsync(_userIds, user.ID))
{
_logger.LogError("Could not post {@User} to the redis userid cache", user.ID);
}

var cachedUser = _mapper.Map<UserMinimalRedis>(user);
await _redis.StringSetAsync(user.ID.ToUserId(), JsonConvert.SerializeObject(cachedUser, Formatting.None));
if (!await _redis.StringSetAsync(user.ID.ToUserId(), JsonConvert.SerializeObject(cachedUser, Formatting.None)))
{
_logger.LogError("Could not post {@User} to the redis user cache", user);
}
}

public async Task<UserMinimalRedis> GetMinimalUser(string id)
Expand Down
25 changes: 25 additions & 0 deletions backend/CircleForms/UnitTestDetector.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using System;

namespace CircleForms;

/// <summary>
/// This exists ONLY for MongoDB.Entities-based models and MUST NOT be used anywhere else.
/// Doing workarounds for unit testing is a very very bad design, but unfortunately we can't avoid it here.
/// </summary>
public static class UnitTestDetector
Copy link
Collaborator

Choose a reason for hiding this comment

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

we don't need to mix aspects, refactor it

{
static UnitTestDetector()
{
foreach (var assem in AppDomain.CurrentDomain.GetAssemblies())
{
if (assem.FullName != null &&
assem.FullName.ToLowerInvariant().StartsWith("xunit"))
{
IsRunningFromXUnit = true;
break;
}
}
}

public static bool IsRunningFromXUnit { get; }
}