Skip to content

Commit

Permalink
Ruff: Add and fix TRY300
Browse files Browse the repository at this point in the history
  • Loading branch information
kiblik committed Feb 6, 2025
1 parent f13769f commit f1d0b21
Show file tree
Hide file tree
Showing 14 changed files with 47 additions and 44 deletions.
2 changes: 1 addition & 1 deletion dojo/api_v2/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -667,12 +667,12 @@ def update_jira_epic(self, request, pk=None):
{"info": "Jira Epic create query sent"},
status=status.HTTP_200_OK,
)
return response
except ValidationError:
return Response(
{"error": "Bad Request!"},
status=status.HTTP_400_BAD_REQUEST,
)
return response


# @extend_schema_view(**schema_with_prefetch())
Expand Down
4 changes: 2 additions & 2 deletions dojo/authorization/roles_permissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@ class Roles(IntEnum):
def has_value(cls, value):
try:
Roles(value)
return True
except ValueError:
return False
return True


def django_enum(cls):
Expand Down Expand Up @@ -129,9 +129,9 @@ class Permissions(IntEnum):
def has_value(cls, value):
try:
Permissions(value)
return True
except ValueError:
return False
return True

@classmethod
def get_engagement_permissions(cls):
Expand Down
8 changes: 4 additions & 4 deletions dojo/context_processors.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import contextlib

# import the settings file
from django.conf import settings

Expand Down Expand Up @@ -47,12 +49,10 @@ def bind_alert_count(request):
def bind_announcement(request):
from dojo.models import UserAnnouncement

try:
with contextlib.suppress(Exception): # TODO: this should be replaced with more meaningful exception
if request.user.is_authenticated:
user_announcement = UserAnnouncement.objects.select_related(
"announcement",
).get(user=request.user)
return {"announcement": user_announcement.announcement}
return {}
except Exception:
return {}
return {}
30 changes: 16 additions & 14 deletions dojo/jira_link/helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -406,7 +406,6 @@ def get_jira_connection_raw(jira_server, jira_username, jira_password):

logger.debug("logged in to JIRA %s successfully", jira_server)

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

Expand All @@ -428,6 +427,8 @@ def get_jira_connection_raw(jira_server, jira_username, jira_password):
add_error_message_to_response("Unable to authenticate to JIRA. Please check the URL, username, password, captcha challenge, Network connection. Details in alert on top right. " + str(error_message))
raise

return jira


# Gets a connection to a Jira server based on the finding
def get_jira_connection(obj):
Expand Down Expand Up @@ -1185,10 +1186,10 @@ def is_jira_project_valid(jira_project):
try:
jira = get_jira_connection(jira_project)
get_issuetype_fields(jira, jira_project.project_key, jira_project.jira_instance.default_issue_type)
return True
except JIRAError:
logger.debug("invalid JIRA Project Config, can't retrieve metadata for '%s'", jira_project)
return False
return True


def jira_attachment(finding, jira, issue, file, jira_filename=None):
Expand All @@ -1209,11 +1210,11 @@ def jira_attachment(finding, jira, issue, file, jira_filename=None):
# read and upload a file
with open(file, "rb") as f:
jira.add_attachment(issue=issue, attachment=f)
return True
except JIRAError as e:
logger.exception("Unable to add attachment")
log_jira_alert("Attachment: " + e.text, finding)
return False
return True
return None


Expand Down Expand Up @@ -1263,11 +1264,11 @@ def close_epic(eng, push_to_jira, **kwargs):
if r.status_code != 204:
logger.warning(f"JIRA close epic failed with error: {r.text}")
return False
return True
except JIRAError as e:
logger.exception("Jira Engagement/Epic Close Error")
log_jira_generic_alert("Jira Engagement/Epic Close Error", str(e))
return False
return True
return None
add_error_message_to_response("Push to JIRA for Epic skipped because enable_engagement_epic_mapping is not checked for this engagement")
return False
Expand Down Expand Up @@ -1304,15 +1305,15 @@ def update_epic(engagement, **kwargs):
if (epic_priority := kwargs.get("epic_priority")) is not None:
jira_issue_update_kwargs["priority"] = {"name": epic_priority}
issue.update(**jira_issue_update_kwargs)
return True
except JIRAError as e:
logger.exception("Jira Engagement/Epic Update Error")
log_jira_generic_alert("Jira Engagement/Epic Update Error", str(e))
return False
else:
add_error_message_to_response("Push to JIRA for Epic skipped because enable_engagement_epic_mapping is not checked for this engagement")

return False
return True

add_error_message_to_response("Push to JIRA for Epic skipped because enable_engagement_epic_mapping is not checked for this engagement")
return False


@dojo_model_to_id
Expand Down Expand Up @@ -1359,7 +1360,6 @@ def add_epic(engagement, **kwargs):
engagement=engagement,
jira_project=jira_project)
j_issue.save()
return True
except JIRAError as e:
# should we try to parse the errors as JIRA is very strange in how it responds.
# for example a non existent project_key leads to "project key is required" which sounds like something is missing
Expand All @@ -1376,9 +1376,11 @@ def add_epic(engagement, **kwargs):
log_jira_generic_alert("Jira Engagement/Epic Creation Error",
message + error)
return False
else:
add_error_message_to_response("Push to JIRA for Epic skipped because enable_engagement_epic_mapping is not checked for this engagement")
return False

return True

add_error_message_to_response("Push to JIRA for Epic skipped because enable_engagement_epic_mapping is not checked for this engagement")
return False


def jira_get_issue(jira_project, issue_key):
Expand Down Expand Up @@ -1415,10 +1417,10 @@ def add_comment(obj, note, *, force_push=False, **kwargs):
jira.add_comment(
j_issue.jira_id,
f"({note.author.get_full_name() or note.author.username}): {note.entry}")
return True
except JIRAError as e:
log_jira_generic_alert("Jira Add Comment Error", str(e))
return False
return True
return None
return None

Expand All @@ -1437,10 +1439,10 @@ def add_simple_jira_comment(jira_instance, jira_issue, comment):
jira.add_comment(
jira_issue.jira_id, comment,
)
return True
except Exception as e:
log_jira_generic_alert("Jira Add Comment Error", str(e))
return False
return True


def jira_already_linked(finding, jira_issue_key, jira_id) -> Finding | None:
Expand Down
2 changes: 1 addition & 1 deletion dojo/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -3085,9 +3085,9 @@ def has_github_issue(self):
try:
# Attempt to access the github issue if it exists. If not, an exception will be caught
_ = self.github_issue
return True
except GITHUB_Issue.DoesNotExist:
return False
return True

def github_conf(self):
try:
Expand Down
2 changes: 1 addition & 1 deletion dojo/templatetags/get_banner.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,6 @@ def get_banner_conf(attribute):
attributes=allowed_attributes,
css_sanitizer=CSSSanitizer(allowed_css_properties=["color", "font-weight"])))
return value
return False
except Exception:
return False
return False
6 changes: 3 additions & 3 deletions dojo/tools/anchore_enterprise/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,11 +114,11 @@ def policy_name(policies, policy_id):
def extract_vulnerability_id(trigger_id):
try:
vulnerability_id, _ = trigger_id.split("+", 2)
if vulnerability_id.startswith("CVE"):
return vulnerability_id
return None
except ValueError:
return None
if vulnerability_id.startswith("CVE"):
return vulnerability_id
return None


def search_filepath(text):
Expand Down
6 changes: 3 additions & 3 deletions dojo/tools/anchorectl_policies/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,11 +116,11 @@ def policy_name(policies, policy_id):
def extract_vulnerability_id(trigger_id):
try:
vulnerability_id, _ = trigger_id.split("+", 2)
if vulnerability_id.startswith("CVE"):
return vulnerability_id
return None
except ValueError:
return None
if vulnerability_id.startswith("CVE"):
return vulnerability_id
return None


def search_filepath(text):
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 @@ -323,8 +323,6 @@ def import_hotspots(self, test):
)
items.append(find)

return items

except Exception as e:
logger.exception("SonarQube API import issue")
create_notification(
Expand All @@ -336,6 +334,8 @@ def import_hotspots(self, test):
obj=test.engagement.product,
)

return items

@staticmethod
def clean_rule_description_html(raw_html):
search = re.search(
Expand Down
3 changes: 2 additions & 1 deletion dojo/tools/kubescape/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,11 @@ def parse_resource_id(self, resource_id):
parts = resource_id.split("/")
resource_type = parts[-2]
resource_name = parts[-1]
return resource_type, resource_name
except IndexError:
return None, None

return resource_type, resource_name

def get_findings(self, filename, test):
findings = []
try:
Expand Down
16 changes: 8 additions & 8 deletions dojo/tools/ptart/ptart_parser_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,12 +87,12 @@ def parse_screenshot_data(screenshot):
try:
title = get_screenshot_title(screenshot)
data = get_screenshot_data(screenshot)
return {
"title": title,
"data": data,
}
except ValueError:
return None
return {
"title": title,
"data": data,
}


def get_screenshot_title(screenshot):
Expand Down Expand Up @@ -129,13 +129,13 @@ def parse_attachment_data(attachment):
try:
title = get_attachement_title(attachment)
data = get_attachment_data(attachment)
return {
"title": title,
"data": data,
}
except ValueError:
# No data in attachment, let's not import this file.
return None
return {
"title": title,
"data": data,
}


def get_attachment_data(attachment):
Expand Down
4 changes: 2 additions & 2 deletions dojo/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -883,12 +883,12 @@ def get_punchcard_data(objs, start_date, weeks, view="Finding"):
punch.append(punch[2])
punch[2] = (sqrt(punch[2] / pi)) / ratio

return punchcard, ticks

except Exception:
logger.exception("Not showing punchcard graph due to exception gathering data")
return None, None

return punchcard, ticks


def get_week_data(week_start_date, tick, day_counts):
data = []
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", "TRY401",
"TRY003", "TRY004", "TRY2", "TRY300", "TRY401",
"FLY",
"NPY",
"FAST",
Expand Down
2 changes: 1 addition & 1 deletion tests/base_test_class.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,9 +261,9 @@ def is_element_by_css_selector_present(self, selector, text=None):
def is_element_by_id_present(self, id):
try:
self.driver.find_element(By.ID, id)
return True
except NoSuchElementException:
return False
return True

def is_success_message_present(self, text=None):
return self.is_element_by_css_selector_present(".alert-success", text=text)
Expand Down

0 comments on commit f1d0b21

Please sign in to comment.