Python hypothesis.strategies() Examples
The following are 9
code examples of hypothesis.strategies().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
hypothesis
, or try the search function
.
Example #1
Source File: strategies-and-tactics.py From escape-from-automanual-testing with GNU Affero General Public License v3.0 | 5 votes |
def test_map_odd_numbers(x): assert x[-1] in "13579" # Takeaway # -------- # `.map` permits us to extend Hypothesis' core strategies in powerful # ways. See that it can be used to affect the individual values being # produced by a strategy (e.g. mapping integers to even-valued # integers), as well as to cast the values to a different type (e.g. # mapping an integer to a string. # # If it seems like a data-type is missing from Hypothesis' # strategies, then it is likely that a simple application of `.map` # will suffice. E.g. suppose you want a strategy that generate deques, # then # `deque_strat = st.lists(...).map(deque)` # will serve nicely - we don't even need a lambda! ############################################################################## # Defining recursive data. # There are a couple of ways to define recursive data with Hypothesis, # leaning on the fact that strategies are lazily instantiated. # # `st.recursive` takes a base strategy, and a function that takes a strategy # and returns an extended strategy. All good if we want that structure! # If you want mutual recursion though, or have a complicated kind of data # (or just limited time in a tutorial), `st.deferred` is the way to go. # # The `Record` exercise in pbt-101.py defined JSON using `st.recursive`, # if you want to compare them, and has some extension problems that you # could write as tests here instead. # JSON values are defined as one of null, false, true, a finite number, # a string, an array of json values, or a dict of string to json values.
Example #2
Source File: strategies-and-tactics.py From escape-from-automanual-testing with GNU Affero General Public License v3.0 | 5 votes |
def a_composite_strategy(draw): """Generates a (List[int], index) pair. The index points to a random positive element (>= 1); if there are no positive elements index is None. `draw` is used within a composite strategy as, e.g.:: >>> draw(st.booleans()) # can draw True or False True Note that `draw` is a reserved parameter that will be used by the `st.composite` decorator to interactively draw values from the strategies that you invoke within this function. That is, you need not pass a value to `draw` when calling this strategy:: >>> a_composite_strategy().example() ([-1, -2, -3, 4], 3) """ # TODO: draw a list, determine the allowed indices, and choose one to return lst = [] # TODO: draw a list of integers here index = None # TODO: determine the list of allowed indices, and choose one if non-empty return (lst, index)
Example #3
Source File: strategies-and-tactics.py From escape-from-automanual-testing with GNU Affero General Public License v3.0 | 5 votes |
def test_a_composite_strategy(value): lst, index = value assert all(isinstance(n, int) for n in lst) if index is None: assert all(n < 1 for n in lst) else: assert lst[index] >= 1 # Takeaway # -------- # Why generate a tuple with a `@composite` strategy instead of using two # separate strategies? This way we can ensure certain relationships between # the `lst` and `index` values! (You can get a similar effect with st.data(), # but the reporting and reproducibility isn't as nice.)
Example #4
Source File: _testing.py From deal with MIT License | 5 votes |
def get_examples(func: typing.Callable, kwargs: typing.Dict[str, typing.Any], count: int) -> typing.List[ArgsKwargsType]: kwargs = kwargs.copy() for name, value in kwargs.items(): if isinstance(value, hypothesis.strategies.SearchStrategy): continue kwargs[name] = hypothesis.strategies.just(value) def pass_along_variables(*args, **kwargs) -> ArgsKwargsType: return args, kwargs pass_along_variables.__signature__ = signature(func) # type: ignore pass_along_variables.__annotations__ = getattr(func, '__annotations__', {}) strategy = hypothesis.strategies.builds(pass_along_variables, **kwargs) examples = [] @hypothesis.given(strategy) @hypothesis.settings( database=None, max_examples=count, deadline=None, verbosity=hypothesis.Verbosity.quiet, phases=(hypothesis.Phase.generate,), suppress_health_check=hypothesis.HealthCheck.all(), ) def example_generator(ex: ArgsKwargsType) -> None: examples.append(ex) example_generator() # pylint: disable=no-value-for-parameter return examples
Example #5
Source File: test_custom_types.py From swagger-conformance with MIT License | 5 votes |
def test_colour_type_reg_for_fmt(self): """Test registering a template for a specific type/format works.""" value_factory = swaggerconformance.strategies.StrategyFactory() value_factory.register("string", "hexcolour", HexColourStrTemplate) self._run_test_colour_type(value_factory)
Example #6
Source File: test_custom_types.py From swagger-conformance with MIT License | 5 votes |
def test_colour_type_default_fmt(self): """Test registering a default template for a type works.""" value_factory = swaggerconformance.strategies.StrategyFactory() value_factory.register_type_default("string", HexColourStrTemplate) self._run_test_colour_type(value_factory)
Example #7
Source File: test_custom_types.py From swagger-conformance with MIT License | 5 votes |
def test_colour_int_codec(self): """Generate `Colour` objects and translate them to `int` at the point of building the JSON body, so the test only accesses `Colour` objects. """ value_factory = swaggerconformance.strategies.StrategyFactory() value_factory.register("integer", "intcolour", ColourObjTemplate) codec = swaggerconformance.codec.CodecFactory() codec.register("integer", "intcolour", ColourIntCodec) self._run_test_colour_type(codec, value_factory)
Example #8
Source File: test_custom_types.py From swagger-conformance with MIT License | 5 votes |
def test_colour_int_codec_with_hex(self): """Generating hex strings for '`intcolour`' fields still means they are converted to `Colour` objects and then to `int` inside the JSON. """ value_factory = swaggerconformance.strategies.StrategyFactory() value_factory.register("integer", "intcolour", HexColourStrTemplate) codec = swaggerconformance.codec.CodecFactory() codec.register("integer", "intcolour", ColourIntCodec) self._run_test_colour_type(codec, value_factory)
Example #9
Source File: test_custom_types.py From swagger-conformance with MIT License | 5 votes |
def test_scene_codec(self): """Test that JSON objects can be converted at both test edges.""" value_factory = swaggerconformance.strategies.StrategyFactory() value_factory.register("integer", "intcolour", ColourObjTemplate) value_factory.register("object", "scene", SceneTemplate) codec = swaggerconformance.codec.CodecFactory() codec.register("integer", "intcolour", ColourIntCodec) codec.register("object", "scene", SceneCodec) self._run_test_colour_type(codec, value_factory)