def resolve_Callable(thing): # Generated functions either accept no arguments, or arbitrary arguments. # This is looser than ideal, but anything tighter would generally break # use of keyword arguments and we'd rather not force positional-only. if not thing.__args__: # pragma: no cover # varies by minor version return st.functions() *args_types, return_type = thing.__args__ # Note that a list can only appear in __args__ under Python 3.9 with the # collections.abc version; see https://bugs.python.org/issue42195 if len(args_types) == 1 and isinstance(args_types[0], list): args_types = tuple(args_types[0]) pep612 = ConcatenateTypes + ParamSpecTypes for arg in args_types: # awkward dance because you can't use Concatenate in isistance or issubclass if getattr(arg, "__origin__", arg) in pep612 or type(arg) in pep612: raise InvalidArgument( "Hypothesis can't yet construct a strategy for instances of a " f"Callable type parametrized by {arg!r}. Consider using an " "explicit strategy, or opening an issue.") if getattr(return_type, "__origin__", None) in TypeGuardTypes: raise InvalidArgument( "Hypothesis cannot yet construct a strategy for callables which " f"are PEP-647 TypeGuards (got {return_type!r}). " "Consider using an explicit strategy, or opening an issue.") return st.functions( like=(lambda *a, **k: None) if args_types else (lambda: None), returns=st.from_type(return_type), )
def resolve_Callable(thing): # Generated functions either accept no arguments, or arbitrary arguments. # This is looser than ideal, but anything tighter would generally break # use of keyword arguments and we'd rather not force positional-only. if not thing.__args__: # pragma: no cover # varies by minor version return st.functions() return st.functions( like=(lambda: None) if len(thing.__args__) == 1 else (lambda *a, **k: None), returns=st.from_type(thing.__args__[-1]), )
def resolve_Callable(thing): # Generated functions either accept no arguments, or arbitrary arguments. # This is looser than ideal, but anything tighter would generally break # use of keyword arguments and we'd rather not force positional-only. if not thing.__args__: # pragma: no cover # varies by minor version return st.functions() # Note that a list can only appear in __args__ under Python 3.9 with the # collections.abc version; see https://bugs.python.org/issue42195 return st.functions( like=(lambda: None) if len(thing.__args__) == 1 or thing.__args__[0] == [] else (lambda *a, **k: None), returns=st.from_type(thing.__args__[-1]), )
def factory(thing) -> st.SearchStrategy: like = (lambda: None) if len( thing.__args__, ) == 1 else (lambda *args, **kwargs: None) return st.functions( like=like, returns=st.from_type(thing.__args__[-1]), pure=True, )
def context_arg_dicts() -> SearchStrategy[ContextArgDict]: ''' Return a search strategy that samples `ContextArgDict`s. ''' return builds( dict, # type: ignore root=none() | builds(str, paths()) | paths(), scope=none() | dictionaries(text(), binary()), builder=none() | functions(like=(lambda artifact, spec: None)))
def test_functions_valid_within_given_invalid_outside(): cache = [None] @given(functions()) def t(f): assert f() is None cache[0] = f t() with pytest.raises(InvalidState): cache[0]()
def monads(draw): """Build us some monads, would you?""" scalars = st.integers() unary_functions = st.functions(like=lambda x: x, returns=scalars) value = draw(st.one_of(scalars, unary_functions)) value = value if not callable(value) else memoize(value) return Identity(value)
def properties(draw: Drawable) -> Property: "Generates Properties objects" return Property( name=draw(text()), datatype=draw(sampled_from(Datatype)), get=draw(functions(like=lambda: "4", returns=shared(text(), key="key"))), retained=draw(booleans()), settable=draw(booleans()), unit=draw(sampled_from(RECOMMENDED_UNITS)), formatOf=draw(text()), )
def percentage_properties(draw: Drawable) -> Property: "Generates PercentageProperty objects" return PercentageProperty( name=draw(text()), get=draw( functions( like=lambda: "4", returns=shared(integers(min_value=0, max_value=100).map(str), key="key"), )), retained=draw(booleans()), settable=draw(booleans()), )
def boolean_properties(draw: Drawable) -> Property: "Generates BooleanProperty objects" return BooleanProperty( name=draw(text()), get=draw( functions( like=lambda: "false", returns=shared( booleans().map(lambda boolean: str(boolean).lower()), key="key"), )), retained=draw(booleans()), settable=draw(booleans()), )
uuid.UUID: st.uuids(), tuple: st.builds(tuple), list: st.builds(list), set: st.builds(set), collections.abc.MutableSet: st.builds(set), frozenset: st.builds(frozenset), dict: st.builds(dict), FunctionType: st.functions(), 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(), numbers.Integral:
# Most of this work is copyright (C) 2013-2019 David R. MacIver # ([email protected]), but it contains contributions by others. See # CONTRIBUTING.rst for a full list of people who may hold copyright, and # consult the git log if you need to determine who owns an individual # contribution. # # This Source Code Form is subject to the terms of the Mozilla Public License, # v. 2.0. If a copy of the MPL was not distributed with this file, You can # obtain one at https://mozilla.org/MPL/2.0/. # # END HEADER from __future__ import absolute_import, division, print_function import pytest from hypothesis import given from hypothesis.strategies import functions def func(arg, *, kwonly_arg): pass @given(functions(func)) def test_functions_strategy_with_kwonly_args(f): with pytest.raises(TypeError): f(1, 2) f(1, kwonly_arg=2) f(kwonly_arg=2, arg=1)
""" Unit test package for drillcore_transformations. """ from pathlib import Path import numpy as np from hypothesis.extra.numpy import arrays from hypothesis.strategies import dictionaries, floats, functions, text alpha_strategy = floats(min_value=-90, max_value=90) beta_strategy = floats(min_value=-360, max_value=360) trend_strategy = floats(min_value=0, max_value=90) plunge_strategy = floats(min_value=-90, max_value=90) gamma_strategy = floats(min_value=-360, max_value=360) vector_strategy = arrays(np.float64, shape=3, elements=floats(-1, 1)) amount_strategy = floats(0, np.pi * 2) dip_strategy = floats(min_value=0, max_value=90) dir_strategy = floats(min_value=0, max_value=360) function_strategy = functions() text_strategy = text() dict_strategy = dictionaries(text_strategy, text_strategy) sample_csv = (Path(__file__).parent.parent / Path("sample_data/Logging_sheet.csv")).absolute() sample_csv_result = ( Path(__file__).parent.parent / Path("sample_data/Logging_sheet_transformed.csv")).absolute()
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(), numbers.Integral: st.integers(), numbers.Complex: st.complex_numbers(), slice: st.builds( slice, st.none() | st.integers(), st.none() | st.integers(), st.none() | st.integers(),
def test_invalid_arguments(like, returns, pure): with pytest.raises(InvalidArgument): functions(like=like, returns=returns, pure=pure).example()
Any]]], v: Optional[Union[int, float, Text]]) -> None: """Test Either construction.""" if v is None: with pytest.raises(TypeError): t() # type: ignore if t == Either: with pytest.raises(TypeError): t(v) # type: ignore else: assert t(v).value is v # type: ignore @hypothesis.given( a=eithers(exceptions(st.text()), st.integers()), # type: ignore f=st.functions(like=lambda x: None, returns=st.text())) def test_fmap(a: Either[E, int], f: Callable[[int], Text]) -> None: """Test fmap method.""" if isinstance(a, Left): assert a.fmap(f) == a elif isinstance(a, Right): assert isinstance(a.fmap(f).value, Text) else: pytest.fail() @hypothesis.given( a=eithers(exceptions(st.text()), st.integers()), # type: ignore b=eithers(exceptions(st.text()), st.functions(like=lambda x: None, returns=st.text()))) def test_apply(a: Either[E, int], b: Either[E, Callable[[int], Text]]) -> None:
import pytest from hypothesis import strategies as st from bootsteps import Blueprint from tests.strategies import non_isomorphic_graph_builder previous_graphs = [] steps_dependency_graph_builder = non_isomorphic_graph_builder( node_keys=st.functions(lambda: None), min_nodes=20, max_nodes=20, min_edges=10, self_loops=False, connected=True, previous_graphs=previous_graphs, ) def test_benchmark_blueprint_start(benchmark): graph = steps_dependency_graph_builder.example() blueprint = Blueprint(graph) benchmark(blueprint.start) def test_benchmark_blueprint_stop(benchmark): graph = steps_dependency_graph_builder.example() blueprint = Blueprint(graph) benchmark(blueprint.stop)
def test_functions_example_is_invalid(): with pytest.raises(InvalidArgument): functions().example()
from __future__ import absolute_import, division, print_function import pytest from hypothesis import given from hypothesis.errors import InvalidArgument, InvalidState from hypothesis.internal.compat import getfullargspec from hypothesis.strategies import booleans, functions def func_a(): pass @given(functions(func_a, booleans())) def test_functions_no_args(f): assert f.__name__ == "func_a" assert f is not func_a assert isinstance(f(), bool) def func_b(a, b, c): pass @given(functions(func_b, booleans())) def test_functions_with_args(f): assert f.__name__ == "func_b" assert f is not func_b with pytest.raises(TypeError):
mg.reset_globals() @given(WORD, st.lists(WORD)) def test_has_mutant_several_files(mutant_name, files): mg.has_mutant(mutant_name, files)(f) for file in files: assert_mutant_registry_correct(mutant_name, file) mg.reset_globals() # Test trivial_mutations @given(st.lists(st.functions())) def test_trivial_mutations_list_only(func_list): mg.trivial_mutations(func_list) for func in func_list: assert_mutant_registry_correct((func.__name__).upper() + "_NOTHING", mg.APPLY_TO_ALL) assert func.__name__ in mg.empty_function.__globals__ mg.reset_globals() @given(st.functions()) def test_trivial_mutations_function_only(func): mg.trivial_mutations(func) assert_mutant_registry_correct((func.__name__).upper() + "_NOTHING", mg.APPLY_TO_ALL) assert func.__name__ in mg.empty_function.__globals__
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
raise InvalidArgument( f"Valid styles are 'pytest' or 'unittest', got {style!r}") # Simple strategies to guess for common argument names - we wouldn't do this in # builds() where strict correctness is required, but we only use these guesses # when the alternative is nothing() to force user edits anyway. # # This table was constructed manually after skimming through the documentation # for the builtins and a few stdlib modules. Future enhancements could be based # on analysis of type-annotated code to detect arguments which almost always # take values of a particular type. _GUESS_STRATEGIES_BY_NAME = ( (st.text(), ["name", "filename", "fname"]), (st.floats(), ["real", "imag"]), (st.functions(), ["function", "func", "f"]), (st.iterables(st.integers()) | st.iterables(st.text()), ["iterable"]), ) def _strategy_for( param: inspect.Parameter) -> Union[st.SearchStrategy, InferType]: # If our default value is an Enum or a boolean, we assume that any value # of that type is acceptable. Otherwise, we only generate the default. if isinstance(param.default, bool): return st.booleans() if isinstance(param.default, enum.Enum): return st.sampled_from(type(param.default)) if param.default is not inspect.Parameter.empty: # Using `st.from_type(type(param.default))` would introduce spurious # failures in cases like the `flags` argument to regex functions.
# obtain one at https://mozilla.org/MPL/2.0/. from inspect import getfullargspec import pytest from hypothesis import assume, given from hypothesis.errors import InvalidArgument, InvalidState from hypothesis.strategies import booleans, functions, integers def func_a(): pass @given(functions(like=func_a, returns=booleans())) def test_functions_no_args(f): assert f.__name__ == "func_a" assert f is not func_a assert isinstance(f(), bool) def func_b(a, b, c): pass @given(functions(like=func_b, returns=booleans())) def test_functions_with_args(f): assert f.__name__ == "func_b" assert f is not func_b with pytest.raises(TypeError):
"qvm-firewall test-vm add action=accept dsthost=192.168.1.1 proto=icmp icmptype=0" ), ]) def test__firewall__happy_path(do, expected): with patch("qsm.dom0.lib.run", return_value=None, autospec=True) as mock_run: with patch("qsm.dom0.exists_or_throws", return_value=True, autospec=True): do() assert re.search(expected, str(mock_run.call_args)), \ "run was not called with expected args -- should be: {}".format(expected) # ~~~ action ~~~ @hypothesis.given(s.one_of(s.integers(), s.text(), s.functions())) def test__firewall__action__fuzz_negative(value): with patch("qsm.dom0.lib.run", return_value=None, autospec=True): with patch("qsm.dom0.exists_or_throws", return_value=True, autospec=True): with pytest.raises(AssertionError): dom0.firewall("test-vm", value, "192.168.1.1", "1") # ~~~ dsthost ~~~ @hypothesis.given(s.one_of(s.integers(), s.text(), s.functions())) def test__firewall__dsthost__fuzz_negative(value): with patch("qsm.dom0.lib.run", return_value=None, autospec=True): with patch("qsm.dom0.exists_or_throws", return_value=True,
def test_invalid_arguments(like, returns): with pytest.raises(InvalidArgument): functions(like, returns).example()
# END HEADER from inspect import getfullargspec import pytest from hypothesis import assume, given from hypothesis.errors import InvalidArgument, InvalidState from hypothesis.strategies import booleans, functions def func_a(): pass @given(functions(like=func_a, returns=booleans())) def test_functions_no_args(f): assert f.__name__ == "func_a" assert f is not func_a assert isinstance(f(), bool) def func_b(a, b, c): pass @given(functions(like=func_b, returns=booleans())) def test_functions_with_args(f): assert f.__name__ == "func_b" assert f is not func_b with pytest.raises(TypeError):