Skip to content

Commit

Permalink
Add more integration tests to up code coverage
Browse files Browse the repository at this point in the history
  • Loading branch information
vanderlan committed Nov 16, 2023
1 parent 85b4c40 commit e7ced12
Show file tree
Hide file tree
Showing 9 changed files with 118 additions and 17 deletions.
2 changes: 1 addition & 1 deletion src/Orion.Api/Controllers/V1/UsersController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ public async Task<IActionResult> Delete(string id)
return NoContent();
}

[HttpPatch("Me/PasswordChange")]
[HttpPatch("Me/Password")]
[SwaggerResponse((int)HttpStatusCode.BadRequest, "A error response with the error description", typeof(ExceptionResponse))]
[SwaggerResponse((int)HttpStatusCode.Accepted)]
[SwaggerResponse((int)HttpStatusCode.NotFound)]
Expand Down
6 changes: 3 additions & 3 deletions src/Orion.Api/Models/UserApiTokenModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ namespace Orion.Api.Models;

public class UserApiTokenModel
{
public string Token { get; set; }
public string RefreshToken { get; set; }
public DateTime Expiration { get; set; }
public string Token { get; init; }
public string RefreshToken { get; init; }
public DateTime Expiration { get; init; }
}
2 changes: 1 addition & 1 deletion src/Orion.Api/Properties/launchSettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"Dev": {
"commandName": "Project",
"launchUrl": "swagger",
"launchBrowser": false,
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
Expand Down
2 changes: 1 addition & 1 deletion src/Orion.Api/appsettings.Test.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
}
},
"ConnectionStrings": {
"OrionDatabase": "Data Source=localhost,1433;Initial Catalog=Orion;User ID=sa;Password=SqlServer2019!;TrustServerCertificate=True"
"OrionDatabase": "Data Source=localhost,1433;Initial Catalog=OrionTests;User ID=sa;Password=SqlServer2019!;TrustServerCertificate=True"
},
"JwtOptions": {
"SymmetricSecurityKey": "5cCI6IkpXVCJ9.eyJlbWFpbCI6InZhbmRlcmxhbi5nc0BnbWFpbC5jb20iLCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL3JvbGUiOiJhZG1p",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,6 @@ public async Task<PagedList<UserGetPaginatedResponse>> Handle(UserGetPaginatedRe

var usersPaginated = users.Items.Select(user => (UserGetPaginatedResponse)user).ToList();

return new PagedList<UserGetPaginatedResponse>(usersPaginated);
return new PagedList<UserGetPaginatedResponse>(usersPaginated, users.Count);
}
}
27 changes: 26 additions & 1 deletion tests/Orion.Test/Api/V1/AuthApiTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public async Task AuthUser_WithRefreshTokenInvalid_ReturnsUnauthorized(string re
}

[Fact]
public async Task AuthUser_WithValidRefreshToken_ReturnsNewToken()
public async Task AuthUser_WithValidRefreshTokenAndExpiredToken_ReturnsNewToken()
{
//arrange
var user = UserFaker.GetUserCreateRequest();
Expand Down Expand Up @@ -85,6 +85,31 @@ public async Task AuthUser_WithValidRefreshToken_ReturnsNewToken()
Assert.NotNull(refreshTokenResponse.RefreshToken);
}

[Fact]
public async Task AuthUser_WithInvalidRefreshTokenAndValidExpiredToken_ReturnsUnauthorized()
{
//arrange
var user = UserFaker.GetUserCreateRequest();

var userCreated = await CreateUserAsync(user);

var httpClient = IntegrationTestsFixture.GetNewHttpClient();

var tokenResult = AuthUser(userCreated.Email, user.Password);

var refreshTokenRequest = new LoginWithRefreshTokenRequest
{
RefreshToken = "invalid-refresh-token",
Token = tokenResult.Token
};

//act
var httpResponseRefreshToken = await httpClient.PostAsync("/api/Auth/RefreshToken", GetStringContent(refreshTokenRequest));

//assert
Assert.Equal(HttpStatusCode.Unauthorized, httpResponseRefreshToken.StatusCode);
}

private async Task<UserCreateResponse> CreateUserAsync(UserCreateRequest userCreateRequest = null)
{
userCreateRequest ??= UserFaker.GetUserCreateRequest();
Expand Down
82 changes: 79 additions & 3 deletions tests/Orion.Test/Api/V1/UsersApiTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Orion.Application.Core.Commands.UserChangePassword;
using Orion.Application.Core.Queries.UserGetPaginated;
using Orion.Domain.Core.ValueObjects.Pagination;
using Xunit;

namespace Orion.Test.Api.V1
Expand All @@ -16,6 +18,52 @@ public UsersApiTest(IntegrationTestsFixture fixture) : base(fixture)
{
LoginWithDefaultUser();
}

[Fact]
public async Task GetUserPaginated_WithoutFilter_ReturnsDefaultUser()
{
//arrange & act
var getUsersHttpResponse = await AuthenticatedHttpClient.GetAsync("/api/Users");

var listUsersPaginated = await GetResultContentAsync<PagedList<UserGetPaginatedResponse>>(getUsersHttpResponse);

//assert
Assert.Contains(listUsersPaginated.Items, x => x.PublicId == DefaultSystemUser.PublicId);
Assert.Contains(listUsersPaginated.Items, x => x.Name == DefaultSystemUser.Name);
Assert.Contains(listUsersPaginated.Items, x => x.Email == DefaultSystemUser.Email);
Assert.True(listUsersPaginated.Count >= 1);
Assert.Equal(HttpStatusCode.OK, getUsersHttpResponse.StatusCode);
}

[Fact]
public async Task GetUserPaginated_WithNameFilter_ReturnsDefaultUser()
{
//arrange & act
var getUsersHttpResponse = await AuthenticatedHttpClient.GetAsync($"/api/Users?filter.Query={DefaultSystemUser.Name}");

var listUsersPaginated = await GetResultContentAsync<PagedList<UserGetPaginatedResponse>>(getUsersHttpResponse);

//assert
Assert.Contains(listUsersPaginated.Items, x => x.PublicId == DefaultSystemUser.PublicId);
Assert.Contains(listUsersPaginated.Items, x => x.Name == DefaultSystemUser.Name);
Assert.Contains(listUsersPaginated.Items, x => x.Email == DefaultSystemUser.Email);
Assert.True(listUsersPaginated.Count >= 1);
Assert.Equal(HttpStatusCode.OK, getUsersHttpResponse.StatusCode);
}

[Fact]
public async Task GetUserPaginated_WithInvalidUserName_ReturnsEmptyList()
{
//arrange & act
var getUsersHttpResponse = await AuthenticatedHttpClient.GetAsync($"/api/Users?filter.Query={Guid.NewGuid()}");

var listUsersPaginated = await GetResultContentAsync<PagedList<UserGetPaginatedResponse>>(getUsersHttpResponse);

//assert
Assert.Empty(listUsersPaginated.Items);
Assert.True(listUsersPaginated.Count == 0);
Assert.Equal(HttpStatusCode.OK, getUsersHttpResponse.StatusCode);
}

[Fact]
public async Task PostUser_WithValidData_CreateAUser()
Expand Down Expand Up @@ -111,13 +159,13 @@ public async Task UpdateUserPassword_WithInvalidPasswordsAndConfirmation_Returns
};

//act
var httpResponsePatch = await AuthenticatedHttpClient.PatchAsync("/api/Users/Me/PasswordChange", GetStringContent(changePasswordRequest));
var httpResponsePatch = await AuthenticatedHttpClient.PatchAsync("/api/Users/Me/Password", GetStringContent(changePasswordRequest));

Assert.Equal(HttpStatusCode.BadRequest, httpResponsePatch.StatusCode);
}

[Fact]
public async Task UpdateUserPassword_WithValidPasswordsAndConfirmation_ReturnsAcepted()
public async Task UpdateUserPassword_WithValidPasswordsAndConfirmation_ReturnsAccepted()
{
//arrange
var user = UserFaker.GetUserCreateRequest();
Expand All @@ -138,12 +186,40 @@ public async Task UpdateUserPassword_WithValidPasswordsAndConfirmation_ReturnsAc
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResult.Token);

//act
var httpResponsePatch = await httpClient.PatchAsync("/api/Users/Me/PasswordChange", GetStringContent(changePasswordRequest));
var httpResponsePatch = await httpClient.PatchAsync("/api/Users/Me/Password", GetStringContent(changePasswordRequest));

//assert
Assert.Equal(HttpStatusCode.Accepted, httpResponsePatch.StatusCode);
}

[Fact]
public async Task UpdateUserPassword_WithInValidCurrentPassword_ReturnsBadRequest()
{
//arrange
var user = UserFaker.GetUserCreateRequest();

var userCreated = await CreateUserAsync(user);

var changePasswordRequest = new UserChangePasswordRequest
{
CurrentPassword = "invalid-pass",
NewPassword = "Ab647477382",
NewPasswordConfirm = "Ab647477382"
};

var httpClient = IntegrationTestsFixture.GetNewHttpClient();

var tokenResult = AuthUser(userCreated.Email, user.Password);

httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResult.Token);

//act
var httpResponsePatch = await httpClient.PatchAsync("/api/Users/Me/Password", GetStringContent(changePasswordRequest));

//assert
Assert.Equal(HttpStatusCode.BadRequest, httpResponsePatch.StatusCode);
}

private async Task<UserCreateResponse> CreateUserAsync(UserCreateRequest userCreateRequest = null)
{
userCreateRequest ??= UserFaker.GetUserCreateRequest();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public abstract class IntegrationTestsBootstrapper : IClassFixture<IntegrationTe
{
protected readonly HttpClient HttpClient;
protected readonly HttpClient AuthenticatedHttpClient;
private readonly User _defaultSystemUser;
protected readonly User DefaultSystemUser;
protected readonly IntegrationTestsFixture IntegrationTestsFixture;

protected IServiceProvider ServiceProvider { get; private set; }
Expand All @@ -24,14 +24,14 @@ protected IntegrationTestsBootstrapper(IntegrationTestsFixture fixture)
{
HttpClient = fixture.HttpClient;
AuthenticatedHttpClient = fixture.AuthenticatedHttpClient;
_defaultSystemUser = fixture.DefaultSystemUser;
DefaultSystemUser = fixture.DefaultSystemUser;
ServiceProvider = fixture.ServiceProvider;
IntegrationTestsFixture = fixture;
}

protected void LoginWithDefaultUser()
{
var tokenResult = AuthUser(_defaultSystemUser.Email, "123");
var tokenResult = AuthUser(DefaultSystemUser.Email, "123");

AuthenticatedHttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResult.Token);
}
Expand Down
6 changes: 3 additions & 3 deletions tests/Orion.Test/Integration/Setup/IntegrationTestsFixture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public class IntegrationTestsFixture
private readonly IUnitOfWork _unitOfWork;
private readonly SqlConnection _sqlConnection;
private IConfiguration _configuration;
private WebApplicationFactory<Program> AppFactory;
private readonly WebApplicationFactory<Program> _appFactory;

public IntegrationTestsFixture()
{
Expand All @@ -47,14 +47,14 @@ public IntegrationTestsFixture()

_sqlConnection = new SqlConnection(_configuration["ConnectionStrings:OrionDatabase"]);

AppFactory = appFactory;
_appFactory = appFactory;

BeforeEachTest();
}

public HttpClient GetNewHttpClient()
{
return AppFactory.CreateClient();
return _appFactory.CreateClient();
}

private void BeforeEachTest()
Expand Down

0 comments on commit e7ced12

Please sign in to comment.