def field_mappings(): global __default_field_mappings if __default_field_mappings is None: # Sized fields are handled in _get_strategy_for_field() # URL fields are not yet handled __default_field_mappings = { dm.SmallIntegerField: st.integers(-32768, 32767), dm.IntegerField: st.integers(-2147483648, 2147483647), dm.BigIntegerField: st.integers(-9223372036854775808, 9223372036854775807), dm.PositiveIntegerField: st.integers(0, 2147483647), dm.PositiveSmallIntegerField: st.integers(0, 32767), dm.BinaryField: st.binary(), dm.BooleanField: st.booleans(), dm.DateField: st.dates(), dm.DateTimeField: st.datetimes(timezones=get_tz_strat()), dm.DurationField: st.timedeltas(), dm.EmailField: emails(), dm.FloatField: st.floats(), dm.NullBooleanField: st.one_of(st.none(), st.booleans()), dm.TimeField: st.times(timezones=get_tz_strat()), dm.UUIDField: st.uuids(), } # SQLite does not support timezone-aware times, or timedeltas that # don't fit in six bytes of microseconds, so we override those db = getattr(django_settings, 'DATABASES', {}).get('default', {}) if db.get('ENGINE', '').endswith('.sqlite3'): # pragma: no branch sqlite_delta = timedelta(microseconds=2 ** 47 - 1) __default_field_mappings.update({ dm.TimeField: st.times(), dm.DurationField: st.timedeltas(-sqlite_delta, sqlite_delta), }) return __default_field_mappings
def services( draw, ids=uuids(), names=text(), descriptions=text(), registration_schemas=dictionaries(text(), text()), result_schemas=dictionaries(text(), text()), are_available=booleans(), service_job_lists=job_lists(), timeouts=timedeltas() ) -> ServiceInterface: return Service( draw(ids), draw(names), draw(descriptions), draw(registration_schemas), draw(result_schemas), draw(are_available), draw(service_job_lists), draw(timeouts) )
def test_can_find_positive_delta(): assert minimal(timedeltas(), lambda x: x.days > 0) == dt.timedelta(1)
from_parts = TimeDelta(days, scale=scale) + TimeDelta(day_frac, scale=scale) assert whole == from_parts def test_datetime_difference_agrees_with_timedelta_no_hypothesis(): scale = "tai" dt1 = datetime(1235, 1, 1, 0, 0) dt2 = datetime(9950, 1, 1, 0, 0, 0, 890773) t1 = Time(dt1, scale=scale) t2 = Time(dt2, scale=scale) assert (abs((t2 - t1) - TimeDelta(dt2 - dt1, scale=scale)) < 1 * u.us) # datetimes have microsecond resolution @given(datetimes(), timedeltas()) @example(dt=datetime(2000, 1, 1, 0, 0), td=timedelta(days=-397683, microseconds=2)) @example(dt=datetime(2179, 1, 1, 0, 0), td=timedelta(days=-795365, microseconds=53)) @example(dt=datetime(2000, 1, 1, 0, 0), td=timedelta(days=1590729, microseconds=10)) @example(dt=datetime(4357, 1, 1, 0, 0), td=timedelta(days=-1590729, microseconds=107770)) @example(dt=datetime(4357, 1, 1, 0, 0, 0, 29), td=timedelta(days=-1590729, microseconds=746292)) @pytest.mark.parametrize("scale", _utc_bad) def test_datetime_timedelta_sum(scale, dt, td): try: dt + td except OverflowError:
_global_type_lookup = { # Types with core Hypothesis strategies type(None): st.none(), bool: st.booleans(), int: st.integers(), float: st.floats(), complex: st.complex_numbers(), fractions.Fraction: st.fractions(), decimal.Decimal: st.decimals(), text_type: st.text(), binary_type: st.binary(), datetime.datetime: st.datetimes(), datetime.date: st.dates(), datetime.time: st.times(), datetime.timedelta: st.timedeltas(), uuid.UUID: st.uuids(), tuple: st.builds(tuple), list: st.builds(list), set: st.builds(set), frozenset: st.builds(frozenset), dict: st.builds(dict), type(lambda: None): st.functions(), # Built-in types type(Ellipsis): st.just(Ellipsis), type(NotImplemented): st.just(NotImplemented), bytearray: st.binary().map(bytearray), memoryview: st.binary().map(memoryview), numbers.Real: st.floats(), numbers.Rational: st.fractions(), numbers.Number: st.complex_numbers(),
# obtain one at https://mozilla.org/MPL/2.0/. # # END HEADER import pytest import hypothesis.strategies as st from hypothesis import example, given, reject from hypothesis.errors import HypothesisDeprecationWarning, InvalidArgument base_reusable_strategies = ( st.text(), st.binary(), st.dates(), st.times(), st.timedeltas(), st.booleans(), st.complex_numbers(), st.floats(), st.floats(-1.0, 1.0), st.integers(), st.integers(1, 10), st.integers(1), ) @st.deferred def reusable(): return st.one_of( st.sampled_from(base_reusable_strategies), st.builds(
def test_max_value_is_respected(): assert minimal(timedeltas(max_delta=dt.timedelta(days=-10))).days == -10
def _for_duration(field): # SQLite stores timedeltas as six bytes of microseconds if using_sqlite(): delta = timedelta(microseconds=2 ** 47 - 1) return st.timedeltas(-delta, delta) return st.timedeltas()
def test_simplifies_towards_zero_delta(): d = minimal(timedeltas()) assert d.days == d.seconds == d.microseconds == 0 def test_min_value_is_respected(): assert minimal(timedeltas(min_value=dt.timedelta(days=10))).days == 10 def test_max_value_is_respected(): assert minimal(timedeltas(max_value=dt.timedelta(days=-10))).days == -10 @given(timedeltas()) def test_single_timedelta(val): assert find_any(timedeltas(val, val)) is val def test_simplifies_towards_millenium(): d = minimal(datetimes()) assert d.year == 2000 assert d.month == d.day == 1 assert d.hour == d.minute == d.second == d.microsecond == 0 @given(datetimes()) def test_default_datetimes_are_naive(dt): assert dt.tzinfo is None
_global_field_lookup = { dm.SmallIntegerField: st.integers(-32768, 32767), dm.IntegerField: st.integers(-2147483648, 2147483647), dm.BigIntegerField: st.integers(-9223372036854775808, 9223372036854775807), dm.PositiveIntegerField: st.integers(0, 2147483647), dm.PositiveSmallIntegerField: st.integers(0, 32767), dm.BinaryField: st.binary(), dm.BooleanField: st.booleans(), dm.DateField: st.dates(), dm.EmailField: emails(), dm.FloatField: st.floats(), dm.NullBooleanField: st.one_of(st.none(), st.booleans()), dm.URLField: urls(), dm.UUIDField: st.uuids(), df.DateField: st.dates(), df.DurationField: st.timedeltas(), df.EmailField: emails(), df.FloatField: st.floats(allow_nan=False, allow_infinity=False), df.IntegerField: st.integers(-2147483648, 2147483647), df.NullBooleanField: st.one_of(st.none(), st.booleans()), df.URLField: urls(), df.UUIDField: st.uuids(), } # type: Dict[Any, Union[st.SearchStrategy, Callable[[Any], st.SearchStrategy]]] def register_for(field_type): def inner(func): _global_field_lookup[field_type] = func return func return inner
def test_get_cache_size_kb(): assert mp.get_cache_size_kb() == 128 @given(st.integers(min_value=0, max_value=2**27)) def test_set_cache_size_kb(size): mp.set_cache_size_kb(size) mp.get_cache_size_kb() == size @given(st.integers(min_value=-(2**32), max_value=-1)) def test_set_cache_size_kb_not_positive(size): with pytest.raises(ValueError) as e: mp.set_cache_size_kb(size) assert e.match('must be non-negative') @given( st.one_of(st.characters(), st.complex_numbers(), st.dates(), st.datetimes(), st.dictionaries(st.integers(), st.integers()), st.floats(), st.iterables(st.integers()), st.lists(st.integers()), st.none(), st.sets(st.integers()), st.text(), st.timedeltas(), st.times(), st.tuples(st.integers()))) def test_set_cache_size_kb_not_integer(size): with pytest.raises(TypeError) as e: mp.set_cache_size_kb(size) assert e.match('integer')
def primitives(): return (st.integers() | st.floats(allow_nan=False) | st.text() | st.binary() | st.datetimes(timezones=timezones() | st.none()) | st.dates() | st.times(timezones=timezones() | st.none()) | st.timedeltas() | st.booleans() | st.none())
return value return _strategy() def primitives(): return (st.integers() | st.floats(allow_nan=False) | st.text() | st.binary() | st.datetimes(timezones=timezones() | st.none()) | st.dates() | st.times(timezones=timezones() | st.none()) | st.timedeltas() | st.booleans() | st.none()) hashable_primitives = (st.booleans() | st.integers() | st.floats(allow_nan=False) | st.text() | st.binary() | st.datetimes() | st.timedeltas()) def hashable_containers(primitives): def extend(base): return st.one_of( st.frozensets(base, average_size=10, max_size=50), st.lists(base, average_size=10, max_size=50).map(tuple), ) return st.recursive(primitives, extend) def containers(primitives): def extend(base): return st.one_of(
to_booleans(), int: to_integers(min_value=MIN_POSITIVE_INTEGER_VALUE, max_value=MAX_SMALLINT_VALUE), float: to_floats(allow_nan=False, allow_infinity=False), Decimal: to_decimals(allow_nan=False, allow_infinity=False), datetime: to_date_times(min_value=MIN_DATE_TIME), date: to_dates(min_value=MIN_DATE_TIME.date()), time: strategies.times(), timedelta: strategies.timedeltas(), } @singledispatch def from_type(type_: TypeEngine) -> Strategy[Any]: return values_by_python_types[type_.python_type] ascii_not_null_characters = strategies.characters(min_codepoint=1, max_codepoint=127) @from_type.register(String) def string_type_values_factory( string_type: String,
def test_can_find_off_the_second(): find_any(timedeltas(), lambda x: x.seconds != 0)
def test_min_value_is_respected(): assert minimal(timedeltas(min_value=dt.timedelta(days=10))).days == 10
def test_can_find_positive_delta(): assert minimal(timedeltas(), lambda x: x.days > 0) == dt.timedelta(1)
def test_can_find_negative_delta(): assert minimal( timedeltas(max_value=dt.timedelta(10 ** 6)), lambda x: x.days < 0 ) == dt.timedelta(-1)
def test_can_find_off_the_second(): find_any(timedeltas(), lambda x: x.seconds != 0)
@given(st.datetimes()) def test_timestamp_from_into(datetime_: datetime.datetime) -> None: assert Timestamp.from_datetime( datetime_=datetime_).into_datetime() == datetime_ def test_epoch_timestamp_is_since_variant() -> None: """Ensure that when a datetime is exactly 1970-01-01T00:00:00.000000Z it is converted into a "since_epoch" protobuf Timestamp. We might state this circumstance in words "it has been 0ms since epoch". """ epoch = datetime.datetime.utcfromtimestamp(0) timestamp = Timestamp.from_datetime(epoch) proto_timestamp = timestamp.into_proto() assert proto_timestamp.WhichOneof("duration") is not None assert proto_timestamp.WhichOneof("duration") == "since_epoch" def test_duration_encode_decode() -> None: check_encode_decode_invariant(durations()) @given(st.timedeltas(min_value=datetime.timedelta(days=0))) def test_duration_from_into(timedelta: datetime.timedelta) -> None: assert Duration.from_timedelta( timedelta=timedelta).into_timedelta() == timedelta
def test_simplifies_towards_zero_delta(): d = minimal(timedeltas()) assert d.days == d.seconds == d.microseconds == 0
def test_single_timedelta(val): assert timedeltas(val, val).example() is val
def test_max_value_is_respected(): assert minimal(timedeltas(max_value=dt.timedelta(days=-10))).days == -10
def arrays(draw, type, size=None, nullable=True): if isinstance(type, st.SearchStrategy): ty = draw(type) elif isinstance(type, pa.DataType): ty = type else: raise TypeError('Type must be a pyarrow DataType') if isinstance(size, st.SearchStrategy): size = draw(size) elif size is None: size = draw(_default_array_sizes) elif not isinstance(size, int): raise TypeError('Size must be an integer') if pa.types.is_null(ty): h.assume(nullable) value = st.none() elif pa.types.is_boolean(ty): value = st.booleans() elif pa.types.is_integer(ty): values = draw(npst.arrays(ty.to_pandas_dtype(), shape=(size,))) return pa.array(values, type=ty) elif pa.types.is_floating(ty): values = draw(npst.arrays(ty.to_pandas_dtype(), shape=(size,))) # Workaround ARROW-4952: no easy way to assert array equality # in a NaN-tolerant way. values[np.isnan(values)] = -42.0 return pa.array(values, type=ty) elif pa.types.is_decimal(ty): # TODO(kszucs): properly limit the precision # value = st.decimals(places=type.scale, allow_infinity=False) h.reject() elif pa.types.is_time(ty): value = st.times() elif pa.types.is_date(ty): value = st.dates() elif pa.types.is_timestamp(ty): min_int64 = -(2**63) max_int64 = 2**63 - 1 min_datetime = datetime.datetime.fromtimestamp(min_int64 // 10**9) max_datetime = datetime.datetime.fromtimestamp(max_int64 // 10**9) try: offset_hours = int(ty.tz) tz = pytz.FixedOffset(offset_hours * 60) except ValueError: tz = pytz.timezone(ty.tz) value = st.datetimes(timezones=st.just(tz), min_value=min_datetime, max_value=max_datetime) elif pa.types.is_duration(ty): value = st.timedeltas() elif pa.types.is_binary(ty) or pa.types.is_large_binary(ty): value = st.binary() elif pa.types.is_string(ty) or pa.types.is_large_string(ty): value = st.text() elif pa.types.is_fixed_size_binary(ty): value = st.binary(min_size=ty.byte_width, max_size=ty.byte_width) elif pa.types.is_list(ty): value = _pylist(ty.value_type, size=size, nullable=nullable) elif pa.types.is_large_list(ty): value = _pylist(ty.value_type, size=size, nullable=nullable) elif pa.types.is_fixed_size_list(ty): value = _pylist(ty.value_type, size=ty.list_size, nullable=nullable) elif pa.types.is_dictionary(ty): values = _pylist(ty.value_type, size=size, nullable=nullable) return pa.array(draw(values), type=ty) elif pa.types.is_map(ty): value = _pymap(ty.key_type, ty.item_type, size=_default_array_sizes, nullable=nullable) elif pa.types.is_struct(ty): h.assume(len(ty) > 0) fields, child_arrays = [], [] for field in ty: fields.append(field) child_arrays.append(draw(arrays(field.type, size=size))) return pa.StructArray.from_arrays(child_arrays, fields=fields) else: raise NotImplementedError(ty) if nullable: value = st.one_of(st.none(), value) values = st.lists(value, min_size=size, max_size=size) return pa.array(draw(values), type=ty)
def test_single_timedelta(val): assert find_any(timedeltas(val, val)) is val
(0, 1, 0), (0, -1, 0), (1, -1, 0), (-1, 1, 0), (0, 0, 123456), (0, 0, -123456), ], ) def test_delta(args): act = pdt.timedelta(*args) exp = rdt.make_delta(*args) assert act == exp @given(td=st.timedeltas()) def test_delta_accessors(td): act = rdt.get_delta_tuple(td) exp = (td.days, td.seconds, td.microseconds) assert act == exp @pytest.mark.parametrize( "args,err_type", [ ((MAX_DAYS + 1, 0, 0), OverflowError), ((MIN_DAYS - 1, 0, 0), OverflowError), ((0, MAX_SECONDS + 1, 0), OverflowError), ((0, MIN_SECONDS - 1, 0), OverflowError), ((0, 0, MAX_MICROSECONDS + 1), OverflowError),
def arrays(draw, type, size=None): if isinstance(type, st.SearchStrategy): type = draw(type) elif not isinstance(type, pa.DataType): raise TypeError('Type must be a pyarrow DataType') if isinstance(size, st.SearchStrategy): size = draw(size) elif size is None: size = draw(_default_array_sizes) elif not isinstance(size, int): raise TypeError('Size must be an integer') shape = (size, ) if pa.types.is_list(type) or pa.types.is_large_list(type): offsets = draw(npst.arrays(np.uint8(), shape=shape)).cumsum() // 20 offsets = np.insert(offsets, 0, 0, axis=0) # prepend with zero values = draw(arrays(type.value_type, size=int(offsets.sum()))) array_type = (pa.LargeListArray if pa.types.is_large_list(type) else pa.ListArray) return array_type.from_arrays(offsets, values) if pa.types.is_struct(type): h.assume(len(type) > 0) fields, child_arrays = [], [] for field in type: fields.append(field) child_arrays.append(draw(arrays(field.type, size=size))) return pa.StructArray.from_arrays(child_arrays, fields=fields) if (pa.types.is_boolean(type) or pa.types.is_integer(type) or pa.types.is_floating(type)): values = npst.arrays(type.to_pandas_dtype(), shape=(size, )) np_arr = draw(values) if pa.types.is_floating(type): # Workaround ARROW-4952: no easy way to assert array equality # in a NaN-tolerant way. np_arr[np.isnan(np_arr)] = -42.0 return pa.array(np_arr, type=type) if pa.types.is_null(type): value = st.none() elif pa.types.is_time(type): value = st.times() elif pa.types.is_date(type): value = st.dates() elif pa.types.is_timestamp(type): tz = pytz.timezone(type.tz) if type.tz is not None else None value = st.datetimes(timezones=st.just(tz)) elif pa.types.is_duration(type): value = st.timedeltas() elif pa.types.is_binary(type) or pa.types.is_large_binary(type): value = st.binary() elif pa.types.is_string(type) or pa.types.is_large_string(type): value = st.text() elif pa.types.is_decimal(type): # TODO(kszucs): properly limit the precision # value = st.decimals(places=type.scale, allow_infinity=False) h.reject() else: raise NotImplementedError(type) values = st.lists(value, min_size=size, max_size=size) return pa.array(draw(values), type=type)
def test_simplifies_towards_zero_delta(): d = minimal(timedeltas()) assert d.days == d.seconds == d.microseconds == 0 def test_min_value_is_respected(): assert minimal(timedeltas(min_value=dt.timedelta(days=10))).days == 10 def test_max_value_is_respected(): assert minimal(timedeltas(max_value=dt.timedelta(days=-10))).days == -10 @given(timedeltas()) def test_single_timedelta(val): assert find_any(timedeltas(val, val)) is val def test_simplifies_towards_millenium(): d = minimal(datetimes()) assert d.year == 2000 assert d.month == d.day == 1 assert d.hour == d.minute == d.second == d.microsecond == 0 @given(datetimes()) def test_default_datetimes_are_naive(dt): assert dt.tzinfo is None
def _for_duration(field): # SQLite stores timedeltas as six bytes of microseconds if using_sqlite(): delta = timedelta(microseconds=2**47 - 1) return st.timedeltas(-delta, delta) return st.timedeltas()
def test_can_find_negative_delta(): assert minimal(timedeltas(max_value=dt.timedelta(10**6)), lambda x: x.days < 0) == dt.timedelta(-1)
class LeaseMaintenanceTests(TestCase): """ Tests for the lease-maintenance related parts of ``VoucherStore``. """ @given( tahoe_configs(), posix_safe_datetimes(), lists( tuples( # How much time passes before this activity starts timedeltas(min_value=timedelta(1), max_value=timedelta(days=1)), # Some activity. This list of two tuples gives us a trivial # way to compute the total passes required (just sum the pass # counts in it). This is nice because it avoids having the # test re-implement size quantization which would just be # repeated code duplicating the implementation. The second # value lets us fuzz the actual size values a little bit in a # way which shouldn't affect the passes required. lists( tuples( # The activity itself, in pass count integers(min_value=1, max_value=2 ** 16 - 1), # Amount by which to trim back the share sizes. This # might exceed the value of a single pass but we don't # know that value yet. We'll map it into a coherent # range with mod inside the test. integers(min_value=0), ), ), # How much time passes before this activity finishes timedeltas(min_value=timedelta(1), max_value=timedelta(days=1)), ), ), ) def test_lease_maintenance_activity(self, get_config, now, activity): """ ``VoucherStore.get_latest_lease_maintenance_activity`` returns a ``LeaseMaintenanceTests`` with fields reflecting the most recently finished lease maintenance activity. """ store = self.useFixture( TemporaryVoucherStore(get_config, lambda: now), ).store expected = None for (start_delay, sizes, finish_delay) in activity: now += start_delay started = now x = store.start_lease_maintenance() passes_required = 0 for (num_passes, trim_size) in sizes: passes_required += num_passes trim_size %= store.pass_value x.observe([ num_passes * store.pass_value - trim_size, ]) now += finish_delay x.finish() finished = now # Let the last iteration of the loop define the expected value. expected = LeaseMaintenanceActivity( started, passes_required, finished, ) self.assertThat( store.get_latest_lease_maintenance_activity(), Equals(expected), )
def test_simplifies_towards_zero_delta(): d = minimal(timedeltas()) assert d.days == d.seconds == d.microseconds == 0
def test_single_timedelta(val): assert find_any(timedeltas(val, val)) is val
# v. 2.0. If a copy of the MPL was not distributed with this file, You can # obtain one at http://mozilla.org/MPL/2.0/. # # END HEADER from __future__ import division, print_function, absolute_import import pytest import hypothesis.strategies as st from hypothesis import given, reject, example from hypothesis.errors import InvalidArgument base_reusable_strategies = ( st.text(), st.binary(), st.dates(), st.times(), st.timedeltas(), st.booleans(), st.complex_numbers(), st.floats(), st.floats(-1.0, 1.0), st.integers(), st.integers(1, 10), st.integers(1), ) @st.deferred def reusable(): return st.one_of( st.sampled_from(base_reusable_strategies), st.builds( st.floats, min_value=st.none() | st.floats(), max_value=st.none() | st.floats(), allow_infinity=st.booleans(), allow_nan=st.booleans() ),
import re import string import warnings import hypothesis import hypothesis.strategies as st from verta._internal_utils.time_utils import duration_millis def duration_millis_ignore_warn(delta): with warnings.catch_warnings(): warnings.simplefilter("ignore") return duration_millis(delta) millis_timedelta_strategy = st.timedeltas(min_value=timedelta(milliseconds=1)) millis_uint64_strategy = millis_timedelta_strategy.map( duration_millis_ignore_warn) # from https://hypothesis.readthedocs.io/en/latest/data.html#recursive-data json_strategy = st.recursive( st.none() | st.booleans() | st.floats() | st.text(string.printable), lambda children: st.lists(children) | st.dictionaries(st.text(string.printable), children), max_leaves=500, ) @st.composite def filepath(draw, allow_parent_dir_segments=False):
# # This is free software; you can do what the LICENCE file allows you to. # from __future__ import ( division as _py3_division, print_function as _py3_print, absolute_import as _py3_abs_import, ) from datetime import timedelta from hypothesis import strategies, given from xoeuf.odoo.tests.common import TransactionCase timedeltas = strategies.timedeltas() ALMOST_A_SECOND = timedelta(seconds=1, microseconds=-0.0001) class TestTimedelta(TransactionCase): def setUp(self): super(TestTimedelta, self).setUp() self.Value = self.env["test.timedelta.value"] @given(timedeltas) def test_create(self, value): obj = self.Value.create({"delta": value}) id = obj.id self.Value.invalidate_cache() obj = self.Value.browse(id) self.assertAlmostEqual(obj.delta, value, delta=ALMOST_A_SECOND)
import datetime as dt import pytest from flaky import flaky from hypothesis import find, given, settings, unlimited from tests.common.debug import minimal from hypothesis.strategies import none, dates, times, binary, datetimes, \ timedeltas from hypothesis.strategytests import strategy_test_suite from hypothesis.internal.compat import hrange from hypothesis.searchstrategy.datetime import DatetimeStrategy from hypothesis.internal.conjecture.data import Status, StopTest, \ ConjectureData TestStandardDescriptorFeatures_timedeltas1 = strategy_test_suite(timedeltas()) def test_can_find_positive_delta(): assert minimal(timedeltas(), lambda x: x.days > 0) == dt.timedelta(1) def test_can_find_negative_delta(): assert minimal(timedeltas(max_delta=dt.timedelta(10**6)), lambda x: x.days < 0) == dt.timedelta(-1) def test_can_find_on_the_second(): timedeltas().filter(lambda x: x.seconds == 0).example()
_global_field_lookup = { dm.SmallIntegerField: st.integers(-32768, 32767), dm.IntegerField: st.integers(-2147483648, 2147483647), dm.BigIntegerField: st.integers(-9223372036854775808, 9223372036854775807), dm.PositiveIntegerField: st.integers(0, 2147483647), dm.PositiveSmallIntegerField: st.integers(0, 32767), dm.BinaryField: st.binary(), dm.BooleanField: st.booleans(), dm.DateField: st.dates(), dm.EmailField: emails(), dm.FloatField: st.floats(), dm.NullBooleanField: st.one_of(st.none(), st.booleans()), dm.URLField: urls(), dm.UUIDField: st.uuids(), df.DateField: st.dates(), df.DurationField: st.timedeltas(), df.EmailField: emails(), df.FloatField: st.floats(allow_nan=False, allow_infinity=False), df.IntegerField: st.integers(-2147483648, 2147483647), df.NullBooleanField: st.one_of(st.none(), st.booleans()), df.URLField: urls(), df.UUIDField: st.uuids(), } def register_for(field_type): def inner(func): _global_field_lookup[field_type] = func return func return inner
def test_can_find_off_the_second(): timedeltas().filter(lambda x: x.seconds != 0).example()
_global_type_lookup = { # Types with core Hypothesis strategies type(None): st.none(), bool: st.booleans(), int: st.integers(), float: st.floats(), complex: st.complex_numbers(), fractions.Fraction: st.fractions(), decimal.Decimal: st.decimals(), text_type: st.text(), bytes: st.binary(), datetime.datetime: st.datetimes(), datetime.date: st.dates(), datetime.time: st.times(), datetime.timedelta: st.timedeltas(), uuid.UUID: st.uuids(), tuple: st.builds(tuple), list: st.builds(list), set: st.builds(set), frozenset: st.builds(frozenset), dict: st.builds(dict), # Built-in types type: st.sampled_from([type(None), bool, int, str, list, set, dict]), type(Ellipsis): st.just(Ellipsis), type(NotImplemented): st.just(NotImplemented), bytearray: st.binary().map(bytearray), memoryview: st.binary().map(memoryview), # Pull requests with more types welcome! }
import decimal import hypothesis as H import hypothesis.strategies as st from bunch import Bunch hashables = st.one_of( st.booleans(), st.none(), st.integers(), st.tuples(st.deferred(lambda: hashables)), st.frozensets(st.deferred(lambda: hashables)), st.floats(), st.text(), st.binary(), st.fractions(), st.decimals().filter(lambda x: not decimal.Decimal.is_snan(x)), st.datetimes(), st.dates(), st.times(), st.timedeltas(), st.uuids()) all_things = st.one_of( hashables, st.one_of( st.lists(st.deferred(lambda: all_things)), st.sets(hashables), st.dictionaries(hashables, st.deferred(lambda: all_things)), ), ) bunches = st.tuples(hashables).map(lambda x: Bunch(*x)) class DescribeBunch: def it_simple_containment(self): assert None in Bunch(None) assert 1 in Bunch(1, 2)