Skip to content

fix Faker::Json width when keys collide - #3326

Open
dpep wants to merge 4 commits into
faker-ruby:mainfrom
dpep:json-width-on-key-collision
Open

dpep wants to merge 4 commits into
faker-ruby:mainfrom
dpep:json-width-on-key-collision

Conversation

@dpep

@dpep dpep commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Motivation / Background

This Pull Request has been created because Faker::Json.shallow_json and add_depth_to_json return fewer than width keys when two generated keys collide. build_shallow_hash assigns into a hash width times, so a repeated first name overwrites an entry. This is also why test_nested_json_length fails whenever the random sequence draws a duplicate name.

It now retries on duplicates. The retries are bounded (10 × width attempts), so a key generator with fewer than width distinct values (e.g. Boolean.boolean with width: 3) still returns.

Additional information

The new test_shallow_json_keeps_width_when_keys_collide pins a seed where the first two boolean keys are equal. It fails without the fix ("<2> expected but was <1>") and passes with it. rake test and rubocop pass.

Checklist

  • This Pull Request is related to one change. Changes that are unrelated should be opened in separate PRs.
  • Commit message has a detailed description of what changed and why. If this PR fixes a related issue include it in the commit message. Ex: [Fix #issue-number]
  • Tests are added or updated if you fix a bug, refactor something, or add a feature.
  • Tests and Rubocop are passing before submitting your proposed changes.

Found via trekr, while turning back on a test it flagged as never running.

build_shallow_hash assigned `width` times into a hash, so a repeated key
(two equal first names) silently produced fewer than `width` entries in
shallow_json and every level of add_depth_to_json. Retry on duplicates,
bounded so a key generator with fewer than `width` values can't loop.

This is what makes test_nested_json_length fail when the random stream
lands on a duplicate name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@dpep dpep mentioned this pull request Oct 4, 2026
4 tasks done
Comment thread test/faker/default/test_faker_json.rb Outdated
Comment thread lib/faker/default/json.rb Outdated
Comment thread lib/faker/default/json.rb Outdated
@dpep dpep changed the title Keep Faker::Json width when generated keys collide fix Faker::Json width when keys collide Oct 4, 2026
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.

1 participant