Skip to content

Commit

Permalink
add method in EmailLastSeenQueryset
Browse files Browse the repository at this point in the history
  • Loading branch information
vincentporte committed Jan 27, 2025
1 parent 4dc3a5f commit dc98940
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
10 changes: 10 additions & 0 deletions lacommunaute/users/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,14 @@ def __str__(self):
return self.email


class EmailLastSeenQuerySet(models.QuerySet):
def seen(self, email, kind):
if kind not in [kind for kind, _ in EmailLastSeenKind.choices]:
raise ValueError(f"Invalid kind: {kind}")

return self.update_or_create(email=email, defaults={"last_seen_at": timezone.now(), "last_seen_kind": kind})


class EmailLastSeen(models.Model):
email = models.EmailField(verbose_name="email", null=True, blank=True, unique=True)
email_hash = models.CharField(max_length=255, verbose_name="email hash", null=False)
Expand All @@ -38,6 +46,8 @@ class EmailLastSeen(models.Model):
)
deleted_at = models.DateTimeField(verbose_name="deleted at", null=True, blank=True)

objects = EmailLastSeenQuerySet.as_manager()

def __str__(self):
return f"{self.email} - {self.last_seen_at}"

Expand Down
29 changes: 28 additions & 1 deletion lacommunaute/users/tests/tests_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@
import pytest
from django.db import IntegrityError

from lacommunaute.users.enums import EmailLastSeenKind
from lacommunaute.users.factories import EmailLastSeenFactory
from lacommunaute.users.models import User
from lacommunaute.users.models import EmailLastSeen, User


email = "[email protected]"
Expand Down Expand Up @@ -51,3 +52,29 @@ def test_soft_delete(db, email_last_seen):
assert email_last_seen.deleted_at is not None
assert email_last_seen.email is None
assert email_last_seen.email_hash not in [None, ""]


# EmailLastSeenQuerySet tests


@pytest.mark.parametrize("kind", [kind for kind, _ in EmailLastSeenKind.choices])
def test_seen(db, email_last_seen, kind):
EmailLastSeen.objects.seen(email, kind)

email_last_seen.refresh_from_db()
assert email_last_seen.last_seen_kind == kind
assert email_last_seen.last_seen_at is not None


def test_seen_invalid_kind(db, email_last_seen):
with pytest.raises(ValueError):
EmailLastSeen.objects.seen(email, "invalid_kind")


@pytest.mark.parametrize("kind", [kind for kind, _ in EmailLastSeenKind.choices])
def test_seen_unknown_email(db, kind):
EmailLastSeen.objects.seen(email, kind)

email_last_seen = EmailLastSeen.objects.get(email=email)
assert email_last_seen.last_seen_kind == kind
assert email_last_seen.last_seen_at is not None

0 comments on commit dc98940

Please sign in to comment.