Skip to content

Commit b96014f

Browse files
committed
chore: small improvement to "level" attribute in scope serializer
1 parent e2f38f1 commit b96014f

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

emeis/core/serializers.py

+7-1
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,13 @@ def get_level(self, obj):
9191
# Sometimes, the model object may come out of a non-django-tree-queries
9292
# QS, and thus would not have the `tree_*` attributes amended. Then we
9393
# need to go the "slow path"
94-
return obj.ancestors().count()
94+
if not obj.pk and obj.parent_id:
95+
# unsaved object, sometimes used in unit tests etc
96+
return self.get_level(obj.parent) + 1
97+
98+
if obj.parent_id:
99+
return obj.ancestors().count()
100+
return 0
95101

96102
class Meta:
97103
model = Scope

emeis/core/tests/test_views.py

+22
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212
HTTP_405_METHOD_NOT_ALLOWED,
1313
)
1414

15+
from emeis.core.serializers import ScopeSerializer
16+
1517

1618
def test_me_200(db, acl, client):
1719
client.force_authenticate(user=acl.user)
@@ -332,3 +334,23 @@ def test_sorted_scopes_when_forced_language(
332334
]
333335

334336
assert received_names == ["eins", "zwei"]
337+
338+
339+
@pytest.mark.parametrize(
340+
"has_parent, is_in_db, expect_level",
341+
[
342+
(False, False, 0),
343+
(False, True, 0),
344+
(True, False, 1),
345+
(True, True, 1),
346+
],
347+
)
348+
def test_serializer_level(db, scope_factory, has_parent, is_in_db, expect_level):
349+
scope = scope_factory(parent=scope_factory() if has_parent else None)
350+
if not is_in_db:
351+
scope.pk = None
352+
353+
ser = ScopeSerializer(instance=scope)
354+
355+
level = ser.data["level"]
356+
assert level == expect_level

0 commit comments

Comments
 (0)