Skip to content

Commit

Permalink
Ruff: Add and fix TRY401
Browse files Browse the repository at this point in the history
  • Loading branch information
kiblik committed Jan 30, 2025
1 parent 420bf66 commit df6232a
Show file tree
Hide file tree
Showing 13 changed files with 43 additions and 45 deletions.
2 changes: 1 addition & 1 deletion dojo/endpoint/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -502,7 +502,7 @@ def import_endpoint_meta(request, pid):
try:
endpoint_meta_import(file, product, create_endpoints, create_tags, create_dojo_meta, origin="UI", request=request)
except Exception as e:
logger.exception(e)
logger.exception("An exception error occurred during the report import")
add_error_message_to_response(f"An exception error occurred during the report import:{e}")
return HttpResponseRedirect(reverse("endpoint") + "?product=" + pid)

Expand Down
6 changes: 3 additions & 3 deletions dojo/engagement/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -928,7 +928,7 @@ def import_findings(
closed_finding_count=closed_finding_count,
))
except Exception as e:
logger.exception(e)
logger.exception("An exception error occurred during the report import")
return f"An exception error occurred during the report import: {e}"
return None

Expand Down Expand Up @@ -1202,10 +1202,10 @@ def add_risk_acceptance(request, eid, fid=None):
# we sometimes see a weird exception here, but are unable to reproduce.
# we add some logging in case it happens
risk_acceptance = form.save()
except Exception as e:
except Exception:
logger.debug(vars(request.POST))
logger.error(vars(form))
logger.exception(e)
logger.exception("Creation of Risk Acc. is not possible")
raise

# attach note to risk acceptance object now in database
Expand Down
4 changes: 2 additions & 2 deletions dojo/finding/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -3291,8 +3291,8 @@ def unlink_jira(request, fid):
)

return JsonResponse({"result": "OK"})
except Exception as e:
logger.exception(e)
except Exception:
logger.exception("Link to JIRA could not be deleted")
messages.add_message(
request,
messages.ERROR,
Expand Down
4 changes: 2 additions & 2 deletions dojo/finding_group/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,8 +153,8 @@ def unlink_jira(request, fgid):
extra_tags="alert-success")

return JsonResponse({"result": "OK"})
except Exception as e:
logger.exception(e)
except Exception:
logger.exception("Link to JIRA could not be deleted")
messages.add_message(
request,
messages.ERROR,
Expand Down
27 changes: 12 additions & 15 deletions dojo/jira_link/helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -409,7 +409,7 @@ def get_jira_connection_raw(jira_server, jira_username, jira_password):

return jira
except JIRAError as e:
logger.exception(e)
logger.exception("logged in to JIRA %s unsuccessful", jira_server)

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

Expand All @@ -422,7 +422,7 @@ def get_jira_connection_raw(jira_server, jira_username, jira_password):
raise

except requests.exceptions.RequestException as re:
logger.exception(re)
logger.exception("Unknown JIRA Connection Error")
error_message = re.text if hasattr(re, "text") else re.message if hasattr(re, "message") else re.args[0]
log_jira_generic_alert("Unknown JIRA Connection Error", re)

Expand Down Expand Up @@ -462,7 +462,7 @@ def jira_transition(jira, issue, transition_id):
return True
except JIRAError as jira_error:
logger.debug("error transitioning jira issue " + issue.key + " " + str(jira_error))
logger.exception(jira_error)
logger.exception("Error with Jira transation issue")
alert_text = f"JiraError HTTP {jira_error.status_code}"
if jira_error.url:
alert_text += f" url: {jira_error.url}"
Expand Down Expand Up @@ -677,8 +677,7 @@ def add_issues_to_epic(jira, obj, epic_id, issue_keys, ignore_epics=True):
try:
return jira.add_issues_to_epic(epic_id=epic_id, issue_keys=issue_keys, ignore_epics=ignore_epics)
except JIRAError as e:
logger.error("error adding issues %s to epic %s for %s", issue_keys, epic_id, obj.id)
logger.exception(e)
logger.exception("error adding issues %s to epic %s for %s", issue_keys, epic_id, obj.id)
log_jira_alert(e.text, obj)
return False

Expand Down Expand Up @@ -1040,8 +1039,7 @@ def get_jira_issue_from_jira(find):
return jira.issue(j_issue.jira_id)

except JIRAError as e:
logger.exception(e)
logger.error("jira_meta for project: %s and url: %s meta: %s", jira_project.project_key, jira_project.jira_instance.url, json.dumps(meta, indent=4)) # this is None safe
logger.exception("jira_meta for project: %s and url: %s meta: %s", jira_project.project_key, jira_project.jira_instance.url, json.dumps(meta, indent=4)) # this is None safe
log_jira_alert(e.text, find)
return None

Expand Down Expand Up @@ -1198,7 +1196,7 @@ def jira_attachment(finding, jira, issue, file, jira_filename=None):
jira.add_attachment(issue=issue, attachment=f)
return True
except JIRAError as e:
logger.exception(e)
logger.exception("Unable to add attachment")
log_jira_alert("Attachment: " + e.text, finding)
return False
return None
Expand Down Expand Up @@ -1252,7 +1250,7 @@ def close_epic(eng, push_to_jira, **kwargs):
return False
return True
except JIRAError as e:
logger.exception(e)
logger.exception("Jira Engagement/Epic Close Error")
log_jira_generic_alert("Jira Engagement/Epic Close Error", str(e))
return False
return None
Expand Down Expand Up @@ -1294,7 +1292,7 @@ def update_epic(engagement, **kwargs):
issue.update(**jira_issue_update_kwargs)
return True
except JIRAError as e:
logger.exception(e)
logger.exception("Jira Engagement/Epic Update Error")
log_jira_generic_alert("Jira Engagement/Epic Update Error", str(e))
return False
else:
Expand Down Expand Up @@ -1351,12 +1349,12 @@ def add_epic(engagement, **kwargs):
# but it's just a non-existent project (or maybe a project for which the account has no create permission?)
#
# {"errorMessages":[],"errors":{"project":"project is required"}}
logger.exception(e)
error = str(e)
message = ""
if "customfield" in error:
message = "The 'Epic name id' in your DefectDojo Jira Configuration does not appear to be correct. Please visit, " + jira_instance.url + \
"/rest/api/2/field and search for Epic Name. Copy the number out of cf[number] and place in your DefectDojo settings for Jira and try again. For example, if your results are cf[100001] then copy 100001 and place it in 'Epic name id'. (Your Epic Id will be different.) \n\n"
logger.exception(message)

log_jira_generic_alert("Jira Engagement/Epic Creation Error",
message + error)
Expand All @@ -1373,8 +1371,7 @@ def jira_get_issue(jira_project, issue_key):
return jira.issue(issue_key)

except JIRAError as jira_error:
logger.debug("error retrieving jira issue " + issue_key + " " + str(jira_error))
logger.exception(jira_error)
logger.exception("error retrieving jira issue %s", issue_key)
log_jira_generic_alert("error retrieving jira issue " + issue_key, str(jira_error))
return None

Expand Down Expand Up @@ -1580,9 +1577,9 @@ def process_jira_project_form(request, instance=None, target=None, product=None,
extra_tags="alert-success")
error = False
logger.debug("stored JIRA_Project successfully")
except Exception as e:
except Exception:
error = True
logger.exception(e)
logger.exception("Unable to store Jira project")
else:
logger.debug(jform.errors)
error = True
Expand Down
18 changes: 10 additions & 8 deletions dojo/jira_link/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -316,8 +316,8 @@ def post(self, request):

try:
jira = jira_helper.get_jira_connection_raw(jira_server, jira_username, jira_password)
except Exception as e:
logger.exception(e) # already logged in jira_helper
except Exception:
logger.exception("Unable to authenticate. Please check credentials.") # already logged in jira_helper
messages.add_message(
request,
messages.ERROR,
Expand All @@ -337,24 +337,26 @@ def post(self, request):
open_key = open_key or int(node["id"])
if node["to"]["statusCategory"]["name"] == "Done":
close_key = close_key or int(node["id"])
except Exception as e:
logger.exception(e) # already logged in jira_helper
except Exception:
msg = "Unable to find Open/Close ID's (invalid issue key specified?). They will need to be found manually"
logger.exception(msg) # already logged in jira_helper
messages.add_message(
request,
messages.ERROR,
"Unable to find Open/Close ID's (invalid issue key specified?). They will need to be found manually",
msg,
extra_tags="alert-danger")
fallback_form = self.get_fallback_form_class()(request.POST, instance=JIRA_Instance())
return render(request, self.get_fallback_template(), {"jform": fallback_form})
# Get the epic id name
try:
epic_name = get_custom_field(jira, "Epic Name")
except Exception as e:
logger.exception(e) # already logged in jira_helper
except Exception:
msg = "Unable to find Epic Name. It will need to be found manually"
logger.exception(msg) # already logged in jira_helper
messages.add_message(
request,
messages.ERROR,
"Unable to find Epic Name. It will need to be found manually",
msg,
extra_tags="alert-danger")
fallback_form = self.get_fallback_form_class()(request.POST, instance=JIRA_Instance())
return render(request, self.get_fallback_template(), {"jform": fallback_form})
Expand Down
10 changes: 5 additions & 5 deletions dojo/notifications/helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ def send_slack_notification(
)

except Exception as exception:
logger.exception(exception)
logger.exception("Unable to send Slack notification")
self._log_alert(
exception,
"Slack Notification",
Expand Down Expand Up @@ -348,7 +348,7 @@ def send_msteams_notification(
"Webhook URL for Microsoft Teams not configured: skipping system notification",
)
except Exception as exception:
logger.exception(exception)
logger.exception("Unable to send Microsoft Teams Notification")
self._log_alert(
exception,
"Microsoft Teams Notification",
Expand Down Expand Up @@ -397,7 +397,7 @@ def send_mail_notification(
email.send(fail_silently=False)

except Exception as exception:
logger.exception(exception)
logger.exception("Unable to send Email Notification")
self._log_alert(
exception,
"Email Notification",
Expand Down Expand Up @@ -460,7 +460,7 @@ def send_webhooks_notification(
except Exception as exception:
error = self.ERROR_PERMANENT
endpoint.note = f"Exception: {exception}"[:1000]
logger.exception(exception)
logger.exception("Unable to send Webhooks Notification")
self._log_alert(exception, "Webhooks Notification")

now = get_current_datetime()
Expand Down Expand Up @@ -601,7 +601,7 @@ def send_alert_notification(
alert.clean_fields(exclude=["url"])
alert.save()
except Exception as exception:
logger.exception(exception)
logger.exception("Unable to create Alert Notification")
self._log_alert(
exception,
"Alert Notification",
Expand Down
2 changes: 1 addition & 1 deletion dojo/product/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -1757,7 +1757,7 @@ def add_api_scan_configuration(request, pid):
return HttpResponseRedirect(reverse("add_api_scan_configuration", args=(pid,)))
return HttpResponseRedirect(reverse("view_api_scan_configurations", args=(pid,)))
except Exception as e:
logger.exception(e)
logger.exception("Unable to add API Scan Configuration")
messages.add_message(request,
messages.ERROR,
str(e),
Expand Down
5 changes: 2 additions & 3 deletions dojo/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,9 +175,8 @@ def async_sla_compute_and_notify_task(*args, **kwargs):
system_settings = System_Settings.objects.get()
if system_settings.enable_finding_sla:
sla_compute_and_notify(*args, **kwargs)
except Exception as e:
logger.exception(e)
logger.error(f"An unexpected error was thrown calling the SLA code: {e}")
except Exception:
logger.exception("An unexpected error was thrown calling the SLA code")


@app.task
Expand Down
2 changes: 1 addition & 1 deletion dojo/test/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -1002,7 +1002,7 @@ def reimport_findings(
untouched_finding_count=untouched_finding_count,
))
except Exception as e:
logger.exception(e)
logger.exception("An exception error occurred during the report import")
return f"An exception error occurred during the report import: {e}"
return None

Expand Down
2 changes: 1 addition & 1 deletion dojo/tool_config/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def new_tool_config(request):
extra_tags="alert-success")
return HttpResponseRedirect(reverse("tool_config"))
except Exception as e:
logger.exception(e)
logger.exception("Unable to connect to API")
messages.add_message(request,
messages.ERROR,
str(e),
Expand Down
4 changes: 2 additions & 2 deletions dojo/tools/api_sonarqube/importer.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ def import_issues(self, test):
items.append(find)

except Exception as e:
logger.exception(e)
logger.exception("SonarQube API import issue")
create_notification(
event="sonarqube_failed",
title="SonarQube API import issue",
Expand Down Expand Up @@ -326,7 +326,7 @@ def import_hotspots(self, test):
return items

except Exception as e:
logger.exception(e)
logger.exception("SonarQube API import issue")
create_notification(
event="sonarqube_failed",
title="SonarQube API import issue",
Expand Down
2 changes: 1 addition & 1 deletion ruff.toml
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ select = [
"PLE",
"PLR01", "PLR0203", "PLR0206", "PLR0915", "PLR1716", "PLR172", "PLR1733", "PLR1736",
"PLW0120", "PLW0129", "PLW013", "PLW017", "PLW02", "PLW04", "PLW07", "PLW1", "PLW2", "PLW3",
"TRY003", "TRY004", "TRY2",
"TRY003", "TRY004", "TRY2", "TRY401",
"FLY",
"NPY",
"FAST",
Expand Down

0 comments on commit df6232a

Please sign in to comment.