pbt 0.7.0 → 0.9.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.
Files changed (54) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +23 -0
  3. data/README.md +117 -80
  4. data/lib/pbt/arbitrary/arbitrary.rb +63 -10
  5. data/lib/pbt/arbitrary/arbitrary_methods.rb +51 -24
  6. data/lib/pbt/arbitrary/array_arbitrary.rb +45 -11
  7. data/lib/pbt/arbitrary/choose_arbitrary.rb +27 -0
  8. data/lib/pbt/arbitrary/constant.rb +0 -1
  9. data/lib/pbt/arbitrary/constant_arbitrary.rb +5 -0
  10. data/lib/pbt/arbitrary/constant_from_arbitrary.rb +39 -0
  11. data/lib/pbt/arbitrary/filter_arbitrary.rb +40 -2
  12. data/lib/pbt/arbitrary/fixed_hash_arbitrary.rb +16 -0
  13. data/lib/pbt/arbitrary/float_arbitrary.rb +31 -0
  14. data/lib/pbt/arbitrary/frequency_arbitrary.rb +61 -0
  15. data/lib/pbt/arbitrary/integer_arbitrary.rb +11 -0
  16. data/lib/pbt/arbitrary/map_arbitrary.rb +40 -2
  17. data/lib/pbt/arbitrary/one_of_arbitrary.rb +46 -13
  18. data/lib/pbt/arbitrary/sample.rb +97 -0
  19. data/lib/pbt/arbitrary/tuple_arbitrary.rb +22 -0
  20. data/lib/pbt/check/case.rb +1 -1
  21. data/lib/pbt/check/configuration.rb +5 -3
  22. data/lib/pbt/check/property.rb +23 -4
  23. data/lib/pbt/check/runner_iterator.rb +84 -10
  24. data/lib/pbt/check/runner_methods.rb +53 -19
  25. data/lib/pbt/check/tosser.rb +1 -1
  26. data/lib/pbt/reporter/run_details.rb +2 -2
  27. data/lib/pbt/reporter/run_details_reporter.rb +46 -4
  28. data/lib/pbt/reporter/run_execution.rb +47 -4
  29. data/lib/pbt/stateful/command.rb +215 -0
  30. data/lib/pbt/stateful/errors.rb +58 -0
  31. data/lib/pbt/stateful/property.rb +276 -276
  32. data/lib/pbt/stateful/shrinker.rb +295 -0
  33. data/lib/pbt/stateful/spec.rb +299 -0
  34. data/lib/pbt/stateful/types.rb +308 -0
  35. data/lib/pbt/statistics.rb +28 -0
  36. data/lib/pbt/version.rb +1 -1
  37. data/lib/pbt.rb +62 -26
  38. data/sig/manifest.yaml +2 -0
  39. data/sig/pbt/arbitrary.rbs +139 -0
  40. data/sig/pbt/check.rbs +74 -0
  41. data/sig/pbt/reporter.rbs +44 -0
  42. data/sig/pbt/stateful.rbs +241 -0
  43. data/sig/pbt.rbs +40 -1
  44. metadata +18 -13
  45. data/.rspec +0 -3
  46. data/.standard.yml +0 -3
  47. data/CLAUDE.md +0 -104
  48. data/Rakefile +0 -70
  49. data/benchmark/README.md +0 -103
  50. data/benchmark/example.txt +0 -299
  51. data/benchmark/failure_simple.rb +0 -29
  52. data/benchmark/success_cpu_bound.rb +0 -35
  53. data/benchmark/success_io_bound.rb +0 -28
  54. data/benchmark/success_simple.rb +0 -24
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 3275eafb6d07373c24f422feafa7300962213568a387cd21fbcd648c85de4193
4
- data.tar.gz: 7a3b902bb323251050ec023ec8318244d777c0bc2584ad0c8bad2504d93888f0
3
+ metadata.gz: 4b46223742e56120329f6e7d8bc534c26440b87309f001d715656c3c472b18e4
4
+ data.tar.gz: 307990ded90589295c40d806579e2e586fd52c38d8a20ad0359a1dcc0de57718
5
5
  SHA512:
6
- metadata.gz: e72d6278580f540b7d0aad1aefb168c2fbc7a3e64d31a90a4929695b979d3d1c29e3dc06fb22fb0fc6d1aadfc121605176cbee7146e298201f9091c0fa2ea647
7
- data.tar.gz: 8967245b883d22dfb00d79b0433acc53502e3e9ecdb07e89bae04002ce413fd67d126f695f4a4e12a965fc7adf171b5cd8e1c9fd3e6d8d28e8ff4444113cbea5
6
+ metadata.gz: fc5a37505bd13299292e7304b43f7c020e96531aa8bd6bbd7e397474775854200d91c647387906b3dd389753bc39db4e3514f962f0034013956a0ca1254a253f
7
+ data.tar.gz: 3ea6eed118b195d4e9676f604d564dafd87d2bb3b1ada8d44661d588c169f3fc46d71a4138674a1dbc253a6a22a2a6d674ca170e34f1eaf98d51380e479151cb
data/CHANGELOG.md CHANGED
@@ -1,5 +1,28 @@
1
1
  ## [Unreleased]
2
2
 
3
+ ## [0.9.0] - 2026-11-23
4
+
5
+ - [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).
6
+ - Migration note: replace `Pbt.stateful(model:, sut:)` and per-command classes (`applicable?`, `run!`, `verify!`) with `Pbt.stateful { |m| m.initial_state ...; m.sut { ... }; m.command(:name) { |c| c.guard ...; c.arguments ...; c.next_state ...; c.run ...; c.verify ... } }`. See `README.md` for full examples.
7
+ - Add complete RBS type signatures under `sig/` (`sig/pbt.rbs`, `sig/pbt/*.rbs`, `sig/manifest.yaml`) with `rbs validate` and `steep check` in CI [#81](https://github.com/ohbarye/pbt/pull/81).
8
+ - Tighten `pbt.gemspec` packaged file allowlist to ship `lib/`, `sig/`, and root documentation only.
9
+ - Automatically create a GitHub Release in `.github/workflows/release.yml` when releasing a gem.
10
+
11
+ ## [0.8.0] - 2026-11-22
12
+
13
+ - [Breaking change] Drop support for Ruby 3.2 and earlier (EOL); Ruby 3.3 or later is now required, and Ruby 4.1.0-preview1 is added to CI [#66](https://github.com/ohbarye/pbt/pull/66)
14
+ - [Breaking change] Split literal constant selection into `Pbt.constant_from(*choices)` and change `Pbt.one_of(*arbitraries)` to select uniformly among arbitraries with contextual shrinking [#70](https://github.com/ohbarye/pbt/pull/70)
15
+ - Add `Pbt.frequency` weighted generators with contextual lazy shrink trees (`Arbitrary::Sample`) [#61](https://github.com/ohbarye/pbt/pull/61)
16
+ - Add `Pbt.statistics` for reproducible generator distribution inspection [#62](https://github.com/ohbarye/pbt/pull/62)
17
+ - Allow `Arbitrary#map` without an `unmapper` and with block syntax (`arb.map { |v| ... }`), shrinking via `Sample` provenance [#71](https://github.com/ohbarye/pbt/pull/71)
18
+ - Add 3-valued `Arbitrary#cover?(value)` (including `FloatArbitrary` for `Pbt.float`) and `RunnerIterator` `same_failure?` / `shrink_case` hooks [#72](https://github.com/ohbarye/pbt/pull/72)
19
+ - Document v1 Property DSL contract and fix positional Hash / strict lambda argument passing in `Check::Property#run` [#73](https://github.com/ohbarye/pbt/pull/73)
20
+ - Re-raise fatal exceptions (`SystemExit`, `SignalException`, `NoMemoryError`) in runners without shrinking [#74](https://github.com/ohbarye/pbt/pull/74)
21
+ - Bound `FilterArbitrary` generation retries with `max_attempts:` (raising `Pbt::Arbitrary::FilterExhaustedError`) to prevent infinite loops [#75](https://github.com/ohbarye/pbt/pull/75)
22
+ - Improve array shrinking (continue element shrinking at `min_length` and support non-contiguous element deletion) and fix `Pbt.nat` default `max` [#76](https://github.com/ohbarye/pbt/pull/76)
23
+ - Add `Pbt.assume` precondition helper with `max_skips` guard (`Pbt::TooManySkipsError`) and `RunDetails#num_skips` [#77](https://github.com/ohbarye/pbt/pull/77)
24
+ - Note: the current `Pbt.stateful(model:, sut:)` API is planned to be replaced with a redesigned DSL in v0.9.0 ([#67](https://github.com/ohbarye/pbt/issues/67)).
25
+
3
26
  ## [0.7.0] - 2026-04-04
4
27
 
5
28
  - [Breaking change] Simplify stateful command protocol: `arguments` must now accept `state` parameter, and `applicable?` must now accept both `state` and `args` parameters
data/README.md CHANGED
@@ -28,6 +28,8 @@ For a more in-depth understanding of Property-Based Testing, please refer to ext
28
28
 
29
29
  ## Installation
30
30
 
31
+ Ruby 3.3 or later is required. CI tests Ruby 3.3, 3.4, 4.0, and 4.1.0-preview1.
32
+
31
33
  Add this line to your application's Gemfile and run `bundle install`.
32
34
 
33
35
  ```ruby
@@ -77,16 +79,36 @@ The above snippet is very simple but contains the basic components.
77
79
 
78
80
  #### Runner
79
81
 
80
- `Pbt.assert` is the runner. The runner interprets and executes the given property. `Pbt.assert` takes a property and runs it multiple times. If the property fails, it tries to shrink the input that caused the failure.
82
+ `Pbt.assert` is the primary runner. It executes the property returned by the block multiple times, shrinks any failure, and raises `Pbt::PropertyFailure` with reproduction details.
83
+
84
+ If you want to inspect predicate failures without raising `Pbt::PropertyFailure`, use `Pbt.check`, which returns a `Pbt::Reporter::RunDetails` struct (`failed`, `num_runs`, `num_skips`, `num_shrinks`, `seed`, `counterexample`, `counterexample_path`, `error_message`, `error_instance`, `failures`, `verbose`, `execution_summary`, `run_configuration`). Exceptions raised during property construction or value generation still propagate to the caller.
85
+
86
+ #### Preconditions (`Pbt.assume`)
87
+
88
+ Use `Pbt.assume(condition)` inside a predicate to discard inputs that do not satisfy a precondition instead of returning early (which would count skipped inputs as passed runs):
89
+
90
+ ```ruby
91
+ Pbt.assert do
92
+ Pbt.property(Pbt.integer, Pbt.integer) do |x, y|
93
+ Pbt.assume(y != 0)
94
+ raise "unexpected" unless (x / y) * y + (x % y) == x
95
+ end
96
+ end
97
+ ```
81
98
 
82
- #### Property
99
+ Discarded cases do not count toward `num_runs` and are skipped during shrinking. If skips exceed `max_skips` (default: `num_runs * 10`), `Pbt.assert` raises `Pbt::TooManySkipsError` (`< Pbt::PropertyFailure`). Prefer narrowing your arbitrary when a precondition rejects most inputs.
83
100
 
84
- The snippet above declared a property by calling `Pbt.property`. The property describes the following:
101
+ #### Property (v1 DSL Contract)
85
102
 
86
- 1. What the user wants to evaluate. This corresponds to the block (let's call this `predicate`) enclosed by `do` `end`
87
- 2. How to generate inputs for the predicate — using `Arbitrary`
103
+ `Pbt` intentionally uses explicit runner/property composition (`Pbt.assert` / `Pbt.check` wrapping `Pbt.property` or `Pbt.stateful`):
88
104
 
89
- The `predicate` block is a function that directly asserts, taking values generated by `Arbitrary` as input.
105
+ 1. Runner options (`seed`, `num_runs`, `verbose`, `worker`) stay separated from generated inputs.
106
+ 2. Predicates fail by **raising** (including RSpec `expect(...)` and Minitest assertions under default `worker: :none`). Returning `false` alone does not fail a property.
107
+ 3. Argument passing rules:
108
+ - Single arbitrary: passed directly (`Pbt.property(Pbt.integer) { |n| ... }`)
109
+ - Multiple positional arbitraries: wrapped as a tuple (`Pbt.property(Pbt.integer, Pbt.symbol) { |n, sym| ... }`)
110
+ - Keyword arbitraries: wrapped as a fixed hash and passed as keyword arguments under `worker: :none` (`Pbt.property(left: Pbt.integer, right: Pbt.integer) { |left:, right:| ... }`). Under `worker: :ractor`, accept a single hash parameter (`{ |h| ... }`).
111
+ - Mixing positional and keyword arbitraries in one `Pbt.property` call raises `ArgumentError`.
90
112
 
91
113
  #### Arbitrary
92
114
 
@@ -138,103 +160,114 @@ Pbt.tuple(Pbt.symbol, Pbt.integer).generate # => [:atq, 42]
138
160
  Pbt.fixed_hash(x: Pbt.symbol, y: Pbt.integer).generate # => {x: :atq, y: 42}
139
161
  Pbt.hash(Pbt.symbol, Pbt.integer).generate # => {atq: 121, ygab: -1142}
140
162
 
141
- Pbt.one_of(:a, 1, 0.1).generate # => :a or 1 or 0.1
163
+ Pbt.constant_from(:a, 1, 0.1).generate # => :a or 1 or 0.1
164
+ Pbt.one_of(Pbt.integer, Pbt.constant(nil)).generate # => 42 or nil
165
+
166
+ Pbt.integer(min: 0, max: 10).map { |n| n * 2 }.generate # => 8
167
+ Pbt.integer(min: 0, max: 10).filter(&:even?).generate # => 4
142
168
  ````
143
169
 
144
170
  See [ArbitraryMethods](https://github.com/ohbarye/pbt/blob/main/lib/pbt/arbitrary/arbitrary_methods.rb) module for more details.
145
171
 
146
- ## Stateful Testing (Experimental)
147
-
148
- `Pbt` also provides an experimental stateful property API for model-based / command-based testing.
149
- It is designed as a property-compatible object (`generate`, `shrink`, `run`) so it works with the existing runner (`Pbt.assert` / `Pbt.check`) without changing the runner API.
150
-
151
- This API is still experimental. Expect interface refinements and behavior changes in future releases.
172
+ ### Weighted generators
152
173
 
153
- ### Minimal usage
174
+ Use `Pbt.frequency` to select generators by relative nonnegative integer weights:
154
175
 
155
176
  ```ruby
156
- class CounterModel
157
- def initialize
158
- @inc = IncrementCommand.new
177
+ Pbt.assert(seed: 42) do
178
+ Pbt.property(Pbt.frequency([3, Pbt.integer], [1, Pbt.constant(nil)])) do |value|
179
+ raise "unexpected value" unless value.nil? || value.is_a?(Integer)
159
180
  end
181
+ end
182
+ ```
160
183
 
161
- def initial_state
162
- 0
163
- end
184
+ At least one weight must be positive. Zero-weight generators are never selected.
185
+ Normal property execution retains the selected generator's shrink tree, including
186
+ inside arrays, tuples, fixed hashes, maps and filters. Shrinking stays within that
187
+ branch. Generated values and reported counterexamples remain ordinary Ruby values.
164
188
 
165
- def commands(_state)
166
- [@inc]
167
- end
189
+ For manual shrinking, retain a sample: `sample = arb.sample(Random.new(42))`,
190
+ 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.
195
+
196
+ ### Generator statistics
197
+
198
+ Inspect generated values before running a property:
199
+
200
+ ```ruby
201
+ stats = Pbt.statistics(Pbt.integer, num_runs: 1000, seed: 42) do |number|
202
+ number.negative? ? :negative : :nonnegative
168
203
  end
204
+ stats.counts # => counts grouped by label
205
+ stats.percentages # => unrounded percentages grouped by label
206
+ stats.seed # => 42; reuse this seed to replay the sample
207
+ ```
169
208
 
170
- class IncrementCommand
171
- def name
172
- :increment
173
- end
209
+ Without a block, actual generated values are counted. Each call generates exactly
210
+ `num_runs` values using its own seeded RNG; it does not execute a property or shrink
211
+ values. The default is 100 runs with a fresh seed, retained in the result. Zero runs
212
+ return empty counts and percentages. Counts are a mutable Hash local to the result;
213
+ values or labels used as its keys must remain stable. For generators that reuse mutable
214
+ objects, return a stable label from the block (for example, a symbol or integer).
215
+ Generator and classifier errors propagate to the caller.
174
216
 
175
- def arguments(_state)
176
- Pbt.nil
177
- end
217
+ ## Stateful Testing
178
218
 
179
- def applicable?(_state, _args)
180
- true
181
- end
219
+ `Pbt.stateful` provides a yield-based model DSL for stateful / command-based property testing.
220
+ It works directly with `Pbt.assert`, `Pbt.check`, `Pbt.statistics`, and `property.replay(run)` while preserving lexical `self` (so RSpec `expect(...)`/`let` and Minitest assertions work naturally inside callbacks).
182
221
 
183
- def next_state(state, _args)
184
- state + 1
185
- end
222
+ ### Usage
186
223
 
187
- def run!(sut, _args)
188
- sut.increment
189
- end
224
+ ```ruby
225
+ BankState = Data.define(:balance, :accounts)
190
226
 
191
- def verify!(before_state:, after_state:, args: _, result:, sut:)
192
- raise "unexpected result" unless result == after_state
193
- raise "state mismatch" unless after_state == before_state + 1
194
- raise "sut mismatch" unless sut.value == after_state
227
+ property = Pbt.stateful(min_steps: 1, max_steps: 20) do |m|
228
+ m.initial_state BankState.new(balance: 0, accounts: [])
229
+ m.sut { Bank.new }
230
+ m.teardown { |sut| sut.close } # or use `m.around { |initial_state, run| ... }`
231
+
232
+ m.invariant(:non_negative) do |state, sut|
233
+ raise "negative balance" unless sut.balance == state.balance && state.balance >= 0
195
234
  end
196
- end
197
235
 
198
- class Counter
199
- attr_reader :value
236
+ m.command(:deposit, weight: 3) do |c|
237
+ c.arguments Pbt.integer(min: 1, max: 100)
238
+ c.next_state { |s, amount| s.with(balance: s.balance + amount) }
239
+ c.run { |sut, amount| sut.deposit(amount) }
240
+ c.verify { |ctx| raise "mismatch" unless ctx.result == ctx.after.balance }
241
+ end
200
242
 
201
- def initialize
202
- @value = 0
243
+ m.command(:create_sub_account) do |c|
244
+ # `ref` is an opaque symbolic token (`Pbt::Stateful::Ref`) referencing this step's SUT return value.
245
+ c.next_state { |s, _args, ref| s.with(accounts: [*s.accounts, ref]) }
246
+ c.run { |sut| sut.create_sub_account }
203
247
  end
204
248
 
205
- def increment
206
- @value += 1
249
+ m.command(:close_sub_account) do |c|
250
+ c.guard { |s| !s.accounts.empty? }
251
+ c.arguments { |s| Pbt.constant_from(*s.accounts) }
252
+ c.next_state { |s, id| s.with(accounts: s.accounts - [id]) }
253
+ c.run { |sut, id| sut.close_sub_account(id) } # `id` is automatically resolved to the concrete SUT value
207
254
  end
208
255
  end
209
256
 
210
- Pbt.assert do
211
- Pbt.stateful(
212
- model: CounterModel.new,
213
- sut: -> { Counter.new },
214
- max_steps: 20
215
- )
216
- end
257
+ Pbt.assert(seed: 42) { property }
217
258
  ```
218
259
 
219
- ### Expected interfaces
260
+ ### Key capabilities
220
261
 
221
- `Pbt.stateful(model:, sut:, max_steps:)` expects the following duck-typed interfaces:
222
-
223
- - `model.initial_state`
224
- - `model.commands(state)` -> `Array<command>`
225
- - `command.name`
226
- - `command.arguments(state)` (a `Pbt` arbitrary, may depend on current model state)
227
- - `command.applicable?(state, args)` -> `true` / `false`
228
- - `command.next_state(state, args)` -> next model state
229
- - `command.run!(sut, args)` -> command result
230
- - `command.verify!(before_state:, after_state:, args:, result:, sut:)`
231
-
232
- ### Current limitations (MVP)
233
-
234
- - `Pbt.stateful` runs sequentially by default, even if the global worker is `:ractor`.
235
- - You can still pass `worker: :none` explicitly if you want to make that choice obvious in a test.
236
- - `worker: :ractor` is currently unsupported and raises `Pbt::InvalidConfiguration`.
237
- - Shrinking supports shorter prefixes and command-argument shrinking (using `command.arguments.shrink(args)`).
262
+ - **Model hooks (`m`)**:
263
+ - `m.initial_state`: accepts a static value, an `Arbitrary` (shrunk automatically on failure), or a zero-arg factory block. Model states are deep-frozen to catch accidental mutation immediately.
264
+ - `m.sut { |initial_state| ... }` + optional `m.teardown { |sut| ... }`, or `m.around { |initial_state, run| ... }` (mutually exclusive with `sut`/`teardown`; must call `run.call(sut)` once). Cleanup runs in `ensure` on every trial and shrink candidate.
265
+ - `m.command(name, weight: 1) { |c| ... }`: defines weighted commands with `c.guard`, `c.arguments` (arbitrary, keyword shorthand `c.arguments(k: arb)`, or state-dependent block `{ |state| arb }`), `c.precondition`, `c.next_state`, `c.run` (required), and `c.verify` (`Context` with `:step`, `:before`, `:after`, `:args`, `:result`, `:sut`).
266
+ - `m.invariant(name = nil) { |state, sut| ... }`: checked after SUT setup (before step 1) and after every step's `verify`.
267
+ - **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
+ - **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
+ - **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.
270
+ - **Worker behavior**: `Pbt.stateful` runs sequentially by default even when `Pbt.configuration.worker = :ractor`. Passing `worker: :ractor` explicitly raises `Pbt::InvalidConfiguration` before generation.
238
271
 
239
272
  ## What if property-based tests fail?
240
273
 
@@ -327,6 +360,10 @@ Pbt.configure do |config|
327
360
  # Whether to report exceptions in threads.
328
361
  # It's useful to suppress error logs on Ractor that reports many errors. Default is `false`.
329
362
  config.thread_report_on_exception = false
363
+
364
+ # Maximum number of skipped cases allowed via `Pbt.assume`.
365
+ # Defaults to `num_runs * 10` when `nil`.
366
+ config.max_skips = nil
330
367
  end
331
368
  ```
332
369
 
@@ -420,11 +457,11 @@ Once this project finishes the following, we will release v1.0.0.
420
457
  - [x] Rich report by verbose mode
421
458
  - [x] (Partially) Allow to use expectations and matchers provided by test framework in Ractor. (dropped)
422
459
  - It'd be so hard to pass assertions like `expect`, `assert` to a Ractor.
423
- - [ ] Implement frequency arbitrary
424
- - [ ] Statistics feature to aggregate generated values
425
- - [ ] Decide DSL
426
- - [ ] Try Fiber
427
- - [x] Stateful property-based testing (experimental, via `Pbt.stateful`)
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`)
428
465
 
429
466
  ## Development
430
467
 
@@ -1,8 +1,11 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "pbt/arbitrary/sample"
4
+
3
5
  module Pbt
4
6
  module Arbitrary
5
7
  class EmptyDomainError < ArgumentError; end
8
+ class FilterExhaustedError < StandardError; end
6
9
 
7
10
  # Abstract class for generating random values on type `T`.
8
11
  #
@@ -27,17 +30,66 @@ module Pbt
27
30
  raise NotImplementedError
28
31
  end
29
32
 
30
- # Create another arbitrary by applying `mapper` value by value.
33
+ # Normalize an arbitrary's 3-valued `cover?` result to `true`, `false`, or `nil`.
31
34
  #
32
- # @example
33
- # integer_generator = Pbt.integer
34
- # num_str_generator = integer_generator.map(->(n){ n.to_s }, ->(s) {s.to_i})
35
+ # @private
36
+ def self.cover_result(arbitrary, value)
37
+ return nil unless arbitrary.respond_to?(:cover?)
38
+
39
+ result = arbitrary.cover?(value)
40
+ (result == true || result == false) ? result : nil
41
+ end
42
+
43
+ # Check whether `value` belongs to this arbitrary's domain.
44
+ # Returns `true` if confirmed inside, `false` if confirmed outside,
45
+ # or `nil` if membership cannot be determined reliably (e.g. custom arbitraries).
46
+ #
47
+ # @param _value [Object]
48
+ # @return [Boolean, nil]
49
+ def cover?(_value)
50
+ nil
51
+ end
52
+
53
+ # Generate a value together with lazy shrinking provenance.
54
+ # @return [Sample]
55
+ def sample(rng = Random.new)
56
+ Sample.from_value(self, generate(rng))
57
+ end
58
+
59
+ # Whether property execution must retain a per-value shrink tree.
60
+ # @private
61
+ def contextual?
62
+ false
63
+ end
64
+
65
+ # Create another arbitrary by applying `mapper` (or a block) value by value.
66
+ # When `unmapper` is omitted, shrinking still works in `Pbt.property` and `sample`
67
+ # by preserving the underlying arbitrary's shrink tree.
68
+ #
69
+ # @example Block form (no unmapper required)
70
+ # Pbt.integer.map { |n| n.to_s }
35
71
  #
36
- # @param mapper [Proc] Proc to map generated values. Mainly used for generation.
37
- # @param unmapper [Proc] Proc to unmap generated values. Used for shrinking.
72
+ # @example Explicit mapper and unmapper (also supports bare `#shrink`)
73
+ # Pbt.integer.map(->(n) { n.to_s }, ->(s) { s.to_i })
74
+ #
75
+ # @param mapper [Proc, nil] Proc to map generated values.
76
+ # @param unmapper [Proc, nil] Optional proc to unmap generated values for bare `#shrink`.
38
77
  # @return [MapArbitrary] New arbitrary with mapped elements
39
- def map(mapper, unmapper)
40
- MapArbitrary.new(self, mapper, unmapper)
78
+ def map(mapper = nil, unmapper = nil, &block)
79
+ if mapper && block
80
+ raise ArgumentError, "map accepts either a mapper argument or a block, not both"
81
+ end
82
+
83
+ resolved_mapper = mapper || block
84
+ unless resolved_mapper.respond_to?(:call)
85
+ raise ArgumentError, "map requires a callable mapper or a block"
86
+ end
87
+
88
+ if !unmapper.nil? && !unmapper.respond_to?(:call)
89
+ raise ArgumentError, "unmapper must be callable or nil"
90
+ end
91
+
92
+ MapArbitrary.new(self, resolved_mapper, unmapper)
41
93
  end
42
94
 
43
95
  # Create another arbitrary by filtering values against `refinement`.
@@ -50,10 +102,11 @@ module Pbt
50
102
  # even_integer_generator = integer_generator.filter { |x| x.even? }
51
103
  # # or `integer_generator.filter(&:even?)`
52
104
  #
105
+ # @param max_attempts [Integer] Maximum generation attempts before raising `FilterExhaustedError`.
53
106
  # @param refinement [Proc] Predicate proc to test each produced element. Return true to keep the element, false otherwise.
54
107
  # @return [FilterArbitrary] New arbitrary filtered using `refinement`.
55
- def filter(&refinement)
56
- FilterArbitrary.new(self, &refinement)
108
+ def filter(max_attempts: FilterArbitrary::DEFAULT_MAX_ATTEMPTS, &refinement)
109
+ FilterArbitrary.new(self, max_attempts: max_attempts, &refinement)
57
110
  end
58
111
  end
59
112
  end
@@ -3,13 +3,16 @@
3
3
  require "pbt/arbitrary/arbitrary"
4
4
  require "pbt/arbitrary/constant"
5
5
  require "pbt/arbitrary/constant_arbitrary"
6
+ require "pbt/arbitrary/constant_from_arbitrary"
6
7
  require "pbt/arbitrary/array_arbitrary"
7
8
  require "pbt/arbitrary/integer_arbitrary"
8
9
  require "pbt/arbitrary/tuple_arbitrary"
9
10
  require "pbt/arbitrary/fixed_hash_arbitrary"
10
11
  require "pbt/arbitrary/choose_arbitrary"
11
12
  require "pbt/arbitrary/one_of_arbitrary"
13
+ require "pbt/arbitrary/frequency_arbitrary"
12
14
  require "pbt/arbitrary/map_arbitrary"
15
+ require "pbt/arbitrary/float_arbitrary"
13
16
  require "pbt/arbitrary/filter_arbitrary"
14
17
 
15
18
  module Pbt
@@ -28,7 +31,7 @@ module Pbt
28
31
  #
29
32
  # @param max [Integer] Upper limit for the generated integers (included).
30
33
  # @return [Arbitrary<Integer>]
31
- def nat(max: nil)
34
+ def nat(max: 1_000_000)
32
35
  integer(min: 0, max: max)
33
36
  end
34
37
 
@@ -68,28 +71,52 @@ module Pbt
68
71
 
69
72
  # Picks a random integer in the given range.
70
73
  #
71
- # @see Pbt.one_of
74
+ # @see Pbt.constant_from
72
75
  # @param range [Range<Integer>] Range of integers to choose from.
73
76
  # @return [Arbitrary<Integer>]
74
77
  def choose(range)
75
78
  ChooseArbitrary.new(range)
76
79
  end
77
80
 
78
- # Picks a random element from the given choices.
81
+ # Picks a random constant value from the given choices.
79
82
  # The choices can be of any type.
80
83
  #
81
- # @see Pbt.one_of
82
- # @param choices [Array<Object>] Array of choices.
83
- # @return [Arbitrary<Object>]
84
- def one_of(*choices)
85
- OneOfArbitrary.new(choices)
84
+ # @example
85
+ # Pbt.constant_from(:a, 1, 0.1).generate # => :a or 1 or 0.1
86
+ #
87
+ # @param choices [Array<Object>] Non-empty list of constant choices.
88
+ # @return [ConstantFromArbitrary]
89
+ def constant_from(*choices)
90
+ ConstantFromArbitrary.new(choices)
91
+ end
92
+
93
+ # Uniformly selects one of the given arbitraries and generates a value from it.
94
+ # Shrinks within the selected arbitrary when used with `Pbt.property` or `sample`.
95
+ #
96
+ # @example
97
+ # Pbt.one_of(Pbt.integer, Pbt.constant(nil))
98
+ #
99
+ # @param arbitraries [Array<Arbitrary>] Non-empty list of arbitraries.
100
+ # @return [OneOfArbitrary]
101
+ def one_of(*arbitraries)
102
+ OneOfArbitrary.new(arbitraries)
103
+ end
104
+
105
+ # Select a generator by relative integer weight. Zero-weight choices are ignored.
106
+ # Shrinks within the selected generator when used with Pbt.property or sample.
107
+ # @example
108
+ # Pbt.frequency([3, Pbt.integer], [1, Pbt.constant(nil)])
109
+ # @param choices [Array<Array(Integer, Arbitrary)>]
110
+ # @return [FrequencyArbitrary]
111
+ def frequency(*choices)
112
+ FrequencyArbitrary.new(choices)
86
113
  end
87
114
 
88
115
  # For a lowercase hexadecimal character.
89
116
  #
90
117
  # @return [Arbitrary<String>]
91
118
  def hexa
92
- one_of(*HEXA_CHARS)
119
+ constant_from(*HEXA_CHARS)
93
120
  end
94
121
 
95
122
  # For lowercase hexadecimal strings.
@@ -98,21 +125,21 @@ module Pbt
98
125
  # @param kwargs [Hash] Options for ArrayArbitrary. See `.array` for more information.
99
126
  # @return [Arbitrary<String>]
100
127
  def hexa_string(**kwargs)
101
- array(hexa, **kwargs).map(STRING_MAPPER, STRING_UNMAPPER)
128
+ MapArbitrary.new(array(hexa, **kwargs), STRING_MAPPER, STRING_UNMAPPER, bijective: true)
102
129
  end
103
130
 
104
131
  # For a single unicode character (including printable and non-printable).
105
132
  #
106
133
  # @return [Arbitrary<String>]
107
134
  def char
108
- choose(CHAR_RANGE).map(CHAR_MAPPER, CHAR_UNMAPPER)
135
+ MapArbitrary.new(choose(CHAR_RANGE), CHAR_MAPPER, CHAR_UNMAPPER, bijective: true)
109
136
  end
110
137
 
111
138
  # For an alphanumeric character.
112
139
  #
113
140
  # @return [Arbitrary<String>]
114
141
  def alphanumeric_char
115
- one_of(*ALPHANUMERIC_CHARS)
142
+ constant_from(*ALPHANUMERIC_CHARS)
116
143
  end
117
144
 
118
145
  # For alphanumeric strings.
@@ -121,14 +148,14 @@ module Pbt
121
148
  # @param kwargs [Hash] Options for ArrayArbitrary. See `.array` for more information.
122
149
  # @return [Arbitrary<String>]
123
150
  def alphanumeric_string(**kwargs)
124
- array(alphanumeric_char, **kwargs).map(STRING_MAPPER, STRING_UNMAPPER)
151
+ MapArbitrary.new(array(alphanumeric_char, **kwargs), STRING_MAPPER, STRING_UNMAPPER, bijective: true)
125
152
  end
126
153
 
127
154
  # For an ascii character.
128
155
  #
129
156
  # @return [Arbitrary<String>]
130
157
  def ascii_char
131
- one_of(*ASCII_CHARS)
158
+ constant_from(*ASCII_CHARS)
132
159
  end
133
160
 
134
161
  # For ascii strings.
@@ -137,14 +164,14 @@ module Pbt
137
164
  # @param kwargs [Hash] Options for ArrayArbitrary. See `.array` for more information.
138
165
  # @return [Arbitrary<String>]
139
166
  def ascii_string(**kwargs)
140
- array(ascii_char, **kwargs).map(STRING_MAPPER, STRING_UNMAPPER)
167
+ MapArbitrary.new(array(ascii_char, **kwargs), STRING_MAPPER, STRING_UNMAPPER, bijective: true)
141
168
  end
142
169
 
143
170
  # For a printable ascii character.
144
171
  #
145
172
  # @return [Arbitrary<String>]
146
173
  def printable_ascii_char
147
- one_of(*PRINTABLE_ASCII_CHARS)
174
+ constant_from(*PRINTABLE_ASCII_CHARS)
148
175
  end
149
176
 
150
177
  # For printable ascii strings.
@@ -153,14 +180,14 @@ module Pbt
153
180
  # @param kwargs [Hash] Options for ArrayArbitrary. See `.array` for more information.
154
181
  # @return [Arbitrary<String>]
155
182
  def printable_ascii_string(**kwargs)
156
- array(printable_ascii_char, **kwargs).map(STRING_MAPPER, STRING_UNMAPPER)
183
+ MapArbitrary.new(array(printable_ascii_char, **kwargs), STRING_MAPPER, STRING_UNMAPPER, bijective: true)
157
184
  end
158
185
 
159
186
  # For a printable character.
160
187
  #
161
188
  # @return [Arbitrary<String>]
162
189
  def printable_char
163
- one_of(*PRINTABLE_CHARS)
190
+ constant_from(*PRINTABLE_CHARS)
164
191
  end
165
192
 
166
193
  # For printable strings.
@@ -169,7 +196,7 @@ module Pbt
169
196
  # @param kwargs [Hash] Options for ArrayArbitrary. See `.array` for more information.
170
197
  # @return [Arbitrary<String>]
171
198
  def printable_string(**kwargs)
172
- array(printable_char, **kwargs).map(STRING_MAPPER, STRING_UNMAPPER)
199
+ MapArbitrary.new(array(printable_char, **kwargs), STRING_MAPPER, STRING_UNMAPPER, bijective: true)
173
200
  end
174
201
 
175
202
  # For symbols.
@@ -178,14 +205,14 @@ module Pbt
178
205
  # @param kwargs [Hash] Options for ArrayArbitrary. See `.array` for more information.
179
206
  # @return [Arbitrary<Symbol>]
180
207
  def symbol(**kwargs)
181
- array(one_of(*SYMBOL_SAFE_CHARS), empty: false, **kwargs).map(SYMBOL_MAPPER, SYMBOL_UNMAPPER)
208
+ MapArbitrary.new(array(constant_from(*SYMBOL_SAFE_CHARS), empty: false, **kwargs), SYMBOL_MAPPER, SYMBOL_UNMAPPER, bijective: true)
182
209
  end
183
210
 
184
211
  # For floats.
185
212
  #
186
213
  # @return [Arbitrary<Float>]
187
214
  def float
188
- tuple(integer, integer).map(FLOAT_MAPPER, FLOAT_UNMAPPER)
215
+ FloatArbitrary.new
189
216
  end
190
217
 
191
218
  # For symbols.
@@ -223,7 +250,7 @@ module Pbt
223
250
  #
224
251
  # @return [Arbitrary<Boolean>]
225
252
  def boolean
226
- one_of(true, false)
253
+ constant_from(true, false)
227
254
  end
228
255
 
229
256
  # For any constant values.
@@ -253,7 +280,7 @@ module Pbt
253
280
  # @return [Arbitrary<Date>]
254
281
  def date(base_date: Date.today, past_offset_days: -18250, future_offset_days: 18250)
255
282
  offset_arb = integer(min: past_offset_days, max: future_offset_days)
256
- offset_arb.map(DATE_MAPPER.call(base_date), DATE_UNMAPPER.call(base_date))
283
+ MapArbitrary.new(offset_arb, DATE_MAPPER.call(base_date), DATE_UNMAPPER.call(base_date), bijective: true)
257
284
  end
258
285
 
259
286
  # For past dates between `base_date - past_offset_days` and `base_date`.
@@ -282,7 +309,7 @@ module Pbt
282
309
  # @return [Arbitrary<Time>]
283
310
  def time(base_time: Time.now, past_offset_seconds: -1576800000, future_offset_seconds: 1576800000)
284
311
  offset_arb = integer(min: past_offset_seconds, max: future_offset_seconds)
285
- offset_arb.map(TIME_MAPPER.call(base_time), TIME_UNMAPPER.call(base_time))
312
+ MapArbitrary.new(offset_arb, TIME_MAPPER.call(base_time), TIME_UNMAPPER.call(base_time), bijective: true)
286
313
  end
287
314
 
288
315
  # For past times between `base_time + past_offset_seconds` and `base_time`