Beispiel #1
0
 def pack(self, value):
     try:
         result = self.model(**value)
         result.save()
         return result
     except (IntegrityError, ValidationError):
         assume(False)
def test_density_voronoi_1(points):
    assume(does_not_raise_Qhull_error(points))
    assume(all_unique(points))

    cell_size = 0.1
    density = density_voronoi_1(points, cell_size=cell_size)
    assert True
Beispiel #3
0
 def pack(self, value):
     try:
         result = self.model(**value)
         result.save()
         return result
     except IntegrityError:
         assume(False)
Beispiel #4
0
 def do_draw(self, data):
     def draw_float_bytes(random, n):
         assert n == 8
         while True:
             i = random.randint(1, 10)
             if i <= 4:
                 f = random.choice(NASTY_FLOATS)
             elif i == 5:
                 return bytes_from_list(
                     random.randint(0, 255) for _ in range(8))
             elif i == 6:
                 f = random.random() * (
                     random.randint(0, 1) * 2 - 1
                 )
             elif i == 7:
                 f = random.gauss(0, 1)
             elif i == 8:
                 f = float(random.randint(-2 ** 63, 2 ** 63))
             else:
                 f = random.gauss(
                     random.randint(-2 ** 63, 2 ** 63), 1
                 )
             if self.permitted(f):
                 return struct.pack(b'!d', f)
     result = struct.unpack(b'!d', bytes(
         data.draw_bytes(8, draw_float_bytes)))[0]
     assume(self.permitted(result))
     return result
Beispiel #5
0
 def pack(self, value):
     try:
         result = self.model(**value)
         result.save()
         return result
     except (IntegrityError, ValidationError):
         assume(False)
Beispiel #6
0
    def do_draw(self, data):
        seen = set()
        result = []
        if self.max_size == self.min_size:
            while len(result) < self.max_size:
                v = data.draw(self.element_strategy)
                k = self.key(v)
                if k not in seen:
                    result.append(v)
                    seen.add(k)
            return result

        stopping_value = 1 - 1.0 / (1 + self.average_size)
        duplicates = 0
        while len(result) < self.max_size:
            data.start_example()
            if len(result) >= self.min_size:
                more = cu.biased_coin(data, stopping_value)
            else:
                more = True
            if not more:
                data.stop_example()
                break
            value = data.draw(self.element_strategy)
            data.stop_example()
            k = self.key(value)
            if k in seen:
                duplicates += 1
                assume(duplicates <= len(result))
                continue
            seen.add(k)
            result.append(value)
        assume(len(result) >= self.min_size)
        return result
 def splat(value):
     try:
         result = target(*value[0], **value[1])
         result.validate()
         return result
     except InvalidArgument:
         assume(False)
Beispiel #8
0
    def do_draw(self, data):
        def draw_float_bytes(random, n):
            assert n == 8
            while True:
                i = random.randint(1, 10)
                if i <= 4:
                    f = random.choice(NASTY_FLOATS)
                elif i == 5:
                    return bytes_from_list(
                        random.randint(0, 255) for _ in range(8))
                elif i == 6:
                    f = random.random() * (random.randint(0, 1) * 2 - 1)
                elif i == 7:
                    f = random.gauss(0, 1)
                elif i == 8:
                    f = float(random.randint(-2**63, 2**63))
                else:
                    f = random.gauss(random.randint(-2**63, 2**63), 1)
                if self.permitted(f):
                    return struct.pack(b'!d', f)

        result = struct.unpack(b'!d',
                               bytes(data.draw_bytes(8, draw_float_bytes)))[0]
        assume(self.permitted(result))
        return result
Beispiel #9
0
 def pack(self, value):
     try:
         result = self.model(**value)
         result.save()
         return result
     except IntegrityError:
         assume(False)
    def do_draw(self, data):
        seen = set()
        result = []
        if self.max_size == self.min_size:
            while len(result) < self.max_size:
                v = data.draw(self.element_strategy)
                k = self.key(v)
                if k not in seen:
                    result.append(v)
                    seen.add(k)
            return result

        stopping_value = 1 - 1.0 / (1 + self.average_size)
        duplicates = 0
        while len(result) < self.max_size:
            data.start_example()
            if len(result) >= self.min_size:
                more = cu.biased_coin(data, stopping_value)
            else:
                more = True
            if not more:
                data.stop_example()
                break
            value = data.draw(self.element_strategy)
            data.stop_example()
            k = self.key(value)
            if k in seen:
                duplicates += 1
                assume(duplicates <= len(result))
                continue
            seen.add(k)
            result.append(value)
        assume(len(result) >= self.min_size)
        return result
Beispiel #11
0
 def do_draw(self, data):
     f = self.lower_bound + (self.upper_bound -
                             self.lower_bound) * d.fractional_float(data)
     if self.width < 64:
         f = float_of(f, self.width)
     assume(self.lower_bound <= f <= self.upper_bound)
     return f
 def splat(value):
     try:
         result = target(*value[0], **value[1])
         result.validate()
         return result
     except InvalidArgument:
         assume(False)
Beispiel #13
0
 def build_dict(data):
     result = dict_class()
     for k, v in data:
         result[k] = v
         if max_size is not None and len(result) >= max_size:
             break
     assume(min_size is None or len(result) >= min_size)
     return result
Beispiel #14
0
 def build_dict(data):
     result = dict_class()
     for k, v in data:
         result[k] = v
         if max_size is not None and len(result) >= max_size:
             break
     assume(min_size is None or len(result) >= min_size)
     return result
Beispiel #15
0
 def do_draw(self, data):
     f = self.lower_bound + (self.upper_bound -
                             self.lower_bound) * d.fractional_float(data)
     if self.width < 64:
         f = float_of(f, self.width)
     assume(self.lower_bound <= f <= self.upper_bound)
     if not self.allow_subnormal:
         assume(f == 0 or abs(f) >= width_smallest_normals[self.width])
     return f
Beispiel #16
0
 def do_draw(self, data):
     f = self.lower_bound + (
         self.upper_bound - self.lower_bound) * d.fractional_float(data)
     assume(self.lower_bound <= f <= self.upper_bound)
     assume(sign(self.lower_bound) <= sign(f) <= sign(self.upper_bound))
     # Special handling for bounds of -0.0
     for g in [self.lower_bound, self.upper_bound]:
         if f == g:
             f = math.copysign(f, g)
     return f
Beispiel #17
0
 def do_draw(self, data):
     f = self.lower_bound + (self.upper_bound -
                             self.lower_bound) * d.fractional_float(data)
     if self.width < 64:
         try:
             f = float_of(f, self.width)
         except OverflowError:  # pragma: no cover
             reject()
     assume(self.lower_bound <= f <= self.upper_bound)
     return f
Beispiel #18
0
 def do_draw(self, data):
     for _ in hrange(3):
         start_index = data.index
         value = data.draw(self.filtered_strategy)
         if self.condition(value):
             return value
         else:
             # This is to guard against the case where we consume no data.
             # As long as we consume data, we'll eventually pass or raise.
             # But if we don't this could be an infinite loop.
             assume(data.index > start_index)
     data.mark_invalid()
Beispiel #19
0
 def do_draw(self, data):
     for _ in hrange(3):
         start_index = data.index
         value = data.draw(self.filtered_strategy)
         if self.condition(value):
             return value
         else:
             # This is to guard against the case where we consume no data.
             # As long as we consume data, we'll eventually pass or raise.
             # But if we don't this could be an infinite loop.
             assume(data.index > start_index)
     data.mark_invalid()
Beispiel #20
0
 def reify(self, template):
     tz = template[-1]
     d = dt.datetime(
         year=template[0], month=template[1], day=template[2],
         hour=template[3], minute=template[4], second=template[5],
         microsecond=template[6]
     )
     if tz:
         try:
             d = pytz.timezone(tz).localize(d)
         except OverflowError:
             assume(False)
     return d
Beispiel #21
0
    def do_draw(self, data):
        def draw_float_bytes(random, n):
            assert n == 8
            i = random.randint(0, 20)
            if i <= 2:
                f = random.choice(self.critical)
            else:
                f = random.random() * (self.upper_bound - self.lower_bound) + self.lower_bound
            return struct.pack(b"!d", f)

        f = struct.unpack(b"!d", bytes(data.draw_bytes(8, draw_float_bytes)))[0]
        assume(self.lower_bound <= f <= self.upper_bound)
        assume(sign(self.lower_bound) <= sign(f) <= sign(self.upper_bound))
        return f
    def default_do_filtered_draw(self, data):
        for i in hrange(3):
            start_index = data.index
            value = data.draw(self.filtered_strategy)
            if self.condition(value):
                return value
            else:
                if i == 0:
                    self.note_retried(data)
                # This is to guard against the case where we consume no data.
                # As long as we consume data, we'll eventually pass or raise.
                # But if we don't this could be an infinite loop.
                assume(data.index > start_index)

        return filter_not_satisfied
    def default_do_filtered_draw(self, data):
        for i in hrange(3):
            start_index = data.index
            value = data.draw(self.filtered_strategy)
            if self.condition(value):
                return value
            else:
                if i == 0:
                    self.note_retried(data)
                # This is to guard against the case where we consume no data.
                # As long as we consume data, we'll eventually pass or raise.
                # But if we don't this could be an infinite loop.
                assume(data.index > start_index)

        return filter_not_satisfied
Beispiel #24
0
    def do_draw(self, data):
        def draw_float_bytes(random, n):
            assert n == 8
            i = random.randint(0, 20)
            if i <= 2:
                f = random.choice(self.critical)
            else:
                f = random.random() * (self.upper_bound -
                                       self.lower_bound) + self.lower_bound
            return struct.pack(b'!d', f)

        f = struct.unpack(b'!d', bytes(data.draw_bytes(8,
                                                       draw_float_bytes)))[0]
        assume(self.lower_bound <= f <= self.upper_bound)
        assume(sign(self.lower_bound) <= sign(f) <= sign(self.upper_bound))
        return f
Beispiel #25
0
    def default_do_filtered_draw(self, data):
        for i in range(3):
            start_index = data.index
            data.start_example(FILTERED_SEARCH_STRATEGY_DO_DRAW_LABEL)
            value = data.draw(self.filtered_strategy)
            if self.condition(value):
                data.stop_example()
                return value
            else:
                data.stop_example(discard=True)
                if i == 0:
                    self.note_retried(data)
                # This is to guard against the case where we consume no data.
                # As long as we consume data, we'll eventually pass or raise.
                # But if we don't this could be an infinite loop.
                assume(data.index > start_index)

        return filter_not_satisfied
Beispiel #26
0
 def do_draw(self, data):
     for i in hrange(3):
         start_index = data.index
         value = data.draw(self.filtered_strategy)
         if self.condition(value):
             return value
         else:
             if i == 0:
                 data.note_event(lazyformat(
                     'Retried draw from %r to satisfy filter', self,))
             # This is to guard against the case where we consume no data.
             # As long as we consume data, we'll eventually pass or raise.
             # But if we don't this could be an infinite loop.
             assume(data.index > start_index)
     data.note_event('Aborted test because unable to satisfy %r' % (
         self,
     ))
     data.mark_invalid()
 def do_draw(self, data):
     for i in hrange(3):
         start_index = data.index
         value = data.draw(self.filtered_strategy)
         if self.condition(value):
             return value
         else:
             if i == 0:
                 data.note_event(deferredformat(
                     'Retried draw from %r to satisfy filter', self,))
             # This is to guard against the case where we consume no data.
             # As long as we consume data, we'll eventually pass or raise.
             # But if we don't this could be an infinite loop.
             assume(data.index > start_index)
     data.note_event('Aborted test because unable to satisfy %r' % (
         self,
     ))
     data.mark_invalid()
 def reify(self, template):
     assume(self.min_year <= template.year <= self.max_year)
     tz = template[-1]
     if tz is None:
         assume(self.allow_naive)
     else:
         assume(template.tzinfo in self.timezones)
     try:
         return template.to_datetime()
     except (OverflowError, ValueError):
         assume(False)
Beispiel #29
0
 def reify(self, template):
     assume(self.min_year <= template.year <= self.max_year)
     tz = template[-1]
     if tz is None:
         assume(self.allow_naive)
     else:
         assume(template.tzinfo in self.timezones)
     try:
         return template.to_datetime()
     except (OverflowError, ValueError):
         assume(False)
 def do_draw(self, data):
     # type: (ConjectureData) -> Ex
     for i in hrange(3):
         start_index = data.index
         value = data.draw(self.filtered_strategy)
         if self.condition(value):
             return value
         else:
             if i == 0:
                 data.note_event(
                     lazyformat("Retried draw from %r to satisfy filter",
                                self))
             # This is to guard against the case where we consume no data.
             # As long as we consume data, we'll eventually pass or raise.
             # But if we don't this could be an infinite loop.
             assume(data.index > start_index)
     data.note_event("Aborted test because unable to satisfy %r" % (self, ))
     data.mark_invalid()
     raise AssertionError("Unreachable, for Mypy")  # pragma: no cover
Beispiel #31
0
 def do_draw(self, data):
     # type: (ConjectureData) -> Ex
     for i in hrange(3):
         start_index = data.index
         value = data.draw(self.filtered_strategy)
         if self.condition(value):
             return value
         else:
             if i == 0:
                 data.note_event(lazyformat(
                     'Retried draw from %r to satisfy filter', self,))
             # This is to guard against the case where we consume no data.
             # As long as we consume data, we'll eventually pass or raise.
             # But if we don't this could be an infinite loop.
             assume(data.index > start_index)
     data.note_event('Aborted test because unable to satisfy %r' % (
         self,
     ))
     data.mark_invalid()
     raise AssertionError('Unreachable, for Mypy')  # pragma: no cover
Beispiel #32
0
 def reify(self, template):
     assert self.min_size <= template.size <= self.max_size
     if template.values is not None:
         assert len(template.values) == template.size
         seen = set()
         result = []
         for t in template.values:
             v = self.elements.reify(t)
             k = self.key(v)
             assume(k not in seen)
             seen.add(k)
             result.append(v)
         assert len(result) == len(template.values)
         return result
     values = []
     results = []
     seen = set()
     random = Random(template.template_seed)
     for i in range(template.size * 10):
         assert len(values) < template.size
         try:
             eltemplate = self.elements.draw_template(
                 random, template.parameter)
         except BadTemplateDraw:  # pragma: no cover
             continue
         elvalue = self.elements.reify(eltemplate)
         k = self.key(elvalue)
         if k in seen:
             continue
         seen.add(k)
         values.append(eltemplate)
         results.append(elvalue)
         if len(results) == template.size:
             template.values = values
             return results
     assume(len(results) >= self.min_size)
     template.values = values
     template.size = len(results)
     return results
Beispiel #33
0
 def reify(self, template):
     assert self.min_size <= template.size <= self.max_size
     if template.values is not None:
         assert len(template.values) == template.size
         seen = set()
         result = []
         for t in template.values:
             v = self.elements.reify(t)
             k = self.key(v)
             assume(k not in seen)
             seen.add(k)
             result.append(v)
         assert len(result) == len(template.values)
         return result
     values = []
     results = []
     seen = set()
     random = Random(template.template_seed)
     for i in range(template.size * 10):
         assert len(values) < template.size
         try:
             eltemplate = self.elements.draw_template(
                 random, template.parameter)
         except BadTemplateDraw:
             continue
         elvalue = self.elements.reify(eltemplate)
         k = self.key(elvalue)
         if k in seen:
             continue
         seen.add(k)
         values.append(eltemplate)
         results.append(elvalue)
         if len(results) == template.size:
             template.values = values
             return results
     assume(len(results) >= self.min_size)
     template.values = values
     template.size = len(results)
     return results
Beispiel #34
0
    def template_condition(template):
        result = search.reify(template)
        success = condition(result)

        if success:
            successful_examples[0] += 1

        if not successful_examples[0]:
            verbose_report(lambda: 'Trying example %s' % (show(result), ))
        elif success:
            if successful_examples[0] == 1:
                verbose_report(lambda: 'Found satisfying example %s' %
                               (show(result), ))
            else:
                verbose_report(lambda: 'Shrunk example to %s' %
                               (show(result), ))
        return assume(success)
Beispiel #35
0
    def template_condition(template):
        result = search.reify(template)
        success = condition(result)

        if success:
            successful_examples[0] += 1

        if not successful_examples[0]:
            verbose_report(lambda: 'Trying example %s' % (
                show(result),
            ))
        elif success:
            if successful_examples[0] == 1:
                verbose_report(lambda: 'Found satisfying example %s' % (
                    show(result),
                ))
            else:
                verbose_report(lambda: 'Shrunk example to %s' % (
                    show(result),
                ))
        return assume(success)
Beispiel #36
0
 def pack(self, value):
     assume(self.condition(value))
     return value
Beispiel #37
0
 def template_condition(template):
     return assume(condition(search.reify(template)))
Beispiel #38
0
 def do_draw(self, data):
     block = data.draw_bytes(self.block_size, self.distribution)
     assert len(block) == self.block_size
     value = self.from_bytes(block)
     assume(self.is_acceptable(value))
     return value
Beispiel #39
0
def floats(
    min_value=None, max_value=None, allow_nan=None, allow_infinity=None
):
    """Returns a strategy which generates floats.

    - If min_value is not None, all values will be >= min_value.
    - If max_value is not None, all values will be <= max_value.
    - If min_value or max_value is not None, it is an error to enable
      allow_nan.
    - If both min_value and max_value are not None, it is an error to enable
      allow_infinity.

    Where not explicitly ruled out by the bounds, all of infinity, -infinity
    and NaN are possible values generated by this strategy.

    """

    if allow_nan is None:
        allow_nan = bool(min_value is None and max_value is None)
    elif allow_nan:
        if min_value is not None or max_value is not None:
            raise InvalidArgument(
                u'Cannot have allow_nan=%r, with min_value or max_value' % (
                    allow_nan
                ))

    check_valid_bound(min_value, u'min_value')
    check_valid_bound(max_value, u'max_value')
    check_valid_interval(min_value, max_value, u'min_value', u'max_value')
    if min_value is not None:
        min_value = float(min_value)
    if max_value is not None:
        max_value = float(max_value)
    if min_value == float(u'-inf'):
        min_value = None
    if max_value == float(u'inf'):
        max_value = None

    if allow_infinity is None:
        allow_infinity = bool(min_value is None or max_value is None)
    elif allow_infinity:
        if min_value is not None and max_value is not None:
            raise InvalidArgument(
                u'Cannot have allow_infinity=%r, with both min_value and '
                u'max_value' % (
                    allow_infinity
                ))

    from hypothesis.searchstrategy.numbers import WrapperFloatStrategy, \
        GaussianFloatStrategy, BoundedFloatStrategy, ExponentialFloatStrategy,\
        JustIntFloats, NastyFloats, FullRangeFloats, \
        FixedBoundedFloatStrategy
    if min_value is None and max_value is None:
        return WrapperFloatStrategy(
            GaussianFloatStrategy() |
            BoundedFloatStrategy() |
            ExponentialFloatStrategy() |
            JustIntFloats() |
            NastyFloats(allow_nan, allow_infinity) |
            FullRangeFloats(allow_nan, allow_infinity)
        )
    elif min_value is not None and max_value is not None:
        if min_value == max_value:
            return just(min_value)
        elif math.isinf(max_value - min_value):
            assert min_value < 0 and max_value > 0
            return floats(min_value=0, max_value=max_value) | floats(
                min_value=min_value, max_value=0
            )
        elif count_between_floats(min_value, max_value) > 1000:
            critical_values = [
                min_value, max_value, min_value + (max_value - min_value) / 2]
            if min_value <= 0 <= max_value:
                if not is_negative(max_value):
                    critical_values.append(0.0)
                if is_negative(min_value):
                    critical_values.append(-0.0)
            return FixedBoundedFloatStrategy(
                lower_bound=min_value, upper_bound=max_value
            ) | sampled_from(critical_values)
        elif is_negative(max_value):
            assert is_negative(min_value)
            ub_int = float_to_int(max_value)
            lb_int = float_to_int(min_value)
            assert ub_int <= lb_int
            return integers(min_value=ub_int, max_value=lb_int).map(
                int_to_float
            )
        elif is_negative(min_value):
            return floats(min_value=min_value, max_value=-0.0) | floats(
                min_value=0, max_value=max_value
            )
        else:
            ub_int = float_to_int(max_value)
            lb_int = float_to_int(min_value)
            assert lb_int <= ub_int
            return integers(min_value=lb_int, max_value=ub_int).map(
                int_to_float
            )
    elif min_value is not None:
        critical_values = [min_value]
        if allow_infinity:
            critical_values.append(float(u'inf'))
        if is_negative(min_value):
            critical_values.append(-0.0)
        if min_value <= 0:
            critical_values.append(0.0)
        return (
            floats(allow_infinity=allow_infinity, allow_nan=False).map(
                lambda x: assume(not math.isnan(x)) and min_value + abs(x)
            )
        ) | sampled_from(critical_values)
    else:
        assert max_value is not None
        critical_values = [max_value]
        if allow_infinity:
            critical_values.append(float(u'-inf'))
        if max_value >= 0:
            critical_values.append(-0.0)
            if not is_negative(max_value):
                critical_values.append(0.0)
        return (
            floats(allow_infinity=allow_infinity, allow_nan=False).map(
                lambda x: assume(not math.isnan(x)) and max_value - abs(x)
            )
        ) | sampled_from(critical_values)
Beispiel #40
0
def floats(min_value=None, max_value=None):
    """Returns a strategy which generates floats. If min_value is not None,
    all values will be >= min_value. If max_value is not None, all values will
    be <= max_value.

    Where not explicitly ruled out by the bounds, all of infinity, -infinity
    and NaN are possible values generated by this strategy.
    """

    for e in (min_value, max_value):
        if e is not None and math.isnan(e):
            raise InvalidArgument(u'nan is not a valid end point')
    if min_value is not None:
        min_value = float(min_value)
    if max_value is not None:
        max_value = float(max_value)
    if min_value == float(u'-inf'):
        min_value = None
    if max_value == float(u'inf'):
        max_value = None

    from hypothesis.searchstrategy.numbers import WrapperFloatStrategy, \
        GaussianFloatStrategy, BoundedFloatStrategy, ExponentialFloatStrategy,\
        JustIntFloats, NastyFloats, FullRangeFloats, \
        FixedBoundedFloatStrategy
    if min_value is None and max_value is None:
        return WrapperFloatStrategy(GaussianFloatStrategy()
                                    | BoundedFloatStrategy()
                                    | ExponentialFloatStrategy()
                                    | JustIntFloats() | NastyFloats()
                                    | FullRangeFloats())
    elif min_value is not None and max_value is not None:
        if max_value < min_value:
            raise InvalidArgument(u'Cannot have max_value=%r < min_value=%r' %
                                  (max_value, min_value))
        elif min_value == max_value:
            return just(min_value)
        elif math.isinf(max_value - min_value):
            assert min_value < 0 and max_value > 0
            return floats(min_value=0, max_value=max_value) | floats(
                min_value=min_value, max_value=0)
        elif count_between_floats(min_value, max_value) > 1000:
            critical_values = [
                min_value, max_value, min_value + (max_value - min_value) / 2
            ]
            if min_value <= 0 <= max_value:
                if not is_negative(max_value):
                    critical_values.append(0.0)
                if is_negative(min_value):
                    critical_values.append(-0.0)
            return FixedBoundedFloatStrategy(
                lower_bound=min_value,
                upper_bound=max_value) | sampled_from(critical_values)
        elif is_negative(max_value):
            assert is_negative(min_value)
            ub_int = float_to_int(max_value)
            lb_int = float_to_int(min_value)
            assert ub_int <= lb_int
            return integers(min_value=ub_int,
                            max_value=lb_int).map(int_to_float)
        elif is_negative(min_value):
            return floats(min_value=min_value, max_value=-0.0) | floats(
                min_value=0, max_value=max_value)
        else:
            ub_int = float_to_int(max_value)
            lb_int = float_to_int(min_value)
            assert lb_int <= ub_int
            return integers(min_value=lb_int,
                            max_value=ub_int).map(int_to_float)
    elif min_value is not None:
        critical_values = [min_value, float(u'inf')]
        if is_negative(min_value):
            critical_values.append(-0.0)
        if min_value <= 0:
            critical_values.append(0.0)
        return (floats().map(lambda x: assume(not math.isnan(x)) and min_value
                             + abs(x))) | sampled_from(critical_values)
    else:
        assert max_value is not None
        critical_values = [max_value, float(u'-inf')]
        if max_value >= 0:
            critical_values.append(-0.0)
            if not is_negative(max_value):
                critical_values.append(0.0)
        return (floats().map(lambda x: assume(not math.isnan(x)) and max_value
                             - abs(x))) | sampled_from(critical_values)
Beispiel #41
0
def floats(min_value=None, max_value=None):
    """Returns a strategy which generates floats. If min_value is not None,
    all values will be >= min_value. If max_value is not None, all values will
    be <= max_value.

    Where not explicitly ruled out by the bounds, all of infinity, -infinity
    and NaN are possible values generated by this strategy.
    """

    for e in (min_value, max_value):
        if e is not None and math.isnan(e):
            raise InvalidArgument(u'nan is not a valid end point')
    if min_value is not None:
        min_value = float(min_value)
    if max_value is not None:
        max_value = float(max_value)
    if min_value == float(u'-inf'):
        min_value = None
    if max_value == float(u'inf'):
        max_value = None

    from hypothesis.searchstrategy.numbers import WrapperFloatStrategy, \
        GaussianFloatStrategy, BoundedFloatStrategy, ExponentialFloatStrategy,\
        JustIntFloats, NastyFloats, FullRangeFloats, \
        FixedBoundedFloatStrategy
    if min_value is None and max_value is None:
        return WrapperFloatStrategy(
            GaussianFloatStrategy() |
            BoundedFloatStrategy() |
            ExponentialFloatStrategy() |
            JustIntFloats() |
            NastyFloats() |
            FullRangeFloats()
        )
    elif min_value is not None and max_value is not None:
        if max_value < min_value:
            raise InvalidArgument(
                u'Cannot have max_value=%r < min_value=%r' % (
                    max_value, min_value
                ))
        elif min_value == max_value:
            return just(min_value)
        elif math.isinf(max_value - min_value):
            assert min_value < 0 and max_value > 0
            return floats(min_value=0, max_value=max_value) | floats(
                min_value=min_value, max_value=0
            )
        elif count_between_floats(min_value, max_value) > 1000:
            critical_values = [
                min_value, max_value, min_value + (max_value - min_value) / 2]
            if min_value <= 0 <= max_value:
                if not is_negative(max_value):
                    critical_values.append(0.0)
                if is_negative(min_value):
                    critical_values.append(-0.0)
            return FixedBoundedFloatStrategy(
                lower_bound=min_value, upper_bound=max_value
            ) | sampled_from(critical_values)
        elif is_negative(max_value):
            assert is_negative(min_value)
            ub_int = float_to_int(max_value)
            lb_int = float_to_int(min_value)
            assert ub_int <= lb_int
            return integers(min_value=ub_int, max_value=lb_int).map(
                int_to_float
            )
        elif is_negative(min_value):
            return floats(min_value=min_value, max_value=-0.0) | floats(
                min_value=0, max_value=max_value
            )
        else:
            ub_int = float_to_int(max_value)
            lb_int = float_to_int(min_value)
            assert lb_int <= ub_int
            return integers(min_value=lb_int, max_value=ub_int).map(
                int_to_float
            )
    elif min_value is not None:
        critical_values = [min_value, float(u'inf')]
        if is_negative(min_value):
            critical_values.append(-0.0)
        if min_value <= 0:
            critical_values.append(0.0)
        return (
            floats().map(
                lambda x: assume(not math.isnan(x)) and min_value + abs(x)
            )
        ) | sampled_from(critical_values)
    else:
        assert max_value is not None
        critical_values = [max_value, float(u'-inf')]
        if max_value >= 0:
            critical_values.append(-0.0)
            if not is_negative(max_value):
                critical_values.append(0.0)
        return (
            floats().map(
                lambda x: assume(not math.isnan(x)) and max_value - abs(x)
            )
        ) | sampled_from(critical_values)
Beispiel #42
0
 def pack(self, value):
     assume(self.condition(value))
     return value
Beispiel #43
0
def floats(
    min_value=None, max_value=None, allow_nan=None, allow_infinity=None
):
    """Returns a strategy which generates floats.

    - If min_value is not None, all values will be >= min_value.
    - If max_value is not None, all values will be <= max_value.
    - If min_value or max_value is not None, it is an error to enable
      allow_nan.
    - If both min_value and max_value are not None, it is an error to enable
      allow_infinity.

    Where not explicitly ruled out by the bounds, all of infinity, -infinity
    and NaN are possible values generated by this strategy.

    """

    if allow_nan is None:
        allow_nan = bool(min_value is None and max_value is None)
    elif allow_nan:
        if min_value is not None or max_value is not None:
            raise InvalidArgument(
                'Cannot have allow_nan=%r, with min_value or max_value' % (
                    allow_nan
                ))

    check_valid_bound(min_value, 'min_value')
    check_valid_bound(max_value, 'max_value')
    check_valid_interval(min_value, max_value, 'min_value', 'max_value')
    if min_value is not None:
        min_value = float(min_value)
    if max_value is not None:
        max_value = float(max_value)
    if min_value == float(u'-inf'):
        min_value = None
    if max_value == float(u'inf'):
        max_value = None

    if allow_infinity is None:
        allow_infinity = bool(min_value is None or max_value is None)
    elif allow_infinity:
        if min_value is not None and max_value is not None:
            raise InvalidArgument(
                'Cannot have allow_infinity=%r, with both min_value and '
                'max_value' % (
                    allow_infinity
                ))

    from hypothesis.searchstrategy.numbers import FloatStrategy, \
        FixedBoundedFloatStrategy
    if min_value is None and max_value is None:
        return FloatStrategy(
            allow_infinity=allow_infinity, allow_nan=allow_nan,
        )
    elif min_value is not None and max_value is not None:
        if min_value == max_value:
            return just(min_value)
        elif math.isinf(max_value - min_value):
            assert min_value < 0 and max_value > 0
            return floats(min_value=0, max_value=max_value) | floats(
                min_value=min_value, max_value=0
            )
        elif count_between_floats(min_value, max_value) > 1000:
            return FixedBoundedFloatStrategy(
                lower_bound=min_value, upper_bound=max_value
            )
        elif is_negative(max_value):
            assert is_negative(min_value)
            ub_int = float_to_int(max_value)
            lb_int = float_to_int(min_value)
            assert ub_int <= lb_int
            return integers(min_value=ub_int, max_value=lb_int).map(
                int_to_float
            )
        elif is_negative(min_value):
            return floats(min_value=min_value, max_value=-0.0) | floats(
                min_value=0, max_value=max_value
            )
        else:
            ub_int = float_to_int(max_value)
            lb_int = float_to_int(min_value)
            assert lb_int <= ub_int
            return integers(min_value=lb_int, max_value=ub_int).map(
                int_to_float
            )
    elif min_value is not None:
        if min_value < 0:
            result = floats(
                min_value=0.0
            ) | floats(min_value=min_value, max_value=0.0)
        else:
            result = (
                floats(allow_infinity=allow_infinity, allow_nan=False).map(
                    lambda x: assume(not math.isnan(x)) and min_value + abs(x)
                )
            )
        if min_value == 0 and not is_negative(min_value):
            result = result.filter(lambda x: math.copysign(1.0, x) == 1)
        return result
    else:
        assert max_value is not None
        if max_value > 0:
            result = floats(
                min_value=0.0,
                max_value=max_value,
            ) | floats(max_value=0.0)
        else:
            result = (
                floats(allow_infinity=allow_infinity, allow_nan=False).map(
                    lambda x: assume(not math.isnan(x)) and max_value - abs(x)
                )
            )
        if max_value == 0 and is_negative(max_value):
            result = result.filter(is_negative)
        return result
Beispiel #44
0
 def splat(value):
     try:
         return target(*value[0], **value[1])
     except InvalidArgument:
         assume(False)
Beispiel #45
0
 def template_condition(template):
     return assume(condition(search.reify(template)))
 def do_draw(self, data):
     b = int_from_bytes(data.draw_bytes(2))
     assume(b == 3)
     print('ohai')
def test_insertInsertWeak(k1, v1, k2, v2, t):
    control.assume(k1 != k2)
    assert eqWeak(insert((k1, v1), insert((k2, v2), t)),
                  insert((k2, v2), insert((k1, v1), t)))
def test_deleteInsertWeak(k1, k2, v2, t):
    control.assume(k1 != k2)
    assert eqWeak(delete(k1, insert((k2, v2), t)),
                  insert((k2, v2), delete(k1, t)))
Beispiel #49
0
 def trade(self, offer, buyer):
     assume(offer.id in self.market.offers)
     self.market.accept_offer(offer, buyer)
 def do_draw(self, data):
     b = int_from_bytes(data.draw_bytes(2))
     assume(b == 3)
     print('ohai')
Beispiel #51
0
def floats(min_value=None,
           max_value=None,
           allow_nan=None,
           allow_infinity=None):
    """Returns a strategy which generates floats.

    - If min_value is not None, all values will be >= min_value.
    - If max_value is not None, all values will be <= max_value.
    - If min_value or max_value is not None, it is an error to enable
      allow_nan.
    - If both min_value and max_value are not None, it is an error to enable
      allow_infinity.

    Where not explicitly ruled out by the bounds, all of infinity, -infinity
    and NaN are possible values generated by this strategy.

    """

    if allow_nan is None:
        allow_nan = bool(min_value is None and max_value is None)
    elif allow_nan:
        if min_value is not None or max_value is not None:
            raise InvalidArgument(
                'Cannot have allow_nan=%r, with min_value or max_value' %
                (allow_nan))

    check_valid_bound(min_value, 'min_value')
    check_valid_bound(max_value, 'max_value')
    check_valid_interval(min_value, max_value, 'min_value', 'max_value')
    if min_value is not None:
        min_value = float(min_value)
    if max_value is not None:
        max_value = float(max_value)
    if min_value == float(u'-inf'):
        min_value = None
    if max_value == float(u'inf'):
        max_value = None

    if allow_infinity is None:
        allow_infinity = bool(min_value is None or max_value is None)
    elif allow_infinity:
        if min_value is not None and max_value is not None:
            raise InvalidArgument(
                'Cannot have allow_infinity=%r, with both min_value and '
                'max_value' % (allow_infinity))

    from hypothesis.searchstrategy.numbers import FloatStrategy, \
        FixedBoundedFloatStrategy
    if min_value is None and max_value is None:
        return FloatStrategy(
            allow_infinity=allow_infinity,
            allow_nan=allow_nan,
        )
    elif min_value is not None and max_value is not None:
        if min_value == max_value:
            return just(min_value)
        elif math.isinf(max_value - min_value):
            assert min_value < 0 and max_value > 0
            return floats(min_value=0, max_value=max_value) | floats(
                min_value=min_value, max_value=0)
        elif count_between_floats(min_value, max_value) > 1000:
            return FixedBoundedFloatStrategy(lower_bound=min_value,
                                             upper_bound=max_value)
        elif is_negative(max_value):
            assert is_negative(min_value)
            ub_int = float_to_int(max_value)
            lb_int = float_to_int(min_value)
            assert ub_int <= lb_int
            return integers(min_value=ub_int,
                            max_value=lb_int).map(int_to_float)
        elif is_negative(min_value):
            return floats(min_value=min_value, max_value=-0.0) | floats(
                min_value=0, max_value=max_value)
        else:
            ub_int = float_to_int(max_value)
            lb_int = float_to_int(min_value)
            assert lb_int <= ub_int
            return integers(min_value=lb_int,
                            max_value=ub_int).map(int_to_float)
    elif min_value is not None:
        if min_value < 0:
            result = floats(min_value=0.0) | floats(min_value=min_value,
                                                    max_value=0.0)
        else:
            result = (floats(allow_infinity=allow_infinity,
                             allow_nan=False).map(lambda x: assume(
                                 not math.isnan(x)) and min_value + abs(x)))
        if min_value == 0 and not is_negative(min_value):
            result = result.filter(lambda x: math.copysign(1.0, x) == 1)
        return result
    else:
        assert max_value is not None
        if max_value > 0:
            result = floats(
                min_value=0.0,
                max_value=max_value,
            ) | floats(max_value=0.0)
        else:
            result = (floats(allow_infinity=allow_infinity,
                             allow_nan=False).map(lambda x: assume(
                                 not math.isnan(x)) and max_value - abs(x)))
        if max_value == 0 and is_negative(max_value):
            result = result.filter(is_negative)
        return result
Beispiel #52
0
 def pack(self, value):
     try:
         result, _ = self.model.objects.get_or_create(**value)
         return result
     except IntegrityError:
         assume(False)
Beispiel #53
0
 def do_draw(self, data):
     block = data.draw_bytes(self.block_size, self.distribution)
     assert len(block) == self.block_size
     value = self.from_bytes(block)
     assume(self.is_acceptable(value))
     return value