pbt 0.9.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 4b46223742e56120329f6e7d8bc534c26440b87309f001d715656c3c472b18e4
4
- data.tar.gz: 307990ded90589295c40d806579e2e586fd52c38d8a20ad0359a1dcc0de57718
3
+ metadata.gz: 6ef5bc626a0a2e8676646b9e289c9427acfe2c7ae519611aec3413314aa76693
4
+ data.tar.gz: 21e8013d277de6780f41cca76f78c0ccd23bc1d7f8dfcd4945c19d69349564ec
5
5
  SHA512:
6
- metadata.gz: fc5a37505bd13299292e7304b43f7c020e96531aa8bd6bbd7e397474775854200d91c647387906b3dd389753bc39db4e3514f962f0034013956a0ca1254a253f
7
- data.tar.gz: 3ea6eed118b195d4e9676f604d564dafd87d2bb3b1ada8d44661d588c169f3fc46d71a4138674a1dbc253a6a22a2a6d674ca170e34f1eaf98d51380e479151cb
6
+ metadata.gz: 83b5153b1e953e71f97f9507a3facbc363a1c7c376278cf67e8db2adafe73280cefef204d6deea404b19e3e4e98d9c1995345501de40d4fa6e1e6b35a7c326e7
7
+ data.tar.gz: 25020fbc085c847bc9b685adbca777276ac569b1d4d619b2c1048b4e5158aefdb97d5c0816e497fb7e08b687db45c21226c7b018f0986ecc74c69a65bb5b40d9
data/CHANGELOG.md CHANGED
@@ -1,5 +1,26 @@
1
1
  ## [Unreleased]
2
2
 
3
+ ## [1.0.0] - 2026-11-27
4
+
5
+ First stable `v1.0.0` release of `pbt` (zero runtime dependencies, Ruby 3.3+, bundled RBS signatures, stateful PBT, integrated shrinking, and edge-case bias).
6
+
7
+ ### Features & Improvements
8
+ - Improve `IntegerArbitrary#shrink` to yield binary-search candidates toward `target`, enabling greedy shrinking to converge to exact failure thresholds ([#82](https://github.com/ohbarye/pbt/issues/82), [#87](https://github.com/ohbarye/pbt/pull/87)).
9
+ - Add `Arbitrary#bind` / `#flat_map` (`BindArbitrary`) for dependent value generation with integrated `Sample` shrinking, including state-change validation in `Pbt.stateful` shrinking ([#84](https://github.com/ohbarye/pbt/issues/84), [#88](https://github.com/ohbarye/pbt/pull/88)).
10
+ - Add `Pbt.string` (printable ASCII default), extend `Pbt.float` with `min:`, `max:`, `allow_nan:`, and `allow_infinity:` plus float-aware binary-search shrinking and inward bound rounding, and fix `ChooseArbitrary` generation/shrinking for `Float` and exclusive ranges ([#85](https://github.com/ohbarye/pbt/issues/85), [#89](https://github.com/ohbarye/pbt/pull/89)).
11
+ - Add seed-reproducible edge-case / boundary-value bias to built-in numeric and ranged arbitraries (`IntegerArbitrary`, `FloatArbitrary`, `ChooseArbitrary`, and large `ArrayArbitrary`/`Pbt.string` lengths) ([#83](https://github.com/ohbarye/pbt/issues/83), [#90](https://github.com/ohbarye/pbt/pull/90)).
12
+ - Fix character/Unicode generators: fix `DEL` (`"\x7F"`) in `ASCII_CHARS`, exclude UTF-16 surrogates from `Pbt.char` so generated strings are always valid UTF-8, and replace the broken `String#succ` `PRINTABLE_CHARS` expansion with codepoint-range generation in `Pbt.printable_char` / `Pbt.printable_string` covering printable ASCII, BMP (including CJK), and supplementary planes (including emoji) ([#91](https://github.com/ohbarye/pbt/pull/91)).
13
+ - Prevent non-terminating shrinking on non-injective `MapArbitrary#shrink` and pathological custom bare shrinkers via non-progress filtering, seen-value tracking, and a shrink-step safety cap in `RunnerIterator` ([#91](https://github.com/ohbarye/pbt/pull/91)).
14
+ - Preserve earlier property failures over later batch generation errors under `worker: :ractor` ([#91](https://github.com/ohbarye/pbt/pull/91)).
15
+ - Make `ChooseArbitrary[T]` generic in RBS (`sig/pbt/arbitrary.rbs`) and update `pbt.gemspec` metadata and documentation ([#91](https://github.com/ohbarye/pbt/pull/91)).
16
+
17
+ ### Breaking Changes (since v0.9.0)
18
+ - [Breaking change] Rewrite `FloatArbitrary` as a direct `Arbitrary` subclass (no longer `< MapArbitrary`) with `Integer | Float | nil` bound validation, removing unused `FLOAT_MAPPER` / `FLOAT_UNMAPPER` ([#89](https://github.com/ohbarye/pbt/pull/89)).
19
+ - [Breaking change] Validate runner options (`num_runs`, `worker`, `seed`, `max_skips`, unknown keys) upfront with `Pbt::InvalidConfiguration`, and validate `Pbt.property` / `Pbt.check` block and arbitrary arguments eagerly with `ArgumentError` ([#91](https://github.com/ohbarye/pbt/pull/91)).
20
+ - [Breaking change] Format reported counterexamples, verbose failures, and execution summaries with `#inspect` (preserving multiline `Pbt::Stateful::Run` formatting) so `""`, `nil`, and `"1"` vs `1` are unambiguous ([#91](https://github.com/ohbarye/pbt/pull/91)).
21
+ - [Breaking change] Clean up public API surface: make `Pbt.toss` and internal mapper/range constants private, remove broken `PRINTABLE_CHARS`, and raise `EmptyDomainError` (`< ArgumentError`) from `Pbt.frequency` on empty domains ([#91](https://github.com/ohbarye/pbt/pull/91)).
22
+ - [Breaking change] PRNG draw sequences and shrink order changed due to binary-search shrinking and edge-case bias, so seeds from v0.9.0 will generate different values and counterexamples.
23
+
3
24
  ## [0.9.0] - 2026-11-23
4
25
 
5
26
  - [Breaking change] Replace `Pbt.stateful(model:, sut:)` with a redesigned yield-based DSL (`Pbt.stateful(max_steps:, min_steps:, max_shrink_attempts:) { |m| ... }`) featuring `initial_state` (value, block, or shrinkable `Arbitrary`), `sut`+`teardown` / `around` lifecycle, weighted commands (`guard`, `arguments`, `precondition`, `next_state`, `run`, `verify`), `invariant`s, symbolic `Ref`s, best-first shrinking with offline `cover?` validation and `FailureSignature` equivalence, `property.replay`, `Pbt.statistics` support, and multiline counterexample reporting [#67](https://github.com/ohbarye/pbt/issues/67) [#79](https://github.com/ohbarye/pbt/pull/79) [#80](https://github.com/ohbarye/pbt/pull/80).
data/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
  [![Build Status](https://github.com/ohbarye/pbt/actions/workflows/main.yml/badge.svg)](https://github.com/ohbarye/pbt/actions/workflows/main.yml)
5
5
  [![RubyDoc](https://img.shields.io/badge/%F0%9F%93%9ARubyDoc-documentation-informational.svg)](https://www.rubydoc.info/gems/pbt)
6
6
 
7
- A property-based testing tool for Ruby with experimental features that allow you to run test cases in parallel.
7
+ A property-based testing library for Ruby with shrinking, stateful testing, RBS type signatures, and optional Ractor parallelism.
8
8
 
9
9
  PBT stands for Property-Based Testing.
10
10
 
@@ -114,6 +114,8 @@ Discarded cases do not count toward `num_runs` and are skipped during shrinking.
114
114
 
115
115
  Arbitrary generates random values. It is also responsible for shrinking those values if asked to shrink a failed value as input.
116
116
 
117
+ Built-in numeric and ranged arbitraries (`Pbt.integer`, `Pbt.nat`, `Pbt.float`, `Pbt.choose`, and large `Pbt.array`/`Pbt.string` lengths) apply seed-reproducible edge-case bias toward boundary values (such as `0`, `1`, `-1`, `min`, `max`, `0.0`, `-0.0`, and empty/max lengths) to increase the likelihood of catching common corner-case bugs within the default `num_runs: 100`.
118
+
117
119
  Here, we used only one type of arbitrary, `Pbt.integer`. There are many other built-in arbitraries, and you can create a variety of inputs by combining existing ones.
118
120
 
119
121
  #### Shrink
@@ -132,9 +134,13 @@ There are many built-in arbitraries in `Pbt`. You can use them to generate rando
132
134
  ```ruby
133
135
  Pbt.integer.generate # => 42
134
136
  Pbt.integer(min: -1, max: 8).generate # => Integer between -1 and 8
137
+ Pbt.float(min: 0.0, max: 1.0).generate # => Float between 0.0 and 1.0
138
+ Pbt.float(allow_nan: true, allow_infinity: true).generate # => Float (including NaN / ±Infinity)
135
139
 
136
140
  Pbt.symbol.generate # => :atq
137
141
 
142
+ Pbt.string.generate # => "aagjZfao" (printable ASCII)
143
+ Pbt.printable_string.generate # => "a中😀" (printable Unicode)
138
144
  Pbt.ascii_char.generate # => "a"
139
145
  Pbt.ascii_string.generate # => "aagjZfao"
140
146
 
@@ -159,13 +165,17 @@ Pbt.tuple(Pbt.symbol, Pbt.integer).generate # => [:atq, 42]
159
165
 
160
166
  Pbt.fixed_hash(x: Pbt.symbol, y: Pbt.integer).generate # => {x: :atq, y: 42}
161
167
  Pbt.hash(Pbt.symbol, Pbt.integer).generate # => {atq: 121, ygab: -1142}
168
+ Pbt.set(Pbt.integer).generate # => #<Set: {1, 42}>
162
169
 
163
170
  Pbt.constant_from(:a, 1, 0.1).generate # => :a or 1 or 0.1
164
171
  Pbt.one_of(Pbt.integer, Pbt.constant(nil)).generate # => 42 or nil
165
172
 
166
173
  Pbt.integer(min: 0, max: 10).map { |n| n * 2 }.generate # => 8
174
+ Pbt.integer(min: 0, max: 10).flat_map { |lo| Pbt.integer(min: lo, max: 10).map { |hi| [lo, hi] } }.generate # => [3, 7]
167
175
  Pbt.integer(min: 0, max: 10).filter(&:even?).generate # => 4
168
- ````
176
+ ```
177
+
178
+ Note: for `Pbt.set` and `Pbt.hash`, `min:` and `max:` bound the number of element/pair draws *before* deduplication (so duplicate elements/keys can result in fewer entries than `min:`).
169
179
 
170
180
  See [ArbitraryMethods](https://github.com/ohbarye/pbt/blob/main/lib/pbt/arbitrary/arbitrary_methods.rb) module for more details.
171
181
 
@@ -188,10 +198,11 @@ branch. Generated values and reported counterexamples remain ordinary Ruby value
188
198
 
189
199
  For manual shrinking, retain a sample: `sample = arb.sample(Random.new(42))`,
190
200
  then inspect `sample.value` and `sample.shrink.map(&:value)`. Calling
191
- `arb.shrink(value)` directly on `Pbt.frequency`, `Pbt.one_of`, or `Arbitrary#map`
192
- without an `unmapper` returns no candidates because a bare value cannot identify its
193
- source branch or preimage. Both `Pbt.property` and `Pbt.stateful` capture `Sample`
194
- provenance automatically, so contextual generators shrink seamlessly in both.
201
+ `arb.shrink(value)` directly on `Pbt.frequency`, `Pbt.one_of`, `Arbitrary#bind` /
202
+ `#flat_map`, or `Arbitrary#map` without an `unmapper` returns no candidates because a
203
+ bare value cannot identify its source branch or preimage. Both `Pbt.property` and
204
+ `Pbt.stateful` capture `Sample` provenance automatically, so contextual generators
205
+ shrink seamlessly in both.
195
206
 
196
207
  ### Generator statistics
197
208
 
@@ -267,6 +278,7 @@ Pbt.assert(seed: 42) { property }
267
278
  - **Symbolic references (`Pbt::Stateful::Ref`)**: `c.next_state { |s, args, ref| ... }` can store `ref` in the pure model state and select it in later commands' `c.arguments`. During execution, `Ref`s inside `Array`, `Hash`, `Set`, `Struct`, and `Data` are resolved to concrete SUT return values (including `nil`).
268
279
  - **Best-first shrinking**: performs post-failure truncation, ddmin chunk deletion, single-step deletion, `initial_state` shrinking, and contextual step argument shrinking (preserving `Pbt.frequency`, `Pbt.one_of`, and block `#map` shrink trees), with offline model validation (`Arbitrary#cover?`, `guard`, `precondition`, `Ref` dependencies), `FailureSignature` equivalence, deduplication, and `max_shrink_attempts` budget.
269
280
  - **Replay & statistics**: `details = Pbt.check { property }; property.replay(details.counterexample)` replays the minimized `Pbt::Stateful::Run`; `Pbt.statistics(property) { |run| run.command_names }` inspects generated command distributions.
281
+ - **Step count bounds (`min_steps:` / `max_steps:`)**: `min_steps:` sets the target lower bound for generated run lengths; if a run reaches a terminal state where no command `guard` is truthy, generation stops early at that terminal state.
270
282
  - **Worker behavior**: `Pbt.stateful` runs sequentially by default even when `Pbt.configuration.worker = :ractor`. Passing `worker: :ractor` explicitly raises `Pbt::InvalidConfiguration` before generation.
271
283
 
272
284
  ## What if property-based tests fail?
@@ -354,7 +366,7 @@ Pbt.configure do |config|
354
366
  config.num_runs = 100
355
367
 
356
368
  # The seed to use for random number generation.
357
- # It's useful to reproduce failed test with the seed you'd pick up from failure messages. Default is a random seed.
369
+ # Initialized once per process by default; pass `seed:` to `Pbt.assert` / `Pbt.check` to vary or replay a failure.
358
370
  config.seed = 42
359
371
 
360
372
  # Whether to report exceptions in threads.
@@ -418,7 +430,7 @@ You cannot use any methods provided by test frameworks like `expect` or `assert`
418
430
  it do
419
431
  Pbt.assert(worker: :ractor) do
420
432
  Pbt.property(Pbt.integer) do |n|
421
- # This is not possible because `self` if a Ractor here.
433
+ # This is not possible because `self` is a Ractor here.
422
434
  expect(n).to be_an(Integer) # => Ractor::RemoteError (cause by NoMethodError for `expect` or `be_an`)
423
435
  end
424
436
  end
@@ -437,31 +449,20 @@ Pbt.assert(worker: :none) do
437
449
  end
438
450
  ```
439
451
 
440
- ## TODOs
441
-
442
- Once this project finishes the following, we will release v1.0.0.
443
-
444
- - [x] Implement basic primitive arbitraries
445
- - [x] Implement composite arbitraries
446
- - [x] Support shrinking
447
- - [x] Support multiple concurrency methods
448
- - [x] Ractor
449
- - [x] Process (dropped)
450
- - [x] Thread (dropped)
451
- - [x] None (Run tests sequentially)
452
- - [x] Documentation
453
- - [x] Add better examples
454
- - [x] Arbitrary usage
455
- - [x] Configuration
456
- - [x] Benchmark
457
- - [x] Rich report by verbose mode
458
- - [x] (Partially) Allow to use expectations and matchers provided by test framework in Ractor. (dropped)
459
- - It'd be so hard to pass assertions like `expect`, `assert` to a Ractor.
460
- - [x] Implement frequency arbitrary
461
- - [x] Statistics feature to aggregate generated values
462
- - [x] Decide DSL (explicit `Pbt.assert` / `Pbt.check` + `Pbt.property` / `Pbt.stateful` composition)
463
- - [x] Try Fiber ([experiment and v1 decision](benchmark/FIBER.md))
464
- - [x] Stateful property-based testing (via `Pbt.stateful`)
452
+ ## Type Signatures (RBS)
453
+
454
+ `pbt` ships complete [RBS](https://github.com/ruby/rbs) type signatures under `sig/` (`sig/pbt.rbs`, `sig/pbt/*.rbs`, and `sig/manifest.yaml`), verified in CI with both `rbs validate` and `steep check`.
455
+
456
+ Steep and RBS-aware editors pick up the bundled signatures automatically. Note that on Ruby 3.3 with RBS 3.x (where `Set` is still a stdlib library rather than core), include `library "set"` in your `Steepfile` if you reference `Pbt.set` or `Pbt::Stateful`.
457
+
458
+ ## Versioning and Stability
459
+
460
+ `pbt` follows [Semantic Versioning](https://semver.org/):
461
+
462
+ - **Stable public API**: top-level `Pbt.*` entry points (`assert`, `check`, `property`, `stateful`, `assume`, `statistics`, `configure`, `configuration`, and arbitrary constructors), public `Arbitrary` / `Sample` methods, the `Pbt.stateful` DSL and its value/error types (`Run`, `Step`, `Ref`, `Context`, `StepFailure`, `InvalidSpec`, `GenerationError`, `ModelError`), and `Pbt::Reporter::RunDetails`.
463
+ - **Experimental**: `worker: :ractor` remains experimental while Ruby's Ractor API continues to evolve.
464
+ - **Internal classes**: implementation helpers (such as `RunnerIterator`, `Tosser`, `Stateful::Shrinker`, `Stateful::ShrinkSession`, `Stateful::RunSample`, and `Stateful::Resolver`) are not covered by SemVer stability guarantees.
465
+ - **Seed reproducibility**: seeds reproduce identical generated values and shrink paths within the same `pbt` version. Minor and major releases may change PRNG consumption or shrinking order as generators and shrinkers improve.
465
466
 
466
467
  ## Development
467
468
 
@@ -469,7 +470,7 @@ Once this project finishes the following, we will release v1.0.0.
469
470
 
470
471
  ```shell
471
472
  bin/setup
472
- bundle exec rake # Run tests and lint at once
473
+ bundle exec rake # Run specs, Standard Ruby lint, RBS validation, and Steep type-checking
473
474
  ```
474
475
 
475
476
  ### Test
@@ -92,6 +92,29 @@ module Pbt
92
92
  MapArbitrary.new(self, resolved_mapper, unmapper)
93
93
  end
94
94
 
95
+ # Create another arbitrary by feeding each generated value into `binder` (or a block)
96
+ # to produce a dependent arbitrary. Shrinking works in `Pbt.property`, `Pbt.stateful`,
97
+ # and `sample` by shrinking both the outer value and the dependent inner value.
98
+ #
99
+ # @example Block form
100
+ # Pbt.integer(min: 0, max: 100).flat_map { |min| Pbt.integer(min: min, max: 100).map { |max| [min, max] } }
101
+ #
102
+ # @param binder [#call, nil] Callable returning an arbitrary for each generated value.
103
+ # @return [BindArbitrary] New dependent arbitrary.
104
+ def bind(binder = nil, &block)
105
+ if binder && block
106
+ raise ArgumentError, "bind accepts either a binder argument or a block, not both"
107
+ end
108
+
109
+ resolved_binder = binder || block
110
+ unless resolved_binder.respond_to?(:call)
111
+ raise ArgumentError, "bind requires a callable binder or a block"
112
+ end
113
+
114
+ BindArbitrary.new(self, resolved_binder)
115
+ end
116
+ alias_method :flat_map, :bind
117
+
95
118
  # Create another arbitrary by filtering values against `refinement`.
96
119
  # All the values produced by the resulting arbitrary satisfy `!!refinement(value) == true`.
97
120
  #
@@ -12,6 +12,7 @@ require "pbt/arbitrary/choose_arbitrary"
12
12
  require "pbt/arbitrary/one_of_arbitrary"
13
13
  require "pbt/arbitrary/frequency_arbitrary"
14
14
  require "pbt/arbitrary/map_arbitrary"
15
+ require "pbt/arbitrary/bind_arbitrary"
15
16
  require "pbt/arbitrary/float_arbitrary"
16
17
  require "pbt/arbitrary/filter_arbitrary"
17
18
 
@@ -43,7 +44,7 @@ module Pbt
43
44
  # @param empty [Boolean] Whether the array can be empty or not.
44
45
  # @return [Arbitrary<T>]
45
46
  def array(arb, min: 0, max: 10, empty: true)
46
- raise ArgumentError if min < 0
47
+ raise ArgumentError, "min must be zero or positive number, got #{min.inspect}" if min < 0
47
48
  min = 1 if min.zero? && !empty
48
49
 
49
50
  ArrayArbitrary.new(arb, min, max)
@@ -128,11 +129,11 @@ module Pbt
128
129
  MapArbitrary.new(array(hexa, **kwargs), STRING_MAPPER, STRING_UNMAPPER, bijective: true)
129
130
  end
130
131
 
131
- # For a single unicode character (including printable and non-printable).
132
+ # For a single valid Unicode scalar value (excluding UTF-16 surrogates U+D800..U+DFFF).
132
133
  #
133
134
  # @return [Arbitrary<String>]
134
135
  def char
135
- MapArbitrary.new(choose(CHAR_RANGE), CHAR_MAPPER, CHAR_UNMAPPER, bijective: true)
136
+ MapArbitrary.new(choose(UNICODE_SCALAR_INDEX_RANGE), CHAR_MAPPER, CHAR_UNMAPPER, bijective: true)
136
137
  end
137
138
 
138
139
  # For an alphanumeric character.
@@ -174,6 +175,16 @@ module Pbt
174
175
  constant_from(*PRINTABLE_ASCII_CHARS)
175
176
  end
176
177
 
178
+ # For printable ascii strings (default string generator).
179
+ # Use `ascii_string` to include ASCII control characters, or `printable_string` for full Unicode.
180
+ #
181
+ # @see Pbt.printable_ascii_string
182
+ # @param kwargs [Hash] Options for ArrayArbitrary (`min:`, `max:`, `empty:`).
183
+ # @return [Arbitrary<String>]
184
+ def string(**kwargs)
185
+ printable_ascii_string(**kwargs)
186
+ end
187
+
177
188
  # For printable ascii strings.
178
189
  #
179
190
  # @see Pbt.array
@@ -183,11 +194,18 @@ module Pbt
183
194
  MapArbitrary.new(array(printable_ascii_char, **kwargs), STRING_MAPPER, STRING_UNMAPPER, bijective: true)
184
195
  end
185
196
 
186
- # For a printable character.
197
+ # For a printable Unicode character across printable ASCII, BMP (including CJK), and supplementary planes (including emoji).
198
+ # Excludes C0/C1 control characters, DEL, UTF-16 surrogates, and U+FFFE/U+FFFF.
187
199
  #
188
200
  # @return [Arbitrary<String>]
189
201
  def printable_char
190
- constant_from(*PRINTABLE_CHARS)
202
+ codepoint_arb = frequency(
203
+ [3, choose(PRINTABLE_ASCII_CODEPOINT_RANGE)],
204
+ [4, choose(PRINTABLE_BMP_MAIN_CODEPOINT_RANGE)],
205
+ [1, choose(PRINTABLE_BMP_HIGH_CODEPOINT_RANGE)],
206
+ [2, choose(PRINTABLE_SUPPLEMENTARY_CODEPOINT_RANGE)]
207
+ )
208
+ MapArbitrary.new(codepoint_arb, CODEPOINT_MAPPER, CODEPOINT_UNMAPPER, bijective: true)
191
209
  end
192
210
 
193
211
  # For printable strings.
@@ -208,25 +226,35 @@ module Pbt
208
226
  MapArbitrary.new(array(constant_from(*SYMBOL_SAFE_CHARS), empty: false, **kwargs), SYMBOL_MAPPER, SYMBOL_UNMAPPER, bijective: true)
209
227
  end
210
228
 
211
- # For floats.
229
+ # For floats within optional finite `Integer` / `Float` bounds, with opt-in NaN / Infinity support.
230
+ # Omitted bounds default generation to `-1_000_000.0..1_000_000.0` (or a scaled span when one-sided)
231
+ # while leaving `cover?` unbounded on omitted sides.
212
232
  #
213
- # @return [Arbitrary<Float>]
214
- def float
215
- FloatArbitrary.new
233
+ # @param min [Integer, Float, nil] Inclusive finite lower bound.
234
+ # @param max [Integer, Float, nil] Inclusive finite upper bound.
235
+ # @param allow_nan [Boolean] Whether `Float::NAN` may be generated. Default is `false`.
236
+ # @param allow_infinity [Boolean] Whether `+/-Float::INFINITY` may be generated when the corresponding bound is unbounded. Default is `false`.
237
+ # @return [FloatArbitrary]
238
+ def float(min: nil, max: nil, allow_nan: false, allow_infinity: false)
239
+ FloatArbitrary.new(min: min, max: max, allow_nan: allow_nan, allow_infinity: allow_infinity)
216
240
  end
217
241
 
218
- # For symbols.
242
+ # For sets of values generated by `arb`.
243
+ # Note: `min` and `max` bound the number of element draws before Set deduplication,
244
+ # so the resulting Set may have fewer than `min` elements when `arb` produces duplicates.
219
245
  #
220
- # @param arb [Arbitrary<T>] Arbitrary used to generate the values of the array.
221
- # @param min [Integer] Lower limit of the generated set size.
222
- # @param max [Integer] Upper limit of the generated set size.
223
- # @param empty [Boolean] Whether the array can be empty or not.
224
- # @return [Arbitrary<T>]
246
+ # @param arb [Arbitrary<T>] Arbitrary used to generate the elements of the set.
247
+ # @param min [Integer] Lower limit of generated draws before deduplication.
248
+ # @param max [Integer] Upper limit of generated draws before deduplication.
249
+ # @param empty [Boolean] Whether the set can be empty or not.
250
+ # @return [Arbitrary<Set<T>>]
225
251
  def set(arb, min: 0, max: 10, empty: true)
226
252
  array(arb, min: min, max: max, empty: empty).map(SET_MAPPER, SET_UNMAPPER)
227
253
  end
228
254
 
229
255
  # For hashes of any keys and values.
256
+ # Note: `min` and `max` bound the number of key-value pair draws before Hash key deduplication,
257
+ # so the resulting Hash may have fewer than `min` entries when `key_arbitrary` produces duplicate keys.
230
258
  # If you want to call `Object#hash` for `Pbt`, call this method without arguments.
231
259
  #
232
260
  # @example
@@ -241,8 +269,10 @@ module Pbt
241
269
  if args.size == 2
242
270
  key_arbitrary, value_arbitrary = args
243
271
  array(tuple(key_arbitrary, value_arbitrary), **kwargs).map(HASH_MAPPER, HASH_UNMAPPER)
244
- else
272
+ elsif args.empty? && kwargs.empty?
245
273
  super # call `Object#hash`
274
+ else
275
+ raise ArgumentError, "Pbt.hash expects (key_arbitrary, value_arbitrary) or no arguments (for Object#hash)"
246
276
  end
247
277
  end
248
278
 
@@ -0,0 +1,54 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Pbt
4
+ module Arbitrary
5
+ # Generates dependent values by passing values from an outer arbitrary into a binder
6
+ # that returns an inner arbitrary. Shrinking uses `Sample` provenance to shrink both
7
+ # the outer choice and the dependent inner value together.
8
+ class BindArbitrary < Arbitrary
9
+ # @param arb [Arbitrary] Outer arbitrary.
10
+ # @param binder [#call] Callable returning an inner arbitrary for each outer value.
11
+ def initialize(arb, binder)
12
+ raise ArgumentError, "binder must be callable" unless binder.respond_to?(:call)
13
+
14
+ @arb = arb
15
+ @binder = binder
16
+ end
17
+
18
+ # @see Arbitrary#generate
19
+ def generate(rng = Random.new)
20
+ outer_val = @arb.generate(rng)
21
+ inner_seed = rng.rand(1 << 64)
22
+ inner_arb = Sample.validate_bound_arbitrary!(@binder.call(outer_val))
23
+ inner_arb.generate(Random.new(inner_seed))
24
+ end
25
+
26
+ # @private
27
+ def contextual?
28
+ true
29
+ end
30
+
31
+ # @see Arbitrary#sample
32
+ def sample(rng = Random.new)
33
+ outer_sample = Sample.capture(@arb, rng)
34
+ inner_seed = rng.rand(1 << 64)
35
+ Sample.bind(outer_sample, inner_seed) { |v| @binder.call(v) }
36
+ end
37
+
38
+ # Conservative 3-valued membership check (cannot determine dependent codomain in general).
39
+ #
40
+ # @see Arbitrary#cover?
41
+ def cover?(_value)
42
+ nil
43
+ end
44
+
45
+ # A bare value cannot identify the outer choice that produced its inner arbitrary.
46
+ # Use `sample`, `Pbt.property`, or `Pbt.stateful` to shrink.
47
+ #
48
+ # @see Arbitrary#shrink
49
+ def shrink(_current)
50
+ [].each
51
+ end
52
+ end
53
+ end
54
+ end
@@ -4,13 +4,26 @@ module Pbt
4
4
  module Arbitrary
5
5
  # Generates a random value from a range.
6
6
  class ChooseArbitrary < Arbitrary
7
- # @param range [Range<Integer>]
7
+ EDGE_CASE_DOMAIN_THRESHOLD = 20
8
+ EDGE_CASE_BIAS_DENOMINATOR = 5
9
+ private_constant :EDGE_CASE_DOMAIN_THRESHOLD, :EDGE_CASE_BIAS_DENOMINATOR
10
+
11
+ # @param range [Range<Integer>, Range<Float>]
8
12
  def initialize(range)
9
13
  @range = range
14
+ @edge_cases = build_edge_cases
10
15
  end
11
16
 
12
17
  # @see Arbitrary#generate
13
18
  def generate(rng = Random.new)
19
+ if @edge_cases && rng.rand(EDGE_CASE_BIAS_DENOMINATOR).zero?
20
+ return @edge_cases[rng.rand(@edge_cases.size)]
21
+ end
22
+
23
+ if float_range? && @range.exclude_end?
24
+ return sample_exclusive_float(rng)
25
+ end
26
+
14
27
  rng.rand(@range)
15
28
  rescue ArgumentError => e
16
29
  raise EmptyDomainError, e.message if empty_range?
@@ -24,7 +37,7 @@ module Pbt
24
37
 
25
38
  if integer_range?
26
39
  return false unless value.is_a?(Integer)
27
- else
40
+ elsif float_range?
28
41
  return false unless value.is_a?(Float) && value.finite?
29
42
  end
30
43
 
@@ -33,9 +46,26 @@ module Pbt
33
46
 
34
47
  # @see Arbitrary#shrink
35
48
  def shrink(current)
36
- # Range is ordered from min to max, so we can just shrink towards min.
37
- min, max = [@range.begin, @range.end].sort
38
- IntegerArbitrary.new(min, max).shrink(current, target: min)
49
+ return [].each if @range.begin.nil? || @range.end.nil? || empty_range?
50
+
51
+ min = @range.begin
52
+ max = @range.end
53
+ if integer_range?
54
+ effective_max = @range.exclude_end? ? (max - 1) : max
55
+ return [].each if min > effective_max
56
+
57
+ IntegerArbitrary.new(min, effective_max).shrink(current, target: min)
58
+ elsif float_range?
59
+ FloatArbitrary.shrink_float(
60
+ current,
61
+ min: min.to_f,
62
+ max: max.to_f,
63
+ target: min.to_f,
64
+ exclude_end: @range.exclude_end?
65
+ )
66
+ else
67
+ [].each
68
+ end
39
69
  end
40
70
 
41
71
  private
@@ -44,9 +74,56 @@ module Pbt
44
74
  @range.begin.is_a?(Integer) && @range.end.is_a?(Integer)
45
75
  end
46
76
 
77
+ def float_range?
78
+ @range.begin.is_a?(Float) || @range.end.is_a?(Float)
79
+ end
80
+
47
81
  def empty_range?
48
82
  !@range.begin.nil? && !@range.end.nil? && !@range.cover?(@range.begin)
49
83
  end
84
+
85
+ def build_edge_cases
86
+ return nil if @range.begin.nil? || @range.end.nil? || empty_range?
87
+
88
+ if integer_range?
89
+ min = @range.begin
90
+ effective_max = @range.exclude_end? ? (@range.end - 1) : @range.end
91
+ return nil if min > effective_max || (effective_max - min + 1) <= EDGE_CASE_DOMAIN_THRESHOLD
92
+
93
+ [0, 1, -1, min, effective_max].uniq.select { |v| v.between?(min, effective_max) }.freeze
94
+ elsif float_range?
95
+ lo = @range.begin.to_f
96
+ hi = @range.end.to_f
97
+ return nil unless lo.finite? && hi.finite? && lo < hi
98
+
99
+ candidates = [0.0, 1.0, -1.0, lo, hi]
100
+ candidates << -0.0 if lo < 0.0 && hi >= 0.0
101
+ edges = candidates
102
+ .select { |v| @range.cover?(v) }
103
+ .uniq { |v| v.zero? ? (1.0 / v) : v }
104
+ edges.empty? ? nil : edges.freeze
105
+ end
106
+ end
107
+
108
+ def sample_exclusive_float(rng)
109
+ raise EmptyDomainError, "cannot generate from empty range #{@range.inspect}" if empty_range?
110
+
111
+ lo = @range.begin.to_f
112
+ hi = @range.end.to_f.prev_float
113
+ if !lo.finite? || !hi.finite? || lo > hi
114
+ raise EmptyDomainError, "cannot generate from range #{@range.inspect}"
115
+ end
116
+
117
+ return lo if lo == hi
118
+
119
+ span = hi - lo
120
+ if span.finite?
121
+ rng.rand(lo..hi)
122
+ else
123
+ mid = (lo / 2.0) + (hi / 2.0)
124
+ rng.rand(2).zero? ? rng.rand(lo..mid) : rng.rand(mid..hi)
125
+ end
126
+ end
50
127
  end
51
128
  end
52
129
  end
@@ -5,25 +5,47 @@ require "date"
5
5
  module Pbt
6
6
  module Arbitrary
7
7
  HEXA_CHARS = [*("0".."9"), *("a".."f")].freeze
8
- CHAR_RANGE = (0..0x10FFFF)
9
8
  SYMBOL_SAFE_CHARS = [*("a".."z"), "-"].freeze
10
9
  ALPHANUMERIC_CHARS = [*("a".."z"), *("A".."Z"), *("0".."9")].freeze
11
10
  PRINTABLE_ASCII_CHARS = [*(" ".."~")].freeze
12
- ASCII_CHARS = [*PRINTABLE_ASCII_CHARS, "\n", "\r", "\t", "\v", "\b", "\f", "\e", "\d", "\a"].freeze
13
- PRINTABLE_CHARS = [
14
- *ASCII_CHARS,
15
- *("\u{A0}".."\u{D7FF}"),
16
- *("\u{E000}".."\u{FFFD}"),
17
- *("\u{10000}".."\u{10FFFF}")
18
- ].freeze
19
- CHAR_MAPPER = ->(v) { [v].pack("U") }
20
- CHAR_UNMAPPER = ->(v) { v.unpack1("U") }
11
+ ASCII_CHARS = [*PRINTABLE_ASCII_CHARS, "\n", "\r", "\t", "\v", "\b", "\f", "\e", "\x7F", "\a"].freeze
12
+
13
+ # Valid Unicode scalar values exclude UTF-16 surrogates (0xD800..0xDFFF).
14
+ SURROGATE_START = 0xD800
15
+ SURROGATE_COUNT = 0x800
16
+ UNICODE_SCALAR_INDEX_RANGE = (0..(0x10FFFF - SURROGATE_COUNT))
17
+
18
+ # Printable Unicode codepoint segments (excludes C0/C1 controls, DEL, surrogates, and U+FFFE/U+FFFF).
19
+ PRINTABLE_ASCII_CODEPOINT_RANGE = (0x20..0x7E)
20
+ PRINTABLE_BMP_MAIN_CODEPOINT_RANGE = (0xA0..0xD7FF)
21
+ PRINTABLE_BMP_HIGH_CODEPOINT_RANGE = (0xE000..0xFFFD)
22
+ PRINTABLE_SUPPLEMENTARY_CODEPOINT_RANGE = (0x10000..0x10FFFF)
23
+
24
+ CHAR_MAPPER = ->(i) {
25
+ return nil unless i.is_a?(Integer) && UNICODE_SCALAR_INDEX_RANGE.cover?(i)
26
+
27
+ [(i < SURROGATE_START) ? i : (i + SURROGATE_COUNT)].pack("U")
28
+ }
29
+ CHAR_UNMAPPER = ->(v) {
30
+ return -1 unless v.is_a?(String) && v.valid_encoding? && v.length == 1
31
+
32
+ cp = v.ord
33
+ (cp < SURROGATE_START) ? cp : (cp - SURROGATE_COUNT)
34
+ }
35
+ CODEPOINT_MAPPER = ->(cp) {
36
+ return nil unless cp.is_a?(Integer) && cp >= 0 && cp <= 0x10FFFF && !(cp >= SURROGATE_START && cp < SURROGATE_START + SURROGATE_COUNT)
37
+
38
+ [cp].pack("U")
39
+ }
40
+ CODEPOINT_UNMAPPER = ->(v) {
41
+ return -1 unless v.is_a?(String) && v.valid_encoding? && v.length == 1
42
+
43
+ v.ord
44
+ }
21
45
  STRING_MAPPER = ->(v) { v.join }
22
46
  STRING_UNMAPPER = ->(v) { v.chars }
23
47
  SYMBOL_MAPPER = ->(v) { v.join.to_sym }
24
48
  SYMBOL_UNMAPPER = ->(v) { v.to_s.chars }
25
- FLOAT_MAPPER = ->((x, y)) { x.to_f / (y.to_f.abs + 1.0) }
26
- FLOAT_UNMAPPER = ->(v) { [v, 0] }
27
49
  SET_MAPPER = ->(v) { v.to_set }
28
50
  SET_UNMAPPER = ->(v) { v.to_a }
29
51
  HASH_MAPPER = ->(v) { v.to_h }
@@ -32,5 +54,13 @@ module Pbt
32
54
  DATE_UNMAPPER = ->(epoch) { ->(v) { (v - epoch).to_i } }
33
55
  TIME_MAPPER = DATE_MAPPER
34
56
  TIME_UNMAPPER = DATE_UNMAPPER
57
+
58
+ private_constant :SURROGATE_START, :SURROGATE_COUNT, :UNICODE_SCALAR_INDEX_RANGE,
59
+ :PRINTABLE_ASCII_CODEPOINT_RANGE, :PRINTABLE_BMP_MAIN_CODEPOINT_RANGE,
60
+ :PRINTABLE_BMP_HIGH_CODEPOINT_RANGE, :PRINTABLE_SUPPLEMENTARY_CODEPOINT_RANGE,
61
+ :CHAR_MAPPER, :CHAR_UNMAPPER, :CODEPOINT_MAPPER, :CODEPOINT_UNMAPPER,
62
+ :STRING_MAPPER, :STRING_UNMAPPER, :SYMBOL_MAPPER, :SYMBOL_UNMAPPER,
63
+ :SET_MAPPER, :SET_UNMAPPER, :HASH_MAPPER, :HASH_UNMAPPER,
64
+ :DATE_MAPPER, :DATE_UNMAPPER, :TIME_MAPPER, :TIME_UNMAPPER
35
65
  end
36
66
  end
@@ -9,12 +9,11 @@ module Pbt
9
9
  raise EmptyDomainError, "constant_from requires at least one choice" if choices.empty?
10
10
 
11
11
  @choices = choices.dup
12
- @idx_arb = IntegerArbitrary.new(0, @choices.size - 1)
13
12
  end
14
13
 
15
14
  # @see Arbitrary#generate
16
15
  def generate(rng = Random.new)
17
- @choices[@idx_arb.generate(rng)]
16
+ @choices[rng.rand(@choices.size)]
18
17
  end
19
18
 
20
19
  # @see Arbitrary#cover?
@@ -28,8 +27,9 @@ module Pbt
28
27
  return Enumerator.new {} if index.nil?
29
28
 
30
29
  # Shrinks to values earlier in the list of `choices`.
30
+ idx_arb = IntegerArbitrary.new(0, @choices.size - 1)
31
31
  Enumerator.new do |y|
32
- @idx_arb.shrink(index).each do |idx|
32
+ idx_arb.shrink(index).each do |idx|
33
33
  y << @choices[idx]
34
34
  end
35
35
  end