Skip to content

Commit

Permalink
Merge pull request #267 from winged/feat_model_strings
Browse files Browse the repository at this point in the history
chore: better model stringification
  • Loading branch information
czosel authored Aug 31, 2021
2 parents a54407a + 50d287b commit 93fa605
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 7 deletions.
23 changes: 16 additions & 7 deletions emeis/core/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ class User(UUIDModel, AbstractBaseUser):
objects = UserManager()

def __str__(self):
return "%s object (%s - %s)" % (self.__class__.__name__, self.pk, self.username)
return "%s (username=%s)" % (type(self).__name__, self.username)

class Meta:
verbose_name = _("user")
Expand Down Expand Up @@ -170,6 +170,17 @@ class Scope(MPTTModel, UUIDModel):
related_name="children",
)

def full_name(self, sep="\u00bb"):
"""Return full name of the scope, including parent scopes."""
if self.parent:
parent_name = self.parent.full_name(sep)
return f"{parent_name} {sep} {self.name}"
return str(self.name)

def __str__(self):
name = self.full_name()
return f"{type(self).__name__} ({name}, pk={self.pk})"


class Role(SlugModel):
name = LocalizedCharField(_("role name"), blank=False, null=False, required=False)
Expand All @@ -178,6 +189,9 @@ class Role(SlugModel):
)
permissions = models.ManyToManyField("Permission", related_name="roles")

def __str__(self):
return f"{type(self).__name__} ({self.pk})"

class Meta:
ordering = ["slug"]

Expand All @@ -197,12 +211,7 @@ class ACL(UUIDModel):
role = models.ForeignKey("Role", on_delete=models.CASCADE, related_name="acls")

def __str__(self):
return "%s object (%s - %s - %s)" % (
self.__class__.__name__,
self.user.username,
self.scope,
self.role,
)
return f"{type(self).__name__} (username={self.user.username}, scope=self.scope, role={self.role.pk})"

class Meta:
unique_together = ["user", "scope", "role"]
11 changes: 11 additions & 0 deletions emeis/core/tests/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,14 @@ def test_can_authenticate(db, user):
request, username=user.username, password="test_password"
)
assert auth == user


def test_scope_hierarchical_name(scope_factory):
root = scope_factory()
child = scope_factory(parent=root)
grandchild = scope_factory(parent=child)

assert (
grandchild.full_name(sep=">")
== f"{root.name} > {child.name} > {grandchild.name}"
)

0 comments on commit 93fa605

Please sign in to comment.