Skip to content

Commit

Permalink
Ruff: Add and fix PLR6201
Browse files Browse the repository at this point in the history
  • Loading branch information
kiblik committed Feb 2, 2025
1 parent e0de953 commit b85acd8
Show file tree
Hide file tree
Showing 46 changed files with 87 additions and 87 deletions.
8 changes: 4 additions & 4 deletions dojo/api_v2/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -625,7 +625,7 @@ def validate(self, data):
msg = "Only superusers are allowed to add or edit superusers."
raise ValidationError(msg)

if self.context["request"].method in ["PATCH", "PUT"] and "password" in data:
if self.context["request"].method in {"PATCH", "PUT"} and "password" in data:
msg = "Update of password though API is not allowed"
raise ValidationError(msg)
if self.context["request"].method == "POST" and "password" not in data and settings.REQUIRE_PASSWORD_ON_USER:
Expand Down Expand Up @@ -1298,7 +1298,7 @@ def validate(self, data):
product=endpoint_ins.product,
)
if (
self.context["request"].method in ["PUT", "PATCH"]
self.context["request"].method in {"PUT", "PATCH"}
and (
(endpoint.count() > 1)
or (
Expand Down Expand Up @@ -1602,7 +1602,7 @@ def validate_findings_have_same_engagement(finding_objects: list[Finding]):
raise PermissionDenied(msg)
if self.context["request"].method == "POST":
validate_findings_have_same_engagement(finding_objects)
elif self.context["request"].method in ["PATCH", "PUT"]:
elif self.context["request"].method in {"PATCH", "PUT"}:
existing_findings = Finding.objects.filter(risk_acceptance=self.instance.id)
existing_and_new_findings = existing_findings | finding_objects
validate_findings_have_same_engagement(existing_and_new_findings)
Expand Down Expand Up @@ -2662,7 +2662,7 @@ def save(self):
Languages.objects.filter(product=product).delete()

for name in deserialized:
if name not in ["header", "SUM"]:
if name not in {"header", "SUM"}:
element = deserialized[name]

try:
Expand Down
2 changes: 1 addition & 1 deletion dojo/api_v2/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -1491,7 +1491,7 @@ def metadata(self, request, pk=None):
return self._get_metadata(request, finding)
if request.method == "POST":
return self._add_metadata(request, finding)
if request.method in ["PUT", "PATCH"]:
if request.method in {"PUT", "PATCH"}:
return self._edit_metadata(request, finding)
if request.method == "DELETE":
return self._remove_metadata(request, finding)
Expand Down
8 changes: 4 additions & 4 deletions dojo/benchmark/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,19 +47,19 @@ def update_benchmark(request, pid, _type):
value = request.POST.get("value")
value = {"true": True, "false": False}.get(value, value)

if field in [
if field in {
"enabled",
"pass_fail",
"notes",
"get_notes",
"delete_notes",
]:
}:
bench = Benchmark_Product.objects.get(id=bench_id)
if field == "enabled":
bench.enabled = value
elif field == "pass_fail":
bench.pass_fail = value
elif field in ["notes", "get_notes", "delete_notes"]:
elif field in {"notes", "get_notes", "delete_notes"}:
if field == "notes":
bench.notes.create(entry=value, author=get_current_user())
if field == "delete_notes":
Expand Down Expand Up @@ -94,7 +94,7 @@ def update_benchmark_summary(request, pid, _type, summary):
value = request.POST.get("value")
value = {"true": True, "false": False}.get(value, value)

if field in ["publish", "desired_level"]:
if field in {"publish", "desired_level"}:
summary = Benchmark_Product_Summary.objects.get(id=summary)
data = {}
if field == "publish":
Expand Down
2 changes: 1 addition & 1 deletion dojo/engagement/signals.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def engagement_post_save(sender, instance, created, **kwargs):
def engagement_pre_save(sender, instance, **kwargs):
old = sender.objects.filter(pk=instance.pk).first()
if old and instance.status != old.status:
if instance.status in ["Cancelled", "Completed"]:
if instance.status in {"Cancelled", "Completed"}:
create_notification(event="engagement_closed",
title=_("Closure of %s") % instance.name,
description=_('The engagement "%s" was closed') % (instance.name),
Expand Down
4 changes: 2 additions & 2 deletions dojo/engagement/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ def engagement_calendar(request):

def get_filtered_engagements(request, view):

if view not in ["all", "active"]:
if view not in {"all", "active"}:
msg = f"View {view} is not allowed"
raise ValidationError(msg)

Expand Down Expand Up @@ -1562,7 +1562,7 @@ def get_engagements(request):
raise ValidationError(msg)

view = query = None
if get_list_index(path_items, 1) in ["active", "all"]:
if get_list_index(path_items, 1) in {"active", "all"}:
view = get_list_index(path_items, 1)
query = get_list_index(path_items, 2)
else:
Expand Down
2 changes: 1 addition & 1 deletion dojo/jira_link/helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -412,7 +412,7 @@ def get_jira_connection_raw(jira_server, jira_username, jira_password):

error_message = e.text if hasattr(e, "text") else e.message if hasattr(e, "message") else e.args[0]

if e.status_code in [401, 403]:
if e.status_code in {401, 403}:
log_jira_generic_alert("JIRA Authentication Error", error_message)
else:
log_jira_generic_alert("Unknown JIRA Connection Error", error_message)
Expand Down
2 changes: 1 addition & 1 deletion dojo/jira_link/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ def webhook(request, secret=None):
try:
parsed = json.loads(request.body.decode("utf-8"))
# Check if the events supplied are supported
if parsed.get("webhookEvent") not in ["comment_created", "jira:issue_updated"]:
if parsed.get("webhookEvent") not in {"comment_created", "jira:issue_updated"}:
return webhook_responser_handler("info", f"Unrecognized JIRA webhook event received: {parsed.get('webhookEvent')}")

if parsed.get("webhookEvent") == "jira:issue_updated":
Expand Down
4 changes: 2 additions & 2 deletions dojo/management/commands/jira_status_reconciliation.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def jira_status_reconciliation(*args, **kwargs):

logger.debug("mode: %s product:%s engagement: %s dryrun: %s", mode, product, engagement, dryrun)

if mode and mode not in ("push_status_to_jira", "import_status_from_jira", "reconcile"):
if mode and mode not in {"push_status_to_jira", "import_status_from_jira", "reconcile"}:
logger.info("mode must be one of reconcile, push_status_to_jira or import_status_from_jira")
return False

Expand Down Expand Up @@ -107,7 +107,7 @@ def jira_status_reconciliation(*args, **kwargs):

else:
# statuses are different
if mode in ("push_status_to_jira", "import_status_from_jira"):
if mode in {"push_status_to_jira", "import_status_from_jira"}:
action = mode
else:
# reconcile
Expand Down
12 changes: 6 additions & 6 deletions dojo/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ def _manage_inherited_tags(obj, incoming_inherited_tags, potentially_existing_ta
def _copy_model_util(model_in_database, exclude_fields: list[str] = []):
new_model_instance = model_in_database.__class__()
for field in model_in_database._meta.fields:
if field.name not in ["id", *exclude_fields]:
if field.name not in {"id", *exclude_fields}:
setattr(new_model_instance, field.name, getattr(model_in_database, field.name))
return new_model_instance

Expand Down Expand Up @@ -2009,10 +2009,10 @@ def from_uri(uri):
query_string = "&".join(query_parts)

protocol = url.scheme if url.scheme != "" else None
userinfo = ":".join(url.userinfo) if url.userinfo not in [(), ("",)] else None
userinfo = ":".join(url.userinfo) if url.userinfo not in {(), ("",)} else None
host = url.host if url.host != "" else None
port = url.port
path = "/".join(url.path)[:500] if url.path not in [None, (), ("",)] else None
path = "/".join(url.path)[:500] if url.path not in {None, (), ("",)} else None
query = query_string[:1000] if query_string is not None and query_string != "" else None
fragment = url.fragment[:500] if url.fragment is not None and url.fragment != "" else None

Expand Down Expand Up @@ -3246,7 +3246,7 @@ def scm_public_prepare_base_link(self, uri):
def git_public_prepare_scm_link(self, uri, scm_type):
# if commit hash or branch/tag is set for engagement/test -
# hash or branch/tag should be appended to base browser link
intermediate_path = "/blob/" if scm_type in ["github", "gitlab"] else "/src/"
intermediate_path = "/blob/" if scm_type in {"github", "gitlab"} else "/src/"

link = self.scm_public_prepare_base_link(uri)
if self.test.commit_hash:
Expand Down Expand Up @@ -3308,7 +3308,7 @@ def get_file_path_with_raw_link(self):
if (self.test.engagement.source_code_management_uri is not None):
if scm_type == "bitbucket-standalone":
link = self.bitbucket_standalone_prepare_scm_link(link)
elif scm_type in ["github", "gitlab", "gitea", "codeberg", "bitbucket"]:
elif scm_type in {"github", "gitlab", "gitea", "codeberg", "bitbucket"}:
link = self.git_public_prepare_scm_link(link, scm_type)
elif "https://github.com/" in self.test.engagement.source_code_management_uri:
link = self.git_public_prepare_scm_link(link, "github")
Expand All @@ -3319,7 +3319,7 @@ def get_file_path_with_raw_link(self):

# than - add line part to browser url
if self.line:
if scm_type in ["github", "gitlab", "gitea", "codeberg"] or "https://github.com/" in self.test.engagement.source_code_management_uri:
if scm_type in {"github", "gitlab", "gitea", "codeberg"} or "https://github.com/" in self.test.engagement.source_code_management_uri:
link = link + "#L" + str(self.line)
elif scm_type == "bitbucket-standalone":
link = link + "#" + str(self.line)
Expand Down
4 changes: 2 additions & 2 deletions dojo/notifications/helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -424,10 +424,10 @@ def send_webhooks_notification(
):
for endpoint in self._get_webhook_endpoints(user=user):
error = None
if endpoint.status not in [
if endpoint.status not in {
Notification_Webhooks.Status.STATUS_ACTIVE,
Notification_Webhooks.Status.STATUS_ACTIVE_TMP,
]:
}:
logger.info(
f"URL for Webhook '{endpoint.name}' is not active: {endpoint.get_status_display()} ({endpoint.status})",
)
Expand Down
2 changes: 1 addition & 1 deletion dojo/product/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -351,7 +351,7 @@ def identify_view(request):
if view:
# value of view is reflected in the template, make sure it's valid
# although any XSS should be catch by django autoescape, we see people sometimes using '|safe'...
if view in ["Endpoint", "Finding"]:
if view in {"Endpoint", "Finding"}:
return view
msg = 'invalid view, view must be "Endpoint" or "Finding"'
raise ValueError(msg)
Expand Down
2 changes: 1 addition & 1 deletion dojo/reports/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -542,7 +542,7 @@ def generate_report(request, obj, host_view=False):
"title": report_title,
"host": report_url_resolver(request),
"user_id": request.user.id}
elif type(obj).__name__ in ["QuerySet", "CastTaggedQuerySet", "TagulousCastTaggedQuerySet"]:
elif type(obj).__name__ in {"QuerySet", "CastTaggedQuerySet", "TagulousCastTaggedQuerySet"}:
findings = report_finding_filter_class(request.GET, queryset=prefetch_related_findings_for_report(obj).distinct())
report_name = "Finding"
template = "dojo/finding_pdf_report.html"
Expand Down
4 changes: 2 additions & 2 deletions dojo/tags_signals.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

@receiver(signals.m2m_changed, sender=Product.tags.through)
def product_tags_post_add_remove(sender, instance, action, **kwargs):
if action in ["post_add", "post_remove"]:
if action in {"post_add", "post_remove"}:
running_async_process = False
with contextlib.suppress(AttributeError):
running_async_process = instance.running_async_process
Expand All @@ -28,7 +28,7 @@ def product_tags_post_add_remove(sender, instance, action, **kwargs):
@receiver(signals.m2m_changed, sender=Test.tags.through)
@receiver(signals.m2m_changed, sender=Finding.tags.through)
def make_inherited_tags_sticky(sender, instance, action, **kwargs):
if action in ["post_add", "post_remove"]:
if action in {"post_add", "post_remove"}:
if inherit_product_tags(instance):
tag_list = [tag.name for tag in instance.tags.all()]
if propagate_inheritance(instance, tag_list=tag_list):
Expand Down
4 changes: 2 additions & 2 deletions dojo/templatetags/display_tags.py
Original file line number Diff line number Diff line change
Expand Up @@ -778,11 +778,11 @@ def vulnerability_url(vulnerability_id):
if vulnerability_id.upper().startswith(key):
if key == "GLSA":
return settings.VULNERABILITY_URLS[key] + str(vulnerability_id.replace("GLSA-", "glsa/"))
if key in ["AVD", "KHV", "C-"]:
if key in {"AVD", "KHV", "C-"}:
return settings.VULNERABILITY_URLS[key] + str(vulnerability_id.lower())
if "&&" in settings.VULNERABILITY_URLS[key]:
# Process specific keys specially if need
if key in ["CAPEC", "CWE"]:
if key in {"CAPEC", "CWE"}:
vuln_id = str(vulnerability_id).replace(f"{key}-", "")
else:
vuln_id = str(vulnerability_id)
Expand Down
2 changes: 1 addition & 1 deletion dojo/tools/acunetix/parse_acunetix360_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ def get_findings(self, filename, test):
else:
cwe = None
sev = item["Severity"]
if sev not in ["Info", "Low", "Medium", "High", "Critical"]:
if sev not in {"Info", "Low", "Medium", "High", "Critical"}:
sev = "Info"
if item["RemedialProcedure"] is not None:
mitigation = text_maker.handle(item.get("RemedialProcedure", ""))
Expand Down
8 changes: 4 additions & 4 deletions dojo/tools/api_sonarqube/importer.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,22 +33,22 @@ def get_findings(self, filename, test):

@staticmethod
def is_confirmed(state):
return state.lower() in [
return state.lower() in {
"confirmed",
"accepted",
"detected",
]
}

@staticmethod
def is_closed(state):
return state.lower() in [
return state.lower() in {
"resolved",
"falsepositive",
"wontfix",
"closed",
"dismissed",
"rejected",
]
}

@staticmethod
def is_reviewed(state):
Expand Down
2 changes: 1 addition & 1 deletion dojo/tools/api_sonarqube/updater_from_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ def get_sonarqube_status_for(finding):

@staticmethod
def update_finding_status(finding, sonarqube_status):
if sonarqube_status in ["OPEN", "REOPENED"]:
if sonarqube_status in {"OPEN", "REOPENED"}:
finding.active = True
finding.verified = False
finding.false_p = False
Expand Down
2 changes: 1 addition & 1 deletion dojo/tools/awssecurityhub/guardduty.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def get_item(self, finding: dict, test):
hosts = []
for resource in finding.get("Resources", []):
component_name = resource.get("Type")
if component_name in ("AwsEcrContainerImage", "AwsEc2Instance"):
if component_name in {"AwsEcrContainerImage", "AwsEc2Instance"}:
hosts.append(Endpoint(host=f"{component_name} {resource.get('Id')}"))
if component_name == "AwsEcrContainerImage":
details = resource.get("Details", {}).get("AwsEcrContainerImage")
Expand Down
6 changes: 3 additions & 3 deletions dojo/tools/burp_api/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,10 +84,10 @@ def get_findings(self, file, test):
]
finding.unsaved_req_resp = []
for evidence in issue.get("evidence", []):
if evidence.get("type") not in [
if evidence.get("type") not in {
"InformationListEvidence",
"FirstOrderEvidence",
]:
}:
continue
request = self.get_clean_base64(
evidence.get("request_response").get("request"),
Expand Down Expand Up @@ -140,7 +140,7 @@ def convert_severity(issue):
},
"""
value = issue.get("severity", "info").lower()
if value in ["high", "medium", "low", "info"]:
if value in {"high", "medium", "low", "info"}:
return value.title()
return "Info"

Expand Down
2 changes: 1 addition & 1 deletion dojo/tools/checkmarx_one/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@ def parse_results(
finding = self.get_results_sast(test, vulnerability)
elif result_type == "kics":
finding = self.get_results_kics(test, vulnerability)
elif result_type in ["sca", "sca-container"]:
elif result_type in {"sca", "sca-container"}:
finding = self.get_results_sca(test, vulnerability)
# Make sure we have a finding before continuing
if finding is not None:
Expand Down
4 changes: 2 additions & 2 deletions dojo/tools/codechecker/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,10 +76,10 @@ def get_item(vuln):
risk_accepted = (
review_status == "intentional"
) # not confirmed, not a bug, there are some reasons to make this code in this manner
false_positive = review_status in [
false_positive = review_status in {
"false_positive",
"suppressed",
] # this finding is false positive
} # this finding is false positive
active = not false_positive and not risk_accepted

hash = hashlib.sha256()
Expand Down
2 changes: 1 addition & 1 deletion dojo/tools/dsop/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def __parse_disa(self, test, items, sheet):
for i in range(len(row)):
headers[row[i]] = i
else:
if row[headers["result"]] not in ("fail", "notchecked"):
if row[headers["result"]] not in {"fail", "notchecked"}:
continue
title = row[headers["title"]]
unique_id = row[headers["ruleid"]]
Expand Down
4 changes: 2 additions & 2 deletions dojo/tools/fortify/xml_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,10 @@ def parse_xml(self, filename, test):
meta_pair = ({}, {})
issue_pair = ([], [])
for ReportSection in root.findall("ReportSection"):
if ReportSection.findtext("Title") in [
if ReportSection.findtext("Title") in {
"Results Outline",
"Issue Count by Category",
]:
}:
place = (
0
if ReportSection.findtext("Title") == "Results Outline"
Expand Down
2 changes: 1 addition & 1 deletion dojo/tools/generic/csv_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,6 @@ def _convert_bool(self, val):
return val.lower()[0:1] == "t" # bool False by default

def get_severity(self, input):
if input in ["Info", "Low", "Medium", "High", "Critical"]:
if input in {"Info", "Low", "Medium", "High", "Critical"}:
return input
return "Info"
2 changes: 1 addition & 1 deletion dojo/tools/gitlab_dep_scan/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ def get_item(self, vuln, test, scan):
)

severity = vuln["severity"]
if severity in ["Undefined", "Unknown"]:
if severity in {"Undefined", "Unknown"}:
# Severity can be "Undefined" or "Unknown" in report
# In that case we set it as Info and specify the initial severity
# in the title
Expand Down
Loading

0 comments on commit b85acd8

Please sign in to comment.