Debian Codegraph @

hypothesis-python/src/hypothesis/strategies/_internal/featureflags.py

raw
1 # This file is part of Hypothesis, which may be found at
2 # https://github.com/HypothesisWorks/hypothesis/
3 #
4 # Copyright the Hypothesis Authors.
5 # Individual contributors are listed in AUTHORS.rst and the git log.
6 #
7 # This Source Code Form is subject to the terms of the Mozilla Public License,
8 # v. 2.0. If a copy of the MPL was not distributed with this file, You can
9 # obtain one at https://mozilla.org/MPL/2.0/.
10
11 from collections.abc import Hashable, Iterable, Sequence
12 from typing import Any
13
14 from hypothesis.internal.conjecture import utils as cu
15 from hypothesis.internal.conjecture.data import ConjectureData
16 from hypothesis.strategies._internal.strategies import SearchStrategy
17
18 FEATURE_LABEL = cu.calc_label_from_name("feature flag")
19
20
21 class FeatureFlags:
22 """Object that can be used to control a number of feature flags for a
23 given test run.
24
25 This enables an approach to data generation called swarm testing (
26 see Groce, Alex, et al. "Swarm testing." Proceedings of the 2012
27 International Symposium on Software Testing and Analysis. ACM, 2012), in
28 which generation is biased by selectively turning some features off for
29 each test case generated. When there are many interacting features this can
30 find bugs that a pure generation strategy would otherwise have missed.
31
32 FeatureFlags are designed to "shrink open", so that during shrinking they
33 become less restrictive. This allows us to potentially shrink to smaller
34 test cases that were forbidden during the generation phase because they
35 required disabled features.
36 """
37
38 def __init__(
39 self,
40 data: ConjectureData | None = None,
41 enabled: Sequence[Any] = (),
42 disabled: Sequence[Any] = (),
43 at_least_one_of: Iterable[Hashable] = (),
44 ):
45 self.__data = data
46 self.__is_disabled = {}
47
48 for f in enabled:
49 self.__is_disabled[f] = False
50
51 for f in disabled:
52 self.__is_disabled[f] = True
53
54 # In the original swarm testing paper they turn features on or off
55 # uniformly at random. Instead we decide the probability with which to
56 # enable features up front. This can allow for scenarios where all or
57 # no features are enabled, which are vanishingly unlikely in the
58 # original model.
59 #
60 # We implement this as a single 8-bit integer and enable features which
61 # score >= that value. In particular when self.__baseline is 0, all
62 # features will be enabled. This is so that we shrink in the direction
63 # of more features being enabled.
64 if self.__data is not None:
65 self.__p_disabled = self.__data.draw_integer(0, 254) / 255
66 else:
67 # If data is None we're in example mode so all that matters is the
68 # enabled/disabled lists above. We set this up so that everything
69 # else is enabled by default.
70 self.__p_disabled = 0.0
71
72 # The naive approach can lead to disabling e.g. every single rule on a
73 # RuleBasedStateMachine, which aborts the test as unable to make progress.
74 # Track the set of possible names, and ensure that at least one is enabled.
75 self.__at_least_one_of = set(at_least_one_of)
76
77 def is_enabled(self, name: Any) -> bool:
78 """Tests whether the feature named ``name`` should be enabled on this
79 test run."""
80 if self.__data is None or self.__data.frozen:
81 # Feature set objects might hang around after data generation has
82 # finished. If this happens then we just report all new features as
83 # enabled, because that's our shrinking direction and they have no
84 # impact on data generation if they weren't used while it was
85 # running.
86 return not self.__is_disabled.get(name, False)
87
88 data = self.__data
89
90 data.start_span(label=FEATURE_LABEL)
91
92 # If we've already decided on this feature then we don't actually
93 # need to draw anything, but we do write the same decision to the
94 # input stream. This allows us to lazily decide whether a feature
95 # is enabled, because it means that if we happen to delete the part
96 # of the test case where we originally decided, the next point at
97 # which we make this decision just makes the decision it previously
98 # made.
99 oneof = self.__at_least_one_of
100 is_disabled = self.__data.draw_boolean(
101 self.__p_disabled,
102 forced=(
103 False
104 if len(oneof) == 1 and name in oneof
105 else self.__is_disabled.get(name)
106 ),
107 )
108 self.__is_disabled[name] = is_disabled
109 if name in oneof and not is_disabled:
110 oneof.clear()
111 oneof.discard(name)
112 data.stop_span()
113 return not is_disabled
114
115 def __repr__(self) -> str:
116 enabled = []
117 disabled = []
118 for name, is_disabled in self.__is_disabled.items():
119 if is_disabled:
120 disabled.append(name)
121 else:
122 enabled.append(name)
123 return f"FeatureFlags({enabled=}, {disabled=})"
124
125
126 class FeatureStrategy(SearchStrategy[FeatureFlags]):
127 def __init__(self, at_least_one_of: Iterable[Hashable] = ()):
128 super().__init__()
129 self._at_least_one_of = frozenset(at_least_one_of)
130
131 def do_draw(self, data: ConjectureData) -> FeatureFlags:
132 return FeatureFlags(data, at_least_one_of=self._at_least_one_of)