-
Notifications
You must be signed in to change notification settings - Fork 6
add UserRepository tests #122
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
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
137 changes: 123 additions & 14 deletions
137
Hikkaba.Tests.Integration/Builders/TestDataBuilder.ApplicationUser.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,36 +1,145 @@ | ||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.Linq; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using Hikkaba.Data.Entities; | ||
| using Hikkaba.Shared.Constants; | ||
| using Microsoft.AspNetCore.Identity; | ||
|
|
||
| namespace Hikkaba.Tests.Integration.Builders; | ||
|
|
||
| internal sealed partial class TestDataBuilder | ||
| { | ||
| private ApplicationUser? _admin; | ||
| private readonly List<ApplicationUser> _users = []; | ||
| private readonly List<(ApplicationUser User, ApplicationRole Role)> _pendingUserRoleAssignments = []; | ||
|
|
||
| public ApplicationUser Admin => _admin ?? throw new InvalidOperationException("Admin not created. Call WithDefaultAdmin() first."); | ||
| /// <summary> | ||
| /// Returns the default admin user (created via WithUser(Defaults.AdministratorUserName, isAdmin: true)). | ||
| /// </summary> | ||
| public ApplicationUser Admin => GetUser(Defaults.AdministratorUserName); | ||
|
|
||
| public TestDataBuilder WithDefaultAdmin() | ||
| /// <summary> | ||
| /// Returns the last created user. | ||
| /// </summary> | ||
| public ApplicationUser LastUser => | ||
| _users.LastOrDefault() | ||
| ?? throw new InvalidOperationException("User not created. Call WithUser() first."); | ||
|
|
||
| /// <summary> | ||
| /// Creates a user with the specified parameters. | ||
| /// </summary> | ||
| /// <param name="userName">The username for the user.</param> | ||
| /// <param name="email">The email address. If null, defaults to "{userName}@example.com".</param> | ||
| /// <param name="isDeleted">Whether the user is marked as deleted.</param> | ||
| /// <param name="emailConfirmed">Whether the email is confirmed.</param> | ||
| /// <param name="lastLoginAt">The last login timestamp.</param> | ||
| /// <param name="lockoutEnabled">Whether lockout is enabled for the user.</param> | ||
| /// <param name="lockoutEnd">The lockout end date.</param> | ||
| /// <param name="isAdmin">Whether to assign the administrator role to the user.</param> | ||
| /// <param name="isModerator">Whether to assign the moderator role to the user.</param> | ||
| public TestDataBuilder WithUser( | ||
| string userName, | ||
| string? email = null, | ||
| bool isDeleted = false, | ||
| bool emailConfirmed = true, | ||
| DateTime? lastLoginAt = null, | ||
| bool lockoutEnabled = false, | ||
| DateTimeOffset? lockoutEnd = null, | ||
| bool isAdmin = false, | ||
| bool isModerator = false) | ||
| { | ||
| _admin = new ApplicationUser | ||
| var emailValue = email ?? $"{userName}@example.com"; | ||
| var user = new ApplicationUser | ||
| { | ||
| UserName = "admin", | ||
| NormalizedUserName = "ADMIN", | ||
| Email = "[email protected]", | ||
| NormalizedEmail = "[email protected]", | ||
| EmailConfirmed = true, | ||
| SecurityStamp = "896e8014-c237-41f5-a925-dabf640ee4c4", | ||
| ConcurrencyStamp = "43035b63-359d-4c23-8812-29bbc5affbf2", | ||
| UserName = userName, | ||
| NormalizedUserName = userName.ToUpperInvariant(), | ||
| Email = emailValue, | ||
| NormalizedEmail = emailValue.ToUpperInvariant(), | ||
| EmailConfirmed = emailConfirmed, | ||
| IsDeleted = isDeleted, | ||
| LastLoginAt = lastLoginAt, | ||
| LockoutEnabled = lockoutEnabled, | ||
| LockoutEnd = lockoutEnd, | ||
| SecurityStamp = _guidGenerator.GenerateSeededGuid().ToString(), | ||
| ConcurrencyStamp = _guidGenerator.GenerateSeededGuid().ToString(), | ||
| CreatedAt = TimeProvider.GetUtcNow().UtcDateTime, | ||
| }; | ||
| _dbContext.Users.Add(_admin); | ||
| _users.Add(user); | ||
| _dbContext.Users.Add(user); | ||
|
|
||
| if (isAdmin) | ||
| { | ||
| WithAdministratorRole(); | ||
| WithUserRole(userName, Defaults.AdministratorRoleName); | ||
| } | ||
|
|
||
| if (isModerator) | ||
| { | ||
| WithModeratorRole(); | ||
| WithUserRole(userName, Defaults.ModeratorRoleName); | ||
| } | ||
|
|
||
| return this; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Gets a user by username. | ||
| /// </summary> | ||
| public ApplicationUser GetUser(string userName) | ||
| { | ||
| return _users.Find(u => u.UserName == userName) | ||
| ?? throw new InvalidOperationException($"User with username '{userName}' not found."); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Assigns a role to a user. The role assignment is deferred until SaveAsync is called. | ||
| /// If the assignment already exists, does nothing. | ||
| /// </summary> | ||
| public TestDataBuilder WithUserRole(string userName, string roleName) | ||
| { | ||
| var user = GetUser(userName); | ||
| var role = GetRole(roleName); | ||
|
|
||
| // Check if assignment already exists | ||
| if (_pendingUserRoleAssignments.Exists(x => x.User == user && x.Role == role)) | ||
| { | ||
| return this; | ||
| } | ||
|
|
||
| _pendingUserRoleAssignments.Add((user, role)); | ||
| return this; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Applies pending user role assignments after users and roles have been saved. | ||
| /// </summary> | ||
| private async Task ApplyPendingUserRoleAssignmentsAsync(CancellationToken cancellationToken) | ||
| { | ||
| if (_pendingUserRoleAssignments.Count == 0) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| foreach (var (user, role) in _pendingUserRoleAssignments) | ||
| { | ||
| _dbContext.UserRoles.Add(new IdentityUserRole<int> | ||
| { | ||
| UserId = user.Id, | ||
| RoleId = role.Id, | ||
| }); | ||
| } | ||
|
|
||
| await _dbContext.SaveChangesAsync(cancellationToken); | ||
| _pendingUserRoleAssignments.Clear(); | ||
| } | ||
|
|
||
| private void EnsureAdminExists() | ||
| { | ||
| if (_admin == null) | ||
| var adminExists = _users.Exists(u => u.UserName == Defaults.AdministratorUserName); | ||
| if (!adminExists) | ||
| { | ||
| throw new InvalidOperationException("Admin must be created first. Call WithDefaultAdmin()."); | ||
| throw new InvalidOperationException("Admin must be created first. Call WithUser(\"admin\", isAdmin: true)."); | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
66 changes: 66 additions & 0 deletions
66
Hikkaba.Tests.Integration/Builders/TestDataBuilder.Role.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,66 @@ | ||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.Linq; | ||
| using Hikkaba.Data.Entities; | ||
| using Hikkaba.Shared.Constants; | ||
|
|
||
| namespace Hikkaba.Tests.Integration.Builders; | ||
|
|
||
| internal sealed partial class TestDataBuilder | ||
| { | ||
| private readonly List<ApplicationRole> _roles = []; | ||
|
|
||
| /// <summary> | ||
| /// Returns the last created role. | ||
| /// </summary> | ||
| public ApplicationRole LastRole => | ||
| _roles.LastOrDefault() | ||
| ?? throw new InvalidOperationException("Role not created. Call WithRole() first."); | ||
|
|
||
| /// <summary> | ||
| /// Creates a role with the specified name. If the role already exists, does nothing. | ||
| /// </summary> | ||
| public TestDataBuilder WithRole(string roleName) | ||
| { | ||
| // Check if role already exists | ||
| if (_roles.Exists(r => r.Name == roleName)) | ||
| { | ||
| return this; | ||
| } | ||
|
|
||
| var role = new ApplicationRole | ||
| { | ||
| Name = roleName, | ||
| NormalizedName = roleName.ToUpperInvariant(), | ||
| ConcurrencyStamp = _guidGenerator.GenerateSeededGuid().ToString(), | ||
| }; | ||
| _roles.Add(role); | ||
| _dbContext.Roles.Add(role); | ||
| return this; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Creates the default administrator role. | ||
| /// </summary> | ||
| public TestDataBuilder WithAdministratorRole() | ||
| { | ||
| return WithRole(Defaults.AdministratorRoleName); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Creates the default moderator role. | ||
| /// </summary> | ||
| public TestDataBuilder WithModeratorRole() | ||
| { | ||
| return WithRole(Defaults.ModeratorRoleName); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Gets a role by name. | ||
| /// </summary> | ||
| public ApplicationRole GetRole(string roleName) | ||
| { | ||
| return _roles.Find(r => r.Name == roleName) | ||
| ?? throw new InvalidOperationException($"Role with name '{roleName}' not found."); | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.