Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion coverage_comment/coverage.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ def compute_coverage(
numerator = decimal.Decimal(num_covered + num_branches_covered)
denominator = decimal.Decimal(num_total + num_branches_total)
if denominator == 0:
return decimal.Decimal("1")
return decimal.Decimal(1)
return numerator / denominator


Expand Down
4 changes: 2 additions & 2 deletions coverage_comment/files.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ def compute_files(
minimum_orange: decimal.Decimal,
http_session: httpx.Client,
) -> list[Operation]:
line_rate *= decimal.Decimal("100")
line_rate *= decimal.Decimal(100)
color = badge.get_badge_color(
rate=line_rate,
minimum_green=minimum_green,
Expand Down Expand Up @@ -113,7 +113,7 @@ def compute_datafile(
def parse_datafile(contents: str) -> tuple[coverage.Coverage | None, decimal.Decimal]:
file_contents = json.loads_dict(contents)
coverage_rate = decimal.Decimal(str(file_contents["coverage"])) / decimal.Decimal(
"100"
100
)
try:
return coverage.extract_info(
Expand Down
2 changes: 0 additions & 2 deletions coverage_comment/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,6 @@ class NoArtifact(Exception):
class CannotGetDiff(Exception):
"""Raised when the diff cannot be fetched from GitHub."""

pass


@dataclasses.dataclass
class RepositoryInfo:
Expand Down
2 changes: 0 additions & 2 deletions coverage_comment/github_client.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
#!/usr/bin/env python

"""
From: https://github.com/michaelliao/githubpy/blob/96d0c3e729c0b3e3c043a604547ccff17782ac2b/github.py
GitHub API Python SDK. (Python >= 2.6)
Expand Down
14 changes: 12 additions & 2 deletions coverage_comment/json.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,17 @@

import json as python_json
from collections.abc import Mapping, Sequence
from json import JSONDecodeError as JSONDecodeError # reexport error
from json import JSONDecodeError

__all__ = [
"JSONDecodeError",
"Json",
"ROJson",
"UnexpectedType",
"dumps",
"loads",
"loads_dict",
]

type Json = dict[str, Json] | list[Json] | str | int | float | bool | None
type ROJson = Mapping[str, Json] | Sequence[Json] | str | int | float | bool | None
Expand All @@ -15,7 +25,7 @@ def dumps(obj: ROJson) -> str:
def loads(serialized: str) -> Json:
try:
return python_json.loads(serialized)
except python_json.JSONDecodeError as exc:
except JSONDecodeError as exc:
exc.add_note(f"Full string that triggered JSONDecodeError: {serialized}")
raise

Expand Down
2 changes: 1 addition & 1 deletion coverage_comment/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ def process_pr(
pr_number=config.GITHUB_PR_NUMBER,
)
else: # pragma: no cover
raise Exception("Unreachable code")
raise AssertionError("Unreachable code")
except github.CannotGetDiff as exc:
failure_msg = str(exc)
log.warning(failure_msg, exc_info=True)
Expand Down
4 changes: 2 additions & 2 deletions coverage_comment/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ class Config:
COMMENT_FILENAME: pathlib.Path = pathlib.Path("python-coverage-comment-action.txt")
SUBPROJECT_ID: str | None = None
GITHUB_OUTPUT: pathlib.Path | None = None
MINIMUM_GREEN: decimal.Decimal = decimal.Decimal("100")
MINIMUM_ORANGE: decimal.Decimal = decimal.Decimal("70")
MINIMUM_GREEN: decimal.Decimal = decimal.Decimal(100)
MINIMUM_ORANGE: decimal.Decimal = decimal.Decimal(70)
MERGE_COVERAGE_FILES: bool = False
ANNOTATE_MISSING_LINES: bool = False
ANNOTATION_TYPE: str = "warning"
Expand Down
2 changes: 1 addition & 1 deletion coverage_comment/template.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ def remove_exponent(val: decimal.Decimal) -> decimal.Decimal:

def percentage_value(val: decimal.Decimal, precision: int = 2) -> decimal.Decimal:
return remove_exponent(
(decimal.Decimal("100") * val).quantize(
(decimal.Decimal(100) * val).quantize(
decimal.Decimal("1." + ("0" * precision)),
rounding=decimal.ROUND_DOWN,
)
Expand Down
9 changes: 5 additions & 4 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ include = ["coverage_comment", "coverage_comment/default.md.j2"]
[tool.pytest.ini_options]
addopts = """
--cov-report term-missing --cov-branch --cov-report html --cov-report term
--cov=coverage_comment --cov-context=test -vv --strict-markers -rfE
--cov=coverage_comment -vv --strict-markers -rfE
--ignore=tests/end_to_end/repo
"""
testpaths = ["tests/unit", "tests/integration", "tests/end_to_end"]
Expand All @@ -58,9 +58,6 @@ relative_files = true
[tool.coverage.report]
exclude_also = ["\\.\\.\\."]

[tool.coverage.html]
show_contexts = true

[tool.mypy]
no_implicit_optional = true

Expand All @@ -79,6 +76,10 @@ extend-select = [
fixable = ["ALL"]
extend-ignore = [
"E501", # line too long
# We read timestamps produced by coverage.py, which are naive.
"DTZ001", # datetime() without tzinfo
# Tests use bare expressions to trigger exceptions.
"B018", # useless expression
]

[tool.ruff.lint.isort]
Expand Down
8 changes: 5 additions & 3 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,9 +131,11 @@ def in_tmp_path(tmp_path):
def zip_bytes():
def _(filename, content):
file = io.BytesIO()
with zipfile.ZipFile(file, mode="w") as zipf:
with zipf.open(filename, "w") as subfile:
subfile.write(content.encode("utf-8"))
with (
zipfile.ZipFile(file, mode="w") as zipf,
zipf.open(filename, "w") as subfile,
):
subfile.write(content.encode("utf-8"))
zip_bytes = file.getvalue()
assert zip_bytes.startswith(b"PK")
return zip_bytes
Expand Down
2 changes: 1 addition & 1 deletion tests/end_to_end/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def _(command, *args, env, **kwargs):
**kwargs,
)
except subprocess.CalledProcessError as exc:
print("\n".join([exc.stdout, exc.stderr]))
print(f"{exc.stdout}\n{exc.stderr}")
raise
return call.stdout

Expand Down
24 changes: 12 additions & 12 deletions tests/unit/test_badge.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,30 +10,30 @@
@pytest.mark.parametrize(
"rate, expected",
[
(decimal.Decimal("10"), "red"),
(decimal.Decimal("80"), "orange"),
(decimal.Decimal("99"), "brightgreen"),
(decimal.Decimal(10), "red"),
(decimal.Decimal(80), "orange"),
(decimal.Decimal(99), "brightgreen"),
],
)
def test_get_badge_color(rate, expected):
color = badge.get_badge_color(
rate=rate,
minimum_green=decimal.Decimal("90"),
minimum_orange=decimal.Decimal("60"),
minimum_green=decimal.Decimal(90),
minimum_orange=decimal.Decimal(60),
)
assert color == expected


@pytest.mark.parametrize(
"delta, up_is_good, neutral_color, expected",
[
(decimal.Decimal("-5"), True, "lightgrey", "red"),
(decimal.Decimal("5"), True, "lightgrey", "brightgreen"),
(decimal.Decimal("-5"), False, "lightgrey", "brightgreen"),
(decimal.Decimal("5"), False, "lightgrey", "red"),
(decimal.Decimal("0"), False, "blue", "blue"),
(decimal.Decimal("0"), False, "lightgrey", "lightgrey"),
(decimal.Decimal("0"), True, "lightgrey", "lightgrey"),
(decimal.Decimal(-5), True, "lightgrey", "red"),
(decimal.Decimal(5), True, "lightgrey", "brightgreen"),
(decimal.Decimal(-5), False, "lightgrey", "brightgreen"),
(decimal.Decimal(5), False, "lightgrey", "red"),
(decimal.Decimal(0), False, "blue", "blue"),
(decimal.Decimal(0), False, "lightgrey", "lightgrey"),
(decimal.Decimal(0), True, "lightgrey", "lightgrey"),
],
)
def test_get_evolution_badge_color(delta, up_is_good, neutral_color, expected):
Expand Down
8 changes: 4 additions & 4 deletions tests/unit/test_coverage.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ def test__make_coverage_info__with_branches():
coverage.DiffCoverage(
total_num_lines=0,
total_num_violations=0,
total_percent_covered=decimal.Decimal("1"),
total_percent_covered=decimal.Decimal(1),
num_changed_lines=2,
files={},
),
Expand All @@ -212,12 +212,12 @@ def test__make_coverage_info__with_branches():
coverage.DiffCoverage(
total_num_lines=0,
total_num_violations=0,
total_percent_covered=decimal.Decimal("1"),
total_percent_covered=decimal.Decimal(1),
num_changed_lines=3,
files={
pathlib.Path("codebase/code.py"): coverage.FileDiffCoverage(
path=pathlib.Path("codebase/code.py"),
percent_covered=decimal.Decimal("1"),
percent_covered=decimal.Decimal(1),
added_statements=[],
covered_statements=[],
missing_statements=[],
Expand Down Expand Up @@ -252,7 +252,7 @@ def test__make_coverage_info__with_branches():
files={
pathlib.Path("codebase/code.py"): coverage.FileDiffCoverage(
path=pathlib.Path("codebase/code.py"),
percent_covered=decimal.Decimal("1"),
percent_covered=decimal.Decimal(1),
added_statements=[5, 6],
covered_statements=[5, 6],
missing_statements=[],
Expand Down
4 changes: 2 additions & 2 deletions tests/unit/test_files.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@ def test_compute_files(session):
line_rate=decimal.Decimal("0.1234"),
raw_coverage_data={"foo": ["bar", "bar2"]},
coverage_path=pathlib.Path("."),
minimum_green=decimal.Decimal("25"),
minimum_orange=decimal.Decimal("70"),
minimum_green=decimal.Decimal(25),
minimum_orange=decimal.Decimal(70),
http_session=session,
)
expected = [
Expand Down
4 changes: 1 addition & 3 deletions tests/unit/test_groups.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,14 @@
([1, 2], {1, 2}, set(), [(1, 2)]),
# Group of lines
([1, 2, 3], {1, 2, 3}, set(), [(1, 3)]),
# Pair of lines with a blank line in between
# Pair of lines with a blank line in between (a 1-sized gap)
([1, 3], {1, 3}, set(), [(1, 3)]),
# Pair of lines with a separator in between
([1, 3], {1, 2, 3}, set(), [(1, 1), (3, 3)]),
# 3 groups of lines with separators in between
([1, 3, 5], {1, 2, 3, 4, 5}, set(), [(1, 1), (3, 3), (5, 5)]),
# 3 groups of lines with a small gap & no separator in between
([1, 3, 5], {1, 3, 5}, set(), [(1, 5)]),
# with a 1-sized gap
([1, 3], {1, 3}, set(), [(1, 3)]),
# with a 2-sized gap
([1, 4], {1, 4}, set(), [(1, 4)]),
# with a 3-sized gap
Expand Down
3 changes: 2 additions & 1 deletion tests/unit/test_log_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ class TestHandler(logging.Handler):
def emit(self, record):
logs.append(self.format(record))

logger = logging.Logger("test", level="DEBUG")
logger = logging.getLogger("test")
logger.setLevel("DEBUG")
handler = TestHandler()
handler.setFormatter(log_utils.GitHubFormatter())
logger.addHandler(handler)
Expand Down
4 changes: 2 additions & 2 deletions tests/unit/test_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ def test_config__from_environ__ok():
COMMENT_TEMPLATE="footemplate",
COVERAGE_DATA_BRANCH="branchname",
COVERAGE_PATH=pathlib.Path("source_folder/"),
MINIMUM_GREEN=decimal.Decimal("90"),
MINIMUM_GREEN=decimal.Decimal(90),
MINIMUM_ORANGE=decimal.Decimal("50.8"),
MERGE_COVERAGE_FILES=True,
ANNOTATE_MISSING_LINES=False,
Expand Down Expand Up @@ -121,7 +121,7 @@ def config() -> Callable[..., settings.Config]:
"COMMENT_ARTIFACT_NAME": "baz",
"COMMENT_FILENAME": pathlib.Path("qux"),
"COVERAGE_DATA_BRANCH": "branchname",
"MINIMUM_GREEN": decimal.Decimal("90"),
"MINIMUM_GREEN": decimal.Decimal(90),
"MINIMUM_ORANGE": decimal.Decimal("50.8"),
"MERGE_COVERAGE_FILES": True,
}
Expand Down
8 changes: 5 additions & 3 deletions tests/unit/test_storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,11 @@ def test_checked_out_branch__fetch_fails(git):
git.register("--config-env=http.extraheader=GIT_EXTRA_HEADER fetch origin")
git.register("rev-parse --verify origin/foo")

with pytest.raises(subprocess.GitError):
with storage.checked_out_branch(git=git, branch="foo", token="secret"):
pass
with (
pytest.raises(subprocess.GitError),
storage.checked_out_branch(git=git, branch="foo", token="secret"),
):
pass


def test_commit_operations__no_diff(git, in_tmp_path):
Expand Down
Loading
Loading