Skip to content

Commit

Permalink
chore: small improvement to "level" attribute in scope serializer
Browse files Browse the repository at this point in the history
  • Loading branch information
winged committed Jun 12, 2024
1 parent e2f38f1 commit b96014f
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
8 changes: 7 additions & 1 deletion emeis/core/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,13 @@ def get_level(self, obj):
# Sometimes, the model object may come out of a non-django-tree-queries
# QS, and thus would not have the `tree_*` attributes amended. Then we
# need to go the "slow path"
return obj.ancestors().count()
if not obj.pk and obj.parent_id:
# unsaved object, sometimes used in unit tests etc
return self.get_level(obj.parent) + 1

if obj.parent_id:
return obj.ancestors().count()
return 0

class Meta:
model = Scope
Expand Down
22 changes: 22 additions & 0 deletions emeis/core/tests/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
HTTP_405_METHOD_NOT_ALLOWED,
)

from emeis.core.serializers import ScopeSerializer


def test_me_200(db, acl, client):
client.force_authenticate(user=acl.user)
Expand Down Expand Up @@ -332,3 +334,23 @@ def test_sorted_scopes_when_forced_language(
]

assert received_names == ["eins", "zwei"]


@pytest.mark.parametrize(
"has_parent, is_in_db, expect_level",
[
(False, False, 0),
(False, True, 0),
(True, False, 1),
(True, True, 1),
],
)
def test_serializer_level(db, scope_factory, has_parent, is_in_db, expect_level):
scope = scope_factory(parent=scope_factory() if has_parent else None)
if not is_in_db:
scope.pk = None

ser = ScopeSerializer(instance=scope)

level = ser.data["level"]
assert level == expect_level

0 comments on commit b96014f

Please sign in to comment.