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 .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.15.18
hooks:
- id: ruff
- id: ruff-check
args: [--fix]
- id: ruff-format

Expand Down
3 changes: 2 additions & 1 deletion coverage_comment/badge.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,12 @@
from __future__ import annotations

import decimal
import json
import urllib.parse

import httpx

from . import json


def get_badge_color(
rate: decimal.Decimal,
Expand Down
9 changes: 5 additions & 4 deletions coverage_comment/coverage.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@
import dataclasses
import datetime
import decimal
import json
import pathlib
from collections.abc import Sequence
from typing import Any

from coverage_comment import log, subprocess
from coverage_comment import subprocess

from . import json


# The dataclasses in this module are accessible in the template, which is overridable by the user.
Expand Down Expand Up @@ -117,12 +118,12 @@ def get_coverage_info(
if merge:
subprocess.run("coverage", "combine", path=coverage_path)

json_coverage = json.loads(
json_coverage = json.loads_dict(
subprocess.run("coverage", "json", "-o", "-", path=coverage_path)
)
except subprocess.SubProcessError as exc:
if "No source for code:" in str(exc):
log.error(
exc.add_note(
"Cannot read .coverage files because files are absolute. You need "
"to configure coverage to write relative paths by adding the following "
"option to your coverage configuration file:\n"
Expand Down
9 changes: 5 additions & 4 deletions coverage_comment/files.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@

import dataclasses
import decimal
import json
import pathlib
import shutil
import tempfile
Expand All @@ -17,6 +16,8 @@

from coverage_comment import badge, coverage, log

from . import json

ENDPOINT_PATH = pathlib.Path("endpoint.json")
DATA_PATH = pathlib.Path("data.json")
BADGE_PATH = pathlib.Path("badge.svg")
Expand Down Expand Up @@ -110,14 +111,14 @@ def compute_datafile(


def parse_datafile(contents: str) -> tuple[coverage.Coverage | None, decimal.Decimal]:
file_contents = json.loads(contents)
file_contents = json.loads_dict(contents)
coverage_rate = decimal.Decimal(str(file_contents["coverage"])) / decimal.Decimal(
"100"
)
try:
return coverage.extract_info(
data=file_contents["raw_data"],
coverage_path=pathlib.Path(file_contents["coverage_path"]),
data=file_contents["raw_data"], # pyright: ignore[reportArgumentType]
coverage_path=pathlib.Path(file_contents["coverage_path"]), # pyright: ignore[reportArgumentType]
), coverage_rate
except KeyError:
return None, coverage_rate
Expand Down
5 changes: 3 additions & 2 deletions coverage_comment/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import dataclasses
import io
import json
import pathlib
import re
import sys
Expand All @@ -13,6 +12,8 @@

from coverage_comment import github_client, log

from . import json

GITHUB_ACTIONS_LOGIN = "github-actions[bot]"


Expand Down Expand Up @@ -339,7 +340,7 @@ def _is_too_large_error(exc: github_client.ApiError) -> bool:
The error response body is JSON from GitHub's API.
"""
try:
error_data: dict[str, Any] = json.loads(str(exc))
error_data: dict[str, Any] = json.loads_dict(str(exc))
errors: list[dict[str, Any]] = error_data.get("errors", [])
return any(error.get("code") == "too_large" for error in errors)
except (json.JSONDecodeError, TypeError):
Expand Down
33 changes: 33 additions & 0 deletions coverage_comment/json.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
from __future__ import annotations

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

type Json = dict[str, Json] | list[Json] | str | int | float | bool | None
type ROJson = Mapping[str, Json] | Sequence[Json] | str | int | float | bool | None


def dumps(obj: ROJson) -> str:
return python_json.dumps(obj=obj)


def loads(serialized: str) -> Json:
try:
return python_json.loads(serialized)
except python_json.JSONDecodeError as exc:
exc.add_note(f"Full string that triggered JSONDecodeError: {serialized}")
raise


class UnexpectedType(Exception):
pass


def loads_dict(serialized: str) -> dict[str, Json]:
result = loads(serialized)
if not isinstance(result, dict):
raise UnexpectedType(
f"Object loaded from json is expected to be a dict, got a {type(result).__name__}\nObject: {result}"
)
return result
7 changes: 6 additions & 1 deletion coverage_comment/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@


def main():
config = None
try:
logging.basicConfig(level="DEBUG")
logging.getLogger().handlers[0].formatter = log_utils.GitHubFormatter()
Expand Down Expand Up @@ -55,7 +56,11 @@ def main():

except Exception:
log.exception(
"Critical error. This error possibly occurred because the permissions of the workflow are set incorrectly. You can see the correct setting of permissions here: https://github.com/py-cov-action/python-coverage-comment-action#basic-usage\nOtherwise please look for open issues or open one in https://github.com/py-cov-action/python-coverage-comment-action/"
"Critical error. Please look at the error details and check the user manual at "
"https://github.com/py-cov-action/python-coverage-comment-action\n"
"If you believe this is a bug in the action, please consult open issues or "
"open a new one at https://github.com/py-cov-action/python-coverage-comment-action/issues .\n"
f"Full config: {config}"
)
sys.exit(1)

Expand Down
5 changes: 3 additions & 2 deletions coverage_comment/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,14 @@
import decimal
import functools
import inspect
import json
import pathlib
from collections.abc import MutableMapping
from typing import Any

from coverage_comment import log

from . import json


class MissingEnvironmentVariable(Exception):
pass
Expand Down Expand Up @@ -149,7 +150,7 @@ def GITHUB_BRANCH_NAME(self) -> str | None:
def GITHUB_EVENT_PAYLOAD(self) -> dict[str, Any]:
if not self.GITHUB_EVENT_PATH:
return {}
return json.loads(self.GITHUB_EVENT_PATH.read_text())
return json.loads_dict(self.GITHUB_EVENT_PATH.read_text())

@property
def GITHUB_EVENT_TYPE(self) -> str | None:
Expand Down
13 changes: 9 additions & 4 deletions coverage_comment/subprocess.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class GitError(SubProcessError):

def run(*args: str, path: pathlib.Path, **kwargs: Any) -> str:
try:
return subprocess.run(
call = subprocess.run(
args,
cwd=path,
text=True,
Expand All @@ -29,12 +29,17 @@ def run(*args: str, path: pathlib.Path, **kwargs: Any) -> str:
check=True,
capture_output=True,
**kwargs,
).stdout
)
except subprocess.CalledProcessError as exc:
exc.add_note(
f"Error on command: {args=} {path=} {kwargs=} {exc.returncode=}\n{exc.stderr=}\n{exc.stdout=}"
)
raise SubProcessError("Error on calling subprocess.") from exc
else:
log.debug(
f"Command failed: {args=} {path=} {kwargs=} {exc.stderr=} {exc.returncode=}"
f"Ran command: {args=} {path=} {kwargs=} {call.stderr=} {call.stdout=} {call.returncode=}"
)
raise SubProcessError("\n".join([exc.stderr, exc.stdout])) from exc
return call.stdout


class Git:
Expand Down
6 changes: 3 additions & 3 deletions tests/unit/test_coverage.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,16 +99,16 @@ def test_get_coverage_info__error_base(mocker, get_logs):
assert not get_logs("ERROR")


def test_get_coverage_info__error_no_source(mocker, get_logs):
def test_get_coverage_info__error_no_source(mocker):
mocker.patch(
"coverage_comment.subprocess.run",
side_effect=subprocess.SubProcessError("No source for code: bla"),
)

with pytest.raises(subprocess.SubProcessError):
with pytest.raises(subprocess.SubProcessError) as exc_info:
coverage.get_coverage_info(merge=False, coverage_path=pathlib.Path("."))

assert get_logs("ERROR", "Cannot read")
assert "No source" in str(exc_info.value)


def test_generate_coverage_html_files(mocker):
Expand Down
29 changes: 29 additions & 0 deletions tests/unit/test_json.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
from __future__ import annotations

import pytest

from coverage_comment import json


def test_dumps():
assert json.dumps({"hello": ["world", 42]}) == '{"hello": ["world", 42]}'


def test_loads():
assert json.loads('{"hello": ["world", 42]}') == {"hello": ["world", 42]}


def test_loads__error():
with pytest.raises(json.JSONDecodeError) as exc_info:
json.loads("a")

assert exc_info.value.__notes__ == ["Full string that triggered JSONDecodeError: a"]


def test_loads_dict():
assert json.loads_dict('{"hello": ["world", 42]}') == {"hello": ["world", 42]}


def test_loads_dict__error():
with pytest.raises(json.UnexpectedType):
json.loads_dict("[]")
5 changes: 3 additions & 2 deletions tests/unit/test_log_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ def emit(self, record):
logger.critical("an error message")
try:
0 / 0
except Exception:
except Exception as exc:
exc.add_note("note")
logger.exception("an exception")

logs = "\n".join(logs)
Expand All @@ -48,6 +49,6 @@ def emit(self, record):
::warning::a warning message
::error::an error message
::error::an error message
::error::an exception%0ATraceback (most recent call last):%0A File "foo.py", line 42, in test__github_formatter%0A 0 / 0%0A ~~^~~%0AZeroDivisionError: division by zero""".strip()
::error::an exception%0ATraceback (most recent call last):%0A File "foo.py", line 42, in test__github_formatter%0A 0 / 0%0A ~~^~~%0AZeroDivisionError: division by zero%0Anote""".strip()

assert logs == expected
Loading