Skip to content

Commit 54ae24f

Browse files
authored
Ruff: Add and autofix PERF401 (#12370)
1 parent 28083c8 commit 54ae24f

File tree

37 files changed

+129
-285
lines changed

37 files changed

+129
-285
lines changed

dojo/api_v2/serializers.py

Lines changed: 27 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -1125,20 +1125,16 @@ class EngagementToFilesSerializer(serializers.Serializer):
11251125
def to_representation(self, data):
11261126
engagement = data.get("engagement_id")
11271127
files = data.get("files")
1128-
new_files = []
1129-
for file in files:
1130-
new_files.append(
1131-
{
1132-
"id": file.id,
1133-
"file": "{site_url}/{file_access_url}".format(
1134-
site_url=settings.SITE_URL,
1135-
file_access_url=file.get_accessible_url(
1136-
engagement, engagement.id,
1137-
),
1128+
new_files = [{
1129+
"id": file.id,
1130+
"file": "{site_url}/{file_access_url}".format(
1131+
site_url=settings.SITE_URL,
1132+
file_access_url=file.get_accessible_url(
1133+
engagement, engagement.id,
11381134
),
1139-
"title": file.title,
1140-
},
1141-
)
1135+
),
1136+
"title": file.title,
1137+
} for file in files]
11421138
return {"engagement_id": engagement.id, "files": new_files}
11431139

11441140

@@ -1497,15 +1493,11 @@ class TestToFilesSerializer(serializers.Serializer):
14971493
def to_representation(self, data):
14981494
test = data.get("test_id")
14991495
files = data.get("files")
1500-
new_files = []
1501-
for file in files:
1502-
new_files.append(
1503-
{
1504-
"id": file.id,
1505-
"file": f"{settings.SITE_URL}/{file.get_accessible_url(test, test.id)}",
1506-
"title": file.title,
1507-
},
1508-
)
1496+
new_files = [{
1497+
"id": file.id,
1498+
"file": f"{settings.SITE_URL}/{file.get_accessible_url(test, test.id)}",
1499+
"title": file.title,
1500+
} for file in files]
15091501
return {"test_id": test.id, "files": new_files}
15101502

15111503

@@ -1787,10 +1779,7 @@ def update(self, instance, validated_data):
17871779
vulnerability_id_set = validated_data.pop("vulnerability_id_set")
17881780
vulnerability_ids = []
17891781
if vulnerability_id_set:
1790-
for vulnerability_id in vulnerability_id_set:
1791-
vulnerability_ids.append(
1792-
vulnerability_id["vulnerability_id"],
1793-
)
1782+
vulnerability_ids.extend(vulnerability_id["vulnerability_id"] for vulnerability_id in vulnerability_id_set)
17941783
save_vulnerability_ids(instance, vulnerability_ids)
17951784

17961785
instance = super(TaggitSerializer, self).update(
@@ -1921,8 +1910,7 @@ def create(self, validated_data):
19211910
# Process the vulnerability IDs specially
19221911
parsed_vulnerability_ids = []
19231912
if (vulnerability_ids := validated_data.pop("vulnerability_id_set", None)):
1924-
for vulnerability_id in vulnerability_ids:
1925-
parsed_vulnerability_ids.append(vulnerability_id["vulnerability_id"])
1913+
parsed_vulnerability_ids.extend(vulnerability_id["vulnerability_id"] for vulnerability_id in vulnerability_ids)
19261914
validated_data["cve"] = parsed_vulnerability_ids[0]
19271915
# Create a findings in memory so that we have access to unsaved_vulnerability_ids
19281916
new_finding = Finding(**validated_data)
@@ -2020,9 +2008,7 @@ def create(self, validated_data):
20202008
)
20212009

20222010
if vulnerability_id_set:
2023-
vulnerability_ids = []
2024-
for vulnerability_id in vulnerability_id_set:
2025-
vulnerability_ids.append(vulnerability_id["vulnerability_id"])
2011+
vulnerability_ids = [vulnerability_id["vulnerability_id"] for vulnerability_id in vulnerability_id_set]
20262012
validated_data["cve"] = vulnerability_ids[0]
20272013
save_vulnerability_ids_template(
20282014
new_finding_template, vulnerability_ids,
@@ -2040,10 +2026,7 @@ def update(self, instance, validated_data):
20402026
)
20412027
vulnerability_ids = []
20422028
if vulnerability_id_set:
2043-
for vulnerability_id in vulnerability_id_set:
2044-
vulnerability_ids.append(
2045-
vulnerability_id["vulnerability_id"],
2046-
)
2029+
vulnerability_ids.extend(vulnerability_id["vulnerability_id"] for vulnerability_id in vulnerability_id_set)
20472030
save_vulnerability_ids_template(instance, vulnerability_ids)
20482031

20492032
return super(TaggitSerializer, self).update(instance, validated_data)
@@ -2710,20 +2693,16 @@ class FindingToFilesSerializer(serializers.Serializer):
27102693
def to_representation(self, data):
27112694
finding = data.get("finding_id")
27122695
files = data.get("files")
2713-
new_files = []
2714-
for file in files:
2715-
new_files.append(
2716-
{
2717-
"id": file.id,
2718-
"file": "{site_url}/{file_access_url}".format(
2719-
site_url=settings.SITE_URL,
2720-
file_access_url=file.get_accessible_url(
2721-
finding, finding.id,
2722-
),
2696+
new_files = [{
2697+
"id": file.id,
2698+
"file": "{site_url}/{file_access_url}".format(
2699+
site_url=settings.SITE_URL,
2700+
file_access_url=file.get_accessible_url(
2701+
finding, finding.id,
27232702
),
2724-
"title": file.title,
2725-
},
2726-
)
2703+
),
2704+
"title": file.title,
2705+
} for file in files]
27272706
return {"finding_id": finding.id, "files": new_files}
27282707

27292708

dojo/checks.py

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,11 @@
55
def check_configuration_deduplication(app_configs, **kwargs):
66
errors = []
77
for scanner in settings.HASHCODE_FIELDS_PER_SCANNER:
8-
for field in settings.HASHCODE_FIELDS_PER_SCANNER.get(scanner):
9-
if field not in settings.HASHCODE_ALLOWED_FIELDS:
10-
errors.append(
11-
Error(
12-
f"Configuration error in HASHCODE_FIELDS_PER_SCANNER: Element {field} is not in the allowed list HASHCODE_ALLOWED_FIELDS for {scanner}.",
13-
hint=f'Check configuration ["HASHCODE_FIELDS_PER_SCANNER"]["{scanner}"] value',
14-
obj=settings.HASHCODE_FIELDS_PER_SCANNER[scanner],
15-
id="dojo.E001",
16-
),
17-
)
8+
errors.extend(Error(
9+
f"Configuration error in HASHCODE_FIELDS_PER_SCANNER: Element {field} is not in the allowed list HASHCODE_ALLOWED_FIELDS for {scanner}.",
10+
hint=f'Check configuration ["HASHCODE_FIELDS_PER_SCANNER"]["{scanner}"] value',
11+
obj=settings.HASHCODE_FIELDS_PER_SCANNER[scanner],
12+
id="dojo.E001",
13+
) for field in settings.HASHCODE_FIELDS_PER_SCANNER.get(scanner)
14+
if field not in settings.HASHCODE_ALLOWED_FIELDS)
1815
return errors

dojo/endpoint/utils.py

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -269,10 +269,7 @@ def validate_endpoints_to_add(endpoints_to_add):
269269
endpoint_ins.fragment,
270270
])
271271
except ValidationError as ves:
272-
for ve in ves:
273-
errors.append(
274-
ValidationError(f"Invalid endpoint {endpoint}: {ve}"),
275-
)
272+
errors.extend(ValidationError(f"Invalid endpoint {endpoint}: {ve}") for ve in ves)
276273
return endpoint_list, errors
277274

278275

@@ -316,7 +313,6 @@ def endpoint_meta_import(file, product, create_endpoints, create_tags, create_me
316313
keys = [key for key in reader.fieldnames if key != "hostname"]
317314

318315
for row in reader:
319-
meta = []
320316
endpoint = None
321317
host = row.get("hostname", None)
322318

@@ -326,8 +322,7 @@ def endpoint_meta_import(file, product, create_endpoints, create_tags, create_me
326322
endpoints = Endpoint.objects.filter(host=host, product=product)
327323
if not endpoints.count() and create_endpoints:
328324
endpoints = [Endpoint.objects.create(host=host, product=product)]
329-
for key in keys:
330-
meta.append((key, row.get(key)))
325+
meta = [(key, row.get(key)) for key in keys]
331326

332327
for endpoint in endpoints:
333328
existing_tags = [tag.name for tag in endpoint.tags.all()]

dojo/engagement/views.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1597,10 +1597,8 @@ def csv_export(request):
15971597
first_row = True
15981598
for engagement in engagements:
15991599
if first_row:
1600-
fields = []
1601-
for key in dir(engagement):
1602-
if key not in get_excludes() and not callable(getattr(engagement, key)) and not key.startswith("_"):
1603-
fields.append(key)
1600+
fields = [key for key in dir(engagement)
1601+
if key not in get_excludes() and not callable(getattr(engagement, key)) and not key.startswith("_")]
16041602
fields.append("tests")
16051603

16061604
writer.writerow(fields)

dojo/finding/helper.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -629,9 +629,7 @@ def removeLoop(finding_id, counter):
629629

630630
def add_endpoints(new_finding, form):
631631
added_endpoints = save_endpoints_to_add(form.endpoints_to_add_list, new_finding.test.engagement.product)
632-
endpoint_ids = []
633-
for endpoint in added_endpoints:
634-
endpoint_ids.append(endpoint.id)
632+
endpoint_ids = [endpoint.id for endpoint in added_endpoints]
635633

636634
new_finding.endpoints.set(form.cleaned_data["endpoints"] | Endpoint.objects.filter(id__in=endpoint_ids))
637635

dojo/jira_link/helper.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -605,8 +605,7 @@ def get_tags(obj):
605605
if isinstance(obj, Finding | Engagement):
606606
obj_tags = obj.tags.all()
607607
if obj_tags:
608-
for tag in obj_tags:
609-
tags.append(str(tag.name.replace(" ", "-")))
608+
tags.extend(str(tag.name.replace(" ", "-")) for tag in obj_tags)
610609
if isinstance(obj, Finding_Group):
611610
for finding in obj.findings.all():
612611
obj_tags = finding.tags.all()

dojo/metrics/views.py

Lines changed: 7 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -287,10 +287,8 @@ def product_type_counts(request):
287287
oip = opened_in_period(start_date, end_date, test__engagement__product__prod_type=pt)
288288

289289
# trending data - 12 months
290-
for x in range(12, 0, -1):
291-
opened_in_period_list.append(
292-
opened_in_period(start_date + relativedelta(months=-x), end_of_month + relativedelta(months=-x),
293-
test__engagement__product__prod_type=pt))
290+
opened_in_period_list.extend(opened_in_period(start_date + relativedelta(months=-x), end_of_month + relativedelta(months=-x),
291+
test__engagement__product__prod_type=pt) for x in range(12, 0, -1))
294292

295293
opened_in_period_list.append(oip)
296294

@@ -486,10 +484,8 @@ def product_tag_counts(request):
486484
test__engagement__product__in=prods)
487485

488486
# trending data - 12 months
489-
for x in range(12, 0, -1):
490-
opened_in_period_list.append(
491-
opened_in_period(start_date + relativedelta(months=-x), end_of_month + relativedelta(months=-x),
492-
test__engagement__product__tags__name=pt, test__engagement__product__in=prods))
487+
opened_in_period_list.extend(opened_in_period(start_date + relativedelta(months=-x), end_of_month + relativedelta(months=-x),
488+
test__engagement__product__tags__name=pt, test__engagement__product__in=prods) for x in range(12, 0, -1))
493489

494490
opened_in_period_list.append(oip)
495491

@@ -704,10 +700,8 @@ def view_engineer(request, eid):
704700
tzinfo=timezone.get_current_timezone())],
705701
owner=user)
706702
for finding in ra.accepted_findings.all()]
707-
closed_month = []
708-
for f in closed_findings:
709-
if f.mitigated and f.mitigated.year == now.year and f.mitigated.month == now.month:
710-
closed_month.append(f)
703+
closed_month = [f for f in closed_findings
704+
if f.mitigated and f.mitigated.year == now.year and f.mitigated.month == now.month]
711705

712706
o_dict, open_count = count_findings(open_month)
713707
c_dict, closed_count = count_findings(closed_month)
@@ -721,7 +715,6 @@ def view_engineer(request, eid):
721715
day_list.append(now)
722716

723717
q_objects = (Q(date=d) for d in day_list)
724-
closed_week = []
725718
open_week = findings.filter(reduce(operator.or_, q_objects))
726719

727720
accepted_week = [finding for ra in Risk_Acceptance.objects.filter(
@@ -730,9 +723,7 @@ def view_engineer(request, eid):
730723

731724
q_objects = (Q(mitigated=d) for d in day_list)
732725
# closed_week= findings.filter(reduce(operator.or_, q_objects))
733-
for f in closed_findings:
734-
if f.mitigated and f.mitigated >= day_list[0]:
735-
closed_week.append(f)
726+
closed_week = [f for f in closed_findings if f.mitigated and f.mitigated >= day_list[0]]
736727

737728
o_week_dict, open_week_count = count_findings(open_week)
738729
c_week_dict, closed_week_count = count_findings(closed_week)

dojo/models.py

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1306,10 +1306,7 @@ def get_product_type(self):
13061306
def open_findings_list(self):
13071307
findings = Finding.objects.filter(test__engagement__product=self,
13081308
active=True)
1309-
findings_list = []
1310-
for i in findings:
1311-
findings_list.append(i.id)
1312-
return findings_list
1309+
return [i.id for i in findings]
13131310

13141311
@property
13151312
def has_jira_configured(self):
@@ -3347,9 +3344,7 @@ def get_references_with_links(self):
33473344
def vulnerability_ids(self):
33483345
# Get vulnerability ids from database and convert to list of strings
33493346
vulnerability_ids_model = self.vulnerability_id_set.all()
3350-
vulnerability_ids = []
3351-
for vulnerability_id in vulnerability_ids_model:
3352-
vulnerability_ids.append(vulnerability_id.vulnerability_id)
3347+
vulnerability_ids = [vulnerability_id.vulnerability_id for vulnerability_id in vulnerability_ids_model]
33533348

33543349
# Synchronize the cve field with the unsaved_vulnerability_ids
33553350
# We do this to be as flexible as possible to handle the fields until
@@ -3556,9 +3551,7 @@ def get_breadcrumbs(self):
35563551
def vulnerability_ids(self):
35573552
# Get vulnerability ids from database and convert to list of strings
35583553
vulnerability_ids_model = self.vulnerability_id_template_set.all()
3559-
vulnerability_ids = []
3560-
for vulnerability_id in vulnerability_ids_model:
3561-
vulnerability_ids.append(vulnerability_id.vulnerability_id)
3554+
vulnerability_ids = [vulnerability_id.vulnerability_id for vulnerability_id in vulnerability_ids_model]
35623555

35633556
# Synchronize the cve field with the unsaved_vulnerability_ids
35643557
# We do this to be as flexible as possible to handle the fields until

dojo/search/views.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -439,11 +439,9 @@ def vulnerability_id_fix(keyword):
439439
# - https://github.com/DefectDojo/django-DefectDojo/issues/1092
440440
# - https://github.com/DefectDojo/django-DefectDojo/issues/2081
441441

442-
vulnerability_ids = []
443442
keyword_parts = keyword.split(",")
444-
for keyword_part in keyword_parts:
445-
if bool(vulnerability_id_pattern.match(keyword_part)):
446-
vulnerability_ids.append("'" + keyword_part + "'")
443+
vulnerability_ids = [f"'{keyword_part}'" for keyword_part in keyword_parts
444+
if bool(vulnerability_id_pattern.match(keyword_part))]
447445

448446
if vulnerability_ids:
449447
return " ".join(vulnerability_ids)

dojo/tools/anchore_grype/parser.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -207,9 +207,8 @@ def get_vulnerability_ids(self, vuln_id, related_vulnerabilities):
207207
if vuln_id:
208208
vulnerability_ids.append(vuln_id)
209209
if related_vulnerabilities:
210-
for related_vulnerability in related_vulnerabilities:
211-
if related_vulnerability.get("id"):
212-
vulnerability_ids.append(related_vulnerability.get("id"))
210+
vulnerability_ids.extend(related_vulnerability_id for related_vulnerability in related_vulnerabilities
211+
if (related_vulnerability_id := related_vulnerability.get("id")))
213212
if vulnerability_ids:
214213
return vulnerability_ids
215214
return None

0 commit comments

Comments
 (0)