def test_mutate_success(field_mock, constructor_mock):
    config.INSTANCE.change_parameter_probability = 1.0
    test_case = dtc.DefaultTestCase()
    const = ps.ConstructorStatement(test_case, constructor_mock)
    const2 = ps.ConstructorStatement(test_case, constructor_mock)
    field = fstmt.FieldStatement(test_case, field_mock, const.return_value)
    const3 = ps.ConstructorStatement(test_case, constructor_mock)
    test_case.add_statement(const)
    test_case.add_statement(const2)
    test_case.add_statement(field)
    test_case.add_statement(const3)
    assert field.mutate()
    assert field.source == const2.return_value
def test_constructor_statement_accept(test_case_mock, variable_reference_mock,
                                      constructor_mock):
    statement = ps.ConstructorStatement(test_case_mock, constructor_mock)
    visitor = MagicMock(sv.StatementVisitor)
    statement.accept(visitor)

    visitor.visit_constructor_statement.assert_called_once_with(statement)
Beispiel #3
0
def test_constructor_mutable_arg_count(test_case_mock, constructor_mock):
    const = ps.ConstructorStatement(
        test_case_mock,
        constructor_mock,
        {"test": MagicMock(vri.VariableReferenceImpl)},
    )
    assert const._mutable_argument_count() == 1
Beispiel #4
0
    def add_constructor(
        self,
        test_case: tc.TestCase,
        constructor: gao.GenericConstructor,
        position: int = -1,
        recursion_depth: int = 0,
        allow_none: bool = True,
    ) -> vr.VariableReference:
        """Adds a constructor statement to a test case at a given position.

        If the position is not given, the constructor will be appended on the end of
        the test case.  A given recursion depth controls how far the factory searches
        for suitable parameter values.

        Args:
            test_case: The test case
            constructor: The constructor to add to the test case
            position: The position where to put the statement in the test case,
                defaults to the end of the test case
            recursion_depth: A recursion limit for the search of parameter values
            allow_none: Whether or not a variable can be an None value

        Returns:
            A variable reference to the constructor

        Raises:
            ConstructionFailedException: if construction of an object failed
        """
        self._logger.debug("Adding constructor %s", constructor)
        if recursion_depth > config.INSTANCE.max_recursion:
            self._logger.debug("Max recursion depth reached")
            raise ConstructionFailedException("Max recursion depth reached")

        if position < 0:
            position = test_case.size()

        signature = constructor.inferred_signature
        length = test_case.size()
        try:
            parameters: List[vr.VariableReference] = self.satisfy_parameters(
                test_case=test_case,
                signature=signature,
                position=position,
                recursion_depth=recursion_depth + 1,
                allow_none=allow_none,
            )
            new_length = test_case.size()
            position = position + new_length - length

            statement = par_stmt.ConstructorStatement(
                test_case=test_case,
                generic_callable=constructor,
                args=parameters,
            )
            return test_case.add_statement(statement, position)
        except BaseException as exception:
            raise ConstructionFailedException(
                f"Failed to add constructor for {constructor} "
                f"due to {exception}.")
Beispiel #5
0
def test_statement_to_ast_constructor_no_args(statement_to_ast_visitor,
                                              test_case_mock,
                                              constructor_mock):
    constr_stmt = param_stmt.ConstructorStatement(test_case_mock,
                                                  constructor_mock)
    statement_to_ast_visitor.visit_constructor_statement(constr_stmt)
    assert (astor.to_source(Module(body=statement_to_ast_visitor.ast_nodes)) ==
            "var0 = module0.SomeType()\n")
def test_mutate_no_replacements(field_mock, constructor_mock):
    config.INSTANCE.change_parameter_probability = 1.0
    test_case = dtc.DefaultTestCase()
    const = ps.ConstructorStatement(test_case, constructor_mock)
    field = fstmt.FieldStatement(test_case, field_mock, const.return_value)
    test_case.add_statement(const)
    test_case.add_statement(field)
    assert not field.mutate()
def test_constructor_replace_return_value(constructor_mock):
    test_case = dtc.DefaultTestCase()
    new_value = prim.IntPrimitiveStatement(test_case, 0)
    const = ps.ConstructorStatement(test_case, constructor_mock)
    test_case.add_statement(new_value)
    test_case.add_statement(const)
    const.replace(const.return_value, new_value.return_value)
    assert const.return_value == new_value.return_value
Beispiel #8
0
def test_test_case_equals_on_different_prim(
        simple_test_case: dtc.DefaultTestCase, constructor_mock):
    cloned = simple_test_case.clone()

    # Original points to int at 0
    simple_test_case.add_statement(
        ps.ConstructorStatement(
            simple_test_case,
            constructor_mock,
            {"y": simple_test_case.statements[0].ret_val},
        ))
    # Clone points to int at 1
    cloned.add_statement(
        ps.ConstructorStatement(cloned, constructor_mock,
                                {"y": cloned.statements[1].ret_val}))

    # Even though they both point to an int, they are not equal
    assert not simple_test_case == cloned
def short_test_case(constructor_mock):
    test_case = dtc.DefaultTestCase()
    int_stmt = prim_stmt.IntPrimitiveStatement(test_case, 5)
    constructor_stmt = param_stmt.ConstructorStatement(test_case,
                                                       constructor_mock,
                                                       [int_stmt.return_value])
    test_case.add_statement(int_stmt)
    test_case.add_statement(constructor_stmt)
    return test_case
def test_constructor_statement_args(test_case_mock, variable_reference_mock,
                                    constructor_mock):
    statement = ps.ConstructorStatement(test_case_mock, constructor_mock)
    references = [
        MagicMock(vri.VariableReferenceImpl),
        MagicMock(vri.VariableReferenceImpl),
    ]
    statement.args = references
    assert statement.args == references
def test_constructor_statement_kwargs(test_case_mock, variable_reference_mock,
                                      constructor_mock):
    statement = ps.ConstructorStatement(test_case_mock, constructor_mock)
    references = {
        "par1": MagicMock(vri.VariableReferenceImpl),
        "par2": MagicMock(vri.VariableReferenceImpl),
    }
    statement.kwargs = references
    assert statement.kwargs == references
def test_constructor_clone_args(constructor_mock):
    test_case = dtc.DefaultTestCase()
    new_test_case = dtc.DefaultTestCase()
    to_clone = MagicMock(vri.VariableReferenceImpl)
    the_clone = MagicMock(vri.VariableReferenceImpl)
    to_clone.clone.return_value = the_clone
    const = ps.ConstructorStatement(test_case, constructor_mock, [to_clone])
    assert const._clone_args(new_test_case, 10) == [the_clone]
    to_clone.clone.assert_called_with(new_test_case, 10)
Beispiel #13
0
def test_constructor_param_count_of_type(test_case_mock, constructor_mock):
    const = ps.ConstructorStatement(
        test_case_mock,
        constructor_mock,
        {
            "test0": vri.VariableReferenceImpl(test_case_mock, float),
            "test1": vri.VariableReferenceImpl(test_case_mock, int),
        },
    )
    assert const._param_count_of_type(float) == 1
def test_constructor_replace_argument(test_case_mock, constructor_mock):
    var0 = vri.VariableReferenceImpl(test_case_mock, float)
    var1 = vri.VariableReferenceImpl(test_case_mock, float)
    var2 = vri.VariableReferenceImpl(test_case_mock, float)
    var3 = vri.VariableReferenceImpl(test_case_mock, float)
    const = ps.ConstructorStatement(test_case_mock, constructor_mock, [var0],
                                    {"test0": var2})
    const._replace_argument(0, var1)
    assert const.args[0] is var1
    const._replace_argument("test0", var3)
    assert const.kwargs["test0"] is var3
Beispiel #15
0
def test_change_call_method(constructor_mock, method_mock):
    test_case = dtc.DefaultTestCase()
    test_case.add_statement(par_stmt.ConstructorStatement(test_case, constructor_mock))
    test_case.add_statement(prim.IntPrimitiveStatement(test_case, 3))
    to_replace = prim.NoneStatement(test_case, float)
    test_case.add_statement(to_replace)
    test_cluster = MagicMock(TestCluster)
    test_factory = tf.TestFactory(test_cluster)
    test_factory.change_call(test_case, to_replace, method_mock)
    assert test_case.statements[2].accessible_object() == method_mock
    assert test_case.statements[2].return_value is to_replace.return_value
Beispiel #16
0
def test_select_random_variable_for_call_one(constructor_mock, function_mock):
    test_case = dtc.DefaultTestCase()
    test_case.add_statement(prim.NoneStatement(test_case, MagicMock))
    test_case.add_statement(prim.FloatPrimitiveStatement(test_case, 5.0))
    function_mock.inferred_signature.update_return_type(None)
    test_case.add_statement(
        par_stmt.FunctionStatement(test_case, function_mock))
    const = par_stmt.ConstructorStatement(test_case, constructor_mock)
    test_case.add_statement(const)
    assert (tf.TestFactory._select_random_variable_for_call(
        test_case, test_case.size()) == const.return_value)
Beispiel #17
0
def test_statement_to_ast_constructor_kwargs(
    statement_to_ast_visitor, test_case_mock, variable_reference_mock, constructor_mock
):
    constr_stmt = param_stmt.ConstructorStatement(
        test_case_mock, constructor_mock, kwargs={"param1": variable_reference_mock},
    )
    statement_to_ast_visitor.visit_constructor_statement(constr_stmt)
    assert (
        astor.to_source(Module(body=statement_to_ast_visitor.ast_nodes))
        == "var0 = module0.SomeType(param1=var1)\n"
    )
def simple_test_case(constructor_mock):
    test_case = dtc.DefaultTestCase()
    int_stmt = prim_stmt.IntPrimitiveStatement(test_case, 5)
    constructor_stmt = param_stmt.ConstructorStatement(test_case,
                                                       constructor_mock,
                                                       [int_stmt.return_value])
    constructor_stmt.add_assertion(
        pas.PrimitiveAssertion(constructor_stmt.return_value, 3))
    test_case.add_statement(int_stmt)
    test_case.add_statement(constructor_stmt)
    return test_case
Beispiel #19
0
def test_constructor_replace_args(constructor_mock):
    test_case = dtc.DefaultTestCase()
    int0 = prim.IntPrimitiveStatement(test_case, 0)
    new_value = prim.IntPrimitiveStatement(test_case, 0)
    const = ps.ConstructorStatement(test_case, constructor_mock,
                                    {"a": int0.ret_val})
    test_case.add_statement(int0)
    test_case.add_statement(new_value)
    test_case.add_statement(const)
    const.replace(int0.ret_val, new_value.ret_val)
    assert const.args == {"a": new_value.ret_val}
def test_constructor_get_argument(test_case_mock, constructor_mock):
    var0 = vri.VariableReferenceImpl(test_case_mock, float)
    var1 = vri.VariableReferenceImpl(test_case_mock, float)
    var2 = vri.VariableReferenceImpl(test_case_mock, float)
    var3 = vri.VariableReferenceImpl(test_case_mock, float)
    const = ps.ConstructorStatement(test_case_mock, constructor_mock,
                                    [var0, var1], {
                                        "test0": var2,
                                        "test1": var3
                                    })
    assert const._get_argument(0) is var0
    assert const._get_argument("test0") is var2
def test_constructor_mutate_parameter_choose_none(constructor_mock):
    test_case = dtc.DefaultTestCase()
    float0 = prim.FloatPrimitiveStatement(test_case, 5.0)
    const = ps.ConstructorStatement(test_case, constructor_mock,
                                    [float0.return_value])
    test_case.add_statement(float0)
    test_case.add_statement(const)
    assert const._mutate_parameter(0)
    assert isinstance(
        test_case.get_statement(const.args[0].get_statement_position()),
        prim.NoneStatement,
    )
def test_constructor_mutate_parameter_get_objects(constructor_mock):
    test_case = dtc.DefaultTestCase()
    float0 = prim.FloatPrimitiveStatement(test_case, 5.0)
    const = ps.ConstructorStatement(test_case, constructor_mock,
                                    [float0.return_value])
    test_case.add_statement(float0)
    test_case.add_statement(const)
    with mock.patch.object(const, "_test_case") as tc:
        tc.get_objects.return_value = [float0.return_value]
        assert const._mutate_parameter(0)
        tc.get_objects.assert_called_with(float0.return_value.variable_type,
                                          const.get_position())
def test_method_mutate_special_parameters_one_found(method_mock,
                                                    constructor_mock):
    test_case = dtc.DefaultTestCase()
    float0 = prim.FloatPrimitiveStatement(test_case, 5.0)
    const0 = ps.ConstructorStatement(test_case, constructor_mock,
                                     [float0.ret_val])
    const1 = ps.ConstructorStatement(test_case, constructor_mock,
                                     [float0.ret_val])
    int0 = prim.IntPrimitiveStatement(test_case, 5)
    meth = ps.MethodStatement(test_case, method_mock, const0.ret_val)
    test_case.add_statement(float0)
    test_case.add_statement(const0)
    test_case.add_statement(const1)
    test_case.add_statement(int0)
    test_case.add_statement(meth)
    with mock.patch.object(meth, "_test_case") as tc:
        tc.get_objects.return_value = [const0.ret_val, const1.ret_val]
        assert meth._mutate_special_parameters(1.0)
        tc.get_objects.assert_called_with(const0.ret_val.variable_type,
                                          meth.get_position())
        assert meth.callee == const1.ret_val
def test_constructor_mutate_parameter_choose_existing(constructor_mock):
    test_case = dtc.DefaultTestCase()
    float0 = prim.FloatPrimitiveStatement(test_case, 5.0)
    float1 = prim.FloatPrimitiveStatement(test_case, 5.0)
    const = ps.ConstructorStatement(test_case, constructor_mock,
                                    [float0.return_value])
    test_case.add_statement(float0)
    test_case.add_statement(float1)
    test_case.add_statement(const)
    with mock.patch("pynguin.utils.randomness.choice") as choice_mock:
        choice_mock.side_effect = lambda coll: coll[0]
        assert const._mutate_parameter(0)
def test_constructor_mutate_parameters_args(test_case_mock, constructor_mock,
                                            variable_reference_mock):
    const = ps.ConstructorStatement(
        test_case_mock,
        constructor_mock,
        [variable_reference_mock, variable_reference_mock],
    )
    with mock.patch("pynguin.utils.randomness.next_float") as float_mock:
        with mock.patch.object(const, "_mutate_parameter") as mutate_parameter:
            mutate_parameter.return_value = True
            float_mock.side_effect = [0.0, 1.0]
            assert const._mutate_parameters(0.5)
            mutate_parameter.assert_called_with(0)
Beispiel #26
0
def test_mutation_change_call_success(constructor_mock, result):
    factory = MagicMock(tf.TestFactory)
    factory.change_random_call.return_value = result
    test_case = dtc.DefaultTestCase(factory)
    const0 = ps.ConstructorStatement(test_case, constructor_mock)
    const0.return_value.distance = 5
    test_case.add_statement(const0)
    with mock.patch("pynguin.utils.randomness.next_float") as float_mock:
        float_mock.return_value = 0.0
        with mock.patch.object(const0, "mutate") as mutate_mock:
            mutate_mock.return_value = False
            assert test_case._mutation_change() == result
            mutate_mock.assert_called_once()
            assert const0.return_value.distance == 5
Beispiel #27
0
def assemble_stmt_from_gen_callable(
    testcase: tc.TestCase,
    gen_callable: GenericCallableAccessibleObject,
    call: ast.Call,
    ref_dict: Dict[str, vr.VariableReference],
) -> Optional[param_stmt.ParametrizedStatement]:
    """Takes a generic callable and assembles the corresponding parametrized statement
    from it.

    Args:
        testcase: the testcase of the statement
        gen_callable: the corresponding callable of the cluster
        call: the ast.Call statement
        ref_dict: a dictionary containing key value pairs of variable ids and
                  variable references.

    Returns:
        The corresponding statement.
    """
    for arg in call.args:
        if not isinstance(arg, (ast.Name, ast.Starred)):
            return None
    for keyword in call.keywords:
        if not isinstance(keyword, ast.keyword):
            return None
    var_refs = create_variable_references_from_call_args(
        call.args,
        call.keywords,
        gen_callable,
        ref_dict  # type: ignore
    )
    if var_refs is None:
        return None
    if isinstance(gen_callable, GenericFunction):
        return param_stmt.FunctionStatement(
            testcase, cast(GenericCallableAccessibleObject, gen_callable),
            var_refs)
    if isinstance(gen_callable, GenericMethod):
        return param_stmt.MethodStatement(
            testcase,
            gen_callable,
            ref_dict[call.func.value.id],  # type: ignore
            var_refs,
        )
    if isinstance(gen_callable, GenericConstructor):
        return param_stmt.ConstructorStatement(
            testcase, cast(GenericCallableAccessibleObject, gen_callable),
            var_refs)
    return None
Beispiel #28
0
def test_constructor_statement_clone(constructor_mock):
    test_case = dtc.DefaultTestCase()
    int_prim = prim.IntPrimitiveStatement(test_case, 5)
    method_stmt = ps.ConstructorStatement(
        test_case,
        constructor_mock,
        {"y": int_prim.ret_val},
    )
    test_case.add_statement(int_prim)
    test_case.add_statement(method_stmt)

    cloned = test_case.clone()
    assert isinstance(cloned.statements[1], ps.ConstructorStatement)
    assert cloned.statements[1] is not method_stmt
    assert cloned.statements[0].ret_val is not test_case.statements[0].ret_val
Beispiel #29
0
def test_constructor_mutate_parameter_choose_none(constructor_mock):
    test_case = dtc.DefaultTestCase()
    float0 = prim.FloatPrimitiveStatement(test_case, 5.0)
    const = ps.ConstructorStatement(test_case, constructor_mock,
                                    {"a": float0.ret_val})
    test_case.add_statement(float0)
    test_case.add_statement(const)
    with mock.patch("pynguin.testcase.testfactory.is_optional_parameter"
                    ) as optional_mock:
        optional_mock.return_value = False
        assert const._mutate_parameter("a", MagicMock(parameters={"a": float}))
        assert isinstance(
            test_case.get_statement(const.args["a"].get_statement_position()),
            prim.NoneStatement,
        )
def test_constructor_mutate_parameter_not_included(constructor_mock):
    test_case = dtc.DefaultTestCase()
    float0 = prim.FloatPrimitiveStatement(test_case, 5.0)
    const = ps.ConstructorStatement(test_case, constructor_mock,
                                    [float0.return_value])
    test_case.add_statement(float0)
    test_case.add_statement(const)
    with mock.patch.object(test_case, "get_objects") as get_objs:
        get_objs.return_value = []
        assert const._mutate_parameter(0)
        get_objs.assert_called_with(float0.return_value.variable_type, 1)
        assert isinstance(
            test_case.get_statement(const.args[0].get_statement_position()),
            prim.NoneStatement,
        )