From 71cdd33503d1f729eb3d880f387566631b1adf20 Mon Sep 17 00:00:00 2001 From: Badmajor Date: Fri, 2 Aug 2024 12:30:19 +0300 Subject: [PATCH 1/2] Safe user extraction --- src/backend/api/v1/projects/serializers.py | 33 +++++++------------ src/backend/tests/conftest.py | 8 +++++ src/backend/tests/profile/conftest.py | 3 +- src/backend/tests/profile/test_model.py | 6 ++-- .../{test_model.py => test_models.py} | 0 .../tests/projects/test_serializers.py | 2 ++ 6 files changed, 26 insertions(+), 26 deletions(-) rename src/backend/tests/projects/{test_model.py => test_models.py} (100%) create mode 100644 src/backend/tests/projects/test_serializers.py diff --git a/src/backend/api/v1/projects/serializers.py b/src/backend/api/v1/projects/serializers.py index c5f1998..b638812 100644 --- a/src/backend/api/v1/projects/serializers.py +++ b/src/backend/api/v1/projects/serializers.py @@ -90,25 +90,10 @@ class Meta: "project_specialists", "status", ) - - def _get_base_fields(self): - """Метод получения полей создателя и владельца.""" - - return { - "creator": serializers.SlugRelatedField( - slug_field="username", read_only=True - ), - "owner": serializers.SlugRelatedField( - slug_field="username", read_only=True - ), - } - - def get_fields(self): - """метод получения полей сериализатора.""" - - fields = super().get_fields() - fields.update(self._get_base_fields()) - return fields + read_only_fields: ClassVar[Tuple[str, ...]] = ( + "creator", + "owner", + ) class ReadParticipantSerializer(CustomModelSerializer): @@ -143,6 +128,9 @@ class ReadProjectSerializer(RecruitmentStatusMixin, BaseProjectSerializer): recruitment_status = serializers.SerializerMethodField() is_favorite = serializers.SerializerMethodField(read_only=True) owner = serializers.SerializerMethodField() + creator = serializers.SlugRelatedField( + slug_field="username", read_only=True + ) project_participants = ReadParticipantSerializer(many=True) unique_project_participants_skills = serializers.SerializerMethodField() @@ -161,9 +149,10 @@ def get_is_favorite(self, project) -> bool: В противном случе возвращает False. Для неавторизованных пользователей всегда возвращает False. """ - user = self.context["request"].user - if user.is_authenticated: - return project.favorited_by.filter(id=user.id).exists() + request = self.context.get("request", None) + if user := getattr(request, "user", None): + if user.is_authenticated: + return project.favorited_by.filter(id=user.id).exists() return False def get_owner(self, project): diff --git a/src/backend/tests/conftest.py b/src/backend/tests/conftest.py index 442e24e..97b80f3 100644 --- a/src/backend/tests/conftest.py +++ b/src/backend/tests/conftest.py @@ -14,3 +14,11 @@ def user(django_user_model): def user_client(user, client): client.force_login(user) return client + + +@pytest.fixture +def profile(user): + profile = user.profile + profile.name = "profile_name" + profile.save() + return profile diff --git a/src/backend/tests/profile/conftest.py b/src/backend/tests/profile/conftest.py index 27c3102..71ac0cc 100644 --- a/src/backend/tests/profile/conftest.py +++ b/src/backend/tests/profile/conftest.py @@ -4,7 +4,8 @@ @pytest.fixture -def profile(user): +def profile_new(user): + """Профайл с незаполненной информацией""" return user.profile diff --git a/src/backend/tests/profile/test_model.py b/src/backend/tests/profile/test_model.py index 3839f0f..57725af 100644 --- a/src/backend/tests/profile/test_model.py +++ b/src/backend/tests/profile/test_model.py @@ -19,10 +19,10 @@ def test_create_profile_with_user(): @pytest.mark.django_db -def test_update_profiles_data(profile, update_data): +def test_update_profiles_data(profile_new, update_data): """Тест обновления информации в профиле""" assert Profile.objects.filter(**update_data).count() == 0 for field, value in update_data.items(): - setattr(profile, field, value) - profile.save() + setattr(profile_new, field, value) + profile_new.save() assert Profile.objects.filter(**update_data).count() == 1 diff --git a/src/backend/tests/projects/test_model.py b/src/backend/tests/projects/test_models.py similarity index 100% rename from src/backend/tests/projects/test_model.py rename to src/backend/tests/projects/test_models.py diff --git a/src/backend/tests/projects/test_serializers.py b/src/backend/tests/projects/test_serializers.py new file mode 100644 index 0000000..788c07e --- /dev/null +++ b/src/backend/tests/projects/test_serializers.py @@ -0,0 +1,2 @@ +def test_owner_field(profile): + assert profile.name == "profile_name" From 71a7929a94eb9d99c748b9d52bfed543c4dd911e Mon Sep 17 00:00:00 2001 From: Badmajor Date: Fri, 2 Aug 2024 12:31:49 +0300 Subject: [PATCH 2/2] add test for owner field --- src/backend/tests/projects/test_serializers.py | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/backend/tests/projects/test_serializers.py b/src/backend/tests/projects/test_serializers.py index 788c07e..ff53d60 100644 --- a/src/backend/tests/projects/test_serializers.py +++ b/src/backend/tests/projects/test_serializers.py @@ -1,2 +1,12 @@ -def test_owner_field(profile): - assert profile.name == "profile_name" +from api.v1.projects.serializers import ReadProjectSerializer + + +def test_owner_field(profile, project): + valid_data = { + "id": profile.user.id, + "username": profile.user.username, + "name": profile.name, + "avatar": (profile.avatar.url if profile.avatar else None), + } + serializer = ReadProjectSerializer(instance=project) + assert serializer.data["owner"] == valid_data