Skip to content

fix(mock): use one-sided bounds when only minLength/maxLength or minItems/maxItems is specified#3120

Open
youngcm2 wants to merge 7 commits intoorval-labs:masterfrom
youngcm2:fix/incorrect-array-values-msw
Open

fix(mock): use one-sided bounds when only minLength/maxLength or minItems/maxItems is specified#3120
youngcm2 wants to merge 7 commits intoorval-labs:masterfrom
youngcm2:fix/incorrect-array-values-msw

Conversation

@youngcm2
Copy link
Copy Markdown

@youngcm2 youngcm2 commented Mar 19, 2026

Closes #3121

Summary

When a schema specifies only maxLength/maxItems without a corresponding min, or only minLength/minItems without a corresponding max, the mock scalar generator was incorrectly falling back to global defaults (stringMin: 10, arrayMin: 1, etc.) for the unspecified bound. This could produce invalid faker calls like faker.string.alpha({length: {min: 10, max: 5}}) where min > max.

Changes

  • Fix strMin/strMax fallback logic: global defaults now only apply when neither bound is schema-specified
  • Fix arrMin/arrMax fallback logic with the same rule
  • Add unit tests for maxLength-only and minLength-only string schema cases
  • Add integration spec (mock-constraints.yaml) and snapshot for one-sided constraint scenarios

Summary by CodeRabbit

  • New Features

    • Added a new OpenAPI mock spec and generated MSW mock endpoint and model to produce constraint-aware sample responses.
  • Bug Fixes

    • Mock generation now respects one-sided string and array constraints so generated values honor explicitly provided min/max bounds.
  • Tests

    • Added tests and snapshots validating one-sided constraint handling in mock data generation.
  • Chore

    • Added mock generation config for the new constraint-focused spec.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Mar 19, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adjust mock scalar generation so global min/max defaults are only applied when neither bound is specified; added tests, an OpenAPI spec, generated model and endpoint snapshots, and a test config covering one-sided string/array constraints.

Changes

Cohort / File(s) Summary
Scalar logic & tests
packages/mock/src/faker/getters/scalar.ts, packages/mock/src/faker/getters/scalar.test.ts
Suppress computed default for the opposite bound when a schema explicitly provides minLength/maxLength or minItems/maxItems; update logic to emit only the specified bound and add tests asserting one-sided behavior.
OpenAPI spec
tests/specifications/mock-constraints.yaml
New OpenAPI 3.1 spec declaring GET /items and a ConstrainedItem schema with one-sided and two-sided string/array constraints.
Generated models (snapshots)
tests/__snapshots__/mock/mock-constraints/model/constrainedItem.ts, tests/__snapshots__/mock/mock-constraints/model/index.ts
Add generated TypeScript model snapshot and barrel export for ConstrainedItem.
Generated endpoint snapshots
tests/__snapshots__/mock/mock-constraints/endpoints.ts
Add generated MSW endpoint snapshot: getItems, getGetItemsResponseMock, getGetItemsMockHandler, and getMockConstraintsMock.
Test config
tests/configs/mock.config.ts
Add mockConstraints config to generate MSW mocks from the new spec and emit endpoints/models to ../generated/mock/mock-constraints/.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • melloware

Poem

🐰 I trimmed the bounds with careful paws,
One-sided limits follow schema laws,
Faker now sings just what you wrote,
No min/max tangle to make it choke,
Hooray — carrots and passing laws! 🥕

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% 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 change: fixing one-sided bounds behavior in mock generation by using only the specified constraint (minLength/maxLength or minItems/maxItems) without applying global defaults to the opposite bound.
Linked Issues check ✅ Passed The pull request fully addresses the requirements in #3121: modifies strMin/strMax and arrMin/arrMax to apply global defaults only when both bounds are unspecified, adds unit tests for one-sided constraints, and includes integration test coverage.
Out of Scope Changes check ✅ Passed All changes are directly related to fixing the one-sided bounds issue: the core fix in scalar.ts, supporting tests, and integration specifications are all within scope.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


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.

🧹 Nitpick comments (1)
packages/mock/src/faker/getters/scalar.test.ts (1)

447-472: Good test coverage for string one-sided constraints.

The tests correctly verify that only the specified bound is included in the output. Consider adding similar unit tests for array one-sided constraints (minItems only and maxItems only) to complement the integration snapshot tests.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/mock/src/faker/getters/scalar.test.ts` around lines 447 - 472, Add
two unit tests alongside the existing string-bound tests that call getMockScalar
with baseArg and an item of type 'array' (use the same baseArg and item.name
'test-item'): one where only maxItems is set (e.g., maxItems: 5) and assert
result.value contains the corresponding faker.array.* call with only max
present, and another where only minItems is set (e.g., minItems: 3) and assert
result.value contains only min; target the getMockScalar function and the item's
minItems/maxItems fields so the tests mirror the string one-sided constraint
cases.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@packages/mock/src/faker/getters/scalar.test.ts`:
- Around line 447-472: Add two unit tests alongside the existing string-bound
tests that call getMockScalar with baseArg and an item of type 'array' (use the
same baseArg and item.name 'test-item'): one where only maxItems is set (e.g.,
maxItems: 5) and assert result.value contains the corresponding faker.array.*
call with only max present, and another where only minItems is set (e.g.,
minItems: 3) and assert result.value contains only min; target the getMockScalar
function and the item's minItems/maxItems fields so the tests mirror the string
one-sided constraint cases.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 8b1b4280-19cb-4a88-9cc1-0586cbdbe791

📥 Commits

Reviewing files that changed from the base of the PR and between 82fde63 and 0575d91.

📒 Files selected for processing (7)
  • packages/mock/src/faker/getters/scalar.test.ts
  • packages/mock/src/faker/getters/scalar.ts
  • tests/__snapshots__/mock/mock-constraints/endpoints.ts
  • tests/__snapshots__/mock/mock-constraints/model/constrainedItem.ts
  • tests/__snapshots__/mock/mock-constraints/model/index.ts
  • tests/configs/mock.config.ts
  • tests/specifications/mock-constraints.yaml

@melloware
Copy link
Copy Markdown
Collaborator

Running build now.

@melloware
Copy link
Copy Markdown
Collaborator

Looks like linter issues

@melloware melloware added msw MSW related issues mock Related to mock generation labels Mar 19, 2026
@melloware
Copy link
Copy Markdown
Collaborator

Looks like Linter is still failing build

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: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/mock/src/faker/getters/scalar.ts`:
- Around line 270-277: The code forces a lower bound of 1 when only a max
constraint is provided; update the min-default logic so a missing min stays
undefined if a max is present. Concretely, change arrMin calculation (using
item.minItems, item.maxItems, safeMockOptions.arrayMin/arrayMax) so it uses
undefined instead of 1 when maxItems is specified but minItems is not, and apply
the same change to the analogous min/max handling for lengths (the
minLength/maxLength variables and their use of safeMockOptions). This preserves
one-sided max-only constraints and prevents invalid ranges like min:1 / max:0.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: d498401e-8abd-409b-be74-89e924643ebc

📥 Commits

Reviewing files that changed from the base of the PR and between 932fa58 and 0363caa.

📒 Files selected for processing (1)
  • packages/mock/src/faker/getters/scalar.ts

Comment thread packages/mock/src/faker/getters/scalar.ts
@youngcm2 youngcm2 force-pushed the fix/incorrect-array-values-msw branch from 0363caa to c1bc38f Compare March 20, 2026 14:29
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.

🧹 Nitpick comments (1)
packages/mock/src/faker/getters/scalar.ts (1)

154-159: Consider applying the same cross-suppression pattern to number constraints.

The number handling still uses simple nullish coalescing without the cross-suppression logic applied to arrays and strings. This could produce invalid faker ranges if a schema specifies minimum: 100 without a maximum, and the global numberMax is set to a value less than 100.

This is out of scope for the current PR but worth considering for consistency in a follow-up.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/mock/src/faker/getters/scalar.ts` around lines 154 - 159, The number
bound computation (numMin/numMax in the scalar getter) should mirror the
cross-suppression pattern used for arrays/strings: compute initial min/max from
(exclusiveMinimum ?? minimum ?? safeMockOptions.numberMin) and (exclusiveMaximum
?? maximum ?? safeMockOptions.numberMax), then sanitize so the two bounds cannot
produce an invalid range — if the schema provides a min that is greater than the
chosen max, clamp/adjust the max to the schema min (or vice versa if schema max
is less than the chosen min); update the logic around numMin and numMax to use
these rules so global defaults from safeMockOptions are suppressed/clamped by
explicit schema constraints and the final range is always valid.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@packages/mock/src/faker/getters/scalar.ts`:
- Around line 154-159: The number bound computation (numMin/numMax in the scalar
getter) should mirror the cross-suppression pattern used for arrays/strings:
compute initial min/max from (exclusiveMinimum ?? minimum ??
safeMockOptions.numberMin) and (exclusiveMaximum ?? maximum ??
safeMockOptions.numberMax), then sanitize so the two bounds cannot produce an
invalid range — if the schema provides a min that is greater than the chosen
max, clamp/adjust the max to the schema min (or vice versa if schema max is less
than the chosen min); update the logic around numMin and numMax to use these
rules so global defaults from safeMockOptions are suppressed/clamped by explicit
schema constraints and the final range is always valid.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 47be989d-fd08-4d30-9416-45ae4c988254

📥 Commits

Reviewing files that changed from the base of the PR and between 0363caa and c1bc38f.

📒 Files selected for processing (2)
  • packages/mock/src/faker/getters/scalar.test.ts
  • packages/mock/src/faker/getters/scalar.ts
✅ Files skipped from review due to trivial changes (1)
  • packages/mock/src/faker/getters/scalar.test.ts

@melloware melloware force-pushed the fix/incorrect-array-values-msw branch from c1bc38f to 4070f72 Compare March 23, 2026 12:29
@melloware
Copy link
Copy Markdown
Collaborator

Looks like Snapshots are failing now

@youngcm2 youngcm2 force-pushed the fix/incorrect-array-values-msw branch from 4070f72 to 7eb3d4b Compare March 23, 2026 15:27
@melloware melloware force-pushed the fix/incorrect-array-values-msw branch 3 times, most recently from 28ff472 to 878651c Compare March 24, 2026 04:55
@youngcm2 youngcm2 force-pushed the fix/incorrect-array-values-msw branch from 878651c to e718086 Compare March 30, 2026 17:04
@melloware
Copy link
Copy Markdown
Collaborator

@snebjorn can you chime in here the SNAPSHOTs seem to be frustrating users?

@snebjorn
Copy link
Copy Markdown
Contributor

Snapshots are working as expected. They're saying that min: 1 was removed in the output

- { length: faker.number.int({ min: 1, max: 100 }) }
+ { length: faker.number.int({ max: 100 }) }

If this is intended, the snapshot should be updated.
If this was unintended, then a bug was found.

@melloware
Copy link
Copy Markdown
Collaborator

@youngcm2 any update on this i agree with @snebjorn your code changes have made the snapshots now broken see his guidance.

@snebjorn snebjorn removed their assignment Apr 6, 2026
@melloware melloware force-pushed the fix/incorrect-array-values-msw branch from 91b3420 to 2f6d2c9 Compare May 4, 2026 20:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

mock Related to mock generation msw MSW related issues

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Incorrect string/array min value in MSW mocks when only maxLength/maxItems is specified

3 participants