Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ruff: Add and fix D2 #10844

Merged
merged 1 commit into from
Oct 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 16 additions & 24 deletions dojo/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,29 +22,25 @@


class QuestionChildAdmin(PolymorphicChildModelAdmin):
"""
Base admin class for all child models of Question
"""

"""Base admin class for all child models of Question"""

base_model = Question


class TextQuestionAdmin(QuestionChildAdmin):
"""
ModelAdmin for a TextQuestion
"""

"""ModelAdmin for a TextQuestion"""


class ChoiceQuestionAdmin(QuestionChildAdmin):
"""
ModelAdmin for a ChoiceQuestion
"""

"""ModelAdmin for a ChoiceQuestion"""


class QuestionParentAdmin(PolymorphicParentModelAdmin):
"""
Question parent model admin
"""

"""Question parent model admin"""

base_model = Question
child_models = (
Expand All @@ -60,29 +56,25 @@ class QuestionParentAdmin(PolymorphicParentModelAdmin):


class AnswerChildAdmin(PolymorphicChildModelAdmin):
"""
Base admin class for all child Answer models
"""

"""Base admin class for all child Answer models"""

base_model = Answer


class TextAnswerAdmin(AnswerChildAdmin):
"""
ModelAdmin for TextAnswer
"""

"""ModelAdmin for TextAnswer"""


class ChoiceAnswerAdmin(AnswerChildAdmin):
"""
ModelAdmin for ChoiceAnswer
"""

"""ModelAdmin for ChoiceAnswer"""


class AnswerParentAdmin(PolymorphicParentModelAdmin):
"""
The parent model admin for answer
"""

"""The parent model admin for answer"""

list_display = (
"answered_survey",
Expand Down
9 changes: 6 additions & 3 deletions dojo/api_v2/prefetch/prefetcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@
class _Prefetcher:
@staticmethod
def _build_serializers():
"""Returns a map model -> serializer where model is a django model and serializer is the corresponding
"""
Returns a map model -> serializer where model is a django model and serializer is the corresponding
serializer used to serialize the model

Returns:
Expand Down Expand Up @@ -52,7 +53,8 @@ def __init__(self):
self._prefetch_data = {}

def _find_serializer(self, field_type):
"""Find the best suited serializer for the given type.
"""
Find the best suited serializer for the given type.

Args:
field_type (django.db.models.fields): the field type for which we need to find a serializer
Expand All @@ -72,7 +74,8 @@ def _find_serializer(self, field_type):
return self._find_serializer(parent_class)

def _prefetch(self, entry, fields_to_fetch):
"""Apply prefetching for the given field on the given entry
"""
Apply prefetching for the given field on the given entry

Args:
entry (ModelInstance): Instance of a model as returned by a django queryset
Expand Down
7 changes: 4 additions & 3 deletions dojo/api_v2/prefetch/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ def _get_path_to_GET_serializer_map(generator):


def get_serializer_ref_name(serializer):
"""Get serializer's ref_name
"""
Get serializer's ref_name
inspired by https://github.com/axnsan12/drf-yasg/blob/78031f0c189585c30fccb5005a6899f2d34289a9/src/drf_yasg/utils.py#L416

:param serializer: Serializer instance
Expand All @@ -37,14 +38,14 @@ def get_serializer_ref_name(serializer):


def prefetch_postprocessing_hook(result, generator, request, public):
"""OpenAPI v3 (drf-spectacular) Some endpoints are using the PrefetchListMixin and PrefetchRetrieveMixin.
"""
OpenAPI v3 (drf-spectacular) Some endpoints are using the PrefetchListMixin and PrefetchRetrieveMixin.
These have nothing to do with Django prefetch_related.
The endpoints have an @extend_schema configured with an extra parameter 'prefetch'
This parameter contains an array of relations to prefetch. These prefetched models
will be returned in an additional property in the response.
The below processor ensures the result schema matches this.
"""

serializer_classes = _get_path_to_GET_serializer_map(generator)

paths = result.get("paths", {})
Expand Down
9 changes: 6 additions & 3 deletions dojo/api_v2/prefetch/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@


def _is_many_to_many_relation(field):
"""Check if a field specified a many-to-many relationship as defined by django.
"""
Check if a field specified a many-to-many relationship as defined by django.
This is the case if the field is an instance of the ManyToManyDescriptor as generated
by the django framework

Expand All @@ -16,7 +17,8 @@ def _is_many_to_many_relation(field):


def _is_one_to_one_relation(field):
"""Check if a field specified a one-to-one relationship as defined by django.
"""
Check if a field specified a one-to-one relationship as defined by django.
This is the case if the field is an instance of the ForwardManyToOne as generated
by the django framework

Expand All @@ -30,7 +32,8 @@ def _is_one_to_one_relation(field):


def _get_prefetchable_fields(serializer):
"""Get the fields that are prefetchable according to the serializer description.
"""
Get the fields that are prefetchable according to the serializer description.
Method mainly used by for automatic schema generation.

Args:
Expand Down
4 changes: 4 additions & 0 deletions dojo/api_v2/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -2360,6 +2360,7 @@ def get(self, request, format=None):

# Authorization: authenticated users, DjangoModelPermissions
class ImportScanView(mixins.CreateModelMixin, viewsets.GenericViewSet):

"""
Imports a scan report into an engagement or product.

Expand Down Expand Up @@ -2423,6 +2424,7 @@ def get_queryset(self):
class EndpointMetaImporterView(
mixins.CreateModelMixin, viewsets.GenericViewSet,
):

"""
Imports a CSV file into a product to propagate arbitrary meta and tags on endpoints.

Expand Down Expand Up @@ -2498,6 +2500,7 @@ def get_queryset(self):

# Authorization: object-based
class ReImportScanView(mixins.CreateModelMixin, viewsets.GenericViewSet):

"""
Reimports a scan report into an existing test.

Expand Down Expand Up @@ -2898,6 +2901,7 @@ def report_generate(request, obj, options):
class SystemSettingsViewSet(
mixins.ListModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet,
):

"""Basic control over System Settings. Use 'id' 1 for PUT, PATCH operations"""

permission_classes = (permissions.IsSuperUser, DjangoModelPermissions)
Expand Down
7 changes: 1 addition & 6 deletions dojo/authorization/authorization_decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@

def user_is_authorized(model, permission, arg, lookup="pk", func=None):
"""Decorator for functions that ensures the user has permission on an object."""

if func is None:
return functools.partial(
user_is_authorized, model, permission, arg, lookup,
Expand Down Expand Up @@ -41,7 +40,6 @@ def _wrapped(request, *args, **kwargs):

def user_has_global_permission(permission, func=None):
"""Decorator for functions that ensures the user has a (global) permission"""

if func is None:
return functools.partial(user_has_global_permission, permission)

Expand All @@ -54,10 +52,7 @@ def _wrapped(request, *args, **kwargs):


def user_is_configuration_authorized(permission, func=None):
"""
Decorator for views that checks whether a user has a particular permission enabled.
"""

"""Decorator for views that checks whether a user has a particular permission enabled."""
if func is None:
return functools.partial(user_is_configuration_authorized, permission)

Expand Down
4 changes: 1 addition & 3 deletions dojo/authorization/roles_permissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -517,9 +517,7 @@ def get_roles_with_permissions():


def get_global_roles_with_permissions():
"""
Extra permissions for global roles, on top of the permissions granted to the "normal" roles above.
"""
"""Extra permissions for global roles, on top of the permissions granted to the "normal" roles above."""
return {
Roles.Maintainer: {Permissions.Product_Type_Add},
Roles.Owner: {Permissions.Product_Type_Add},
Expand Down
48 changes: 12 additions & 36 deletions dojo/engagement/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -693,9 +693,7 @@ def add_tests(request, eid):

class ImportScanResultsView(View):
def get_template(self) -> str:
"""
Returns the template that will be presented to the user
"""
"""Returns the template that will be presented to the user"""
return "dojo/import_scan_results.html"

def get_development_environment(
Expand All @@ -715,9 +713,7 @@ def get_engagement_or_product(
engagement_id: Optional[int] = None,
product_id: Optional[int] = None,
) -> Tuple[Engagement, Product, Product | Engagement]:
"""
Using the path parameters, either fetch the product or engagement
"""
"""Using the path parameters, either fetch the product or engagement"""
engagement = product = engagement_or_product = None
# Get the product if supplied
# Get the engagement if supplied
Expand All @@ -740,9 +736,7 @@ def get_form(
request: HttpRequest,
**kwargs: dict,
) -> ImportScanForm:
"""
Returns the default import form for importing findings
"""
"""Returns the default import form for importing findings"""
if request.method == "POST":
return ImportScanForm(request.POST, request.FILES, **kwargs)
return ImportScanForm(**kwargs)
Expand Down Expand Up @@ -776,9 +770,7 @@ def get_jira_form(
request: HttpRequest,
engagement_or_product: Engagement | Product,
) -> Tuple[JIRAImportScanForm | None, bool]:
"""
Returns a JiraImportScanForm if jira is enabled
"""
"""Returns a JiraImportScanForm if jira is enabled"""
jira_form = None
push_all_jira_issues = False
# Determine if jira issues should be pushed automatically
Expand Down Expand Up @@ -919,18 +911,14 @@ def get_importer(
self,
context: dict,
) -> BaseImporter:
"""
Gets the importer to use
"""
"""Gets the importer to use"""
return DefaultImporter(**context)

def import_findings(
self,
context: dict,
) -> str | None:
"""
Attempt to import with all the supplied information
"""
"""Attempt to import with all the supplied information"""
try:
importer_client = self.get_importer(context)
context["test"], _, finding_count, closed_finding_count, _, _, _ = importer_client.process_scan(
Expand All @@ -952,9 +940,7 @@ def process_form(
form: ImportScanForm,
context: dict,
) -> str | None:
"""
Process the form and manipulate the input in any way that is appropriate
"""
"""Process the form and manipulate the input in any way that is appropriate"""
# Update the running context dict with cleaned form input
context.update({
"scan": request.FILES.get("file", None),
Expand Down Expand Up @@ -1024,9 +1010,7 @@ def process_credentials_form(
form: CredMappingForm,
context: dict,
) -> str | None:
"""
Process the credentials form by creating
"""
"""Process the credentials form by creating"""
if cred_user := form.cleaned_data["cred_user"]:
# Select the credential mapping object from the selected list and only allow if the credential is associated with the product
cred_user = Cred_Mapping.objects.filter(
Expand All @@ -1046,18 +1030,14 @@ def success_redirect(
self,
context: dict,
) -> HttpResponseRedirect:
"""
Redirect the user to a place that indicates a successful import
"""
"""Redirect the user to a place that indicates a successful import"""
return HttpResponseRedirect(reverse("view_test", args=(context.get("test").id, )))

def failure_redirect(
self,
context: dict,
) -> HttpResponseRedirect:
"""
Redirect the user to a place that indicates a failed import
"""
"""Redirect the user to a place that indicates a failed import"""
return HttpResponseRedirect(reverse(
"import_scan_results",
args=(context.get("engagement", context.get("product")).id, ),
Expand All @@ -1069,9 +1049,7 @@ def get(
engagement_id: Optional[int] = None,
product_id: Optional[int] = None,
) -> HttpResponse:
"""
Process GET requests for the Import View
"""
"""Process GET requests for the Import View"""
# process the request and path parameters
request, context = self.handle_request(
request,
Expand All @@ -1087,9 +1065,7 @@ def post(
engagement_id: Optional[int] = None,
product_id: Optional[int] = None,
) -> HttpResponse:
"""
Process POST requests for the Import View
"""
"""Process POST requests for the Import View"""
# process the request and path parameters
request, context = self.handle_request(
request,
Expand Down
2 changes: 1 addition & 1 deletion dojo/finding/helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -566,7 +566,7 @@ def engagement_post_delete(sender, instance, **kwargs):


def fix_loop_duplicates():
""" Due to bugs in the past and even currently when under high parallel load, there can be transitive duplicates. """
"""Due to bugs in the past and even currently when under high parallel load, there can be transitive duplicates."""
""" i.e. A -> B -> C. This can lead to problems when deleting findingns, performing deduplication, etc """
candidates = Finding.objects.filter(duplicate_finding__isnull=False, original_finding__isnull=False).order_by("-id")

Expand Down
6 changes: 4 additions & 2 deletions dojo/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ def render(self, name, *args, **kwargs):


class MonthYearWidget(Widget):

"""
A Widget that splits date input into two <select> boxes for month and year,
with 'day' defaulting to the first of the month.
Expand All @@ -148,6 +149,7 @@ class MonthYearWidget(Widget):

django/trunk/django/forms/extras/widgets.py
"""

none_value = (0, "---")
month_field = "%s_month"
year_field = "%s_year"
Expand Down Expand Up @@ -3176,8 +3178,8 @@ def __init__(self, *args, **kwargs):
# Show in admin a multichoice list of validator names
# pass this to form using field_name='validator_name' ?
class QuestionForm(forms.Form):
""" Base class for a Question
"""

"""Base class for a Question"""

def __init__(self, *args, **kwargs):
self.helper = FormHelper()
Expand Down
Loading
Loading