def path_segments(draw): # pragma: no cover # type: (DrawCallable) -> Text """ A strategy which generates URL path segments. """ return draw( iterables( text(min_size=1, alphabet=_path_characters), max_size=10, average_size=3, ) )
def resolve_Iterator(thing): return st.iterables(st.from_type(thing.__args__[0]))
return st.frozensets(st.from_type(thing.__args__[0])) @register(typing.Dict, st.builds(dict)) def resolve_Dict(thing): # If thing is a Collection instance, we need to fill in the values keys_vals = [st.from_type(t) for t in thing.__args__] * 2 return st.dictionaries(keys_vals[0], keys_vals[1]) @register('DefaultDict', st.builds(collections.defaultdict)) def resolve_DefaultDict(thing): return resolve_Dict(thing).map( lambda d: collections.defaultdict(None, d)) @register(typing.ItemsView, st.builds(dict).map(dict.items)) def resolve_ItemsView(thing): return resolve_Dict(thing).map(dict.items) @register(typing.KeysView, st.builds(dict).map(dict.keys)) def resolve_KeysView(thing): return st.dictionaries(st.from_type(thing.__args__[0]), st.none() ).map(dict.keys) @register(typing.ValuesView, st.builds(dict).map(dict.values)) def resolve_ValuesView(thing): return st.dictionaries(st.integers(), st.from_type(thing.__args__[0]) ).map(dict.values) @register(typing.Iterator, st.iterables(st.nothing())) def resolve_Iterator(thing): return st.iterables(st.from_type(thing.__args__[0]))
def test_preserves_sequence_type_of_argument(): assert repr(st.sampled_from([0])) == "sampled_from([0])" class IHaveABadRepr(object): def __repr__(self): raise ValueError("Oh no!") def test_errors_are_deferred_until_repr_is_calculated(): s = ( st.builds( lambda x, y: 1, st.just(IHaveABadRepr()), y=st.one_of(st.sampled_from((IHaveABadRepr(),)), st.just(IHaveABadRepr())), ) .map(lambda t: t) .filter(lambda t: True) .flatmap(lambda t: st.just(IHaveABadRepr())) ) with pytest.raises(ValueError): repr(s) @given(st.iterables(st.integers())) def test_iterables_repr_is_useful(it): # fairly hard-coded but useful; also ensures _values are inexhaustible assert repr(it) == "iter({!r})".format(it._values)
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')
import pytest # type: ignore from io import StringIO from itertools import groupby from typing import Set, Tuple, Iterable, Callable, Any from hypothesis import assume, given # type: ignore import hypothesis.strategies as st # type: ignore from patch import Compost MAX_OFFSET = 1000 ints = st.integers(min_value=0, max_value=MAX_OFFSET) @given(ranges=st.iterables(st.tuples(ints, ints))) def test_compost_free(ranges: Iterable[Tuple[int, int]]) -> None: compost = Compost() # Use a completely different (however inefficient) implementation here to # check for overlaps so that we can make sure the actual implementation # isn't "accidentally correct". bitset: Set[int] = set() for start, end in ranges: if end < start: with pytest.raises(ValueError): compost.free(start, end) else: must_fail = False new_bitset = set() for bit in range(start, end + 1):
import traceback import sys from time import time from stricttuple import stricttuple from collections import deque __all__ = 'battle_tested', 'fuzz', 'disable_traceback', 'enable_traceback', 'garbage', 'crash_map', 'success_map', 'results', 'stats', 'print_stats' garbage = (st.binary(), st.booleans(), st.characters(), st.complex_numbers(), st.decimals(), st.floats(), st.fractions(), st.integers(), st.none(), st.random_module(), st.randoms(), st.text(), st.tuples(), st.uuids(), st.dictionaries(keys=st.text(), values=st.text())) garbage += ( # iterables st.lists(elements=st.one_of(*garbage)), st.iterables(elements=st.one_of(*garbage)), st.dictionaries(keys=st.text(), values=st.one_of(*garbage))) garbage = st.one_of(*garbage) def is_py3(): return sys.version_info >= (3, 0) class UniqueCrashContainer(tuple): ''' a pretty printable container for crashes ''' def __repr__(self): table = PrettyTable( ('exception type', 'arg types', 'location', 'crash message'), sortby='exception type') table.align["exception type"] = "l"
from itertools import tee import hypothesis.strategies as st import pytest from hypothesis import given from ...abuiltin import adict, aiter @given(listish=st.one_of( st.lists(st.tuples(st.text(), st.integers())), st.lists(st.lists(st.integers(), min_size=2, max_size=2)), st.sets(st.tuples(st.text(), st.integers())), )) @pytest.mark.trio async def test_all_listish(listish): ait = aiter(listish) assert await adict(ait) == dict(listish) @given(iterable=st.one_of( st.iterables(st.tuples(st.text(), st.integers())), st.iterables(st.lists(st.integers(), min_size=2, max_size=2)), )) @pytest.mark.trio async def test_all_iterable(iterable): it1, it2 = tee(iterable) ait = aiter(it1) assert await adict(ait) == dict(it2)
import responses from request_libraries_io_load_sqlite import * from utils.libraries_io_project_contributors_endpoint import content_and_error def get_api_key(): api_key = os.environ.get("APIKEY") if api_key is None: print("'APIKEY' is not among environment variables!", file=sys.stderr) sys.exit(1) return api_key @given(st.iterables(st.none()), st.integers()) def test_chunk__is_iterator(i, n): chunks = chunk(i, n) assert iter(chunks) is chunks @given(st.iterables(st.none(), min_size=0, max_size=0), st.integers(min_value=1, max_value=1000)) def test_chunk__empty_list_yields_empty_generator(i, n): chunks = chunk(i, n) with pt.raises(StopIteration): next(chunks) # @given(st.iterables(st.none(), min_size=1), st.integers(min_value=1)) # def test_chunk__chunks_recombine_into_original_list(l, n):
from itertools import tee T = TypeVar("T") @given(stp.urls()) def test_is_valid_url_valid_example(url: str): assert hf.is_valid_url(url) == True @given(st.text()) def test_is_valid_url_invalid_example(url: str): assert hf.is_valid_url(url) == False @given(st.iterables(st.integers(), unique=True, min_size=1)) def test_tail_only_removes_first_item(iterable: Iterable[T]): # If iterable is an iterator then it will be consumed so we need a copy iterable1, iterable2 = tee(iterable) # Force to list for easy testing iterable1 = list(iterable1) # type: ignore new_iterable = list(hf.tail(iterable2)) assert iterable1[0] not in new_iterable # type: ignore assert all(x in iterable1 for x in new_iterable) @given(st.iterables(st.booleans())) def test_partition(iterable: Iterable[T]): iterable1, iterable2 = tee(iterable) trues, falses = hf.partition(bool, iterable2) trues, falses = list(trues), list(falses)
from itertools import chain, tee from typing import Iterable, List from hypothesis import assume, given from hypothesis.strategies import integers, iterables, lists from LZW.extra_itertools import iappend, iequal @given(iterables(integers()), integers(min_value=0, max_value=10)) def test_iequal(l: Iterable[int], n: int) -> None: itrs = tee(l, n) assert iequal(*itrs) @given(lists(integers()), lists(integers()), integers(min_value=1, max_value=10)) def test_iequal_on_non_equal_iterables(l1: List[int], l2: List[int], n: int) -> None: assume(l1 != l2) itr1, itr2 = iter(l1), iter(l2) itrs = chain(tee(itr1, n), [itr2]) assert not iequal(*itrs) @given(iterables(integers()), integers()) def test_iappend(l: Iterable[int], x: int) -> None: l1, l2 = tee(l) assert list(iappend(l1, x)) == list(l2) + [x]
import hypothesis.strategies as st import pytest from hypothesis import given from ...abuiltin import aenumerate, aiter, alist @given( listish=st.one_of( st.binary(), st.lists(st.integers()), st.sets(st.integers()), st.text(), st.tuples(st.integers()), ), start=st.integers(), ) @pytest.mark.trio async def test_all_listish(listish, start): ait = aiter(listish) assert await alist(aenumerate(ait, start)) == list(enumerate(listish, start)) @given(iterable=st.iterables(st.integers()), start=st.integers()) @pytest.mark.trio async def test_all_iterable(iterable, start): it1, it2 = tee(iterable) ait = aiter(it1) assert await alist(aenumerate(ait, start)) == list(enumerate(it2, start))
child_rule_3 = ExampleRule(name="Test", param=None) child_rule_3.execute = Mock() rule = ExampleRule(name="Test", param="Rule", children=[child_rule_1, child_rule_2, child_rule_3]) rule.execute() child_rule_1.execute.assert_called_once_with(rule.param) child_rule_2.execute.assert_called_once_with(rule.param) child_rule_3.execute.assert_called_once_with(rule.param) @given(value=st.one_of(st.text(), st.integers(), st.iterables(st.one_of(st.text(), st.integers())))) def test_validate_param(value): rule = ExampleRule(name="Test", param="Rule") # Casting to string is the safest result = rule.validate(value, cast_to=str) assert result == str(value) @given(value=st.one_of(st.text(), st.integers(), st.iterables(st.one_of(st.text(), st.integers())))) def test_validate_no_casting(value): rule = ExampleRule(name="Test", param="Rule") result = rule.validate(val=value)
expected_xml = cET.Element(tag) inner_expected_xml = cET.SubElement( expected_xml, inner_tag, attrib={"attr1": attr1_val, attr2_name: attr2_val} ) cET.SubElement(inner_expected_xml, "float_el").text = str(float_val) cET.SubElement(inner_expected_xml, "str_el").text = str_val assert _elements_equal( generated_xml, expected_xml ), "Generated xml does not match the expected_xml." @given( vec_xyz=st.tuples(st.floats(), st.floats(), st.floats()), iterable=st.iterables(st.one_of(st.floats(), st.text())), ) @log_parameters def test_custom_values(vec_xyz: Tuple[float, float, float], iterable: Iterable): iterable, itr_cp = itertools.tee(iterable) @dataclass class TestXml(XmlObject): TAG = "tag" vec: Vector = Vector(*vec_xyz) itr: Iterable = iterable test_xml = TestXml() generated_xml = test_xml.create_xml()
@settings(max_examples=50) def test_dictionaries_respect_zero_size(d): assert len(d) <= 5 @given(ds.lists(ds.none(), max_size=5)) def test_none_lists_respect_max_size(ls): assert len(ls) <= 5 @given(ds.lists(ds.none(), max_size=5, min_size=1)) def test_none_lists_respect_max_and_min_size(ls): assert 1 <= len(ls) <= 5 @given(ds.iterables(ds.integers(), max_size=5, min_size=1)) def test_iterables_are_exhaustible(it): for _ in it: pass with pytest.raises(StopIteration): next(it) def test_minimal_iterable(): assert list(minimal(ds.iterables(ds.integers()), lambda x: True)) == [] @checks_deprecated_behaviour @pytest.mark.parametrize( "fn,kwargs", [
from pymesis import _cache as pymesis_cache strategies = ( st.integers(), st.text(), st.binary(), st.booleans(), st.characters(), st.complex_numbers(allow_nan=False), st.dates(), st.datetimes(), st.decimals(allow_nan=False), st.dictionaries(st.text(), st.text()), st.floats(allow_nan=False), st.fractions(), st.functions(), st.iterables(st.text()), st.none(), ) @given(st.one_of(strategies)) def test_cache(data): pymesis_cache.clear_cache() pymesis_cache.add_data(hash("key"), data) retrieved_data = pymesis_cache.get_data_if_cached(hash("key")) assert retrieved_data == data
def test_minimal_iterable(): assert list(minimal(ds.iterables(ds.integers()), lambda x: True)) == []
def __eq__(self, other): return self.attr == other.attr assert s.setattr_immutable(C(1), 'attr', 2) == C(2) def test_setattr_imm_namedtuple(): Tup = collections.namedtuple('Tup', 'attr') assert s.setattr_immutable(Tup(1), 'attr', 2) == Tup(2) @hypothesis.given( strats.one_of( strats.lists(strats.integers()), strats.iterables(strats.integers()).map(tuple), strats.dictionaries(strats.text(), strats.integers()), strats.iterables(strats.integers()).map(set), strats.lists(strats.integers()).map(Box), )) def test_contains(container): item = object() added = s.contains_add(container, item) assert isinstance(added, type(container)) assert item in added removed = s.contains_remove(added, item) assert isinstance(removed, type(container)) assert item not in removed def test_contains_add_failure():