Repository navigation
test: replace mocks with real fake implementations - #3017
Conversation
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughReplaces inline Vitest mocks and a deprecated mock-actor helper with a suite of concrete fake test doubles and updates 40+ unit tests to use call-recording fakes for permission evaluation, identity providers/resolvers, OAuth2 helpers, mail, and session management. Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related issues
Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Pull request overview
Refactors server-core unit tests to replace ad-hoc vi.fn() mocks with reusable “fake” implementations, reducing duplication and making test setups more realistic and consistent.
Changes:
- Added a suite of reusable fake implementations (OAuth2 repos/issuer/signer, session manager, permission evaluator/actor, mail client, identity resolver/role/permission providers).
- Updated multiple unit test suites to use the new fakes and seed behavior via helper APIs instead of per-test mock wiring.
- Removed the legacy
mock-actorhelper and updated helper exports/imports accordingly.
Reviewed changes
Copilot reviewed 39 out of 39 changed files in this pull request and generated 4 comments.
Show a summary per file
| File | Description |
|---|---|
| apps/server-core/test/unit/core/oauth2/token/verifier/module.spec.ts | Switches token verifier tests from inline repository mocks to fake OAuth2 repos with seeding helpers. |
| apps/server-core/test/unit/core/oauth2/token/signer/module.spec.ts | Uses FakeOAuth2KeyRepository instead of local mock key repository. |
| apps/server-core/test/unit/core/oauth2/token/issuer/open-id/module.spec.ts | Uses fake token repo/signer/identity resolver instead of inline mocks. |
| apps/server-core/test/unit/core/oauth2/token/issuer/access/module.spec.ts | Uses fake token repo/signer and fake role provider, simplifying access-claim tests. |
| apps/server-core/test/unit/core/oauth2/grant-types/identity.spec.ts | Replaces mock token issuers and session manager with fake implementations. |
| apps/server-core/test/unit/core/identity/registration/service.spec.ts | Replaces mocked mail client with FakeMailClient and asserts via sent/failNext. |
| apps/server-core/test/unit/core/identity/password-recovery/service.spec.ts | Replaces mocked mail client with FakeMailClient and asserts via sent/failNext. |
| apps/server-core/test/unit/core/helpers/mock-actor.ts | Removes old mock actor helper in favor of new fake-based actor utilities. |
| apps/server-core/test/unit/core/helpers/index.ts | Updates helper barrel exports to include new fake helpers and drop mock-actor. |
| apps/server-core/test/unit/core/helpers/fake-session-manager.ts | Adds a fake ISessionManager backed by an in-memory map and vi.fn methods. |
| apps/server-core/test/unit/core/helpers/fake-permission-evaluator.ts | Adds configurable fake permission evaluator supporting per-method deny/behavior hooks. |
| apps/server-core/test/unit/core/helpers/fake-oauth2-token-signer.ts | Adds fake token signer returning a configurable signature. |
| apps/server-core/test/unit/core/helpers/fake-oauth2-token-repository.ts | Adds in-memory fake token repository with inactive tracking and signature cache. |
| apps/server-core/test/unit/core/helpers/fake-oauth2-token-issuer.ts | Adds fake token issuer producing signed token strings and payloads with jti/exp. |
| apps/server-core/test/unit/core/helpers/fake-oauth2-key-repository.ts | Adds fake key repository returning a configurable key. |
| apps/server-core/test/unit/core/helpers/fake-mail-client.ts | Adds fake mail client that records sends and can fail deterministically. |
| apps/server-core/test/unit/core/helpers/fake-identity-role-provider.ts | Adds fake identity role provider returning configurable roles. |
| apps/server-core/test/unit/core/helpers/fake-identity-resolver.ts | Adds fake identity resolver returning a configurable identity. |
| apps/server-core/test/unit/core/helpers/fake-identity-permission-provider.ts | Adds fake identity permission provider with configurable superset/bindings/junction policy. |
| apps/server-core/test/unit/core/helpers/fake-actor.ts | Adds fake actor helpers powered by FakePermissionEvaluator. |
| apps/server-core/test/unit/core/entities/user/service.spec.ts | Migrates actor mocking to FakePermissionEvaluator and fake actor helpers. |
| apps/server-core/test/unit/core/entities/user-role/service.spec.ts | Uses FakeIdentityPermissionProvider and fake actor helpers; removes inline provider mocks. |
| apps/server-core/test/unit/core/entities/user-permission/service.spec.ts | Updates actor helper import to fake-actor. |
| apps/server-core/test/unit/core/entities/user-attribute/service.spec.ts | Migrates permission evaluator behavior to FakePermissionEvaluator APIs. |
| apps/server-core/test/unit/core/entities/scope/service.spec.ts | Updates actor helper import to fake-actor. |
| apps/server-core/test/unit/core/entities/role/service.spec.ts | Updates actor helper import to fake-actor. |
| apps/server-core/test/unit/core/entities/role-permission/service.spec.ts | Updates actor helper import to fake-actor. |
| apps/server-core/test/unit/core/entities/role-attribute/service.spec.ts | Uses FakePermissionEvaluator.setBehavior instead of vi.mocked implementations. |
| apps/server-core/test/unit/core/entities/robot/service.spec.ts | Migrates actors to FakePermissionEvaluator and updates deny behavior via fake API. |
| apps/server-core/test/unit/core/entities/robot-role/service.spec.ts | Uses FakeIdentityPermissionProvider and fake actor helpers; removes inline provider mocks. |
| apps/server-core/test/unit/core/entities/robot-permission/service.spec.ts | Updates actor helper import to fake-actor. |
| apps/server-core/test/unit/core/entities/realm/service.spec.ts | Updates actor helper import to fake-actor. |
| apps/server-core/test/unit/core/entities/permission/service.spec.ts | Updates actor helper import to fake-actor. |
| apps/server-core/test/unit/core/entities/permission-policy/service.spec.ts | Updates actor helper import to fake-actor. |
| apps/server-core/test/unit/core/entities/identity-provider-role-mapping/service.spec.ts | Uses FakeIdentityPermissionProvider and fake actor helpers; removes inline provider mocks. |
| apps/server-core/test/unit/core/entities/client/service.spec.ts | Migrates permission denial to FakePermissionEvaluator.deny. |
| apps/server-core/test/unit/core/entities/client-scope/service.spec.ts | Updates actor helper import to fake-actor. |
| apps/server-core/test/unit/core/entities/client-role/service.spec.ts | Uses FakeIdentityPermissionProvider and fake actor helpers; removes inline provider mocks. |
| apps/server-core/test/unit/core/entities/client-permission/service.spec.ts | Updates actor helper import to fake-actor. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| export class FakeOAuth2TokenSigner implements IOAuth2TokenSigner { | ||
| constructor(private signature = 'signed-token') {} | ||
|
|
||
| public readonly sign = vi.fn(async () => this.signature); |
There was a problem hiding this comment.
IOAuth2TokenSigner.sign is defined as sign(payload), but this fake mock is declared with no parameters. While runtime calls work, it makes sign(payload) a TypeScript error when using the concrete FakeOAuth2TokenSigner type and reduces type safety around call args. Please update the mock signature to accept the payload parameter (even if unused).
| public readonly sign = vi.fn(async () => this.signature); | |
| public readonly sign = vi.fn(async (_payload) => this.signature); |
|
|
||
| public readonly refresh = vi.fn(async (session: Session) => session); | ||
|
|
||
| public readonly verify = vi.fn(async () => {}); |
There was a problem hiding this comment.
ISessionManager.verify(session) expects a Session parameter, but the fake mock is declared with no parameters. This makes fake.verify(session) a TypeScript error when the instance is typed as FakeSessionManager and weakens typed call assertions. Please align the mock signature to accept the session argument (even if unused).
| public readonly verify = vi.fn(async () => {}); | |
| public readonly verify = vi.fn(async (session: Session) => {}); |
| public readonly findByRealmId = vi.fn(async () => this.key); | ||
|
|
||
| public readonly findById = vi.fn(async () => this.key); |
There was a problem hiding this comment.
findByRealmId / findById are declared as mocks with no parameters, even though IOAuth2KeyRepository requires (realmId: string) and (id: string). When the fake is used directly (typed as FakeOAuth2KeyRepository), calling these methods with arguments becomes a TypeScript error and makes assertions on call args less type-safe. Please update the mock signatures to accept the expected parameters (even if unused).
| public readonly findByRealmId = vi.fn(async () => this.key); | |
| public readonly findById = vi.fn(async () => this.key); | |
| public readonly findByRealmId = vi.fn(async (realmId: string) => { | |
| return this.key; | |
| }); | |
| public readonly findById = vi.fn(async (id: string) => { | |
| return this.key; | |
| }); |
| this.identity = identity; | ||
| } | ||
|
|
||
| public readonly resolve = vi.fn(async () => this.identity); |
There was a problem hiding this comment.
IIdentityResolver.resolve takes (type, key, realmKey?), but this fake mock is declared with no parameters. This makes resolver.resolve(type, key) a TypeScript error when the instance is referenced as FakeIdentityResolver (and weakens type safety for call expectations). Please align the mock’s parameter list with the interface signature (even if the args are unused).
| public readonly resolve = vi.fn(async () => this.identity); | |
| public readonly resolve = vi.fn(async (type, key, realmKey?) => this.identity); |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (6)
apps/server-core/test/unit/core/helpers/fake-identity-permission-provider.ts (1)
34-48: Wrap interface methods withvi.fnfor parity with sibling fakes.Unlike the other helpers in this PR (
FakeIdentityRoleProvider,FakeIdentityResolver,FakeOAuth2TokenSigner,FakeOAuth2TokenRepository, …),getFor/isSuperset/resolveJunctionPolicyare plain methods. That blocks specs from asserting call args/counts (expect(provider.getFor).toHaveBeenCalledWith(identity)) and is inconsistent with the rest of the suite. Consider:♻️ Proposed refactor
- async getFor(_identity: IdentityPolicyData): Promise<PermissionPolicyBinding[]> { - return this.bindings; - } - - async isSuperset(_parent: IdentityPolicyData, _child: IdentityPolicyData): Promise<boolean> { - return this.supersetResult; - } - - async resolveJunctionPolicy( - _identity: IdentityPolicyData, - _options: ResolveJunctionPolicyOptions, - ): Promise<Policy | undefined> { - return this.junctionPolicy; - } + public readonly getFor = vi.fn(async (_identity: IdentityPolicyData): Promise<PermissionPolicyBinding[]> => this.bindings); + + public readonly isSuperset = vi.fn( + async (_parent: IdentityPolicyData, _child: IdentityPolicyData): Promise<boolean> => this.supersetResult, + ); + + public readonly resolveJunctionPolicy = vi.fn( + async (_identity: IdentityPolicyData, _options: ResolveJunctionPolicyOptions): Promise<Policy | undefined> => this.junctionPolicy, + );…and add
import { vi } from 'vitest';.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/test/unit/core/helpers/fake-identity-permission-provider.ts` around lines 34 - 48, The three methods on FakeIdentityPermissionProvider (getFor, isSuperset, resolveJunctionPolicy) are plain async functions which prevents test spies from asserting calls; wrap each method with vitest spies (vi.fn) and import { vi } from 'vitest'. Replace the plain methods by assigning getFor = vi.fn(async (_identity: IdentityPolicyData) => this.bindings), isSuperset = vi.fn(async (_parent, _child) => this.supersetResult) and resolveJunctionPolicy = vi.fn(async (_identity, _options) => this.junctionPolicy) so tests can assert call counts and args while preserving existing return behavior.apps/server-core/test/unit/core/identity/registration/service.spec.ts (1)
118-120: Subject assertion is locale-coupled.Same nit as in
password-recovery/service.spec.ts: hard-coded'Activation'couples the assertion to an English template. Asserting on the recipient and that a subject exists (or a stable template identifier) would be more resilient to copy/i18n changes.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/test/unit/core/identity/registration/service.spec.ts` around lines 118 - 120, The test currently asserts a locale-dependent subject string by checking mailClient.sent[0].subject contains 'Activation'; update the assertion to avoid i18n coupling by asserting the recipient and that a subject exists (e.g., expect(mailClient.sent[0]).toMatchObject({ to: data.email }) and expect(mailClient.sent[0].subject).toBeTruthy()) or, if the mail system provides a stable template identifier, assert that identifier instead (check mailClient.sent[0].templateId or similar). Ensure you modify the assertions referencing mailClient.sent and data.email in the registration service test to use subject existence or templateId rather than the hard-coded 'Activation' substring.apps/server-core/test/unit/core/identity/password-recovery/service.spec.ts (1)
126-128: Subject assertion is locale-coupled.
toContain('Reset')depends on the English template. If subjects ever become i18n-driven or are renamed, this assertion will silently break. Consider asserting on a stable structural marker (template name, header, or the recipient + a non-empty subject) instead of an English keyword.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/test/unit/core/identity/password-recovery/service.spec.ts` around lines 126 - 128, The subject assertion in the password-recovery test is coupled to English text; instead of expect(mailClient.sent[0].subject).toContain('Reset') update the assertion to use a stable marker such as checking the mail record metadata or structure (e.g., assert mailClient.sent[0] contains a template identifier or header field if available), or at minimum assert the subject is a non-empty string and that the recipient matches (keep expect(mailClient.sent).toHaveLength(1) and expect(mailClient.sent[0]).toMatchObject({ to: email })); locate references to mailClient.sent and the subject assertion in the test and replace the language-dependent check with a template/header or non-empty subject assertion.apps/server-core/test/unit/core/helpers/fake-permission-evaluator.ts (1)
21-65: Solid design — optional: consider areset()/allowAll()helper.The chained
denysemantics (each call wrapsprevious) is nice for layering, but it means there is no way to "undo" a priordenywithout callingsetBehavior(() => {}). For per-test instances this is moot, but if any test reuses an evaluator across sub-cases it could surprise. A small explicit helper (e.g.allowAll()) would document the intent.♻️ Tiny addition
+ allowAll() { + this.behavior = () => {}; + }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/test/unit/core/helpers/fake-permission-evaluator.ts` around lines 21 - 65, Add a small helper on FakePermissionEvaluator to reset behavior to a permissive no-op (e.g. allowAll() or reset()) so tests can undo prior deny() calls without using setBehavior directly; implement it to set this.behavior = () => Promise.resolve() (or () => {} if synchronous) and export the method alongside existing methods (FakePermissionEvaluator.allowAll / reset) so callers can call it to clear layered denies created by deny() and restore default permissive behavior.apps/server-core/test/unit/core/entities/user/service.spec.ts (1)
57-74: Consider promotingcreateSelfActorto the sharedfake-actor.tshelper.Several other entity service specs (robot, client, scope, user-attribute, etc.) likely need the same "actor whose identity matches a specific user id" shape. Centralizing this avoids divergence (e.g., the inline
'test-realm'realm name here mirrorscreateNonMasterRealmActorand could drift).♻️ Sketch of a shared helper
// in fake-actor.ts export function createSelfActor( userId: string, options: { userName?: string; realmId?: string; realmName?: string } = {}, ): FakeActorContext { const id = options.realmId || randomUUID(); return { permissionEvaluator: new FakePermissionEvaluator(), identity: { type: IdentityType.USER, data: { id: userId, name: options.userName || 'self-user', realm_id: id, realm: { id, name: options.realmName || 'test-realm' } as Realm, } as User, }, }; }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/test/unit/core/entities/user/service.spec.ts` around lines 57 - 74, Promote the local createSelfActor test helper into the shared fake-actor.ts by exporting a createSelfActor(userId: string, options?: { userName?: string; realmId?: string; realmName?: string }) function; keep the existing structure (FakePermissionEvaluator, IdentityType.USER, User with id/name, realm_id and realm object) but replace hard-coded 'test-realm' with options.realmName || 'test-realm' and use options.realmId || randomUUID(); then update tests (including this spec) to import the shared createSelfActor instead of the inline function to ensure consistency across entity service specs.apps/server-core/test/unit/core/helpers/fake-session-manager.ts (1)
13-30: Remove the redundantas stringcast onsession.id.On line 17,
(session.id as string) || randomUUID()unnecessarily castssession.idwhen it's alreadystring | undefinedfromPartial<Session>. Simplifying tosession.id || randomUUID()preserves the same behavior while making the type more transparent.All five methods from
ISessionManagerare implemented (create, ping, refresh, verify, findOneById).♻️ Proposed change
const id = (session.id as string) || randomUUID(); + const id = session.id || randomUUID();🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/test/unit/core/helpers/fake-session-manager.ts` around lines 13 - 30, Remove the redundant type assertion on session.id inside FakeSessionManager.create: replace the expression using (session.id as string) with plain session.id so the id assignment reads like session.id || randomUUID(); update the create method in class FakeSessionManager (the vi.fn async create implementation) to use session.id directly while keeping the rest of the logic (id, created, sessions.set, return created) unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@apps/server-core/test/unit/core/helpers/fake-oauth2-token-repository.ts`:
- Around line 34-40: The insert mock in fake-oauth2-token-repository can let a
caller-provided jti (even undefined) override the generated ID; update the logic
in the insert function (the vi.fn that builds stored and uses this.byId) so the
generated randomUUID() is used as a fallback instead of being overwritten—e.g.,
compute stored so the payload is spread first and then jti defaults to
randomUUID() or explicitly set jti = payload.jti ?? randomUUID(); keep the
existing check on stored.jti and byId.set(stored.jti, stored).
---
Nitpick comments:
In `@apps/server-core/test/unit/core/entities/user/service.spec.ts`:
- Around line 57-74: Promote the local createSelfActor test helper into the
shared fake-actor.ts by exporting a createSelfActor(userId: string, options?: {
userName?: string; realmId?: string; realmName?: string }) function; keep the
existing structure (FakePermissionEvaluator, IdentityType.USER, User with
id/name, realm_id and realm object) but replace hard-coded 'test-realm' with
options.realmName || 'test-realm' and use options.realmId || randomUUID(); then
update tests (including this spec) to import the shared createSelfActor instead
of the inline function to ensure consistency across entity service specs.
In
`@apps/server-core/test/unit/core/helpers/fake-identity-permission-provider.ts`:
- Around line 34-48: The three methods on FakeIdentityPermissionProvider
(getFor, isSuperset, resolveJunctionPolicy) are plain async functions which
prevents test spies from asserting calls; wrap each method with vitest spies
(vi.fn) and import { vi } from 'vitest'. Replace the plain methods by assigning
getFor = vi.fn(async (_identity: IdentityPolicyData) => this.bindings),
isSuperset = vi.fn(async (_parent, _child) => this.supersetResult) and
resolveJunctionPolicy = vi.fn(async (_identity, _options) =>
this.junctionPolicy) so tests can assert call counts and args while preserving
existing return behavior.
In `@apps/server-core/test/unit/core/helpers/fake-permission-evaluator.ts`:
- Around line 21-65: Add a small helper on FakePermissionEvaluator to reset
behavior to a permissive no-op (e.g. allowAll() or reset()) so tests can undo
prior deny() calls without using setBehavior directly; implement it to set
this.behavior = () => Promise.resolve() (or () => {} if synchronous) and export
the method alongside existing methods (FakePermissionEvaluator.allowAll / reset)
so callers can call it to clear layered denies created by deny() and restore
default permissive behavior.
In `@apps/server-core/test/unit/core/helpers/fake-session-manager.ts`:
- Around line 13-30: Remove the redundant type assertion on session.id inside
FakeSessionManager.create: replace the expression using (session.id as string)
with plain session.id so the id assignment reads like session.id ||
randomUUID(); update the create method in class FakeSessionManager (the vi.fn
async create implementation) to use session.id directly while keeping the rest
of the logic (id, created, sessions.set, return created) unchanged.
In `@apps/server-core/test/unit/core/identity/password-recovery/service.spec.ts`:
- Around line 126-128: The subject assertion in the password-recovery test is
coupled to English text; instead of
expect(mailClient.sent[0].subject).toContain('Reset') update the assertion to
use a stable marker such as checking the mail record metadata or structure
(e.g., assert mailClient.sent[0] contains a template identifier or header field
if available), or at minimum assert the subject is a non-empty string and that
the recipient matches (keep expect(mailClient.sent).toHaveLength(1) and
expect(mailClient.sent[0]).toMatchObject({ to: email })); locate references to
mailClient.sent and the subject assertion in the test and replace the
language-dependent check with a template/header or non-empty subject assertion.
In `@apps/server-core/test/unit/core/identity/registration/service.spec.ts`:
- Around line 118-120: The test currently asserts a locale-dependent subject
string by checking mailClient.sent[0].subject contains 'Activation'; update the
assertion to avoid i18n coupling by asserting the recipient and that a subject
exists (e.g., expect(mailClient.sent[0]).toMatchObject({ to: data.email }) and
expect(mailClient.sent[0].subject).toBeTruthy()) or, if the mail system provides
a stable template identifier, assert that identifier instead (check
mailClient.sent[0].templateId or similar). Ensure you modify the assertions
referencing mailClient.sent and data.email in the registration service test to
use subject existence or templateId rather than the hard-coded 'Activation'
substring.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 8806d551-d3cc-4f79-88e2-dcc9ea31112c
📒 Files selected for processing (39)
apps/server-core/test/unit/core/entities/client-permission/service.spec.tsapps/server-core/test/unit/core/entities/client-role/service.spec.tsapps/server-core/test/unit/core/entities/client-scope/service.spec.tsapps/server-core/test/unit/core/entities/client/service.spec.tsapps/server-core/test/unit/core/entities/identity-provider-role-mapping/service.spec.tsapps/server-core/test/unit/core/entities/permission-policy/service.spec.tsapps/server-core/test/unit/core/entities/permission/service.spec.tsapps/server-core/test/unit/core/entities/realm/service.spec.tsapps/server-core/test/unit/core/entities/robot-permission/service.spec.tsapps/server-core/test/unit/core/entities/robot-role/service.spec.tsapps/server-core/test/unit/core/entities/robot/service.spec.tsapps/server-core/test/unit/core/entities/role-attribute/service.spec.tsapps/server-core/test/unit/core/entities/role-permission/service.spec.tsapps/server-core/test/unit/core/entities/role/service.spec.tsapps/server-core/test/unit/core/entities/scope/service.spec.tsapps/server-core/test/unit/core/entities/user-attribute/service.spec.tsapps/server-core/test/unit/core/entities/user-permission/service.spec.tsapps/server-core/test/unit/core/entities/user-role/service.spec.tsapps/server-core/test/unit/core/entities/user/service.spec.tsapps/server-core/test/unit/core/helpers/fake-actor.tsapps/server-core/test/unit/core/helpers/fake-identity-permission-provider.tsapps/server-core/test/unit/core/helpers/fake-identity-resolver.tsapps/server-core/test/unit/core/helpers/fake-identity-role-provider.tsapps/server-core/test/unit/core/helpers/fake-mail-client.tsapps/server-core/test/unit/core/helpers/fake-oauth2-key-repository.tsapps/server-core/test/unit/core/helpers/fake-oauth2-token-issuer.tsapps/server-core/test/unit/core/helpers/fake-oauth2-token-repository.tsapps/server-core/test/unit/core/helpers/fake-oauth2-token-signer.tsapps/server-core/test/unit/core/helpers/fake-permission-evaluator.tsapps/server-core/test/unit/core/helpers/fake-session-manager.tsapps/server-core/test/unit/core/helpers/index.tsapps/server-core/test/unit/core/helpers/mock-actor.tsapps/server-core/test/unit/core/identity/password-recovery/service.spec.tsapps/server-core/test/unit/core/identity/registration/service.spec.tsapps/server-core/test/unit/core/oauth2/grant-types/identity.spec.tsapps/server-core/test/unit/core/oauth2/token/issuer/access/module.spec.tsapps/server-core/test/unit/core/oauth2/token/issuer/open-id/module.spec.tsapps/server-core/test/unit/core/oauth2/token/signer/module.spec.tsapps/server-core/test/unit/core/oauth2/token/verifier/module.spec.ts
💤 Files with no reviewable changes (1)
- apps/server-core/test/unit/core/helpers/mock-actor.ts
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
🧹 Nitpick comments (6)
apps/server-core/test/unit/core/helpers/fake-oauth2-token-issuer.ts (1)
22-31: Optional: record a defensive copy and drop the redundant cast.
issueCalls.push(input)stores the caller's reference, so any later mutation of the payload by code under test (or by the spread on Line 26) is visible in the recorded call. Capturing{ ...input }avoids that subtle coupling. Theas OAuth2TokenPayloadcast on Line 29 is also redundant since the object literal already satisfies the type.♻️ Proposed refactor
async issue(input: OAuth2TokenPayload): Promise<OAuth2TokenIssuerResponse> { - this.issueCalls.push(input); + this.issueCalls.push({ ...input }); const jti = randomUUID(); const payload: OAuth2TokenPayload = { ...input, jti, exp: this.exp, - } as OAuth2TokenPayload; + }; return [`signed-token-${jti}`, payload]; }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/test/unit/core/helpers/fake-oauth2-token-issuer.ts` around lines 22 - 31, The test helper's issue method records the caller's object reference and uses an unnecessary type cast; change issueCalls.push(input) to push a defensive copy (e.g., issueCalls.push({ ...input })) and build the payload with a plain object literal (const payload = { ...input, jti, exp: this.exp }) removing the redundant "as OAuth2TokenPayload" cast so the recorded call is decoupled from later mutations and the code is type-clean.apps/server-core/test/unit/core/helpers/fake-identity-resolver.ts (1)
24-31: Optional: omitrealmKeyfrom recorded calls when not supplied.Currently every recorded entry carries
realmKey: undefinedeven when the caller didn’t pass one. It’s harmless with Vitest deep-equality, but slightly noisier than necessary if anyone snapshotsresolveCallsor compares with strict equality.♻️ Suggested tweak
- async resolve(type: `${IdentityType}`, key: string, realmKey?: string): Promise<Identity | null> { - this.resolveCalls.push({ - type, - key, - realmKey, - }); - return this.identity; - } + async resolve(type: `${IdentityType}`, key: string, realmKey?: string): Promise<Identity | null> { + this.resolveCalls.push({ + type, + key, + ...(realmKey !== undefined ? { realmKey } : {}), + }); + return this.identity; + }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/test/unit/core/helpers/fake-identity-resolver.ts` around lines 24 - 31, The resolve method in FakeIdentityResolver is always recording realmKey as undefined; change the recording logic in resolve (method name: resolve, class/file: fake-identity-resolver.ts) to only include realmKey in the pushed object when the caller supplied it (i.e., omit the realmKey property if realmKey is undefined), so resolveCalls entries contain realmKey only when provided.apps/server-core/test/unit/core/oauth2/token/issuer/open-id/module.spec.ts (1)
67-74: Optional: drop the unusedsetIdentityin the missing-claims test.Both
issue(...)calls here should fail validation before identity resolution is attempted, so configuring the resolver with an identity is misleading — readers may think the resolver path is exercised. You can also use the default resolver fromcreateIssuer()and skip the local instance entirely.♻️ Suggested cleanup
it('should throw when sub_kind or sub is missing', async () => { - const resolver = new FakeIdentityResolver(); - resolver.setIdentity(identity); - const issuer = createIssuer({ identityResolver: resolver }); + const issuer = createIssuer(); await expect(issuer.issue({ sub: userId } as OAuth2TokenPayload)).rejects.toThrow(JWTError); await expect(issuer.issue({ sub_kind: OAuth2SubKind.USER } as OAuth2TokenPayload)).rejects.toThrow(JWTError); });🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/test/unit/core/oauth2/token/issuer/open-id/module.spec.ts` around lines 67 - 74, Remove the misleading resolver setup in the test "should throw when sub_kind or sub is missing": don't instantiate FakeIdentityResolver or call resolver.setIdentity(identity); instead use the default resolver returned by createIssuer() (i.e., just call createIssuer() without passing identityResolver) and then call issuer.issue(...) for both invalid payloads so the failure is clearly due to validation before identity resolution; update assertions to still expect JWTError from issuer.issue when sub or sub_kind is missing.apps/server-core/test/unit/core/helpers/fake-permission-evaluator.ts (1)
21-71: Optional: store call snapshots and consider an undo path fordeny.Two minor observations on the fake:
- The
*Callsarrays store thectxby reference. As long as services treatPermissionEvaluationContextas immutable (which appears to be the case today),toContainEqual(...)assertions are stable. If a service ever mutates the context after invoking the evaluator, recorded entries would silently change. A defensive{ ...ctx }(or structured clone) would harden the fake against that future risk.deny(method, error)wraps the previous behavior in a closure but provides no way to roll back to the prior behavior. Combined withdenyAll(which replaces the chain entirely), the only way to "undo" adenyis to callsetBehavior(...)again. Consider exposing areset()(clearsbehaviorto no-op and clears the*Callsarrays) for ergonomics in longer test setups.Both are nice-to-haves; current per-test actor instantiation avoids any cross-test bleed.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/test/unit/core/helpers/fake-permission-evaluator.ts` around lines 21 - 71, The fake currently stores PermissionEvaluationContext objects by reference and has no convenient undo for behavioral changes; update each place that pushes contexts (evaluate, evaluateOneOf, preEvaluate, preEvaluateOneOf) to push a shallow-cloned snapshot of ctx (e.g., { ...ctx } or structured clone) instead of the original object, and add a reset() method that clears evaluateCalls/evaluateOneOfCalls/preEvaluateCalls/preEvaluateOneOfCalls and restores behavior to the default noop (same as the constructor's default EvaluatorBehavior) so tests can cleanly reset the fake without calling setBehavior manually; keep deny and denyAll behavior intact.apps/server-core/test/unit/core/entities/user-role/service.spec.ts (1)
31-37: Same unused outer-scopeidentityPermissionProvideras inrobot-role/service.spec.ts.The closure-scoped
identityPermissionProvideris never read after assignment — the superset test instantiates its ownidentityPermissionProviderDeny. Consider inlining the construction inside the service factory call to drop the unused binding.♻️ Suggested simplification
- let identityPermissionProvider: FakeIdentityPermissionProvider; - beforeEach(() => { repository = new FakeEntityRepository<UserRole>(); - identityPermissionProvider = new FakeIdentityPermissionProvider(); - service = new UserRoleService({ repository, identityPermissionProvider }); + service = new UserRoleService({ + repository, + identityPermissionProvider: new FakeIdentityPermissionProvider(), + }); });🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/test/unit/core/entities/user-role/service.spec.ts` around lines 31 - 37, The outer-scope variable identityPermissionProvider (type FakeIdentityPermissionProvider) is assigned but never used; replace the separate binding by inlining new FakeIdentityPermissionProvider() into the UserRoleService constructor (where service = new UserRoleService({ repository, identityPermissionProvider })) and remove the unused identityPermissionProvider declaration so tests only create the provider instance where needed (the superset test can continue to instantiate identityPermissionProviderDeny as before).apps/server-core/test/unit/core/entities/robot-role/service.spec.ts (1)
31-37: Outer-scopeidentityPermissionProvideris assigned but never read.After the refactor, the closure-scoped
identityPermissionProvideris only written inbeforeEachand passed into the service constructor; no test reads it back (the superset-denial test creates its ownidentityPermissionProviderDeny). You can drop the outerletand inline the instance to reduce noise.♻️ Suggested simplification
- let identityPermissionProvider: FakeIdentityPermissionProvider; - beforeEach(() => { repository = new FakeEntityRepository<RobotRole>(); - identityPermissionProvider = new FakeIdentityPermissionProvider(); - service = new RobotRoleService({ repository, identityPermissionProvider }); + service = new RobotRoleService({ + repository, + identityPermissionProvider: new FakeIdentityPermissionProvider(), + }); });🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/test/unit/core/entities/robot-role/service.spec.ts` around lines 31 - 37, The outer-scope variable identityPermissionProvider is assigned in beforeEach but never read; remove the top-level declaration and inline new FakeIdentityPermissionProvider() when constructing the RobotRoleService in beforeEach (replace identityPermissionProvider with a direct new FakeIdentityPermissionProvider() in the RobotRoleService call), leaving other tests that create their own identityPermissionProviderDeny untouched; update any references in beforeEach to use the inlined instance and delete the unused identityPermissionProvider declaration.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@apps/server-core/test/unit/core/entities/robot-role/service.spec.ts`:
- Around line 31-37: The outer-scope variable identityPermissionProvider is
assigned in beforeEach but never read; remove the top-level declaration and
inline new FakeIdentityPermissionProvider() when constructing the
RobotRoleService in beforeEach (replace identityPermissionProvider with a direct
new FakeIdentityPermissionProvider() in the RobotRoleService call), leaving
other tests that create their own identityPermissionProviderDeny untouched;
update any references in beforeEach to use the inlined instance and delete the
unused identityPermissionProvider declaration.
In `@apps/server-core/test/unit/core/entities/user-role/service.spec.ts`:
- Around line 31-37: The outer-scope variable identityPermissionProvider (type
FakeIdentityPermissionProvider) is assigned but never used; replace the separate
binding by inlining new FakeIdentityPermissionProvider() into the
UserRoleService constructor (where service = new UserRoleService({ repository,
identityPermissionProvider })) and remove the unused identityPermissionProvider
declaration so tests only create the provider instance where needed (the
superset test can continue to instantiate identityPermissionProviderDeny as
before).
In `@apps/server-core/test/unit/core/helpers/fake-identity-resolver.ts`:
- Around line 24-31: The resolve method in FakeIdentityResolver is always
recording realmKey as undefined; change the recording logic in resolve (method
name: resolve, class/file: fake-identity-resolver.ts) to only include realmKey
in the pushed object when the caller supplied it (i.e., omit the realmKey
property if realmKey is undefined), so resolveCalls entries contain realmKey
only when provided.
In `@apps/server-core/test/unit/core/helpers/fake-oauth2-token-issuer.ts`:
- Around line 22-31: The test helper's issue method records the caller's object
reference and uses an unnecessary type cast; change issueCalls.push(input) to
push a defensive copy (e.g., issueCalls.push({ ...input })) and build the
payload with a plain object literal (const payload = { ...input, jti, exp:
this.exp }) removing the redundant "as OAuth2TokenPayload" cast so the recorded
call is decoupled from later mutations and the code is type-clean.
In `@apps/server-core/test/unit/core/helpers/fake-permission-evaluator.ts`:
- Around line 21-71: The fake currently stores PermissionEvaluationContext
objects by reference and has no convenient undo for behavioral changes; update
each place that pushes contexts (evaluate, evaluateOneOf, preEvaluate,
preEvaluateOneOf) to push a shallow-cloned snapshot of ctx (e.g., { ...ctx } or
structured clone) instead of the original object, and add a reset() method that
clears evaluateCalls/evaluateOneOfCalls/preEvaluateCalls/preEvaluateOneOfCalls
and restores behavior to the default noop (same as the constructor's default
EvaluatorBehavior) so tests can cleanly reset the fake without calling
setBehavior manually; keep deny and denyAll behavior intact.
In `@apps/server-core/test/unit/core/oauth2/token/issuer/open-id/module.spec.ts`:
- Around line 67-74: Remove the misleading resolver setup in the test "should
throw when sub_kind or sub is missing": don't instantiate FakeIdentityResolver
or call resolver.setIdentity(identity); instead use the default resolver
returned by createIssuer() (i.e., just call createIssuer() without passing
identityResolver) and then call issuer.issue(...) for both invalid payloads so
the failure is clearly due to validation before identity resolution; update
assertions to still expect JWTError from issuer.issue when sub or sub_kind is
missing.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 9bc46f22-9bd2-4c9c-a79b-85a8b7816ed4
📒 Files selected for processing (31)
apps/server-core/test/unit/core/entities/client-permission/service.spec.tsapps/server-core/test/unit/core/entities/client-role/service.spec.tsapps/server-core/test/unit/core/entities/client-scope/service.spec.tsapps/server-core/test/unit/core/entities/client/service.spec.tsapps/server-core/test/unit/core/entities/identity-provider-role-mapping/service.spec.tsapps/server-core/test/unit/core/entities/permission-policy/service.spec.tsapps/server-core/test/unit/core/entities/permission/service.spec.tsapps/server-core/test/unit/core/entities/realm/service.spec.tsapps/server-core/test/unit/core/entities/robot-permission/service.spec.tsapps/server-core/test/unit/core/entities/robot-role/service.spec.tsapps/server-core/test/unit/core/entities/robot/service.spec.tsapps/server-core/test/unit/core/entities/role-attribute/service.spec.tsapps/server-core/test/unit/core/entities/role-permission/service.spec.tsapps/server-core/test/unit/core/entities/role/service.spec.tsapps/server-core/test/unit/core/entities/scope/service.spec.tsapps/server-core/test/unit/core/entities/user-attribute/service.spec.tsapps/server-core/test/unit/core/entities/user-permission/service.spec.tsapps/server-core/test/unit/core/entities/user-role/service.spec.tsapps/server-core/test/unit/core/entities/user/service.spec.tsapps/server-core/test/unit/core/helpers/fake-identity-resolver.tsapps/server-core/test/unit/core/helpers/fake-identity-role-provider.tsapps/server-core/test/unit/core/helpers/fake-oauth2-key-repository.tsapps/server-core/test/unit/core/helpers/fake-oauth2-token-issuer.tsapps/server-core/test/unit/core/helpers/fake-oauth2-token-repository.tsapps/server-core/test/unit/core/helpers/fake-oauth2-token-signer.tsapps/server-core/test/unit/core/helpers/fake-permission-evaluator.tsapps/server-core/test/unit/core/helpers/fake-session-manager.tsapps/server-core/test/unit/core/oauth2/grant-types/identity.spec.tsapps/server-core/test/unit/core/oauth2/token/issuer/access/module.spec.tsapps/server-core/test/unit/core/oauth2/token/issuer/open-id/module.spec.tsapps/server-core/test/unit/core/oauth2/token/verifier/module.spec.ts
✅ Files skipped from review due to trivial changes (3)
- apps/server-core/test/unit/core/helpers/fake-identity-role-provider.ts
- apps/server-core/test/unit/core/helpers/fake-session-manager.ts
- apps/server-core/test/unit/core/entities/user/service.spec.ts
🚧 Files skipped from review as they are similar to previous changes (13)
- apps/server-core/test/unit/core/helpers/fake-oauth2-token-signer.ts
- apps/server-core/test/unit/core/entities/permission-policy/service.spec.ts
- apps/server-core/test/unit/core/entities/user-permission/service.spec.ts
- apps/server-core/test/unit/core/entities/role/service.spec.ts
- apps/server-core/test/unit/core/entities/client/service.spec.ts
- apps/server-core/test/unit/core/oauth2/grant-types/identity.spec.ts
- apps/server-core/test/unit/core/entities/client-permission/service.spec.ts
- apps/server-core/test/unit/core/entities/client-role/service.spec.ts
- apps/server-core/test/unit/core/helpers/fake-oauth2-token-repository.ts
- apps/server-core/test/unit/core/entities/robot/service.spec.ts
- apps/server-core/test/unit/core/entities/identity-provider-role-mapping/service.spec.ts
- apps/server-core/test/unit/core/oauth2/token/issuer/access/module.spec.ts
- apps/server-core/test/unit/core/oauth2/token/verifier/module.spec.ts
Summary by CodeRabbit
Tests
Chores