2828)
2929
3030from hypothesis .errors import (
31+ CannotInvert ,
3132 CannotProceedScopeT ,
3233 ChoiceTooLarge ,
3334 FlakyStrategyDefinition ,
4849 FloatConstraints ,
4950 IntegerConstraints ,
5051 StringConstraints ,
52+ ValueHole ,
5153 choice_constraints_key ,
5254 choice_from_index ,
5355 choice_permitted ,
@@ -139,6 +141,10 @@ def structural_coverage(label: int) -> StructuralCoverageTag:
139141# performance. We lose scan resistance, but that's probably fine here.
140142POOLED_CONSTRAINTS_CACHE : LRUCache [tuple [Any , ...], ChoiceConstraintsT ] = LRUCache (4096 )
141143
144+ # A tuple rather than a set so that ``in`` works even if a value's class has
145+ # an unhashable metaclass. Exact type checks also exclude symbolic backends.
146+ _PRIMITIVE_CHOICE_TYPES : tuple [type , ...] = (int , bool , str , bytes , float )
147+
142148
143149class Span :
144150 """A span tracks the hierarchical structure of choices within a single test run.
@@ -240,6 +246,13 @@ def children(self) -> "list[Span]":
240246 order."""
241247 return [self .owner [i ] for i in self .owner .children [self .index ]]
242248
249+ @property
250+ def recorded_value (self ) -> Any :
251+ """The value produced by the strategy draw corresponding to this span,
252+ or ``None`` if no value was recorded. Only values of the primitive
253+ choice types (int, bool, float, str, bytes) are recorded."""
254+ return self .owner .span_values .get (self .index )
255+
243256
244257class SpanProperty :
245258 """There are many properties of spans that we calculate by
@@ -325,6 +338,7 @@ def __init__(self) -> None:
325338 # The number of spans started so far, which is also the index that the
326339 # next span to start will get. Spans are indexed in start order.
327340 self .span_count = 0
341+ self .span_values : dict [int , Any ] = {}
328342
329343 def freeze (self ) -> None :
330344 self .__index_of_labels = None
@@ -348,6 +362,14 @@ def stop_span(self, *, discard: bool) -> None:
348362 else :
349363 self .trail .append (TrailType .STOP_SPAN_NO_DISCARD )
350364
365+ def record_value_for_span (self , span_index : int , value : Any ) -> None :
366+ # Record ``value`` against the span at ``span_index``, if it is one of
367+ # the primitive choice types. Called by ConjectureData.draw with the
368+ # value each strategy's do_draw returned.
369+ if type (value ) not in _PRIMITIVE_CHOICE_TYPES :
370+ return
371+ self .span_values [span_index ] = value
372+
351373
352374class _starts_and_ends (SpanProperty ):
353375 def __init__ (self , spans : "Spans" ) -> None :
@@ -447,6 +469,7 @@ class Spans:
447469 def __init__ (self , record : SpanRecord ) -> None :
448470 self .trail = record .trail
449471 self .labels = record .labels
472+ self .span_values = record .span_values
450473 self .__length = self .trail .count (
451474 TrailType .STOP_SPAN_DISCARD
452475 ) + record .trail .count (TrailType .STOP_SPAN_NO_DISCARD )
@@ -608,7 +631,7 @@ class ConjectureData:
608631 @classmethod
609632 def for_choices (
610633 cls ,
611- choices : Sequence [ChoiceTemplate | ChoiceT ],
634+ choices : Sequence [ChoiceTemplate | ValueHole | ChoiceT ],
612635 * ,
613636 observer : DataObserver | None = None ,
614637 provider : PrimitiveProvider | type [PrimitiveProvider ] = HypothesisProvider ,
@@ -630,7 +653,7 @@ def __init__(
630653 random : Random | None ,
631654 observer : DataObserver | None = None ,
632655 provider : PrimitiveProvider | type [PrimitiveProvider ] = HypothesisProvider ,
633- prefix : Sequence [ChoiceTemplate | ChoiceT ] | None = None ,
656+ prefix : Sequence [ChoiceTemplate | ValueHole | ChoiceT ] | None = None ,
634657 max_choices : int | None = None ,
635658 provider_kw : dict [str , Any ] | None = None ,
636659 ) -> None :
@@ -1079,6 +1102,19 @@ def _pop_choice(
10791102 self .mark_overrun ()
10801103 return choice
10811104
1105+ if isinstance (value , ValueHole ):
1106+ # A hole that no strategy claimed: either its value could not be
1107+ # inverted, or it fell out of alignment with strategy draw
1108+ # boundaries. Treat it as a misalignment.
1109+ if self .misaligned_at is None :
1110+ self .misaligned_at = (self .index , choice_type , constraints , forced )
1111+ try :
1112+ choice = choice_from_index (0 , choice_type , constraints )
1113+ except ChoiceTooLarge :
1114+ self .mark_overrun ()
1115+ self .index += 1
1116+ return choice
1117+
10821118 choice = value
10831119 node_choice_type = {
10841120 str : "string" ,
@@ -1203,11 +1239,35 @@ def draw(
12031239 label = unwrapped .label
12041240 assert isinstance (label , int )
12051241
1242+ # If the next prefix element is a ValueHole, we are the strategy being
1243+ # asked to re-encode its value: replace the hole with our inversion of
1244+ # it, and let do_draw consume those choices (under our own constraints)
1245+ # as usual. If we can't invert it, leave the hole for _pop_choice to
1246+ # treat as a misalignment.
1247+ if (
1248+ self .prefix is not None
1249+ and self .index < len (self .prefix )
1250+ and isinstance (hole := self .prefix [self .index ], ValueHole )
1251+ ):
1252+ try :
1253+ inverted = unwrapped ._invert (hole .value )
1254+ except CannotInvert :
1255+ pass
1256+ else :
1257+ self .prefix = (
1258+ tuple (self .prefix [: self .index ])
1259+ + inverted
1260+ + tuple (self .prefix [self .index + 1 :])
1261+ )
1262+
1263+ span_index = self .__span_record .span_count
12061264 self .start_span (label = label )
12071265 try :
12081266 if not at_top_level :
12091267 try :
1210- return unwrapped .do_draw (self )
1268+ v = unwrapped .do_draw (self )
1269+ self .__span_record .record_value_for_span (span_index , v )
1270+ return v
12111271 except FlakyStrategyDefinition as err :
12121272 # Record the strategy stack as the error unwinds, so that an
12131273 # inconsistent-generation failure is explained in terms of the
@@ -1234,6 +1294,7 @@ def draw(
12341294 if observability_enabled ():
12351295 avoid = self .provider .avoid_realization
12361296 self ._observability_args [key ] = to_jsonable (v , avoid_realization = avoid )
1297+ self .__span_record .record_value_for_span (span_index , v )
12371298 return v
12381299 finally :
12391300 self .stop_span ()
0 commit comments