Skip to content
This repository was archived by the owner on Jun 13, 2025. It is now read-only.

Commit 902a5cb

Browse files
authored
API Improvements: Fix typings for various files pt4 (#1086)
1 parent 5433cb3 commit 902a5cb

File tree

10 files changed

+57
-37
lines changed

10 files changed

+57
-37
lines changed

api/internal/commit/serializers.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import logging
2+
from typing import Dict, List
23

34
import shared.reports.api_report_service as report_service
45
from rest_framework import serializers
@@ -32,7 +33,7 @@ class Meta:
3233
class CommitWithFileLevelReportSerializer(CommitSerializer):
3334
report = serializers.SerializerMethodField()
3435

35-
def get_report(self, commit: Commit):
36+
def get_report(self, commit: Commit) -> Dict[str, List[Dict] | Dict] | None:
3637
report = report_service.build_report_from_commit(commit)
3738
if report is None:
3839
return None

codecov_auth/commands/owner/interactors/save_terms_agreement.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from dataclasses import dataclass
2-
from typing import Optional
2+
from typing import Any, Optional
33

44
from django.utils import timezone
55

@@ -20,7 +20,7 @@ class TermsAgreementInput:
2020
class SaveTermsAgreementInteractor(BaseInteractor):
2121
requires_service = False
2222

23-
def validate(self, input: TermsAgreementInput):
23+
def validate(self, input: TermsAgreementInput) -> None:
2424
valid_customer_intents = ["Business", "BUSINESS", "Personal", "PERSONAL"]
2525
if (
2626
input.customer_intent
@@ -30,7 +30,7 @@ def validate(self, input: TermsAgreementInput):
3030
if not self.current_user.is_authenticated:
3131
raise Unauthenticated()
3232

33-
def update_terms_agreement(self, input: TermsAgreementInput):
33+
def update_terms_agreement(self, input: TermsAgreementInput) -> None:
3434
self.current_user.terms_agreement = input.terms_agreement
3535
self.current_user.terms_agreement_at = timezone.now()
3636
self.current_user.customer_intent = input.customer_intent
@@ -44,14 +44,14 @@ def update_terms_agreement(self, input: TermsAgreementInput):
4444
if input.marketing_consent:
4545
self.send_data_to_marketo()
4646

47-
def send_data_to_marketo(self):
47+
def send_data_to_marketo(self) -> None:
4848
event_data = {
4949
"email": self.current_user.email,
5050
}
5151
AnalyticsService().opt_in_email(self.current_user.id, event_data)
5252

5353
@sync_to_async
54-
def execute(self, input):
54+
def execute(self, input: Any) -> None:
5555
typed_input = TermsAgreementInput(
5656
business_email=input.get("business_email"),
5757
terms_agreement=input.get("terms_agreement"),

codecov_auth/signals.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import Any, Dict, Optional, Type
1+
from typing import Any, Dict, Optional, Type, cast
22

33
from django.db.models.signals import post_save
44
from django.dispatch import receiver
@@ -38,7 +38,7 @@ def update_owner(
3838
"""
3939
Shelter tracks a limited set of Owner fields - only update if those fields have changed.
4040
"""
41-
created: bool = kwargs["created"]
41+
created: bool = cast(bool, kwargs["created"])
4242
tracked_fields = [
4343
"upload_token_required_for_public_repos",
4444
"username",

codecov_auth/views/sentry.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ def _perform_login(self, request: HttpRequest) -> HttpResponse:
123123
# user has not connected any owners yet
124124
return redirect(f"{settings.CODECOV_DASHBOARD_URL}/sync")
125125

126-
def _login_user(self, request: HttpRequest, user_data: dict):
126+
def _login_user(self, request: HttpRequest, user_data: dict) -> User:
127127
sentry_id = user_data["user"]["id"]
128128
user_name = user_data["user"].get("name")
129129
user_email = user_data["user"].get("email")
@@ -177,7 +177,7 @@ def _login_user(self, request: HttpRequest, user_data: dict):
177177
login(request, current_user)
178178
return current_user
179179

180-
def get(self, request):
180+
def get(self, request: HttpRequest) -> HttpResponse:
181181
if request.GET.get("code"):
182182
return self._perform_login(request)
183183
else:

core/commands/commit/interactors/get_file_content.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
11
import logging
2+
from typing import Any, Coroutine
23

34
from codecov.commands.base import BaseInteractor
5+
from core.models import Commit
46
from services.repo_providers import RepoProviderService
57

68
log = logging.getLogger(__name__)
79

810

911
class GetFileContentInteractor(BaseInteractor):
10-
async def get_file_from_service(self, commit, path):
12+
async def get_file_from_service(self, commit: Commit, path: str) -> str | None:
1113
try:
1214
repository_service = await RepoProviderService().async_get_adapter(
1315
owner=self.current_owner, repo=commit.repository
@@ -27,5 +29,5 @@ async def get_file_from_service(self, commit, path):
2729
)
2830
return None
2931

30-
def execute(self, commit, path):
32+
def execute(self, commit: Commit, path: str) -> Coroutine[Any, Any, str | None]:
3133
return self.get_file_from_service(commit, path)

graphql_api/actions/repository.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,9 @@
99
log = logging.getLogger(__name__)
1010

1111

12-
def apply_filters_to_queryset(queryset, filters: dict[str, Any]) -> QuerySet:
12+
def apply_filters_to_queryset(
13+
queryset: QuerySet, filters: dict[str, Any] | None
14+
) -> QuerySet:
1315
filters = filters or {}
1416
term = filters.get("term")
1517
active = filters.get("active")

upload/serializers.py

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
1+
from typing import Any, Dict, List
2+
13
from django.conf import settings
4+
from django.db.models import QuerySet
25
from rest_framework import serializers
36
from shared.api_archive.archive import ArchiveService
47

@@ -11,7 +14,7 @@
1114
class FlagListField(serializers.ListField):
1215
child = serializers.CharField()
1316

14-
def to_representation(self, data):
17+
def to_representation(self, data: QuerySet) -> List[str | None]:
1518
return [item.flag_name if item is not None else None for item in data.all()]
1619

1720

@@ -47,12 +50,12 @@ class Meta:
4750

4851
raw_upload_location = serializers.SerializerMethodField()
4952

50-
def get_raw_upload_location(self, obj: ReportSession):
53+
def get_raw_upload_location(self, obj: ReportSession) -> str:
5154
repo = obj.report.commit.repository
5255
archive_service = ArchiveService(repo)
5356
return archive_service.create_presigned_put(obj.storage_path)
5457

55-
def get_url(self, obj: ReportSession):
58+
def get_url(self, obj: ReportSession) -> str:
5659
repository = obj.report.commit.repository
5760
commit = obj.report.commit
5861
return f"{settings.CODECOV_DASHBOARD_URL}/{repository.author.service}/{repository.author.username}/{repository.name}/commit/{commit.commitid}"
@@ -64,7 +67,7 @@ def _create_existing_flags_map(self, repoid: int) -> dict:
6467
existing_flags_map[flag_obj.flag_name] = flag_obj
6568
return existing_flags_map
6669

67-
def create(self, validated_data):
70+
def create(self, validated_data: Dict[str, Any]) -> ReportSession | None:
6871
flag_names = (
6972
validated_data.pop("flags") if "flags" in validated_data.keys() else []
7073
)
@@ -134,7 +137,7 @@ class Meta:
134137
"branch",
135138
)
136139

137-
def create(self, validated_data):
140+
def create(self, validated_data: Dict[str, Any]) -> Commit:
138141
repo = validated_data.pop("repository", None)
139142
commitid = validated_data.pop("commitid", None)
140143
commit, created = Commit.objects.get_or_create(
@@ -161,7 +164,7 @@ class Meta:
161164
)
162165
fields = read_only_fields + ("code",)
163166

164-
def create(self, validated_data) -> tuple[CommitReport, bool]:
167+
def create(self, validated_data: Dict[str, Any]) -> tuple[CommitReport, bool]:
165168
report = (
166169
CommitReport.objects.coverage_reports()
167170
.filter(

upload/tokenless/azure.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import logging
22
from datetime import datetime, timedelta
3+
from typing import Any, Dict
34

45
import requests
56
from requests.exceptions import ConnectionError, HTTPError
@@ -12,7 +13,7 @@
1213

1314

1415
class TokenlessAzureHandler(BaseTokenlessUploadHandler):
15-
def get_build(self):
16+
def get_build(self) -> Dict[str, Any]:
1617
try:
1718
response = requests.get(
1819
f"{self.server_uri}{self.project}/_apis/build/builds/{self.job}?api-version=5.0",
@@ -54,7 +55,7 @@ def get_build(self):
5455
)
5556
return build
5657

57-
def verify(self):
58+
def verify(self) -> None:
5859
if not self.upload_params.get("job"):
5960
raise NotFound(
6061
'Missing "job" argument. Please upload with the Codecov repository upload token to resolve issue.'

upload/views/uploads.py

Lines changed: 22 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
import logging
2+
from typing import Any, Callable, Dict
23

34
from django.http import HttpRequest, HttpResponseNotAllowed
45
from django.utils import timezone
56
from rest_framework.exceptions import ValidationError
67
from rest_framework.generics import ListCreateAPIView
78
from rest_framework.permissions import BasePermission
9+
from rest_framework.response import Response
10+
from rest_framework.views import APIView
811
from shared.api_archive.archive import ArchiveService, MinioEndpoints
912
from shared.metrics import inc_counter
1013
from shared.upload.utils import UploaderType, insert_coverage_measurement
@@ -40,8 +43,13 @@
4043

4144

4245
def create_upload(
43-
serializer, repository, commit, report, is_shelter_request, analytics_token
44-
):
46+
serializer: UploadSerializer,
47+
repository: Repository,
48+
commit: Commit,
49+
report: CommitReport,
50+
is_shelter_request: bool,
51+
analytics_token: str,
52+
) -> ReportSession:
4553
version = (
4654
serializer.validated_data["version"]
4755
if "version" in serializer.validated_data
@@ -82,7 +90,9 @@ def create_upload(
8290
return instance
8391

8492

85-
def trigger_upload_task(repository, commit_sha, upload, report):
93+
def trigger_upload_task(
94+
repository: Repository, commit_sha: str, upload: ReportSession, report: CommitReport
95+
) -> None:
8696
log.info(
8797
"Triggering upload task",
8898
extra=dict(
@@ -103,7 +113,7 @@ def trigger_upload_task(repository, commit_sha, upload, report):
103113
dispatch_upload_task(task_arguments, repository, redis)
104114

105115

106-
def activate_repo(repository):
116+
def activate_repo(repository: Repository) -> None:
107117
# Only update the fields if needed
108118
if (
109119
repository.activated
@@ -128,8 +138,8 @@ def activate_repo(repository):
128138

129139

130140
def send_analytics_data(
131-
commit: Commit, upload: ReportSession, version, analytics_token
132-
):
141+
commit: Commit, upload: ReportSession, version: str, analytics_token: str
142+
) -> None:
133143
analytics_upload_data = {
134144
"commit": commit.commitid,
135145
"branch": commit.branch,
@@ -154,7 +164,7 @@ def send_analytics_data(
154164
)
155165

156166

157-
def get_token_for_analytics(commit: Commit, request):
167+
def get_token_for_analytics(commit: Commit, request: HttpRequest) -> str:
158168
repo = commit.repository
159169
if isinstance(request.auth, TokenlessAuth):
160170
analytics_token = "tokenless_upload"
@@ -170,7 +180,7 @@ def get_token_for_analytics(commit: Commit, request):
170180

171181

172182
class CanDoCoverageUploadsPermission(BasePermission):
173-
def has_permission(self, request, view):
183+
def has_permission(self, request: HttpRequest, view: APIView) -> bool:
174184
repository = view.get_repo()
175185
return (
176186
request.auth is not None
@@ -194,10 +204,10 @@ class UploadViews(ListCreateAPIView, GetterMixin):
194204
]
195205
throttle_classes = [UploadsPerCommitThrottle, UploadsPerWindowThrottle]
196206

197-
def get_exception_handler(self):
207+
def get_exception_handler(self) -> Callable[[Exception, Dict[str, Any]], Response]:
198208
return repo_auth_custom_exception_handler
199209

200-
def perform_create(self, serializer: UploadSerializer):
210+
def perform_create(self, serializer: UploadSerializer) -> ReportSession:
201211
inc_counter(
202212
API_UPLOAD_COUNTER,
203213
labels=generate_upload_prometheus_metrics_labels(
@@ -253,7 +263,7 @@ def list(
253263
repo: str,
254264
commit_sha: str,
255265
report_code: str,
256-
):
266+
) -> HttpResponseNotAllowed:
257267
return HttpResponseNotAllowed(permitted_methods=["POST"])
258268

259269
def get_repo(self) -> Repository:
@@ -270,7 +280,7 @@ def get_commit(self, repo: Repository) -> Commit:
270280
except ValidationError as excpetion:
271281
raise excpetion
272282

273-
def get_report(self, commit: Commit) -> CommitReport:
283+
def get_report(self, commit: Commit, _: Any = None) -> CommitReport:
274284
try:
275285
report = super().get_report(commit)
276286
return report

validate/views.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
import logging
22
from json import dumps
3+
from typing import Any
34

45
from django.conf import settings
5-
from django.http import HttpResponse
6+
from django.http import HttpRequest, HttpResponse
67
from rest_framework import status
78
from rest_framework.permissions import AllowAny
89
from rest_framework.response import Response
@@ -23,14 +24,14 @@
2324
class V1ValidateYamlHandler(APIView):
2425
permission_classes = [AllowAny]
2526

26-
def get(self, request, *args, **kwargs):
27+
def get(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse:
2728
return HttpResponse(
2829
f"Usage:\n\ncurl -X POST --data-binary @codecov.yml {settings.CODECOV_URL}/validate\n",
2930
status=status.HTTP_200_OK,
3031
content_type="text/plain",
3132
)
3233

33-
def post(self, request, *args, **kwargs):
34+
def post(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse:
3435
if not self.request.body:
3536
return HttpResponse(
3637
"No content posted.",
@@ -82,7 +83,7 @@ def post(self, request, *args, **kwargs):
8283
class V2ValidateYamlHandler(V1ValidateYamlHandler):
8384
permission_classes = [AllowAny]
8485

85-
def post(self, request, *args, **kwargs):
86+
def post(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse:
8687
source = self.request.query_params.get("source", "unknown")
8788
inc_counter(
8889
API_VALIDATE_V2_COUNTER,

0 commit comments

Comments
 (0)