|
| 1 | +from datetime import date, timedelta |
| 2 | +from unittest.mock import patch |
| 3 | + |
| 4 | +from django.test import TestCase |
| 5 | +from django.utils import timezone |
| 6 | +from rest_framework.test import APIClient |
| 7 | + |
| 8 | +from projects.models import Collaborator, Project |
| 9 | +from users.models import CustomUser |
| 10 | + |
| 11 | +from .helpers import add_user_to_program, build_partner_program, build_user |
| 12 | + |
| 13 | + |
| 14 | +class MemberStatisticsAPITests(TestCase): |
| 15 | + """Счётчики проверяются через публичный HTTP-контракт, включая число SQL.""" |
| 16 | + |
| 17 | + url = "/auth/public-users/stats/" |
| 18 | + |
| 19 | + def setUp(self): |
| 20 | + self.client = APIClient() |
| 21 | + |
| 22 | + def statistics(self, params=None): |
| 23 | + response = self.client.get(self.url, params or {}) |
| 24 | + self.assertEqual(response.status_code, 200) |
| 25 | + self.assertEqual( |
| 26 | + set(response.data), |
| 27 | + {"total", "in_projects", "in_programs", "new_last_30_days"}, |
| 28 | + ) |
| 29 | + self.assertTrue(all(type(value) is int for value in response.data.values())) |
| 30 | + return response.data |
| 31 | + |
| 32 | + def project(self, leader, **overrides): |
| 33 | + project = Project.objects.create( |
| 34 | + leader=leader, name="Синтетический проект", **{"draft": False, **overrides} |
| 35 | + ) |
| 36 | + # Сигнал создаёт Collaborator лидера. Убираем его только в fixture, |
| 37 | + # чтобы независимо проверить оба источника участия и их пересечение. |
| 38 | + Collaborator.objects.filter(project=project, user=leader).delete() |
| 39 | + return project |
| 40 | + |
| 41 | + def test_empty_catalog_is_zero_and_public(self): |
| 42 | + self.assertEqual( |
| 43 | + self.statistics(), |
| 44 | + {"total": 0, "in_projects": 0, "in_programs": 0, "new_last_30_days": 0}, |
| 45 | + ) |
| 46 | + |
| 47 | + def test_only_active_members_enter_all_metrics(self): |
| 48 | + program = build_partner_program() |
| 49 | + for index, (kind, active) in enumerate( |
| 50 | + ( |
| 51 | + (CustomUser.MEMBER, True), |
| 52 | + (CustomUser.MEMBER, False), |
| 53 | + (CustomUser.MENTOR, True), |
| 54 | + (CustomUser.EXPERT, True), |
| 55 | + (CustomUser.ADMIN, True), |
| 56 | + (CustomUser.INVESTOR, True), |
| 57 | + ) |
| 58 | + ): |
| 59 | + user = build_user( |
| 60 | + email=f"role-{index}@example.test", user_type=kind, is_active=active |
| 61 | + ) |
| 62 | + self.project(user) |
| 63 | + add_user_to_program(user, program) |
| 64 | + self.assertEqual( |
| 65 | + self.statistics(), |
| 66 | + {"total": 1, "in_projects": 1, "in_programs": 1, "new_last_30_days": 1}, |
| 67 | + ) |
| 68 | + |
| 69 | + def test_leader_counts_as_participant(self): |
| 70 | + self.project(build_user()) |
| 71 | + self.assertEqual(self.statistics()["in_projects"], 1) |
| 72 | + |
| 73 | + def test_collaborator_counts_without_leadership(self): |
| 74 | + leader = build_user(email="mentor@example.test", user_type=CustomUser.MENTOR) |
| 75 | + Collaborator.objects.create(user=build_user(), project=self.project(leader)) |
| 76 | + self.assertEqual(self.statistics()["in_projects"], 1) |
| 77 | + |
| 78 | + def test_multiple_projects_and_both_roles_count_a_person_once(self): |
| 79 | + leader = build_user() |
| 80 | + participant = build_user(email="participant@example.test") |
| 81 | + for _ in range(3): |
| 82 | + project = self.project(leader) |
| 83 | + Collaborator.objects.create(user=leader, project=project) |
| 84 | + Collaborator.objects.create(user=participant, project=project) |
| 85 | + self.assertEqual(self.statistics()["in_projects"], 2) |
| 86 | + |
| 87 | + def test_draft_and_private_projects_do_not_count_either_role(self): |
| 88 | + leader = build_user() |
| 89 | + participant = build_user(email="participant@example.test") |
| 90 | + for overrides in ({"draft": True}, {"is_public": False}): |
| 91 | + with self.subTest(overrides=overrides): |
| 92 | + Collaborator.objects.create( |
| 93 | + user=participant, project=self.project(leader, **overrides) |
| 94 | + ) |
| 95 | + self.assertEqual(self.statistics()["in_projects"], 0) |
| 96 | + |
| 97 | + def test_program_registrations_count_people_not_rows(self): |
| 98 | + user = build_user() |
| 99 | + for index in range(5): |
| 100 | + add_user_to_program(user, build_partner_program(tag=f"program-{index}")) |
| 101 | + self.assertEqual(self.statistics()["in_programs"], 1) |
| 102 | + |
| 103 | + def test_draft_program_does_not_count(self): |
| 104 | + add_user_to_program(build_user(), build_partner_program(draft=True)) |
| 105 | + self.assertEqual(self.statistics()["in_programs"], 0) |
| 106 | + |
| 107 | + def test_thirty_day_boundary_is_inclusive_and_timezone_aware(self): |
| 108 | + now = timezone.now() |
| 109 | + for index, age in enumerate( |
| 110 | + (timedelta(days=1), timedelta(days=30), timedelta(days=30, microseconds=1)) |
| 111 | + ): |
| 112 | + user = build_user(email=f"age-{index}@example.test") |
| 113 | + CustomUser.objects.filter(pk=user.pk).update(datetime_created=now - age) |
| 114 | + with patch("users.services.member_statistics.timezone.now", return_value=now): |
| 115 | + self.assertEqual(self.statistics()["new_last_30_days"], 2) |
| 116 | + |
| 117 | + def test_search_filters_and_pagination_do_not_change_statistics(self): |
| 118 | + build_user() |
| 119 | + expected = self.statistics() |
| 120 | + self.assertEqual( |
| 121 | + self.statistics( |
| 122 | + { |
| 123 | + "fullname": "Несуществующий", |
| 124 | + "skills__contains": "Несуществующий", |
| 125 | + "speciality__icontains": "Несуществующий", |
| 126 | + "offset": 999, |
| 127 | + "limit": 0, |
| 128 | + "user_type": CustomUser.EXPERT, |
| 129 | + } |
| 130 | + ), |
| 131 | + expected, |
| 132 | + ) |
| 133 | + |
| 134 | + def test_response_is_only_numbers_without_personal_or_relation_data(self): |
| 135 | + user = build_user(email="private@example.test", first_name="Секрет") |
| 136 | + self.project(user) |
| 137 | + add_user_to_program(user, build_partner_program()) |
| 138 | + response = self.client.get(self.url) |
| 139 | + self.assertEqual(len(response.data), 4) |
| 140 | + self.assertTrue(all(type(value) is int for value in response.data.values())) |
| 141 | + for forbidden in ("email", "id", "first_name", "project", "partner_program"): |
| 142 | + self.assertNotIn(forbidden, response.data) |
| 143 | + |
| 144 | + def test_non_read_methods_are_not_supported(self): |
| 145 | + self.assertEqual(self.client.post(self.url, {}).status_code, 405) |
| 146 | + |
| 147 | + def test_one_select_for_ten_hundred_and_thousand_users(self): |
| 148 | + """Подготовка данных вне замера: endpoint всегда делает один SELECT.""" |
| 149 | + previous = 0 |
| 150 | + for total in (10, 100, 1000): |
| 151 | + CustomUser.objects.bulk_create( |
| 152 | + [ |
| 153 | + CustomUser( |
| 154 | + email=f"scale-{index}@example.test", |
| 155 | + first_name="Участник", |
| 156 | + last_name="Тестовый", |
| 157 | + birthday=date(2000, 1, 1), |
| 158 | + is_active=True, |
| 159 | + user_type=CustomUser.MEMBER, |
| 160 | + ) |
| 161 | + for index in range(previous, total) |
| 162 | + ] |
| 163 | + ) |
| 164 | + previous = total |
| 165 | + with self.subTest(total=total), self.assertNumQueries(1): |
| 166 | + self.assertEqual(self.statistics()["total"], total) |
| 167 | + |
| 168 | + def test_query_count_stays_one_with_many_relations(self): |
| 169 | + user = build_user() |
| 170 | + for index in range(10): |
| 171 | + Collaborator.objects.create(user=user, project=self.project(user)) |
| 172 | + add_user_to_program(user, build_partner_program(tag=f"related-{index}")) |
| 173 | + with self.assertNumQueries(1): |
| 174 | + self.assertEqual(self.statistics()["in_projects"], 1) |
0 commit comments