from django.contrib.auth import get_user_model from django.contrib.auth.models import Permission from django.test import TestCase from django.urls import reverse from .test_utils import create_election User = get_user_model() class AdminViewsTest(TestCase): def setUp(self): perm = Permission.objects.get(codename="is_admin") self.admin_1 = User.objects.create( username="pwd__admin1", email="admin1@ens.fr", full_name="Alfred Dmin" ) self.admin_2 = User.objects.create( username="pwd__admin2", email="admin2@ens.fr", full_name="Albert Dmin" ) self.base_user = User.objects.create( username="cas__user", email="user@clipper.ens.fr", full_name="Ulric Ser" ) self.admin_1.user_permissions.add(perm) self.admin_2.user_permissions.add(perm) self.election_1 = create_election(1, creator=self.admin_1) self.election_2 = create_election(2, creator=self.admin_1, future=True) self.election_3 = create_election(3, creator=self.admin_2) self.election_4 = create_election(4) def test_create_view(self): url = reverse("election.create") # Création possible pour un admin self.client.force_login(self.admin_1) self.assertEqual(self.client.get(url).status_code, 200) # Création impossible pour un user lambda self.client.force_login(self.base_user) self.assertEqual(self.client.get(url).status_code, 403) def test_admin_view(self): url_1 = reverse("election.admin", args=[self.election_1.pk]) url_3 = reverse("election.admin", args=[self.election_3.pk]) url_4 = reverse("election.admin", args=[self.election_4.pk]) # Accès uniquement à sa propre élection self.client.force_login(self.admin_1) self.assertEqual(self.client.get(url_1).status_code, 200) self.assertEqual(self.client.get(url_3).status_code, 404) self.assertEqual(self.client.get(url_4).status_code, 404) # Accès refusé pour un user lambda self.client.force_login(self.base_user) self.assertEqual(self.client.get(url_1).status_code, 403)