Skip to content

Commit

Permalink
Role and permission service test (#73)
Browse files Browse the repository at this point in the history
* feat(Role) : add role test

* feat(Role) : add role test

* feat(Role) : add permission test

* fix(Test) : fix test
  • Loading branch information
mahdijafariii authored Sep 4, 2024
1 parent 0da447b commit 5bec44d
Show file tree
Hide file tree
Showing 5 changed files with 255 additions and 1 deletion.
3 changes: 3 additions & 0 deletions AnalysisData/AnalysisData.sln.DotSettings.user
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,9 @@
<TestId>xUnit::9AEC1F3F-B1B3-47C1-82D4-E432E2D77E0E::net8.0::TestProject.User.Repository.UserRepository.UserRepositoryTests.GetUserByUsernameAsync_ShouldReturnsUserWithInputUsername_WhenUserWithInputUsernameExists</TestId>
<TestId>xUnit::9AEC1F3F-B1B3-47C1-82D4-E432E2D77E0E::net8.0::TestProject.User.Repository.UserRepository.UserRepositoryTests</TestId>
</TestAncestor>
&lt;/SessionState&gt;</s:String>
<s:String x:Key="/Default/Environment/UnitTesting/UnitTestSessionStore/Sessions/=6ba9e519_002D8508_002D49c3_002D99c9_002Da5d3c0910628/@EntryIndexedValue">&lt;SessionState ContinuousTestingMode="0" Name="PermissionServiceTest" xmlns="urn:schemas-jetbrains-com:jetbrains-ut-session"&gt;&#xD;
&lt;Project Location="C:\Users\Mahdi\Desktop\New folder (2)\Summer1403-Project-Group03-Backend\AnalysisData\TestProject" Presentation="&amp;lt;TestProject&amp;gt;" /&gt;&#xD;
&lt;/SessionState&gt;</s:String>
<s:String x:Key="/Default/Environment/UnitTesting/UnitTestSessionStore/Sessions/=8ae15fa0_002Dd719_002D4ce1_002D847c_002De586feccc67f/@EntryIndexedValue">&lt;SessionState ContinuousTestingMode="0" Name="AddRole_ShouldAddsRoleToDatabase_Whenever" xmlns="urn:schemas-jetbrains-com:jetbrains-ut-session"&gt;&#xD;
&lt;TestAncestor&gt;&#xD;
Expand Down
6 changes: 6 additions & 0 deletions AnalysisData/AnalysisData/AnalysisData.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,16 @@
<PackageReference Include="AWSSDK.S3" Version="4.0.0-preview.2" />
<PackageReference Include="Azure.Extensions.AspNetCore.Configuration.Secrets" Version="1.3.2" />
<PackageReference Include="Azure.Identity" Version="1.12.0" />
<PackageReference Include="CoverageChecker" Version="0.3.1" />
<PackageReference Include="coverlet.collector" Version="6.0.2">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="CsvHelper" Version="33.0.1" />
<PackageReference Include="JWT" Version="10.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.7" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.7" />
<PackageReference Include="Microsoft.CodeCoverage" Version="17.11.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.7" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.7">
<PrivateAssets>all</PrivateAssets>
Expand Down
6 changes: 5 additions & 1 deletion AnalysisData/TestProject/TestProject.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,11 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.0" />
<PackageReference Include="coverlet.collector" Version="6.0.2">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.CodeCoverage" Version="17.11.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="8.0.7" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="MockQueryable.Core" Version="7.0.3" />
Expand Down
76 changes: 76 additions & 0 deletions AnalysisData/TestProject/mahdi-test/PermissionServiceTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
using System.Reflection;
using System.Security.Claims;
using AnalysisData.User.Services.PermissionService;
using NSubstitute;

namespace TestProject.mahdi_test;

public class PermissionServiceTest
{
private readonly PermissionService _sut;

// public PermissionServiceTest()
// {
// _sut = new PermissionService();
// }

// [Fact]
// public void GetPermission_ShouldReturnsPermissions_WhenUserHasRole()
// {
// // Arrange
// var role = "Admin";
// var userClaims = new ClaimsPrincipal(new ClaimsIdentity(new Claim[]
// {
// new Claim(ClaimTypes.Role, role)
// }));
//
// // Act
// var result = _sut.GetPermission(userClaims);
//
// // Assert
// var expectedPermissions = new List<string> { "permission1", "permission2", "permission3", "permission4" };
//
// // Convert result to a list and compare
// var resultList = result.ToList();
// Assert.Equal(expectedPermissions.Count, resultList.Count);
// foreach (var permission in expectedPermissions)
// {
// Assert.Contains(permission, resultList);
// }
// }

// [Fact]
// public void GetPermission_ShouldReturnsEmpty_WhenUserHasNoRole()
// {
// // Arrange
// var userClaims = new ClaimsPrincipal(new ClaimsIdentity(new Claim[]
// {
// new Claim(ClaimTypes.Role, string.Empty)
// }));
//
// // Act
// var result = _sut.GetPermission(userClaims);
//
// // Assert
// Assert.Empty(result);
// }
//
// [Fact]
// public void GetPermission_ShouldReturnsEmpty_WhenRoleHasNoPermissions()
// {
// // Arrange
// var role = "Admin";
// var userClaims = new ClaimsPrincipal(new ClaimsIdentity(new Claim[]
// {
// new Claim(ClaimTypes.Role, role)
// }));
//
// // Act
// var result = _sut.GetPermission(userClaims);
//
// // Assert
// Assert.Empty(result);
// }
//
//
}
165 changes: 165 additions & 0 deletions AnalysisData/TestProject/mahdi-test/RoleManagementServiceTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
using AnalysisData.Exception;
using AnalysisData.Exception.UserException;

using AnalysisData.User.Model;
using AnalysisData.User.Repository.RoleRepository.Abstraction;
using AnalysisData.User.Services.RoleService;
using AnalysisData.User.UserDto.RoleDto;
using NSubstitute;

namespace TestProject.mahdi_test;

public class RoleManagementServiceTests
{
private readonly IRoleRepository _roleRepositoryMock;
private readonly RoleManagementService _sut;

public RoleManagementServiceTests()
{
_roleRepositoryMock = Substitute.For<IRoleRepository>();
_sut = new RoleManagementService(_roleRepositoryMock);
}


[Fact]
public async Task GetRoleCount_ShouldReturnsCorrectCount_WhenHaveManyRolesInRepository()
{
// Arrange
int expectedCount = 5;
_roleRepositoryMock.GetRolesCountAsync()
.Returns(expectedCount);

// Act
int result = await _sut.GetRoleCount();

// Assert
Assert.Equal(expectedCount, result);
}

[Fact]
public async Task GetRoleCount_ShouldReturnReturnsZero_WhenNoRolesExist()
{
// Arrange
int expectedCount = 0;
_roleRepositoryMock.GetRolesCountAsync()
.Returns(expectedCount);

// Act
int result = await _sut.GetRoleCount();

// Assert
Assert.Equal(expectedCount, result);
}

[Fact]
public async Task GetRolePagination_ShouldReturnsCorrectPagedRoles_WhenMultipleRolesExist()
{
// Arrange
int page = 1;
int limit = 10;
var roles = new List<Role>
{
new Role { Id = 1, RoleName = "Admin", RolePolicy = "AdminPolicy" },
new Role { Id = 2, RoleName = "User", RolePolicy = "UserPolicy" }
};

_roleRepositoryMock.GetAllRolesPaginationAsync(page, limit)
.Returns(Task.FromResult(roles));

var expectedRoles = roles.Select(x => new RolePaginationDto
{
Id = x.Id.ToString(),
Name = x.RoleName,
Policy = x.RolePolicy
}).ToList();

// Act
var result = await _sut.GetRolePagination(page, limit);

// Assert
Assert.Equivalent(expectedRoles, result);
}


[Fact]
public async Task GetRolePagination_ShouldReturnsCorrectPagedRoles_WhenNoRolesExist()
{
// Arrange
int page = 1;
int limit = 10;
var roles = new List<Role>();

_roleRepositoryMock.GetAllRolesPaginationAsync(page, limit)
.Returns(Task.FromResult(roles));

var expectedRoles = roles.Select(x => new RolePaginationDto
{
Id = x.Id.ToString(),
Name = x.RoleName,
Policy = x.RolePolicy
}).ToList();

// Act
var result = await _sut.GetRolePagination(page, limit);

// Assert
Assert.Equivalent(expectedRoles, result);
}

[Fact]
public async Task DeleteRole_ShouldDeleteRole_WhenRoleExists()
{
// Arrange
string roleName = "Admin";
var existingRole = new Role { RoleName = roleName };
_roleRepositoryMock.GetRoleByNameAsync(roleName).Returns(existingRole);

// Act
await _sut.DeleteRole(roleName);

// Assert
await _roleRepositoryMock.Received(1).DeleteRoleAsync(roleName);
}

[Fact]
public async Task DeleteRole_ShouldThrowRoleNotFoundException_WhenRoleDoesNotExist()
{
// Arrange
string roleName = "NonExistentRole";
_roleRepositoryMock.GetRoleByNameAsync(roleName).Returns((Role)null);

// Act & Assert
await Assert.ThrowsAsync<RoleNotFoundException>(() => _sut.DeleteRole(roleName));
}

[Fact]
public async Task AddRole_ShouldNotAddRole_WhenRoleExistsBefore()
{
// Arrange
string roleName = "admin";
var existingRole = new Role { RoleName = roleName , RolePolicy = "gold"};
_roleRepositoryMock.GetRoleByNameAsync(roleName).Returns(existingRole);

// Assert && Act
await Assert.ThrowsAsync<DuplicateRoleExistException>(() => _sut.AddRole(roleName, "gold"));
}

[Fact]
public async Task AddRole_ShouldAddRole_WhenRoleNotExistsBefore()
{
// Arrange
string roleName = "Admin";
string rolePolicy = "Gold";

var newRole = new Role { RoleName = roleName.ToLower(), RolePolicy = rolePolicy.ToLower() };

_roleRepositoryMock.GetRoleByNameAsync(roleName).Returns((Role)null);

// Act
await _sut.AddRole(roleName, rolePolicy);


// Assert
await _roleRepositoryMock.Received(1).AddRoleAsync(Arg.Is<Role>(r =>
r.RoleName == roleName.ToLower() && r.RolePolicy == rolePolicy.ToLower())); }
}

0 comments on commit 5bec44d

Please sign in to comment.