Skip to content

Commit

Permalink
Share test mocks
Browse files Browse the repository at this point in the history
  • Loading branch information
volkanceylan committed Feb 28, 2025
1 parent aab6d20 commit ef6a9f5
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 2 deletions.
39 changes: 37 additions & 2 deletions tests/Serenity.Net.Tests/testutils/mocks/MockUserAccessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,16 @@ namespace Serenity.TestUtils;
public class MockUserAccessor : IUserAccessor
{
private readonly Func<ClaimsPrincipal> getUser;
private readonly Func<string> getUsername;
private readonly Func<string> getIdentifier;
private readonly Action<ClaimsIdentity> configureIdentity;

public MockUserAccessor(Func<string> getUsername, Func<string> getIdentifier = null, Action<ClaimsIdentity> configureIdentity = null)
{
this.getUsername = getUsername ?? throw new ArgumentNullException(nameof(getUsername));
this.getIdentifier = getIdentifier;
this.configureIdentity = configureIdentity;
}

public MockUserAccessor(Func<ClaimsPrincipal> getUser)
{
Expand Down Expand Up @@ -32,5 +42,30 @@ public MockUserAccessor(Func<string> getUsername)
};
}

public ClaimsPrincipal User => getUser();
}
public ClaimsPrincipal User
{
get
{
if (getUser != null)
return getUser();

var username = getUsername();
if (username == null)
return null;

var identity = new GenericIdentity(username, "Test");
var claimsPrincipal = new ClaimsPrincipal(identity);

if (getIdentifier != null)
{
var identifier = getIdentifier();
if (identifier != null)
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, getIdentifier()));
}

configureIdentity?.Invoke(identity);

return claimsPrincipal;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,13 @@ public NullRequestContext AsGuest()
return this;
}

public NullRequestContext AsGuest(string identifier)
{
UserAccessor = new MockUserAccessor(() => TestUser.Guest, () => identifier);
Permissions = new MockPermissions(perm => false);
return this;
}

public NullRequestContext WithPermissions(Func<string, bool> hasPermission)
{
Permissions = new MockPermissions(hasPermission);
Expand Down

0 comments on commit ef6a9f5

Please sign in to comment.