Use pytest for tests (#681)

* use pytest for tests

Eh ouais, il y a que la config qui change. Pytest est implémentable par étapes. Et ça c'est beau.

* rework tests with pytest

* remove unittest custom TestRunner

* Edit doc and CI
This commit is contained in:
thomas girod 2024-06-26 19:10:24 +02:00 committed by GitHub
parent a5cbac1f97
commit d97602e60b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
19 changed files with 1268 additions and 1515 deletions

View File

@ -25,12 +25,12 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Check out repository
uses: actions/checkout@v3
uses: actions/checkout@v4
- uses: ./.github/actions/setup_project
- uses: ./.github/actions/setup_xapian
- uses: ./.github/actions/compile_messages
- name: Run tests
run: poetry run coverage run ./manage.py test
run: poetry run coverage run -m pytest
- name: Generate coverage report
run: |
poetry run coverage report

View File

@ -30,71 +30,66 @@ from core.models import User
class RefoundAccountTest(TestCase):
def setUp(self):
self.skia = User.objects.filter(username="skia").first()
@classmethod
def setUpTestData(cls):
cls.skia = User.objects.get(username="skia")
# reffil skia's account
self.skia.customer.amount = 800
self.skia.customer.save()
cls.skia.customer.amount = 800
cls.skia.customer.save()
cls.refound_account_url = reverse("accounting:refound_account")
def test_permission_denied(self):
self.client.login(username="guy", password="plop")
self.client.force_login(User.objects.get(username="guy"))
response_post = self.client.post(
reverse("accounting:refound_account"), {"user": self.skia.id}
self.refound_account_url, {"user": self.skia.id}
)
response_get = self.client.get(reverse("accounting:refound_account"))
self.assertTrue(response_get.status_code == 403)
self.assertTrue(response_post.status_code == 403)
response_get = self.client.get(self.refound_account_url)
assert response_get.status_code == 403
assert response_post.status_code == 403
def test_root_granteed(self):
self.client.login(username="root", password="plop")
response_post = self.client.post(
reverse("accounting:refound_account"), {"user": self.skia.id}
)
self.skia = User.objects.filter(username="skia").first()
response_get = self.client.get(reverse("accounting:refound_account"))
self.assertFalse(response_get.status_code == 403)
self.assertTrue('<form action="" method="post">' in str(response_get.content))
self.assertFalse(response_post.status_code == 403)
self.assertTrue(self.skia.customer.amount == 0)
self.client.force_login(User.objects.get(username="root"))
response = self.client.post(self.refound_account_url, {"user": self.skia.id})
self.assertRedirects(response, self.refound_account_url)
self.skia.refresh_from_db()
response = self.client.get(self.refound_account_url)
assert response.status_code == 200
assert '<form action="" method="post">' in str(response.content)
assert self.skia.customer.amount == 0
def test_comptable_granteed(self):
self.client.login(username="comptable", password="plop")
response_post = self.client.post(
reverse("accounting:refound_account"), {"user": self.skia.id}
)
self.skia = User.objects.filter(username="skia").first()
response_get = self.client.get(reverse("accounting:refound_account"))
self.assertFalse(response_get.status_code == 403)
self.assertTrue('<form action="" method="post">' in str(response_get.content))
self.assertFalse(response_post.status_code == 403)
self.assertTrue(self.skia.customer.amount == 0)
self.client.force_login(User.objects.get(username="comptable"))
response = self.client.post(self.refound_account_url, {"user": self.skia.id})
self.assertRedirects(response, self.refound_account_url)
self.skia.refresh_from_db()
response = self.client.get(self.refound_account_url)
assert response.status_code == 200
assert '<form action="" method="post">' in str(response.content)
assert self.skia.customer.amount == 0
class JournalTest(TestCase):
def setUp(self):
self.journal = GeneralJournal.objects.filter(id=1).first()
@classmethod
def setUpTestData(cls):
cls.journal = GeneralJournal.objects.get(id=1)
def test_permission_granted(self):
self.client.login(username="comptable", password="plop")
self.client.force_login(User.objects.get(username="comptable"))
response_get = self.client.get(
reverse("accounting:journal_details", args=[self.journal.id])
)
self.assertTrue(response_get.status_code == 200)
self.assertTrue(
"<td>M\\xc3\\xa9thode de paiement</td>" in str(response_get.content)
)
assert response_get.status_code == 200
assert "<td>M\\xc3\\xa9thode de paiement</td>" in str(response_get.content)
def test_permission_not_granted(self):
self.client.login(username="skia", password="plop")
self.client.force_login(User.objects.get(username="skia"))
response_get = self.client.get(
reverse("accounting:journal_details", args=[self.journal.id])
)
self.assertTrue(response_get.status_code == 403)
self.assertFalse(
"<td>M\xc3\xa9thode de paiement</td>" in str(response_get.content)
)
assert response_get.status_code == 403
assert "<td>M\xc3\xa9thode de paiement</td>" not in str(response_get.content)
class OperationTest(TestCase):
@ -108,9 +103,8 @@ class OperationTest(TestCase):
code="443", label="Ce code n'existe pas", movement_type="CREDIT"
)
at.save()
l = Label(club_account=self.journal.club_account, name="bob")
l.save()
self.client.login(username="comptable", password="plop")
l = Label.objects.create(club_account=self.journal.club_account, name="bob")
self.client.force_login(User.objects.get(username="comptable"))
self.op1 = Operation(
journal=self.journal,
date=date.today(),
@ -139,8 +133,7 @@ class OperationTest(TestCase):
self.op2.save()
def test_new_operation(self):
self.client.login(username="comptable", password="plop")
at = AccountingType.objects.filter(code="604").first()
at = AccountingType.objects.get(code="604")
response = self.client.post(
reverse("accounting:op_new", args=[self.journal.id]),
{
@ -172,8 +165,7 @@ class OperationTest(TestCase):
self.assertTrue("<td>Le fantome de la nuit</td>" in str(response_get.content))
def test_bad_new_operation(self):
self.client.login(username="comptable", password="plop")
AccountingType.objects.filter(code="604").first()
AccountingType.objects.get(code="604")
response = self.client.post(
reverse("accounting:op_new", args=[self.journal.id]),
{
@ -199,7 +191,7 @@ class OperationTest(TestCase):
)
def test_new_operation_not_authorized(self):
self.client.login(username="skia", password="plop")
self.client.force_login(self.skia)
at = AccountingType.objects.filter(code="604").first()
response = self.client.post(
reverse("accounting:op_new", args=[self.journal.id]),
@ -226,7 +218,6 @@ class OperationTest(TestCase):
)
def test__operation_simple_accounting(self):
self.client.login(username="comptable", password="plop")
sat = SimplifiedAccountingType.objects.all().first()
response = self.client.post(
reverse("accounting:op_new", args=[self.journal.id]),
@ -263,14 +254,12 @@ class OperationTest(TestCase):
)
def test_nature_statement(self):
self.client.login(username="comptable", password="plop")
response = self.client.get(
reverse("accounting:journal_nature_statement", args=[self.journal.id])
)
self.assertContains(response, "bob (Troll Penché) : 3.00", status_code=200)
def test_person_statement(self):
self.client.login(username="comptable", password="plop")
response = self.client.get(
reverse("accounting:journal_person_statement", args=[self.journal.id])
)
@ -292,7 +281,6 @@ class OperationTest(TestCase):
)
def test_accounting_statement(self):
self.client.login(username="comptable", password="plop")
response = self.client.get(
reverse("accounting:journal_accounting_statement", args=[self.journal.id])
)

View File

@ -19,7 +19,7 @@ from django.conf import settings
from django.core.cache import cache
from django.test import TestCase
from django.urls import reverse
from django.utils import html, timezone
from django.utils import timezone
from django.utils.timezone import localtime, now
from django.utils.translation import gettext as _
@ -49,6 +49,7 @@ class ClubTest(TestCase):
cls.richard = User.objects.get(username="rbatsbak")
cls.comptable = User.objects.get(username="comptable")
cls.sli = User.objects.get(username="sli")
cls.root = User.objects.get(username="root")
# subscribed users - not initial members
cls.krophil = User.objects.get(username="krophil")
@ -102,45 +103,42 @@ class MembershipQuerySetTest(ClubTest):
Test that the ongoing queryset method returns the memberships that
are not ended.
"""
current_members = self.club.members.ongoing()
current_members = list(self.club.members.ongoing().order_by("id"))
expected = [
self.skia.memberships.get(club=self.club),
self.comptable.memberships.get(club=self.club),
self.richard.memberships.get(club=self.club),
]
self.assertEqual(len(current_members), len(expected))
for member in current_members:
self.assertIn(member, expected)
expected.sort(key=lambda i: i.id)
assert current_members == expected
def test_board(self):
"""
Test that the board queryset method returns the memberships
of user in the club board
"""
board_members = list(self.club.members.board())
board_members = list(self.club.members.board().order_by("id"))
expected = [
self.skia.memberships.get(club=self.club),
self.comptable.memberships.get(club=self.club),
# sli is no more member, but he was in the board
self.sli.memberships.get(club=self.club),
]
self.assertEqual(len(board_members), len(expected))
for member in board_members:
self.assertIn(member, expected)
expected.sort(key=lambda i: i.id)
assert board_members == expected
def test_ongoing_board(self):
"""
Test that combining ongoing and board returns users
who are currently board members of the club
"""
members = list(self.club.members.ongoing().board())
members = list(self.club.members.ongoing().board().order_by("id"))
expected = [
self.skia.memberships.get(club=self.club),
self.comptable.memberships.get(club=self.club),
]
self.assertEqual(len(members), len(expected))
for member in members:
self.assertIn(member, expected)
expected.sort(key=lambda i: i.id)
assert members == expected
def test_update_invalidate_cache(self):
"""
@ -149,8 +147,9 @@ class MembershipQuerySetTest(ClubTest):
mem_skia = self.skia.memberships.get(club=self.club)
cache.set(f"membership_{mem_skia.club_id}_{mem_skia.user_id}", mem_skia)
self.skia.memberships.update(end_date=localtime(now()).date())
self.assertEqual(
cache.get(f"membership_{mem_skia.club_id}_{mem_skia.user_id}"), "not_member"
assert (
cache.get(f"membership_{mem_skia.club_id}_{mem_skia.user_id}")
== "not_member"
)
mem_richard = self.richard.memberships.get(club=self.club)
@ -159,8 +158,8 @@ class MembershipQuerySetTest(ClubTest):
)
self.richard.memberships.update(role=5)
new_mem = self.richard.memberships.get(club=self.club)
self.assertNotEqual(new_mem, "not_member")
self.assertEqual(new_mem.role, 5)
assert new_mem != "not_member"
assert new_mem.role == 5
def test_delete_invalidate_cache(self):
"""
@ -177,40 +176,39 @@ class MembershipQuerySetTest(ClubTest):
# should delete the subscriptions of skia and comptable
self.club.members.ongoing().board().delete()
self.assertEqual(
cache.get(f"membership_{mem_skia.club_id}_{mem_skia.user_id}"), "not_member"
assert (
cache.get(f"membership_{mem_skia.club_id}_{mem_skia.user_id}")
== "not_member"
)
self.assertEqual(
cache.get(f"membership_{mem_comptable.club_id}_{mem_comptable.user_id}"),
"not_member",
assert (
cache.get(f"membership_{mem_comptable.club_id}_{mem_comptable.user_id}")
== "not_member",
)
class ClubModelTest(ClubTest):
def assert_membership_just_started(self, user: User, role: int):
def assert_membership_started_today(self, user: User, role: int):
"""
Assert that the given membership is active and started today
"""
membership = user.memberships.ongoing().filter(club=self.club).first()
self.assertIsNotNone(membership)
self.assertEqual(localtime(now()).date(), membership.start_date)
self.assertIsNone(membership.end_date)
self.assertEqual(membership.role, role)
self.assertEqual(membership.club.get_membership_for(user), membership)
assert membership is not None
assert localtime(now()).date() == membership.start_date
assert membership.end_date is None
assert membership.role == role
assert membership.club.get_membership_for(user) == membership
member_group = self.club.unix_name + settings.SITH_MEMBER_SUFFIX
board_group = self.club.unix_name + settings.SITH_BOARD_SUFFIX
self.assertTrue(user.is_in_group(name=member_group))
self.assertTrue(user.is_in_group(name=board_group))
assert user.is_in_group(name=member_group)
assert user.is_in_group(name=board_group)
def assert_membership_just_ended(self, user: User):
def assert_membership_ended_today(self, user: User):
"""
Assert that the given user have a membership which ended today
"""
today = localtime(now()).date()
self.assertIsNotNone(
user.memberships.filter(club=self.club, end_date=today).first()
)
self.assertIsNone(self.club.get_membership_for(user))
assert user.memberships.filter(club=self.club, end_date=today).exists()
assert self.club.get_membership_for(user) is None
def test_access_unauthorized(self):
"""
@ -218,20 +216,20 @@ class ClubModelTest(ClubTest):
cannot see the page
"""
response = self.client.post(self.members_url)
self.assertEqual(response.status_code, 403)
assert response.status_code == 403
self.client.login(username="public", password="plop")
self.client.force_login(self.public)
response = self.client.post(self.members_url)
self.assertEqual(response.status_code, 403)
assert response.status_code == 403
def test_display(self):
"""
Test that a GET request return a page where the requested
information are displayed.
"""
self.client.login(username=self.skia.username, password="plop")
self.client.force_login(self.skia)
response = self.client.get(self.members_url)
self.assertEqual(response.status_code, 200)
assert response.status_code == 200
expected_html = (
"<table><thead><tr>"
"<td>Utilisateur</td><td>Rôle</td><td>Description</td>"
@ -264,20 +262,20 @@ class ClubModelTest(ClubTest):
"""
Test that root users can add members to clubs, one at a time
"""
self.client.login(username="root", password="plop")
self.client.force_login(self.root)
response = self.client.post(
self.members_url,
{"users": self.subscriber.id, "role": 3},
)
self.assertRedirects(response, self.members_url)
self.subscriber.refresh_from_db()
self.assert_membership_just_started(self.subscriber, role=3)
self.assert_membership_started_today(self.subscriber, role=3)
def test_root_add_multiple_club_member(self):
"""
Test that root users can add multiple members at once to clubs
"""
self.client.login(username="root", password="plop")
self.client.force_login(self.root)
response = self.client.post(
self.members_url,
{
@ -287,36 +285,36 @@ class ClubModelTest(ClubTest):
)
self.assertRedirects(response, self.members_url)
self.subscriber.refresh_from_db()
self.assert_membership_just_started(self.subscriber, role=3)
self.assert_membership_just_started(self.krophil, role=3)
self.assert_membership_started_today(self.subscriber, role=3)
self.assert_membership_started_today(self.krophil, role=3)
def test_add_unauthorized_members(self):
"""
Test that users who are not currently subscribed
cannot be members of clubs.
"""
self.client.login(username="root", password="plop")
self.client.force_login(self.root)
response = self.client.post(
self.members_url,
{"users": self.public.id, "role": 1},
)
self.assertIsNone(self.public.memberships.filter(club=self.club).first())
self.assertTrue('<ul class="errorlist"><li>' in str(response.content))
assert not self.public.memberships.filter(club=self.club).exists()
assert '<ul class="errorlist"><li>' in response.content.decode()
response = self.client.post(
self.members_url,
{"users": self.old_subscriber.id, "role": 1},
)
self.assertIsNone(self.public.memberships.filter(club=self.club).first())
self.assertIsNone(self.club.get_membership_for(self.public))
self.assertTrue('<ul class="errorlist"><li>' in str(response.content))
assert not self.public.memberships.filter(club=self.club).exists()
assert self.club.get_membership_for(self.public) is None
assert '<ul class="errorlist"><li>' in response.content.decode()
def test_add_members_already_members(self):
"""
Test that users who are already members of a club
cannot be added again to this club
"""
self.client.login(username="root", password="plop")
self.client.force_login(self.root)
current_membership = self.skia.memberships.ongoing().get(club=self.club)
nb_memberships = self.skia.memberships.count()
self.client.post(
@ -324,10 +322,10 @@ class ClubModelTest(ClubTest):
{"users": self.skia.id, "role": current_membership.role + 1},
)
self.skia.refresh_from_db()
self.assertEqual(nb_memberships, self.skia.memberships.count())
assert nb_memberships == self.skia.memberships.count()
new_membership = self.skia.memberships.ongoing().get(club=self.club)
self.assertEqual(current_membership, new_membership)
self.assertEqual(self.club.get_membership_for(self.skia), new_membership)
assert current_membership == new_membership
assert self.club.get_membership_for(self.skia) == new_membership
def test_add_not_existing_users(self):
"""
@ -335,15 +333,16 @@ class ClubModelTest(ClubTest):
If one user in the request is invalid, no membership creation at all
can take place.
"""
self.client.login(username="root", password="plop")
self.client.force_login(self.root)
nb_memberships = self.club.members.count()
response = self.client.post(
self.members_url,
{"users": [9999], "role": 1},
)
self.assertContains(response, '<ul class="errorlist"><li>')
assert response.status_code == 200
assert '<ul class="errorlist"><li>' in response.content.decode()
self.club.refresh_from_db()
self.assertEqual(self.club.members.count(), nb_memberships)
assert self.club.members.count() == nb_memberships
response = self.client.post(
self.members_url,
{
@ -352,9 +351,10 @@ class ClubModelTest(ClubTest):
"role": 3,
},
)
self.assertContains(response, '<ul class="errorlist"><li>')
assert response.status_code == 200
assert '<ul class="errorlist"><li>' in response.content.decode()
self.club.refresh_from_db()
self.assertEqual(self.club.members.count(), nb_memberships)
assert self.club.members.count() == nb_memberships
def test_president_add_members(self):
"""
@ -363,7 +363,7 @@ class ClubModelTest(ClubTest):
president = self.club.members.get(role=10).user
nb_club_membership = self.club.members.count()
nb_subscriber_memberships = self.subscriber.memberships.count()
self.client.login(username=president.username, password="plop")
self.client.force_login(president)
response = self.client.post(
self.members_url,
{"users": self.subscriber.id, "role": 9},
@ -371,56 +371,55 @@ class ClubModelTest(ClubTest):
self.assertRedirects(response, self.members_url)
self.club.refresh_from_db()
self.subscriber.refresh_from_db()
self.assertEqual(self.club.members.count(), nb_club_membership + 1)
self.assertEqual(
self.subscriber.memberships.count(), nb_subscriber_memberships + 1
)
self.assert_membership_just_started(self.subscriber, role=9)
assert self.club.members.count() == nb_club_membership + 1
assert self.subscriber.memberships.count() == nb_subscriber_memberships + 1
self.assert_membership_started_today(self.subscriber, role=9)
def test_add_member_greater_role(self):
"""
Test that a member of the club member cannot create
a membership with a greater role than its own.
"""
self.client.login(username=self.skia.username, password="plop")
self.client.force_login(self.skia)
nb_memberships = self.club.members.count()
response = self.client.post(
self.members_url,
{"users": self.subscriber.id, "role": 10},
)
self.assertEqual(response.status_code, 200)
assert response.status_code == 200
self.assertInHTML(
"<li>Vous n'avez pas la permission de faire cela</li>",
response.content.decode(),
)
self.club.refresh_from_db()
self.assertEqual(nb_memberships, self.club.members.count())
self.assertIsNone(self.subscriber.memberships.filter(club=self.club).first())
assert nb_memberships == self.club.members.count()
assert not self.subscriber.memberships.filter(club=self.club).exists()
def test_add_member_without_role(self):
"""
Test that trying to add members without specifying their role fails
"""
self.client.login(username="root", password="plop")
self.client.force_login(self.root)
response = self.client.post(
self.members_url,
{"users": self.subscriber.id, "start_date": "12/06/2016"},
)
self.assertTrue(
'<ul class="errorlist"><li>Vous devez choisir un r' in str(response.content)
assert (
'<ul class="errorlist"><li>Vous devez choisir un r'
in response.content.decode()
)
def test_end_membership_self(self):
"""
Test that a member can end its own membership
"""
self.client.login(username="skia", password="plop")
self.client.force_login(self.skia)
self.client.post(
self.members_url,
{"users_old": self.skia.id},
)
self.skia.refresh_from_db()
self.assert_membership_just_ended(self.skia)
self.assert_membership_ended_today(self.skia)
def test_end_membership_lower_role(self):
"""
@ -428,14 +427,14 @@ class ClubModelTest(ClubTest):
of users with lower roles
"""
# remainder : skia has role 3, comptable has role 10, richard has role 1
self.client.login(username=self.skia.username, password="plop")
self.client.force_login(self.skia)
response = self.client.post(
self.members_url,
{"users_old": self.richard.id},
)
self.assertRedirects(response, self.members_url)
self.club.refresh_from_db()
self.assert_membership_just_ended(self.richard)
self.assert_membership_ended_today(self.richard)
def test_end_membership_higher_role(self):
"""
@ -443,18 +442,18 @@ class ClubModelTest(ClubTest):
of users with higher roles
"""
membership = self.comptable.memberships.filter(club=self.club).first()
self.client.login(username=self.skia.username, password="plop")
self.client.force_login(self.skia)
self.client.post(
self.members_url,
{"users_old": self.comptable.id},
)
self.club.refresh_from_db()
new_membership = self.club.get_membership_for(self.comptable)
self.assertIsNotNone(new_membership)
self.assertEqual(new_membership, membership)
assert new_membership is not None
assert new_membership == membership
membership = self.comptable.memberships.filter(club=self.club).first()
self.assertIsNone(membership.end_date)
assert membership.end_date is None
def test_end_membership_as_main_club_board(self):
"""
@ -466,29 +465,29 @@ class ClubModelTest(ClubTest):
Membership.objects.create(club=self.ae, user=self.subscriber, role=3)
nb_memberships = self.club.members.count()
self.client.login(username=self.subscriber.username, password="plop")
self.client.force_login(self.subscriber)
response = self.client.post(
self.members_url,
{"users_old": self.comptable.id},
)
self.assertRedirects(response, self.members_url)
self.assert_membership_just_ended(self.comptable)
self.assertEqual(self.club.members.ongoing().count(), nb_memberships - 1)
self.assert_membership_ended_today(self.comptable)
assert self.club.members.ongoing().count() == nb_memberships - 1
def test_end_membership_as_root(self):
"""
Test that root users can end the membership of anyone
"""
nb_memberships = self.club.members.count()
self.client.login(username="root", password="plop")
self.client.force_login(self.root)
response = self.client.post(
self.members_url,
{"users_old": [self.comptable.id]},
)
self.assertRedirects(response, self.members_url)
self.assert_membership_just_ended(self.comptable)
self.assertEqual(self.club.members.ongoing().count(), nb_memberships - 1)
self.assertEqual(self.club.members.count(), nb_memberships)
self.assert_membership_ended_today(self.comptable)
assert self.club.members.ongoing().count() == nb_memberships - 1
assert self.club.members.count() == nb_memberships
def test_end_membership_as_foreigner(self):
"""
@ -496,16 +495,15 @@ class ClubModelTest(ClubTest):
"""
nb_memberships = self.club.members.count()
membership = self.richard.memberships.filter(club=self.club).first()
self.client.login(username="subscriber", password="root")
self.client.force_login(self.subscriber)
self.client.post(
self.members_url,
{"users_old": [self.richard.id]},
)
# nothing should have changed
new_mem = self.club.get_membership_for(self.richard)
self.assertIsNotNone(new_mem)
self.assertEqual(self.club.members.count(), nb_memberships)
self.assertEqual(membership, new_mem)
assert self.club.members.count() == nb_memberships
assert membership == new_mem
def test_delete_remove_from_meta_group(self):
"""
@ -518,7 +516,7 @@ class ClubModelTest(ClubTest):
self.club.delete()
for user in users:
self.assertFalse(user.is_in_group(name=meta_group))
assert not user.is_in_group(name=meta_group)
def test_add_to_meta_group(self):
"""
@ -526,11 +524,11 @@ class ClubModelTest(ClubTest):
"""
group_members = self.club.unix_name + settings.SITH_MEMBER_SUFFIX
board_members = self.club.unix_name + settings.SITH_BOARD_SUFFIX
self.assertFalse(self.subscriber.is_in_group(name=group_members))
self.assertFalse(self.subscriber.is_in_group(name=board_members))
assert not self.subscriber.is_in_group(name=group_members)
assert not self.subscriber.is_in_group(name=board_members)
Membership.objects.create(club=self.club, user=self.subscriber, role=3)
self.assertTrue(self.subscriber.is_in_group(name=group_members))
self.assertTrue(self.subscriber.is_in_group(name=board_members))
assert self.subscriber.is_in_group(name=group_members)
assert self.subscriber.is_in_group(name=board_members)
def test_remove_from_meta_group(self):
"""
@ -538,24 +536,24 @@ class ClubModelTest(ClubTest):
"""
group_members = self.club.unix_name + settings.SITH_MEMBER_SUFFIX
board_members = self.club.unix_name + settings.SITH_BOARD_SUFFIX
self.assertTrue(self.comptable.is_in_group(name=group_members))
self.assertTrue(self.comptable.is_in_group(name=board_members))
assert self.comptable.is_in_group(name=group_members)
assert self.comptable.is_in_group(name=board_members)
self.comptable.memberships.update(end_date=localtime(now()))
self.assertFalse(self.comptable.is_in_group(name=group_members))
self.assertFalse(self.comptable.is_in_group(name=board_members))
assert not self.comptable.is_in_group(name=group_members)
assert not self.comptable.is_in_group(name=board_members)
def test_club_owner(self):
"""
Test that a club is owned only by board members of the main club
"""
anonymous = AnonymousUser()
self.assertFalse(self.club.is_owned_by(anonymous))
self.assertFalse(self.club.is_owned_by(self.subscriber))
assert not self.club.is_owned_by(anonymous)
assert not self.club.is_owned_by(self.subscriber)
# make sli a board member
self.sli.memberships.all().delete()
Membership(club=self.ae, user=self.sli, role=3).save()
self.assertTrue(self.club.is_owned_by(self.sli))
assert self.club.is_owned_by(self.sli)
class MailingFormTest(TestCase):
@ -563,11 +561,13 @@ class MailingFormTest(TestCase):
@classmethod
def setUpTestData(cls):
cls.skia = User.objects.filter(username="skia").first()
cls.rbatsbak = User.objects.filter(username="rbatsbak").first()
cls.krophil = User.objects.filter(username="krophil").first()
cls.comunity = User.objects.filter(username="comunity").first()
cls.bdf = Club.objects.filter(unix_name=SITH_BAR_MANAGER["unix_name"]).first()
cls.skia = User.objects.get(username="skia")
cls.rbatsbak = User.objects.get(username="rbatsbak")
cls.krophil = User.objects.get(username="krophil")
cls.comunity = User.objects.get(username="comunity")
cls.root = User.objects.get(username="root")
cls.bdf = Club.objects.get(unix_name=SITH_BAR_MANAGER["unix_name"])
cls.mail_url = reverse("club:mailing", kwargs={"club_id": cls.bdf.id})
def setUp(self):
Membership(
@ -579,134 +579,125 @@ class MailingFormTest(TestCase):
def test_mailing_list_add_no_moderation(self):
# Test with Communication admin
self.client.login(username="comunity", password="plop")
self.client.post(
reverse("club:mailing", kwargs={"club_id": self.bdf.id}),
self.client.force_login(self.comunity)
response = self.client.post(
self.mail_url,
{"action": MailingForm.ACTION_NEW_MAILING, "mailing_email": "foyer"},
)
response = self.client.get(
reverse("club:mailing", kwargs={"club_id": self.bdf.id})
)
self.assertContains(response, text="Liste de diffusion foyer@utbm.fr")
self.assertRedirects(response, self.mail_url)
response = self.client.get(self.mail_url)
assert response.status_code == 200
assert "Liste de diffusion foyer@utbm.fr" in response.content.decode()
# Test with Root
self.client.login(username="root", password="plop")
self.client.force_login(self.root)
self.client.post(
reverse("club:mailing", kwargs={"club_id": self.bdf.id}),
self.mail_url,
{"action": MailingForm.ACTION_NEW_MAILING, "mailing_email": "mde"},
)
response = self.client.get(
reverse("club:mailing", kwargs={"club_id": self.bdf.id})
)
self.assertContains(response, text="Liste de diffusion mde@utbm.fr")
response = self.client.get(self.mail_url)
assert response.status_code == 200
assert "Liste de diffusion mde@utbm.fr" in response.content.decode()
def test_mailing_list_add_moderation(self):
self.client.login(username="rbatsbak", password="plop")
self.client.force_login(self.rbatsbak)
self.client.post(
reverse("club:mailing", kwargs={"club_id": self.bdf.id}),
self.mail_url,
{"action": MailingForm.ACTION_NEW_MAILING, "mailing_email": "mde"},
)
response = self.client.get(
reverse("club:mailing", kwargs={"club_id": self.bdf.id})
)
self.assertNotContains(response, text="Liste de diffusion mde@utbm.fr")
self.assertContains(
response, text="<p>Listes de diffusions en attente de modération</p>"
)
self.assertContains(response, "<li>mde@utbm.fr")
response = self.client.get(self.mail_url)
assert response.status_code == 200
content = response.content.decode()
assert "Liste de diffusion mde@utbm.fr" not in content
assert "<p>Listes de diffusions en attente de modération</p>" in content
assert "<li>mde@utbm.fr" in content
def test_mailing_list_forbidden(self):
# With anonymous user
response = self.client.get(
reverse("club:mailing", kwargs={"club_id": self.bdf.id})
)
response = self.client.get(self.mail_url)
self.assertContains(response, "", status_code=403)
# With user not in club
self.client.login(username="krophil", password="plop")
response = self.client.get(
reverse("club:mailing", kwargs={"club_id": self.bdf.id})
)
self.assertContains(response, "", status_code=403)
self.client.force_login(self.krophil)
response = self.client.get(self.mail_url)
assert response.status_code == 403
def test_add_new_subscription_fail_not_moderated(self):
self.client.login(username="rbatsbak", password="plop")
self.client.force_login(self.rbatsbak)
self.client.post(
reverse("club:mailing", kwargs={"club_id": self.bdf.id}),
self.mail_url,
{"action": MailingForm.ACTION_NEW_MAILING, "mailing_email": "mde"},
)
self.client.post(
reverse("club:mailing", kwargs={"club_id": self.bdf.id}),
self.mail_url,
{
"action": MailingForm.ACTION_NEW_SUBSCRIPTION,
"subscription_users": self.skia.id,
"subscription_mailing": Mailing.objects.get(email="mde").id,
},
)
response = self.client.get(
reverse("club:mailing", kwargs={"club_id": self.bdf.id})
)
self.assertNotContains(response, "skia@git.an")
response = self.client.get(self.mail_url)
assert response.status_code == 200
assert "skia@git.an" not in response.content.decode()
def test_add_new_subscription_success(self):
# Prepare mailing list
self.client.login(username="comunity", password="plop")
self.client.force_login(self.comunity)
self.client.post(
reverse("club:mailing", kwargs={"club_id": self.bdf.id}),
self.mail_url,
{"action": MailingForm.ACTION_NEW_MAILING, "mailing_email": "mde"},
)
# Add single user
self.client.post(
reverse("club:mailing", kwargs={"club_id": self.bdf.id}),
self.mail_url,
{
"action": MailingForm.ACTION_NEW_SUBSCRIPTION,
"subscription_users": self.skia.id,
"subscription_mailing": Mailing.objects.get(email="mde").id,
},
)
response = self.client.get(
reverse("club:mailing", kwargs={"club_id": self.bdf.id})
)
self.assertContains(response, "skia@git.an")
response = self.client.get(self.mail_url)
assert response.status_code == 200
assert "skia@git.an" in response.content.decode()
# Add multiple users
self.client.post(
reverse("club:mailing", kwargs={"club_id": self.bdf.id}),
self.mail_url,
{
"action": MailingForm.ACTION_NEW_SUBSCRIPTION,
"subscription_users": "|%s|%s|" % (self.comunity.id, self.rbatsbak.id),
"subscription_mailing": Mailing.objects.get(email="mde").id,
},
)
response = self.client.get(
reverse("club:mailing", kwargs={"club_id": self.bdf.id})
)
self.assertContains(response, "richard@git.an")
self.assertContains(response, "comunity@git.an")
self.assertContains(response, "skia@git.an")
response = self.client.get(self.mail_url)
assert response.status_code == 200
content = response.content.decode()
assert "richard@git.an" in content
assert "comunity@git.an" in content
assert "skia@git.an" in content
# Add arbitrary email
self.client.post(
reverse("club:mailing", kwargs={"club_id": self.bdf.id}),
self.mail_url,
{
"action": MailingForm.ACTION_NEW_SUBSCRIPTION,
"subscription_email": "arbitrary@git.an",
"subscription_mailing": Mailing.objects.get(email="mde").id,
},
)
response = self.client.get(
reverse("club:mailing", kwargs={"club_id": self.bdf.id})
)
self.assertContains(response, "richard@git.an")
self.assertContains(response, "comunity@git.an")
self.assertContains(response, "skia@git.an")
self.assertContains(response, "arbitrary@git.an")
response = self.client.get(self.mail_url)
assert response.status_code == 200
content = response.content.decode()
assert "richard@git.an" in content
assert "comunity@git.an" in content
assert "skia@git.an" in content
assert "arbitrary@git.an" in content
# Add user and arbitrary email
self.client.post(
reverse("club:mailing", kwargs={"club_id": self.bdf.id}),
self.mail_url,
{
"action": MailingForm.ACTION_NEW_SUBSCRIPTION,
"subscription_email": "more.arbitrary@git.an",
@ -714,57 +705,61 @@ class MailingFormTest(TestCase):
"subscription_mailing": Mailing.objects.get(email="mde").id,
},
)
response = self.client.get(
reverse("club:mailing", kwargs={"club_id": self.bdf.id})
)
self.assertContains(response, "richard@git.an")
self.assertContains(response, "comunity@git.an")
self.assertContains(response, "skia@git.an")
self.assertContains(response, "arbitrary@git.an")
self.assertContains(response, "more.arbitrary@git.an")
self.assertContains(response, "krophil@git.an")
response = self.client.get(self.mail_url)
assert response.status_code == 200
content = response.content.decode()
assert "richard@git.an" in content
assert "comunity@git.an" in content
assert "skia@git.an" in content
assert "arbitrary@git.an" in content
assert "more.arbitrary@git.an" in content
assert "krophil@git.an" in content
def test_add_new_subscription_fail_form_errors(self):
# Prepare mailing list
self.client.login(username="comunity", password="plop")
self.client.force_login(self.comunity)
self.client.post(
reverse("club:mailing", kwargs={"club_id": self.bdf.id}),
self.mail_url,
{"action": MailingForm.ACTION_NEW_MAILING, "mailing_email": "mde"},
)
# Neither email or email is specified
response = self.client.post(
reverse("club:mailing", kwargs={"club_id": self.bdf.id}),
self.mail_url,
{
"action": MailingForm.ACTION_NEW_SUBSCRIPTION,
"subscription_mailing": Mailing.objects.get(email="mde").id,
},
)
self.assertContains(
response, text=_("You must specify at least an user or an email address")
assert response.status_code
self.assertInHTML(
_("You must specify at least an user or an email address"),
response.content.decode(),
)
# No mailing specified
response = self.client.post(
reverse("club:mailing", kwargs={"club_id": self.bdf.id}),
self.mail_url,
{
"action": MailingForm.ACTION_NEW_SUBSCRIPTION,
"subscription_users": self.krophil.id,
},
)
self.assertContains(response, text=_("This field is required"))
assert response.status_code == 200
assert _("This field is required") in response.content.decode()
# One of the selected users doesn't exist
response = self.client.post(
reverse("club:mailing", kwargs={"club_id": self.bdf.id}),
self.mail_url,
{
"action": MailingForm.ACTION_NEW_SUBSCRIPTION,
"subscription_users": "|789|",
"subscription_mailing": Mailing.objects.get(email="mde").id,
},
)
self.assertContains(
response, text=html.escape(_("One of the selected users doesn't exist"))
assert response.status_code == 200
self.assertInHTML(
_("One of the selected users doesn't exist"), response.content.decode()
)
# An user has no email adress
@ -772,18 +767,17 @@ class MailingFormTest(TestCase):
self.krophil.save()
response = self.client.post(
reverse("club:mailing", kwargs={"club_id": self.bdf.id}),
self.mail_url,
{
"action": MailingForm.ACTION_NEW_SUBSCRIPTION,
"subscription_users": self.krophil.id,
"subscription_mailing": Mailing.objects.get(email="mde").id,
},
)
self.assertContains(
response,
text=html.escape(
_("One of the selected users doesn't have an email address")
),
assert response.status_code == 200
self.assertInHTML(
_("One of the selected users doesn't have an email address"),
response.content.decode(),
)
self.krophil.email = "krophil@git.an"
@ -792,7 +786,7 @@ class MailingFormTest(TestCase):
# An user is added twice
self.client.post(
reverse("club:mailing", kwargs={"club_id": self.bdf.id}),
self.mail_url,
{
"action": MailingForm.ACTION_NEW_SUBSCRIPTION,
"subscription_users": self.krophil.id,
@ -801,28 +795,29 @@ class MailingFormTest(TestCase):
)
response = self.client.post(
reverse("club:mailing", kwargs={"club_id": self.bdf.id}),
self.mail_url,
{
"action": MailingForm.ACTION_NEW_SUBSCRIPTION,
"subscription_users": self.krophil.id,
"subscription_mailing": Mailing.objects.get(email="mde").id,
},
)
self.assertContains(
response,
text=html.escape(_("This email is already suscribed in this mailing")),
assert response.status_code == 200
self.assertInHTML(
_("This email is already suscribed in this mailing"),
response.content.decode(),
)
def test_remove_subscription_success(self):
# Prepare mailing list
self.client.login(username="comunity", password="plop")
self.client.force_login(self.comunity)
self.client.post(
reverse("club:mailing", kwargs={"club_id": self.bdf.id}),
self.mail_url,
{"action": MailingForm.ACTION_NEW_MAILING, "mailing_email": "mde"},
)
mde = Mailing.objects.get(email="mde")
self.client.post(
reverse("club:mailing", kwargs={"club_id": self.bdf.id}),
self.mail_url,
{
"action": MailingForm.ACTION_NEW_SUBSCRIPTION,
"subscription_users": "|%s|%s|%s|"
@ -831,33 +826,33 @@ class MailingFormTest(TestCase):
},
)
response = self.client.get(
reverse("club:mailing", kwargs={"club_id": self.bdf.id})
)
response = self.client.get(self.mail_url)
assert response.status_code == 200
content = response.content.decode()
self.assertContains(response, "comunity@git.an")
self.assertContains(response, "richard@git.an")
self.assertContains(response, "krophil@git.an")
assert "comunity@git.an" in content
assert "richard@git.an" in content
assert "krophil@git.an" in content
# Delete one user
self.client.post(
reverse("club:mailing", kwargs={"club_id": self.bdf.id}),
self.mail_url,
{
"action": MailingForm.ACTION_REMOVE_SUBSCRIPTION,
"removal_%d" % mde.id: mde.subscriptions.get(user=self.krophil).id,
},
)
response = self.client.get(
reverse("club:mailing", kwargs={"club_id": self.bdf.id})
)
response = self.client.get(self.mail_url)
assert response.status_code == 200
content = response.content.decode()
self.assertContains(response, "comunity@git.an")
self.assertContains(response, "richard@git.an")
self.assertNotContains(response, "krophil@git.an")
assert "comunity@git.an" in content
assert "richard@git.an" in content
assert "krophil@git.an" not in content
# Delete multiple users
self.client.post(
reverse("club:mailing", kwargs={"club_id": self.bdf.id}),
self.mail_url,
{
"action": MailingForm.ACTION_REMOVE_SUBSCRIPTION,
"removal_%d" % mde.id: [
@ -868,13 +863,13 @@ class MailingFormTest(TestCase):
],
},
)
response = self.client.get(
reverse("club:mailing", kwargs={"club_id": self.bdf.id})
)
response = self.client.get(self.mail_url)
assert response.status_code == 200
content = response.content.decode()
self.assertNotContains(response, "comunity@git.an")
self.assertNotContains(response, "richard@git.an")
self.assertNotContains(response, "krophil@git.an")
assert "comunity@git.an" not in content
assert "richard@git.an" not in content
assert "krophil@git.an" not in content
class ClubSellingViewTest(TestCase):
@ -882,15 +877,17 @@ class ClubSellingViewTest(TestCase):
Perform basics tests to ensure that the page is available
"""
def setUp(self):
self.ae = Club.objects.filter(unix_name="ae").first()
@classmethod
def setUpTestData(cls):
cls.ae = Club.objects.get(unix_name="ae")
cls.skia = User.objects.get(username="skia")
def test_page_not_internal_error(self):
"""
Test that the page does not return and internal error
"""
self.client.login(username="skia", password="plop")
self.client.force_login(self.skia)
response = self.client.get(
reverse("club:club_sellings", kwargs={"club_id": self.ae.id})
)
self.assertFalse(response.status_code == 500)
assert response.status_code == 200

View File

@ -603,7 +603,7 @@ class ClubMailingView(ClubTabsMixin, CanEditMixin, DetailFormView):
}
return kwargs
def add_new_mailing(self, cleaned_data) -> ValidationError:
def add_new_mailing(self, cleaned_data) -> ValidationError | None:
"""
Create a new mailing list from the form
"""
@ -620,7 +620,7 @@ class ClubMailingView(ClubTabsMixin, CanEditMixin, DetailFormView):
mailing.save()
return None
def add_new_subscription(self, cleaned_data) -> ValidationError:
def add_new_subscription(self, cleaned_data) -> ValidationError | None:
"""
Add mailing subscriptions for each user given and/or for the specified email in form
"""

View File

@ -13,6 +13,7 @@
# OR WITHIN THE LOCAL FILE "LICENSE"
#
#
import pytest
from django.conf import settings
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase
@ -26,37 +27,39 @@ from com.models import News, Poster, Sith, Weekmail, WeekmailArticle
from core.models import AnonymousUser, RealGroup, User
class ComAlertTest(TestCase):
def test_page_is_working(self):
self.client.login(username="comunity", password="plop")
response = self.client.get(reverse("com:alert_edit"))
self.assertNotEqual(response.status_code, 500)
self.assertEqual(response.status_code, 200)
@pytest.fixture()
def user_community():
return User.objects.get(username="comunity")
class ComInfoTest(TestCase):
def test_page_is_working(self):
self.client.login(username="comunity", password="plop")
response = self.client.get(reverse("com:info_edit"))
self.assertNotEqual(response.status_code, 500)
self.assertEqual(response.status_code, 200)
@pytest.mark.django_db
@pytest.mark.parametrize(
"url",
[
reverse("com:alert_edit"),
reverse("com:info_edit"),
],
)
def test_com_page_is_working(client, url, user_community):
client.force_login(user_community)
response = client.get(url)
assert response.status_code == 200
class ComTest(TestCase):
@classmethod
def setUpTestData(cls):
cls.skia = User.objects.filter(username="skia").first()
cls.skia = User.objects.get(username="skia")
cls.com_group = RealGroup.objects.filter(
id=settings.SITH_GROUP_COM_ADMIN_ID
).first()
cls.skia.groups.set([cls.com_group])
cls.skia.save()
def setUp(self):
self.client.login(username=self.skia.username, password="plop")
self.client.force_login(self.skia)
def test_alert_msg(self):
response = self.client.post(
self.client.post(
reverse("com:alert_edit"),
{
"alert_msg": """
@ -67,7 +70,6 @@ class ComTest(TestCase):
},
)
r = self.client.get(reverse("core:index"))
self.assertTrue(r.status_code == 200)
self.assertContains(
r,
"""<div id="alert_box">
@ -76,7 +78,7 @@ class ComTest(TestCase):
)
def test_info_msg(self):
response = self.client.post(
self.client.post(
reverse("com:info_edit"),
{
"info_msg": """
@ -85,7 +87,6 @@ class ComTest(TestCase):
},
)
r = self.client.get(reverse("core:index"))
self.assertTrue(r.status_code == 200)
self.assertContains(
r,
"""<div id="info_box">
@ -93,7 +94,7 @@ class ComTest(TestCase):
)
def test_birthday_non_subscribed_user(self):
self.client.login(username="guy", password="plop")
self.client.force_login(User.objects.get(username="guy"))
response = self.client.get(reverse("core:index"))
self.assertContains(
response,
@ -122,13 +123,13 @@ class SithTest(TestCase):
sith: Sith = Sith.objects.first()
com_admin = User.objects.get(username="comunity")
self.assertTrue(sith.is_owned_by(com_admin))
assert sith.is_owned_by(com_admin)
anonymous = AnonymousUser()
self.assertFalse(sith.is_owned_by(anonymous))
assert not sith.is_owned_by(anonymous)
sli = User.objects.get(username="sli")
self.assertFalse(sith.is_owned_by(sli))
assert not sith.is_owned_by(sli)
class NewsTest(TestCase):
@ -153,10 +154,10 @@ class NewsTest(TestCase):
or by their author but nobody else
"""
self.assertTrue(self.new.is_owned_by(self.com_admin))
self.assertTrue(self.new.is_owned_by(self.author))
self.assertFalse(self.new.is_owned_by(self.anonymous))
self.assertFalse(self.new.is_owned_by(self.sli))
assert self.new.is_owned_by(self.com_admin)
assert self.new.is_owned_by(self.author)
assert not self.new.is_owned_by(self.anonymous)
assert not self.new.is_owned_by(self.sli)
def test_news_viewer(self):
"""
@ -164,26 +165,26 @@ class NewsTest(TestCase):
and not moderated news only by com admins
"""
# by default a news isn't moderated
self.assertTrue(self.new.can_be_viewed_by(self.com_admin))
self.assertFalse(self.new.can_be_viewed_by(self.sli))
self.assertFalse(self.new.can_be_viewed_by(self.anonymous))
self.assertFalse(self.new.can_be_viewed_by(self.author))
assert self.new.can_be_viewed_by(self.com_admin)
assert not self.new.can_be_viewed_by(self.sli)
assert not self.new.can_be_viewed_by(self.anonymous)
assert not self.new.can_be_viewed_by(self.author)
self.new.is_moderated = True
self.new.save()
self.assertTrue(self.new.can_be_viewed_by(self.com_admin))
self.assertTrue(self.new.can_be_viewed_by(self.sli))
self.assertTrue(self.new.can_be_viewed_by(self.anonymous))
self.assertTrue(self.new.can_be_viewed_by(self.author))
assert self.new.can_be_viewed_by(self.com_admin)
assert self.new.can_be_viewed_by(self.sli)
assert self.new.can_be_viewed_by(self.anonymous)
assert self.new.can_be_viewed_by(self.author)
def test_news_editor(self):
"""
Test that only com admins can edit news
"""
self.assertTrue(self.new.can_be_edited_by(self.com_admin))
self.assertFalse(self.new.can_be_edited_by(self.sli))
self.assertFalse(self.new.can_be_edited_by(self.anonymous))
self.assertFalse(self.new.can_be_edited_by(self.author))
assert self.new.can_be_edited_by(self.com_admin)
assert not self.new.can_be_edited_by(self.sli)
assert not self.new.can_be_edited_by(self.anonymous)
assert not self.new.can_be_edited_by(self.author)
class WeekmailArticleTest(TestCase):
@ -206,10 +207,10 @@ class WeekmailArticleTest(TestCase):
"""
Test that weekmails are owned only by com admins
"""
self.assertTrue(self.article.is_owned_by(self.com_admin))
self.assertFalse(self.article.is_owned_by(self.author))
self.assertFalse(self.article.is_owned_by(self.anonymous))
self.assertFalse(self.article.is_owned_by(self.sli))
assert self.article.is_owned_by(self.com_admin)
assert not self.article.is_owned_by(self.author)
assert not self.article.is_owned_by(self.anonymous)
assert not self.article.is_owned_by(self.sli)
class PosterTest(TestCase):
@ -232,8 +233,8 @@ class PosterTest(TestCase):
"""
Test that poster are owned by com admins and board members in clubs
"""
self.assertTrue(self.poster.is_owned_by(self.com_admin))
self.assertFalse(self.poster.is_owned_by(self.anonymous))
assert self.poster.is_owned_by(self.com_admin)
assert not self.poster.is_owned_by(self.anonymous)
self.assertFalse(self.poster.is_owned_by(self.susbcriber))
self.assertTrue(self.poster.is_owned_by(self.sli))
assert not self.poster.is_owned_by(self.susbcriber)
assert self.poster.is_owned_by(self.sli)

14
conftest.py Normal file
View File

@ -0,0 +1,14 @@
import pytest
from django.core.management import call_command
from django.utils.translation import activate
@pytest.fixture(scope="session")
def django_db_setup(django_db_setup, django_db_blocker):
with django_db_blocker.unblock():
call_command("setup")
@pytest.fixture(scope="session", autouse=True)
def set_default_language():
activate("fr")

View File

@ -18,10 +18,12 @@ import os
from datetime import date, timedelta
import freezegun
import pytest
from django.core.cache import cache
from django.test import Client, TestCase
from django.test import TestCase
from django.urls import reverse
from django.utils.timezone import now
from pytest_django.asserts import assertRedirects
from club.models import Membership
from core.markdown import markdown
@ -29,270 +31,105 @@ from core.models import AnonymousUser, Group, Page, User
from core.utils import get_semester_code, get_start_of_semester
from sith import settings
"""
to run these tests :
python3 manage.py test
"""
@pytest.mark.django_db
class TestUserRegistration:
@pytest.fixture()
def valid_payload(self):
return {
"first_name": "this user does not exist (yet)",
"last_name": "this user does not exist (yet)",
"email": "i-dont-exist-yet@git.an",
"password1": "plop",
"password2": "plop",
"captcha_0": "dummy-value",
"captcha_1": "PASSED",
}
def test_register_user_form_ok(self, client, valid_payload):
"""Should register a user correctly."""
response = client.post(reverse("core:register"), valid_payload)
assert response.status_code == 200
assert "TEST_REGISTER_USER_FORM_OK" in str(response.content)
@pytest.mark.parametrize(
"payload_edit",
[
{"password2": "not the same as password1"},
{"email": "not-an-email"},
{"first_name": ""},
{"last_name": ""},
{"captcha_1": "WRONG_CAPTCHA"},
],
)
def test_register_user_form_fail(self, client, valid_payload, payload_edit):
"""Should not register a user correctly."""
payload = valid_payload | payload_edit
response = client.post(reverse("core:register"), payload)
assert response.status_code == 200
assert "TEST_REGISTER_USER_FORM_FAIL" in str(response.content)
def test_register_user_form_fail_already_exists(self, client, valid_payload):
"""Should not register a user correctly if it already exists."""
# create the user, then try to create it again
client.post(reverse("core:register"), valid_payload)
response = client.post(reverse("core:register"), valid_payload)
assert response.status_code == 200
assert "TEST_REGISTER_USER_FORM_FAIL" in str(response.content)
class UserRegistrationTest(TestCase):
@classmethod
def setUpTestData(cls):
User.objects.all().delete()
@pytest.mark.django_db
class TestUserLogin:
@pytest.fixture()
def user(self) -> User:
return User.objects.first()
def test_register_user_form_ok(self):
"""
Should register a user correctly
"""
c = Client()
response = c.post(
reverse("core:register"),
{
"first_name": "Guy",
"last_name": "Carlier",
"email": "guy@git.an",
"date_of_birth": "12/6/1942",
"password1": "plop",
"password2": "plop",
"captcha_0": "dummy-value",
"captcha_1": "PASSED",
},
)
self.assertTrue(response.status_code == 200)
self.assertTrue("TEST_REGISTER_USER_FORM_OK" in str(response.content))
def test_register_user_form_fail_password(self):
"""
Should not register a user correctly
"""
c = Client()
response = c.post(
reverse("core:register"),
{
"first_name": "Guy",
"last_name": "Carlier",
"email": "bibou@git.an",
"date_of_birth": "12/6/1942",
"password1": "plop",
"password2": "plop2",
"captcha_0": "dummy-value",
"captcha_1": "PASSED",
},
)
self.assertTrue(response.status_code == 200)
self.assertTrue("TEST_REGISTER_USER_FORM_FAIL" in str(response.content))
def test_register_user_form_fail_email(self):
"""
Should not register a user correctly
"""
c = Client()
response = c.post(
reverse("core:register"),
{
"first_name": "Guy",
"last_name": "Carlier",
"email": "bibou.git.an",
"date_of_birth": "12/6/1942",
"password1": "plop",
"password2": "plop",
"captcha_0": "dummy-value",
"captcha_1": "PASSED",
},
)
self.assertTrue(response.status_code == 200)
self.assertTrue("TEST_REGISTER_USER_FORM_FAIL" in str(response.content))
def test_register_user_form_fail_missing_name(self):
"""
Should not register a user correctly
"""
c = Client()
response = c.post(
reverse("core:register"),
{
"first_name": "Guy",
"last_name": "",
"email": "bibou@git.an",
"date_of_birth": "12/6/1942",
"password1": "plop",
"password2": "plop",
"captcha_0": "dummy-value",
"captcha_1": "PASSED",
},
)
self.assertTrue(response.status_code == 200)
self.assertTrue("TEST_REGISTER_USER_FORM_FAIL" in str(response.content))
def test_register_user_form_fail_missing_date_of_birth(self):
"""
Should not register a user correctly
"""
c = Client()
response = c.post(
reverse("core:register"),
{
"first_name": "",
"last_name": "Carlier",
"email": "bibou@git.an",
"date_of_birth": "",
"password1": "plop",
"password2": "plop",
"captcha_0": "dummy-value",
"captcha_1": "PASSED",
},
)
self.assertTrue(response.status_code == 200)
self.assertTrue("TEST_REGISTER_USER_FORM_FAIL" in str(response.content))
def test_register_user_form_fail_missing_first_name(self):
"""
Should not register a user correctly
"""
c = Client()
response = c.post(
reverse("core:register"),
{
"first_name": "",
"last_name": "Carlier",
"email": "bibou@git.an",
"date_of_birth": "12/6/1942",
"password1": "plop",
"password2": "plop",
"captcha_0": "dummy-value",
"captcha_1": "PASSED",
},
)
self.assertTrue(response.status_code == 200)
self.assertTrue("TEST_REGISTER_USER_FORM_FAIL" in str(response.content))
def test_register_user_form_fail_wrong_captcha(self):
"""
Should not register a user correctly
"""
c = Client()
response = c.post(
reverse("core:register"),
{
"first_name": "Bibou",
"last_name": "Carlier",
"email": "bibou@git.an",
"date_of_birth": "12/6/1942",
"password1": "plop",
"password2": "plop",
"captcha_0": "dummy-value",
"captcha_1": "WRONG_CAPTCHA",
},
)
self.assertTrue(response.status_code == 200)
self.assertTrue("TEST_REGISTER_USER_FORM_FAIL" in str(response.content))
def test_register_user_form_fail_already_exists(self):
"""
Should not register a user correctly
"""
c = Client()
c.post(
reverse("core:register"),
{
"first_name": "Guy",
"last_name": "Carlier",
"email": "bibou@git.an",
"date_of_birth": "12/6/1942",
"password1": "plop",
"password2": "plop",
"captcha_0": "dummy-value",
"captcha_1": "PASSED",
},
)
response = c.post(
reverse("core:register"),
{
"first_name": "Bibou",
"last_name": "Carlier",
"email": "bibou@git.an",
"date_of_birth": "12/6/1942",
"password1": "plop",
"password2": "plop",
"captcha_0": "dummy-value",
"captcha_1": "PASSED",
},
)
self.assertTrue(response.status_code == 200)
self.assertTrue("TEST_REGISTER_USER_FORM_FAIL" in str(response.content))
def test_login_success(self):
"""
Should login a user correctly
"""
c = Client()
c.post(
reverse("core:register"),
{
"first_name": "Guy",
"last_name": "Carlier",
"email": "bibou@git.an",
"date_of_birth": "12/6/1942",
"password1": "plop",
"password2": "plop",
"captcha_0": "dummy-value",
"captcha_1": "PASSED",
},
)
response = c.post(
reverse("core:login"), {"username": "gcarlier", "password": "plop"}
)
self.assertTrue(response.status_code == 302)
# self.assertTrue('Hello, world' in str(response.content))
def test_login_fail(self):
def test_login_fail(self, client, user):
"""
Should not login a user correctly
"""
c = Client()
c.post(
reverse("core:register"),
{
"first_name": "Guy",
"last_name": "Carlier",
"email": "bibou@git.an",
"date_of_birth": "12/6/1942",
"password1": "plop",
"password2": "plop",
"captcha_0": "dummy-value",
"captcha_1": "PASSED",
},
response = client.post(
reverse("core:login"),
{"username": user.username, "password": "wrong-password"},
)
response = c.post(
reverse("core:login"), {"username": "gcarlier", "password": "guy"}
)
self.assertTrue(response.status_code == 200)
self.assertTrue(
"""<p class="alert alert-red">Votre nom d\\'utilisateur et votre mot de passe ne correspondent pas. Merci de r\\xc3\\xa9essayer.</p>"""
in str(response.content)
assert response.status_code == 200
assert (
'<p class="alert alert-red">Votre nom d\'utilisateur '
"et votre mot de passe ne correspondent pas. Merci de réessayer.</p>"
) in str(response.content.decode())
def test_login_success(self, client, user):
"""
Should login a user correctly
"""
response = client.post(
reverse("core:login"), {"username": user.username, "password": "plop"}
)
assertRedirects(response, reverse("core:index"))
class MarkdownTest(TestCase):
def test_full_markdown_syntax(self):
root_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
with open(os.path.join(root_path) + "/doc/SYNTAX.md", "r") as md_file:
md = md_file.read()
with open(os.path.join(root_path) + "/doc/SYNTAX.html", "r") as html_file:
html = html_file.read()
result = markdown(md)
self.assertTrue(result == html)
def test_full_markdown_syntax():
root_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
with open(os.path.join(root_path) + "/doc/SYNTAX.md", "r") as md_file:
md = md_file.read()
with open(os.path.join(root_path) + "/doc/SYNTAX.html", "r") as html_file:
html = html_file.read()
result = markdown(md)
assert result == html
class PageHandlingTest(TestCase):
@classmethod
def setUpTestData(cls):
cls.root = User.objects.get(username="root")
cls.root_group = Group.objects.get(name="Root")
def setUp(self):
self.client.login(username="root", password="plop")
self.root_group = Group.objects.get(name="Root")
self.client.force_login(self.root)
def test_create_page_ok(self):
"""
Should create a page correctly
"""
"""Should create a page correctly."""
response = self.client.post(
reverse("core:page_new"),
@ -301,19 +138,17 @@ class PageHandlingTest(TestCase):
self.assertRedirects(
response, reverse("core:page", kwargs={"page_name": "guy"})
)
self.assertTrue(Page.objects.filter(name="guy").exists())
assert Page.objects.filter(name="guy").exists()
response = self.client.get(reverse("core:page", kwargs={"page_name": "guy"}))
self.assertEqual(response.status_code, 200)
assert response.status_code == 200
html = response.content.decode()
self.assertIn('<a href="/page/guy/hist/">', html)
self.assertIn('<a href="/page/guy/edit/">', html)
self.assertIn('<a href="/page/guy/prop/">', html)
assert '<a href="/page/guy/hist/">' in html
assert '<a href="/page/guy/edit/">' in html
assert '<a href="/page/guy/prop/">' in html
def test_create_child_page_ok(self):
"""
Should create a page correctly
"""
"""Should create a page correctly."""
# remove all other pages to make sure there is no side effect
Page.objects.all().delete()
self.client.post(
@ -321,7 +156,7 @@ class PageHandlingTest(TestCase):
{"parent": "", "name": "guy", "owner_group": str(self.root_group.id)},
)
page = Page.objects.first()
response = self.client.post(
self.client.post(
reverse("core:page_new"),
{
"parent": str(page.id),
@ -332,8 +167,8 @@ class PageHandlingTest(TestCase):
response = self.client.get(
reverse("core:page", kwargs={"page_name": "guy/bibou"})
)
self.assertTrue(response.status_code == 200)
self.assertTrue('<a href="/page/guy/bibou/">' in str(response.content))
assert response.status_code == 200
assert '<a href="/page/guy/bibou/">' in str(response.content)
def test_access_child_page_ok(self):
"""
@ -346,7 +181,7 @@ class PageHandlingTest(TestCase):
response = self.client.get(
reverse("core:page", kwargs={"page_name": "guy/bibou"})
)
self.assertTrue(response.status_code == 200)
assert response.status_code == 200
html = response.content.decode()
self.assertIn('<a href="/page/guy/bibou/edit/">', html)
@ -355,7 +190,7 @@ class PageHandlingTest(TestCase):
Should not display a page correctly
"""
response = self.client.get(reverse("core:page", kwargs={"page_name": "swagg"}))
self.assertTrue(response.status_code == 200)
assert response.status_code == 200
html = response.content.decode()
self.assertIn('<a href="/page/create/?page=swagg">', html)
@ -383,8 +218,8 @@ http://git.an
},
)
response = self.client.get(reverse("core:page", kwargs={"page_name": "guy"}))
self.assertTrue(response.status_code == 200)
self.assertTrue(
assert response.status_code == 200
assert (
'<p>Guy <em>bibou</em></p>\\n<p><a href="http://git.an">http://git.an</a></p>\\n'
+ "<h1>Swag</h1>\\n&lt;guy&gt;Bibou&lt;/guy&gt;"
+ "&lt;script&gt;alert(\\'Guy\\');&lt;/script&gt;"
@ -392,35 +227,19 @@ http://git.an
)
class UserToolsTest(TestCase):
def test_anonymous_user_unauthorized(self):
response = self.client.get(reverse("core:user_tools"))
self.assertEqual(response.status_code, 403)
class UserToolsTest:
def test_anonymous_user_unauthorized(self, client):
"""An anonymous user shouldn't have access to the tools page"""
response = client.get(reverse("core:user_tools"))
assert response.status_code == 403
def test_page_is_working(self):
@pytest.mark.parametrize("username", ["guy", "root", "skia", "comunity"])
def test_page_is_working(self, client, username):
"""All existing users should be able to see the test page"""
# Test for simple user
self.client.login(username="guy", password="plop")
response = self.client.get(reverse("core:user_tools"))
self.assertNotEqual(response.status_code, 500)
self.assertEqual(response.status_code, 200)
# Test for root
self.client.login(username="root", password="plop")
response = self.client.get(reverse("core:user_tools"))
self.assertNotEqual(response.status_code, 500)
self.assertEqual(response.status_code, 200)
# Test for skia
self.client.login(username="skia", password="plop")
response = self.client.get(reverse("core:user_tools"))
self.assertNotEqual(response.status_code, 500)
self.assertEqual(response.status_code, 200)
# Test for comunity
self.client.login(username="comunity", password="plop")
response = self.client.get(reverse("core:user_tools"))
self.assertNotEqual(response.status_code, 500)
self.assertEqual(response.status_code, 200)
client.force_login(User.objects.get(username=username))
response = client.get(reverse("core:user_tools"))
assert response.status_code == 200
# TODO: many tests on the pages:
@ -442,12 +261,12 @@ class FileHandlingTest(TestCase):
reverse("core:file_detail", kwargs={"file_id": self.subscriber.home.id}),
{"folder_name": "GUY_folder_test"},
)
self.assertTrue(response.status_code == 302)
assert response.status_code == 302
response = self.client.get(
reverse("core:file_detail", kwargs={"file_id": self.subscriber.home.id})
)
self.assertTrue(response.status_code == 200)
self.assertTrue("GUY_folder_test</a>" in str(response.content))
assert response.status_code == 200
assert "GUY_folder_test</a>" in str(response.content)
def test_upload_file_home(self):
with open("/bin/ls", "rb") as f:
@ -457,12 +276,12 @@ class FileHandlingTest(TestCase):
),
{"file_field": f},
)
self.assertTrue(response.status_code == 302)
assert response.status_code == 302
response = self.client.get(
reverse("core:file_detail", kwargs={"file_id": self.subscriber.home.id})
)
self.assertTrue(response.status_code == 200)
self.assertTrue("ls</a>" in str(response.content))
assert response.status_code == 200
assert "ls</a>" in str(response.content)
class UserIsInGroupTest(TestCase):
@ -477,6 +296,10 @@ class UserIsInGroupTest(TestCase):
cls.root_group = Group.objects.get(name="Root")
cls.public = Group.objects.get(name="Public")
cls.skia = User.objects.get(username="skia")
cls.toto = User.objects.create(
username="toto", first_name="a", last_name="b", email="a.b@toto.fr"
)
cls.subscribers = Group.objects.get(name="Subscribers")
cls.old_subscribers = Group.objects.get(name="Old subscribers")
cls.accounting_admin = Group.objects.get(name="Accounting admin")
@ -493,21 +316,15 @@ class UserIsInGroupTest(TestCase):
)
cls.main_club = Club.objects.get(id=1)
def setUp(self) -> None:
self.toto = User.objects.create(
username="toto", first_name="a", last_name="b", email="a.b@toto.fr"
)
self.skia = User.objects.get(username="skia")
def assert_in_public_group(self, user):
self.assertTrue(user.is_in_group(pk=self.public.id))
self.assertTrue(user.is_in_group(name=self.public.name))
assert user.is_in_group(pk=self.public.id)
assert user.is_in_group(name=self.public.name)
def assert_in_club_metagroups(self, user, club):
meta_groups_board = club.unix_name + settings.SITH_BOARD_SUFFIX
meta_groups_members = club.unix_name + settings.SITH_MEMBER_SUFFIX
self.assertFalse(user.is_in_group(name=meta_groups_board))
self.assertFalse(user.is_in_group(name=meta_groups_members))
assert user.is_in_group(name=meta_groups_board) is False
assert user.is_in_group(name=meta_groups_members) is False
def assert_only_in_public_group(self, user):
self.assert_in_public_group(user)
@ -519,12 +336,12 @@ class UserIsInGroupTest(TestCase):
self.subscribers,
self.old_subscribers,
):
self.assertFalse(user.is_in_group(pk=group.pk))
self.assertFalse(user.is_in_group(name=group.name))
assert not user.is_in_group(pk=group.pk)
assert not user.is_in_group(name=group.name)
meta_groups_board = self.club.unix_name + settings.SITH_BOARD_SUFFIX
meta_groups_members = self.club.unix_name + settings.SITH_MEMBER_SUFFIX
self.assertFalse(user.is_in_group(name=meta_groups_board))
self.assertFalse(user.is_in_group(name=meta_groups_members))
assert user.is_in_group(name=meta_groups_board) is False
assert user.is_in_group(name=meta_groups_members) is False
def test_anonymous_user(self):
"""
@ -583,15 +400,13 @@ class UserIsInGroupTest(TestCase):
)
meta_groups_members = self.club.unix_name + settings.SITH_MEMBER_SUFFIX
cache.clear()
self.assertTrue(self.toto.is_in_group(name=meta_groups_members))
self.assertEqual(
membership, cache.get(f"membership_{self.club.id}_{self.toto.id}")
)
assert self.toto.is_in_group(name=meta_groups_members) is True
assert membership == cache.get(f"membership_{self.club.id}_{self.toto.id}")
membership.end_date = now() - timedelta(minutes=5)
membership.save()
cached_membership = cache.get(f"membership_{self.club.id}_{self.toto.id}")
self.assertEqual(cached_membership, "not_member")
self.assertFalse(self.toto.is_in_group(name=meta_groups_members))
assert cached_membership == "not_member"
assert self.toto.is_in_group(name=meta_groups_members) is False
def test_cache_properly_cleared_group(self):
"""
@ -600,24 +415,24 @@ class UserIsInGroupTest(TestCase):
"""
# testing with pk
self.toto.groups.add(self.com_admin.pk)
self.assertTrue(self.toto.is_in_group(pk=self.com_admin.pk))
assert self.toto.is_in_group(pk=self.com_admin.pk) is True
self.toto.groups.remove(self.com_admin.pk)
self.assertFalse(self.toto.is_in_group(pk=self.com_admin.pk))
assert self.toto.is_in_group(pk=self.com_admin.pk) is False
# testing with name
self.toto.groups.add(self.sas_admin.pk)
self.assertTrue(self.toto.is_in_group(name="SAS admin"))
assert self.toto.is_in_group(name="SAS admin") is True
self.toto.groups.remove(self.sas_admin.pk)
self.assertFalse(self.toto.is_in_group(name="SAS admin"))
assert self.toto.is_in_group(name="SAS admin") is False
def test_not_existing_group(self):
"""
Test that searching for a not existing group
returns False
"""
self.assertFalse(self.skia.is_in_group(name="This doesn't exist"))
assert self.skia.is_in_group(name="This doesn't exist") is False
class DateUtilsTest(TestCase):
@ -639,29 +454,25 @@ class DateUtilsTest(TestCase):
"""
Test that the get_semester function returns the correct semester string
"""
self.assertEqual(get_semester_code(self.autumn_semester_january), "A24")
self.assertEqual(get_semester_code(self.autumn_semester_september), "A24")
self.assertEqual(get_semester_code(self.autumn_first_day), "A24")
assert get_semester_code(self.autumn_semester_january) == "A24"
assert get_semester_code(self.autumn_semester_september) == "A24"
assert get_semester_code(self.autumn_first_day) == "A24"
self.assertEqual(get_semester_code(self.spring_semester_march), "P23")
self.assertEqual(get_semester_code(self.spring_first_day), "P23")
assert get_semester_code(self.spring_semester_march) == "P23"
assert get_semester_code(self.spring_first_day) == "P23"
def test_get_start_of_semester_fixed_date(self):
"""
Test that the get_start_of_semester correctly the starting date of the semester.
"""
automn_2024 = date(2024, self.autumn_month, self.autumn_day)
self.assertEqual(
get_start_of_semester(self.autumn_semester_january), automn_2024
)
self.assertEqual(
get_start_of_semester(self.autumn_semester_september), automn_2024
)
self.assertEqual(get_start_of_semester(self.autumn_first_day), automn_2024)
assert get_start_of_semester(self.autumn_semester_january) == automn_2024
assert get_start_of_semester(self.autumn_semester_september) == automn_2024
assert get_start_of_semester(self.autumn_first_day) == automn_2024
spring_2023 = date(2023, self.spring_month, self.spring_day)
self.assertEqual(get_start_of_semester(self.spring_semester_march), spring_2023)
self.assertEqual(get_start_of_semester(self.spring_first_day), spring_2023)
assert get_start_of_semester(self.spring_semester_march) == spring_2023
assert get_start_of_semester(self.spring_first_day) == spring_2023
def test_get_start_of_semester_today(self):
"""
@ -669,10 +480,10 @@ class DateUtilsTest(TestCase):
when no date is given
"""
with freezegun.freeze_time(self.autumn_semester_september):
self.assertEqual(get_start_of_semester(), self.autumn_first_day)
assert get_start_of_semester() == self.autumn_first_day
with freezegun.freeze_time(self.spring_semester_march):
self.assertEqual(get_start_of_semester(), self.spring_first_day)
assert get_start_of_semester() == self.spring_first_day
def test_get_start_of_semester_changing_date(self):
"""
@ -685,8 +496,8 @@ class DateUtilsTest(TestCase):
mid_autumn = autumn_2023 + timedelta(days=45)
with freezegun.freeze_time(mid_spring) as frozen_time:
self.assertEqual(get_start_of_semester(), spring_2023)
assert get_start_of_semester() == spring_2023
# forward time to the middle of the next semester
frozen_time.move_to(mid_autumn)
self.assertEqual(get_start_of_semester(), autumn_2023)
assert get_start_of_semester() == autumn_2023

View File

@ -46,9 +46,7 @@ class CounterTest(TestCase):
reverse("counter:details", kwargs={"counter_id": self.mde.id})
)
self.assertTrue(
'class="link-button">S&#39; Kia</button>' in str(response.content)
)
assert 'class="link-button">S&#39; Kia</button>' in str(response.content)
counter_token = re.search(
r'name="counter_token" value="([^"]*)"', str(response.content)
@ -60,7 +58,7 @@ class CounterTest(TestCase):
)
counter_url = response.get("location")
response = self.client.get(response.get("location"))
self.assertTrue(">Richard Batsbak</" in str(response.content))
assert ">Richard Batsbak</" in str(response.content)
self.client.post(
counter_url,
@ -90,11 +88,10 @@ class CounterTest(TestCase):
response_get = self.client.get(response.get("location"))
response_content = response_get.content.decode("utf-8")
self.assertTrue("2 x Barbar" in str(response_content))
self.assertTrue("2 x Déconsigne Eco-cup" in str(response_content))
self.assertTrue(
"<p>Client : Richard Batsbak - Nouveau montant : 3.60"
in str(response_content)
assert "2 x Barbar" in str(response_content)
assert "2 x Déconsigne Eco-cup" in str(response_content)
assert "<p>Client : Richard Batsbak - Nouveau montant : 3.60" in str(
response_content
)
self.client.post(
@ -111,7 +108,7 @@ class CounterTest(TestCase):
"bank": "OTHER",
},
)
self.assertTrue(response.status_code == 200)
assert response.status_code == 200
self.client.post(
reverse("counter:login", kwargs={"counter_id": self.foyer.id}),
@ -141,27 +138,26 @@ class CounterTest(TestCase):
"bank": "OTHER",
},
)
self.assertTrue(response.status_code == 200)
assert response.status_code == 200
def test_annotate_has_barman_queryset(self):
"""
Test if the custom queryset method ``annotate_has_barman``
works as intended
"""
self.sli.counters.clear()
self.sli.counters.add(self.foyer, self.mde)
self.sli.counters.set([self.foyer, self.mde])
counters = Counter.objects.annotate_has_barman(self.sli)
for counter in counters:
if counter.name in ("Foyer", "MDE"):
self.assertTrue(counter.has_annotated_barman)
assert counter.has_annotated_barman
else:
self.assertFalse(counter.has_annotated_barman)
assert not counter.has_annotated_barman
class CounterStatsTest(TestCase):
@classmethod
def setUpTestData(cls):
cls.counter = Counter.objects.filter(id=2).first()
cls.counter = Counter.objects.get(id=2)
cls.krophil = User.objects.get(username="krophil")
cls.skia = User.objects.get(username="skia")
cls.sli = User.objects.get(username="sli")
@ -262,110 +258,57 @@ class CounterStatsTest(TestCase):
def test_not_authenticated_user_fail(self):
# Test with not login user
response = self.client.get(reverse("counter:stats", args=[self.counter.id]))
self.assertTrue(response.status_code == 403)
assert response.status_code == 403
def test_unauthorized_user_fails(self):
user = User.objects.get(username="public")
self.client.login(username=user.username, password="plop")
self.client.force_login(User.objects.get(username="public"))
response = self.client.get(reverse("counter:stats", args=[self.counter.id]))
self.assertTrue(response.status_code == 403)
assert response.status_code == 403
def test_get_total_sales(self):
"""
Test the result of the Counter.get_total_sales() method
"""
total = self.counter.get_total_sales()
self.assertEqual(total, 3102)
assert self.counter.get_total_sales() == 3102
def test_top_barmen(self):
"""
Test the result of Counter.get_top_barmen() is correct
"""
top = iter(self.counter.get_top_barmen())
self.assertEqual(
next(top),
users = [self.skia, self.root, self.sli]
perm_times = [
timedelta(days=16, hours=2, minutes=35, seconds=54),
timedelta(hours=21),
timedelta(hours=5),
]
assert list(self.counter.get_top_barmen()) == [
{
"user": self.skia.id,
"name": f"{self.skia.first_name} {self.skia.last_name}",
"promo": self.skia.promo,
"nickname": self.skia.nick_name,
"perm_sum": timedelta(days=16, hours=2, minutes=35, seconds=54),
},
)
self.assertEqual(
next(top),
{
"user": self.root.id,
"name": f"{self.root.first_name} {self.root.last_name}",
"promo": self.root.promo,
"nickname": self.root.nick_name,
"perm_sum": timedelta(hours=21),
},
)
self.assertEqual(
next(top),
{
"user": self.sli.id,
"name": f"{self.sli.first_name} {self.sli.last_name}",
"promo": self.sli.promo,
"nickname": self.sli.nick_name,
"perm_sum": timedelta(hours=5),
},
)
self.assertIsNone(
next(top, None), msg="barmen with no office hours should not be in the top"
)
"user": user.id,
"name": f"{user.first_name} {user.last_name}",
"promo": user.promo,
"nickname": user.nick_name,
"perm_sum": perm_time,
}
for user, perm_time in zip(users, perm_times)
]
def test_top_customer(self):
"""
Test the result of Counter.get_top_customers() is correct
"""
top = iter(self.counter.get_top_customers())
expected_results = [
users = [self.sli, self.skia, self.krophil, self.root]
sale_amounts = [2000, 1000, 100, 2]
assert list(self.counter.get_top_customers()) == [
{
"user": self.sli.id,
"name": f"{self.sli.first_name} {self.sli.last_name}",
"promo": self.sli.promo,
"nickname": self.sli.nick_name,
"selling_sum": 2000,
},
{
"user": self.skia.id,
"name": f"{self.skia.first_name} {self.skia.last_name}",
"promo": self.skia.promo,
"nickname": self.skia.nick_name,
"selling_sum": 1000,
},
{
"user": self.krophil.id,
"name": f"{self.krophil.first_name} {self.krophil.last_name}",
"promo": self.krophil.promo,
"nickname": self.krophil.nick_name,
"selling_sum": 100,
},
{
"user": self.root.id,
"name": f"{self.root.first_name} {self.root.last_name}",
"promo": self.root.promo,
"nickname": self.root.nick_name,
"selling_sum": 2,
},
"user": user.id,
"name": f"{user.first_name} {user.last_name}",
"promo": user.promo,
"nickname": user.nick_name,
"selling_sum": sale_amount,
}
for user, sale_amount in zip(users, sale_amounts)
]
for result in expected_results:
self.assertEqual(
next(top),
{
"user": result["user"],
"name": result["name"],
"promo": result["promo"],
"nickname": result["nickname"],
"selling_sum": result["selling_sum"],
},
)
self.assertIsNone(next(top, None))
class BillingInfoTest(TestCase):
@classmethod
@ -386,13 +329,15 @@ class BillingInfoTest(TestCase):
"city": "Sète",
"country": "FR",
}
cls.root = User.objects.get(username="root")
cls.subscriber = User.objects.get(username="subscriber")
def test_edit_infos(self):
user = User.objects.get(username="subscriber")
user = self.subscriber
BillingInfo.objects.get_or_create(
customer=user.customer, defaults=self.payload_1
)
self.client.login(username=user.username, password="plop")
self.client.force_login(user)
response = self.client.post(
reverse("counter:edit_billing_info", args=[user.id]),
json.dumps(self.payload_2),
@ -400,23 +345,23 @@ class BillingInfoTest(TestCase):
)
user = User.objects.get(username="subscriber")
infos = BillingInfo.objects.get(customer__user=user)
self.assertEqual(200, response.status_code)
assert response.status_code == 200
self.assertJSONEqual(response.content, {"errors": None})
self.assertTrue(hasattr(user.customer, "billing_infos"))
self.assertEqual(user.customer, infos.customer)
self.assertEqual("Subscribed", infos.first_name)
self.assertEqual("User", infos.last_name)
self.assertEqual("3, rue de Troyes", infos.address_1)
self.assertEqual(None, infos.address_2)
self.assertEqual("34301", infos.zip_code)
self.assertEqual("Sète", infos.city)
self.assertEqual("FR", infos.country)
assert hasattr(user.customer, "billing_infos")
assert infos.customer == user.customer
assert infos.first_name == "Subscribed"
assert infos.last_name == "User"
assert infos.address_1 == "3, rue de Troyes"
assert infos.address_2 is None
assert infos.zip_code == "34301"
assert infos.city == "Sète"
assert infos.country == "FR"
def test_create_infos_for_user_with_account(self):
user = User.objects.get(username="subscriber")
if hasattr(user.customer, "billing_infos"):
user.customer.billing_infos.delete()
self.client.login(username=user.username, password="plop")
self.client.force_login(user)
response = self.client.post(
reverse("counter:create_billing_info", args=[user.id]),
json.dumps(self.payload_1),
@ -424,48 +369,48 @@ class BillingInfoTest(TestCase):
)
user = User.objects.get(username="subscriber")
infos = BillingInfo.objects.get(customer__user=user)
self.assertEqual(200, response.status_code)
assert response.status_code == 200
self.assertJSONEqual(response.content, {"errors": None})
self.assertTrue(hasattr(user.customer, "billing_infos"))
self.assertEqual(user.customer, infos.customer)
self.assertEqual("Subscribed", infos.first_name)
self.assertEqual("User", infos.last_name)
self.assertEqual("1 rue des Huns", infos.address_1)
self.assertEqual(None, infos.address_2)
self.assertEqual("90000", infos.zip_code)
self.assertEqual("Belfort", infos.city)
self.assertEqual("FR", infos.country)
assert hasattr(user.customer, "billing_infos")
assert infos.customer == user.customer
assert infos.first_name == "Subscribed"
assert infos.last_name == "User"
assert infos.address_1 == "1 rue des Huns"
assert infos.address_2 is None
assert infos.zip_code == "90000"
assert infos.city == "Belfort"
assert infos.country == "FR"
def test_create_infos_for_user_without_account(self):
user = User.objects.get(username="subscriber")
if hasattr(user, "customer"):
user.customer.delete()
self.client.login(username=user.username, password="plop")
self.client.force_login(user)
response = self.client.post(
reverse("counter:create_billing_info", args=[user.id]),
json.dumps(self.payload_1),
content_type="application/json",
)
user = User.objects.get(username="subscriber")
self.assertTrue(hasattr(user, "customer"))
self.assertTrue(hasattr(user.customer, "billing_infos"))
self.assertEqual(200, response.status_code)
assert hasattr(user, "customer")
assert hasattr(user.customer, "billing_infos")
assert response.status_code == 200
self.assertJSONEqual(response.content, {"errors": None})
infos = BillingInfo.objects.get(customer__user=user)
self.assertEqual(user.customer, infos.customer)
self.assertEqual("Subscribed", infos.first_name)
self.assertEqual("User", infos.last_name)
self.assertEqual("1 rue des Huns", infos.address_1)
self.assertEqual(None, infos.address_2)
self.assertEqual("90000", infos.zip_code)
self.assertEqual("Belfort", infos.city)
self.assertEqual("FR", infos.country)
assert infos.first_name == "Subscribed"
assert infos.last_name == "User"
assert infos.address_1 == "1 rue des Huns"
assert infos.address_2 is None
assert infos.zip_code == "90000"
assert infos.city == "Belfort"
assert infos.country == "FR"
def test_create_invalid(self):
user = User.objects.get(username="subscriber")
if hasattr(user.customer, "billing_infos"):
user.customer.billing_infos.delete()
self.client.login(username=user.username, password="plop")
self.client.force_login(user)
# address_1, zip_code and country are missing
payload = {
"first_name": user.first_name,
@ -479,7 +424,7 @@ class BillingInfoTest(TestCase):
)
user = User.objects.get(username="subscriber")
self.assertEqual(400, response.status_code)
self.assertFalse(hasattr(user.customer, "billing_infos"))
assert not hasattr(user.customer, "billing_infos")
expected_errors = {
"errors": [
{"field": "Adresse 1", "messages": ["Ce champ est obligatoire."]},
@ -494,7 +439,7 @@ class BillingInfoTest(TestCase):
BillingInfo.objects.get_or_create(
customer=user.customer, defaults=self.payload_1
)
self.client.login(username=user.username, password="plop")
self.client.force_login(user)
# address_1, zip_code and country are missing
payload = {
"first_name": user.first_name,
@ -508,7 +453,7 @@ class BillingInfoTest(TestCase):
)
user = User.objects.get(username="subscriber")
self.assertEqual(400, response.status_code)
self.assertTrue(hasattr(user.customer, "billing_infos"))
assert hasattr(user.customer, "billing_infos")
expected_errors = {
"errors": [
{"field": "Adresse 1", "messages": ["Ce champ est obligatoire."]},
@ -535,7 +480,7 @@ class BillingInfoTest(TestCase):
user = User.objects.get(username="subscriber")
if hasattr(user.customer, "billing_infos"):
user.customer.billing_infos.delete()
self.client.login(username=user.username, password="plop")
self.client.force_login(user)
response = self.client.post(
reverse("counter:edit_billing_info", args=[user.id]),
json.dumps(self.payload_2),
@ -548,17 +493,17 @@ class BillingInfoTest(TestCase):
BillingInfo.objects.get_or_create(
customer=user.customer, defaults=self.payload_1
)
self.client.login(username="root", password="plop")
self.client.force_login(self.root)
response = self.client.post(
reverse("counter:edit_billing_info", args=[user.id]),
json.dumps(self.payload_2),
content_type="application/json",
)
self.assertEqual(200, response.status_code)
assert response.status_code == 200
user = User.objects.get(username="subscriber")
infos = BillingInfo.objects.get(customer__user=user)
self.assertJSONEqual(response.content, {"errors": None})
self.assertTrue(hasattr(user.customer, "billing_infos"))
assert hasattr(user.customer, "billing_infos")
self.assertEqual(user.customer, infos.customer)
self.assertEqual("Subscribed", infos.first_name)
self.assertEqual("User", infos.last_name)
@ -572,61 +517,55 @@ class BillingInfoTest(TestCase):
user = User.objects.get(username="subscriber")
if hasattr(user.customer, "billing_infos"):
user.customer.billing_infos.delete()
self.client.login(username="root", password="plop")
self.client.force_login(self.root)
response = self.client.post(
reverse("counter:create_billing_info", args=[user.id]),
json.dumps(self.payload_2),
content_type="application/json",
)
self.assertEqual(200, response.status_code)
assert response.status_code == 200
user = User.objects.get(username="subscriber")
infos = BillingInfo.objects.get(customer__user=user)
self.assertJSONEqual(response.content, {"errors": None})
self.assertTrue(hasattr(user.customer, "billing_infos"))
self.assertEqual(user.customer, infos.customer)
self.assertEqual("Subscribed", infos.first_name)
self.assertEqual("User", infos.last_name)
self.assertEqual("3, rue de Troyes", infos.address_1)
self.assertEqual(None, infos.address_2)
self.assertEqual("34301", infos.zip_code)
self.assertEqual("Sète", infos.city)
self.assertEqual("FR", infos.country)
assert hasattr(user.customer, "billing_infos")
assert infos.customer == user.customer
assert infos.first_name == "Subscribed"
assert infos.last_name == "User"
assert infos.address_1 == "3, rue de Troyes"
assert infos.address_2 is None
assert infos.zip_code == "34301"
assert infos.city == "Sète"
assert infos.country == "FR"
class BarmanConnectionTest(TestCase):
def setUp(self):
self.krophil = User.objects.get(username="krophil")
self.skia = User.objects.get(username="skia")
self.skia.customer.account = 800
self.krophil.customer.save()
self.skia.customer.save()
@classmethod
def setUpTestData(cls):
cls.krophil = User.objects.get(username="krophil")
cls.skia = User.objects.get(username="skia")
cls.skia.customer.account = 800
cls.krophil.customer.save()
cls.skia.customer.save()
self.counter = Counter.objects.filter(id=2).first()
cls.counter = Counter.objects.get(id=2)
def test_barman_granted(self):
self.client.post(
reverse("counter:login", args=[self.counter.id]),
{"username": "krophil", "password": "plop"},
)
response_get = self.client.get(
reverse("counter:details", args=[self.counter.id])
)
response = self.client.get(reverse("counter:details", args=[self.counter.id]))
self.assertTrue("<p>Entrez un code client : </p>" in str(response_get.content))
assert "<p>Entrez un code client : </p>" in str(response.content)
def test_counters_list_barmen(self):
self.client.post(
reverse("counter:login", args=[self.counter.id]),
{"username": "krophil", "password": "plop"},
)
response_get = self.client.get(
reverse("counter:activity", args=[self.counter.id])
)
response = self.client.get(reverse("counter:activity", args=[self.counter.id]))
self.assertTrue(
'<li><a href="/user/10/">Kro Phil&#39;</a></li>'
in str(response_get.content)
)
assert '<li><a href="/user/10/">Kro Phil&#39;</a></li>' in str(response.content)
def test_barman_denied(self):
self.client.post(
@ -637,20 +576,16 @@ class BarmanConnectionTest(TestCase):
reverse("counter:details", args=[self.counter.id])
)
self.assertTrue("<p>Merci de vous identifier</p>" in str(response_get.content))
assert "<p>Merci de vous identifier</p>" in str(response_get.content)
def test_counters_list_no_barmen(self):
self.client.post(
reverse("counter:login", args=[self.counter.id]),
{"username": "krophil", "password": "plop"},
)
response_get = self.client.get(
reverse("counter:activity", args=[self.counter.id])
)
response = self.client.get(reverse("counter:activity", args=[self.counter.id]))
self.assertFalse(
'<li><a href="/user/1/">S&#39; Kia</a></li>' in str(response_get.content)
)
assert not '<li><a href="/user/1/">S&#39; Kia</a></li>' in str(response.content)
class StudentCardTest(TestCase):
@ -659,12 +594,16 @@ class StudentCardTest(TestCase):
Test that an user can be found with it's student card
"""
@classmethod
def setUpTestData(cls):
cls.krophil = User.objects.get(username="krophil")
cls.sli = User.objects.get(username="sli")
cls.skia = User.objects.get(username="skia")
cls.root = User.objects.get(username="root")
cls.counter = Counter.objects.get(id=2)
def setUp(self):
self.krophil = User.objects.get(username="krophil")
self.sli = User.objects.get(username="sli")
self.counter = Counter.objects.filter(id=2).first()
# Auto login on counter
self.client.post(
reverse("counter:login", args=[self.counter.id]),
@ -677,12 +616,9 @@ class StudentCardTest(TestCase):
{"code": "9A89B82018B0A0"},
)
self.assertEqual(
response.url,
reverse(
"counter:click",
kwargs={"counter_id": self.counter.id, "user_id": self.sli.id},
),
assert response.url == reverse(
"counter:click",
kwargs={"counter_id": self.counter.id, "user_id": self.sli.id},
)
def test_add_student_card_from_counter(self):
@ -778,7 +714,7 @@ class StudentCardTest(TestCase):
)
def test_delete_student_card_with_owner(self):
self.client.login(username="sli", password="plop")
self.client.force_login(self.sli)
self.client.post(
reverse(
"counter:delete_student_card",
@ -788,10 +724,10 @@ class StudentCardTest(TestCase):
},
)
)
self.assertFalse(self.sli.customer.student_cards.exists())
assert not self.sli.customer.student_cards.exists()
def test_delete_student_card_with_board_member(self):
self.client.login(username="skia", password="plop")
self.client.force_login(self.skia)
self.client.post(
reverse(
"counter:delete_student_card",
@ -801,10 +737,10 @@ class StudentCardTest(TestCase):
},
)
)
self.assertFalse(self.sli.customer.student_cards.exists())
assert not self.sli.customer.student_cards.exists()
def test_delete_student_card_with_root(self):
self.client.login(username="root", password="plop")
self.client.force_login(self.root)
self.client.post(
reverse(
"counter:delete_student_card",
@ -814,10 +750,10 @@ class StudentCardTest(TestCase):
},
)
)
self.assertFalse(self.sli.customer.student_cards.exists())
assert not self.sli.customer.student_cards.exists()
def test_delete_student_card_fail(self):
self.client.login(username="krophil", password="plop")
self.client.force_login(self.krophil)
response = self.client.post(
reverse(
"counter:delete_student_card",
@ -827,12 +763,12 @@ class StudentCardTest(TestCase):
},
)
)
self.assertEqual(response.status_code, 403)
self.assertTrue(self.sli.customer.student_cards.exists())
assert response.status_code == 403
assert self.sli.customer.student_cards.exists()
def test_add_student_card_from_user_preferences(self):
# Test with owner of the card
self.client.login(username="sli", password="plop")
self.client.force_login(self.sli)
self.client.post(
reverse(
"counter:add_student_card", kwargs={"customer_id": self.sli.customer.pk}
@ -846,7 +782,7 @@ class StudentCardTest(TestCase):
self.assertContains(response, text="8B90734A802A8F")
# Test with board member
self.client.login(username="skia", password="plop")
self.client.force_login(self.skia)
self.client.post(
reverse(
"counter:add_student_card", kwargs={"customer_id": self.sli.customer.pk}
@ -884,7 +820,7 @@ class StudentCardTest(TestCase):
self.assertContains(response, text="ABCAAAFAAFAAAB")
# Test with root
self.client.login(username="root", password="plop")
self.client.force_login(self.root)
self.client.post(
reverse(
"counter:add_student_card", kwargs={"customer_id": self.sli.customer.pk}
@ -898,7 +834,7 @@ class StudentCardTest(TestCase):
self.assertContains(response, text="8B90734A802A8B")
def test_add_student_card_from_user_preferences_fail(self):
self.client.login(username="sli", password="plop")
self.client.force_login(self.sli)
# UID too short
response = self.client.post(
reverse(
@ -943,29 +879,30 @@ class StudentCardTest(TestCase):
reverse(
"counter:add_student_card", kwargs={"customer_id": self.sli.customer.pk}
),
{"uid": " "},
{"uid": " " * 14},
)
self.assertContains(response, text="Cet UID est invalide")
# Test with unauthorized user
self.client.login(username="krophil", password="plop")
self.client.force_login(self.krophil)
response = self.client.post(
reverse(
"counter:add_student_card", kwargs={"customer_id": self.sli.customer.pk}
),
{"uid": "8B90734A802A8F"},
)
self.assertEqual(response.status_code, 403)
assert response.status_code == 403
class CustomerAccountIdTest(TestCase):
def setUp(self):
self.user_a = User.objects.create(
@classmethod
def setUpTestData(cls):
cls.user_a = User.objects.create(
username="a", password="plop", email="a.a@a.fr"
)
user_b = User.objects.create(username="b", password="plop", email="b.b@b.fr")
user_c = User.objects.create(username="c", password="plop", email="c.c@c.fr")
Customer.objects.create(user=self.user_a, amount=10, account_id="1111a")
Customer.objects.create(user=cls.user_a, amount=10, account_id="1111a")
Customer.objects.create(user=user_b, amount=0, account_id="9999z")
Customer.objects.create(user=user_c, amount=0, account_id="12345f")
@ -974,14 +911,14 @@ class CustomerAccountIdTest(TestCase):
customer, created = Customer.get_or_create(user_d)
account_id = customer.account_id
number = account_id[:-1]
self.assertTrue(created)
self.assertEqual(number, "12346")
self.assertEqual(6, len(account_id))
self.assertIn(account_id[-1], string.ascii_lowercase)
self.assertEqual(0, customer.amount)
assert created is True
assert number == "12346"
assert 6 == len(account_id)
assert account_id[-1] in string.ascii_lowercase
assert customer.amount == 0
def test_get_existing_account(self):
account, created = Customer.get_or_create(self.user_a)
self.assertFalse(created)
self.assertEqual(account.account_id, "1111a")
self.assertEqual(10, account.amount)
assert created is False
assert account.account_id == "1111a"
assert account.amount == 10

View File

@ -196,16 +196,16 @@ Pour lancer les tests il suffit d'utiliser la commande intégrée à django.
.. code-block:: bash
# Lancer tous les tests
python manage.py test
pytest
# Lancer les tests de l'application core
python manage.py test core
pytest core
# Lancer les tests de la classe UserRegistrationTest de core
python manage.py test core.tests.UserRegistrationTest
pytest core.tests.UserRegistrationTest
# Lancer une méthode en particulier de cette même classe
python manage.py test core.tests.UserRegistrationTest.test_register_user_form_ok
pytest core.tests.UserRegistrationTest.test_register_user_form_ok
Vérifier les dépendances Javascript
-----------------------------------

View File

@ -40,14 +40,14 @@ from eboutic.models import Basket
class EbouticTest(TestCase):
@classmethod
def setUpTestData(cls):
cls.barbar = Product.objects.filter(code="BARB").first()
cls.refill = Product.objects.filter(code="15REFILL").first()
cls.cotis = Product.objects.filter(code="1SCOTIZ").first()
cls.eboutic = Counter.objects.filter(name="Eboutic").first()
cls.skia = User.objects.filter(username="skia").first()
cls.subscriber = User.objects.filter(username="subscriber").first()
cls.old_subscriber = User.objects.filter(username="old_subscriber").first()
cls.public = User.objects.filter(username="public").first()
cls.barbar = Product.objects.get(code="BARB")
cls.refill = Product.objects.get(code="15REFILL")
cls.cotis = Product.objects.get(code="1SCOTIZ")
cls.eboutic = Counter.objects.get(name="Eboutic")
cls.skia = User.objects.get(username="skia")
cls.subscriber = User.objects.get(username="subscriber")
cls.old_subscriber = User.objects.get(username="old_subscriber")
cls.public = User.objects.get(username="public")
def get_busy_basket(self, user) -> Basket:
"""
@ -82,7 +82,7 @@ class EbouticTest(TestCase):
return url
def test_buy_with_sith_account(self):
self.client.login(username="subscriber", password="plop")
self.client.force_login(self.subscriber)
self.subscriber.customer.amount = 100 # give money before test
self.subscriber.customer.save()
basket = self.get_busy_basket(self.subscriber)
@ -90,14 +90,12 @@ class EbouticTest(TestCase):
response = self.client.post(reverse("eboutic:pay_with_sith"))
self.assertRedirects(response, "/eboutic/pay/success/")
new_balance = Customer.objects.get(user=self.subscriber).amount
self.assertEqual(float(new_balance), 100 - amount)
self.assertEqual(
'basket_items=""; expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0; Path=/eboutic',
self.client.cookies["basket_items"].OutputString(),
)
assert float(new_balance) == 100 - amount
expected = 'basket_items=""; expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0; Path=/eboutic'
assert expected == self.client.cookies["basket_items"].OutputString()
def test_buy_with_sith_account_no_money(self):
self.client.login(username="subscriber", password="plop")
self.client.force_login(self.subscriber)
basket = self.get_busy_basket(self.subscriber)
initial = basket.get_total() - 1 # just not enough to complete the sale
self.subscriber.customer.amount = initial
@ -105,20 +103,19 @@ class EbouticTest(TestCase):
response = self.client.post(reverse("eboutic:pay_with_sith"))
self.assertRedirects(response, "/eboutic/pay/failure/")
new_balance = Customer.objects.get(user=self.subscriber).amount
self.assertEqual(float(new_balance), initial)
self.assertEqual(
'basket_items=""; expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0; Path=/eboutic',
self.client.cookies["basket_items"].OutputString(),
) # this cookie should be removed after payment
assert float(new_balance) == initial
# this cookie should be removed after payment
expected = 'basket_items=""; expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0; Path=/eboutic'
assert expected == self.client.cookies["basket_items"].OutputString()
def test_submit_basket(self):
self.client.login(username="subscriber", password="plop")
self.client.force_login(self.subscriber)
self.client.cookies["basket_items"] = """[
{"id": 2, "name": "Cotis 2 semestres", "quantity": 1, "unit_price": 28},
{"id": 4, "name": "Barbar", "quantity": 3, "unit_price": 1.7}
]"""
response = self.client.get(reverse("eboutic:command"))
self.assertEqual(response.status_code, 200)
assert response.status_code == 200
self.assertInHTML(
"<tr><td>Cotis 2 semestres</td><td>1</td><td>28.00 €</td></tr>",
response.content.decode(),
@ -127,42 +124,37 @@ class EbouticTest(TestCase):
"<tr><td>Barbar</td><td>3</td><td>1.70 €</td></tr>",
response.content.decode(),
)
self.assertIn("basket_id", self.client.session)
assert "basket_id" in self.client.session
basket = Basket.objects.get(id=self.client.session["basket_id"])
self.assertEqual(basket.items.count(), 2)
assert basket.items.count() == 2
barbar = basket.items.filter(product_name="Barbar").first()
self.assertIsNotNone(barbar)
self.assertEqual(barbar.quantity, 3)
assert barbar is not None
assert barbar.quantity == 3
cotis = basket.items.filter(product_name="Cotis 2 semestres").first()
self.assertIsNotNone(cotis)
self.assertEqual(cotis.quantity, 1)
self.assertEqual(basket.get_total(), 3 * 1.7 + 28)
assert cotis is not None
assert cotis.quantity == 1
assert basket.get_total() == 3 * 1.7 + 28
def test_submit_empty_basket(self):
self.client.login(username="subscriber", password="plop")
self.client.force_login(self.subscriber)
self.client.cookies["basket_items"] = "[]"
response = self.client.get(reverse("eboutic:command"))
self.assertRedirects(response, "/eboutic/")
def test_submit_invalid_basket(self):
self.client.login(username="subscriber", password="plop")
self.client.force_login(self.subscriber)
max_id = Product.objects.aggregate(res=Max("id"))["res"]
self.client.cookies["basket_items"] = f"""[
{{"id": {max_id + 1}, "name": "", "quantity": 1, "unit_price": 28}}
]"""
response = self.client.get(reverse("eboutic:command"))
self.assertIn(
'basket_items=""',
self.client.cookies["basket_items"].OutputString(),
)
self.assertIn(
"Path=/eboutic",
self.client.cookies["basket_items"].OutputString(),
)
cookie = self.client.cookies["basket_items"].OutputString()
assert 'basket_items=""' in cookie
assert "Path=/eboutic" in cookie
self.assertRedirects(response, "/eboutic/")
def test_submit_basket_illegal_quantity(self):
self.client.login(username="subscriber", password="plop")
self.client.force_login(self.subscriber)
self.client.cookies["basket_items"] = """[
{"id": 4, "name": "Barbar", "quantity": -1, "unit_price": 1.7}
]"""
@ -170,11 +162,11 @@ class EbouticTest(TestCase):
self.assertRedirects(response, "/eboutic/")
def test_buy_subscribe_product_with_credit_card(self):
self.client.login(username="old_subscriber", password="plop")
self.client.force_login(self.old_subscriber)
response = self.client.get(
reverse("core:user_profile", kwargs={"user_id": self.old_subscriber.id})
)
self.assertTrue("Non cotisant" in str(response.content))
assert "Non cotisant" in str(response.content)
self.client.cookies["basket_items"] = """[
{"id": 2, "name": "Cotis 2 semestres", "quantity": 1, "unit_price": 28}
]"""
@ -184,21 +176,21 @@ class EbouticTest(TestCase):
response.content.decode(),
)
basket = Basket.objects.get(id=self.client.session["basket_id"])
self.assertEqual(basket.items.count(), 1)
assert basket.items.count() == 1
response = self.client.get(self.generate_bank_valid_answer())
self.assertTrue(response.status_code == 200)
self.assertTrue(response.content.decode("utf-8") == "Payment successful")
assert response.status_code == 200
assert response.content.decode("utf-8") == "Payment successful"
subscriber = User.objects.get(id=self.old_subscriber.id)
self.assertEqual(subscriber.subscriptions.count(), 2)
assert subscriber.subscriptions.count() == 2
sub = subscriber.subscriptions.order_by("-subscription_end").first()
self.assertTrue(sub.is_valid_now())
self.assertEqual(sub.member, subscriber)
self.assertEqual(sub.subscription_type, "deux-semestres")
self.assertEqual(sub.location, "EBOUTIC")
assert sub.is_valid_now()
assert sub.member == subscriber
assert sub.subscription_type == "deux-semestres"
assert sub.location == "EBOUTIC"
def test_buy_refill_product_with_credit_card(self):
self.client.login(username="subscriber", password="plop")
self.client.force_login(self.subscriber)
# basket contains 1 refill item worth 15€
self.client.cookies["basket_items"] = json.dumps(
[{"id": 3, "name": "Rechargement 15 €", "quantity": 1, "unit_price": 15}]
@ -208,13 +200,13 @@ class EbouticTest(TestCase):
url = self.generate_bank_valid_answer()
response = self.client.get(url)
self.assertTrue(response.status_code == 200)
self.assertTrue(response.content.decode() == "Payment successful")
assert response.status_code == 200
assert response.content.decode() == "Payment successful"
new_balance = Customer.objects.get(user=self.subscriber).amount
self.assertEqual(new_balance, initial_balance + 15)
assert new_balance == initial_balance + 15
def test_alter_basket_after_submission(self):
self.client.login(username="subscriber", password="plop")
self.client.force_login(self.subscriber)
self.client.cookies["basket_items"] = json.dumps(
[{"id": 4, "name": "Barbar", "quantity": 1, "unit_price": 1.7}]
)
@ -227,30 +219,30 @@ class EbouticTest(TestCase):
)
self.client.get(reverse("eboutic:command"))
response = self.client.get(et_answer_url)
self.assertEqual(response.status_code, 500)
self.assertIn(
"Basket processing failed with error: SuspiciousOperation('Basket total and amount do not match'",
response.content.decode("utf-8"),
assert response.status_code == 500
assert (
"Basket processing failed with error: SuspiciousOperation('Basket total and amount do not match'"
in response.content.decode("utf-8"),
)
def test_buy_simple_product_with_credit_card(self):
self.client.login(username="subscriber", password="plop")
self.client.force_login(self.subscriber)
self.client.cookies["basket_items"] = json.dumps(
[{"id": 4, "name": "Barbar", "quantity": 1, "unit_price": 1.7}]
)
self.client.get(reverse("eboutic:command"))
et_answer_url = self.generate_bank_valid_answer()
response = self.client.get(et_answer_url)
self.assertTrue(response.status_code == 200)
self.assertTrue(response.content.decode("utf-8") == "Payment successful")
assert response.status_code == 200
assert response.content.decode("utf-8") == "Payment successful"
selling = (
Selling.objects.filter(customer=self.subscriber.customer)
.order_by("-date")
.first()
)
self.assertEqual(selling.payment_method, "CARD")
self.assertEqual(selling.quantity, 1)
self.assertEqual(selling.unit_price, self.barbar.selling_price)
self.assertEqual(selling.counter.type, "EBOUTIC")
self.assertEqual(selling.product, self.barbar)
assert selling.payment_method == "CARD"
assert selling.quantity == 1
assert selling.unit_price == self.barbar.selling_price
assert selling.counter.type == "EBOUTIC"
assert selling.product == self.barbar

View File

@ -6,56 +6,44 @@ from core.models import Group, User
from election.models import Election
class MainElection(TestCase):
def setUp(self):
self.election = Election.objects.all().first()
self.public_group = Group.objects.get(id=settings.SITH_GROUP_PUBLIC_ID)
self.subscriber_group = Group.objects.get(name=settings.SITH_MAIN_MEMBERS_GROUP)
self.ae_board_group = Group.objects.get(name=settings.SITH_MAIN_BOARD_GROUP)
self.sli = User.objects.get(username="sli")
self.subscriber = User.objects.get(username="subscriber")
self.public = User.objects.get(username="public")
class ElectionTest(TestCase):
@classmethod
def setUpTestData(cls):
cls.election = Election.objects.first()
cls.public_group = Group.objects.get(id=settings.SITH_GROUP_PUBLIC_ID)
cls.subscriber_group = Group.objects.get(name=settings.SITH_MAIN_MEMBERS_GROUP)
cls.ae_board_group = Group.objects.get(name=settings.SITH_MAIN_BOARD_GROUP)
cls.sli = User.objects.get(username="sli")
cls.subscriber = User.objects.get(username="subscriber")
cls.public = User.objects.get(username="public")
class ElectionDetailTest(MainElection):
class ElectionDetailTest(ElectionTest):
def test_permission_denied(self):
self.election.view_groups.remove(self.public_group)
self.election.view_groups.add(self.subscriber_group)
self.election.save()
self.client.login(username=self.public.username, password="plop")
response_get = self.client.get(
self.client.force_login(self.public)
response = self.client.get(
reverse("election:detail", args=str(self.election.id))
)
response_post = self.client.get(
reverse("election:detail", args=str(self.election.id))
)
self.assertTrue(response_get.status_code == 403)
self.assertTrue(response_post.status_code == 403)
self.election.view_groups.remove(self.subscriber_group)
self.election.view_groups.add(self.public_group)
self.election.save()
assert response.status_code == 403
def test_permisson_granted(self):
self.client.login(username=self.public.username, password="plop")
response_get = self.client.get(
self.client.force_login(self.public)
response = self.client.get(
reverse("election:detail", args=str(self.election.id))
)
response_post = self.client.post(
reverse("election:detail", args=str(self.election.id))
)
self.assertFalse(response_get.status_code == 403)
self.assertFalse(response_post.status_code == 403)
self.assertTrue("La roue tourne" in str(response_get.content))
assert response.status_code == 200
assert "La roue tourne" in str(response.content)
class ElectionUpdateView(MainElection):
class ElectionUpdateView(ElectionTest):
def test_permission_denied(self):
self.client.login(username=self.subscriber.username, password="plop")
response_get = self.client.get(
self.client.force_login(self.subscriber)
response = self.client.get(
reverse("election:update", args=str(self.election.id))
)
response_post = self.client.post(
assert response.status_code == 403
response = self.client.post(
reverse("election:update", args=str(self.election.id))
)
self.assertTrue(response_get.status_code == 403)
self.assertTrue(response_post.status_code == 403)
assert response.status_code == 403

View File

@ -34,29 +34,30 @@ from galaxy.models import Galaxy
class GalaxyTestModel(TestCase):
def setUp(self):
self.root = User.objects.get(username="root")
self.skia = User.objects.get(username="skia")
self.sli = User.objects.get(username="sli")
self.krophil = User.objects.get(username="krophil")
self.richard = User.objects.get(username="rbatsbak")
self.subscriber = User.objects.get(username="subscriber")
self.public = User.objects.get(username="public")
self.com = User.objects.get(username="comunity")
@classmethod
def setUpTestData(cls):
cls.root = User.objects.get(username="root")
cls.skia = User.objects.get(username="skia")
cls.sli = User.objects.get(username="sli")
cls.krophil = User.objects.get(username="krophil")
cls.richard = User.objects.get(username="rbatsbak")
cls.subscriber = User.objects.get(username="subscriber")
cls.public = User.objects.get(username="public")
cls.com = User.objects.get(username="comunity")
def test_user_self_score(self):
"""
Test that individual user scores are correct
"""
with self.assertNumQueries(8):
self.assertEqual(Galaxy.compute_user_score(self.root), 9)
self.assertEqual(Galaxy.compute_user_score(self.skia), 10)
self.assertEqual(Galaxy.compute_user_score(self.sli), 8)
self.assertEqual(Galaxy.compute_user_score(self.krophil), 2)
self.assertEqual(Galaxy.compute_user_score(self.richard), 10)
self.assertEqual(Galaxy.compute_user_score(self.subscriber), 8)
self.assertEqual(Galaxy.compute_user_score(self.public), 8)
self.assertEqual(Galaxy.compute_user_score(self.com), 1)
assert Galaxy.compute_user_score(self.root) == 9
assert Galaxy.compute_user_score(self.skia) == 10
assert Galaxy.compute_user_score(self.sli) == 8
assert Galaxy.compute_user_score(self.krophil) == 2
assert Galaxy.compute_user_score(self.richard) == 10
assert Galaxy.compute_user_score(self.subscriber) == 8
assert Galaxy.compute_user_score(self.public) == 8
assert Galaxy.compute_user_score(self.com) == 1
def test_users_score(self):
"""
@ -155,12 +156,13 @@ class GalaxyTestView(TestCase):
call_command("generate_galaxy_test_data", "-v", "0")
galaxy = Galaxy.objects.create()
galaxy.rule(26) # We want a fast test
cls.root = User.objects.get(username="root")
def test_page_is_citizen(self):
"""
Test that users can access the galaxy page of users who are citizens
"""
self.client.login(username="root", password="plop")
self.client.force_login(self.root)
user = User.objects.get(last_name="n°500")
response = self.client.get(reverse("galaxy:user", args=[user.id]))
self.assertContains(
@ -174,10 +176,10 @@ class GalaxyTestView(TestCase):
Test that trying to access the galaxy page of a user who is not
citizens return a 404
"""
self.client.login(username="root", password="plop")
self.client.force_login(self.root)
user = User.objects.get(last_name="n°1")
response = self.client.get(reverse("galaxy:user", args=[user.id]))
self.assertEquals(response.status_code, 404)
assert response.status_code == 404
def test_full_galaxy_state(self):
"""
@ -185,7 +187,7 @@ class GalaxyTestView(TestCase):
command that the relation scores are correct, and that the view exposes the
right data.
"""
self.client.login(username="root", password="plop")
self.client.force_login(self.root)
response = self.client.get(reverse("galaxy:data"))
state = response.json()
@ -194,7 +196,6 @@ class GalaxyTestView(TestCase):
# Dump computed state, either for easier debugging, or to copy as new reference if changes are legit
(galaxy_dir / "test_galaxy_state.json").write_text(json.dumps(state))
self.assertEqual(
state,
json.loads((galaxy_dir / "ref_galaxy_state.json").read_text()),
assert (
state == json.loads((galaxy_dir / "ref_galaxy_state.json").read_text()),
)

File diff suppressed because it is too large Load Diff

103
poetry.lock generated
View File

@ -321,6 +321,9 @@ files = [
{file = "coverage-7.5.4.tar.gz", hash = "sha256:a44963520b069e12789d0faea4e9fdb1e410cdc4aab89d94f7f55cbb7fef0353"},
]
[package.dependencies]
tomli = {version = "*", optional = true, markers = "python_full_version <= \"3.11.0a6\" and extra == \"toml\""}
[package.extras]
toml = ["tomli"]
@ -575,6 +578,20 @@ files = [
{file = "docutils-0.18.1.tar.gz", hash = "sha256:679987caf361a7539d76e584cbeddc311e3aee937877c87346f31debc63e9d06"},
]
[[package]]
name = "exceptiongroup"
version = "1.2.1"
description = "Backport of PEP 654 (exception groups)"
optional = false
python-versions = ">=3.7"
files = [
{file = "exceptiongroup-1.2.1-py3-none-any.whl", hash = "sha256:5258b9ed329c5bbdd31a309f53cbfb0b155341807f6ff7606a1e801a891b29ad"},
{file = "exceptiongroup-1.2.1.tar.gz", hash = "sha256:a4785e48b045528f5bfe627b6ad554ff32def154f42372786903b7abcfe1aa16"},
]
[package.extras]
test = ["pytest (>=6)"]
[[package]]
name = "filelock"
version = "3.15.4"
@ -627,6 +644,17 @@ files = [
{file = "imagesize-1.4.1.tar.gz", hash = "sha256:69150444affb9cb0d5cc5a92b3676f0b2fb7cd9ae39e947a5e11a36b4497cd4a"},
]
[[package]]
name = "iniconfig"
version = "2.0.0"
description = "brain-dead simple config-ini parsing"
optional = false
python-versions = ">=3.7"
files = [
{file = "iniconfig-2.0.0-py3-none-any.whl", hash = "sha256:b6a85871a79d2e3b22d2d1b94ac2824226a63c6b741c88f7ae975f18b6778374"},
{file = "iniconfig-2.0.0.tar.gz", hash = "sha256:2d91e135bf72d31a410b17c16da610a82cb55f6b0477d1a902134b24a455b8b3"},
]
[[package]]
name = "ipython"
version = "7.34.0"
@ -949,6 +977,21 @@ files = [
docs = ["furo", "olefile", "sphinx (>=2.4)", "sphinx-copybutton", "sphinx-inline-tabs", "sphinx-removed-in", "sphinxext-opengraph"]
tests = ["check-manifest", "coverage", "defusedxml", "markdown2", "olefile", "packaging", "pyroma", "pytest", "pytest-cov", "pytest-timeout"]
[[package]]
name = "pluggy"
version = "1.5.0"
description = "plugin and hook calling mechanisms for python"
optional = false
python-versions = ">=3.8"
files = [
{file = "pluggy-1.5.0-py3-none-any.whl", hash = "sha256:44e1ad92c8ca002de6377e165f3e0f1be63266ab4d554740532335b9d75ea669"},
{file = "pluggy-1.5.0.tar.gz", hash = "sha256:2cffa88e94fdc978c4c574f15f9e59b7f4201d439195c3715ca9e2486f1d0cf1"},
]
[package.extras]
dev = ["pre-commit", "tox"]
testing = ["pytest", "pytest-benchmark"]
[[package]]
name = "prompt-toolkit"
version = "3.0.47"
@ -1108,6 +1151,64 @@ cryptography = ">=38.0.0,<40.0.0 || >40.0.0,<40.0.1 || >40.0.1,<42"
docs = ["sphinx (!=5.2.0,!=5.2.0.post0)", "sphinx-rtd-theme"]
test = ["flaky", "pretend", "pytest (>=3.0.1)"]
[[package]]
name = "pytest"
version = "8.2.2"
description = "pytest: simple powerful testing with Python"
optional = false
python-versions = ">=3.8"
files = [
{file = "pytest-8.2.2-py3-none-any.whl", hash = "sha256:c434598117762e2bd304e526244f67bf66bbd7b5d6cf22138be51ff661980343"},
{file = "pytest-8.2.2.tar.gz", hash = "sha256:de4bb8104e201939ccdc688b27a89a7be2079b22e2bd2b07f806b6ba71117977"},
]
[package.dependencies]
colorama = {version = "*", markers = "sys_platform == \"win32\""}
exceptiongroup = {version = ">=1.0.0rc8", markers = "python_version < \"3.11\""}
iniconfig = "*"
packaging = "*"
pluggy = ">=1.5,<2.0"
tomli = {version = ">=1", markers = "python_version < \"3.11\""}
[package.extras]
dev = ["argcomplete", "attrs (>=19.2)", "hypothesis (>=3.56)", "mock", "pygments (>=2.7.2)", "requests", "setuptools", "xmlschema"]
[[package]]
name = "pytest-cov"
version = "5.0.0"
description = "Pytest plugin for measuring coverage."
optional = false
python-versions = ">=3.8"
files = [
{file = "pytest-cov-5.0.0.tar.gz", hash = "sha256:5837b58e9f6ebd335b0f8060eecce69b662415b16dc503883a02f45dfeb14857"},
{file = "pytest_cov-5.0.0-py3-none-any.whl", hash = "sha256:4f0764a1219df53214206bf1feea4633c3b558a2925c8b59f144f682861ce652"},
]
[package.dependencies]
coverage = {version = ">=5.2.1", extras = ["toml"]}
pytest = ">=4.6"
[package.extras]
testing = ["fields", "hunter", "process-tests", "pytest-xdist", "virtualenv"]
[[package]]
name = "pytest-django"
version = "4.8.0"
description = "A Django plugin for pytest."
optional = false
python-versions = ">=3.8"
files = [
{file = "pytest-django-4.8.0.tar.gz", hash = "sha256:5d054fe011c56f3b10f978f41a8efb2e5adfc7e680ef36fb571ada1f24779d90"},
{file = "pytest_django-4.8.0-py3-none-any.whl", hash = "sha256:ca1ddd1e0e4c227cf9e3e40a6afc6d106b3e70868fd2ac5798a22501271cd0c7"},
]
[package.dependencies]
pytest = ">=7.0.0"
[package.extras]
docs = ["sphinx", "sphinx-rtd-theme"]
testing = ["Django", "django-configurations (>=2.0)"]
[[package]]
name = "python-dateutil"
version = "2.9.0.post0"
@ -1561,4 +1662,4 @@ filelock = ">=3.4"
[metadata]
lock-version = "2.0"
python-versions = "^3.10,<3.12"
content-hash = "78f859d93ec1f207dbdebd5b608abfac44f87bb254a37ebeafaaf1823f605a71"
content-hash = "76711479953fc14d7761c3bdcc27088d301df318ebda1a6d8c4a4ab930e341f3"

View File

@ -55,10 +55,9 @@ ipython = "^7.28.0"
ruff = "^0.4.10"
[tool.poetry.group.tests.dependencies]
coverage = "^7.5.4"
[tool.poetry.group.tests]
optional = true
pytest = "^8.2.2"
pytest-cov = "^5.0.0"
pytest-django = "^4.8.0"
[tool.poetry.group.docs.dependencies]
sphinx-rtd-theme = "^1.0.0"
@ -73,6 +72,10 @@ version = "1.4.25"
[tool.ruff.lint]
select = ["I", "F401"]
[tool.pytest.ini_options]
DJANGO_SETTINGS_MODULE = "sith.settings"
python_files = ["tests.py", "test_*.py", "*_tests.py"]
[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"

View File

@ -13,10 +13,11 @@
# OR WITHIN THE LOCAL FILE "LICENSE"
#
#
from datetime import date, timedelta
from datetime import timedelta
from django.test import TestCase
from django.urls import reverse
from django.utils.timezone import localtime, now
from club.models import Club
from core.models import RealGroup, User
@ -41,7 +42,7 @@ class MergeUserTest(TestCase):
)
def setUp(self) -> None:
self.client.login(username="root", password="plop")
self.client.force_login(self.root)
def test_simple(self):
self.to_delete.first_name = "Biggus"
@ -66,15 +67,15 @@ class MergeUserTest(TestCase):
self.to_keep = User.objects.get(pk=self.to_keep.pk)
# fields of to_delete should be assigned to to_keep
# if they were not set beforehand
self.assertEqual("Biggus", self.to_keep.first_name)
self.assertEqual("Dickus", self.to_keep.last_name)
self.assertEqual("B'ian", self.to_keep.nick_name)
self.assertEqual("Jerusalem", self.to_keep.address)
self.assertEqual("Rome", self.to_keep.parent_address)
self.assertEqual(3, self.to_keep.groups.count())
groups = list(self.to_keep.groups.all())
expected = [subscribers, mde_admin, sas_admin]
self.assertCountEqual(groups, expected)
assert "Biggus" == self.to_keep.first_name
assert "Dickus" == self.to_keep.last_name
assert "B'ian" == self.to_keep.nick_name
assert "Jerusalem" == self.to_keep.address
assert "Rome" == self.to_keep.parent_address
assert (3, self.to_keep.groups.count())
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
def test_both_subscribers_and_with_account(self):
Customer(user=self.to_keep, account_id="11000l", amount=0).save()
@ -113,7 +114,7 @@ class MergeUserTest(TestCase):
quantity=4,
payment_method="SITH_ACCOUNT",
).save()
today = date.today()
today = localtime(now()).date()
# both subscriptions began last month and shall end in 5 months
Subscription(
member=self.to_keep,
@ -137,9 +138,9 @@ class MergeUserTest(TestCase):
# to_delete had 20€ and bought 4 barbar
# total should be 10 - 4 + 20 - 8 = 18
self.assertAlmostEqual(18, self.to_keep.customer.amount, delta=0.0001)
self.assertEqual(2, self.to_keep.customer.buyings.count())
self.assertEqual(2, self.to_keep.customer.refillings.count())
self.assertTrue(self.to_keep.is_subscribed)
assert self.to_keep.customer.buyings.count() == 2
assert self.to_keep.customer.refillings.count() == 2
assert self.to_keep.is_subscribed
# to_keep had 5 months of subscription remaining and received
# 5 more months from to_delete, so he should be subscribed for 10 months
self.assertAlmostEqual(
@ -191,7 +192,7 @@ class MergeUserTest(TestCase):
self.assertRedirects(res, self.to_keep.get_absolute_url())
# to_delete had 20€ and bought 4 barbar worth 2€ each
# total should be 20 - 8 = 12
self.assertTrue(hasattr(self.to_keep, "customer"))
assert hasattr(self.to_keep, "customer")
self.assertAlmostEqual(12, self.to_keep.customer.amount, delta=0.0001)
def test_delete_has_no_account(self):
@ -219,5 +220,5 @@ class MergeUserTest(TestCase):
self.assertRedirects(res, self.to_keep.get_absolute_url())
# to_keep had 20€ and bought 4 barbar worth 2€ each
# total should be 20 - 8 = 12
self.assertTrue(hasattr(self.to_keep, "customer"))
assert hasattr(self.to_keep, "customer")
self.assertAlmostEqual(12, self.to_keep.customer.amount, delta=0.0001)

View File

@ -57,6 +57,7 @@ SECRET_KEY = "(4sjxvhz@m5$0a$j0_pqicnc$s!vbve)z+&++m%g%bjhlz4+g2"
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
TESTING = "pytest" in sys.modules
INTERNAL_IPS = ["127.0.0.1"]
ALLOWED_HOSTS = ["*"]
@ -113,8 +114,6 @@ MIDDLEWARE = (
"core.middleware.SignalRequestMiddleware",
)
TEST_RUNNER = "sith.testrunner.SithTestRunner"
ROOT_URLCONF = "sith.urls"
TEMPLATES = [
@ -697,7 +696,7 @@ if DEBUG:
SASS_INCLUDE_FOLDERS = ["core/static/"]
SENTRY_ENV = "development"
if "test" in sys.argv:
if TESTING:
CAPTCHA_TEST_MODE = True
if SENTRY_DSN:

View File

@ -1,9 +0,0 @@
from django.core.management import call_command
from django.test.runner import DiscoverRunner
class SithTestRunner(DiscoverRunner):
def setup_databases(self, **kwargs):
res = super().setup_databases(**kwargs)
call_command("populate")
return res

View File

@ -14,8 +14,9 @@
#
#
from datetime import date
from unittest import mock
import freezegun
import pytest
from django.conf import settings
from django.test import TestCase
@ -23,113 +24,92 @@ from core.models import User
from subscription.models import Subscription
class FakeDate(date):
"""A fake replacement for date that can be mocked for testing."""
def __new__(cls, *args, **kwargs):
return date.__new__(date, *args, **kwargs)
@pytest.mark.parametrize(
("today", "duration", "expected_start"),
[
(date(2020, 9, 18), 1, date(2020, 9, 18)),
(date(2020, 9, 18), 2, date(2020, 9, 18)),
(date(2020, 5, 17), 3, date(2020, 2, 15)),
(date(2021, 1, 18), 4, date(2020, 8, 15)),
(date(2020, 9, 18), 4, date(2020, 8, 15)),
],
)
def test_subscription_compute_start_from_today(today, duration, expected_start):
with freezegun.freeze_time(today):
assert Subscription.compute_start(duration=duration) == expected_start
def date_mock_today(year, month, day):
FakeDate.today = classmethod(lambda cls: date(year, month, day))
@pytest.mark.parametrize(
("start_date", "duration", "expected_start"),
[
(date(2020, 5, 17), 1, date(2020, 5, 17)),
(date(2020, 5, 17), 2, date(2020, 5, 17)),
(date(2020, 5, 17), 3, date(2020, 2, 15)),
(date(2020, 1, 11), 3, date(2019, 8, 15)),
],
)
def test_subscription_compute_start_explicit(start_date, duration, expected_start):
assert Subscription.compute_start(start_date, duration=duration) == expected_start
class SubscriptionUnitTest(TestCase):
@mock.patch("subscription.models.date", FakeDate)
def test_start_dates_sliding_without_start(self):
date_mock_today(2015, 9, 18)
d = Subscription.compute_start(duration=1)
self.assertTrue(d == date(2015, 9, 18))
self.assertTrue(Subscription.compute_start(duration=2) == date(2015, 9, 18))
@pytest.mark.parametrize(
("today", "duration", "expected_end"),
[
(date(2020, 9, 18), 1, date(2021, 3, 18)),
(date(2020, 9, 18), 2, date(2021, 9, 18)),
(date(2020, 9, 18), 3, date(2022, 2, 15)),
(date(2020, 5, 17), 4, date(2022, 8, 15)),
(date(2020, 9, 18), 0.33, date(2020, 11, 18)),
(date(2020, 9, 18), 0.67, date(2021, 1, 19)),
(date(2020, 9, 18), 0.5, date(2020, 12, 18)),
],
)
def test_subscription_compute_end_from_today(today, duration, expected_end):
with freezegun.freeze_time(today):
assert Subscription.compute_end(duration=duration) == expected_end
def test_start_dates_sliding_with_start(self):
self.assertTrue(
Subscription.compute_start(date(2015, 5, 17), 1) == date(2015, 5, 17)
)
self.assertTrue(
Subscription.compute_start(date(2015, 5, 17), 2) == date(2015, 5, 17)
)
@mock.patch("subscription.models.date", FakeDate)
def test_start_dates_not_sliding_without_start(self):
date_mock_today(2015, 5, 17)
self.assertTrue(Subscription.compute_start(duration=3) == date(2015, 2, 15))
date_mock_today(2016, 1, 18)
self.assertTrue(Subscription.compute_start(duration=4) == date(2015, 8, 15))
date_mock_today(2015, 9, 18)
self.assertTrue(Subscription.compute_start(duration=4) == date(2015, 8, 15))
def test_start_dates_not_sliding_with_start(self):
self.assertTrue(
Subscription.compute_start(date(2015, 5, 17), 3) == date(2015, 2, 15)
)
self.assertTrue(
Subscription.compute_start(date(2015, 1, 11), 3) == date(2014, 8, 15)
)
@mock.patch("subscription.models.date", FakeDate)
def test_end_dates_sliding(self):
date_mock_today(2015, 9, 18)
d = Subscription.compute_end(2)
self.assertTrue(d == date(2016, 9, 18))
d = Subscription.compute_end(1)
self.assertTrue(d == date(2016, 3, 18))
@mock.patch("subscription.models.date", FakeDate)
def test_end_dates_not_sliding_without_start(self):
date_mock_today(2015, 9, 18)
d = Subscription.compute_end(duration=3)
self.assertTrue(d == date(2017, 2, 15))
d = Subscription.compute_end(duration=4)
self.assertTrue(d == date(2017, 8, 15))
@mock.patch("subscription.models.date", FakeDate)
def test_end_dates_with_float(self):
date_mock_today(2015, 9, 18)
d = Subscription.compute_end(duration=0.33)
self.assertTrue(d == date(2015, 11, 18))
d = Subscription.compute_end(duration=0.67)
self.assertTrue(d == date(2016, 1, 19))
d = Subscription.compute_end(duration=0.5)
self.assertTrue(d == date(2015, 12, 18))
def test_end_dates_not_sliding_with_start(self):
d = Subscription.compute_end(duration=3, start=date(2015, 9, 18))
self.assertTrue(d == date(2017, 3, 18))
d = Subscription.compute_end(duration=4, start=date(2015, 9, 18))
self.assertTrue(d == date(2017, 9, 18))
@pytest.mark.parametrize(
("start_date", "duration", "expected_end"),
[
(date(2020, 9, 18), 3, date(2022, 3, 18)),
(date(2020, 9, 18), 4, date(2022, 9, 18)),
],
)
def test_subscription_compute_end_from_today(start_date, duration, expected_end):
assert Subscription.compute_end(duration, start_date) == expected_end
class SubscriptionIntegrationTest(TestCase):
@classmethod
def setUp(cls):
cls.user = User.objects.filter(username="public").first()
def setUpTestData(cls):
cls.user = User.objects.get(username="public")
def test_duration_one_month(self):
s = Subscription(
member=User.objects.filter(pk=self.user.pk).first(),
member=self.user,
subscription_type=list(settings.SITH_SUBSCRIPTIONS.keys())[3],
payment_method=settings.SITH_SUBSCRIPTION_PAYMENT_METHOD[0],
)
s.subscription_start = date(2017, 8, 29)
s.subscription_end = s.compute_end(duration=0.166, start=s.subscription_start)
s.save()
self.assertTrue(s.subscription_end == date(2017, 9, 29))
assert s.subscription_end == date(2017, 9, 29)
def test_duration_two_months(self):
s = Subscription(
member=User.objects.filter(pk=self.user.pk).first(),
member=self.user,
subscription_type=list(settings.SITH_SUBSCRIPTIONS.keys())[3],
payment_method=settings.SITH_SUBSCRIPTION_PAYMENT_METHOD[0],
)
s.subscription_start = date(2017, 8, 29)
s.subscription_end = s.compute_end(duration=0.333, start=s.subscription_start)
s.save()
self.assertTrue(s.subscription_end == date(2017, 10, 29))
assert s.subscription_end == date(2017, 10, 29)
def test_duration_one_day(self):
s = Subscription(
member=User.objects.filter(pk=self.user.pk).first(),
member=self.user,
subscription_type=list(settings.SITH_SUBSCRIPTIONS.keys())[3],
payment_method=settings.SITH_SUBSCRIPTION_PAYMENT_METHOD[0],
)
@ -139,44 +119,43 @@ class SubscriptionIntegrationTest(TestCase):
start=s.subscription_start,
)
s.save()
self.assertTrue(s.subscription_end == date(2017, 8, 30))
assert s.subscription_end == date(2017, 8, 30)
def test_duration_three_months(self):
s = Subscription(
member=User.objects.filter(pk=self.user.pk).first(),
member=self.user,
subscription_type=list(settings.SITH_SUBSCRIPTIONS.keys())[3],
payment_method=settings.SITH_SUBSCRIPTION_PAYMENT_METHOD[0],
)
s.subscription_start = date(2017, 8, 29)
s.subscription_end = s.compute_end(duration=0.5, start=s.subscription_start)
s.save()
self.assertTrue(s.subscription_end == date(2017, 11, 29))
assert s.subscription_end == date(2017, 11, 29)
def test_duration_four_months(self):
s = Subscription(
member=User.objects.filter(pk=self.user.pk).first(),
member=self.user,
subscription_type=list(settings.SITH_SUBSCRIPTIONS.keys())[3],
payment_method=settings.SITH_SUBSCRIPTION_PAYMENT_METHOD[0],
)
s.subscription_start = date(2017, 8, 29)
s.subscription_end = s.compute_end(duration=0.67, start=s.subscription_start)
s.save()
self.assertTrue(s.subscription_end == date(2017, 12, 30))
assert s.subscription_end == date(2017, 12, 30)
def test_duration_six_weeks(self):
s = Subscription(
member=User.objects.filter(pk=self.user.pk).first(),
member=self.user,
subscription_type=list(settings.SITH_SUBSCRIPTIONS.keys())[3],
payment_method=settings.SITH_SUBSCRIPTION_PAYMENT_METHOD[0],
)
s.subscription_start = date(2018, 9, 1)
s.subscription_end = s.compute_end(duration=0.23, start=s.subscription_start)
s.save()
self.assertTrue(s.subscription_end == date(2018, 10, 13))
assert s.subscription_end == date(2018, 10, 13)
@mock.patch("subscription.models.date", FakeDate)
def test_dates_sliding_with_subscribed_user(self):
user = User.objects.filter(pk=self.user.pk).first()
user = self.user
s = Subscription(
member=user,
subscription_type="deux-semestres",
@ -188,18 +167,16 @@ class SubscriptionIntegrationTest(TestCase):
start=s.subscription_start,
)
s.save()
self.assertTrue(s.subscription_end == date(2016, 8, 29))
date_mock_today(2016, 8, 25)
d = Subscription.compute_end(
duration=settings.SITH_SUBSCRIPTIONS["deux-semestres"]["duration"],
user=user,
)
assert s.subscription_end == date(2016, 8, 29)
with freezegun.freeze_time("2016-08-25"):
d = Subscription.compute_end(
duration=settings.SITH_SUBSCRIPTIONS["deux-semestres"]["duration"],
user=user,
)
assert d == date(2017, 8, 29)
self.assertTrue(d == date(2017, 8, 29))
@mock.patch("subscription.models.date", FakeDate)
def test_dates_renewal_sliding_during_two_free_monthes(self):
user = User.objects.filter(pk=self.user.pk).first()
user = self.user
s = Subscription(
member=user,
subscription_type="deux-mois-essai",
@ -211,17 +188,16 @@ class SubscriptionIntegrationTest(TestCase):
start=s.subscription_start,
)
s.save()
self.assertTrue(s.subscription_end == date(2015, 10, 29))
date_mock_today(2015, 9, 25)
d = Subscription.compute_end(
duration=settings.SITH_SUBSCRIPTIONS["deux-semestres"]["duration"],
user=user,
)
self.assertTrue(d == date(2016, 10, 29))
assert s.subscription_end == date(2015, 10, 29)
with freezegun.freeze_time("2015-09-25"):
d = Subscription.compute_end(
duration=settings.SITH_SUBSCRIPTIONS["deux-semestres"]["duration"],
user=user,
)
assert d == date(2016, 10, 29)
@mock.patch("subscription.models.date", FakeDate)
def test_dates_renewal_sliding_after_two_free_monthes(self):
user = User.objects.filter(pk=self.user.pk).first()
user = self.user
s = Subscription(
member=user,
subscription_type="deux-mois-essai",
@ -233,10 +209,10 @@ class SubscriptionIntegrationTest(TestCase):
start=s.subscription_start,
)
s.save()
self.assertTrue(s.subscription_end == date(2015, 10, 29))
date_mock_today(2015, 11, 5)
d = Subscription.compute_end(
duration=settings.SITH_SUBSCRIPTIONS["deux-semestres"]["duration"],
user=user,
)
self.assertTrue(d == date(2016, 11, 5))
assert s.subscription_end == date(2015, 10, 29)
with freezegun.freeze_time("2015-11-05"):
d = Subscription.compute_end(
duration=settings.SITH_SUBSCRIPTIONS["deux-semestres"]["duration"],
user=user,
)
assert d == date(2016, 11, 5)