Skip to content

Commit

Permalink
Give the public group to newly created users
Browse files Browse the repository at this point in the history
  • Loading branch information
imperosol committed Dec 28, 2024
1 parent 7bff28e commit f7ba1d9
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 24 deletions.
42 changes: 25 additions & 17 deletions core/management/commands/populate_more.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

from dateutil.relativedelta import relativedelta
from django.conf import settings
from django.contrib.auth.hashers import make_password
from django.core.management.base import BaseCommand
from django.db.models import Count, Exists, Min, OuterRef, Subquery
from django.utils.timezone import localdate, make_aware, now
Expand Down Expand Up @@ -38,23 +39,7 @@ def handle(self, *args, **options):
raise Exception("Never call this command in prod. Never.")

self.stdout.write("Creating users...")
users = [
User(
username=self.faker.user_name(),
first_name=self.faker.first_name(),
last_name=self.faker.last_name(),
date_of_birth=self.faker.date_of_birth(minimum_age=15, maximum_age=25),
email=self.faker.email(),
phone=self.faker.phone_number(),
address=self.faker.address(),
)
for _ in range(600)
]
# there may a duplicate or two
# Not a problem, we will just have 599 users instead of 600
User.objects.bulk_create(users, ignore_conflicts=True)
users = list(User.objects.order_by("-id")[: len(users)])

users = self.create_users()
subscribers = random.sample(users, k=int(0.8 * len(users)))
self.stdout.write("Creating subscriptions...")
self.create_subscriptions(subscribers)
Expand Down Expand Up @@ -102,6 +87,29 @@ def handle(self, *args, **options):

self.stdout.write("Done")

def create_users(self) -> list[User]:
password = make_password("plop")
users = [
User(
username=self.faker.user_name(),
first_name=self.faker.first_name(),
last_name=self.faker.last_name(),
date_of_birth=self.faker.date_of_birth(minimum_age=15, maximum_age=25),
email=self.faker.email(),
phone=self.faker.phone_number(),
address=self.faker.address(),
password=password,
)
for _ in range(600)
]
# there may a duplicate or two
# Not a problem, we will just have 599 users instead of 600
users = User.objects.bulk_create(users, ignore_conflicts=True)
users = list(User.objects.order_by("-id")[: len(users)])
public_group = Group.objects.get(pk=settings.SITH_GROUP_PUBLIC_ID)
public_group.users.add(*users)
return users

def create_subscriptions(self, users: list[User]):
def prepare_subscription(_user: User, start_date: date) -> Subscription:
payment_method = random.choice(settings.SITH_SUBSCRIPTION_PAYMENT_METHOD)[0]
Expand Down
8 changes: 5 additions & 3 deletions core/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -370,12 +370,16 @@ def __str__(self):
return self.get_display_name()

def save(self, *args, **kwargs):
adding = self._state.adding
with transaction.atomic():
if self.id:
if not adding:
old = User.objects.filter(id=self.id).first()
if old and old.username != self.username:
self._change_username(self.username)
super().save(*args, **kwargs)
if adding:
# All users are in the public group.
self.groups.add(settings.SITH_GROUP_PUBLIC_ID)

def get_absolute_url(self) -> str:
return reverse("core:user_profile", kwargs={"user_id": self.pk})
Expand Down Expand Up @@ -430,8 +434,6 @@ def is_in_group(self, *, pk: int | None = None, name: str | None = None) -> bool
raise ValueError("You must either provide the id or the name of the group")
if group is None:
return False
if group.id == settings.SITH_GROUP_PUBLIC_ID:
return True
if group.id == settings.SITH_GROUP_SUBSCRIBERS_ID:
return self.is_subscribed
if group.id == settings.SITH_GROUP_ROOT_ID:
Expand Down
8 changes: 8 additions & 0 deletions core/tests/test_user.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,3 +187,11 @@ def test_generate_username(first_name: str, last_name: str, expected: str):
new_user = User(first_name=first_name, last_name=last_name, email="[email protected]")
new_user.generate_username()
assert new_user.username == expected


@pytest.mark.django_db
def test_user_added_to_public_group():
"""Test that newly created users are added to the public group"""
user = baker.make(User)
assert user.groups.filter(pk=settings.SITH_GROUP_PUBLIC_ID).exists()
assert user.is_in_group(pk=settings.SITH_GROUP_PUBLIC_ID)
11 changes: 7 additions & 4 deletions rootplace/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
#
from datetime import timedelta

from django.conf import settings
from django.test import TestCase
from django.urls import reverse
from django.utils.timezone import localtime, now
Expand Down Expand Up @@ -71,10 +72,12 @@ def test_simple(self):
assert self.to_keep.nick_name == "B'ian"
assert self.to_keep.address == "Jerusalem"
assert self.to_keep.parent_address == "Rome"
assert self.to_keep.groups.count() == 3
groups = sorted(self.to_keep.groups.all(), key=lambda i: i.id)
expected = sorted([subscribers, mde_admin, sas_admin], key=lambda i: i.id)
assert groups == expected
assert set(self.to_keep.groups.values_list("id", flat=True)) == {
settings.SITH_GROUP_PUBLIC_ID,
subscribers.id,
mde_admin.id,
sas_admin.id,
}

def test_both_subscribers_and_with_account(self):
Customer(user=self.to_keep, account_id="11000l", amount=0).save()
Expand Down

0 comments on commit f7ba1d9

Please sign in to comment.