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
@@ -5,10 +5,14 @@ module Pbt
5
5
  # Represents a property to be tested.
6
6
  # This class holds an arbitrary to generate values and a predicate to test them.
7
7
  class Property
8
- # @param arb [Array<Arbitrary>]
8
+ # @param arb [Arbitrary]
9
+ # @param keyword_args [Boolean] Whether generated Hash values should be splatted as keyword arguments.
10
+ # @param splat_args [Boolean] Whether generated tuple values should be splatted as positional arguments.
9
11
  # @param predicate [Proc] Predicate proc to test the generated values. Library users write this.
10
- def initialize(arb, &predicate)
12
+ def initialize(arb, keyword_args: false, splat_args: false, &predicate)
11
13
  @arb = arb
14
+ @keyword_args = keyword_args
15
+ @splat_args = splat_args
12
16
  @predicate = predicate
13
17
  end
14
18
 
@@ -20,6 +24,15 @@ module Pbt
20
24
  @arb.generate(rng)
21
25
  end
22
26
 
27
+ # @private Generate with provenance only when a composite needs it.
28
+ def generate_for_check(rng)
29
+ if Arbitrary::Sample.contextual?(@arb)
30
+ Arbitrary::Sample.capture(@arb, rng)
31
+ else
32
+ generate(rng)
33
+ end
34
+ end
35
+
23
36
  # Shrink the `val` to a smaller one.
24
37
  # This is used to find the smallest failing case after a failure.
25
38
  #
@@ -34,8 +47,10 @@ module Pbt
34
47
  # @param val [Object]
35
48
  # @return [void]
36
49
  def run(val)
37
- if val.is_a?(Hash)
50
+ if @keyword_args
38
51
  @predicate.call(**val)
52
+ elsif @splat_args
53
+ @predicate.call(*val)
39
54
  else
40
55
  @predicate.call(val)
41
56
  end
@@ -47,7 +62,11 @@ module Pbt
47
62
  # @param val [Object]
48
63
  # @return [Ractor]
49
64
  def run_in_ractor(val)
50
- Ractor.new(val, &@predicate)
65
+ if @splat_args
66
+ Ractor.new(*val, &@predicate)
67
+ else
68
+ Ractor.new(val, &@predicate)
69
+ end
51
70
  end
52
71
  end
53
72
  end
@@ -12,13 +12,20 @@ module Pbt
12
12
  class RunnerIterator < DelegateClass(Array)
13
13
  attr_reader :run_execution
14
14
 
15
- # @param source_values [Enumerator] Enumerator of generated values by arbitrary. This is used to determine initial N (=`num_runs`) cases.
15
+ # @param source_values [Enumerator] Enumerator of generated values by arbitrary.
16
16
  # @param property [Property] Property to test. This is used to shrink the failed case.
17
17
  # @param verbose [Boolean] Controls the verbosity of the output.
18
- def initialize(source_values, property, verbose)
18
+ # @param target_runs [Integer, nil] Number of non-skipped runs to complete before stopping.
19
+ # @param max_skips [Integer, nil] Maximum number of skipped initial runs allowed via `Pbt.assume`.
20
+ def initialize(source_values, property, verbose, target_runs: nil, max_skips: nil)
19
21
  @run_execution = Reporter::RunExecution.new(verbose)
20
22
  @property = property
21
- @next_values = source_values
23
+ @source_stream = source_values
24
+ @target_runs = target_runs
25
+ @max_skips = max_skips
26
+ @initial_failure = nil
27
+ @initial_offset = 0
28
+ @next_values = @target_runs ? next_initial_batch(@target_runs) : source_values
22
29
  enumerator = Enumerator.new do |y|
23
30
  loop do
24
31
  y.yield @next_values.next
@@ -32,26 +39,93 @@ module Pbt
32
39
  #
33
40
  # @return [Boolean]
34
41
  def has_next?
35
- @next_values.peek
36
- true
37
- rescue StopIteration
42
+ return false if @run_execution.too_many_skips?
43
+
44
+ begin
45
+ @next_values.peek
46
+ true
47
+ rescue StopIteration
48
+ if @target_runs && @initial_failure.nil?
49
+ remaining = @target_runs - @run_execution.num_successes
50
+ if remaining.positive?
51
+ @next_values = next_initial_batch(remaining)
52
+ @next_values.peek
53
+ return true
54
+ end
55
+ end
56
+ false
57
+ end
58
+ end
59
+
60
+ # Map a pass-local index to the stream index during initial runs, or keep local index during shrinking.
61
+ #
62
+ # @param local_index [Integer]
63
+ # @return [Integer]
64
+ def case_index(local_index)
65
+ (@target_runs && @initial_failure.nil?) ? (@initial_offset + local_index) : local_index
66
+ end
67
+
68
+ # Handle a case discarded by `Pbt.assume`.
69
+ # During shrinking, skipped candidates are ignored without counting toward `max_skips`.
70
+ #
71
+ # @return [Boolean] whether the skip budget was exceeded and execution should stop
72
+ def handle_skip
73
+ return false if @initial_failure
74
+
75
+ @run_execution.record_skip
76
+ if @max_skips && @run_execution.num_skips > @max_skips
77
+ error = TooManySkipsError.new(
78
+ "Too many skipped runs: #{@run_execution.num_skips} skip(s) while attempting #{@target_runs} run(s) (#{@run_execution.num_successes} passed)"
79
+ )
80
+ @run_execution.record_too_many_skips(error)
81
+ return true
82
+ end
83
+
38
84
  false
39
85
  end
40
86
 
41
87
  # Handle result of a test.
42
- # When a test is successful, it records the success.
43
- # When a test is failed, it records the failure and set up the next values to test with property#shrink.
88
+ # When a test is successful, it records the success and returns false.
89
+ # When a test fails with an accepted failure, it records the failure, sets up the next shrink values,
90
+ # and returns true. When a shrink candidate fails with an unrelated error according to `property#same_failure?`,
91
+ # it is ignored and returns false so shrinking continues on the current level.
92
+ # Properties implementing `shrink_case(c)` must return an `Enumerator` (since `#has_next?` calls `#peek`).
44
93
  #
45
94
  # @param c [Case]
46
- # @return [void]
95
+ # @return [Boolean] whether the failure was accepted
47
96
  def handle_result(c)
48
97
  if c.exception
98
+ if @initial_failure && @property.respond_to?(:same_failure?) && !@property.same_failure?(@initial_failure, c.exception)
99
+ return false
100
+ end
101
+
49
102
  # failed run
103
+ @initial_failure ||= c.exception
50
104
  @run_execution.record_failure(c)
51
- @next_values = @property.shrink(c.val)
105
+ @next_values =
106
+ if @property.respond_to?(:shrink_case)
107
+ @property.shrink_case(c)
108
+ elsif c.sample
109
+ c.sample.shrink
110
+ else
111
+ @property.shrink(c.val)
112
+ end
113
+ true
52
114
  else
53
115
  # successful run
54
116
  @run_execution.record_success(c)
117
+ false
118
+ end
119
+ end
120
+
121
+ private
122
+
123
+ def next_initial_batch(count)
124
+ @initial_offset = @run_execution.num_successes + @run_execution.num_skips
125
+ Enumerator.new(count) do |y|
126
+ count.times do
127
+ y.yield @source_stream.next
128
+ end
55
129
  end
56
130
  end
57
131
  end
@@ -7,6 +7,9 @@ require "pbt/reporter/run_details_reporter"
7
7
 
8
8
  module Pbt
9
9
  module Check
10
+ # Exceptions that must never be treated as property failures or swallowed during shrinking.
11
+ FATAL_EXCEPTIONS = [SystemExit, SignalException, NoMemoryError].freeze
12
+
10
13
  # Module to be
11
14
  module RunnerMethods
12
15
  include Check::Tosser
@@ -36,19 +39,23 @@ module Pbt
36
39
  property = property.call
37
40
  config = Pbt.configuration.to_h.merge(options.to_h)
38
41
 
39
- if property.respond_to?(:stateful?) && property.stateful? && !options.key?(:worker)
40
- config[:worker] = :none
42
+ if property.respond_to?(:stateful?) && property.stateful?
43
+ if options.key?(:worker) && config[:worker] == :ractor
44
+ raise Pbt::InvalidConfiguration, "Pbt.stateful does not support worker: :ractor. Use worker: :none instead."
45
+ end
46
+
47
+ config[:worker] = :none unless options.key?(:worker)
41
48
  end
42
49
 
43
- initial_values = toss(property, config[:seed])
44
- source_values = Enumerator.new(config[:num_runs]) do |y|
45
- config[:num_runs].times do
46
- y.yield initial_values.next
47
- end
50
+ max_skips = config[:max_skips]
51
+ if !max_skips.nil? && !(max_skips.is_a?(Integer) && max_skips >= 0)
52
+ raise Pbt::InvalidConfiguration, "max_skips must be a non-negative Integer or nil"
48
53
  end
49
54
 
55
+ initial_values = toss(property, config[:seed])
56
+
50
57
  setup_for_ractor(config, property) do
51
- run_it(property, source_values, config).to_run_details(config)
58
+ run_it(property, initial_values, config).to_run_details(config)
52
59
  end
53
60
  end
54
61
 
@@ -78,11 +85,18 @@ module Pbt
78
85
  # Run the property test for each value.
79
86
  #
80
87
  # @param property [Property] Property to test.
81
- # @param source_values [Enumerator] Enumerator of values to test.
88
+ # @param source_values [Enumerator] Infinite enumerator of values to test.
82
89
  # @param config [Hash] Configuration parameters.
83
90
  # @return [RunExecution] Result of the test.
84
91
  def run_it(property, source_values, config)
85
- runner = Check::RunnerIterator.new(source_values, property, config[:verbose])
92
+ max_skips = config[:max_skips].nil? ? config[:num_runs] * 10 : config[:max_skips]
93
+ runner = Check::RunnerIterator.new(
94
+ source_values,
95
+ property,
96
+ config[:verbose],
97
+ target_runs: config[:num_runs],
98
+ max_skips: max_skips
99
+ )
86
100
  while runner.has_next?
87
101
  case config[:worker]
88
102
  in :none
@@ -99,15 +113,18 @@ module Pbt
99
113
  # @return [void]
100
114
  def run_it_in_sequential(property, runner)
101
115
  runner.each_with_index do |val, index|
102
- c = Case.new(val:, index:)
116
+ c = build_case(val, runner.case_index(index))
103
117
  begin
104
- property.run(val)
118
+ property.run(c.val)
105
119
  runner.handle_result(c)
106
- # Catch all exceptions including RSpec's ExpectationNotMet (It inherits Exception).
120
+ rescue PreconditionNotMet
121
+ break if runner.handle_skip
122
+ rescue *FATAL_EXCEPTIONS
123
+ raise
124
+ # Catch all other exceptions including RSpec's ExpectationNotMet (It inherits Exception).
107
125
  rescue Exception => e # standard:disable Lint/RescueException:
108
126
  c.exception = e
109
- runner.handle_result(c)
110
- break # Ignore the rest of the cases. Just pick up the first failure.
127
+ break if runner.handle_result(c) # Ignore the rest of the cases when failure is accepted.
111
128
  end
112
129
  end
113
130
  end
@@ -117,14 +134,31 @@ module Pbt
117
134
  # @return [void]
118
135
  def run_it_in_ractors(property, runner)
119
136
  runner.map.with_index { |val, index|
120
- Case.new(val:, index:, ractor: property.run_in_ractor(val))
137
+ c = build_case(val, runner.case_index(index))
138
+ c.ractor = property.run_in_ractor(c.val)
139
+ c
121
140
  }.each do |c|
122
141
  wait_ractor_result(c.ractor)
123
142
  runner.handle_result(c)
124
143
  rescue => e
125
- c.exception = unwrap_ractor_exception(e)
126
- runner.handle_result(c)
127
- break # Ignore the rest of the cases. Just pick up the first failure.
144
+ cause = unwrap_ractor_exception(e)
145
+ if cause.is_a?(PreconditionNotMet)
146
+ break if runner.handle_skip
147
+
148
+ next
149
+ end
150
+ raise cause if FATAL_EXCEPTIONS.any? { |klass| cause.is_a?(klass) }
151
+
152
+ c.exception = cause
153
+ break if runner.handle_result(c) # Ignore the rest of the cases when failure is accepted.
154
+ end
155
+ end
156
+
157
+ def build_case(value, index)
158
+ if value.is_a?(Arbitrary::Sample)
159
+ Case.new(val: value.value, sample: value, index: index)
160
+ else
161
+ Case.new(val: value, index: index)
128
162
  end
129
163
  end
130
164
 
@@ -25,7 +25,7 @@ module Pbt
25
25
  # @param arb [Arbitrary] Arbitrary to generate a value.
26
26
  # @param rng [Random] Random number generator.
27
27
  def toss_next(arb, rng)
28
- arb.generate(rng)
28
+ arb.respond_to?(:generate_for_check) ? arb.generate_for_check(rng) : arb.generate(rng)
29
29
  end
30
30
  end
31
31
  end
@@ -6,6 +6,7 @@ module Pbt
6
6
  RunDetails = Struct.new(
7
7
  :failed,
8
8
  :num_runs,
9
+ :num_skips,
9
10
  :num_shrinks,
10
11
  :seed,
11
12
  :counterexample,
@@ -15,8 +16,7 @@ module Pbt
15
16
  :failures,
16
17
  :verbose,
17
18
  :execution_summary,
18
- :run_configuration,
19
- keyword_init: true
19
+ :run_configuration
20
20
  )
21
21
  end
22
22
  end
@@ -15,6 +15,10 @@ module Pbt
15
15
  # @raise [PropertyFailure]
16
16
  def report_run_details
17
17
  if @run_details.failed
18
+ if @run_details.error_instance.is_a?(TooManySkipsError)
19
+ raise TooManySkipsError, format_too_many_skips_message
20
+ end
21
+
18
22
  message = []
19
23
  message << format_error_message
20
24
  message << error_backtrace
@@ -28,22 +32,60 @@ module Pbt
28
32
 
29
33
  private
30
34
 
35
+ # @return [String]
36
+ def format_too_many_skips_message
37
+ <<~MSG.chomp
38
+ #{@run_details.error_message}
39
+ seed: #{@run_details.seed}
40
+ Consider narrowing your arbitrary instead of relying heavily on Pbt.assume.
41
+ MSG
42
+ end
43
+
31
44
  # @return [String]
32
45
  def format_error_message
46
+ counterexample_str = format_counterexample
47
+ error_line = "Got #{@run_details.error_instance.class}: #{@run_details.error_message}"
48
+ if @run_details.error_instance.is_a?(Pbt::Stateful::StepFailure) && @run_details.error_instance.cause
49
+ error_line = "#{error_line}\n (cause: #{@run_details.error_instance.cause.class})"
50
+ end
51
+
33
52
  <<~MSG.chomp
34
53
  Property failed after #{@run_details.num_runs} test(s)
35
54
  seed: #{@run_details.seed}
36
- counterexample: #{@run_details.counterexample}
55
+ counterexample:#{counterexample_str}
37
56
  Shrunk #{@run_details.num_shrinks} time(s)
38
- Got #{@run_details.error_instance.class}: #{@run_details.error_message}
57
+ #{error_line}
39
58
  MSG
40
59
  end
41
60
 
61
+ def format_counterexample
62
+ ce = @run_details.counterexample
63
+ if ce.is_a?(Pbt::Stateful::Run)
64
+ err = @run_details.error_instance
65
+ formatted =
66
+ if err.is_a?(Pbt::Stateful::StepFailure)
67
+ ce.format(failed_step_index: err.step_index, failed_stage: err.stage)
68
+ else
69
+ ce.format
70
+ end
71
+ indented = formatted.lines.map { |line| " #{line.chomp}" }.join("\n")
72
+ "\n#{indented}"
73
+ else
74
+ " #{ce}"
75
+ end
76
+ end
77
+
42
78
  def error_backtrace
43
- return "" if @run_details.error_instance.backtrace_locations.nil? # It can be nil.
79
+ locations =
80
+ if @run_details.error_instance.is_a?(Pbt::Stateful::StepFailure)
81
+ @run_details.error_instance.backtrace || @run_details.error_instance.backtrace_locations
82
+ else
83
+ @run_details.error_instance.backtrace_locations
84
+ end
85
+ return "" if locations.nil? # It can be nil.
44
86
 
45
87
  i = @run_details.verbose ? -1 : 3
46
- " #{@run_details.error_instance.backtrace_locations[..i].join("\n ")}"
88
+ " #{locations[..i].join("\n ")}"
47
89
  end
48
90
 
49
91
  # @return [String]
@@ -6,12 +6,13 @@ module Pbt
6
6
  module Reporter
7
7
  # Represents the result of a single run of a property test.
8
8
  class RunExecution
9
+ attr_reader :num_successes, :num_skips
10
+
9
11
  # A tree node of the execution for verbose output.
10
12
  ExecutionTreeNode = Struct.new(
11
13
  :result,
12
14
  :value,
13
- :children,
14
- keyword_init: true
15
+ :children
15
16
  )
16
17
 
17
18
  # @param verbose [Boolean] Whether to print verbose output.
@@ -19,8 +20,11 @@ module Pbt
19
20
  @verbose = verbose
20
21
  @path_to_failure = []
21
22
  @failure = nil
23
+ @too_many_skips_error = nil
22
24
  @failures = []
23
25
  @num_successes = 0
26
+ @num_skips = 0
27
+ @num_runs_on_failure = nil
24
28
  @root_execution_trees = []
25
29
  @current_level_execution_trees = @root_execution_trees
26
30
  end
@@ -29,6 +33,7 @@ module Pbt
29
33
  #
30
34
  # @param c [Pbt::Check::Case]
31
35
  def record_failure(c)
36
+ @num_runs_on_failure ||= @num_successes + 1
32
37
  if @verbose
33
38
  current_tree = append_execution_tree_node(:failure, c.val)
34
39
  @current_level_execution_trees = current_tree.children
@@ -52,11 +57,31 @@ module Pbt
52
57
  @num_successes += 1
53
58
  end
54
59
 
60
+ # Record a skipped initial run (from `Pbt.assume`).
61
+ #
62
+ # @return [void]
63
+ def record_skip
64
+ @num_skips += 1
65
+ end
66
+
67
+ # Record a failure caused by exceeding `max_skips`.
68
+ #
69
+ # @param error [Pbt::TooManySkipsError]
70
+ # @return [void]
71
+ def record_too_many_skips(error)
72
+ @too_many_skips_error = error
73
+ end
74
+
75
+ # @return [Boolean]
76
+ def too_many_skips?
77
+ !@too_many_skips_error.nil?
78
+ end
79
+
55
80
  # Whether the test was successful.
56
81
  #
57
82
  # @return [Boolean]
58
83
  def success?
59
- !@failure
84
+ !@failure && !@too_many_skips_error
60
85
  end
61
86
 
62
87
  # Convert execution to run details.
@@ -68,6 +93,7 @@ module Pbt
68
93
  RunDetails.new(
69
94
  failed: false,
70
95
  num_runs: @num_successes,
96
+ num_skips: @num_skips,
71
97
  num_shrinks: 0,
72
98
  seed: config[:seed],
73
99
  counterexample: nil,
@@ -79,10 +105,27 @@ module Pbt
79
105
  execution_summary: @root_execution_trees,
80
106
  run_configuration: config
81
107
  )
108
+ elsif @too_many_skips_error
109
+ RunDetails.new(
110
+ failed: true,
111
+ num_runs: @num_successes,
112
+ num_skips: @num_skips,
113
+ num_shrinks: 0,
114
+ seed: config[:seed],
115
+ counterexample: nil,
116
+ counterexample_path: nil,
117
+ error_message: @too_many_skips_error.message,
118
+ error_instance: @too_many_skips_error,
119
+ failures: @failures,
120
+ verbose: @verbose,
121
+ execution_summary: @root_execution_trees,
122
+ run_configuration: config
123
+ )
82
124
  else
83
125
  RunDetails.new(
84
126
  failed: true,
85
- num_runs: @path_to_failure[0] + 1,
127
+ num_runs: @num_runs_on_failure,
128
+ num_skips: @num_skips,
86
129
  num_shrinks: @path_to_failure.size - 1,
87
130
  seed: config[:seed],
88
131
  counterexample: @value,