From e8610ca1eefe8960a8747e456b8bf97393ac427c Mon Sep 17 00:00:00 2001 From: Mohsen Azimi <543633+mohsen1@users.noreply.github.com> Date: Sun, 25 Oct 2026 22:30:49 +0100 Subject: [PATCH] feat: upload coverage reports with sync and async clients --- README.md | 30 +++ openapi.public.json | 200 ++++++++++++++++ proofline/__init__.py | 6 + .../api/default/upload_coverage_reports.py | 225 ++++++++++++++++++ proofline/_generated/models/__init__.py | 8 + .../_generated/models/coverage_refused.py | 79 ++++++ .../models/coverage_upload_request.py | 68 ++++++ .../models/coverage_upload_response.py | 104 ++++++++ .../_generated/models/uploaded_report.py | 51 ++++ proofline/client.py | 25 ++ scripts/contracts.py | 4 +- tests/test_http.py | 59 +++++ 12 files changed, 857 insertions(+), 2 deletions(-) create mode 100644 proofline/_generated/api/default/upload_coverage_reports.py create mode 100644 proofline/_generated/models/coverage_refused.py create mode 100644 proofline/_generated/models/coverage_upload_request.py create mode 100644 proofline/_generated/models/coverage_upload_response.py create mode 100644 proofline/_generated/models/uploaded_report.py diff --git a/README.md b/README.md index 8ff44241..4e6fbaf0 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,36 @@ coroutines. The [SDK guide](https://proofline.sh/docs/sdks/) and Licensed under the Apache License, Version 2.0. The generated models under `proofline/_generated` carry the MIT license of the generator templates. +## Coverage uploads + +Use a repository-restricted token with `coverage:write` and current repository write +access to upload reports from your CI. Name the full commit SHA the tests ran on. +Reports may use LCOV, Cobertura XML, JaCoCo XML or Go cover profiles. + +```python +import os +from pathlib import Path +from uuid import UUID +from proofline import CoverageUploadRequest, ProoflineClient, UploadedReport + +with ProoflineClient() as client: + report = client.upload_coverage_reports( + UUID(os.environ["PROOFLINE_ORGANIZATION_ID"]), + UUID(os.environ["PROOFLINE_REPOSITORY_ID"]), + body=CoverageUploadRequest( + tested_sha=os.environ["TESTED_SHA"], + reports=[UploadedReport( + name="lcov.info", + content=Path("lcov.info").read_text(encoding="utf-8"), + )], + ), + ) +``` + +The response names the recorded report and its covered and instrumented line counts. +An identical upload returns that report with `created=False`. Refused reports raise +`ProoflineError`; uploading a report does not establish a check verdict. + ## Development The repository bundles its public API contract in `openapi.public.json`. diff --git a/openapi.public.json b/openapi.public.json index 17205ad1..7c11188d 100644 --- a/openapi.public.json +++ b/openapi.public.json @@ -953,6 +953,100 @@ ], "type": "object" }, + "CoverageRefused": { + "description": "An upload refused for its content: a symbolic or unknown commit, or a\n report that cannot be read. Nothing is stored.", + "properties": { + "detail": { + "description": "One sentence naming what was refused and why.", + "type": "string" + }, + "status": { + "description": "Always 422.", + "format": "uint16", + "maximum": 65535, + "minimum": 0, + "type": "integer" + }, + "title": { + "description": "Always `unprocessable coverage upload`.", + "type": "string" + } + }, + "required": [ + "title", + "status", + "detail" + ], + "type": "object" + }, + "CoverageUploadRequest": { + "additionalProperties": false, + "description": "The coverage reports a CI run produced for one commit.", + "properties": { + "reports": { + "description": "One to 50 reports, each LCOV, Cobertura XML, `JaCoCo` XML or a Go\n cover profile, in a JSON body of at most 64 MiB.", + "items": { + "$ref": "#/components/schemas/UploadedReport" + }, + "type": "array" + }, + "tested_sha": { + "description": "The full 40-character commit the tests ran on. GitHub must have it in\n this repository. A merge commit counts for a pull request head that is\n one of its two parents.", + "type": "string" + } + }, + "required": [ + "tested_sha", + "reports" + ], + "type": "object" + }, + "CoverageUploadResponse": { + "description": "The report the upload recorded, or the one an identical upload recorded.", + "properties": { + "covered_lines": { + "description": "Covered lines among those instrumented lines.", + "format": "uint64", + "minimum": 0, + "type": "integer" + }, + "created": { + "description": "False when the same reports for this commit were already recorded.", + "type": "boolean" + }, + "formats": { + "description": "The format of each report, in upload order.", + "items": { + "type": "string" + }, + "type": "array" + }, + "instrumented_lines": { + "description": "Instrumented lines across the reports, a file two reports name under\n one path counted once.", + "format": "uint64", + "minimum": 0, + "type": "integer" + }, + "report_id": { + "description": "The recorded report.", + "format": "uuid", + "type": "string" + }, + "tested_sha": { + "description": "The commit the reports tested, as the upload named it.", + "type": "string" + } + }, + "required": [ + "report_id", + "tested_sha", + "created", + "formats", + "instrumented_lines", + "covered_lines" + ], + "type": "object" + }, "CustomerAssessment": { "properties": { "checks": { @@ -6217,6 +6311,24 @@ ], "type": "object" }, + "UploadedReport": { + "additionalProperties": false, + "properties": { + "content": { + "description": "The report text, exactly as the coverage tool wrote it.", + "type": "string" + }, + "name": { + "description": "A relative name for the report, such as `web/lcov.info`, unique in\n the upload.", + "type": "string" + } + }, + "required": [ + "name", + "content" + ], + "type": "object" + }, "WalkthroughFileView": { "properties": { "additions": { @@ -6882,6 +6994,94 @@ "x-proofline-token-scope": "reviews:request" } }, + "/api/v1/organizations/{org_id}/repositories/{repo_id}/coverage-reports": { + "post": { + "description": "Records the LCOV, Cobertura, JaCoCo or Go coverage reports a CI run produced for one exact commit GitHub has in the repository, for COVERAGE checks that accept uploads. A branch, tag or abbreviated SHA, or a report that cannot be read, gets 422 and stores nothing. Requires a repository-restricted token and live GitHub write access; the same reports for the same commit return the report already recorded.", + "operationId": "upload_coverage_reports", + "parameters": [ + { + "in": "path", + "name": "org_id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + }, + "style": "simple" + }, + { + "in": "path", + "name": "repo_id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + }, + "style": "simple" + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CoverageUploadRequest" + } + } + }, + "description": "The coverage reports a CI run produced for one commit.", + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CoverageUploadResponse" + } + } + }, + "description": "The report the upload recorded, or the one an identical upload recorded." + }, + "201": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CoverageUploadResponse" + } + } + }, + "description": "The report the upload recorded, or the one an identical upload recorded." + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CoverageRefused" + } + } + }, + "description": "An upload refused for its content: a symbolic or unknown commit, or a\n report that cannot be read. Nothing is stored." + }, + "default": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "An RFC 9457 problem; the HTTP status remains authoritative." + } + }, + "security": [ + { + "bearerAuth": [] + } + ], + "summary": "Upload coverage reports", + "x-proofline-token-scope": "coverage:write" + } + }, "/api/v1/organizations/{org_id}/repositories/{repo_id}/file-reviews": { "post": { "description": "Reviews up to twenty exact file paths at one pushed commit. Requires live GitHub read access and verifies every path at that commit. The retained selection is immutable; a repeat by the same person returns its review. Results remain in Proofline and are never posted to GitHub.", diff --git a/proofline/__init__.py b/proofline/__init__.py index 0b6b82ea..4a7d3a52 100644 --- a/proofline/__init__.py +++ b/proofline/__init__.py @@ -8,6 +8,8 @@ AgentVendor, CommitReviewRequest, CommitReviewResponse, + CoverageUploadRequest, + CoverageUploadResponse, CustomerAssessmentDetail, CustomerFinding, CustomerReviewDetail, @@ -25,6 +27,7 @@ RunNowResponse, StartSession, StopResponse, + UploadedReport, ) from ._transport import VERSION as __version__ from ._transport import ProoflineError @@ -39,6 +42,8 @@ "CheckGap", "CommitReviewRequest", "CommitReviewResponse", + "CoverageUploadRequest", + "CoverageUploadResponse", "CustomerAssessmentDetail", "CustomerFinding", "CustomerReviewDetail", @@ -61,6 +66,7 @@ "SecretStr", "StartSession", "StopResponse", + "UploadedReport", "__version__", "models", ] diff --git a/proofline/_generated/api/default/upload_coverage_reports.py b/proofline/_generated/api/default/upload_coverage_reports.py new file mode 100644 index 00000000..ded75e8d --- /dev/null +++ b/proofline/_generated/api/default/upload_coverage_reports.py @@ -0,0 +1,225 @@ +from http import HTTPStatus +from typing import Any +from urllib.parse import quote +from uuid import UUID + +import httpx + +from ...client import AuthenticatedClient, Client +from ...models.coverage_refused import CoverageRefused +from ...models.coverage_upload_request import CoverageUploadRequest +from ...models.coverage_upload_response import CoverageUploadResponse +from ...models.problem import Problem +from ...types import Response + + +def _get_kwargs( + org_id: UUID, + repo_id: UUID, + *, + body: CoverageUploadRequest, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/api/v1/organizations/{org_id}/repositories/{repo_id}/coverage-reports".format( + org_id=quote(str(org_id), safe=""), + repo_id=quote(str(repo_id), safe=""), + ), + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx.Response +) -> CoverageRefused | CoverageUploadResponse | Problem: + if response.status_code == 200: + response_200 = CoverageUploadResponse.from_dict(response.json()) + + return response_200 + + if response.status_code == 201: + response_201 = CoverageUploadResponse.from_dict(response.json()) + + return response_201 + + if response.status_code == 422: + response_422 = CoverageRefused.from_dict(response.json()) + + return response_422 + + response_default = Problem.from_dict(response.json()) + + return response_default + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx.Response +) -> Response[CoverageRefused | CoverageUploadResponse | Problem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + org_id: UUID, + repo_id: UUID, + *, + client: AuthenticatedClient, + body: CoverageUploadRequest, +) -> Response[CoverageRefused | CoverageUploadResponse | Problem]: + """Upload coverage reports + + Records the LCOV, Cobertura, JaCoCo or Go coverage reports a CI run produced for one exact commit + GitHub has in the repository, for COVERAGE checks that accept uploads. A branch, tag or abbreviated + SHA, or a report that cannot be read, gets 422 and stores nothing. Requires a repository-restricted + token and live GitHub write access; the same reports for the same commit return the report already + recorded. + + Args: + org_id (UUID): + repo_id (UUID): + body (CoverageUploadRequest): The coverage reports a CI run produced for one commit. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[CoverageRefused | CoverageUploadResponse | Problem] + """ + + kwargs = _get_kwargs( + org_id=org_id, + repo_id=repo_id, + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + org_id: UUID, + repo_id: UUID, + *, + client: AuthenticatedClient, + body: CoverageUploadRequest, +) -> CoverageRefused | CoverageUploadResponse | Problem | None: + """Upload coverage reports + + Records the LCOV, Cobertura, JaCoCo or Go coverage reports a CI run produced for one exact commit + GitHub has in the repository, for COVERAGE checks that accept uploads. A branch, tag or abbreviated + SHA, or a report that cannot be read, gets 422 and stores nothing. Requires a repository-restricted + token and live GitHub write access; the same reports for the same commit return the report already + recorded. + + Args: + org_id (UUID): + repo_id (UUID): + body (CoverageUploadRequest): The coverage reports a CI run produced for one commit. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + CoverageRefused | CoverageUploadResponse | Problem + """ + + return sync_detailed( + org_id=org_id, + repo_id=repo_id, + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + org_id: UUID, + repo_id: UUID, + *, + client: AuthenticatedClient, + body: CoverageUploadRequest, +) -> Response[CoverageRefused | CoverageUploadResponse | Problem]: + """Upload coverage reports + + Records the LCOV, Cobertura, JaCoCo or Go coverage reports a CI run produced for one exact commit + GitHub has in the repository, for COVERAGE checks that accept uploads. A branch, tag or abbreviated + SHA, or a report that cannot be read, gets 422 and stores nothing. Requires a repository-restricted + token and live GitHub write access; the same reports for the same commit return the report already + recorded. + + Args: + org_id (UUID): + repo_id (UUID): + body (CoverageUploadRequest): The coverage reports a CI run produced for one commit. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[CoverageRefused | CoverageUploadResponse | Problem] + """ + + kwargs = _get_kwargs( + org_id=org_id, + repo_id=repo_id, + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + org_id: UUID, + repo_id: UUID, + *, + client: AuthenticatedClient, + body: CoverageUploadRequest, +) -> CoverageRefused | CoverageUploadResponse | Problem | None: + """Upload coverage reports + + Records the LCOV, Cobertura, JaCoCo or Go coverage reports a CI run produced for one exact commit + GitHub has in the repository, for COVERAGE checks that accept uploads. A branch, tag or abbreviated + SHA, or a report that cannot be read, gets 422 and stores nothing. Requires a repository-restricted + token and live GitHub write access; the same reports for the same commit return the report already + recorded. + + Args: + org_id (UUID): + repo_id (UUID): + body (CoverageUploadRequest): The coverage reports a CI run produced for one commit. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + CoverageRefused | CoverageUploadResponse | Problem + """ + + return ( + await asyncio_detailed( + org_id=org_id, + repo_id=repo_id, + client=client, + body=body, + ) + ).parsed diff --git a/proofline/_generated/models/__init__.py b/proofline/_generated/models/__init__.py index 7f6e8d05..5099610c 100644 --- a/proofline/_generated/models/__init__.py +++ b/proofline/_generated/models/__init__.py @@ -27,6 +27,9 @@ from .commit_review_request import CommitReviewRequest from .commit_review_response import CommitReviewResponse from .complete_record_view import CompleteRecordView +from .coverage_refused import CoverageRefused +from .coverage_upload_request import CoverageUploadRequest +from .coverage_upload_response import CoverageUploadResponse from .customer_assessment import CustomerAssessment from .customer_assessment_detail import CustomerAssessmentDetail from .customer_check import CustomerCheck @@ -170,6 +173,7 @@ from .thread_provider_state import ThreadProviderState from .thread_reply_evidence import ThreadReplyEvidence from .untrusted_text import UntrustedText +from .uploaded_report import UploadedReport from .walkthrough_file_view import WalkthroughFileView from .walkthrough_group_view import WalkthroughGroupView from .walkthrough_view import WalkthroughView @@ -202,6 +206,9 @@ "CommitReviewRequest", "CommitReviewResponse", "CompleteRecordView", + "CoverageRefused", + "CoverageUploadRequest", + "CoverageUploadResponse", "CustomerAssessment", "CustomerAssessmentDetail", "CustomerCheck", @@ -345,6 +352,7 @@ "ThreadProviderState", "ThreadReplyEvidence", "UntrustedText", + "UploadedReport", "WalkthroughFileView", "WalkthroughGroupView", "WalkthroughView", diff --git a/proofline/_generated/models/coverage_refused.py b/proofline/_generated/models/coverage_refused.py new file mode 100644 index 00000000..8e42004b --- /dev/null +++ b/proofline/_generated/models/coverage_refused.py @@ -0,0 +1,79 @@ +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="CoverageRefused") + + +@_attrs_define +class CoverageRefused: + """An upload refused for its content: a symbolic or unknown commit, or a + report that cannot be read. Nothing is stored. + + Attributes: + detail (str): One sentence naming what was refused and why. + status (int): Always 422. + title (str): Always `unprocessable coverage upload`. + """ + + detail: str + status: int + title: str + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + detail = self.detail + + status = self.status + + title = self.title + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "detail": detail, + "status": status, + "title": title, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + detail = d.pop("detail") + + status = d.pop("status") + + title = d.pop("title") + + coverage_refused = cls( + detail=detail, + status=status, + title=title, + ) + + coverage_refused.additional_properties = d + return coverage_refused + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/proofline/_generated/models/coverage_upload_request.py b/proofline/_generated/models/coverage_upload_request.py new file mode 100644 index 00000000..8f61ca01 --- /dev/null +++ b/proofline/_generated/models/coverage_upload_request.py @@ -0,0 +1,68 @@ +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar + +from attrs import define as _attrs_define + +if TYPE_CHECKING: + from ..models.uploaded_report import UploadedReport + + +T = TypeVar("T", bound="CoverageUploadRequest") + + +@_attrs_define +class CoverageUploadRequest: + """The coverage reports a CI run produced for one commit. + + Attributes: + reports (list[UploadedReport]): One to 50 reports, each LCOV, Cobertura XML, `JaCoCo` XML or a Go + cover profile, in a JSON body of at most 64 MiB. + tested_sha (str): The full 40-character commit the tests ran on. GitHub must have it in + this repository. A merge commit counts for a pull request head that is + one of its two parents. + """ + + reports: list[UploadedReport] + tested_sha: str + + def to_dict(self) -> dict[str, Any]: + reports = [] + for reports_item_data in self.reports: + reports_item = reports_item_data.to_dict() + reports.append(reports_item) + + tested_sha = self.tested_sha + + field_dict: dict[str, Any] = {} + + field_dict.update( + { + "reports": reports, + "tested_sha": tested_sha, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.uploaded_report import UploadedReport # noqa: PLC0415 + + d = dict(src_dict) + reports = [] + _reports = d.pop("reports") + for reports_item_data in _reports: + reports_item = UploadedReport.from_dict(reports_item_data) + + reports.append(reports_item) + + tested_sha = d.pop("tested_sha") + + coverage_upload_request = cls( + reports=reports, + tested_sha=tested_sha, + ) + + return coverage_upload_request diff --git a/proofline/_generated/models/coverage_upload_response.py b/proofline/_generated/models/coverage_upload_response.py new file mode 100644 index 00000000..37ffab5e --- /dev/null +++ b/proofline/_generated/models/coverage_upload_response.py @@ -0,0 +1,104 @@ +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar, cast +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="CoverageUploadResponse") + + +@_attrs_define +class CoverageUploadResponse: + """The report the upload recorded, or the one an identical upload recorded. + + Attributes: + covered_lines (int): Covered lines among those instrumented lines. + created (bool): False when the same reports for this commit were already recorded. + formats (list[str]): The format of each report, in upload order. + instrumented_lines (int): Instrumented lines across the reports, a file two reports name under + one path counted once. + report_id (UUID): The recorded report. + tested_sha (str): The commit the reports tested, as the upload named it. + """ + + covered_lines: int + created: bool + formats: list[str] + instrumented_lines: int + report_id: UUID + tested_sha: str + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + covered_lines = self.covered_lines + + created = self.created + + formats = self.formats + + instrumented_lines = self.instrumented_lines + + report_id = str(self.report_id) + + tested_sha = self.tested_sha + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "covered_lines": covered_lines, + "created": created, + "formats": formats, + "instrumented_lines": instrumented_lines, + "report_id": report_id, + "tested_sha": tested_sha, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + covered_lines = d.pop("covered_lines") + + created = d.pop("created") + + formats = cast(list[str], d.pop("formats")) + + instrumented_lines = d.pop("instrumented_lines") + + report_id = UUID(d.pop("report_id")) + + tested_sha = d.pop("tested_sha") + + coverage_upload_response = cls( + covered_lines=covered_lines, + created=created, + formats=formats, + instrumented_lines=instrumented_lines, + report_id=report_id, + tested_sha=tested_sha, + ) + + coverage_upload_response.additional_properties = d + return coverage_upload_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/proofline/_generated/models/uploaded_report.py b/proofline/_generated/models/uploaded_report.py new file mode 100644 index 00000000..dcb17f81 --- /dev/null +++ b/proofline/_generated/models/uploaded_report.py @@ -0,0 +1,51 @@ +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define + +T = TypeVar("T", bound="UploadedReport") + + +@_attrs_define +class UploadedReport: + """ + Attributes: + content (str): The report text, exactly as the coverage tool wrote it. + name (str): A relative name for the report, such as `web/lcov.info`, unique in + the upload. + """ + + content: str + name: str + + def to_dict(self) -> dict[str, Any]: + content = self.content + + name = self.name + + field_dict: dict[str, Any] = {} + + field_dict.update( + { + "content": content, + "name": name, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + content = d.pop("content") + + name = d.pop("name") + + uploaded_report = cls( + content=content, + name=name, + ) + + return uploaded_report diff --git a/proofline/client.py b/proofline/client.py index 1ff185f4..8c0b4eb6 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -36,6 +36,7 @@ rerun_review, start_agent_session, stop_review, + upload_coverage_reports, ) from ._generated.client import AuthenticatedClient from ._generated.models.agent_session import AgentSession @@ -43,6 +44,8 @@ from ._generated.models.agent_session_prompt_type_1 import AgentSessionPromptType1 from ._generated.models.commit_review_request import CommitReviewRequest from ._generated.models.commit_review_response import CommitReviewResponse +from ._generated.models.coverage_upload_request import CoverageUploadRequest +from ._generated.models.coverage_upload_response import CoverageUploadResponse from ._generated.models.customer_assessment_detail import CustomerAssessmentDetail from ._generated.models.customer_finding import CustomerFinding from ._generated.models.customer_review_detail import CustomerReviewDetail @@ -375,6 +378,17 @@ def request_patch_review( body=body, ) + def upload_coverage_reports( + self, organization_id: UUID, repository_id: UUID, *, body: CoverageUploadRequest + ) -> CoverageUploadResponse: + return self._call( + upload_coverage_reports.sync_detailed, + CoverageUploadResponse, + organization_id, + repository_id, + body=body, + ) + def request_file_review( self, organization_id: UUID, repository_id: UUID, *, body: FileReviewRequest ) -> FileReviewResponse: @@ -680,6 +694,17 @@ async def request_patch_review( body=body, ) + async def upload_coverage_reports( + self, organization_id: UUID, repository_id: UUID, *, body: CoverageUploadRequest + ) -> CoverageUploadResponse: + return await self._call( + upload_coverage_reports.asyncio_detailed, + CoverageUploadResponse, + organization_id, + repository_id, + body=body, + ) + async def request_file_review( self, organization_id: UUID, repository_id: UUID, *, body: FileReviewRequest ) -> FileReviewResponse: diff --git a/scripts/contracts.py b/scripts/contracts.py index f372bfc0..3b3e7378 100644 --- a/scripts/contracts.py +++ b/scripts/contracts.py @@ -24,9 +24,9 @@ def main() -> None: for path in (ROOT / "proofline/_generated/api/default").glob("*.py") if path.name != "__init__.py" } - if declared != generated or len(declared) != 20: + if declared != generated or len(declared) != 21: raise SystemExit( - "The generated JSON operations must match the twenty public JSON token routes." + "The generated JSON operations must match the twenty-one public JSON token routes." ) tree = ast.parse((ROOT / "proofline/client.py").read_text()) helpers = {"close", "aclose", "iter_reviews", "wait_for_review"} diff --git a/tests/test_http.py b/tests/test_http.py index 15e11fdf..f44e157d 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -23,6 +23,8 @@ AsyncProoflineClient, CommitReviewRequest, CommitReviewResponse, + CoverageUploadRequest, + CoverageUploadResponse, CustomerAssessmentDetail, CustomerFinding, CustomerReviewDetail, @@ -40,6 +42,7 @@ RunNowRequest, RunNowResponse, StopResponse, + UploadedReport, _sync_http, _transport, models, @@ -391,6 +394,62 @@ def respond(request: Request, index: int) -> Reply: assert len(server.requests) == 1 +@MODES +async def test_coverage_upload_preserves_reports_commit_and_server_refusal(mode: str) -> None: + content = "SF:src/main.py\nDA:1,1\nDA:2,0\nend_of_record\n" + body = CoverageUploadRequest( + tested_sha="a" * 40, + reports=[UploadedReport(name="python/lcov.info", content=content)], + ) + + def respond(request: Request, index: int) -> Reply: + assert request.method == "POST" + assert request.path == ( + f"/api/v1/organizations/{ORG}/repositories/{REPOSITORY}/coverage-reports" + ) + assert request.headers["Authorization"] == f"Bearer {TOKEN}" + assert request.headers["Content-Type"] == "application/json" + assert json.loads(request.body) == { + "tested_sha": "a" * 40, + "reports": [{"name": "python/lcov.info", "content": content}], + } + if index == 2: + return Reply( + status=422, + body={ + "title": "unprocessable coverage upload", + "status": 422, + "detail": "The coverage upload was refused.", + }, + ) + return Reply( + status=201 if index == 0 else 200, + body={ + "report_id": str(REVIEW), + "tested_sha": "a" * 40, + "created": index == 0, + "formats": ["LCOV"], + "instrumented_lines": 2, + "covered_lines": 1, + }, + ) + + with Server(respond) as server: + async with session(mode, server.url) as client: + for created in (True, False): + result = await call(client, "upload_coverage_reports", ORG, REPOSITORY, body=body) + assert isinstance(result, CoverageUploadResponse) + assert result.report_id == REVIEW + assert result.tested_sha == "a" * 40 + assert result.created is created + assert result.formats == ["LCOV"] + assert (result.covered_lines, result.instrumented_lines) == (1, 2) + with pytest.raises(ProoflineError) as refused: + await call(client, "upload_coverage_reports", ORG, REPOSITORY, body=body) + assert refused.value.status == 422 + assert len(server.requests) == 3 + + @MODES @pytest.mark.parametrize("summary_state", ["absent", "null", "published", "withheld"]) async def test_review_reads_preserve_summary_and_exact_code_identity(