def test_multi_argument_contract_with_closure(self) -> None: SOME_CONSTANT = -math.inf ANOTHER_CONSTANT = math.inf # We must have -512 and +512 so that EXTENDED_ARG opcode is tested as well. @icontract.require( lambda x, y: SOME_CONSTANT < x - 512 < SOME_GLOBAL_CONST < y + 512 < ANOTHER_CONSTANT ) def some_func(x: float, y: float) -> None: pass strategy = icontract_hypothesis.infer_strategy(some_func) self.assertEqual( """\ fixed_dictionaries({'x': floats(), 'y': floats()}).filter(lambda d: SOME_CONSTANT < d['x'] - 512 < SOME_GLOBAL_CONST < d['y'] + 512 < ANOTHER_CONSTANT)""", str(strategy), ) icontract_hypothesis.test_with_inferred_strategy(some_func)
def test_function_with_self_as_argument(self) -> None: class A: def __init__(self) -> None: self.x = 1 # noinspection PyShadowingNames,PyUnusedLocal @icontract.require(lambda self: self.x > 10) def some_func(self: A) -> None: pass strategy = icontract_hypothesis.infer_strategy(some_func) self.assertEqual( "fixed_dictionaries({'self': builds(A).filter(lambda self: self.x > 10)})", str(strategy), ) error = None # type: Optional[hypothesis.errors.Unsatisfiable] try: icontract_hypothesis.test_with_inferred_strategy(some_func) except hypothesis.errors.Unsatisfiable as err: error = err assert error is not None self.assertIsInstance(error, hypothesis.errors.Unsatisfiable)
def test_precondition_with_typed_self_argument(self) -> None: class A(icontract.DBC): def __init__(self) -> None: self.x = 0 # noinspection PyShadowingNames @icontract.require(lambda self: self.x >= 0) def some_func(self: "A") -> None: pass def __repr__(self) -> str: return "An instance of A" a = A() strategy = icontract_hypothesis.infer_strategy( a.some_func, localns={A.__name__: A} ) self.assertEqual( "fixed_dictionaries({" "'self': just(An instance of A)})" ".filter(lambda d: d['self'].x >= 0)", str(strategy), ) icontract_hypothesis.test_with_inferred_strategy( a.some_func, localns={A.__name__: A} )
def test_new(self) -> None: strategy = icontract_hypothesis.infer_strategy(some_func_on_c) if hypothesis.__version_info__ <= (6, 14, 0): self.assertEqual( "fixed_dictionaries(" "{'c': " "fixed_dictionaries(" "{'xs': one_of(binary(), lists(integers()))" ".filter(lambda xs: all(x > -(2 ** 63) for x in xs))})" ".map(lambda d: C(**d))})", str(strategy), ) else: self.assertEqual( "fixed_dictionaries(" "{'c': " "fixed_dictionaries(" "{'xs': one_of(" "binary().filter(lambda xs: all(x > -(2 ** 63) for x in xs)), " "lists(integers()).filter(lambda xs: all(x > -(2 ** 63) for x in xs)))})" ".map(lambda d: C(**d))})", str(strategy), ) icontract_hypothesis.test_with_inferred_strategy(do_something)
def test_unsatisfiable_precondition_with_self_argument(self) -> None: class A(icontract.DBC): def __init__(self) -> None: # This will make the pre-condition of ``some_func`` unsatisfiable. self.x = -1 # noinspection PyShadowingNames @icontract.require(lambda number: number > 0) @icontract.require(lambda self: self.x >= 0) def some_func(self, number: int) -> None: pass def __repr__(self) -> str: return "An instance of A" a = A() strategy = icontract_hypothesis.infer_strategy(a.some_func) self.assertEqual( "fixed_dictionaries({" "'number': integers(min_value=1), " "'self': just(An instance of A)})" ".filter(lambda d: d['self'].x >= 0)", str(strategy), ) error = None # type: Optional[hypothesis.errors.FailedHealthCheck] try: icontract_hypothesis.test_with_inferred_strategy(a.some_func) except hypothesis.errors.FailedHealthCheck as err: error = err assert error is not None self.assertIsInstance(error, hypothesis.errors.FailedHealthCheck)
def test_that_a_multi_line_condition_renders_correctly(self) -> None: # This test case was taken from a solution for Advent of Code, day 8. class Operation(enum.Enum): NOP = "nop" ACC = "acc" JMP = "jmp" @dataclasses.dataclass class Instruction: operation: Operation argument: int @icontract.require( lambda instructions: all( 0 <= i + instruction.argument < len(instructions) for i, instruction in enumerate(instructions) if instruction.operation == Operation.JMP ) ) def execute_instructions(instructions: List[Instruction]) -> Optional[int]: ... strategy = icontract_hypothesis.infer_strategy(execute_instructions) self.assertEqual( """\ fixed_dictionaries({'instructions': lists(builds(Instruction)).filter(lambda instructions: all( 0 <= i + instruction.argument < len(instructions) for i, instruction in enumerate(instructions) if instruction.operation == Operation.JMP ))})""", str(strategy), )
def test_typed_dict(self) -> None: # TypedDict not available below Python version 3.8. if sys.version_info >= (3, 8): class A(icontract.DBC): @icontract.require(lambda x: x > 0) def __init__(self, x: int): self.x = x def __repr__(self) -> str: return "A(x={})".format(self.x) # noinspection PyTypedDict class B(TypedDict): a: A def some_func(b: B) -> None: pass strategy = icontract_hypothesis.infer_strategy(some_func) self.assertEqual( "fixed_dictionaries(" "{'b': fixed_dictionaries(" "{'a': fixed_dictionaries(" "{'x': integers(min_value=1)})" ".map(lambda d: A(**d))}, optional={})})", str(strategy), ) icontract_hypothesis.test_with_inferred_strategy(some_func)
def test_composition(self) -> None: class A(icontract.DBC): @icontract.require(lambda x: x > 0) def __init__(self, x: int): self.x = x def __repr__(self) -> str: return "A(x={})".format(self.x) class B(icontract.DBC): @icontract.require(lambda y: y > 2020) def __init__(self, a: A, y: int): self.a = a self.y = y def __repr__(self) -> str: return "B(a={!r}, y={})".format(self.a, self.y) def some_func(b: B) -> None: pass strategy = icontract_hypothesis.infer_strategy(some_func) self.assertEqual( "fixed_dictionaries(" "{'b': " "fixed_dictionaries(" "{'a': " "fixed_dictionaries(" "{'x': integers(min_value=1)}).map(lambda d: A(**d)),\n" " 'y': integers(min_value=2021)}).map(lambda d: B(**d))})", str(strategy), ) icontract_hypothesis.test_with_inferred_strategy(some_func)
def test_precondition_on_self_on_unbound_instance_method_fails_on_nested_classes( self, ) -> None: class A(icontract.DBC): def __init__(self) -> None: self.x = 1 # noinspection PyShadowingNames @icontract.require(lambda number: number > 0) @icontract.require(lambda self: self.x >= 0) def some_func(self, number: int) -> None: pass def __repr__(self) -> str: return f"An instance of {A.__name__}" # We can not infer the type of ``self`` as ``A`` is a nested class so we can not # "descend" to it from the top of the module based on ``__qualname__`` of ``some_func``. error = None # type: Optional[TypeError] try: _ = icontract_hypothesis.infer_strategy(A.some_func) except TypeError as err: error = err assert error is not None got_error = re.sub(r"<function .*>", "<function ...>", str(error)) self.assertEqual( "No search strategy could be inferred for the function: <function ...>; " "the following arguments are missing the type annotations: ['self'];\n\n" "sorted typed_args was ['number'], sorted parameter_set was ['number', 'self']", got_error, )
def test_precondition_on_self_on_unbound_instance_method_with_localns(self) -> None: class A(icontract.DBC): def __init__(self) -> None: self.x = 1 # We need to annotate ``self`` explicitly as we can not figure out the class from # an unbound method. # noinspection PyShadowingNames @icontract.require(lambda number: number > 0) @icontract.require(lambda self: self.x >= 0) def some_func(self: "A", number: int) -> None: pass def __repr__(self) -> str: return f"An instance of {A.__name__}" # We need to supply ``localns`` as ``self`` is annotated with a forward declaration and # ``A`` is a nested class. strategy = icontract_hypothesis.infer_strategy(A.some_func, localns={"A": A}) self.assertEqual( "fixed_dictionaries({" "'number': integers(min_value=1),\n" " 'self': builds(A).filter(lambda self: self.x >= 0)})", str(strategy), ) icontract_hypothesis.test_with_inferred_strategy(A.some_func, localns={"A": A})
def test_union(self) -> None: class A(icontract.DBC): @icontract.require(lambda x: x > 0) def __init__(self, x: int): self.x = x def __repr__(self) -> str: return "A(x={})".format(self.x) class B(icontract.DBC): @icontract.require(lambda x: x < 0) def __init__(self, x: int): self.x = x def __repr__(self) -> str: return "B(x={})".format(self.x) def some_func(a_or_b: Union[A, B]) -> None: pass strategy = icontract_hypothesis.infer_strategy(some_func) self.assertEqual( "fixed_dictionaries(" "{'a_or_b': one_of(" "fixed_dictionaries({'x': integers(min_value=1)}).map(lambda d: A(**d)), " "fixed_dictionaries({'x': integers(max_value=-1)}).map(lambda d: B(**d)))})", str(strategy), ) icontract_hypothesis.test_with_inferred_strategy(some_func)
def test_without_contracts(self) -> None: def some_func(x: int) -> None: pass strategy = icontract_hypothesis.infer_strategy(some_func) self.assertEqual("fixed_dictionaries({'x': integers()})", str(strategy)) icontract_hypothesis.test_with_inferred_strategy(some_func)
def test_with_only_preconditions(self) -> None: @icontract.ensure(lambda result: result > 0) def some_func(x: int) -> int: return 1 strategy = icontract_hypothesis.infer_strategy(some_func) self.assertEqual("fixed_dictionaries({'x': integers()})", str(strategy)) icontract_hypothesis.test_with_inferred_strategy(some_func)
def test_instance_method(self) -> None: b = B(0) strategy = icontract_hypothesis.infer_strategy(b.do_something) self.assertEqual( "fixed_dictionaries({'x1': integers()})", str(strategy), ) icontract_hypothesis.test_with_inferred_strategy(do_something)
def test_no_preconditions_and_no_argument_init(self) -> None: class A: def __repr__(self) -> str: return "A()" def some_func(a: A) -> None: pass strategy = icontract_hypothesis.infer_strategy(some_func) self.assertEqual("fixed_dictionaries({'a': builds(A)})", str(strategy)) icontract_hypothesis.test_with_inferred_strategy(some_func)
def test_condition_without_arguments(self) -> None: @icontract.require(lambda: SOME_GLOBAL_CONST >= 0) def some_func(x: int) -> None: pass strategy = icontract_hypothesis.infer_strategy(some_func) self.assertEqual( "fixed_dictionaries({'x': integers()}).filter(lambda: SOME_GLOBAL_CONST >= 0)", str(strategy), ) icontract_hypothesis.test_with_inferred_strategy(some_func)
def test_binary_operation(self) -> None: strategy = icontract_hypothesis.infer_strategy( problem_03._execute_binary_operation) @hypothesis.given(strategy) def execute(kwargs: Dict[str, Any]) -> None: try: problem_03._execute_binary_operation(**kwargs) except (OverflowError, ZeroDivisionError): pass execute()
def test_unmatched_pattern(self) -> None: @icontract.require(lambda x: x > 0 and x > math.sqrt(x)) def some_func(x: float) -> None: pass strategy = icontract_hypothesis.infer_strategy(some_func) self.assertEqual( "fixed_dictionaries({'x': floats().filter(lambda x: x > 0 and x > math.sqrt(x))})", str(strategy), ) icontract_hypothesis.test_with_inferred_strategy(some_func)
def test_multi_argument_contract(self) -> None: @icontract.require(lambda x, y: x < y) def some_func(x: float, y: float) -> None: pass strategy = icontract_hypothesis.infer_strategy(some_func) self.assertEqual( "fixed_dictionaries({'x': floats(), 'y': floats()}).filter(lambda d: d['x'] < d['y'])", str(strategy), ) icontract_hypothesis.test_with_inferred_strategy(some_func)
def test_infer_self_if_class_is_not_nested(self) -> None: strategy = icontract_hypothesis.infer_strategy(SomeGlobalClass.some_func) self.assertEqual( "fixed_dictionaries({" "'number': integers(min_value=1),\n" " 'self': builds(SomeGlobalClass)" ".filter(lambda self: self.x >= 0)})", str(strategy), ) icontract_hypothesis.test_with_inferred_strategy(SomeGlobalClass.some_func)
def test_re_match(self) -> None: @icontract.require(lambda s: re.match(r"^Start.*End$", s, flags=0)) def some_func(s: str) -> None: pass strategy = icontract_hypothesis.infer_strategy(some_func) self.assertEqual( "fixed_dictionaries({'s': from_regex(re.compile(r'^Start.*End$', re.UNICODE))})", str(strategy), ) icontract_hypothesis.test_with_inferred_strategy(some_func)
def test_function(self) -> None: strategy = icontract_hypothesis.infer_strategy(do_something) self.assertEqual( "fixed_dictionaries(" "{'a': " "fixed_dictionaries({'x': integers()})" ".map(lambda d: A(**d))})", str(strategy), ) icontract_hypothesis.test_with_inferred_strategy(do_something)
def test_resorting_to_from_type(self) -> None: # We can not handle ``.startswith`` at the moment, so we expect # ``from_type`` Hypothesis strategy followed by a filter. @icontract.require(lambda x: x.startswith("something")) def some_func(x: str) -> None: pass strategy = icontract_hypothesis.infer_strategy(some_func) self.assertEqual( "fixed_dictionaries({'x': text().filter(lambda x: x.startswith(\"something\"))})", str(strategy), )
def test_max_exclusive(self) -> None: @icontract.require(lambda x: x < datetime.time(1, 2, 3, 4)) def some_func(x: datetime.time) -> None: pass strategy = icontract_hypothesis.infer_strategy(some_func) self.assertEqual( "fixed_dictionaries({" "'x': times(max_value=datetime.time(1, 2, 3, 3))})", str(strategy), ) icontract_hypothesis.test_with_inferred_strategy(some_func)
def test_max_inclusive(self) -> None: @icontract.require(lambda x: x <= fractions.Fraction(1, 2)) def some_func(x: fractions.Fraction) -> None: pass strategy = icontract_hypothesis.infer_strategy(some_func) self.assertEqual( "fixed_dictionaries({" "'x': fractions(max_value=Fraction(1, 2))})", str(strategy), ) icontract_hypothesis.test_with_inferred_strategy(some_func)
def test_constant_ge_argument_gt_argument(self) -> None: @icontract.require(lambda x: 100 >= x > 10) def some_func(x: int) -> None: pass strategy = icontract_hypothesis.infer_strategy(some_func) self.assertEqual( "fixed_dictionaries({'x': integers(min_value=11, max_value=100)})", str(strategy), ) icontract_hypothesis.test_with_inferred_strategy(some_func)
def test_min_inclusive(self) -> None: @icontract.require(lambda x: 0 <= x) def some_func(x: float) -> None: pass strategy = icontract_hypothesis.infer_strategy(some_func) self.assertEqual( "fixed_dictionaries({'x': floats(min_value=0)})", str(strategy), ) icontract_hypothesis.test_with_inferred_strategy(some_func)
def test_max_inclusive(self) -> None: @icontract.require(lambda x: x <= datetime.date(2014, 3, 2)) def some_func(x: datetime.date) -> None: pass strategy = icontract_hypothesis.infer_strategy(some_func) self.assertEqual( "fixed_dictionaries({'x': dates(max_value=datetime.date(2014, 3, 2))})", str(strategy), ) icontract_hypothesis.test_with_inferred_strategy(some_func)
def test_condition_on_kwargs(self) -> None: @icontract.require(lambda _KWARGS: len(_KWARGS) == 1) def some_func(x: int) -> None: pass strategy = icontract_hypothesis.infer_strategy(some_func) self.assertEqual( "fixed_dictionaries({'x': integers()}).filter(lambda d: len(d) == 1)", str(strategy), ) icontract_hypothesis.test_with_inferred_strategy(some_func)
def test_max_exclusive(self) -> None: @icontract.require(lambda x: x < 100) def some_func(x: float) -> None: pass strategy = icontract_hypothesis.infer_strategy(some_func) self.assertEqual( "fixed_dictionaries({'x': floats(max_value=100, exclude_max=True)})", str(strategy), ) icontract_hypothesis.test_with_inferred_strategy(some_func)