Skip to content

Commit

Permalink
UserController integration tests.
Browse files Browse the repository at this point in the history
  • Loading branch information
msmahdinejad committed Aug 29, 2024
1 parent 7296e9d commit 8b2de5b
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 105 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,19 @@ private void SeedDatabase(ApplicationDbContext dbContext)
LastName = "User",
Email = "[email protected]"
};
var user2 = new User
{
Id = 2,
Username = "admin2",
PasswordHash = "74b2c5bd3a8de69c8c7c643e8b5c49d6552dc636aeb0995aff6f01a1f661a979",
FirstName = "Admin2",
LastName = "User2",
Email = "[email protected]"
};
var role = new Role
{
Id = 1,
Name = "admin",
Name = "Admin",
Permissions = "[\"AdminPermissions\"]"
};
var userRole = new UserRole
Expand All @@ -73,6 +82,7 @@ private void SeedDatabase(ApplicationDbContext dbContext)
user.UserRoles.Add(userRole);
role.UserRoles.Add(userRole);
dbContext.Users.Add(user);
dbContext.Users.Add(user2);
dbContext.Roles.Add(role);
dbContext.SaveChanges();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,37 +3,30 @@
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using Microsoft.Extensions.Options;
using Moq;
using RelationshipAnalysis.Dto;
using RelationshipAnalysis.Dto.Panel.User;
using RelationshipAnalysis.Models.Auth;
using RelationshipAnalysis.Services.AuthServices;
using RelationshipAnalysis.Settings.JWT;

namespace RelationshipAnalysis.Integration.Test.Controllers.Panel;

public class UserControllerTests : IClassFixture<CustomWebApplicationFactory<Program>>
public class UserControllerIntegrationTests : IClassFixture<CustomWebApplicationFactory<Program>>
{
private readonly HttpClient _client;

public UserControllerTests(CustomWebApplicationFactory<Program> factory)
public UserControllerIntegrationTests(CustomWebApplicationFactory<Program> factory)
{
_client = factory.CreateClient();
}

[Fact]
public async Task GetUser_ShouldReturnUser_WhenUserIsAuthorized()
private string GenerateJwtToken()
{
// Arrange
var request = new HttpRequestMessage(HttpMethod.Get, "/api/user");
var jwtSettings = new JwtSettings
{
Key = "kajbdiuhdqhpjQE89HBSDJIABFCIWSGF89GW3EJFBWEIUBCZNMXCJNLZDKNJKSNJKFBIGW3EASHHDUIASZGCUI",
ExpireMinutes = 60
};
Mock<IOptions<JwtSettings>> mockJwtSettings = new();
mockJwtSettings.Setup(m => m.Value).Returns(jwtSettings);


var user = new User
{
Expand All @@ -45,7 +38,15 @@ public async Task GetUser_ShouldReturnUser_WhenUserIsAuthorized()
Email = "[email protected]"
};

var token = new JwtTokenGenerator(mockJwtSettings.Object).GenerateJwtToken(user);
return new JwtTokenGenerator(new Microsoft.Extensions.Options.OptionsWrapper<JwtSettings>(jwtSettings)).GenerateJwtToken(user);
}

[Fact]
public async Task GetUser_ShouldReturnUser_WhenUserIsAuthorized()
{
// Arrange
var request = new HttpRequestMessage(HttpMethod.Get, "/api/user");
var token = GenerateJwtToken();
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

// Act
Expand All @@ -55,17 +56,17 @@ public async Task GetUser_ShouldReturnUser_WhenUserIsAuthorized()
response.EnsureSuccessStatusCode();
var responseData = await response.Content.ReadFromJsonAsync<UserOutputInfoDto>();
Assert.NotNull(responseData);
Assert.NotEmpty(responseData.Username);
Assert.Equal("admin", responseData.Username);
}

[Fact]
public async Task GetUser_ShouldReturnUnauthorized_WhenUserIsNotAuthorized()
{
// Arrange
_client.DefaultRequestHeaders.Authorization = null;
var request = new HttpRequestMessage(HttpMethod.Get, "/api/user");

// Act
var response = await _client.GetAsync("/api/user");
var response = await _client.SendAsync(request);

// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Expand All @@ -75,93 +76,54 @@ public async Task GetUser_ShouldReturnUnauthorized_WhenUserIsNotAuthorized()
public async Task UpdateUser_ShouldReturnSuccess_WhenUpdateIsValid()
{
// Arrange
var user = new User
{
Id = 1,
Username = "admin",
PasswordHash = "74b2c5bd3a8de69c8c7c643e8b5c49d6552dc636aeb0995aff6f01a1f661a979",
FirstName = "Admin",
LastName = "User",
Email = "[email protected]"
};
var token = GenerateJwtToken();

var userUpdateInfoDto = new UserUpdateInfoDto
{
Username = "Updated Name",
FirstName = "justrandomName",
LastName = "justrandomName",
Username = "UpdatedName",
FirstName = "UpdatedFirstName",
LastName = "UpdatedLastName",
Email = "[email protected]"
};


var jwtSettings = new JwtSettings
{
Key = "kajbdiuhdqhpjQE89HBSDJIABFCIWSGF89GW3EJFBWEIUBCZNMXCJNLZDKNJKSNJKFBIGW3EASHHDUIASZGCUI",
ExpireMinutes = 60
};
Mock<IOptions<JwtSettings>> mockJwtSettings = new();
mockJwtSettings.Setup(m => m.Value).Returns(jwtSettings);

var request = new HttpRequestMessage(HttpMethod.Put, "/api/user");
request.Content = new StringContent(
JsonSerializer.Serialize(userUpdateInfoDto),
Encoding.UTF8,
"application/json"
);

var token = new JwtTokenGenerator(mockJwtSettings.Object).GenerateJwtToken(user);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);


// Act
var response = await _client.SendAsync(request);

// Assert
response.EnsureSuccessStatusCode();
var responseData = await response.Content.ReadFromJsonAsync<UserOutputInfoDto>();
var responseData = await response.Content.ReadFromJsonAsync<MessageDto>();
Assert.NotNull(responseData);
Assert.Equal(Resources.SuccessfulUpdateUserMessage, responseData.Message);
}

[Fact]
public async Task UpdatePassword_ShouldReturnSuccess_WhenPasswordUpdateIsValid()
{
// Arrange
var user = new User
{
Id = 1,
Username = "admin",
PasswordHash = "74b2c5bd3a8de69c8c7c643e8b5c49d6552dc636aeb0995aff6f01a1f661a979",
FirstName = "Admin",
LastName = "User",
Email = "[email protected]"
};
var token = GenerateJwtToken();

var passwordInfo = new UserPasswordInfoDto
{
OldPassword = "validPassword",
NewPassword = "Af3$aaaa"
NewPassword = "NewValidPassword1!"
};


var jwtSettings = new JwtSettings
{
Key = "kajbdiuhdqhpjQE89HBSDJIABFCIWSGF89GW3EJFBWEIUBCZNMXCJNLZDKNJKSNJKFBIGW3EASHHDUIASZGCUI",
ExpireMinutes = 60
};
Mock<IOptions<JwtSettings>> mockJwtSettings = new();
mockJwtSettings.Setup(m => m.Value).Returns(jwtSettings);

var request = new HttpRequestMessage(HttpMethod.Patch, "/api/user/password");
request.Content = new StringContent(
JsonSerializer.Serialize(passwordInfo),
Encoding.UTF8,
"application/json"
);

var token = new JwtTokenGenerator(mockJwtSettings.Object).GenerateJwtToken(user);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);


// Act
var response = await _client.SendAsync(request);

Expand All @@ -175,62 +137,28 @@ public async Task UpdatePassword_ShouldReturnSuccess_WhenPasswordUpdateIsValid()
public async Task Logout_ShouldReturnOk_OnSuccessfulLogout()
{
// Arrange
var user = new User
{
Id = 1,
Username = "admin",
PasswordHash = "74b2c5bd3a8de69c8c7c643e8b5c49d6552dc636aeb0995aff6f01a1f661a979",
FirstName = "Admin",
LastName = "User",
Email = "[email protected]"
};


var jwtSettings = new JwtSettings
{
Key = "kajbdiuhdqhpjQE89HBSDJIABFCIWSGF89GW3EJFBWEIUBCZNMXCJNLZDKNJKSNJKFBIGW3EASHHDUIASZGCUI",
ExpireMinutes = 60
};
Mock<IOptions<JwtSettings>> mockJwtSettings = new();
mockJwtSettings.Setup(m => m.Value).Returns(jwtSettings);
var token = GenerateJwtToken();

var request = new HttpRequestMessage(HttpMethod.Post, "/api/user/logout");

var token = new JwtTokenGenerator(mockJwtSettings.Object).GenerateJwtToken(user);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);


// Act
var response = await _client.SendAsync(request);

// Assert
response.EnsureSuccessStatusCode();
var responseData = await response.Content.ReadFromJsonAsync<UserOutputInfoDto>();
var responseData = await response.Content.ReadFromJsonAsync<MessageDto>();
Assert.NotNull(responseData);
Assert.Equal(Resources.SuccessfulLogoutMessage, responseData.Message);
}

[Fact]
public async Task GetPermissions_ShouldReturnPermissions_WhenUserIsAuthorized()
{
// Arrange
var request = new HttpRequestMessage(HttpMethod.Get, "/api/user/permissions");
var jwtSettings = new JwtSettings
{
Key = "kajbdiuhdqhpjQE89HBSDJIABFCIWSGF89GW3EJFBWEIUBCZNMXCJNLZDKNJKSNJKFBIGW3EASHHDUIASZGCUI",
ExpireMinutes = 60
};
Mock<IOptions<JwtSettings>> mockJwtSettings = new();
mockJwtSettings.Setup(m => m.Value).Returns(jwtSettings);


var user = new User
{
Id = 1,
Username = "Test",
UserRoles = new List<UserRole> { new() { Role = new Role { Name = "admin" } } }
};
var token = GenerateJwtToken();

var token = new JwtTokenGenerator(mockJwtSettings.Object).GenerateJwtToken(user);
var request = new HttpRequestMessage(HttpMethod.Get, "/api/user/permissions");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

// Act
Expand All @@ -240,17 +168,17 @@ public async Task GetPermissions_ShouldReturnPermissions_WhenUserIsAuthorized()
response.EnsureSuccessStatusCode();
var responseData = await response.Content.ReadFromJsonAsync<PermissionDto>();
Assert.NotNull(responseData);
Assert.NotEmpty(responseData.Permissions);
Assert.Contains("AdminPermissions", responseData.Permissions);
}

[Fact]
public async Task GetPermissions_ShouldReturnUnauthorized_WhenUserIsNotAuthorized()
{
// Arrange
_client.DefaultRequestHeaders.Authorization = null;
var request = new HttpRequestMessage(HttpMethod.Get, "/api/user/permissions");

// Act
var response = await _client.GetAsync("/api/user/permissions");
var response = await _client.SendAsync(request);

// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Expand Down

0 comments on commit 8b2de5b

Please sign in to comment.