gestioCOF/gestioncof/tests/utils.py

107 lines
2.8 KiB
Python

import os
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.management import call_command
from gestioncof.petits_cours_models import (
PetitCoursAbility,
PetitCoursAttributionCounter,
PetitCoursDemande,
PetitCoursSubject,
)
User = get_user_model()
def _create_user(username, is_cof=False, is_staff=False, attrs=None):
if attrs is None:
attrs = {}
password = attrs.pop("password", username)
user_keys = ["first_name", "last_name", "email", "is_staff", "is_superuser"]
user_attrs = {k: v for k, v in attrs.items() if k in user_keys}
profile_keys = [
"is_cof",
"login_clipper",
"phone",
"occupation",
"departement",
"type_cotiz",
"mailing_cof",
"mailing_bda",
"mailing_bda_revente",
"comments",
"is_buro",
"petit_cours_accept",
"petit_cours_remarques",
]
profile_attrs = {k: v for k, v in attrs.items() if k in profile_keys}
if is_cof:
profile_attrs["is_cof"] = True
if is_staff:
# At the moment, admin is accessible by COF staff.
user_attrs["is_staff"] = True
profile_attrs["is_buro"] = True
user = User(username=username, **user_attrs)
user.set_password(password)
user.save()
for k, v in profile_attrs.items():
setattr(user.profile, k, v)
user.profile.save()
return user
def create_user(username, attrs=None):
return _create_user(username, attrs=attrs)
def create_member(username, attrs=None):
return _create_user(username, is_cof=True, attrs=attrs)
def create_staff(username, attrs=None):
return _create_user(username, is_cof=True, is_staff=True, attrs=attrs)
def create_root(username, attrs=None):
if attrs is None:
attrs = {}
attrs.setdefault("is_staff", True)
attrs.setdefault("is_superuser", True)
return _create_user(username, attrs=attrs)
def create_petitcours_ability(**kwargs):
if "user" not in kwargs:
kwargs["user"] = create_user()
if "matiere" not in kwargs:
kwargs["matiere"] = create_petitcours_subject()
if "niveau" not in kwargs:
kwargs["niveau"] = "college"
ability = PetitCoursAbility.objects.create(**kwargs)
PetitCoursAttributionCounter.get_uptodate(ability.user, ability.matiere)
return ability
def create_petitcours_demande(**kwargs):
return PetitCoursDemande.objects.create(**kwargs)
def create_petitcours_subject(**kwargs):
return PetitCoursSubject.objects.create(**kwargs)
class PetitCoursTestHelpers:
def require_custommails(self):
data_file = os.path.join(
settings.BASE_DIR, "gestioncof", "management", "data", "custommail.json"
)
call_command("syncmails", data_file, verbosity=0)