Python hypothesis.strategies.composite() Examples

The following are 11 code examples of hypothesis.strategies.composite(). 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.strategies , or try the search function .
Example #1
Source File: tough-bonus-problems.py    From escape-from-automanual-testing with GNU Affero General Public License v3.0 6 votes vote down vote up
def from_schema(schema):
    """Returns a strategy for objects that match the given schema."""
    check_schema(schema)
    # TODO: actually handle constraints on number/string/array schemas
    return dict(
        null=st.none(),
        bool=st.booleans(),
        number=st.floats(allow_nan=False),
        string=st.text(),
        array=st.lists(st.nothing()),
    )[schema["type"]]


# `@st.composite` is one way to write this - another would be to define a
# bare function, and `return st.one_of(st.none(), st.booleans(), ...)` so
# each strategy can be defined individually.  Use whichever seems more
# natural to you - the important thing in tests is usually readability! 
Example #2
Source File: strategies-and-tactics.py    From escape-from-automanual-testing with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_json_dumps(value):
    """Checks that value is serialisable as JSON."""
    # We expect this test to always pass - the point of this exercise is
    # to define a recursive strategy, and then investigate the values it
    # generates for a *passing* test.
    hypothesis.note("type: {}".format(type(value)))
    hypothesis.event("type: {}".format(type(value)))
    json.dumps(value)


# Takeaway: you've seen and played with a few ways to see what a
# passing test is doing, without having to inject a failure.


##############################################################################
# `@st.composite` exercise

# This goal of this exercise is to play with a contrived data dependency,
# using a composite strategy to generate inputs.  You can use the same tricks
# as above to check what's being generated, so try to keep the test passing! 
Example #3
Source File: strategies.py    From pymtl3 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def bits( nbits, signed=False, min_value=None, max_value=None ):
  BitsN = mk_bits( nbits )

  if (min_value is not None or max_value is not None) and signed:
    raise ValueError("bits strategy currently doesn't support setting "
                     "signedness and min/max value at the same time")

  if min_value is None:
    min_value = (-(2**(nbits-1))) if signed else 0
  if max_value is None:
    max_value = (2**(nbits-1)-1)  if signed else (2**nbits - 1)

  strat = st.booleans() if nbits == 1 else st.integers( min_value, max_value )

  @st.composite
  def strategy_bits( draw ):
    return BitsN( draw( strat ) )

  return strategy_bits() # RETURN A STRATEGY INSTEAD OF FUNCTION

#-------------------------------------------------------------------------
# strategies.bitslists
#-------------------------------------------------------------------------
# Return the SearchStrategy for a list of Bits with the support of
# dictionary based min/max value limit 
Example #4
Source File: test_prettyprinter.py    From prettyprinter with MIT License 6 votes vote down vote up
def possibly_commented(strategy):
    @st.composite
    def _strategy(draw):
        value = draw(strategy)

        add_trailing_comment = False
        if isinstance(value, (list, tuple, set)):
            add_trailing_comment = draw(st.booleans())

        add_comment = draw(st.booleans())

        if add_trailing_comment:
            comment_text = draw(st.text(alphabet='abcdefghijklmnopqrstuvwxyz #\\\'"'))
            value = trailing_comment(value, comment_text)

        if add_comment:
            comment_text = draw(st.text(alphabet='abcdefghijklmnopqrstuvwxyz #\\\'"'))
            value = comment(value, comment_text)

        return value

    return _strategy() 
Example #5
Source File: strategies-and-tactics.py    From escape-from-automanual-testing with GNU Affero General Public License v3.0 5 votes vote down vote up
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 #6
Source File: strategies-and-tactics.py    From escape-from-automanual-testing with GNU Affero General Public License v3.0 5 votes vote down vote up
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 #7
Source File: strategies.py    From pymtl3 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def bitslists( types, limit_dict=None ):
  # Make sure limit_dict becomes a dict, not None
  limit_dict = limit_dict or {}
  if not isinstance( limit_dict, dict ):
    raise TypeError( f"bitlist '{types}' doesn't not take '{limit_dict}' " \
                      "to specify min/max limit. Here only a dictionary " \
                      "like { 0:range(1,2), 1:range(3,4) } is accepted. " )

  # We capture the strategies inside a list inside closure of the
  # strategy. For each element, we recursively compose a strategy based on
  # the type and the field limit.

  strats = [ _strategy_dispatch( type_, limit_dict.get( i, None ) )
              for i, type_ in enumerate(types) ]

  @st.composite
  def strategy_list( draw ):
    return [ draw(strat) for strat in strats ]

  return strategy_list() # RETURN A STRATEGY INSTEAD OF FUNCTION

#-------------------------------------------------------------------------
# strategies.bitstructs
#-------------------------------------------------------------------------
# Return the SearchStrategy for bitstruct type T with the support of
# dictionary-based min/max value limit 
Example #8
Source File: strategies.py    From pymtl3 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def bitstructs( T, limit_dict=None ):
  # Make sure limit_dict becomes a dict, not None
  limit_dict = limit_dict or {}
  if not isinstance( limit_dict, dict ):
    raise TypeError( f"bitstruct '{T}' doesn't not take '{limit_dict}' " \
                      "to specify min/max limit. Here only a dictionary " \
                      "like { 'x':range(1,2), 'y':range(3,4), 'z': { ... } } is accepted. " )

  # We capture the fields of T inside a list inside closure of the
  # strategy. For each field, we recursively compose a strategy based on
  # the type and the field limit.

  strats = [ _strategy_dispatch( type_, limit_dict.get( name, None ) )
              for name, type_ in T.__bitstruct_fields__.items() ]

  @st.composite
  def strategy_bitstruct( draw ):
    # Since strats already preserves the order of bitstruct fields,
    # we can directly asterisk the generatort to pass in as *args
    return T( * (draw(strat) for strat in strats) )

  return strategy_bitstruct() # RETURN A STRATEGY INSTEAD OF FUNCTION

# Dispatch to construct corresponding strategy based on given type
# The type can be a list of types, a Bits type, or a nested
# bitstruct. For nested bitstruct, we recursively call the bitstruct(T)
# function to construct the strategy 
Example #9
Source File: hashable_strategies.py    From py-ssz with MIT License 5 votes vote down vote up
def bytevector_sedes_and_values_st(draw):
    size = draw(st.integers(1, 65))
    return ByteVector(size), bytevector_value_st(size)


#
# Strategies for composite sedes objects with corresponding value strategy
# 
Example #10
Source File: hashable_strategies.py    From py-ssz with MIT License 5 votes vote down vote up
def general_container_sedes_and_values_st(draw, element_sedes_and_elements_sequence):
    element_sedes, elements = zip(*element_sedes_and_elements_sequence)
    sedes = Container(element_sedes)
    values = st.tuples(*elements)
    return sedes, values


#
# Strategies for depth-1 composite sedes objects with corresponding value strategy
# 
Example #11
Source File: hashable_strategies.py    From py-ssz with MIT License 5 votes vote down vote up
def basic_container_sedes_and_values_st(draw, size=None):
    if size is None:
        size = draw(st.integers(min_value=1, max_value=4))

    element_sedes_and_elements_sequence = draw(
        st.lists(basic_sedes_and_values_st(), min_size=size, max_size=size)
    )
    return draw(
        general_container_sedes_and_values_st(element_sedes_and_elements_sequence)
    )


#
# Strategies for depth-2 composite sedes objects with corresponding value strategy
#