Skip to content

Refactor: Remove access check in Preview handler and add unit tests f… - #175

Merged
AhmadRAbuhussein merged 1 commit into
releases/r8.0from
hamza/test/scriban-parity-and-unit-tests
Jun 1, 2026
Merged

Refactor: Remove access check in Preview handler and add unit tests f…#175
AhmadRAbuhussein merged 1 commit into
releases/r8.0from
hamza/test/scriban-parity-and-unit-tests

Conversation

@hamzahalq

@hamzahalq hamzahalq commented Jun 1, 2026

Copy link
Copy Markdown
Contributor

…or Scriban JSON mapping

  • Removed the access check for Admin and Member roles in the Preview handler.
  • Added unit tests for NativeJSONMapper to ensure correct mapping using startup templates.
  • Introduced tests for RunMapperEnrichment to validate JSON parsing and enrichment logic.
  • Created ScribanGeneratorParityTests to ensure parity with the output of the Scriban generator.
  • Added ScribanJsonHelperArrayMappingTests to verify array mapping functionality.
  • Implemented ScribanJsonHelperErrorHandlingTests to check error handling for invalid templates.
  • Developed ScribanJsonHelperLookupAndTypeRuleTests to validate lookup and type rule mappings.
  • Added ScribanJsonHelperRootMappingTests to test root mapping functionality.
  • Created a helper class for rendering JSON templates and asserting JSON equality.

Summary by CodeRabbit

  • Bug Fixes

    • Removed access control requirement from preview operations
  • Tests

    • Added extensive unit test coverage for JSON template rendering functionality, including nested array mapping, type conversions, lookup operations, partner and global variable injection, error handling, and special character escaping

…or Scriban JSON mapping

- Removed the access check for Admin and Member roles in the Preview handler.
- Added unit tests for NativeJSONMapper to ensure correct mapping using startup templates.
- Introduced tests for RunMapperEnrichment to validate JSON parsing and enrichment logic.
- Created ScribanGeneratorParityTests to ensure parity with the output of the Scriban generator.
- Added ScribanJsonHelperArrayMappingTests to verify array mapping functionality.
- Implemented ScribanJsonHelperErrorHandlingTests to check error handling for invalid templates.
- Developed ScribanJsonHelperLookupAndTypeRuleTests to validate lookup and type rule mappings.
- Added ScribanJsonHelperRootMappingTests to test root mapping functionality.
- Created a helper class for rendering JSON templates and asserting JSON equality.
@coderabbitai

coderabbitai Bot commented Jun 1, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

This PR removes an authorization check from the Preview.Handle request processor and adds extensive test coverage for Scriban JSON template rendering, including root variable mapping, type conversions, array handling, error cases, and integration scenarios.

Changes

Authorization Guard Removal

Layer / File(s) Summary
Preview handler authorization guard removal
SW.Bitween.Api/Resources/Mappers/Preview.cs
The _requestContext.EnsureAccess(...) call is removed from the start of Preview.Handle; subsequent enrichment and template-rendering logic remains unchanged.

Scriban JSON Rendering Test Suite

Layer / File(s) Summary
Test helper for Scriban JSON rendering
SW.Bitween.UnitTests/ScribanJsonTestHelper.cs
Internal static helper class providing template rendering, JSON object/token parsing, and deep-equality assertion utilities with formatted failure output.
Root variable and field mapping tests
SW.Bitween.UnitTests/ScribanJsonHelperRootMappingTests.cs
Tests covering flat-field renaming, nested dotted-path expansion, PascalCase/lowercase alias resolution, string variable interpolation, partner/global scoping, and null handling for missing variables.
Lookup mapping and type rule conversion tests
SW.Bitween.UnitTests/ScribanJsonHelperLookupAndTypeRuleTests.cs
Tests validating dictionary lookup hit/miss/fallback, numeric/boolean target typing, math/transform expressions, and type conversions (bool↔number↔string) including edge cases like invalid string-to-number producing null.
Array and nested structure mapping tests
SW.Bitween.UnitTests/ScribanJsonHelperArrayMappingTests.cs
Tests covering object/primitive array mapping with source/lookup/transform/fixed/partner/global injection, conditional filtering, nested fields, multi-level nesting, smart-array member access, empty arrays, and trailing-comma removal.
Error handling and character escaping tests
SW.Bitween.UnitTests/ScribanJsonHelperErrorHandlingTests.cs
Tests asserting that invalid templates throw parse-error exceptions, invalid-JSON templates throw appropriate errors, and special characters are correctly escaped in output.
Parity tests covering comprehensive template scenarios
SW.Bitween.UnitTests/ScribanGeneratorParityTests.cs
Extensive test suite validating source field renaming, fixed constants, partner/global lookups, lookup dictionaries, arithmetic transforms, array iteration, type-rule casting, transform expressions, root field access inside loops, and array filtering.
JSON enrichment and mapper integration tests
SW.Bitween.UnitTests/RunMapperEnrichmentTests.cs, SW.Bitween.UnitTests/NativeJsonMapperTests.cs
Tests validating JSON string/object/array parsing behavior, enrichment via __partner__ injection, NativeJsonMapper template-driven mapping, default empty-object fallback, and non-mutating instance behavior.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • simplify9/Bitween-api#141: Introduced the Preview handler with the _requestContext.EnsureAccess(...) call that this PR removes.

Suggested reviewers

  • AhmadRAbuhussein
  • mmalkhatib

Poem

🐰 A rabbit hops through templates bright,
Scriban rendering in the light,
No guards to block the preview way,
Tests ensure each map will play!
Arrays, types, and partners too,
JSON magic, tried and true!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 17.57% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main changes: removing an access check in the Preview handler and adding comprehensive unit tests for Scriban functionality.
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.

✏️ 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 hamza/test/scriban-parity-and-unit-tests

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick comments (2)
SW.Bitween.UnitTests/ScribanJsonHelperRootMappingTests.cs (1)

131-138: ⚡ Quick win

Test does not validate partner/global typed mapping behavior

Line 134 hardcodes null for both fields, so this test passes without exercising __partner__/__globals__ mapping at all. Please use typed conversion expressions (or generated parity expressions) so the assertion actually guards the intended behavior.

Proposed test adjustment
-        var template = "{ \"partnerBoolTarget\": null, \"globalNumberTarget\": null }";
+        var template =
+            "{ \"partnerBoolTarget\": {{ (__partner__?.flag == null ? null : (__partner__?.flag ? 1 : 0)) | json }}, " +
+            "\"globalNumberTarget\": {{ (__globals__?.S[\"K\"] | to_float) | json }} }";
 
         var output = Render(template, input);
 
-        AssertJsonEquals("{\"partnerBoolTarget\":null,\"globalNumberTarget\":null}", output);
+        AssertJsonEquals("{\"partnerBoolTarget\":1,\"globalNumberTarget\":1.0}", output);
🤖 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 `@SW.Bitween.UnitTests/ScribanJsonHelperRootMappingTests.cs` around lines 131 -
138, The test PartnerAndGlobalTypedTargets_AreRepresentedAsNullTemplateLiteral
currently hardcodes null in the template so it never exercises
__partner__/__globals__ mapping; update the template string (the variable named
template) to use typed conversion/parity expressions that reference the input's
__partner__ and __globals__ properties (e.g., convert __partner__.flag to a
typed template expression and __globals__.S.K to a typed numeric expression) so
Render(template, input) actually triggers the partner/global mapping logic, then
keep the AssertJsonEquals against the expected JSON produced by those typed
conversions; use the Render method and AssertJsonEquals as-is to validate the
behavior.
SW.Bitween.UnitTests/ScribanJsonHelperLookupAndTypeRuleTests.cs (1)

115-121: ⚡ Quick win

String-to-bool test is currently a tautology

Line 119 renders a literal null, so this test never validates string-to-bool behavior. Replace it with the actual cast expression under test (with both valid/invalid string cases) to make the test meaningful.

Proposed test adjustment
-        var input = "{\"name\":\"x\"}";
-
-        var value = RenderValue("{{ null | json }}", input);
+        var input = "{\"name\":\"x\"}";
+        var value = RenderValue(
+            "{{ (name == \"true\" ? true : (name == \"false\" ? false : null)) | json }}",
+            input);
 
         Assert.AreEqual(JTokenType.Null, value.Type);
🤖 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 `@SW.Bitween.UnitTests/ScribanJsonHelperLookupAndTypeRuleTests.cs` around lines
115 - 121, The test TypeRules_StringToBool_IsNull is rendering a literal null
instead of exercising the string-to-bool cast; update the RenderValue call to
use the actual cast/filter expression under test (replace "{{ null | json }}"
with the cast expression you use to convert strings to bool) and add two
assertions: one using a valid boolean string input (e.g. input with
"name":"true") asserting JTokenType.Boolean, and one using an invalid string
input (e.g. "name":"x") asserting JTokenType.Null; keep the test helper
RenderValue and the method name unchanged so the test targets the same code
paths.
🤖 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.

Nitpick comments:
In `@SW.Bitween.UnitTests/ScribanJsonHelperLookupAndTypeRuleTests.cs`:
- Around line 115-121: The test TypeRules_StringToBool_IsNull is rendering a
literal null instead of exercising the string-to-bool cast; update the
RenderValue call to use the actual cast/filter expression under test (replace
"{{ null | json }}" with the cast expression you use to convert strings to bool)
and add two assertions: one using a valid boolean string input (e.g. input with
"name":"true") asserting JTokenType.Boolean, and one using an invalid string
input (e.g. "name":"x") asserting JTokenType.Null; keep the test helper
RenderValue and the method name unchanged so the test targets the same code
paths.

In `@SW.Bitween.UnitTests/ScribanJsonHelperRootMappingTests.cs`:
- Around line 131-138: The test
PartnerAndGlobalTypedTargets_AreRepresentedAsNullTemplateLiteral currently
hardcodes null in the template so it never exercises __partner__/__globals__
mapping; update the template string (the variable named template) to use typed
conversion/parity expressions that reference the input's __partner__ and
__globals__ properties (e.g., convert __partner__.flag to a typed template
expression and __globals__.S.K to a typed numeric expression) so
Render(template, input) actually triggers the partner/global mapping logic, then
keep the AssertJsonEquals against the expected JSON produced by those typed
conversions; use the Render method and AssertJsonEquals as-is to validate the
behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 76d64941-a6c6-4686-808c-11f6326118e3

📥 Commits

Reviewing files that changed from the base of the PR and between 2aa7d9a and bd069ea.

📒 Files selected for processing (9)
  • SW.Bitween.Api/Resources/Mappers/Preview.cs
  • SW.Bitween.UnitTests/NativeJsonMapperTests.cs
  • SW.Bitween.UnitTests/RunMapperEnrichmentTests.cs
  • SW.Bitween.UnitTests/ScribanGeneratorParityTests.cs
  • SW.Bitween.UnitTests/ScribanJsonHelperArrayMappingTests.cs
  • SW.Bitween.UnitTests/ScribanJsonHelperErrorHandlingTests.cs
  • SW.Bitween.UnitTests/ScribanJsonHelperLookupAndTypeRuleTests.cs
  • SW.Bitween.UnitTests/ScribanJsonHelperRootMappingTests.cs
  • SW.Bitween.UnitTests/ScribanJsonTestHelper.cs
💤 Files with no reviewable changes (1)
  • SW.Bitween.Api/Resources/Mappers/Preview.cs

@AhmadRAbuhussein
AhmadRAbuhussein merged commit 9050872 into releases/r8.0 Jun 1, 2026
2 checks passed
@MusaMisto
MusaMisto deleted the hamza/test/scriban-parity-and-unit-tests branch July 2, 2026 09:29
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.

2 participants