Esempio n. 1
0
    def test_settings(self) -> None:
        settings_parsing, errors = _test._parse_hypothesis_settings(
            {"max_examples": 10})
        self.assertListEqual([], errors)
        assert settings_parsing is not None

        this_dir = pathlib.Path(os.path.realpath(__file__)).parent
        path = (this_dir.parent.parent /
                "test_samples/pyicontract_hypothesis/sample_module.py")

        mod, errors = _general.load_module_from_source_file(path=path)
        self.assertListEqual([], errors)
        assert mod is not None

        points, errors = _general.select_function_points(
            source_code=path.read_text(), mod=mod, include=[], exclude=[])
        self.assertListEqual([], errors)

        for point in points:
            test_errors = _test._test_function_point(
                point=point, hypothesis_settings=settings_parsing.product)
            self.assertListEqual([], test_errors)

        some_func_calls = getattr(mod, "SOME_FUNC_CALLS")
        self.assertEqual(10, some_func_calls)

        another_func_calls = getattr(mod, "ANOTHER_FUNC_CALLS")
        self.assertEqual(10, another_func_calls)
    def test_no_include_and_no_exclude(self) -> None:
        this_dir = pathlib.Path(os.path.realpath(__file__)).parent
        path = (this_dir.parent.parent /
                "test_samples/pyicontract_hypothesis/sample_module.py")

        mod, errors = _general.load_module_from_source_file(path=path)
        self.assertListEqual([], errors)
        assert mod is not None

        points, errors = _general.select_function_points(
            source_code=path.read_text(), mod=mod, include=[], exclude=[])
        self.assertListEqual([], errors)

        self.assertListEqual(
            ["some_func", "another_func", "yet_another_func"],
            [point.func.__name__ for point in points],
        )
    def test_invalid_module(self) -> None:
        this_dir = pathlib.Path(os.path.realpath(__file__)).parent
        path = (this_dir.parent.parent /
                "test_samples/pyicontract_hypothesis/sample_invalid_module.py")

        mod, errors = _general.load_module_from_source_file(path=path)
        self.assertListEqual([], errors)
        assert mod is not None

        points, errors = _general.select_function_points(
            source_code=path.read_text(), mod=mod, include=[], exclude=[])

        self.assertListEqual(
            [
                "Unexpected directive on line 8. "
                "Expected '# pyicontract-hypothesis: (disable|enable)', "
                "but got: # pyicontract-hypothesis: disable-once"
            ],
            errors,
        )
    def test_include_line_range(self) -> None:
        this_dir = pathlib.Path(os.path.realpath(__file__)).parent
        path = (this_dir.parent.parent /
                "test_samples/pyicontract_hypothesis/sample_module.py")

        mod, errors = _general.load_module_from_source_file(path=path)
        self.assertListEqual([], errors)
        assert mod is not None

        points, errors = _general.select_function_points(
            source_code=path.read_text(),
            mod=mod,
            # A single line that overlaps the function should be enough to include it.
            include=[_general._LineRange(first=13, last=13)],
            exclude=[],
        )
        self.assertListEqual([], errors)

        self.assertListEqual(["some_func"],
                             [point.func.__name__ for point in points])
Esempio n. 5
0
def test(general: _general.Params, command: Params,
         stdout: TextIO) -> List[str]:
    """
    Test the specified functions.

    Return errors if any.
    """
    if not command.path.exists():
        return [
            "The file to be tested does not exist: {}".format(command.path)
        ]

    try:
        source_code = command.path.read_text(encoding="utf-8")
    except Exception as error:
        return ["Failed to read the file {}: {}".format(command.path, error)]

    mod, errors = _general.load_module_from_source_file(path=command.path)
    if errors:
        return errors

    assert mod is not None

    points, errors = _general.select_function_points(
        source_code=source_code,
        mod=mod,
        include=general.include,
        exclude=general.exclude,
    )
    if errors:
        return errors

    if command.inspect:
        printed_previously = False
        for point in points:
            inspection, test_errors = _inspect_test_function_point(
                point=point, settings_parsing=command.settings_parsing)
            errors.extend(test_errors)

            if not test_errors:
                if printed_previously:
                    stdout.write("\n")

                stdout.write(
                    f"{point.func.__name__} at line {point.first_row}:\n")
                stdout.write(textwrap.indent(inspection, "   "))
                stdout.write("\n")
                printed_previously = True
    else:
        for point in points:
            start = datetime.datetime.now()
            test_errors = _test_function_point(
                point=point,
                hypothesis_settings=(command.settings_parsing.product
                                     if command.settings_parsing is not None
                                     else None),
            )
            errors.extend(test_errors)

            duration = datetime.datetime.now() - start

            if not test_errors:
                stdout.write(
                    f"Tested {point.func.__name__} at line {point.first_row} "
                    f"(time delta {duration}).\n")

    if errors:
        return errors

    return []
def ghostwrite(general: _general.Params,
               command: Params) -> Tuple[str, List[str]]:
    """
    Write a unit test module for the specified functions.

    Return (generated code, errors if any).
    """
    if command.module_name is not None:
        mod, errors = _general.load_module_with_name(command.module_name)
    elif command.path is not None:
        mod, errors = _general.load_module_from_source_file(path=command.path)
    else:
        raise AssertionError(
            f"Unexpected execution path. The command was: {command.__dict__!r}"
        )

    if errors:
        return "", errors

    assert mod is not None

    ##
    # Load the source code
    ##

    if command.module_name is not None:
        source_code = inspect.getsource(mod)
    elif command.path is not None:
        source_code = command.path.read_text()
    else:
        raise AssertionError(
            f"Unexpected execution path. The command was: {command.__dict__!r}"
        )

    ##
    # Select points
    ##

    points, errors = _general.select_function_points(
        source_code=source_code,
        mod=mod,
        include=general.include,
        exclude=general.exclude,
    )
    if errors:
        return "", errors

    ##
    # Figure out the qualified name of the module
    ##

    if command.module_name is not None:
        qualified_name = command.module_name
    elif command.path is not None:
        qualified_name = _qualified_module_name_from_path(path=command.path,
                                                          sys_path=sys.path)
    else:
        raise AssertionError(
            f"Unexpected execution path. The command was: {command.__dict__!r}"
        )

    ##
    # Ghostwrite
    ##

    return _ghostwrite_for_function_points(
        points=points,
        module_name=qualified_name,
        explicit=command.explicit,
        bare=command.bare,
    )