Skip to content

feat: TCS, Simulation and Masking unit test cases#331

Merged
Justus-at-Tazama merged 9 commits intodevfrom
feat-paysys-test-coverage
May 7, 2026
Merged

feat: TCS, Simulation and Masking unit test cases#331
Justus-at-Tazama merged 9 commits intodevfrom
feat-paysys-test-coverage

Conversation

@MuhammadAli-Paysys
Copy link
Copy Markdown
Member

@MuhammadAli-Paysys MuhammadAli-Paysys commented May 6, 2026

SPDX-License-Identifier: Apache-2.0

This pull request significantly expands the test coverage for the masking repository and masking logic service, and introduces new tests for update and review functionality. It also adds tests for date filtering in rule logic and corrects a database query in the network map repository tests. The main improvements focus on ensuring robust handling of create, read, update, and review operations for masking configurations, as well as better validation of query construction and error handling.

Masking Repository and Logic Service Enhancements:

  • Expanded CRUD Test Coverage:

    • Added comprehensive tests for createMasking, findMaskByIdInDB, and updateMaskingInDB functions, including handling of valid/invalid inputs, error scenarios, and SQL query correctness.
    • Updated mocks and imports to include new repository methods in the test files. [1] [2]
  • Masking Logic Service:

    • Added tests for handleUpdateMask, covering successful updates, error handling, and updating with multiple fields.
    • Added tests for handleGetMaskById, verifying retrieval, not found, and error scenarios.
    • Added a comprehensive test suite for handleReviewMask, including approval, rejection (with/without comments), validation of review status, comment trimming, and error handling.

Rule Logic Service Improvements:

  • Date Filtering Tests:
    • Added tests to verify that rules can be filtered by startDate and endDate independently, ensuring correct SQL WHERE clause construction.

Network Map Repository:

  • Query Correction:
    • Updated the expected SQL query in tests to match the actual implementation, ensuring correct parameter usage in the UPDATE statement.

How was it tested?

  • Locally
  • Development Environment
  • Not needed, changes very basic
  • Husky successfully run
  • Unit tests passing and Documentation done
image

Release Notes

  • Tests

    • Added comprehensive unit test coverage for masking operations and repository functions.
    • Introduced test suites for rule flow management and simulation log handling.
    • Extended date filtering and configuration operation tests.
  • Bug Fixes

    • Simplified TCS configuration service API by streamlining update methods.
    • Refined network map repository update logic.

@MuhammadAli-Paysys MuhammadAli-Paysys requested review from a team as code owners May 6, 2026 11:22
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 6, 2026

📝 Walkthrough

Walkthrough

This PR extends test coverage across multiple repository and service modules, introduces new test files for rule-flow and simulation-logs repositories, and removes the updatedAt parameter from six TCS config service handler method signatures, updating all corresponding tests and repository interactions accordingly.

Changes

TCS Config Service Refactoring

Layer / File(s) Summary
Method Signatures
__tests__/unit/tcs-config.logic.service.test.ts
Six service handler methods (handleUpdateConfig, handleUpdatePublishingStatus, handleAddMapping, handleRemoveMapping, handleAddFunction, handleRemoveFunction) refactored to remove updatedAt parameter from signatures and test invocations. Updated all test expectations and mock assertions to reflect parameter removal.
Test Coverage Expansion
__tests__/unit/tcs-config.logic.service.test.ts
Added comprehensive edge-case tests for mapping and function handlers, including null/undefined list handling, empty list scenarios, invalid index validation, HTTP 409 conflict paths, and missing-config error cases.
Repository Test Coverage
__tests__/unit/tcs.config.repository.test.ts
Expanded imports to include additional repository functions (previously only two, now five exported functions). Added comprehensive test suite for createConfig covering insertion with/without id, XML/JSON handling, null mappings, default values, and payload scenarios.

Masking Service & Repository Tests

Layer / File(s) Summary
Repository Mock Extensions
__tests__/unit/masking.logic.service.test.ts
Extended masking.repository mock to export updateMaskingInDB and findMaskByIdInDB for service-level test mocking.
Service Handler Tests
__tests__/unit/masking.logic.service.test.ts
Added new test suite for handleUpdateMask covering success paths, update failures, not-found scenarios, and multi-field updates. Added rejection assertion to handlePostMask test for createMasking failures.
Repository CRUD Tests
__tests__/unit/repositories/masking.repository.test.ts
Added comprehensive test suites for createMasking, findMaskByIdInDB, and updateMaskingInDB, validating SQL generation, parameter handling, column selection, placeholder generation, and RETURNING clauses.

Core Repository Test Expansion

Layer / File(s) Summary
Rule Flow Repository Tests
__tests__/unit/repositories/rule-flow.repository.test.ts
New test file (670 lines) providing comprehensive Jest test suite for rule-flow repository methods (getRuleRequestByRuleId, getRuleConfigById, createRuleFlowInDB, findRuleFlowFromDB, updateRuleFlowInDB, findRuleFlowStatusFromDB) with coverage for success paths, null scenarios, JSON field handling, and SQL/parameter validation including NOW() and RETURNING clause verification.
Simulation Logs Repository Tests
__tests__/unit/repositories/simulation-logs.repository.test.ts
New test file (662 lines) providing comprehensive test suite for simulation logs repository methods (getSimulationLogsFromDb, createSimulationLogsInDb) covering sorting, filtering, pagination, column selection, JSON stringification, timestamp handling, and schema validation.
Rule Logic Service Date Filtering
__tests__/unit/rule.logic.service.test.ts
Added two new date-filter test cases within findRulesWithFilters suite validating startDate-only filtering (verifying created_at >= clause) and endDate-only filtering (verifying created_at <= clause) generation.
Network Map Update Path Change
__tests__/unit/repositories/network.map.repository.test.ts
Updated the repository update test expectations to reflect that row identification now uses cfg and tenantId instead of id-based lookup, with corresponding SQL text and parameter array adjustments.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Possibly related PRs

  • tazama-lf/admin-service#307: Both PRs modify the TCS config service API and tests to remove the updatedAt parameter—main PR updates tcs-config.logic.service tests/signatures while retrieved PR changes the service/controller/repository implementations.
  • tazama-lf/admin-service#306: Both PRs add and modify the same masking repository/service functions and corresponding unit tests (createMasking, findMaskByIdInDB, updateMaskingInDB, and masking.logic.service test coverage).
  • tazama-lf/admin-service#269: Both PRs modify the tcs-config code paths, updating tcs.config.repository and tcs-config.logic.service handlers with overlapping signature and implementation changes.

Suggested labels

test

Suggested reviewers

  • Justus-at-Tazama
  • MAdeel95
  • Sandy-at-Tazama

Poem

🐰 With whiskers twitching and tests abound,
Coverage spreads to every ground,
Parameters trimmed like carrots so neat,
Mock repositories now skip to the beat,
Rule flows and logs dance in delight—
This PR's a feast of testing might!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main objective of the PR, which is to add unit test cases across TCS, Simulation, and Masking modules.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat-paysys-test-coverage

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
__tests__/unit/tcs-config.logic.service.test.ts (3)

445-475: 🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Test has no assertions — only verifies absence of throw.

handleAddMapping returns a value into result but nothing is asserted on it (or on the repository call). The same gap exists in 'should add function with default empty arrays' at lines 676-705. As written, these tests pass as long as the call doesn't throw, which doesn't validate the "add to existing mappings" / "default empty arrays" intent.

✅ Suggested assertions for the existing-mappings test
       const result = await tcsConfigService.handleAddMapping(1, mockTenantId, newMapping as any);
+
+      expect(tcsConfigRepository.updateConfig).toHaveBeenCalledWith(
+        1,
+        mockTenantId,
+        { mapping: [existingMapping, { ...newMapping, source: ['newField'] }] },
+      );
+      expect(result.mapping).toHaveLength(2);
     });
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@__tests__/unit/tcs-config.logic.service.test.ts` around lines 445 - 475, The
test "should add mapping to existing mappings" currently only calls
tcsConfigService.handleAddMapping and doesn't assert behavior; update the test
to assert the returned result equals the mockUpdatedConfig and verify
tcsConfigRepository.findConfigById and tcsConfigRepository.updateConfig were
called with the expected arguments (id, tenant id and the updated mapping
payload where newMapping.source has been normalized to an array). Do the same
for the related "should add function with default empty arrays" test: assert the
returned value, and verify repository calls include the default-empty-array
normalization for function properties so the tests validate the intended
additions rather than merely ensuring no exception was thrown.

271-277: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Stale 4th argument to handleUpdateConfig.

The service signature is now handleUpdateConfig(id, tenantId, updates) (3 args) — the updatedAt parameter was removed in this PR. The trailing '2026-04-07T10:00:00.000Z' here is a leftover that no longer maps to any parameter and will either be a TS error or silently ignored at runtime.

✂️ Suggested fix
-      await expect(tcsConfigService.handleUpdateConfig(1, mockTenantId, { msgFam: 'Updated' }, '2026-04-07T10:00:00.000Z')).rejects.toThrow(
-        'Failed to update configuration',
-      );
+      await expect(tcsConfigService.handleUpdateConfig(1, mockTenantId, { msgFam: 'Updated' })).rejects.toThrow(
+        'Failed to update configuration',
+      );
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@__tests__/unit/tcs-config.logic.service.test.ts` around lines 271 - 277, The
test calls tcsConfigService.handleUpdateConfig with a stale 4th argument
(timestamp) but the service signature is handleUpdateConfig(id, tenantId,
updates); remove the trailing '2026-04-07T10:00:00.000Z' from the test
invocation so it calls handleUpdateConfig(1, mockTenantId, { msgFam: 'Updated'
}) and adjust any related expectations/mocks referencing the old 4th param
accordingly.

600-642: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Duplicate test cases — drop the second copy.

The test 'should set mapping to empty array when last mapping is removed' is defined twice with identical bodies (lines 600-620 and 622-642). The same duplication exists in handleRemoveFunction for 'should set functions to empty array when last function is removed' at lines 799-819 and 821-841. Remove one copy of each pair.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@__tests__/unit/tcs-config.logic.service.test.ts` around lines 600 - 642,
Remove the duplicated test blocks that repeat the same assertions: delete one of
the two identical "should set mapping to empty array when last mapping is
removed" tests that exercise tcsConfigService.handleRemoveMapping (the
duplicated test bodies that mock tcsConfigRepository.findConfigById and
updateConfig and assert updateConfig called with { mapping: [] }), and likewise
delete one of the two identical "should set functions to empty array when last
function is removed" tests that exercise tcsConfigService.handleRemoveFunction;
keep a single instance of each test case so only one test per behavior remains.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@__tests__/unit/repositories/masking.repository.test.ts`:
- Around line 238-245: The test uses expect.objectContaining with duplicate
"text" keys when asserting calls to mockHandlePostExecuteSqlStatement (e.g.
checking 'INSERT INTO trs_masking' and 'RETURNING id'), which silently drops
earlier text assertions; change the assertion to capture the actual argument
passed to mockHandlePostExecuteSqlStatement and use separate toContain (or
expect.stringContaining) assertions against the capturedArg.text for each
fragment (e.g., assert capturedArg.text contains 'INSERT INTO trs_masking' and
capturedArg.text contains 'RETURNING id' and values equals
['DEFAULT','pain.001.001.11','11']), and apply the same fix for the other block
that checks 'UPDATE trs_masking' / 'SET' so each SQL fragment is asserted
separately rather than using duplicate "text" keys in expect.objectContaining.

In `@__tests__/unit/repositories/rule-flow.repository.test.ts`:
- Around line 345-355: The test is incorrectly using multiple `text` keys inside
expect.objectContaining which only keeps the last one; instead capture the
actual SQL argument passed to mockHandlePostExecuteSqlStatement (e.g., const
sqlArg = mockHandlePostExecuteSqlStatement.mock.calls[0][0]) in the test for
findRuleFlowFromDB and then assert each SQL fragment separately with
expect(sqlArg.text).toContain('SELECT *'), expect(sqlArg.text).toContain('FROM
trs_rule_flow'), expect(sqlArg.text).toContain('WHERE rule_id = $1 AND tenant_id
= $2') and assert values separately (expect(sqlArg.values).toEqual([mockRuleId,
mockTenantId])); apply the same pattern to the other two failing tests that
currently repeat `text` (the blocks around the other occurrences noted in the
comment) so each fragment (e.g., RETURNING, LIMIT 1, etc.) is asserted via
toContain on the captured sqlArg.text rather than repeated keys in
expect.objectContaining.

---

Outside diff comments:
In `@__tests__/unit/tcs-config.logic.service.test.ts`:
- Around line 445-475: The test "should add mapping to existing mappings"
currently only calls tcsConfigService.handleAddMapping and doesn't assert
behavior; update the test to assert the returned result equals the
mockUpdatedConfig and verify tcsConfigRepository.findConfigById and
tcsConfigRepository.updateConfig were called with the expected arguments (id,
tenant id and the updated mapping payload where newMapping.source has been
normalized to an array). Do the same for the related "should add function with
default empty arrays" test: assert the returned value, and verify repository
calls include the default-empty-array normalization for function properties so
the tests validate the intended additions rather than merely ensuring no
exception was thrown.
- Around line 271-277: The test calls tcsConfigService.handleUpdateConfig with a
stale 4th argument (timestamp) but the service signature is
handleUpdateConfig(id, tenantId, updates); remove the trailing
'2026-04-07T10:00:00.000Z' from the test invocation so it calls
handleUpdateConfig(1, mockTenantId, { msgFam: 'Updated' }) and adjust any
related expectations/mocks referencing the old 4th param accordingly.
- Around line 600-642: Remove the duplicated test blocks that repeat the same
assertions: delete one of the two identical "should set mapping to empty array
when last mapping is removed" tests that exercise
tcsConfigService.handleRemoveMapping (the duplicated test bodies that mock
tcsConfigRepository.findConfigById and updateConfig and assert updateConfig
called with { mapping: [] }), and likewise delete one of the two identical
"should set functions to empty array when last function is removed" tests that
exercise tcsConfigService.handleRemoveFunction; keep a single instance of each
test case so only one test per behavior remains.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: fcf22ce2-3e75-4bef-b381-b98c8742270d

📥 Commits

Reviewing files that changed from the base of the PR and between e770034 and b3577a2.

📒 Files selected for processing (8)
  • __tests__/unit/masking.logic.service.test.ts
  • __tests__/unit/repositories/masking.repository.test.ts
  • __tests__/unit/repositories/network.map.repository.test.ts
  • __tests__/unit/repositories/rule-flow.repository.test.ts
  • __tests__/unit/repositories/simulation-logs.repository.test.ts
  • __tests__/unit/rule.logic.service.test.ts
  • __tests__/unit/tcs-config.logic.service.test.ts
  • __tests__/unit/tcs.config.repository.test.ts

Comment thread __tests__/unit/repositories/masking.repository.test.ts
Comment thread __tests__/unit/repositories/rule-flow.repository.test.ts
MuhammadAli-Paysys and others added 2 commits May 6, 2026 16:40
@Justus-at-Tazama Justus-at-Tazama merged commit adbc92c into dev May 7, 2026
13 of 20 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[DEV] Improve test coverage for TCS, simulation and masking

3 participants