Example #1
0
def sampled_from(elements):
    """Returns a strategy which generates any value present in the iterable
    elements.

    Note that as with just, values will not be copied and thus you
    should be careful of using mutable data

    """

    from hypothesis.searchstrategy.misc import SampledFromStrategy, \
        JustStrategy
    elements = tuple(iter(elements))
    if not elements:
        raise InvalidArgument(
            u'sampled_from requires at least one value'
        )
    if len(elements) == 1:
        result = JustStrategy(elements[0])
    else:
        result = SampledFromStrategy(elements)
    return ReprWrapperStrategy(
        result, u'sampled_from((%s))' % (u', '.join(
            map(unicode_safe_repr, elements)
        ))
    )
Example #2
0
def builds(target, *args, **kwargs):
    """Generates values by drawing from args and kwargs and passing them to
    target in the appropriate argument position.

    e.g. builds(target,
    integers(), flag=booleans()) would draw an integer i and a boolean b and
    call target(i, flag=b).

    """
    from hypothesis.internal.reflection import nicerepr

    def splat(value):
        return target(*value[0], **value[1])

    target_name = getattr(target, u'__name__', type(target).__name__)
    splat.__name__ = str(u'splat(%s)' % (target_name, ))

    def calc_repr():
        return u'builds(%s)' % (
            u', '.join([nicerepr(target)] + list(map(nicerepr, args)) +
                       sorted([u'%s=%r' % (k, v) for k, v in kwargs.items()])))

    return ReprWrapperStrategy(
        tuples(tuples(*args), fixed_dictionaries(kwargs)).map(splat),
        calc_repr)
Example #3
0
def just(value):
    """Return a strategy which only generates value.

    Note: value is not copied. Be wary of using mutable values.

    """
    from hypothesis.searchstrategy.misc import JustStrategy
    return ReprWrapperStrategy(
        JustStrategy(value), u'just(%s)' % (unicode_safe_repr(value),))
Example #4
0
def uuids():
    """Returns a strategy that generates UUIDs.

    All returned values from this will be unique, so e.g. if you do
    lists(uuids()) the resulting list will never contain duplicates.

    """
    from uuid import UUID
    return ReprWrapperStrategy(
        shared(randoms(), key='hypothesis.strategies.uuids.generator').map(
            lambda r: UUID(int=r.getrandbits(128))), 'uuids()')
Example #5
0
 def accept(*args, **kwargs):
     result = strategy_definition(*args, **kwargs)
     args, kwargs = convert_positional_arguments(strategy_definition, args,
                                                 kwargs)
     kwargs_for_repr = dict(kwargs)
     for k, v in defaults.items():
         if k in kwargs_for_repr and kwargs_for_repr[k] is defaults[k]:
             del kwargs_for_repr[k]
     representation = u'%s(%s)' % (strategy_definition.__name__,
                                   arg_string(strategy_definition, args,
                                              kwargs_for_repr))
     return ReprWrapperStrategy(result, representation)
Example #6
0
def builds(target, *args, **kwargs):
    """Generates values by drawing from args and kwargs and passing them to
    target in the appropriate argument position.

    e.g. builds(target,
    integers(), flag=booleans()) would draw an integer i and a boolean b and
    call target(i, flag=b).

    """
    def splat(value):
        return target(*value[0], **value[1])

    target_name = getattr(target, '__name__', type(target).__name__)
    splat.__name__ = str('splat(%s)' % (target_name, ))
    return ReprWrapperStrategy(
        tuples(tuples(*args), fixed_dictionaries(kwargs)).map(splat),
        'builds(%s, %s)' % (target_name, ', '.join(
            list(map(repr, args)) +
            ['%s=%r' % (k, v) for k, v in kwargs.items()])))
Example #7
0
def choices():
    """Strategy that generates a function that behaves like random.choice.

    Will note choices made for reproducibility.

    """
    from hypothesis.control import note, current_build_context

    def build_chooser(stream):
        index = [-1]
        choice_count = [0]
        context = current_build_context()
        context.mark_captured()

        def choice(values):
            if not values:
                raise IndexError('Cannot choose from empty sequence')
            k = len(values) - 1
            if k == 0:
                chosen = 0
            else:
                mask = _right_saturate(k)
                while True:
                    index[0] += 1
                    probe = stream[index[0]] & mask
                    if probe <= k:
                        chosen = probe
                        break
            choice_count[0] += 1
            result = values[chosen]
            with context.local():
                note('Choice #%d: %r' % (choice_count[0], result))
            return result

        return choice

    return ReprWrapperStrategy(
        shared(builds(build_chooser, streaming(integers(min_value=0))),
               key='hypothesis.strategies.chooser.choice_function'),
        'chooser()')
Example #8
0
def choices():
    """Strategy that generates a function that behaves like random.choice.

    Will note choices made for reproducibility.

    """
    from hypothesis.control import note, current_build_context
    from hypothesis.internal.conjecture.utils import choice

    class Chooser(object):

        def __init__(self, build_context, data):
            self.build_context = build_context
            self.data = data
            self.choice_count = 0

        def __call__(self, values):
            if not values:
                raise IndexError('Cannot choose from empty sequence')
            result = choice(self.data, values)
            with self.build_context.local():
                self.choice_count += 1
                note('Choice #%d: %r' % (self.choice_count, result))
            return result

        def __repr__(self):
            return 'choice'

    class ChoiceStrategy(SearchStrategy):
        supports_find = False

        def do_draw(self, data):
            return Chooser(current_build_context(), data)

    return ReprWrapperStrategy(
        shared(
            ChoiceStrategy(),
            key='hypothesis.strategies.chooser.choice_function'
        ), 'choices()')