Esempio n. 1
0
def test_badge_save(given_path, coverage, mocker):
    """Test that :meth:`docstr_coverage.badge.Badge.save` opens the expected filepath and writes the
    correct badge contents to the expected location"""
    mock_open = mocker.patch("docstr_coverage.badge.open", mocker.mock_open())

    b = Badge(given_path, coverage)
    b.save()
    mock_open.assert_called_once_with(b.path, "w")
    mock_open().write.assert_called_once_with(b.badge)
Esempio n. 2
0
def execute(paths, **kwargs):
    """Measure docstring coverage for `PATHS`"""
    for deprecated_name, name in [
        ("skipmagic", "skip_magic"),
        ("skipfiledoc", "skip_file_doc"),
        ("skipinit", "skip_init"),
        ("skipclassdef", "skip_class_def"),
        ("followlinks", "follow_links"),
    ]:
        if kwargs.get(deprecated_name):
            new_flag = name.replace("_", "-")
            if kwargs.get(name):
                raise ValueError(
                    "Should not set deprecated --{} and new --{}".format(
                        deprecated_name, new_flag))
            click.secho("Using deprecated --{}, should use --{}".format(
                deprecated_name, new_flag),
                        fg="red")
            kwargs[name] = kwargs.pop(deprecated_name)

    # handle fail under
    if kwargs.get("failunder") is not None:
        if kwargs.get("fail_under") != 100.0:
            raise ValueError(
                "Should not set deprecated --failunder and --fail-under")
        click.secho("Using deprecated --failunder, should use --fail-under",
                    fg="red")
        kwargs["fail_under"] = kwargs.pop("failunder")

    # TODO: Add option to generate pretty coverage reports - Like Python's test `coverage`
    # TODO: Add option to sort reports by filename, coverage score... (ascending/descending)
    if kwargs["percentage_only"] is True:
        # Override verbosity to ensure only the overall percentage is printed
        kwargs["verbose"] = 0

    all_paths = collect_filepaths(*paths,
                                  follow_links=kwargs["follow_links"],
                                  exclude=kwargs["exclude"])

    if len(all_paths) < 1:
        if kwargs["accept_empty"] is True:
            warnings.warn(
                "No Python files found in specified paths. Processing aborted")
            sys.exit(0)
        else:
            sys.exit(
                "No Python files found "
                "(use `--accept-empty` to exit with code 0 if you expect this case)"
            )

    # Parse ignore names file
    has_ignore_patterns_in_config = "ignore_patterns" in kwargs
    if os.path.isfile(
            kwargs["ignore_names_file"]) and has_ignore_patterns_in_config:
        raise ValueError((
            "The docstr-coverage configuration file {} contains ignore_patterns,"
            " and at the same time an ignore file {} was found."
            " Ignore patterns must be specified in only one location at a time."
        ).format(kwargs["config_file"], kwargs["ignore_names_file"]))
    elif os.path.isfile(kwargs["ignore_names_file"]):
        ignore_names = parse_ignore_names_file(kwargs["ignore_names_file"])
    elif has_ignore_patterns_in_config:
        ignore_names = parse_ignore_patterns_from_dict(
            kwargs["ignore_patterns"])
    else:
        ignore_names = []

    # Calculate docstring coverage
    file_results, total_results = get_docstring_coverage(
        all_paths,
        skip_magic=kwargs["skip_magic"],
        skip_file_docstring=kwargs["skip_file_doc"],
        skip_init=kwargs["skip_init"],
        skip_class_def=kwargs["skip_class_def"],
        skip_private=kwargs["skip_private"],
        verbose=kwargs["verbose"],
        ignore_names=ignore_names,
    )

    # Save badge
    if kwargs["badge"]:
        badge = Badge(kwargs["badge"], total_results["coverage"])
        badge.save()

        if kwargs["verbose"]:
            print("Docstring coverage badge saved to {!r}".format(badge.path))

    if kwargs["percentage_only"] is True:
        print(total_results["coverage"])

    # Exit
    if total_results["coverage"] < kwargs["fail_under"]:
        raise SystemExit(1)

    raise SystemExit(0)
Esempio n. 3
0
def test_badge_contents(coverage, expected_filename):
    """Test that stringified badge (:attr:`docstr_coverage.badge.Badge.badge`) is correct before
    saving SVG file"""
    b = Badge(".", coverage)
    with open(os.path.join(SAMPLE_BADGE_DIR, expected_filename), "r") as f:
        assert b.badge == f.read()
Esempio n. 4
0
def test_badge_color(coverage, expected):
    """Test that :attr:`docstr_coverage.badge.Badge.color` is correct according to `coverage`"""
    b = Badge(".", coverage)
    assert b.color == expected
Esempio n. 5
0
def test_badge_path(given_path, expected):
    """Test that :attr:`docstr_coverage.badge.Badge.path` is set correctly when given paths to both
    files and directories"""
    b = Badge(given_path, 100)
    assert b.path == expected
Esempio n. 6
0
def execute(paths, **kwargs):
    """Measure docstring coverage for `PATHS`"""
    for deprecated_name, name in [
        ("skipmagic", "skip_magic"),
        ("skipfiledoc", "skip_file_doc"),
        ("skipinit", "skip_init"),
        ("skipclassdef", "skip_class_def"),
        ("followlinks", "follow_links"),
    ]:
        if kwargs.get(deprecated_name):
            new_flag = name.replace("_", "-")
            if kwargs.get(name):
                raise ValueError(
                    "Should not set deprecated --{} and new --{}".format(deprecated_name, new_flag)
                )
            click.secho(
                "Using deprecated --{}, should use --{}".format(deprecated_name, new_flag),
                fg="red",
            )
            kwargs[name] = kwargs.pop(deprecated_name)

    # handle fail under
    if kwargs.get("failunder") is not None:
        if kwargs.get("fail_under") is not None:
            raise ValueError("Should not set deprecated --failunder and --fail-under")
        click.secho("Using deprecated --failunder, should use --fail-under", fg="red")
        kwargs["fail_under"] = kwargs.pop("failunder")

    # TODO: Add option to generate pretty coverage reports - Like Python's test `coverage`
    # TODO: Add option to sort reports by filename, coverage score... (ascending/descending)
    if kwargs["percentage_only"] is True:
        # Override verbosity to ensure only the overall percentage is printed
        kwargs["verbose"] = 0

    all_paths = collect_filepaths(
        *paths, follow_links=kwargs["follow_links"], exclude=kwargs["exclude"]
    )

    if len(all_paths) < 1:
        sys.exit("No Python files found")

    # Parse ignore names file
    ignore_names = parse_ignore_names_file(kwargs["ignore_names_file"])

    # Calculate docstring coverage
    file_results, total_results = get_docstring_coverage(
        all_paths,
        skip_magic=kwargs["skip_magic"],
        skip_file_docstring=kwargs["skip_file_doc"],
        skip_init=kwargs["skip_init"],
        skip_class_def=kwargs["skip_class_def"],
        skip_private=kwargs["skip_private"],
        verbose=kwargs["verbose"],
        ignore_names=ignore_names,
    )

    # Save badge
    if kwargs["badge"]:
        badge = Badge(kwargs["badge"], total_results["coverage"])
        badge.save()

        if kwargs["verbose"]:
            print("Docstring coverage badge saved to {!r}".format(badge.path))

    if kwargs["percentage_only"] is True:
        print(total_results["coverage"])

    # Exit
    if total_results["coverage"] < kwargs["fail_under"]:
        raise SystemExit(1)

    raise SystemExit(0)