Skip to content

test: use shared response test helpers - #1930

Merged
jerome-benoit merged 7 commits into
mainfrom
test/helper-usage-cleanup
Jun 29, 2026
Merged

jerome-benoit merged 7 commits into
mainfrom
test/helper-usage-cleanup

Conversation

@jerome-benoit

@jerome-benoit jerome-benoit commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

PR Checklist

  • Please add a description of your changes.
  • Please ensure title follows conventional commits.
  • We need your changes to come with unit tests in order to keep this project in quality and easy to maintain.
  • If your changes contain any new feature please be sure to document it. Not applicable: test cleanup only.
  • Please add a link to the open issue or task that this pull request will resolve. Closes Use shared test helpers for UI and OCPP response-service tests #1929.

Does this PR introduce a breaking change?

  • Yes
  • No

Description

This PR cleans up test helpers and removes test-side monkey-patching of internal factories:

  • UI server response tests: replace ad hoc await once(res, 'finish') waits with the existing
    awaitFinish() / drainResponses() helpers; add a local emitRequest() wrapper in
    UIHttpServer.test.ts for access-gate request emission.
  • OCPP 2.0 ResponseService tests: extract the duplicated buildTransactionEventRequest payload
    builder into OCPP20ResponseServiceTestUtils.ts, and move the createTestableResponseService
    wrapper into the standard src/charging-station/ocpp/2.0/__testable__/ location to match the
    OCPP20RequestService / OCPP20VariableManager precedent.
  • OCPP 2.0 IncomingRequest tests (ClearCache, LocalAuthList): migrate from monkey-patched
    Object.assign(OCPPAuthServiceFactory, …) to the proper setInstanceForTesting /
    clearAllInstances injection API, plus two shared helpers injectMockAuthService and
    withThrowingAuthServiceFactory in MockFactories.ts.

No production behavior is changed.

Validation

  • pnpm format
  • pnpm lint
  • pnpm typecheck
  • GIT_MASTER=1 git diff --check origin/main..HEAD
  • pnpm exec cross-env NODE_ENV=test node --import tsx --test --test-force-exit tests/charging-station/ui-server/UIHttpServer.test.ts tests/charging-station/ui-server/UIMetricsEndpoint.test.ts tests/charging-station/ui-server/UIMCPServer.test.ts tests/charging-station/ui-server/UIWebSocketServer.test.ts
  • pnpm exec cross-env NODE_ENV=test node --import tsx --test --test-force-exit tests/charging-station/ocpp/2.0/OCPP20ResponseService-TransactionEvent.test.ts tests/charging-station/ocpp/2.0/OCPP20ResponseService-ForceTxOnInvalid.test.ts tests/charging-station/ocpp/2.0/OCPP20IncomingRequestService-ClearCache.test.ts tests/charging-station/ocpp/2.0/OCPP20IncomingRequestService-LocalAuthList.test.ts

Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
@hyperspace-pr-bot

Copy link
Copy Markdown
Contributor

Summary

The following content is AI-generated and provides a summary of the pull request:


Refactor: Use Shared Test Helpers for UI Server and OCPP 2.0 Response Service Tests

Refactor

♻️ This PR consolidates duplicated test utilities across UI server and OCPP 2.0 response-service test suites into shared helpers. No production behavior is changed.

Key cleanups:

  • Replaces ad hoc once(res, 'finish') waits with the shared awaitFinish() helper across all UI server tests
  • Replaces Promise.all([once(resA, 'finish'), once(resB, 'finish')]) with drainResponses() helper
  • Extracts the duplicated TestableOCPP20ResponseService interface, buildTransactionEventRequest(), and createTestableResponseService() functions (previously defined independently in two test files) into a new shared OCPP20ResponseServiceTestUtils.ts
  • Adds a public emitRequest() wrapper to TestableUIHttpServer in UIHttpServer.test.ts, replacing direct httpServer.emit('request', ...) calls in access-gate tests

Changes

  • tests/charging-station/ocpp/2.0/OCPP20ResponseServiceTestUtils.ts (new): Shared test utility module exporting TestableOCPP20ResponseService interface, buildTransactionEventRequest(), and createTestableOCPP20ResponseService() — consolidating helpers previously duplicated across two test files.
  • tests/charging-station/ocpp/2.0/OCPP20ResponseService-TransactionEvent.test.ts: Removed local duplicates of the above helpers; now imports from OCPP20ResponseServiceTestUtils.ts. Cleaned up unused type imports.
  • tests/charging-station/ocpp/2.0/OCPP20ResponseService-ForceTxOnInvalid.test.ts: Same as above — removed local duplicates, imports shared helpers, cleaned up unused imports.
  • tests/charging-station/ui-server/UIHttpServer.test.ts: Removed once import; added public emitRequest() method to TestableUIHttpServer; replaced direct httpServer.emit calls and once(res, 'finish') waits with emitRequest() and awaitFinish().
  • tests/charging-station/ui-server/UIMetricsEndpoint.test.ts: Removed once import; replaced all once(res, 'finish') and Promise.all([once(...), once(...)]) calls with awaitFinish() and drainResponses() helpers.

GitHub Issues

  • #1929: Use shared test helpers for UI and OCPP response-service tests

  • 🔄 Regenerate and Update Summary
  • ✏️ Insert as PR Description (deletes this comment)
  • 🗑️ Delete comment
PR Bot Information

Version: 1.26.11

@hyperspace-pr-bot hyperspace-pr-bot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The PR is well-structured and achieves its goal of eliminating code duplication. There is one minor issue: the emitRequest helper in TestableUIHttpServer uses Reflect.get to access httpServer unnecessarily, since the field is already protected and directly accessible — the existing TestableUIWebSocketServer equivalent shows the correct pattern.

PR Bot Information

Version: 1.26.11

Comment on lines +38 to +43
public emitRequest (req: IncomingMessage, res: MockServerResponse): void {
const httpServer = Reflect.get(this, 'httpServer') as {
emit: (eventName: string, req: IncomingMessage, res: MockServerResponse) => boolean
}
httpServer.emit('request', req, res)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unnecessary indirection: httpServer is protected on AbstractUIServer, so TestableUIHttpServer can access it directly as this.httpServer — no Reflect.get needed. Compare with TestableUIWebSocketServer.emitRequest in UIServerTestUtils.ts (line 72) which uses this.httpServer.emit(...) directly.

Suggested change
public emitRequest (req: IncomingMessage, res: MockServerResponse): void {
const httpServer = Reflect.get(this, 'httpServer') as {
emit: (eventName: string, req: IncomingMessage, res: MockServerResponse) => boolean
}
httpServer.emit('request', req, res)
}
public emitRequest (req: IncomingMessage, res: MockServerResponse): void {
this.httpServer.emit('request', req, res)
}

Double-check suggestion before committing. Edit this comment for amendments.


Please provide feedback on the review comment by checking the appropriate box:

  • 🌟 Awesome comment, a human might have missed that.
  • ✅ Helpful comment
  • 🤷 Neutral
  • ❌ This comment is not helpful

Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
Aligns OCPP 2.0 ResponseService test wiring with the established pattern used
by RequestService and VariableManager:

- New src/charging-station/ocpp/2.0/__testable__/OCPP20ResponseServiceTestable.ts
  exporting createTestableResponseService + TestableOCPP20ResponseService;
  mirrors OCPP20RequestServiceTestable.ts structure (function declarations,
  file-level JSDoc with @example, double-cast through unknown).
- __testable__/index.ts re-exports the new module.
- OCPP20ResponseService-TransactionEvent.test.ts and -ForceTxOnInvalid.test.ts
  now import createTestableResponseService from __testable__/index.js;
  call sites renamed (drops redundant OCPP20 prefix, consistent with
  createTestableRequestService).
- OCPP20ResponseServiceTestUtils.ts now contains only the test-only
  buildTransactionEventRequest payload builder; adopts @file header and
  arrow-style export to harmonize with MockFactories.ts neighbour.

Test-only refactor; no production behavior change.

Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
Centralizes the two patterns used by OCPP 2.0 IncomingRequest tests to
inject mock OCPPAuthService instances into the factory cache:

- injectMockAuthService(station, service) — wraps the station-id lookup +
  OCPPAuthServiceFactory.setInstanceForTesting plumbing; replaces the
  duplicated boilerplate in ClearCache.test.ts and LocalAuthList.test.ts.
- withThrowingAuthServiceFactory(errorMessage, fn) — scoped monkey-patch +
  try/finally restore for the 3 sites that must exercise a failing
  getInstance (factory unavailable, no Authorization Cache support).
  Required because setInstanceForTesting only injects a returned instance;
  it cannot make getInstance itself throw.

Side effect of the helper adoption:

- LocalAuthList.test.ts drops the suite-scoped originalGetInstance save
  and afterEach restore — no longer needed since every monkey-patch is
  now scoped to its own test via withThrowingAuthServiceFactory.
- ClearCache.test.ts drops the local try/finally on the no-cache-support
  test for the same reason.

Test-only refactor; no production behavior change.

Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
V2-1: harmonize JSDoc verbs across the auth injection helpers — `inject*`
docstrings now start with 'Inject' to match the function name, and the local
`setupMockAuthService` wrappers (which build the mock + inject it) now start
with 'Configure and inject' to reflect their broader role. Avoids the verb
collision between the shared `injectMockAuthService` and the local
`setupMockAuthService` helpers.

V2-2: drop the dead `OCPPAuthService` return type from LocalAuthList's local
`setupMockAuthService` — no call site captured the return value. Also drops
the now-unused `OCPPAuthService` type import.

Test-only refactor; no production behavior change.

Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
Moves the `afterEach` block below `beforeEach` in ClearCache.test.ts to match
the before-then-after ordering used by LocalAuthList, TransactionEvent and
ForceTxOnInvalid test files. Cosmetic; no behavior change.

Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
@jerome-benoit
jerome-benoit merged commit c2ea863 into main Jun 29, 2026
44 checks passed
@jerome-benoit
jerome-benoit deleted the test/helper-usage-cleanup branch June 29, 2026 18:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Use shared test helpers for UI and OCPP response-service tests

1 participant