Skip to content

Commit

Permalink
fix: Do not try to call an ordering object's order method if it is …
Browse files Browse the repository at this point in the history
…not a decorated method (#584)
  • Loading branch information
bellini666 authored Jul 14, 2024
1 parent 862e64e commit 2897bab
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
6 changes: 4 additions & 2 deletions strawberry_django/ordering.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,10 @@ def process_order(
sequence = sequence or {}
args = []

if not skip_object_order_method and (order_method := getattr(order, "order", None)):
assert isinstance(order_method, FilterOrderFieldResolver)
if not skip_object_order_method and isinstance(
order_method := getattr(order, "order", None),
FilterOrderFieldResolver,
):
return order_method(
order, info, queryset=queryset, prefix=prefix, sequence=sequence
)
Expand Down
29 changes: 29 additions & 0 deletions tests/test_ordering.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
# ruff: noqa: TRY002, B904, BLE001, F811, PT012
from typing import Any, List, Optional, cast
from unittest import mock

import pytest
import strawberry
from django.db.models import Case, Count, Value, When
from pytest_mock import MockFixture
from strawberry import auto
from strawberry.annotation import StrawberryAnnotation
from strawberry.exceptions import MissingArgumentsAnnotationsError
Expand Down Expand Up @@ -331,6 +333,33 @@ def custom_order(self, root, info, prefix, value: auto, sequence, queryset):
process_order(_order, _info, _queryset, prefix="ROOT", sequence=_sequence)


def test_order_method_not_called_when_not_decorated(mocker: MockFixture):
@strawberry_django.ordering.order(models.Fruit)
class Order:
def order(self, root, info, prefix, value: auto, sequence, queryset):
pytest.fail("Should not have been called")

mock_order_method = mocker.spy(Order, "order")

process_order(
cast(WithStrawberryObjectDefinition, Order()), mock.Mock(), mock.Mock()
)

mock_order_method.assert_not_called()


def test_order_field_not_called(mocker: MockFixture):
@strawberry_django.ordering.order(models.Fruit)
class Order:
order: Ordering = Ordering.ASC

# Calling this and no error being raised is the test, as the wrong behavior would
# be for the field to be called like a method
process_order(
cast(WithStrawberryObjectDefinition, Order()), mock.Mock(), mock.Mock()
)


def test_order_object_method():
@strawberry_django.ordering.order(models.Fruit)
class Order:
Expand Down

0 comments on commit 2897bab

Please sign in to comment.